@duckcodeailabs/dql-cli 1.12.11 → 1.13.0

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 (96) hide show
  1. package/dist/apps-api.d.ts +151 -3
  2. package/dist/apps-api.d.ts.map +1 -1
  3. package/dist/apps-api.js +675 -97
  4. package/dist/apps-api.js.map +1 -1
  5. package/dist/assets/dql-notebook/assets/AgentAnswerCard-Cp0eh6zU.js +5 -0
  6. package/dist/assets/dql-notebook/assets/{AgentLogPage-hzHqpD3-.js → AgentLogPage-CBGEoGmU.js} +1 -1
  7. package/dist/assets/dql-notebook/assets/{AiBuildDialog-BQRWoxp9.js → AiBuildDialog-CwAD3tXE.js} +1 -1
  8. package/dist/assets/dql-notebook/assets/{AiBuildResult-D9t_4sQl.js → AiBuildResult-CyqTuQe5.js} +1 -1
  9. package/dist/assets/dql-notebook/assets/AiSidePanel-DjB8PWHG.js +6 -0
  10. package/dist/assets/dql-notebook/assets/AnalyticsHome-B7BkvA-R.js +6 -0
  11. package/dist/assets/dql-notebook/assets/AppsView-CUrqtEGC.js +4583 -0
  12. package/dist/assets/dql-notebook/assets/BlockStudio-Bl0aGQJR.js +60 -0
  13. package/dist/assets/dql-notebook/assets/{BusinessArtifactView-CnTbFVGT.js → BusinessArtifactView-C4SZVNW-.js} +1 -1
  14. package/dist/assets/dql-notebook/assets/DbtFirstModelingPage-B0uxitnx.js +22 -0
  15. package/dist/assets/dql-notebook/assets/GitPage-BfVD4tVq.js +7 -0
  16. package/dist/assets/dql-notebook/assets/GlobalAiRail-DUwdy3fB.js +1 -0
  17. package/dist/assets/dql-notebook/assets/GovernedContextPage-D9f26ZFb.js +7 -0
  18. package/dist/assets/dql-notebook/assets/{HelpDocsPage-CL0vbSER.js → HelpDocsPage-BDPNVot1.js} +1 -1
  19. package/dist/assets/dql-notebook/assets/{HomePage-DzAucwBW.js → HomePage-DiOnRhEG.js} +1 -1
  20. package/dist/assets/dql-notebook/assets/LineageDAG-BiUFX2KL.js +1 -0
  21. package/dist/assets/dql-notebook/assets/{LineageDetailView-DdVH-nz6.js → LineageDetailView-CfbSvlPJ.js} +1 -1
  22. package/dist/assets/dql-notebook/assets/{LineageDrawer-BvrVZNKY.js → LineageDrawer-CgTScaGB.js} +1 -1
  23. package/dist/assets/dql-notebook/assets/{LineagePathBreadcrumb-CSut-zvm.js → LineagePathBreadcrumb-D7ZA7k68.js} +3 -3
  24. package/dist/assets/dql-notebook/assets/{MiniLineageGraph-zg_1wW3M.js → MiniLineageGraph-GkD4y17x.js} +1 -1
  25. package/dist/assets/dql-notebook/assets/{NewBlockModal-9cDletl-.js → NewBlockModal-B9TfRjt7.js} +1 -1
  26. package/dist/assets/dql-notebook/assets/{NewNotebookModal-V6de8L4d.js → NewNotebookModal-BbO9NKUl.js} +2 -2
  27. package/dist/assets/dql-notebook/assets/NotebookEditor-CuMpvXR9.js +200 -0
  28. package/dist/assets/dql-notebook/assets/ReadinessPage-BROJ9YBM.js +1 -0
  29. package/dist/assets/dql-notebook/assets/{SetupOnboarding-Bg-MjbC9.js → SetupOnboarding-BCcZlpuQ.js} +2 -2
  30. package/dist/assets/dql-notebook/assets/{TrustBadge-DGuHB8kP.js → TrustBadge-vQQh8d0D.js} +1 -1
  31. package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel-Dj4AXAhT.js +83 -0
  32. package/dist/assets/dql-notebook/assets/{answer-to-notebook-BDzY4MuQ.js → answer-to-notebook-DuqCcDDl.js} +1 -1
  33. package/dist/assets/dql-notebook/assets/{arrow-left-IjlnAihE.js → arrow-left-CMe1kkOL.js} +1 -1
  34. package/dist/assets/dql-notebook/assets/{arrow-right-BI4cXgOY.js → arrow-right-DvB_DONr.js} +1 -1
  35. package/dist/assets/dql-notebook/assets/{book-open-text-i6xhxu_I.js → book-open-text-CJ3NAvrs.js} +1 -1
  36. package/dist/assets/dql-notebook/assets/{bot-C6DE7Q6m.js → bot-CV8DYRrt.js} +1 -1
  37. package/dist/assets/dql-notebook/assets/{chevron-up-DSEILnDs.js → chevron-up-HxU1l85K.js} +1 -1
  38. package/dist/assets/dql-notebook/assets/{circle-x-BoAorVSm.js → circle-x-BCgtha1W.js} +1 -1
  39. package/dist/assets/dql-notebook/assets/{dagre.esm-CycymVj6.js → dagre.esm-GKp7qoUL.js} +1 -1
  40. package/dist/assets/dql-notebook/assets/{external-link-ZwE5iHsX.js → external-link-C-PXokWV.js} +1 -1
  41. package/dist/assets/dql-notebook/assets/{grip-vertical-Dnp2st8l.js → grip-vertical-B4EHbGXW.js} +1 -1
  42. package/dist/assets/dql-notebook/assets/index-1mIC_XX4.js +634 -0
  43. package/dist/assets/dql-notebook/assets/{link-2-CTKe6Snr.js → link-2-BLx-goet.js} +1 -1
  44. package/dist/assets/dql-notebook/assets/{list-tree-Ced8e_S1.js → list-tree-BRFpEmvV.js} +1 -1
  45. package/dist/assets/dql-notebook/assets/{maximize-2-Cojc6867.js → maximize-2-CCd5uRIZ.js} +1 -1
  46. package/dist/assets/dql-notebook/assets/{minimize-2-CBIAE0XH.js → minimize-2-CDwSCGlO.js} +1 -1
  47. package/dist/assets/dql-notebook/assets/{panel-right-open-po3bWSeL.js → panel-right-open-CunA1xO7.js} +1 -1
  48. package/dist/assets/dql-notebook/assets/{pencil-Cb45c6WU.js → pencil-D_I14Wyk.js} +1 -1
  49. package/dist/assets/dql-notebook/assets/{rotate-ccw-B9v1LTJ0.js → rotate-ccw-DOrfTZk8.js} +1 -1
  50. package/dist/assets/dql-notebook/assets/{semantic-fields-B6ii0an0.js → semantic-fields-AfQvjt5R.js} +1 -1
  51. package/dist/assets/dql-notebook/assets/{star-CO4tfaDq.js → star-DDhv4e8M.js} +1 -1
  52. package/dist/assets/dql-notebook/assets/{triangle-alert-BSdIu2El.js → triangle-alert-2ZXx8wAu.js} +1 -1
  53. package/dist/assets/dql-notebook/assets/usePersistedAgentThreadId-3rzkZrqc.js +18 -0
  54. package/dist/assets/dql-notebook/assets/{user-round-BfrV8U-W.js → user-round-BA074kiQ.js} +1 -1
  55. package/dist/assets/dql-notebook/assets/{wand-sparkles-BgTxZNBc.js → wand-sparkles-CEYHLt9b.js} +1 -1
  56. package/dist/assets/dql-notebook/assets/{workflow--2ycp0yy.js → workflow-CZtyrcR-.js} +1 -1
  57. package/dist/assets/dql-notebook/assets/{wrench-LMCrpa9_.js → wrench-Ong23-wu.js} +1 -1
  58. package/dist/assets/dql-notebook/assets/{x-CeNgQwGm.js → x-CSo1M3tu.js} +1 -1
  59. package/dist/assets/dql-notebook/index.html +1 -1
  60. package/dist/llm/providers/dql-agent-provider.d.ts +4 -3
  61. package/dist/llm/providers/dql-agent-provider.d.ts.map +1 -1
  62. package/dist/llm/providers/dql-agent-provider.js +13 -10
  63. package/dist/llm/providers/dql-agent-provider.js.map +1 -1
  64. package/dist/local-operation-coordinator.d.ts +59 -0
  65. package/dist/local-operation-coordinator.d.ts.map +1 -0
  66. package/dist/local-operation-coordinator.js +256 -0
  67. package/dist/local-operation-coordinator.js.map +1 -0
  68. package/dist/local-runtime.d.ts +49 -1
  69. package/dist/local-runtime.d.ts.map +1 -1
  70. package/dist/local-runtime.js +1590 -323
  71. package/dist/local-runtime.js.map +1 -1
  72. package/dist/package.json +12 -11
  73. package/dist/project-refresh-coordinator.d.ts +19 -0
  74. package/dist/project-refresh-coordinator.d.ts.map +1 -0
  75. package/dist/project-refresh-coordinator.js +134 -0
  76. package/dist/project-refresh-coordinator.js.map +1 -0
  77. package/dist/project-refresh-worker.d.ts +13 -0
  78. package/dist/project-refresh-worker.d.ts.map +1 -0
  79. package/dist/project-refresh-worker.js +58 -0
  80. package/dist/project-refresh-worker.js.map +1 -0
  81. package/package.json +13 -11
  82. package/dist/assets/dql-notebook/assets/AgentAnswerCard-CpL2kDCV.js +0 -5
  83. package/dist/assets/dql-notebook/assets/AiSidePanel-BCQB9rVF.js +0 -6
  84. package/dist/assets/dql-notebook/assets/AnalyticsHome-Ba4Ve_Gd.js +0 -6
  85. package/dist/assets/dql-notebook/assets/AppsView-CdAT9BOq.js +0 -4466
  86. package/dist/assets/dql-notebook/assets/BlockStudio-Brg4fwn5.js +0 -60
  87. package/dist/assets/dql-notebook/assets/DbtFirstModelingPage-CQe2FUZq.js +0 -22
  88. package/dist/assets/dql-notebook/assets/GitPage-DHyDBChc.js +0 -7
  89. package/dist/assets/dql-notebook/assets/GlobalAiRail-Cys4n_rq.js +0 -1
  90. package/dist/assets/dql-notebook/assets/GovernedContextPage-DyKoDSZ2.js +0 -7
  91. package/dist/assets/dql-notebook/assets/LineageDAG-QHqd_AM5.js +0 -1
  92. package/dist/assets/dql-notebook/assets/NotebookEditor-EZ0pfWVs.js +0 -200
  93. package/dist/assets/dql-notebook/assets/ReadinessPage-BaGvjyfd.js +0 -1
  94. package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel-BlWAVEwO.js +0 -83
  95. package/dist/assets/dql-notebook/assets/index-BTuliKhK.js +0 -634
  96. package/dist/assets/dql-notebook/assets/usePersistedAgentThreadId-CkVFrrjk.js +0 -18
@@ -0,0 +1,634 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/HomePage-DiOnRhEG.js","assets/TrustBadge-vQQh8d0D.js","assets/arrow-right-DvB_DONr.js","assets/triangle-alert-2ZXx8wAu.js","assets/book-open-text-CJ3NAvrs.js","assets/workflow-CZtyrcR-.js","assets/react-CRB3T2We.js","assets/AnalyticsHome-B7BkvA-R.js","assets/answer-to-notebook-DuqCcDDl.js","assets/UnifiedAgentRunPanel-Dj4AXAhT.js","assets/AgentAnswerCard-Cp0eh6zU.js","assets/usePersistedAgentThreadId-3rzkZrqc.js","assets/wrench-Ong23-wu.js","assets/AiBuildResult-CyqTuQe5.js","assets/user-round-BA074kiQ.js","assets/rotate-ccw-DOrfTZk8.js","assets/x-CSo1M3tu.js","assets/pencil-D_I14Wyk.js","assets/list-tree-BRFpEmvV.js","assets/minimize-2-CDwSCGlO.js","assets/maximize-2-CCd5uRIZ.js","assets/chevron-up-HxU1l85K.js","assets/star-DDhv4e8M.js","assets/GlobalAiRail-DUwdy3fB.js","assets/AiSidePanel-DjB8PWHG.js","assets/NotebookEditor-CuMpvXR9.js","assets/LineagePathBreadcrumb-D7ZA7k68.js","assets/codemirror-DXt7RW72.js","assets/semantic-fields-AfQvjt5R.js","assets/MiniLineageGraph-GkD4y17x.js","assets/dagre.esm-GKp7qoUL.js","assets/dagre-BZV40eAE.css","assets/link-2-BLx-goet.js","assets/NewNotebookModal-BbO9NKUl.js","assets/NewBlockModal-B9TfRjt7.js","assets/SetupOnboarding-BCcZlpuQ.js","assets/arrow-left-CMe1kkOL.js","assets/BlockStudio-Bl0aGQJR.js","assets/panel-right-open-CunA1xO7.js","assets/bot-CV8DYRrt.js","assets/BusinessArtifactView-C4SZVNW-.js","assets/LineageDetailView-CfbSvlPJ.js","assets/LineageDAG-BiUFX2KL.js","assets/HelpDocsPage-BDPNVot1.js","assets/GitPage-BfVD4tVq.js","assets/external-link-C-PXokWV.js","assets/ReadinessPage-BROJ9YBM.js","assets/ai-build-bus-1BR770pY.js","assets/wand-sparkles-CEYHLt9b.js","assets/AgentLogPage-CBGEoGmU.js","assets/circle-x-BCgtha1W.js","assets/GovernedContextPage-D9f26ZFb.js","assets/DbtFirstModelingPage-B0uxitnx.js","assets/AppsView-CUrqtEGC.js","assets/grip-vertical-B4EHbGXW.js","assets/LineageDrawer-CgTScaGB.js","assets/AiBuildDialog-CwAD3tXE.js"])))=>i.map(i=>d[i]);
2
+ var gf=Object.defineProperty;var Ja=e=>{throw TypeError(e)};var yf=(e,t,n)=>t in e?gf(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Pe=(e,t,n)=>yf(e,typeof t!="symbol"?t+"":t,n),Ps=(e,t,n)=>t.has(e)||Ja("Cannot "+n);var R=(e,t,n)=>(Ps(e,t,"read from private field"),n?n.call(e):t.get(e)),le=(e,t,n)=>t.has(e)?Ja("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Z=(e,t,n,r)=>(Ps(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),fe=(e,t,n)=>(Ps(e,t,"access private method"),n);var Ao=(e,t,n,r)=>({set _(o){Z(e,t,o,n)},get _(){return R(e,t,r)}});import{r as Hl,a as Gl,g as Ql}from"./react-CRB3T2We.js";function bf(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 c of i.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).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 Ds={exports:{}},Mr={};/**
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 Ya;function xf(){if(Ya)return Mr;Ya=1;var e=Hl(),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 c(a,l,u){var f,d={},h=null,m=null;u!==void 0&&(h=""+u),l.key!==void 0&&(h=""+l.key),l.ref!==void 0&&(m=l.ref);for(f in l)r.call(l,f)&&!i.hasOwnProperty(f)&&(d[f]=l[f]);if(a&&a.defaultProps)for(f in l=a.defaultProps,l)d[f]===void 0&&(d[f]=l[f]);return{$$typeof:t,type:a,key:h,ref:m,props:d,_owner:o.current}}return Mr.Fragment=n,Mr.jsx=c,Mr.jsxs=c,Mr}var Xa;function vf(){return Xa||(Xa=1,Ds.exports=xf()),Ds.exports}var s=vf(),_o={},Za;function Sf(){if(Za)return _o;Za=1;var e=Gl();return _o.createRoot=e.createRoot,_o.hydrateRoot=e.hydrateRoot,_o}var wf=Sf(),p=Hl();const qe=Ql(p),Jl=bf({__proto__:null,default:qe},[p]);var ho=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Dn,sn,ur,Ll,kf=(Ll=class extends ho{constructor(){super();le(this,Dn);le(this,sn);le(this,ur);Z(this,ur,t=>{if(typeof window<"u"&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){R(this,sn)||this.setEventListener(R(this,ur))}onUnsubscribe(){var t;this.hasListeners()||((t=R(this,sn))==null||t.call(this),Z(this,sn,void 0))}setEventListener(t){var n;Z(this,ur,t),(n=R(this,sn))==null||n.call(this),Z(this,sn,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){R(this,Dn)!==t&&(Z(this,Dn,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof R(this,Dn)=="boolean"?R(this,Dn):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},Dn=new WeakMap,sn=new WeakMap,ur=new WeakMap,Ll),Ui=new kf,Cf={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},an,qi,Nl,jf=(Nl=class{constructor(){le(this,an,Cf);le(this,qi,!1)}setTimeoutProvider(e){Z(this,an,e)}setTimeout(e,t){return R(this,an).setTimeout(e,t)}clearTimeout(e){R(this,an).clearTimeout(e)}setInterval(e,t){return R(this,an).setInterval(e,t)}clearInterval(e){R(this,an).clearInterval(e)}},an=new WeakMap,qi=new WeakMap,Nl),On=new jf;function Ef(e){setTimeout(e,0)}var Tf=typeof window>"u"||"Deno"in globalThis;function at(){}function Rf(e,t){return typeof e=="function"?e(t):e}function ui(e){return typeof e=="number"&&e>=0&&e!==1/0}function Yl(e,t){return Math.max(e+(t||0)-Date.now(),0)}function hn(e,t){return typeof e=="function"?e(t):e}function ft(e,t){return typeof e=="function"?e(t):e}function ec(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:c,stale:a}=e;if(c){if(r){if(t.queryHash!==Wi(c,t.options))return!1}else if(!Cr(t.queryKey,c))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||o&&o!==t.state.fetchStatus||i&&!i(t))}function tc(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Xr(t.options.mutationKey)!==Xr(i))return!1}else if(!Cr(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Wi(e,t){return((t==null?void 0:t.queryKeyHashFn)||Xr)(e)}function Xr(e){return JSON.stringify(e,(t,n)=>fi(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function Cr(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(!Cr(e[r],t[r]))return!1;return!0}const n=Object.keys(t);for(const r of n)if(!Cr(e[r],t[r]))return!1;return!0}return!1}var Af=Object.prototype.hasOwnProperty;function Xl(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=nc(e)&&nc(t);if(!r&&!(fi(e)&&fi(t)))return t;const i=(r?e:Object.keys(e)).length,c=r?t:Object.keys(t),a=c.length,l=r?new Array(a):{};let u=0;for(let f=0;f<a;f++){const d=r?f:c[f],h=e[d],m=t[d];if(h===m){l[d]=h,(r?f<i:Af.call(e,d))&&u++;continue}if(h===null||m===null||typeof h!="object"||typeof m!="object"){l[d]=m;continue}const S=Xl(h,m,n+1);l[d]=S,S===h&&u++}return i===a&&u===i?e:l}function pi(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 nc(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function fi(e){if(!rc(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!rc(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function rc(e){return Object.prototype.toString.call(e)==="[object Object]"}function _f(e){return new Promise(t=>{On.setTimeout(t,e)})}function hi(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Xl(e,t):t}function Of(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Pf(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Ki=Symbol();function Zl(e,t){return!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===Ki?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ed(e,t){return typeof e=="function"?e(...t):!!e}function Df(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 Zr=(()=>{let e=()=>Tf;return{isServer(){return e()},setIsServer(t){e=t}}})();function mi(){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 If=Ef;function Mf(){let e=[],t=0,n=a=>{a()},r=a=>{a()},o=If;const i=a=>{t?e.push(a):o(()=>{n(a)})},c=()=>{const a=e;e=[],a.length&&o(()=>{r(()=>{a.forEach(l=>{n(l)})})})};return{batch:a=>{let l;t++;try{l=a()}finally{t--,t||c()}return l},batchCalls:a=>(...l)=>{i(()=>{a(...l)})},schedule:i,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{o=a}}}var Ue=Mf(),pr,cn,fr,Bl,$f=(Bl=class extends ho{constructor(){super();le(this,pr,!0);le(this,cn);le(this,fr);Z(this,fr,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,cn)||this.setEventListener(R(this,fr))}onUnsubscribe(){var t;this.hasListeners()||((t=R(this,cn))==null||t.call(this),Z(this,cn,void 0))}setEventListener(t){var n;Z(this,fr,t),(n=R(this,cn))==null||n.call(this),Z(this,cn,t(this.setOnline.bind(this)))}setOnline(t){R(this,pr)!==t&&(Z(this,pr,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return R(this,pr)}},pr=new WeakMap,cn=new WeakMap,fr=new WeakMap,Bl),es=new $f;function Lf(e){return Math.min(1e3*2**e,3e4)}function td(e){return(e??"online")==="online"?es.isOnline():!0}var gi=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function nd(e){let t=!1,n=0,r;const o=mi(),i=()=>o.status!=="pending",c=b=>{var x;if(!i()){const w=new gi(b);h(w),(x=e.onCancel)==null||x.call(e,w)}},a=()=>{t=!0},l=()=>{t=!1},u=()=>Ui.isFocused()&&(e.networkMode==="always"||es.isOnline())&&e.canRun(),f=()=>td(e.networkMode)&&e.canRun(),d=b=>{i()||(r==null||r(),o.resolve(b))},h=b=>{i()||(r==null||r(),o.reject(b))},m=()=>new Promise(b=>{var x;r=w=>{(i()||u())&&b(w)},(x=e.onPause)==null||x.call(e)}).then(()=>{var b;r=void 0,i()||(b=e.onContinue)==null||b.call(e)}),S=()=>{if(i())return;let b;const x=n===0?e.initialPromise:void 0;try{b=x??e.fn()}catch(w){b=Promise.reject(w)}Promise.resolve(b).then(d).catch(w=>{var D;if(i())return;const C=e.retry??(Zr.isServer()?0:3),k=e.retryDelay??Lf,v=typeof k=="function"?k(n,w):k,j=C===!0||typeof C=="number"&&n<C||typeof C=="function"&&C(n,w);if(t||!j){h(w);return}n++,(D=e.onFail)==null||D.call(e,n,w),_f(v).then(()=>u()?void 0:m()).then(()=>{t?h(w):S()})})};return{promise:o,status:()=>o.status,cancel:c,continue:()=>(r==null||r(),o),cancelRetry:a,continueRetry:l,canStart:f,start:()=>(f()?S():m().then(S),o)}}var In,Fl,rd=(Fl=class{constructor(){le(this,In)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ui(this.gcTime)&&Z(this,In,On.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Zr.isServer()?1/0:300*1e3))}clearGcTimeout(){R(this,In)!==void 0&&(On.clearTimeout(R(this,In)),Z(this,In,void 0))}},In=new WeakMap,Fl);function Nf(e){return{onFetch:(t,n)=>{var f,d,h,m,S;const r=t.options,o=(h=(d=(f=t.fetchOptions)==null?void 0:f.meta)==null?void 0:d.fetchMore)==null?void 0:h.direction,i=((m=t.state.data)==null?void 0:m.pages)||[],c=((S=t.state.data)==null?void 0:S.pageParams)||[];let a={pages:[],pageParams:[]},l=0;const u=async()=>{let b=!1;const x=k=>{Df(k,()=>t.signal,()=>b=!0)},w=Zl(t.options,t.fetchOptions),C=async(k,v,j)=>{if(b)return Promise.reject(t.signal.reason);if(v==null&&k.pages.length)return Promise.resolve(k);const T=(()=>{const _={client:t.client,queryKey:t.queryKey,pageParam:v,direction:j?"backward":"forward",meta:t.options.meta};return x(_),_})(),y=await w(T),{maxPages:O}=t.options,A=j?Pf:Of;return{pages:A(k.pages,y,O),pageParams:A(k.pageParams,v,O)}};if(o&&i.length){const k=o==="backward",v=k?Bf:oc,j={pages:i,pageParams:c},D=v(r,j);a=await C(j,D,k)}else{const k=e??i.length;do{const v=l===0?c[0]??r.initialPageParam:oc(r,a);if(l>0&&v==null)break;a=await C(a,v),l++}while(l<k)}return a};t.options.persister?t.fetchFn=()=>{var b,x;return(x=(b=t.options).persister)==null?void 0:x.call(b,u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=u}}}function oc(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 Bf(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 hr,Mn,mr,yt,$n,Le,co,Ln,pt,od,Vt,zl,Ff=(zl=class extends rd{constructor(t){super();le(this,pt);le(this,hr);le(this,Mn);le(this,mr);le(this,yt);le(this,$n);le(this,Le);le(this,co);le(this,Ln);Z(this,Ln,!1),Z(this,co,t.defaultOptions),this.setOptions(t.options),this.observers=[],Z(this,$n,t.client),Z(this,yt,R(this,$n).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,Z(this,Mn,ic(this.options)),this.state=t.state??R(this,Mn),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return R(this,hr)}get promise(){var t;return(t=R(this,Le))==null?void 0:t.promise}setOptions(t){if(this.options={...R(this,co),...t},t!=null&&t._type&&Z(this,hr,t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=ic(this.options);n.data!==void 0&&(this.setState(sc(n.data,n.dataUpdatedAt)),Z(this,Mn,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&R(this,yt).remove(this)}setData(t,n){const r=hi(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,Mn)}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===Ki||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>hn(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:!Yl(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,od).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,f,d,h,m,S,b,x,w,C,k;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 v=this.observers.find(j=>j.options.queryFn);v&&this.setOptions(v.options)}const r=new AbortController,o=v=>{Object.defineProperty(v,"signal",{enumerable:!0,get:()=>(Z(this,Ln,!0),r.signal)})},i=()=>{const v=Zl(this.options,n),D=(()=>{const T={client:R(this,$n),queryKey:this.queryKey,meta:this.meta};return o(T),T})();return Z(this,Ln,!1),this.options.persister?this.options.persister(v,D,this):v(D)},a=(()=>{const v={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:R(this,$n),state:this.state,fetchFn:i};return o(v),v})(),l=R(this,hr)==="infinite"?Nf(this.options.pages):this.options.behavior;l==null||l.onFetch(a,this),Z(this,mr,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((f=a.fetchOptions)==null?void 0:f.meta))&&fe(this,pt,Vt).call(this,{type:"fetch",meta:(d=a.fetchOptions)==null?void 0:d.meta}),Z(this,Le,nd({initialPromise:n==null?void 0:n.initialPromise,fn:a.fetchFn,onCancel:v=>{v instanceof gi&&v.revert&&this.setState({...R(this,mr),fetchStatus:"idle"}),r.abort()},onFail:(v,j)=>{fe(this,pt,Vt).call(this,{type:"failed",failureCount:v,error:j})},onPause:()=>{fe(this,pt,Vt).call(this,{type:"pause"})},onContinue:()=>{fe(this,pt,Vt).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{const v=await R(this,Le).start();if(v===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(v),(m=(h=R(this,yt).config).onSuccess)==null||m.call(h,v,this),(b=(S=R(this,yt).config).onSettled)==null||b.call(S,v,this.state.error,this),v}catch(v){if(v instanceof gi){if(v.silent)return R(this,Le).promise;if(v.revert){if(this.state.data===void 0)throw v;return this.state.data}}throw fe(this,pt,Vt).call(this,{type:"error",error:v}),(w=(x=R(this,yt).config).onError)==null||w.call(x,v,this),(k=(C=R(this,yt).config).onSettled)==null||k.call(C,this.state.data,v,this),v}finally{this.scheduleGc()}}},hr=new WeakMap,Mn=new WeakMap,mr=new WeakMap,yt=new WeakMap,$n=new WeakMap,Le=new WeakMap,co=new WeakMap,Ln=new WeakMap,pt=new WeakSet,od=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,...sd(r.data,this.options),fetchMeta:t.meta??null};case"success":const o={...r,...sc(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return Z(this,mr,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})})},zl);function sd(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:td(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function sc(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function ic(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,lo,Xe,Nn,gr,Ht,ln,uo,yr,br,Bn,Fn,dn,xr,Se,zr,yi,bi,xi,vi,Si,wi,ki,id,ql,zf=(ql=class extends ho{constructor(t,n){super();le(this,Se);le(this,it);le(this,he);le(this,lo);le(this,Xe);le(this,Nn);le(this,gr);le(this,Ht);le(this,ln);le(this,uo);le(this,yr);le(this,br);le(this,Bn);le(this,Fn);le(this,dn);le(this,xr,new Set);this.options=n,Z(this,it,t),Z(this,ln,null),Z(this,Ht,mi()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(R(this,he).addObserver(this),ac(R(this,he),this.options)?fe(this,Se,zr).call(this):this.updateResult(),fe(this,Se,vi).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ci(R(this,he),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ci(R(this,he),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,fe(this,Se,Si).call(this),fe(this,Se,wi).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,ki).call(this),R(this,he).setOptions(this.options),n._defaulted&&!pi(this.options,n)&&R(this,it).getQueryCache().notify({type:"observerOptionsUpdated",query:R(this,he),observer:this});const o=this.hasListeners();o&&cc(R(this,he),r,this.options,n)&&fe(this,Se,zr).call(this),this.updateResult(),o&&(R(this,he)!==r||ft(this.options.enabled,R(this,he))!==ft(n.enabled,R(this,he))||hn(this.options.staleTime,R(this,he))!==hn(n.staleTime,R(this,he)))&&fe(this,Se,yi).call(this);const i=fe(this,Se,bi).call(this);o&&(R(this,he)!==r||ft(this.options.enabled,R(this,he))!==ft(n.enabled,R(this,he))||i!==R(this,dn))&&fe(this,Se,xi).call(this,i)}getOptimisticResult(t){const n=R(this,it).getQueryCache().build(R(this,it),t),r=this.createResult(n,t);return Uf(this,r)&&(Z(this,Xe,r),Z(this,gr,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,xr).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,zr).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),R(this,Xe)))}createResult(t,n){var O;const r=R(this,he),o=this.options,i=R(this,Xe),c=R(this,Nn),a=R(this,gr),u=t!==r?t.state:R(this,lo),{state:f}=t;let d={...f},h=!1,m;if(n._optimisticResults){const A=this.hasListeners(),_=!A&&ac(t,n),P=A&&cc(t,r,n,o);(_||P)&&(d={...d,...sd(f.data,t.options)}),n._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:S,errorUpdatedAt:b,status:x}=d;m=d.data;let w=!1;if(n.placeholderData!==void 0&&m===void 0&&x==="pending"){let A;i!=null&&i.isPlaceholderData&&n.placeholderData===(a==null?void 0:a.placeholderData)?(A=i.data,w=!0):A=typeof n.placeholderData=="function"?n.placeholderData((O=R(this,br))==null?void 0:O.state.data,R(this,br)):n.placeholderData,A!==void 0&&(x="success",m=hi(i==null?void 0:i.data,A,n),h=!0)}if(n.select&&m!==void 0&&!w)if(i&&m===(c==null?void 0:c.data)&&n.select===R(this,uo))m=R(this,yr);else try{Z(this,uo,n.select),m=n.select(m),m=hi(i==null?void 0:i.data,m,n),Z(this,yr,m),Z(this,ln,null)}catch(A){Z(this,ln,A)}R(this,ln)&&(S=R(this,ln),m=R(this,yr),b=Date.now(),x="error");const C=d.fetchStatus==="fetching",k=x==="pending",v=x==="error",j=k&&C,D=m!==void 0,y={status:x,fetchStatus:d.fetchStatus,isPending:k,isSuccess:x==="success",isError:v,isInitialLoading:j,isLoading:j,data:m,dataUpdatedAt:d.dataUpdatedAt,error:S,errorUpdatedAt:b,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:d.dataUpdateCount>u.dataUpdateCount||d.errorUpdateCount>u.errorUpdateCount,isFetching:C,isRefetching:C&&!k,isLoadingError:v&&!D,isPaused:d.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:v&&D,isStale:Vi(t,n),refetch:this.refetch,promise:R(this,Ht),isEnabled:ft(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const A=y.data!==void 0,_=y.status==="error"&&!A,P=G=>{_?G.reject(y.error):A&&G.resolve(y.data)},$=()=>{const G=Z(this,Ht,y.promise=mi());P(G)},q=R(this,Ht);switch(q.status){case"pending":t.queryHash===r.queryHash&&P(q);break;case"fulfilled":(_||y.data!==q.value)&&$();break;case"rejected":(!_||y.error!==q.reason)&&$();break}}return y}updateResult(){const t=R(this,Xe),n=this.createResult(R(this,he),this.options);if(Z(this,Nn,R(this,he).state),Z(this,gr,this.options),R(this,Nn).data!==void 0&&Z(this,br,R(this,he)),pi(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,xr).size)return!0;const c=new Set(i??R(this,xr));return this.options.throwOnError&&c.add("error"),Object.keys(R(this,Xe)).some(a=>{const l=a;return R(this,Xe)[l]!==t[l]&&c.has(l)})};fe(this,Se,id).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&fe(this,Se,vi).call(this)}},it=new WeakMap,he=new WeakMap,lo=new WeakMap,Xe=new WeakMap,Nn=new WeakMap,gr=new WeakMap,Ht=new WeakMap,ln=new WeakMap,uo=new WeakMap,yr=new WeakMap,br=new WeakMap,Bn=new WeakMap,Fn=new WeakMap,dn=new WeakMap,xr=new WeakMap,Se=new WeakSet,zr=function(t){fe(this,Se,ki).call(this);let n=R(this,he).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(at)),n},yi=function(){fe(this,Se,Si).call(this);const t=hn(this.options.staleTime,R(this,he));if(Zr.isServer()||R(this,Xe).isStale||!ui(t))return;const r=Yl(R(this,Xe).dataUpdatedAt,t)+1;Z(this,Bn,On.setTimeout(()=>{R(this,Xe).isStale||this.updateResult()},r))},bi=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(R(this,he)):this.options.refetchInterval)??!1},xi=function(t){fe(this,Se,wi).call(this),Z(this,dn,t),!(Zr.isServer()||ft(this.options.enabled,R(this,he))===!1||!ui(R(this,dn))||R(this,dn)===0)&&Z(this,Fn,On.setInterval(()=>{(this.options.refetchIntervalInBackground||Ui.isFocused())&&fe(this,Se,zr).call(this)},R(this,dn)))},vi=function(){fe(this,Se,yi).call(this),fe(this,Se,xi).call(this,fe(this,Se,bi).call(this))},Si=function(){R(this,Bn)!==void 0&&(On.clearTimeout(R(this,Bn)),Z(this,Bn,void 0))},wi=function(){R(this,Fn)!==void 0&&(On.clearInterval(R(this,Fn)),Z(this,Fn,void 0))},ki=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,lo,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},id=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"})})},ql);function qf(e,t){return ft(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&ft(t.retryOnMount,e)===!1)}function ac(e,t){return qf(e,t)||e.state.data!==void 0&&Ci(e,t,t.refetchOnMount)}function Ci(e,t,n){if(ft(t.enabled,e)!==!1&&hn(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Vi(e,t)}return!1}function cc(e,t,n,r){return(e!==t||ft(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Vi(e,n)}function Vi(e,t){return ft(t.enabled,e)!==!1&&e.isStaleByTime(hn(t.staleTime,e))}function Uf(e,t){return!pi(e.getCurrentResult(),t)}var po,Mt,He,zn,$t,rn,Ul,Wf=(Ul=class extends rd{constructor(t){super();le(this,$t);le(this,po);le(this,Mt);le(this,He);le(this,zn);Z(this,po,t.client),this.mutationId=t.mutationId,Z(this,He,t.mutationCache),Z(this,Mt,[]),this.state=t.state||Kf(),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,Mt).includes(t)||(R(this,Mt).push(t),this.clearGcTimeout(),R(this,He).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){Z(this,Mt,R(this,Mt).filter(n=>n!==t)),this.scheduleGc(),R(this,He).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){R(this,Mt).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 c,a,l,u,f,d,h,m,S,b,x,w,C,k,v,j,D,T;const n=()=>{fe(this,$t,rn).call(this,{type:"continue"})},r={client:R(this,po),meta:this.options.meta,mutationKey:this.options.mutationKey};Z(this,zn,nd({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(y,O)=>{fe(this,$t,rn).call(this,{type:"failed",failureCount:y,error:O})},onPause:()=>{fe(this,$t,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,$t,rn).call(this,{type:"pending",variables:t,isPaused:i}),R(this,He).config.onMutate&&await R(this,He).config.onMutate(t,this,r);const O=await((a=(c=this.options).onMutate)==null?void 0:a.call(c,t,r));O!==this.state.context&&fe(this,$t,rn).call(this,{type:"pending",context:O,variables:t,isPaused:i})}const y=await R(this,zn).start();return await((u=(l=R(this,He).config).onSuccess)==null?void 0:u.call(l,y,t,this.state.context,this,r)),await((d=(f=this.options).onSuccess)==null?void 0:d.call(f,y,t,this.state.context,r)),await((m=(h=R(this,He).config).onSettled)==null?void 0:m.call(h,y,null,this.state.variables,this.state.context,this,r)),await((b=(S=this.options).onSettled)==null?void 0:b.call(S,y,null,t,this.state.context,r)),fe(this,$t,rn).call(this,{type:"success",data:y}),y}catch(y){try{await((w=(x=R(this,He).config).onError)==null?void 0:w.call(x,y,t,this.state.context,this,r))}catch(O){Promise.reject(O)}try{await((k=(C=this.options).onError)==null?void 0:k.call(C,y,t,this.state.context,r))}catch(O){Promise.reject(O)}try{await((j=(v=R(this,He).config).onSettled)==null?void 0:j.call(v,void 0,y,this.state.variables,this.state.context,this,r))}catch(O){Promise.reject(O)}try{await((T=(D=this.options).onSettled)==null?void 0:T.call(D,void 0,y,t,this.state.context,r))}catch(O){Promise.reject(O)}throw fe(this,$t,rn).call(this,{type:"error",error:y}),y}finally{R(this,He).runNext(this)}}},po=new WeakMap,Mt=new WeakMap,He=new WeakMap,zn=new WeakMap,$t=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,Mt).forEach(r=>{r.onMutationUpdate(t)}),R(this,He).notify({mutation:this,type:"updated",action:t})})},Ul);function Kf(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Gt,At,fo,Wl,Vf=(Wl=class extends ho{constructor(t={}){super();le(this,Gt);le(this,At);le(this,fo);this.config=t,Z(this,Gt,new Set),Z(this,At,new Map),Z(this,fo,0)}build(t,n,r){const o=new Wf({client:t,mutationCache:this,mutationId:++Ao(this,fo)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){R(this,Gt).add(t);const n=Oo(t);if(typeof n=="string"){const r=R(this,At).get(n);r?r.push(t):R(this,At).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(R(this,Gt).delete(t)){const n=Oo(t);if(typeof n=="string"){const r=R(this,At).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,At).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=Oo(t);if(typeof n=="string"){const r=R(this,At).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=Oo(t);if(typeof n=="string"){const o=(r=R(this,At).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,At).clear()})}getAll(){return Array.from(R(this,Gt))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>tc(n,r))}findAll(t={}){return this.getAll().filter(n=>tc(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,At=new WeakMap,fo=new WeakMap,Wl);function Oo(e){var t;return(t=e.options.scope)==null?void 0:t.id}var Lt,Kl,Hf=(Kl=class extends ho{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??Wi(o,n);let c=this.get(i);return c||(c=new Ff({client:t,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(c)),c}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=>ec(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>ec(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,Kl),Re,un,pn,vr,Sr,fn,wr,kr,Vl,Gf=(Vl=class{constructor(e={}){le(this,Re);le(this,un);le(this,pn);le(this,vr);le(this,Sr);le(this,fn);le(this,wr);le(this,kr);Z(this,Re,e.queryCache||new Hf),Z(this,un,e.mutationCache||new Vf),Z(this,pn,e.defaultOptions||{}),Z(this,vr,new Map),Z(this,Sr,new Map),Z(this,fn,0)}mount(){Ao(this,fn)._++,R(this,fn)===1&&(Z(this,wr,Ui.subscribe(async e=>{e&&(await this.resumePausedMutations(),R(this,Re).onFocus())})),Z(this,kr,es.subscribe(async e=>{e&&(await this.resumePausedMutations(),R(this,Re).onOnline())})))}unmount(){var e,t;Ao(this,fn)._--,R(this,fn)===0&&((e=R(this,wr))==null||e.call(this),Z(this,wr,void 0),(t=R(this,kr))==null||t.call(this),Z(this,kr,void 0))}isFetching(e){return R(this,Re).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return R(this,un).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=R(this,Re).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=R(this,Re).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(hn(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return R(this,Re).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,Re).get(r.queryHash),i=o==null?void 0:o.state.data,c=Rf(t,i);if(c!==void 0)return R(this,Re).build(this,r).setData(c,{...n,manual:!0})}setQueriesData(e,t,n){return Ue.batch(()=>R(this,Re).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,Re).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=R(this,Re);Ue.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=R(this,Re);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,Re).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(at).catch(at)}invalidateQueries(e,t={}){return Ue.batch(()=>(R(this,Re).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,Re).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,Re).build(this,t);return n.isStaleByTime(hn(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 es.isOnline()?R(this,un).resumePausedMutations():Promise.resolve()}getQueryCache(){return R(this,Re)}getMutationCache(){return R(this,un)}getDefaultOptions(){return R(this,pn)}setDefaultOptions(e){Z(this,pn,e)}setQueryDefaults(e,t){R(this,vr).set(Xr(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...R(this,vr).values()],n={};return t.forEach(r=>{Cr(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){R(this,Sr).set(Xr(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...R(this,Sr).values()],n={};return t.forEach(r=>{Cr(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...R(this,pn).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Wi(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===Ki&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...R(this,pn).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){R(this,Re).clear(),R(this,un).clear()}},Re=new WeakMap,un=new WeakMap,pn=new WeakMap,vr=new WeakMap,Sr=new WeakMap,fn=new WeakMap,wr=new WeakMap,kr=new WeakMap,Vl),ad=p.createContext(void 0),Hi=e=>{const t=p.useContext(ad);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Qf=({client:e,children:t})=>(p.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),s.jsx(ad.Provider,{value:e,children:t})),cd=p.createContext(!1),Jf=()=>p.useContext(cd);cd.Provider;function Yf(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Xf=p.createContext(Yf()),Zf=()=>p.useContext(Xf),eh=(e,t,n)=>{const r=n!=null&&n.state.error&&typeof e.throwOnError=="function"?ed(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},th=e=>{p.useEffect(()=>{e.clearReset()},[e])},nh=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(o&&e.data===void 0||ed(n,[e.error,r])),rh=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))}},oh=(e,t)=>e.isLoading&&e.isFetching&&!t,sh=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,lc=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function ih(e,t,n){var m,S,b,x;const r=Jf(),o=Zf(),i=Hi(),c=i.defaultQueryOptions(e);(S=(m=i.getDefaultOptions().queries)==null?void 0:m._experimental_beforeQuery)==null||S.call(m,c);const a=i.getQueryCache().get(c.queryHash),l=e.subscribed!==!1;c._optimisticResults=r?"isRestoring":l?"optimistic":void 0,rh(c),eh(c,o,a),th(o);const u=!i.getQueryCache().get(c.queryHash),[f]=p.useState(()=>new t(i,c)),d=f.getOptimisticResult(c),h=!r&&l;if(p.useSyncExternalStore(p.useCallback(w=>{const C=h?f.subscribe(Ue.batchCalls(w)):at;return f.updateResult(),C},[f,h]),()=>f.getCurrentResult(),()=>f.getCurrentResult()),p.useEffect(()=>{f.setOptions(c)},[c,f]),sh(c,d))throw lc(c,f,o);if(nh({result:d,errorResetBoundary:o,throwOnError:c.throwOnError,query:a,suspense:c.suspense}))throw d.error;if((x=(b=i.getDefaultOptions().queries)==null?void 0:b._experimental_afterQuery)==null||x.call(b,c,d),c.experimental_prefetchInRender&&!Zr.isServer()&&oh(d,r)){const w=u?lc(c,f,o):a==null?void 0:a.promise;w==null||w.catch(at).finally(()=>{f.updateResult()})}return c.notifyOnChangeProps?d:f.trackResult(d)}function ji(e,t){return ih(e,zf)}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"},vn={sm:"4px",md:"6px",lg:"8px"},Ze={xs:"11px",sm:"12px",md:"14px"},Gi={medium:"500",semibold:"600"},eo={overlay:1e3,modal:1100,popover:1200,tooltip:1300},Is={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)"},Po={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)"},ah={obsidian:Is,paper:Po,white:Po,dark:Is,light:Po,midnight:Is,arctic:Po};function ld(e){return`--dql-${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function dc(e){const t={};for(const[n,r]of Object.entries(e))t[ld(n)]=r;return t}function pe(e){return`var(${ld(e)})`}const ch=p.createContext(null);function lh({theme:e,defaultTheme:t="dark",onThemeChange:n,applyGlobal:r=!1,children:o}){const[i,c]=p.useState(t),a=e??i,l=ah[a],u=p.useCallback(h=>{e===void 0&&c(h),n==null||n(h)},[e,n]);p.useEffect(()=>{if(!r)return;const h=dc(l),m=document.documentElement;for(const[S,b]of Object.entries(h))m.style.setProperty(S,b);return m.setAttribute("data-theme",a),()=>{for(const S of Object.keys(h))m.style.removeProperty(S);m.removeAttribute("data-theme")}},[r,a,l]);const f=p.useMemo(()=>({theme:a,tokens:l,setTheme:u}),[a,l,u]),d=r?void 0:dc(l);return s.jsx(ch.Provider,{value:f,children:s.jsx("div",{"data-theme":a,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 uc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function hs(...e){return t=>{let n=!1;const r=e.map(o=>{const i=uc(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():uc(e[o],null)}}}}function _e(...e){return p.useCallback(hs(...e),e)}function dh(e,t){const n=p.createContext(t),r=i=>{const{children:c,...a}=i,l=p.useMemo(()=>a,Object.values(a));return s.jsx(n.Provider,{value:l,children:c})};r.displayName=e+"Provider";function o(i){const c=p.useContext(n);if(c)return c;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return[r,o]}function Sn(e,t=[]){let n=[];function r(i,c){const a=p.createContext(c),l=n.length;n=[...n,c];const u=d=>{var w;const{scope:h,children:m,...S}=d,b=((w=h==null?void 0:h[e])==null?void 0:w[l])||a,x=p.useMemo(()=>S,Object.values(S));return s.jsx(b.Provider,{value:x,children:m})};u.displayName=i+"Provider";function f(d,h){var b;const m=((b=h==null?void 0:h[e])==null?void 0:b[l])||a,S=p.useContext(m);if(S)return S;if(c!==void 0)return c;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[u,f]}const o=()=>{const i=n.map(c=>p.createContext(c));return function(a){const l=(a==null?void 0:a[e])||i;return p.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,uh(o,...t)]}function uh(...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 c=r.reduce((a,{useScope:l,scopeName:u})=>{const d=l(i)[`__scope${u}`];return{...a,...d}},{});return p.useMemo(()=>({[`__scope${t.scopeName}`]:c}),[c])}};return n.scopeName=t.scopeName,n}var Qi=Gl();const ph=Ql(Qi);function jr(e){const t=fh(e),n=p.forwardRef((r,o)=>{const{children:i,...c}=r,a=p.Children.toArray(i),l=a.find(mh);if(l){const u=l.props.children,f=a.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,{...c,ref:o,children:p.isValidElement(u)?p.cloneElement(u,void 0,f):null})}return s.jsx(t,{...c,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}function fh(e){const t=p.forwardRef((n,r)=>{const{children:o,...i}=n;if(p.isValidElement(o)){const c=yh(o),a=gh(i,o.props);return o.type!==p.Fragment&&(a.ref=r?hs(r,c):c),p.cloneElement(o,a)}return p.Children.count(o)>1?p.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var dd=Symbol("radix.slottable");function hh(e){const t=({children:n})=>s.jsx(s.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=dd,t}function mh(e){return p.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===dd}function gh(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{const l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}function yh(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 bh=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Te=bh.reduce((e,t)=>{const n=jr(`Primitive.${t}`),r=p.forwardRef((o,i)=>{const{asChild:c,...a}=o,l=c?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),s.jsx(l,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function ud(e,t){e&&Qi.flushSync(()=>e.dispatchEvent(t))}function mn(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 xh(e,t=globalThis==null?void 0:globalThis.document){const n=mn(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 vh="DismissableLayer",Ei="dismissableLayer.update",Sh="dismissableLayer.pointerDownOutside",wh="dismissableLayer.focusOutside",pc,pd=p.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),mo=p.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:c,onDismiss:a,...l}=e,u=p.useContext(pd),[f,d]=p.useState(null),h=(f==null?void 0:f.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,m]=p.useState({}),S=_e(t,T=>d(T)),b=Array.from(u.layers),[x]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),w=b.indexOf(x),C=f?b.indexOf(f):-1,k=u.layersWithOutsidePointerEventsDisabled.size>0,v=C>=w,j=jh(T=>{const y=T.target,O=[...u.branches].some(A=>A.contains(y));!v||O||(o==null||o(T),c==null||c(T),T.defaultPrevented||a==null||a())},h),D=Eh(T=>{const y=T.target;[...u.branches].some(A=>A.contains(y))||(i==null||i(T),c==null||c(T),T.defaultPrevented||a==null||a())},h);return xh(T=>{C===u.layers.size-1&&(r==null||r(T),!T.defaultPrevented&&a&&(T.preventDefault(),a()))},h),p.useEffect(()=>{if(f)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(pc=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(f)),u.layers.add(f),fc(),()=>{n&&u.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=pc)}},[f,h,n,u]),p.useEffect(()=>()=>{f&&(u.layers.delete(f),u.layersWithOutsidePointerEventsDisabled.delete(f),fc())},[f,u]),p.useEffect(()=>{const T=()=>m({});return document.addEventListener(Ei,T),()=>document.removeEventListener(Ei,T)},[]),s.jsx(Te.div,{...l,ref:S,style:{pointerEvents:k?v?"auto":"none":void 0,...e.style},onFocusCapture:de(e.onFocusCapture,D.onFocusCapture),onBlurCapture:de(e.onBlurCapture,D.onBlurCapture),onPointerDownCapture:de(e.onPointerDownCapture,j.onPointerDownCapture)})});mo.displayName=vh;var kh="DismissableLayerBranch",Ch=p.forwardRef((e,t)=>{const n=p.useContext(pd),r=p.useRef(null),o=_e(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})});Ch.displayName=kh;function jh(e,t=globalThis==null?void 0:globalThis.document){const n=mn(e),r=p.useRef(!1),o=p.useRef(()=>{});return p.useEffect(()=>{const i=a=>{if(a.target&&!r.current){let l=function(){fd(Sh,n,u,{discrete:!0})};const u={originalEvent:a};a.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},c=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(c),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Eh(e,t=globalThis==null?void 0:globalThis.document){const n=mn(e),r=p.useRef(!1);return p.useEffect(()=>{const o=i=>{i.target&&!r.current&&fd(wh,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 fc(){const e=new CustomEvent(Ei);document.dispatchEvent(e)}function fd(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?ud(o,i):o.dispatchEvent(i)}var gn=globalThis!=null&&globalThis.document?p.useLayoutEffect:()=>{},Th=Jl[" useId ".trim().toString()]||(()=>{}),Rh=0;function Qr(e){const[t,n]=p.useState(Th());return gn(()=>{n(r=>r??String(Rh++))},[e]),t?`radix-${t}`:""}const Ah=["top","right","bottom","left"],yn=Math.min,ht=Math.max,ts=Math.round,Do=Math.floor,qt=e=>({x:e,y:e}),_h={left:"right",right:"left",bottom:"top",top:"bottom"};function Ti(e,t,n){return ht(e,yn(t,n))}function Qt(e,t){return typeof e=="function"?e(t):e}function Jt(e){return e.split("-")[0]}function Ar(e){return e.split("-")[1]}function Ji(e){return e==="x"?"y":"x"}function Yi(e){return e==="y"?"height":"width"}function zt(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function Xi(e){return Ji(zt(e))}function Oh(e,t,n){n===void 0&&(n=!1);const r=Ar(e),o=Xi(e),i=Yi(o);let c=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(c=ns(c)),[c,ns(c)]}function Ph(e){const t=ns(e);return[Ri(e),t,Ri(t)]}function Ri(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const hc=["left","right"],mc=["right","left"],Dh=["top","bottom"],Ih=["bottom","top"];function Mh(e,t,n){switch(e){case"top":case"bottom":return n?t?mc:hc:t?hc:mc;case"left":case"right":return t?Dh:Ih;default:return[]}}function $h(e,t,n,r){const o=Ar(e);let i=Mh(Jt(e),n==="start",r);return o&&(i=i.map(c=>c+"-"+o),t&&(i=i.concat(i.map(Ri)))),i}function ns(e){const t=Jt(e);return _h[t]+e.slice(t.length)}function Lh(e){return{top:0,right:0,bottom:0,left:0,...e}}function hd(e){return typeof e!="number"?Lh(e):{top:e,right:e,bottom:e,left:e}}function rs(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 gc(e,t,n){let{reference:r,floating:o}=e;const i=zt(t),c=Xi(t),a=Yi(c),l=Jt(t),u=i==="y",f=r.x+r.width/2-o.width/2,d=r.y+r.height/2-o.height/2,h=r[a]/2-o[a]/2;let m;switch(l){case"top":m={x:f,y:r.y-o.height};break;case"bottom":m={x:f,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(Ar(t)){case"start":m[c]-=h*(n&&u?-1:1);break;case"end":m[c]+=h*(n&&u?-1:1);break}return m}async function Nh(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:i,rects:c,elements:a,strategy:l}=e,{boundary:u="clippingAncestors",rootBoundary:f="viewport",elementContext:d="floating",altBoundary:h=!1,padding:m=0}=Qt(t,e),S=hd(m),x=a[h?d==="floating"?"reference":"floating":d],w=rs(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(x)))==null||n?x:x.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(a.floating)),boundary:u,rootBoundary:f,strategy:l})),C=d==="floating"?{x:r,y:o,width:c.floating.width,height:c.floating.height}:c.reference,k=await(i.getOffsetParent==null?void 0:i.getOffsetParent(a.floating)),v=await(i.isElement==null?void 0:i.isElement(k))?await(i.getScale==null?void 0:i.getScale(k))||{x:1,y:1}:{x:1,y:1},j=rs(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:C,offsetParent:k,strategy:l}):C);return{top:(w.top-j.top+S.top)/v.y,bottom:(j.bottom-w.bottom+S.bottom)/v.y,left:(w.left-j.left+S.left)/v.x,right:(j.right-w.right+S.right)/v.x}}const Bh=50,Fh=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:c}=n,a=c.detectOverflow?c:{...c,detectOverflow:Nh},l=await(c.isRTL==null?void 0:c.isRTL(t));let u=await c.getElementRects({reference:e,floating:t,strategy:o}),{x:f,y:d}=gc(u,r,l),h=r,m=0;const S={};for(let b=0;b<i.length;b++){const x=i[b];if(!x)continue;const{name:w,fn:C}=x,{x:k,y:v,data:j,reset:D}=await C({x:f,y:d,initialPlacement:r,placement:h,strategy:o,middlewareData:S,rects:u,platform:a,elements:{reference:e,floating:t}});f=k??f,d=v??d,S[w]={...S[w],...j},D&&m<Bh&&(m++,typeof D=="object"&&(D.placement&&(h=D.placement),D.rects&&(u=D.rects===!0?await c.getElementRects({reference:e,floating:t,strategy:o}):D.rects),{x:f,y:d}=gc(u,h,l)),b=-1)}return{x:f,y:d,placement:h,strategy:o,middlewareData:S}},zh=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:c,elements:a,middlewareData:l}=t,{element:u,padding:f=0}=Qt(e,t)||{};if(u==null)return{};const d=hd(f),h={x:n,y:r},m=Xi(o),S=Yi(m),b=await c.getDimensions(u),x=m==="y",w=x?"top":"left",C=x?"bottom":"right",k=x?"clientHeight":"clientWidth",v=i.reference[S]+i.reference[m]-h[m]-i.floating[S],j=h[m]-i.reference[m],D=await(c.getOffsetParent==null?void 0:c.getOffsetParent(u));let T=D?D[k]:0;(!T||!await(c.isElement==null?void 0:c.isElement(D)))&&(T=a.floating[k]||i.floating[S]);const y=v/2-j/2,O=T/2-b[S]/2-1,A=yn(d[w],O),_=yn(d[C],O),P=A,$=T-b[S]-_,q=T/2-b[S]/2+y,G=Ti(P,q,$),J=!l.arrow&&Ar(o)!=null&&q!==G&&i.reference[S]/2-(q<P?A:_)-b[S]/2<0,H=J?q<P?q-P:q-$:0;return{[m]:h[m]+H,data:{[m]:G,centerOffset:q-G-H,...J&&{alignmentOffset:H}},reset:J}}}),qh=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:i,rects:c,initialPlacement:a,platform:l,elements:u}=t,{mainAxis:f=!0,crossAxis:d=!0,fallbackPlacements:h,fallbackStrategy:m="bestFit",fallbackAxisSideDirection:S="none",flipAlignment:b=!0,...x}=Qt(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const w=Jt(o),C=zt(a),k=Jt(a)===a,v=await(l.isRTL==null?void 0:l.isRTL(u.floating)),j=h||(k||!b?[ns(a)]:Ph(a)),D=S!=="none";!h&&D&&j.push(...$h(a,b,S,v));const T=[a,...j],y=await l.detectOverflow(t,x),O=[];let A=((r=i.flip)==null?void 0:r.overflows)||[];if(f&&O.push(y[w]),d){const q=Oh(o,c,v);O.push(y[q[0]],y[q[1]])}if(A=[...A,{placement:o,overflows:O}],!O.every(q=>q<=0)){var _,P;const q=(((_=i.flip)==null?void 0:_.index)||0)+1,G=T[q];if(G&&(!(d==="alignment"?C!==zt(G):!1)||A.every(L=>zt(L.placement)===C?L.overflows[0]>0:!0)))return{data:{index:q,overflows:A},reset:{placement:G}};let J=(P=A.filter(H=>H.overflows[0]<=0).sort((H,L)=>H.overflows[1]-L.overflows[1])[0])==null?void 0:P.placement;if(!J)switch(m){case"bestFit":{var $;const H=($=A.filter(L=>{if(D){const M=zt(L.placement);return M===C||M==="y"}return!0}).map(L=>[L.placement,L.overflows.filter(M=>M>0).reduce((M,X)=>M+X,0)]).sort((L,M)=>L[1]-M[1])[0])==null?void 0:$[0];H&&(J=H);break}case"initialPlacement":J=a;break}if(o!==J)return{reset:{placement:J}}}return{}}}};function yc(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function bc(e){return Ah.some(t=>e[t]>=0)}const Uh=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 c=await r.detectOverflow(t,{...i,elementContext:"reference"}),a=yc(c,n.reference);return{data:{referenceHiddenOffsets:a,referenceHidden:bc(a)}}}case"escaped":{const c=await r.detectOverflow(t,{...i,altBoundary:!0}),a=yc(c,n.floating);return{data:{escapedOffsets:a,escaped:bc(a)}}}default:return{}}}}},md=new Set(["left","top"]);async function Wh(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),c=Jt(n),a=Ar(n),l=zt(n)==="y",u=md.has(c)?-1:1,f=i&&l?-1:1,d=Qt(t,e);let{mainAxis:h,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 a&&typeof S=="number"&&(m=a==="end"?S*-1:S),l?{x:m*f,y:h*u}:{x:h*u,y:m*f}}const Kh=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:i,placement:c,middlewareData:a}=t,l=await Wh(t,e);return c===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:i+l.y,data:{...l,placement:c}}}}},Vh=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:c=!0,crossAxis:a=!1,limiter:l={fn:w=>{let{x:C,y:k}=w;return{x:C,y:k}}},...u}=Qt(e,t),f={x:n,y:r},d=await i.detectOverflow(t,u),h=zt(Jt(o)),m=Ji(h);let S=f[m],b=f[h];if(c){const w=m==="y"?"top":"left",C=m==="y"?"bottom":"right",k=S+d[w],v=S-d[C];S=Ti(k,S,v)}if(a){const w=h==="y"?"top":"left",C=h==="y"?"bottom":"right",k=b+d[w],v=b-d[C];b=Ti(k,b,v)}const x=l.fn({...t,[m]:S,[h]:b});return{...x,data:{x:x.x-n,y:x.y-r,enabled:{[m]:c,[h]:a}}}}}},Hh=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:c}=t,{offset:a=0,mainAxis:l=!0,crossAxis:u=!0}=Qt(e,t),f={x:n,y:r},d=zt(o),h=Ji(d);let m=f[h],S=f[d];const b=Qt(a,t),x=typeof b=="number"?{mainAxis:b,crossAxis:0}:{mainAxis:0,crossAxis:0,...b};if(l){const k=h==="y"?"height":"width",v=i.reference[h]-i.floating[k]+x.mainAxis,j=i.reference[h]+i.reference[k]-x.mainAxis;m<v?m=v:m>j&&(m=j)}if(u){var w,C;const k=h==="y"?"width":"height",v=md.has(Jt(o)),j=i.reference[d]-i.floating[k]+(v&&((w=c.offset)==null?void 0:w[d])||0)+(v?0:x.crossAxis),D=i.reference[d]+i.reference[k]+(v?0:((C=c.offset)==null?void 0:C[d])||0)-(v?x.crossAxis:0);S<j?S=j:S>D&&(S=D)}return{[h]:m,[d]:S}}}},Gh=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:i,platform:c,elements:a}=t,{apply:l=()=>{},...u}=Qt(e,t),f=await c.detectOverflow(t,u),d=Jt(o),h=Ar(o),m=zt(o)==="y",{width:S,height:b}=i.floating;let x,w;d==="top"||d==="bottom"?(x=d,w=h===(await(c.isRTL==null?void 0:c.isRTL(a.floating))?"start":"end")?"left":"right"):(w=d,x=h==="end"?"top":"bottom");const C=b-f.top-f.bottom,k=S-f.left-f.right,v=yn(b-f[x],C),j=yn(S-f[w],k),D=!t.middlewareData.shift;let T=v,y=j;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(y=k),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(T=C),D&&!h){const A=ht(f.left,0),_=ht(f.right,0),P=ht(f.top,0),$=ht(f.bottom,0);m?y=S-2*(A!==0||_!==0?A+_:ht(f.left,f.right)):T=b-2*(P!==0||$!==0?P+$:ht(f.top,f.bottom))}await l({...t,availableWidth:y,availableHeight:T});const O=await c.getDimensions(a.floating);return S!==O.width||b!==O.height?{reset:{rects:!0}}:{}}}};function ms(){return typeof window<"u"}function _r(e){return gd(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=(gd(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function gd(e){return ms()?e instanceof Node||e instanceof mt(e).Node:!1}function Ot(e){return ms()?e instanceof Element||e instanceof mt(e).Element:!1}function Yt(e){return ms()?e instanceof HTMLElement||e instanceof mt(e).HTMLElement:!1}function xc(e){return!ms()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof mt(e).ShadowRoot}function go(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 Qh(e){return/^(table|td|th)$/.test(_r(e))}function gs(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const Jh=/transform|translate|scale|rotate|perspective|filter/,Yh=/paint|layout|strict|content/,Tn=e=>!!e&&e!=="none";let Ms;function Zi(e){const t=Ot(e)?Pt(e):e;return Tn(t.transform)||Tn(t.translate)||Tn(t.scale)||Tn(t.rotate)||Tn(t.perspective)||!ea()&&(Tn(t.backdropFilter)||Tn(t.filter))||Jh.test(t.willChange||"")||Yh.test(t.contain||"")}function Xh(e){let t=bn(e);for(;Yt(t)&&!Er(t);){if(Zi(t))return t;if(gs(t))return null;t=bn(t)}return null}function ea(){return Ms==null&&(Ms=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ms}function Er(e){return/^(html|body|#document)$/.test(_r(e))}function Pt(e){return mt(e).getComputedStyle(e)}function ys(e){return Ot(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function bn(e){if(_r(e)==="html")return e;const t=e.assignedSlot||e.parentNode||xc(e)&&e.host||Ut(e);return xc(t)?t.host:t}function yd(e){const t=bn(e);return Er(t)?e.ownerDocument?e.ownerDocument.body:e.body:Yt(t)&&go(t)?t:yd(t)}function to(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=yd(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),c=mt(o);if(i){const a=Ai(c);return t.concat(c,c.visualViewport||[],go(o)?o:[],a&&n?to(a):[])}else return t.concat(o,to(o,[],n))}function Ai(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function bd(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,c=o?e.offsetHeight:r,a=ts(n)!==i||ts(r)!==c;return a&&(n=i,r=c),{width:n,height:r,$:a}}function ta(e){return Ot(e)?e:e.contextElement}function cr(e){const t=ta(e);if(!Yt(t))return qt(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=bd(t);let c=(i?ts(n.width):n.width)/r,a=(i?ts(n.height):n.height)/o;return(!c||!Number.isFinite(c))&&(c=1),(!a||!Number.isFinite(a))&&(a=1),{x:c,y:a}}const Zh=qt(0);function xd(e){const t=mt(e);return!ea()||!t.visualViewport?Zh:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function em(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=ta(e);let c=qt(1);t&&(r?Ot(r)&&(c=cr(r)):c=cr(e));const a=em(i,n,r)?xd(i):qt(0);let l=(o.left+a.x)/c.x,u=(o.top+a.y)/c.y,f=o.width/c.x,d=o.height/c.y;if(i){const h=mt(i),m=r&&Ot(r)?mt(r):r;let S=h,b=Ai(S);for(;b&&r&&m!==S;){const x=cr(b),w=b.getBoundingClientRect(),C=Pt(b),k=w.left+(b.clientLeft+parseFloat(C.paddingLeft))*x.x,v=w.top+(b.clientTop+parseFloat(C.paddingTop))*x.y;l*=x.x,u*=x.y,f*=x.x,d*=x.y,l+=k,u+=v,S=mt(b),b=Ai(S)}}return rs({width:f,height:d,x:l,y:u})}function bs(e,t){const n=ys(e).scrollLeft;return t?t.left+n:Un(Ut(e)).left+n}function vd(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-bs(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function tm(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const i=o==="fixed",c=Ut(r),a=t?gs(t.floating):!1;if(r===c||a&&i)return n;let l={scrollLeft:0,scrollTop:0},u=qt(1);const f=qt(0),d=Yt(r);if((d||!d&&!i)&&((_r(r)!=="body"||go(c))&&(l=ys(r)),d)){const m=Un(r);u=cr(r),f.x=m.x+r.clientLeft,f.y=m.y+r.clientTop}const h=c&&!d&&!i?vd(c,l):qt(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-l.scrollLeft*u.x+f.x+h.x,y:n.y*u.y-l.scrollTop*u.y+f.y+h.y}}function nm(e){return Array.from(e.getClientRects())}function rm(e){const t=Ut(e),n=ys(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 c=-n.scrollLeft+bs(e);const a=-n.scrollTop;return Pt(r).direction==="rtl"&&(c+=ht(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:c,y:a}}const vc=25;function om(e,t){const n=mt(e),r=Ut(e),o=n.visualViewport;let i=r.clientWidth,c=r.clientHeight,a=0,l=0;if(o){i=o.width,c=o.height;const f=ea();(!f||f&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const u=bs(r);if(u<=0){const f=r.ownerDocument,d=f.body,h=getComputedStyle(d),m=f.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,S=Math.abs(r.clientWidth-d.clientWidth-m);S<=vc&&(i-=S)}else u<=vc&&(i+=u);return{width:i,height:c,x:a,y:l}}function sm(e,t){const n=Un(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=Yt(e)?cr(e):qt(1),c=e.clientWidth*i.x,a=e.clientHeight*i.y,l=o*i.x,u=r*i.y;return{width:c,height:a,x:l,y:u}}function Sc(e,t,n){let r;if(t==="viewport")r=om(e,n);else if(t==="document")r=rm(Ut(e));else if(Ot(t))r=sm(t,n);else{const o=xd(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return rs(r)}function Sd(e,t){const n=bn(e);return n===t||!Ot(n)||Er(n)?!1:Pt(n).position==="fixed"||Sd(n,t)}function im(e,t){const n=t.get(e);if(n)return n;let r=to(e,[],!1).filter(a=>Ot(a)&&_r(a)!=="body"),o=null;const i=Pt(e).position==="fixed";let c=i?bn(e):e;for(;Ot(c)&&!Er(c);){const a=Pt(c),l=Zi(c);!l&&a.position==="fixed"&&(o=null),(i?!l&&!o:!l&&a.position==="static"&&!!o&&(o.position==="absolute"||o.position==="fixed")||go(c)&&!l&&Sd(e,c))?r=r.filter(f=>f!==c):o=a,c=bn(c)}return t.set(e,r),r}function am(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const c=[...n==="clippingAncestors"?gs(t)?[]:im(t,this._c):[].concat(n),r],a=Sc(t,c[0],o);let l=a.top,u=a.right,f=a.bottom,d=a.left;for(let h=1;h<c.length;h++){const m=Sc(t,c[h],o);l=ht(m.top,l),u=yn(m.right,u),f=yn(m.bottom,f),d=ht(m.left,d)}return{width:u-d,height:f-l,x:d,y:l}}function cm(e){const{width:t,height:n}=bd(e);return{width:t,height:n}}function lm(e,t,n){const r=Yt(t),o=Ut(t),i=n==="fixed",c=Un(e,!0,i,t);let a={scrollLeft:0,scrollTop:0};const l=qt(0);function u(){l.x=bs(o)}if(r||!r&&!i)if((_r(t)!=="body"||go(o))&&(a=ys(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 f=o&&!r&&!i?vd(o,a):qt(0),d=c.left+a.scrollLeft-l.x-f.x,h=c.top+a.scrollTop-l.y-f.y;return{x:d,y:h,width:c.width,height:c.height}}function $s(e){return Pt(e).position==="static"}function wc(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 wd(e,t){const n=mt(e);if(gs(e))return n;if(!Yt(e)){let o=bn(e);for(;o&&!Er(o);){if(Ot(o)&&!$s(o))return o;o=bn(o)}return n}let r=wc(e,t);for(;r&&Qh(r)&&$s(r);)r=wc(r,t);return r&&Er(r)&&$s(r)&&!Zi(r)?n:r||Xh(e)||n}const dm=async function(e){const t=this.getOffsetParent||wd,n=this.getDimensions,r=await n(e.floating);return{reference:lm(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function um(e){return Pt(e).direction==="rtl"}const pm={convertOffsetParentRelativeRectToViewportRelativeRect:tm,getDocumentElement:Ut,getClippingRect:am,getOffsetParent:wd,getElementRects:dm,getClientRects:nm,getDimensions:cm,getScale:cr,isElement:Ot,isRTL:um};function kd(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function fm(e,t){let n=null,r;const o=Ut(e);function i(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function c(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),i();const u=e.getBoundingClientRect(),{left:f,top:d,width:h,height:m}=u;if(a||t(),!h||!m)return;const S=Do(d),b=Do(o.clientWidth-(f+h)),x=Do(o.clientHeight-(d+m)),w=Do(f),k={rootMargin:-S+"px "+-b+"px "+-x+"px "+-w+"px",threshold:ht(0,yn(1,l))||1};let v=!0;function j(D){const T=D[0].intersectionRatio;if(T!==l){if(!v)return c();T?c(!1,T):r=setTimeout(()=>{c(!1,1e-7)},1e3)}T===1&&!kd(u,e.getBoundingClientRect())&&c(),v=!1}try{n=new IntersectionObserver(j,{...k,root:o.ownerDocument})}catch{n=new IntersectionObserver(j,k)}n.observe(e)}return c(!0),i}function hm(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:c=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,u=ta(e),f=o||i?[...u?to(u):[],...t?to(t):[]]:[];f.forEach(w=>{o&&w.addEventListener("scroll",n,{passive:!0}),i&&w.addEventListener("resize",n)});const d=u&&a?fm(u,n):null;let h=-1,m=null;c&&(m=new ResizeObserver(w=>{let[C]=w;C&&C.target===u&&m&&t&&(m.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var k;(k=m)==null||k.observe(t)})),n()}),u&&!l&&m.observe(u),t&&m.observe(t));let S,b=l?Un(e):null;l&&x();function x(){const w=Un(e);b&&!kd(b,w)&&n(),b=w,S=requestAnimationFrame(x)}return n(),()=>{var w;f.forEach(C=>{o&&C.removeEventListener("scroll",n),i&&C.removeEventListener("resize",n)}),d==null||d(),(w=m)==null||w.disconnect(),m=null,l&&cancelAnimationFrame(S)}}const mm=Kh,gm=Vh,ym=qh,bm=Gh,xm=Uh,kc=zh,vm=Hh,Sm=(e,t,n)=>{const r=new Map,o={platform:pm,...n},i={...o.platform,_c:r};return Fh(e,t,{...o,platform:i})};var wm=typeof document<"u",km=function(){},Go=wm?p.useLayoutEffect:km;function os(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(!os(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)&&!os(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function Cd(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Cc(e,t){const n=Cd(e);return Math.round(t*n)/n}function Ls(e){const t=p.useRef(e);return Go(()=>{t.current=e}),t}function Cm(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:c}={},transform:a=!0,whileElementsMounted:l,open:u}=e,[f,d]=p.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[h,m]=p.useState(r);os(h,r)||m(r);const[S,b]=p.useState(null),[x,w]=p.useState(null),C=p.useCallback(L=>{L!==D.current&&(D.current=L,b(L))},[]),k=p.useCallback(L=>{L!==T.current&&(T.current=L,w(L))},[]),v=i||S,j=c||x,D=p.useRef(null),T=p.useRef(null),y=p.useRef(f),O=l!=null,A=Ls(l),_=Ls(o),P=Ls(u),$=p.useCallback(()=>{if(!D.current||!T.current)return;const L={placement:t,strategy:n,middleware:h};_.current&&(L.platform=_.current),Sm(D.current,T.current,L).then(M=>{const X={...M,isPositioned:P.current!==!1};q.current&&!os(y.current,X)&&(y.current=X,Qi.flushSync(()=>{d(X)}))})},[h,t,n,_,P]);Go(()=>{u===!1&&y.current.isPositioned&&(y.current.isPositioned=!1,d(L=>({...L,isPositioned:!1})))},[u]);const q=p.useRef(!1);Go(()=>(q.current=!0,()=>{q.current=!1}),[]),Go(()=>{if(v&&(D.current=v),j&&(T.current=j),v&&j){if(A.current)return A.current(v,j,$);$()}},[v,j,$,A,O]);const G=p.useMemo(()=>({reference:D,floating:T,setReference:C,setFloating:k}),[C,k]),J=p.useMemo(()=>({reference:v,floating:j}),[v,j]),H=p.useMemo(()=>{const L={position:n,left:0,top:0};if(!J.floating)return L;const M=Cc(J.floating,f.x),X=Cc(J.floating,f.y);return a?{...L,transform:"translate("+M+"px, "+X+"px)",...Cd(J.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:M,top:X}},[n,a,J.floating,f.x,f.y]);return p.useMemo(()=>({...f,update:$,refs:G,elements:J,floatingStyles:H}),[f,$,G,J,H])}const jm=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?kc({element:r.current,padding:o}).fn(n):{}:r?kc({element:r,padding:o}).fn(n):{}}}},Em=(e,t)=>{const n=mm(e);return{name:n.name,fn:n.fn,options:[e,t]}},Tm=(e,t)=>{const n=gm(e);return{name:n.name,fn:n.fn,options:[e,t]}},Rm=(e,t)=>({fn:vm(e).fn,options:[e,t]}),Am=(e,t)=>{const n=ym(e);return{name:n.name,fn:n.fn,options:[e,t]}},_m=(e,t)=>{const n=bm(e);return{name:n.name,fn:n.fn,options:[e,t]}},Om=(e,t)=>{const n=xm(e);return{name:n.name,fn:n.fn,options:[e,t]}},Pm=(e,t)=>{const n=jm(e);return{name:n.name,fn:n.fn,options:[e,t]}};var Dm="Arrow",jd=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"})})});jd.displayName=Dm;var Im=jd;function Mm(e){const[t,n]=p.useState(void 0);return gn(()=>{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 c,a;if("borderBoxSize"in i){const l=i.borderBoxSize,u=Array.isArray(l)?l[0]:l;c=u.inlineSize,a=u.blockSize}else c=e.offsetWidth,a=e.offsetHeight;n({width:c,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var na="Popper",[Ed,Or]=Sn(na),[$m,Td]=Ed(na),Rd=e=>{const{__scopePopper:t,children:n}=e,[r,o]=p.useState(null);return s.jsx($m,{scope:t,anchor:r,onAnchorChange:o,children:n})};Rd.displayName=na;var Ad="PopperAnchor",_d=p.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=Td(Ad,n),c=p.useRef(null),a=_e(t,c),l=p.useRef(null);return p.useEffect(()=>{const u=l.current;l.current=(r==null?void 0:r.current)||c.current,u!==l.current&&i.onAnchorChange(l.current)}),r?null:s.jsx(Te.div,{...o,ref:a})});_d.displayName=Ad;var ra="PopperContent",[Lm,Nm]=Ed(ra),Od=p.forwardRef((e,t)=>{var ce,ke,xe,Ie,We,Be;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:i="center",alignOffset:c=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:u=[],collisionPadding:f=0,sticky:d="partial",hideWhenDetached:h=!1,updatePositionStrategy:m="optimized",onPlaced:S,...b}=e,x=Td(ra,n),[w,C]=p.useState(null),k=_e(t,Ee=>C(Ee)),[v,j]=p.useState(null),D=Mm(v),T=(D==null?void 0:D.width)??0,y=(D==null?void 0:D.height)??0,O=r+(i!=="center"?"-"+i:""),A=typeof f=="number"?f:{top:0,right:0,bottom:0,left:0,...f},_=Array.isArray(u)?u:[u],P=_.length>0,$={padding:A,boundary:_.filter(Fm),altBoundary:P},{refs:q,floatingStyles:G,placement:J,isPositioned:H,middlewareData:L}=Cm({strategy:"fixed",placement:O,whileElementsMounted:(...Ee)=>hm(...Ee,{animationFrame:m==="always"}),elements:{reference:x.anchor},middleware:[Em({mainAxis:o+y,alignmentAxis:c}),l&&Tm({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?Rm():void 0,...$}),l&&Am({...$}),_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`)}}),v&&Pm({element:v,padding:a}),zm({arrowWidth:T,arrowHeight:y}),h&&Om({strategy:"referenceHidden",...$})]}),[M,X]=Id(J),W=mn(S);gn(()=>{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 gn(()=>{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":[(Ie=L.transformOrigin)==null?void 0:Ie.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(Lm,{scope:n,placedSide:M,onArrowChange:j,arrowX:te,arrowY:F,shouldHideArrow:K,children:s.jsx(Te.div,{"data-side":M,"data-align":X,...b,ref:k,style:{...b.style,animation:H?void 0:"none"}})})})});Od.displayName=ra;var Pd="PopperArrow",Bm={top:"bottom",right:"left",bottom:"top",left:"right"},Dd=p.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,i=Nm(Pd,r),c=Bm[i.placedSide];return s.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[c]: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(Im,{...o,ref:n,style:{...o.style,display:"block"}})})});Dd.displayName=Pd;function Fm(e){return e!==null}var zm=e=>({name:"transformOrigin",options:e,fn(t){var x,w,C;const{placement:n,rects:r,middlewareData:o}=t,c=((x=o.arrow)==null?void 0:x.centerOffset)!==0,a=c?0:e.arrowWidth,l=c?0:e.arrowHeight,[u,f]=Id(n),d={start:"0%",center:"50%",end:"100%"}[f],h=(((w=o.arrow)==null?void 0:w.x)??0)+a/2,m=(((C=o.arrow)==null?void 0:C.y)??0)+l/2;let S="",b="";return u==="bottom"?(S=c?d:`${h}px`,b=`${-l}px`):u==="top"?(S=c?d:`${h}px`,b=`${r.floating.height+l}px`):u==="right"?(S=`${-l}px`,b=c?d:`${m}px`):u==="left"&&(S=`${r.floating.width+l}px`,b=c?d:`${m}px`),{data:{x:S,y:b}}}});function Id(e){const[t,n="center"]=e.split("-");return[t,n]}var qm=Rd,xs=_d,oa=Od,sa=Dd,Um="Portal",yo=p.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,i]=p.useState(!1);gn(()=>i(!0),[]);const c=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return c?ph.createPortal(s.jsx(Te.div,{...r,ref:t}),c):null});yo.displayName=Um;function Wm(e,t){return p.useReducer((n,r)=>t[n][r]??n,e)}var wt=e=>{const{present:t,children:n}=e,r=Km(t),o=typeof n=="function"?n({present:r.isPresent}):p.Children.only(n),i=_e(r.ref,Vm(o));return typeof n=="function"||r.isPresent?p.cloneElement(o,{ref:i}):null};wt.displayName="Presence";function Km(e){const[t,n]=p.useState(),r=p.useRef(null),o=p.useRef(e),i=p.useRef("none"),c=e?"mounted":"unmounted",[a,l]=Wm(c,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return p.useEffect(()=>{const u=Io(r.current);i.current=a==="mounted"?u:"none"},[a]),gn(()=>{const u=r.current,f=o.current;if(f!==e){const h=i.current,m=Io(u);e?l("MOUNT"):m==="none"||(u==null?void 0:u.display)==="none"?l("UNMOUNT"):l(f&&h!==m?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),gn(()=>{if(t){let u;const f=t.ownerDocument.defaultView??window,d=m=>{const b=Io(r.current).includes(CSS.escape(m.animationName));if(m.target===t&&b&&(l("ANIMATION_END"),!o.current)){const x=t.style.animationFillMode;t.style.animationFillMode="forwards",u=f.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=x)})}},h=m=>{m.target===t&&(i.current=Io(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{f.clearTimeout(u),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:p.useCallback(u=>{r.current=u?getComputedStyle(u):null,n(u)},[])}}function Io(e){return(e==null?void 0:e.animationName)||"none"}function Vm(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 Hm=Jl[" useInsertionEffect ".trim().toString()]||gn;function ia({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,i,c]=Gm({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const f=p.useRef(e!==void 0);p.useEffect(()=>{const d=f.current;d!==a&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),f.current=a},[a,r])}const u=p.useCallback(f=>{var d;if(a){const h=Qm(f)?f(e):f;h!==e&&((d=c.current)==null||d.call(c,h))}else i(f)},[a,e,i,c]);return[l,u]}function Gm({defaultProp:e,onChange:t}){const[n,r]=p.useState(e),o=p.useRef(n),i=p.useRef(t);return Hm(()=>{i.current=t},[t]),p.useEffect(()=>{var c;o.current!==n&&((c=i.current)==null||c.call(i,n),o.current=n)},[n,o]),[n,r,i]}function Qm(e){return typeof e=="function"}var Jm=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"}),Ym="VisuallyHidden",Md=p.forwardRef((e,t)=>s.jsx(Te.span,{...e,ref:t,style:{...Jm,...e.style}}));Md.displayName=Ym;var Xm=Md,[vs]=Sn("Tooltip",[Or]),Ss=Or(),$d="TooltipProvider",Zm=700,_i="tooltip.open",[eg,aa]=vs($d),Ld=e=>{const{__scopeTooltip:t,delayDuration:n=Zm,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,c=p.useRef(!0),a=p.useRef(!1),l=p.useRef(0);return p.useEffect(()=>{const u=l.current;return()=>window.clearTimeout(u)},[]),s.jsx(eg,{scope:t,isOpenDelayedRef:c,delayDuration:n,onOpen:p.useCallback(()=>{window.clearTimeout(l.current),c.current=!1},[]),onClose:p.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>c.current=!0,r)},[r]),isPointerInTransitRef:a,onPointerInTransitChange:p.useCallback(u=>{a.current=u},[]),disableHoverableContent:o,children:i})};Ld.displayName=$d;var no="Tooltip",[tg,bo]=vs(no),Nd=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o,onOpenChange:i,disableHoverableContent:c,delayDuration:a}=e,l=aa(no,e.__scopeTooltip),u=Ss(t),[f,d]=p.useState(null),h=Qr(),m=p.useRef(0),S=c??l.disableHoverableContent,b=a??l.delayDuration,x=p.useRef(!1),[w,C]=ia({prop:r,defaultProp:o??!1,onChange:T=>{T?(l.onOpen(),document.dispatchEvent(new CustomEvent(_i))):l.onClose(),i==null||i(T)},caller:no}),k=p.useMemo(()=>w?x.current?"delayed-open":"instant-open":"closed",[w]),v=p.useCallback(()=>{window.clearTimeout(m.current),m.current=0,x.current=!1,C(!0)},[C]),j=p.useCallback(()=>{window.clearTimeout(m.current),m.current=0,C(!1)},[C]),D=p.useCallback(()=>{window.clearTimeout(m.current),m.current=window.setTimeout(()=>{x.current=!0,C(!0),m.current=0},b)},[b,C]);return p.useEffect(()=>()=>{m.current&&(window.clearTimeout(m.current),m.current=0)},[]),s.jsx(qm,{...u,children:s.jsx(tg,{scope:t,contentId:h,open:w,stateAttribute:k,trigger:f,onTriggerChange:d,onTriggerEnter:p.useCallback(()=>{l.isOpenDelayedRef.current?D():v()},[l.isOpenDelayedRef,D,v]),onTriggerLeave:p.useCallback(()=>{S?j():(window.clearTimeout(m.current),m.current=0)},[j,S]),onOpen:v,onClose:j,disableHoverableContent:S,children:n})})};Nd.displayName=no;var Oi="TooltipTrigger",Bd=p.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=bo(Oi,n),i=aa(Oi,n),c=Ss(n),a=p.useRef(null),l=_e(t,a,o.onTriggerChange),u=p.useRef(!1),f=p.useRef(!1),d=p.useCallback(()=>u.current=!1,[]);return p.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),s.jsx(xs,{asChild:!0,...c,children:s.jsx(Te.button,{"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute,...r,ref:l,onPointerMove:de(e.onPointerMove,h=>{h.pointerType!=="touch"&&!f.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),f.current=!0)}),onPointerLeave:de(e.onPointerLeave,()=>{o.onTriggerLeave(),f.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)})})});Bd.displayName=Oi;var ca="TooltipPortal",[ng,rg]=vs(ca,{forceMount:void 0}),Fd=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:o}=e,i=bo(ca,t);return s.jsx(ng,{scope:t,forceMount:n,children:s.jsx(wt,{present:n||i.open,children:s.jsx(yo,{asChild:!0,container:o,children:r})})})};Fd.displayName=ca;var Tr="TooltipContent",zd=p.forwardRef((e,t)=>{const n=rg(Tr,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,c=bo(Tr,e.__scopeTooltip);return s.jsx(wt,{present:r||c.open,children:c.disableHoverableContent?s.jsx(qd,{side:o,...i,ref:t}):s.jsx(og,{side:o,...i,ref:t})})}),og=p.forwardRef((e,t)=>{const n=bo(Tr,e.__scopeTooltip),r=aa(Tr,e.__scopeTooltip),o=p.useRef(null),i=_e(t,o),[c,a]=p.useState(null),{trigger:l,onClose:u}=n,f=o.current,{onPointerInTransitChange:d}=r,h=p.useCallback(()=>{a(null),d(!1)},[d]),m=p.useCallback((S,b)=>{const x=S.currentTarget,w={x:S.clientX,y:S.clientY},C=lg(w,x.getBoundingClientRect()),k=dg(w,C),v=ug(b.getBoundingClientRect()),j=fg([...k,...v]);a(j),d(!0)},[d]);return p.useEffect(()=>()=>h(),[h]),p.useEffect(()=>{if(l&&f){const S=x=>m(x,f),b=x=>m(x,l);return l.addEventListener("pointerleave",S),f.addEventListener("pointerleave",b),()=>{l.removeEventListener("pointerleave",S),f.removeEventListener("pointerleave",b)}}},[l,f,m,h]),p.useEffect(()=>{if(c){const S=b=>{const x=b.target,w={x:b.clientX,y:b.clientY},C=(l==null?void 0:l.contains(x))||(f==null?void 0:f.contains(x)),k=!pg(w,c);C?h():k&&(h(),u())};return document.addEventListener("pointermove",S),()=>document.removeEventListener("pointermove",S)}},[l,f,c,u,h]),s.jsx(qd,{...e,ref:i})}),[sg,ig]=vs(no,{isInside:!1}),ag=hh("TooltipContent"),qd=p.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:c,...a}=e,l=bo(Tr,n),u=Ss(n),{onClose:f}=l;return p.useEffect(()=>(document.addEventListener(_i,f),()=>document.removeEventListener(_i,f)),[f]),p.useEffect(()=>{if(l.trigger){const d=h=>{const m=h.target;m!=null&&m.contains(l.trigger)&&f()};return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[l.trigger,f]),s.jsx(mo,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:c,onFocusOutside:d=>d.preventDefault(),onDismiss:f,children:s.jsxs(oa,{"data-state":l.stateAttribute,...u,...a,ref:t,style:{...a.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[s.jsx(ag,{children:r}),s.jsx(sg,{scope:n,isInside:!0,children:s.jsx(Xm,{id:l.contentId,role:"tooltip",children:o||r})})]})})});zd.displayName=Tr;var Ud="TooltipArrow",cg=p.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Ss(n);return ig(Ud,n).isInside?null:s.jsx(sa,{...o,...r,ref:t})});cg.displayName=Ud;function lg(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 dg(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 ug(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 pg(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,c=t.length-1;i<t.length;c=i++){const a=t[i],l=t[c],u=a.x,f=a.y,d=l.x,h=l.y;f>r!=h>r&&n<(d-u)*(r-f)/(h-f)+u&&(o=!o)}return o}function fg(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),hg(t)}function hg(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],c=t[t.length-2];if((i.x-c.x)*(o.y-c.y)>=(i.y-c.y)*(o.x-c.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],c=n[n.length-2];if((i.x-c.x)*(o.y-c.y)>=(i.y-c.y)*(o.x-c.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 mg=Ld,gg=Nd,yg=Bd,bg=Fd,xg=zd;function Wd({content:e,children:t,side:n="right",align:r="center",sideOffset:o=6,delayMs:i=200,container:c}){return s.jsxs(gg,{delayDuration:i,children:[s.jsx(yg,{asChild:!0,children:t}),s.jsx(bg,{container:c,children:s.jsx(xg,{side:n,align:r,sideOffset:o,style:{background:pe("surfaceElevated"),color:pe("textPrimary"),border:`1px solid ${pe("borderDefault")}`,borderRadius:vn.sm,padding:`${be[1]} ${be[2]}`,fontSize:Ze.sm,boxShadow:pe("shadowMd"),zIndex:eo.tooltip,userSelect:"none"},children:e})})]})}const vg=mg;var Ns="focusScope.autoFocusOnMount",Bs="focusScope.autoFocusOnUnmount",jc={bubbles:!1,cancelable:!0},Sg="FocusScope",ws=p.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...c}=e,[a,l]=p.useState(null),u=mn(o),f=mn(i),d=p.useRef(null),h=_e(t,b=>l(b)),m=p.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;p.useEffect(()=>{if(r){let b=function(k){if(m.paused||!a)return;const v=k.target;a.contains(v)?d.current=v:on(d.current,{select:!0})},x=function(k){if(m.paused||!a)return;const v=k.relatedTarget;v!==null&&(a.contains(v)||on(d.current,{select:!0}))},w=function(k){if(document.activeElement===document.body)for(const j of k)j.removedNodes.length>0&&on(a)};document.addEventListener("focusin",b),document.addEventListener("focusout",x);const C=new MutationObserver(w);return a&&C.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",x),C.disconnect()}}},[r,a,m.paused]),p.useEffect(()=>{if(a){Tc.add(m);const b=document.activeElement;if(!a.contains(b)){const w=new CustomEvent(Ns,jc);a.addEventListener(Ns,u),a.dispatchEvent(w),w.defaultPrevented||(wg(Tg(Kd(a)),{select:!0}),document.activeElement===b&&on(a))}return()=>{a.removeEventListener(Ns,u),setTimeout(()=>{const w=new CustomEvent(Bs,jc);a.addEventListener(Bs,f),a.dispatchEvent(w),w.defaultPrevented||on(b??document.body,{select:!0}),a.removeEventListener(Bs,f),Tc.remove(m)},0)}}},[a,u,f,m]);const S=p.useCallback(b=>{if(!n&&!r||m.paused)return;const x=b.key==="Tab"&&!b.altKey&&!b.ctrlKey&&!b.metaKey,w=document.activeElement;if(x&&w){const C=b.currentTarget,[k,v]=kg(C);k&&v?!b.shiftKey&&w===v?(b.preventDefault(),n&&on(k,{select:!0})):b.shiftKey&&w===k&&(b.preventDefault(),n&&on(v,{select:!0})):w===C&&b.preventDefault()}},[n,r,m.paused]);return s.jsx(Te.div,{tabIndex:-1,...c,ref:h,onKeyDown:S})});ws.displayName=Sg;function wg(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(on(r,{select:t}),document.activeElement!==n)return}function kg(e){const t=Kd(e),n=Ec(t,e),r=Ec(t.reverse(),e);return[n,r]}function Kd(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 Ec(e,t){for(const n of e)if(!Cg(n,{upTo:t}))return n}function Cg(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 jg(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&&jg(e)&&t&&e.select()}}var Tc=Eg();function Eg(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Rc(e,t),e.unshift(t)},remove(t){var n;e=Rc(e,t),(n=e[0])==null||n.resume()}}}function Rc(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Tg(e){return e.filter(t=>t.tagName!=="A")}var Fs=0;function la(){p.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Ac()),document.body.insertAdjacentElement("beforeend",e[1]??Ac()),Fs++,()=>{Fs===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Fs--}},[])}function Ac(){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 Vd(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 Rg(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 Qo="right-scroll-bar-position",Jo="width-before-scroll-bar",Ag="with-scroll-bars-hidden",_g="--removed-body-scroll-bar-size";function zs(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Og(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 Pg=typeof window<"u"?p.useLayoutEffect:p.useEffect,_c=new WeakMap;function Dg(e,t){var n=Og(null,function(r){return e.forEach(function(o){return zs(o,r)})});return Pg(function(){var r=_c.get(n);if(r){var o=new Set(r),i=new Set(e),c=n.current;o.forEach(function(a){i.has(a)||zs(a,null)}),i.forEach(function(a){o.has(a)||zs(a,c)})}_c.set(n,e)},[e]),n}function Ig(e){return e}function Mg(e,t){t===void 0&&(t=Ig);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 c=t(i,r);return n.push(c),function(){n=n.filter(function(a){return a!==c})}},assignSyncMedium:function(i){for(r=!0;n.length;){var c=n;n=[],c.forEach(i)}n={push:function(a){return i(a)},filter:function(){return n}}},assignMedium:function(i){r=!0;var c=[];if(n.length){var a=n;n=[],a.forEach(i),c=n}var l=function(){var f=c;c=[],f.forEach(i)},u=function(){return Promise.resolve().then(l)};u(),n={push:function(f){c.push(f),u()},filter:function(f){return c=c.filter(f),n}}}};return o}function $g(e){e===void 0&&(e={});var t=Mg(null);return t.options=Bt({async:!0,ssr:!1},e),t}var Hd=function(e){var t=e.sideCar,n=Vd(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))};Hd.isSideCarExport=!0;function Lg(e,t){return e.useMedium(t),Hd}var Gd=$g(),qs=function(){},ks=p.forwardRef(function(e,t){var n=p.useRef(null),r=p.useState({onScrollCapture:qs,onWheelCapture:qs,onTouchMoveCapture:qs}),o=r[0],i=r[1],c=e.forwardProps,a=e.children,l=e.className,u=e.removeScrollBar,f=e.enabled,d=e.shards,h=e.sideCar,m=e.noRelative,S=e.noIsolation,b=e.inert,x=e.allowPinchZoom,w=e.as,C=w===void 0?"div":w,k=e.gapMode,v=Vd(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),j=h,D=Dg([n,t]),T=Bt(Bt({},v),o);return p.createElement(p.Fragment,null,f&&p.createElement(j,{sideCar:Gd,removeScrollBar:u,shards:d,noRelative:m,noIsolation:S,inert:b,setCallbacks:i,allowPinchZoom:!!x,lockRef:n,gapMode:k}),c?p.cloneElement(p.Children.only(a),Bt(Bt({},T),{ref:D})):p.createElement(C,Bt({},T,{className:l,ref:D}),a))});ks.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};ks.classNames={fullWidth:Jo,zeroRight:Qo};var Ng=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Bg(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Ng();return t&&e.setAttribute("nonce",t),e}function Fg(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function zg(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var qg=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Bg())&&(Fg(t,n),zg(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Ug=function(){var e=qg();return function(t,n){p.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Qd=function(){var e=Ug(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Wg={left:0,top:0,right:0,gap:0},Us=function(e){return parseInt(e||"",10)||0},Kg=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[Us(n),Us(r),Us(o)]},Vg=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Wg;var t=Kg(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])}},Hg=Qd(),lr="data-scroll-locked",Gg=function(e,t,n,r){var o=e.left,i=e.top,c=e.right,a=e.gap;return n===void 0&&(n="margin"),`
11
+ .`.concat(Ag,` {
12
+ overflow: hidden `).concat(r,`;
13
+ padding-right: `).concat(a,"px ").concat(r,`;
14
+ }
15
+ body[`).concat(lr,`] {
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(c,`px;
22
+ margin-left:0;
23
+ margin-top:0;
24
+ margin-right: `).concat(a,"px ").concat(r,`;
25
+ `),n==="padding"&&"padding-right: ".concat(a,"px ").concat(r,";")].filter(Boolean).join(""),`
26
+ }
27
+
28
+ .`).concat(Qo,` {
29
+ right: `).concat(a,"px ").concat(r,`;
30
+ }
31
+
32
+ .`).concat(Jo,` {
33
+ margin-right: `).concat(a,"px ").concat(r,`;
34
+ }
35
+
36
+ .`).concat(Qo," .").concat(Qo,` {
37
+ right: 0 `).concat(r,`;
38
+ }
39
+
40
+ .`).concat(Jo," .").concat(Jo,` {
41
+ margin-right: 0 `).concat(r,`;
42
+ }
43
+
44
+ body[`).concat(lr,`] {
45
+ `).concat(_g,": ").concat(a,`px;
46
+ }
47
+ `)},Oc=function(){var e=parseInt(document.body.getAttribute(lr)||"0",10);return isFinite(e)?e:0},Qg=function(){p.useEffect(function(){return document.body.setAttribute(lr,(Oc()+1).toString()),function(){var e=Oc()-1;e<=0?document.body.removeAttribute(lr):document.body.setAttribute(lr,e.toString())}},[])},Jg=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r;Qg();var i=p.useMemo(function(){return Vg(o)},[o]);return p.createElement(Hg,{styles:Gg(i,!t,o,n?"":"!important")})},Pi=!1;if(typeof window<"u")try{var Mo=Object.defineProperty({},"passive",{get:function(){return Pi=!0,!0}});window.addEventListener("test",Mo,Mo),window.removeEventListener("test",Mo,Mo)}catch{Pi=!1}var Zn=Pi?{passive:!1}:!1,Yg=function(e){return e.tagName==="TEXTAREA"},Jd=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!Yg(e)&&n[t]==="visible")},Xg=function(e){return Jd(e,"overflowY")},Zg=function(e){return Jd(e,"overflowX")},Pc=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=Yd(e,r);if(o){var i=Xd(e,r),c=i[1],a=i[2];if(c>a)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},ey=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},ty=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},Yd=function(e,t){return e==="v"?Xg(t):Zg(t)},Xd=function(e,t){return e==="v"?ey(t):ty(t)},ny=function(e,t){return e==="h"&&t==="rtl"?-1:1},ry=function(e,t,n,r,o){var i=ny(e,window.getComputedStyle(t).direction),c=i*r,a=n.target,l=t.contains(a),u=!1,f=c>0,d=0,h=0;do{if(!a)break;var m=Xd(e,a),S=m[0],b=m[1],x=m[2],w=b-x-i*S;(S||w)&&Yd(e,a)&&(d+=w,h+=S);var C=a.parentNode;a=C&&C.nodeType===Node.DOCUMENT_FRAGMENT_NODE?C.host:C}while(!l&&a!==document.body||l&&(t.contains(a)||t===a));return(f&&Math.abs(d)<1||!f&&Math.abs(h)<1)&&(u=!0),u},$o=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Dc=function(e){return[e.deltaX,e.deltaY]},Ic=function(e){return e&&"current"in e?e.current:e},oy=function(e,t){return e[0]===t[0]&&e[1]===t[1]},sy=function(e){return`
48
+ .block-interactivity-`.concat(e,` {pointer-events: none;}
49
+ .allow-interactivity-`).concat(e,` {pointer-events: all;}
50
+ `)},iy=0,er=[];function ay(e){var t=p.useRef([]),n=p.useRef([0,0]),r=p.useRef(),o=p.useState(iy++)[0],i=p.useState(Qd)[0],c=p.useRef(e);p.useEffect(function(){c.current=e},[e]),p.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var b=Rg([e.lockRef.current],(e.shards||[]).map(Ic),!0).filter(Boolean);return b.forEach(function(x){return x.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),b.forEach(function(x){return x.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var a=p.useCallback(function(b,x){if("touches"in b&&b.touches.length===2||b.type==="wheel"&&b.ctrlKey)return!c.current.allowPinchZoom;var w=$o(b),C=n.current,k="deltaX"in b?b.deltaX:C[0]-w[0],v="deltaY"in b?b.deltaY:C[1]-w[1],j,D=b.target,T=Math.abs(k)>Math.abs(v)?"h":"v";if("touches"in b&&T==="h"&&D.type==="range")return!1;var y=window.getSelection(),O=y&&y.anchorNode,A=O?O===D||O.contains(D):!1;if(A)return!1;var _=Pc(T,D);if(!_)return!0;if(_?j=T:(j=T==="v"?"h":"v",_=Pc(T,D)),!_)return!1;if(!r.current&&"changedTouches"in b&&(k||v)&&(r.current=j),!j)return!0;var P=r.current||j;return ry(P,x,b,P==="h"?k:v)},[]),l=p.useCallback(function(b){var x=b;if(!(!er.length||er[er.length-1]!==i)){var w="deltaY"in x?Dc(x):$o(x),C=t.current.filter(function(j){return j.name===x.type&&(j.target===x.target||x.target===j.shadowParent)&&oy(j.delta,w)})[0];if(C&&C.should){x.cancelable&&x.preventDefault();return}if(!C){var k=(c.current.shards||[]).map(Ic).filter(Boolean).filter(function(j){return j.contains(x.target)}),v=k.length>0?a(x,k[0]):!c.current.noIsolation;v&&x.cancelable&&x.preventDefault()}}},[]),u=p.useCallback(function(b,x,w,C){var k={name:b,delta:x,target:w,should:C,shadowParent:cy(w)};t.current.push(k),setTimeout(function(){t.current=t.current.filter(function(v){return v!==k})},1)},[]),f=p.useCallback(function(b){n.current=$o(b),r.current=void 0},[]),d=p.useCallback(function(b){u(b.type,Dc(b),b.target,a(b,e.lockRef.current))},[]),h=p.useCallback(function(b){u(b.type,$o(b),b.target,a(b,e.lockRef.current))},[]);p.useEffect(function(){return er.push(i),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:h}),document.addEventListener("wheel",l,Zn),document.addEventListener("touchmove",l,Zn),document.addEventListener("touchstart",f,Zn),function(){er=er.filter(function(b){return b!==i}),document.removeEventListener("wheel",l,Zn),document.removeEventListener("touchmove",l,Zn),document.removeEventListener("touchstart",f,Zn)}},[]);var m=e.removeScrollBar,S=e.inert;return p.createElement(p.Fragment,null,S?p.createElement(i,{styles:sy(o)}):null,m?p.createElement(Jg,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function cy(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const ly=Lg(Gd,ay);var Cs=p.forwardRef(function(e,t){return p.createElement(ks,Bt({},e,{ref:t,sideCar:ly}))});Cs.classNames=ks.classNames;var dy=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},tr=new WeakMap,Lo=new WeakMap,No={},Ws=0,Zd=function(e){return e&&(e.host||Zd(e.parentNode))},uy=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=Zd(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})},py=function(e,t,n,r){var o=uy(t,Array.isArray(e)?e:[e]);No[n]||(No[n]=new WeakMap);var i=No[n],c=[],a=new Set,l=new Set(o),u=function(d){!d||a.has(d)||(a.add(d),u(d.parentNode))};o.forEach(u);var f=function(d){!d||l.has(d)||Array.prototype.forEach.call(d.children,function(h){if(a.has(h))f(h);else try{var m=h.getAttribute(r),S=m!==null&&m!=="false",b=(tr.get(h)||0)+1,x=(i.get(h)||0)+1;tr.set(h,b),i.set(h,x),c.push(h),b===1&&S&&Lo.set(h,!0),x===1&&h.setAttribute(n,"true"),S||h.setAttribute(r,"true")}catch(w){console.error("aria-hidden: cannot operate on ",h,w)}})};return f(t),a.clear(),Ws++,function(){c.forEach(function(d){var h=tr.get(d)-1,m=i.get(d)-1;tr.set(d,h),i.set(d,m),h||(Lo.has(d)||d.removeAttribute(r),Lo.delete(d)),m||d.removeAttribute(n)}),Ws--,Ws||(tr=new WeakMap,tr=new WeakMap,Lo=new WeakMap,No={})}},da=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=dy(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),py(r,o,n,"aria-hidden")):function(){return null}},js="Dialog",[eu]=Sn(js),[fy,Dt]=eu(js),tu=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:c=!0}=e,a=p.useRef(null),l=p.useRef(null),[u,f]=ia({prop:r,defaultProp:o??!1,onChange:i,caller:js});return s.jsx(fy,{scope:t,triggerRef:a,contentRef:l,contentId:Qr(),titleId:Qr(),descriptionId:Qr(),open:u,onOpenChange:f,onOpenToggle:p.useCallback(()=>f(d=>!d),[f]),modal:c,children:n})};tu.displayName=js;var nu="DialogTrigger",hy=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Dt(nu,n),i=_e(t,o.triggerRef);return s.jsx(Te.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":fa(o.open),...r,ref:i,onClick:de(e.onClick,o.onOpenToggle)})});hy.displayName=nu;var ua="DialogPortal",[my,ru]=eu(ua,{forceMount:void 0}),ou=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=Dt(ua,t);return s.jsx(my,{scope:t,forceMount:n,children:p.Children.map(r,c=>s.jsx(wt,{present:n||i.open,children:s.jsx(yo,{asChild:!0,container:o,children:c})}))})};ou.displayName=ua;var ss="DialogOverlay",su=p.forwardRef((e,t)=>{const n=ru(ss,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Dt(ss,e.__scopeDialog);return i.modal?s.jsx(wt,{present:r||i.open,children:s.jsx(yy,{...o,ref:t})}):null});su.displayName=ss;var gy=jr("DialogOverlay.RemoveScroll"),yy=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Dt(ss,n);return s.jsx(Cs,{as:gy,allowPinchZoom:!0,shards:[o.contentRef],children:s.jsx(Te.div,{"data-state":fa(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Wn="DialogContent",iu=p.forwardRef((e,t)=>{const n=ru(Wn,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Dt(Wn,e.__scopeDialog);return s.jsx(wt,{present:r||i.open,children:i.modal?s.jsx(by,{...o,ref:t}):s.jsx(xy,{...o,ref:t})})});iu.displayName=Wn;var by=p.forwardRef((e,t)=>{const n=Dt(Wn,e.__scopeDialog),r=p.useRef(null),o=_e(t,n.contentRef,r);return p.useEffect(()=>{const i=r.current;if(i)return da(i)},[]),s.jsx(au,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:de(e.onCloseAutoFocus,i=>{var c;i.preventDefault(),(c=n.triggerRef.current)==null||c.focus()}),onPointerDownOutside:de(e.onPointerDownOutside,i=>{const c=i.detail.originalEvent,a=c.button===0&&c.ctrlKey===!0;(c.button===2||a)&&i.preventDefault()}),onFocusOutside:de(e.onFocusOutside,i=>i.preventDefault())})}),xy=p.forwardRef((e,t)=>{const n=Dt(Wn,e.__scopeDialog),r=p.useRef(!1),o=p.useRef(!1);return s.jsx(au,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var c,a;(c=e.onCloseAutoFocus)==null||c.call(e,i),i.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),i.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:i=>{var l,u;(l=e.onInteractOutside)==null||l.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const c=i.target;((u=n.triggerRef.current)==null?void 0:u.contains(c))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}})}),au=p.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...c}=e,a=Dt(Wn,n),l=p.useRef(null),u=_e(t,l);return la(),s.jsxs(s.Fragment,{children:[s.jsx(ws,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i,children:s.jsx(mo,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":fa(a.open),...c,ref:u,onDismiss:()=>a.onOpenChange(!1)})}),s.jsxs(s.Fragment,{children:[s.jsx(wy,{titleId:a.titleId}),s.jsx(Cy,{contentRef:l,descriptionId:a.descriptionId})]})]})}),pa="DialogTitle",cu=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Dt(pa,n);return s.jsx(Te.h2,{id:o.titleId,...r,ref:t})});cu.displayName=pa;var lu="DialogDescription",vy=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Dt(lu,n);return s.jsx(Te.p,{id:o.descriptionId,...r,ref:t})});vy.displayName=lu;var du="DialogClose",Sy=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Dt(du,n);return s.jsx(Te.button,{type:"button",...r,ref:t,onClick:de(e.onClick,()=>o.onOpenChange(!1))})});Sy.displayName=du;function fa(e){return e?"open":"closed"}var uu="DialogTitleWarning",[sj,pu]=dh(uu,{contentName:Wn,titleName:pa,docsSlug:"dialog"}),wy=({titleId:e})=>{const t=pu(uu),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},ky="DialogDescriptionWarning",Cy=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${pu(ky).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},jy=tu,Ey=ou,Ty=su,Ry=iu,Ay=cu;function fu(e){const t=e+"CollectionProvider",[n,r]=Sn(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),c=b=>{const{scope:x,children:w}=b,C=qe.useRef(null),k=qe.useRef(new Map).current;return s.jsx(o,{scope:x,itemMap:k,collectionRef:C,children:w})};c.displayName=t;const a=e+"CollectionSlot",l=jr(a),u=qe.forwardRef((b,x)=>{const{scope:w,children:C}=b,k=i(a,w),v=_e(x,k.collectionRef);return s.jsx(l,{ref:v,children:C})});u.displayName=a;const f=e+"CollectionItemSlot",d="data-radix-collection-item",h=jr(f),m=qe.forwardRef((b,x)=>{const{scope:w,children:C,...k}=b,v=qe.useRef(null),j=_e(x,v),D=i(f,w);return qe.useEffect(()=>(D.itemMap.set(v,{ref:v,...k}),()=>void D.itemMap.delete(v))),s.jsx(h,{[d]:"",ref:j,children:C})});m.displayName=f;function S(b){const x=i(e+"CollectionConsumer",b);return qe.useCallback(()=>{const C=x.collectionRef.current;if(!C)return[];const k=Array.from(C.querySelectorAll(`[${d}]`));return Array.from(x.itemMap.values()).sort((D,T)=>k.indexOf(D.ref.current)-k.indexOf(T.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:c,Slot:u,ItemSlot:m},S,r]}var _y=p.createContext(void 0);function Oy(e){const t=p.useContext(_y);return e||t||"ltr"}var Ks="rovingFocusGroup.onEntryFocus",Py={bubbles:!1,cancelable:!0},xo="RovingFocusGroup",[Di,hu,Dy]=fu(xo),[Iy,mu]=Sn(xo,[Dy]),[My,$y]=Iy(xo),gu=p.forwardRef((e,t)=>s.jsx(Di.Provider,{scope:e.__scopeRovingFocusGroup,children:s.jsx(Di.Slot,{scope:e.__scopeRovingFocusGroup,children:s.jsx(Ly,{...e,ref:t})})}));gu.displayName=xo;var Ly=p.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:c,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:u,preventScrollOnEntryFocus:f=!1,...d}=e,h=p.useRef(null),m=_e(t,h),S=Oy(i),[b,x]=ia({prop:c,defaultProp:a??null,onChange:l,caller:xo}),[w,C]=p.useState(!1),k=mn(u),v=hu(n),j=p.useRef(!1),[D,T]=p.useState(0);return p.useEffect(()=>{const y=h.current;if(y)return y.addEventListener(Ks,k),()=>y.removeEventListener(Ks,k)},[k]),s.jsx(My,{scope:n,orientation:r,dir:S,loop:o,currentTabStopId:b,onItemFocus:p.useCallback(y=>x(y),[x]),onItemShiftTab:p.useCallback(()=>C(!0),[]),onFocusableItemAdd:p.useCallback(()=>T(y=>y+1),[]),onFocusableItemRemove:p.useCallback(()=>T(y=>y-1),[]),children:s.jsx(Te.div,{tabIndex:w||D===0?-1:0,"data-orientation":r,...d,ref:m,style:{outline:"none",...e.style},onMouseDown:de(e.onMouseDown,()=>{j.current=!0}),onFocus:de(e.onFocus,y=>{const O=!j.current;if(y.target===y.currentTarget&&O&&!w){const A=new CustomEvent(Ks,Py);if(y.currentTarget.dispatchEvent(A),!A.defaultPrevented){const _=v().filter(J=>J.focusable),P=_.find(J=>J.active),$=_.find(J=>J.id===b),G=[P,$,..._].filter(Boolean).map(J=>J.ref.current);xu(G,f)}}j.current=!1}),onBlur:de(e.onBlur,()=>C(!1))})})}),yu="RovingFocusGroupItem",bu=p.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,children:c,...a}=e,l=Qr(),u=i||l,f=$y(yu,n),d=f.currentTabStopId===u,h=hu(n),{onFocusableItemAdd:m,onFocusableItemRemove:S,currentTabStopId:b}=f;return p.useEffect(()=>{if(r)return m(),()=>S()},[r,m,S]),s.jsx(Di.ItemSlot,{scope:n,id:u,focusable:r,active:o,children:s.jsx(Te.span,{tabIndex:d?0:-1,"data-orientation":f.orientation,...a,ref:t,onMouseDown:de(e.onMouseDown,x=>{r?f.onItemFocus(u):x.preventDefault()}),onFocus:de(e.onFocus,()=>f.onItemFocus(u)),onKeyDown:de(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){f.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const w=Fy(x,f.orientation,f.dir);if(w!==void 0){if(x.metaKey||x.ctrlKey||x.altKey||x.shiftKey)return;x.preventDefault();let k=h().filter(v=>v.focusable).map(v=>v.ref.current);if(w==="last")k.reverse();else if(w==="prev"||w==="next"){w==="prev"&&k.reverse();const v=k.indexOf(x.currentTarget);k=f.loop?zy(k,v+1):k.slice(v+1)}setTimeout(()=>xu(k))}}),children:typeof c=="function"?c({isCurrentTabStop:d,hasTabStop:b!=null}):c})})});bu.displayName=yu;var Ny={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function By(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Fy(e,t,n){const r=By(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Ny[r]}function xu(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function zy(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var qy=gu,Uy=bu,Ii=["Enter"," "],Wy=["ArrowDown","PageUp","Home"],vu=["ArrowUp","PageDown","End"],Ky=[...Wy,...vu],Vy={ltr:[...Ii,"ArrowRight"],rtl:[...Ii,"ArrowLeft"]},Hy={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Es="Menu",[ro,Gy,Qy]=fu(Es),[Hn,Su]=Sn(Es,[Qy,Or,mu]),ha=Or(),wu=mu(),[ij,Gn]=Hn(Es),[aj,vo]=Hn(Es),Jy="MenuAnchor",ma=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ha(n);return s.jsx(xs,{...o,...r,ref:t})});ma.displayName=Jy;var ga="MenuPortal",[Yy,ku]=Hn(ga,{forceMount:void 0}),Cu=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Gn(ga,t);return s.jsx(Yy,{scope:t,forceMount:n,children:s.jsx(wt,{present:n||i.open,children:s.jsx(yo,{asChild:!0,container:o,children:r})})})};Cu.displayName=ga;var vt="MenuContent",[Xy,ya]=Hn(vt),ju=p.forwardRef((e,t)=>{const n=ku(vt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Gn(vt,e.__scopeMenu),c=vo(vt,e.__scopeMenu);return s.jsx(ro.Provider,{scope:e.__scopeMenu,children:s.jsx(wt,{present:r||i.open,children:s.jsx(ro.Slot,{scope:e.__scopeMenu,children:c.modal?s.jsx(Zy,{...o,ref:t}):s.jsx(eb,{...o,ref:t})})})})}),Zy=p.forwardRef((e,t)=>{const n=Gn(vt,e.__scopeMenu),r=p.useRef(null),o=_e(t,r);return p.useEffect(()=>{const i=r.current;if(i)return da(i)},[]),s.jsx(ba,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:de(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),eb=p.forwardRef((e,t)=>{const n=Gn(vt,e.__scopeMenu);return s.jsx(ba,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),tb=jr("MenuContent.ScrollLock"),ba=p.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:c,disableOutsidePointerEvents:a,onEntryFocus:l,onEscapeKeyDown:u,onPointerDownOutside:f,onFocusOutside:d,onInteractOutside:h,onDismiss:m,disableOutsideScroll:S,...b}=e,x=Gn(vt,n),w=vo(vt,n),C=ha(n),k=wu(n),v=Gy(n),[j,D]=p.useState(null),T=p.useRef(null),y=_e(t,T,x.onContentChange),O=p.useRef(0),A=p.useRef(""),_=p.useRef(0),P=p.useRef(null),$=p.useRef("right"),q=p.useRef(0),G=S?Cs:p.Fragment,J=S?{as:tb,allowPinchZoom:!0}:void 0,H=M=>{var ce,ke;const X=A.current+M,W=v().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=fb(K,X,F),ee=(ke=W.find(xe=>xe.textValue===oe))==null?void 0:ke.ref.current;(function xe(Ie){A.current=Ie,window.clearTimeout(O.current),Ie!==""&&(O.current=window.setTimeout(()=>xe(""),1e3))})(X),ee&&setTimeout(()=>ee.focus())};p.useEffect(()=>()=>window.clearTimeout(O.current),[]),la();const L=p.useCallback(M=>{var W,te;return $.current===((W=P.current)==null?void 0:W.side)&&mb(M,(te=P.current)==null?void 0:te.area)},[]);return s.jsx(Xy,{scope:n,searchRef:A,onItemEnter:p.useCallback(M=>{L(M)&&M.preventDefault()},[L]),onItemLeave:p.useCallback(M=>{var X;L(M)||((X=T.current)==null||X.focus(),D(null))},[L]),onTriggerLeave:p.useCallback(M=>{L(M)&&M.preventDefault()},[L]),pointerGraceTimerRef:_,onPointerGraceIntentChange:p.useCallback(M=>{P.current=M},[]),children:s.jsx(G,{...J,children:s.jsx(ws,{asChild:!0,trapped:o,onMountAutoFocus:de(i,M=>{var X;M.preventDefault(),(X=T.current)==null||X.focus({preventScroll:!0})}),onUnmountAutoFocus:c,children:s.jsx(mo,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:u,onPointerDownOutside:f,onFocusOutside:d,onInteractOutside:h,onDismiss:m,children:s.jsx(qy,{asChild:!0,...k,dir:w.dir,orientation:"vertical",loop:r,currentTabStopId:j,onCurrentTabStopIdChange:D,onEntryFocus:de(l,M=>{w.isUsingKeyboardRef.current||M.preventDefault()}),preventScrollOnEntryFocus:!0,children:s.jsx(oa,{role:"menu","aria-orientation":"vertical","data-state":zu(x.open),"data-radix-menu-content":"",dir:w.dir,...C,...b,ref:y,style:{outline:"none",...b.style},onKeyDown:de(b.onKeyDown,M=>{const W=M.target.closest("[data-radix-menu-content]")===M.currentTarget,te=M.ctrlKey||M.altKey||M.metaKey,F=M.key.length===1;W&&(M.key==="Tab"&&M.preventDefault(),!te&&F&&H(M.key));const K=T.current;if(M.target!==K||!Ky.includes(M.key))return;M.preventDefault();const ee=v().filter(ce=>!ce.disabled).map(ce=>ce.ref.current);vu.includes(M.key)&&ee.reverse(),ub(ee)}),onBlur:de(e.onBlur,M=>{M.currentTarget.contains(M.target)||(window.clearTimeout(O.current),A.current="")}),onPointerMove:de(e.onPointerMove,oo(M=>{const X=M.target,W=q.current!==M.clientX;if(M.currentTarget.contains(X)&&W){const te=M.clientX>q.current?"right":"left";$.current=te,q.current=M.clientX}}))})})})})})})});ju.displayName=vt;var nb="MenuGroup",xa=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(Te.div,{role:"group",...r,ref:t})});xa.displayName=nb;var rb="MenuLabel",Eu=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(Te.div,{...r,ref:t})});Eu.displayName=rb;var is="MenuItem",Mc="menu.itemSelect",Ts=p.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=p.useRef(null),c=vo(is,e.__scopeMenu),a=ya(is,e.__scopeMenu),l=_e(t,i),u=p.useRef(!1),f=()=>{const d=i.current;if(!n&&d){const h=new CustomEvent(Mc,{bubbles:!0,cancelable:!0});d.addEventListener(Mc,m=>r==null?void 0:r(m),{once:!0}),ud(d,h),h.defaultPrevented?u.current=!1:c.onClose()}};return s.jsx(Tu,{...o,ref:l,disabled:n,onClick:de(e.onClick,f),onPointerDown:d=>{var h;(h=e.onPointerDown)==null||h.call(e,d),u.current=!0},onPointerUp:de(e.onPointerUp,d=>{var h;u.current||(h=d.currentTarget)==null||h.click()}),onKeyDown:de(e.onKeyDown,d=>{const h=a.searchRef.current!=="";n||h&&d.key===" "||Ii.includes(d.key)&&(d.currentTarget.click(),d.preventDefault())})})});Ts.displayName=is;var Tu=p.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,c=ya(is,n),a=wu(n),l=p.useRef(null),u=_e(t,l),[f,d]=p.useState(!1),[h,m]=p.useState("");return p.useEffect(()=>{const S=l.current;S&&m((S.textContent??"").trim())},[i.children]),s.jsx(ro.ItemSlot,{scope:n,disabled:r,textValue:o??h,children:s.jsx(Uy,{asChild:!0,...a,focusable:!r,children:s.jsx(Te.div,{role:"menuitem","data-highlighted":f?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:u,onPointerMove:de(e.onPointerMove,oo(S=>{r?c.onItemLeave(S):(c.onItemEnter(S),S.defaultPrevented||S.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:de(e.onPointerLeave,oo(S=>c.onItemLeave(S))),onFocus:de(e.onFocus,()=>d(!0)),onBlur:de(e.onBlur,()=>d(!1))})})})}),ob="MenuCheckboxItem",Ru=p.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return s.jsx(Du,{scope:e.__scopeMenu,checked:n,children:s.jsx(Ts,{role:"menuitemcheckbox","aria-checked":as(n)?"mixed":n,...o,ref:t,"data-state":Sa(n),onSelect:de(o.onSelect,()=>r==null?void 0:r(as(n)?!0:!n),{checkForDefaultPrevented:!1})})})});Ru.displayName=ob;var Au="MenuRadioGroup",[sb,ib]=Hn(Au,{value:void 0,onValueChange:()=>{}}),_u=p.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,i=mn(r);return s.jsx(sb,{scope:e.__scopeMenu,value:n,onValueChange:i,children:s.jsx(xa,{...o,ref:t})})});_u.displayName=Au;var Ou="MenuRadioItem",Pu=p.forwardRef((e,t)=>{const{value:n,...r}=e,o=ib(Ou,e.__scopeMenu),i=n===o.value;return s.jsx(Du,{scope:e.__scopeMenu,checked:i,children:s.jsx(Ts,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":Sa(i),onSelect:de(r.onSelect,()=>{var c;return(c=o.onValueChange)==null?void 0:c.call(o,n)},{checkForDefaultPrevented:!1})})})});Pu.displayName=Ou;var va="MenuItemIndicator",[Du,ab]=Hn(va,{checked:!1}),Iu=p.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=ab(va,n);return s.jsx(wt,{present:r||as(i.checked)||i.checked===!0,children:s.jsx(Te.span,{...o,ref:t,"data-state":Sa(i.checked)})})});Iu.displayName=va;var cb="MenuSeparator",Mu=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(Te.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});Mu.displayName=cb;var lb="MenuArrow",$u=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ha(n);return s.jsx(sa,{...o,...r,ref:t})});$u.displayName=lb;var db="MenuSub",[cj,Lu]=Hn(db),qr="MenuSubTrigger",Nu=p.forwardRef((e,t)=>{const n=Gn(qr,e.__scopeMenu),r=vo(qr,e.__scopeMenu),o=Lu(qr,e.__scopeMenu),i=ya(qr,e.__scopeMenu),c=p.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:l}=i,u={__scopeMenu:e.__scopeMenu},f=p.useCallback(()=>{c.current&&window.clearTimeout(c.current),c.current=null},[]);return p.useEffect(()=>f,[f]),p.useEffect(()=>{const d=a.current;return()=>{window.clearTimeout(d),l(null)}},[a,l]),s.jsx(ma,{asChild:!0,...u,children:s.jsx(Tu,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":zu(n.open),...e,ref:hs(t,o.onTriggerChange),onClick:d=>{var h;(h=e.onClick)==null||h.call(e,d),!(e.disabled||d.defaultPrevented)&&(d.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:de(e.onPointerMove,oo(d=>{i.onItemEnter(d),!d.defaultPrevented&&!e.disabled&&!n.open&&!c.current&&(i.onPointerGraceIntentChange(null),c.current=window.setTimeout(()=>{n.onOpenChange(!0),f()},100))})),onPointerLeave:de(e.onPointerLeave,oo(d=>{var m,S;f();const h=(m=n.content)==null?void 0:m.getBoundingClientRect();if(h){const b=(S=n.content)==null?void 0:S.dataset.side,x=b==="right",w=x?-5:5,C=h[x?"left":"right"],k=h[x?"right":"left"];i.onPointerGraceIntentChange({area:[{x:d.clientX+w,y:d.clientY},{x:C,y:h.top},{x:k,y:h.top},{x:k,y:h.bottom},{x:C,y:h.bottom}],side:b}),window.clearTimeout(a.current),a.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 h=i.searchRef.current!=="";e.disabled||h&&d.key===" "||Vy[r.dir].includes(d.key)&&(n.onOpenChange(!0),(m=n.content)==null||m.focus(),d.preventDefault())})})})});Nu.displayName=qr;var Bu="MenuSubContent",Fu=p.forwardRef((e,t)=>{const n=ku(vt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Gn(vt,e.__scopeMenu),c=vo(vt,e.__scopeMenu),a=Lu(Bu,e.__scopeMenu),l=p.useRef(null),u=_e(t,l);return s.jsx(ro.Provider,{scope:e.__scopeMenu,children:s.jsx(wt,{present:r||i.open,children:s.jsx(ro.Slot,{scope:e.__scopeMenu,children:s.jsx(ba,{id:a.contentId,"aria-labelledby":a.triggerId,...o,ref:u,align:"start",side:c.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:f=>{var d;c.isUsingKeyboardRef.current&&((d=l.current)==null||d.focus()),f.preventDefault()},onCloseAutoFocus:f=>f.preventDefault(),onFocusOutside:de(e.onFocusOutside,f=>{f.target!==a.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:de(e.onEscapeKeyDown,f=>{c.onClose(),f.preventDefault()}),onKeyDown:de(e.onKeyDown,f=>{var m;const d=f.currentTarget.contains(f.target),h=Hy[c.dir].includes(f.key);d&&h&&(i.onOpenChange(!1),(m=a.trigger)==null||m.focus(),f.preventDefault())})})})})})});Fu.displayName=Bu;function zu(e){return e?"open":"closed"}function as(e){return e==="indeterminate"}function Sa(e){return as(e)?"indeterminate":e?"checked":"unchecked"}function ub(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function pb(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function fb(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 c=pb(e,Math.max(i,0));o.length===1&&(c=c.filter(u=>u!==n));const l=c.find(u=>u.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function hb(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,c=t.length-1;i<t.length;c=i++){const a=t[i],l=t[c],u=a.x,f=a.y,d=l.x,h=l.y;f>r!=h>r&&n<(d-u)*(r-f)/(h-f)+u&&(o=!o)}return o}function mb(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return hb(n,t)}function oo(e){return t=>t.pointerType==="mouse"?e(t):void 0}var gb=ma,yb=Cu,bb=ju,xb=xa,vb=Eu,Sb=Ts,wb=Ru,kb=_u,Cb=Pu,jb=Iu,Eb=Mu,Tb=$u,Rb=Nu,Ab=Fu,qu="DropdownMenu",[_b]=Sn(qu,[Su]),dt=Su(),[lj,Uu]=_b(qu),Wu="DropdownMenuTrigger",Ob=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=Uu(Wu,n),c=dt(n);return s.jsx(gb,{asChild:!0,...c,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:hs(t,i.triggerRef),onPointerDown:de(e.onPointerDown,a=>{!r&&a.button===0&&a.ctrlKey===!1&&(i.onOpenToggle(),i.open||a.preventDefault())}),onKeyDown:de(e.onKeyDown,a=>{r||(["Enter"," "].includes(a.key)&&i.onOpenToggle(),a.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});Ob.displayName=Wu;var Pb="DropdownMenuPortal",Ku=e=>{const{__scopeDropdownMenu:t,...n}=e,r=dt(t);return s.jsx(yb,{...r,...n})};Ku.displayName=Pb;var Vu="DropdownMenuContent",Hu=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Uu(Vu,n),i=dt(n),c=p.useRef(!1);return s.jsx(bb,{id:o.contentId,"aria-labelledby":o.triggerId,...i,...r,ref:t,onCloseAutoFocus:de(e.onCloseAutoFocus,a=>{var l;c.current||(l=o.triggerRef.current)==null||l.focus(),c.current=!1,a.preventDefault()}),onInteractOutside:de(e.onInteractOutside,a=>{const l=a.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,f=l.button===2||u;(!o.modal||f)&&(c.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)"}})});Hu.displayName=Vu;var Db="DropdownMenuGroup",Ib=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(xb,{...o,...r,ref:t})});Ib.displayName=Db;var Mb="DropdownMenuLabel",Gu=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(vb,{...o,...r,ref:t})});Gu.displayName=Mb;var $b="DropdownMenuItem",Qu=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Sb,{...o,...r,ref:t})});Qu.displayName=$b;var Lb="DropdownMenuCheckboxItem",Nb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(wb,{...o,...r,ref:t})});Nb.displayName=Lb;var Bb="DropdownMenuRadioGroup",Fb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(kb,{...o,...r,ref:t})});Fb.displayName=Bb;var zb="DropdownMenuRadioItem",qb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Cb,{...o,...r,ref:t})});qb.displayName=zb;var Ub="DropdownMenuItemIndicator",Wb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(jb,{...o,...r,ref:t})});Wb.displayName=Ub;var Kb="DropdownMenuSeparator",Ju=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Eb,{...o,...r,ref:t})});Ju.displayName=Kb;var Vb="DropdownMenuArrow",Hb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Tb,{...o,...r,ref:t})});Hb.displayName=Vb;var Gb="DropdownMenuSubTrigger",Qb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Rb,{...o,...r,ref:t})});Qb.displayName=Gb;var Jb="DropdownMenuSubContent",Yb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Ab,{...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)"}})});Yb.displayName=Jb;var Xb=Ku,Zb=Hu,ex=Gu,tx=Qu,nx=Ju;const rx=p.forwardRef(({container:e,style:t,sideOffset:n=4,...r},o)=>s.jsx(Xb,{container:e,children:s.jsx(Zb,{ref:o,sideOffset:n,style:{minWidth:180,background:pe("surfaceElevated"),color:pe("textPrimary"),border:`1px solid ${pe("borderDefault")}`,borderRadius:vn.md,boxShadow:pe("shadowMd"),padding:be[1],zIndex:eo.popover,...t},...r})}));rx.displayName="DropdownMenuContent";const ox=p.forwardRef(({style:e,...t},n)=>s.jsx(tx,{ref:n,style:{display:"flex",alignItems:"center",gap:be[2],padding:`${be[1]} ${be[2]}`,fontSize:Ze.sm,borderRadius:vn.sm,cursor:"default",outline:"none",userSelect:"none",...e},...t}));ox.displayName="DropdownMenuItem";const sx=p.forwardRef(({style:e,...t},n)=>s.jsx(nx,{ref:n,style:{height:1,background:pe("borderSubtle"),margin:`${be[1]} 0`,...e},...t}));sx.displayName="DropdownMenuSeparator";const ix=p.forwardRef(({style:e,...t},n)=>s.jsx(ex,{ref:n,style:{padding:`${be[1]} ${be[2]}`,fontSize:Ze.xs,color:pe("textMuted"),textTransform:"uppercase",letterSpacing:"0.04em",...e},...t}));ix.displayName="DropdownMenuLabel";var Yu="Popover",[Xu]=Sn(Yu,[Or]),Rs=Or(),[dj,wn]=Xu(Yu),Zu="PopoverAnchor",ax=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=wn(Zu,n),i=Rs(n),{onCustomAnchorAdd:c,onCustomAnchorRemove:a}=o;return p.useEffect(()=>(c(),()=>a()),[c,a]),s.jsx(xs,{...i,...r,ref:t})});ax.displayName=Zu;var ep="PopoverTrigger",cx=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=wn(ep,n),i=Rs(n),c=_e(t,o.triggerRef),a=s.jsx(Te.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":sp(o.open),...r,ref:c,onClick:de(e.onClick,o.onOpenToggle)});return o.hasCustomAnchor?a:s.jsx(xs,{asChild:!0,...i,children:a})});cx.displayName=ep;var wa="PopoverPortal",[lx,dx]=Xu(wa,{forceMount:void 0}),tp=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=wn(wa,t);return s.jsx(lx,{scope:t,forceMount:n,children:s.jsx(wt,{present:n||i.open,children:s.jsx(yo,{asChild:!0,container:o,children:r})})})};tp.displayName=wa;var Rr="PopoverContent",np=p.forwardRef((e,t)=>{const n=dx(Rr,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=wn(Rr,e.__scopePopover);return s.jsx(wt,{present:r||i.open,children:i.modal?s.jsx(px,{...o,ref:t}):s.jsx(fx,{...o,ref:t})})});np.displayName=Rr;var ux=jr("PopoverContent.RemoveScroll"),px=p.forwardRef((e,t)=>{const n=wn(Rr,e.__scopePopover),r=p.useRef(null),o=_e(t,r),i=p.useRef(!1);return p.useEffect(()=>{const c=r.current;if(c)return da(c)},[]),s.jsx(Cs,{as:ux,allowPinchZoom:!0,children:s.jsx(rp,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:de(e.onCloseAutoFocus,c=>{var a;c.preventDefault(),i.current||(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:de(e.onPointerDownOutside,c=>{const a=c.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0,u=a.button===2||l;i.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:de(e.onFocusOutside,c=>c.preventDefault(),{checkForDefaultPrevented:!1})})})}),fx=p.forwardRef((e,t)=>{const n=wn(Rr,e.__scopePopover),r=p.useRef(!1),o=p.useRef(!1);return s.jsx(rp,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var c,a;(c=e.onCloseAutoFocus)==null||c.call(e,i),i.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),i.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:i=>{var l,u;(l=e.onInteractOutside)==null||l.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const c=i.target;((u=n.triggerRef.current)==null?void 0:u.contains(c))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}})}),rp=p.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:c,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:f,...d}=e,h=wn(Rr,n),m=Rs(n);return la(),s.jsx(ws,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i,children:s.jsx(mo,{asChild:!0,disableOutsidePointerEvents:c,onInteractOutside:f,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:u,onDismiss:()=>h.onOpenChange(!1),children:s.jsx(oa,{"data-state":sp(h.open),role:"dialog",id:h.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)"}})})})}),op="PopoverClose",hx=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=wn(op,n);return s.jsx(Te.button,{type:"button",...r,ref:t,onClick:de(e.onClick,()=>o.onOpenChange(!1))})});hx.displayName=op;var mx="PopoverArrow",gx=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Rs(n);return s.jsx(sa,{...o,...r,ref:t})});gx.displayName=mx;function sp(e){return e?"open":"closed"}var yx=tp,bx=np;const xx=p.forwardRef(({container:e,style:t,sideOffset:n=6,...r},o)=>s.jsx(yx,{container:e,children:s.jsx(bx,{ref:o,sideOffset:n,style:{background:pe("surfaceElevated"),color:pe("textPrimary"),border:`1px solid ${pe("borderDefault")}`,borderRadius:vn.md,boxShadow:pe("shadowMd"),padding:be[3],zIndex:eo.popover,minWidth:220,...t},...r})}));xx.displayName="PopoverContent";function ka({icon:e,eyebrow:t,title:n,subtitle:r,status:o,actions:i,toolbar:c,bodyPadding:a=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})]}),c&&s.jsx("div",{className:"panel-frame-toolbar",children:c}),s.jsx("div",{className:"panel-frame-body",style:{padding:a},children:l})]})}function ip({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 Jr({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 ap({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 vx({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:vn.sm,border:`1px solid ${pe("borderSubtle")}`,background:pe("surfaceRaised"),color:pe("textSecondary"),fontFamily:"var(--dql-font-mono, monospace)",fontSize:Ze.xs,fontWeight:Gi.medium,lineHeight:1,whiteSpace:"nowrap",...n},children:e??t})}const $c=e=>{let t;const n=new Set,r=(u,f)=>{const d=typeof u=="function"?u(t):u;if(!Object.is(d,t)){const h=t;t=f??(typeof d!="object"||d===null)?d:Object.assign({},t,d),n.forEach(m=>m(t,h))}},o=()=>t,a={setState:r,getState:o,getInitialState:()=>l,subscribe:u=>(n.add(u),()=>n.delete(u))},l=t=e(r,o,a);return a},Sx=(e=>e?$c(e):$c),wx=e=>e;function kx(e,t=wx){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 Lc=e=>{const t=Sx(e),n=r=>kx(t,r);return Object.assign(n,t),n},Cx=(e=>e?Lc(e):Lc),Nc=e=>Symbol.iterator in e,Bc=e=>"entries"in e,Fc=(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},jx=(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 Ex(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:Nc(e)&&Nc(t)?Bc(e)&&Bc(t)?Fc(e,t):jx(e,t):Fc({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Pr(e){const t=qe.useRef(void 0);return n=>{const r=e(n);return Ex(t.current,r)?t.current:t.current=r}}const Tx=/\{\{\s*([A-Za-z_][\w.-]*)\s*\}\}/g;function Ca(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(Tx)){const i=o[1],c=n.get(i);c&&c!==e.id&&r.set(c,{cellId:c,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 Rx(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,[]])),c=[];for(const u of t)for(const f of Ca(u,e)){if(!r.has(f.cellId)){c.push({cellId:u.id,dependency:f.cellId});continue}n.has(f.cellId)&&(i.get(f.cellId).push(u.id),o.set(u.id,(o.get(u.id)??0)+1))}const a=t.filter(u=>o.get(u.id)===0),l=[];for(;a.length>0;){const u=a.shift();l.push(u);for(const f of i.get(u.id)??[]){const d=(o.get(f)??0)-1;if(o.set(f,d),d===0){const h=t.find(m=>m.id===f);h&&a.push(h)}}}return{ordered:l,cycleCellIds:t.filter(u=>!l.some(f=>f.id===u.id)).map(u=>u.id),missing:c}}function Ax(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||Ca(i,t).some(c=>c.cellId===o)&&(n.add(i.id),r.push(i.id))}return n}function _x(){var e;if(typeof window<"u")try{(e=window.localStorage)==null||e.removeItem("dql-app-mode")}catch{}return"studio"}function Ox(){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 Px(){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 Dx={mainView:Px(),agentLogRun:void 0,settingsTab:"overview",themeMode:Ox(),appMode:_x(),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,blockStudioValidation:null,blockStudioMetadata:null,blockStudioCatalog:null,blockStudioCatalogLoading:!1,blockStudioImportOpen:!1,blockStudioDbtStatus:null,setupOpen:!1,inspectorOpen:!1,inspectorContext:null,apps:[],appsLoading:!1,activeAppId:null,activeDashboardId:null,activeAppExperience:"view",activeAppSection:"dashboards",activePersona:null,globalAi:{open:!1,audience:"stakeholder",context:{}}};function Mi(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 Ix(e,t){var n,r,o,i,c,a,l,u,f;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"],h=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&&!h,...m==="notebook"&&((c=e.activeFile)==null?void 0:c.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,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:Mi(t.cells),notebookTitle:t.title,notebookMetadata:t.metadata??{},notebookDirty:!1,mainView:t.file.type==="block"?"block_studio":"notebook",activeBlockPath:t.file.type==="block"?t.file.path:null,blockStudioDraft:t.file.type==="block"?e.blockStudioDraft:"",blockStudioDirty:!1,blockStudioPreview:t.file.type==="block"?e.blockStudioPreview:null,blockStudioValidation:t.file.type==="block"?e.blockStudioValidation:null,blockStudioMetadata:t.file.type==="block"?e.blockStudioMetadata:null,lineageFullscreen:!1,lineageFocusNodeId:null};case"OPEN_BLOCK_STUDIO":return{...e,activeFile:t.file,cells:[],notebookTitle:t.payload.metadata.name,notebookDirty:!1,mainView:"block_studio",dashboardMode:!1,activeBlockPath:t.payload.path,blockStudioDraft:t.payload.source,blockStudioDirty:!1,blockStudioPreview:null,blockStudioValidation:t.payload.validation,blockStudioMetadata:t.payload.metadata,blockStudioImportOpen:!1,lineageFullscreen:!1,lineageFocusNodeId:(a=t.payload.metadata)!=null&&a.name?`block:${t.payload.metadata.name}`:null};case"BLOCK_CERTIFICATION_ACCEPTED":return{...e,blockStudioDraft:t.source,blockStudioDirty:!1,blockStudioPreview:null,blockStudioMetadata:e.blockStudioMetadata?{...e.blockStudioMetadata,reviewStatus:"draft"}:null};case"RECONCILE_BLOCK_CERTIFICATION":{const d=t.newPath??t.payload.path,h={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(C=>C!==d&&C.includes("/_drafts/"))):new Set,S=e.files.filter(C=>!m.has(C.path)),b=S.findIndex(C=>C.path===d),x=b>=0?S.map((C,k)=>k===b?{...C,...h}:C):[...S,h];return e.mainView==="block_studio"&&!e.blockStudioDirty&&(!e.activeBlockPath||[t.oldPath,t.draftPath,d].includes(e.activeBlockPath))?{...e,files:x,activeFile:h,activeBlockPath:d,notebookTitle:t.payload.metadata.name,blockStudioDraft:t.payload.source,blockStudioDirty:!1,blockStudioPreview:null,blockStudioValidation:t.payload.validation,blockStudioMetadata:t.payload.metadata,lineageFocusNodeId:`block:${t.payload.metadata.name}`}:{...e,files:x}}case"SET_CELLS":return{...e,cells:Mi(t.cells),notebookDirty:!0};case"UPDATE_NOTEBOOK_METADATA":{const d=e.notebookMetadata;let h=!1;for(const m of Object.keys(t.updates))if(d[m]!==t.updates[m]){h=!0;break}return h?{...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 h=e.cells.findIndex(S=>S.id===t.afterId);if(h===-1)return{...e,cells:[...e.cells,d],notebookDirty:!0};const m=[...e.cells];return m.splice(h+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,h=d?Ax(t.id,e.cells):new Set,m=e.cells.map(b=>{if(b.id===t.id){const x={...b,...t.updates};return d&&b.result&&t.updates.stale===void 0?{...x,stale:!0}:x}return h.has(b.id)&&b.result?{...b,stale:!0}:b}),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 h=[...e.cells];return t.direction==="up"&&d>0?[h[d-1],h[d]]=[h[d],h[d-1]]:t.direction==="down"&&d<h.length-1&&([h[d],h[d+1]]=[h[d+1],h[d]]),{...e,cells:h,notebookDirty:!0}}case"REORDER_CELL":{const{fromIndex:d,toIndex:h}=t;if(d===h||d<0||h<0||d>=e.cells.length||h>=e.cells.length)return e;const m=[...e.cells],[S]=m.splice(d,1);return m.splice(h,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(h=>[h.path.toLowerCase(),h]));for(const h of t.tables){const m=h.path.toLowerCase(),S=d.get(m);d.set(m,S?{...S,...h,columns:h.columns.length>0?h.columns:S.columns,expanded:S.expanded}:h)}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,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(h=>h.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(h=>h!==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};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,h=t.dashboardId!==void 0?t.dashboardId:((u=d==null?void 0:d.homepage)==null?void 0:u.type)==="dashboard"?d.homepage.id:((f=d==null?void 0:d.dashboards[0])==null?void 0:f.id)??null,m=e.activeAppId===t.appId;return{...e,mainView:"apps",activeAppId:t.appId,activeDashboardId:h,activeAppExperience:t.experience??(m?e.activeAppExperience:"view"),activeAppSection:t.section??(m?e.activeAppSection:"dashboards"),lineageReturnTarget:null}}case"CLOSE_APP":return{...e,activeAppId: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=Cx((e,t)=>({...Dx,dispatch:n=>{const r=Ix(t(),n);e(r)}})),Pn=Ge,Mx=p.createContext(null);function $x({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(Pr(r=>{const{dispatch:o,...i}=r;return i})),t=Ge(r=>r.dispatch);return p.useContext(Mx)??{state:e,dispatch:t}}function kn(){return Ge(e=>e.dispatch)}function bt(){return`cell_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function ja(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 Lx="modulepreload",Nx=function(e){return"/"+e},zc={},Oe=function(t,n,r){let o=Promise.resolve();if(n&&n.length>0){let c=function(u){return Promise.all(u.map(f=>Promise.resolve(f).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),l=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));o=c(n.map(u=>{if(u=Nx(u),u in zc)return;zc[u]=!0;const f=u.endsWith(".css"),d=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const h=document.createElement("link");if(h.rel=f?"stylesheet":Lx,f||(h.as="script"),h.crossOrigin="",h.href=u,l&&h.setAttribute("nonce",l),document.head.appendChild(h),f)return new Promise((m,S)=>{h.addEventListener("load",m),h.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(c){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=c,window.dispatchEvent(a),!a.defaultPrevented)throw c}return o.then(c=>{for(const a of c||[])a.status==="rejected"&&i(a.reason);return t().catch(i)})};/**
55
+ * @license lucide-react v0.563.0 - ISC
56
+ *
57
+ * This source code is licensed under the ISC license.
58
+ * See the LICENSE file in the root directory of this source tree.
59
+ */const cp=(...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 Bx=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 Fx=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 qc=e=>{const t=Fx(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 zx={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 qx=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 Ux=p.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:c,...a},l)=>p.createElement("svg",{ref:l,...zx,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:cp("lucide",o),...!i&&!qx(a)&&{"aria-hidden":"true"},...a},[...c.map(([u,f])=>p.createElement(u,f)),...Array.isArray(i)?i:[i]]));/**
90
+ * @license lucide-react v0.563.0 - ISC
91
+ *
92
+ * This source code is licensed under the ISC license.
93
+ * See the LICENSE file in the root directory of this source tree.
94
+ */const ne=(e,t)=>{const n=p.forwardRef(({className:r,...o},i)=>p.createElement(Ux,{ref:i,iconNode:t,className:cp(`lucide-${Bx(qc(e))}`,`lucide-${e}`,r),...o}));return n.displayName=qc(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 Wx=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Kx=ne("arrow-down",Wx);/**
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 Vx=[["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"}]],Hx=ne("arrow-right-left",Vx);/**
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 Gx=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Qx=ne("arrow-up",Gx);/**
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 Jx=[["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"}]],Ea=ne("blocks",Jx);/**
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 Yx=[["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"}]],Xx=ne("bookmark",Yx);/**
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 Zx=[["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"}]],ev=ne("box",Zx);/**
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 tv=[["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"}]],$i=ne("boxes",tv);/**
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 nv=[["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"}]],rv=ne("briefcase",nv);/**
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 ov=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],sv=ne("check",ov);/**
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 iv=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Ta=ne("chevron-down",iv);/**
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 av=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],As=ne("chevron-right",av);/**
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 cv=[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]],lv=ne("chevrons-left",cv);/**
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 dv=[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]],uv=ne("chevrons-right",dv);/**
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 pv=[["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"}]],fv=ne("circle-alert",pv);/**
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 hv=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],lp=ne("circle-check",hv);/**
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 mv=[["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"}]],gv=ne("circle-question-mark",mv);/**
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 yv=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],bv=ne("clock",yv);/**
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 xv=[["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"}]],vv=ne("command",xv);/**
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 Sv=[["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"}]],So=ne("database",Sv);/**
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 wv=[["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"}]],dp=ne("download",wv);/**
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 kv=[["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"}]],Cv=ne("eye-off",kv);/**
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 jv=[["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"}]],Ev=ne("eye",jv);/**
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 Tv=[["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"}]],Rv=ne("file-check",Tv);/**
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 Av=[["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"}]],_v=ne("file-pen",Av);/**
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 Ov=[["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"}]],up=ne("file-plus",Ov);/**
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 Pv=[["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"}]],Dv=ne("file-question-mark",Pv);/**
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 Iv=[["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"}]],Ra=ne("file-text",Iv);/**
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 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:"m14.5 12.5-5 5",key:"b62r18"}],["path",{d:"m9.5 12.5 5 5",key:"1rk7el"}]],$v=ne("file-x",Mv);/**
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 Lv=[["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"}]],Nv=ne("files",Lv);/**
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 Bv=[["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"}]],pp=ne("folder-open",Bv);/**
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 Fv=[["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"}]],Yr=ne("folder",Fv);/**
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 zv=[["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"}]],qv=ne("funnel",zv);/**
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 Uv=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Wv=ne("gauge",Uv);/**
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 Kv=[["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"}]],Dr=ne("git-branch",Kv);/**
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 Vv=[["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"}]],Hv=ne("git-commit-horizontal",Vv);/**
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 Gv=[["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"}]],Qv=ne("git-fork",Gv);/**
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 Jv=[["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"}]],fp=ne("layers",Jv);/**
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 Yv=[["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"}]],Xv=ne("layout-dashboard",Yv);/**
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 Zv=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],qn=ne("loader-circle",Zv);/**
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 eS=[["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"}]],tS=ne("message-circle",eS);/**
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 nS=[["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"}]],rS=ne("monitor",nS);/**
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 oS=[["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"}]],sS=ne("network",oS);/**
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 iS=[["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"}]],aS=ne("notebook-pen",iS);/**
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 cS=[["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"}]],lS=ne("package",cS);/**
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 dS=[["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"}]],uS=ne("palette",dS);/**
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 pS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],fS=ne("panel-left",pS);/**
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 hS=[["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"}]],mS=ne("plug",hS);/**
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 gS=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],yS=ne("plus",gS);/**
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 bS=[["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"}]],cs=ne("refresh-cw",bS);/**
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 xS=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Uc=ne("search",xS);/**
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 vS=[["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"}]],SS=ne("settings-2",vS);/**
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 wS=[["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"}]],kS=ne("settings",wS);/**
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 CS=[["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"}]],jS=ne("shield-alert",CS);/**
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 ES=[["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"}]],TS=ne("shield-check",ES);/**
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 RS=[["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"}]],AS=ne("sigma",RS);/**
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 _S=[["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"}]],hp=ne("sparkles",_S);/**
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 OS=[["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"}]],PS=ne("square-dashed",OS);/**
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 DS=[["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"}]],IS=ne("tag",DS);/**
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 MS=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],$S=ne("terminal",MS);/**
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 LS=[["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"}]],mp=ne("trash-2",LS);function NS(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 BS(e,t){const n=e.mode??"both";return n==="both"||n===t}function FS({open:e,onClose:t}){const{state:n,dispatch:r}=et(),[o,i]=p.useState(""),[c,a]=p.useState(0),l=p.useRef(null);p.useEffect(()=>{e&&(i(""),a(0))},[e]);const u=p.useMemo(()=>{const m=v=>r(v),S=()=>t(),b=v=>()=>{v(),S()},x=[["Files","files",Nv],["Lineage","lineage",Qv],["Git","git",Dr],["Block Library","block_library",Ea],["Apps","apps",sS],["Connections","connection",mS]],w=[{mode:"obsidian",label:"Obsidian"},{mode:"paper",label:"Paper"},{mode:"white",label:"White"}],C=[];C.push({id:"sidebar.toggle",label:n.sidebarOpen?"Hide sidebar":"Show sidebar",group:"View",icon:fS,shortcut:"⌘B",mode:"studio",run:b(()=>m({type:"TOGGLE_SIDEBAR"}))},{id:"inspector.toggle",label:n.inspectorOpen?"Hide inspector":"Show inspector",group:"View",icon:n.inspectorOpen?Cv:Ev,shortcut:"⌘⇧I",mode:"studio",run:b(()=>m({type:"TOGGLE_INSPECTOR"}))},{id:"dashboard.toggle",label:n.dashboardMode?"Exit dashboard mode":"Enter dashboard mode",group:"View",icon:Xv,shortcut:"⌘D",run:b(()=>m({type:"TOGGLE_DASHBOARD_MODE"}))},{id:"dev.toggle",label:"Toggle dev panel",group:"View",icon:$S,shortcut:"⌘J",mode:"studio",run:b(()=>m({type:"TOGGLE_DEV_PANEL"}))});for(const[v,j,D]of x)C.push({id:`panel.${j}`,label:`Go to ${v}`,group:"Navigate",icon:D,mode:"studio",run:b(()=>{m({type:"SET_SIDEBAR_PANEL",panel:j}),j!=="lineage"&&!n.sidebarOpen&&m({type:"TOGGLE_SIDEBAR"})})});C.push({id:"notebook.new",label:"New notebook…",group:"Create",icon:up,mode:"studio",run:b(()=>m({type:"OPEN_NEW_NOTEBOOK_MODAL"}))},{id:"block.new",label:"New block…",group:"Create",icon:PS,mode:"studio",run:b(()=>m({type:"OPEN_NEW_BLOCK_MODAL"}))});const k=n.themeMode==="dark"||n.themeMode==="midnight"?"obsidian":n.themeMode==="light"?"paper":n.themeMode==="arctic"?"white":n.themeMode;for(const v of w)v.mode!==k&&C.push({id:`theme.${v.mode}`,label:`Switch to ${v.label}`,group:"Theme",icon:uS,keywords:"appearance color",run:b(()=>m({type:"SET_THEME",mode:v.mode}))});return C},[n.sidebarOpen,n.inspectorOpen,n.themeMode,n.dashboardMode,n.appMode,n.sidebarPanel,r,t]),f=p.useMemo(()=>{const S=u.filter(b=>BS(b,n.appMode)).map(b=>({a:b,s:NS(b,o)})).filter(b=>b.s>0);return S.sort((b,x)=>x.s-b.s),S.map(b=>b.a)},[u,o,n.appMode]);p.useEffect(()=>{a(0)},[o]),p.useEffect(()=>{var S;const m=(S=l.current)==null?void 0:S.querySelector(`[data-palette-idx="${c}"]`);m==null||m.scrollIntoView({block:"nearest"})},[c]);const d=m=>{var S;m.key==="ArrowDown"?(m.preventDefault(),a(b=>Math.min(f.length-1,b+1))):m.key==="ArrowUp"?(m.preventDefault(),a(b=>Math.max(0,b-1))):m.key==="Enter"&&(m.preventDefault(),(S=f[c])==null||S.run())};let h="";return s.jsx(jy,{open:e,onOpenChange:m=>!m&&t(),children:s.jsxs(Ey,{children:[s.jsx(Ty,{style:{position:"fixed",inset:0,background:pe("surfaceOverlay"),zIndex:eo.overlay}}),s.jsxs(Ry,{"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:vn.lg,boxShadow:pe("shadowLg"),zIndex:eo.modal,display:"flex",flexDirection:"column",overflow:"hidden"},onKeyDown:d,children:[s.jsx(Ay,{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(vv,{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:[f.length===0&&s.jsx("div",{style:{padding:be[4],fontSize:Ze.sm,color:pe("textMuted"),textAlign:"center"},children:"No matching commands"}),f.map((m,S)=>{const b=m.group!==h;h=m.group;const x=S===c,w=m.icon;return s.jsxs(qe.Fragment,{children:[b&&s.jsx("div",{style:{padding:`${be[2]}px ${be[4]}px ${be[1]}px`},children:s.jsx(ip,{tone:"neutral",children:m.group})}),s.jsxs("div",{"data-palette-idx":S,role:"option","aria-selected":x,onMouseEnter:()=>a(S),onMouseDown:C=>{C.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:x?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(vx,{shortcut:m.shortcut})]})]},m.id)})]})]})]})})}function Li(e){const t=Xt(e);if(!t)return;const n=WS(t.kind),r=zS(t.source);if(!n||!r)return;const o=tw(t.limit);return{kind:n,source:r,name:St(t.name),sourcePath:St(t.sourcePath),metrics:Ni(t.metrics),dimensions:Ni(t.dimensions),filters:KS(t.filters),timeDimension:VS(t.timeDimension),orderBy:HS(t.orderBy),parameters:GS(t.parameters),parameterValues:XS(t.parameterValues),persistence:ZS(t.persistence),trustState:ew(t.trustState),compiledSql:St(t.compiledSql),executionReceipt:US(t.executionReceipt),filterableColumns:qS(t.filterableColumns),...o===void 0?{}:{limit:o}}}function zS(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function qS(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 US(e){const t=Xt(e);if(!t)return;const n=Bo(t.sourceFingerprint),r=Bo(t.compiledSqlFingerprint),o=Bo(t.parameterFingerprint),i=Bo(t.resultFingerprint);return n&&r&&o&&i?{sourceFingerprint:n,compiledSqlFingerprint:r,parameterFingerprint:o,resultFingerprint:i}:void 0}function Bo(e){return typeof e=="string"&&/^[a-f0-9]{64}$/i.test(e.trim())?e.trim().toLowerCase():void 0}function WS(e){return e==="certified_block"||e==="semantic_block"||e==="sql_block"?e:void 0}function KS(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:Ni(r.values)??[]}]});return t.length?t:void 0}function VS(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 HS(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 GS(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),c=QS(o==null?void 0:o.type),a=JS(o==null?void 0:o.policy);if(!o||!i||!c||!a||t.has(i))return[];t.add(i);const l=YS(o.binding);return[{name:i,type:c,required:o.required===!0,...o.default===void 0?{}:{default:o.default},policy:a,...l?{binding:l}:{}}]});return n.length?n:void 0}function QS(e){return e==="string"||e==="number"||e==="boolean"||e==="date"||e==="string[]"||e==="number[]"||e==="date[]"?e:void 0}function JS(e){return e==="dynamic"||e==="static"||e==="business"||e==="derived"||e==="optional"||e==="ambiguous_review_required"?e:void 0}function YS(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 XS(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 ZS(e){return e==="transient"||e==="saved"?e:void 0}function ew(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 Ni(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 tw(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):void 0}const gp="dql_token",Wc="dql.server-token.v1";function nw(e){var r;return((r=new URLSearchParams(e.replace(/^#/,"")).get(gp))==null?void 0:r.trim())||void 0}function rw(e){const t=new URLSearchParams(e.replace(/^#/,""));t.delete(gp);const n=t.toString();return n?`#${n}`:""}function ow(){var e;if(!(typeof window>"u"))try{const t=nw(window.location.hash);if(t){window.sessionStorage.setItem(Wc,t);const n=rw(window.location.hash);return window.history.replaceState(window.history.state,"",`${window.location.pathname}${window.location.search}${n}`),t}return((e=window.sessionStorage.getItem(Wc))==null?void 0:e.trim())||void 0}catch{return}}const Kc=ow();function Ur(e){const t=new Headers(e);return Kc&&t.set("Authorization",`Bearer ${Kc}`),t}const sw={totals:{modelsScanned:0,businessModels:0,plumbingExcluded:0,metricsFound:0},willGenerate:0,willSkip:0,domains:[],config:{businessLayers:[],excludeLayers:[],maxPerDomain:0,minScore:0,aiEnrichment:"auto"}};function Fo(){return{total:0,tracked:0,changed:0,untracked:0,ignored:0,paths:[]}}const Wr=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 Bi(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=typeof(r==null?void 0:r.message)=="string"&&r.message.trim()?r.message:typeof(r==null?void 0:r.error)=="string"&&r.error.trim()?r.error:n;return new xt({message:o,status:e.status,code:typeof(r==null?void 0:r.code)=="string"?r.code:void 0,recoverable:typeof(r==null?void 0:r.recoverable)=="boolean"?r.recoverable:void 0,details:r==null?void 0:r.details,nextActions:Array.isArray(r==null?void 0:r.nextActions)?r.nextActions.filter(i=>typeof i=="string"):void 0,requestId:typeof(r==null?void 0:r.requestId)=="string"?r.requestId:void 0,snapshotId:typeof(r==null?void 0:r.snapshotId)=="string"?r.snapshotId:void 0})}catch{return new xt({message:n,status:e.status})}}const Vs=new Map;async function E(e,t){if(((t==null?void 0:t.method)??"GET").toUpperCase()==="GET"&&!(t!=null&&t.signal)&&!(t!=null&&t.body)){const o=Vs.get(e);if(o)return o;const i=Vc(e,t).finally(()=>{Vs.delete(e)});return Vs.set(e,i),i}return Vc(e,t)}async function Vc(e,t){var r;let n;try{const o=Ur(t==null?void 0:t.headers);o.has("Content-Type")||o.set("Content-Type","application/json"),n=await fetch(`${Wr}${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 Bi(n,o)}if(n.status!==204)return n.json()}async function iw(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 c=a=>{const l=a.split(/\r?\n/);let u="message";const f=[];for(const h of l)h.startsWith("event:")&&(u=h.slice(6).trim()),h.startsWith("data:")&&f.push(h.slice(5).trimStart());if(f.length===0)return;const d=JSON.parse(f.join(`
395
+ `));if(u==="agent-run-event")t({kind:"event",event:d});else if(u==="agent-run-answer-delta"){const h=typeof(d==null?void 0:d.delta)=="string"?d.delta:"";h&&t({kind:"answer-delta",delta:h})}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:a,done:l}=await n.read();if(a){o+=r.decode(a,{stream:!l});let u=o.search(/\r?\n\r?\n/);for(;u>=0;){const f=o.slice(0,u);o=o.slice(o[u]==="\r"?u+4:u+2),c(f),u=o.search(/\r?\n\r?\n/)}}if(l)break}if(o.trim()&&c(o),!i)throw new Error("Agent run stream ended before completion.");return i}function _n(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"?_n(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:Li(e==null?void 0:e.dqlArtifact),dqlPromotionAction:gw((e==null?void 0:e.dqlPromotionAction)??((n=e==null?void 0:e.dqlPromotion)==null?void 0:n.recommendedAction)),dqlPromotion:yp(e==null?void 0:e.dqlPromotion),researchPlan:aw(e==null?void 0:e.researchPlan),reviewChecklist:hw(e==null?void 0:e.reviewChecklist,e),...t?{resultPreview:t}:{resultPreview:void 0}}}function aw(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",c=r.status==="ready"||r.status==="error"?r.status:"not_run",a=o.path==="review_context"||o.path==="run_preview"||o.path==="reuse_existing"||o.path==="create_dql_draft"||o.path==="open_certification"||o.path==="complete_review"?o.path:"needs_sql",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:cw(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:c,...l===void 0?{}:{rowCount:l}},promotion:{path:a,duplicateDecision:typeof o.duplicateDecision=="string"&&o.duplicateDecision.trim()?o.duplicateDecision:void 0},reviewFocus:Array.isArray(t.reviewFocus)?t.reviewFocus.map(String).filter(Boolean):[],generatedAt:typeof t.generatedAt=="string"&&t.generatedAt.trim()?t.generatedAt:new Date(0).toISOString()}}function cw(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 lw(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 dw(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:{},c=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(c.pageSize)||25,maxPageSize:Ce(c.maxPageSize)||500,sourceCoverageLimit:Ce(c.sourceCoverageLimit)||1e4,seedCellLimit:Ce(c.seedCellLimit)||1e3},warnings:Array.isArray(t.warnings)?t.warnings.filter(a=>typeof a=="string"):[]}}function uw(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 pw(e){const t=typeof e=="string"?e:"";return(t.split(/[\\/]/).pop()??t).replace(/\.dqlnb$/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim()||"Untitled notebook"}function fw(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 zo(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 hw(e,t){var u,f;if(e&&typeof e=="object"&&Array.isArray(e.items))return{readyForDqlDraft:e.readyForDqlDraft===!0,readyForCertificationReview:e.readyForCertificationReview===!0,blockers:Array.isArray(e.blockers)?e.blockers.filter(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)??((f=t.resultPreview)==null?void 0:f.rows.length)??0,i=!!(t.resultPreview&&(t.resultPreview.columns.length>0||o>0)),c=!!t.draftBlockPath,a=!!(t.contextPackId||t.evidence),l=t.dqlPromotionAction==="reuse_existing";return{readyForDqlDraft:!!(!l&&t.question&&n&&a&&t.status!=="error"),readyForCertificationReview:!!(!l&&t.question&&n&&a&&i&&c),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:a||l?"passed":"warning",detail:a?"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:c||l?"passed":"pending",detail:c?`Draft saved at ${t.draftBlockPath}.`:l?"No new DQL draft is required.":"Create a DQL draft after review."}]}}function mw(e){var r,o,i,c;const t=e&&typeof e=="object"?e:{},n=t.routeDecision&&typeof t.routeDecision=="object"?{route:typeof t.routeDecision.route=="string"?t.routeDecision.route:void 0,intent:typeof t.routeDecision.intent=="string"?t.routeDecision.intent:void 0,reason:typeof t.routeDecision.reason=="string"?t.routeDecision.reason:void 0}:void 0;return{contextPackId:typeof t.contextPackId=="string"?t.contextPackId:"",trustLabel:typeof t.trustLabel=="string"?t.trustLabel:void 0,routeDecision:n,evidence:Array.isArray(t.evidence)?t.evidence.map(a=>({objectKey:typeof a.objectKey=="string"?a.objectKey:void 0,objectType:typeof a.objectType=="string"?a.objectType:void 0,name:typeof a.name=="string"?a.name:"Evidence",role:typeof a.role=="string"?a.role:void 0,reason:typeof a.reason=="string"?a.reason:""})):[],summaries:Array.isArray(t.summaries)?t.summaries.map(a=>({title:typeof a.title=="string"?a.title:"Context",detail:typeof a.detail=="string"?a.detail:"",objectType:typeof a.objectType=="string"?a.objectType:void 0,reason:typeof a.reason=="string"?a.reason:void 0})):[],relations:Array.isArray(t.relations)?t.relations.map(a=>({relation:typeof a.relation=="string"?a.relation:"",name:typeof a.name=="string"?a.name:"Relation",source:typeof a.source=="string"?a.source:"",columns:Array.isArray(a.columns)?a.columns.map(String):[]})).filter(a=>a.relation||a.name):[],missingContext:Array.isArray(t.missingContext)?t.missingContext.map(a=>({kind:typeof a.kind=="string"?a.kind:"metadata",message:typeof a.message=="string"?a.message:"",severity:typeof a.severity=="string"?a.severity:"warning"})).filter(a=>a.message):[],warnings:Array.isArray(t.warnings)?t.warnings.filter(a=>typeof a=="string"):[],topRejected:Array.isArray(t.topRejected)?t.topRejected.map(a=>({name:typeof a.name=="string"?a.name:"Rejected context",objectType:typeof a.objectType=="string"?a.objectType:void 0,reason:typeof a.reason=="string"?a.reason:"",score:typeof a.score=="number"&&Number.isFinite(a.score)?a.score:void 0})).filter(a=>a.reason):[],counts:{objects:typeof((r=t.counts)==null?void 0:r.objects)=="number"?t.counts.objects:0,evidence:typeof((o=t.counts)==null?void 0:o.evidence)=="number"?t.counts.evidence:0,relations:typeof((i=t.counts)==null?void 0:i.relations)=="number"?t.counts.relations:0,warnings:typeof((c=t.counts)==null?void 0:c.warnings)=="number"?t.counts.warnings:0}}}function gw(e){return e==="reuse_existing"||e==="extend_existing"||e==="create_replacement"||e==="create_new"||e==="review_required"?e:void 0}function yp(e){if(!(!e||typeof e!="object"))return{importId:typeof e.importId=="string"?e.importId:"",candidateIds:Array.isArray(e.candidateIds)?e.candidateIds.filter(t=>typeof t=="string"):[],draftBlockPath:typeof e.draftBlockPath=="string"?e.draftBlockPath:void 0,recommendedAction:typeof e.recommendedAction=="string"?e.recommendedAction:void 0,similarityMatches:Array.isArray(e.similarityMatches)?e.similarityMatches:[],candidates:Array.isArray(e.candidates)?e.candidates.map(t=>({...t,similarityMatches:Array.isArray(t.similarityMatches)?t.similarityMatches:[],parameterPolicy:Array.isArray(t.parameterPolicy)?t.parameterPolicy:[],allowedFilters:Array.isArray(t.allowedFilters)?t.allowedFilters:[],warnings:Array.isArray(t.warnings)?t.warnings:[]})):[],createdAt:typeof e.createdAt=="string"?e.createdAt:""}}const B={async listOperations(e=50){return E(`/api/operations?limit=${Math.max(1,Math.min(100,Math.floor(e)))}`)},async cancelOperation(e){return E(`/api/operations/${encodeURIComponent(e)}`,{method:"DELETE"})},async requestBlockStudioCertification(e){return E("/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 E("/api/modeling/dbt-first")},async getDbtModelingNode(e){return E(`/api/modeling/dbt-first/nodes/${encodeURIComponent(e)}`)},async getDbtModelingNodes(e){return E("/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"),E(`/api/modeling/dbt-first/inventory?${t.toString()}`)},async getDomainWorkspaces(){return E("/api/domain-workspaces")},async getRelatedDomainProducts(e){return E(`/api/domain-workspaces/${encodeURIComponent(e)}/related-products`)},async getAllRelatedDomainProducts(){return E("/api/domain-workspaces/related-products")},async getDomainKnowledge(e){return E(`/api/domain-workspaces/${encodeURIComponent(e)}/knowledge`)},async previewModelingChange(e,t){return E("/api/modeling/dbt-first/preview",{method:"POST",body:JSON.stringify({change:e,expectedSnapshotId:t})})},async applyModelingChange(e,t,n){return E("/api/modeling/dbt-first/apply",{method:"POST",body:JSON.stringify({change:e,fingerprint:t,expectedSnapshotId:n})})},async validateModelingRelationship(e,t){return(await E("/api/modeling/dbt-first/relationships/validate",{method:"POST",body:JSON.stringify({relationship:e,expectedSnapshotId:t})})).evidence},async previewDbtSourcePatch(e,t){return E("/api/modeling/dbt-first/dbt-source/preview",{method:"POST",body:JSON.stringify({change:e,expectedSnapshotId:t})})},async applyDbtSourcePatch(e,t,n){return E("/api/modeling/dbt-first/dbt-source/apply",{method:"POST",body:JSON.stringify({change:e,expectedFingerprint:t,expectedSnapshotId:n})})},async getSettingsEnvStatus(){try{return await E("/api/settings/env-status")}catch{return{groups:[]}}},async getProposeReadiness(e){try{return await E("/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:sw,proposals:[]}}},async generateProposeDrafts(e){try{return await E("/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 E(`/api/propose/preview?slug=${encodeURIComponent(e)}`)},async aiBuild(e){return E("/api/ai/build",{method:"POST",body:JSON.stringify(e)})},async createAgentRun(e){return(await E("/api/agent-runs",{method:"POST",body:JSON.stringify(e)})).run},async createAgentRunStream(e,t,n){let r;try{r=await fetch(`${Wr}/api/agent-runs?stream=1`,{method:"POST",headers:Ur({"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 Bi(r,o)}return iw(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 E(`/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 E(`/api/agent-runs/${encodeURIComponent(e)}`)},async deriveAnalyticalRepair(e,t){return E(`/api/agent-runs/${encodeURIComponent(e)}/analytical-repair`,{method:"POST",body:JSON.stringify({repair:t})})},async repairAgentRunExecution(e,t){return E(`/api/agent-runs/${encodeURIComponent(e)}/repair-execution`,{method:"POST",body:JSON.stringify({threadId:t})})},async repairNotebookCellExecution(e,t,n){var o,i,c,a,l,u;const r=await E("/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:((c=e.blockBinding)==null?void 0:c.state)==="bound"?e.blockBinding.parameterValues:e.dqlParameterValues,executionContext:n})});if(n!=null&&n.runId&&typeof((a=r==null?void 0:r.executionContext)==null?void 0:a.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:_n(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 E(`/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 E(`/api/agent/threads${n}`)},async createAgentThread(e={}){return(await E("/api/agent/threads",{method:"POST",body:JSON.stringify(e)})).thread},async getAgentThread(e){return E(`/api/agent/threads/${encodeURIComponent(e)}`)},async updateAgentThread(e,t){return E(`/api/agent/threads/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})},async archiveAgentThread(e){return E(`/api/agent/threads/${encodeURIComponent(e)}/archive`,{method:"POST"})},async deleteAgentThread(e){return E(`/api/agent/threads/${encodeURIComponent(e)}`,{method:"DELETE"})},async requestCertification(e){return E("/api/agent-runs/request-certification",{method:"POST",body:JSON.stringify(e)})},async getIdentity(){return E("/api/identity")},async getProviderSettings(){try{return await E("/api/settings/providers")}catch{return{providers:[]}}},async getProviderCliStatus(){try{return await E("/api/settings/providers/cli-status")}catch{return{status:{}}}},async saveProviderSettings(e){return E("/api/settings/providers",{method:"POST",body:JSON.stringify(e)})},async startOAuth(e){return E(`/api/auth/${e}/start`,{method:"POST"})},async getOAuthStatus(e){return E(`/api/auth/${e}/status`)},async signOutOAuth(e){return E(`/api/auth/${e}/signout`,{method:"POST"})},async testProviderSettings(e,t){try{return await E("/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 E("/api/settings/mcp")}catch{return{settings:{path:"",entries:[],warnings:[]}}}},async saveRemoteMcpSettings(e){return E("/api/settings/mcp",{method:"POST",body:JSON.stringify({entries:e})})},async recordAgentCorrection(e){return E("/api/agent/learnings/correction",{method:"POST",body:JSON.stringify(e)})},async listAgentHints(e){const t=e?`?status=${encodeURIComponent(e)}`:"";return E(`/api/agent/hints${t}`)},async reviewAgentHint(e,t,n){return E(`/api/agent/hints/${encodeURIComponent(e)}/review`,{method:"POST",body:JSON.stringify({decision:t,...n?{note:n}:{}})})},async updateAgentHint(e,t){return E(`/api/agent/hints/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})},async transitionAgentHint(e,t){return E(`/api/agent/hints/${encodeURIComponent(e)}/lifecycle`,{method:"POST",body:JSON.stringify(t)})},async listAgentMemory(e){const t=e?`?scope=${encodeURIComponent(e)}`:"";try{return await E(`/api/agent/memory${t}`)}catch{return{memories:[]}}},async saveAgentMemory(e){return E("/api/agent/memory",{method:"POST",body:JSON.stringify(e)})},async deleteAgentMemory(e){return E(`/api/agent/memory?id=${encodeURIComponent(e)}`,{method:"DELETE"})},async ensureAgentMemoryFiles(){return E("/api/agent/memory/default-files",{method:"POST"})},async listNotebooks(){try{return await E("/api/notebooks")}catch{return[]}},async readNotebook(e){return E(`/api/notebook-content?path=${encodeURIComponent(e)}`)},async deleteNotebook(e){return E(`/api/notebooks?path=${encodeURIComponent(e)}`,{method:"DELETE"})},async createNotebook(e,t,n={}){return E("/api/notebooks",{method:"POST",body:JSON.stringify({name:e,template:t,...n})})},async createBlock(e,t){return E("/api/blocks",{method:"POST",body:JSON.stringify({name:e,...t})})},async getBlockLibrary(){try{return await E("/api/blocks/library")}catch{return{blocks:[]}}},async getApps(){try{return await E("/api/apps")}catch{return{apps:[]}}},async updateBlockStatus(e,t){return E("/api/blocks/status",{method:"POST",body:JSON.stringify({path:e,newStatus:t})})},async getBlockHistory(e){try{return await E(`/api/blocks/history?path=${encodeURIComponent(e)}`)}catch{return{entries:[]}}},async runBlockTests(e,t){return E("/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 E(`/api/block-studio/catalog${n?`?${n}`:""}`)},async getBlockStudioDbtStatus(){return E("/api/block-studio/dbt-status")},async openBlockStudio(e){return E(`/api/block-studio/open?path=${encodeURIComponent(e)}`)},async getBlockBody(e){return E(`/api/blocks/body?path=${encodeURIComponent(e)}`)},async validateBlockStudio(e,t,n){return E("/api/block-studio/validate",{method:"POST",body:JSON.stringify({source:e,path:t}),signal:n})},async runBlockStudio(e,t,n){return E("/api/block-studio/run",{method:"POST",body:JSON.stringify({source:e,path:t,parameters:n})})},async getCertifiedBlockParameters(e){return E(`/api/blocks/parameters?name=${encodeURIComponent(e)}`)},async invokeCertifiedBlock(e,t,n){var o,i,c,a,l,u;const r=await E("/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:{..._n(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((c=r==null?void 0:r.result)==null?void 0:c.blockPath)=="string"?{blockPath:r.result.blockPath}:{},...(a=r==null?void 0:r.result)!=null&&a.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 E("/api/dql/artifacts/add-filter",{method:"POST",body:JSON.stringify({artifact:e,resultColumns:t,column:n,value:r,executionTarget:o})}),c=Li(i==null?void 0:i.artifact);if(!c)throw new Error("Adding the filter input returned an invalid artifact contract.");return{artifact:c,parameterName:String((i==null?void 0:i.parameterName)??n)}},async invokeDqlArtifact(e,t,n,r,o){var a,l,u,f,d,h;const i=await E("/api/dql/artifacts/execute",{method:"POST",body:JSON.stringify({artifact:e,parameters:t,question:n,blockName:r,executionTarget:o})}),c=Li(i==null?void 0:i.artifact);if(!c)throw new Error("DQL artifact execution returned an invalid artifact contract.");return{artifact:c,parameters:c.parameters??[],result:{..._n(i==null?void 0:i.result),...typeof((a=i==null?void 0:i.result)==null?void 0:a.sql)=="string"?{sql:i.result.sql}:{},...typeof((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}:{},...(f=i==null?void 0:i.result)!=null&&f.chartConfig?{chartConfig:i.result.chartConfig}:{},...Array.isArray((d=i==null?void 0:i.result)==null?void 0:d.parameters)?{parameters:i.result.parameters}:{},...typeof((h=i==null?void 0:i.result)==null?void 0:h.auditId)=="string"?{auditId:i.result.auditId}:{}}}},async composeSemanticBlock(e){return E("/api/block-studio/compose-semantic",{method:"POST",body:JSON.stringify({question:e})})},async saveBlockStudio(e){return E("/api/block-studio/save",{method:"POST",body:JSON.stringify(e)})},async saveAgentBlockDraft(e){return E("/api/block-studio/agent-drafts",{method:"POST",body:JSON.stringify(e)})},async deleteBlockStudio(e){return E(`/api/block-studio/block?path=${encodeURIComponent(e)}`,{method:"DELETE"})},async previewBlockStudioImport(e){return E("/api/block-studio/import/preview",{method:"POST",body:JSON.stringify(e)})},async listBlockStudioImports(){return E("/api/block-studio/imports")},async createBlockStudioImport(e){return E("/api/block-studio/imports",{method:"POST",body:JSON.stringify(e)})},async createDqlGenerationSession(e){return E("/api/block-studio/ai-imports",{method:"POST",body:JSON.stringify(e)})},async getDqlGenerationSession(e){return E(`/api/block-studio/ai-imports/${encodeURIComponent(e)}`)},async getBlockStudioImport(e){return E(`/api/block-studio/imports/${encodeURIComponent(e)}`)},async deleteBlockStudioImport(e){return E(`/api/block-studio/imports/${encodeURIComponent(e)}`,{method:"DELETE"})},async clearBlockStudioImports(){return E("/api/block-studio/imports",{method:"DELETE"})},async updateBlockStudioImportCandidate(e,t,n){return E(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})},async updateDqlGenerationCandidate(e,t,n){return E(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})},async matchSqlForBlockReuse(e,t){return E("/api/block-studio/match-sql",{method:"POST",body:JSON.stringify({sql:e,...t??{}})})},async previewDqlGenerationCandidate(e,t){return E(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/preview`,{method:"POST"})},async certifyDqlGenerationCandidate(e,t){return E(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/certify`,{method:"POST"})},async saveSelectedDqlGenerationCandidates(e,t){return E(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/save-selected`,{method:"POST",body:JSON.stringify(t)})},async runBlockStudioImportCandidate(e,t){return E(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/run`,{method:"POST"})},async saveBlockStudioImportCandidate(e,t){return E(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/save`,{method:"POST"})},async saveAllBlockStudioImportCandidates(e){return E(`/api/block-studio/imports/${encodeURIComponent(e)}/save-all`,{method:"POST"})},async assistBlockStudioImportCandidate(e,t,n){return E(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/ai-assist`,{method:"POST",body:JSON.stringify({action:n})})},async getSemanticLayerDiagnostics(){return E("/api/semantic-layer/diagnostics")},async reloadSemanticLayer(){return E("/api/semantic-layer/reload",{method:"POST"})},async certifyBlockStudio(e){const t=await fetch(`${Wr}/api/block-studio/certify`,{headers:Ur({"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 E("/api/blocks/save-from-cell",{method:"POST",body:JSON.stringify(e)})},async getBlockTemplates(){try{return(await E("/api/blocks/templates")).templates}catch{return[]}},async listBlocks(e){try{return(await E("/api/notebooks")).filter(n=>n.type==="block"&&(!e||n.path.startsWith(`blocks/${e}/`)))}catch{return[]}},async saveNotebook(e,t){return E("/api/notebook-content",{method:"PUT",body:JSON.stringify({path:e,content:t})})},async executeQuery(e,t,n,r){var i,c,a;const o=await E("/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{..._n(o),executionTarget:((c=o==null?void 0:o.executionTarget)==null?void 0:c.target)==="local"?{target:"local"}:((a=o==null?void 0:o.executionTarget)==null?void 0:a.target)==="connection"?{target:"connection",...typeof o.executionTarget.connectionName=="string"?{connectionName:o.executionTarget.connectionName}:{}}:void 0,compiledSql:typeof(o==null?void 0:o.compiledSql)=="string"?o.compiledSql:void 0,executedSql:typeof(o==null?void 0:o.executedSql)=="string"?o.executedSql:void 0,targetBinding:o!=null&&o.targetBinding&&typeof o.targetBinding=="object"?o.targetBinding:void 0,executionReceipt:o!=null&&o.executionReceipt&&typeof o.executionReceipt=="object"?o.executionReceipt:void 0}},async previewGeneratedSql(e,t){try{const n=await E("/api/ai/sql-draft/preview",{method:"POST",body:JSON.stringify({sql:e}),signal:t});return{ok:!0,result:_n(n.result)}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async executeNotebookCell(e,t,n){var o,i,c,a,l,u;const r=await E("/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((c=r==null?void 0:r.executionContext)==null?void 0:c.cellId)=="string"?r.executionContext.cellId:void 0,runId:typeof((a=r==null?void 0:r.executionContext)==null?void 0:a.runId)=="string"?r.executionContext.runId:void 0,title:typeof(r==null?void 0:r.title)=="string"?r.title:void 0,blockName:typeof(r==null?void 0:r.blockName)=="string"?r.blockName:void 0,blockPath:typeof(r==null?void 0:r.blockPath)=="string"?r.blockPath:void 0,chartConfig:r!=null&&r.chartConfig&&typeof r.chartConfig=="object"?r.chartConfig:void 0,tests:Array.isArray(r==null?void 0:r.tests)?r.tests:void 0,result:r!=null&&r.result?_n(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 E("/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(`${Wr}/api/datasets/import`,{method:"POST",headers:Ur(),body:t});if(!n.ok){const r=await n.text().catch(()=>"");throw Bi(n,r)}return n.json()}return E("/api/datasets/import",{method:"POST",body:JSON.stringify(e)})},async refreshDataset(e){return E(`/api/datasets/${encodeURIComponent(e)}/refresh`,{method:"POST"})},async updateDatasetSchema(e,t){return E(`/api/datasets/${encodeURIComponent(e)}/schema`,{method:"POST",body:JSON.stringify({overrides:t})})},async renameDataset(e,t,n){return E(`/api/datasets/${encodeURIComponent(e)}/rename`,{method:"POST",body:JSON.stringify({name:t,alias:n})})},async pinDataset(e,t=!0){return E(`/api/datasets/${encodeURIComponent(e)}/pin`,{method:"POST",body:JSON.stringify({pinned:t})})},async removeDataset(e){await E(`/api/datasets/${encodeURIComponent(e)}`,{method:"DELETE"})},async stageDataset(e){return E("/api/datasets/stage",{method:"POST",body:JSON.stringify(e)})},async listNotebookResearch(e){var o,i,c,a,l,u,f,d,h,m,S,b,x,w,C,k,v,j,D,T;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 E(`/api/notebook/research${n}`);return{runs:r.runs.map(Wt),total:typeof r.total=="number"?r.total:r.runs.length,domains:Array.isArray(r.domains)?r.domains.map(y=>({domain:typeof y.domain=="string"&&y.domain.trim()?y.domain:"uncategorized",total:typeof y.total=="number"?y.total:0,draftReady:typeof y.draftReady=="number"?y.draftReady:0,certificationReady:typeof y.certificationReady=="number"?y.certificationReady:0,blocked:typeof y.blocked=="number"?y.blocked:0,staleOpen:typeof y.staleOpen=="number"?y.staleOpen:0,expiredOpen:typeof y.expiredOpen=="number"?y.expiredOpen:0,nextAction:zo(y.nextAction),nextActionCount:typeof y.nextActionCount=="number"&&Number.isFinite(y.nextActionCount)?Math.max(0,Math.floor(y.nextActionCount)):void 0})):[],owners:Array.isArray(r.owners)?r.owners.map(y=>({owner:typeof y.owner=="string"&&y.owner.trim()?y.owner:"unassigned",total:typeof y.total=="number"?y.total:0,draftReady:typeof y.draftReady=="number"?y.draftReady:0,certificationReady:typeof y.certificationReady=="number"?y.certificationReady:0,blocked:typeof y.blocked=="number"?y.blocked:0,staleOpen:typeof y.staleOpen=="number"?y.staleOpen:0,expiredOpen:typeof y.expiredOpen=="number"?y.expiredOpen:0,nextAction:zo(y.nextAction),nextActionCount:typeof y.nextActionCount=="number"&&Number.isFinite(y.nextActionCount)?Math.max(0,Math.floor(y.nextActionCount)):void 0})):[],intents:Array.isArray(r.intents)?r.intents.map(y=>({intent:uw(y.intent),total:typeof y.total=="number"?y.total:0,draftReady:typeof y.draftReady=="number"?y.draftReady:0,certificationReady:typeof y.certificationReady=="number"?y.certificationReady:0,blocked:typeof y.blocked=="number"?y.blocked:0,staleOpen:typeof y.staleOpen=="number"?y.staleOpen:0,expiredOpen:typeof y.expiredOpen=="number"?y.expiredOpen:0,nextAction:zo(y.nextAction),nextActionCount:typeof y.nextActionCount=="number"&&Number.isFinite(y.nextActionCount)?Math.max(0,Math.floor(y.nextActionCount)):void 0})):[],notebooks:Array.isArray(r.notebooks)?r.notebooks.map(y=>({path:typeof y.path=="string"&&y.path.trim()?y.path:"notebooks/untitled.dqlnb",title:typeof y.title=="string"&&y.title.trim()?y.title:pw(y.path),total:typeof y.total=="number"?y.total:0,draftReady:typeof y.draftReady=="number"?y.draftReady:0,certificationReady:typeof y.certificationReady=="number"?y.certificationReady:0,blocked:typeof y.blocked=="number"?y.blocked:0,staleOpen:typeof y.staleOpen=="number"?y.staleOpen:0,expiredOpen:typeof y.expiredOpen=="number"?y.expiredOpen:0,nextAction:zo(y.nextAction),nextActionCount:typeof y.nextActionCount=="number"&&Number.isFinite(y.nextActionCount)?Math.max(0,Math.floor(y.nextActionCount)):void 0})):[],counts:{total:typeof((o=r.counts)==null?void 0:o.total)=="number"?r.counts.total:r.runs.length,ready:typeof((i=r.counts)==null?void 0:i.ready)=="number"?r.counts.ready:0,needsReview:typeof((c=r.counts)==null?void 0:c.needsReview)=="number"?r.counts.needsReview:0,dqlDrafts:typeof((a=r.counts)==null?void 0:a.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((f=r.counts)==null?void 0:f.extendExisting)=="number"?r.counts.extendExisting:0,replacements:typeof((d=r.counts)==null?void 0:d.replacements)=="number"?r.counts.replacements:0,createNew:typeof((h=r.counts)==null?void 0:h.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((b=r.counts)==null?void 0:b.blocked)=="number"?r.counts.blocked:0,staleOpen:typeof((x=r.counts)==null?void 0:x.staleOpen)=="number"?r.counts.staleOpen:0,expiredOpen:typeof((w=r.counts)==null?void 0:w.expiredOpen)=="number"?r.counts.expiredOpen:0,sourceLinked:typeof((C=r.counts)==null?void 0:C.sourceLinked)=="number"?r.counts.sourceLinked:0,nextActions:fw((k=r.counts)==null?void 0:k.nextActions)},groupCounts:{domains:typeof((v=r.groupCounts)==null?void 0:v.domains)=="number"&&Number.isFinite(r.groupCounts.domains)?Math.max(0,Math.floor(r.groupCounts.domains)):Array.isArray(r.domains)?r.domains.length:0,owners:typeof((j=r.groupCounts)==null?void 0:j.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((D=r.groupCounts)==null?void 0:D.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((T=r.groupCounts)==null?void 0:T.notebooks)=="number"&&Number.isFinite(r.groupCounts.notebooks)?Math.max(0,Math.floor(r.groupCounts.notebooks)):Array.isArray(r.notebooks)?r.notebooks.length:0},reviewMetrics:lw(r.reviewMetrics),limit:r.limit,offset:typeof r.offset=="number"?r.offset:0}},async getNotebookResearchDiagnostics(){const e=await E("/api/notebook/research/diagnostics");return dw(e)},async createNotebookResearch(e){const t=await E("/api/notebook/research",{method:"POST",body:JSON.stringify(e)});return Wt(t.run)},async seedNotebookResearchFromCells(e){const t=await E("/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 E("/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 E("/api/notebook/research/context-preview",{method:"POST",body:JSON.stringify(e)});return mw(t)},async getNotebookResearch(e){const t=await E(`/api/notebook/research/${encodeURIComponent(e)}`);return Wt(t.run)},async updateNotebookResearch(e,t){const n=await E(`/api/notebook/research/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)});return Wt(n.run)},async runNotebookResearch(e,t){const n=await E(`/api/notebook/research/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(t??{})});return Wt(n.run)},async checkNotebookResearchReuse(e,t){const n=await E(`/api/notebook/research/${encodeURIComponent(e)}/reuse-check`,{method:"POST",body:JSON.stringify(t??{})});return{...n,run:Wt(n.run),promotion:yp(n.promotion)??n.promotion}},async promoteNotebookResearchToDql(e,t){const n=await E(`/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(`${Wr}/api/schema`,{headers:Ur()});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 E("/api/connections")}catch{return{default:"unknown",connections:{}}}},async previewDbtProfiles(e){return E("/api/connections/dbt-profiles/preview",{method:"POST",body:JSON.stringify({path:e})})},async saveConnections(e,t){return E("/api/connections",{method:"PUT",body:JSON.stringify({connections:e,defaultConnectionName:t})})},async previewConnectionMetadataScope(e,t={}){return E(`/api/connections/${encodeURIComponent(e)}/metadata-scope/preview`,{method:"POST",body:JSON.stringify(t)})},async discoverConnectionMetadataScopes(e){return E(`/api/connections/${encodeURIComponent(e)}/metadata-scope/discovery`,{method:"POST"})},async getConnectionMetadataScope(e){return E(`/api/connections/${encodeURIComponent(e)}/metadata-scope`)},async applyConnectionMetadataScope(e,t){return E(`/api/connections/${encodeURIComponent(e)}/metadata-scope`,{method:"PUT",body:JSON.stringify(t)})},async refreshConnectionMetadata(e){return E(`/api/connections/${encodeURIComponent(e)}/metadata-sync`,{method:"POST"})},async installConnector(e){return E("/api/connectors/install",{method:"POST",body:JSON.stringify({driver:e})})},async testConnection(){try{return await E("/api/test-connection",{method:"POST",body:JSON.stringify({})})}catch(e){return{ok:!1,message:e.message??"Connection failed"}}},async getSemanticRuntimeSettings(){return E("/api/semantic-runtime")},async getMetricFlowInstallerStatus(){return E("/api/semantic-runtime/metricflow/installer")},async installMetricFlow(e){return E("/api/semantic-runtime/metricflow/install",{method:"POST",body:JSON.stringify(e?{adapter:e}:{})})},async testDbtCloudSemanticRuntime(e){try{return await E("/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 E("/api/semantic-runtime/dbt-cloud/apply",{method:"POST",body:JSON.stringify(e)})},async setSemanticRuntimePreference(e){return E("/api/semantic-runtime/preference",{method:"POST",body:JSON.stringify({preference:e})})},async getSemanticLayer(){try{return await E("/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 E("/api/semantic-layer/tree")).tree},async getSemanticObject(e){return E(`/api/semantic-layer/object/${encodeURIComponent(e)}`)},async getSetupLaunch(){return E("/api/onboarding/launch")},async acknowledgeSetupLaunch(){return E("/api/onboarding/acknowledge",{method:"POST",body:"{}"})},async getOnboardingStatus(){return E("/api/onboarding/status")},async previewDbtOnboarding(e){return E("/api/onboarding/dbt/preview",{method:"POST",body:JSON.stringify(e)})},async applyDbtOnboarding(e){return E("/api/onboarding/dbt/apply",{method:"POST",body:JSON.stringify({...e,fingerprint:e.expectedFingerprint})})},async refreshDbtOnboarding(e={}){return E("/api/onboarding/refresh",{method:"POST",body:JSON.stringify(e)})},async getOnboardingJob(e){return E(`/api/onboarding/jobs/${encodeURIComponent(e)}`)},async cancelOnboardingJob(e){return E(`/api/onboarding/jobs/${encodeURIComponent(e)}`,{method:"DELETE"})},async discoverOnboardingDomains(e={}){return E("/api/onboarding/domains/discover",{method:"POST",body:JSON.stringify(e)})},async applyOnboardingDomains(e){return E("/api/onboarding/domains/apply",{method:"POST",body:JSON.stringify(e)})},async importSemanticLayer(e){return E("/api/semantic-layer/import",{method:"POST",body:JSON.stringify(e)})},async syncSemanticLayer(){return E("/api/semantic-layer/sync",{method:"POST",body:JSON.stringify({})})},async previewSemanticImport(e){return E("/api/semantic-layer/import-preview",{method:"POST",body:JSON.stringify(e)})},async previewSyncDiff(){return E("/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 E(`/api/semantic-layer/search?${t.toString()}`)}catch{return{metrics:[],measures:[],dimensions:[],timeDimensions:[],entities:[],hierarchies:[],semanticModels:[],savedQueries:[]}}},async getFavorites(){try{return(await E("/api/user-prefs/favorites")).favorites}catch{return[]}},async toggleFavorite(e){return(await E("/api/user-prefs/favorites",{method:"POST",body:JSON.stringify({name:e})})).favorites},async getRecentlyUsed(){try{return(await E("/api/user-prefs/recent")).recentlyUsed}catch{return[]}},async trackUsage(e){try{return(await E("/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 E(`/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 E(`/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 E("/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 E("/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 E("/api/semantic-builder/save",{method:"POST",body:JSON.stringify(e)})},async createMetric(e){try{return await E("/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 E(`/api/describe-table?${t.toString()}`)}catch{return[]}},async fetchLineage(){try{return await E("/api/lineage")}catch{return{nodes:[],edges:[]}}},async searchLineage(e){try{return await E(`/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 E(`/api/lineage/query?${t.toString()}`)}catch{return{graph:{nodes:[],edges:[]},matches:[]}}},async fetchLineageNode(e){try{return await E(`/api/lineage/node/${encodeURIComponent(e)}`)}catch{return null}},async fetchBusiness360(e){try{return await E(`/api/lineage/business-360/${encodeURIComponent(e)}`)}catch{return null}},async fetchBlockLineage(e){try{return await E(`/api/lineage/block/${encodeURIComponent(e)}`)}catch{return null}},async fetchImpactAnalysis(e){try{return await E(`/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 E(o)}catch{return null}},async fetchGitStatus(){try{return await E("/api/git/status")}catch{return{inRepo:!1,branch:null,ahead:0,behind:0,changes:[]}}},async fetchGitLog(e=20){try{return await E(`/api/git/log?limit=${e}`)}catch{return{inRepo:!1,commits:[]}}},async fetchRunSnapshot(e){try{return await E(`/api/run-snapshot?path=${encodeURIComponent(e)}`)}catch{return{found:!1,snapshot:null}}},async saveRunSnapshot(e,t){await E("/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 E(`/api/git/diff${r?`?${r}`:""}`)}catch{return{inRepo:!1,diff:"",before:null,after:null,diffReport:null}}},async fetchGitBranches(){try{return await E("/api/git/branches")}catch{return{inRepo:!1,current:null,branches:[]}}},async fetchGitRemote(){try{return await E("/api/git/remote")}catch{return{inRepo:!1,url:null,name:null}}},async fetchGitGovernedContext(){try{return await E("/api/git/governed-context")}catch{return{inRepo:!1,trackingReady:!1,legacyBroadIgnore:!1,domains:Fo(),skills:Fo(),artifacts:Fo(),learning:Fo()}}},async enableGitGovernedContextTracking(){try{return await E("/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 E("/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 E("/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 E("/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 E("/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 E("/api/git/push",{method:"POST",body:"{}"})}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},async gitPull(){try{return await E("/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 E("/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 E("/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 E("/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 E("/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 E("/api/apps");return e}catch{return[]}},async listAppsStrict(){const{apps:e}=await E("/api/apps");return e},async recommendAppBlocks(e,t){try{const{blocks:n}=await E("/api/apps/recommend-blocks",{method:"POST",body:JSON.stringify(e),signal:t});return n}catch(n){if(t!=null&&t.aborted)throw n;return[]}},async createApp(e){return E("/api/apps",{method:"POST",body:JSON.stringify(e)})},async generateApp(e){try{return await E("/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 E("/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 E(`/api/apps/ai-builds/${encodeURIComponent(e)}`);return t}catch{return null}},async proposeAppAiBuild(e){try{return await E("/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 E("/api/apps/ai-builds/propose-background",{method:"POST",body:JSON.stringify(e)})},async commitAppAiBuild(e,t={}){try{return await E(`/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 E(`/api/apps/${encodeURIComponent(e)}`)}catch{return null}},async deleteApp(e){return E(`/api/apps/${encodeURIComponent(e)}`,{method:"DELETE"})},async attachAppNotebook(e,t){try{return await E(`/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 E(`/api/apps/${encodeURIComponent(e)}/notebook-candidates`);return t}catch{return[]}},async createAppNotebook(e,t){try{return await E(`/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 E(`/api/apps/${encodeURIComponent(e)}/notebooks/preview?path=${encodeURIComponent(t)}`)}catch{return null}},async runAppNotebook(e,t){try{return await E(`/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 E(`/api/apps/${encodeURIComponent(e)}/conversations`);return t}catch{return[]}},async createAppConversation(e,t){try{return await E(`/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 E(`/api/apps/${encodeURIComponent(e)}/conversations/${encodeURIComponent(t)}`);return n}catch{return null}},async updateAppConversation(e,t,n){try{return await E(`/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 E(`/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 E(`/api/apps/${encodeURIComponent(e)}/investigations${r?`?${r}`:""}`);return o}catch{return[]}},async createAppInvestigation(e,t){try{return await E(`/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 E(`/api/apps/${encodeURIComponent(e)}/investigations/${encodeURIComponent(t)}`);return n}catch{return null}},async runAppInvestigation(e,t,n){try{return await E(`/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 E(`/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 E(`/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 E(`/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 E(`/api/apps/${encodeURIComponent(e)}/editor/catalog${r?`?${r}`:""}`)}catch{return null}},async createAppDashboard(e,t){try{return await E(`/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 E(`/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 E(`/api/apps/${encodeURIComponent(e)}/ask`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async promoteApp(e,t){try{return await E(`/api/apps/${encodeURIComponent(e)}/promote`,{method:"POST",body:JSON.stringify(t??{})})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async approveAppSemanticTiles(e,t,n){try{return await E(`/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 E("/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 E(`/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 E(`/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 E(`/api/apps/${encodeURIComponent(e)}/ai-pins${r?`?${r}`:""}`);return o}catch{return[]}},async refreshAiPin(e,t){try{return await E(`/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 E(`/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 E(`/api/lineage/scope?${t.toString()}`)}catch{return null}},async runDashboard(e,t,n){try{return await E(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({variables:n??{}})})}catch{return null}},async retryDashboardTile(e,t,n,r){try{return await E(`/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 E(`/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 E(`/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 E("/api/persona");return e}catch{return null}},async setPersona(e,t){try{const{persona:n}=await E("/api/persona",{method:"POST",body:JSON.stringify({userId:e,appId:t})});return n}catch{return null}},async clearPersona(){try{await E("/api/persona",{method:"DELETE"})}catch{}},async getSkills(){return E("/api/skills")},async getSkillPathSettings(){return E("/api/skills/settings")},async updateSkillPath(e){return E("/api/skills/settings",{method:"PUT",body:JSON.stringify({path:e})})},async getSkillOptions(e=""){const t=e.trim()?`?q=${encodeURIComponent(e.trim())}`:"";return E(`/api/skills/options${t}`)},async createSkill(e){return E("/api/skills",{method:"POST",body:JSON.stringify({skill:e})})},async updateSkill(e,t){return E(`/api/skills/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({skill:t})})},async getEmbeddingSettings(){return E("/api/settings/embeddings")},async saveEmbeddingSettings(e){return E("/api/settings/embeddings",{method:"PUT",body:JSON.stringify(e)})},async listEmbeddingModels(e){const t=e?`?endpoint=${encodeURIComponent(e)}`:"";return E(`/api/settings/embeddings/models${t}`)},async installEmbeddingModel(e,t){return E("/api/settings/embeddings/install",{method:"POST",body:JSON.stringify({model:e,endpoint:t})})},async testEmbeddingProvider(){return E("/api/settings/embeddings/test",{method:"POST"})},async reindexEmbeddings(){return E("/api/settings/embeddings/reindex",{method:"POST"})},async deleteSkill(e){return E(`/api/skills/${encodeURIComponent(e)}`,{method:"DELETE"})},async getDomains(){try{return await E("/api/domains")}catch{return{domains:[]}}},async createDomain(e){return E("/api/domains",{method:"POST",body:JSON.stringify({domain:e})})},async updateDomain(e,t){return E(`/api/domains/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({domain:t})})},async deleteDomain(e){return E(`/api/domains/${encodeURIComponent(e)}`,{method:"DELETE"})},async startContextBootstrap(e={}){return E("/api/context-bootstrap",{method:"POST",body:JSON.stringify(e)})},async getContextBootstrap(e){return E(`/api/context-bootstrap/${encodeURIComponent(e)}`)},async getLatestContextBootstrap(){return(await E("/api/context-bootstrap/latest")).session??null},async saveContextBootstrapSelected(e,t){return E(`/api/context-bootstrap/${encodeURIComponent(e)}/save-selected`,{method:"POST",body:JSON.stringify({candidateIds:t})})}},yw={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"},bw={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"},bp={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"},uj={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"},pj={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"},xw={source:"#79c0ff",transform:"#ff7b72",answer:"#56d364",consumption:"#d2a8ff"},Hc={source:"Sources",transform:"Transform",answer:"Answer",consumption:"Consumption"},Gc=["source","transform","answer","consumption"],fj=["term","business_view","block","metric","dimension","domain","source_table","dbt_source","dbt_model","chart","notebook","dashboard","app"],hj=["source_table","dbt_source","dbt_model"],vw=["term","domain","business_view","metric","dimension","block"];[...vw];function Sw(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 ww(){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:Gi.semibold},children:n?kw(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:vn.sm},children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"auto",padding:be[4]},children:n?s.jsx(Cw,{context:n}):s.jsx(Rw,{})})]})}function kw(e){switch(e.kind){case"cell":return"Cell";case"lineage-node":return"Lineage node";case"metric":return"Metric"}}function Cw({context:e}){return e.kind==="cell"?s.jsx(jw,{cellId:e.cellId}):e.kind==="lineage-node"?s.jsx(Ew,{nodeId:e.nodeId}):s.jsx(Tw,{name:e.name})}function jw({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(De,{label:"Type",children:n.type}),s.jsx(De,{label:"ID",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:n.id})}),s.jsxs(De,{label:"Length",children:[n.content.length," chars"]}),n.status&&s.jsx(De,{label:"Status",children:n.status})]}):s.jsx(ls,{children:"No matching cell in the active notebook."})}function Ew({nodeId:e}){const[t,n]=p.useState(null),[r,o]=p.useState(!0);if(p.useEffect(()=>{let a=!1;return o(!0),B.fetchLineageNode(e).then(l=>{a||(n(l),o(!1))}).catch(()=>{a||o(!1)}),()=>{a=!0}},[e]),r)return s.jsx(ls,{children:"Loading node…"});if(!t||!t.node)return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3]},children:[s.jsx(De,{label:"Node ID",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:e})}),s.jsx(ls,{children:"No metadata available for this node."})]});const i=t.node,c=i.metadata??{};return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3]},children:[s.jsx(De,{label:"Name",children:i.name??e}),s.jsx(De,{label:"Type",children:bp[i.type]??i.type}),i.domain&&s.jsx(De,{label:"Domain",children:i.domain}),i.owner&&s.jsx(De,{label:"Owner",children:i.owner}),i.status&&s.jsx(De,{label:"Status",children:i.status}),typeof c.termType=="string"&&s.jsx(De,{label:"Term Type",children:c.termType}),typeof c.description=="string"&&s.jsx(De,{label:"Description",children:c.description}),Array.isArray(c.identifiers)&&c.identifiers.length>0&&s.jsx(De,{label:"Identifiers",children:c.identifiers.map(String).join(", ")}),Array.isArray(c.synonyms)&&c.synonyms.length>0&&s.jsx(De,{label:"Synonyms",children:c.synonyms.map(String).join(", ")}),typeof c.businessOutcome=="string"&&s.jsx(De,{label:"Business Outcome",children:c.businessOutcome}),i.layer&&s.jsx(De,{label:"Layer",children:i.layer}),s.jsx(De,{label:"Upstream",children:t.incoming.length}),s.jsx(De,{label:"Downstream",children:t.outgoing.length}),(i.path||c.filePath)&&s.jsx(De,{label:"Path",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)",fontSize:Ze.xs},children:i.path??c.filePath})})]})}function Tw({name:e}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3]},children:[s.jsx(De,{label:"Metric",children:e}),s.jsx(ls,{children:"Definition, dimensions, and governance surface will render here."})]})}function De({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:Gi.medium},children:e}),s.jsx("div",{style:{fontSize:Ze.sm,color:pe("textPrimary")},children:t})]})}function ls({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:vn.md,padding:be[3]},children:e})}function Rw(){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 Kr={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"},Qc={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 Jc(e){if(typeof document>"u")return Qc[e];const t=Kr[e];return getComputedStyle(document.documentElement).getPropertyValue(t).trim()||Qc[e]}function Aw(){return new Proxy({},{get(e,t){if(typeof t=="string"&&t in Kr)return Jc(t)},has(e,t){return typeof t=="string"&&t in Kr},ownKeys(){return Object.keys(Kr)},getOwnPropertyDescriptor(e,t){if(!(typeof t!="string"||!(t in Kr)))return{enumerable:!0,configurable:!0,value:Jc(t)}}})}const Rn=Aw(),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 _w=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 Ow=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"})]})),mj=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 gj=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 xp=44,vp=188,Sp="dql-activitybar-expanded";function Pw(){var e;if(typeof window>"u")return!1;try{return((e=window.localStorage)==null?void 0:e.getItem(Sp))==="1"}catch{return!1}}function Dw(e){var t;try{(t=window.localStorage)==null||t.setItem(Sp,e?"1":"0")}catch{}}function Yc({title:e,icon:t,active:n,expanded:r,onClick:o,t:i}){const[c,a]=p.useState(!1),l=s.jsxs("button",{"aria-label":e,onClick:o,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{width:r?vp-12:xp-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":c?i.textPrimary+"0f":"transparent",border:"none",borderRadius:6,cursor:"pointer",color:n?i.accent:c?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(Wd,{content:e,side:"right",children:l})}function Iw(){const e=Ge(Pr(l=>({mainView:l.mainView,sidebarOpen:l.sidebarOpen,sidebarPanel:l.sidebarPanel,themeMode:l.themeMode}))),t=kn(),n=Qe[e.themeMode],[r,o]=p.useState(Pw);p.useEffect(()=>{Dw(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 c=[{label:"Insights",items:[{key:"apps",title:"Apps",icon:s.jsx(lS,{size:16,strokeWidth:1.75}),active:e.mainView==="apps"},{key:"ask",title:"Ask",icon:s.jsx(tS,{size:16,strokeWidth:1.75}),active:e.mainView==="ask"}]},{label:"Build",items:[{key:"files",title:"Notebooks",icon:s.jsx(Ra,{size:16,strokeWidth:1.75}),active:e.sidebarPanel==="files"&&e.sidebarOpen},{key:"block_library",title:"Blocks",icon:s.jsx(_w,{size:16}),active:e.sidebarPanel==="block_library"&&e.sidebarOpen},{key:"lineage",title:"Lineage",icon:s.jsx(Ow,{size:16}),active:e.mainView==="lineage"||e.mainView==="lineage_detail"}]},{label:"Govern",items:[{key:"domains",title:"Domains",icon:s.jsx($i,{size:16,strokeWidth:1.75}),active:e.mainView==="domains"||e.mainView==="modeling"||e.mainView==="skills"},{key:"git",title:"Source control",icon:s.jsx(Dr,{size:16,strokeWidth:1.75}),active:e.mainView==="git"},{key:"settings",title:"Settings",icon:s.jsx(kS,{size:16,strokeWidth:1.75}),active:e.mainView==="settings"||e.mainView==="connection"}]}],a=[{key:"help",title:"Help",icon:s.jsx(gv,{size:16,strokeWidth:1.75}),active:e.mainView==="help",onClick:()=>t({type:"SET_MAIN_VIEW",view:"help"})}];return s.jsxs("div",{style:{width:r?vp:xp,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(Wd,{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(lv,{size:14,strokeWidth:2}):s.jsx(uv,{size:14,strokeWidth:2})})})}),c.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(f=>s.jsx(Yc,{title:f.title,icon:f.icon,active:f.active,expanded:r,onClick:()=>i(f.key),t:n},f.key))]},l.label)),s.jsx("div",{style:{flex:1}}),a.map(l=>s.jsx(Yc,{title:l.title,icon:l.icon,active:l.active,expanded:r,onClick:l.onClick,t:n},l.key))]})}const Mw=2e4,yj="application/dql-semantic-ref",Xc=new Map;let so=null;function $w(e){B.trackUsage(e),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:e}}))}async function Zc(e,t){const n=`${e}:${t.toLowerCase()}`,r=Xc.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 c=await i.json(),a=Array.isArray(c.completions)?c.completions:[];return Xc.set(n,{items:a,expiresAt:Date.now()+Mw}),a}function wp(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 bj(e){so=e}function xj(e){so===e&&(so=null)}function Lw(e){return so?(wp(so,e),!0):!1}function vj(e,t,n){const r=n?e.posAtCoords(n)??e.state.selection.main.from:e.state.selection.main.from;wp(e,t,r)}function el(e,t,n){return{label:e.name,detail:e.type==="metric"?"@metric":"@dim",type:e.type==="metric"?"function":"variable",info:`${e.label}${e.description?`
396
+ ${e.description}`:""}${e.sql?`
397
+ ${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}}),$w(e.name)}}}function Nw(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 Sj=async e=>{const{state:t,pos:n}=e,r=t.sliceDoc(Math.max(0,n-120),n),o=/@metric\(([^)]*)$/i.exec(r);if(o){const a=o[1].trim().toLowerCase(),l=n-o[1].length,u=await Zc("metric",a);return{from:l,options:u.map(f=>el(f,l,n)),validFor:/^[\w-]*$/}}const i=/@dim\(([^)]*)$/i.exec(r);if(i){const a=i[1].trim().toLowerCase(),l=n-i[1].length,u=await Zc("dimension",a);return{from:l,options:u.map(f=>el(f,l,n)),validFor:/^[\w-]*$/}}const c=/@([md][a-z_]*)?$/i.exec(r);return c?Nw(n-c[0].length):(e.explicit,null)};function wj(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 Bw=6,Fw=999,zw={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 Ae(e,t={}){const{variant:n="secondary",size:r="sm",active:o=!1,disabled:i=!1,pill:c=!1}=t,a=zw[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:a.gap,height:a.height,padding:`0 ${a.paddingX}px`,borderRadius:c?Fw:Bw,fontSize:a.fontSize,fontWeight:n==="primary"?700:600,fontFamily:e.font,lineHeight:1,whiteSpace:"nowrap",cursor:i?"not-allowed":"pointer",opacity:i?.55:1,transition:"background 0.15s, border-color 0.15s, color 0.15s"};return n==="primary"?{...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 qw=new Set(["metric","measure","dimension","time_dimension"]);function _s(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 Fi(e){const t=_s(e);return e.kind==="metric"||e.kind==="measure"?`@metric(${t})`:`@dim(${t})`}function kp(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():"")||_s(e)}function Aa(e,t){return!t||e.label.toLowerCase().includes(t)||e.id.toLowerCase().includes(t)||_s(e).toLowerCase().includes(t)||kp(e).toLowerCase().includes(t)?!0:(e.children??[]).some(n=>Aa(n,t))}function Cp(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,c=i?`group:${o.label.toLowerCase()}`:`leaf:${Fi(o).toLowerCase()}`,a=n.get(c);if(a){i&&a.children&&(a.children=a.children.concat(o.children??[]));continue}const l=o.children?{...o,children:[...o.children]}:o;n.set(c,l),t.push(l)}for(const o of t)o.children&&(o.children=Cp(o.children));return t}const Hs={metric:{Icon:Wv,tone:e=>e.accent},measure:{Icon:AS,tone:e=>e.accent},dimension:{Icon:IS,tone:e=>e.success},time_dimension:{Icon:bv,tone:e=>e.warning},entity:{Icon:ev,tone:e=>e.textSecondary},segment:{Icon:qv,tone:e=>e.textMuted},hierarchy:{Icon:Dr,tone:e=>e.textMuted},pre_aggregation:{Icon:fp,tone:e=>e.textMuted},cube:{Icon:$i,tone:e=>e.textSecondary},semantic_model:{Icon:$i,tone:e=>e.textSecondary},saved_query:{Icon:Xx,tone:e=>e.textMuted},provider:{Icon:Yr,tone:e=>e.textMuted},domain:{Icon:Yr,tone:e=>e.textMuted},group:{Icon:Yr,tone:e=>e.textMuted}};function Uw(e){var t;if(e.kind==="group"){const n=typeof((t=e.meta)==null?void 0:t.objectKind)=="string"?e.meta.objectKind:"";return Hs[n]??Hs.group}return Hs[e.kind]}function Ww({tree:e,themeMode:t,search:n="",onInsert:r,selectionMode:o=!1,selected:i=new Set,onToggleSelection:c,canSelect:a=()=>({allowed:!0})}){const l=Qe[t],u=n.trim().toLowerCase(),f=Cp(e.children??[]).filter(d=>Aa(d,u));return f.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:f.map(d=>s.jsx(jp,{node:d,t:l,q:u,onInsert:r,depth:0,selectionMode:o,selected:i,onToggleSelection:c,canSelect:a},d.id))})}function jp({node:e,t,q:n,onInsert:r,depth:o,selectionMode:i,selected:c,onToggleSelection:a,canSelect:l}){var T;const u=(((T=e.children)==null?void 0:T.length)??0)>0,[f,d]=p.useState(o<1||!!n);p.useEffect(()=>{n&&d(!0)},[n]);const h=qw.has(e.kind),m=Uw(e),S=m==null?void 0:m.Icon,b=10+o*13,x=e.kind==="metric"||e.kind==="measure"?"metric":e.kind==="dimension"||e.kind==="time_dimension"?"dimension":null,w=_s(e),C=kp(e),k=w!==C?` · DQL ${w}`:"",v=x?`${x}:${w}`:"",j=x?l(x,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&&x&&j.allowed?a==null||a(x,w):!i&&h&&r(Fi(e))},disabled:i&&!!x&&!j.allowed,title:i&&x?j.allowed?`Select ${e.label} · dbt ${C}${k}`:j.reason||"Not compatible with the current selection":h?`Insert ${Fi(e)} · dbt ${C}${k}`:e.label,style:{display:"flex",alignItems:"center",gap:7,flex:1,minWidth:0,boxSizing:"border-box",padding:`5px 6px 5px ${b+15}px`,border:"none",background:"transparent",cursor:i&&x?j.allowed?"pointer":"not-allowed":h?"pointer":"default",textAlign:"left",fontFamily:t.font,color:j.allowed||!x?t.textPrimary:t.textMuted,opacity:i&&x&&!j.allowed?.55:1},children:[i&&x&&s.jsx("input",{type:"checkbox",readOnly:!0,checked:c.has(v),disabled:!j.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}),C!==e.label?s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:9.5,fontFamily:t.fontMono,color:t.textMuted},children:C}):null]})]})});const D=(e.children??[]).filter(y=>Aa(y,n));return s.jsxs("div",{children:[s.jsxs("button",{type:"button",onClick:()=>d(y=>!y),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minWidth:0,boxSizing:"border-box",padding:`6px 10px 6px ${b}px`,border:"none",borderBottom:`1px solid ${t.cellBorder}`,background:"transparent",cursor:"pointer",textAlign:"left",fontFamily:t.font,color:t.textPrimary},children:[f?s.jsx(Ta,{size:13,color:t.textMuted,style:{flexShrink:0}}):s.jsx(As,{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??D.length})]}),f&&D.map(y=>s.jsx(jp,{node:y,t,q:n,onInsert:r,depth:o+1,selectionMode:i,selected:c,onToggleSelection:a,canSelect:l},y.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 c=Ft(r.parent);for(;c&&!i.has(c);){i.add(c);const a=t.get(c);if(!a)break;o.unshift(Ft(a.name)||a.id),c=Ft(a.parent)}return o.join(" / ")};return[...t.values()].map(r=>({value:r.id,label:n(r)})).sort((r,o)=>r.label.localeCompare(o.label))}function kj(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 wo(e){return new Set(Qn(e).map(t=>t.value))}function Cj(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 Kw(e,t){const n=wo(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 Vw(e,t,n="",r=[]){const o=n.trim().toLowerCase(),i=wo(r);return Array.from(new Map(e.map(c=>[c.path,c])).values()).filter(c=>{var l;const a=((l=c.domain)==null?void 0:l.trim())??"";return t==="uncategorized"&&i.has(a)||t&&t!=="uncategorized"&&(!i.has(t)||a!==t)?!1:!o||c.name.toLowerCase().includes(o)||(c.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 ir;(function(e){e.Error="error",e.Warning="warning",e.Info="info"})(ir||(ir={}));class Hw{constructor(){Pe(this,"diagnostics",[])}report(t){this.diagnostics.push(t)}error(t,n,r){this.report({severity:ir.Error,message:t,span:n,hint:r})}warning(t,n,r){this.report({severity:ir.Warning,message:t,span:n,hint:r})}hasErrors(){return this.diagnostics.some(t=>t.severity===ir.Error)}getErrors(){return this.diagnostics.filter(t=>t.severity===ir.Error)}getAll(){return[...this.diagnostics]}clear(){this.diagnostics=[]}format(t){return this.diagnostics.map(n=>Gw(n,t)).join(`
398
+
399
+ `)}}function Gw(e,t){const{severity:n,message:r,span:o,hint:i}=e,a=t.split(`
400
+ `)[o.start.line-1]??"",l=String(o.start.line),u=" ".repeat(l.length),f=o.start.file?`${o.start.file}:`:"";let d=`${n}: ${r}
401
+ `;d+=` --> ${f}${o.start.line}:${o.start.column}
402
+ `,d+=`${u} |
403
+ `,d+=`${l} | ${a}
404
+ `;const h=o.start.column-1,m=Math.max(1,o.start.line===o.end.line?o.end.column-o.start.column:a.length-h);return d+=`${u} | ${" ".repeat(h)}${"^".repeat(m)}`,i&&(d+=`
405
+ ${u} = hint: ${i}`),d}class Qw extends Error{constructor(n,r){super(n);Pe(this,"diagnostics");this.diagnostics=r,this.name="DQLSyntaxError"}}var g;(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"})(g||(g={}));const Jw={dashboard:g.DashboardKeyword,workbook:g.WorkbookKeyword,page:g.PageKeyword,let:g.LetKeyword,param:g.ParamKeyword,chart:g.ChartKeyword,filter:g.FilterKeyword,true:g.BooleanLiteral,false:g.BooleanLiteral,INTERVAL:g.IntervalKeyword,import:g.ImportKeyword,from:g.FromKeyword,use:g.UseKeyword,layout:g.LayoutKeyword,row:g.RowKeyword,block:g.BlockKeyword,term:g.TermKeyword,terms:g.TermsKeyword,business_view:g.BusinessViewKeyword,includes:g.IncludesKeyword,domain:g.DomainKeyword,type:g.TypeKeyword,description:g.DescriptionKeyword,tags:g.TagsKeyword,owner:g.OwnerKeyword,query:g.QueryKeyword,visualization:g.VisualizationKeyword,tests:g.TestsKeyword,params:g.ParamsKeyword,assert:g.AssertKeyword,var:g.VarKeyword,default:g.DefaultKeyword,IN:g.InKeyword,metric:g.MetricKeyword,metrics:g.MetricsKeyword,dimensions:g.DimensionsKeyword,digest:g.DigestKeyword,narrative:g.NarrativeKeyword};function Yw(e){return Jw[e]??g.Identifier}const Gs=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"]),Xw={"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 Zw(e){return Xw[e]??e}const Qs=new Set(["dropdown","date_range","text","multi_select","range"]),e0=new Set(["SELECT","WITH"]);class ds{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!==g.Comment&&t.push(n)}return t.push(this.makeToken(g.EOF,"",this.location())),t}nextToken(){if(this.skipWhitespace(),this.isAtEnd())return this.makeToken(g.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(g.GreaterThanOrEqual,">=",t)):n==="<"&&this.peekNext()==="="?(this.advance(),this.advance(),this.makeToken(g.LessThanOrEqual,"<=",t)):n==="="&&this.peekNext()==="="?(this.advance(),this.advance(),this.makeToken(g.DoubleEquals,"==",t)):n==="!"&&this.peekNext()==="="?(this.advance(),this.advance(),this.makeToken(g.NotEquals,"!=",t)):this.readPunctuation(t)}static scanSQLBoundary(t,n,r){let o=n,i=r;const c=t.length;for(;o<c;){const l=t[o];if(l==="'"||l==='"'){o=ds.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<c&&/\s/.test(t[u]);)u++;if(u<c&&/[a-zA-Z_]/.test(t[u])){let f=u;for(;f<c&&/[a-zA-Z0-9_]/.test(t[f]);)f++;let d=f;for(;d<c&&/\s/.test(t[d]);)d++;if(d<c&&t[d]==="="&&(d+1>=c||t[d+1]!=="="))return{sql:t.substring(n,o).trim(),endOffset:o}}}o++}return{sql:t.substring(n,o).trim(),endOffset:o}}static skipStringInSQL(t,n){const r=t[n];for(n++;n<t.length;){if(t[n]==="\\"){n+=2;continue}if(t[n]===r)return n++,n;n++}return n}readComment(t){let n="";for(;!this.isAtEnd()&&this.peek()!==`
406
+ `;)n+=this.advance();return this.makeToken(g.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+=`
407
+ `;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(g.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(g.NumberLiteral,n,t)}readIdentifierOrKeyword(t){let n="";for(;!this.isAtEnd()&&(this.isAlphaNumeric(this.peek())||this.peek()==="_");)n+=this.advance();const r=Yw(n);return this.makeToken(r,n,t)}readPunctuation(t){const n=this.advance();switch(n){case"(":return this.makeToken(g.LeftParen,n,t);case")":return this.makeToken(g.RightParen,n,t);case"{":return this.makeToken(g.LeftBrace,n,t);case"}":return this.makeToken(g.RightBrace,n,t);case"[":return this.makeToken(g.LeftBracket,n,t);case"]":return this.makeToken(g.RightBracket,n,t);case",":return this.makeToken(g.Comma,n,t);case".":return this.makeToken(g.Dot,n,t);case"=":return this.makeToken(g.Equals,n,t);case"+":return this.makeToken(g.Plus,n,t);case"-":return this.makeToken(g.Minus,n,t);case"*":return this.makeToken(g.Star,n,t);case"@":return this.makeToken(g.AtSign,n,t);case":":return this.makeToken(g.ColonToken,n,t);case">":return this.makeToken(g.GreaterThan,n,t);case"<":return this.makeToken(g.LessThan,n,t);default:return this.makeToken(g.Identifier,n,t)}}skipWhitespace(){for(;!this.isAtEnd();){const t=this.peek();if(t===" "||t===" "||t==="\r"||t===`
408
+ `)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===`
409
+ `?(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()===`
410
+ `&&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(g.TripleQuoteString,n,t);n+=this.advance()}return this.makeToken(g.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 t0=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"]),n0=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 r0(e){return t0.has(e)}function o0(e){return n0.has(e)}class s0{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 Hw;const r=new ds(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 Qw(`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(g.WorkbookKeyword)?this.parseWorkbook(t):this.check(g.DashboardKeyword)?this.parseDashboard(t):this.check(g.DigestKeyword)?this.parseDigest(t):this.check(g.ChartKeyword)?this.parseChartCall(t):this.check(g.BlockKeyword)?this.parseBlockDecl(t):this.check(g.DomainKeyword)?this.parseDomainDecl(t):this.check(g.TermKeyword)?this.parseTermDecl(t):this.check(g.BusinessViewKeyword)?this.parseBusinessViewDecl(t):this.check(g.ImportKeyword)?(t.length>0&&this.error("Decorators cannot be applied to import statements."),this.parseImportDecl()):(this.check(g.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(g.FilterKeyword),this.expect(g.Dot);const n=this.expect(g.Identifier);Qs.has(n.value)||this.reporter.error(`Unknown filter type '${n.value}'. Valid types: ${[...Qs].join(", ")}`,n.span,`Did you mean one of: ${[...Qs].join(", ")}?`),this.expect(g.LeftParen);let r;const i=this.current().value.toUpperCase();(i==="SELECT"||i==="WITH")&&(r=this.parseSQLQuery());const c=[];for(;(this.check(g.Comma)||!r&&(this.check(g.Identifier)||this.isKeywordUsableAsArgName(this.current().type)))&&(this.check(g.Comma)&&this.advance(),!this.check(g.RightParen));)c.push(this.parseNamedArg());return this.expect(g.RightParen),{kind:Q.FilterCall,filterType:n.value,query:r,args:c,span:this.makeSpan(t,this.previousSpan())}}parseDashboard(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(g.DashboardKeyword);const r=this.expect(g.StringLiteral);this.expect(g.LeftBrace);const o=[];for(;!this.check(g.RightBrace)&&!this.isAtEnd();){const i=this.parseDecoratorList();if(this.check(g.LetKeyword))i.length>0&&this.error("Decorators cannot be applied to variable declarations."),o.push(this.parseVariableDecl());else if(this.check(g.ParamKeyword))i.length>0&&this.error("Decorators cannot be applied to param declarations."),o.push(this.parseParamDecl());else if(this.check(g.ChartKeyword))o.push(this.parseChartCall(i));else if(this.check(g.FilterKeyword))i.length>0&&this.error("Decorators cannot be applied to filter declarations."),o.push(this.parseFilterCall());else if(this.check(g.UseKeyword))i.length>0&&this.error("Decorators cannot be applied to use declarations."),o.push(this.parseUseDecl());else if(this.check(g.LayoutKeyword))i.length>0&&this.error("Decorators cannot be applied to layout blocks."),o.push(this.parseLayoutBlock());else{if(this.check(g.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside dashboard. Expected 'let', 'param', 'chart', 'filter', 'use', 'layout', or '}'.`),this.advance()}}return this.expect(g.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(g.DigestKeyword);const r=this.expect(g.StringLiteral);this.expect(g.LeftBrace);const o=[];let i;for(;!this.check(g.RightBrace)&&!this.isAtEnd();){const c=this.parseDecoratorList();if(this.check(g.NarrativeKeyword))c.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(g.LetKeyword))c.length>0&&this.error("Decorators cannot be applied to variable declarations."),o.push(this.parseVariableDecl());else if(this.check(g.ParamKeyword))c.length>0&&this.error("Decorators cannot be applied to param declarations."),o.push(this.parseParamDecl());else if(this.check(g.ChartKeyword))o.push(this.parseChartCall(c));else if(this.check(g.FilterKeyword))c.length>0&&this.error("Decorators cannot be applied to filter declarations."),o.push(this.parseFilterCall());else if(this.check(g.UseKeyword))c.length>0&&this.error("Decorators cannot be applied to use declarations."),o.push(this.parseUseDecl());else if(this.check(g.LayoutKeyword))c.length>0&&this.error("Decorators cannot be applied to layout blocks."),o.push(this.parseLayoutBlock());else{if(this.check(g.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(g.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(g.NarrativeKeyword),this.expect(g.LeftBrace);const n=[];for(;!this.check(g.RightBrace)&&!this.isAtEnd();)n.push(this.parseNamedArg());return this.expect(g.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(g.ChartKeyword),this.expect(g.Dot);const r=this.currentSpan();let i=this.expect(g.Identifier).value;for(;this.check(g.Minus);)this.advance(),i+=`-${this.expect(g.Identifier).value}`;const c=this.makeSpan(r,this.previousSpan());Gs.has(i)||this.reporter.error(`Unknown chart type '${i}'. Valid types: ${[...Gs].join(", ")}`,c,`Did you mean one of: ${[...Gs].join(", ")}?`);const a=Zw(i);this.expect(g.LeftParen);const l=this.parseSQLQuery(),u=[];for(;this.check(g.Comma)&&(this.advance(),!this.check(g.RightParen));)u.push(this.parseNamedArg());return this.expect(g.RightParen),{kind:Q.ChartCall,chartType:a,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}=ds.scanSQLBoundary(this.source,r,1),c=this.extractInterpolations(o,t);for(;!this.isAtEnd()&&this.current().span.start.offset<i;)this.advance();const a=this.makeSpan(t,this.currentSpan());return{kind:Q.SQLQuery,rawSQL:o,interpolations:c,span:a}}extractInterpolations(t,n){const r=[],o=/\$\{(\w+)\}|\{(\w+)\}/g;let i;for(;(i=o.exec(t))!==null;){const c=i[1]||i[2];c&&r.push({variableName:c,offsetInSQL:i.index,span:n})}return r}parseNamedArg(){const t=this.currentSpan(),n=this.current();n.type===g.Identifier||this.isKeywordUsableAsArgName(n.type)?this.advance():(this.error(`Expected argument name, got '${n.value}'.`),this.advance()),this.expect(g.Equals);const r=this.parseExpression();return{kind:Q.NamedArg,name:n.value,value:r,span:this.makeSpan(t,this.previousSpan())}}isKeywordUsableAsArgName(t){return t===g.ParamKeyword||t===g.FromKeyword||t===g.LayoutKeyword||t===g.RowKeyword||t===g.UseKeyword||t===g.ImportKeyword||t===g.MetricKeyword||t===g.MetricsKeyword||t===g.TermsKeyword||t===g.IncludesKeyword}parseVariableDecl(){const t=this.currentSpan();this.expect(g.LetKeyword);const n=this.expect(g.Identifier);this.expect(g.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(g.AtSign);)t.push(this.parseDecorator());return t}parseDecorator(){const t=this.currentSpan();this.expect(g.AtSign);const n=this.expect(g.Identifier),r=[];if(this.check(g.LeftParen)){if(this.advance(),!this.check(g.RightParen))for(r.push(this.parseExpression());this.check(g.Comma);)this.advance(),r.push(this.parseExpression());this.expect(g.RightParen)}return{kind:Q.Decorator,name:n.value,arguments:r,span:this.makeSpan(t,this.previousSpan())}}parseExpression(){let t=this.parsePrimary();for(;this.check(g.Plus)||this.check(g.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(g.StringLiteral))return this.advance(),{kind:Q.StringLiteral,value:t.value,span:t.span};if(this.check(g.NumberLiteral))return this.advance(),{kind:Q.NumberLiteral,value:Number(t.value),span:t.span};if(this.check(g.BooleanLiteral))return this.advance(),{kind:Q.BooleanLiteral,value:t.value==="true",span:t.span};if(this.check(g.LeftBracket))return this.parseArrayLiteral();if(this.check(g.IntervalKeyword)){const n=this.currentSpan();this.advance();const r=this.expect(g.StringLiteral);return{kind:Q.IntervalExpr,value:r.value,span:this.makeSpan(n,this.previousSpan())}}if(this.check(g.Identifier)){this.advance();const n=t.value;return this.check(g.LeftParen)?this.parseFunctionCall(n,t.span):{kind:Q.Identifier,name:n,span:t.span}}if(this.check(g.Minus)){const n=this.currentSpan();this.advance();const r=this.expect(g.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(g.LeftBracket);const n=[];if(!this.check(g.RightBracket))for(n.push(this.parseExpression());this.check(g.Comma)&&(this.advance(),!this.check(g.RightBracket));)n.push(this.parseExpression());return this.expect(g.RightBracket),{kind:Q.ArrayLiteral,elements:n,span:this.makeSpan(t,this.previousSpan())}}parseFunctionCall(t,n){this.expect(g.LeftParen);const r=[];if(!this.check(g.RightParen))for(r.push(this.parseExpression());this.check(g.Comma);)this.advance(),r.push(this.parseExpression());return this.expect(g.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(g.LeftBrace))return;let t=0;for(;!this.isAtEnd();){if(this.check(g.LeftBrace)){t+=1,this.advance();continue}if(this.check(g.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(g.StringLiteral)||this.check(g.TripleQuoteString)?this.advance():this.expect(g.StringLiteral)}isAtEnd(){return this.current().type===g.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(g.DomainKeyword);const r=this.expect(g.StringLiteral);this.expect(g.LeftBrace);let o,i,c,a,l,u,f,d,h,m,S,b,x,w,C,k,v,j,D;for(;!this.check(g.RightBrace)&&!this.isAtEnd();)if(this.check(g.OwnerKeyword))this.advance(),this.expect(g.Equals),i=this.expect(g.StringLiteral).value;else if(this.check(g.DescriptionKeyword))this.advance(),this.expect(g.Equals),S=this.expectStringLike().value;else if(this.check(g.TagsKeyword))this.advance(),this.expect(g.Equals),h=this.parseStringArrayValues();else if(this.check(g.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 T=this.advance();this.expect(g.Equals),T.value==="id"?o=this.expect(g.StringLiteral).value:T.value==="parent"?c=this.expect(g.StringLiteral).value:T.value==="businessOwner"?a=this.expect(g.StringLiteral).value:T.value==="boundedContext"?l=this.expectStringLike().value:T.value==="sourceSystems"?u=this.parseStringArrayValues():T.value==="primaryTerms"?f=this.parseStringArrayValues():T.value==="reviewCadence"?d=this.expect(g.StringLiteral).value:T.value==="businessOutcome"?m=this.expect(g.StringLiteral).value:T.value==="inScope"?b=this.parseStringArrayValues():T.value==="outOfScope"?x=this.parseStringArrayValues():T.value==="dbtGroups"?w=this.parseStringArrayValues():T.value==="dbtPaths"?C=this.parseStringArrayValues():T.value==="dbtTags"?k=this.parseStringArrayValues():T.value==="semanticDomains"?v=this.parseStringArrayValues():T.value==="semanticTags"?j=this.parseStringArrayValues():T.value==="exports"&&(D=this.parseStringArrayValues())}else{if(this.check(g.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(g.RightBrace),{kind:Q.DomainDecl,name:r.value,id:o,parent:c,owner:i,businessOwner:a,boundedContext:l,sourceSystems:u,primaryTerms:f,reviewCadence:d,tags:h,businessOutcome:m,description:S,inScope:b,outOfScope:x,dbtGroups:w,dbtPaths:C,dbtTags:k,semanticDomains:v,semanticTags:j,exports:D,decorators:t,span:this.makeSpan(n,this.previousSpan())}}parseTermDecl(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(g.TermKeyword);const r=this.expect(g.StringLiteral);this.expect(g.LeftBrace);let o,i,c,a,l,u,f,d,h,m,S,b,x,w,C;for(;!this.check(g.RightBrace)&&!this.isAtEnd();)if(this.check(g.DomainKeyword))this.advance(),this.expect(g.Equals),o=this.expect(g.StringLiteral).value;else if(this.check(g.TypeKeyword))this.advance(),this.expect(g.Equals),i=this.expect(g.StringLiteral).value;else if(this.check(g.DescriptionKeyword))this.advance(),this.expect(g.Equals),a=this.expectStringLike().value;else if(this.check(g.TagsKeyword))this.advance(),this.expect(g.Equals),l=this.parseStringArrayValues();else if(this.check(g.OwnerKeyword))this.advance(),this.expect(g.Equals),u=this.expect(g.StringLiteral).value;else if(this.check(g.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 k=this.advance();this.expect(g.Equals),k.value==="status"?c=this.expect(g.StringLiteral).value:k.value==="identifiers"?f=this.parseStringArrayValues():k.value==="synonyms"?d=this.parseStringArrayValues():k.value==="metricRefs"?h=this.parseStringArrayValues():k.value==="businessOutcome"?m=this.expect(g.StringLiteral).value:k.value==="businessOwner"?S=this.expect(g.StringLiteral).value:k.value==="decisionUse"?b=this.expect(g.StringLiteral).value:k.value==="reviewCadence"?x=this.expect(g.StringLiteral).value:k.value==="businessRules"?w=this.parseStringArrayValues():k.value==="caveats"&&(C=this.parseStringArrayValues())}else{if(this.check(g.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(g.RightBrace),{kind:Q.TermDecl,name:r.value,domain:o,termType:i,status:c,description:a,tags:l,owner:u,identifiers:f,synonyms:d,metricRefs:h,businessOutcome:m,businessOwner:S,decisionUse:b,reviewCadence:x,businessRules:w,caveats:C,decorators:t,span:this.makeSpan(n,this.previousSpan())}}parseBusinessViewDecl(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(g.BusinessViewKeyword);const r=this.expect(g.StringLiteral);this.expect(g.LeftBrace);let o,i,c,a,l,u,f,d,h,m,S,b,x=[];for(;!this.check(g.RightBrace)&&!this.isAtEnd();)if(this.check(g.DomainKeyword))this.advance(),this.expect(g.Equals),o=this.expect(g.StringLiteral).value;else if(this.check(g.DescriptionKeyword))this.advance(),this.expect(g.Equals),c=this.expectStringLike().value;else if(this.check(g.TagsKeyword))this.advance(),this.expect(g.Equals),a=this.parseStringArrayValues();else if(this.check(g.OwnerKeyword))this.advance(),this.expect(g.Equals),l=this.expect(g.StringLiteral).value;else if(this.check(g.TermsKeyword))this.advance(),this.expect(g.Equals),u=this.parseStringArrayValues();else if(this.check(g.IncludesKeyword))x=this.parseBusinessViewIncludes();else if(this.check(g.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(g.Equals),w.value==="status"?i=this.expect(g.StringLiteral).value:w.value==="businessOutcome"?f=this.expect(g.StringLiteral).value:w.value==="businessOwner"?d=this.expect(g.StringLiteral).value:w.value==="decisionUse"?h=this.expect(g.StringLiteral).value:w.value==="reviewCadence"?m=this.expect(g.StringLiteral).value:w.value==="businessRules"?S=this.parseStringArrayValues():w.value==="caveats"&&(b=this.parseStringArrayValues())}else{if(this.check(g.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(g.RightBrace),{kind:Q.BusinessViewDecl,name:r.value,domain:o,status:i,description:c,tags:a,owner:l,termRefs:u,businessOutcome:f,businessOwner:d,decisionUse:h,reviewCadence:m,businessRules:S,caveats:b,includes:x,decorators:t,span:this.makeSpan(n,this.previousSpan())}}parseBusinessViewIncludes(){this.expect(g.IncludesKeyword),this.expect(g.LeftBrace);const t=[];for(;!this.check(g.RightBrace)&&!this.isAtEnd();){const n=this.currentSpan();if(this.check(g.BlockKeyword)){this.advance();const r=this.expect(g.StringLiteral);t.push({kind:Q.BusinessViewInclude,refType:"block",name:r.value,span:this.makeSpan(n,this.previousSpan())})}else if(this.check(g.BusinessViewKeyword)){this.advance();const r=this.expect(g.StringLiteral);t.push({kind:Q.BusinessViewInclude,refType:"business_view",name:r.value,span:this.makeSpan(n,this.previousSpan())})}else{if(this.check(g.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside includes. Expected 'block', 'business_view', or '}'.`),this.advance()}}return this.expect(g.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(g.BlockKeyword);const r=this.expect(g.StringLiteral);this.expect(g.LeftBrace);let o,i,c,a,l,u,f,d,h,m,S,b,x,w,C,k,v,j,D,T,y,O,A,_,P,$,q,G,J,H,L,M,X,W,te,F,K,oe,ee,ce,ke,xe,Ie,We,Be,Ee,ge,Je,tt,Fe,Ke,gt,It,Ct,jt,Zt,en,jn,En,U,se,je,ve,me;for(;!this.check(g.RightBrace)&&!this.isAtEnd();)if(this.check(g.DomainKeyword))this.advance(),this.expect(g.Equals),o=this.expect(g.StringLiteral).value;else if(this.check(g.TypeKeyword)){this.advance(),this.expect(g.Equals);const Y=this.expect(g.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(g.MetricKeyword))this.advance(),this.expect(g.Equals),c=this.expect(g.StringLiteral).value;else if(this.check(g.MetricsKeyword)){this.advance(),this.expect(g.Equals);const ie=this.parseArrayLiteral();ie.kind===Q.ArrayLiteral&&(a=ie.elements.filter(Y=>Y.kind===Q.StringLiteral).map(Y=>Y.value))}else if(this.check(g.DimensionsKeyword)){this.advance(),this.expect(g.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(g.DescriptionKeyword))this.advance(),this.expect(g.Equals),u=this.expectStringLike().value;else if(this.check(g.TagsKeyword)){this.advance(),this.expect(g.Equals);const ie=this.parseArrayLiteral();ie.kind===Q.ArrayLiteral&&(f=ie.elements.filter(Y=>Y.kind===Q.StringLiteral).map(Y=>Y.value))}else if(this.check(g.OwnerKeyword))this.advance(),this.expect(g.Equals),d=this.expect(g.StringLiteral).value;else if(this.check(g.TermsKeyword))this.advance(),this.expect(g.Equals),h=this.parseStringArrayValues();else if(this.check(g.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(g.Equals),ie.value==="pattern"?m=this.expect(g.StringLiteral).value:ie.value==="grain"?S=this.expect(g.StringLiteral).value:ie.value==="entities"?b=this.parseStringArrayValues():ie.value==="outputs"?x=this.parseStringArrayValues():ie.value==="allowedFilters"?w=this.parseStringArrayValues():ie.value==="sourceSystems"?v=this.parseStringArrayValues():ie.value==="replacementFor"&&(j=this.parseStringArrayValues())}else if(this.check(g.ParamsKeyword))D=this.parseBlockParams();else if(this.check(g.Identifier)&&this.current().value==="parameterPolicy")C=this.parseBlockParameterPolicy();else if(this.check(g.Identifier)&&this.current().value==="filterBindings")k=this.parseBlockFilterBindings();else if(this.check(g.QueryKeyword))if(this.advance(),this.check(g.LeftBrace))T=this.parseLegacyBlockQuerySection();else if(this.expect(g.Equals),this.check(g.TripleQuoteString)){const ie=this.advance(),Y=this.extractInterpolations(ie.value,ie.span);T={kind:Q.SQLQuery,rawSQL:ie.value,interpolations:Y,span:ie.span}}else T=this.parseSQLQuery();else if(this.check(g.VisualizationKeyword))y=this.parseBlockVisualization();else if(this.check(g.TestsKeyword))O=this.parseBlockTests();else{if(this.check(g.RightBrace))break;if(this.check(g.Identifier)&&this.current().value==="status")this.advance(),this.expect(g.Equals),M=this.expect(g.StringLiteral).value;else if(this.check(g.Identifier)&&this.current().value==="datalex_contract")this.advance(),this.expect(g.Equals),X=this.expect(g.StringLiteral).value;else if(this.check(g.Identifier)&&(this.current().value==="asked_times"||this.current().value==="limit"||this.current().value==="source_dql_limit")){const ie=this.advance();this.expect(g.Equals);const Y=this.expect(g.NumberLiteral);ie.value==="asked_times"?W=Number(Y.value):ie.value==="limit"?jn=Number(Y.value):ve=Number(Y.value)}else if(this.check(g.Identifier)&&r0(this.current().value)){const ie=this.advance();this.expect(g.Equals);const Y=this.expect(g.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":Ie=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":It=Y.value;break}}else if(this.check(g.Identifier)&&o0(this.current().value)){const ie=this.advance();this.expect(g.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":En=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(g.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(g.Equals),ie.value==="llmContext")A=this.expect(g.StringLiteral).value;else if(ie.value==="invariants"){const Y=this.parseArrayLiteral();Y.kind===Q.ArrayLiteral&&(_=Y.elements.filter(Me=>Me.kind===Q.StringLiteral).map(Me=>Me.value))}else if(ie.value==="examples"){this.expect(g.LeftBracket);const Y=[];for(;!this.check(g.RightBracket)&&!this.isAtEnd();){this.expect(g.LeftBrace);let Me,Jn;for(;!this.check(g.RightBrace)&&!this.isAtEnd();){const Yn=this.current();if(Yn.type!==g.Identifier){this.error(`Expected 'question' or 'sql' in example entry, got '${Yn.value}'.`),this.advance();continue}this.advance(),this.expect(g.Equals);const ko=this.expect(g.StringLiteral);Yn.value==="question"?Me=ko.value:Yn.value==="sql"&&(Jn=ko.value),this.check(g.Comma)&&this.advance()}this.expect(g.RightBrace),Me&&Y.push(Jn?{question:Me,sql:Jn}:{question:Me}),this.check(g.Comma)&&this.advance()}this.expect(g.RightBracket),Y.length>0&&(P=Y)}else if(ie.value==="businessOutcome")$=this.expect(g.StringLiteral).value;else if(ie.value==="businessOwner")q=this.expect(g.StringLiteral).value;else if(ie.value==="decisionUse")G=this.expect(g.StringLiteral).value;else if(ie.value==="reviewCadence")J=this.expect(g.StringLiteral).value;else if(ie.value==="businessRules"){const Y=this.parseArrayLiteral();Y.kind===Q.ArrayLiteral&&(H=Y.elements.filter(Me=>Me.kind===Q.StringLiteral).map(Me=>Me.value))}else if(ie.value==="caveats"){const Y=this.parseArrayLiteral();Y.kind===Q.ArrayLiteral&&(L=Y.elements.filter(Me=>Me.kind===Q.StringLiteral).map(Me=>Me.value))}}else{if(this.check(g.Identifier)&&((tn=this.tokens[this.pos+1])==null?void 0:tn.type)===g.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(g.RightBrace),{kind:Q.BlockDecl,name:r.value,domain:o,blockType:i,metricRef:c,metricsRef:a,dimensionsRef:i==="semantic"?l:void 0,description:u,tags:f,owner:d,termRefs:h,pattern:m,grain:S,entities:b,outputs:x,dimensions:i==="semantic"?void 0:l,allowedFilters:w,parameterPolicy:C,filterBindings:k,sourceSystems:v,replacementFor:j,params:D,query:T,visualization:y,tests:O,decorators:t,llmContext:A,invariants:_,examples:P,businessOutcome:$,businessOwner:q,decisionUse:G,reviewCadence:J,businessRules:H,caveats:L,status:M,datalexContract:X,askedTimes:W,firstAsked:te,lastAsked:F,proposedContractId:K,proposedDomain:oe,proposedEntity:ee,sourceQuestion:ce,sourceBlock:ke,sourceDqlKind:xe,sourceDqlName:Ie,sourceDqlPath:We,sourceDqlHash:Be,sourceDqlTimeDimension:Ee,sourceDqlGranularity:ge,followupKind:Je,contextPackId:tt,routeIntent:Fe,timeDimension:Ke,granularity:gt,draftPath:It,upstreamRefs:Ct,requestedFilters:jt,requestedDimensions:Zt,orderBy:en,limit:jn,sourceDqlMetrics:En,sourceDqlDimensions:U,sourceDqlFilters:se,sourceDqlOrderBy:je,sourceDqlLimit:ve,validationWarnings:me,span:this.makeSpan(n,this.previousSpan())}}parseLegacyBlockQuerySection(){const t=this.currentSpan();this.expect(g.LeftBrace);let n;for(;!this.check(g.RightBrace)&&!this.isAtEnd();)if(this.check(g.Identifier)&&this.current().value==="sql")if(this.advance(),this.expect(g.Equals),this.check(g.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(g.Identifier)&&e0.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(g.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(g.ParamsKeyword),this.expect(g.LeftBrace);const n=[];for(;!this.check(g.RightBrace)&&!this.isAtEnd();){const o=this.currentSpan(),i=this.current();if(i.type===g.Identifier||this.isBlockFieldKeyword(i.type))this.advance();else{this.error(`Expected parameter name, got '${i.value}'.`),this.advance();continue}let c;if(this.check(g.ColonToken)){this.advance();let u=this.expect(g.Identifier).value;this.check(g.LeftBracket)&&((r=this.tokens[this.pos+1])==null?void 0:r.type)===g.RightBracket&&(this.advance(),this.advance(),u+="[]");const f=["string","number","boolean","date","string[]","number[]","date[]"];f.includes(u)?c=u:this.error(`Invalid block parameter type '${u}'. Valid types: ${f.join(", ")}`)}let a;this.check(g.Equals)&&(this.advance(),a=this.parseExpression()),n.push({name:i.value,paramType:c,initializer:a,span:this.makeSpan(o,this.previousSpan())})}return this.expect(g.RightBrace),{kind:Q.BlockParams,params:n,span:this.makeSpan(t,this.previousSpan())}}parseBlockParameterPolicy(){const t=[];for(this.expect(g.Identifier),this.expect(g.LeftBrace);!this.check(g.RightBrace)&&!this.isAtEnd();){const n=this.currentSpan(),r=this.current();if(r.type===g.Identifier||this.isBlockFieldKeyword(r.type))this.advance();else{this.error(`Expected parameter name inside parameterPolicy, got '${r.value}'.`),this.advance();continue}this.expect(g.Equals);const o=this.expectStringLike();t.push({name:r.value,policy:o.value,span:this.makeSpan(n,this.previousSpan())})}return this.expect(g.RightBrace),t}parseBlockFilterBindings(){const t=[];for(this.expect(g.Identifier),this.expect(g.LeftBrace);!this.check(g.RightBrace)&&!this.isAtEnd();){const n=this.currentSpan(),r=this.current();if(r.type===g.Identifier||this.isBlockFieldKeyword(r.type))this.advance();else{this.error(`Expected business filter name inside filterBindings, got '${r.value}'.`),this.advance();continue}this.expect(g.Equals);const o=this.expectStringLike();t.push({filter:r.value,binding:o.value,span:this.makeSpan(n,this.previousSpan())})}return this.expect(g.RightBrace),t}parseBlockVisualization(){const t=this.currentSpan();this.expect(g.VisualizationKeyword),this.expect(g.LeftBrace);const n=[];for(;!this.check(g.RightBrace)&&!this.isAtEnd();){const r=this.currentSpan(),o=this.current();if(o.type===g.Identifier||this.isBlockFieldKeyword(o.type))this.advance();else{this.error(`Expected property name, got '${o.value}'.`),this.advance();continue}this.expect(g.Equals);const i=this.parseExpression();n.push({kind:Q.NamedArg,name:o.value,value:i,span:this.makeSpan(r,this.previousSpan())})}return this.expect(g.RightBrace),{kind:Q.BlockVisualization,properties:n,span:this.makeSpan(t,this.previousSpan())}}parseBlockTests(){this.currentSpan(),this.expect(g.TestsKeyword),this.expect(g.LeftBrace);const t=[];for(;!this.check(g.RightBrace)&&!this.isAtEnd();)if(this.check(g.AssertKeyword)){const n=this.currentSpan();this.advance();const r=this.current();if(r.type===g.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(g.GreaterThan))this.advance(),o=">";else if(this.check(g.LessThan))this.advance(),o="<";else if(this.check(g.GreaterThanOrEqual))this.advance(),o=">=";else if(this.check(g.LessThanOrEqual))this.advance(),o="<=";else if(this.check(g.DoubleEquals))this.advance(),o="==";else if(this.check(g.NotEquals))this.advance(),o="!=";else if(this.check(g.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(g.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside tests. Expected 'assert' or '}'.`),this.advance()}return this.expect(g.RightBrace),t}isBlockFieldKeyword(t){return t===g.DomainKeyword||t===g.TypeKeyword||t===g.MetricKeyword||t===g.DescriptionKeyword||t===g.TagsKeyword||t===g.OwnerKeyword||t===g.TermsKeyword||t===g.ChartKeyword||t===g.QueryKeyword||t===g.DefaultKeyword||t===g.FromKeyword}parseWorkbook(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(g.WorkbookKeyword);const r=this.expect(g.StringLiteral);this.expect(g.LeftBrace);const o=[];for(;!this.check(g.RightBrace)&&!this.isAtEnd();)if(this.check(g.PageKeyword))o.push(this.parsePage());else{if(this.check(g.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside workbook. Expected 'page' or '}'.`),this.advance()}return this.expect(g.RightBrace),{kind:Q.Workbook,title:r.value,decorators:t,pages:o,span:this.makeSpan(n,this.previousSpan())}}parsePage(){const t=this.currentSpan();this.expect(g.PageKeyword);const n=this.expect(g.StringLiteral);this.expect(g.LeftBrace);const r=[];for(;!this.check(g.RightBrace)&&!this.isAtEnd();){const o=this.parseDecoratorList();if(this.check(g.LetKeyword))o.length>0&&this.error("Decorators cannot be applied to variable declarations."),r.push(this.parseVariableDecl());else if(this.check(g.ParamKeyword))o.length>0&&this.error("Decorators cannot be applied to param declarations."),r.push(this.parseParamDecl());else if(this.check(g.ChartKeyword))r.push(this.parseChartCall(o));else if(this.check(g.FilterKeyword))o.length>0&&this.error("Decorators cannot be applied to filter declarations."),r.push(this.parseFilterCall());else if(this.check(g.UseKeyword))o.length>0&&this.error("Decorators cannot be applied to use declarations."),r.push(this.parseUseDecl());else if(this.check(g.LayoutKeyword))o.length>0&&this.error("Decorators cannot be applied to layout blocks."),r.push(this.parseLayoutBlock());else{if(this.check(g.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside page. Expected 'let', 'param', 'chart', 'filter', 'use', 'layout', or '}'.`),this.advance()}}return this.expect(g.RightBrace),{kind:Q.Page,title:n.value,body:r,span:this.makeSpan(t,this.previousSpan())}}parseParamDecl(){const t=this.currentSpan();this.expect(g.ParamKeyword);const n=this.expect(g.Identifier);let r="string";if(this.check(g.ColonToken)){this.advance();const i=this.expect(g.Identifier),c=["string","number","boolean","date"];c.includes(i.value)?r=i.value:this.reporter.error(`Invalid param type '${i.value}'. Valid types: ${c.join(", ")}`,i.span)}let o;return this.check(g.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(g.ImportKeyword),this.expect(g.LeftBrace);const n=[];if(!this.check(g.RightBrace))for(n.push(this.expect(g.Identifier).value);this.check(g.Comma)&&(this.advance(),!this.check(g.RightBrace));)n.push(this.expect(g.Identifier).value);this.expect(g.RightBrace),this.expect(g.FromKeyword);const r=this.expect(g.StringLiteral);return{kind:Q.ImportDecl,names:n,path:r.value,span:this.makeSpan(t,this.previousSpan())}}parseUseDecl(){const t=this.currentSpan();this.expect(g.UseKeyword);let n;return this.check(g.Identifier)||this.check(g.StringLiteral)?n=this.advance():n=this.expect(g.Identifier),{kind:Q.UseDecl,name:n.value,span:this.makeSpan(t,this.previousSpan())}}parseLayoutBlock(){const t=this.currentSpan();this.expect(g.LayoutKeyword);let n=12;if(this.check(g.LeftParen)){this.advance();const o=[];if(!this.check(g.RightParen))for(o.push(this.parseNamedArg());this.check(g.Comma)&&(this.advance(),!this.check(g.RightParen));)o.push(this.parseNamedArg());this.expect(g.RightParen);const i=o.find(c=>c.name==="columns");i&&i.value.kind===Q.NumberLiteral&&(n=i.value.value)}this.expect(g.LeftBrace);const r=[];for(;!this.check(g.RightBrace)&&!this.isAtEnd();)if(this.check(g.RowKeyword))r.push(this.parseLayoutRow());else{if(this.check(g.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside layout. Expected 'row' or '}'.`),this.advance()}return this.expect(g.RightBrace),{kind:Q.LayoutBlock,columns:n,rows:r,span:this.makeSpan(t,this.previousSpan())}}parseLayoutRow(){const t=this.currentSpan();this.expect(g.RowKeyword),this.expect(g.LeftBrace);const n=[];for(;!this.check(g.RightBrace)&&!this.isAtEnd();){const r=this.parseDecoratorList();let o;if(this.check(g.ChartKeyword))o=this.parseChartCall(r);else if(this.check(g.FilterKeyword))r.length>0&&this.error("Decorators cannot be applied to filter declarations."),o=this.parseFilterCall();else{if(this.check(g.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside row. Expected 'chart', 'filter', or '}'.`),this.advance();continue}let i;if(this.check(g.Identifier)&&this.current().value==="span"){this.advance();const c=this.expect(g.NumberLiteral);i=Number(c.value)}n.push({node:o,span:i})}return this.expect(g.RightBrace),{kind:Q.LayoutRow,items:n,span:this.makeSpan(t,this.previousSpan())}}synchronize(){for(;!this.isAtEnd();){const t=this.current();if(t.type===g.DashboardKeyword||t.type===g.WorkbookKeyword||t.type===g.ChartKeyword||t.type===g.FilterKeyword||t.type===g.ImportKeyword||t.type===g.BlockKeyword||t.type===g.TermKeyword||t.type===g.BusinessViewKeyword||t.type===g.AtSign||t.type===g.RightBrace)return;this.advance()}}}function i0(e,t){return new s0(e,t).parse()}function a0(e,t={}){const n=i0(e);return c0(n,t)}function c0(e,t={}){const n={indentUnit:t.indent??" "},r=e.statements.map(o=>l0(o,0,n)).join(`
411
+
412
+ `).trimEnd();return t.finalNewline===!1?r:`${r}
413
+ `}function N(e,t){return t.indentUnit.repeat(e)}function l0(e,t,n){switch(e.kind){case Q.Dashboard:return d0(e,t,n);case Q.ChartCall:return Oa(e,t,n);case Q.Workbook:return f0(e,t,n);case Q.ImportDecl:return m0(e,t,n);case Q.DomainDecl:return w0(e,t,n);case Q.BlockDecl:return S0(e,t,n);case Q.TermDecl:return k0(e,t,n);case Q.BusinessViewDecl:return C0(e,t,n);case Q.Digest:return u0(e,t,n);default:return""}}function d0(e,t,n){const r=[];r.push(...Cn(e.decorators,t,n)),r.push(`${N(t,n)}dashboard ${V(e.title)} {`);for(const o of e.body)r.push(_a(o,t+1,n));return r.push(`${N(t,n)}}`),r.join(`
414
+ `)}function u0(e,t,n){const r=[];r.push(...Cn(e.decorators,t,n)),r.push(`${N(t,n)}digest ${V(e.title)} {`),e.narrative&&r.push(p0(e.narrative,t+1,n));for(const o of e.body)r.push(_a(o,t+1,n));return r.push(`${N(t,n)}}`),r.join(`
415
+ `)}function p0(e,t,n){const r=[];r.push(`${N(t,n)}narrative {`);for(const o of e.properties)r.push(`${N(t+1,n)}${Pa(o)}`);return r.push(`${N(t,n)}}`),r.join(`
416
+ `)}function f0(e,t,n){const r=[];r.push(...Cn(e.decorators,t,n)),r.push(`${N(t,n)}workbook ${V(e.title)} {`);for(const o of e.pages)r.push(h0(o,t+1,n));return r.push(`${N(t,n)}}`),r.join(`
417
+ `)}function h0(e,t,n){const r=[];r.push(`${N(t,n)}page ${V(e.title)} {`);for(const o of e.body)r.push(_a(o,t+1,n));return r.push(`${N(t,n)}}`),r.join(`
418
+ `)}function _a(e,t,n){switch(e.kind){case Q.VariableDecl:return y0(e,t,n);case Q.ParamDecl:return b0(e,t,n);case Q.ChartCall:return Oa(e,t,n);case Q.FilterCall:return Ep(e,t,n);case Q.UseDecl:return g0(e,t,n);case Q.LayoutBlock:return x0(e,t,n);default:return""}}function m0(e,t,n){return`${N(t,n)}import { ${e.names.join(", ")} } from ${V(e.path)}`}function g0(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 y0(e,t,n){return`${N(t,n)}let ${e.name} = ${_t(e.initializer)}`}function b0(e,t,n){const r=`: ${e.paramType}`,o=e.defaultValue?` = ${_t(e.defaultValue)}`:"";return`${N(t,n)}param ${e.name}${r}${o}`}function Cn(e,t,n){return e.map(r=>{if(r.arguments.length===0)return`${N(t,n)}@${r.name}`;const o=r.arguments.map(i=>_t(i)).join(", ");return`${N(t,n)}@${r.name}(${o})`})}function Oa(e,t,n){return Tp(`chart.${e.chartType}`,e.decorators,e.query,e.args,t,n)}function Ep(e,t,n){return Tp(`filter.${e.filterType}`,[],e.query,e.args,t,n)}function Tp(e,t,n,r,o,i){const c=[];c.push(...Cn(t,o,i)),c.push(`${N(o,i)}${e}(`);const a=[];n&&a.push(Rp(n,o+1,i));for(const l of r)a.push([`${N(o+1,i)}${Pa(l)}`]);for(let l=0;l<a.length;l++){const u=l===a.length-1,f=a[l];for(let d=0;d<f.length;d++){const h=d===f.length-1;c.push(h&&!u?`${f[d]},`:f[d])}}return c.push(`${N(o,i)})`),c.join(`
419
+ `)}function x0(e,t,n){const r=[];r.push(`${N(t,n)}layout(columns = ${e.columns}) {`);for(const o of e.rows)r.push(v0(o,t+1,n));return r.push(`${N(t,n)}}`),r.join(`
420
+ `)}function v0(e,t,n){const r=[];r.push(`${N(t,n)}row {`);for(const o of e.items){const i=o.node.kind===Q.ChartCall?Oa(o.node,t+1,n):Ep(o.node,t+1,n);if(o.span==null){r.push(i);continue}const c=i.split(`
421
+ `);c[c.length-1]=`${c[c.length-1]} span ${o.span}`,r.push(c.join(`
422
+ `))}return r.push(`${N(t,n)}}`),r.join(`
423
+ `)}function S0(e,t,n){const r=[];if(r.push(...Cn(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 = [${j0(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}`:"",c=o.initializer?` = ${_t(o.initializer)}`:"";r.push(`${N(t+2,n)}${o.name}${i}${c}`)}r.push(`${N(t+1,n)}}`)}if(e.query&&(r.push(`${N(t+1,n)}query = """`),r.push(...Rp(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)}${Pa(o)}`);r.push(`${N(t+1,n)}}`)}if(e.tests&&e.tests.length>0){r.push(`${N(t+1,n)}tests {`);for(const o of e.tests)r.push(`${N(t+2,n)}assert ${o.field} ${o.operator} ${_t(o.expected)}`);r.push(`${N(t+1,n)}}`)}return r.push(`${N(t,n)}}`),r.join(`
424
+ `)}function w0(e,t,n){var o,i,c,a,l,u,f,d;const r=[];return r.push(...Cn(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(", ")}]`),(c=e.dbtGroups)!=null&&c.length&&r.push(`${N(t+1,n)}dbtGroups = [${e.dbtGroups.map(V).join(", ")}]`),(a=e.dbtPaths)!=null&&a.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(", ")}]`),(f=e.semanticTags)!=null&&f.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(`
425
+ `)}function k0(e,t,n){const r=[];return r.push(...Cn(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(`
426
+ `)}function C0(e,t,n){const r=[];r.push(...Cn(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(`
427
+ `)}function Rp(e,t,n){const r=e.rawSQL.replace(/^\n+|\s+$/g,"");if(!r.trim())return[`${N(t,n)}SELECT 1`];const o=r.split(`
428
+ `).map(l=>l.trimEnd()),i=o.slice(1).filter(l=>l.length>0),c=i.length?i:o.filter(l=>l.length>0),a=c.length?Math.min(...c.map(l=>l.match(/^[ \t]*/)[0].length)):0;return o.map(l=>{if(l.length===0)return"";const u=l.startsWith(" ".repeat(a))||l.startsWith(" ".repeat(a))?l.slice(a):l.trimStart();return`${N(t,n)}${u}`})}function Pa(e){return`${e.name} = ${_t(e.value)}`}function j0(e){return e.map(t=>{const n=[`question = ${V(t.question)}`];return t.sql&&n.push(`sql = ${V(t.sql)}`),`{ ${n.join(", ")} }`}).join(", ")}function _t(e){switch(e.kind){case Q.StringLiteral:return V(e.value);case Q.NumberLiteral:return String(e.value);case Q.BooleanLiteral:return e.value?"true":"false";case Q.Identifier:return e.name;case Q.ArrayLiteral:return`[${e.elements.map(t=>_t(t)).join(", ")}]`;case Q.BinaryExpr:return`${_t(e.left)} ${e.operator} ${_t(e.right)}`;case Q.IntervalExpr:return`INTERVAL ${V(e.value)}`;case Q.FunctionCall:return`${e.callee}(${e.arguments.map(t=>_t(t)).join(", ")})`;case Q.TemplateString:return V(e.parts.map(t=>typeof t=="string"?t:`{${_t(t)}}`).join(""));default:return""}}function V(e){return JSON.stringify(e)}function E0(e){var u,f,d,h,m,S,b,x;const t=$r(e.metrics),n=$r(e.dimensions??[]),r=$r(e.requestedFilters??[]),o=$r((e.orderBy??[]).map(w=>typeof w=="string"?w:`${w.name} ${w.direction}`)),i=R0(e.parameters??[]),c=[`block ${ze(e.name)} {`,' type = "semantic"',` status = ${ze(((u=e.status)==null?void 0:u.trim())||"draft")}`],a=T0(e.domain);a&&c.push(` domain = ${ze(a)}`),(f=e.description)!=null&&f.trim()&&c.push(` description = ${ze(e.description.trim())}`);const l=$r(e.tags??[]);if(l.length>0&&c.push(` tags = [${l.map(ze).join(", ")}]`),(d=e.owner)!=null&&d.trim()&&c.push(` owner = ${ze(e.owner.trim())}`),c.push(` metrics = [${t.map(ze).join(", ")}]`),c.push(` dimensions = [${n.map(ze).join(", ")}]`),(h=e.timeDimension)!=null&&h.name.trim()&&(c.push(` time_dimension = ${ze(e.timeDimension.name.trim())}`),e.timeDimension.granularity.trim()&&c.push(` granularity = ${ze(e.timeDimension.granularity.trim())}`)),r.length>0&&c.push(` requested_filters = [${r.map(ze).join(", ")}]`),o.length>0&&c.push(` order_by = [${o.map(ze).join(", ")}]`),A0(e.limit)&&c.push(` limit = ${Math.floor(e.limit)}`),i.length>0){c.push(" params {");for(const k of i){const v=(m=k.type)!=null&&m.trim()?`: ${k.type.trim()}`:"",j=k.default!==void 0?` = ${Ap(k.default)}`:"";c.push(` ${k.name}${v}${j}`)}c.push(" }");const w=i.filter(k=>{var v;return(v=k.policy)==null?void 0:v.trim()});if(w.length>0){c.push(" parameterPolicy {");for(const k of w)c.push(` ${k.name} = ${ze(k.policy.trim())}`);c.push(" }")}const C=i.filter(k=>{var v;return(v=k.binding)==null?void 0:v.trim()});if(C.length>0){c.push(" filterBindings {");for(const k of C)c.push(` ${k.name} = ${ze(k.binding.trim())}`);c.push(" }")}}return(S=e.visualization)!=null&&S.chart.trim()&&(c.push(" visualization {"),c.push(` chart = ${ze(e.visualization.chart.trim())}`),(b=e.visualization.x)!=null&&b.trim()&&c.push(` x = ${tl(e.visualization.x.trim())}`),(x=e.visualization.y)!=null&&x.trim()&&c.push(` y = ${tl(e.visualization.y.trim())}`),c.push(" }")),c.push("}"),a0(`${c.join(`
429
+ `)}
430
+ `)}function T0(e){const t=e==null?void 0:e.trim();if(!(!t||t==="uncategorized"||t==="_uncategorized"))return t}function $r(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))]}function R0(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 A0(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function Ap(e){return Array.isArray(e)?`[${e.map(Ap).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 tl(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)?e:ze(e)}function _0(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 E0({name:i,status:"draft",metrics:n,dimensions:r}).trimEnd()}function O0(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 P0(e,t){var o;const n={path:"",folders:new Map,blocks:[]};for(const i of e){const c=((o=i.domain)==null?void 0:o.trim())||"uncategorized",l=O0(i.path,t||c).split("/").filter(Boolean),u=t?l.slice(0,-1):[c,...l.slice(0,-1)];let f=n;for(const d of u){const h=[f.path,d].filter(Boolean).join("/");let m=f.folders.get(d);m||(m={name:d,path:h,folders:new Map,blocks:[]},f.folders.set(d,m)),f=m}f.blocks.push(i)}const r=i=>[...Array.from(i.folders.values()).sort((c,a)=>c.name.localeCompare(a.name)).map(c=>({kind:"folder",name:c.name,path:c.path,children:r(c)})),...i.blocks.sort((c,a)=>c.name.localeCompare(a.name)).map(c=>({kind:"block",block:c}))];return r(n)}function D0(e,t){const n={path:"",folders:new Map,files:[]};for(const o of e){const i=I0(o,t);let c=n;for(const a of i){const l=[c.path,a].filter(Boolean).join("/");let u=c.folders.get(a);u||(u={name:a,path:l,folders:new Map,files:[]},c.folders.set(a,u)),c=u}c.files.push(o)}const r=o=>[...Array.from(o.folders.values()).sort((i,c)=>i.name.localeCompare(c.name)).map(i=>({kind:"folder",name:i.name,path:i.path,children:r(i)})),...o.files.sort((i,c)=>i.name.localeCompare(c.name)).map(i=>({kind:"file",file:i}))];return r(n)}function I0(e,t){const n=e.path.replace(/\\/g,"/").split("/").filter(Boolean);if(n[0]==="domains"){const i=["notebooks","workbooks"],c=n.findIndex((a,l)=>l>0&&i.includes(a));if(c>0)return["Domains",...n.slice(1,c),...n.slice(c+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(c=>c.trim()).filter(Boolean),...o]:["Project",...o]}function _p({id:e,ariaLabel:t,value:n,options:r,onChange:o,summary:i,t:c}){return s.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${c.headerBorder}`,display:"grid",gap:5},children:[s.jsx("label",{htmlFor:e,style:{color:c.textMuted,fontSize:9,fontWeight:750,letterSpacing:".06em",textTransform:"uppercase"},children:"Domain"}),s.jsxs("select",{id:e,"aria-label":t,value:n,onChange:a=>o(a.target.value),style:{width:"100%",background:c.inputBg,border:`1px solid ${c.inputBorder}`,borderRadius:6,color:c.textPrimary,fontFamily:c.font,fontSize:12,padding:"7px 8px"},children:[s.jsx("option",{value:"",children:"All domains"}),r.map(a=>{const l=typeof a=="string"?{value:a,label:a}:a;return s.jsx("option",{value:l.value,children:l.label??l.value},l.value)})]}),i!==void 0?s.jsx("span",{style:{color:c.textMuted,fontSize:10},children:i}):null]})}function M0(e,t){const n=wo(t),r=e.some(o=>o.type!=="notebook"?!1:![o.ownerDomain,...o.usesDomains??[]].map(c=>c==null?void 0:c.trim()).filter(c=>!!c).some(c=>n.has(c)));return[...Qn(t).map(o=>o.value),...r?["uncategorized"]:[]]}function nl(e,t,n="",r=[]){const o=t.trim().toLowerCase(),i=wo(r);return Array.from(new Map(e.filter(c=>c.type==="notebook").map(c=>[c.path,c])).values()).filter(c=>{var u,f;const a=[c.ownerDomain,...c.usesDomains??[]].map(d=>d==null?void 0:d.trim()).filter(d=>!!d);return(!n||(n==="uncategorized"?!a.some(d=>i.has(d)):i.has(n)&&a.includes(n)))&&(!o||c.name.toLowerCase().includes(o)||c.path.toLowerCase().includes(o)||((u=c.ownerDomain)==null?void 0:u.toLowerCase().includes(o))||((f=c.usesDomains)==null?void 0:f.some(d=>d.toLowerCase().includes(o))))}).sort((c,a)=>c.name.localeCompare(a.name))}const Js=25;function rl(e){var t;return!!((t=e.relation)!=null&&t.trim())}function ol(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:F0(e.binding.status)}:void 0}}function $0(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 L0(e,t){const n=new Map(t.map(i=>[i.name.toLowerCase(),i])),r=e.columns.map(i=>{var c;return{name:i.name,type:i.type??((c=n.get(i.name.toLowerCase()))==null?void 0:c.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 N0(e){return e.split(".").filter(Boolean).at(-1)??e}function B0(e){const t=e.split(".").filter(Boolean);return t.length>1?t.slice(0,-1).join("."):""}function F0(e){if(e==="draft"||e==="review"||e==="certified"||e==="deprecated"||e==="pending_recertification")return e}function z0({t:e,search:t,onInsert:n}){const{dispatch:r}=et(),[o,i]=p.useState([]),[c,a]=p.useState(0),[l,u]=p.useState(null),[f,d]=p.useState(!0),[h,m]=p.useState(!1),[S,b]=p.useState(null),[x,w]=p.useState(new Set),[C,k]=p.useState(new Set),[v,j]=p.useState(new Set),[D,T]=p.useState({}),y=p.useRef(0),O=t.trim();p.useEffect(()=>{const P=++y.current,$=window.setTimeout(()=>{d(!0),b(null),B.getDbtModelInventory({q:O,limit:Js,physicalOnly:!0}).then(q=>{if(P!==y.current)return;const G=q.items.filter(rl).map(ol);i(G),a(q.total),u(q.nextCursor),w(new Set),k(new Set),T({}),r({type:"MERGE_SCHEMA_TABLES",tables:G})}).catch(q=>{P===y.current&&(i([]),a(0),u(null),b(q instanceof Error?q:new Error(String(q))))}).finally(()=>{P===y.current&&d(!1)})},180);return()=>window.clearTimeout($)},[r,O]);const A=async()=>{if(l===null||h)return;const P=y.current;m(!0);try{const $=await B.getDbtModelInventory({q:O,cursor:l,limit:Js,physicalOnly:!0});if(P!==y.current)return;const q=$.items.filter(rl).map(ol);i(G=>$0(G,q)),a($.total),u($.nextCursor),r({type:"MERGE_SCHEMA_TABLES",tables:q})}catch($){P===y.current&&b($ instanceof Error?$:new Error(String($)))}finally{P===y.current&&m(!1)}},_=async P=>{const $=!x.has(P.dbtUniqueId);if(w(q=>{const G=new Set(q);return $?G.add(P.dbtUniqueId):G.delete(P.dbtUniqueId),G}),!(!$||C.has(P.dbtUniqueId)||v.has(P.dbtUniqueId))){j(q=>new Set(q).add(P.dbtUniqueId)),T(q=>{const G={...q};return delete G[P.dbtUniqueId],G});try{const q=await B.getDbtModelingNode(P.dbtUniqueId),J=q.columns.length===0||q.columns.some(M=>!M.type)?await B.describeTable(P.path):[],H=L0(q,J),L={...P,columns:H};i(M=>M.map(X=>X.dbtUniqueId===P.dbtUniqueId?L:X)),k(M=>new Set(M).add(P.dbtUniqueId)),r({type:"MERGE_SCHEMA_TABLES",tables:[L]})}catch(q){T(G=>({...G,[P.dbtUniqueId]:q instanceof Error?q.message:String(q)}))}finally{j(q=>{const G=new Set(q);return G.delete(P.dbtUniqueId),G})}}};return f?s.jsxs(sr,{t:e,children:[s.jsx(qn,{size:13,className:"dql-spin"})," Loading dbt database objects…"]}):S?s.jsx(q0,{error:S,t:e}):o.length===0?s.jsx(sr,{t:e,children:O?`No dbt models or sources match “${O}”.`:"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 ",c.toLocaleString()," object",c===1?"":"s"]}),o.map(P=>{const $=x.has(P.dbtUniqueId),q=v.has(P.dbtUniqueId),G=D[P.dbtUniqueId],J=N0(P.path),H=B0(P.path);return s.jsxs("div",{children:[s.jsxs("div",{style:{...sl(e),alignItems:"flex-start"},children:[s.jsx("button",{type:"button",onClick:()=>void _(P),"aria-label":`${$?"Collapse":"Expand"} ${J}`,title:$?"Collapse columns":"Load columns",style:U0(e),children:$?s.jsx(Ta,{size:13}):s.jsx(As,{size:13})}),s.jsxs("button",{type:"button",onClick:()=>n(`SELECT * FROM ${P.path} LIMIT 100`),title:`Insert a bounded SELECT from ${P.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(So,{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:P.dbtResourceType}),C.has(P.dbtUniqueId)?s.jsx("span",{style:{fontSize:10,color:e.textMuted,flexShrink:0},children:P.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]})]}),$?s.jsxs("div",{children:[q?s.jsxs(sr,{t:e,compact:!0,children:[s.jsx(qn,{size:11,className:"dql-spin"})," Loading columns…"]}):null,!q&&G?s.jsx(sr,{t:e,compact:!0,children:"Columns unavailable. The relation can still be inserted and queried."}):null,!q&&!G&&C.has(P.dbtUniqueId)&&P.columns.length===0?s.jsx(sr,{t:e,compact:!0,children:"No columns are documented in dbt or visible from the selected connection."}):null,!q&&P.columns.map(L=>s.jsxs("button",{type:"button",onClick:()=>n(L.name),title:`Insert column ${L.name}`,style:{...sl(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]},P.dbtUniqueId)}),l!==null?s.jsx("button",{type:"button",onClick:()=>void A(),disabled:h,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:h?"wait":"pointer",fontSize:10.5,fontFamily:e.font},children:h?"Loading…":`Load ${Math.min(Js,c-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 q0({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(sr,{t,children:r})}function sr({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 sl=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}),U0=e=>({border:"none",background:"transparent",cursor:"pointer",color:e.textMuted,display:"flex",padding:"1px 0 0",flexShrink:0}),W0=[{collection:"metrics",kind:"metric",label:"Metrics"},{collection:"dimensions",kind:"dimension",label:"Dimensions"},{collection:"timeDimensions",kind:"time_dimension",label:"Time Dimensions"},{collection:"entities",kind:"entity",label:"Entities"},{collection:"measures",kind:"measure",label:"Underlying measures"}];function st(e){return String(e??"").trim()||"uncategorized"}function Rt(e){const t=Array.isArray(e.semanticModelIds)?e.semanticModelIds.map(String).filter(Boolean):[];return t.length>0?Array.from(new Set(t)).sort((n,r)=>n.localeCompare(r)):e.cube?[String(e.cube)]:[]}function K0(e,t){return String((t==="dimension"||t==="time_dimension")&&e.reference||e.name)}function V0(e,t,n){const r=K0(e,t),o=st(e.domain);return{id:`${t}:${r}`,label:String(e.label||e.name),kind:t,meta:{provider:n,domain:o,localName:String(e.name),reference:r,...e.canonicalId?{canonicalId:String(e.canonicalId)}:{},...e.qualifiedName?{qualifiedName:String(e.qualifiedName)}:{},...e.entityLink?{entityLink:String(e.entityLink)}:{},...e.table?{table:String(e.table)}:{},...e.cube?{cube:String(e.cube)}:{},...Rt(e).length>0?{semanticModelIds:Rt(e).join(",")}:{},...e.owner?{owner:String(e.owner)}:{},...Array.isArray(e.tags)&&e.tags.length>0?{tags:e.tags.join(",")}:{}}}}function Kt(e,t,n,r,o){if(r.length===0)return null;const i=r.map(c=>V0(c,n,o)).sort((c,a)=>c.label.localeCompare(a.label)||c.id.localeCompare(a.id));return{id:e,label:t,kind:"group",count:i.length,meta:{provider:o,objectKind:n},children:i}}function ar(e){var t;return(t=e.children)!=null&&t.length?e.children.reduce((n,r)=>n+ar(r),0):1}function H0(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 f of Rt(u))o.add(f);const i=u=>{const f=r.get(u);if(f)return st(f.domain);const d=n.find(h=>Rt(h).includes(u));return st(d==null?void 0:d.domain)},c=new Set([...e.domains.map(st),...e.semanticModels.map(u=>st(u.domain)),...n.map(u=>st(u.domain))]),a=Array.from(c).sort((u,f)=>u.localeCompare(f)).flatMap(u=>{const d=Array.from(o).filter(v=>i(v)===u).sort((v,j)=>v.localeCompare(j)).flatMap(v=>{const j=r.get(v),D=W0.flatMap(({collection:y,kind:O,label:A})=>{const _=e[y].filter($=>{const q=Rt($);return q.length===1&&q[0]===v&&(y!=="dimensions"||!$.isTimeDimension)}),P=Kt(`group:${u}:${v}:${O}`,A,O,_,t);return P?[P]:[]});return D.length===0&&!j?[]:[{id:`semantic_model:${v}`,label:(j==null?void 0:j.label)||v,kind:"semantic_model",count:D.reduce((y,O)=>y+ar(O),0),meta:{provider:t,domain:u,cube:v,...j!=null&&j.table?{table:j.table}:{},...j!=null&&j.owner?{owner:j.owner}:{}},children:D}]}),h=e.metrics.filter(v=>st(v.domain)===u&&Rt(v).length>1),m=e.metrics.filter(v=>st(v.domain)===u&&Rt(v).length===0),S=[Kt(`group:${u}:unassigned-dimensions`,"Dimensions","dimension",e.dimensions.filter(v=>st(v.domain)===u&&Rt(v).length===0&&!v.isTimeDimension),t),Kt(`group:${u}:unassigned-time-dimensions`,"Time Dimensions","time_dimension",e.timeDimensions.filter(v=>st(v.domain)===u&&Rt(v).length===0),t),Kt(`group:${u}:unassigned-measures`,"Underlying measures","measure",e.measures.filter(v=>st(v.domain)===u&&Rt(v).length===0),t),Kt(`group:${u}:unassigned-entities`,"Entities","entity",e.entities.filter(v=>st(v.domain)===u&&Rt(v).length===0),t)].filter(v=>!!v),b=[...d],x=Kt(`group:${u}:cross-model-metrics`,"Cross-model metrics","metric",h,t);x&&b.push(x);const w=Kt(`group:${u}:unassigned-metrics`,"Unassigned metrics","metric",m,t);w&&b.push(w),S.length>0&&b.push({id:`group:${u}:unassigned-objects`,label:"Unassigned objects",kind:"group",count:S.reduce((v,j)=>v+ar(j),0),meta:{provider:t,domain:u},children:S});const C=Kt(`group:${u}:hierarchies`,"Hierarchies","hierarchy",e.hierarchies.filter(v=>st(v.domain)===u),t);C&&b.push(C);const k=Kt(`group:${u}:saved-queries`,"Saved Queries","saved_query",e.savedQueries.filter(v=>st(v.domain)===u),t);return k&&b.push(k),b.length===0?[]:[{id:`domain:${t}:${u}`,label:u,kind:"domain",count:b.reduce((v,j)=>v+ar(j),0),meta:{provider:t,domain:u},children:b}]});if(a.length===0)return null;const l=a.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,f)=>u+ar(f),0),meta:{provider:t},children:l}]}}function G0(e,t,n,r){const o=i=>{var a,l;if(!((a=i.children)!=null&&a.length)){if(i.kind==="metric")return{...i};if(i.kind==="dimension"||i.kind==="time_dimension"){if(t===0||r!=="ready"||!n)return null;const 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 c=i.children.map(o).filter(u=>!!u);return c.length===0?null:{...i,count:c.reduce((u,f)=>u+ar(f),0),children:c}};return o(e)??{...e,children:[]}}const il=[{id:"notebooks",label:"Notebooks",icon:Ra},{id:"semantic",label:"Semantic",icon:fp},{id:"database",label:"Database",icon:So},{id:"blocks",label:"Blocks",icon:Ea}],Q0={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 J0({defaultTab:e,onOpenFile:t,tabs:n,onInsertText:r,onSemanticCompose:o,blockDomain:i="",onBlockDomainChange:c,onNewBlock:a,onDeleteBlock:l,blockLibraryRefreshKey:u=0,footer:f,footerStatus:d="ready",onCollapse:h}){var y;const{state:m,dispatch:S}=et(),b=Qe[m.themeMode],x=n?n.map(O=>il.find(A=>A.id===O)).filter(O=>!!O):il,[w,C]=p.useState(e??((y=x[0])==null?void 0:y.id)??"notebooks"),[k,v]=p.useState(""),[j,D]=p.useState("");p.useEffect(()=>{e&&C(e)},[e]);const T=r??(O=>{Lw(O)||S({type:"ADD_CELL",cell:ja("sql",O)})});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:[x.map(({id:O,label:A,icon:_})=>{const P=w===O;return s.jsxs("button",{type:"button",onClick:()=>C(O),title:A,style:{flex:x.length>3?"1 1 auto":1,minWidth:0,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,border:"none",borderBottom:`2px solid ${P?b.accent:"transparent"}`,background:"transparent",color:P?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:A})]},O)}),h?s.jsx("button",{type:"button",onClick:h,title:"Collapse explorer",style:{border:"none",background:"transparent",color:b.textMuted,cursor:"pointer",fontSize:13,padding:"0 6px",flexShrink:0},children:"‹"}):null]}),w==="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(Uc,{size:12,style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:b.textMuted}}),s.jsx("input",{value:k,onChange:O=>v(O.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:()=>S({type:"OPEN_NEW_NOTEBOOK_MODAL"}),title:"Create notebook","aria-label":"Create notebook",style:{width:28,height:28,flexShrink:0,borderRadius:7,border:`1px solid ${b.accent}55`,background:"var(--accent-dim)",color:b.accent,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},children:s.jsx(aS,{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(Uc,{size:12,style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:b.textMuted}}),s.jsx("input",{value:k,onChange:O=>v(O.target.value),placeholder:`Search ${w}…`,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"}})]}),a?s.jsx("button",{type:"button",onClick:a,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(yS,{size:14,strokeWidth:2})}):null]}),s.jsxs("div",{style:{flex:1,minHeight:0,overflow:"auto"},children:[w==="notebooks"&&t&&s.jsx(Y0,{t:b,onOpenFile:t,search:k,domain:j,onDomainChange:D}),w==="semantic"&&s.jsx(tk,{t:b,search:k,onInsert:T,notebookMode:!r||!!o,onSemanticCompose:o}),w==="database"&&s.jsx(z0,{t:b,search:k,onInsert:T}),w==="blocks"&&s.jsx(nk,{t:b,search:k,domain:i,onDomainChange:c,onDeleteBlock:l,refreshKey:u})]}),f?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:d==="ready"?"var(--status-success)":"var(--status-warning)",flexShrink:0}}),s.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:f})]}):null]})}const Op=(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 dr({text:e,t}){return s.jsx("div",{style:{padding:"16px 12px",fontSize:11.5,color:t.textMuted,textAlign:"center"},children:e})}function Y0({t:e,onOpenFile:t,search:n,domain:r,onDomainChange:o}){var D;const{state:i,dispatch:c}=et(),[a,l]=p.useState(null),[u,f]=p.useState(!1),[d,h]=p.useState(null),m=M0(i.files,i.authoredDomains),S=m.includes(r)?r:"",x=[...Qn(i.authoredDomains).filter(T=>m.includes(T.value)),...m.includes("uncategorized")?[{value:"uncategorized",label:"Unassigned"}]:[]],w=nl(i.files,"",S,i.authoredDomains),C=nl(i.files,n,S,i.authoredDomains),k=D0(C,"notebooks"),v=S==="uncategorized"?"unassigned":S||"all domains",j=async()=>{if(a){f(!0),h(null);try{const T=await B.deleteNotebook(a.path);if(!T.ok){h(T.error??"Could not delete this notebook.");return}c({type:"FILE_REMOVED",path:a.path}),l(null)}catch(T){h(T instanceof Error?T.message:String(T))}finally{f(!1)}}};return s.jsxs("div",{children:[s.jsx(_p,{id:"notebook-domain-filter",ariaLabel:"Notebook domain",value:S,options:x,onChange:o,summary:s.jsxs(s.Fragment,{children:[C.length," notebook",C.length===1?"":"s"," · ",v]}),t:e}),C.length===0?s.jsx(dr,{text:w.length===0?S?`No notebooks are related to ${v} yet.`:"No notebooks yet. Use the notebook icon above to create one.":`No ${v} notebooks match “${n.trim()}”.`,t:e}):s.jsx(Pp,{nodes:k,activePath:(D=i.activeFile)==null?void 0:D.path,onOpenFile:t,onDelete:T=>{h(null),l(T)},t:e}),s.jsx("style",{children:`
431
+ .dql-nb-delete { opacity: 0; transition: opacity .12s, color .12s, background .12s, border-color .12s; }
432
+ .dql-nb-row:hover .dql-nb-delete { opacity: 1; }
433
+ .dql-nb-delete:hover { color: ${e.error} !important; background: ${e.error}12 !important; border-color: ${e.error}44 !important; }
434
+ .dql-nb-delete:focus-visible { opacity: 1; }
435
+ `}),a?s.jsx(ek,{file:a,t:e,busy:u,error:d,onCancel:()=>{l(null),h(null)},onConfirm:()=>void j()}):null]})}function Pp({nodes:e,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i=0}){return s.jsx(s.Fragment,{children:e.map(c=>c.kind==="folder"?s.jsx(X0,{node:c,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i},`notebook-folder:${c.path}`):s.jsx(Z0,{file:c.file,active:t===c.file.path,onOpenFile:n,onDelete:r,t:o,depth:i},c.file.path))})}function X0({node:e,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i}){const[c,a]=p.useState(!0);return s.jsxs("div",{children:[s.jsxs("button",{type:"button",onClick:()=>a(l=>!l),"aria-expanded":c,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(As,{size:11,style:{transform:c?"rotate(90deg)":void 0,flexShrink:0}}),c?s.jsx(pp,{size:13}):s.jsx(Yr,{size:13}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]}),c?s.jsx(Pp,{nodes:e.children,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i+1}):null]})}function Z0({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:{...Op(o,t),paddingLeft:10+i*14,paddingRight:30},title:`${e.path}${e.ownerDomain?` · Owner domain: ${e.ownerDomain}`:""}`,children:[s.jsx(Ra,{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:c=>{c.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(mp,{size:12})})]})}function ek({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:c=>c.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:Ae(t,{variant:"secondary",size:"md",disabled:n}),children:"Cancel"}),s.jsx("button",{type:"button",onClick:i,disabled:n,style:Ae(t,{variant:"danger",size:"md",disabled:n}),children:n?"Deleting…":"Delete notebook"})]})]})})}function tk({t:e,search:t,onInsert:n,notebookMode:r,onSemanticCompose:o}){var X;const{state:i,dispatch:c}=et(),a=p.useMemo(()=>H0(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,f]=p.useState(new Set),[d,h]=p.useState(new Set),[m,S]=p.useState(null),[b,x]=p.useState("idle"),[w,C]=p.useState(null),[k,v]=p.useState(!1),[j,D]=p.useState(null),[T,y]=p.useState(null),[O,A]=p.useState(),_=new Map(i.semanticLayer.metrics.map(W=>[W.name,W])),P=()=>{c({type:"SET_SETTINGS_TAB",tab:"project"}),c({type:"SET_MAIN_VIEW",view:"settings"})};p.useEffect(()=>{let W=!0;return B.getConnections().then(te=>{W&&A(te.default?{target:"connection",connectionName:te.default}:void 0)}).catch(()=>{W&&A(void 0)}),()=>{W=!1}},[]),p.useEffect(()=>{let W=!0;if(D(null),y(null),u.size===0){S(null),x("idle"),C(null),h(new Set);return}return S(null),x("loading"),C(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),x("ready"),C(te.engine),h(K=>new Set(Array.from(K).filter(oe=>F.has(oe))))}).catch(te=>{W&&(S(new Set),x("error"),C(null),h(new Set),y(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 $=p.useMemo(()=>!a||!r?a:G0(a,u.size,m,b),[a,r,u.size,m,b]),q=(W,te)=>{D(null),y(null),(W==="metric"?f:h)(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=_.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&&b==="ready"&&!k,L=async()=>{if(u.size!==0){v(!0),y(null);try{const W=await B.previewSemanticBuilder({metrics:Array.from(u),dimensions:Array.from(d),executionTarget:O,limit:50});if("error"in W){D(null),y(W.error);return}D({sql:W.sql,rows:W.result.rowCount??W.result.rows.length,executionTarget:O,engine:W.engine})}catch(W){D(null),y(W instanceof xt?`${W.code?`${W.code}: `:""}${W.message}`:W instanceof Error?W.message:"The governed semantic preview could not run.")}finally{v(!1)}}},M=()=>{if(!H)return;const W=Array.from(u),te=Array.from(d);if(o){o(W,te),f(new Set),h(new Set),D(null),y(null);return}const F=_0(W,te),K=ja("dql",F);K.executionTarget=(j==null?void 0:j.executionTarget)??O,K.dqlArtifact={source:F,kind:"semantic_block",metrics:W,dimensions:te,persistence:"transient",trustState:"governed",reviewState:"draft",routeEvidence:[{route:"semantic",authoringState:j?"previewed":"selected",compatibilityState:b,...w?{compatibilityEngine:w}:{},...j?{engine:j.engine,executionTarget:j.executionTarget,previewRows:j.rows}:{}}],...j?{sql:j.sql,compiledSql:j.sql}:{}},c({type:"ADD_CELL",cell:K}),f(new Set),h(new Set),D(null),y(null)};return l&&!a?s.jsx(dr,{text:"Loading semantic layer…",t:e}):!a||!$||(((X=a.children)==null?void 0:X.length)??0)===0?s.jsx(dr,{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.":b==="loading"?"Checking governed dimensions…":b==="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:k||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:k?"Running…":"Preview & run"}),s.jsx("button",{type:"button",onClick:M,disabled:!H,title:H?o?"Apply this governed selection to the Block Studio visual builder":j?"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"})]}),j&&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 · ",j.rows," row",j.rows===1?"":"s"]}),s.jsx("code",{style:{display:"block",maxHeight:48,overflow:"hidden",whiteSpace:"pre-wrap",fontSize:9,color:e.textMuted},children:j.sql})]}),T&&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:T}),/semantic runtime|MetricFlow/i.test(T)?s.jsx("button",{type:"button",onClick:P,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:P,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(Ww,{tree:$,themeMode:i.themeMode,search:t,onInsert:n,selectionMode:r,selected:J,onToggleSelection:q,canSelect:G})]})}function nk({t:e,search:t,domain:n,onDomainChange:r,onDeleteBlock:o,refreshKey:i}){const{state:c,dispatch:a}=et(),[l,u]=p.useState([]),[f,d]=p.useState(!0),[h,m]=p.useState(new Set),S=c.files.filter(T=>T.type==="block").map(T=>T.path).sort().join("|");p.useEffect(()=>{let T=!0;return d(!0),B.getBlockLibrary().then(y=>{T&&u(y.blocks)}).finally(()=>{T&&d(!1)}),()=>{T=!1}},[S,i]);const b=Kw(l,c.authoredDomains),x=b.includes(n)?n:"",C=[...Qn(c.authoredDomains).filter(T=>b.includes(T.value)),...b.includes("uncategorized")?[{value:"uncategorized",label:"Unassigned"}]:[]],k=Vw(l,x,t,c.authoredDomains),v=p.useMemo(()=>P0(k,x),[k,x]),j=x==="uncategorized"?"unassigned":x||"all domains",D=T=>{const y={name:T.path.split("/").pop()??T.name,path:T.path,type:"block",folder:"blocks"};c.files.some(O=>O.path===T.path)||a({type:"FILE_ADDED",file:y}),B.openBlockStudio(T.path).then(O=>a({type:"OPEN_BLOCK_STUDIO",file:y,payload:O}))};return f?s.jsx(dr,{text:"Loading blocks…",t:e}):l.length===0?s.jsx(dr,{text:"No blocks yet.",t:e}):s.jsxs("div",{children:[s.jsx(_p,{id:"block-domain-filter",ariaLabel:"Block domain",value:x,options:C,onChange:T=>r==null?void 0:r(T),summary:s.jsxs(s.Fragment,{children:[k.length," block",k.length===1?"":"s"," · ",j]}),t:e}),k.length===0?s.jsx(dr,{text:t?`No ${j} blocks match this search.`:x?`No blocks in ${x} yet.`:"No blocks yet.",t:e}):s.jsx(Dp,{nodes:v,depth:0,expandAll:!!t.trim(),expandedFolders:h,onToggleFolder:T=>m(y=>{const O=new Set(y);return O.has(T)?O.delete(T):O.add(T),O}),onOpen:D,onDelete:o,t:e})]})}function Dp({nodes:e,depth:t,expandAll:n,expandedFolders:r,onToggleFolder:o,onOpen:i,onDelete:c,t:a}){return s.jsx(s.Fragment,{children:e.map(l=>{if(l.kind==="block")return s.jsx(rk,{block:l.block,depth:t,t:a,onOpen:()=>i(l.block),onDelete:c?()=>c(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:{...Op(a),paddingLeft:10+t*16,borderBottom:"none",fontWeight:650},children:[u?s.jsx(Ta,{size:13,color:a.textMuted}):s.jsx(As,{size:13,color:a.textMuted}),u?s.jsx(pp,{size:14,color:a.accent}):s.jsx(Yr,{size:14,color:a.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:a.textMuted},children:Ip(l.children)})]}),u?s.jsx(Dp,{nodes:l.children,depth:t+1,expandAll:n,expandedFolders:r,onToggleFolder:o,onOpen:i,onDelete:c,t:a}):null]},`folder:${l.path}`)})})}function Ip(e){return e.reduce((t,n)=>t+(n.kind==="block"?1:Ip(n.children)),0)}function rk({block:e,depth:t=0,t:n,onOpen:r,onDelete:o}){const i=String(e.status??"draft"),c=Q0[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(Ea,{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:c}}),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(mp,{size:13})}):null]})}const qo=(e,t)=>`https://cdn.simpleicons.org/${e}/${t}`,ok={duckdb:[qo("duckdb","FFF000")],file:[qo("duckdb","FFF000")],snowflake:[qo("snowflake","29B5E8")],databricks:[qo("databricks","FF3621")]},sk={duckdb:"#f4bc00",file:"#f4bc00",snowflake:"#29b5e8",databricks:"#ff3621"};function ik({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 Vr({driver:e,size:t=16,fallbackColor:n}){const r=ok[e]??[],o=n??sk[e]??"#888",[i,c]=p.useState(0);return r.length===0||i>=r.length?s.jsx(ik,{size:t,color:o}):s.jsx("img",{src:r[i],alt:`${e} logo`,width:t,height:t,loading:"lazy",onError:()=>c(i+1),style:{flexShrink:0,display:"block",objectFit:"contain"}})}function ak(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 Uo="http://127.0.0.1:11434";function ck({t:e,onStatus:t}){const[n,r]=p.useState("hashed"),[o,i]=p.useState(Uo),[c,a]=p.useState(""),[l,u]=p.useState(""),[f,d]=p.useState(!1),[h,m]=p.useState({ollama:[],openai:[]}),[S,b]=p.useState([]),[x,w]=p.useState(!1),[C,k]=p.useState({id:"",semantic:!1,reindexRequired:!1}),[v,j]=p.useState(null),[D,T]=p.useState(null),[y,O]=p.useState(null),A=p.useCallback(M=>{r(M.settings.provider),i(M.settings.endpoint||Uo),a(M.settings.model),d(M.settings.apiKeySet),k({id:M.activeProviderId,semantic:M.semantic,reindexRequired:M.reindexRequired})},[]),_=p.useCallback(async M=>{try{const X=await B.listEmbeddingModels(M);m(X.catalog),b(X.installed),w(X.ollamaReachable)}catch{}},[]);p.useEffect(()=>{(async()=>{try{const M=await B.getEmbeddingSettings();A(M),await _(M.settings.endpoint||Uo)}catch(M){T(M instanceof Error?M.message:String(M))}})()},[A,_]);const P=async(M,X)=>{j(M),T(null),O(null);try{await X()}catch(W){T(W instanceof Error?W.message:String(W))}finally{j(null)}},$=(M,X)=>P("save",async()=>{const W=await B.saveEmbeddingSettings({provider:M,...M==="ollama"?{endpoint:o}:{},...X?{model:X}:{},...M==="openai"&&l?{apiKey:l}:{}});r(M),a(X),l&&(d(!0),u("")),k({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"?h.openai:h.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=M=>({display:"inline-flex",alignItems:"center",gap:6,height:28,padding:"0 11px",borderRadius:6,border:`1px solid ${M?e.accent:e.btnBorder}`,background:M?e.accent:e.btnBg,color:M?"#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:C.semantic?"var(--status-success-bg)":"var(--status-warning-bg)",color:C.semantic?"var(--status-success)":"var(--status-warning)",border:`1px solid ${C.semantic?"var(--status-success-border)":"var(--status-warning-border)"}`},children:[C.semantic?s.jsx(TS,{size:11}):s.jsx(jS,{size:11}),C.semantic?"Semantic":"Lexical only"]})]}),s.jsx("div",{style:{display:"flex",gap:6,marginTop:12,flexWrap:"wrap"},children:["hashed","ollama","openai"].map(M=>s.jsx("button",{type:"button",onClick:()=>{r(M),M==="hashed"&&$("hashed","")},style:{...L(n===M),textTransform:"capitalize"},children:M==="hashed"?"Offline (default)":M==="ollama"?"Ollama (local)":"OpenAI"},M))}),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:M=>i(M.target.value),onBlur:()=>void _(o),style:H,placeholder:Uo}),s.jsx("span",{style:{fontSize:11,whiteSpace:"nowrap",color:x?"var(--status-success)":e.textMuted},children:x?"reachable":"not reachable"})]}),!x&&s.jsx("div",{style:{fontSize:11.5,color:e.textMuted,marginTop:6,lineHeight:1.5},children:"Start Ollama first — nothing leaves your machine with the local option."})]}),n==="openai"&&s.jsxs("div",{style:{marginTop:12},children:[s.jsxs("div",{style:J,children:["API key ",f?"(stored — leave blank to keep)":""]}),s.jsx("input",{type:"password",value:l,onChange:M=>u(M.target.value),style:{...H,marginTop:4},placeholder:f?"••••••••":"sk-…"}),s.jsx("div",{style:{fontSize:11.5,color:e.textMuted,marginTop:6,lineHeight:1.5},children:"Catalog text (metric names, descriptions, business context) is sent to this endpoint to be embedded. Your answer-model key is never reused for this."})]}),n!=="hashed"&&s.jsxs("div",{style:{marginTop:14},children:[s.jsx("div",{style:J,children:"Model"}),s.jsx("div",{style:{display:"grid",gap:6,marginTop:6},children:q.map(M=>{const X=n==="openai"||S.includes(M.model),W=c===M.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:M.model}),M.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:[M.dimensions," dims · ",M.size]})]}),s.jsx("div",{style:{fontSize:11.5,color:e.textSecondary,marginTop:3,lineHeight:1.45},children:M.description})]}),X?s.jsx("button",{type:"button",onClick:()=>void $(n,M.model),disabled:v!==null,style:L(W),children:W?s.jsxs(s.Fragment,{children:[s.jsx(sv,{size:12})," In use"]}):"Use this"}):s.jsx("button",{type:"button",disabled:v!==null||!x,onClick:()=>void P(`install:${M.model}`,async()=>{await B.installEmbeddingModel(M.model,o),await _(o),await B.saveEmbeddingSettings({provider:"ollama",endpoint:o,model:M.model}),a(M.model);const te=await B.getEmbeddingSettings();A(te),t==null||t(`${M.model} installed and selected. Re-index to apply it.`)}),style:L(!0),children:v===`install:${M.model}`?s.jsxs(s.Fragment,{children:[s.jsx(qn,{size:12,className:"dql-spin"})," Installing…"]}):s.jsxs(s.Fragment,{children:[s.jsx(dp,{size:12})," Install"]})})]},M.model)})})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:14,flexWrap:"wrap"},children:[s.jsxs("button",{type:"button",disabled:v!==null,onClick:()=>void P("test",async()=>{const M=await B.testEmbeddingProvider();t==null||t(`${M.providerId} responded in ${M.elapsedMs} ms (${M.dimensions} dims).`)}),style:L(),children:[v==="test"?s.jsx(qn,{size:12,className:"dql-spin"}):null," Test"]}),s.jsxs("button",{type:"button",disabled:v!==null,onClick:()=>void P("reindex",async()=>{const M=await B.reindexEmbeddings(),X=await B.getEmbeddingSettings();A(X);const W=ak(M,X);O(W),t==null||t(W.message)}),style:L(C.reindexRequired),children:[v==="reindex"?s.jsx(qn,{size:12,className:"dql-spin"}):s.jsx(cs,{size:12}),v==="reindex"?"Re-indexing…":"Re-index catalog"]}),s.jsxs("span",{style:{fontSize:11,color:e.textMuted,fontFamily:e.fontMono},children:["active: ",C.id||"—"]})]}),C.reindexRequired&&s.jsx("div",{style:{fontSize:11.5,color:"var(--status-warning)",marginTop:8,lineHeight:1.5},children:"The catalog still holds vectors from the previous embedder. Re-index to search with the new one — until then the vector lane keeps using the old index."}),v==="reindex"&&s.jsx("div",{role:"status",style:{fontSize:11.5,color:e.textSecondary,marginTop:8,lineHeight:1.5},children:"Rebuilding the local vector index. This page will update automatically when it finishes."}),y&&s.jsx("div",{role:y.ok?"status":"alert",style:{fontSize:11.5,color:y.ok?"var(--status-success)":"var(--status-error)",marginTop:8,lineHeight:1.5},children:y.message}),D&&s.jsx("div",{style:{fontSize:11.5,color:e.error,marginTop:8,lineHeight:1.5},children:D})]})}function lk({values:e,onChange:t,placeholder:n,style:r,ariaLabel:o,title:i,disabled:c}){const a=e.join(", "),[l,u]=p.useState(a),f=p.useRef(!1);return p.useEffect(()=>{f.current||u(a)},[a]),s.jsx("input",{type:"text",value:l,disabled:c,"aria-label":o,title:i,placeholder:n,style:r,onFocus:()=>{f.current=!0},onBlur:()=>{f.current=!1,u(al(l).join(", "))},onChange:d=>{u(d.target.value),t(al(d.target.value))}})}function al(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function dk(e){var t;return((t=e.evaluation)==null?void 0:t.status)==="failed"?"Rerun checks & approve":"Run checks & approve"}function uk(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 pk(e,t,n){const r=n.trim();return{...e,[t]:r||void 0}}async function fk(e,t){try{return await e()}finally{await t()}}const hk=["claude-code","codex","anthropic","openai","gemini","ollama","custom-openai"],mk=["claude-code","codex"],gk=["anthropic","openai","gemini","ollama","custom-openai"];function Mp(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 Ys({includeMemory:e=!0,embedded:t=!1,section:n,editorMode:r="settings",onProviderConfigured:o}){const i=Qe[Ge(T=>T.themeMode)],[c,a]=p.useState([]),[l,u]=p.useState([]),[f,d]=p.useState({}),[h,m]=p.useState({path:"",entries:[],warnings:[]}),[S,b]=p.useState([]),[x,w]=p.useState(!0),[C,k]=p.useState(null),v=async()=>{w(!0);try{const T=!n||n==="providers",y=e&&(!n||n==="memory"),O=!n||n==="advanced",[A,_,P,$]=await Promise.all([O?B.getSettingsEnvStatus():Promise.resolve({groups:[]}),T?B.getProviderSettings():Promise.resolve({providers:[]}),O?B.getRemoteMcpSettings():Promise.resolve({settings:{path:"",entries:[],warnings:[]}}),y?B.listAgentMemory():Promise.resolve({memories:[]})]);a(A.groups),u(_.providers),m(P.settings),b($.memories)}finally{w(!1)}};p.useEffect(()=>{v()},[]),p.useEffect(()=>{if(x||n&&n!=="providers")return;let T=!1;return B.getProviderCliStatus().then(y=>{T||d(y.status??{})}),()=>{T=!0}},[x]);const j=p.useMemo(()=>l.filter(T=>T.enabled&&T.configured).length,[l]),D=l.find(T=>T.active&&T.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(wk,{configured:j,total:l.length||hk.length,activeLabel:D==null?void 0:D.label,t:i})]}),C&&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:C}),x?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(xk,{providers:l,cliStatus:f,t:i,onSaved:T=>u(T),onStatus:k,editorMode:r,onProviderConfigured:o}),s.jsx(ck,{t:i,onStatus:k})]}),!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(ll,{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:mk.map(T=>{const y=l.find(O=>O.id===T);return y?s.jsx(pl,{provider:y,cliStatus:f[T],t:i,onSaved:O=>u(O),onStatus:k},T):null})}),s.jsx(ll,{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:gk.map(T=>{const y=l.find(O=>O.id===T);return y?s.jsx(pl,{provider:y,t:i,onSaved:O=>u(O),onStatus:k},T):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(Sk,{memories:S,t:i,onChange:b,onStatus:k}),s.jsx(vk,{t:i,onStatus:k})]}),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(cl,{settings:h,t:i,onChange:m,onStatus:k})]}),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:c.map(T=>s.jsx(hl,{group:T,t:i},T.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(cl,{settings:h,t:i,onChange:m,onStatus:k})]}),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:c.map(T=>s.jsx(hl,{group:T,t:i},T.id))})]})]})]})]})]})}function cl({settings:e,t,onChange:n,onStatus:r}){const[o,i]=p.useState(e.entries),[c,a]=p.useState("form"),[l,u]=p.useState(()=>Nr(e.entries)),[f,d]=p.useState(null),[h,m]=p.useState(!1);p.useEffect(()=>{i(e.entries),u(Nr(e.entries)),d(null)},[e]);const S=_=>{i(_),u(Nr(_)),d(null)},b=(_,P)=>{S(o.map(($,q)=>q===_?Vn({...$,...P}):$))},x=_=>{S(o.filter((P,$)=>$!==_))},w=()=>{S([...o,{kind:"server",name:"",url:"",enabled:!0,trusted:!1,providers:["openai","anthropic"]}])},C=()=>{S([...o,{kind:"connector",name:"",connectorId:"connector_googledrive",enabled:!0,trusted:!1,providers:["openai"]}])},k=_=>{_==="json"&&u(Nr(o)),d(null),a(_)},v=()=>{const _=jk(l);return i(_),u(Nr(_)),d(null),_},j=()=>{try{v()}catch(_){d(_ instanceof Error?_.message:String(_))}},D=()=>{try{v(),a("form"),r("MCP JSON applied.")}catch(_){d(_ instanceof Error?_.message:String(_))}},T=async()=>{m(!0);try{const _=c==="json"?v():o,P=await B.saveRemoteMcpSettings(_.map(q=>Vn(q)));n(P.settings);const $=P.settings.warnings.length?` ${P.settings.warnings.join(" ")}`:"";r(`MCP connections saved.${$}`)}catch(_){const P=_ instanceof Error?_.message:String(_);c==="json"&&d(P),r(P)}finally{m(!1)}},y=o.filter(_=>_.enabled&&_.trusted).length,O=o.filter(_=>_.kind==="server").length,A=o.filter(_=>_.kind==="connector").length;return s.jsxs("section",{style:{border:`1px solid ${t.headerBorder}`,borderRadius:8,background:t.cellBg,padding:14},children:[s.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center",flexWrap:"wrap"},children:[s.jsxs("div",{style:{flex:1,minWidth:240},children:[s.jsxs("div",{style:{fontSize:12,color:t.textSecondary},children:[y," trusted connection",y===1?"":"s"," available to SDK providers"]}),s.jsxs("div",{style:{fontSize:11,color:t.textMuted,marginTop:3},children:[O," remote server",O===1?"":"s"," / ",A," OpenAI connector",A===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:()=>k("form"),style:ml(t,c==="form"),children:"Form"}),s.jsx("button",{type:"button",onClick:()=>k("json"),style:ml(t,c==="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:C,style:Nt(t,!1),children:"Add OpenAI connector"}),s.jsx("button",{type:"button",onClick:T,disabled:h,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(Xs,{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(Xs,{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(Xs,{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(" ")}),c==="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:_=>{u(_.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}}),f&&s.jsx("div",{style:{color:"#b42318",fontSize:12,marginTop:8},children:f}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:10},children:[s.jsx("button",{type:"button",onClick:j,style:Nt(t,!1),children:"Format JSON"}),s.jsx("button",{type:"button",onClick:D,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((_,P)=>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:_.kind,onChange:$=>b(P,{kind:$.target.value==="connector"?"connector":"server",providers:$.target.value==="connector"?["openai"]:_.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:_.name,onChange:$=>b(P,{name:$.target.value}),placeholder:"Name",style:{...Ne(t),flex:1}}),s.jsx("button",{type:"button",onClick:()=>x(P),style:Nt(t,!1),children:"Remove"})]}),s.jsxs("div",{style:{display:"grid",gap:8,marginTop:10},children:[_.kind==="connector"?s.jsx("input",{value:_.connectorId??"",onChange:$=>b(P,{connectorId:$.target.value}),placeholder:"connector_googledrive",style:Ne(t)}):s.jsx("input",{value:_.url??"",onChange:$=>b(P,{url:$.target.value}),placeholder:"https://example.com/mcp or /sse",style:Ne(t)}),s.jsx("input",{value:_.description??"",onChange:$=>b(P,{description:$.target.value}),placeholder:"Description shown to the model",style:Ne(t)}),s.jsx("input",{value:_.authorizationTokenEnv??"",onChange:$=>b(P,{authorizationTokenEnv:$.target.value}),placeholder:"Authorization token env var",style:Ne(t)}),s.jsx("input",{value:_.authorizationToken??"",onChange:$=>b(P,{authorizationToken:$.target.value}),type:"password",placeholder:_.hasAuthorizationToken?`Leave blank to keep ${_.authorizationTokenPreview??"stored token"}`:"Optional OAuth token",style:Ne(t)}),s.jsx(lk,{values:_.allowedTools??[],onChange:$=>b(P,{allowedTools:$}),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:Lr(t),children:[s.jsx("input",{type:"checkbox",checked:_.enabled,onChange:$=>b(P,{enabled:$.target.checked})})," Enabled"]}),s.jsxs("label",{style:Lr(t),children:[s.jsx("input",{type:"checkbox",checked:_.trusted,onChange:$=>b(P,{trusted:$.target.checked})})," Trusted"]}),s.jsxs("label",{style:Lr(t),children:[s.jsx("input",{type:"checkbox",checked:!!_.deferLoading,onChange:$=>b(P,{deferLoading:$.target.checked})})," Defer tools"]}),s.jsxs("label",{style:Lr(t),children:[s.jsx("input",{type:"checkbox",checked:(_.providers??[]).includes("openai"),onChange:$=>b(P,{providers:yl(_.providers,"openai",$.target.checked)})})," OpenAI"]}),s.jsxs("label",{style:Lr(t),children:[s.jsx("input",{type:"checkbox",checked:(_.providers??[]).includes("anthropic"),disabled:_.kind==="connector",onChange:$=>b(P,{providers:yl(_.providers,"anthropic",$.target.checked)})})," Anthropic"]})]})]},`${_.kind}-${_.name||P}`))})]})}function Xs({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 yk({status:e,command:t,loginCmd:n,t:r}){let o=r.textMuted,i=r.textMuted,c="Checking for the CLI…";if(e)if(!e.installed)o=r.warning,i=r.warning,c=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,c=s.jsxs(s.Fragment,{children:["Installed but not signed in — run ",s.jsxs("code",{children:[t," ",n]}),"."]});else{o=r.success,i=r.success;const a=[e.email,e.subscriptionType?`${e.subscriptionType} plan`:e.authMethod].filter(Boolean).join(" · ");c=s.jsxs(s.Fragment,{children:["Signed in",a?s.jsxs(s.Fragment,{children:[" — ",a]}):"",". Ready to use."]})}return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,fontSize:12,color:o},children:[s.jsx("span",{style:{width:7,height:7,borderRadius:"50%",background:i,flex:"0 0 auto"}}),s.jsx("span",{children:c})]})}function ll({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 $p(e){return e==="codex"?"codex":"claude"}function Lp({oauthProvider:e,label:t,model:n,setModel:r,cliStatus:o,command:i,loginCmd:c,t:a,onStatus:l,onConnected:u}){const[f,d]=p.useState(null),[h,m]=p.useState(!1),S=p.useRef(null),b=p.useRef(!0),x=e==="codex"?"ChatGPT":"Claude",w=p.useCallback(()=>{S.current!==null&&(window.clearInterval(S.current),S.current=null)},[]);p.useEffect(()=>(b.current=!0,B.getOAuthStatus(e).then(v=>{b.current&&d(v)}).catch(()=>{}),()=>{b.current=!1,w()}),[e,w]);const C=async()=>{m(!0);try{const v=await B.startOAuth(e);d(v),window.open(v.url,"_blank","noopener,noreferrer"),l(`Opened your browser to sign in to ${x}. Complete it there — this updates automatically.`);const j=Date.now();w(),S.current=window.setInterval(async()=>{const D=await B.getOAuthStatus(e).catch(()=>null);if(!b.current){w();return}D&&d(D),D!=null&&D.connected?(w(),m(!1),u(D.defaultModel)):Date.now()-j>300*1e3&&(w(),m(!1),l(`${x} sign-in timed out. Try again.`))},2500)}catch(v){m(!1),l(v instanceof Error?v.message:String(v))}},k=async()=>{m(!0),w();try{d(await B.signOutOAuth(e)),l(`Signed out of ${x}.`)}catch(v){l(v instanceof Error?v.message:String(v))}finally{m(!1)}};if(f!=null&&f.connected){const v=f.models.length>0?f.models:[f.defaultModel];return s.jsxs("div",{style:{display:"grid",gap:8},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12.5},children:[s.jsxs("span",{style:{color:"#16a34a",fontWeight:700},children:["✓ Signed in to ",x]}),f.email?s.jsxs("span",{style:{color:a.textSecondary},children:["as ",f.email]}):null]}),s.jsx("label",{style:{fontSize:11,color:a.textSecondary,fontWeight:600},children:"Model"}),s.jsx("select",{value:n||f.defaultModel,onChange:j=>r(j.target.value),style:Ne(a),children:v.map(j=>s.jsx("option",{value:j,children:j},j))}),s.jsx("div",{children:s.jsx("button",{type:"button",onClick:k,disabled:h,style:Nt(a,!1),children:"Sign out"})})]})}return s.jsxs("div",{style:{display:"grid",gap:8},children:[s.jsx("button",{type:"button",onClick:C,disabled:h,style:Nt(a,!0),children:h||f!=null&&f.pending?`Waiting for ${x}…`:`Sign in with ${x}`}),s.jsxs("div",{style:{fontSize:12,color:a.textSecondary,lineHeight:1.5},children:["No API key needed — signs in with your ",x," subscription in the browser."]}),s.jsxs("details",{children:[s.jsx("summary",{style:{fontSize:11.5,color:a.textSecondary,cursor:"pointer"},children:"Prefer the CLI?"}),s.jsxs("div",{style:{marginTop:6,display:"grid",gap:6},children:[s.jsx(yk,{status:o,command:i,loginCmd:c,t:a}),s.jsxs("div",{style:{fontSize:11.5,color:a.textSecondary,lineHeight:1.5},children:["Or install the ",s.jsx("code",{children:i})," CLI and run ",s.jsxs("code",{children:[i," ",c]}),", then Enable + Save."]})]})]})]})}const Yo=[{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"}}],dl={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 bk(e){if(!e)return"claude";const t=Yo.find(n=>Object.values(n.modes).includes(e));return(t==null?void 0:t.key)??"claude"}function xk({providers:e,cliStatus:t,t:n,onSaved:r,onStatus:o,editorMode:i,onProviderConfigured:c}){var F;const a=e.find(K=>K.active&&K.configured),[l,u]=p.useState(()=>bk(a==null?void 0:a.id)),f=Yo.find(K=>K.key===l)??Yo[0],d=Object.keys(f.modes),[h,m]=p.useState(()=>d.find(oe=>f.modes[oe]===(a==null?void 0:a.id))??d[0]),S=d.includes(h)?h:d[0],b=f.modes[S],x=e.find(K=>K.id===b),[w,C]=p.useState(""),[k,v]=p.useState((x==null?void 0:x.baseUrl)??""),[j,D]=p.useState((x==null?void 0:x.model)??""),[T,y]=p.useState((x==null?void 0:x.reasoningEffort)??"auto"),[O,A]=p.useState(!1),[_,P]=p.useState({state:"idle"}),[$,q]=p.useState({state:"idle"});p.useEffect(()=>{C(""),v((x==null?void 0:x.baseUrl)??""),D((x==null?void 0:x.model)??""),y((x==null?void 0:x.reasoningEffort)??"auto"),q({state:"idle"})},[b,x==null?void 0:x.baseUrl,x==null?void 0:x.model,x==null?void 0:x.reasoningEffort]);const G=async()=>{if(!a)return;P({state:"testing"});const K=Date.now(),oe=await B.testProviderSettings(a.id,{}),ee=oe.ok!==!1;P({state:"done",ok:ee,message:oe.message,seconds:((Date.now()-K)/1e3).toFixed(1)})},J=()=>{var K;return b==="custom-openai"&&!k.trim()?"Custom OpenAI-compatible providers require a Base URL.":b==="custom-openai"&&!j.trim()?"Custom OpenAI-compatible providers require a model.":S==="api"&&b!=="custom-openai"&&!w.trim()&&!(x!=null&&x.hasApiKey)?`Add an API key${(K=x==null?void 0:x.envVars)!=null&&K[0]?` or set ${x.envVars[0]}`:""}.`:S==="local"&&!k.trim()&&!j.trim()&&!(x!=null&&x.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(b,{apiKey:w||void 0,baseUrl:k||void 0,model:j||void 0});return q({state:"done",ok:oe.ok,message:oe.message}),oe.ok},L=async()=>{A(!0);try{if(!await H()){o("Test failed. Your existing provider configuration was not changed.");return}const oe=await B.saveProviderSettings({id:b,enabled:!0,apiKey:w||void 0,baseUrl:k,model:j,reasoningEffort:T});r(oe.providers);const ee=oe.providers.find(ce=>ce.id===b);ee&&(c==null||c(ee)),o(`${f.label} passed its test and is now the active provider.`)}catch(K){o(K instanceof Error?K.message:String(K))}finally{A(!1)}},M=async K=>{const oe=j||K;D(oe);try{const ee=await B.saveProviderSettings({id:b,enabled:!0,model:oe});r(ee.providers);const ce=ee.providers.find(ke=>ke.id===b);ce&&(c==null||c(ce)),o(`${f.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."]})]}),a?s.jsxs("div",{style:{border:"1px solid var(--status-success-border)",borderRadius:12,background:n.cellBg,padding:"16px 18px",display:"flex",alignItems:"center",gap:12},children:[s.jsx("span",{style:{width:36,height:36,borderRadius:9,background:"var(--status-success-bg)",color:"var(--status-success)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:s.jsx(hp,{size:17,strokeWidth:1.75})}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsxs("div",{style:{fontSize:13,fontWeight:700,color:n.textPrimary},children:["Active · ",a.label,a.model?` — ${a.model}`:""]}),s.jsx("div",{style:{fontSize:11.5,color:_.state==="done"&&_.ok===!1?"var(--status-error)":"var(--status-success)",marginTop:2},children:_.state==="testing"?"Testing…":_.state==="done"?_.ok?`Test passed · ${_.seconds}s`:_.message||"Test failed":a.source==="env"?"Configured from environment — run Test to verify":"Configured — run Test to verify reachability"})]}),s.jsx("button",{type:"button",onClick:()=>void G(),disabled:_.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:_.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:f.key,onChange:K=>{u(K.target.value),m("subscription")},style:W,children:Yo.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:dl[K].label}),s.jsx("span",{style:{fontSize:10,color:n.textMuted},children:dl[K].hint})]})]},K)})})]}),S==="subscription"&&x?s.jsx("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:9,background:"var(--bg-1)",padding:"11px 13px"},children:s.jsx(Lp,{oauthProvider:$p(b),label:x.label,model:j,setModel:D,cliStatus:t[b],command:x.command,loginCmd:b==="claude-code"?"/login":"login",t:n,onStatus:o,onConnected:M})}):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=>C(K.target.value),placeholder:x!=null&&x.hasApiKey?"Leave blank to keep existing key":"API key",style:{...W,fontFamily:n.fontMono}})]}),(F=x==null?void 0:x.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:x.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:k,onChange:K=>v(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:x!=null&&x.enabled?"var(--status-success)":n.textMuted},children:[s.jsx("span",{style:{width:7,height:7,borderRadius:999,background:x!=null&&x.enabled?"var(--status-success)":"var(--border-strong)"}}),x!=null&&x.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(ul,{providerId:b,provider:x,mode:S,baseUrl:k,setBaseUrl:v,model:j,setModel:D,reasoningEffort:T,setReasoningEffort:y,t:n,input:W,fieldLabel:X})})]}):s.jsx("div",{style:{display:"grid",gap:10},children:s.jsx(ul,{providerId:b,provider:x,mode:S,baseUrl:k,setBaseUrl:v,model:j,setModel:D,reasoningEffort:T,setReasoningEffort:y,t:n,input:W,fieldLabel:X})}),$.state!=="idle"?s.jsx("div",{role:$.ok===!1?"alert":"status",style:{fontSize:11.5,lineHeight:1.5,color:$.state==="testing"?n.textMuted:$.ok?"var(--status-success)":"var(--status-error)"},children:$.state==="testing"?"Testing these unsaved values through the governed runtime…":$.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:O||$.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:$.state==="testing"?"Testing…":"Test unsaved values"}),s.jsx("button",{type:"button",onClick:()=>void L(),disabled:O,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:O?.7:1},children:O?"Testing…":"Test, save & activate"})]})]})]})}function ul({providerId:e,provider:t,mode:n,baseUrl:r,setBaseUrl:o,model:i,setModel:c,reasoningEffort:a,setReasoningEffort:l,t:u,input:f,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:h=>o(h.target.value),placeholder:Mp(e),style:{...f,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:h=>c(h.target.value),placeholder:(t==null?void 0:t.model)||"Provider default",style:f})]}),t!=null&&t.supportsReasoningEffort&&n==="api"?s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsx("span",{style:d,children:"Reasoning effort"}),s.jsxs("select",{value:a,onChange:h=>l(h.target.value),style:f,children:[s.jsx("option",{value:"auto",children:"Auto — pick per task (up to High)"}),s.jsx("option",{value:"low",children:"Low — fastest, cheapest"}),s.jsx("option",{value:"medium",children:"Medium"}),s.jsx("option",{value:"high",children:"High — deepest reasoning"})]})]}):null]})}function pl({provider:e,cliStatus:t,t:n,onSaved:r,onStatus:o}){const[i,c]=p.useState(e.enabled),[a,l]=p.useState(""),[u,f]=p.useState(e.baseUrl??""),[d,h]=p.useState(e.model??""),[m,S]=p.useState(e.reasoningEffort??"auto"),[b,x]=p.useState(!1),[w,C]=p.useState(!1),[k,v]=p.useState(null),j=e.authMode==="subscription_cli",D=e.id==="claude-code"?"/login":"login",T=e.supportsReasoningEffort===!0&&!j&&e.id!=="ollama";p.useEffect(()=>{c(e.enabled),f(e.baseUrl??""),h(e.model??""),S(e.reasoningEffort??"auto"),l(""),v(null)},[e.id,e.enabled,e.baseUrl,e.model,e.reasoningEffort]);const y=async()=>{x(!0);try{const _=await B.saveProviderSettings({id:e.id,enabled:i,apiKey:a||void 0,baseUrl:u,model:d,reasoningEffort:m});r(_.providers),o(`${e.label} settings saved.`)}catch(_){o(_ instanceof Error?_.message:String(_))}finally{x(!1)}},O=async()=>{C(!0),v(null);const _=await B.testProviderSettings(e.id,{apiKey:a||void 0,baseUrl:u||void 0,model:d||void 0}),P=_.ok!==!1;v({ok:P,message:_.message||(P?`${e.label} is reachable.`:`${e.label} test failed.`)}),C(!1)},A=async _=>{const P=d||_;h(P),c(!0);try{const $=await B.saveProviderSettings({id:e.id,enabled:!0,model:P});r($.providers),o(`${e.label} connected and activated.`)}catch($){o($ instanceof Error?$.message:String($))}};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:Ck(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:_=>c(_.target.checked)}),"Enabled"]})]}),s.jsxs("div",{style:{display:"grid",gap:8,marginTop:12},children:[j?s.jsx(Lp,{oauthProvider:$p(e.id),label:e.label,model:d,setModel:h,cliStatus:t,command:e.command,loginCmd:D,t:n,onStatus:o,onConnected:A}):s.jsxs(s.Fragment,{children:[e.id!=="ollama"&&s.jsx("input",{value:a,onChange:_=>l(_.target.value),type:"password",placeholder:e.hasApiKey?"Leave blank to keep existing key":"API key",style:Ne(n)}),s.jsx("input",{value:u,onChange:_=>f(_.target.value),placeholder:Mp(e.id),style:Ne(n)})]}),!j&&s.jsx("input",{value:d,onChange:_=>h(_.target.value),placeholder:"Default model",style:Ne(n)}),T&&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:_=>S(_.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:y,disabled:b||w,style:Nt(n,!0),children:e.active?"Save active provider":"Save and use"}),s.jsx("button",{type:"button",onClick:O,disabled:b||w,style:Nt(n,!1),children:w?"Testing…":"Test"})]}),k&&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:k.ok?n.success:n.error,background:`${k.ok?n.success:n.error}12`,border:`1px solid ${k.ok?n.success:n.error}40`},children:[s.jsx("span",{style:{flexShrink:0,fontWeight:700},children:k.ok?"✓":"✗"}),s.jsx("span",{children:k.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 fl(e){return[...new Map(e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean).map(t=>[t.toLowerCase(),t])).values()].slice(0,8)}function vk({t:e,onStatus:t}){const[n,r]=p.useState([]),[o,i]=p.useState({candidate:0,approved:0,rejected:0,retired:0}),[c,a]=p.useState(null),[l,u]=p.useState(!1),[f,d]=p.useState({}),[h,m]=p.useState(null),S=p.useCallback(async()=>{try{const y=await B.listAgentHints();r(y.hints??[]),i(y.counts??{candidate:0,approved:0,rejected:0,retired:0})}catch{r([])}finally{u(!0)}},[]);p.useEffect(()=>{S()},[S]);const b=async(y,O)=>{var A;a(y.id),t(null);try{const _=(A=f[y.id])==null?void 0:A.trim(),P=await fk(()=>B.reviewAgentHint(y.id,O,_),S);P.ok?t(O==="approved"?`Approved. DQL will apply "${y.title}" to matching questions.`:`Rejected. "${y.title}" will not be used.`):t(P.error??`Could not ${O==="approved"?"approve":"reject"} this correction.`)}catch(_){t(_ instanceof Error?_.message:String(_))}finally{a(null)}},x=async(y,O,A)=>{var _;a(y.id),t(null);try{const P=await B.transitionAgentHint(y.id,{action:O,targetHintId:A,note:((_=f[y.id])==null?void 0:_.trim())||void 0});t(P.ok?O==="retire"?`Retired "${y.title}". It is excluded from future answers.`:O==="reopen"?`Reopened "${y.title}" as a candidate.`:`Resolved the conflict. "${y.title}" is authoritative.`:P.error??`Could not ${O} this hint.`),await S()}catch(P){t(P instanceof Error?P.message:String(P))}finally{a(null)}},w=async()=>{if(h){a(h.id),t(null);try{const y=await B.updateAgentHint(h.id,{title:h.title,guidance:h.guidance,lesson:{...rt(h),rule:h.guidance},correctedSql:h.correctedSql,scope:h.scope});y.ok?(t(`Updated "${h.title}" and refreshed its current dependencies.`),m(null)):t(y.error??"Could not update this candidate."),await S()}catch(y){t(y instanceof Error?y.message:String(y))}finally{a(null)}}},C=async y=>{var O;if(!((O=y.trace)!=null&&O.question)||!y.correctedSql){t("This hint is missing the question or SQL required for an analyst certification request.");return}a(y.id);try{const A=await B.requestCertification({question:y.trace.question,generatedSql:y.correctedSql,domain:y.scope.domain,context:{source:"governed_hint_review",hintId:y.id,evaluationId:y.evaluationId,snapshotId:y.snapshotId}});t(A.ok?`Certification research requested for "${y.title}". Approval of a hint did not certify an asset.`:A.error??"Could not request certification.")}catch(A){t(A instanceof Error?A.message:String(A))}finally{a(null)}},k=n.filter(y=>y.status==="candidate"),v=n.filter(y=>y.status==="approved"),j=n.filter(y=>y.status==="rejected"||y.status==="retired");if(!l)return null;const D=y=>{var O,A,_,P,$,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:[(O=y.trace)!=null&&O.question?s.jsxs("div",{children:[s.jsx("b",{children:"Question:"})," ",y.trace.question]}):null,(A=y.trace)!=null&&A.wrongAnswer?s.jsxs("div",{children:[s.jsx("b",{children:"Previous answer:"})," ",y.trace.wrongAnswer]}):null,(_=y.trace)!=null&&_.rationale?s.jsxs("div",{children:[s.jsx("b",{children:"Why the correction is right:"})," ",y.trace.rationale]}):null,s.jsxs("div",{children:[s.jsx("b",{children:"Snapshot:"})," ",y.snapshotId??"missing",(P=y.inspection)!=null&&P.currentSnapshotId?` · current ${y.inspection.currentSnapshotId}`:""]}),s.jsxs("div",{children:[s.jsx("b",{children:"Dependencies:"})," ",(($=y.dependencies)==null?void 0:$.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=y.graphEdges)!=null&&q.length?y.graphEdges.map(L=>`${L.kind.replace(/_/g," ")} → ${L.targetName}`).join(" · "):"none materialized"]}),(G=y.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}`)),y.evaluation?s.jsxs("div",{children:[s.jsxs("b",{children:["Evaluation ",y.evaluation.status,":"]}),y.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=y.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=y.exclusions)==null?void 0:H.map((L,M)=>s.jsxs("div",{style:{color:e.error},children:[s.jsxs("b",{children:["Excluded: ",L.reason]})," — ",L.detail]},`${L.reason}-${M}`))]})]})},T=y=>{var P,$,q,G,J,H;const O=((P=y.exclusions)==null?void 0:P.filter(L=>L.reason==="conflict"&&L.relatedHintId))??[],A=(h==null?void 0:h.id)===y.id,_=y.status==="approved"&&(($=y.evaluation)==null?void 0:$.status)==="passed"&&((q=y.inspection)==null?void 0:q.state)==="current"&&(((G=y.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:y.title}),s.jsx("span",{style:{fontSize:10,color:(J=y.exclusions)!=null&&J.length||((H=y.evaluation)==null?void 0:H.status)==="failed"?e.error:e.success},children:uk(y)})]}),A?s.jsxs(s.Fragment,{children:[s.jsx("input",{value:h.title,onChange:L=>m({...h,title:L.target.value}),placeholder:"Hint title",style:Ae(e,{size:"sm"})}),s.jsx("textarea",{value:h.guidance,onChange:L=>m({...h,guidance:L.target.value}),placeholder:"Guidance for matching questions",rows:3,style:{...Ae(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(h).category,onChange:L=>m({...h,lesson:{...rt(h),category:L.target.value}}),style:Ae(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(h).intentExamples.join(`
436
+ `),onChange:L=>m({...h,lesson:{...rt(h),intentExamples:L.target.value.split(/\r?\n/)}}),onBlur:()=>m({...h,lesson:{...rt(h),intentExamples:fl(rt(h).intentExamples.join(`
437
+ `))}}),placeholder:"Similar questions, one per line",rows:3,style:{...Ae(e,{size:"sm"}),resize:"vertical"}}),s.jsx("textarea",{value:rt(h).avoid.join(`
438
+ `),onChange:L=>m({...h,lesson:{...rt(h),avoid:L.target.value.split(/\r?\n/)}}),onBlur:()=>m({...h,lesson:{...rt(h),avoid:fl(rt(h).avoid.join(`
439
+ `))}}),placeholder:"Known mistakes to avoid, one per line",rows:2,style:{...Ae(e,{size:"sm"}),resize:"vertical"}}),s.jsx("input",{value:rt(h).expectedOutcome??"",onChange:L=>m({...h,lesson:{...rt(h),expectedOutcome:L.target.value||void 0}}),placeholder:"Expected outcome or result shape",style:Ae(e,{size:"sm"})})]})]}),s.jsx("textarea",{value:h.correctedSql??"",onChange:L=>m({...h,correctedSql:L.target.value}),placeholder:"Read-only corrected SQL",rows:5,style:{...Ae(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,M])=>s.jsxs("label",{style:{display:"grid",gap:3,fontSize:10,color:e.textMuted},children:[M,s.jsx("input",{value:h.scope[L]??"",onChange:X=>m({...h,scope:pk(h.scope,L,X.target.value)}),placeholder:`Optional ${M}`,style:Ae(e,{size:"sm"})})]},L))}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsx("button",{type:"button",disabled:c===y.id,onClick:()=>void w(),style:Ae(e,{variant:"primary",size:"sm",disabled:c===y.id}),children:"Save & recheck"}),s.jsx("button",{type:"button",onClick:()=>m(null),style:Ae(e,{variant:"ghost",size:"sm"}),children:"Cancel"})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{fontSize:11.5,color:e.textSecondary,lineHeight:1.5},children:y.guidance}),y.lesson?s.jsxs("div",{style:{display:"grid",gap:3,padding:"7px 8px",borderRadius:6,background:e.btnBg,fontSize:10.5,color:e.textMuted},children:[s.jsxs("div",{children:[s.jsx("b",{children:"Lesson type:"})," ",y.lesson.category.replace(/_/g," ")]}),y.lesson.intentExamples.length?s.jsxs("div",{children:[s.jsx("b",{children:"Similar questions:"})," ",y.lesson.intentExamples.join(" · ")]}):null,y.lesson.avoid.length?s.jsxs("div",{children:[s.jsx("b",{children:"Avoid:"})," ",y.lesson.avoid.join(" · ")]}):null,y.lesson.expectedOutcome?s.jsxs("div",{children:[s.jsx("b",{children:"Expected:"})," ",y.lesson.expectedOutcome]}):null]}):null,y.correctedSql?s.jsx("pre",{style:{margin:0,fontSize:10.5,fontFamily:e.fontMono,color:e.textMuted,whiteSpace:"pre-wrap",maxHeight:120,overflow:"auto"},children:y.correctedSql}):null,D(y),s.jsx("textarea",{value:f[y.id]??"",onChange:L=>d({...f,[y.id]:L.target.value}),placeholder:"Reviewer note or result assertion (required evidence when this surface cannot execute)",rows:2,style:{...Ae(e,{size:"sm"}),resize:"vertical"}}),s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[y.status==="candidate"?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",disabled:c===y.id,onClick:()=>void b(y,"approved"),style:Ae(e,{variant:"primary",size:"sm",disabled:c===y.id}),children:c===y.id?"Checking…":dk(y)}),s.jsx("button",{type:"button",disabled:c===y.id,onClick:()=>m({...y,lesson:rt(y)}),style:Ae(e,{size:"sm",disabled:c===y.id}),children:"Edit candidate"}),s.jsx("button",{type:"button",disabled:c===y.id,onClick:()=>void b(y,"rejected"),style:Ae(e,{variant:"danger",size:"sm",disabled:c===y.id}),children:"Reject"})]}):null,y.status==="approved"?s.jsxs(s.Fragment,{children:[_?s.jsx("button",{type:"button",disabled:c===y.id,onClick:()=>void C(y),style:Ae(e,{variant:"primary",size:"sm",disabled:c===y.id}),children:"Request certification"}):null,s.jsx("button",{type:"button",disabled:c===y.id,onClick:()=>void x(y,"reopen"),style:Ae(e,{size:"sm",disabled:c===y.id}),children:"Reopen & edit"}),s.jsx("button",{type:"button",disabled:c===y.id,onClick:()=>void x(y,"retire"),style:Ae(e,{variant:"danger",size:"sm",disabled:c===y.id}),children:"Retire"}),O.map(L=>s.jsx("button",{type:"button",disabled:c===y.id,onClick:()=>void x(y,"supersede",L.relatedHintId),style:Ae(e,{size:"sm",disabled:c===y.id}),children:"Keep this; supersede conflict"},L.relatedHintId))]}):null,y.status==="retired"?s.jsx("button",{type:"button",disabled:c===y.id,onClick:()=>void x(y,"reopen"),style:Ae(e,{size:"sm",disabled:c===y.id}),children:"Reopen as candidate"}):null,s.jsx("span",{style:{fontSize:10.5,color:e.textMuted},children:[y.scope.dbtModel,y.scope.metric,y.scope.domain].filter(Boolean).join(" · ")||"project-wide"})]})]})]},y.id)};return s.jsxs("div",{style:{marginTop:18},children:[s.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:8},children:[s.jsx("span",{style:{fontSize:12.5,fontWeight:650,color:e.textPrimary},children:"Corrections awaiting review"}),s.jsxs("span",{style:{fontSize:11,color:e.textMuted},children:[o.candidate," pending · ",o.approved," approved",o.rejected?` · ${o.rejected} rejected`:"",o.retired?` · ${o.retired} retired`:""]})]}),k.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:k.map(T)}),v.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{margin:"16px 0 8px",fontSize:12.5,fontWeight:650,color:e.textPrimary},children:"Approved learning"}),s.jsx("div",{style:{display:"grid",gap:8},children:v.map(T)})]}):null,j.length>0?s.jsxs("details",{style:{marginTop:16},children:[s.jsxs("summary",{style:{cursor:"pointer",fontSize:12,color:e.textSecondary},children:["Rejected & retired history (",j.length,")"]}),s.jsx("div",{style:{display:"grid",gap:8,marginTop:8},children:j.map(T)})]}):null]})}function Sk({memories:e,t,onChange:n,onStatus:r}){const[o,i]=p.useState("project"),[c,a]=p.useState(""),[l,u]=p.useState(""),[f,d]=p.useState(""),h=async()=>{const A=await B.listAgentMemory();n(A.memories)},m=async A=>{await B.deleteAgentMemory(A),await h(),r("Memory deleted.")},[S,b]=p.useState(!1),[x,w]=p.useState("all"),[C,k]=p.useState(null),v=A=>A==="project"?{label:"project",bg:"var(--accent-dim)",color:t.accent}:A==="user"?{label:"just me",bg:`${t.textMuted}1f`,color:t.textMuted}:{label:A,bg:"var(--status-success-bg)",color:"var(--status-success)"},j=e.filter(A=>x==="all"?!0:x==="project"?A.scope==="project":A.scope==="user"),D=A=>{k(A.id),i(A.scope),a(A.title),u(A.content),d(A.tags.join(", ")),b(!0)},T=()=>{b(!1),k(null),a(""),u(""),d("")},y=async()=>{if(!l.trim())return;c.trim()||a(l.trim().slice(0,60));const A=c.trim()||l.trim().slice(0,60);await B.saveAgentMemory({scope:o,title:A,content:l,tags:f.split(",").map(_=>_.trim()).filter(Boolean),source:"settings-ui",confidence:.8,importance:o==="project"?.7:.5,enabled:!0}),C&&await B.deleteAgentMemory(C).catch(()=>{}),T(),await h(),r(C?"Memory updated.":"Memory saved.")},O=(A,_)=>s.jsx("button",{type:"button",onClick:()=>w(A),style:{border:"none",borderRadius:5,padding:"4px 11px",fontSize:11.5,fontWeight:600,cursor:"pointer",fontFamily:t.font,background:x===A?"var(--accent-dim)":"transparent",color:x===A?t.accent:t.textMuted},children:_},A);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:[O("all","All"),O("project","Project"),O("me","Just me")]}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{type:"button",onClick:()=>S?T():b(!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:A=>u(A.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:A=>i(A.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:f,onChange:A=>d(A.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:T,style:{height:28,padding:"0 12px",borderRadius:7,border:`1px solid ${t.headerBorder}`,background:t.cellBg,color:t.textSecondary,fontSize:11.5,fontWeight:600,cursor:"pointer",fontFamily:t.font},children:"Cancel"}),s.jsx("button",{type:"button",onClick:()=>void y(),disabled:!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:C?"Update memory":"Save memory"})]})]}):null,s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:j.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."}):j.slice(0,30).map(A=>{const _=!["settings-ui","manual",""].includes(A.source),P=v(A.scope),$=_?`Saved from ${A.source}${typeof A.confidence=="number"?` · ${Math.round(A.confidence*100)}% confidence`:""}`:`Added by hand${A.tags.length?` · ${A.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:P.bg,color:P.color},children:P.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:A.content||A.title}),s.jsx("div",{style:{fontSize:10.5,color:t.textMuted,marginTop:4},children:$})]}),s.jsx("button",{type:"button",title:"Edit",onClick:()=>D(A),style:{flexShrink:0,width:25,height:25,borderRadius:6,border:"1px solid var(--border-subtle)",background:"var(--bg-1)",color:t.textMuted,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:11},children:"✎"}),s.jsx("button",{type:"button",title:"Stop using",onClick:()=>void m(A.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:"🗑"})]},A.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 hl({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(kk,{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 wk({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 kk({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 ml(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 Ck(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 Lr(e){return{display:"flex",alignItems:"center",gap:5,fontSize:12,color:e.textSecondary}}function Nr(e){const t=e.filter(r=>r.kind!=="connector").map(r=>gl({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=>gl({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 jk(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)=>us(r,"server",`servers[${o}]`))),Array.isArray(t.connectors)&&n.push(...t.connectors.map((r,o)=>us(r,"connector",`connectors[${o}]`))),Array.isArray(t.tools)&&n.push(...Ek(t.tools)),Array.isArray(t.mcp_servers)&&n.push(...Tk(t.mcp_servers)),Kn(t.mcpServers)&&n.push(...Rk(t.mcpServers)),n.map(Vn)}function Ek(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:io(t,["allowedTools","allowed_tools"]),enabled:!0,trusted:t.trusted===!0||t.require_approval==="never",providers:["openai"]})]:[us({...t,name:ct(t,["name","server_label","serverLabel"]),url:ct(t,["url","server_url","serverUrl"]),authorizationToken:o??Da(t.headers),allowedTools:io(t,["allowedTools","allowed_tools"]),enabled:!0,trusted:t.trusted===!0||t.require_approval==="never",providers:["openai"]},"server",`tools[${n}]`)]})}function Tk(e){return e.map((t,n)=>{const r=us(t,"server",`mcp_servers[${n}]`);return Vn({...r,authorizationToken:r.authorizationToken??(Kn(t)?ct(t,["authorization_token"]):void 0),providers:["anthropic"]})})}function Rk(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:Da(n.headers),enabled:n.enabled!==!1,trusted:n.trusted===!0,allowedTools:io(n,["allowedTools","allowed_tools"]),providers:Np(n,["providers"])??["openai","anthropic"]})})}function us(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"])??Da(e.headers),authorizationTokenEnv:ct(e,["authorizationTokenEnv","authorizationEnv","authorization_token_env"]),allowedTools:io(e,["allowedTools","allowed_tools"]),enabled:e.enabled!==!1,trusted:e.trusted===!0,deferLoading:e.deferLoading===!0||e.defer_loading===!0,providers:Np(e,["providers"])}}function gl(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 io(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 Np(e,t){const n=io(e,t);if(!n)return;const r=n.filter(o=>o==="openai"||o==="anthropic");return r.length?r:void 0}function Da(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 yl(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 Zs(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 Ak=e=>new Promise(t=>{window.setTimeout(t,e)});async function _k({jobId:e,loadStatus:t,onCompleted:n,onFailed:r,isCancelled:o=()=>!1,wait:i=Ak,intervalMs:c=700}){for(;!o();){if(await i(c),o())return;const a=await t();if(o())return;const l=a.job;if(!l||l.id!==e)return;if(!(l.state==="queued"||l.state==="running")){l.state==="completed"?await n(a):l.state==="failed"&&await r(a);return}}}function Ok(e){return/^(?:https?:\/\/|ssh:\/\/|git@|file:\/\/)/i.test(e.trim())}function Pk(e){const t=e.trim();return t?Ok(t)?{repoUrl:t}:{projectDir:t}:{}}const ei={auto:"Auto",native:"Native (DQL)","metricflow-cli":"Local MetricFlow","dbt-cloud":"dbt Cloud"};function Dk({compact:e=!1,reapplyRequired:t=!1,onConfigured:n}){var Zt,en,jn,En;const{state:r,dispatch:o}=et(),i=Qe[r.themeMode],[c,a]=p.useState(null),[l,u]=p.useState(!1),[f,d]=p.useState(""),[h,m]=p.useState(null),[S,b]=p.useState(null),[x,w]=p.useState("loading"),[C,k]=p.useState(null),[v,j]=p.useState(null),[D,T]=p.useState(""),[y,O]=p.useState(""),[A,_]=p.useState(""),[P,$]=p.useState(null),[q,G]=p.useState(null),[J,H]=p.useState(null),[L,M]=p.useState(""),[X,W]=p.useState(!1),te=p.useCallback(async()=>{const U=await B.getSemanticRuntimeSettings();return j(U),T(U.dbtCloud.host??""),O(U.dbtCloud.environmentId??""),_(""),U},[]),F=p.useCallback(async()=>{const U=await B.getMetricFlowInstallerStatus();return H(U),M(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)]);a(U),b(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&&k({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 _k({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=Zs(ve);if(!me)return;b(me),me.status==="completed"?(await K(),U&&k({ok:!0,text:me.message||"dbt metadata and governed search indexes are ready."})):me.status==="failed"||me.status==="cancelled"?k({ok:!1,text:me.error||me.message||`dbt preparation ${me.status}.`}):se=window.setTimeout(()=>void je(),650)}catch(ve){U&&k({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"),k(null);try{const U=await B.previewDbtOnboarding(Pk(f));m(U),k({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),k({ok:!1,text:U instanceof Error?U.message:String(U)})}finally{w(null)}},ee=async()=>{if(h){w("apply"),k(null);try{const U=await B.applyDbtOnboarding({...h.repoUrl?{repoUrl:h.repoUrl,branch:h.branch,subPath:h.subPath}:{projectDir:h.projectDir},manifestPath:h.manifestPath,profilesDir:h.profilesDir,expectedFingerprint:h.fingerprint}),se=Zs(U);se&&b(se);const je=await K();await F();const ve=je.preparation??se,me=`${h.counts.models??0} models · ${h.counts.sources??0} sources · ${h.counts.metrics??0} metrics`;k({ok:!0,text:(ve==null?void 0:ve.status)==="completed"?ve.message||`Connected ${h.projectName||h.projectDir}. Governed search is ready.`:ve?`Connected ${h.projectName||h.projectDir}. DQL is preparing ${me} for fast governed search in the background.`:`Applied ${h.projectName||h.projectDir}. ${me}.`}),n==null||n({name:h.projectName||"dbt project",path:h.projectDir,summary:me,readiness:(ve==null?void 0:ve.status)==="completed"?"ready":"preparing",readinessDetail:ve==null?void 0:ve.message}),m(null)}catch(U){k({ok:!1,text:U instanceof Error?U.message:String(U)})}finally{w(null)}}},ce=async()=>{w("refresh"),k(null);try{const U=await B.previewDbtOnboarding({}),se=await B.refreshDbtOnboarding({expectedFingerprint:U.fingerprint}),je=Zs(se);je&&b(je);const me=(await K()).preparation??je;k({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){k({ok:!1,text:U instanceof Error?U.message:String(U)})}finally{w(null)}},ke=()=>({preference:(v==null?void 0:v.preference)??"auto",dbtCloud:{host:D,environmentId:y,serviceToken:A}}),xe=async U=>{$("apply"),G(null);try{const se=await B.setSemanticRuntimePreference(U);j(se),G({ok:!0,text:`Preferred runtime set to ${ei[U]??U}.`})}catch(se){G({ok:!1,text:se instanceof Error?se.message:String(se)})}finally{$(null)}},Ie=async()=>{$("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{$(null)}},We=async()=>{$("apply"),G(null);try{const U=await B.applyDbtCloudSemanticRuntime(ke());j(U),_(""),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{$(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",It=t?"Review the prefilled project, choose Preview, then Reapply project.":(S==null?void 0:S.message)??(Ee?((en=c==null?void 0:c.dbt)==null?void 0:en.repoUrl)||((jn=c==null?void 0:c.dbt)==null?void 0:jn.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:x?"wait":"pointer",opacity:x?.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(cs,{size:17}):Ke?s.jsx(fv,{size:17}):Fe?s.jsx(qn,{className:"dql-dbt-preparing-icon",size:17}):Ee?s.jsx(lp,{size:17}):s.jsx(Dr,{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:It}),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:!!x,style:jt,children:[s.jsx(cs,{size:12,style:{verticalAlign:-2,marginRight:6}}),x==="refresh"?"Refreshing…":"Refresh"]}):null]}),s.jsx("style",{children:"@keyframes dql-dbt-preparing-spin { to { transform: rotate(360deg); } } .dql-dbt-preparing-icon { animation: dql-dbt-preparing-spin 1s linear infinite; } @media (prefers-reduced-motion: reduce) { .dql-dbt-preparing-icon { animation: none; } }"}),s.jsxs("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:12,background:i.cellBg,padding:16,display:"grid",gap:10},children:[s.jsxs("label",{style:{display:"grid",gap:5},children:[s.jsx("span",{style:{fontSize:11,fontWeight:650,color:i.textSecondary},children:"Local dbt project path or Git repository URL"}),s.jsx("input",{value:f,onChange:U=>{d(U.target.value),m(null)},placeholder:". or https://github.com/org/analytics.git",style:Ct})]}),h?s.jsxs("div",{style:{border:`1px solid ${i.headerBorder}`,borderRadius:8,padding:"10px 11px",color:i.textSecondary,fontSize:11.5,lineHeight:1.5},children:[s.jsx("strong",{style:{color:i.textPrimary},children:h.projectName||h.projectDir}),s.jsx("br",{}),h.counts.models??0," models · ",h.counts.sources??0," sources · ",h.counts.metrics??0," metrics",s.jsx("br",{}),s.jsx("span",{style:{fontFamily:i.fontMono},children:h.manifestPath})]}):null,C?s.jsx("div",{role:C.ok?"status":"alert",style:{fontSize:11.5,lineHeight:1.5,color:C.ok?"var(--status-success)":"var(--status-error)"},children:C.text}):null,s.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[s.jsx("button",{type:"button",onClick:()=>void oe(),disabled:!!x,style:jt,children:x==="preview"?"Inspecting…":"Preview"}),h?s.jsx("button",{type:"button",onClick:()=>void ee(),disabled:!!x,style:{...jt,border:"none",background:i.accent,color:"#fff"},children:x==="apply"?"Applying…":t?"Reapply project":"Apply project"}):null]})]}),s.jsxs("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:12,background:i.cellBg,padding:16,display:"grid",gap:12},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:13,fontWeight:700,color:i.textPrimary},children:"Semantic execution adapters"}),s.jsx("div",{style:{fontSize:11.5,color:i.textMuted,marginTop:3,lineHeight:1.5},children:"Adapter code is included with DQL. Auto selects one ready adapter in priority order: dbt Cloud, local MetricFlow, then native for simple metrics. Once selected, an adapter failure is shown directly and never silently downgraded."}),v!=null&&v.dbtCloud.configured?s.jsxs("div",{style:{fontSize:10.5,color:v.dbtCloud.targetBindingState==="bound"&&v.dbtCloud.metricInventoryState==="complete"?"var(--status-success)":"var(--status-warning)",marginTop:6,lineHeight:1.5},children:["dbt Cloud target: ",v.dbtCloud.targetBindingState==="bound"?`bound · ${(En=v.dbtCloud.executionTargetFingerprint)==null?void 0:En.slice(0,12)}`:"reapply required before execution",s.jsx("br",{}),"Metric inventory: ",v.dbtCloud.metricInventoryState,v.dbtCloud.semanticCatalogFingerprint?` · ${v.dbtCloud.semanticCatalogFingerprint.slice(0,12)}`:" · reapply required"]}):null,s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:10,flexWrap:"wrap"},children:[s.jsx("label",{style:{fontSize:11,fontWeight:700,color:i.textSecondary},children:"Preferred runtime"}),s.jsxs("select",{value:(v==null?void 0:v.preference)??"auto",onChange:U=>{xe(U.target.value)},disabled:P==="apply",style:{fontSize:11.5,padding:"4px 8px",borderRadius:7,border:"1px solid var(--border-subtle)",background:i.cellBg,color:i.textPrimary,fontFamily:i.font},children:[s.jsx("option",{value:"auto",children:"Auto (recommended)"}),s.jsx("option",{value:"dbt-cloud",children:"dbt Cloud"}),s.jsx("option",{value:"metricflow-cli",children:"Local MetricFlow"}),s.jsx("option",{value:"native",children:"Native (DQL)"})]}),v!=null&&v.runtime.active?s.jsxs("span",{style:{fontSize:10.5,color:i.textMuted},children:["Active: ",s.jsx("strong",{style:{color:i.textSecondary},children:ei[v.runtime.active]??v.runtime.active}),v.preference&&v.preference!=="auto"&&v.preference!==v.runtime.active?` (preferred ${ei[v.preference]??v.preference} is not ready)`:""]}):null]})]}),s.jsx("div",{style:{display:"grid",gap:7},children:((v==null?void 0:v.runtime.adapters)??[]).map(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}),(v==null?void 0:v.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=>M(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(dp,{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(`
440
+ `)})]}):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:D,onChange:U=>T(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:y,onChange:U=>O(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:A,onChange:U=>_(U.target.value),placeholder:(v==null?void 0:v.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 Ie(),disabled:!!P,style:jt,children:P==="test"?"Testing…":"Test draft"}),s.jsx("button",{type:"button",onClick:()=>void We(),disabled:!!P,style:{...jt,border:"none",background:i.accent,color:"#fff"},children:P==="apply"?"Testing & binding…":"Test, bind & save"})]})]})]})]})]})}function Wo(e){return e.map(t=>`${t.catalogOrDatabase}: ${t.schemas.join(", ")}`).join(`
441
+ `)}function ti(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 c=o.toLowerCase(),a=t.get(c)??{catalogOrDatabase:o,schemas:new Set};for(const l of i)a.schemas.add(l);t.set(c,a)}return Array.from(t.values()).map(n=>({catalogOrDatabase:n.catalogOrDatabase,schemas:Array.from(n.schemas)}))}function Ik(e,t,n){return e.some(r=>r.catalogOrDatabase.toLowerCase()===t.toLowerCase()&&r.schemas.some(o=>o.toLowerCase()===n.toLowerCase()))}function Mk(e,t,n,r){const o=new Map(e.map(a=>[a.catalogOrDatabase.toLowerCase(),{catalogOrDatabase:a.catalogOrDatabase,schemas:new Map(a.schemas.map(l=>[l.toLowerCase(),l]))}])),i=t.toLowerCase(),c=o.get(i)??{catalogOrDatabase:t,schemas:new Map};return r?c.schemas.set(n.toLowerCase(),n):c.schemas.delete(n.toLowerCase()),c.schemas.size>0?o.set(i,c):o.delete(i),Array.from(o.values()).map(a=>({catalogOrDatabase:a.catalogOrDatabase,schemas:Array.from(a.schemas.values())}))}function $k(e){return e.scopes.reduce((t,n)=>t+n.schemas.filter(r=>!r.inDbtProject).length,0)}const ni={duckdb:"DuckDB",file:"Local File / DuckDB",snowflake:"Snowflake",databricks:"Databricks"},Xo={duckdb:"#f4bc00",file:"#f4bc00",snowflake:"#29b5e8",databricks:"#ff3621"},Lk={duckdb:"In-process analytical database",file:"Local CSV / Parquet via DuckDB",snowflake:"Cloud data platform",databricks:"Lakehouse platform"},Os=[{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"}]}],Ia=Object.fromEntries(Os.map(e=>[e.driver,e])),Nk=[{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 Hr(e){return e==="postgres"?"postgresql":e}function zi(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 Bk(e){return`${e.profileName}_${e.targetName}`.toLowerCase().replace(/[^a-z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")||"dbt_profile"}function Fk(e){const t={};return Object.entries(e.connection??{}).forEach(([n,r])=>{n!=="driver"&&r!==void 0&&r!==null&&(t[zi(n)]=String(r))}),t}function zk(e){const n=e.indexOf("/.dbt/");return n>=0?`~${e.slice(n)}`:e.split("/").slice(-3).join("/")}function qk(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 bl(e,t){return e.startsWith("Error")||e.toLowerCase().includes("failed")?t.error:e.toLowerCase().includes("testing")?t.warning:t.success}function ao(e){const t=Hr(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 Uk(e,t,n,r){const o=r!==null&&r===t,i=!!(t&&e[t]),c=e[n];return r===null||o||!i||t==="default"&&ao(e.default)&&!ao(c)?n:t}function Wk(e){const t=Object.keys(e);return t.find(n=>!ao(e[n]))??t[0]}function Bp({variant:e="panel",onConfigured:t}={}){var Wa,Ka,Va,Ha,Ga;const n=Ge(Pr(I=>({settingsTab:I.settingsTab,themeMode:I.themeMode}))),r=kn(),o=Qe[n.themeMode],i=e==="page",c=e==="setup",[a,l]=p.useState(null),[u,f]=p.useState(!1),[d,h]=p.useState(null),[m,S]=p.useState(null),[b,x]=p.useState(!1),[w,C]=p.useState(!1),[k,v]=p.useState(null),[j,D]=p.useState(null),[T,y]=p.useState(""),[O,A]=p.useState(!1),[_,P]=p.useState(null),[$,q]=p.useState([]),[G,J]=p.useState(!1),[H,L]=p.useState(null),[M,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,Ie]=p.useState(!1),[We,Be]=p.useState(""),[Ee,ge]=p.useState("duckdb"),[Je,tt]=p.useState({}),[Fe,Ke]=p.useState("duckdb"),[gt,It]=p.useState({}),Ct=p.useRef(null);p.useEffect(()=>{B.getConnections().then(I=>{l(I),I.metadataScope&&(X(I.metadataScope.mode),te(Wo(I.metadataScope.selectedScopes??I.metadataScope.scopes)))})},[]);const jt=a?`${a.default}:${JSON.stringify(((Wa=a.connections)==null?void 0:Wa[a.default])??null)}`:"";p.useEffect(()=>{if(!a||i&&n.settingsTab!=="database"||!Object.values(a.connections).some(z=>!ao(z)))return;let I=!0;return f(!0),B.testConnection().then(z=>{I&&h(z)}).catch(z=>{I&&h({ok:!1,message:z instanceof Error?z.message:String(z)})}).finally(()=>{I&&f(!1)}),()=>{I=!1}},[jt,i,n.settingsTab]),p.useEffect(()=>{if(!i)return;let I=!0;return Promise.all([B.getProviderSettings(),B.getOnboardingStatus(),B.getBlockStudioDbtStatus().catch(()=>null)]).then(([z,ae,re])=>{var ue;I&&(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(()=>{}),()=>{I=!1}},[i]),p.useEffect(()=>{if(!i||!H||H.status!=="queued"&&H.status!=="running")return;let I=!0,z;const ae=async()=>{var re,ue,we;try{const Ve=await B.getOnboardingStatus();if(!I)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),()=>{I=!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(!a)return;const I=a.default,z=I?(re=a.connections)==null?void 0:re[I]:void 0,ae=z?`${I}::${JSON.stringify(z)}`:"::none";if(Ct.current!==ae)if(Ct.current=ae,z){Ke(Hr(String(z.driver??z.type??"duckdb")));const ue={};Object.entries(z).forEach(([we,Ve])=>{we!=="driver"&&we!=="type"&&(ue[zi(we)]=String(Ve??""))}),It(ue)}else Ke("duckdb"),It({})},[a]);const Zt=async()=>{if(!a||Object.keys(a.connections??{}).length===0){h({ok:!1,message:"Add or import a connection before testing."});return}f(!0),h(null);const I=await B.testConnection();h(I),I.ok&&(t==null||t(I.message)),f(!1)},en=I=>{l(z=>z&&{...z,metadataScope:I.scope,metadataStatus:I.status}),X(I.scope.mode),te(Wo(I.scope.selectedScopes??I.scope.scopes))},jn=async()=>{if(!(!(a!=null&&a.default)||!(d!=null&&d.ok))){Ie(!0),ee("Finding databases/catalogs and schemas visible to this connection…");try{const I=await B.discoverConnectionMetadataScopes(a.default);ke(I),ee(I.message)}catch(I){ke(null),ee(I instanceof Error?I.message:String(I))}finally{Ie(!1)}}},En=(I,z,ae)=>{const re=Mk(ti(W),I,z,ae);te(Wo(re)),X(((ce==null?void 0:ce.dbtScopes.length)??0)>0?"dbt_plus_selected":"selected_scopes")},U=async()=>{if(!(a!=null&&a.default))return;const I=ti(W);if(M==="selected_scopes"&&I.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(a.default,{mode:M,...M==="dbt_relations"?{}:{scopes:I}});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(a!=null&&a.default){K(!0),ee("Refreshing the applied metadata scope…");try{const I=await B.refreshConnectionMetadata(a.default);en(I),ee(`Refreshed · ${I.status.relationCount.toLocaleString()} relations · ${I.status.columnCount.toLocaleString()} columns`)}catch(I){ee(I instanceof Error?I.message:String(I))}finally{K(!1)}}},je=(I,z)=>{S(I),x(!1),Be(I),ge(Hr((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[zi(re)]=String(ue??""))}),tt(ae)},ve=()=>{x(!0),S(null),Be(""),ge("duckdb"),tt({})},me=()=>{S(null),x(!1)},tn=async I=>{D(I),v(null);try{const z=await B.installConnector(I);if(z.connectorStatus&&a)l({...a,connectorStatus:z.connectorStatus});else{const ae=await B.getConnections();l(ae)}v(z.ok?"Connector installed":`Error: ${z.error??"Install failed"}`)}catch(z){v(`Error: ${(z==null?void 0:z.message)??"Install failed"}`)}finally{D(null)}},ie=async I=>{if(!a)return!1;C(!0),v(null);const z=I.name.trim()||(I.previousName??"default"),ae={driver:I.driver},re=Ia[I.driver],ue=new Map(((re==null?void 0:re.fields)??[]).map(Ye=>[Ye.key,Ye]));Object.entries(I.fields).forEach(([Ye,nt])=>{const Tt=ue.get(Ye);if((Tt==null?void 0:Tt.type)==="checkbox"){nt!==""&&(ae[Ye]=nt==="true");return}const Ro=nt.trim();Ro&&((Tt==null?void 0:Tt.type)==="number"&&!isNaN(Number(Ro))?ae[Ye]=Number(Ro):ae[Ye]=Ro)});const we={...a.connections},Ve=a.default,Xn={...a.connections};I.previousName&&I.previousName!==z&&delete Xn[I.previousName],Xn[z]=ae;const mf=Uk(Xn,a.default,z,I.previousName);let Qa=!1;try{await B.saveConnections(Xn,mf);const Ye=await B.getConnections();l(Ye),Ye.metadataScope&&(X(Ye.metadataScope.mode),te(Wo(Ye.metadataScope.selectedScopes??Ye.metadataScope.scopes))),ke(null),v("Saved. Testing connection..."),S(null),x(!1);try{f(!0);const nt=await B.testConnection();if(h(nt),Qa=nt.ok,nt.ok)v("Test passed. Connection saved and activated."),t==null||t(nt.message),setTimeout(()=>v(null),2e3);else{await B.saveConnections(we,Ve||void 0);const Tt=await B.getConnections();l(Tt),v(`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),v(`Test failed. Previous connection preserved: ${nt.message??"Connection failed"}`)}finally{f(!1)}}catch(Ye){await B.saveConnections(we,Ve||void 0).catch(()=>{});const nt=await B.getConnections().catch(()=>null);nt&&l(nt),v(`Test or save failed. Previous connection preserved: ${Ye.message}`)}finally{C(!1)}return Qa},Y=I=>{const z=Hr(String(I.connection.driver??I.adapter??"duckdb")),ae=Fk(I);h(null),(i||c)&&(Ke(z),It(ae)),x(!1),S(null),ie({name:Bk(I),driver:z,fields:ae,previousName:null})},Me=async()=>{const I=T.trim();if(!I){P("Enter a profiles.yml file or folder path.");return}A(!0),P(null);try{const z=await B.previewDbtProfiles(I);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){P(z instanceof Error?z.message:"Could not read that profiles.yml path.")}finally{A(!1)}},Jn=()=>ie({name:We,driver:Ee,fields:Je,previousName:m}),Yn=()=>ie({name:(a==null?void 0:a.default)||"default",driver:Fe,fields:gt,previousName:(a==null?void 0:a.default)||null}),ko=I=>{Ke(I),It({}),h(null)},rf=async I=>{if(!a)return;const z={...a.connections};delete z[I];const ae=I===a.default?Wk(z):a.default;C(!0);try{await B.saveConnections(z,ae);const re=await B.getConnections();l(re),S(null)}finally{C(!1)}},of=async I=>{if(!a)return;const z=a.default;C(!0),v(null);try{await B.saveConnections(a.connections,I);const ae=await B.getConnections();l(ae),v("Default updated. Testing connection..."),f(!0);const re=await B.testConnection();if(h(re),re.ok)v("Test passed. Default connection updated."),t==null||t(re.message),setTimeout(()=>v(null),2e3);else{await B.saveConnections(a.connections,z||void 0);const ue=await B.getConnections();l(ue),v(`Test failed. Previous default preserved: ${re.message}`)}}catch(ae){await B.saveConnections(a.connections,z||void 0).catch(()=>{});const re=await B.getConnections().catch(()=>null);re&&l(re),v(`Test or save failed. Previous default preserved: ${ae.message}`)}finally{f(!1),C(!1)}},Co={fontSize:10,fontWeight:600,letterSpacing:"0.07em",textTransform:"uppercase",color:o.textMuted,fontFamily:o.font,marginBottom:6},jo={background:o.cellBg,border:`1px solid ${o.cellBorder}`,borderRadius:7,padding:"10px 12px",marginBottom:10},Eo=(a==null?void 0:a.connections)??{},sf=(a==null?void 0:a.default)??"",Na=(a==null?void 0:a.dbtProfiles)??[],Ba=Object.fromEntries(((a==null?void 0:a.connectorStatus)??[]).map(I=>[I.driver,I])),Fa=Object.keys(Eo).length,To=Fa>0,af=s.jsxs(s.Fragment,{children:[s.jsx("div",{style:Co,children:"Connections"}),a===null?s.jsx("div",{style:{fontSize:12,color:o.textMuted,fontFamily:o.font},children:"Loading…"}):Object.entries(Eo).map(([I,z])=>{const ae=(z==null?void 0:z.driver)??(z==null?void 0:z.type)??"unknown",re=I===sf,ue=Xo[ae]??o.accent;return m===I?s.jsx(xl,{t:o,editName:We,setEditName:Be,editDriver:Ee,setEditDriver:ge,editFields:Je,setEditFields:tt,onSave:Jn,onCancel:me,onDelete:()=>rf(I),saving:w,isNew:!1},I):s.jsxs("div",{style:{...jo,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(Vr,{driver:ae,size:18,fallbackColor:ue}),s.jsx("span",{style:{fontSize:12,fontWeight:600,color:o.textPrimary,fontFamily:o.font},children:ni[ae]??ae}),s.jsx("span",{style:{fontSize:11,fontFamily:o.fontMono,color:o.textMuted},children:I}),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:()=>of(I),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(I,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:qk(we)?"••••••••":String(Ve)})]},we))})]},I)}),a!==null&&Fa===0&&s.jsx("div",{style:{...jo,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."})]}),za=s.jsxs("div",{style:{...jo,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:T,onChange:I=>y(I.target.value),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),Me())},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 Me(),disabled:O,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:O?"wait":"pointer"},children:O?"Reading…":"Find profiles"})]}),_?s.jsx("div",{role:"alert",style:{marginTop:6,color:o.error,fontSize:10.5,fontFamily:o.font},children:_}):null]}),qa=s.jsx(s.Fragment,{children:!b&&!m&&Na.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{...Co,marginTop:8},children:"dbt profiles"}),s.jsx("div",{style:{display:"grid",gap:8,marginBottom:12},children:Na.map(I=>{var we;const z=Hr(String(I.connection.driver??I.adapter)),ae=Xo[z]??o.accent,re=I.missingFields.length===0,ue=((we=a==null?void 0:a.activeConnection)==null?void 0:we.source)==="dbt_profile"&&a.activeConnection.profileId===I.id;return s.jsxs("div",{style:{...jo,marginBottom:0,display:"flex",alignItems:"center",gap:10},children:[s.jsx(Vr,{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:I.profileName}),s.jsx("span",{style:{fontSize:11,color:o.textMuted,fontFamily:o.fontMono},children:I.targetName})]}),s.jsxs("div",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[ni[z]??I.adapter," from ",zk(I.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 ${I.missingFields.join(", ")}`})]}),s.jsx("button",{onClick:()=>Y(I),disabled:w,title:I.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"})]},I.id)})})]})}),cf=s.jsx(s.Fragment,{children:!b&&!m&&Object.keys(Eo).length===0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{...Co,marginTop:8},children:"Quick Connect"}),s.jsx("div",{style:{display:"grid",gap:6,marginBottom:12},children:Nk.map(I=>s.jsxs("button",{onClick:async()=>{C(!0);try{const z={...Eo,[I.name]:I.config};await B.saveConnections(z,I.name);const ae=await B.getConnections();l(ae),f(!0);const re=await B.testConnection();h(re),f(!1)}finally{C(!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(Vr,{driver:I.config.driver,size:18}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:12,fontWeight:600,color:o.textPrimary,fontFamily:o.font},children:I.label}),s.jsx("div",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:I.description})]})]},I.name))})]})}),lf=s.jsx(s.Fragment,{children:b?s.jsx(xl,{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"]})}),df=s.jsx(s.Fragment,{children:k&&s.jsx("div",{style:{fontSize:11,fontFamily:o.font,padding:"4px 10px",borderRadius:4,marginBottom:8,color:bl(k,o),background:`${bl(k,o)}12`},children:k})}),uf=s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:Zt,disabled:u||!To,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||!To?"not-allowed":"pointer",marginBottom:8,opacity:u||!To?.7:1,transition:"all 0.15s"},children:u?"Testing...":To?"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]})]}),pf=s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{...Co,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:Os.map(({driver:I,label:z})=>{const ae=Xo[I]??o.accent,re=Lk[I]??"",ue=Ba[I],we=(ue==null?void 0:ue.installed)??!0,Ve=(ue==null?void 0:ue.builtIn)??!1,Xn=j===I;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(Vr,{driver:I,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(I),disabled:!!j,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:j?"not-allowed":"pointer",whiteSpace:"nowrap"},children:Xn?"Installing...":"Install"})]}),s.jsx("code",{style:{fontSize:9,color:o.textMuted,fontFamily:o.fontMono},children:I})]},I)})})]}),Et=!!(a&&Object.values(a.connections??{}).some(I=>!ao(I))),$e=a==null?void 0:a.metadataStatus,ff=ti(W),hf=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 jn(),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((I,z)=>I+z.schemas.length,0).toLocaleString()," dbt-covered schema(s)"," · ",$k(ce).toLocaleString()," additional schema(s) available"," · ",ce.queryCount.toLocaleString()," discovery query(s)"]}),ce.scopes.map(I=>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:I.catalogOrDatabase}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(210px, 1fr))",gap:5},children:I.schemas.map(z=>{const ae=Ik(ff,I.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=>En(I.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"]})]},`${I.catalogOrDatabase}.${z.name}`)})})]},I.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:M,onChange:I=>X(I.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"})]})]}),M!=="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:I=>te(I.target.value),disabled:F,placeholder:`ANALYTICS_PROD: SALES, FINANCE
442
+ REFERENCE_DATA: SHARED`,rows:4,style:{resize:"vertical",borderRadius:7,border:`1px solid ${o.cellBorder}`,background:o.cellBg,color:o.textPrimary,padding:"8px 10px",fontFamily:o.fontMono,fontSize:11.5,lineHeight:1.5}}),s.jsx("span",{style:{fontSize:10.5,color:o.textMuted},children:"Only additional schemas outside dbt belong here. Discovery is explicit and setup-only; Ask AI never scans the warehouse for available schemas."})]}):null,$e?s.jsxs("div",{style:{fontSize:11.5,color:$e.state==="ready"?"var(--status-success)":"var(--status-warning)",fontFamily:o.font},children:[$e.state==="ready"?"Warehouse metadata index ready":$e.state==="stale"?"Warehouse metadata refresh required":G?"Optional warehouse metadata index not synchronized · dbt project objects remain available":"Warehouse metadata index not synchronized"," · ",$e.relationCount.toLocaleString()," indexed warehouse relations"," · ",$e.columnCount.toLocaleString()," indexed warehouse columns",$e.capturedAt?` · ${new Date($e.capturedAt).toLocaleString()}`:""]}):null,$e!=null&&$e.observedTarget?s.jsx("div",{style:{fontSize:10.5,color:o.textMuted,fontFamily:o.fontMono},children:[$e.observedTarget.accountOrWorkspace,$e.observedTarget.role,$e.observedTarget.warehouse,$e.observedTarget.defaultCatalogOrDatabase,$e.observedTarget.defaultSchema].filter(Boolean).join(" · ")}):null,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||($e==null?void 0:$e.state)==="missing",style:{height:32,padding:"0 13px",borderRadius:8,border:`1px solid ${o.cellBorder}`,background:o.cellBg,color:o.textSecondary,fontSize:12,fontWeight:650,cursor: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,Ua=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(So,{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:[ni[String(((Va=(Ka=a==null?void 0:a.connections)==null?void 0:Ka[(a==null?void 0:a.default)??""])==null?void 0:Va.driver)??"")]??((Ga=(Ha=a==null?void 0:a.connections)==null?void 0:Ha[(a==null?void 0:a.default)??""])==null?void 0:Ga.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:[za,qa]}),s.jsx(Gk,{t:o,driver:Fe,fields:gt,onDriverChange:ko,onFieldsChange:It,onSave:()=>void Yn(),saving:w,saveMessage:k,connectorStatus:Ba[Fe],installing:j===Fe,onInstall:()=>void tn(Fe)}),hf]});if(c)return Ua;if(i){const I=n.settingsTab,z=$.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:Vk}),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(I==="overview","Overview",()=>r({type:"SET_SETTINGS_TAB",tab:"overview"})),ae(I==="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(I==="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(I==="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(I==="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(I==="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:I==="overview"?s.jsx(Kk,{dbtConfigured:G,dbtPreparation:H,databaseConfigured:Et,databaseTest:d,providers:$}):I==="project"?s.jsx(Dk,{onConfigured:()=>{J(!0),B.getOnboardingStatus().then(re=>L(re.preparation??null)).catch(()=>{})}}):I==="advanced"?s.jsx(Ys,{embedded:!0,section:"advanced"}):I==="database"?Ua:I==="ai"?s.jsx(Ys,{embedded:!0,section:"providers",onProviderConfigured:re=>q(ue=>ue.map(we=>we.id===re.id?re:{...we,active:!1}))}):s.jsx(Ys,{embedded:!0,section:"memory"})})]})]})}return s.jsxs(ka,{title:"Connections",bodyPadding:12,children:[af,za,qa,cf,lf,df,uf,pf]})}function Kk({dbtConfigured:e,dbtPreparation:t,databaseConfigured:n,databaseTest:r,providers:o}){const i=Ge(d=>d.themeMode),c=kn(),a=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(Dr,{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(So,{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(hp,{size:18}),optional:!0}],f={missing:"Missing",configured:"Configured",preparing:"Preparing",passed:"Test passed",failed:"Test failed"};return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:820},children:[s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:16},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:20,fontWeight:750,color:a.textPrimary},children:"Settings overview"}),s.jsx("div",{style:{fontSize:12.5,color:a.textMuted,marginTop:4,lineHeight:1.5},children:"One place for project, data, AI, memory, and advanced runtime configuration."})]}),s.jsxs("button",{type:"button",onClick:()=>c({type:"OPEN_SETUP"}),style:{display:"inline-flex",alignItems:"center",gap:7,height:34,padding:"0 15px",borderRadius:8,border:"none",background:a.accent,color:"#fff",fontSize:12,fontWeight:700,cursor:"pointer",fontFamily:a.font,whiteSpace:"nowrap"},children:[s.jsx(SS,{size:14})," Guided Setup"]})]}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(210px, 1fr))",gap:12},children:u.map(d=>{const h=d.state==="configured"||d.state==="passed",m=d.state==="preparing",S=d.state==="failed",b=S?"var(--status-error)":m?"var(--status-info)":h?"var(--status-success)":"var(--status-warning)",x=S?"var(--status-error-bg)":m?"var(--status-info-bg)":h?"var(--status-success-bg)":"var(--status-warning-bg)";return s.jsxs("button",{type:"button",onClick:()=>c({type:"SET_SETTINGS_TAB",tab:d.tab}),style:{border:"1px solid var(--border-subtle)",borderRadius:12,background:a.cellBg,padding:16,textAlign:"left",cursor:"pointer",fontFamily:a.font,minHeight:158,display:"flex",flexDirection:"column"},children:[s.jsx("span",{style:{width:36,height:36,borderRadius:9,display:"inline-flex",alignItems:"center",justifyContent:"center",color:b,background:x},children:h?s.jsx(lp,{size:18}):d.icon}),s.jsx("span",{style:{fontSize:13.5,fontWeight:700,color:a.textPrimary,marginTop:12},children:d.title}),s.jsxs("span",{style:{fontSize:11,fontWeight:700,color:b,marginTop:4},children:[f[d.state],d.optional?" · optional":""]}),s.jsx("span",{style:{fontSize:11.5,color:a.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:a.textSecondary,borderRadius:10,padding:"11px 13px",fontSize:11.5,lineHeight:1.5},children:"Limited-AI mode is active: SQL execution, dbt metadata, lineage, deterministic helpers, and other non-AI paths continue to work. Configure a provider when you want governed Ask and AI-assisted authoring."})]})}const Vk=`
443
+ .dql-connection-page-stack {
444
+ display: grid;
445
+ gap: 16px;
446
+ }
447
+
448
+ .dql-connection-page-grid {
449
+ display: grid;
450
+ grid-template-columns: minmax(0, 1.18fr) minmax(320px, 0.82fr);
451
+ gap: 16px;
452
+ align-items: start;
453
+ }
454
+
455
+ @media (max-width: 920px) {
456
+ .dql-connection-page-grid {
457
+ grid-template-columns: minmax(0, 1fr);
458
+ }
459
+ }
460
+
461
+ @keyframes dql-connector-shimmer {
462
+ 0% { opacity: 1; }
463
+ 50% { opacity: 0.45; }
464
+ 100% { opacity: 1; }
465
+ }
466
+
467
+ .dql-connector-installing {
468
+ animation: dql-connector-shimmer 1.4s ease-in-out infinite;
469
+ }
470
+ `;function xl({t:e,editName:t,setEditName:n,editDriver:r,setEditDriver:o,editFields:i,setEditFields:c,onSave:a,onCancel:l,onDelete:u,saving:f,isNew:d}){const h=Ia[r],m=(h==null?void 0:h.fields)??[],S={background:e.inputBg,border:`1px solid ${e.inputBorder}`,borderRadius:4,color:e.textPrimary,fontSize:11,fontFamily:e.fontMono,padding:"4px 8px",outline:"none",width:"100%"},b={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:b,children:"Name"}),s.jsx("input",{style:S,value:t,onChange:x=>n(x.target.value),placeholder:"e.g. production"})]}),s.jsxs("div",{style:{marginBottom:6},children:[s.jsx("div",{style:b,children:"Driver"}),s.jsx("select",{style:{...S,fontFamily:e.font},value:r,onChange:x=>{o(x.target.value),c({})},children:Os.map(x=>s.jsx("option",{value:x.driver,children:x.label},x.driver))})]}),m.map(x=>s.jsxs("div",{style:{marginBottom:6},children:[s.jsxs("div",{style:b,children:[x.label,x.required?" *":""]}),x.type==="select"?s.jsxs("select",{style:{...S,fontFamily:e.font},value:i[x.key]??"",onChange:w=>c({...i,[x.key]:w.target.value}),children:[s.jsx("option",{value:"",children:"Default"}),(x.options??[]).map(w=>s.jsx("option",{value:w.value,children:w.label},w.value))]}):x.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[x.key]==="true",onChange:w=>c({...i,[x.key]:w.target.checked?"true":"false"})}),"Enabled"]}):x.type==="textarea"?s.jsx("textarea",{style:{...S,minHeight:72,resize:"vertical"},value:i[x.key]??"",placeholder:x.placeholder??"",onChange:w=>c({...i,[x.key]:w.target.value})}):s.jsx("input",{style:S,type:x.type==="password"?"password":x.type==="number"?"number":"text",value:i[x.key]??"",placeholder:x.placeholder??"",onChange:w=>c({...i,[x.key]:w.target.value})}),x.helpText&&s.jsx("div",{style:{fontSize:10,color:e.textMuted,fontFamily:e.font,marginTop:3,lineHeight:1.35},children:x.helpText})]},x.key)),s.jsxs("div",{style:{display:"flex",gap:6,marginTop:8},children:[s.jsx("button",{onClick:a,disabled:f,style:{flex:1,padding:"5px 0",borderRadius:5,border:"none",background:e.accent,color:"#fff",fontSize:11,fontFamily:e.font,fontWeight:600,cursor:f?"not-allowed":"pointer",opacity:f?.6:1},children:f?"Saving…":"Save"}),s.jsx("button",{onClick: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 Hk(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 vl=new Set(["filepath","httpPath","accessUrl"]);function Gk({t:e,driver:t,fields:n,onDriverChange:r,onFieldsChange:o,onSave:i,saving:c,saveMessage:a,connectorStatus:l,installing:u,onInstall:f}){const[d,h]=p.useState(!1),m=Ia[t],S=(m==null?void 0:m.fields)??[],b=Hk(t,n),x=new Set(b),w=S.filter(v=>x.has(v.key)),C=S.filter(v=>!x.has(v.key)),k=(v,j)=>o({...n,[v]:j});return s.jsxs("div",{style:{border:`1px solid ${e.cellBorder}`,borderRadius:12,background:e.cellBg,padding:18,display:"flex",flexDirection:"column",gap:13,maxWidth:640},children:[s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4,maxWidth:280},children:[s.jsx("span",{style:{fontSize:11,fontWeight:650,color:e.textSecondary,fontFamily:e.font},children:"Warehouse"}),s.jsx("select",{value:t,onChange:v=>r(v.target.value),style:{border:`1px solid ${e.cellBorder}`,background:e.cellBg,borderRadius:8,padding:"8px 9px",fontSize:12.5,fontFamily:e.font,color:e.textPrimary,outline:"none"},children:Os.map(({driver:v,label:j})=>s.jsx("option",{value:v,children:j},v))})]}),s.jsx(Qk,{t:e,driver:t,label:(m==null?void 0:m.label)??t,status:l,installing:u,onInstall:f}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:w.map(v=>s.jsx(Sl,{t:e,field:v,value:n[v.key]??"",onChange:j=>k(v.key,j),fullWidth:vl.has(v.key)},v.key))}),C.length>0&&s.jsxs("details",{open:d,onToggle:v=>h(v.target.open),style:{borderTop:`1px solid ${e.headerBorder}`,paddingTop:12},children:[s.jsxs("summary",{style:{cursor:"pointer",listStyle:"none",display:"flex",alignItems:"center",gap:7,fontSize:11.5,fontWeight:650,color:e.textSecondary,fontFamily:e.font},children:[s.jsx("span",{style:{color:e.textMuted,fontSize:10,transform: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:[C.length," more"]})]}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginTop:12},children:C.map(v=>s.jsx(Sl,{t:e,field:v,value:n[v.key]??"",onChange:j=>k(v.key,j),fullWidth:vl.has(v.key)||v.type==="textarea"},v.key))})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,paddingTop:4,borderTop:`1px solid ${e.headerBorder}`},children:[s.jsx("span",{style:{fontSize:10.5,color:e.textMuted,flex:1,fontFamily:e.font},children:a??"Changes apply after a successful test."}),s.jsx("button",{type:"button",onClick:i,disabled:c,style:{height:30,padding:"0 15px",borderRadius:8,border:"none",background:e.accent,color:"#fff",fontSize:12,fontWeight:650,cursor:c?"not-allowed":"pointer",fontFamily:e.font,boxShadow:"0 1px 4px rgba(107,93,211,0.25)",opacity:c?.7:1},children:c?"Saving…":"Save connection"})]})]})}function Qk({t:e,driver:t,label:n,status:r,installing:o,onInstall:i}){const c=(r==null?void 0:r.builtIn)??!0,a=(r==null?void 0:r.installed)??!0,l=!a&&!c,u=o||l?e.warning:e.success,f=o||l?"var(--status-warning-bg)":"var(--status-success-bg)",d=o||l?"var(--status-warning-border)":"var(--status-success-border)",h=o?"Installing connector package…":c?"Built in — no installation needed":a?"Connector installed and ready":"Connector package required before you can connect";return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,border:`1px solid ${d}`,borderRadius:9,background:f,padding:"10px 12px"},children:[s.jsx(Vr,{driver:t,size:18,fallbackColor:Xo[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:h})]}),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"})}),c?"Ready":"Installed"]})]})}function Sl({t:e,field:t,value:n,onChange:r,fullWidth:o}){const[i,c]=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},f=s.jsxs("span",{style:{fontSize:11,fontWeight:650,color:e.textSecondary,fontFamily:e.font},children:[t.label,t.required?" *":""]});return t.type==="checkbox"?s.jsxs("label",{style:{...u,flexDirection:"row",alignItems:"center",gap:8},children:[s.jsx("input",{type:"checkbox",checked:n==="true",onChange:d=>r(d.target.checked?"true":"false")}),f]}):s.jsxs("label",{style:u,children:[f,t.type==="select"?s.jsxs("select",{value:n,onChange:d=>r(d.target.value),onFocus:()=>c(!0),onBlur:()=>c(!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:()=>c(!0),onBlur:()=>c(!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:()=>c(!0),onBlur:()=>c(!1),style:l}),t.helpText&&s.jsx("span",{style:{fontSize:10,color:e.textMuted,fontFamily:e.font,lineHeight:1.35},children:t.helpText})]})}const Jk=Object.freeze(Object.defineProperty({__proto__:null,ConnectionPanel:Bp},Symbol.toStringTag,{value:"Module"}));function Yk({type:e}){const t=yw[e]??"#8b949e";return s.jsx("span",{style:{color:t,fontSize:10,fontWeight:700,textTransform:"uppercase",minWidth:34},title:bp[e]??e,children:bw[e]??e.slice(0,4).toUpperCase()})}function Xk({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 Fp({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(Yk,{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 Zk=30,ri=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 oi({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>Zk,[c,a]=p.useState(!i),[l,u]=p.useState(ri);if(t.length===0)return null;const f=c?Math.min(l,t.length):0,d=Math.max(0,t.length-f);return s.jsxs("div",{style:{padding:"8px 0",borderTop:`1px solid ${n.headerBorder}`},children:[s.jsxs("button",{onClick:()=>a(h=>!h),"aria-expanded":c,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:c?"▾":"▸"}),s.jsx("span",{children:e}),s.jsx("span",{style:{marginLeft:"auto",fontWeight:500},children:t.length})]}),c&&t.slice(0,f).map(h=>s.jsx(Fp,{node:h,t:n,onClick:()=>r(h),secondary:o==null?void 0:o(h)},h.id)),c&&d>0&&s.jsxs("button",{onClick:()=>u(h=>h+ri),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(ri,d)," more (",d," hidden)"]})]})}function e1({variant:e="sidebar"}){const{state:t,dispatch:n}=et(),r=Qe[t.themeMode],o=e==="page",[i,c]=p.useState(()=>typeof window<"u"?window.innerWidth<700:!1),[a,l]=p.useState(!0),[u,f]=p.useState([]),[d,h]=p.useState([]),[m,S]=p.useState(""),[b,x]=p.useState([]),w=p.useCallback(async()=>{l(!0);const y=await B.fetchLineage();f(y.nodes??[]),h(y.edges??[]),l(!1)},[]);p.useEffect(()=>{w()},[w]),p.useEffect(()=>{if(!o)return;const y=()=>c(window.innerWidth<700);return y(),window.addEventListener("resize",y),()=>window.removeEventListener("resize",y)},[o]),p.useEffect(()=>{let y=!1;if(m.trim().length<2){x([]);return}return B.searchLineage(m.trim()).then(O=>{y||x(O.matches??[])}),()=>{y=!0}},[m]);const C=p.useCallback(y=>{n({type:"OPEN_LINEAGE_DETAIL",nodeId:y.id})},[n]),[k,v]=p.useState("type"),j=p.useMemo(()=>({terms:u.filter(y=>y.type==="term"),businessViews:u.filter(y=>y.type==="business_view"),dashboards:u.filter(y=>y.type==="dashboard"),notebooks:u.filter(y=>y.type==="notebook"),apps:u.filter(y=>y.type==="app"),charts:u.filter(y=>y.type==="chart"),blocks:u.filter(y=>y.type==="block"),metrics:u.filter(y=>y.type==="metric"),dimensions:u.filter(y=>y.type==="dimension"),dbtModels:u.filter(y=>y.type==="dbt_model"),dbtSources:u.filter(y=>y.type==="dbt_source"),tables:u.filter(y=>y.type==="source_table"),domains:u.filter(y=>y.type==="domain")}),[u]),D=p.useMemo(()=>({businessNodes:j.terms.length+j.businessViews.length,businessEdges:d.filter(y=>y.type==="defines"||y.type==="composes").length,technicalNodes:j.tables.length+j.dbtSources.length+j.dbtModels.length+j.metrics.length+j.dimensions.length+j.blocks.length,consumptionNodes:j.charts.length+j.notebooks.length+j.dashboards.length+j.apps.length}),[d,j]),T=p.useMemo(()=>{const y={source:[],transform:[],answer:[],consumption:[]};for(const O of u){const A=Sw(O);y[A].push(O)}return y},[u]);return a?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(Jr,{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(Xk,{value:m,onChange:S,placeholder:"Search lineage...",t:r})}),s.jsxs("div",{style:{flex:1,overflow:"auto"},children:[m.trim().length>=2&&b.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"}),b.slice(0,8).map(y=>s.jsx(Fp,{node:y.node,t:r,onClick:()=>C(y.node),secondary:y.node.domain},y.node.id))]}),s.jsxs("div",{style:{padding:"8px 12px",display:"grid",gridTemplateColumns:o&&!i?"repeat(3, minmax(0, 1fr))":"1fr",gap:6,borderBottom:`1px solid ${r.headerBorder}`},children:[s.jsx(oi,{Icon:rv,label:"Business",value:D.businessNodes,detail:`${j.terms.length} terms · ${j.businessViews.length} views · ${D.businessEdges} edges`,t:r}),s.jsx(oi,{Icon:So,label:"Technical",value:D.technicalNodes,detail:`${j.tables.length} tables · ${j.dbtModels.length+j.dbtSources.length} dbt · ${j.blocks.length} blocks`,t:r}),s.jsx(oi,{Icon:rS,label:"Consumption",value:D.consumptionNodes,detail:`${j.dashboards.length} dashboards · ${j.notebooks.length} notebooks · ${j.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:[Gc.map(y=>{const O=T[y].length;return O===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:xw[y],display:"inline-block"}}),Hc[y],": ",O]},y)}),s.jsx("span",{style:{flex:1}}),s.jsxs("div",{style:{display:"flex",borderRadius:4,border:`1px solid ${r.headerBorder}`,overflow:"hidden"},children:[s.jsx("button",{onClick:()=>v("type"),style:{padding:"2px 6px",fontSize:9,fontWeight:700,border:"none",cursor:"pointer",background:k==="type"?`${r.headerBorder}`:"transparent",color:k==="type"?r.textPrimary:r.textMuted},children:"Type"}),s.jsx("button",{onClick:()=>v("layer"),style:{padding:"2px 6px",fontSize:9,fontWeight:700,border:"none",cursor:"pointer",borderLeft:`1px solid ${r.headerBorder}`,background:k==="layer"?`${r.headerBorder}`:"transparent",color:k==="layer"?r.textPrimary:r.textMuted},children:"Layer"})]})]}),k==="type"?s.jsxs(s.Fragment,{children:[s.jsx(ot,{title:"Business Terms",nodes:j.terms,t:r,onSelect:C,secondaryFor:ut}),s.jsx(ot,{title:"Business Views",nodes:j.businessViews,t:r,onSelect:C,secondaryFor:ut}),s.jsx(ot,{title:"DQL Blocks",nodes:j.blocks,t:r,onSelect:C,secondaryFor:ut}),s.jsx(ot,{title:"Metrics",nodes:j.metrics,t:r,onSelect:C,secondaryFor:ut}),s.jsx(ot,{title:"Dimensions",nodes:j.dimensions,t:r,onSelect:C,secondaryFor:ut}),s.jsx(ot,{title:"Dashboards",nodes:j.dashboards,t:r,onSelect:C,secondaryFor:ut}),s.jsx(ot,{title:"Notebooks",nodes:j.notebooks,t:r,onSelect:C,secondaryFor:ut}),s.jsx(ot,{title:"Apps",nodes:j.apps,t:r,onSelect:C,secondaryFor:ut}),s.jsx(ot,{title:"Charts",nodes:j.charts,t:r,onSelect:C,secondaryFor:ut}),s.jsx(ot,{title:"dbt Models",nodes:j.dbtModels,t:r,onSelect:C,secondaryFor:ut}),s.jsx(ot,{title:"dbt Sources",nodes:j.dbtSources,t:r,onSelect:C,secondaryFor:ut}),s.jsx(ot,{title:"Source Tables",nodes:j.tables,t:r,onSelect:C,secondaryFor:ut}),s.jsx(ot,{title:"Business Domains",nodes:j.domains,t:r,onSelect:C,secondaryFor:ut})]}):s.jsx(s.Fragment,{children:Gc.map(y=>s.jsx(ot,{title:Hc[y],nodes:T[y],t:r,onSelect:C},y))})]})]})}function t1({diff:e,diffReport:t,activeFilePath:n,diffPath:r,onScopeToFile:o,onClearScope:i,t:c}){const a=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:kl(r==null,c),children:"All"}),n&&s.jsx("button",{onClick:o,style:kl(r===n,c),children:"Active file"}),r&&s.jsx("span",{style:{color:c.textMuted,fontSize:10,alignSelf:"center",fontFamily:c.fontMono},children:r})]}),a&&s.jsx(n1,{report:t,t:c}),!a&&l&&s.jsx(s1,{diff:e,t:c}),!a&&!l&&s.jsx("div",{style:{color:c.textMuted},children:t&&t.identical?"No semantic changes.":"No unstaged changes."})]})}function n1({report:e,t}){return s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.changes.map((n,r)=>s.jsx(r1,{change:n,t},r))})}function r1({change:e,t}){const{marker:n,color:r,label:o}=i1(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((c,a)=>s.jsx(o1,{field:c,t},a))})]})}function o1({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:wl(e.before)}),s.jsx("span",{style:{color:t.textMuted},children:" → "}),s.jsx("span",{style:{color:t.success},children:wl(e.after)})]})}function s1({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(`
471
+ `).map((n,r)=>s.jsx("div",{style:{color:a1(n,t)},children:n||" "},r))})}function i1(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 ${si(e.id,e.name)} [${e.cellType}]`};case"cell-removed":return{...n,label:`cell ${si(e.id,e.name)} [${e.cellType}]`};case"cell-changed":return{...r,label:`cell ${si(e.id,e.name)}`};case"notebook-changed":return{...r,label:"notebook"}}}function si(e,t){return t?`"${t}" (${e.slice(0,8)})`:e.slice(0,8)}function wl(e,t=60){if(e==null)return"∅";const n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}…`:n}function kl(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 a1(e,t){return e.startsWith("+++")||e.startsWith("---")?t.textMuted:e.startsWith("+")?t.success:e.startsWith("-")?t.error:e.startsWith("@@")?t.accent:t.textPrimary}const c1=2e3,l1={modified:{label:"Modified",color:e=>e.warning,Icon:_v},added:{label:"Added",color:e=>e.success,Icon:up},deleted:{label:"Deleted",color:e=>e.error,Icon:$v},renamed:{label:"Renamed",color:e=>e.accent,Icon:Hx},untracked:{label:"Untracked",color:e=>e.textMuted,Icon:Dv}},Cl=["modified","added","renamed","deleted","untracked"];function d1(e){const t=e.trim();return t==="??"?"untracked":t.startsWith("R")?"renamed":t.includes("D")?"deleted":t.includes("A")?"added":"modified"}function u1(){var D;const{state:e}=et(),t=Qe[e.themeMode],[n,r]=p.useState("status"),[o,i]=p.useState(null),[c,a]=p.useState(null),[l,u]=p.useState(""),[f,d]=p.useState(null),[h,m]=p.useState(null),[S,b]=p.useState(!1),[x,w]=p.useState(!1),C=p.useCallback(async()=>{b(!0),w(!0);try{if(n==="status")i(await B.fetchGitStatus());else if(n==="log")a(await B.fetchGitLog(30));else{const T=await B.fetchGitDiff(h??void 0);u(T.diff),d(T.diffReport)}}finally{b(!1),window.setTimeout(()=>w(!1),400)}},[n,h]);p.useEffect(()=>{C()},[C]),p.useEffect(()=>{if(n!=="status")return;const T=window.setInterval(()=>{B.fetchGitStatus().then(y=>{i(O=>p1(O,y)?O:y)})},c1);return()=>window.clearInterval(T)},[n]);const k=((D=e.activeFile)==null?void 0:D.path)??null,v=s.jsxs("button",{onClick:()=>void C(),title:"Refresh","aria-label":"Refresh",style:{background:"transparent",border:`1px solid ${t.btnBorder}`,cursor:"pointer",color:t.textMuted,padding:"3px 6px",borderRadius:4,display:"flex",alignItems:"center",justifyContent:"center"},children:[s.jsx(cs,{size:12,strokeWidth:1.75,style:{animation:x?"dql-spin 0.6s linear":void 0}}),s.jsx("style",{children:"@keyframes dql-spin { to { transform: rotate(360deg); } }"})]}),j=s.jsxs(ap,{children:[s.jsx(ii,{t,active:n==="status",onClick:()=>r("status"),children:"Status"}),s.jsx(ii,{t,active:n==="log",onClick:()=>r("log"),children:"History"}),s.jsx(ii,{t,active:n==="diff",onClick:()=>r("diff"),children:"Diff"})]});return s.jsxs(ka,{title:"Git",actions:v,toolbar:j,bodyPadding:12,children:[S&&!o&&!c&&s.jsx(Jr,{title:"Loading…"}),n==="status"&&o&&s.jsx(f1,{status:o,t}),n==="log"&&c&&s.jsx(b1,{log:c,t}),n==="diff"&&s.jsx(t1,{diff:l,diffReport:f,activeFilePath:k,diffPath:h,onScopeToFile:()=>m(k),onClearScope:()=>m(null),t})]})}function p1(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 f1({status:e,t}){const n=p.useMemo(()=>{const r={modified:[],added:[],deleted:[],renamed:[],untracked:[]};for(const o of e.changes)r[d1(o.status)].push(o);for(const o of Cl)r[o].sort((i,c)=>i.path.localeCompare(c.path));return r},[e.changes]);return e.inRepo?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[s.jsx(h1,{status:e,t}),e.changes.length===0?s.jsx(m1,{t}):Cl.map(r=>{const o=n[r];return o.length===0?null:s.jsx(g1,{group:r,items:o,t},r)})]}):s.jsx(zp,{t})}function h1({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(Dr,{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:ai(t.success,t),children:[s.jsx(Qx,{size:11,strokeWidth:2})," ",n]}),r>0&&s.jsxs("span",{title:`${r} commit(s) behind upstream`,style:ai(t.warning,t),children:[s.jsx(Kx,{size:11,strokeWidth:2})," ",r]}),n===0&&r===0&&s.jsx("span",{style:{...ai(t.textMuted,t),opacity:.7},children:"up to date"})]})}function m1({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(Rv,{size:14,strokeWidth:1.75,color:e.success}),"Working tree clean"]})}function zp({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 g1({group:e,items:t,t:n}){const r=l1[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((c,a)=>s.jsx(y1,{change:c,t:n,color:o,divider:a<t.length-1},c.path))})]})}function y1({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 b1({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(Hv,{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(zp,{t})}function ii({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 ai(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 x1(e){const{state:t,dispatch:n}=et(),r=Qe[t.themeMode],[o,i]=p.useState([]),[c,a]=p.useState(!0),[l,u]=p.useState(""),[f,d]=p.useState(""),[h,m]=p.useState(new Set),S=()=>{a(!0),B.listApps().then(y=>i(y)).finally(()=>a(!1))};p.useEffect(()=>{S()},[]);const b=wo(t.authoredDomains),x=Qn(t.authoredDomains),w=o.some(y=>{var O;return!b.has(((O=y.domain)==null?void 0:O.trim())??"")}),C=o.filter(y=>{var A;const O=l.toLowerCase();return!(O&&!y.name.toLowerCase().includes(O)&&!(y.description??"").toLowerCase().includes(O)||f==="uncategorized"&&b.has(((A=y.domain)==null?void 0:A.trim())??"")||f&&f!=="uncategorized"&&(!b.has(f)||y.domain!==f))}),k=y=>{m(O=>{const A=new Set(O);return A.has(y)?A.delete(y):A.add(y),A})},v=(y,O)=>{n({type:"OPEN_APP",appId:y.id,dashboardId:O})},j={background:r.inputBg,border:`1px solid ${r.inputBorder}`,borderRadius:4,color:r.textPrimary,fontSize:11,fontFamily:r.font,padding:"4px 6px",outline:"none"},D=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"}),T=s.jsxs(ap,{children:[s.jsx("input",{value:l,onChange:y=>u(y.target.value),placeholder:"Search apps...",style:{...j,flex:1,minWidth:100}}),s.jsxs("select",{value:f,onChange:y=>d(y.target.value),style:j,children:[s.jsx("option",{value:"",children:"All domains"}),x.map(y=>s.jsx("option",{value:y.value,children:y.label},y.value)),w?s.jsx("option",{value:"uncategorized",children:"Unassigned"}):null]})]});return s.jsx(ka,{title:"Apps",status:s.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font},children:C.length}),actions:D,toolbar:T,bodyPadding:0,children:c?s.jsx(Jr,{title:"Loading apps…"}):C.length===0?o.length===0?s.jsx(Jr,{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(Jr,{title:"No matches",description:"No apps match your filters."}):C.map(y=>{const O=h.has(y.id);return s.jsxs("div",{style:{borderBottom:`1px solid ${r.cellBorder}`},children:[s.jsxs("button",{onClick:()=>k(y.id),style:{display:"block",width:"100%",textAlign:"left",background:"transparent",border:"none",cursor:"pointer",padding:"10px 12px",transition:"background 0.1s"},onMouseEnter:A=>{A.currentTarget.style.background=`${r.accent}0a`},onMouseLeave:A=>{A.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:O?"▾":"▸"}),s.jsx("span",{style:{fontSize:12,fontWeight:600,color:r.textPrimary,fontFamily:r.font},children:y.name}),s.jsx(ip,{tone:"accent",children:y.domain})]}),y.description&&s.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,lineHeight:1.3,marginBottom:4,marginLeft:16},children:y.description}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:10,color:r.textMuted,fontFamily:r.font,marginLeft:16},children:[y.owners[0]&&s.jsxs("span",{children:["by ",y.owners[0]]}),s.jsxs("span",{children:[y.dashboards.length," dashboard",y.dashboards.length===1?"":"s"]}),s.jsxs("span",{children:[y.members," member",y.members===1?"":"s"]})]})]}),O&&s.jsxs("div",{style:{padding:"4px 0 10px 28px",background:`${r.accent}04`},children:[y.dashboards.length===0&&s.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,padding:"4px 0"},children:"(empty app scaffold)"}),y.dashboards.map(A=>s.jsx("button",{onClick:()=>v(y,A.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:A.title},A.id))]})]},y.id)})})}const v1={files:"Build",block_library:"Build",lineage:"Lineage",connection:"Connection",git:"Git",apps:"Apps"};function S1({onOpenFile:e}){const t=Ge(Pr(w=>({schemaTables:w.schemaTables,semanticLayer:w.semanticLayer,sidebarPanel:w.sidebarPanel,themeMode:w.themeMode}))),n=kn(),r=Qe[t.themeMode],[o,i]=p.useState(!1),[c,a]=p.useState(340),[l,u]=p.useState(!1),[f,d]=p.useState(""),h=p.useRef(c),m=t.sidebarPanel,S=m==="files"||m==="block_library",b=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(C=>{w&&n({type:"SET_SEMANTIC_LAYER",layer:C})}).catch(()=>{}).finally(()=>{w&&n({type:"SET_SEMANTIC_LOADING",loading:!1})}),()=>{w=!1}},[S,n]);const x=w=>{w.preventDefault();const C=w.clientX,k=h.current;u(!0);const v=D=>{const T=Math.min(560,Math.max(180,k+(D.clientX-C)));h.current=T,a(T)},j=()=>{u(!1),window.removeEventListener("mousemove",v),window.removeEventListener("mouseup",j)};window.addEventListener("mousemove",v),window.addEventListener("mouseup",j)};return s.jsxs("div",{style:{width:c,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:v1[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(J0,{defaultTab:m==="block_library"?"blocks":"notebooks",tabs:["notebooks","semantic","database","blocks"],onOpenFile:e,blockDomain:f,onBlockDomainChange:d,onNewBlock:()=>n({type:"OPEN_NEW_BLOCK_MODAL"}),onCollapse:()=>n({type:"TOGGLE_SIDEBAR"}),footer:b,footerStatus:t.semanticLayer.loading?"loading":"ready"}),m==="lineage"&&s.jsx(e1,{}),m==="connection"&&s.jsx(Bp,{}),m==="git"&&s.jsx(u1,{}),m==="apps"&&s.jsx(x1,{onOpenFile:e})]}),s.jsx("div",{onMouseDown:x,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 qp=2;function w1(e,t={}){const n=t.version??qp,r=JSON.parse(e),{dqlnbVersion:o,...i}=r,c={dqlnbVersion:n,...i};return JSON.stringify(c,k1(),2)+`
472
+ `}function k1(){return function(t,n){if(n===null||typeof n!="object"||Array.isArray(n))return n;const r=n,o=Object.keys(r);o.sort((c,a)=>{const l=jl[c],u=jl[a];return l!==void 0&&u!==void 0?l-u:l!==void 0?-1:u!==void 0?1:c<a?-1:c>a?1:0});const i={};for(const c of o)i[c]=r[c];return i}}const jl={dqlnbVersion:0,version:1,title:2,metadata:3,cells:4,id:10,type:11,name:12,content:13};function C1(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 c=i[1],a=i[2].trim();r.push({id:bt(),type:"markdown",content:`# ${c}`,status:"idle"}),a&&r.push({id:bt(),type:"dql",name:c.toLowerCase().replace(/\s+/g,"_"),content:a,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 j1=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 E1(e){var t;try{const n=JSON.parse(e),r=n.title||((t=n.metadata)==null?void 0:t.title)||"Untitled",o=Mi((n.cells||[]).map(a=>{const l=Object.fromEntries(Object.entries(a).filter(([u])=>!j1.has(u)));return{id:a.id||bt(),type:a.type||"sql",content:a.content??a.source??"",name:a.name||a.title,status:"idle",...a.paramConfig?{paramConfig:a.paramConfig}:{},...a.paramValue!==void 0?{paramValue:a.paramValue}:{},...a.chartConfig?{chartConfig:a.chartConfig}:{},...a.filterConfig?{filterConfig:a.filterConfig}:{},...a.pivotConfig?{pivotConfig:a.pivotConfig}:{},...a.singleValueConfig?{singleValueConfig:a.singleValueConfig}:{},...a.tableConfig?{tableConfig:a.tableConfig}:{},...a.chatConfig?{chatConfig:a.chatConfig}:{},...a.upstream?{upstream:a.upstream}:{},...a.blockBinding?{blockBinding:a.blockBinding}:{},...a.dqlParameterValues?{dqlParameterValues:a.dqlParameterValues}:{},...a.dqlArtifact?{dqlArtifact:a.dqlArtifact}:{},...a.correctionProvenance?{correctionProvenance:a.correctionProvenance}:{},...a.executionTarget?{executionTarget:a.executionTarget}:{},...a.datasetRefs?{datasetRefs:a.datasetRefs}:{},...a.dependencies?{dependencies:a.dependencies}:{},...a.annotations?{annotations:a.annotations}:{},...a.mixedSourcePlan?{mixedSourcePlan:a.mixedSourcePlan}:{},...a.kernel?{kernel:a.kernel}:{},...Object.keys(l).length>0?{preservedFields:l}:{}}})),{title:i,...c}=n.metadata??{};return{title:r,cells:o,metadata:c}}catch(n){return console.warn("parse-workbook: falling back after error",n),{title:"Untitled",cells:[{id:bt(),type:"sql",content:e,status:"idle"}]}}}function T1(e,t,n){const r={dqlnbVersion:qp,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 w1(JSON.stringify(r))}function R1(e,t){return e.endsWith(".dql")?C1(t):E1(t)}const Up=/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g;function jj(e){const t=new Set;for(const n of e.matchAll(Up))t.add(n[1]);return[...t]}function A1(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(c=>`(${n.map(l=>{const u=c[l];return u==null?"NULL":typeof u=="number"?String(u):typeof u=="boolean"?u?"TRUE":"FALSE":`'${String(u).replace(/'/g,"''")}'`}).join(", ")})`).join(`,
473
+ `),i=n.map(c=>`"${c.replace(/"/g,'""')}"`).join(", ");return`${e} AS (
474
+ SELECT * FROM (VALUES
475
+ ${o}
476
+ ) AS _t(${i})
477
+ )`}function _1(e,t){if(t==="number"){const n=Number(e);return isNaN(n)?`'${e.replace(/'/g,"''")}'`:String(n)}return`'${e.replace(/'/g,"''")}'`}function O1(e,t){var u;const n=[...e.matchAll(Up)];if(n.length===0)return{sql:e,substituted:[],unresolved:[],ambiguous:[]};const r=new Map;for(const f of t){const d=[f.id,(u=f.name)==null?void 0:u.trim()].filter(h=>!!h);for(const h of d)r.set(h,[...r.get(h)??[],f])}const o=[],i=[],c=[],a=[];let l=e;for(const f of n){const d=f[1],h=r.get(d)??[];if(h.length===0){i.push(d);continue}if(h.length>1){c.push(d);continue}const m=h[0];if(m.type==="param"){const S=m.paramConfig,b=m.paramValue??(S==null?void 0:S.defaultValue)??"",x=(S==null?void 0:S.paramType)??"text";l=l.replace(f[0],_1(b,x)),o.push(d);continue}if(!m.result||m.error||m.stale){i.push(d);continue}a.push(A1(d,m.result)),l=l.replace(f[0],`"${d}"`),o.push(d)}if(a.length>0){const f=l.trimStart();/^WITH\s+/i.test(f)?l=l.replace(/^(\s*WITH\s+)/i,`$1${a.join(`,
478
+ `)},
479
+ `):l=`WITH ${a.join(`,
480
+ `)}
481
+ ${l}`}return{sql:l,substituted:Array.from(new Set(o)),unresolved:Array.from(new Set(i)),ambiguous:Array.from(new Set(c))}}function Wp(e){const t=i=>{var c;return((c=e.match(new RegExp(`\\b${i}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:c[1])??""},n=i=>{const c=e.match(new RegExp(`\\b${i}\\s*=\\s*\\[([\\s\\S]*?)\\]`,"i"));return((c==null?void 0:c[1].match(/"([^"]*)"/g))??[]).map(a=>a.slice(1,-1)).filter(Boolean)},r=n("metrics"),o=t("metric");return{metrics:r.length>0?r:o?[o]:[],dimensions:n("dimensions"),requestedFilters:n("requested_filters"),timeDimension:t("time_dimension"),granularity:t("granularity")}}function Ej(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 $a(n,` metrics = [${r.map(o=>`"${xn(o)}"`).join(", ")}]`)}function Kp(e,t,n){const r=Array.from(new Set(n.filter(Boolean))),o=`${t} = [${r.map(c=>`"${xn(c)}"`).join(", ")}]`,i=new RegExp(`\\b${t}\\s*=\\s*\\[[\\s\\S]*?\\]`,"i");return i.test(e)?e.replace(i,o):$a(e,` ${o}`)}function Vp(e){const t=Tl(e,"parameterPolicy"),n=Tl(e,"filterBindings"),r=new Set(Array.from(e.matchAll(/\$\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}/g)).map(c=>c[1])),o=/\btype\s*=\s*"semantic"/i.test(e);return Ma(e,"params").split(/\r?\n/).flatMap(c=>{const a=c.trim();if(!a||a.startsWith("//")||a.startsWith("#"))return[];const l=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?::\s*(string|number|boolean|date)(\[\])?)?\s*(?:=\s*(.+))?$/.exec(a);if(!l)return[];const u=l[1],f=l[4]===void 0?void 0:Yp(l[4]),d=l[2]?`${l[2]}${l[3]??""}`:P1(Xp(f),u),h=n.get(u),m=r.has(u)?{kind:"sql_value"}:u==="top_n"||u==="limit"?{kind:"limit"}:o&&h?{kind:"semantic_filter",field:h,operator:u.endsWith("_set")?"in":"equals"}:void 0;return[{name:u,type:d,required:l[4]===void 0,...l[4]===void 0?{}:{default:f},policy:I1(t.get(u)),...m?{binding:m}:{}}]})}function P1(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=>El(i))?"date[]":o.length>0&&o.every(i=>ps(i))?"number[]":"string[]"}return n==="true"||n==="false"?"boolean":El(n)?"date":ps(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 Hp(e){return e.default===void 0?"":Xp(e.default)}function Tj(e){if(/^\s*block\s+"/i.test(e))return e;const t=e.trim();return`block "notebook_query" {
482
+ status = "draft"
483
+ domain = "uncategorized"
484
+ type = "custom"
485
+ description = "Notebook analysis"
486
+
487
+ query = """
488
+ ${t?t.split(/\r?\n/).map(r=>` ${r}`).join(`
489
+ `):" -- Write query"}
490
+ """
491
+ }
492
+ `}function Rj(e,t){const n=Jp(t.name);if(!n)return e;const r=Vp(e).filter(o=>o.name!==t.previousName&&o.name!==n).map(o=>({name:o.name,type:o.type,required:o.required,defaultText:Hp(o),policy:o.policy}));return r.push({name:n,type:t.type,required:t.required,defaultText:t.defaultText??"",policy:t.policy}),Gp(e,r)}function Aj(e,t){const n=Vp(e).filter(r=>r.name!==t).map(r=>({name:r.name,type:r.type,required:r.required,defaultText:Hp(r),policy:r.policy}));return Gp(e,n)}function _j(e,t,n){const r=Jp(t),o=n.trim();if(!r||!o)return e;const c=Ma(e,"filterBindings").split(/\r?\n/).filter(a=>a.trim()&&!new RegExp(`^${r}\\s*=`).test(a.trim()));return c.push(`${r} = "${xn(o)}"`),fs(e,"filterBindings",c.join(`
493
+ `))}function Gp(e,t){const n=t.map(i=>{const c=`${i.name}: ${i.type}`;return i.required?c:`${c} = ${Qp(i.defaultText,i.type)}`}).join(`
494
+ `),r=t.map(i=>`${i.name} = "${i.policy}"`).join(`
495
+ `);let o=fs(e,"params",n);return o=fs(o,"parameterPolicy",r),o}function Qp(e,t){const n=e.trim();if(t==="boolean")return n==="true"?"true":"false";if(t==="number")return ps(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=>Qp(i,r)).join(", ")}]`}return`"${xn(n)}"`}function Jp(e){const t=e.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return/^[a-z_][a-z0-9_]*$/.test(t)?t:""}function ps(e){return e!==""&&Number.isFinite(Number(e))}function El(e){return/^\d{4}-\d{2}-\d{2}$/.test(e)}function Ma(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 Tl(e,t){const n=new Map;for(const r of Ma(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 Yp(e){const t=e.trim();return t==="true"?!0:t==="false"?!1:ps(t)?Number(t):t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"):t.startsWith("[")&&t.endsWith("]")?D1(t.slice(1,-1)).map(Yp):t}function D1(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 Xp(e){return Array.isArray(e)?e.join(", "):String(e??"")}function I1(e){return e==="static"||e==="business"||e==="derived"||e==="optional"||e==="ambiguous_review_required"?e:"dynamic"}function M1(e,t){const n=new Set(Wp(e).requestedFilters),r=Array.from(new Set(t.filter(Boolean)));let o=Kp(e,"requested_filters",r);return o=ci(o,"params",n,r,i=>`${i}: string`),o=ci(o,"parameterPolicy",n,r,i=>`${i} = "dynamic"`),o=ci(o,"filterBindings",n,r,i=>`${i} = "${xn(i)}"`),o}function ci(e,t,n,r,o){const a=[...z1(e,t).split(/\r?\n/).filter(l=>{var f;const u=(f=l.trim().match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?::|=)/))==null?void 0:f[1];return!u||!n.has(u)}).filter(l=>l.trim()),...r.map(o)].join(`
496
+ `);return fs(e,t,a)}function Rl(e,t,n){const r=xn(n),o=new RegExp(`(\\b${t}\\s*=\\s*)"[^"]*"`,"i");return o.test(e)?e.replace(o,`$1"${r}"`):$a(e,` ${t} = "${r}"`)}function Oj(e,t){const n=new Set(t.filter(Boolean)),r=Wp(e);let o=Kp(e,"dimensions",r.dimensions.filter(i=>n.has(i)));return o=M1(o,r.requestedFilters.filter(i=>n.has(i))),r.timeDimension&&!n.has(r.timeDimension)&&(o=Rl(o,"time_dimension",""),o=Rl(o,"granularity","")),o}function xn(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function $a(e,t){return/visualization\s*\{/i.test(e)?e.replace(/\n\s*visualization\s*\{/i,`
497
+ ${t}
498
+
499
+ visualization {`):e.replace(/\n\}\s*$/,`
500
+ ${t}
501
+ }
502
+ `)}function $1(e){var i;const t=e.match(/visualization\s*\{([^}]+)\}/is);if(!t)return;const n=t[1],r=c=>{var a;return(a=n.match(new RegExp(`\\b${c}\\s*=\\s*["']?([\\w-]+)["']?`,"i")))==null?void 0:a[1]},o=r("chart");if(o)return{chart:o,x:r("x"),y:r("y"),color:r("color"),title:(i=n.match(/\btitle\s*=\s*"([^"]+)"/i))==null?void 0:i[1]}}function L1(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 c=i.search(/\b(visualization|tests|block)\s*\{/i);return c>0&&(i=i.slice(0,c)),i=N1(i),i.trim()||null}return null}function N1(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 Pj(e){const t=La(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 B1(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}"`):Ir(e,` ${t} = "${r}"`)}function F1(e,t){const n=t.replace(/"/g,'\\"');return/^\s*block\s+"/i.test(e)?e.replace(/^(\s*block\s+)"[^"]+"/i,`$1"${n}"`):e}function Dj(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}]`):Ir(e,` tags = [${n}]`)}function Ij(e,t,n){const r=Array.from(new Set(n.map(c=>c.trim()).filter(Boolean))),o=`${t} = [${r.map(c=>`"${xn(c)}"`).join(", ")}]`,i=new RegExp(`(\\b${t}\\s*=\\s*)\\[[\\s\\S]*?\\]`,"i");return i.test(e)?e.replace(i,`$1[${r.map(c=>`"${xn(c)}"`).join(", ")}]`):Ir(e,` ${o}`)}function Mj(e,t){const n=/visualization\s*\{[\s\S]*?\n\s*\}/i;if(!n.test(e)){const r=U1(t);return Ir(e,` ${r.replace(/\n/g,`
503
+ `)}`,!0)}return e.replace(n,r=>{let o=r;for(const[i,c]of Object.entries(t)){if(c==null||c==="")continue;const a=String(c).replace(/"/g,'\\"'),l=new RegExp(`(\\b${i}\\s*=\\s*)"[^"]*"`,"i");l.test(o)?o=o.replace(l,`$1"${a}"`):o=o.replace(/\n(\s*)\}$/,`
504
+ $1 ${i} = "${a}"
505
+ $1}`)}return o})}function z1(e,t){var r;const n=e.match(new RegExp(`\\b${t}\\s*\\{([\\s\\S]*?)\\n\\s*\\}`,"i"));return((r=n==null?void 0:n[1])==null?void 0:r.split(/\r?\n/).map(o=>o.replace(/^\s{4}/,"")).join(`
506
+ `).trim())??""}function fs(e,t,n){const r=n.trim(),o=r?` ${t} {
507
+ ${r.split(/\r?\n/).map(c=>` ${c.trimEnd()}`).join(`
508
+ `)}
509
+ }`:"",i=new RegExp(`\\n\\s*${t}\\s*\\{[\\s\\S]*?\\n\\s*\\}`,"i");return i.test(e)?e.replace(i,o?`
510
+ ${o}`:""):o?/\n\s*visualization\s*\{/i.test(e)?e.replace(/\n\s*visualization\s*\{/i,`
511
+ ${o}
512
+
513
+ visualization {`):Ir(e,o,!0):e}function $j(e,t){return e==="metric"?`@metric(${t})`:`@dim(${t})`}function Lj(e,t){const n=La(e);if(!n||n.blockType!=="custom")return`${e.trimEnd()}
514
+ ${t}
515
+ `;const r=n.query.trimEnd(),o=r?`${r}
516
+ ${t}`:t;return q1(e,o)}function q1(e,t){if(!La(e))return e;const r=B1(e,"type","custom"),o=` query = """
517
+ ${t.trimEnd()}
518
+ """`,i=/\n\s*query\s*=\s*"""[\s\S]*?"""/i;return i.test(r)?r.replace(i,`
519
+ ${o}`):Ir(r,o,!0)}function La(e){var i,c;if(!/^\s*block\s+"/i.test(e.trim()))return null;const t=a=>{var l;return((l=e.match(new RegExp(`\\b${a}\\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(a=>a.slice(1,-1)):[],metric:t("metric"),metrics:Br(e,"metrics"),dimensions:Br(e,"dimensions"),requestedFilters:Br(e,"requested_filters"),sourceDqlKind:t("source_dql_kind"),sourceDqlName:t("source_dql_name"),sourceDqlPath:t("source_dql_path"),sourceDqlHash:t("source_dql_hash"),sourceDqlMetrics:Br(e,"source_dql_metrics"),sourceDqlDimensions:Br(e,"source_dql_dimensions"),timeDimension:t("time_dimension"),granularity:t("granularity"),query:((c=o==null?void 0:o[1])==null?void 0:c.trim())??"",visualization:Al(e,"visualization"),tests:Al(e,"tests")}}function Br(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 Al(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 c=e[i];if(c==="{")r===0&&(o=i),r++;else if(c==="}"&&(r--,r===0&&o>=0))return e.slice(n.index,i+1).trim()}return""}function U1(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 = "${W1(e.title)}"`),t.push("}"),t.join(`
520
+ `)}function W1(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Ir(e,t,n=!1){const r=e.trimEnd();if(!/^\s*block\s+"/i.test(r))return`${r}
521
+ ${t}
522
+ `;const o=n?`
523
+
524
+ ${t}
525
+ `:`
526
+ ${t}`;return r.replace(/\n\}\s*$/,`${o}
527
+ }`)}function _l(e,t){return t.filter(n=>n.datasetId&&(n.objectType==="dataset"||n.objectType==="staged_dataset")).filter(n=>Zp(n.name).test(e)).map(n=>({id:n.datasetId,alias:n.name,role:n.objectType==="staged_dataset"?"staged":"source",fingerprint:n.fileFingerprint}))}function K1(e,t){return t.filter(n=>n.source==="database").filter(n=>Zp(n.name).test(e)).map(n=>n.name)}function Nj(e,t){const n=[];for(const r of e)for(const o of t){const i=V1(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 Bj(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(G1)).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 Fj(e){const t=new Set(e.staged.columns??[]),r=[" warehouse.*",...(e.local.columns??[]).filter(i=>i!==e.localKey).map(i=>{const c=t.has(i)?`local_${i}`:i;return` local_data.${or(i)} AS ${or(c)}`})];return{id:`cell_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,type:"sql",name:`${e.local.alias}_${e.staged.alias}_analysis`,content:["-- Local research join: governed warehouse snapshot plus local dataset","-- Review required: verify join cardinality and freshness before sharing","SELECT",r.join(`,
528
+ `),`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(`
529
+ `),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 V1(e,t,n){const r=e.toLowerCase(),o=t.toLowerCase();if(r===o)return{score:100,reason:"Same column name"};const i=Ol(r),c=Ol(o);return i===c?{score:90,reason:"Same normalized name"}:(i.endsWith(c)||c.endsWith(i))&&(i.endsWith("id")||c.endsWith("id"))?{score:n.includes("identifier")?78:70,reason:"Related identifier names"}:Pl(r).filter(l=>Pl(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 Ol(e){return e.replace(/[^a-z0-9]/g,"").replace(/identifier$/,"id")}function Pl(e){return e.split(/[^a-z0-9]+/).filter(t=>t.length>1)}function Zp(e){return new RegExp(`(?:^|[^a-zA-Z0-9_])(?:["\`])?${H1(e)}(?:["\`])?(?=$|[^a-zA-Z0-9_])`,"i")}function or(e){return`"${e.replace(/"/g,'""')}"`}function H1(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function G1(e){return typeof e=="string"?e:JSON.stringify(e)}const An=new Map,nn=new Map;function li(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 Q1(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?L1(t):null}function J1(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 Gr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Y1(e){const t=Gr(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 Fr(e,t,n){return new xt({status:400,code:e,message:t,recoverable:!0,details:{phase:"preflight",...n}})}function Ko(e){const t=e.error instanceof xt?e.error:void 0,n=Gr(t==null?void 0:t.details),r=Gr(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??Y1(n==null?void 0:n.executionTarget),compiledSql:e.attemptedSql,semanticTrace:r,targetBinding:Gr(n==null?void 0:n.targetBinding),executionReceipt:Gr(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 Vo(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 ef(){const e=kn(),t=p.useCallback(async(i,c)=>{var D,T,y,O;const a=Pn.getState(),l=c??a.cells,u=l.find(A=>A.id===i);if(!u)return{cellId:i,status:"skipped"};const f=u.type==="dql"?"notebook_dql_cell":"notebook_sql_cell",d=u.type==="dql"?null:Q1(u);if(u.type!=="dql"&&!d)return{cellId:i,status:"skipped"};const h=An.get(i);h&&h.controller.abort();const m=li(i),S=new Date().toISOString(),b=Date.now(),x=new AbortController,w={controller:x,runId:m,startedAt:S,route:f,executionTarget:u.executionTarget};An.set(i,w),nn.set(i,m);const C=()=>{var A;return((A=An.get(i))==null?void 0:A.runId)===m&&nn.get(i)===m},k=(u.executionCount??0)+1;let v=d??void 0;e({type:"UPDATE_CELL",id:i,updates:{status:"running",error:void 0,result:void 0,execution:void 0,fromSnapshot:!1}});const j=(A,_,P="error")=>{const $=new Date().toISOString(),q=Ko({cell:u,runId:m,route:f,startedAt:S,completedAt:$,durationMs:Date.now()-b,message:A,error:_,status:P,attemptedSql:v});return C()&&(e({type:"UPDATE_CELL",id:i,updates:{status:P==="cancelled"?"idle":"error",error:P==="cancelled"?void 0:A,result:void 0,execution:q,executionCount:k,stale:!1}}),e({type:"APPEND_QUERY_LOG",entry:{id:bt(),cellName:u.name??u.id,rows:0,time:q.durationMs,ts:new Date,...P==="cancelled"?{}:{error:A}}})),{cellId:i,runId:m,status:P,error:P==="cancelled"?void 0:A,execution:q}};try{if(u.type==="dql"){const ee=await B.executeNotebookCell(u,x.signal,{notebookPath:(D=a.activeFile)==null?void 0:D.path,cellId:u.id,cellName:u.name,source:f,runId:m});if(!ee.result)throw new Error("DQL cell produced no executable result.");if(!C())return{cellId:i,runId:m,status:"cancelled"};const ce=new Date().toISOString(),ke=Date.now()-b,xe={...ee.result,executionTime:ee.result.executionTime??ke,rowCount:ee.result.rowCount??ee.result.rows.length},Ie=J1(ee.chartConfig)??$1(u.content),We={version:1,runId:m,cellId:i,route:f,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,...Ie?{chartConfig:Ie}:{},executionCount:k,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 A=_l(d,a.schemaTables),_=K1(d,a.schemaTables);if(A.length>0&&_.length>0){const ee=[`Mixed-source query detected: ${_.join(", ")} runs in the warehouse, while ${A.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 j(ee,Fr("CROSS_ENGINE_JOIN_REQUIRED",ee,{warehouseTables:_,datasets:A.map(ce=>ce.alias??ce.id)}))}const P=A.length>0?{target:"local"}:u.executionTarget;A.length>0&&((T=u.executionTarget)==null?void 0:T.target)!=="local"&&e({type:"UPDATE_CELL",id:i,updates:{executionTarget:P,datasetRefs:A}});const $=O1(d,l);if($.ambiguous.length>0){const ee=`Ambiguous notebook dependency: ${$.ambiguous.join(", ")} matches more than one cell. Rename the duplicate cells or reference a stable cell ID.`;return j(ee,Fr("AMBIGUOUS_NOTEBOOK_DEPENDENCY",ee,{ambiguousReferences:$.ambiguous}))}if($.unresolved.length>0){const ee=`Notebook dependency result is unavailable: ${$.unresolved.join(", ")}. Run or repair the upstream cell before retrying this cell.`;return j(ee,Fr("UPSTREAM_RESULT_UNAVAILABLE",ee,{unresolvedReferences:$.unresolved}))}v=$.sql;const q=await B.executeQuery($.sql,x.signal,{notebookPath:(y=a.activeFile)==null?void 0:y.path,cellId:u.id,cellName:u.name,source:f,runId:m},P);if(!C())return{cellId:i,runId:m,status:"cancelled"};const G=new Date().toISOString(),J=Date.now()-b,{executionTarget:H,compiledSql:L,executedSql:M,targetBinding:X,executionReceipt:W,...te}=q,F={...te,executionTime:te.executionTime??J,rowCount:te.rowCount??te.rows.length},K=(P==null?void 0:P.target)==="local"?_l($.sql,a.schemaTables):u.datasetRefs,oe={version:1,runId:m,cellId:i,route:f,status:"success",startedAt:S,completedAt:G,durationMs:J,executionTarget:H??P,compiledSql:L??$.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:k,stale:!1,datasetRefs:K,executionTarget:H??P}}),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(A){if(x.signal.aborted||!C())return j("Cell execution was cancelled.",A,"cancelled");const _=A instanceof Error?A.message:String(A);return j(_,A)}finally{((O=An.get(i))==null?void 0:O.runId)===m&&An.delete(i)}},[e]),n=p.useCallback(async()=>{const i=Pn.getState().cells,c=Rx(i);let a=i.map(f=>({...f}));const l=new Map,u=new Map;for(const f of c.missing)u.set(f.cellId,[...u.get(f.cellId)??[],f.dependency]);for(const f of c.cycleCellIds){const d=a.find(w=>w.id===f);if(!d)continue;const h=li(f),m=new Date().toISOString(),S="Dependency cycle detected. Update the cell dependencies before running all.",b=Ko({cell:d,runId:h,route:d.type==="dql"?"notebook_dql_cell":"notebook_sql_cell",startedAt:m,completedAt:m,durationMs:0,message:S,error:Fr("DEPENDENCY_CYCLE",S,{cycleCellIds:c.cycleCellIds}),status:"blocked"}),x={cellId:f,runId:h,status:"blocked",error:S,execution:b};l.set(f,x),a=Vo(a,x),e({type:"UPDATE_CELL",id:f,updates:{status:"error",error:S,result:void 0,execution:b,executionCount:(d.executionCount??0)+1,stale:!1}})}for(const f of c.ordered){const d=a.find(b=>b.id===f.id)??f,h=u.get(d.id)??[],m=Ca(d,a).filter(b=>{const x=l.get(b.cellId);return x&&x.status!=="success"});if(h.length>0||m.length>0){const b=[...h,...m.map(j=>{var D;return((D=a.find(T=>T.id===j.cellId))==null?void 0:D.name)??j.cellId})],x=li(d.id),w=new Date().toISOString(),C=`Not executed because ${b.join(", ")} did not produce a valid upstream result.`,k=Ko({cell:d,runId:x,route:d.type==="dql"?"notebook_dql_cell":"notebook_sql_cell",startedAt:w,completedAt:w,durationMs:0,message:C,error:Fr("UPSTREAM_EXECUTION_FAILED",C,{blockedBy:b}),status:"blocked"}),v={cellId:d.id,runId:x,status:"blocked",error:C,execution:k};l.set(d.id,v),a=Vo(a,v),e({type:"UPDATE_CELL",id:d.id,updates:{status:"error",error:C,result:void 0,execution:k,executionCount:(d.executionCount??0)+1,stale:!1}});continue}const S=await t(d.id,a);l.set(d.id,S),a=Vo(a,S)}},[e,t]),r=p.useCallback(async i=>{if(!i)return;const c=`{{${i}}}`;let a=Pn.getState().cells.map(l=>({...l}));for(const l of a){if(l.type==="markdown"||l.type==="param"||!l.content.includes(c))continue;const u=await t(l.id,a);a=Vo(a,u)}},[t]),o=p.useCallback(i=>{const c=An.get(i);if(!c)return;c.controller.abort(),An.delete(i),nn.get(i)===c.runId&&nn.delete(i);const a=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:Ko({cell:l,runId:c.runId,route:c.route,startedAt:c.startedAt,completedAt:a,durationMs:Date.parse(a)-Date.parse(c.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 X1(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 Z1(e){const t=e.split(`
530
+ `),n=[];let r=!1,o=!1;for(const i of t){const c=i;if(c.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(c));continue}if(c.startsWith("### ")){o&&(n.push("</ul>"),o=!1),n.push(`<h3>${lt(c.slice(4))}</h3>`);continue}if(c.startsWith("## ")){o&&(n.push("</ul>"),o=!1),n.push(`<h2>${lt(c.slice(3))}</h2>`);continue}if(c.startsWith("# ")){o&&(n.push("</ul>"),o=!1),n.push(`<h1>${lt(c.slice(2))}</h1>`);continue}if(c.startsWith("> ")){o&&(n.push("</ul>"),o=!1),n.push(`<blockquote><p>${lt(c.slice(2))}</p></blockquote>`);continue}if(c.startsWith("- ")||c.startsWith("* ")){o||(n.push("<ul>"),o=!0),n.push(`<li>${Dl(c.slice(2))}</li>`);continue}if(o&&(n.push("</ul>"),o=!1),c.trim()===""){n.push("<br>");continue}n.push(`<p>${Dl(c)}</p>`)}return o&&n.push("</ul>"),r&&n.push("</code></pre>"),n.join(`
531
+ `)}function Dl(e){return lt(e).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/`(.+?)`/g,"<code>$1</code>")}function eC(e){const{columns:t,rows:n}=e,r=n.slice(0,200),o=n.length>200,i=t.map(a=>`<th>${lt(a)}</th>`).join(""),c=r.map(a=>`<tr>${t.map(u=>{const f=a[u],d=typeof f=="number",h=f==null?"—":String(f);return`<td${d?' class="num"':""}>${lt(h)}</td>`}).join("")}</tr>`).join("");return`
532
+ <div class="table-wrap">
533
+ <table>
534
+ <thead><tr>${i}</tr></thead>
535
+ <tbody>${c}</tbody>
536
+ </table>
537
+ ${o?`<p class="truncated">Showing first 200 of ${n.length.toLocaleString()} rows</p>`:""}
538
+ </div>`}function tC(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 nC(e){const t=tC(e);if(!t)return null;const n=e.rows.slice(0,20).map(f=>({label:String(f[t.labelCol]??""),value:Number(f[t.valueCol]??0)})),r=Math.max(...n.map(f=>f.value),1),o=28,i=6,c=140,a=440,l=n.length*(o+i)+40,u=n.map((f,d)=>{const h=d*(o+i)+20,m=Math.max(f.value/r*a,2);return`
539
+ <text x="${c-6}" y="${h+o/2+4}" text-anchor="end" font-size="11" fill="#8b949e">${lt(f.label.slice(0,20))}</text>
540
+ <rect x="${c}" y="${h}" width="${m}" height="${o}" rx="3" fill="#388bfd" />
541
+ <text x="${c+m+5}" y="${h+o/2+4}" font-size="11" fill="#e6edf3">${X1(f.value)}</text>`}).join("");return`<svg xmlns="http://www.w3.org/2000/svg" width="${c+a+80}" height="${l}" style="max-width:100%">${u}</svg>`}function rC(e,t){const n=t.map(r=>{if(r.type==="markdown")return`<section class="cell md-cell">${Z1(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 c="";if(r.result&&r.result.rows.length>0){const a=nC(r.result),l=eC(r.result);c=`<div class="cell-output">${`<div class="output-meta">${r.result.rows.length.toLocaleString()} rows${r.result.executionTime?` · ${r.result.executionTime}ms`:""}</div>`}${a??""}${a?"":l}</div>`}else r.error&&(c=`<div class="cell-error">⚠ ${lt(r.error)}</div>`);return`<section class="cell sql-cell">${o}${i}${c}</section>`}).join(`
542
+ `);return`<!DOCTYPE html>
543
+ <html lang="en">
544
+ <head>
545
+ <meta charset="UTF-8">
546
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
547
+ <title>${lt(e)}</title>
548
+ <style>
549
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
550
+ body {
551
+ font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
552
+ background: #0d1117; color: #e6edf3;
553
+ line-height: 1.6; padding: 0;
554
+ }
555
+ .page-header {
556
+ background: #161b22; border-bottom: 1px solid #21262d;
557
+ padding: 16px 32px; display: flex; align-items: center; gap: 12px;
558
+ }
559
+ .logo {
560
+ width: 28px; height: 28px; border-radius: 6px;
561
+ background: linear-gradient(135deg, #388bfd, #1f6feb);
562
+ display: flex; align-items: center; justify-content: center;
563
+ font-size: 10px; font-weight: 700; color: #fff;
564
+ font-family: monospace; letter-spacing: -0.5px; flex-shrink: 0;
565
+ }
566
+ .page-title { font-size: 18px; font-weight: 600; color: #e6edf3; }
567
+ .page-meta { font-size: 12px; color: #8b949e; margin-left: auto; }
568
+ .content { max-width: 900px; margin: 0 auto; padding: 32px 24px; display: flex; flex-direction: column; gap: 24px; }
569
+ .cell { border-radius: 8px; overflow: hidden; }
570
+ .md-cell { padding: 4px 0; }
571
+ .md-cell h1 { font-size: 26px; font-weight: 700; color: #e6edf3; margin: 0 0 12px; }
572
+ .md-cell h2 { font-size: 20px; font-weight: 600; color: #e6edf3; margin: 20px 0 10px; }
573
+ .md-cell h3 { font-size: 16px; font-weight: 600; color: #e6edf3; margin: 16px 0 8px; }
574
+ .md-cell p { color: #c9d1d9; margin-bottom: 8px; }
575
+ .md-cell ul { padding-left: 20px; color: #c9d1d9; margin-bottom: 8px; }
576
+ .md-cell code { background: #21262d; padding: 2px 6px; border-radius: 4px; font-family: monospace; font-size: 13px; }
577
+ .md-cell pre { background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 14px; overflow-x: auto; margin-bottom: 8px; }
578
+ .md-cell pre code { background: none; padding: 0; }
579
+ .md-cell blockquote { border-left: 3px solid #388bfd; padding-left: 14px; color: #8b949e; }
580
+ .sql-cell { background: #161b22; border: 1px solid #30363d; }
581
+ .cell-header { display: flex; align-items: center; gap: 8px; padding: 8px 14px; border-bottom: 1px solid #21262d; background: #1c2128; }
582
+ .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; }
583
+ .cell-name { font-size: 12px; color: #388bfd; font-family: monospace; }
584
+ .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; }
585
+ .cell-output { padding: 14px; }
586
+ .output-meta { font-size: 11px; color: #8b949e; margin-bottom: 10px; }
587
+ .table-wrap { overflow-x: auto; }
588
+ table { width: 100%; border-collapse: collapse; font-size: 12px; }
589
+ th { background: #1c2128; color: #8b949e; font-weight: 600; text-align: left; padding: 7px 12px; border-bottom: 1px solid #30363d; white-space: nowrap; }
590
+ td { padding: 6px 12px; border-bottom: 1px solid #21262d; color: #e6edf3; }
591
+ td.num { text-align: right; font-family: monospace; }
592
+ tr:last-child td { border-bottom: none; }
593
+ .truncated { font-size: 11px; color: #8b949e; margin-top: 8px; }
594
+ .cell-error { padding: 12px 14px; background: #3d1a1a; border-top: 1px solid #f85149; color: #f85149; font-size: 13px; }
595
+ .exported-by { text-align: center; color: #484f58; font-size: 11px; padding: 40px 0 24px; }
596
+ </style>
597
+ </head>
598
+ <body>
599
+ <div class="page-header">
600
+ <div class="logo">DQL</div>
601
+ <span class="page-title">${lt(e)}</span>
602
+ <span class="page-meta">Exported ${new Date().toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}</span>
603
+ </div>
604
+ <div class="content">
605
+ ${n}
606
+ </div>
607
+ <p class="exported-by">Built with DQL Workbench</p>
608
+ </body>
609
+ </html>`}function oC(e,t){const n=rC(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 Ho=["local-operations"],tf=p.createContext(null);function di(e,t){const n=e.filter(r=>r.id!==t.id);return n.push(t),n.sort((r,o)=>o.updatedAt.localeCompare(r.updatedAt)).slice(0,50)}function sC({children:e}){const t=Hi(),n=p.useRef(new Set),r=Ge(a=>a.dispatch),o=ji({queryKey:Ho,queryFn:async()=>(await B.listOperations(50)).operations,staleTime:15e3,refetchOnWindowFocus:!1}),i=o.data??[];p.useEffect(()=>{if(typeof EventSource>"u")return;const a=new EventSource("/api/operations/events"),l=u=>{try{const f=JSON.parse(u.data);t.setQueryData(Ho,(d=[])=>di(d,f))}catch{}};return a.addEventListener("operation",l),()=>{a.removeEventListener("operation",l),a.close()}},[t]),p.useEffect(()=>{for(const a of i){if(a.type!=="block_certification"||a.status!=="succeeded"||n.current.has(a.id))continue;const l=a.result;!(l!=null&&l.block)||!l.outcome||(n.current.add(a.id),r({type:"RECONCILE_BLOCK_CERTIFICATION",outcome:l.outcome,oldPath:l.oldPath,draftPath:l.draftPath,newPath:l.newPath,payload:l.block}),window.dispatchEvent(new CustomEvent("dql:block-library-invalidated",{detail:{operationId:a.id,outcome:l.outcome}})))}},[r,i]);const c=p.useMemo(()=>({operations:i,activeCount:i.filter(a=>a.status==="queued"||a.status==="running").length,loading:o.isLoading,cancel:async a=>{const l=await B.cancelOperation(a);t.setQueryData(Ho,(u=[])=>di(u,l))},track:a=>{t.setQueryData(Ho,(l=[])=>di(l,a))}}),[i,o.isLoading,t]);return s.jsx(tf.Provider,{value:c,children:e})}function iC(){const e=p.useContext(tf);if(!e)throw new Error("useOperations must be used inside OperationsProvider.");return e}const aC=new Set(["succeeded","failed","cancelled","interrupted"]);function cC(){const e=Ge(f=>f.themeMode),t=Qe[e],{operations:n,activeCount:r,loading:o,cancel:i}=iC(),[c,a]=p.useState(!1),l=p.useRef(null),u=n.filter(f=>!aC.has(f.status)||f.type!=="project_refresh").slice(0,8);return p.useEffect(()=>{if(!c)return;const f=h=>{l.current&&!l.current.contains(h.target)&&a(!1)},d=h=>{h.key==="Escape"&&a(!1)};return document.addEventListener("mousedown",f),document.addEventListener("keydown",d),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("keydown",d)}},[c]),!o&&u.length===0?null:s.jsxs("div",{ref:l,style:{position:"relative"},children:[s.jsxs("button",{type:"button","aria-label":"Background tasks","aria-expanded":c,onClick:()=>a(f=>!f),style:{height:28,padding:"0 9px",borderRadius:6,border:`1px solid ${r>0?t.accent:t.btnBorder}`,background:c?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:r>0?t.accent:t.success,boxShadow:r>0?`0 0 0 3px ${t.accent}20`:"none"}}),r>0?`${r} running`:"Tasks"]}),c&&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"}),u.map(f=>{var m;const d=f.status==="queued"||f.status==="running",h=f.status==="failed"||f.status==="interrupted";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:lC(f.type)}),s.jsx("span",{style:{color:h?t.error:f.status==="succeeded"?t.success:t.textMuted,fontSize:10},children:f.status})]}),s.jsx("div",{style:{color:h?t.error:t.textSecondary,fontSize:10.5,lineHeight:1.4},children:((m=f.error)==null?void 0:m.message)??f.message}),d&&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,f.progress)}%`,height:"100%",background:t.accent,transition:"width 180ms ease"}})}),f.cancellable&&s.jsx("button",{type:"button",onClick:()=>void i(f.id),style:{border:0,background:"transparent",color:t.textMuted,cursor:"pointer",fontSize:10,padding:0},children:"Cancel"})]}),f.type==="block_certification"&&s.jsx("div",{style:{color:t.textMuted,fontSize:9.5},children:d?"You can change pages while certification continues.":f.status==="succeeded"?"Completed without blocking the rest of your work.":"The saved draft is preserved for review or retry."}),(f.type==="agent_run"||f.type==="app_ai_build")&&s.jsx("div",{style:{color:t.textMuted,fontSize:9.5},children:d?"This continues while you work on another page.":f.status==="succeeded"?"Completed in the background.":"Open the original surface to review or retry."})]},f.id)})]})]})}function lC(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 Zo=new Map;function dC(e,t){let n=Zo.get(e);n||(n={running:!1},Zo.set(e,n));const r=n,o=new Promise((i,c)=>{r.pending?(r.pending.content=t,r.pending.waiters.push({resolve:i,reject:c})):r.pending={content:t,waiters:[{resolve:i,reject:c}]}});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 c of i.waiters)c.resolve()}catch(c){for(const a of i.waiters)a.reject(c)}}})().finally(()=>{r.running=!1,r.pending||Zo.delete(e)})),o}function uC(e){const t=Zo.get(e);return!!(t!=null&&t.running||t!=null&&t.pending)}function pC({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 fC(){var te;const e=Ge(Pr(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=kn(),n=Qe[e.themeMode],{executeAll:r}=ef(),[o,i]=p.useState(!1),[c,a]=p.useState(""),[l,u]=p.useState(!1),[f,d]=p.useState(!1),[h,m]=p.useState(!1),[S,b]=p.useState(!1),[x,w]=p.useState(!1),C=p.useRef(null),[k,v]=p.useState(!1),[j,D]=p.useState(!1),T=p.useRef(null),y=p.useRef(null),O=e.mainView==="block_studio"?e.blockStudioDirty:e.notebookDirty,A=e.mainView==="notebook",_=e.mainView==="notebook"||e.mainView==="block_studio",P=_&&!!e.activeFile,$={home:"Home",business_artifact:((te=e.activeFile)==null?void 0:te.name.replace(/\.(dqlnb|dql)$/i,""))??"Business Definition",lineage:"Lineage",lineage_detail:"Lineage",connection:"Settings",apps:"Apps",git:"Source control",settings:"Settings",imports:"Import SQL",domains:"Domains",modeling:"Domains"},q=_?e.activeFile?e.notebookTitle||"Untitled":e.mainView==="block_studio"?"Blocks":"Notebooks":$[e.mainView]??"DQL Workbench";p.useEffect(()=>{o&&y.current&&(y.current.focus(),y.current.select())},[o]),p.useEffect(()=>{if(!j)return;function F(K){T.current&&!T.current.contains(K.target)&&D(!1)}return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[j]);const G=()=>{a(e.notebookTitle),i(!0)},J=()=>{i(!1),c.trim()&&c!==e.notebookTitle&&(e.mainView==="block_studio"&&e.blockStudioMetadata?(t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,name:c.trim()}}),t({type:"SET_BLOCK_STUDIO_DRAFT",draft:F1(e.blockStudioDraft,c.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,Ie=F.notebookMetadata,We=ce.type==="block"?((K=ke[0])==null?void 0:K.content)??"":T1(xe,ke,Ie);await dC(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===Ie&&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||!uC(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||!O||!e.activeFile||e.mainView==="block_studio")return;const F=setTimeout(()=>{H()},750);return()=>clearTimeout(F)},[e.autoSave,O,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"}],M=e.themeMode==="dark"||e.themeMode==="midnight"?"obsidian":e.themeMode==="light"?"paper":e.themeMode==="arctic"?"white":e.themeMode,X=L.find(F=>F.mode===M)??L[0];p.useEffect(()=>{if(!x)return;const F=oe=>{C.current&&!C.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)}},[x]);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(pC,{t:n}),s.jsx("div",{style:{width:1,height:20,background:n.headerBorder,flexShrink:0}}),e.activeFile&&_&&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?s.jsx("input",{ref:y,value:c,onChange:F=>a(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,O&&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(cC,{}),e.appMode==="studio"&&P&&e.mainView!=="block_studio"&&s.jsx(s.Fragment,{children:s.jsxs("button",{onClick:A?r:void 0,disabled:!e.activeFile||!A,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||!A?.4:f?.9:1,boxShadow:"0 1px 2px rgba(107,93,211,0.25)",gap:6},children:[s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:s.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})}),"Run all"]})}),s.jsxs("div",{ref:C,style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>w(F=>!F),onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),title:`Theme: ${X.label}`,"aria-haspopup":"true","aria-expanded":x,style:{...W,background:S||x?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:"▾"})]}),x&&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===M;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"&&P&&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:h&&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(mC,{}),"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}})]}),P&&e.mainView!=="block_studio"&&s.jsxs("div",{ref:T,style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>{e.activeFile&&D(F=>!F)},disabled:!e.activeFile,onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),title:"Share / export",style:{...W,height:30,padding:"0 14px",borderRadius:999,background:(k||j)&&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"})})]}),j&&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(hC,{label:"Export HTML",description:"Standalone dashboard",t:n,onClick:()=>{oC(e.notebookTitle||"dashboard",e.cells),D(!1)}})})]})]})]})}function hC({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 mC(){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 gC(e){return e.toTimeString().slice(0,8)}function yC(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}function bC(){const{state:e,dispatch:t}=et(),n=Qe[e.themeMode],[r,o]=p.useState(!1),i=e.queryLog.filter(a=>a.error),c=a=>t({type:"SET_DEV_PANEL_TAB",tab:a});return s.jsxs("div",{style:{height:e.devPanelOpen?180:0,flexShrink:0,background:n.sidebarBg,borderTop:`1px solid ${n.headerBorder}`,display:"flex",flexDirection:"column",overflow:"hidden",transition:"height 0.2s ease",position:"relative"},children:[e.devPanelOpen&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{height:32,flexShrink:0,display:"flex",alignItems:"center",borderBottom:`1px solid ${n.headerBorder}`,padding:"0 8px",gap:2},children:[["logs","errors"].map(a=>s.jsx(xC,{label:a==="errors"?`Errors${i.length>0?` (${i.length})`:""}`:`Logs (${e.queryLog.length})`,active:e.devPanelTab===a,onClick:()=>c(a),t:n},a)),s.jsx("div",{style:{flex:1}}),s.jsx("button",{onClick:()=>t({type:"SET_CELLS",cells:e.cells}),title:"Clear logs",style:{background:"transparent",borderTop:"none",borderLeft:"none",borderRight:"none",borderBottom:"none",cursor:"pointer",color:n.textMuted,fontSize:11,fontFamily:n.font,padding:"2px 6px",borderRadius:4},children:"Clear"})]}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[e.devPanelTab==="logs"&&(e.queryLog.length===0?s.jsx(Il,{t:n,message:"No queries executed yet."}):[...e.queryLog].reverse().map(a=>s.jsx(Ml,{entry:a,t:n},a.id))),e.devPanelTab==="errors"&&(i.length===0?s.jsx(Il,{t:n,message:"No errors."}):[...i].reverse().map(a=>s.jsx(Ml,{entry:a,t:n},a.id)))]})]}),s.jsxs("button",{onClick:()=>t({type:"TOGGLE_DEV_PANEL"}),onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),title:e.devPanelOpen?"Close panel":"Open dev panel",style:{position:"absolute",bottom:e.devPanelOpen?4:-28,right:8,height:22,padding:"0 8px",borderRadius:"4px 4px 0 0",borderTop:`1px solid ${n.headerBorder}`,borderLeft:`1px solid ${n.headerBorder}`,borderRight:`1px solid ${n.headerBorder}`,borderBottom:e.devPanelOpen?`1px solid ${n.sidebarBg}`:`1px solid ${n.headerBorder}`,background:r?n.btnHover:n.sidebarBg,color:n.textMuted,cursor:"pointer",fontSize:11,fontFamily:n.font,display:"flex",alignItems:"center",gap:4,transition:"background 0.15s, bottom 0.2s ease",zIndex:10},children:[s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:s.jsx("path",{d:e.devPanelOpen?"M1 7l4-4 4 4":"M1 3l4 4 4-4",strokeWidth:"1.5",stroke:"currentColor",fill:"none"})}),"Dev"]})]})}function xC({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 Il({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 Ml({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:gC(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:yC(e.time)})]})]})}function vC(){const{state:e,dispatch:t}=et(),{executeAll:n}=ef();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 SC=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 $l(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 a;const i=((a=e.activeFile)==null?void 0:a.path)??null;if(!i)return;if(i!==r.current){r.current=i,n.current=$l(e.cells);return}const c=$l(e.cells);return c!==n.current&&(n.current=c,t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{const l=wC(i,e.cells);B.saveRunSnapshot(i,l).catch(()=>{})},SC)),()=>{t.current&&(clearTimeout(t.current),t.current=null)}},[e.cells,(o=e.activeFile)==null?void 0:o.path])}const CC=[{items:[{id:"diagram",label:"Models"},{id:"skills",label:"Skills"},{id:"blocks",label:"Blocks"},{id:"notebooks",label:"Notebooks"},{id:"apps",label:"Apps"}]}],jC=new Set(CC.flatMap(e=>e.items.map(t=>t.id)));function zj(e){return e!==null&&jC.has(e)}function qj(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 EC(e){const t=new URL(e);for(const n of["domain","domainSection","modelArea","domainObject"])t.searchParams.delete(n);return`${t.pathname}${t.search}${t.hash}`}function Uj(e){const t=Object.values(e),n=new Map;for(const c of t){const a=c.parent&&e[c.parent]?c.parent:void 0;n.set(a,[...n.get(a)??[],c])}for(const c of n.values())c.sort((a,l)=>a.id.localeCompare(l.id));const r=[],o=new Set,i=(c,a)=>{for(const l of n.get(c)??[])o.has(l.id)||(o.add(l.id),r.push({id:l.id,parent:l.parent,depth:a,label:a===0?l.id:`${"— ".repeat(a)}${l.id.split(".").at(-1)??l.id}`}),i(l.id,a+1))};i(void 0,0);for(const c of t.sort((a,l)=>a.id.localeCompare(l.id)))o.has(c.id)||r.push({id:c.id,parent:c.parent,depth:0,label:c.id});return r}function Wj(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 nf(e){return Object.entries(e.entities).map(([t,n])=>({recordKey:t,entity:n}))}function Kj(e,t){if(e.entities[t])return t;const n=nf(e).filter(({entity:r})=>r.id===t||r.qualifiedId===t);return n.length===1?n[0].recordKey:void 0}function Vj(e,t){return nf(e).filter(({entity:n})=>!t||n.domain===t)}const TC=p.lazy(()=>Oe(()=>import("./HomePage-DiOnRhEG.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.HomePage}))),RC=p.lazy(()=>Oe(()=>import("./AnalyticsHome-B7BkvA-R.js"),__vite__mapDeps([7,8,9,10,11,12,1,13,14,3,15,16,17,18,19,20,2,21,22,6])).then(e=>({default:e.AnalyticsHome}))),AC=p.lazy(()=>Oe(()=>import("./GlobalAiRail-DUwdy3fB.js"),__vite__mapDeps([23,9,10,11,12,1,13,14,3,15,16,17,18,19,20,2,21,24,6])).then(e=>({default:e.GlobalAiRail}))),_C=p.lazy(()=>Oe(()=>import("./NotebookEditor-CuMpvXR9.js"),__vite__mapDeps([25,4,2,5,26,27,28,11,12,9,10,1,13,14,3,15,16,17,18,19,20,21,8,29,30,6,31,32,24])).then(e=>({default:e.NotebookEditor}))),OC=p.lazy(()=>Oe(()=>import("./NewNotebookModal-BbO9NKUl.js"),__vite__mapDeps([33,4,16,6])).then(e=>({default:e.NewNotebookModal}))),PC=p.lazy(()=>Oe(()=>import("./NewBlockModal-B9TfRjt7.js"),__vite__mapDeps([34,6])).then(e=>({default:e.NewBlockModal}))),DC=p.lazy(()=>Oe(()=>import("./SetupOnboarding-BCcZlpuQ.js"),__vite__mapDeps([35,36,2,6])).then(e=>({default:e.SetupOnboarding}))),IC=p.lazy(()=>Oe(()=>import("./BlockStudio-Bl0aGQJR.js"),__vite__mapDeps([37,26,27,11,12,29,30,6,31,9,10,1,13,14,3,15,16,17,18,19,20,2,21,24,38,39])).then(e=>({default:e.BlockStudio}))),MC=p.lazy(()=>Oe(()=>import("./BusinessArtifactView-C4SZVNW-.js"),__vite__mapDeps([40,29,30,6,31])).then(e=>({default:e.BusinessArtifactView}))),$C=p.lazy(()=>Oe(()=>import("./LineageDetailView-CfbSvlPJ.js"),__vite__mapDeps([41,29,30,6,31,42,36,18])).then(e=>({default:e.LineageDetailView}))),LC=p.lazy(()=>Oe(()=>import("./LineageDAG-BiUFX2KL.js"),__vite__mapDeps([42,30,6,31])).then(e=>({default:e.LineageDAG}))),NC=p.lazy(()=>Oe(()=>import("./HelpDocsPage-BDPNVot1.js"),__vite__mapDeps([43,6])).then(e=>({default:e.HelpDocsPage}))),BC=p.lazy(()=>Oe(()=>Promise.resolve().then(()=>Jk),void 0).then(e=>({default:e.ConnectionPanel}))),FC=p.lazy(()=>Oe(()=>import("./GitPage-BfVD4tVq.js"),__vite__mapDeps([44,45,16,6])).then(e=>({default:e.GitPage}))),zC=p.lazy(()=>Oe(()=>import("./ReadinessPage-BROJ9YBM.js"),__vite__mapDeps([46,1,47,48,14,3,2,6])).then(e=>({default:e.ReadinessPage}))),qC=p.lazy(()=>Oe(()=>import("./AgentLogPage-CBGEoGmU.js"),__vite__mapDeps([49,36,12,50,6])).then(e=>({default:e.AgentLogPage}))),UC=p.lazy(()=>Oe(()=>import("./GovernedContextPage-D9f26ZFb.js").then(e=>e.G),__vite__mapDeps([51,3,14,21,17,16])).then(e=>({default:e.GovernedContextPage}))),WC=p.lazy(()=>Oe(()=>import("./DbtFirstModelingPage-B0uxitnx.js"),__vite__mapDeps([52,51,3,14,21,17,16,30,6,31,32,20,38,50,15])).then(e=>({default:e.DbtFirstModelingPage}))),KC=p.lazy(()=>Oe(()=>import("./AppsView-CUrqtEGC.js"),__vite__mapDeps([53,24,19,20,16,11,12,28,8,48,39,54,3,36,5,17,22,4,6])).then(e=>({default:e.AppsView}))),VC=p.lazy(()=>Oe(()=>import("./LineageDrawer-CgTScaGB.js"),__vite__mapDeps([55,29,30,6,31,38,16,19,15,54,45])).then(e=>({default:e.LineageDrawer}))),HC=p.lazy(()=>Oe(()=>import("./AiBuildDialog-CwAD3tXE.js"),__vite__mapDeps([56,47,13,14,3,15,16,6])).then(e=>({default:e.AiBuildDialog})));function GC(){const e=Ge(Pr(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=kn(),n=Qe[e.themeMode],r=p.useRef({}),o=e.mainView==="block_studio"||e.mainView==="imports",[i,c]=p.useState(!1),[a,l]=p.useState(null);p.useEffect(()=>{let d=!0;return B.getSetupLaunch().then(h=>{d&&(l(h),h.shouldOpen&&t({type:"OPEN_SETUP"}))}).catch(()=>{}),()=>{d=!1}},[t]),p.useEffect(()=>{if(e.mainView==="domains"||e.mainView==="modeling"||e.mainView==="skills")return;const d=EC(window.location.href),h=`${window.location.pathname}${window.location.search}${window.location.hash}`;d!==h&&window.history.replaceState(window.history.state,"",d)},[e.mainView]),vC(),kC(),p.useEffect(()=>{const d=h=>{(h.metaKey||h.ctrlKey)&&h.key.toLowerCase()==="k"&&!h.shiftKey&&(h.preventDefault(),c(m=>!m)),(h.metaKey||h.ctrlKey)&&h.shiftKey&&h.key.toLowerCase()==="i"&&(h.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 C=await B.openBlockStudio(d.path);t({type:"OPEN_BLOCK_STUDIO",file:d,payload:C});return}const{content:h}=await B.readNotebook(d.path),{title:m,cells:S,metadata:b}=R1(d.path,h),x=d.path.endsWith(".dqlnb")?await B.fetchRunSnapshot(d.path):null;let w=S;if(x!=null&&x.found&&x.snapshot){const C=new Map(x.snapshot.cells.map(k=>[k.cellId,k]));w=S.map(k=>{const v=C.get(k.id);return v?{...k,status:v.status??k.status,result:v.result??k.result,error:v.error??k.error,executionCount:v.executionCount??k.executionCount,execution:v.execution??k.execution,fromSnapshot:v.result!=null}:k})}t({type:"OPEN_FILE",file:d,cells:w,title:m,metadata:b}),e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"})}catch(h){if(console.error("Failed to open file:",h),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:[ja("sql")],title:d.name})}},[t,e.sidebarPanel]);p.useCallback(d=>{const h=r.current[d];h&&h.scrollIntoView({behavior:"smooth",block:"start"})},[]);const f=p.useCallback((d,h)=>{h?r.current[d]=h: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(fC,{}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[e.appMode==="studio"&&s.jsx(Iw,{}),e.appMode==="studio"&&e.sidebarOpen&&!o&&s.jsx(S1,{onOpenFile:u}),s.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:s.jsx(p.Suspense,{fallback:s.jsx(QC,{t:n}),children:e.mainView==="home"?s.jsx(TC,{}):e.mainView==="ask"?s.jsx(RC,{}):e.mainView==="business_artifact"?s.jsx(MC,{}):e.mainView==="lineage"?s.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:s.jsx(LC,{})}):e.mainView==="lineage_detail"?s.jsx($C,{}):e.mainView==="help"?s.jsx(NC,{}):e.mainView==="connection"||e.mainView==="settings"?s.jsx(YC,{children:s.jsx(BC,{variant:"page"})}):e.mainView==="git"?s.jsx(FC,{}):e.mainView==="readiness"?s.jsx(zC,{}):e.mainView==="skills"?s.jsx(UC,{initialTab:"skills"}):e.mainView==="domains"||e.mainView==="modeling"?s.jsx(WC,{}):e.mainView==="apps"?s.jsx(KC,{}):e.mainView==="agent_log"?s.jsx(XC,{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(qC,{})}):s.jsx(s.Fragment,{children:e.mainView==="imports"||e.mainView==="block_studio"?s.jsx(IC,{},"block-editor"):s.jsxs(s.Fragment,{children:[s.jsx(_C,{onOpenFile:u,registerCellRef:f}),e.appMode==="studio"&&s.jsx(bC,{})]})})})}),e.appMode==="studio"&&e.lineageDrawerOpen&&!e.lineageFullscreen&&!e.dashboardMode&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(VC,{})}),e.appMode==="studio"&&e.inspectorOpen&&!e.lineageFullscreen&&!e.lineageDrawerOpen&&!e.dashboardMode&&s.jsx(ww,{}),e.globalAi.open&&e.mainView==="apps"&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(AC,{})})]}),e.newNotebookModalOpen&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(OC,{onFileOpened:u})}),e.newBlockModalOpen&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(PC,{onFileOpened:u})}),s.jsx(FS,{open:i,onClose:()=>c(!1)}),s.jsx(p.Suspense,{fallback:null,children:s.jsx(HC,{})}),e.setupOpen&&s.jsx(p.Suspense,{fallback:s.jsx(JC,{t:n}),children:s.jsx(DC,{launch:a!=null&&a.shouldOpen?a:void 0,onAcknowledged:()=>l(d=>d&&{...d,shouldOpen:!1,reason:null})})})]})}function QC({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 JC({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 YC({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 XC({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 ZC(){const e=kn(),t=Hi(),n=p.useRef(null);p.useEffect(()=>{if(typeof EventSource>"u")return;let r=!0,o=null,i=null,c=null,a=null;const l=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,B.listNotebooks().then(h=>{r&&(t.setQueryData(["notebooks"],h),e({type:"SET_FILES",files:h}))}).catch(()=>{})},150)},u=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null,B.getDomains().then(({domains:h})=>{r&&(t.setQueryData(["authored-domains"],{domains:h}),e({type:"SET_AUTHORED_DOMAINS",domains:h}))}).catch(()=>{})},150)},f=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,e({type:"SET_SEMANTIC_LOADING",loading:!0}),B.getSemanticLayer().then(h=>{r&&(t.setQueryData(["semantic-layer"],h),e({type:"SET_SEMANTIC_LAYER",layer:h}))}).catch(()=>{})},100)},d=()=>{if(!r)return;const h=new EventSource(`${window.location.origin}/api/watch`);n.current=h,h.addEventListener("change",m=>{try{const S=JSON.parse(m.data);if(S.type==="file-added"||S.type==="file-deleted"||S.type==="file-changed"){const b=S.path??"";/^(?:notebooks|workbooks|blocks|skills|apps|dashboards)\//.test(b)&&l(),b.startsWith("domains/")&&(l(),u())}S.type==="semantic-reload"&&f()}catch{}}),h.addEventListener("error",()=>{h.close(),o&&clearTimeout(o),o=setTimeout(d,5e3)})};return d(),()=>{var h;r=!1,o&&clearTimeout(o),i&&clearTimeout(i),c&&clearTimeout(c),a&&clearTimeout(a),(h=n.current)==null||h.close(),n.current=null}},[e,t])}const ej=new Gf({defaultOptions:{queries:{staleTime:15e3,gcTime:5*6e4,retry:1,refetchOnWindowFocus:!1}}});function tj(){const e=Ge(i=>i.themeMode),t=Ge(i=>i.dispatch),n=Qe[e];p.useEffect(()=>{const i="dql-global-styles";let c=document.getElementById(i);c||(c=document.createElement("style"),c.id=i,document.head.appendChild(c)),c.textContent=`
610
+ * { margin: 0; padding: 0; box-sizing: border-box; }
611
+ body {
612
+ font-family: var(--font-ui, ${n.font});
613
+ overflow: hidden;
614
+ background: var(--color-bg-primary);
615
+ color: var(--color-text-primary);
616
+ }
617
+ ::-webkit-scrollbar { width: 6px; height: 6px; }
618
+ ::-webkit-scrollbar-track { background: transparent; }
619
+ ::-webkit-scrollbar-thumb {
620
+ background: var(--color-border-secondary);
621
+ border-radius: 3px;
622
+ }
623
+ ::-webkit-scrollbar-thumb:hover {
624
+ background: var(--color-text-tertiary);
625
+ }
626
+ ::selection {
627
+ background: color-mix(in srgb, var(--color-accent-blue) 25%, transparent);
628
+ color: var(--color-text-primary);
629
+ }
630
+ .dql-meta-pill:hover {
631
+ background: var(--dql-pill-hover-bg) !important;
632
+ border-color: var(--dql-pill-hover-border) !important;
633
+ }
634
+ `},[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=ji({queryKey:["notebooks"],queryFn:()=>B.listNotebooks()}),o=ji({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]),ZC(),s.jsx(lh,{theme:e,applyGlobal:!0,children:s.jsx(vg,{delayDuration:200,skipDelayDuration:400,children:s.jsx(GC,{})})})}function nj(){return s.jsx(Qf,{client:ej,children:s.jsx($x,{children:s.jsx(sC,{children:s.jsx(tj,{})})})})}wf.createRoot(document.getElementById("root")).render(s.jsx(nj,{}));export{pp as $,Wp as A,Ea as B,gv as C,So as D,P1 as E,Ra as F,Dr as G,Rj as H,Tj as I,Pn as J,ef as K,qn as L,bt as M,sS as N,Fj as O,yS as P,lk as Q,qe as R,hp as S,mp as T,wo as U,Qn as V,_w as W,mj as X,gj as Y,wj as Z,yj as _,B as a,_v as a$,cs as a0,Dk as a1,Bp as a2,Ys as a3,$i as a4,kj as a5,iC as a6,ji as a7,Pj as a8,J0 as a9,uj as aA,Gc as aB,tS as aC,Kx as aD,Qx as aE,Hv as aF,qv as aG,bv as aH,Kj as aI,nf as aJ,Wj as aK,Vj as aL,zj as aM,qj as aN,Uj as aO,_p as aP,CC as aQ,Cv as aR,dp as aS,R1 as aT,fv as aU,Oe as aV,Hi as aW,Cj as aX,Xv as aY,Ev as aZ,jS as a_,$j as aa,Lj as ab,B1 as ac,F1 as ad,Dj as ae,Ej as af,Kp as ag,Ij as ah,q1 as ai,z1 as aj,Oj as ak,Rl as al,Mj as am,fs as an,E0 as ao,Uc as ap,vj as aq,Sj as ar,xj as as,bj as at,bp as au,pj as av,fj as aw,hj as ax,vw as ay,Sw as az,Ae as b,Li as b0,_j as b1,Qi as b2,ip as b3,ne as c,Ta as d,As as e,lp as f,sv as g,Ge as h,Pr as i,s as j,kn as k,TS as l,ja as m,L1 as n,jj as o,yw as p,bw as q,p as r,Nj as s,Qe as t,et as u,Bj as v,Vp as w,Hp as x,Aj as y,M1 as z};