@duckcodeailabs/dql-cli 1.5.1 → 1.5.3
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.
- package/dist/apps-api.d.ts +45 -0
- package/dist/apps-api.d.ts.map +1 -1
- package/dist/apps-api.js +351 -12
- package/dist/apps-api.js.map +1 -1
- package/dist/apps-api.test.js +39 -2
- package/dist/apps-api.test.js.map +1 -1
- package/dist/assets/dql-notebook/assets/index-B5jI3I8Q.js +869 -0
- package/dist/assets/dql-notebook/assets/index-cv-O4BEj.css +1 -0
- package/dist/assets/dql-notebook/index.html +2 -2
- package/dist/block-studio-import.d.ts +51 -1
- package/dist/block-studio-import.d.ts.map +1 -1
- package/dist/block-studio-import.js +153 -18
- package/dist/block-studio-import.js.map +1 -1
- package/dist/block-studio-import.test.js +59 -1
- package/dist/block-studio-import.test.js.map +1 -1
- package/dist/local-runtime.d.ts +46 -0
- package/dist/local-runtime.d.ts.map +1 -1
- package/dist/local-runtime.js +716 -98
- package/dist/local-runtime.js.map +1 -1
- package/dist/local-runtime.test.js +61 -2
- package/dist/local-runtime.test.js.map +1 -1
- package/package.json +11 -11
- package/dist/assets/dql-notebook/assets/index-DZ2X3-OY.js +0 -862
- package/dist/assets/dql-notebook/assets/index-R3UrqjLQ.css +0 -1
|
@@ -0,0 +1,869 @@
|
|
|
1
|
+
import{r as Ia,a as cS,g as Oa}from"./react-CRB3T2We.js";import{S as Na,g as dS,E as jt,s as cI,a as Qe,b as uS,c as dI,P as uI,d as EI,e as fI,F as pI,f as TI,h as ES,V as SI,D as ir,R as hI,i as RI,C as vn,j as fS,k as At,r as AI,H as mI,t as be,l as gI,m as II,u as OI,n as NI,o as xI,p as yI,q as CI,v as LI,w as _I,x as bI,y as vI,z as Xs,A as DI,B as MI,G as PI,I as wI,J as UI,K as BI,L as jI,M as kI,N as FI,O as GI}from"./codemirror-DJYUkPr1.js";function HI(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const s in r)if(s!=="default"&&!(s in e)){const i=Object.getOwnPropertyDescriptor(r,s);i&&Object.defineProperty(e,s,i.get?i:{enumerable:!0,get:()=>r[s]})}}}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 s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();var xl={exports:{}},wo={};/**
|
|
2
|
+
* @license React
|
|
3
|
+
* react-jsx-runtime.production.min.js
|
|
4
|
+
*
|
|
5
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
6
|
+
*
|
|
7
|
+
* This source code is licensed under the MIT license found in the
|
|
8
|
+
* LICENSE file in the root directory of this source tree.
|
|
9
|
+
*/var rE;function WI(){if(rE)return wo;rE=1;var e=Ia(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,s=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function a(l,c,d){var u,E={},f=null,T=null;d!==void 0&&(f=""+d),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(T=c.ref);for(u in c)r.call(c,u)&&!i.hasOwnProperty(u)&&(E[u]=c[u]);if(l&&l.defaultProps)for(u in c=l.defaultProps,c)E[u]===void 0&&(E[u]=c[u]);return{$$typeof:t,type:l,key:f,ref:T,props:E,_owner:s.current}}return wo.Fragment=n,wo.jsx=a,wo.jsxs=a,wo}var oE;function YI(){return oE||(oE=1,xl.exports=WI()),xl.exports}var o=YI(),Ks={},sE;function $I(){if(sE)return Ks;sE=1;var e=cS();return Ks.createRoot=e.createRoot,Ks.hydrateRoot=e.hydrateRoot,Ks}var VI=$I(),p=Ia();const Be=Oa(p),pS=HI({__proto__:null,default:Be},[p]),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"},Ce={1:"4px",2:"8px",3:"12px",4:"16px"},Yn={sm:"4px",md:"6px",lg:"8px"},et={xs:"11px",sm:"12px",md:"14px"},Pd={medium:"500",semibold:"600"},Jo={overlay:1e3,modal:1100,popover:1200,tooltip:1300},yl={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)"},qs={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)"},zI={obsidian:yl,paper:qs,white:qs,dark:yl,light:qs,midnight:yl,arctic:qs};function TS(e){return`--dql-${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function iE(e){const t={};for(const[n,r]of Object.entries(e))t[TS(n)]=r;return t}function me(e){return`var(${TS(e)})`}const XI=p.createContext(null);function KI({theme:e,defaultTheme:t="dark",onThemeChange:n,applyGlobal:r=!1,children:s}){const[i,a]=p.useState(t),l=e??i,c=zI[l],d=p.useCallback(f=>{e===void 0&&a(f),n==null||n(f)},[e,n]);p.useEffect(()=>{if(!r)return;const f=iE(c),T=document.documentElement;for(const[A,R]of Object.entries(f))T.style.setProperty(A,R);return T.setAttribute("data-theme",l),()=>{for(const A of Object.keys(f))T.style.removeProperty(A);T.removeAttribute("data-theme")}},[r,l,c]);const u=p.useMemo(()=>({theme:l,tokens:c,setTheme:d}),[l,c,d]),E=r?void 0:iE(c);return o.jsx(XI.Provider,{value:u,children:o.jsx("div",{"data-theme":l,style:E,children:s})})}function he(e,t,{checkForDefaultPrevented:n=!0}={}){return function(s){if(e==null||e(s),n===!1||!s.defaultPrevented)return t==null?void 0:t(s)}}function aE(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function xa(...e){return t=>{let n=!1;const r=e.map(s=>{const i=aE(s,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let s=0;s<r.length;s++){const i=r[s];typeof i=="function"?i():aE(e[s],null)}}}}function ke(...e){return p.useCallback(xa(...e),e)}function qI(e,t){const n=p.createContext(t),r=i=>{const{children:a,...l}=i,c=p.useMemo(()=>l,Object.values(l));return o.jsx(n.Provider,{value:c,children:a})};r.displayName=e+"Provider";function s(i){const a=p.useContext(n);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return[r,s]}function $n(e,t=[]){let n=[];function r(i,a){const l=p.createContext(a),c=n.length;n=[...n,a];const d=E=>{var h;const{scope:f,children:T,...A}=E,R=((h=f==null?void 0:f[e])==null?void 0:h[c])||l,S=p.useMemo(()=>A,Object.values(A));return o.jsx(R.Provider,{value:S,children:T})};d.displayName=i+"Provider";function u(E,f){var R;const T=((R=f==null?void 0:f[e])==null?void 0:R[c])||l,A=p.useContext(T);if(A)return A;if(a!==void 0)return a;throw new Error(`\`${E}\` must be used within \`${i}\``)}return[d,u]}const s=()=>{const i=n.map(a=>p.createContext(a));return function(l){const c=(l==null?void 0:l[e])||i;return p.useMemo(()=>({[`__scope${e}`]:{...l,[e]:c}}),[l,c])}};return s.scopeName=e,[r,JI(s,...t)]}function JI(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(i){const a=r.reduce((l,{useScope:c,scopeName:d})=>{const E=c(i)[`__scope${d}`];return{...l,...E}},{});return p.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}var wd=cS();const QI=Oa(wd);function ro(e){const t=ZI(e),n=p.forwardRef((r,s)=>{const{children:i,...a}=r,l=p.Children.toArray(i),c=l.find(tO);if(c){const d=c.props.children,u=l.map(E=>E===c?p.Children.count(d)>1?p.Children.only(null):p.isValidElement(d)?d.props.children:null:E);return o.jsx(t,{...a,ref:s,children:p.isValidElement(d)?p.cloneElement(d,void 0,u):null})}return o.jsx(t,{...a,ref:s,children:i})});return n.displayName=`${e}.Slot`,n}function ZI(e){const t=p.forwardRef((n,r)=>{const{children:s,...i}=n;if(p.isValidElement(s)){const a=rO(s),l=nO(i,s.props);return s.type!==p.Fragment&&(l.ref=r?xa(r,a):a),p.cloneElement(s,l)}return p.Children.count(s)>1?p.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var SS=Symbol("radix.slottable");function eO(e){const t=({children:n})=>o.jsx(o.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=SS,t}function tO(e){return p.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===SS}function nO(e,t){const n={...t};for(const r in t){const s=e[r],i=t[r];/^on[A-Z]/.test(r)?s&&i?n[r]=(...l)=>{const c=i(...l);return s(...l),c}:s&&(n[r]=s):r==="style"?n[r]={...s,...i}:r==="className"&&(n[r]=[s,i].filter(Boolean).join(" "))}return{...e,...n}}function rO(e){var r,s;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=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var oO=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Pe=oO.reduce((e,t)=>{const n=ro(`Primitive.${t}`),r=p.forwardRef((s,i)=>{const{asChild:a,...l}=s,c=a?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(c,{...l,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function hS(e,t){e&&wd.flushSync(()=>e.dispatchEvent(t))}function Bn(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 sO(e,t=globalThis==null?void 0:globalThis.document){const n=Bn(e);p.useEffect(()=>{const r=s=>{s.key==="Escape"&&n(s)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var iO="DismissableLayer",$c="dismissableLayer.update",aO="dismissableLayer.pointerDownOutside",lO="dismissableLayer.focusOutside",lE,RS=p.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Rs=p.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:i,onInteractOutside:a,onDismiss:l,...c}=e,d=p.useContext(RS),[u,E]=p.useState(null),f=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,T]=p.useState({}),A=ke(t,x=>E(x)),R=Array.from(d.layers),[S]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),h=R.indexOf(S),g=u?R.indexOf(u):-1,m=d.layersWithOutsidePointerEventsDisabled.size>0,I=g>=h,O=uO(x=>{const _=x.target,C=[...d.branches].some(v=>v.contains(_));!I||C||(s==null||s(x),a==null||a(x),x.defaultPrevented||l==null||l())},f),N=EO(x=>{const _=x.target;[...d.branches].some(v=>v.contains(_))||(i==null||i(x),a==null||a(x),x.defaultPrevented||l==null||l())},f);return sO(x=>{g===d.layers.size-1&&(r==null||r(x),!x.defaultPrevented&&l&&(x.preventDefault(),l()))},f),p.useEffect(()=>{if(u)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(lE=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(u)),d.layers.add(u),cE(),()=>{n&&d.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=lE)}},[u,f,n,d]),p.useEffect(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),cE())},[u,d]),p.useEffect(()=>{const x=()=>T({});return document.addEventListener($c,x),()=>document.removeEventListener($c,x)},[]),o.jsx(Pe.div,{...c,ref:A,style:{pointerEvents:m?I?"auto":"none":void 0,...e.style},onFocusCapture:he(e.onFocusCapture,N.onFocusCapture),onBlurCapture:he(e.onBlurCapture,N.onBlurCapture),onPointerDownCapture:he(e.onPointerDownCapture,O.onPointerDownCapture)})});Rs.displayName=iO;var cO="DismissableLayerBranch",dO=p.forwardRef((e,t)=>{const n=p.useContext(RS),r=p.useRef(null),s=ke(t,r);return p.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),o.jsx(Pe.div,{...e,ref:s})});dO.displayName=cO;function uO(e,t=globalThis==null?void 0:globalThis.document){const n=Bn(e),r=p.useRef(!1),s=p.useRef(()=>{});return p.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let c=function(){AS(aO,n,d,{discrete:!0})};const d={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",s.current),s.current=c,t.addEventListener("click",s.current,{once:!0})):c()}else t.removeEventListener("click",s.current);r.current=!1},a=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(a),t.removeEventListener("pointerdown",i),t.removeEventListener("click",s.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function EO(e,t=globalThis==null?void 0:globalThis.document){const n=Bn(e),r=p.useRef(!1);return p.useEffect(()=>{const s=i=>{i.target&&!r.current&&AS(lO,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",s),()=>t.removeEventListener("focusin",s)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function cE(){const e=new CustomEvent($c);document.dispatchEvent(e)}function AS(e,t,n,{discrete:r}){const s=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&s.addEventListener(e,t,{once:!0}),r?hS(s,i):s.dispatchEvent(i)}var jn=globalThis!=null&&globalThis.document?p.useLayoutEffect:()=>{},fO=pS[" useId ".trim().toString()]||(()=>{}),pO=0;function Vo(e){const[t,n]=p.useState(fO());return jn(()=>{n(r=>r??String(pO++))},[e]),t?`radix-${t}`:""}const TO=["top","right","bottom","left"],kn=Math.min,dt=Math.max,Wi=Math.round,Js=Math.floor,en=e=>({x:e,y:e}),SO={left:"right",right:"left",bottom:"top",top:"bottom"};function Vc(e,t,n){return dt(e,kn(t,n))}function fn(e,t){return typeof e=="function"?e(t):e}function pn(e){return e.split("-")[0]}function mo(e){return e.split("-")[1]}function Ud(e){return e==="x"?"y":"x"}function Bd(e){return e==="y"?"height":"width"}function Qt(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function jd(e){return Ud(Qt(e))}function hO(e,t,n){n===void 0&&(n=!1);const r=mo(e),s=jd(e),i=Bd(s);let a=s==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(a=Yi(a)),[a,Yi(a)]}function RO(e){const t=Yi(e);return[zc(e),t,zc(t)]}function zc(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const dE=["left","right"],uE=["right","left"],AO=["top","bottom"],mO=["bottom","top"];function gO(e,t,n){switch(e){case"top":case"bottom":return n?t?uE:dE:t?dE:uE;case"left":case"right":return t?AO:mO;default:return[]}}function IO(e,t,n,r){const s=mo(e);let i=gO(pn(e),n==="start",r);return s&&(i=i.map(a=>a+"-"+s),t&&(i=i.concat(i.map(zc)))),i}function Yi(e){const t=pn(e);return SO[t]+e.slice(t.length)}function OO(e){return{top:0,right:0,bottom:0,left:0,...e}}function mS(e){return typeof e!="number"?OO(e):{top:e,right:e,bottom:e,left:e}}function $i(e){const{x:t,y:n,width:r,height:s}=e;return{width:r,height:s,top:n,left:t,right:t+r,bottom:n+s,x:t,y:n}}function EE(e,t,n){let{reference:r,floating:s}=e;const i=Qt(t),a=jd(t),l=Bd(a),c=pn(t),d=i==="y",u=r.x+r.width/2-s.width/2,E=r.y+r.height/2-s.height/2,f=r[l]/2-s[l]/2;let T;switch(c){case"top":T={x:u,y:r.y-s.height};break;case"bottom":T={x:u,y:r.y+r.height};break;case"right":T={x:r.x+r.width,y:E};break;case"left":T={x:r.x-s.width,y:E};break;default:T={x:r.x,y:r.y}}switch(mo(t)){case"start":T[a]-=f*(n&&d?-1:1);break;case"end":T[a]+=f*(n&&d?-1:1);break}return T}async function NO(e,t){var n;t===void 0&&(t={});const{x:r,y:s,platform:i,rects:a,elements:l,strategy:c}=e,{boundary:d="clippingAncestors",rootBoundary:u="viewport",elementContext:E="floating",altBoundary:f=!1,padding:T=0}=fn(t,e),A=mS(T),S=l[f?E==="floating"?"reference":"floating":E],h=$i(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(S)))==null||n?S:S.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(l.floating)),boundary:d,rootBoundary:u,strategy:c})),g=E==="floating"?{x:r,y:s,width:a.floating.width,height:a.floating.height}:a.reference,m=await(i.getOffsetParent==null?void 0:i.getOffsetParent(l.floating)),I=await(i.isElement==null?void 0:i.isElement(m))?await(i.getScale==null?void 0:i.getScale(m))||{x:1,y:1}:{x:1,y:1},O=$i(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:g,offsetParent:m,strategy:c}):g);return{top:(h.top-O.top+A.top)/I.y,bottom:(O.bottom-h.bottom+A.bottom)/I.y,left:(h.left-O.left+A.left)/I.x,right:(O.right-h.right+A.right)/I.x}}const xO=50,yO=async(e,t,n)=>{const{placement:r="bottom",strategy:s="absolute",middleware:i=[],platform:a}=n,l=a.detectOverflow?a:{...a,detectOverflow:NO},c=await(a.isRTL==null?void 0:a.isRTL(t));let d=await a.getElementRects({reference:e,floating:t,strategy:s}),{x:u,y:E}=EE(d,r,c),f=r,T=0;const A={};for(let R=0;R<i.length;R++){const S=i[R];if(!S)continue;const{name:h,fn:g}=S,{x:m,y:I,data:O,reset:N}=await g({x:u,y:E,initialPlacement:r,placement:f,strategy:s,middlewareData:A,rects:d,platform:l,elements:{reference:e,floating:t}});u=m??u,E=I??E,A[h]={...A[h],...O},N&&T<xO&&(T++,typeof N=="object"&&(N.placement&&(f=N.placement),N.rects&&(d=N.rects===!0?await a.getElementRects({reference:e,floating:t,strategy:s}):N.rects),{x:u,y:E}=EE(d,f,c)),R=-1)}return{x:u,y:E,placement:f,strategy:s,middlewareData:A}},CO=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:s,rects:i,platform:a,elements:l,middlewareData:c}=t,{element:d,padding:u=0}=fn(e,t)||{};if(d==null)return{};const E=mS(u),f={x:n,y:r},T=jd(s),A=Bd(T),R=await a.getDimensions(d),S=T==="y",h=S?"top":"left",g=S?"bottom":"right",m=S?"clientHeight":"clientWidth",I=i.reference[A]+i.reference[T]-f[T]-i.floating[A],O=f[T]-i.reference[T],N=await(a.getOffsetParent==null?void 0:a.getOffsetParent(d));let x=N?N[m]:0;(!x||!await(a.isElement==null?void 0:a.isElement(N)))&&(x=l.floating[m]||i.floating[A]);const _=I/2-O/2,C=x/2-R[A]/2-1,v=kn(E[h],C),b=kn(E[g],C),P=v,j=x-R[A]-b,L=x/2-R[A]/2+_,B=Vc(P,L,j),M=!c.arrow&&mo(s)!=null&&L!==B&&i.reference[A]/2-(L<P?v:b)-R[A]/2<0,U=M?L<P?L-P:L-j:0;return{[T]:f[T]+U,data:{[T]:B,centerOffset:L-B-U,...M&&{alignmentOffset:U}},reset:M}}}),LO=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:s,middlewareData:i,rects:a,initialPlacement:l,platform:c,elements:d}=t,{mainAxis:u=!0,crossAxis:E=!0,fallbackPlacements:f,fallbackStrategy:T="bestFit",fallbackAxisSideDirection:A="none",flipAlignment:R=!0,...S}=fn(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const h=pn(s),g=Qt(l),m=pn(l)===l,I=await(c.isRTL==null?void 0:c.isRTL(d.floating)),O=f||(m||!R?[Yi(l)]:RO(l)),N=A!=="none";!f&&N&&O.push(...IO(l,R,A,I));const x=[l,...O],_=await c.detectOverflow(t,S),C=[];let v=((r=i.flip)==null?void 0:r.overflows)||[];if(u&&C.push(_[h]),E){const L=hO(s,a,I);C.push(_[L[0]],_[L[1]])}if(v=[...v,{placement:s,overflows:C}],!C.every(L=>L<=0)){var b,P;const L=(((b=i.flip)==null?void 0:b.index)||0)+1,B=x[L];if(B&&(!(E==="alignment"?g!==Qt(B):!1)||v.every(D=>Qt(D.placement)===g?D.overflows[0]>0:!0)))return{data:{index:L,overflows:v},reset:{placement:B}};let M=(P=v.filter(U=>U.overflows[0]<=0).sort((U,D)=>U.overflows[1]-D.overflows[1])[0])==null?void 0:P.placement;if(!M)switch(T){case"bestFit":{var j;const U=(j=v.filter(D=>{if(N){const y=Qt(D.placement);return y===g||y==="y"}return!0}).map(D=>[D.placement,D.overflows.filter(y=>y>0).reduce((y,w)=>y+w,0)]).sort((D,y)=>D[1]-y[1])[0])==null?void 0:j[0];U&&(M=U);break}case"initialPlacement":M=l;break}if(s!==M)return{reset:{placement:M}}}return{}}}};function fE(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function pE(e){return TO.some(t=>e[t]>=0)}const _O=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:s="referenceHidden",...i}=fn(e,t);switch(s){case"referenceHidden":{const a=await r.detectOverflow(t,{...i,elementContext:"reference"}),l=fE(a,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:pE(l)}}}case"escaped":{const a=await r.detectOverflow(t,{...i,altBoundary:!0}),l=fE(a,n.floating);return{data:{escapedOffsets:l,escaped:pE(l)}}}default:return{}}}}},gS=new Set(["left","top"]);async function bO(e,t){const{placement:n,platform:r,elements:s}=e,i=await(r.isRTL==null?void 0:r.isRTL(s.floating)),a=pn(n),l=mo(n),c=Qt(n)==="y",d=gS.has(a)?-1:1,u=i&&c?-1:1,E=fn(t,e);let{mainAxis:f,crossAxis:T,alignmentAxis:A}=typeof E=="number"?{mainAxis:E,crossAxis:0,alignmentAxis:null}:{mainAxis:E.mainAxis||0,crossAxis:E.crossAxis||0,alignmentAxis:E.alignmentAxis};return l&&typeof A=="number"&&(T=l==="end"?A*-1:A),c?{x:T*u,y:f*d}:{x:f*d,y:T*u}}const vO=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:s,y:i,placement:a,middlewareData:l}=t,c=await bO(t,e);return a===((n=l.offset)==null?void 0:n.placement)&&(r=l.arrow)!=null&&r.alignmentOffset?{}:{x:s+c.x,y:i+c.y,data:{...c,placement:a}}}}},DO=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:s,platform:i}=t,{mainAxis:a=!0,crossAxis:l=!1,limiter:c={fn:h=>{let{x:g,y:m}=h;return{x:g,y:m}}},...d}=fn(e,t),u={x:n,y:r},E=await i.detectOverflow(t,d),f=Qt(pn(s)),T=Ud(f);let A=u[T],R=u[f];if(a){const h=T==="y"?"top":"left",g=T==="y"?"bottom":"right",m=A+E[h],I=A-E[g];A=Vc(m,A,I)}if(l){const h=f==="y"?"top":"left",g=f==="y"?"bottom":"right",m=R+E[h],I=R-E[g];R=Vc(m,R,I)}const S=c.fn({...t,[T]:A,[f]:R});return{...S,data:{x:S.x-n,y:S.y-r,enabled:{[T]:a,[f]:l}}}}}},MO=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:s,rects:i,middlewareData:a}=t,{offset:l=0,mainAxis:c=!0,crossAxis:d=!0}=fn(e,t),u={x:n,y:r},E=Qt(s),f=Ud(E);let T=u[f],A=u[E];const R=fn(l,t),S=typeof R=="number"?{mainAxis:R,crossAxis:0}:{mainAxis:0,crossAxis:0,...R};if(c){const m=f==="y"?"height":"width",I=i.reference[f]-i.floating[m]+S.mainAxis,O=i.reference[f]+i.reference[m]-S.mainAxis;T<I?T=I:T>O&&(T=O)}if(d){var h,g;const m=f==="y"?"width":"height",I=gS.has(pn(s)),O=i.reference[E]-i.floating[m]+(I&&((h=a.offset)==null?void 0:h[E])||0)+(I?0:S.crossAxis),N=i.reference[E]+i.reference[m]+(I?0:((g=a.offset)==null?void 0:g[E])||0)-(I?S.crossAxis:0);A<O?A=O:A>N&&(A=N)}return{[f]:T,[E]:A}}}},PO=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:s,rects:i,platform:a,elements:l}=t,{apply:c=()=>{},...d}=fn(e,t),u=await a.detectOverflow(t,d),E=pn(s),f=mo(s),T=Qt(s)==="y",{width:A,height:R}=i.floating;let S,h;E==="top"||E==="bottom"?(S=E,h=f===(await(a.isRTL==null?void 0:a.isRTL(l.floating))?"start":"end")?"left":"right"):(h=E,S=f==="end"?"top":"bottom");const g=R-u.top-u.bottom,m=A-u.left-u.right,I=kn(R-u[S],g),O=kn(A-u[h],m),N=!t.middlewareData.shift;let x=I,_=O;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(_=m),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(x=g),N&&!f){const v=dt(u.left,0),b=dt(u.right,0),P=dt(u.top,0),j=dt(u.bottom,0);T?_=A-2*(v!==0||b!==0?v+b:dt(u.left,u.right)):x=R-2*(P!==0||j!==0?P+j:dt(u.top,u.bottom))}await c({...t,availableWidth:_,availableHeight:x});const C=await a.getDimensions(l.floating);return A!==C.width||R!==C.height?{reset:{rects:!0}}:{}}}};function ya(){return typeof window<"u"}function go(e){return IS(e)?(e.nodeName||"").toLowerCase():"#document"}function ft(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function on(e){var t;return(t=(IS(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function IS(e){return ya()?e instanceof Node||e instanceof ft(e).Node:!1}function kt(e){return ya()?e instanceof Element||e instanceof ft(e).Element:!1}function hn(e){return ya()?e instanceof HTMLElement||e instanceof ft(e).HTMLElement:!1}function TE(e){return!ya()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof ft(e).ShadowRoot}function As(e){const{overflow:t,overflowX:n,overflowY:r,display:s}=Ft(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&s!=="inline"&&s!=="contents"}function wO(e){return/^(table|td|th)$/.test(go(e))}function Ca(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const UO=/transform|translate|scale|rotate|perspective|filter/,BO=/paint|layout|strict|content/,er=e=>!!e&&e!=="none";let Cl;function kd(e){const t=kt(e)?Ft(e):e;return er(t.transform)||er(t.translate)||er(t.scale)||er(t.rotate)||er(t.perspective)||!Fd()&&(er(t.backdropFilter)||er(t.filter))||UO.test(t.willChange||"")||BO.test(t.contain||"")}function jO(e){let t=Fn(e);for(;hn(t)&&!oo(t);){if(kd(t))return t;if(Ca(t))return null;t=Fn(t)}return null}function Fd(){return Cl==null&&(Cl=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Cl}function oo(e){return/^(html|body|#document)$/.test(go(e))}function Ft(e){return ft(e).getComputedStyle(e)}function La(e){return kt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Fn(e){if(go(e)==="html")return e;const t=e.assignedSlot||e.parentNode||TE(e)&&e.host||on(e);return TE(t)?t.host:t}function OS(e){const t=Fn(e);return oo(t)?e.ownerDocument?e.ownerDocument.body:e.body:hn(t)&&As(t)?t:OS(t)}function Qo(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const s=OS(e),i=s===((r=e.ownerDocument)==null?void 0:r.body),a=ft(s);if(i){const l=Xc(a);return t.concat(a,a.visualViewport||[],As(s)?s:[],l&&n?Qo(l):[])}else return t.concat(s,Qo(s,[],n))}function Xc(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function NS(e){const t=Ft(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const s=hn(e),i=s?e.offsetWidth:n,a=s?e.offsetHeight:r,l=Wi(n)!==i||Wi(r)!==a;return l&&(n=i,r=a),{width:n,height:r,$:l}}function Gd(e){return kt(e)?e:e.contextElement}function qr(e){const t=Gd(e);if(!hn(t))return en(1);const n=t.getBoundingClientRect(),{width:r,height:s,$:i}=NS(t);let a=(i?Wi(n.width):n.width)/r,l=(i?Wi(n.height):n.height)/s;return(!a||!Number.isFinite(a))&&(a=1),(!l||!Number.isFinite(l))&&(l=1),{x:a,y:l}}const kO=en(0);function xS(e){const t=ft(e);return!Fd()||!t.visualViewport?kO:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function FO(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==ft(e)?!1:t}function Er(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const s=e.getBoundingClientRect(),i=Gd(e);let a=en(1);t&&(r?kt(r)&&(a=qr(r)):a=qr(e));const l=FO(i,n,r)?xS(i):en(0);let c=(s.left+l.x)/a.x,d=(s.top+l.y)/a.y,u=s.width/a.x,E=s.height/a.y;if(i){const f=ft(i),T=r&&kt(r)?ft(r):r;let A=f,R=Xc(A);for(;R&&r&&T!==A;){const S=qr(R),h=R.getBoundingClientRect(),g=Ft(R),m=h.left+(R.clientLeft+parseFloat(g.paddingLeft))*S.x,I=h.top+(R.clientTop+parseFloat(g.paddingTop))*S.y;c*=S.x,d*=S.y,u*=S.x,E*=S.y,c+=m,d+=I,A=ft(R),R=Xc(A)}}return $i({width:u,height:E,x:c,y:d})}function _a(e,t){const n=La(e).scrollLeft;return t?t.left+n:Er(on(e)).left+n}function yS(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-_a(e,n),s=n.top+t.scrollTop;return{x:r,y:s}}function GO(e){let{elements:t,rect:n,offsetParent:r,strategy:s}=e;const i=s==="fixed",a=on(r),l=t?Ca(t.floating):!1;if(r===a||l&&i)return n;let c={scrollLeft:0,scrollTop:0},d=en(1);const u=en(0),E=hn(r);if((E||!E&&!i)&&((go(r)!=="body"||As(a))&&(c=La(r)),E)){const T=Er(r);d=qr(r),u.x=T.x+r.clientLeft,u.y=T.y+r.clientTop}const f=a&&!E&&!i?yS(a,c):en(0);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-c.scrollLeft*d.x+u.x+f.x,y:n.y*d.y-c.scrollTop*d.y+u.y+f.y}}function HO(e){return Array.from(e.getClientRects())}function WO(e){const t=on(e),n=La(e),r=e.ownerDocument.body,s=dt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=dt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let a=-n.scrollLeft+_a(e);const l=-n.scrollTop;return Ft(r).direction==="rtl"&&(a+=dt(t.clientWidth,r.clientWidth)-s),{width:s,height:i,x:a,y:l}}const SE=25;function YO(e,t){const n=ft(e),r=on(e),s=n.visualViewport;let i=r.clientWidth,a=r.clientHeight,l=0,c=0;if(s){i=s.width,a=s.height;const u=Fd();(!u||u&&t==="fixed")&&(l=s.offsetLeft,c=s.offsetTop)}const d=_a(r);if(d<=0){const u=r.ownerDocument,E=u.body,f=getComputedStyle(E),T=u.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,A=Math.abs(r.clientWidth-E.clientWidth-T);A<=SE&&(i-=A)}else d<=SE&&(i+=d);return{width:i,height:a,x:l,y:c}}function $O(e,t){const n=Er(e,!0,t==="fixed"),r=n.top+e.clientTop,s=n.left+e.clientLeft,i=hn(e)?qr(e):en(1),a=e.clientWidth*i.x,l=e.clientHeight*i.y,c=s*i.x,d=r*i.y;return{width:a,height:l,x:c,y:d}}function hE(e,t,n){let r;if(t==="viewport")r=YO(e,n);else if(t==="document")r=WO(on(e));else if(kt(t))r=$O(t,n);else{const s=xS(e);r={x:t.x-s.x,y:t.y-s.y,width:t.width,height:t.height}}return $i(r)}function CS(e,t){const n=Fn(e);return n===t||!kt(n)||oo(n)?!1:Ft(n).position==="fixed"||CS(n,t)}function VO(e,t){const n=t.get(e);if(n)return n;let r=Qo(e,[],!1).filter(l=>kt(l)&&go(l)!=="body"),s=null;const i=Ft(e).position==="fixed";let a=i?Fn(e):e;for(;kt(a)&&!oo(a);){const l=Ft(a),c=kd(a);!c&&l.position==="fixed"&&(s=null),(i?!c&&!s:!c&&l.position==="static"&&!!s&&(s.position==="absolute"||s.position==="fixed")||As(a)&&!c&&CS(e,a))?r=r.filter(u=>u!==a):s=l,a=Fn(a)}return t.set(e,r),r}function zO(e){let{element:t,boundary:n,rootBoundary:r,strategy:s}=e;const a=[...n==="clippingAncestors"?Ca(t)?[]:VO(t,this._c):[].concat(n),r],l=hE(t,a[0],s);let c=l.top,d=l.right,u=l.bottom,E=l.left;for(let f=1;f<a.length;f++){const T=hE(t,a[f],s);c=dt(T.top,c),d=kn(T.right,d),u=kn(T.bottom,u),E=dt(T.left,E)}return{width:d-E,height:u-c,x:E,y:c}}function XO(e){const{width:t,height:n}=NS(e);return{width:t,height:n}}function KO(e,t,n){const r=hn(t),s=on(t),i=n==="fixed",a=Er(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const c=en(0);function d(){c.x=_a(s)}if(r||!r&&!i)if((go(t)!=="body"||As(s))&&(l=La(t)),r){const T=Er(t,!0,i,t);c.x=T.x+t.clientLeft,c.y=T.y+t.clientTop}else s&&d();i&&!r&&s&&d();const u=s&&!r&&!i?yS(s,l):en(0),E=a.left+l.scrollLeft-c.x-u.x,f=a.top+l.scrollTop-c.y-u.y;return{x:E,y:f,width:a.width,height:a.height}}function Ll(e){return Ft(e).position==="static"}function RE(e,t){if(!hn(e)||Ft(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return on(e)===n&&(n=n.ownerDocument.body),n}function LS(e,t){const n=ft(e);if(Ca(e))return n;if(!hn(e)){let s=Fn(e);for(;s&&!oo(s);){if(kt(s)&&!Ll(s))return s;s=Fn(s)}return n}let r=RE(e,t);for(;r&&wO(r)&&Ll(r);)r=RE(r,t);return r&&oo(r)&&Ll(r)&&!kd(r)?n:r||jO(e)||n}const qO=async function(e){const t=this.getOffsetParent||LS,n=this.getDimensions,r=await n(e.floating);return{reference:KO(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function JO(e){return Ft(e).direction==="rtl"}const QO={convertOffsetParentRelativeRectToViewportRelativeRect:GO,getDocumentElement:on,getClippingRect:zO,getOffsetParent:LS,getElementRects:qO,getClientRects:HO,getDimensions:XO,getScale:qr,isElement:kt,isRTL:JO};function _S(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function ZO(e,t){let n=null,r;const s=on(e);function i(){var l;clearTimeout(r),(l=n)==null||l.disconnect(),n=null}function a(l,c){l===void 0&&(l=!1),c===void 0&&(c=1),i();const d=e.getBoundingClientRect(),{left:u,top:E,width:f,height:T}=d;if(l||t(),!f||!T)return;const A=Js(E),R=Js(s.clientWidth-(u+f)),S=Js(s.clientHeight-(E+T)),h=Js(u),m={rootMargin:-A+"px "+-R+"px "+-S+"px "+-h+"px",threshold:dt(0,kn(1,c))||1};let I=!0;function O(N){const x=N[0].intersectionRatio;if(x!==c){if(!I)return a();x?a(!1,x):r=setTimeout(()=>{a(!1,1e-7)},1e3)}x===1&&!_S(d,e.getBoundingClientRect())&&a(),I=!1}try{n=new IntersectionObserver(O,{...m,root:s.ownerDocument})}catch{n=new IntersectionObserver(O,m)}n.observe(e)}return a(!0),i}function eN(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:s=!0,ancestorResize:i=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:c=!1}=r,d=Gd(e),u=s||i?[...d?Qo(d):[],...t?Qo(t):[]]:[];u.forEach(h=>{s&&h.addEventListener("scroll",n,{passive:!0}),i&&h.addEventListener("resize",n)});const E=d&&l?ZO(d,n):null;let f=-1,T=null;a&&(T=new ResizeObserver(h=>{let[g]=h;g&&g.target===d&&T&&t&&(T.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var m;(m=T)==null||m.observe(t)})),n()}),d&&!c&&T.observe(d),t&&T.observe(t));let A,R=c?Er(e):null;c&&S();function S(){const h=Er(e);R&&!_S(R,h)&&n(),R=h,A=requestAnimationFrame(S)}return n(),()=>{var h;u.forEach(g=>{s&&g.removeEventListener("scroll",n),i&&g.removeEventListener("resize",n)}),E==null||E(),(h=T)==null||h.disconnect(),T=null,c&&cancelAnimationFrame(A)}}const tN=vO,nN=DO,rN=LO,oN=PO,sN=_O,AE=CO,iN=MO,aN=(e,t,n)=>{const r=new Map,s={platform:QO,...n},i={...s.platform,_c:r};return yO(e,t,{...s,platform:i})};var lN=typeof document<"u",cN=function(){},_i=lN?p.useLayoutEffect:cN;function Vi(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,s;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(!Vi(e[r],t[r]))return!1;return!0}if(s=Object.keys(e),n=s.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,s[r]))return!1;for(r=n;r--!==0;){const i=s[r];if(!(i==="_owner"&&e.$$typeof)&&!Vi(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function bS(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function mE(e,t){const n=bS(e);return Math.round(t*n)/n}function _l(e){const t=p.useRef(e);return _i(()=>{t.current=e}),t}function dN(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:s,elements:{reference:i,floating:a}={},transform:l=!0,whileElementsMounted:c,open:d}=e,[u,E]=p.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,T]=p.useState(r);Vi(f,r)||T(r);const[A,R]=p.useState(null),[S,h]=p.useState(null),g=p.useCallback(D=>{D!==N.current&&(N.current=D,R(D))},[]),m=p.useCallback(D=>{D!==x.current&&(x.current=D,h(D))},[]),I=i||A,O=a||S,N=p.useRef(null),x=p.useRef(null),_=p.useRef(u),C=c!=null,v=_l(c),b=_l(s),P=_l(d),j=p.useCallback(()=>{if(!N.current||!x.current)return;const D={placement:t,strategy:n,middleware:f};b.current&&(D.platform=b.current),aN(N.current,x.current,D).then(y=>{const w={...y,isPositioned:P.current!==!1};L.current&&!Vi(_.current,w)&&(_.current=w,wd.flushSync(()=>{E(w)}))})},[f,t,n,b,P]);_i(()=>{d===!1&&_.current.isPositioned&&(_.current.isPositioned=!1,E(D=>({...D,isPositioned:!1})))},[d]);const L=p.useRef(!1);_i(()=>(L.current=!0,()=>{L.current=!1}),[]),_i(()=>{if(I&&(N.current=I),O&&(x.current=O),I&&O){if(v.current)return v.current(I,O,j);j()}},[I,O,j,v,C]);const B=p.useMemo(()=>({reference:N,floating:x,setReference:g,setFloating:m}),[g,m]),M=p.useMemo(()=>({reference:I,floating:O}),[I,O]),U=p.useMemo(()=>{const D={position:n,left:0,top:0};if(!M.floating)return D;const y=mE(M.floating,u.x),w=mE(M.floating,u.y);return l?{...D,transform:"translate("+y+"px, "+w+"px)",...bS(M.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:y,top:w}},[n,l,M.floating,u.x,u.y]);return p.useMemo(()=>({...u,update:j,refs:B,elements:M,floatingStyles:U}),[u,j,B,M,U])}const uN=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:s}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?AE({element:r.current,padding:s}).fn(n):{}:r?AE({element:r,padding:s}).fn(n):{}}}},EN=(e,t)=>{const n=tN(e);return{name:n.name,fn:n.fn,options:[e,t]}},fN=(e,t)=>{const n=nN(e);return{name:n.name,fn:n.fn,options:[e,t]}},pN=(e,t)=>({fn:iN(e).fn,options:[e,t]}),TN=(e,t)=>{const n=rN(e);return{name:n.name,fn:n.fn,options:[e,t]}},SN=(e,t)=>{const n=oN(e);return{name:n.name,fn:n.fn,options:[e,t]}},hN=(e,t)=>{const n=sN(e);return{name:n.name,fn:n.fn,options:[e,t]}},RN=(e,t)=>{const n=uN(e);return{name:n.name,fn:n.fn,options:[e,t]}};var AN="Arrow",vS=p.forwardRef((e,t)=>{const{children:n,width:r=10,height:s=5,...i}=e;return o.jsx(Pe.svg,{...i,ref:t,width:r,height:s,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:o.jsx("polygon",{points:"0,0 30,0 15,10"})})});vS.displayName=AN;var mN=vS;function gN(e){const[t,n]=p.useState(void 0);return jn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;const i=s[0];let a,l;if("borderBoxSize"in i){const c=i.borderBoxSize,d=Array.isArray(c)?c[0]:c;a=d.inlineSize,l=d.blockSize}else a=e.offsetWidth,l=e.offsetHeight;n({width:a,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Hd="Popper",[DS,Io]=$n(Hd),[IN,MS]=DS(Hd),PS=e=>{const{__scopePopper:t,children:n}=e,[r,s]=p.useState(null);return o.jsx(IN,{scope:t,anchor:r,onAnchorChange:s,children:n})};PS.displayName=Hd;var wS="PopperAnchor",US=p.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...s}=e,i=MS(wS,n),a=p.useRef(null),l=ke(t,a),c=p.useRef(null);return p.useEffect(()=>{const d=c.current;c.current=(r==null?void 0:r.current)||a.current,d!==c.current&&i.onAnchorChange(c.current)}),r?null:o.jsx(Pe.div,{...s,ref:l})});US.displayName=wS;var Wd="PopperContent",[ON,NN]=DS(Wd),BS=p.forwardRef((e,t)=>{var ne,z,oe,le,ae,X;const{__scopePopper:n,side:r="bottom",sideOffset:s=0,align:i="center",alignOffset:a=0,arrowPadding:l=0,avoidCollisions:c=!0,collisionBoundary:d=[],collisionPadding:u=0,sticky:E="partial",hideWhenDetached:f=!1,updatePositionStrategy:T="optimized",onPlaced:A,...R}=e,S=MS(Wd,n),[h,g]=p.useState(null),m=ke(t,H=>g(H)),[I,O]=p.useState(null),N=gN(I),x=(N==null?void 0:N.width)??0,_=(N==null?void 0:N.height)??0,C=r+(i!=="center"?"-"+i:""),v=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},b=Array.isArray(d)?d:[d],P=b.length>0,j={padding:v,boundary:b.filter(yN),altBoundary:P},{refs:L,floatingStyles:B,placement:M,isPositioned:U,middlewareData:D}=dN({strategy:"fixed",placement:C,whileElementsMounted:(...H)=>eN(...H,{animationFrame:T==="always"}),elements:{reference:S.anchor},middleware:[EN({mainAxis:s+_,alignmentAxis:a}),c&&fN({mainAxis:!0,crossAxis:!1,limiter:E==="partial"?pN():void 0,...j}),c&&TN({...j}),SN({...j,apply:({elements:H,rects:re,availableWidth:ie,availableHeight:de})=>{const{width:se,height:ge}=re.reference,xe=H.floating.style;xe.setProperty("--radix-popper-available-width",`${ie}px`),xe.setProperty("--radix-popper-available-height",`${de}px`),xe.setProperty("--radix-popper-anchor-width",`${se}px`),xe.setProperty("--radix-popper-anchor-height",`${ge}px`)}}),I&&RN({element:I,padding:l}),CN({arrowWidth:x,arrowHeight:_}),f&&hN({strategy:"referenceHidden",...j})]}),[y,w]=FS(M),F=Bn(A);jn(()=>{U&&(F==null||F())},[U,F]);const k=(ne=D.arrow)==null?void 0:ne.x,V=(z=D.arrow)==null?void 0:z.y,ee=((oe=D.arrow)==null?void 0:oe.centerOffset)!==0,[Y,te]=p.useState();return jn(()=>{h&&te(window.getComputedStyle(h).zIndex)},[h]),o.jsx("div",{ref:L.setFloating,"data-radix-popper-content-wrapper":"",style:{...B,transform:U?B.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Y,"--radix-popper-transform-origin":[(le=D.transformOrigin)==null?void 0:le.x,(ae=D.transformOrigin)==null?void 0:ae.y].join(" "),...((X=D.hide)==null?void 0:X.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o.jsx(ON,{scope:n,placedSide:y,onArrowChange:O,arrowX:k,arrowY:V,shouldHideArrow:ee,children:o.jsx(Pe.div,{"data-side":y,"data-align":w,...R,ref:m,style:{...R.style,animation:U?void 0:"none"}})})})});BS.displayName=Wd;var jS="PopperArrow",xN={top:"bottom",right:"left",bottom:"top",left:"right"},kS=p.forwardRef(function(t,n){const{__scopePopper:r,...s}=t,i=NN(jS,r),a=xN[i.placedSide];return o.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[a]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:o.jsx(mN,{...s,ref:n,style:{...s.style,display:"block"}})})});kS.displayName=jS;function yN(e){return e!==null}var CN=e=>({name:"transformOrigin",options:e,fn(t){var S,h,g;const{placement:n,rects:r,middlewareData:s}=t,a=((S=s.arrow)==null?void 0:S.centerOffset)!==0,l=a?0:e.arrowWidth,c=a?0:e.arrowHeight,[d,u]=FS(n),E={start:"0%",center:"50%",end:"100%"}[u],f=(((h=s.arrow)==null?void 0:h.x)??0)+l/2,T=(((g=s.arrow)==null?void 0:g.y)??0)+c/2;let A="",R="";return d==="bottom"?(A=a?E:`${f}px`,R=`${-c}px`):d==="top"?(A=a?E:`${f}px`,R=`${r.floating.height+c}px`):d==="right"?(A=`${-c}px`,R=a?E:`${T}px`):d==="left"&&(A=`${r.floating.width+c}px`,R=a?E:`${T}px`),{data:{x:A,y:R}}}});function FS(e){const[t,n="center"]=e.split("-");return[t,n]}var LN=PS,ba=US,Yd=BS,$d=kS,_N="Portal",ms=p.forwardRef((e,t)=>{var l;const{container:n,...r}=e,[s,i]=p.useState(!1);jn(()=>i(!0),[]);const a=n||s&&((l=globalThis==null?void 0:globalThis.document)==null?void 0:l.body);return a?QI.createPortal(o.jsx(Pe.div,{...r,ref:t}),a):null});ms.displayName=_N;function bN(e,t){return p.useReducer((n,r)=>t[n][r]??n,e)}var Ot=e=>{const{present:t,children:n}=e,r=vN(t),s=typeof n=="function"?n({present:r.isPresent}):p.Children.only(n),i=ke(r.ref,DN(s));return typeof n=="function"||r.isPresent?p.cloneElement(s,{ref:i}):null};Ot.displayName="Presence";function vN(e){const[t,n]=p.useState(),r=p.useRef(null),s=p.useRef(e),i=p.useRef("none"),a=e?"mounted":"unmounted",[l,c]=bN(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return p.useEffect(()=>{const d=Qs(r.current);i.current=l==="mounted"?d:"none"},[l]),jn(()=>{const d=r.current,u=s.current;if(u!==e){const f=i.current,T=Qs(d);e?c("MOUNT"):T==="none"||(d==null?void 0:d.display)==="none"?c("UNMOUNT"):c(u&&f!==T?"ANIMATION_OUT":"UNMOUNT"),s.current=e}},[e,c]),jn(()=>{if(t){let d;const u=t.ownerDocument.defaultView??window,E=T=>{const R=Qs(r.current).includes(CSS.escape(T.animationName));if(T.target===t&&R&&(c("ANIMATION_END"),!s.current)){const S=t.style.animationFillMode;t.style.animationFillMode="forwards",d=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=S)})}},f=T=>{T.target===t&&(i.current=Qs(r.current))};return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",E),t.addEventListener("animationend",E),()=>{u.clearTimeout(d),t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",E),t.removeEventListener("animationend",E)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:p.useCallback(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function Qs(e){return(e==null?void 0:e.animationName)||"none"}function DN(e){var r,s;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=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var MN=pS[" useInsertionEffect ".trim().toString()]||jn;function Vd({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[s,i,a]=PN({defaultProp:t,onChange:n}),l=e!==void 0,c=l?e:s;{const u=p.useRef(e!==void 0);p.useEffect(()=>{const E=u.current;E!==l&&console.warn(`${r} is changing from ${E?"controlled":"uncontrolled"} to ${l?"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.`),u.current=l},[l,r])}const d=p.useCallback(u=>{var E;if(l){const f=wN(u)?u(e):u;f!==e&&((E=a.current)==null||E.call(a,f))}else i(u)},[l,e,i,a]);return[c,d]}function PN({defaultProp:e,onChange:t}){const[n,r]=p.useState(e),s=p.useRef(n),i=p.useRef(t);return MN(()=>{i.current=t},[t]),p.useEffect(()=>{var a;s.current!==n&&((a=i.current)==null||a.call(i,n),s.current=n)},[n,s]),[n,r,i]}function wN(e){return typeof e=="function"}var UN=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"}),BN="VisuallyHidden",GS=p.forwardRef((e,t)=>o.jsx(Pe.span,{...e,ref:t,style:{...UN,...e.style}}));GS.displayName=BN;var jN=GS,[va]=$n("Tooltip",[Io]),Da=Io(),HS="TooltipProvider",kN=700,Kc="tooltip.open",[FN,zd]=va(HS),WS=e=>{const{__scopeTooltip:t,delayDuration:n=kN,skipDelayDuration:r=300,disableHoverableContent:s=!1,children:i}=e,a=p.useRef(!0),l=p.useRef(!1),c=p.useRef(0);return p.useEffect(()=>{const d=c.current;return()=>window.clearTimeout(d)},[]),o.jsx(FN,{scope:t,isOpenDelayedRef:a,delayDuration:n,onOpen:p.useCallback(()=>{window.clearTimeout(c.current),a.current=!1},[]),onClose:p.useCallback(()=>{window.clearTimeout(c.current),c.current=window.setTimeout(()=>a.current=!0,r)},[r]),isPointerInTransitRef:l,onPointerInTransitChange:p.useCallback(d=>{l.current=d},[]),disableHoverableContent:s,children:i})};WS.displayName=HS;var Zo="Tooltip",[GN,gs]=va(Zo),YS=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:s,onOpenChange:i,disableHoverableContent:a,delayDuration:l}=e,c=zd(Zo,e.__scopeTooltip),d=Da(t),[u,E]=p.useState(null),f=Vo(),T=p.useRef(0),A=a??c.disableHoverableContent,R=l??c.delayDuration,S=p.useRef(!1),[h,g]=Vd({prop:r,defaultProp:s??!1,onChange:x=>{x?(c.onOpen(),document.dispatchEvent(new CustomEvent(Kc))):c.onClose(),i==null||i(x)},caller:Zo}),m=p.useMemo(()=>h?S.current?"delayed-open":"instant-open":"closed",[h]),I=p.useCallback(()=>{window.clearTimeout(T.current),T.current=0,S.current=!1,g(!0)},[g]),O=p.useCallback(()=>{window.clearTimeout(T.current),T.current=0,g(!1)},[g]),N=p.useCallback(()=>{window.clearTimeout(T.current),T.current=window.setTimeout(()=>{S.current=!0,g(!0),T.current=0},R)},[R,g]);return p.useEffect(()=>()=>{T.current&&(window.clearTimeout(T.current),T.current=0)},[]),o.jsx(LN,{...d,children:o.jsx(GN,{scope:t,contentId:f,open:h,stateAttribute:m,trigger:u,onTriggerChange:E,onTriggerEnter:p.useCallback(()=>{c.isOpenDelayedRef.current?N():I()},[c.isOpenDelayedRef,N,I]),onTriggerLeave:p.useCallback(()=>{A?O():(window.clearTimeout(T.current),T.current=0)},[O,A]),onOpen:I,onClose:O,disableHoverableContent:A,children:n})})};YS.displayName=Zo;var qc="TooltipTrigger",$S=p.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,s=gs(qc,n),i=zd(qc,n),a=Da(n),l=p.useRef(null),c=ke(t,l,s.onTriggerChange),d=p.useRef(!1),u=p.useRef(!1),E=p.useCallback(()=>d.current=!1,[]);return p.useEffect(()=>()=>document.removeEventListener("pointerup",E),[E]),o.jsx(ba,{asChild:!0,...a,children:o.jsx(Pe.button,{"aria-describedby":s.open?s.contentId:void 0,"data-state":s.stateAttribute,...r,ref:c,onPointerMove:he(e.onPointerMove,f=>{f.pointerType!=="touch"&&!u.current&&!i.isPointerInTransitRef.current&&(s.onTriggerEnter(),u.current=!0)}),onPointerLeave:he(e.onPointerLeave,()=>{s.onTriggerLeave(),u.current=!1}),onPointerDown:he(e.onPointerDown,()=>{s.open&&s.onClose(),d.current=!0,document.addEventListener("pointerup",E,{once:!0})}),onFocus:he(e.onFocus,()=>{d.current||s.onOpen()}),onBlur:he(e.onBlur,s.onClose),onClick:he(e.onClick,s.onClose)})})});$S.displayName=qc;var Xd="TooltipPortal",[HN,WN]=va(Xd,{forceMount:void 0}),VS=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:s}=e,i=gs(Xd,t);return o.jsx(HN,{scope:t,forceMount:n,children:o.jsx(Ot,{present:n||i.open,children:o.jsx(ms,{asChild:!0,container:s,children:r})})})};VS.displayName=Xd;var so="TooltipContent",zS=p.forwardRef((e,t)=>{const n=WN(so,e.__scopeTooltip),{forceMount:r=n.forceMount,side:s="top",...i}=e,a=gs(so,e.__scopeTooltip);return o.jsx(Ot,{present:r||a.open,children:a.disableHoverableContent?o.jsx(XS,{side:s,...i,ref:t}):o.jsx(YN,{side:s,...i,ref:t})})}),YN=p.forwardRef((e,t)=>{const n=gs(so,e.__scopeTooltip),r=zd(so,e.__scopeTooltip),s=p.useRef(null),i=ke(t,s),[a,l]=p.useState(null),{trigger:c,onClose:d}=n,u=s.current,{onPointerInTransitChange:E}=r,f=p.useCallback(()=>{l(null),E(!1)},[E]),T=p.useCallback((A,R)=>{const S=A.currentTarget,h={x:A.clientX,y:A.clientY},g=KN(h,S.getBoundingClientRect()),m=qN(h,g),I=JN(R.getBoundingClientRect()),O=ZN([...m,...I]);l(O),E(!0)},[E]);return p.useEffect(()=>()=>f(),[f]),p.useEffect(()=>{if(c&&u){const A=S=>T(S,u),R=S=>T(S,c);return c.addEventListener("pointerleave",A),u.addEventListener("pointerleave",R),()=>{c.removeEventListener("pointerleave",A),u.removeEventListener("pointerleave",R)}}},[c,u,T,f]),p.useEffect(()=>{if(a){const A=R=>{const S=R.target,h={x:R.clientX,y:R.clientY},g=(c==null?void 0:c.contains(S))||(u==null?void 0:u.contains(S)),m=!QN(h,a);g?f():m&&(f(),d())};return document.addEventListener("pointermove",A),()=>document.removeEventListener("pointermove",A)}},[c,u,a,d,f]),o.jsx(XS,{...e,ref:i})}),[$N,VN]=va(Zo,{isInside:!1}),zN=eO("TooltipContent"),XS=p.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":s,onEscapeKeyDown:i,onPointerDownOutside:a,...l}=e,c=gs(so,n),d=Da(n),{onClose:u}=c;return p.useEffect(()=>(document.addEventListener(Kc,u),()=>document.removeEventListener(Kc,u)),[u]),p.useEffect(()=>{if(c.trigger){const E=f=>{const T=f.target;T!=null&&T.contains(c.trigger)&&u()};return window.addEventListener("scroll",E,{capture:!0}),()=>window.removeEventListener("scroll",E,{capture:!0})}},[c.trigger,u]),o.jsx(Rs,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:a,onFocusOutside:E=>E.preventDefault(),onDismiss:u,children:o.jsxs(Yd,{"data-state":c.stateAttribute,...d,...l,ref:t,style:{...l.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:[o.jsx(zN,{children:r}),o.jsx($N,{scope:n,isInside:!0,children:o.jsx(jN,{id:c.contentId,role:"tooltip",children:s||r})})]})})});zS.displayName=so;var KS="TooltipArrow",XN=p.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,s=Da(n);return VN(KS,n).isInside?null:o.jsx($d,{...s,...r,ref:t})});XN.displayName=KS;function KN(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),s=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,r,s,i)){case i:return"left";case s:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function qN(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 JN(e){const{top:t,right:n,bottom:r,left:s}=e;return[{x:s,y:t},{x:n,y:t},{x:n,y:r},{x:s,y:r}]}function QN(e,t){const{x:n,y:r}=e;let s=!1;for(let i=0,a=t.length-1;i<t.length;a=i++){const l=t[i],c=t[a],d=l.x,u=l.y,E=c.x,f=c.y;u>r!=f>r&&n<(E-d)*(r-u)/(f-u)+d&&(s=!s)}return s}function ZN(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),ex(t)}function ex(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const s=e[r];for(;t.length>=2;){const i=t[t.length-1],a=t[t.length-2];if((i.x-a.x)*(s.y-a.y)>=(i.y-a.y)*(s.x-a.x))t.pop();else break}t.push(s)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const s=e[r];for(;n.length>=2;){const i=n[n.length-1],a=n[n.length-2];if((i.x-a.x)*(s.y-a.y)>=(i.y-a.y)*(s.x-a.x))n.pop();else break}n.push(s)}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 tx=WS,nx=YS,rx=$S,ox=VS,sx=zS;function qS({content:e,children:t,side:n="right",align:r="center",sideOffset:s=6,delayMs:i=200,container:a}){return o.jsxs(nx,{delayDuration:i,children:[o.jsx(rx,{asChild:!0,children:t}),o.jsx(ox,{container:a,children:o.jsx(sx,{side:n,align:r,sideOffset:s,style:{background:me("surfaceElevated"),color:me("textPrimary"),border:`1px solid ${me("borderDefault")}`,borderRadius:Yn.sm,padding:`${Ce[1]} ${Ce[2]}`,fontSize:et.sm,boxShadow:me("shadowMd"),zIndex:Jo.tooltip,userSelect:"none"},children:e})})]})}const ix=tx;var bl="focusScope.autoFocusOnMount",vl="focusScope.autoFocusOnUnmount",gE={bubbles:!1,cancelable:!0},ax="FocusScope",Ma=p.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:s,onUnmountAutoFocus:i,...a}=e,[l,c]=p.useState(null),d=Bn(s),u=Bn(i),E=p.useRef(null),f=ke(t,R=>c(R)),T=p.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;p.useEffect(()=>{if(r){let R=function(m){if(T.paused||!l)return;const I=m.target;l.contains(I)?E.current=I:Cn(E.current,{select:!0})},S=function(m){if(T.paused||!l)return;const I=m.relatedTarget;I!==null&&(l.contains(I)||Cn(E.current,{select:!0}))},h=function(m){if(document.activeElement===document.body)for(const O of m)O.removedNodes.length>0&&Cn(l)};document.addEventListener("focusin",R),document.addEventListener("focusout",S);const g=new MutationObserver(h);return l&&g.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",R),document.removeEventListener("focusout",S),g.disconnect()}}},[r,l,T.paused]),p.useEffect(()=>{if(l){OE.add(T);const R=document.activeElement;if(!l.contains(R)){const h=new CustomEvent(bl,gE);l.addEventListener(bl,d),l.dispatchEvent(h),h.defaultPrevented||(lx(fx(JS(l)),{select:!0}),document.activeElement===R&&Cn(l))}return()=>{l.removeEventListener(bl,d),setTimeout(()=>{const h=new CustomEvent(vl,gE);l.addEventListener(vl,u),l.dispatchEvent(h),h.defaultPrevented||Cn(R??document.body,{select:!0}),l.removeEventListener(vl,u),OE.remove(T)},0)}}},[l,d,u,T]);const A=p.useCallback(R=>{if(!n&&!r||T.paused)return;const S=R.key==="Tab"&&!R.altKey&&!R.ctrlKey&&!R.metaKey,h=document.activeElement;if(S&&h){const g=R.currentTarget,[m,I]=cx(g);m&&I?!R.shiftKey&&h===I?(R.preventDefault(),n&&Cn(m,{select:!0})):R.shiftKey&&h===m&&(R.preventDefault(),n&&Cn(I,{select:!0})):h===g&&R.preventDefault()}},[n,r,T.paused]);return o.jsx(Pe.div,{tabIndex:-1,...a,ref:f,onKeyDown:A})});Ma.displayName=ax;function lx(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Cn(r,{select:t}),document.activeElement!==n)return}function cx(e){const t=JS(e),n=IE(t,e),r=IE(t.reverse(),e);return[n,r]}function JS(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const s=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||s?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function IE(e,t){for(const n of e)if(!dx(n,{upTo:t}))return n}function dx(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 ux(e){return e instanceof HTMLInputElement&&"select"in e}function Cn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&ux(e)&&t&&e.select()}}var OE=Ex();function Ex(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=NE(e,t),e.unshift(t)},remove(t){var n;e=NE(e,t),(n=e[0])==null||n.resume()}}}function NE(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function fx(e){return e.filter(t=>t.tagName!=="A")}var Dl=0;function Kd(){p.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??xE()),document.body.insertAdjacentElement("beforeend",e[1]??xE()),Dl++,()=>{Dl===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Dl--}},[])}function xE(){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 Jt=function(){return Jt=Object.assign||function(t){for(var n,r=1,s=arguments.length;r<s;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},Jt.apply(this,arguments)};function QS(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 s=0,r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]]);return n}function px(e,t,n){if(n||arguments.length===2)for(var r=0,s=t.length,i;r<s;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 bi="right-scroll-bar-position",vi="width-before-scroll-bar",Tx="with-scroll-bars-hidden",Sx="--removed-body-scroll-bar-size";function Ml(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function hx(e,t){var n=p.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var s=n.value;s!==r&&(n.value=r,n.callback(r,s))}}}})[0];return n.callback=t,n.facade}var Rx=typeof window<"u"?p.useLayoutEffect:p.useEffect,yE=new WeakMap;function Ax(e,t){var n=hx(null,function(r){return e.forEach(function(s){return Ml(s,r)})});return Rx(function(){var r=yE.get(n);if(r){var s=new Set(r),i=new Set(e),a=n.current;s.forEach(function(l){i.has(l)||Ml(l,null)}),i.forEach(function(l){s.has(l)||Ml(l,a)})}yE.set(n,e)},[e]),n}function mx(e){return e}function gx(e,t){t===void 0&&(t=mx);var n=[],r=!1,s={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(i){var a=t(i,r);return n.push(a),function(){n=n.filter(function(l){return l!==a})}},assignSyncMedium:function(i){for(r=!0;n.length;){var a=n;n=[],a.forEach(i)}n={push:function(l){return i(l)},filter:function(){return n}}},assignMedium:function(i){r=!0;var a=[];if(n.length){var l=n;n=[],l.forEach(i),a=n}var c=function(){var u=a;a=[],u.forEach(i)},d=function(){return Promise.resolve().then(c)};d(),n={push:function(u){a.push(u),d()},filter:function(u){return a=a.filter(u),n}}}};return s}function Ix(e){e===void 0&&(e={});var t=gx(null);return t.options=Jt({async:!0,ssr:!1},e),t}var ZS=function(e){var t=e.sideCar,n=QS(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,Jt({},n))};ZS.isSideCarExport=!0;function Ox(e,t){return e.useMedium(t),ZS}var eh=Ix(),Pl=function(){},Pa=p.forwardRef(function(e,t){var n=p.useRef(null),r=p.useState({onScrollCapture:Pl,onWheelCapture:Pl,onTouchMoveCapture:Pl}),s=r[0],i=r[1],a=e.forwardProps,l=e.children,c=e.className,d=e.removeScrollBar,u=e.enabled,E=e.shards,f=e.sideCar,T=e.noRelative,A=e.noIsolation,R=e.inert,S=e.allowPinchZoom,h=e.as,g=h===void 0?"div":h,m=e.gapMode,I=QS(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),O=f,N=Ax([n,t]),x=Jt(Jt({},I),s);return p.createElement(p.Fragment,null,u&&p.createElement(O,{sideCar:eh,removeScrollBar:d,shards:E,noRelative:T,noIsolation:A,inert:R,setCallbacks:i,allowPinchZoom:!!S,lockRef:n,gapMode:m}),a?p.cloneElement(p.Children.only(l),Jt(Jt({},x),{ref:N})):p.createElement(g,Jt({},x,{className:c,ref:N}),l))});Pa.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Pa.classNames={fullWidth:vi,zeroRight:bi};var Nx=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function xx(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Nx();return t&&e.setAttribute("nonce",t),e}function yx(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Cx(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Lx=function(){var e=0,t=null;return{add:function(n){e==0&&(t=xx())&&(yx(t,n),Cx(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},_x=function(){var e=Lx();return function(t,n){p.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},th=function(){var e=_x(),t=function(n){var r=n.styles,s=n.dynamic;return e(r,s),null};return t},bx={left:0,top:0,right:0,gap:0},wl=function(e){return parseInt(e||"",10)||0},vx=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],s=t[e==="padding"?"paddingRight":"marginRight"];return[wl(n),wl(r),wl(s)]},Dx=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return bx;var t=vx(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])}},Mx=th(),Jr="data-scroll-locked",Px=function(e,t,n,r){var s=e.left,i=e.top,a=e.right,l=e.gap;return n===void 0&&(n="margin"),`
|
|
10
|
+
.`.concat(Tx,` {
|
|
11
|
+
overflow: hidden `).concat(r,`;
|
|
12
|
+
padding-right: `).concat(l,"px ").concat(r,`;
|
|
13
|
+
}
|
|
14
|
+
body[`).concat(Jr,`] {
|
|
15
|
+
overflow: hidden `).concat(r,`;
|
|
16
|
+
overscroll-behavior: contain;
|
|
17
|
+
`).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&`
|
|
18
|
+
padding-left: `.concat(s,`px;
|
|
19
|
+
padding-top: `).concat(i,`px;
|
|
20
|
+
padding-right: `).concat(a,`px;
|
|
21
|
+
margin-left:0;
|
|
22
|
+
margin-top:0;
|
|
23
|
+
margin-right: `).concat(l,"px ").concat(r,`;
|
|
24
|
+
`),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),`
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
.`).concat(bi,` {
|
|
28
|
+
right: `).concat(l,"px ").concat(r,`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
.`).concat(vi,` {
|
|
32
|
+
margin-right: `).concat(l,"px ").concat(r,`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
.`).concat(bi," .").concat(bi,` {
|
|
36
|
+
right: 0 `).concat(r,`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
.`).concat(vi," .").concat(vi,` {
|
|
40
|
+
margin-right: 0 `).concat(r,`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
body[`).concat(Jr,`] {
|
|
44
|
+
`).concat(Sx,": ").concat(l,`px;
|
|
45
|
+
}
|
|
46
|
+
`)},CE=function(){var e=parseInt(document.body.getAttribute(Jr)||"0",10);return isFinite(e)?e:0},wx=function(){p.useEffect(function(){return document.body.setAttribute(Jr,(CE()+1).toString()),function(){var e=CE()-1;e<=0?document.body.removeAttribute(Jr):document.body.setAttribute(Jr,e.toString())}},[])},Ux=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,s=r===void 0?"margin":r;wx();var i=p.useMemo(function(){return Dx(s)},[s]);return p.createElement(Mx,{styles:Px(i,!t,s,n?"":"!important")})},Jc=!1;if(typeof window<"u")try{var Zs=Object.defineProperty({},"passive",{get:function(){return Jc=!0,!0}});window.addEventListener("test",Zs,Zs),window.removeEventListener("test",Zs,Zs)}catch{Jc=!1}var Br=Jc?{passive:!1}:!1,Bx=function(e){return e.tagName==="TEXTAREA"},nh=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!Bx(e)&&n[t]==="visible")},jx=function(e){return nh(e,"overflowY")},kx=function(e){return nh(e,"overflowX")},LE=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var s=rh(e,r);if(s){var i=oh(e,r),a=i[1],l=i[2];if(a>l)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Fx=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},Gx=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},rh=function(e,t){return e==="v"?jx(t):kx(t)},oh=function(e,t){return e==="v"?Fx(t):Gx(t)},Hx=function(e,t){return e==="h"&&t==="rtl"?-1:1},Wx=function(e,t,n,r,s){var i=Hx(e,window.getComputedStyle(t).direction),a=i*r,l=n.target,c=t.contains(l),d=!1,u=a>0,E=0,f=0;do{if(!l)break;var T=oh(e,l),A=T[0],R=T[1],S=T[2],h=R-S-i*A;(A||h)&&rh(e,l)&&(E+=h,f+=A);var g=l.parentNode;l=g&&g.nodeType===Node.DOCUMENT_FRAGMENT_NODE?g.host:g}while(!c&&l!==document.body||c&&(t.contains(l)||t===l));return(u&&Math.abs(E)<1||!u&&Math.abs(f)<1)&&(d=!0),d},ei=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},_E=function(e){return[e.deltaX,e.deltaY]},bE=function(e){return e&&"current"in e?e.current:e},Yx=function(e,t){return e[0]===t[0]&&e[1]===t[1]},$x=function(e){return`
|
|
47
|
+
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
48
|
+
.allow-interactivity-`).concat(e,` {pointer-events: all;}
|
|
49
|
+
`)},Vx=0,jr=[];function zx(e){var t=p.useRef([]),n=p.useRef([0,0]),r=p.useRef(),s=p.useState(Vx++)[0],i=p.useState(th)[0],a=p.useRef(e);p.useEffect(function(){a.current=e},[e]),p.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(s));var R=px([e.lockRef.current],(e.shards||[]).map(bE),!0).filter(Boolean);return R.forEach(function(S){return S.classList.add("allow-interactivity-".concat(s))}),function(){document.body.classList.remove("block-interactivity-".concat(s)),R.forEach(function(S){return S.classList.remove("allow-interactivity-".concat(s))})}}},[e.inert,e.lockRef.current,e.shards]);var l=p.useCallback(function(R,S){if("touches"in R&&R.touches.length===2||R.type==="wheel"&&R.ctrlKey)return!a.current.allowPinchZoom;var h=ei(R),g=n.current,m="deltaX"in R?R.deltaX:g[0]-h[0],I="deltaY"in R?R.deltaY:g[1]-h[1],O,N=R.target,x=Math.abs(m)>Math.abs(I)?"h":"v";if("touches"in R&&x==="h"&&N.type==="range")return!1;var _=window.getSelection(),C=_&&_.anchorNode,v=C?C===N||C.contains(N):!1;if(v)return!1;var b=LE(x,N);if(!b)return!0;if(b?O=x:(O=x==="v"?"h":"v",b=LE(x,N)),!b)return!1;if(!r.current&&"changedTouches"in R&&(m||I)&&(r.current=O),!O)return!0;var P=r.current||O;return Wx(P,S,R,P==="h"?m:I)},[]),c=p.useCallback(function(R){var S=R;if(!(!jr.length||jr[jr.length-1]!==i)){var h="deltaY"in S?_E(S):ei(S),g=t.current.filter(function(O){return O.name===S.type&&(O.target===S.target||S.target===O.shadowParent)&&Yx(O.delta,h)})[0];if(g&&g.should){S.cancelable&&S.preventDefault();return}if(!g){var m=(a.current.shards||[]).map(bE).filter(Boolean).filter(function(O){return O.contains(S.target)}),I=m.length>0?l(S,m[0]):!a.current.noIsolation;I&&S.cancelable&&S.preventDefault()}}},[]),d=p.useCallback(function(R,S,h,g){var m={name:R,delta:S,target:h,should:g,shadowParent:Xx(h)};t.current.push(m),setTimeout(function(){t.current=t.current.filter(function(I){return I!==m})},1)},[]),u=p.useCallback(function(R){n.current=ei(R),r.current=void 0},[]),E=p.useCallback(function(R){d(R.type,_E(R),R.target,l(R,e.lockRef.current))},[]),f=p.useCallback(function(R){d(R.type,ei(R),R.target,l(R,e.lockRef.current))},[]);p.useEffect(function(){return jr.push(i),e.setCallbacks({onScrollCapture:E,onWheelCapture:E,onTouchMoveCapture:f}),document.addEventListener("wheel",c,Br),document.addEventListener("touchmove",c,Br),document.addEventListener("touchstart",u,Br),function(){jr=jr.filter(function(R){return R!==i}),document.removeEventListener("wheel",c,Br),document.removeEventListener("touchmove",c,Br),document.removeEventListener("touchstart",u,Br)}},[]);var T=e.removeScrollBar,A=e.inert;return p.createElement(p.Fragment,null,A?p.createElement(i,{styles:$x(s)}):null,T?p.createElement(Ux,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Xx(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Kx=Ox(eh,zx);var wa=p.forwardRef(function(e,t){return p.createElement(Pa,Jt({},e,{ref:t,sideCar:Kx}))});wa.classNames=Pa.classNames;var qx=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},kr=new WeakMap,ti=new WeakMap,ni={},Ul=0,sh=function(e){return e&&(e.host||sh(e.parentNode))},Jx=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=sh(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})},Qx=function(e,t,n,r){var s=Jx(t,Array.isArray(e)?e:[e]);ni[n]||(ni[n]=new WeakMap);var i=ni[n],a=[],l=new Set,c=new Set(s),d=function(E){!E||l.has(E)||(l.add(E),d(E.parentNode))};s.forEach(d);var u=function(E){!E||c.has(E)||Array.prototype.forEach.call(E.children,function(f){if(l.has(f))u(f);else try{var T=f.getAttribute(r),A=T!==null&&T!=="false",R=(kr.get(f)||0)+1,S=(i.get(f)||0)+1;kr.set(f,R),i.set(f,S),a.push(f),R===1&&A&&ti.set(f,!0),S===1&&f.setAttribute(n,"true"),A||f.setAttribute(r,"true")}catch(h){console.error("aria-hidden: cannot operate on ",f,h)}})};return u(t),l.clear(),Ul++,function(){a.forEach(function(E){var f=kr.get(E)-1,T=i.get(E)-1;kr.set(E,f),i.set(E,T),f||(ti.has(E)||E.removeAttribute(r),ti.delete(E)),T||E.removeAttribute(n)}),Ul--,Ul||(kr=new WeakMap,kr=new WeakMap,ti=new WeakMap,ni={})}},qd=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),s=qx(e);return s?(r.push.apply(r,Array.from(s.querySelectorAll("[aria-live], script"))),Qx(r,s,n,"aria-hidden")):function(){return null}},Ua="Dialog",[ih]=$n(Ua),[Zx,Gt]=ih(Ua),ah=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:s,onOpenChange:i,modal:a=!0}=e,l=p.useRef(null),c=p.useRef(null),[d,u]=Vd({prop:r,defaultProp:s??!1,onChange:i,caller:Ua});return o.jsx(Zx,{scope:t,triggerRef:l,contentRef:c,contentId:Vo(),titleId:Vo(),descriptionId:Vo(),open:d,onOpenChange:u,onOpenToggle:p.useCallback(()=>u(E=>!E),[u]),modal:a,children:n})};ah.displayName=Ua;var lh="DialogTrigger",ey=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=Gt(lh,n),i=ke(t,s.triggerRef);return o.jsx(Pe.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":Zd(s.open),...r,ref:i,onClick:he(e.onClick,s.onOpenToggle)})});ey.displayName=lh;var Jd="DialogPortal",[ty,ch]=ih(Jd,{forceMount:void 0}),dh=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:s}=e,i=Gt(Jd,t);return o.jsx(ty,{scope:t,forceMount:n,children:p.Children.map(r,a=>o.jsx(Ot,{present:n||i.open,children:o.jsx(ms,{asChild:!0,container:s,children:a})}))})};dh.displayName=Jd;var zi="DialogOverlay",uh=p.forwardRef((e,t)=>{const n=ch(zi,e.__scopeDialog),{forceMount:r=n.forceMount,...s}=e,i=Gt(zi,e.__scopeDialog);return i.modal?o.jsx(Ot,{present:r||i.open,children:o.jsx(ry,{...s,ref:t})}):null});uh.displayName=zi;var ny=ro("DialogOverlay.RemoveScroll"),ry=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=Gt(zi,n);return o.jsx(wa,{as:ny,allowPinchZoom:!0,shards:[s.contentRef],children:o.jsx(Pe.div,{"data-state":Zd(s.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),fr="DialogContent",Eh=p.forwardRef((e,t)=>{const n=ch(fr,e.__scopeDialog),{forceMount:r=n.forceMount,...s}=e,i=Gt(fr,e.__scopeDialog);return o.jsx(Ot,{present:r||i.open,children:i.modal?o.jsx(oy,{...s,ref:t}):o.jsx(sy,{...s,ref:t})})});Eh.displayName=fr;var oy=p.forwardRef((e,t)=>{const n=Gt(fr,e.__scopeDialog),r=p.useRef(null),s=ke(t,n.contentRef,r);return p.useEffect(()=>{const i=r.current;if(i)return qd(i)},[]),o.jsx(fh,{...e,ref:s,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:he(e.onCloseAutoFocus,i=>{var a;i.preventDefault(),(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:he(e.onPointerDownOutside,i=>{const a=i.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0;(a.button===2||l)&&i.preventDefault()}),onFocusOutside:he(e.onFocusOutside,i=>i.preventDefault())})}),sy=p.forwardRef((e,t)=>{const n=Gt(fr,e.__scopeDialog),r=p.useRef(!1),s=p.useRef(!1);return o.jsx(fh,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var a,l;(a=e.onCloseAutoFocus)==null||a.call(e,i),i.defaultPrevented||(r.current||(l=n.triggerRef.current)==null||l.focus(),i.preventDefault()),r.current=!1,s.current=!1},onInteractOutside:i=>{var c,d;(c=e.onInteractOutside)==null||c.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const a=i.target;((d=n.triggerRef.current)==null?void 0:d.contains(a))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&s.current&&i.preventDefault()}})}),fh=p.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:i,...a}=e,l=Gt(fr,n),c=p.useRef(null),d=ke(t,c);return Kd(),o.jsxs(o.Fragment,{children:[o.jsx(Ma,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:s,onUnmountAutoFocus:i,children:o.jsx(Rs,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Zd(l.open),...a,ref:d,onDismiss:()=>l.onOpenChange(!1)})}),o.jsxs(o.Fragment,{children:[o.jsx(ly,{titleId:l.titleId}),o.jsx(dy,{contentRef:c,descriptionId:l.descriptionId})]})]})}),Qd="DialogTitle",ph=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=Gt(Qd,n);return o.jsx(Pe.h2,{id:s.titleId,...r,ref:t})});ph.displayName=Qd;var Th="DialogDescription",iy=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=Gt(Th,n);return o.jsx(Pe.p,{id:s.descriptionId,...r,ref:t})});iy.displayName=Th;var Sh="DialogClose",ay=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=Gt(Sh,n);return o.jsx(Pe.button,{type:"button",...r,ref:t,onClick:he(e.onClick,()=>s.onOpenChange(!1))})});ay.displayName=Sh;function Zd(e){return e?"open":"closed"}var hh="DialogTitleWarning",[s4,Rh]=qI(hh,{contentName:fr,titleName:Qd,docsSlug:"dialog"}),ly=({titleId:e})=>{const t=Rh(hh),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
50
|
+
|
|
51
|
+
If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
|
|
52
|
+
|
|
53
|
+
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},cy="DialogDescriptionWarning",dy=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Rh(cy).contentName}}.`;return p.useEffect(()=>{var i;const s=(i=e.current)==null?void 0:i.getAttribute("aria-describedby");t&&s&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},uy=ah,Ey=dh,fy=uh,py=Eh,Ty=ph;function Ah(e){const t=e+"CollectionProvider",[n,r]=$n(t),[s,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),a=R=>{const{scope:S,children:h}=R,g=Be.useRef(null),m=Be.useRef(new Map).current;return o.jsx(s,{scope:S,itemMap:m,collectionRef:g,children:h})};a.displayName=t;const l=e+"CollectionSlot",c=ro(l),d=Be.forwardRef((R,S)=>{const{scope:h,children:g}=R,m=i(l,h),I=ke(S,m.collectionRef);return o.jsx(c,{ref:I,children:g})});d.displayName=l;const u=e+"CollectionItemSlot",E="data-radix-collection-item",f=ro(u),T=Be.forwardRef((R,S)=>{const{scope:h,children:g,...m}=R,I=Be.useRef(null),O=ke(S,I),N=i(u,h);return Be.useEffect(()=>(N.itemMap.set(I,{ref:I,...m}),()=>void N.itemMap.delete(I))),o.jsx(f,{[E]:"",ref:O,children:g})});T.displayName=u;function A(R){const S=i(e+"CollectionConsumer",R);return Be.useCallback(()=>{const g=S.collectionRef.current;if(!g)return[];const m=Array.from(g.querySelectorAll(`[${E}]`));return Array.from(S.itemMap.values()).sort((N,x)=>m.indexOf(N.ref.current)-m.indexOf(x.ref.current))},[S.collectionRef,S.itemMap])}return[{Provider:a,Slot:d,ItemSlot:T},A,r]}var Sy=p.createContext(void 0);function hy(e){const t=p.useContext(Sy);return e||t||"ltr"}var Bl="rovingFocusGroup.onEntryFocus",Ry={bubbles:!1,cancelable:!0},Is="RovingFocusGroup",[Qc,mh,Ay]=Ah(Is),[my,gh]=$n(Is,[Ay]),[gy,Iy]=my(Is),Ih=p.forwardRef((e,t)=>o.jsx(Qc.Provider,{scope:e.__scopeRovingFocusGroup,children:o.jsx(Qc.Slot,{scope:e.__scopeRovingFocusGroup,children:o.jsx(Oy,{...e,ref:t})})}));Ih.displayName=Is;var Oy=p.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:s=!1,dir:i,currentTabStopId:a,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:c,onEntryFocus:d,preventScrollOnEntryFocus:u=!1,...E}=e,f=p.useRef(null),T=ke(t,f),A=hy(i),[R,S]=Vd({prop:a,defaultProp:l??null,onChange:c,caller:Is}),[h,g]=p.useState(!1),m=Bn(d),I=mh(n),O=p.useRef(!1),[N,x]=p.useState(0);return p.useEffect(()=>{const _=f.current;if(_)return _.addEventListener(Bl,m),()=>_.removeEventListener(Bl,m)},[m]),o.jsx(gy,{scope:n,orientation:r,dir:A,loop:s,currentTabStopId:R,onItemFocus:p.useCallback(_=>S(_),[S]),onItemShiftTab:p.useCallback(()=>g(!0),[]),onFocusableItemAdd:p.useCallback(()=>x(_=>_+1),[]),onFocusableItemRemove:p.useCallback(()=>x(_=>_-1),[]),children:o.jsx(Pe.div,{tabIndex:h||N===0?-1:0,"data-orientation":r,...E,ref:T,style:{outline:"none",...e.style},onMouseDown:he(e.onMouseDown,()=>{O.current=!0}),onFocus:he(e.onFocus,_=>{const C=!O.current;if(_.target===_.currentTarget&&C&&!h){const v=new CustomEvent(Bl,Ry);if(_.currentTarget.dispatchEvent(v),!v.defaultPrevented){const b=I().filter(M=>M.focusable),P=b.find(M=>M.active),j=b.find(M=>M.id===R),B=[P,j,...b].filter(Boolean).map(M=>M.ref.current);xh(B,u)}}O.current=!1}),onBlur:he(e.onBlur,()=>g(!1))})})}),Oh="RovingFocusGroupItem",Nh=p.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:s=!1,tabStopId:i,children:a,...l}=e,c=Vo(),d=i||c,u=Iy(Oh,n),E=u.currentTabStopId===d,f=mh(n),{onFocusableItemAdd:T,onFocusableItemRemove:A,currentTabStopId:R}=u;return p.useEffect(()=>{if(r)return T(),()=>A()},[r,T,A]),o.jsx(Qc.ItemSlot,{scope:n,id:d,focusable:r,active:s,children:o.jsx(Pe.span,{tabIndex:E?0:-1,"data-orientation":u.orientation,...l,ref:t,onMouseDown:he(e.onMouseDown,S=>{r?u.onItemFocus(d):S.preventDefault()}),onFocus:he(e.onFocus,()=>u.onItemFocus(d)),onKeyDown:he(e.onKeyDown,S=>{if(S.key==="Tab"&&S.shiftKey){u.onItemShiftTab();return}if(S.target!==S.currentTarget)return;const h=yy(S,u.orientation,u.dir);if(h!==void 0){if(S.metaKey||S.ctrlKey||S.altKey||S.shiftKey)return;S.preventDefault();let m=f().filter(I=>I.focusable).map(I=>I.ref.current);if(h==="last")m.reverse();else if(h==="prev"||h==="next"){h==="prev"&&m.reverse();const I=m.indexOf(S.currentTarget);m=u.loop?Cy(m,I+1):m.slice(I+1)}setTimeout(()=>xh(m))}}),children:typeof a=="function"?a({isCurrentTabStop:E,hasTabStop:R!=null}):a})})});Nh.displayName=Oh;var Ny={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function xy(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function yy(e,t,n){const r=xy(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Ny[r]}function xh(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Cy(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Ly=Ih,_y=Nh,Zc=["Enter"," "],by=["ArrowDown","PageUp","Home"],yh=["ArrowUp","PageDown","End"],vy=[...by,...yh],Dy={ltr:[...Zc,"ArrowRight"],rtl:[...Zc,"ArrowLeft"]},My={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Ba="Menu",[es,Py,wy]=Ah(Ba),[Ir,Ch]=$n(Ba,[wy,Io,gh]),eu=Io(),Lh=gh(),[i4,Or]=Ir(Ba),[a4,Os]=Ir(Ba),Uy="MenuAnchor",tu=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,s=eu(n);return o.jsx(ba,{...s,...r,ref:t})});tu.displayName=Uy;var nu="MenuPortal",[By,_h]=Ir(nu,{forceMount:void 0}),bh=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:s}=e,i=Or(nu,t);return o.jsx(By,{scope:t,forceMount:n,children:o.jsx(Ot,{present:n||i.open,children:o.jsx(ms,{asChild:!0,container:s,children:r})})})};bh.displayName=nu;var It="MenuContent",[jy,ru]=Ir(It),vh=p.forwardRef((e,t)=>{const n=_h(It,e.__scopeMenu),{forceMount:r=n.forceMount,...s}=e,i=Or(It,e.__scopeMenu),a=Os(It,e.__scopeMenu);return o.jsx(es.Provider,{scope:e.__scopeMenu,children:o.jsx(Ot,{present:r||i.open,children:o.jsx(es.Slot,{scope:e.__scopeMenu,children:a.modal?o.jsx(ky,{...s,ref:t}):o.jsx(Fy,{...s,ref:t})})})})}),ky=p.forwardRef((e,t)=>{const n=Or(It,e.__scopeMenu),r=p.useRef(null),s=ke(t,r);return p.useEffect(()=>{const i=r.current;if(i)return qd(i)},[]),o.jsx(ou,{...e,ref:s,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:he(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),Fy=p.forwardRef((e,t)=>{const n=Or(It,e.__scopeMenu);return o.jsx(ou,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),Gy=ro("MenuContent.ScrollLock"),ou=p.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:s,onOpenAutoFocus:i,onCloseAutoFocus:a,disableOutsidePointerEvents:l,onEntryFocus:c,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:E,onInteractOutside:f,onDismiss:T,disableOutsideScroll:A,...R}=e,S=Or(It,n),h=Os(It,n),g=eu(n),m=Lh(n),I=Py(n),[O,N]=p.useState(null),x=p.useRef(null),_=ke(t,x,S.onContentChange),C=p.useRef(0),v=p.useRef(""),b=p.useRef(0),P=p.useRef(null),j=p.useRef("right"),L=p.useRef(0),B=A?wa:p.Fragment,M=A?{as:Gy,allowPinchZoom:!0}:void 0,U=y=>{var ne,z;const w=v.current+y,F=I().filter(oe=>!oe.disabled),k=document.activeElement,V=(ne=F.find(oe=>oe.ref.current===k))==null?void 0:ne.textValue,ee=F.map(oe=>oe.textValue),Y=Zy(ee,w,V),te=(z=F.find(oe=>oe.textValue===Y))==null?void 0:z.ref.current;(function oe(le){v.current=le,window.clearTimeout(C.current),le!==""&&(C.current=window.setTimeout(()=>oe(""),1e3))})(w),te&&setTimeout(()=>te.focus())};p.useEffect(()=>()=>window.clearTimeout(C.current),[]),Kd();const D=p.useCallback(y=>{var F,k;return j.current===((F=P.current)==null?void 0:F.side)&&tC(y,(k=P.current)==null?void 0:k.area)},[]);return o.jsx(jy,{scope:n,searchRef:v,onItemEnter:p.useCallback(y=>{D(y)&&y.preventDefault()},[D]),onItemLeave:p.useCallback(y=>{var w;D(y)||((w=x.current)==null||w.focus(),N(null))},[D]),onTriggerLeave:p.useCallback(y=>{D(y)&&y.preventDefault()},[D]),pointerGraceTimerRef:b,onPointerGraceIntentChange:p.useCallback(y=>{P.current=y},[]),children:o.jsx(B,{...M,children:o.jsx(Ma,{asChild:!0,trapped:s,onMountAutoFocus:he(i,y=>{var w;y.preventDefault(),(w=x.current)==null||w.focus({preventScroll:!0})}),onUnmountAutoFocus:a,children:o.jsx(Rs,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:E,onInteractOutside:f,onDismiss:T,children:o.jsx(Ly,{asChild:!0,...m,dir:h.dir,orientation:"vertical",loop:r,currentTabStopId:O,onCurrentTabStopIdChange:N,onEntryFocus:he(c,y=>{h.isUsingKeyboardRef.current||y.preventDefault()}),preventScrollOnEntryFocus:!0,children:o.jsx(Yd,{role:"menu","aria-orientation":"vertical","data-state":zh(S.open),"data-radix-menu-content":"",dir:h.dir,...g,...R,ref:_,style:{outline:"none",...R.style},onKeyDown:he(R.onKeyDown,y=>{const F=y.target.closest("[data-radix-menu-content]")===y.currentTarget,k=y.ctrlKey||y.altKey||y.metaKey,V=y.key.length===1;F&&(y.key==="Tab"&&y.preventDefault(),!k&&V&&U(y.key));const ee=x.current;if(y.target!==ee||!vy.includes(y.key))return;y.preventDefault();const te=I().filter(ne=>!ne.disabled).map(ne=>ne.ref.current);yh.includes(y.key)&&te.reverse(),Jy(te)}),onBlur:he(e.onBlur,y=>{y.currentTarget.contains(y.target)||(window.clearTimeout(C.current),v.current="")}),onPointerMove:he(e.onPointerMove,ts(y=>{const w=y.target,F=L.current!==y.clientX;if(y.currentTarget.contains(w)&&F){const k=y.clientX>L.current?"right":"left";j.current=k,L.current=y.clientX}}))})})})})})})});vh.displayName=It;var Hy="MenuGroup",su=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(Pe.div,{role:"group",...r,ref:t})});su.displayName=Hy;var Wy="MenuLabel",Dh=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(Pe.div,{...r,ref:t})});Dh.displayName=Wy;var Xi="MenuItem",vE="menu.itemSelect",ja=p.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...s}=e,i=p.useRef(null),a=Os(Xi,e.__scopeMenu),l=ru(Xi,e.__scopeMenu),c=ke(t,i),d=p.useRef(!1),u=()=>{const E=i.current;if(!n&&E){const f=new CustomEvent(vE,{bubbles:!0,cancelable:!0});E.addEventListener(vE,T=>r==null?void 0:r(T),{once:!0}),hS(E,f),f.defaultPrevented?d.current=!1:a.onClose()}};return o.jsx(Mh,{...s,ref:c,disabled:n,onClick:he(e.onClick,u),onPointerDown:E=>{var f;(f=e.onPointerDown)==null||f.call(e,E),d.current=!0},onPointerUp:he(e.onPointerUp,E=>{var f;d.current||(f=E.currentTarget)==null||f.click()}),onKeyDown:he(e.onKeyDown,E=>{const f=l.searchRef.current!=="";n||f&&E.key===" "||Zc.includes(E.key)&&(E.currentTarget.click(),E.preventDefault())})})});ja.displayName=Xi;var Mh=p.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:s,...i}=e,a=ru(Xi,n),l=Lh(n),c=p.useRef(null),d=ke(t,c),[u,E]=p.useState(!1),[f,T]=p.useState("");return p.useEffect(()=>{const A=c.current;A&&T((A.textContent??"").trim())},[i.children]),o.jsx(es.ItemSlot,{scope:n,disabled:r,textValue:s??f,children:o.jsx(_y,{asChild:!0,...l,focusable:!r,children:o.jsx(Pe.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:d,onPointerMove:he(e.onPointerMove,ts(A=>{r?a.onItemLeave(A):(a.onItemEnter(A),A.defaultPrevented||A.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:he(e.onPointerLeave,ts(A=>a.onItemLeave(A))),onFocus:he(e.onFocus,()=>E(!0)),onBlur:he(e.onBlur,()=>E(!1))})})})}),Yy="MenuCheckboxItem",Ph=p.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...s}=e;return o.jsx(kh,{scope:e.__scopeMenu,checked:n,children:o.jsx(ja,{role:"menuitemcheckbox","aria-checked":Ki(n)?"mixed":n,...s,ref:t,"data-state":au(n),onSelect:he(s.onSelect,()=>r==null?void 0:r(Ki(n)?!0:!n),{checkForDefaultPrevented:!1})})})});Ph.displayName=Yy;var wh="MenuRadioGroup",[$y,Vy]=Ir(wh,{value:void 0,onValueChange:()=>{}}),Uh=p.forwardRef((e,t)=>{const{value:n,onValueChange:r,...s}=e,i=Bn(r);return o.jsx($y,{scope:e.__scopeMenu,value:n,onValueChange:i,children:o.jsx(su,{...s,ref:t})})});Uh.displayName=wh;var Bh="MenuRadioItem",jh=p.forwardRef((e,t)=>{const{value:n,...r}=e,s=Vy(Bh,e.__scopeMenu),i=n===s.value;return o.jsx(kh,{scope:e.__scopeMenu,checked:i,children:o.jsx(ja,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":au(i),onSelect:he(r.onSelect,()=>{var a;return(a=s.onValueChange)==null?void 0:a.call(s,n)},{checkForDefaultPrevented:!1})})})});jh.displayName=Bh;var iu="MenuItemIndicator",[kh,zy]=Ir(iu,{checked:!1}),Fh=p.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...s}=e,i=zy(iu,n);return o.jsx(Ot,{present:r||Ki(i.checked)||i.checked===!0,children:o.jsx(Pe.span,{...s,ref:t,"data-state":au(i.checked)})})});Fh.displayName=iu;var Xy="MenuSeparator",Gh=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return o.jsx(Pe.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});Gh.displayName=Xy;var Ky="MenuArrow",Hh=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,s=eu(n);return o.jsx($d,{...s,...r,ref:t})});Hh.displayName=Ky;var qy="MenuSub",[l4,Wh]=Ir(qy),Go="MenuSubTrigger",Yh=p.forwardRef((e,t)=>{const n=Or(Go,e.__scopeMenu),r=Os(Go,e.__scopeMenu),s=Wh(Go,e.__scopeMenu),i=ru(Go,e.__scopeMenu),a=p.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:c}=i,d={__scopeMenu:e.__scopeMenu},u=p.useCallback(()=>{a.current&&window.clearTimeout(a.current),a.current=null},[]);return p.useEffect(()=>u,[u]),p.useEffect(()=>{const E=l.current;return()=>{window.clearTimeout(E),c(null)}},[l,c]),o.jsx(tu,{asChild:!0,...d,children:o.jsx(Mh,{id:s.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":s.contentId,"data-state":zh(n.open),...e,ref:xa(t,s.onTriggerChange),onClick:E=>{var f;(f=e.onClick)==null||f.call(e,E),!(e.disabled||E.defaultPrevented)&&(E.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:he(e.onPointerMove,ts(E=>{i.onItemEnter(E),!E.defaultPrevented&&!e.disabled&&!n.open&&!a.current&&(i.onPointerGraceIntentChange(null),a.current=window.setTimeout(()=>{n.onOpenChange(!0),u()},100))})),onPointerLeave:he(e.onPointerLeave,ts(E=>{var T,A;u();const f=(T=n.content)==null?void 0:T.getBoundingClientRect();if(f){const R=(A=n.content)==null?void 0:A.dataset.side,S=R==="right",h=S?-5:5,g=f[S?"left":"right"],m=f[S?"right":"left"];i.onPointerGraceIntentChange({area:[{x:E.clientX+h,y:E.clientY},{x:g,y:f.top},{x:m,y:f.top},{x:m,y:f.bottom},{x:g,y:f.bottom}],side:R}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(E),E.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:he(e.onKeyDown,E=>{var T;const f=i.searchRef.current!=="";e.disabled||f&&E.key===" "||Dy[r.dir].includes(E.key)&&(n.onOpenChange(!0),(T=n.content)==null||T.focus(),E.preventDefault())})})})});Yh.displayName=Go;var $h="MenuSubContent",Vh=p.forwardRef((e,t)=>{const n=_h(It,e.__scopeMenu),{forceMount:r=n.forceMount,...s}=e,i=Or(It,e.__scopeMenu),a=Os(It,e.__scopeMenu),l=Wh($h,e.__scopeMenu),c=p.useRef(null),d=ke(t,c);return o.jsx(es.Provider,{scope:e.__scopeMenu,children:o.jsx(Ot,{present:r||i.open,children:o.jsx(es.Slot,{scope:e.__scopeMenu,children:o.jsx(ou,{id:l.contentId,"aria-labelledby":l.triggerId,...s,ref:d,align:"start",side:a.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{var E;a.isUsingKeyboardRef.current&&((E=c.current)==null||E.focus()),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:he(e.onFocusOutside,u=>{u.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:he(e.onEscapeKeyDown,u=>{a.onClose(),u.preventDefault()}),onKeyDown:he(e.onKeyDown,u=>{var T;const E=u.currentTarget.contains(u.target),f=My[a.dir].includes(u.key);E&&f&&(i.onOpenChange(!1),(T=l.trigger)==null||T.focus(),u.preventDefault())})})})})})});Vh.displayName=$h;function zh(e){return e?"open":"closed"}function Ki(e){return e==="indeterminate"}function au(e){return Ki(e)?"indeterminate":e?"checked":"unchecked"}function Jy(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function Qy(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function Zy(e,t,n){const s=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let a=Qy(e,Math.max(i,0));s.length===1&&(a=a.filter(d=>d!==n));const c=a.find(d=>d.toLowerCase().startsWith(s.toLowerCase()));return c!==n?c:void 0}function eC(e,t){const{x:n,y:r}=e;let s=!1;for(let i=0,a=t.length-1;i<t.length;a=i++){const l=t[i],c=t[a],d=l.x,u=l.y,E=c.x,f=c.y;u>r!=f>r&&n<(E-d)*(r-u)/(f-u)+d&&(s=!s)}return s}function tC(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return eC(n,t)}function ts(e){return t=>t.pointerType==="mouse"?e(t):void 0}var nC=tu,rC=bh,oC=vh,sC=su,iC=Dh,aC=ja,lC=Ph,cC=Uh,dC=jh,uC=Fh,EC=Gh,fC=Hh,pC=Yh,TC=Vh,Xh="DropdownMenu",[SC]=$n(Xh,[Ch]),st=Ch(),[c4,Kh]=SC(Xh),qh="DropdownMenuTrigger",hC=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...s}=e,i=Kh(qh,n),a=st(n);return o.jsx(nC,{asChild:!0,...a,children:o.jsx(Pe.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,...s,ref:xa(t,i.triggerRef),onPointerDown:he(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:he(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});hC.displayName=qh;var RC="DropdownMenuPortal",Jh=e=>{const{__scopeDropdownMenu:t,...n}=e,r=st(t);return o.jsx(rC,{...r,...n})};Jh.displayName=RC;var Qh="DropdownMenuContent",Zh=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Kh(Qh,n),i=st(n),a=p.useRef(!1);return o.jsx(oC,{id:s.contentId,"aria-labelledby":s.triggerId,...i,...r,ref:t,onCloseAutoFocus:he(e.onCloseAutoFocus,l=>{var c;a.current||(c=s.triggerRef.current)==null||c.focus(),a.current=!1,l.preventDefault()}),onInteractOutside:he(e.onInteractOutside,l=>{const c=l.detail.originalEvent,d=c.button===0&&c.ctrlKey===!0,u=c.button===2||d;(!s.modal||u)&&(a.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Zh.displayName=Qh;var AC="DropdownMenuGroup",mC=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=st(n);return o.jsx(sC,{...s,...r,ref:t})});mC.displayName=AC;var gC="DropdownMenuLabel",eR=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=st(n);return o.jsx(iC,{...s,...r,ref:t})});eR.displayName=gC;var IC="DropdownMenuItem",tR=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=st(n);return o.jsx(aC,{...s,...r,ref:t})});tR.displayName=IC;var OC="DropdownMenuCheckboxItem",NC=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=st(n);return o.jsx(lC,{...s,...r,ref:t})});NC.displayName=OC;var xC="DropdownMenuRadioGroup",yC=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=st(n);return o.jsx(cC,{...s,...r,ref:t})});yC.displayName=xC;var CC="DropdownMenuRadioItem",LC=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=st(n);return o.jsx(dC,{...s,...r,ref:t})});LC.displayName=CC;var _C="DropdownMenuItemIndicator",bC=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=st(n);return o.jsx(uC,{...s,...r,ref:t})});bC.displayName=_C;var vC="DropdownMenuSeparator",nR=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=st(n);return o.jsx(EC,{...s,...r,ref:t})});nR.displayName=vC;var DC="DropdownMenuArrow",MC=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=st(n);return o.jsx(fC,{...s,...r,ref:t})});MC.displayName=DC;var PC="DropdownMenuSubTrigger",wC=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=st(n);return o.jsx(pC,{...s,...r,ref:t})});wC.displayName=PC;var UC="DropdownMenuSubContent",BC=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=st(n);return o.jsx(TC,{...s,...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)"}})});BC.displayName=UC;var jC=Jh,kC=Zh,FC=eR,GC=tR,HC=nR;const WC=p.forwardRef(({container:e,style:t,sideOffset:n=4,...r},s)=>o.jsx(jC,{container:e,children:o.jsx(kC,{ref:s,sideOffset:n,style:{minWidth:180,background:me("surfaceElevated"),color:me("textPrimary"),border:`1px solid ${me("borderDefault")}`,borderRadius:Yn.md,boxShadow:me("shadowMd"),padding:Ce[1],zIndex:Jo.popover,...t},...r})}));WC.displayName="DropdownMenuContent";const YC=p.forwardRef(({style:e,...t},n)=>o.jsx(GC,{ref:n,style:{display:"flex",alignItems:"center",gap:Ce[2],padding:`${Ce[1]} ${Ce[2]}`,fontSize:et.sm,borderRadius:Yn.sm,cursor:"default",outline:"none",userSelect:"none",...e},...t}));YC.displayName="DropdownMenuItem";const $C=p.forwardRef(({style:e,...t},n)=>o.jsx(HC,{ref:n,style:{height:1,background:me("borderSubtle"),margin:`${Ce[1]} 0`,...e},...t}));$C.displayName="DropdownMenuSeparator";const VC=p.forwardRef(({style:e,...t},n)=>o.jsx(FC,{ref:n,style:{padding:`${Ce[1]} ${Ce[2]}`,fontSize:et.xs,color:me("textMuted"),textTransform:"uppercase",letterSpacing:"0.04em",...e},...t}));VC.displayName="DropdownMenuLabel";var rR="Popover",[oR]=$n(rR,[Io]),ka=Io(),[d4,Vn]=oR(rR),sR="PopoverAnchor",zC=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,s=Vn(sR,n),i=ka(n),{onCustomAnchorAdd:a,onCustomAnchorRemove:l}=s;return p.useEffect(()=>(a(),()=>l()),[a,l]),o.jsx(ba,{...i,...r,ref:t})});zC.displayName=sR;var iR="PopoverTrigger",XC=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,s=Vn(iR,n),i=ka(n),a=ke(t,s.triggerRef),l=o.jsx(Pe.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":uR(s.open),...r,ref:a,onClick:he(e.onClick,s.onOpenToggle)});return s.hasCustomAnchor?l:o.jsx(ba,{asChild:!0,...i,children:l})});XC.displayName=iR;var lu="PopoverPortal",[KC,qC]=oR(lu,{forceMount:void 0}),aR=e=>{const{__scopePopover:t,forceMount:n,children:r,container:s}=e,i=Vn(lu,t);return o.jsx(KC,{scope:t,forceMount:n,children:o.jsx(Ot,{present:n||i.open,children:o.jsx(ms,{asChild:!0,container:s,children:r})})})};aR.displayName=lu;var io="PopoverContent",lR=p.forwardRef((e,t)=>{const n=qC(io,e.__scopePopover),{forceMount:r=n.forceMount,...s}=e,i=Vn(io,e.__scopePopover);return o.jsx(Ot,{present:r||i.open,children:i.modal?o.jsx(QC,{...s,ref:t}):o.jsx(ZC,{...s,ref:t})})});lR.displayName=io;var JC=ro("PopoverContent.RemoveScroll"),QC=p.forwardRef((e,t)=>{const n=Vn(io,e.__scopePopover),r=p.useRef(null),s=ke(t,r),i=p.useRef(!1);return p.useEffect(()=>{const a=r.current;if(a)return qd(a)},[]),o.jsx(wa,{as:JC,allowPinchZoom:!0,children:o.jsx(cR,{...e,ref:s,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:he(e.onCloseAutoFocus,a=>{var l;a.preventDefault(),i.current||(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:he(e.onPointerDownOutside,a=>{const l=a.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,d=l.button===2||c;i.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:he(e.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1})})})}),ZC=p.forwardRef((e,t)=>{const n=Vn(io,e.__scopePopover),r=p.useRef(!1),s=p.useRef(!1);return o.jsx(cR,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var a,l;(a=e.onCloseAutoFocus)==null||a.call(e,i),i.defaultPrevented||(r.current||(l=n.triggerRef.current)==null||l.focus(),i.preventDefault()),r.current=!1,s.current=!1},onInteractOutside:i=>{var c,d;(c=e.onInteractOutside)==null||c.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const a=i.target;((d=n.triggerRef.current)==null?void 0:d.contains(a))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&s.current&&i.preventDefault()}})}),cR=p.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:d,onInteractOutside:u,...E}=e,f=Vn(io,n),T=ka(n);return Kd(),o.jsx(Ma,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:s,onUnmountAutoFocus:i,children:o.jsx(Rs,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:u,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:d,onDismiss:()=>f.onOpenChange(!1),children:o.jsx(Yd,{"data-state":uR(f.open),role:"dialog",id:f.contentId,...T,...E,ref:t,style:{...E.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)"}})})})}),dR="PopoverClose",eL=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,s=Vn(dR,n);return o.jsx(Pe.button,{type:"button",...r,ref:t,onClick:he(e.onClick,()=>s.onOpenChange(!1))})});eL.displayName=dR;var tL="PopoverArrow",nL=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,s=ka(n);return o.jsx($d,{...s,...r,ref:t})});nL.displayName=tL;function uR(e){return e?"open":"closed"}var rL=aR,oL=lR;const sL=p.forwardRef(({container:e,style:t,sideOffset:n=6,...r},s)=>o.jsx(rL,{container:e,children:o.jsx(oL,{ref:s,sideOffset:n,style:{background:me("surfaceElevated"),color:me("textPrimary"),border:`1px solid ${me("borderDefault")}`,borderRadius:Yn.md,boxShadow:me("shadowMd"),padding:Ce[3],zIndex:Jo.popover,minWidth:220,...t},...r})}));sL.displayName="PopoverContent";function Tn({icon:e,eyebrow:t,title:n,subtitle:r,status:s,actions:i,toolbar:a,bodyPadding:l=14,children:c}){return o.jsxs("div",{className:"panel-frame",children:[o.jsxs("div",{className:"panel-frame-header",children:[o.jsxs("div",{className:"panel-frame-heading",children:[e&&o.jsx("span",{className:"panel-frame-icon",children:e}),o.jsxs("div",{className:"panel-frame-title-col",children:[t&&o.jsx("div",{className:"panel-frame-eyebrow",children:t}),o.jsxs("div",{className:"panel-frame-title-row",children:[n&&o.jsx("h2",{className:"panel-frame-title",children:n}),s&&o.jsx("span",{className:"panel-frame-status",children:s})]}),r&&o.jsx("div",{className:"panel-frame-subtitle",children:r})]})]}),i&&o.jsx("div",{className:"panel-frame-actions",children:i})]}),a&&o.jsx("div",{className:"panel-frame-toolbar",children:a}),o.jsx("div",{className:"panel-frame-body",style:{padding:l},children:c})]})}function cu({tone:e="neutral",icon:t,children:n,className:r="",...s}){return o.jsxs("span",{className:`status-pill tone-${e} ${r}`,...s,children:[t&&o.jsx("span",{className:"status-pill-icon",children:t}),n]})}function En({icon:e,title:t,description:n,action:r}){return o.jsxs("div",{className:"panel-empty",children:[e&&o.jsx("span",{className:"panel-empty-icon",children:e}),t&&o.jsx("p",{className:"panel-empty-title",children:t}),n&&o.jsx("p",{className:"panel-empty-desc",children:n}),r]})}function Ns({left:e,right:t,children:n,className:r=""}){return o.jsxs("div",{className:`panel-toolbar ${r}`,children:[e&&o.jsx("div",{className:"panel-toolbar-left",children:e}),n&&o.jsx("div",{className:"panel-toolbar-center",children:n}),t&&o.jsx("div",{className:"panel-toolbar-right",children:t})]})}function ER({typeLabel:e,typeColor:t,accent:n,idleBorder:r,background:s,headerBackground:i,active:a=!1,title:l,status:c,actions:d,toolbar:u,subheader:E,footer:f,children:T,onMouseEnter:A,onMouseLeave:R,onClick:S,gutter:h,className:g,style:m}){const I=t??"var(--color-accent-blue, #388bfd)",O=n??r??"var(--color-border-subtle, rgba(148,163,184,0.18))",N=r??"var(--color-border-subtle, rgba(148,163,184,0.18))",x=s??"var(--color-bg-1, rgba(22,27,34,0.5))",_=i??"transparent";return o.jsxs("div",{onMouseEnter:A,onMouseLeave:R,onClick:S,className:g,style:{display:"flex",gap:0,marginBottom:2,...m},children:[h!==void 0&&h,o.jsxs("div",{style:{flex:1,minWidth:0,borderRadius:8,border:`1px solid ${a?O:N}`,background:x,overflow:"hidden",transition:"border-color 0.2s, box-shadow 0.2s",boxShadow:a?`0 0 0 3px ${I}14, 0 1px 2px rgba(0,0,0,0.04)`:"0 1px 2px rgba(0,0,0,0.02)"},children:[o.jsxs("div",{style:{minHeight:32,display:"flex",alignItems:"center",padding:"8px 14px",gap:8,background:_},children:[o.jsx("span",{"aria-hidden":!0,style:{width:6,height:6,borderRadius:999,background:I,flexShrink:0}}),o.jsx("span",{style:{fontSize:11,fontWeight:500,letterSpacing:"0.2px",color:"var(--color-text-secondary, #4a4a52)",flexShrink:0,whiteSpace:"nowrap"},children:e}),l!==void 0&&o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{color:"var(--color-text-tertiary, #8a8d96)",fontSize:11},children:"·"}),l]}),u!==void 0&&u,o.jsx("span",{style:{flex:1}}),c!==void 0&&c,d!==void 0&&d]}),E!==void 0&&E,T,f!==void 0&&f]})]})}function iL({shortcut:e,children:t,style:n,...r}){return o.jsx("kbd",{...r,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:18,height:18,padding:`0 ${Ce[1]}px`,borderRadius:Yn.sm,border:`1px solid ${me("borderSubtle")}`,background:me("surfaceRaised"),color:me("textSecondary"),fontFamily:"var(--dql-font-mono, monospace)",fontSize:et.xs,fontWeight:Pd.medium,lineHeight:1,whiteSpace:"nowrap",...n},children:e??t})}const DE=e=>{let t;const n=new Set,r=(d,u)=>{const E=typeof d=="function"?d(t):d;if(!Object.is(E,t)){const f=t;t=u??(typeof E!="object"||E===null)?E:Object.assign({},t,E),n.forEach(T=>T(t,f))}},s=()=>t,l={setState:r,getState:s,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=e(r,s,l);return l},aL=(e=>e?DE(e):DE),lL=e=>e;function cL(e,t=lL){const n=Be.useSyncExternalStore(e.subscribe,Be.useCallback(()=>t(e.getState()),[e,t]),Be.useCallback(()=>t(e.getInitialState()),[e,t]));return Be.useDebugValue(n),n}const ME=e=>{const t=aL(e),n=r=>cL(t,r);return Object.assign(n,t),n},dL=(e=>e?ME(e):ME),PE=e=>Symbol.iterator in e,wE=e=>"entries"in e,UE=(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[s,i]of n)if(!r.has(s)||!Object.is(i,r.get(s)))return!1;return!0},uL=(e,t)=>{const n=e[Symbol.iterator](),r=t[Symbol.iterator]();let s=n.next(),i=r.next();for(;!s.done&&!i.done;){if(!Object.is(s.value,i.value))return!1;s=n.next(),i=r.next()}return!!s.done&&!!i.done};function EL(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:PE(e)&&PE(t)?wE(e)&&wE(t)?UE(e,t):uL(e,t):UE({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function fL(e){const t=Be.useRef(void 0);return n=>{const r=e(n);return EL(t.current,r)?t.current:t.current=r}}function pL(){var e;if(typeof window<"u")try{(e=window.localStorage)==null||e.removeItem("dql-app-mode")}catch{}return"studio"}function TL(){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"}const SL={mainView:"notebook",themeMode:TL(),appMode:pL(),sidebarPanel:"files",sidebarOpen:!0,files:[],filesLoading:!1,activeFile:null,cells:[],notebookTitle:"",notebookMetadata:{},notebookDirty:!1,schemaTables:[],schemaLoading:!1,semanticLayer:{available:!1,provider:null,metrics:[],measures:[],dimensions:[],timeDimensions:[],entities:[],hierarchies:[],semanticModels:[],savedQueries:[],domains:[],tags:[],favorites:[],recentlyUsed:[],loading:!1,lastSyncTime:null},devPanelOpen:!1,devPanelTab:"logs",queryLog:[],newNotebookModalOpen:!1,newBlockModalOpen:!1,newBlockModalDefaultType:"custom",autoSave:!1,executionCounter:0,savingFile:!1,lineageFullscreen:!1,lineageFocusNodeId: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,inspectorOpen:!1,inspectorContext:null,apps:[],appsLoading:!1,activeAppId:null,activeDashboardId:null,activePersona:null};function hL(e,t){var n,r,s,i,a,l;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}:{...e,mainView:t.view,lineageFullscreen:!1,lineageFocusNodeId:null};case"SET_THEME":{if(typeof document<"u"){const c=t.mode==="dark"||t.mode==="midnight"?"obsidian":t.mode==="light"?"paper":t.mode==="arctic"?"white":t.mode;document.documentElement.setAttribute("data-theme",c);try{(n=window.localStorage)==null||n.setItem("dql-theme",t.mode)}catch{}}return{...e,themeMode:t.mode}}case"SET_APP_MODE":{if(typeof window<"u")try{(r=window.localStorage)==null||r.removeItem("dql-app-mode")}catch{}return{...e,appMode:"studio"}}case"SET_SIDEBAR_PANEL":{const c=["connection","reference","git","apps","settings"],d=t.panel!==null&&c.includes(t.panel);return{...e,sidebarPanel:t.panel,sidebarOpen:t.panel!==null&&!d,lineageFullscreen:!1,lineageFocusNodeId:null,mainView:t.panel==="connection"?"connection":t.panel==="reference"?"reference":t.panel==="git"?"git":t.panel==="apps"?"apps":t.panel==="settings"?"settings":t.panel==="files"?"notebook":t.panel==="block_library"||((s=e.activeFile)==null?void 0:s.type)==="block"?"block_studio":"notebook"}}case"TOGGLE_SIDEBAR":return{...e,sidebarOpen:!e.sidebarOpen};case"SET_FILES":return{...e,files:t.files};case"SET_FILES_LOADING":return{...e,filesLoading:t.loading};case"OPEN_FILE":return{...e,activeFile:t.file,cells:t.cells,notebookTitle:t.title,notebookMetadata:t.metadata??{},notebookDirty:!1,mainView:t.file.type==="block"?"block_studio":"notebook",activeBlockPath:t.file.type==="block"?t.file.path:null,blockStudioDraft:t.file.type==="block"?e.blockStudioDraft:"",blockStudioDirty:!1,blockStudioPreview:t.file.type==="block"?e.blockStudioPreview:null,blockStudioValidation:t.file.type==="block"?e.blockStudioValidation:null,blockStudioMetadata:t.file.type==="block"?e.blockStudioMetadata:null,lineageFullscreen:!1,lineageFocusNodeId:null};case"OPEN_BLOCK_STUDIO":return{...e,activeFile:t.file,cells:[],notebookTitle:t.payload.metadata.name,notebookDirty:!1,mainView:"block_studio",dashboardMode:!1,activeBlockPath:t.payload.path,blockStudioDraft:t.payload.source,blockStudioDirty:!1,blockStudioPreview:null,blockStudioValidation:t.payload.validation,blockStudioMetadata:t.payload.metadata,blockStudioImportOpen:!1,lineageFullscreen:!1,lineageFocusNodeId:(i=t.payload.metadata)!=null&&i.name?`block:${t.payload.metadata.name}`:null};case"SET_CELLS":return{...e,cells:t.cells,notebookDirty:!0};case"UPDATE_NOTEBOOK_METADATA":{const c=e.notebookMetadata;let d=!1;for(const u of Object.keys(t.updates))if(c[u]!==t.updates[u]){d=!0;break}return d?{...e,notebookMetadata:{...c,...t.updates},notebookDirty:!0}:e}case"ADD_CELL":{if(!t.afterId)return{...e,cells:[...e.cells,t.cell],notebookDirty:!0};const c=e.cells.findIndex(u=>u.id===t.afterId);if(c===-1)return{...e,cells:[...e.cells,t.cell],notebookDirty:!0};const d=[...e.cells];return d.splice(c+1,0,t.cell),{...e,cells:d,notebookDirty:!0}}case"UPDATE_CELL":{const c=e.cells.map(u=>u.id===t.id?{...u,...t.updates}:u),d=t.updates.executionCount!==void 0?e.executionCounter+1:e.executionCounter;return{...e,cells:c,notebookDirty:!0,executionCounter:d}}case"DELETE_CELL":return{...e,cells:e.cells.filter(c=>c.id!==t.id),notebookDirty:!0};case"MOVE_CELL":{const c=e.cells.findIndex(u=>u.id===t.id);if(c===-1)return e;const d=[...e.cells];return t.direction==="up"&&c>0?[d[c-1],d[c]]=[d[c],d[c-1]]:t.direction==="down"&&c<d.length-1&&([d[c],d[c+1]]=[d[c+1],d[c]]),{...e,cells:d,notebookDirty:!0}}case"REORDER_CELL":{const{fromIndex:c,toIndex:d}=t;if(c===d||c<0||d<0||c>=e.cells.length||d>=e.cells.length)return e;const u=[...e.cells],[E]=u.splice(c,1);return u.splice(d,0,E),{...e,cells:u,notebookDirty:!0}}case"SET_SCHEMA":return{...e,schemaTables:t.tables};case"SET_SCHEMA_LOADING":return{...e,schemaLoading:t.loading};case"TOGGLE_SCHEMA_TABLE":return{...e,schemaTables:e.schemaTables.map(c=>c.name===t.tableName?{...c,expanded:!c.expanded}:c)};case"TOGGLE_DEV_PANEL":return{...e,devPanelOpen:!e.devPanelOpen};case"SET_DEV_PANEL_TAB":return{...e,devPanelTab:t.tab};case"APPEND_QUERY_LOG":return{...e,queryLog:[...e.queryLog,t.entry]};case"OPEN_NEW_NOTEBOOK_MODAL":return{...e,newNotebookModalOpen:!0};case"CLOSE_NEW_NOTEBOOK_MODAL":return{...e,newNotebookModalOpen:!1};case"OPEN_NEW_BLOCK_MODAL":return{...e,newBlockModalOpen:!0,newBlockModalDefaultType:t.blockType??"custom"};case"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:[...e.files,t.file]};case"SET_TABLE_COLUMNS":return{...e,schemaTables:e.schemaTables.map(c=>c.name===t.tableName?{...c,columns:t.columns}:c)};case"SET_PARAM_VALUE":return{...e,cells:e.cells.map(c=>c.id===t.id?{...c,paramValue:t.value}:c),notebookDirty:!0};case"SET_SEMANTIC_LAYER":return{...e,semanticLayer:{...t.layer,loading:!1}};case"SET_SEMANTIC_LOADING":return{...e,semanticLayer:{...e.semanticLayer,loading:t.loading}};case"SET_SEMANTIC_FAVORITES":return{...e,semanticLayer:{...e.semanticLayer,favorites:t.favorites}};case"ADD_SEMANTIC_RECENT":{const c=[t.name,...e.semanticLayer.recentlyUsed.filter(d=>d!==t.name)].slice(0,12);return{...e,semanticLayer:{...e.semanticLayer,recentlyUsed:c}}}case"SET_SEMANTIC_DOMAINS":return{...e,semanticLayer:{...e.semanticLayer,domains:t.domains,tags:t.tags,lastSyncTime:t.lastSyncTime??e.semanticLayer.lastSyncTime}};case"TOGGLE_LINEAGE_FULLSCREEN":return{...e,lineageFullscreen:!e.lineageFullscreen};case"SET_LINEAGE_FOCUS":return{...e,lineageFocusNodeId:t.nodeId};case"OPEN_LINEAGE_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"TOGGLE_INSPECTOR":return{...e,inspectorOpen:!e.inspectorOpen};case"SET_INSPECTOR":return{...e,inspectorOpen:t.open,inspectorContext:t.context===void 0?e.inspectorContext:t.context};case"SET_INSPECTOR_CONTEXT":return{...e,inspectorContext:t.context,inspectorOpen:t.context!==null?!0:e.inspectorOpen};case"SET_APPS":return{...e,apps:t.apps};case"SET_APPS_LOADING":return{...e,appsLoading:t.loading};case"OPEN_APP":{const c=e.apps.find(u=>u.id===t.appId)??null,d=t.dashboardId!==void 0?t.dashboardId:((a=c==null?void 0:c.homepage)==null?void 0:a.type)==="dashboard"?c.homepage.id:((l=c==null?void 0:c.dashboards[0])==null?void 0:l.id)??null;return{...e,mainView:"apps",activeAppId:t.appId,activeDashboardId:d}}case"OPEN_DASHBOARD":return{...e,activeDashboardId:t.dashboardId};case"SET_ACTIVE_PERSONA":return{...e,activePersona:t.persona};default:return e}}const ed=dL((e,t)=>({...SL,dispatch:n=>{const r=hL(t(),n);e(r)}})),RL=p.createContext(null);function AL({children:e}){return Be.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")&&ed.getState().dispatch({type:"SET_THEME",mode:r})};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]),o.jsx(o.Fragment,{children:e})}function Re(){const e=ed(fL(r=>{const{dispatch:s,...i}=r;return i})),t=ed(r=>r.dispatch);return p.useContext(RL)??{state:e,dispatch:t}}function Pt(){return`cell_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function ct(e,t=""){const n={id:Pt(),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}/**
|
|
54
|
+
* @license lucide-react v0.563.0 - ISC
|
|
55
|
+
*
|
|
56
|
+
* This source code is licensed under the ISC license.
|
|
57
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
58
|
+
*/const fR=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();/**
|
|
59
|
+
* @license lucide-react v0.563.0 - ISC
|
|
60
|
+
*
|
|
61
|
+
* This source code is licensed under the ISC license.
|
|
62
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
63
|
+
*/const mL=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
|
|
64
|
+
* @license lucide-react v0.563.0 - ISC
|
|
65
|
+
*
|
|
66
|
+
* This source code is licensed under the ISC license.
|
|
67
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
68
|
+
*/const gL=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());/**
|
|
69
|
+
* @license lucide-react v0.563.0 - ISC
|
|
70
|
+
*
|
|
71
|
+
* This source code is licensed under the ISC license.
|
|
72
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
73
|
+
*/const BE=e=>{const t=gL(e);return t.charAt(0).toUpperCase()+t.slice(1)};/**
|
|
74
|
+
* @license lucide-react v0.563.0 - ISC
|
|
75
|
+
*
|
|
76
|
+
* This source code is licensed under the ISC license.
|
|
77
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
78
|
+
*/var IL={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
|
|
79
|
+
* @license lucide-react v0.563.0 - ISC
|
|
80
|
+
*
|
|
81
|
+
* This source code is licensed under the ISC license.
|
|
82
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
83
|
+
*/const OL=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};/**
|
|
84
|
+
* @license lucide-react v0.563.0 - ISC
|
|
85
|
+
*
|
|
86
|
+
* This source code is licensed under the ISC license.
|
|
87
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
88
|
+
*/const NL=p.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:s="",children:i,iconNode:a,...l},c)=>p.createElement("svg",{ref:c,...IL,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:fR("lucide",s),...!i&&!OL(l)&&{"aria-hidden":"true"},...l},[...a.map(([d,u])=>p.createElement(d,u)),...Array.isArray(i)?i:[i]]));/**
|
|
89
|
+
* @license lucide-react v0.563.0 - ISC
|
|
90
|
+
*
|
|
91
|
+
* This source code is licensed under the ISC license.
|
|
92
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
93
|
+
*/const Ae=(e,t)=>{const n=p.forwardRef(({className:r,...s},i)=>p.createElement(NL,{ref:i,iconNode:t,className:fR(`lucide-${mL(BE(e))}`,`lucide-${e}`,r),...s}));return n.displayName=BE(e),n};/**
|
|
94
|
+
* @license lucide-react v0.563.0 - ISC
|
|
95
|
+
*
|
|
96
|
+
* This source code is licensed under the ISC license.
|
|
97
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
98
|
+
*/const xL=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],yL=Ae("activity",xL);/**
|
|
99
|
+
* @license lucide-react v0.563.0 - ISC
|
|
100
|
+
*
|
|
101
|
+
* This source code is licensed under the ISC license.
|
|
102
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
103
|
+
*/const CL=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],pR=Ae("arrow-down",CL);/**
|
|
104
|
+
* @license lucide-react v0.563.0 - ISC
|
|
105
|
+
*
|
|
106
|
+
* This source code is licensed under the ISC license.
|
|
107
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
108
|
+
*/const LL=[["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"}]],_L=Ae("arrow-right-left",LL);/**
|
|
109
|
+
* @license lucide-react v0.563.0 - ISC
|
|
110
|
+
*
|
|
111
|
+
* This source code is licensed under the ISC license.
|
|
112
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
113
|
+
*/const bL=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],TR=Ae("arrow-up",bL);/**
|
|
114
|
+
* @license lucide-react v0.563.0 - ISC
|
|
115
|
+
*
|
|
116
|
+
* This source code is licensed under the ISC license.
|
|
117
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
118
|
+
*/const vL=[["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"}]],DL=Ae("blocks",vL);/**
|
|
119
|
+
* @license lucide-react v0.563.0 - ISC
|
|
120
|
+
*
|
|
121
|
+
* This source code is licensed under the ISC license.
|
|
122
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
123
|
+
*/const ML=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],SR=Ae("book-open",ML);/**
|
|
124
|
+
* @license lucide-react v0.563.0 - ISC
|
|
125
|
+
*
|
|
126
|
+
* This source code is licensed under the ISC license.
|
|
127
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
128
|
+
*/const PL=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],hR=Ae("check",PL);/**
|
|
129
|
+
* @license lucide-react v0.563.0 - ISC
|
|
130
|
+
*
|
|
131
|
+
* This source code is licensed under the ISC license.
|
|
132
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
133
|
+
*/const wL=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],UL=Ae("chevron-down",wL);/**
|
|
134
|
+
* @license lucide-react v0.563.0 - ISC
|
|
135
|
+
*
|
|
136
|
+
* This source code is licensed under the ISC license.
|
|
137
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
138
|
+
*/const BL=[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]],jL=Ae("chevrons-left",BL);/**
|
|
139
|
+
* @license lucide-react v0.563.0 - ISC
|
|
140
|
+
*
|
|
141
|
+
* This source code is licensed under the ISC license.
|
|
142
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
143
|
+
*/const kL=[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]],FL=Ae("chevrons-right",kL);/**
|
|
144
|
+
* @license lucide-react v0.563.0 - ISC
|
|
145
|
+
*
|
|
146
|
+
* This source code is licensed under the ISC license.
|
|
147
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
148
|
+
*/const GL=[["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"}]],HL=Ae("circle-question-mark",GL);/**
|
|
149
|
+
* @license lucide-react v0.563.0 - ISC
|
|
150
|
+
*
|
|
151
|
+
* This source code is licensed under the ISC license.
|
|
152
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
153
|
+
*/const WL=[["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"}]],YL=Ae("command",WL);/**
|
|
154
|
+
* @license lucide-react v0.563.0 - ISC
|
|
155
|
+
*
|
|
156
|
+
* This source code is licensed under the ISC license.
|
|
157
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
158
|
+
*/const $L=[["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"}]],td=Ae("database",$L);/**
|
|
159
|
+
* @license lucide-react v0.563.0 - ISC
|
|
160
|
+
*
|
|
161
|
+
* This source code is licensed under the ISC license.
|
|
162
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
163
|
+
*/const VL=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],zL=Ae("external-link",VL);/**
|
|
164
|
+
* @license lucide-react v0.563.0 - ISC
|
|
165
|
+
*
|
|
166
|
+
* This source code is licensed under the ISC license.
|
|
167
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
168
|
+
*/const XL=[["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"}]],KL=Ae("eye-off",XL);/**
|
|
169
|
+
* @license lucide-react v0.563.0 - ISC
|
|
170
|
+
*
|
|
171
|
+
* This source code is licensed under the ISC license.
|
|
172
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
173
|
+
*/const qL=[["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"}]],JL=Ae("eye",qL);/**
|
|
174
|
+
* @license lucide-react v0.563.0 - ISC
|
|
175
|
+
*
|
|
176
|
+
* This source code is licensed under the ISC license.
|
|
177
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
178
|
+
*/const QL=[["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"}]],ZL=Ae("file-check",QL);/**
|
|
179
|
+
* @license lucide-react v0.563.0 - ISC
|
|
180
|
+
*
|
|
181
|
+
* This source code is licensed under the ISC license.
|
|
182
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
183
|
+
*/const e_=[["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"}]],t_=Ae("file-pen",e_);/**
|
|
184
|
+
* @license lucide-react v0.563.0 - ISC
|
|
185
|
+
*
|
|
186
|
+
* This source code is licensed under the ISC license.
|
|
187
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
188
|
+
*/const n_=[["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"}]],RR=Ae("file-plus",n_);/**
|
|
189
|
+
* @license lucide-react v0.563.0 - ISC
|
|
190
|
+
*
|
|
191
|
+
* This source code is licensed under the ISC license.
|
|
192
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
193
|
+
*/const r_=[["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"}]],o_=Ae("file-question-mark",r_);/**
|
|
194
|
+
* @license lucide-react v0.563.0 - ISC
|
|
195
|
+
*
|
|
196
|
+
* This source code is licensed under the ISC license.
|
|
197
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
198
|
+
*/const s_=[["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"}]],AR=Ae("file-text",s_);/**
|
|
199
|
+
* @license lucide-react v0.563.0 - ISC
|
|
200
|
+
*
|
|
201
|
+
* This source code is licensed under the ISC license.
|
|
202
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
203
|
+
*/const i_=[["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"}]],a_=Ae("file-x",i_);/**
|
|
204
|
+
* @license lucide-react v0.563.0 - ISC
|
|
205
|
+
*
|
|
206
|
+
* This source code is licensed under the ISC license.
|
|
207
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
208
|
+
*/const l_=[["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"}]],c_=Ae("files",l_);/**
|
|
209
|
+
* @license lucide-react v0.563.0 - ISC
|
|
210
|
+
*
|
|
211
|
+
* This source code is licensed under the ISC license.
|
|
212
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
213
|
+
*/const d_=[["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"}]],Oo=Ae("git-branch",d_);/**
|
|
214
|
+
* @license lucide-react v0.563.0 - ISC
|
|
215
|
+
*
|
|
216
|
+
* This source code is licensed under the ISC license.
|
|
217
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
218
|
+
*/const u_=[["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"}]],mR=Ae("git-commit-horizontal",u_);/**
|
|
219
|
+
* @license lucide-react v0.563.0 - ISC
|
|
220
|
+
*
|
|
221
|
+
* This source code is licensed under the ISC license.
|
|
222
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
223
|
+
*/const E_=[["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"}]],f_=Ae("git-fork",E_);/**
|
|
224
|
+
* @license lucide-react v0.563.0 - ISC
|
|
225
|
+
*
|
|
226
|
+
* This source code is licensed under the ISC license.
|
|
227
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
228
|
+
*/const p_=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],T_=Ae("grip-vertical",p_);/**
|
|
229
|
+
* @license lucide-react v0.563.0 - ISC
|
|
230
|
+
*
|
|
231
|
+
* This source code is licensed under the ISC license.
|
|
232
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
233
|
+
*/const S_=[["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"}]],h_=Ae("layout-dashboard",S_);/**
|
|
234
|
+
* @license lucide-react v0.563.0 - ISC
|
|
235
|
+
*
|
|
236
|
+
* This source code is licensed under the ISC license.
|
|
237
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
238
|
+
*/const R_=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],gR=Ae("maximize-2",R_);/**
|
|
239
|
+
* @license lucide-react v0.563.0 - ISC
|
|
240
|
+
*
|
|
241
|
+
* This source code is licensed under the ISC license.
|
|
242
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
243
|
+
*/const A_=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],m_=Ae("minimize-2",A_);/**
|
|
244
|
+
* @license lucide-react v0.563.0 - ISC
|
|
245
|
+
*
|
|
246
|
+
* This source code is licensed under the ISC license.
|
|
247
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
248
|
+
*/const g_=[["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"}]],I_=Ae("network",g_);/**
|
|
249
|
+
* @license lucide-react v0.563.0 - ISC
|
|
250
|
+
*
|
|
251
|
+
* This source code is licensed under the ISC license.
|
|
252
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
253
|
+
*/const O_=[["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"}]],N_=Ae("package",O_);/**
|
|
254
|
+
* @license lucide-react v0.563.0 - ISC
|
|
255
|
+
*
|
|
256
|
+
* This source code is licensed under the ISC license.
|
|
257
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
258
|
+
*/const x_=[["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"}]],y_=Ae("palette",x_);/**
|
|
259
|
+
* @license lucide-react v0.563.0 - ISC
|
|
260
|
+
*
|
|
261
|
+
* This source code is licensed under the ISC license.
|
|
262
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
263
|
+
*/const C_=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],L_=Ae("panel-left",C_);/**
|
|
264
|
+
* @license lucide-react v0.563.0 - ISC
|
|
265
|
+
*
|
|
266
|
+
* This source code is licensed under the ISC license.
|
|
267
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
268
|
+
*/const __=[["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"}]],b_=Ae("plug",__);/**
|
|
269
|
+
* @license lucide-react v0.563.0 - ISC
|
|
270
|
+
*
|
|
271
|
+
* This source code is licensed under the ISC license.
|
|
272
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
273
|
+
*/const v_=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],D_=Ae("plus",v_);/**
|
|
274
|
+
* @license lucide-react v0.563.0 - ISC
|
|
275
|
+
*
|
|
276
|
+
* This source code is licensed under the ISC license.
|
|
277
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
278
|
+
*/const M_=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],IR=Ae("refresh-cw",M_);/**
|
|
279
|
+
* @license lucide-react v0.563.0 - ISC
|
|
280
|
+
*
|
|
281
|
+
* This source code is licensed under the ISC license.
|
|
282
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
283
|
+
*/const P_=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],w_=Ae("search",P_);/**
|
|
284
|
+
* @license lucide-react v0.563.0 - ISC
|
|
285
|
+
*
|
|
286
|
+
* This source code is licensed under the ISC license.
|
|
287
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
288
|
+
*/const U_=[["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"}]],B_=Ae("settings",U_);/**
|
|
289
|
+
* @license lucide-react v0.563.0 - ISC
|
|
290
|
+
*
|
|
291
|
+
* This source code is licensed under the ISC license.
|
|
292
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
293
|
+
*/const j_=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],k_=Ae("sliders-horizontal",j_);/**
|
|
294
|
+
* @license lucide-react v0.563.0 - ISC
|
|
295
|
+
*
|
|
296
|
+
* This source code is licensed under the ISC license.
|
|
297
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
298
|
+
*/const F_=[["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"}]],G_=Ae("square-dashed",F_);/**
|
|
299
|
+
* @license lucide-react v0.563.0 - ISC
|
|
300
|
+
*
|
|
301
|
+
* This source code is licensed under the ISC license.
|
|
302
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
303
|
+
*/const H_=[["path",{d:"M12 3v18",key:"108xh3"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}]],W_=Ae("table",H_);/**
|
|
304
|
+
* @license lucide-react v0.563.0 - ISC
|
|
305
|
+
*
|
|
306
|
+
* This source code is licensed under the ISC license.
|
|
307
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
308
|
+
*/const Y_=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],$_=Ae("terminal",Y_);/**
|
|
309
|
+
* @license lucide-react v0.563.0 - ISC
|
|
310
|
+
*
|
|
311
|
+
* This source code is licensed under the ISC license.
|
|
312
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
313
|
+
*/const V_=[["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"}]],z_=Ae("trash-2",V_);/**
|
|
314
|
+
* @license lucide-react v0.563.0 - ISC
|
|
315
|
+
*
|
|
316
|
+
* This source code is licensed under the ISC license.
|
|
317
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
318
|
+
*/const X_=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],du=Ae("x",X_);function K_(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 s=0;for(const i of n)if(i===r[s]&&s++,s===r.length)return 10;return 0}function q_(e,t){const n=e.mode??"both";return n==="both"||n===t}function J_({open:e,onClose:t}){const{state:n,dispatch:r}=Re(),[s,i]=p.useState(""),[a,l]=p.useState(0),c=p.useRef(null);p.useEffect(()=>{e&&(i(""),l(0))},[e]);const d=p.useMemo(()=>{const T=I=>r(I),A=()=>t(),R=I=>()=>{I(),A()},S=[["Files","files",c_],["Schema","schema",td],["Lineage","lineage",f_],["Git","git",Oo],["Block Library","block_library",DL],["Apps","apps",I_],["Connections","connection",b_],["Reference","reference",SR]],h=[{mode:"obsidian",label:"Obsidian"},{mode:"paper",label:"Paper"},{mode:"white",label:"White"}],g=[];g.push({id:"sidebar.toggle",label:n.sidebarOpen?"Hide sidebar":"Show sidebar",group:"View",icon:L_,shortcut:"⌘B",mode:"studio",run:R(()=>T({type:"TOGGLE_SIDEBAR"}))},{id:"inspector.toggle",label:n.inspectorOpen?"Hide inspector":"Show inspector",group:"View",icon:n.inspectorOpen?KL:JL,shortcut:"⌘⇧I",mode:"studio",run:R(()=>T({type:"TOGGLE_INSPECTOR"}))},{id:"dashboard.toggle",label:n.dashboardMode?"Exit dashboard mode":"Enter dashboard mode",group:"View",icon:h_,shortcut:"⌘D",run:R(()=>T({type:"TOGGLE_DASHBOARD_MODE"}))},{id:"dev.toggle",label:"Toggle dev panel",group:"View",icon:$_,shortcut:"⌘J",mode:"studio",run:R(()=>T({type:"TOGGLE_DEV_PANEL"}))},{id:"lineage.fullscreen",label:n.lineageFullscreen?"Exit full-screen lineage":"Open full-screen lineage",group:"Lineage",icon:yL,keywords:"graph dag",run:R(()=>T({type:"TOGGLE_LINEAGE_FULLSCREEN"}))});for(const[I,O,N]of S)g.push({id:`panel.${O}`,label:`Go to ${I}`,group:"Navigate",icon:N,mode:"studio",run:R(()=>{T({type:"SET_SIDEBAR_PANEL",panel:O}),n.sidebarOpen||T({type:"TOGGLE_SIDEBAR"})})});g.push({id:"notebook.new",label:"New notebook…",group:"Create",icon:RR,mode:"studio",run:R(()=>T({type:"OPEN_NEW_NOTEBOOK_MODAL"}))},{id:"block.new",label:"New block…",group:"Create",icon:G_,mode:"studio",run:R(()=>T({type:"OPEN_NEW_BLOCK_MODAL"}))});const m=n.themeMode==="dark"||n.themeMode==="midnight"?"obsidian":n.themeMode==="light"?"paper":n.themeMode==="arctic"?"white":n.themeMode;for(const I of h)I.mode!==m&&g.push({id:`theme.${I.mode}`,label:`Switch to ${I.label}`,group:"Theme",icon:y_,keywords:"appearance color",run:R(()=>T({type:"SET_THEME",mode:I.mode}))});return g},[n.sidebarOpen,n.inspectorOpen,n.themeMode,n.dashboardMode,n.lineageFullscreen,n.appMode,n.sidebarPanel,r,t]),u=p.useMemo(()=>{const A=d.filter(R=>q_(R,n.appMode)).map(R=>({a:R,s:K_(R,s)})).filter(R=>R.s>0);return A.sort((R,S)=>S.s-R.s),A.map(R=>R.a)},[d,s,n.appMode]);p.useEffect(()=>{l(0)},[s]),p.useEffect(()=>{var A;const T=(A=c.current)==null?void 0:A.querySelector(`[data-palette-idx="${a}"]`);T==null||T.scrollIntoView({block:"nearest"})},[a]);const E=T=>{var A;T.key==="ArrowDown"?(T.preventDefault(),l(R=>Math.min(u.length-1,R+1))):T.key==="ArrowUp"?(T.preventDefault(),l(R=>Math.max(0,R-1))):T.key==="Enter"&&(T.preventDefault(),(A=u[a])==null||A.run())};let f="";return o.jsx(uy,{open:e,onOpenChange:T=>!T&&t(),children:o.jsxs(Ey,{children:[o.jsx(fy,{style:{position:"fixed",inset:0,background:me("surfaceOverlay"),zIndex:Jo.overlay}}),o.jsxs(py,{"aria-label":"Command palette",style:{position:"fixed",top:"18vh",left:"50%",transform:"translateX(-50%)",width:"92vw",maxWidth:620,background:me("surfaceRaised"),color:me("textPrimary"),border:`1px solid ${me("borderDefault")}`,borderRadius:Yn.lg,boxShadow:me("shadowLg"),zIndex:Jo.modal,display:"flex",flexDirection:"column",overflow:"hidden"},onKeyDown:E,children:[o.jsx(Ty,{style:{position:"absolute",left:-9999},children:"Command palette"}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:Ce[2],padding:`${Ce[3]}px ${Ce[4]}px`,borderBottom:`1px solid ${me("borderSubtle")}`},children:[o.jsx(YL,{size:14,strokeWidth:1.75,color:me("textMuted")}),o.jsx("input",{autoFocus:!0,value:s,onChange:T=>i(T.target.value),placeholder:"Type a command…",style:{flex:1,border:"none",outline:"none",background:"transparent",color:me("textPrimary"),fontSize:et.md}})]}),o.jsxs("div",{ref:c,style:{maxHeight:360,overflowY:"auto",padding:`${Ce[1]}px 0`},children:[u.length===0&&o.jsx("div",{style:{padding:Ce[4],fontSize:et.sm,color:me("textMuted"),textAlign:"center"},children:"No matching commands"}),u.map((T,A)=>{const R=T.group!==f;f=T.group;const S=A===a,h=T.icon;return o.jsxs(Be.Fragment,{children:[R&&o.jsx("div",{style:{padding:`${Ce[2]}px ${Ce[4]}px ${Ce[1]}px`},children:o.jsx(cu,{tone:"neutral",children:T.group})}),o.jsxs("div",{"data-palette-idx":A,role:"option","aria-selected":S,onMouseEnter:()=>l(A),onMouseDown:g=>{g.preventDefault(),T.run()},style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:Ce[3],padding:`${Ce[2]}px ${Ce[4]}px`,fontSize:et.sm,cursor:"pointer",background:S?me("surfaceHover"):"transparent",color:me("textPrimary")},children:[o.jsxs("span",{style:{display:"flex",alignItems:"center",gap:Ce[2],minWidth:0,flex:1},children:[h&&o.jsx(h,{size:14,strokeWidth:1.75}),o.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:T.label})]}),T.shortcut&&o.jsx(iL,{shortcut:T.shortcut})]})]},T.id)})]})]})]})})}const nd=window.location.origin;async function Q(e,t){const n=await fetch(`${nd}${e}`,{headers:{"Content-Type":"application/json"},...t});if(!n.ok){const r=await n.text().catch(()=>n.statusText);throw new Error(r||`HTTP ${n.status}`)}if(n.status!==204)return n.json()}function jE(e){var r;const t=Array.isArray(e==null?void 0:e.columns)?e.columns.map(s=>typeof s=="string"?s:typeof(s==null?void 0:s.name)=="string"?s.name:String(s)):[],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}:{}}}const $={async getSettingsEnvStatus(){try{return await Q("/api/settings/env-status")}catch{return{groups:[]}}},async getProviderSettings(){try{return await Q("/api/settings/providers")}catch{return{providers:[]}}},async saveProviderSettings(e){return Q("/api/settings/providers",{method:"POST",body:JSON.stringify(e)})},async testProviderSettings(e){return Q("/api/settings/providers/test",{method:"POST",body:JSON.stringify({id:e})})},async listAgentMemory(e){const t=e?`?scope=${encodeURIComponent(e)}`:"";try{return await Q(`/api/agent/memory${t}`)}catch{return{memories:[]}}},async saveAgentMemory(e){return Q("/api/agent/memory",{method:"POST",body:JSON.stringify(e)})},async deleteAgentMemory(e){return Q(`/api/agent/memory?id=${encodeURIComponent(e)}`,{method:"DELETE"})},async ensureAgentMemoryFiles(){return Q("/api/agent/memory/default-files",{method:"POST"})},async listNotebooks(){try{return await Q("/api/notebooks")}catch{return[]}},async readNotebook(e){return Q(`/api/notebook-content?path=${encodeURIComponent(e)}`)},async createNotebook(e,t){return Q("/api/notebooks",{method:"POST",body:JSON.stringify({name:e,template:t})})},async createBlock(e,t){return Q("/api/blocks",{method:"POST",body:JSON.stringify({name:e,...t})})},async getBlockLibrary(){try{return await Q("/api/blocks/library")}catch{return{blocks:[]}}},async getApps(){try{return await Q("/api/apps")}catch{return{apps:[]}}},async updateBlockStatus(e,t){return Q("/api/blocks/status",{method:"POST",body:JSON.stringify({path:e,newStatus:t})})},async getBlockHistory(e){try{return await Q(`/api/blocks/history?path=${encodeURIComponent(e)}`)}catch{return{entries:[]}}},async runBlockTests(e,t){return Q("/api/blocks/run-tests",{method:"POST",body:JSON.stringify({source:e,path:t})})},async getBlockStudioCatalog(){return Q("/api/block-studio/catalog")},async getBlockStudioDbtStatus(){return Q("/api/block-studio/dbt-status")},async openBlockStudio(e){return Q(`/api/block-studio/open?path=${encodeURIComponent(e)}`)},async getBlockBody(e){return Q(`/api/blocks/body?path=${encodeURIComponent(e)}`)},async validateBlockStudio(e,t){return Q("/api/block-studio/validate",{method:"POST",body:JSON.stringify({source:e,path:t})})},async runBlockStudio(e,t){return Q("/api/block-studio/run",{method:"POST",body:JSON.stringify({source:e,path:t})})},async saveBlockStudio(e){return Q("/api/block-studio/save",{method:"POST",body:JSON.stringify(e)})},async previewBlockStudioImport(e){return Q("/api/block-studio/import/preview",{method:"POST",body:JSON.stringify(e)})},async listBlockStudioImports(){return Q("/api/block-studio/imports")},async createBlockStudioImport(e){return Q("/api/block-studio/imports",{method:"POST",body:JSON.stringify(e)})},async getBlockStudioImport(e){return Q(`/api/block-studio/imports/${encodeURIComponent(e)}`)},async deleteBlockStudioImport(e){return Q(`/api/block-studio/imports/${encodeURIComponent(e)}`,{method:"DELETE"})},async clearBlockStudioImports(){return Q("/api/block-studio/imports",{method:"DELETE"})},async updateBlockStudioImportCandidate(e,t,n){return Q(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})},async runBlockStudioImportCandidate(e,t){return Q(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/run`,{method:"POST"})},async saveBlockStudioImportCandidate(e,t){return Q(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/save`,{method:"POST"})},async saveAllBlockStudioImportCandidates(e){return Q(`/api/block-studio/imports/${encodeURIComponent(e)}/save-all`,{method:"POST"})},async assistBlockStudioImportCandidate(e,t,n){return Q(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/ai-assist`,{method:"POST",body:JSON.stringify({action:n})})},async certifyBlockStudio(e){const t=await fetch(`${nd}/api/block-studio/certify`,{headers:{"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 Q("/api/blocks/save-from-cell",{method:"POST",body:JSON.stringify(e)})},async getBlockTemplates(){try{return(await Q("/api/blocks/templates")).templates}catch{return[]}},async listBlocks(e){try{return(await Q("/api/notebooks")).filter(n=>n.type==="block"&&(!e||n.path.startsWith(`blocks/${e}/`)))}catch{return[]}},async saveNotebook(e,t){return Q("/api/notebook-content",{method:"PUT",body:JSON.stringify({path:e,content:t})})},async executeQuery(e,t){const n=await Q("/api/query",{method:"POST",body:JSON.stringify({sql:e}),signal:t});return jE(n)},async executeNotebookCell(e,t){const n=await Q("/api/notebook/execute",{method:"POST",body:JSON.stringify({cell:{id:e.id,type:e.type,source:e.content,title:e.name,config:e.chartConfig}}),signal:t});return{cellType:String((n==null?void 0:n.cellType)??e.type),title:typeof(n==null?void 0:n.title)=="string"?n.title:void 0,blockName:typeof(n==null?void 0:n.blockName)=="string"?n.blockName:void 0,blockPath:typeof(n==null?void 0:n.blockPath)=="string"?n.blockPath:void 0,chartConfig:n!=null&&n.chartConfig&&typeof n.chartConfig=="object"?n.chartConfig:void 0,tests:Array.isArray(n==null?void 0:n.tests)?n.tests:void 0,result:n!=null&&n.result?jE(n.result):null}},async getSchema(){try{const e=await fetch(`${nd}/api/schema`);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 Q("/api/connections")}catch{return{default:"unknown",connections:{}}}},async saveConnections(e){return Q("/api/connections",{method:"PUT",body:JSON.stringify({connections:e})})},async testConnection(){try{return await Q("/api/test-connection",{method:"POST",body:JSON.stringify({})})}catch(e){return{ok:!1,message:e.message??"Connection failed"}}},async getSemanticLayer(){try{return await Q("/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 Q("/api/semantic-layer/tree")).tree},async getSemanticObject(e){return Q(`/api/semantic-layer/object/${encodeURIComponent(e)}`)},async importSemanticLayer(e){return Q("/api/semantic-layer/import",{method:"POST",body:JSON.stringify(e)})},async syncSemanticLayer(){return Q("/api/semantic-layer/sync",{method:"POST",body:JSON.stringify({})})},async previewSemanticImport(e){return Q("/api/semantic-layer/import-preview",{method:"POST",body:JSON.stringify(e)})},async previewSyncDiff(){return Q("/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 Q(`/api/semantic-layer/search?${t.toString()}`)}catch{return{metrics:[],measures:[],dimensions:[],timeDimensions:[],entities:[],hierarchies:[],semanticModels:[],savedQueries:[]}}},async getFavorites(){try{return(await Q("/api/user-prefs/favorites")).favorites}catch{return[]}},async toggleFavorite(e){return(await Q("/api/user-prefs/favorites",{method:"POST",body:JSON.stringify({name:e})})).favorites},async getRecentlyUsed(){try{return(await Q("/api/user-prefs/recent")).recentlyUsed}catch{return[]}},async trackUsage(e){try{return(await Q("/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 Q(`/api/semantic-layer/compatible-dims?${t.toString()}`)).dimensions}catch{return[]}},async composeQuery(e,t,n){try{return await Q("/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 Q("/api/semantic-builder/preview",{method:"POST",body:JSON.stringify(e)})}catch(t){return{error:t.message??"Failed to preview semantic block"}}},async saveSemanticBuilder(e){return Q("/api/semantic-builder/save",{method:"POST",body:JSON.stringify(e)})},async createMetric(e){try{return await Q("/api/semantic-layer/metric",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t.message??"Failed to create metric"}}},async describeTable(e){const t=e.split("."),n=t.length>1?t[t.length-1]:e,r=t.length>1?t.slice(0,-1).join("."):"",s=new URLSearchParams({table:n});r&&s.set("schema",r);try{return await Q(`/api/describe-table?${s.toString()}`)}catch{return[]}},async fetchLineage(){try{return await Q("/api/lineage")}catch{return{nodes:[],edges:[]}}},async searchLineage(e){try{return await Q(`/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 Q(`/api/lineage/query?${t.toString()}`)}catch{return{graph:{nodes:[],edges:[]},matches:[]}}},async fetchLineageNode(e){try{return await Q(`/api/lineage/node/${encodeURIComponent(e)}`)}catch{return null}},async fetchBlockLineage(e){try{return await Q(`/api/lineage/block/${encodeURIComponent(e)}`)}catch{return null}},async fetchImpactAnalysis(e){try{return await Q(`/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(),s=`/api/lineage/paths/${encodeURIComponent(e)}${r?`?${r}`:""}`;return await Q(s)}catch{return null}},async fetchGitStatus(){try{return await Q("/api/git/status")}catch{return{inRepo:!1,branch:null,ahead:0,behind:0,changes:[]}}},async fetchGitLog(e=20){try{return await Q(`/api/git/log?limit=${e}`)}catch{return{inRepo:!1,commits:[]}}},async fetchRunSnapshot(e){try{return await Q(`/api/run-snapshot?path=${encodeURIComponent(e)}`)}catch{return{found:!1,snapshot:null}}},async saveRunSnapshot(e,t){await Q("/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 Q(`/api/git/diff${r?`?${r}`:""}`)}catch{return{inRepo:!1,diff:"",before:null,after:null,diffReport:null}}},async fetchGitBranches(){try{return await Q("/api/git/branches")}catch{return{inRepo:!1,current:null,branches:[]}}},async fetchGitRemote(){try{return await Q("/api/git/remote")}catch{return{inRepo:!1,url:null,name:null}}},async gitStage(e){try{return await Q("/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 Q("/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 Q("/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 Q("/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 Q("/api/git/push",{method:"POST",body:"{}"})}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},async gitPull(){try{return await Q("/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 Q("/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 gitCheckout(e){try{return await Q("/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 Q("/api/apps");return e}catch{return[]}},async recommendAppBlocks(e){try{const{blocks:t}=await Q("/api/apps/recommend-blocks",{method:"POST",body:JSON.stringify(e)});return t}catch{return[]}},async createApp(e){return Q("/api/apps",{method:"POST",body:JSON.stringify(e)})},async getApp(e){try{return await Q(`/api/apps/${encodeURIComponent(e)}`)}catch{return null}},async attachAppNotebook(e,t){try{return await Q(`/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 Q(`/api/apps/${encodeURIComponent(e)}/notebook-candidates`);return t}catch{return[]}},async createAppNotebook(e,t){try{return await Q(`/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 Q(`/api/apps/${encodeURIComponent(e)}/notebooks/preview?path=${encodeURIComponent(t)}`)}catch{return null}},async runAppNotebook(e,t){try{return await Q(`/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 Q(`/api/apps/${encodeURIComponent(e)}/conversations`);return t}catch{return[]}},async createAppConversation(e,t){try{return await Q(`/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 Q(`/api/apps/${encodeURIComponent(e)}/conversations/${encodeURIComponent(t)}`);return n}catch{return null}},async updateAppConversation(e,t,n){try{return await Q(`/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 Q(`/api/apps/${encodeURIComponent(e)}/conversations/${encodeURIComponent(t)}`,{method:"DELETE"})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async getDashboard(e,t){try{return await Q(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}`)}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 Q(`/api/apps/${encodeURIComponent(e)}/editor/catalog${r?`?${r}`:""}`)}catch{return null}},async createAppDashboard(e,t){try{return await Q(`/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 Q(`/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 createAiPin(e,t){try{return await Q(`/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:s}=await Q(`/api/apps/${encodeURIComponent(e)}/ai-pins${r?`?${r}`:""}`);return s}catch{return[]}},async refreshAiPin(e,t){try{return await Q(`/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 Q(`/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 Q(`/api/lineage/scope?${t.toString()}`)}catch{return null}},async runDashboard(e,t,n){try{return await Q(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({variables:n??{}})})}catch{return null}},async saveDashboard(e,t,n){try{return{ok:!!(await Q(`/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 Q("/api/persona");return e}catch{return null}},async setPersona(e,t){try{const{persona:n}=await Q("/api/persona",{method:"POST",body:JSON.stringify({userId:e,appId:t})});return n}catch{return null}},async clearPersona(){try{await Q("/api/persona",{method:"DELETE"})}catch{}}};function Q_(){const{state:e,dispatch:t}=Re(),n=e.inspectorContext;return o.jsxs("aside",{"aria-label":"Inspector",style:{width:320,borderLeft:`1px solid ${me("borderSubtle")}`,background:me("surfaceBase"),color:me("textPrimary"),display:"flex",flexDirection:"column",overflow:"hidden",flexShrink:0},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:`${Ce[3]}px ${Ce[4]}px`,borderBottom:`1px solid ${me("borderSubtle")}`},children:[o.jsx("div",{style:{fontSize:et.sm,fontWeight:Pd.semibold},children:n?Z_(n):"Inspector"}),o.jsx("button",{onClick:()=>t({type:"SET_INSPECTOR",open:!1}),"aria-label":"Close inspector",style:{background:"transparent",border:"none",color:me("textMuted"),cursor:"pointer",fontSize:et.md,padding:2,borderRadius:Yn.sm},children:"×"})]}),o.jsx("div",{style:{flex:1,overflow:"auto",padding:Ce[4]},children:n?o.jsx(e0,{context:n}):o.jsx(o0,{})})]})}function Z_(e){switch(e.kind){case"cell":return"Cell";case"lineage-node":return"Lineage node";case"metric":return"Metric"}}function e0({context:e}){return e.kind==="cell"?o.jsx(t0,{cellId:e.cellId}):e.kind==="lineage-node"?o.jsx(n0,{nodeId:e.nodeId}):o.jsx(r0,{name:e.name})}function t0({cellId:e}){const{state:t}=Re(),n=t.cells.find(r=>r.id===e);return n?o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:Ce[3],fontSize:et.sm},children:[o.jsx(lt,{label:"Type",children:n.type}),o.jsx(lt,{label:"ID",children:o.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:n.id})}),o.jsxs(lt,{label:"Length",children:[n.content.length," chars"]}),n.status&&o.jsx(lt,{label:"Status",children:n.status})]}):o.jsx(qi,{children:"No matching cell in the active notebook."})}function n0({nodeId:e}){const[t,n]=p.useState(null),[r,s]=p.useState(!0);if(p.useEffect(()=>{let a=!1;return s(!0),$.fetchLineageNode(e).then(l=>{a||(n(l),s(!1))}).catch(()=>{a||s(!1)}),()=>{a=!0}},[e]),r)return o.jsx(qi,{children:"Loading node…"});if(!t||!t.node)return o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:Ce[3]},children:[o.jsx(lt,{label:"Node ID",children:o.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:e})}),o.jsx(qi,{children:"No metadata available for this node."})]});const i=t.node;return o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:Ce[3]},children:[o.jsx(lt,{label:"Name",children:i.name??e}),o.jsx(lt,{label:"Type",children:i.type}),i.domain&&o.jsx(lt,{label:"Domain",children:i.domain}),i.layer&&o.jsx(lt,{label:"Layer",children:i.layer}),o.jsx(lt,{label:"Upstream",children:t.incoming.length}),o.jsx(lt,{label:"Downstream",children:t.outgoing.length}),i.path&&o.jsx(lt,{label:"Path",children:o.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)",fontSize:et.xs},children:i.path})})]})}function r0({name:e}){return o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:Ce[3]},children:[o.jsx(lt,{label:"Metric",children:e}),o.jsx(qi,{children:"Definition, dimensions, and governance surface will render here."})]})}function lt({label:e,children:t}){return o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[o.jsx("div",{style:{fontSize:et.xs,color:me("textMuted"),textTransform:"uppercase",letterSpacing:.5,fontWeight:Pd.medium},children:e}),o.jsx("div",{style:{fontSize:et.sm,color:me("textPrimary")},children:t})]})}function qi({children:e}){return o.jsx("div",{style:{fontSize:et.sm,color:me("textSecondary"),lineHeight:1.5,background:me("surfaceSunken"),border:`1px solid ${me("borderSubtle")}`,borderRadius:Yn.md,padding:Ce[3]},children:e})}function o0(){return o.jsx("div",{style:{fontSize:et.sm,color:me("textMuted"),lineHeight:1.5},children:"Select a cell, lineage node, or metric to inspect its details here."})}const Ho={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"},kE={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 FE(e){if(typeof document>"u")return kE[e];const t=Ho[e];return getComputedStyle(document.documentElement).getPropertyValue(t).trim()||kE[e]}function s0(){return new Proxy({},{get(e,t){if(typeof t=="string"&&t in Ho)return FE(t)},has(e,t){return typeof t=="string"&&t in Ho},ownKeys(){return Object.keys(Ho)},getOwnPropertyDescriptor(e,t){if(!(typeof t!="string"||!(t in Ho)))return{enumerable:!0,configurable:!0,value:FE(t)}}})}const tr=s0(),ce={obsidian:tr,paper:tr,white:tr,dark:tr,light:tr,midnight:tr,arctic:tr};function Nt(e,t="0 0 24 24"){return function({size:r=16,strokeWidth:s=1.75,...i}){return o.jsx("svg",{width:r,height:r,viewBox:t,fill:"none",stroke:"currentColor",strokeWidth:s,strokeLinecap:"round",strokeLinejoin:"round",...i,children:e})}}const NR=Nt(o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"3",y:"3",width:"8",height:"8",rx:"1.5"}),o.jsx("rect",{x:"13",y:"3",width:"8",height:"8",rx:"1.5"}),o.jsx("rect",{x:"3",y:"13",width:"8",height:"8",rx:"1.5"}),o.jsx("rect",{x:"13",y:"13",width:"8",height:"8",rx:"1.5"})]}));Nt(o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M12 2l8 3v6c0 5-3.5 9-8 11-4.5-2-8-6-8-11V5l8-3z"}),o.jsx("path",{d:"M9 12l2 2 4-4"})]}));const i0=Nt(o.jsxs(o.Fragment,{children:[o.jsx("circle",{cx:"5",cy:"12",r:"2"}),o.jsx("circle",{cx:"19",cy:"5",r:"2"}),o.jsx("circle",{cx:"19",cy:"19",r:"2"}),o.jsx("path",{d:"M7 12l10-6M7 12l10 6"})]})),a0=Nt(o.jsxs(o.Fragment,{children:[o.jsx("ellipse",{cx:"12",cy:"5",rx:"8",ry:"3"}),o.jsx("path",{d:"M4 5v6c0 1.66 3.58 3 8 3s8-1.34 8-3V5"}),o.jsx("path",{d:"M4 11v6c0 1.66 3.58 3 8 3s8-1.34 8-3v-6"})]}));Nt(o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M4 4h8a8 8 0 010 16H4z"}),o.jsx("path",{d:"M16 20l4 4"})]}));const l0=Nt(o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M3 3v18h18"}),o.jsx("path",{d:"M7 15l4-4 4 4 5-7"})]})),c0=Nt(o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),o.jsx("path",{d:"M3 9h18M9 3v18"})]})),d0=Nt(o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),o.jsx("path",{d:"M8 12h8M12 8v8"})]})),u0=Nt(o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M4 7h16M4 12h16M4 17h10"}),o.jsx("circle",{cx:"18",cy:"17",r:"2"})]})),E0=Nt(o.jsx(o.Fragment,{children:o.jsx("path",{d:"M3 5h18l-7 9v5l-4-2v-3L3 5z"})}));Nt(o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M4 4h10l6 6v10H4z"}),o.jsx("path",{d:"M14 4v6h6"}),o.jsx("path",{d:"M8 14l3 3 5-5"})]}));const f0=Nt(o.jsx(o.Fragment,{children:o.jsx("path",{d:"M21 12a8 8 0 01-11.5 7.2L4 21l1.8-5.5A8 8 0 1121 12z"})})),xR=44,yR=188,CR="dql-activitybar-expanded";function p0(){var e;if(typeof window>"u")return!1;try{return((e=window.localStorage)==null?void 0:e.getItem(CR))==="1"}catch{return!1}}function T0(e){var t;try{(t=window.localStorage)==null||t.setItem(CR,e?"1":"0")}catch{}}function jl({title:e,icon:t,active:n,expanded:r,onClick:s,t:i}){const[a,l]=p.useState(!1),c=o.jsxs("button",{"aria-label":e,onClick:s,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{width:r?yR-12:xR-8,height:32,display:"flex",alignItems:"center",justifyContent:r?"flex-start":"center",gap:10,padding:r?"0 10px":0,marginLeft:r?6:4,marginRight:r?6:4,background:n?i.accent+"1f":a?i.textPrimary+"0f":"transparent",border:"none",borderRadius:6,cursor:"pointer",color:n?i.accent:a?i.textPrimary:i.textSecondary,transition:"background 0.15s, color 0.15s",fontFamily:i.font,fontSize:13,fontWeight:n?500:400,textAlign:"left",overflow:"hidden",whiteSpace:"nowrap"},children:[o.jsx("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,width:18,height:18},children:t}),r&&o.jsx("span",{style:{flex:1,textOverflow:"ellipsis",overflow:"hidden"},children:e})]});return r?c:o.jsx(qS,{content:e,side:"right",children:c})}function S0(){const{state:e,dispatch:t}=Re(),n=ce[e.themeMode],[r,s]=p.useState(p0);p.useEffect(()=>{T0(r)},[r]);function i(d){if(d==="review"){t({type:"SET_MAIN_VIEW",view:d});return}if(d==="lineage"){if(e.lineageFullscreen&&e.sidebarPanel==="lineage"&&e.sidebarOpen){t({type:"TOGGLE_LINEAGE_FULLSCREEN"}),t({type:"TOGGLE_SIDEBAR"});return}t({type:"SET_SIDEBAR_PANEL",panel:"lineage"}),t({type:"TOGGLE_LINEAGE_FULLSCREEN"});return}if(d==="connection"||d==="reference"||d==="git"||d==="apps"||d==="settings"){t({type:"SET_SIDEBAR_PANEL",panel:d});return}e.sidebarPanel===d&&e.sidebarOpen?t({type:"TOGGLE_SIDEBAR"}):t({type:"SET_SIDEBAR_PANEL",panel:d})}const a=[{key:"apps",title:"Apps",icon:o.jsx(N_,{size:16,strokeWidth:1.75}),active:e.mainView==="apps"},{key:"files",title:"Notebooks",icon:o.jsx(AR,{size:16,strokeWidth:1.75}),active:e.sidebarPanel==="files"&&e.sidebarOpen},{key:"block_library",title:"Blocks",icon:o.jsx(NR,{size:16}),active:e.sidebarPanel==="block_library"&&e.sidebarOpen},{key:"review",title:"Review",icon:o.jsx(hR,{size:16,strokeWidth:1.75}),active:e.mainView==="review"}],l=[{key:"schema",title:"Schema",icon:o.jsx(td,{size:16,strokeWidth:1.75}),active:e.sidebarPanel==="schema"&&e.sidebarOpen},{key:"lineage",title:"Lineage",icon:o.jsx(i0,{size:16}),active:e.lineageFullscreen},{key:"git",title:"Source control",icon:o.jsx(Oo,{size:16,strokeWidth:1.75}),active:e.mainView==="git"},{key:"connection",title:"Connections",icon:o.jsx(td,{size:16,strokeWidth:1.75}),active:e.mainView==="connection"}],c=[{key:"reference",title:"Reference",icon:o.jsx(SR,{size:16,strokeWidth:1.75}),active:e.mainView==="reference",onClick:()=>i("reference")},{key:"help",title:"Help",icon:o.jsx(HL,{size:16,strokeWidth:1.75}),active:!1,onClick:()=>i("reference")},{key:"settings",title:"Settings",icon:o.jsx(B_,{size:16,strokeWidth:1.75}),active:e.mainView==="settings",onClick:()=>i("settings")}];return o.jsxs("div",{style:{width:r?yR:xR,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:[o.jsx("div",{style:{display:"flex",justifyContent:r?"flex-end":"center",paddingLeft:r?6:0,paddingRight:r?6:0,marginBottom:4},children:o.jsx(qS,{content:r?"Collapse":"Expand",side:"right",children:o.jsx("button",{"aria-label":r?"Collapse sidebar rail":"Expand sidebar rail",onClick:()=>s(d=>!d),style:{width:28,height:26,display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",borderRadius:5,cursor:"pointer",color:n.textMuted,padding:0},onMouseEnter:d=>{d.currentTarget.style.color=n.textPrimary,d.currentTarget.style.background=n.textPrimary+"0f"},onMouseLeave:d=>{d.currentTarget.style.color=n.textMuted,d.currentTarget.style.background="transparent"},children:r?o.jsx(jL,{size:14,strokeWidth:2}):o.jsx(FL,{size:14,strokeWidth:2})})})}),a.map(d=>o.jsx(jl,{title:d.title,icon:d.icon,active:d.active,expanded:r,onClick:()=>i(d.key),t:n},d.key)),o.jsx("div",{style:{height:1,margin:r?"6px 10px":"6px 12px",background:n.headerBorder}}),l.map(d=>o.jsx(jl,{title:d.title,icon:d.icon,active:d.active,expanded:r,onClick:()=>i(d.key),t:n},d.key??d.title)),o.jsx("div",{style:{flex:1}}),c.map(d=>o.jsx(jl,{title:d.title,icon:d.icon,active:d.active,expanded:r,onClick:d.onClick,t:n},d.key))]})}const kl={notebooks:"Notebooks",blocks:"Blocks",dashboards:"Dashboards"},h0={notebooks:!1,blocks:!1,dashboards:!0};function R0({type:e}){switch(e){case"notebook":return o.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M0 1.75A.75.75 0 0 1 .75 1h4.253c1.227 0 2.317.59 3 1.501A3.743 3.743 0 0 1 11.006 1h4.245a.75.75 0 0 1 .75.75v10.5a.75.75 0 0 1-.75.75h-4.507a2.25 2.25 0 0 0-1.591.659l-.622.621a.75.75 0 0 1-1.063 0L7.597 13.66A2.25 2.25 0 0 0 6.007 13H.75a.75.75 0 0 1-.75-.75Zm7.251 10.324.004-5.073-.002-2.253A2.25 2.25 0 0 0 5.003 2.5H1.5v9h4.507c.656 0 1.287.169 1.744.324Zm1.499.004c.457-.155 1.088-.324 1.744-.324H15v-9h-3.495a2.25 2.25 0 0 0-2.252 2.247l-.002 9.077Z"})});case"block":return o.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M10.5 0l5.25 4-5.25 4V6H9.25A1.75 1.75 0 0 0 7.5 7.75v2.5A1.75 1.75 0 0 0 9.25 12h1.25v8H9v-6.5A3.25 3.25 0 0 1 5.75 10h-2A3.25 3.25 0 0 1 .5 6.75v-2.5A3.25 3.25 0 0 1 3.75 1h2A3.25 3.25 0 0 1 9 4.5V6h1.5V0z"})});default:return o.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M.24 2.375C.24 1.064 1.225.001 2.409.001h6.451a1.17 1.17 0 0 1 .828.344l3.311 3.312a1.17 1.17 0 0 1 .344.828v9.14c0 1.31-.985 2.374-2.169 2.374H2.41C1.225 16 .24 14.937.24 13.625Zm2.169-1a.846.846 0 0 0-.844.86v11.39c0 .47.38.86.844.86h8.774a.847.847 0 0 0 .844-.86V5.157L8.688 1.373H2.41Z"})})}}function A0({expanded:e}){return o.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:e?o.jsx("path",{d:"M1.75 2.5a.25.25 0 0 0-.25.25v10.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V4.25a.25.25 0 0 0-.25-.25H7.5A1.75 1.75 0 0 1 5.75 2.5h-4ZM0 2.75C0 1.784.784 1 1.75 1h4c.966 0 1.75.784 1.75 1.75H14.25c.966 0 1.75.784 1.75 1.75v8.5A1.75 1.75 0 0 1 14.25 14H1.75A1.75 1.75 0 0 1 0 12.25Z"}):o.jsx("path",{d:"M1.75 2.5a.25.25 0 0 0-.25.25v10.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V4.25a.25.25 0 0 0-.25-.25H7.5A1.75 1.75 0 0 1 5.75 2.5h-4ZM0 2.75C0 1.784.784 1 1.75 1h4c.966 0 1.75.784 1.75 1.75H14.25c.966 0 1.75.784 1.75 1.75v8.5A1.75 1.75 0 0 1 14.25 14H1.75A1.75 1.75 0 0 1 0 12.25Z"})})}function rd(e){return e.name.replace(/\.(dqlnb|dql)$/,"")}function m0({onOpenFile:e}){const{state:t,dispatch:n}=Re(),r=ce[t.themeMode],[s,i]=p.useState({notebooks:!0,blocks:!1,dashboards:!1}),[a,l]=p.useState(!1),c={notebooks:[],blocks:[],dashboards:[]};for(const E of t.files){const f=E.folder.toLowerCase();f in c&&c[f].push(E)}const d=E=>{i(f=>({...f,[E]:!f[E]}))},u=o.jsx("div",{style:{padding:"0 8px 8px"},children:o.jsxs("button",{onClick:()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}),onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{width:"100%",height:30,background:"transparent",border:`1px dashed ${a?r.accent:r.cellBorder}`,borderRadius:6,color:a?r.accent:r.textSecondary,cursor:"pointer",fontSize:12,fontFamily:r.font,fontWeight:500,display:"flex",alignItems:"center",justifyContent:"center",gap:6,transition:"border-color 0.15s, color 0.15s"},children:[o.jsx("span",{style:{fontSize:16,lineHeight:1},children:"+"}),"New Notebook"]})});return o.jsxs(Tn,{title:"Files",bodyPadding:0,children:[u,t.filesLoading&&o.jsx("div",{style:{padding:"8px 14px",color:r.textMuted,fontSize:12,fontFamily:r.font},children:"Loading files…"}),Object.keys(kl).map(E=>{const f=c[E];if(h0[E]&&f.length===0)return null;const T=s[E],A=E==="notebooks"?()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}):E==="blocks"?()=>n({type:"OPEN_NEW_BLOCK_MODAL"}):void 0;return o.jsxs("div",{children:[o.jsx(g0,{label:kl[E],count:f.length,expanded:T,onToggle:()=>d(E),onAdd:A,t:r}),T&&o.jsx("div",{children:f.length===0?o.jsxs("div",{style:{padding:"4px 14px 4px 32px",fontSize:12,color:r.textMuted,fontFamily:r.font,fontStyle:"italic"},children:["No ",kl[E].toLowerCase()]}):f.map(R=>{var S;return o.jsx(I0,{file:R,active:((S=t.activeFile)==null?void 0:S.path)===R.path,onClick:()=>e(R),onShowLineage:()=>n({type:"OPEN_LINEAGE_DRAWER",nodeId:rd(R)}),t:r},R.path)})})]},E)})]})}function g0({label:e,count:t,expanded:n,onToggle:r,onAdd:s,t:i}){const[a,l]=p.useState(!1),[c,d]=p.useState(!1);return o.jsxs("div",{onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{display:"flex",alignItems:"center",background:a?i.sidebarItemHover:"transparent",transition:"background 0.1s"},children:[o.jsxs("button",{onClick:r,style:{flex:1,display:"flex",alignItems:"center",gap:6,padding:"3px 0 3px 10px",background:"transparent",border:"none",cursor:"pointer",color:i.textSecondary,fontSize:11,fontWeight:600,fontFamily:i.font,letterSpacing:"0.04em",textTransform:"uppercase",textAlign:"left"},children:[o.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:n?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.15s",flexShrink:0},children:o.jsx("path",{d:"M3 2l4 3-4 3V2Z"})}),o.jsx(A0,{expanded:n}),o.jsx("span",{style:{flex:1},children:e}),t>0&&o.jsx("span",{style:{background:i.pillBg,color:i.textMuted,borderRadius:10,padding:"0 5px",fontSize:10,fontWeight:500},children:t})]}),s&&a&&o.jsx("button",{onClick:u=>{u.stopPropagation(),s()},onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),title:`New ${e.slice(0,-1)}`,style:{background:c?i.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:c?i.accent:i.textMuted,fontSize:14,lineHeight:1,padding:"2px 8px",marginRight:4,flexShrink:0,transition:"color 0.1s"},children:"+"})]})}function I0({file:e,active:t,onClick:n,onShowLineage:r,t:s}){const[i,a]=p.useState(!1),[l,c]=p.useState(!1),d=e.type==="notebook"||e.type==="block"||e.type==="dashboard";return o.jsxs("div",{onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{position:"relative",display:"flex",alignItems:"center",background:t?s.sidebarItemActive:i?s.sidebarItemHover:"transparent",borderLeft:t?`2px solid ${s.accent}`:"2px solid transparent",transition:"background 0.1s"},children:[o.jsxs("button",{onClick:n,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:6,padding:"4px 8px 4px 24px",background:"transparent",border:"none",cursor:"pointer",color:t||i?s.textPrimary:s.textSecondary,fontSize:13,fontFamily:s.font,textAlign:"left",transition:"color 0.1s",overflow:"hidden"},children:[o.jsx("span",{style:{flexShrink:0,color:t?s.accent:s.textMuted},children:o.jsx(R0,{type:e.type})}),o.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:rd(e)}),e.isNew&&o.jsx("span",{style:{fontSize:9,fontWeight:600,color:s.accent,background:s.sidebarItemActive,borderRadius:4,padding:"1px 4px",flexShrink:0},children:"NEW"})]}),i&&d&&r&&o.jsx("button",{onClick:u=>{u.stopPropagation(),r()},onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),"aria-label":`Show lineage for ${rd(e)}`,title:"Show lineage",style:{position:"absolute",right:6,top:"50%",transform:"translateY(-50%)",width:22,height:22,display:"inline-flex",alignItems:"center",justifyContent:"center",background:l?s.btnHover:"transparent",border:"none",borderRadius:4,color:l?s.accent:s.textMuted,cursor:"pointer"},children:o.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("circle",{cx:"6",cy:"6",r:"2.5"}),o.jsx("circle",{cx:"18",cy:"6",r:"2.5"}),o.jsx("circle",{cx:"12",cy:"18",r:"2.5"}),o.jsx("path",{d:"M6 8.5v2A2.5 2.5 0 0 0 8.5 13h7A2.5 2.5 0 0 0 18 10.5v-2"}),o.jsx("path",{d:"M12 13v2.5"})]})})]})}const O0={varchar:"#388bfd",text:"#388bfd",string:"#388bfd",char:"#388bfd",integer:"#56d364",int:"#56d364",bigint:"#56d364",smallint:"#56d364",float:"#56d364",double:"#56d364",decimal:"#56d364",numeric:"#56d364",real:"#56d364",date:"#e3b341",timestamp:"#e3b341",datetime:"#e3b341",time:"#e3b341",boolean:"#f778ba",bool:"#f778ba",json:"#79c0ff",jsonb:"#79c0ff",uuid:"#d2a8ff",bytea:"#ffa657",binary:"#ffa657"};function LR(e,t){const n=e.toLowerCase().split("(")[0].trim();return O0[n]??t}function N0({t:e}){return o.jsxs("div",{style:{padding:"8px 12px",display:"flex",flexDirection:"column",gap:8},children:[[1,2,3].map(t=>o.jsx("div",{style:{height:28,borderRadius:4,background:e.pillBg,opacity:.6,animation:"pulse 1.5s ease-in-out infinite"}},t)),o.jsx("style",{children:"@keyframes pulse { 0%,100%{opacity:.6} 50%{opacity:.3} }"})]})}function x0(){const{state:e,dispatch:t}=Re(),n=ce[e.themeMode],[r,s]=p.useState(!1),[i,a]=p.useState(""),l=async()=>{t({type:"SET_SCHEMA_LOADING",loading:!0});try{const A=await $.getSchema();t({type:"SET_SCHEMA",tables:A})}catch(A){console.error("Schema refresh failed:",A)}finally{t({type:"SET_SCHEMA_LOADING",loading:!1})}},c=p.useMemo(()=>{const A=i.trim().toLowerCase();return A?e.schemaTables.filter(R=>{const S=[R.name,R.path,R.objectType].filter(g=>!!g).some(g=>g.toLowerCase().includes(A)),h=R.columns.some(g=>g.name.toLowerCase().includes(A)||g.type.toLowerCase().includes(A));return S||h}):e.schemaTables},[i,e.schemaTables]),d=p.useMemo(()=>{const A=new Map;for(const R of c){const[S,...h]=R.name.split("."),g=h.length>0?S:R.source==="file"?"files":"default",m=A.get(g)??[];m.push(R),A.set(g,m)}return Array.from(A.entries()).sort((R,S)=>R[0].localeCompare(S[0]))},[c]),u={schemas:d.length,tables:e.schemaTables.length,columns:e.schemaTables.reduce((A,R)=>A+R.columns.length,0)},E={width:"100%",background:n.inputBg,border:`1px solid ${n.inputBorder}`,borderRadius:6,color:n.textPrimary,fontSize:12,fontFamily:n.font,padding:"7px 10px",outline:"none",boxSizing:"border-box"},f=o.jsxs("button",{onClick:l,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),title:"Refresh schema",style:{background:r?n.btnHover:"transparent",border:`1px solid ${n.btnBorder}`,borderRadius:6,cursor:"pointer",color:r?n.textSecondary:n.textMuted,fontSize:11,fontFamily:n.font,padding:"6px 8px",display:"flex",alignItems:"center",gap:4,transition:"all 0.15s"},children:[o.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M1.705 8.005a.75.75 0 0 1 .834.656 5.5 5.5 0 0 0 9.592 2.97l-1.204-1.204a.25.25 0 0 1 .177-.427h3.646a.25.25 0 0 1 .25.25v3.646a.25.25 0 0 1-.427.177l-1.38-1.38A7.002 7.002 0 0 1 1.05 8.84a.75.75 0 0 1 .656-.834ZM8 2.5a5.487 5.487 0 0 0-4.131 1.869l1.204 1.204A.25.25 0 0 1 4.896 6H1.25A.25.25 0 0 1 1 5.75V2.104a.25.25 0 0 1 .427-.177l1.38 1.38A7.002 7.002 0 0 1 14.95 7.16a.75.75 0 0 1-1.49.178A5.5 5.5 0 0 0 8 2.5Z"})}),"Refresh"]}),T=o.jsx(Ns,{children:o.jsx("input",{value:i,onChange:A=>a(A.target.value),placeholder:"Search schemas, tables, columns...",style:{...E,flex:1,minWidth:100}})});return o.jsxs(Tn,{title:"Data Catalog",subtitle:"Schemas, tables, views, and columns from the active connection.",actions:f,toolbar:T,bodyPadding:0,children:[o.jsx(y0,{stats:u,t:n}),e.schemaLoading?o.jsx(N0,{t:n}):e.schemaTables.length===0?o.jsx(En,{title:"No tables found",description:"Connect a data source to explore schema."}):c.length===0?o.jsx(En,{title:"No matches",description:"No database objects match the current search."}):o.jsx("div",{style:{overflow:"auto",flex:1},children:d.map(([A,R])=>o.jsx(C0,{name:A,tables:R,defaultExpanded:d.length<=2||i.trim().length>0,t:n},A))})]})}function y0({stats:e,t}){return o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"8px 12px",borderBottom:`1px solid ${t.headerBorder}`,fontSize:11,fontFamily:t.font,color:t.textMuted},children:[o.jsx(Fl,{label:"schemas",value:e.schemas,t}),o.jsx("span",{style:{color:t.headerBorder},children:"·"}),o.jsx(Fl,{label:"tables",value:e.tables,t}),o.jsx("span",{style:{color:t.headerBorder},children:"·"}),o.jsx(Fl,{label:"columns",value:e.columns,t})]})}function Fl({label:e,value:t,t:n}){return o.jsxs("span",{style:{display:"inline-flex",alignItems:"baseline",gap:4},children:[o.jsx("span",{style:{color:n.textPrimary,fontWeight:600,fontSize:12},children:t}),o.jsx("span",{children:e})]})}function C0({name:e,tables:t,defaultExpanded:n,t:r}){const[s,i]=p.useState(n),[a,l]=p.useState(!1);return o.jsxs("div",{children:[o.jsxs("button",{onClick:()=>i(c=>!c),onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),"aria-expanded":s,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"6px 12px",background:a?r.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:r.textSecondary,fontSize:11,fontWeight:700,fontFamily:r.font,textTransform:"uppercase",letterSpacing:"0.05em",textAlign:"left",transition:"background 0.1s",position:"sticky",top:0,zIndex:1,backdropFilter:"blur(6px)"},children:[o.jsx("svg",{width:"9",height:"9",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:s?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.15s",color:r.textMuted,flexShrink:0},children:o.jsx("path",{d:"M3 2l4 3-4 3V2Z"})}),o.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",style:{color:r.textMuted,flexShrink:0},children:o.jsx("path",{d:"M1 3.5c0-1.865 2.91-3 6-3s6 1.135 6 3v9c0 1.865-2.91 3-6 3s-6-1.135-6-3Zm1.5.5c.484.85 2.28 1.5 4.5 1.5s4.016-.65 4.5-1.5V6c-.484.85-2.28 1.5-4.5 1.5S2.984 6.85 2.5 6Zm0 4c.484.85 2.28 1.5 4.5 1.5s4.016-.65 4.5-1.5v2c-.484.85-2.28 1.5-4.5 1.5S2.984 10.85 2.5 10Z"})}),o.jsx("span",{style:{flex:1},children:e}),o.jsx("span",{style:{background:r.pillBg,color:r.textMuted,borderRadius:10,padding:"0 6px",fontSize:10,fontWeight:500},children:t.length})]}),s&&t.map(c=>o.jsx(L0,{table:c,t:r},c.name))]})}function L0({table:e,t}){var E,f;const{dispatch:n}=Re(),[r,s]=p.useState(!1),[i,a]=p.useState(!1),l=async()=>{if(n({type:"TOGGLE_SCHEMA_TABLE",tableName:e.name}),!e.expanded&&e.columns.length===0){a(!0);try{const T=await $.describeTable(e.path);T.length>0&&n({type:"SET_TABLE_COLUMNS",tableName:e.name,columns:T})}catch(T){console.error("describeTable failed:",T)}finally{a(!1)}}},c=((E=e.objectType)==null?void 0:E.toLowerCase().includes("view"))??!1,d=c?"view":"table",u=c?"#d2a8ff":t.accent;return o.jsxs("div",{children:[o.jsxs("button",{onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),onClick:l,style:{width:"100%",display:"flex",alignItems:"center",gap:7,padding:"6px 12px 6px 22px",background:r?t.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:t.textPrimary,fontSize:12.5,fontFamily:t.font,fontWeight:500,textAlign:"left",transition:"background 0.1s"},children:[o.jsx("svg",{width:"9",height:"9",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:e.expanded?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.15s",flexShrink:0,color:t.textMuted},children:o.jsx("path",{d:"M3 2l4 3-4 3V2Z"})}),c?o.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:u,flexShrink:0},children:[o.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12z"}),o.jsx("circle",{cx:"12",cy:"12",r:"3"})]}):o.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:u,flexShrink:0},children:[o.jsx("ellipse",{cx:"12",cy:"5",rx:"9",ry:"3"}),o.jsx("path",{d:"M3 5v14a9 3 0 0 0 18 0V5"}),o.jsx("path",{d:"M3 12a9 3 0 0 0 18 0"})]}),o.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name.includes(".")?e.name.split(".").slice(1).join("."):e.name}),o.jsx("span",{style:{fontSize:9,fontFamily:t.fontMono,color:u,background:`${u}1f`,borderRadius:3,padding:"1px 5px",flexShrink:0,fontWeight:600,letterSpacing:"0.04em"},children:d}),((f=e.governance)==null?void 0:f.status)&&o.jsx(D0,{status:e.governance.status,t}),e.columns.length>0&&o.jsx("span",{style:{fontSize:10,color:t.textMuted,background:t.pillBg,borderRadius:8,padding:"1px 6px",flexShrink:0,fontVariantNumeric:"tabular-nums"},title:`${e.columns.length} columns`,children:e.columns.length})]}),e.expanded&&o.jsxs("div",{style:{paddingLeft:26},children:[e.governance&&(e.governance.owner||e.governance.domain)&&o.jsxs("div",{style:{padding:"3px 10px",display:"flex",gap:8,flexWrap:"wrap"},children:[e.governance.domain&&o.jsxs("span",{style:{fontSize:9,fontFamily:t.font,color:t.textMuted},children:[o.jsx("span",{style:{fontWeight:600},children:"domain:"})," ",e.governance.domain]}),e.governance.owner&&o.jsxs("span",{style:{fontSize:9,fontFamily:t.font,color:t.textMuted},children:[o.jsx("span",{style:{fontWeight:600},children:"owner:"})," ",e.governance.owner]})]}),i?o.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:"..."}):e.columns.length===0?o.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:"No columns"}):e.columns.map(T=>o.jsx(_0,{col:T,t},T.name))]})]})}function _0({col:e,t}){const[n,r]=p.useState(!1),[s,i]=p.useState(!1),a=LR(e.type,t.accent),l=async c=>{c.stopPropagation();try{await navigator.clipboard.writeText(e.name),i(!0),setTimeout(()=>i(!1),1200)}catch{}};return o.jsxs("div",{onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),style:{display:"flex",alignItems:"center",gap:8,padding:"4px 12px 4px 44px",background:n?t.sidebarItemHover:"transparent",cursor:"default",transition:"background 0.1s"},children:[o.jsx("span",{"aria-hidden":!0,style:{flexShrink:0,width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",borderRadius:3,background:`${a}1a`,color:a,fontFamily:t.fontMono,fontSize:9,fontWeight:700,letterSpacing:0},title:e.type,children:b0(e.type)}),o.jsx("span",{style:{flex:1,fontSize:11.5,fontFamily:t.fontMono,color:t.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.name,children:e.name}),o.jsx("span",{style:{fontSize:10,fontFamily:t.fontMono,color:a,background:`${a}1a`,borderRadius:3,padding:"1px 5px",flexShrink:0,fontWeight:500},children:e.type.toLowerCase()}),n&&o.jsx("button",{onClick:l,"aria-label":`Copy column name ${e.name}`,title:s?"Copied!":"Copy column name",style:{flexShrink:0,width:20,height:20,display:"inline-flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",borderRadius:3,color:s?"#56d364":t.textMuted,cursor:"pointer"},children:s?o.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:o.jsx("polyline",{points:"20 6 9 17 4 12"})}):o.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),o.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]})}function b0(e){const t=e.toLowerCase();return/(int|long|short|byte|number|numeric|decimal|float|double|real)/.test(t)?"#":/(bool)/.test(t)?"B":/(date|time|timestamp)/.test(t)?"⌚":/(json|map|struct|object|variant)/.test(t)?"{}":/(array|list)/.test(t)?"[]":/(uuid|guid)/.test(t)?"U":/(char|text|string|varchar)/.test(t)?"A":"·"}const v0={certified:{color:"#56d364",label:"Certified",icon:"✓"},review:{color:"#e3b341",label:"In Review",icon:"◎"},draft:{color:"#8b949e",label:"Draft",icon:"○"},deprecated:{color:"#f85149",label:"Deprecated",icon:"✗"},pending_recertification:{color:"#ffa657",label:"Re-cert",icon:"↻"}};function D0({status:e,t}){const n=v0[e];return n?o.jsxs("span",{title:n.label,style:{fontSize:8,fontWeight:700,fontFamily:t.font,color:n.color,background:`${n.color}18`,border:`1px solid ${n.color}40`,borderRadius:3,padding:"0 4px",flexShrink:0,letterSpacing:"0.04em",lineHeight:"14px"},children:[n.icon," ",n.label.toUpperCase()]}):null}const zt=(e,t)=>`https://cdn.simpleicons.org/${e}/${t}`,Fr=(e,t)=>`https://cdn.jsdelivr.net/gh/devicons/devicon@latest/icons/${e}/${e}-${t}.svg`,M0={duckdb:[zt("duckdb","FFF000")],file:[zt("duckdb","FFF000")],postgres:[zt("postgresql","4169E1")],mysql:[zt("mysql","4479A1"),Fr("mysql","original")],sqlite:[zt("sqlite","003B57"),Fr("sqlite","original")],mssql:[Fr("microsoftsqlserver","original")],redshift:[],snowflake:[zt("snowflake","29B5E8")],bigquery:[zt("googlebigquery","4285F4"),Fr("googlecloud","plain")],databricks:[zt("databricks","FF3621")],clickhouse:[zt("clickhouse","FFCC01")],trino:[zt("trino","DD00A1")],athena:[Fr("amazonwebservices","plain-wordmark")],fabric:[Fr("azure","original")]},P0={duckdb:"#f4bc00",file:"#f4bc00",postgres:"#336791",bigquery:"#4285f4",snowflake:"#29b5e8",sqlite:"#003b57",mysql:"#00758f",mssql:"#cc2927",redshift:"#8c4fff",databricks:"#ff3621",clickhouse:"#ffcc00",athena:"#ff9900",trino:"#dd00a1",fabric:"#0078d4"};function w0({size:e,color:t}){return o.jsx("span",{"aria-hidden":!0,style:{width:e,height:e,borderRadius:3,background:t,flexShrink:0,display:"inline-block"}})}function Gl({driver:e,size:t=16,fallbackColor:n}){const r=M0[e]??[],s=n??P0[e]??"#888",[i,a]=p.useState(0);return r.length===0||i>=r.length?o.jsx(w0,{size:t,color:s}):o.jsx("img",{src:r[i],alt:`${e} logo`,width:t,height:t,loading:"lazy",onError:()=>a(i+1),style:{flexShrink:0,display:"block",objectFit:"contain"}})}const od={duckdb:"DuckDB",file:"Local File / DuckDB",postgres:"PostgreSQL",bigquery:"BigQuery",snowflake:"Snowflake",sqlite:"SQLite",mysql:"MySQL",mssql:"SQL Server",redshift:"Amazon Redshift",databricks:"Databricks",clickhouse:"ClickHouse",athena:"Amazon Athena",trino:"Trino",fabric:"Microsoft Fabric"},GE={duckdb:"#f4bc00",file:"#f4bc00",postgres:"#336791",bigquery:"#4285f4",snowflake:"#29b5e8",sqlite:"#003b57",mysql:"#00758f",mssql:"#cc2927",redshift:"#8c4fff",databricks:"#ff3621",clickhouse:"#ffcc00",athena:"#ff9900",trino:"#dd00a1",fabric:"#0078d4"},U0={duckdb:"In-process analytical database",file:"Local CSV / Parquet via DuckDB",postgres:"Open-source relational warehouse",bigquery:"Google Cloud serverless warehouse",snowflake:"Cloud data platform",sqlite:"Embedded SQL database",mysql:"Open-source relational database",mssql:"Microsoft SQL Server",redshift:"AWS cloud data warehouse",databricks:"Lakehouse platform",clickhouse:"Columnar OLAP database",athena:"AWS serverless S3 query engine",trino:"Distributed SQL query engine",fabric:"Microsoft unified analytics"},B0={duckdb:["filepath"],postgres:["host","port","database","user","password"],mysql:["host","port","database","user","password"],bigquery:["project","dataset","keyFilename"],snowflake:["account","warehouse","database","schema","username","password"],mssql:["server","port","database","user","password"],redshift:["host","port","database","user","password"],sqlite:["filepath"],databricks:["host","path","token"],clickhouse:["host","port","database","user","password"],athena:["region","database","outputLocation"],trino:["host","port","catalog","schema","user"],fabric:["server","database","authentication"]},j0=[{name:"default",label:"Local DuckDB",description:"In-memory DuckDB — no configuration needed",config:{driver:"duckdb",filepath:":memory:"}},{name:"postgres",label:"PostgreSQL",description:"Connect to a local PostgreSQL instance",config:{driver:"postgres",host:"localhost",port:5432,database:"postgres",user:"postgres",password:""}},{name:"snowflake",label:"Snowflake",description:"Connect to your Snowflake data warehouse",config:{driver:"snowflake",account:"",warehouse:"",database:"",schema:"PUBLIC",username:"",password:""}}];function _R(){const{state:e}=Re(),t=ce[e.themeMode],[n,r]=p.useState(null),[s,i]=p.useState(!1),[a,l]=p.useState(null),[c,d]=p.useState(null),[u,E]=p.useState(!1),[f,T]=p.useState(!1),[A,R]=p.useState(null),[S,h]=p.useState(""),[g,m]=p.useState("duckdb"),[I,O]=p.useState({});p.useEffect(()=>{$.getConnections().then(M=>{r(M),Object.keys(M.connections).length>0&&$.testConnection().then(l)})},[]);const N=async()=>{i(!0),l(null);const M=await $.testConnection();l(M),i(!1)},x=(M,U)=>{d(M),E(!1),h(M),m((U==null?void 0:U.driver)??"duckdb");const D={};Object.entries(U??{}).forEach(([y,w])=>{y!=="driver"&&y!=="type"&&(D[y]=String(w??""))}),O(D)},_=()=>{E(!0),d(null),h(""),m("duckdb"),O({})},C=()=>{d(null),E(!1)},v=async()=>{if(!n)return;T(!0),R(null);const M=S.trim()||(c??"default"),U={driver:g};Object.entries(I).forEach(([y,w])=>{w.trim()&&(y==="port"&&!isNaN(Number(w))?U[y]=Number(w):U[y]=w)});const D={...n.connections};c&&c!==M&&delete D[c],D[M]=U;try{await $.saveConnections(D);const y=await $.getConnections();r(y),R("Saved"),setTimeout(()=>R(null),2e3),d(null),E(!1);try{i(!0);const w=await $.testConnection();l(w)}catch{}finally{i(!1)}}catch(y){R(`Error: ${y.message}`)}finally{T(!1)}},b=async M=>{if(!n)return;const U={...n.connections};delete U[M],T(!0);try{await $.saveConnections(U);const D=await $.getConnections();r(D),d(null)}finally{T(!1)}},P={fontSize:10,fontWeight:600,letterSpacing:"0.07em",textTransform:"uppercase",color:t.textMuted,fontFamily:t.font,marginBottom:6},j={background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:7,padding:"10px 12px",marginBottom:10},L=(n==null?void 0:n.connections)??{},B=(n==null?void 0:n.default)??"";return o.jsxs(Tn,{title:"Connections",bodyPadding:12,children:[o.jsx("div",{style:P,children:"Connections"}),n===null?o.jsx("div",{style:{fontSize:12,color:t.textMuted,fontFamily:t.font},children:"Loading…"}):Object.entries(L).map(([M,U])=>{const D=(U==null?void 0:U.driver)??(U==null?void 0:U.type)??"unknown",y=M===B||Object.keys(L).length===1,w=GE[D]??t.accent;return c===M?o.jsx(HE,{t,editName:S,setEditName:h,editDriver:g,setEditDriver:m,editFields:I,setEditFields:O,onSave:v,onCancel:C,onDelete:()=>b(M),saving:f,isNew:!1},M):o.jsxs("div",{style:{...j,borderLeft:y?`3px solid ${w}`:`1px solid ${t.cellBorder}`},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6},children:[o.jsx(Gl,{driver:D,size:18,fallbackColor:w}),o.jsx("span",{style:{fontSize:12,fontWeight:600,color:t.textPrimary,fontFamily:t.font},children:od[D]??D}),o.jsx("span",{style:{fontSize:11,fontFamily:t.fontMono,color:t.textMuted},children:M}),y&&(a==null?void 0:a.ok)&&o.jsx("span",{title:"Connected","aria-label":"Connected",style:{width:7,height:7,borderRadius:"50%",background:t.success,flexShrink:0,boxShadow:`0 0 0 2px ${t.success}25`}}),y&&a&&!a.ok&&o.jsx("span",{title:a.message,"aria-label":"Disconnected",style:{width:7,height:7,borderRadius:"50%",background:t.error,flexShrink:0,boxShadow:`0 0 0 2px ${t.error}25`}}),y&&o.jsx("span",{style:{fontSize:9,color:t.accent,fontFamily:t.font,fontWeight:600,letterSpacing:"0.05em"},children:"DEFAULT"}),o.jsx("div",{style:{flex:1}}),o.jsx("button",{onClick:()=>x(M,U),style:{background:"transparent",border:`1px solid ${t.btnBorder}`,borderRadius:3,cursor:"pointer",color:t.textMuted,fontSize:10,fontFamily:t.font,padding:"1px 6px",transition:"all 0.15s"},children:"Edit"})]}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:3},children:Object.entries(U??{}).filter(([F])=>F!=="driver"&&F!=="type").map(([F,k])=>o.jsxs("div",{style:{display:"flex",gap:6,alignItems:"baseline"},children:[o.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.fontMono,minWidth:70,flexShrink:0},children:F}),o.jsx("span",{style:{fontSize:11,color:t.textSecondary,fontFamily:t.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:F.toLowerCase().includes("password")||F.toLowerCase().includes("token")?"••••••••":String(k)})]},F))})]},M)}),!u&&!c&&Object.keys(L).length===0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{...P,marginTop:8},children:"Quick Connect"}),o.jsx("div",{style:{display:"grid",gap:6,marginBottom:12},children:j0.map(M=>o.jsxs("button",{onClick:async()=>{T(!0);try{const U={...L,[M.name]:M.config};await $.saveConnections(U);const D=await $.getConnections();r(D),i(!0);const y=await $.testConnection();l(y),i(!1)}finally{T(!1)}},disabled:f,style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:7,cursor:f?"not-allowed":"pointer",textAlign:"left",transition:"border-color 0.15s"},children:[o.jsx(Gl,{driver:M.config.driver,size:18}),o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:12,fontWeight:600,color:t.textPrimary,fontFamily:t.font},children:M.label}),o.jsx("div",{style:{fontSize:10,color:t.textMuted,fontFamily:t.font},children:M.description})]})]},M.name))})]}),u?o.jsx(HE,{t,editName:S,setEditName:h,editDriver:g,setEditDriver:m,editFields:I,setEditFields:O,onSave:v,onCancel:C,saving:f,isNew:!0}):o.jsxs("button",{onClick:_,style:{width:"100%",padding:"7px 0",borderRadius:6,border:`1px dashed ${t.cellBorder}`,background:"transparent",color:t.textSecondary,fontSize:12,fontFamily:t.font,fontWeight:500,cursor:"pointer",marginBottom:12,display:"flex",alignItems:"center",justifyContent:"center",gap:6,transition:"border-color 0.15s, color 0.15s"},children:[o.jsx("span",{style:{fontSize:16,lineHeight:1},children:"+"}),"Add Connection"]}),A&&o.jsx("div",{style:{fontSize:11,fontFamily:t.font,padding:"4px 10px",borderRadius:4,marginBottom:8,color:A.startsWith("Error")?t.error:t.success,background:A.startsWith("Error")?`${t.error}12`:`${t.success}12`},children:A}),o.jsx("button",{onClick:N,disabled:s,style:{width:"100%",padding:"7px 0",borderRadius:6,border:`1px solid ${t.btnBorder}`,background:t.btnBg,color:t.textSecondary,fontSize:12,fontFamily:t.font,fontWeight:500,cursor:s?"not-allowed":"pointer",marginBottom:8,opacity:s?.7:1,transition:"all 0.15s"},children:s?"Testing…":"Test Connection"}),a&&o.jsxs("div",{style:{fontSize:12,fontFamily:t.font,color:a.ok?t.success:t.error,background:a.ok?`${t.success}12`:`${t.error}12`,border:`1px solid ${a.ok?t.success:t.error}40`,borderRadius:6,padding:"7px 10px",marginBottom:12},children:[a.ok?"✓ ":"✗ ",a.message]}),o.jsx("div",{style:{...P,marginTop:4},children:"Catalog"}),o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(160px, 1fr))",gap:8,marginBottom:12},children:Object.entries(od).map(([M,U])=>{const D=GE[M]??t.accent,y=U0[M]??"";return o.jsxs("div",{style:{background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:8,padding:"10px 12px",display:"flex",flexDirection:"column",gap:4,minHeight:76,position:"relative",transition:"border-color 0.15s"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsx(Gl,{driver:M,size:18,fallbackColor:D}),o.jsx("span",{style:{fontSize:12,fontWeight:600,color:t.textPrimary,fontFamily:t.font},children:U})]}),o.jsx("div",{style:{fontSize:10,color:t.textMuted,fontFamily:t.font,lineHeight:1.35},children:y}),o.jsx("code",{style:{fontSize:9,color:t.textMuted,fontFamily:t.fontMono,marginTop:"auto"},children:M})]},M)})})]})}function HE({t:e,editName:t,setEditName:n,editDriver:r,setEditDriver:s,editFields:i,setEditFields:a,onSave:l,onCancel:c,onDelete:d,saving:u,isNew:E}){const f=B0[r]??[],T={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%"},A={fontSize:9,fontWeight:600,color:e.textMuted,fontFamily:e.font,letterSpacing:"0.05em",textTransform:"uppercase",marginBottom:2};return o.jsxs("div",{style:{background:e.cellBg,border:`1px solid ${e.accent}40`,borderRadius:7,padding:"10px 12px",marginBottom:10},children:[o.jsx("div",{style:{fontSize:11,fontWeight:600,color:e.accent,fontFamily:e.font,marginBottom:8},children:E?"New Connection":"Edit Connection"}),o.jsxs("div",{style:{marginBottom:6},children:[o.jsx("div",{style:A,children:"Name"}),o.jsx("input",{style:T,value:t,onChange:R=>n(R.target.value),placeholder:"e.g. production"})]}),o.jsxs("div",{style:{marginBottom:6},children:[o.jsx("div",{style:A,children:"Driver"}),o.jsx("select",{style:{...T,fontFamily:e.font},value:r,onChange:R=>{s(R.target.value),a({})},children:Object.entries(od).map(([R,S])=>o.jsx("option",{value:R,children:S},R))})]}),f.map(R=>o.jsxs("div",{style:{marginBottom:6},children:[o.jsx("div",{style:A,children:R}),o.jsx("input",{style:T,type:R.toLowerCase().includes("password")||R.toLowerCase().includes("token")?"password":"text",value:i[R]??"",placeholder:R==="port"?"5432":R==="filepath"?":memory:":"",onChange:S=>a({...i,[R]:S.target.value})})]},R)),o.jsxs("div",{style:{display:"flex",gap:6,marginTop:8},children:[o.jsx("button",{onClick:l,disabled:u,style:{flex:1,padding:"5px 0",borderRadius:5,border:"none",background:e.accent,color:"#fff",fontSize:11,fontFamily:e.font,fontWeight:600,cursor:u?"not-allowed":"pointer",opacity:u?.6:1},children:u?"Saving…":"Save"}),o.jsx("button",{onClick:c,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"}),d&&!E&&o.jsx("button",{onClick:d,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 ln({title:e,defaultOpen:t=!1,children:n,t:r}){const[s,i]=p.useState(t),[a,l]=p.useState(!1);return o.jsxs("div",{style:{borderBottom:`1px solid ${r.headerBorder}`},children:[o.jsxs("button",{onClick:()=>i(c=>!c),onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{width:"100%",padding:"7px 12px",display:"flex",alignItems:"center",gap:6,background:a?r.sidebarItemHover:"transparent",border:"none",cursor:"pointer",textAlign:"left",transition:"background 0.1s"},children:[o.jsx("span",{style:{fontSize:9,color:r.textMuted,display:"inline-block",transition:"transform 0.15s",transform:s?"rotate(90deg)":"rotate(0deg)",lineHeight:1},children:"▶"}),o.jsx("span",{style:{fontSize:11,fontWeight:600,fontFamily:r.font,color:r.textSecondary,letterSpacing:"0.04em"},children:e})]}),s&&o.jsx("div",{style:{padding:"4px 12px 10px"},children:n})]})}function k0({code:e,t}){const[n,r]=p.useState(!1);async function s(){try{await navigator.clipboard.writeText(e)}catch{const i=document.createElement("textarea");i.value=e,document.body.appendChild(i),i.select(),document.execCommand("copy"),document.body.removeChild(i)}r(!0),setTimeout(()=>r(!1),1500)}return o.jsx("button",{onClick:s,title:"Copy to clipboard",style:{position:"absolute",top:6,right:6,padding:"2px 6px",fontSize:10,fontFamily:t.font,background:n?`${t.success}20`:t.btnBg,border:`1px solid ${n?t.success+"50":t.btnBorder}`,borderRadius:4,cursor:"pointer",color:n?t.success:t.textMuted,transition:"all 0.15s"},children:n?"✓":"Copy"})}function Xe({code:e,t}){return o.jsxs("div",{style:{position:"relative",marginTop:6},children:[o.jsx("pre",{style:{margin:0,padding:"8px 10px",paddingRight:52,background:t.editorBg,border:`1px solid ${t.cellBorder}`,borderRadius:6,fontFamily:t.fontMono,fontSize:11,color:t.textPrimary,lineHeight:1.6,whiteSpace:"pre",overflowX:"auto"},children:e}),o.jsx(k0,{code:e,t})]})}function WE({rows:e,t}){return o.jsx("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11,fontFamily:t.font,marginTop:6},children:o.jsx("tbody",{children:e.map(([n,r],s)=>o.jsxs("tr",{style:{borderBottom:`1px solid ${t.tableBorder}`},children:[o.jsx("td",{style:{padding:"5px 6px 5px 0",fontFamily:t.fontMono,fontSize:11,color:t.accent,whiteSpace:"nowrap",verticalAlign:"top",width:"45%"},children:n}),o.jsx("td",{style:{padding:"5px 0",color:t.textSecondary,verticalAlign:"top",lineHeight:1.5},children:r})]},s))})})}const F0=`block "Revenue by Channel" {
|
|
319
|
+
domain = "revenue"
|
|
320
|
+
type = "custom"
|
|
321
|
+
description = "Revenue grouped by sales channel"
|
|
322
|
+
owner = "data-team"
|
|
323
|
+
tags = ["revenue"]
|
|
324
|
+
|
|
325
|
+
params {
|
|
326
|
+
period = "current_quarter"
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
query = """
|
|
330
|
+
SELECT channel,
|
|
331
|
+
SUM(order_total) AS revenue
|
|
332
|
+
FROM read_csv_auto('data/orders.csv')
|
|
333
|
+
WHERE fiscal_period = \${period}
|
|
334
|
+
GROUP BY channel
|
|
335
|
+
ORDER BY revenue DESC
|
|
336
|
+
"""
|
|
337
|
+
|
|
338
|
+
visualization {
|
|
339
|
+
chart = "bar"
|
|
340
|
+
x = channel
|
|
341
|
+
y = revenue
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
tests {
|
|
345
|
+
assert row_count > 0
|
|
346
|
+
}
|
|
347
|
+
}`,G0=`# semantic-layer/metrics/total_revenue.yaml
|
|
348
|
+
name: total_revenue
|
|
349
|
+
label: Total Revenue
|
|
350
|
+
description: Sum of all recognized revenue.
|
|
351
|
+
domain: finance
|
|
352
|
+
sql: SUM(amount)
|
|
353
|
+
type: sum # sum|count|count_distinct|avg|min|max|custom
|
|
354
|
+
table: fct_revenue
|
|
355
|
+
tags:
|
|
356
|
+
- revenue
|
|
357
|
+
- kpi`,H0=`# semantic-layer/dimensions/segment.yaml
|
|
358
|
+
name: segment
|
|
359
|
+
label: Customer Segment
|
|
360
|
+
description: Customer segment tier.
|
|
361
|
+
sql: segment_tier
|
|
362
|
+
type: string # string|number|date|boolean
|
|
363
|
+
table: fct_revenue`,W0=`# semantic-layer/hierarchies/time.yaml
|
|
364
|
+
name: fiscal_time
|
|
365
|
+
label: Fiscal Time
|
|
366
|
+
description: Drill from year to quarter.
|
|
367
|
+
domain: finance
|
|
368
|
+
levels:
|
|
369
|
+
- name: fiscal_year
|
|
370
|
+
dimension: fiscal_year
|
|
371
|
+
order: 1
|
|
372
|
+
- name: fiscal_quarter
|
|
373
|
+
dimension: fiscal_quarter
|
|
374
|
+
order: 2
|
|
375
|
+
defaultRollup: sum`,Y0=`# semantic-layer/cubes/revenue_cube.yaml
|
|
376
|
+
name: revenue
|
|
377
|
+
label: Revenue Cube
|
|
378
|
+
table: fct_revenue
|
|
379
|
+
domain: finance
|
|
380
|
+
|
|
381
|
+
measures:
|
|
382
|
+
- name: total_revenue
|
|
383
|
+
sql: SUM(amount)
|
|
384
|
+
type: sum
|
|
385
|
+
- name: deal_count
|
|
386
|
+
sql: COUNT(*)
|
|
387
|
+
type: count
|
|
388
|
+
|
|
389
|
+
dimensions:
|
|
390
|
+
- name: segment_tier
|
|
391
|
+
sql: segment_tier
|
|
392
|
+
type: string
|
|
393
|
+
|
|
394
|
+
time_dimensions:
|
|
395
|
+
- name: recognized_at
|
|
396
|
+
sql: recognized_at
|
|
397
|
+
primary_time: true
|
|
398
|
+
granularities: [day, month, quarter, year]
|
|
399
|
+
|
|
400
|
+
joins:
|
|
401
|
+
- name: customers
|
|
402
|
+
type: left
|
|
403
|
+
sql: "\${left}.customer_id = \${right}.id"`,$0=`{
|
|
404
|
+
"semanticLayer": {
|
|
405
|
+
"provider": "dql"
|
|
406
|
+
}
|
|
407
|
+
}`,V0=`{
|
|
408
|
+
"semanticLayer": {
|
|
409
|
+
"provider": "dbt",
|
|
410
|
+
"projectPath": "/path/to/your/dbt-project"
|
|
411
|
+
}
|
|
412
|
+
}`,z0=`{
|
|
413
|
+
"semanticLayer": {
|
|
414
|
+
"provider": "cubejs",
|
|
415
|
+
"projectPath": "/path/to/your/cube-project"
|
|
416
|
+
}
|
|
417
|
+
}`,X0=`{
|
|
418
|
+
"defaultConnection": {
|
|
419
|
+
"driver": "file",
|
|
420
|
+
"filepath": ":memory:"
|
|
421
|
+
}
|
|
422
|
+
}`,K0=`{
|
|
423
|
+
"defaultConnection": {
|
|
424
|
+
"driver": "snowflake",
|
|
425
|
+
"account": "acme.snowflakecomputing.com",
|
|
426
|
+
"username": "your_user",
|
|
427
|
+
"password": "\${SNOWFLAKE_PASSWORD}",
|
|
428
|
+
"database": "ANALYTICS",
|
|
429
|
+
"schema": "PUBLIC",
|
|
430
|
+
"warehouse": "COMPUTE_WH",
|
|
431
|
+
"role": "ANALYST"
|
|
432
|
+
}
|
|
433
|
+
}`,q0=`{
|
|
434
|
+
"defaultConnection": {
|
|
435
|
+
"driver": "bigquery",
|
|
436
|
+
"project": "your-gcp-project-id",
|
|
437
|
+
"dataset": "analytics",
|
|
438
|
+
"keyFilename": "./service-account.json"
|
|
439
|
+
}
|
|
440
|
+
}`,J0=`{
|
|
441
|
+
"defaultConnection": {
|
|
442
|
+
"driver": "postgres",
|
|
443
|
+
"host": "localhost",
|
|
444
|
+
"port": 5432,
|
|
445
|
+
"database": "analytics",
|
|
446
|
+
"username": "your_user",
|
|
447
|
+
"password": "\${POSTGRES_PASSWORD}"
|
|
448
|
+
}
|
|
449
|
+
}`,Q0=`-- Primary workflow: use Compose Query in the Semantic Layer panel
|
|
450
|
+
-- 1. Pick metrics + dimensions (+ optional time dimension)
|
|
451
|
+
-- 2. Click "Compose SQL"
|
|
452
|
+
-- 3. Click "+ Insert as Cell" → edit and run
|
|
453
|
+
|
|
454
|
+
-- Advanced: reference metrics inline in any SQL cell
|
|
455
|
+
-- DQL resolves @metric() and @dim() at query time
|
|
456
|
+
SELECT
|
|
457
|
+
@dim(segment_tier),
|
|
458
|
+
@metric(total_revenue)
|
|
459
|
+
FROM fct_revenue
|
|
460
|
+
GROUP BY @dim(segment_tier)
|
|
461
|
+
ORDER BY @metric(total_revenue) DESC`,Z0=`{
|
|
462
|
+
"semanticLayer": {
|
|
463
|
+
"provider": "snowflake",
|
|
464
|
+
"projectPath": "MY_DATABASE"
|
|
465
|
+
}
|
|
466
|
+
}`;function bR({themeMode:e}){const t=ce[e];return o.jsxs(Tn,{title:"Reference",subtitle:"Quick syntax, operators, and cell reference.",bodyPadding:0,children:[o.jsx(ln,{title:"SQL Essentials",defaultOpen:!0,t,children:o.jsx(Xe,{t,code:`-- Basic select
|
|
467
|
+
SELECT col1, col2
|
|
468
|
+
FROM table_name
|
|
469
|
+
WHERE condition
|
|
470
|
+
ORDER BY col1 DESC
|
|
471
|
+
LIMIT 100
|
|
472
|
+
|
|
473
|
+
-- GROUP BY
|
|
474
|
+
SELECT col, COUNT(*), SUM(val)
|
|
475
|
+
FROM table_name
|
|
476
|
+
GROUP BY col
|
|
477
|
+
|
|
478
|
+
-- JOIN
|
|
479
|
+
SELECT a.*, b.col
|
|
480
|
+
FROM table_a AS a
|
|
481
|
+
JOIN table_b AS b ON a.id = b.id
|
|
482
|
+
|
|
483
|
+
-- CTE (WITH)
|
|
484
|
+
WITH cte AS (
|
|
485
|
+
SELECT * FROM table_name WHERE val > 0
|
|
486
|
+
)
|
|
487
|
+
SELECT * FROM cte
|
|
488
|
+
|
|
489
|
+
-- Window function
|
|
490
|
+
SELECT *,
|
|
491
|
+
ROW_NUMBER() OVER (
|
|
492
|
+
PARTITION BY group_col
|
|
493
|
+
ORDER BY val DESC
|
|
494
|
+
) AS rank
|
|
495
|
+
FROM table_name`})}),o.jsx(ln,{title:"DuckDB Functions",defaultOpen:!1,t,children:o.jsx(WE,{t,rows:[["read_csv_auto(path)","Auto-detect CSV schema and load"],["read_parquet(path)","Load a Parquet file"],["strftime(date, fmt)","Format date as string (e.g. '%Y-%m')"],["date_trunc(part, date)","Truncate date to part ('month', 'year'…)"],["CURRENT_DATE","Today's date"],["epoch_ms(ts)","Convert epoch milliseconds to timestamp"],["array_agg(col)","Aggregate column values into an array"],["string_agg(col, sep)","Concatenate values with separator"]]})}),o.jsxs(ln,{title:"DQL Block Structure",defaultOpen:!0,t,children:[o.jsx(Xe,{t,code:F0}),o.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.6},children:["Run ",o.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql certify <file> --connection duckdb"})," to execute ",o.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"tests {}"})," assertions against live data. Use ",o.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"--skip-tests"})," to check governance fields only."]})]}),o.jsxs(ln,{title:"DQL Chart Types",defaultOpen:!1,t,children:[o.jsx(WE,{t,rows:[["table","Tabular data grid (default)"],["bar","Bar chart — use x and y fields"],["line","Line chart — use x (date) and y (value)"],["pie","Pie/donut chart — use x (label) and y (value)"],["kpi","Single big-number KPI card (dql preview)"]]}),o.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.6},children:["Set chart type inside the"," ",o.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:'visualization { chart = "pie"; x = label_col; y = value_col }'})," ","block."]})]}),o.jsxs(ln,{title:"Semantic Layer Usage",defaultOpen:!1,t,children:[o.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:6},children:["Primary workflow: open the ",o.jsx("strong",{children:"Semantic Layer"})," panel → Compose Query → pick metrics and dimensions → Compose SQL → + Insert as Cell. Advanced: use ",o.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"@metric(name)"})," and ",o.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"@dim(name)"})," refs directly in any SQL cell."]}),o.jsx(Xe,{t,code:Q0})]}),o.jsxs(ln,{title:"Semantic Layer",defaultOpen:!1,t,children:[o.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Define reusable metrics, dimensions, and hierarchies in YAML. They appear in the"," ",o.jsx("strong",{style:{color:t.textPrimary},children:"Semantic Layer"})," sidebar panel."]}),o.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"10px 0 4px",letterSpacing:"0.03em"},children:"Directory Structure"}),o.jsx(Xe,{t,code:`my-project/
|
|
496
|
+
├── dql.config.json
|
|
497
|
+
└── semantic-layer/
|
|
498
|
+
├── metrics/ ← one YAML per metric
|
|
499
|
+
├── dimensions/ ← one YAML per dimension
|
|
500
|
+
├── hierarchies/ ← optional drill paths
|
|
501
|
+
└── cubes/ ← optional (groups all into one)`}),o.jsxs("div",{style:{marginTop:8,padding:"6px 8px",background:`${t.accent}10`,border:`1px solid ${t.accent}30`,borderRadius:4,fontSize:11,color:t.textSecondary,fontFamily:t.font,lineHeight:1.6},children:[o.jsx("strong",{style:{color:t.textPrimary},children:"Recommended:"})," For multi-table projects, use a ",o.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"cubes/"})," file — it keeps metrics, dimensions, and joins together. Use standalone ",o.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"metrics/"})," and ",o.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dimensions/"})," files only for simple single-table projects."]}),o.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Metric YAML"}),o.jsx(Xe,{t,code:G0}),o.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Dimension YAML"}),o.jsx(Xe,{t,code:H0}),o.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Hierarchy YAML"}),o.jsx(Xe,{t,code:W0}),o.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Cube YAML (advanced — multi-table with joins)"}),o.jsx(Xe,{t,code:Y0})]}),o.jsxs(ln,{title:"Semantic Layer Providers",defaultOpen:!1,t,children:[o.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Add to your ",o.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql.config.json"})," to connect a semantic layer provider."]}),o.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"10px 0 4px",letterSpacing:"0.03em"},children:"DQL Native (YAML files in semantic-layer/)"}),o.jsx(Xe,{t,code:$0}),o.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"dbt (reads models/**/*.yml)"}),o.jsx(Xe,{t,code:V0}),o.jsxs("div",{style:{marginTop:4,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:["Point to your dbt project root (directory with ",o.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dbt_project.yml"}),"). Reads ",o.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"semantic_models"})," and"," ",o.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"metrics"})," blocks (dbt 1.6+)."]}),o.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Cube.js (reads model/ or schema/)"}),o.jsx(Xe,{t,code:z0}),o.jsxs("div",{style:{marginTop:4,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:["Point to your Cube.js project root. Reads"," ",o.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"cubes:"})," blocks from YAML schema files."]}),o.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Snowflake Semantic Views (requires live connection)"}),o.jsx(Xe,{t,code:Z0}),o.jsxs("div",{style:{marginTop:4,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:["Introspects Snowflake semantic views via"," ",o.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"SHOW SEMANTIC VIEWS"}),". Set ",o.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"projectPath"})," to your database name to scope discovery. Requires a Snowflake connection in ",o.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"defaultConnection"}),"."]})]}),o.jsxs(ln,{title:"Connection Setup",defaultOpen:!1,t,children:[o.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Configure ",o.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"defaultConnection"})," in"," ",o.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql.config.json"}),"."]}),o.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"10px 0 4px",letterSpacing:"0.03em"},children:"DuckDB (in-memory — default)"}),o.jsx(Xe,{t,code:X0}),o.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Snowflake"}),o.jsx(Xe,{t,code:K0}),o.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"BigQuery"}),o.jsx(Xe,{t,code:q0}),o.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"PostgreSQL"}),o.jsx(Xe,{t,code:J0}),o.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:["Use ",o.jsxs("code",{style:{fontFamily:t.fontMono,fontSize:10},children:["$","${ENV_VAR}"]})," syntax for secrets. Run ",o.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dql doctor"})," to verify your connection."]})]}),o.jsxs(ln,{title:"Variable References",defaultOpen:!1,t,children:[o.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Use"," ",o.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"{{cell_name}}"})," ","to reference other cells:",o.jsxs("ul",{style:{margin:"6px 0 0",paddingLeft:18},children:[o.jsxs("li",{children:[o.jsx("strong",{children:"Param cell"})," → substituted as a SQL literal value"]}),o.jsxs("li",{children:[o.jsx("strong",{children:"SQL cell"})," → injected as a CTE"]})]})]}),o.jsx(Xe,{t,code:`-- Param cell named "start_date" holds '2024-01-01'
|
|
502
|
+
SELECT *
|
|
503
|
+
FROM read_csv_auto('data/sales.csv')
|
|
504
|
+
WHERE date >= {{start_date}}
|
|
505
|
+
|
|
506
|
+
-- SQL cell named "base_query" used as CTE
|
|
507
|
+
SELECT segment, SUM(revenue) AS total
|
|
508
|
+
FROM {{base_query}}
|
|
509
|
+
GROUP BY segment`})]})]})}const ze={source_table:"#8b949e",dbt_model:"#ff7b72",dbt_source:"#79c0ff",block:"#56d364",metric:"#388bfd",dimension:"#e3b341",domain:"#d2a8ff",chart:"#f778ba",notebook:"#bc8cff",dashboard:"#a371f7",app:"#db6d28"},Fa={source_table:"TBL",dbt_model:"DBT",dbt_source:"SRC",block:"BLK",metric:"MET",dimension:"DIM",domain:"DOM",chart:"CHT",notebook:"NB",dashboard:"DASH",app:"APP"},Ga={source_table:"Source Table",dbt_model:"dbt Model",dbt_source:"dbt Source",block:"DQL Block",metric:"Metric",dimension:"Dimension",domain:"Domain",chart:"Chart",notebook:"Notebook",dashboard:"Dashboard",app:"App"},zo={reads_from:"#8b949e",feeds_into:"#56d364",aggregates:"#388bfd",visualizes:"#f778ba",depends_on:"#ff7b72",contains:"#d2a8ff",crosses_domain:"#d2a8ff"},eb={reads_from:"reads from",feeds_into:"feeds into",aggregates:"aggregates into",visualizes:"visualizes",depends_on:"dbt depends on",contains:"contains",crosses_domain:"crosses domain"},tb={source:"#79c0ff",transform:"#ff7b72",answer:"#56d364",consumption:"#d2a8ff"},YE={source:"Sources",transform:"Transform",answer:"Answer",consumption:"Consumption"},Ji=["source","transform","answer","consumption"];function uu(e){if(e.layer)return e.layer;switch(e.type){case"source_table":case"dbt_source":return"source";case"dbt_model":return"transform";case"block":case"metric":case"dimension":case"domain":return"answer";case"chart":case"notebook":case"dashboard":case"app":return"consumption";default:return"answer"}}function nb({type:e}){const t=ze[e]??"#8b949e";return o.jsx("span",{style:{color:t,fontSize:10,fontWeight:700,textTransform:"uppercase",minWidth:34},title:Ga[e]??e,children:Fa[e]??e.slice(0,4).toUpperCase()})}function rb({value:e,onChange:t,placeholder:n,t:r}){return o.jsx("input",{value:e,onChange:s=>t(s.target.value),placeholder:n,style:{width:"100%",padding:"8px 10px",borderRadius:6,border:`1px solid ${r.headerBorder}`,background:r.sidebarBg,color:r.textPrimary,fontSize:12,outline:"none"}})}function vR({node:e,t,onClick:n,secondary:r}){return o.jsxs("button",{onClick:n,style:{width:"100%",textAlign:"left",background:"transparent",border:"none",borderRadius:6,padding:"6px 8px",cursor:"pointer",color:t.textPrimary},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[o.jsx(nb,{type:e.type}),o.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12},title:e.name,children:e.name})]}),(r||e.domain)&&o.jsx("div",{style:{marginLeft:40,marginTop:2,color:t.textMuted,fontSize:11},children:r??e.domain})]})}const ob=30,Hl=200;function nr({title:e,nodes:t,t:n,onSelect:r}){const s=t.length>ob,[i,a]=p.useState(!s),[l,c]=p.useState(Hl);if(t.length===0)return null;const d=i?Math.min(l,t.length):0,u=Math.max(0,t.length-d);return o.jsxs("div",{style:{padding:"8px 0",borderTop:`1px solid ${n.headerBorder}`},children:[o.jsxs("button",{onClick:()=>a(E=>!E),"aria-expanded":i,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:[o.jsx("span",{style:{display:"inline-block",width:10},children:i?"▾":"▸"}),o.jsx("span",{children:e}),o.jsx("span",{style:{marginLeft:"auto",fontWeight:500},children:t.length})]}),i&&t.slice(0,d).map(E=>o.jsx(vR,{node:E,t:n,onClick:()=>r(E)},E.id)),i&&u>0&&o.jsxs("button",{onClick:()=>c(E=>E+Hl),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(Hl,u)," more (",u," hidden)"]})]})}function sb(){const{state:e,dispatch:t}=Re(),n=ce[e.themeMode],[r,s]=p.useState(!0),[i,a]=p.useState([]),[,l]=p.useState([]),[c,d]=p.useState(""),[u,E]=p.useState([]),f=p.useCallback(async()=>{s(!0);const m=await $.fetchLineage();a(m.nodes??[]),l(m.edges??[]),s(!1)},[]);p.useEffect(()=>{f()},[f]),p.useEffect(()=>{let m=!1;if(c.trim().length<2){E([]);return}return $.searchLineage(c.trim()).then(I=>{m||E(I.matches??[])}),()=>{m=!0}},[c]);const T=p.useCallback(m=>{t({type:"SET_LINEAGE_FOCUS",nodeId:m.id}),t({type:"OPEN_LINEAGE_DRAWER",nodeId:m.id})},[t]),[A,R]=p.useState("type"),S=p.useMemo(()=>({dashboards:i.filter(m=>m.type==="dashboard"),blocks:i.filter(m=>m.type==="block"),dbtModels:i.filter(m=>m.type==="dbt_model"),dbtSources:i.filter(m=>m.type==="dbt_source"),tables:i.filter(m=>m.type==="source_table"),domains:i.filter(m=>m.type==="domain")}),[i]),h=p.useMemo(()=>{const m={source:[],transform:[],answer:[],consumption:[]};for(const I of i){const O=uu(I);m[O].push(I)}return m},[i]);if(r)return o.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"Loading lineage..."});if(i.length===0)return o.jsx(Tn,{title:"Lineage",bodyPadding:0,children:o.jsx(En,{title:"No lineage data",description:"Run `dql compile` or add notebooks/blocks first."})});const g=o.jsx(Ns,{children:o.jsx(rb,{value:c,onChange:d,placeholder:"Search blocks, tables, dbt models, notebooks...",t:n})});return o.jsxs(Tn,{title:"Lineage",toolbar:g,bodyPadding:0,children:[o.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`},children:[o.jsx("button",{onClick:()=>t({type:"TOGGLE_LINEAGE_FULLSCREEN"}),style:{width:"100%",padding:"8px 10px",borderRadius:6,border:`1px solid ${e.lineageFullscreen?"#388bfd":n.headerBorder}`,background:e.lineageFullscreen?"#388bfd":"transparent",color:e.lineageFullscreen?"#fff":n.textPrimary,fontSize:12,fontWeight:600,cursor:"pointer"},children:e.lineageFullscreen?"Close Graph View":"Open Graph View"}),o.jsx("div",{style:{marginTop:8,color:n.textMuted,fontSize:11,lineHeight:1.5},children:"Search across source tables, dbt sources/models, DQL blocks, metrics, and notebooks. Selecting any item opens a focused lineage path instead of the full graph."})]}),o.jsxs("div",{style:{flex:1,overflow:"auto"},children:[c.trim().length>=2&&u.length>0&&o.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`},children:[o.jsx("div",{style:{color:n.textMuted,fontSize:11,fontWeight:700,textTransform:"uppercase",marginBottom:6},children:"Search Results"}),u.slice(0,8).map(m=>o.jsx(vR,{node:m.node,t:n,onClick:()=>T(m.node),secondary:m.node.domain},m.node.id))]}),o.jsxs("div",{style:{padding:"6px 8px",display:"flex",gap:8,flexWrap:"wrap",borderBottom:`1px solid ${n.headerBorder}`},children:[Ji.map(m=>{const I=h[m].length;return I===0?null:o.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:10,color:n.textMuted},children:[o.jsx("span",{style:{width:8,height:8,borderRadius:2,background:tb[m],display:"inline-block"}}),YE[m],": ",I]},m)}),o.jsx("span",{style:{flex:1}}),o.jsxs("div",{style:{display:"flex",borderRadius:4,border:`1px solid ${n.headerBorder}`,overflow:"hidden"},children:[o.jsx("button",{onClick:()=>R("type"),style:{padding:"2px 6px",fontSize:9,fontWeight:700,border:"none",cursor:"pointer",background:A==="type"?`${n.headerBorder}`:"transparent",color:A==="type"?n.textPrimary:n.textMuted},children:"Type"}),o.jsx("button",{onClick:()=>R("layer"),style:{padding:"2px 6px",fontSize:9,fontWeight:700,border:"none",cursor:"pointer",borderLeft:`1px solid ${n.headerBorder}`,background:A==="layer"?`${n.headerBorder}`:"transparent",color:A==="layer"?n.textPrimary:n.textMuted},children:"Layer"})]})]}),A==="type"?o.jsxs(o.Fragment,{children:[o.jsx(nr,{title:"Notebooks",nodes:S.dashboards,t:n,onSelect:T}),o.jsx(nr,{title:"DQL Blocks",nodes:S.blocks,t:n,onSelect:T}),o.jsx(nr,{title:"dbt Models",nodes:S.dbtModels,t:n,onSelect:T}),o.jsx(nr,{title:"dbt Sources",nodes:S.dbtSources,t:n,onSelect:T}),o.jsx(nr,{title:"Source Tables",nodes:S.tables,t:n,onSelect:T}),o.jsx(nr,{title:"Business Domains",nodes:S.domains,t:n,onSelect:T})]}):o.jsx(o.Fragment,{children:Ji.map(m=>o.jsx(nr,{title:YE[m],nodes:h[m],t:n,onSelect:T},m))})]})]})}const ib={certified:"success",published:"success",deprecated:"error",draft:"warning",pending:"warning",review:"accent"};function ab(){const{state:e,dispatch:t}=Re(),n=ce[e.themeMode],[r,s]=p.useState([]),[i,a]=p.useState(!0),[l,c]=p.useState(""),[d,u]=p.useState(""),[E,f]=p.useState(""),[T,A]=p.useState(!1);p.useEffect(()=>{a(!0),$.getBlockLibrary().then(v=>s(v.blocks)).finally(()=>a(!1))},[]);const R=[...new Set(r.map(v=>v.domain))].sort(),S=[...new Set(r.map(v=>v.status))].sort(),h=r.filter(v=>!(l&&!v.name.toLowerCase().includes(l.toLowerCase())&&!v.description.toLowerCase().includes(l.toLowerCase())||d&&v.domain!==d||E&&v.status!==E)),g=T||l||d||E?h:h.slice(0,10),m=v=>{const b={name:v.path.split("/").pop()??v.name,path:v.path,type:"block",folder:"blocks"};e.files.some(P=>P.path===v.path)||t({type:"FILE_ADDED",file:b}),$.openBlockStudio(v.path).then(P=>{t({type:"OPEN_BLOCK_STUDIO",file:b,payload:P})})},I=()=>{a(!0),$.getBlockLibrary().then(v=>s(v.blocks)).finally(()=>a(!1))},O={background:n.inputBg,border:`1px solid ${n.inputBorder}`,borderRadius:6,color:n.textPrimary,fontSize:11,fontFamily:n.font,padding:"6px 10px",outline:"none"},N=`data:image/svg+xml;utf8,${encodeURIComponent(`<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 10 10'><path fill='none' stroke='${n.textMuted}' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round' d='M2 4l3 3 3-3'/></svg>`)}`,x={...O,appearance:"none",WebkitAppearance:"none",MozAppearance:"none",backgroundImage:`url("${N}")`,backgroundRepeat:"no-repeat",backgroundPosition:"right 8px center",paddingRight:24,cursor:"pointer"},_=o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>t({type:"OPEN_BLOCK_IMPORT"}),style:{background:`${n.accent}18`,border:`1px solid ${n.accent}`,borderRadius:4,color:n.accent,cursor:"pointer",fontSize:10,fontWeight:600,fontFamily:n.font,padding:"3px 10px"},children:"Import SQL"}),o.jsx("button",{onClick:()=>t({type:"OPEN_NEW_BLOCK_MODAL"}),style:{background:n.accent,border:"none",borderRadius:4,color:"#fff",cursor:"pointer",fontSize:10,fontWeight:600,fontFamily:n.font,padding:"3px 10px"},children:"+ New"}),o.jsx("button",{onClick:I,style:{background:"transparent",border:`1px solid ${n.cellBorder}`,borderRadius:4,color:n.textSecondary,cursor:"pointer",fontSize:10,fontFamily:n.font,padding:"3px 8px"},children:"Refresh"})]}),C=o.jsxs(Ns,{children:[o.jsx("input",{value:l,onChange:v=>c(v.target.value),placeholder:"Search blocks...",style:{...O,flex:1,minWidth:100}}),o.jsxs("select",{value:d,onChange:v=>u(v.target.value),style:x,children:[o.jsx("option",{value:"",children:"All domains"}),R.map(v=>o.jsx("option",{value:v,children:v},v))]}),o.jsxs("select",{value:E,onChange:v=>f(v.target.value),style:x,children:[o.jsx("option",{value:"",children:"All statuses"}),S.map(v=>o.jsx("option",{value:v,children:v},v))]})]});return o.jsx(Tn,{title:"Blocks",status:o.jsx("span",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:h.length}),actions:_,toolbar:C,bodyPadding:0,children:i?o.jsx(En,{title:"Loading blocks…"}):h.length===0?o.jsx(En,{title:r.length===0?"No blocks yet":"No matches",description:r.length===0?"Create your first block to get started.":"No blocks match your filters."}):o.jsxs(o.Fragment,{children:[g.map(v=>o.jsxs("button",{onClick:()=>m(v),style:{display:"block",width:"100%",textAlign:"left",background:"transparent",border:"none",borderBottom:`1px solid ${n.cellBorder}`,cursor:"pointer",padding:"10px 12px",transition:"background 0.1s"},onMouseEnter:b=>{b.currentTarget.style.background=`${n.accent}0a`},onMouseLeave:b=>{b.currentTarget.style.background="transparent"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[o.jsx("span",{style:{fontSize:12,fontWeight:600,color:n.textPrimary,fontFamily:n.font},children:v.name}),o.jsx(cu,{tone:ib[v.status]??"neutral",children:v.status})]}),v.description&&o.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font,lineHeight:1.3,marginBottom:4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v.description}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:10,color:n.textMuted,fontFamily:n.font},children:[o.jsx("span",{style:{background:n.pillBg,padding:"1px 6px",borderRadius:4},children:v.domain}),v.owner&&o.jsxs("span",{children:["by ",v.owner]}),v.llmContext&&o.jsx("span",{title:v.llmContext,style:{color:n.accent,fontWeight:600,letterSpacing:"0.04em"},children:"AI"}),o.jsx("span",{style:{marginLeft:"auto"},children:new Date(v.lastModified).toLocaleDateString()})]})]},v.path)),!T&&!l&&!d&&!E&&h.length>10&&o.jsxs("button",{onClick:()=>A(!0),style:{width:"100%",background:n.btnBg,border:"none",borderBottom:`1px solid ${n.cellBorder}`,color:n.accent,cursor:"pointer",fontSize:11,fontWeight:700,fontFamily:n.font,padding:"10px 12px"},children:["Show all ",h.length," blocks"]})]})})}function lb({diff:e,diffReport:t,activeFilePath:n,diffPath:r,onScopeToFile:s,onClearScope:i,t:a}){const l=t!==null&&!t.identical,c=e.trim()!=="";return o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[o.jsxs("div",{style:{display:"flex",gap:6,fontSize:11},children:[o.jsx("button",{onClick:i,style:VE(r==null,a),children:"All"}),n&&o.jsx("button",{onClick:s,style:VE(r===n,a),children:"Active file"}),r&&o.jsx("span",{style:{color:a.textMuted,fontSize:10,alignSelf:"center",fontFamily:a.fontMono},children:r})]}),l&&o.jsx(cb,{report:t,t:a}),!l&&c&&o.jsx(Eb,{diff:e,t:a}),!l&&!c&&o.jsx("div",{style:{color:a.textMuted},children:t&&t.identical?"No semantic changes.":"No unstaged changes."})]})}function cb({report:e,t}){return o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.changes.map((n,r)=>o.jsx(db,{change:n,t},r))})}function db({change:e,t}){const{marker:n,color:r,label:s}=fb(e),i="fields"in e?e.fields:null;return o.jsxs("div",{style:{border:`1px solid ${t.editorBorder}`,borderRadius:6,padding:"6px 10px",background:t.editorBg},children:[o.jsxs("div",{style:{display:"flex",gap:8,alignItems:"baseline"},children:[o.jsx("span",{style:{color:r,fontFamily:t.fontMono,fontWeight:700,width:14},children:n}),o.jsx("span",{style:{color:t.textPrimary,fontSize:12,fontFamily:t.fontMono},children:s})]}),i&&i.length>0&&o.jsx("div",{style:{marginTop:4,display:"flex",flexDirection:"column",gap:2},children:i.map((a,l)=>o.jsx(ub,{field:a,t},l))})]})}function ub({field:e,t}){return o.jsxs("div",{style:{fontSize:11,fontFamily:t.fontMono,color:t.textPrimary,paddingLeft:22},children:[o.jsx("span",{style:{color:t.accent},children:e.path}),o.jsx("span",{style:{color:t.textMuted},children:": "}),o.jsx("span",{style:{color:t.error,textDecoration:"line-through"},children:$E(e.before)}),o.jsx("span",{style:{color:t.textMuted},children:" → "}),o.jsx("span",{style:{color:t.success},children:$E(e.after)})]})}function Eb({diff:e,t}){return o.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(`
|
|
510
|
+
`).map((n,r)=>o.jsx("div",{style:{color:pb(n,t)},children:n||" "},r))})}function fb(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 ${Wl(e.id,e.name)} [${e.cellType}]`};case"cell-removed":return{...n,label:`cell ${Wl(e.id,e.name)} [${e.cellType}]`};case"cell-changed":return{...r,label:`cell ${Wl(e.id,e.name)}`};case"notebook-changed":return{...r,label:"notebook"}}}function Wl(e,t){return t?`"${t}" (${e.slice(0,8)})`:e.slice(0,8)}function $E(e,t=60){if(e==null)return"∅";const n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}…`:n}function VE(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 pb(e,t){return e.startsWith("+++")||e.startsWith("---")?t.textMuted:e.startsWith("+")?t.success:e.startsWith("-")?t.error:e.startsWith("@@")?t.accent:t.textPrimary}const Tb=2e3,Sb={modified:{label:"Modified",color:e=>e.warning,Icon:t_},added:{label:"Added",color:e=>e.success,Icon:RR},deleted:{label:"Deleted",color:e=>e.error,Icon:a_},renamed:{label:"Renamed",color:e=>e.accent,Icon:_L},untracked:{label:"Untracked",color:e=>e.textMuted,Icon:o_}},zE=["modified","added","renamed","deleted","untracked"];function hb(e){const t=e.trim();return t==="??"?"untracked":t.startsWith("R")?"renamed":t.includes("D")?"deleted":t.includes("A")?"added":"modified"}function Rb(){var N;const{state:e}=Re(),t=ce[e.themeMode],[n,r]=p.useState("status"),[s,i]=p.useState(null),[a,l]=p.useState(null),[c,d]=p.useState(""),[u,E]=p.useState(null),[f,T]=p.useState(null),[A,R]=p.useState(!1),[S,h]=p.useState(!1),g=p.useCallback(async()=>{R(!0),h(!0);try{if(n==="status")i(await $.fetchGitStatus());else if(n==="log")l(await $.fetchGitLog(30));else{const x=await $.fetchGitDiff(f??void 0);d(x.diff),E(x.diffReport)}}finally{R(!1),window.setTimeout(()=>h(!1),400)}},[n,f]);p.useEffect(()=>{g()},[g]),p.useEffect(()=>{if(n!=="status")return;const x=window.setInterval(()=>{$.fetchGitStatus().then(_=>{i(C=>Ab(C,_)?C:_)})},Tb);return()=>window.clearInterval(x)},[n]);const m=((N=e.activeFile)==null?void 0:N.path)??null,I=o.jsxs("button",{onClick:()=>void g(),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:[o.jsx(IR,{size:12,strokeWidth:1.75,style:{animation:S?"dql-spin 0.6s linear":void 0}}),o.jsx("style",{children:"@keyframes dql-spin { to { transform: rotate(360deg); } }"})]}),O=o.jsxs(Ns,{children:[o.jsx(Yl,{t,active:n==="status",onClick:()=>r("status"),children:"Status"}),o.jsx(Yl,{t,active:n==="log",onClick:()=>r("log"),children:"History"}),o.jsx(Yl,{t,active:n==="diff",onClick:()=>r("diff"),children:"Diff"})]});return o.jsxs(Tn,{title:"Git",actions:I,toolbar:O,bodyPadding:12,children:[A&&!s&&!a&&o.jsx(En,{title:"Loading…"}),n==="status"&&s&&o.jsx(mb,{status:s,t}),n==="log"&&a&&o.jsx(xb,{log:a,t}),n==="diff"&&o.jsx(lb,{diff:c,diffReport:u,activeFilePath:m,diffPath:f,onScopeToFile:()=>T(m),onClearScope:()=>T(null),t})]})}function Ab(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(s=>`${s.path}\0${s.status}`).sort(),r=t.changes.map(s=>`${s.path}\0${s.status}`).sort();for(let s=0;s<n.length;s++)if(n[s]!==r[s])return!1;return!0}function mb({status:e,t}){const n=p.useMemo(()=>{const r={modified:[],added:[],deleted:[],renamed:[],untracked:[]};for(const s of e.changes)r[hb(s.status)].push(s);for(const s of zE)r[s].sort((i,a)=>i.path.localeCompare(a.path));return r},[e.changes]);return e.inRepo?o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[o.jsx(gb,{status:e,t}),e.changes.length===0?o.jsx(Ib,{t}):zE.map(r=>{const s=n[r];return s.length===0?null:o.jsx(Ob,{group:r,items:s,t},r)})]}):o.jsx(DR,{t})}function gb({status:e,t}){const n=e.ahead??0,r=e.behind??0;return o.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:[o.jsx(Oo,{size:16,strokeWidth:1.75,color:t.accent}),o.jsx("span",{style:{fontSize:13,fontWeight:600,color:t.textPrimary,fontFamily:t.fontMono},children:e.branch??"detached"}),o.jsx("div",{style:{flex:1}}),n>0&&o.jsxs("span",{title:`${n} commit(s) ahead of upstream`,style:$l(t.success,t),children:[o.jsx(TR,{size:11,strokeWidth:2})," ",n]}),r>0&&o.jsxs("span",{title:`${r} commit(s) behind upstream`,style:$l(t.warning,t),children:[o.jsx(pR,{size:11,strokeWidth:2})," ",r]}),n===0&&r===0&&o.jsx("span",{style:{...$l(t.textMuted,t),opacity:.7},children:"up to date"})]})}function Ib({t:e}){return o.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:[o.jsx(ZL,{size:14,strokeWidth:1.75,color:e.success}),"Working tree clean"]})}function DR({t:e}){return o.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 Ob({group:e,items:t,t:n}){const r=Sb[e],s=r.color(n),i=r.Icon;return o.jsxs("div",{children:[o.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:[o.jsx(i,{size:11,strokeWidth:1.75}),o.jsx("span",{children:r.label}),o.jsx("span",{style:{marginLeft:2,padding:"0 5px",borderRadius:8,background:`${s}1a`,color:s,fontWeight:700,fontSize:9,letterSpacing:"0.04em"},children:t.length})]}),o.jsx("div",{style:{display:"flex",flexDirection:"column",background:n.cellBg,border:`1px solid ${n.cellBorder}`,borderRadius:7,overflow:"hidden"},children:t.map((a,l)=>o.jsx(Nb,{change:a,t:n,color:s,divider:l<t.length-1},a.path))})]})}function Nb({change:e,t,color:n,divider:r}){const s=e.status.trim()||"??";return o.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:[o.jsx("span",{style:{width:22,textAlign:"center",flexShrink:0,color:n,fontWeight:700,fontSize:10,letterSpacing:"0.02em"},children:s}),o.jsx("span",{style:{color:t.textPrimary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:e.path})]})}function xb({log:e,t}){return e.inRepo?e.commits.length===0?o.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"}):o.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)=>o.jsxs("div",{style:{display:"flex",gap:10,padding:"8px 12px",borderBottom:r<e.commits.length-1?`1px solid ${t.cellBorder}`:"none"},children:[o.jsx(mR,{size:13,strokeWidth:1.75,color:t.accent,style:{flexShrink:0,marginTop:2}}),o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsx("div",{style:{color:t.textPrimary,fontSize:12,fontFamily:t.font,fontWeight:500,lineHeight:1.35,wordBreak:"break-word"},children:n.subject}),o.jsxs("div",{style:{color:t.textMuted,fontSize:10,marginTop:3,display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[o.jsx("span",{style:{fontFamily:t.fontMono,color:t.accent},children:n.hash.slice(0,7)}),o.jsx("span",{children:"·"}),o.jsx("span",{style:{fontFamily:t.font},children:n.author}),o.jsx("span",{children:"·"}),o.jsx("span",{style:{fontFamily:t.fontMono},children:n.date})]})]})]},n.hash))}):o.jsx(DR,{t})}function Yl({active:e,onClick:t,children:n,t:r}){return o.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 $l(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 yb(e){const{state:t,dispatch:n}=Re(),r=ce[t.themeMode],[s,i]=p.useState([]),[a,l]=p.useState(!0),[c,d]=p.useState(""),[u,E]=p.useState(""),[f,T]=p.useState(new Set),A=()=>{l(!0),$.listApps().then(N=>i(N)).finally(()=>l(!1))};p.useEffect(()=>{A()},[]);const R=[...new Set(s.map(N=>N.domain))].sort(),S=s.filter(N=>{const x=c.toLowerCase();return!(x&&!N.name.toLowerCase().includes(x)&&!(N.description??"").toLowerCase().includes(x)||u&&N.domain!==u)}),h=N=>{T(x=>{const _=new Set(x);return _.has(N)?_.delete(N):_.add(N),_})},g=(N,x)=>{n({type:"OPEN_APP",appId:N.id,dashboardId:x})},m={background:r.inputBg,border:`1px solid ${r.inputBorder}`,borderRadius:4,color:r.textPrimary,fontSize:11,fontFamily:r.font,padding:"4px 6px",outline:"none"},I=o.jsx("button",{onClick:A,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"}),O=o.jsxs(Ns,{children:[o.jsx("input",{value:c,onChange:N=>d(N.target.value),placeholder:"Search apps...",style:{...m,flex:1,minWidth:100}}),o.jsxs("select",{value:u,onChange:N=>E(N.target.value),style:m,children:[o.jsx("option",{value:"",children:"All domains"}),R.map(N=>o.jsx("option",{value:N,children:N},N))]})]});return o.jsx(Tn,{title:"Apps",status:o.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font},children:S.length}),actions:I,toolbar:O,bodyPadding:0,children:a?o.jsx(En,{title:"Loading apps…"}):S.length===0?s.length===0?o.jsx(En,{title:"No apps yet",description:o.jsxs(o.Fragment,{children:["Create one from the CLI:",o.jsx("br",{}),o.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>"})]})}):o.jsx(En,{title:"No matches",description:"No apps match your filters."}):S.map(N=>{const x=f.has(N.id);return o.jsxs("div",{style:{borderBottom:`1px solid ${r.cellBorder}`},children:[o.jsxs("button",{onClick:()=>h(N.id),style:{display:"block",width:"100%",textAlign:"left",background:"transparent",border:"none",cursor:"pointer",padding:"10px 12px",transition:"background 0.1s"},onMouseEnter:_=>{_.currentTarget.style.background=`${r.accent}0a`},onMouseLeave:_=>{_.currentTarget.style.background="transparent"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[o.jsx("span",{style:{fontSize:10,color:r.textMuted,fontFamily:r.font,width:10},children:x?"▾":"▸"}),o.jsx("span",{style:{fontSize:12,fontWeight:600,color:r.textPrimary,fontFamily:r.font},children:N.name}),o.jsx(cu,{tone:"accent",children:N.domain})]}),N.description&&o.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,lineHeight:1.3,marginBottom:4,marginLeft:16},children:N.description}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:10,color:r.textMuted,fontFamily:r.font,marginLeft:16},children:[N.owners[0]&&o.jsxs("span",{children:["by ",N.owners[0]]}),o.jsxs("span",{children:[N.dashboards.length," dashboard",N.dashboards.length===1?"":"s"]}),o.jsxs("span",{children:[N.members," member",N.members===1?"":"s"]})]})]}),x&&o.jsxs("div",{style:{padding:"4px 0 10px 28px",background:`${r.accent}04`},children:[N.dashboards.length===0&&o.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,padding:"4px 0"},children:"(empty app scaffold)"}),N.dashboards.map(_=>o.jsx("button",{onClick:()=>g(N,_.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:_.title},_.id))]})]},N.id)})})}const Cb={files:"Explorer",schema:"Schema",block_library:"Block Library",lineage:"Lineage",connection:"Connection",reference:"Quick Reference",git:"Git",apps:"Apps"};function Lb({onOpenFile:e}){const{state:t,dispatch:n}=Re(),r=ce[t.themeMode],[s,i]=p.useState(!1),[a,l]=p.useState(240),[c,d]=p.useState(!1),u=p.useRef(a),E=t.sidebarPanel,f=T=>{T.preventDefault();const A=T.clientX,R=u.current;d(!0);const S=g=>{const m=Math.min(560,Math.max(180,R+(g.clientX-A)));u.current=m,l(m)},h=()=>{d(!1),window.removeEventListener("mousemove",S),window.removeEventListener("mouseup",h)};window.addEventListener("mousemove",S),window.addEventListener("mouseup",h)};return o.jsxs("div",{style:{width:a,flexShrink:0,background:r.sidebarBg,borderRight:`1px solid ${r.headerBorder}`,display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:[o.jsxs("div",{style:{height:36,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 10px 0 14px",borderBottom:`1px solid ${r.headerBorder}`},children:[o.jsx("span",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.06em",textTransform:"uppercase",color:r.textSecondary,fontFamily:r.font},children:Cb[E??""]??""}),o.jsx("button",{title:"Collapse sidebar",onClick:()=>n({type:"TOGGLE_SIDEBAR"}),onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{background:"transparent",border:"none",cursor:"pointer",color:s?r.textPrimary:r.textMuted,padding:"2px 4px",borderRadius:4,fontSize:14,lineHeight:1,transition:"color 0.15s",display:"flex",alignItems:"center"},children:"‹"})]}),o.jsxs("div",{style:{flex:1,overflow:"hidden",display:"flex",flexDirection:"column"},children:[E==="files"&&o.jsx(m0,{onOpenFile:e}),E==="schema"&&o.jsx(x0,{}),E==="block_library"&&o.jsx(ab,{}),E==="lineage"&&o.jsx(sb,{}),E==="connection"&&o.jsx(_R,{}),E==="reference"&&o.jsx(bR,{themeMode:t.themeMode}),E==="git"&&o.jsx(Rb,{}),E==="apps"&&o.jsx(yb,{onOpenFile:e})]}),o.jsx("div",{onMouseDown:f,title:"Drag to resize",style:{position:"absolute",top:0,right:-3,width:6,height:"100%",cursor:"col-resize",background:c?r.accent:"transparent",zIndex:10,transition:c?"none":"background 0.15s"},onMouseEnter:T=>{c||(T.currentTarget.style.background=`${r.accent}40`)},onMouseLeave:T=>{c||(T.currentTarget.style.background="transparent")}})]})}var XE;(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.BlockParams="BlockParams",e.BlockVisualization="BlockVisualization",e.BlockTest="BlockTest",e.Digest="Digest",e.Narrative="Narrative"})(XE||(XE={}));var KE;(function(e){e.Error="error",e.Warning="warning",e.Info="info"})(KE||(KE={}));var Ie;(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.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.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"})(Ie||(Ie={}));Ie.DashboardKeyword,Ie.WorkbookKeyword,Ie.PageKeyword,Ie.LetKeyword,Ie.ParamKeyword,Ie.ChartKeyword,Ie.FilterKeyword,Ie.BooleanLiteral,Ie.BooleanLiteral,Ie.IntervalKeyword,Ie.ImportKeyword,Ie.FromKeyword,Ie.UseKeyword,Ie.LayoutKeyword,Ie.RowKeyword,Ie.BlockKeyword,Ie.DomainKeyword,Ie.TypeKeyword,Ie.DescriptionKeyword,Ie.TagsKeyword,Ie.OwnerKeyword,Ie.QueryKeyword,Ie.VisualizationKeyword,Ie.TestsKeyword,Ie.ParamsKeyword,Ie.AssertKeyword,Ie.VarKeyword,Ie.DefaultKeyword,Ie.InKeyword,Ie.MetricKeyword,Ie.MetricsKeyword,Ie.DigestKeyword,Ie.NarrativeKeyword;const MR=1;function _b(e,t={}){const n=t.version??MR,r=JSON.parse(e),{dqlnbVersion:s,...i}=r,a={dqlnbVersion:n,...i};return JSON.stringify(a,bb(),2)+`
|
|
511
|
+
`}function bb(){return function(t,n){if(n===null||typeof n!="object"||Array.isArray(n))return n;const r=n,s=Object.keys(r);s.sort((a,l)=>{const c=qE[a],d=qE[l];return c!==void 0&&d!==void 0?c-d:c!==void 0?-1:d!==void 0?1:a<l?-1:a>l?1:0});const i={};for(const a of s)i[a]=r[a];return i}}const qE={dqlnbVersion:0,version:1,title:2,metadata:3,cells:4,id:10,type:11,name:12,content:13};function vb(e){try{const t=e.match(/workbook\s+"([^"]+)"/i),n=t?t[1]:"Untitled Workbook",r=[],s=/page\s+"([^"]+)"\s*\{([\s\S]*?)\}/gi;let i;for(;(i=s.exec(e))!==null;){const a=i[1],l=i[2].trim();r.push({id:Pt(),type:"markdown",content:`# ${a}`,status:"idle"}),l&&r.push({id:Pt(),type:"dql",name:a.toLowerCase().replace(/\s+/g,"_"),content:l,status:"idle"})}return r.length===0&&r.push({id:Pt(),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:Pt(),type:"dql",content:e.trim(),status:"idle"}]}}}function Db(e){var t;try{const n=JSON.parse(e),r=n.title||((t=n.metadata)==null?void 0:t.title)||"Untitled",s=(n.cells||[]).map(l=>({id:l.id||Pt(),type:l.type||"sql",content:l.content??l.source??"",name:l.name||l.title,status:"idle",...l.paramConfig?{paramConfig:l.paramConfig}:{},...l.paramValue!==void 0?{paramValue:l.paramValue}:{},...l.chartConfig?{chartConfig:l.chartConfig}:{},...l.filterConfig?{filterConfig:l.filterConfig}:{},...l.pivotConfig?{pivotConfig:l.pivotConfig}:{},...l.singleValueConfig?{singleValueConfig:l.singleValueConfig}:{},...l.tableConfig?{tableConfig:l.tableConfig}:{},...l.upstream?{upstream:l.upstream}:{},...l.blockBinding?{blockBinding:l.blockBinding}:{}})),{title:i,...a}=n.metadata??{};return{title:r,cells:s,metadata:a}}catch(n){return console.warn("parse-workbook: falling back after error",n),{title:"Untitled",cells:[{id:Pt(),type:"sql",content:e,status:"idle"}]}}}function Mb(e,t,n){const r={dqlnbVersion:MR,version:1,title:e,metadata:{...n,modifiedAt:new Date().toISOString(),...n!=null&&n.createdAt?{}:{createdAt:new Date().toISOString()}},cells:t.map(s=>({id:s.id,type:s.type,content:s.content,...s.name?{name:s.name}:{},...s.paramConfig?{paramConfig:s.paramConfig}:{},...s.paramValue!==void 0?{paramValue:s.paramValue}:{},...s.chartConfig?{chartConfig:s.chartConfig}:{},...s.filterConfig?{filterConfig:s.filterConfig}:{},...s.pivotConfig?{pivotConfig:s.pivotConfig}:{},...s.singleValueConfig?{singleValueConfig:s.singleValueConfig}:{},...s.tableConfig?{tableConfig:s.tableConfig}:{},...s.upstream?{upstream:s.upstream}:{},...s.blockBinding?{blockBinding:s.blockBinding}:{}}))};return _b(JSON.stringify(r))}function PR(e,t){return e.endsWith(".dql")?vb(t):Db(t)}const wR=/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g;function Pb(e){const t=new Set;for(const n of e.matchAll(wR))t.add(n[1]);return[...t]}function wb(e,t){if(!t.columns.length||!t.rows.length)return`${e} AS (SELECT 1 WHERE 1=0)`;const n=t.columns,s=t.rows.slice(0,5e3).map(a=>`(${n.map(c=>{const d=a[c];return d==null?"NULL":typeof d=="number"?String(d):typeof d=="boolean"?d?"TRUE":"FALSE":`'${String(d).replace(/'/g,"''")}'`}).join(", ")})`).join(`,
|
|
512
|
+
`),i=n.map(a=>`"${a.replace(/"/g,'""')}"`).join(", ");return`${e} AS (
|
|
513
|
+
SELECT * FROM (VALUES
|
|
514
|
+
${s}
|
|
515
|
+
) AS _t(${i})
|
|
516
|
+
)`}function Ub(e,t){if(t==="number"){const n=Number(e);return isNaN(n)?`'${e.replace(/'/g,"''")}'`:String(n)}return`'${e.replace(/'/g,"''")}'`}function Bb(){const{state:e}=Re();return{substituteVariables:p.useCallback(n=>{var d;const r=[...n.matchAll(wR)];if(r.length===0)return{sql:n,substituted:[]};const s=[],i=[];let a=n;const l=new Map,c=new Map;for(const u of e.cells){const E=(d=u.name)==null?void 0:d.trim();E&&(u.type==="param"?l.set(E,u):u.status==="success"&&u.result&&c.set(E,u.result))}for(const u of r){const E=u[1];if(l.has(E)){const f=l.get(E),T=f.paramConfig,A=f.paramValue??(T==null?void 0:T.defaultValue)??"",R=(T==null?void 0:T.paramType)??"text",S=Ub(A,R);a=a.replace(u[0],S),s.push(E)}else c.has(E)&&(i.push(wb(E,c.get(E))),a=a.replace(u[0],`"${E}"`),s.push(E))}if(i.length===0&&s.length===0)return{sql:n,substituted:[]};if(i.length>0){const u=a.trimStart();/^WITH\s+/i.test(u)?a=a.replace(/^(\s*WITH\s+)/i,`$1${i.join(`,
|
|
517
|
+
`)},
|
|
518
|
+
`):a=`WITH ${i.join(`,
|
|
519
|
+
`)}
|
|
520
|
+
${a}`}return{sql:a,substituted:s}},[e.cells])}}function jb(e){var i;const t=e.match(/visualization\s*\{([^}]+)\}/is);if(!t)return;const n=t[1],r=a=>{var l;return(l=n.match(new RegExp(`\\b${a}\\s*=\\s*["']?([\\w-]+)["']?`,"i")))==null?void 0:l[1]},s=r("chart");if(s)return{chart:s,x:r("x"),y:r("y"),color:r("color"),title:(i=n.match(/\btitle\s*=\s*"([^"]+)"/i))==null?void 0:i[1]}}function Eu(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 s=t.match(/\b(SELECT|WITH|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|SHOW|DESCRIBE|EXPLAIN)\b([\s\S]*)/i);if(s){let i=s[0];const a=i.search(/\b(visualization|tests|block)\s*\{/i);return a>0&&(i=i.slice(0,a)),i=kb(i),i.trim()||null}return null}function kb(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 s=n+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(s<e.length&&/[a-zA-Z_]/.test(e[s])){for(;s<e.length&&/[a-zA-Z0-9_]/.test(e[s]);)s++;let i=s;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 Fb(e){const t=Nr(e);return t?{name:t.name,domain:t.domain,owner:t.owner,description:t.description,blockType:t.blockType,status:t.status,tags:t.tags}:null}function Gr(e,t,n){const r=Nr(e);if(!r){const i=n.replace(/"/g,'\\"'),a=new RegExp(`(\\b${t}\\s*=\\s*)"[^"]*"`,"i");return a.test(e)?e.replace(a,`$1"${i}"`):fu(e,` ${t} = "${i}"`)}const s={...r};return t==="domain"&&(s.domain=n),t==="owner"&&(s.owner=n),t==="description"&&(s.description=n),t==="type"&&(s.blockType=n),t==="status"&&(s.status=n),No(s)}function UR(e,t){const n=Nr(e);if(!n){const r=t.replace(/"/g,'\\"');return/^\s*block\s+"/i.test(e)?e.replace(/^(\s*block\s+)"[^"]+"/i,`$1"${r}"`):e}return No({...n,name:t})}function Gb(e,t){const n=Nr(e);if(!n){const r=t.map(i=>`"${i.replace(/"/g,'\\"')}"`).join(", "),s=/(\btags\s*=\s*)\[[^\]]*\]/i;return s.test(e)?e.replace(s,`$1[${r}]`):fu(e,` tags = [${r}]`)}return No({...n,tags:t})}function sd(e,t){const n=Nr(e),r=$b(t);return n?No({...n,visualization:r}):/visualization\s*\{[\s\S]*?\n\s*\}/i.test(e)?e.replace(/visualization\s*\{[\s\S]*?\n\s*\}/i,r):fu(e,` ${r.replace(/\n/g,`
|
|
521
|
+
`)}`,!0)}function Hb(e,t){return e==="metric"?`@metric(${t})`:`@dim(${t})`}function Wb(e,t){const n=Nr(e);if(!n||n.blockType!=="semantic")return e;const r={...n,metrics:[...n.metrics],dimensions:[...n.dimensions]};if(t.kind==="metric"){const s=new Set;r.metric&&s.add(r.metric);for(const a of r.metrics)s.add(a);s.add(t.name);const i=Array.from(s);r.metric=i.length===1?i[0]:"",r.metrics=i.length>1?i:[]}else r.dimensions.includes(t.name)||(r.dimensions=[...r.dimensions,t.name]);return No(r)}function Yb(e,t){const n=Nr(e);if(!n||n.blockType!=="custom")return`${e.trimEnd()}
|
|
522
|
+
${t}
|
|
523
|
+
`;const r=n.query.trimEnd(),s=r?`${r}
|
|
524
|
+
${t}`:t;return No({...n,query:s})}function Nr(e){var i,a;if(!/^\s*block\s+"/i.test(e.trim()))return null;const t=l=>{var c;return((c=e.match(new RegExp(`\\b${l}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:c[1])??""},n=((i=e.match(/^\s*block\s+"([^"]+)"/i))==null?void 0:i[1])??"",r=e.match(/\btags\s*=\s*\[([^\]]*)\]/i),s=e.match(/query\s*=\s*"""([\s\S]*?)"""/i);return{name:n,domain:t("domain"),owner:t("owner"),description:t("description"),status:t("status")||"draft",blockType:(t("type")||"custom").toLowerCase()==="semantic"?"semantic":"custom",tags:r?(r[1].match(/"([^"]*)"/g)??[]).map(l=>l.slice(1,-1)):[],metric:t("metric"),metrics:JE(e,"metrics"),dimensions:JE(e,"dimensions"),timeDimension:t("time_dimension"),granularity:t("granularity"),query:((a=s==null?void 0:s[1])==null?void 0:a.trim())??"",visualization:QE(e,"visualization"),tests:QE(e,"tests")}}function JE(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 QE(e,t){const n=new RegExp(`\\b${t}\\s*\\{`,"i").exec(e);if(!n||n.index==null)return"";let r=0,s=-1;for(let i=n.index;i<e.length;i++){const a=e[i];if(a==="{")r===0&&(s=i),r++;else if(a==="}"&&(r--,r===0&&s>=0))return e.slice(n.index,i+1).trim()}return""}function No(e){const t=[`block "${mt(e.name||"New Block")}" {`,` status = "${mt(e.status||"draft")}"`,` domain = "${mt(e.domain||"uncategorized")}"`,` type = "${e.blockType}"`,` description = "${mt(e.description)}"`,` owner = "${mt(e.owner)}"`,` tags = [${e.tags.map(n=>`"${mt(n)}"`).join(", ")}]`];if(e.blockType==="semantic"){const n=e.metrics.length>0?Array.from(new Set(e.metrics)):e.metric?[e.metric]:[];n.length===1?t.push(` metric = "${mt(n[0])}"`):n.length>1&&t.push(` metrics = [${n.map(r=>`"${mt(r)}"`).join(", ")}]`),e.dimensions.length>0&&t.push(` dimensions = [${Array.from(new Set(e.dimensions)).map(r=>`"${mt(r)}"`).join(", ")}]`),e.timeDimension&&t.push(` time_dimension = "${mt(e.timeDimension)}"`),e.granularity&&t.push(` granularity = "${mt(e.granularity)}"`)}return e.blockType==="custom"&&(t.push(""),t.push(' query = """'),t.push(...Vb(e.query.trim(),4)),t.push(' """')),e.visualization&&(t.push(""),t.push(...ZE(e.visualization,2))),e.tests&&(t.push(""),t.push(...ZE(e.tests,2))),t.push("}"),t.join(`
|
|
525
|
+
`)+`
|
|
526
|
+
`}function $b(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 = "${mt(e.title)}"`),t.push("}"),t.join(`
|
|
527
|
+
`)}function Vb(e,t){const n=" ".repeat(t);return(e?e.split(`
|
|
528
|
+
`):[""]).map(s=>`${n}${s}`)}function ZE(e,t){const n=" ".repeat(t);return e.split(`
|
|
529
|
+
`).map(r=>`${n}${r.trimEnd()}`)}function mt(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function fu(e,t,n=!1){const r=e.trimEnd();if(!/^\s*block\s+"/i.test(r))return`${r}
|
|
530
|
+
${t}
|
|
531
|
+
`;const s=n?`
|
|
532
|
+
|
|
533
|
+
${t}
|
|
534
|
+
`:`
|
|
535
|
+
${t}`;return r.replace(/\n\}\s*$/,`${s}
|
|
536
|
+
}`)}const In=new Map;function zb(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?Eu(t):null}function Xb(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 Ha(){const{state:e,dispatch:t}=Re(),{substituteVariables:n}=Bb(),r=p.useCallback(async l=>{const c=e.cells.find(A=>A.id===l);if(!c)return;if(c.type==="dql"){const A=Date.now(),R=In.get(l);R&&R.abort();const S=new AbortController;In.set(l,S),t({type:"UPDATE_CELL",id:l,updates:{status:"running",error:void 0,result:void 0,fromSnapshot:!1}});try{const h=await $.executeNotebookCell(c,S.signal);if(!h.result)throw new Error("DQL cell produced no executable result.");const g=Date.now()-A,m=(c.executionCount??0)+1,I=Xb(h.chartConfig)??jb(c.content);t({type:"UPDATE_CELL",id:l,updates:{status:"success",result:{...h.result,executionTime:h.result.executionTime??g,rowCount:h.result.rowCount??h.result.rows.length},...I?{chartConfig:I}:{},executionCount:m}}),t({type:"APPEND_QUERY_LOG",entry:{id:Pt(),cellName:h.blockName??c.name??c.id,rows:h.result.rowCount??h.result.rows.length,time:h.result.executionTime??g,ts:new Date}}),setTimeout(()=>{t({type:"UPDATE_CELL",id:l,updates:{status:"idle"}})},2e3)}catch(h){if(S.signal.aborted){t({type:"UPDATE_CELL",id:l,updates:{status:"idle",error:void 0}});return}const g=Date.now()-A,m=h instanceof Error?h.message:String(h);t({type:"UPDATE_CELL",id:l,updates:{status:"error",error:m,executionCount:(c.executionCount??0)+1}}),t({type:"APPEND_QUERY_LOG",entry:{id:Pt(),cellName:c.name??c.id,rows:0,time:g,ts:new Date,error:m}})}finally{In.delete(l)}return}const d=zb(c);if(!d)return;const{sql:u}=n(d),E=Date.now(),f=In.get(l);f&&f.abort();const T=new AbortController;In.set(l,T),t({type:"UPDATE_CELL",id:l,updates:{status:"running",error:void 0,result:void 0,fromSnapshot:!1}});try{const A=await $.executeQuery(u,T.signal),R=Date.now()-E,S=(c.executionCount??0)+1;t({type:"UPDATE_CELL",id:l,updates:{status:"success",result:{...A,executionTime:A.executionTime??R,rowCount:A.rowCount??A.rows.length},executionCount:S}}),t({type:"APPEND_QUERY_LOG",entry:{id:Pt(),cellName:c.name??c.id,rows:A.rowCount??A.rows.length,time:A.executionTime??R,ts:new Date}}),setTimeout(()=>{t({type:"UPDATE_CELL",id:l,updates:{status:"idle"}})},2e3)}catch(A){if(T.signal.aborted){t({type:"UPDATE_CELL",id:l,updates:{status:"idle",error:void 0}});return}const R=Date.now()-E,S=A instanceof Error?A.message:String(A);t({type:"UPDATE_CELL",id:l,updates:{status:"error",error:S,executionCount:(c.executionCount??0)+1}}),t({type:"APPEND_QUERY_LOG",entry:{id:Pt(),cellName:c.name??c.id,rows:0,time:R,ts:new Date,error:S}})}finally{In.delete(l)}},[e.cells,t]),s=p.useCallback(async()=>{for(const l of e.cells)l.type!=="markdown"&&await r(l.id)},[e.cells,r]),i=p.useCallback(async l=>{if(!l)return;const c=`{{${l}}}`;for(const d of e.cells)d.type==="markdown"||d.type==="param"||d.content.includes(c)&&await r(d.id)},[e.cells,r]),a=p.useCallback(l=>{const c=In.get(l);c&&(c.abort(),In.delete(l)),t({type:"UPDATE_CELL",id:l,updates:{status:"idle"}})},[t]);return{executeCell:r,executeAll:s,executeDependents:i,cancelCell:a}}function rt(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Kb(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 qb(e){const t=e.split(`
|
|
537
|
+
`),n=[];let r=!1,s=!1;for(const i of t){const a=i;if(a.startsWith("```")){s&&(n.push("</ul>"),s=!1),r?(n.push("</code></pre>"),r=!1):(n.push("<pre><code>"),r=!0);continue}if(r){n.push(rt(a));continue}if(a.startsWith("### ")){s&&(n.push("</ul>"),s=!1),n.push(`<h3>${rt(a.slice(4))}</h3>`);continue}if(a.startsWith("## ")){s&&(n.push("</ul>"),s=!1),n.push(`<h2>${rt(a.slice(3))}</h2>`);continue}if(a.startsWith("# ")){s&&(n.push("</ul>"),s=!1),n.push(`<h1>${rt(a.slice(2))}</h1>`);continue}if(a.startsWith("> ")){s&&(n.push("</ul>"),s=!1),n.push(`<blockquote><p>${rt(a.slice(2))}</p></blockquote>`);continue}if(a.startsWith("- ")||a.startsWith("* ")){s||(n.push("<ul>"),s=!0),n.push(`<li>${ef(a.slice(2))}</li>`);continue}if(s&&(n.push("</ul>"),s=!1),a.trim()===""){n.push("<br>");continue}n.push(`<p>${ef(a)}</p>`)}return s&&n.push("</ul>"),r&&n.push("</code></pre>"),n.join(`
|
|
538
|
+
`)}function ef(e){return rt(e).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/`(.+?)`/g,"<code>$1</code>")}function Jb(e){const{columns:t,rows:n}=e,r=n.slice(0,200),s=n.length>200,i=t.map(l=>`<th>${rt(l)}</th>`).join(""),a=r.map(l=>`<tr>${t.map(d=>{const u=l[d],E=typeof u=="number",f=u==null?"—":String(u);return`<td${E?' class="num"':""}>${rt(f)}</td>`}).join("")}</tr>`).join("");return`
|
|
539
|
+
<div class="table-wrap">
|
|
540
|
+
<table>
|
|
541
|
+
<thead><tr>${i}</tr></thead>
|
|
542
|
+
<tbody>${a}</tbody>
|
|
543
|
+
</table>
|
|
544
|
+
${s?`<p class="truncated">Showing first 200 of ${n.length.toLocaleString()} rows</p>`:""}
|
|
545
|
+
</div>`}function Qb(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"),s=t.find(i=>i!==r);return!r||!s?null:{labelCol:s,valueCol:r}}function Zb(e){const t=Qb(e);if(!t)return null;const n=e.rows.slice(0,20).map(u=>({label:String(u[t.labelCol]??""),value:Number(u[t.valueCol]??0)})),r=Math.max(...n.map(u=>u.value),1),s=28,i=6,a=140,l=440,c=n.length*(s+i)+40,d=n.map((u,E)=>{const f=E*(s+i)+20,T=Math.max(u.value/r*l,2);return`
|
|
546
|
+
<text x="${a-6}" y="${f+s/2+4}" text-anchor="end" font-size="11" fill="#8b949e">${rt(u.label.slice(0,20))}</text>
|
|
547
|
+
<rect x="${a}" y="${f}" width="${T}" height="${s}" rx="3" fill="#388bfd" />
|
|
548
|
+
<text x="${a+T+5}" y="${f+s/2+4}" font-size="11" fill="#e6edf3">${Kb(u.value)}</text>`}).join("");return`<svg xmlns="http://www.w3.org/2000/svg" width="${a+l+80}" height="${c}" style="max-width:100%">${d}</svg>`}function e1(e,t){const n=t.map(r=>{if(r.type==="markdown")return`<section class="cell md-cell">${qb(r.content)}</section>`;const s=r.name?`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span><span class="cell-name">${rt(r.name)}</span></div>`:`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span></div>`,i=`<pre class="cell-code"><code>${rt(r.content)}</code></pre>`;let a="";if(r.result&&r.result.rows.length>0){const l=Zb(r.result),c=Jb(r.result);a=`<div class="cell-output">${`<div class="output-meta">${r.result.rows.length.toLocaleString()} rows${r.result.executionTime?` · ${r.result.executionTime}ms`:""}</div>`}${l??""}${l?"":c}</div>`}else r.error&&(a=`<div class="cell-error">⚠ ${rt(r.error)}</div>`);return`<section class="cell sql-cell">${s}${i}${a}</section>`}).join(`
|
|
549
|
+
`);return`<!DOCTYPE html>
|
|
550
|
+
<html lang="en">
|
|
551
|
+
<head>
|
|
552
|
+
<meta charset="UTF-8">
|
|
553
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
554
|
+
<title>${rt(e)}</title>
|
|
555
|
+
<style>
|
|
556
|
+
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
|
557
|
+
body {
|
|
558
|
+
font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
559
|
+
background: #0d1117; color: #e6edf3;
|
|
560
|
+
line-height: 1.6; padding: 0;
|
|
561
|
+
}
|
|
562
|
+
.page-header {
|
|
563
|
+
background: #161b22; border-bottom: 1px solid #21262d;
|
|
564
|
+
padding: 16px 32px; display: flex; align-items: center; gap: 12px;
|
|
565
|
+
}
|
|
566
|
+
.logo {
|
|
567
|
+
width: 28px; height: 28px; border-radius: 6px;
|
|
568
|
+
background: linear-gradient(135deg, #388bfd, #1f6feb);
|
|
569
|
+
display: flex; align-items: center; justify-content: center;
|
|
570
|
+
font-size: 10px; font-weight: 700; color: #fff;
|
|
571
|
+
font-family: monospace; letter-spacing: -0.5px; flex-shrink: 0;
|
|
572
|
+
}
|
|
573
|
+
.page-title { font-size: 18px; font-weight: 600; color: #e6edf3; }
|
|
574
|
+
.page-meta { font-size: 12px; color: #8b949e; margin-left: auto; }
|
|
575
|
+
.content { max-width: 900px; margin: 0 auto; padding: 32px 24px; display: flex; flex-direction: column; gap: 24px; }
|
|
576
|
+
.cell { border-radius: 8px; overflow: hidden; }
|
|
577
|
+
.md-cell { padding: 4px 0; }
|
|
578
|
+
.md-cell h1 { font-size: 26px; font-weight: 700; color: #e6edf3; margin: 0 0 12px; }
|
|
579
|
+
.md-cell h2 { font-size: 20px; font-weight: 600; color: #e6edf3; margin: 20px 0 10px; }
|
|
580
|
+
.md-cell h3 { font-size: 16px; font-weight: 600; color: #e6edf3; margin: 16px 0 8px; }
|
|
581
|
+
.md-cell p { color: #c9d1d9; margin-bottom: 8px; }
|
|
582
|
+
.md-cell ul { padding-left: 20px; color: #c9d1d9; margin-bottom: 8px; }
|
|
583
|
+
.md-cell code { background: #21262d; padding: 2px 6px; border-radius: 4px; font-family: monospace; font-size: 13px; }
|
|
584
|
+
.md-cell pre { background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 14px; overflow-x: auto; margin-bottom: 8px; }
|
|
585
|
+
.md-cell pre code { background: none; padding: 0; }
|
|
586
|
+
.md-cell blockquote { border-left: 3px solid #388bfd; padding-left: 14px; color: #8b949e; }
|
|
587
|
+
.sql-cell { background: #161b22; border: 1px solid #30363d; }
|
|
588
|
+
.cell-header { display: flex; align-items: center; gap: 8px; padding: 8px 14px; border-bottom: 1px solid #21262d; background: #1c2128; }
|
|
589
|
+
.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; }
|
|
590
|
+
.cell-name { font-size: 12px; color: #388bfd; font-family: monospace; }
|
|
591
|
+
.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; }
|
|
592
|
+
.cell-output { padding: 14px; }
|
|
593
|
+
.output-meta { font-size: 11px; color: #8b949e; margin-bottom: 10px; }
|
|
594
|
+
.table-wrap { overflow-x: auto; }
|
|
595
|
+
table { width: 100%; border-collapse: collapse; font-size: 12px; }
|
|
596
|
+
th { background: #1c2128; color: #8b949e; font-weight: 600; text-align: left; padding: 7px 12px; border-bottom: 1px solid #30363d; white-space: nowrap; }
|
|
597
|
+
td { padding: 6px 12px; border-bottom: 1px solid #21262d; color: #e6edf3; }
|
|
598
|
+
td.num { text-align: right; font-family: monospace; }
|
|
599
|
+
tr:last-child td { border-bottom: none; }
|
|
600
|
+
.truncated { font-size: 11px; color: #8b949e; margin-top: 8px; }
|
|
601
|
+
.cell-error { padding: 12px 14px; background: #3d1a1a; border-top: 1px solid #f85149; color: #f85149; font-size: 13px; }
|
|
602
|
+
.exported-by { text-align: center; color: #484f58; font-size: 11px; padding: 40px 0 24px; }
|
|
603
|
+
</style>
|
|
604
|
+
</head>
|
|
605
|
+
<body>
|
|
606
|
+
<div class="page-header">
|
|
607
|
+
<div class="logo">DQL</div>
|
|
608
|
+
<span class="page-title">${rt(e)}</span>
|
|
609
|
+
<span class="page-meta">Exported ${new Date().toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}</span>
|
|
610
|
+
</div>
|
|
611
|
+
<div class="content">
|
|
612
|
+
${n}
|
|
613
|
+
</div>
|
|
614
|
+
<p class="exported-by">Built with DQL Notebook</p>
|
|
615
|
+
</body>
|
|
616
|
+
</html>`}function t1(e,t){const n=e1(e,t),r=new Blob([n],{type:"text/html;charset=utf-8"}),s=URL.createObjectURL(r),i=document.createElement("a");i.href=s,i.download=`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}-dashboard.html`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(s)}function n1({t:e}){return o.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:o.jsx("span",{style:{color:"#ffffff",fontSize:10,fontWeight:700,fontFamily:e.fontMono,letterSpacing:"-0.5px"},children:"DQL"})})}function r1(){const{state:e,dispatch:t}=Re(),n=ce[e.themeMode],{executeAll:r}=Ha(),[s,i]=p.useState(!1),[a,l]=p.useState(""),[c,d]=p.useState(!1),[u,E]=p.useState(!1),[f,T]=p.useState(!1),[A,R]=p.useState(!1),[S,h]=p.useState(!1),g=p.useRef(null),[m,I]=p.useState(!1),[O,N]=p.useState(!1),x=p.useRef(null),_=p.useRef(null),C=e.mainView==="block_studio"?e.blockStudioDirty:e.notebookDirty,v=e.mainView==="notebook",b=e.mainView==="connection"?"Connections":e.mainView==="reference"?"Quick Reference":e.notebookTitle||"Untitled";p.useEffect(()=>{s&&_.current&&(_.current.focus(),_.current.select())},[s]),p.useEffect(()=>{if(!O)return;function y(w){x.current&&!x.current.contains(w.target)&&N(!1)}return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[O]);const P=()=>{l(e.notebookTitle),i(!0)},j=()=>{i(!1),a.trim()&&a!==e.notebookTitle&&(e.mainView==="block_studio"&&e.blockStudioMetadata?(t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,name:a.trim()}}),t({type:"SET_BLOCK_STUDIO_DRAFT",draft:UR(e.blockStudioDraft,a.trim())})):t({type:"SET_NOTEBOOK_DIRTY",dirty:!0}))},L=p.useCallback(async()=>{var y;if(e.activeFile){t({type:"SET_SAVING",saving:!0});try{if(e.mainView==="block_studio"){if(!e.blockStudioMetadata)return;const w=await $.saveBlockStudio({path:e.activeBlockPath,source:e.blockStudioDraft,metadata:{name:e.blockStudioMetadata.name,domain:e.blockStudioMetadata.domain,description:e.blockStudioMetadata.description,owner:e.blockStudioMetadata.owner,tags:e.blockStudioMetadata.tags}});t({type:"OPEN_BLOCK_STUDIO",file:{name:`${w.metadata.name}.dql`,path:w.path,type:"block",folder:"blocks"},payload:w}),e.files.some(F=>F.path===w.path)||t({type:"FILE_ADDED",file:{name:`${w.metadata.name}.dql`,path:w.path,type:"block",folder:"blocks"}})}else{const w=e.activeFile.type==="block"?((y=e.cells[0])==null?void 0:y.content)??"":Mb(e.notebookTitle,e.cells,e.notebookMetadata);await $.saveNotebook(e.activeFile.path,w),t({type:"SET_NOTEBOOK_DIRTY",dirty:!1})}d(!0),setTimeout(()=>d(!1),2e3)}catch(w){console.error("Save failed:",w)}finally{t({type:"SET_SAVING",saving:!1})}}},[e.activeFile,e.activeBlockPath,e.blockStudioDraft,e.blockStudioMetadata,e.files,e.mainView,e.notebookTitle,e.notebookMetadata,e.cells,t]);p.useEffect(()=>{const y=w=>{(w.metaKey||w.ctrlKey)&&w.key==="s"&&(w.preventDefault(),L())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[L]),p.useEffect(()=>{if(!e.autoSave||!C||!e.activeFile)return;const y=setTimeout(()=>{L()},2e3);return()=>clearTimeout(y)},[e.autoSave,C,e.activeFile,e.cells,e.blockStudioDraft,L]);const B=[{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,U=B.find(y=>y.mode===M)??B[0];p.useEffect(()=>{if(!S)return;const y=F=>{g.current&&!g.current.contains(F.target)&&h(!1)},w=F=>{F.key==="Escape"&&h(!1)};return document.addEventListener("mousedown",y),document.addEventListener("keydown",w),()=>{document.removeEventListener("mousedown",y),document.removeEventListener("keydown",w)}},[S]);const D={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 o.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:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[o.jsx(n1,{t:n}),o.jsx("div",{style:{width:1,height:20,background:n.headerBorder,flexShrink:0}}),e.activeFile&&o.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&&e.mainView!=="connection"&&e.mainView!=="reference"?s?o.jsx("input",{ref:_,value:a,onChange:y=>l(y.target.value),onBlur:j,onKeyDown:y=>{y.key==="Enter"&&j(),y.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}}):o.jsxs("span",{onClick:P,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:[b,C&&o.jsx("span",{style:{color:n.textMuted,marginLeft:4},children:"●"})]}):o.jsx("span",{style:{color:n.textSecondary,fontSize:13,fontFamily:n.font,padding:"2px 4px"},children:b})]}),o.jsx("div",{style:{flex:1}}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.appMode==="studio"&&o.jsx(o.Fragment,{children:o.jsxs("button",{onClick:v?r:void 0,disabled:!e.activeFile||!v,onMouseEnter:()=>E(!0),onMouseLeave:()=>E(!1),style:{...D,height:30,padding:"0 14px",borderRadius:999,background:n.accent,color:"#ffffff",border:`1px solid ${n.accent}`,opacity:!e.activeFile||!v?.4:u?.9:1,boxShadow:"0 1px 2px rgba(107,93,211,0.25)",gap:6},children:[o.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:o.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})}),"Run all"]})}),o.jsxs("div",{ref:g,style:{position:"relative"},children:[o.jsxs("button",{onClick:()=>h(y=>!y),onMouseEnter:()=>R(!0),onMouseLeave:()=>R(!1),title:`Theme: ${U.label}`,"aria-haspopup":"true","aria-expanded":S,style:{...D,background:A||S?n.btnHover:n.btnBg,color:n.textSecondary,padding:"0 10px",fontSize:12,display:"flex",alignItems:"center",gap:6},children:[o.jsx("span",{style:{width:12,height:12,borderRadius:3,background:U.swatch,border:`1px solid ${n.headerBorder}`,flexShrink:0}}),o.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10,letterSpacing:"0.04em"},children:U.label}),o.jsx("span",{style:{fontSize:8,color:n.textMuted},children:"▾"})]}),S&&o.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:B.map(y=>{const w=y.mode===M;return o.jsxs("button",{role:"menuitemradio","aria-checked":w,onClick:()=>{t({type:"SET_THEME",mode:y.mode}),h(!1)},style:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",background:w?n.btnHover:"transparent",color:n.textPrimary,cursor:"pointer",borderRadius:4,fontSize:12,fontFamily:n.font,textAlign:"left"},onMouseEnter:F=>{w||(F.currentTarget.style.background=n.btnHover)},onMouseLeave:F=>{w||(F.currentTarget.style.background="transparent")},children:[o.jsx("span",{style:{width:14,height:14,borderRadius:3,background:y.swatch,border:`1px solid ${n.headerBorder}`,flexShrink:0}}),o.jsx("span",{style:{flex:1},children:y.label}),w&&o.jsx("span",{style:{color:n.accent,fontSize:11},children:"✓"})]},y.mode)})})]}),e.appMode==="studio"&&o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:L,disabled:!e.activeFile||e.savingFile,onMouseEnter:()=>T(!0),onMouseLeave:()=>T(!1),title:"Save (Cmd+S)",style:{...D,background:f&&e.activeFile?n.btnHover:n.btnBg,color:c?n.success:n.textSecondary,opacity:e.activeFile?1:.4},children:e.savingFile?o.jsxs(o.Fragment,{children:[o.jsx(s1,{}),"Saving…"]}):c?o.jsx(o.Fragment,{children:"✓ Saved"}):o.jsx(o.Fragment,{children:"Save"})}),o.jsx("button",{onClick:()=>t({type:"SET_AUTO_SAVE",enabled:!e.autoSave}),title:e.autoSave?"Auto-save on":"Auto-save off",style:{...D,background:e.autoSave?`${n.accent}20`:n.btnBg,color:e.autoSave?n.accent:n.textMuted,padding:"0 6px",fontSize:10,fontWeight:600,letterSpacing:"0.03em",border:`1px solid ${e.autoSave?n.accent:n.btnBorder}`},children:"AUTO"}),o.jsxs("button",{onClick:()=>t({type:"TOGGLE_DASHBOARD_MODE"}),disabled:!e.activeFile,title:e.dashboardMode?"Switch to editor mode":"Switch to dashboard mode",style:{...D,background:e.dashboardMode?`${n.accent}20`:n.btnBg,color:e.dashboardMode?n.accent:n.textSecondary,border:`1px solid ${e.dashboardMode?n.accent:n.btnBorder}`,opacity:e.activeFile?1:.4,padding:"0 8px"},children:[o.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:e.dashboardMode?o.jsx("path",{d:"M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 8.75 4.25V1.5Z"}):o.jsx("path",{d:"M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v3.585a.746.746 0 0 1 0 .83v8.085A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25Zm1.75-.25a.25.25 0 0 0-.25.25V5h13V1.75a.25.25 0 0 0-.25-.25ZM1.5 6.5v7.75c0 .138.112.25.25.25H7v-8Zm7 8h5.75a.25.25 0 0 0 .25-.25V6.5h-6Z"})}),e.dashboardMode?"Editor":"Dashboard"]}),o.jsx("div",{style:{width:1,height:20,background:n.headerBorder}})]}),o.jsxs("div",{ref:x,style:{position:"relative"},children:[o.jsxs("button",{onClick:()=>{e.activeFile&&N(y=>!y)},disabled:!e.activeFile,onMouseEnter:()=>I(!0),onMouseLeave:()=>I(!1),title:"Share / export",style:{...D,height:30,padding:"0 14px",borderRadius:999,background:(m||O)&&e.activeFile?"#2a2a30":"#1a1a1a",color:"#ffffff",border:"1px solid #1a1a1a",opacity:e.activeFile?1:.4,gap:6},children:[o.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:o.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",o.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"currentColor",style:{marginLeft:1,opacity:.7},children:o.jsx("path",{d:"M1 2.5l3 3 3-3",stroke:"currentColor",fill:"none",strokeWidth:"1.2",strokeLinecap:"round"})})]}),O&&o.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:o.jsx(o1,{label:"Export HTML",description:"Standalone dashboard",t:n,onClick:()=>{t1(e.notebookTitle||"dashboard",e.cells),N(!1)}})})]})]})]})}function o1({label:e,description:t,t:n,onClick:r}){const[s,i]=p.useState(!1);return o.jsxs("button",{onClick:r,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{background:s?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:[o.jsx("span",{style:{fontSize:12,fontWeight:500,color:n.textPrimary,fontFamily:n.font},children:e}),o.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font},children:t})]})}function s1(){return o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",style:{animation:"spin 0.8s linear infinite"},children:[o.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"}),o.jsx("circle",{cx:"6",cy:"6",r:"4.5",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"14 7"})]})}function i1(e){return e.toTimeString().slice(0,8)}function a1(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}function l1(){const{state:e,dispatch:t}=Re(),n=ce[e.themeMode],[r,s]=p.useState(!1),i=e.queryLog.filter(l=>l.error),a=l=>t({type:"SET_DEV_PANEL_TAB",tab:l});return o.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&&o.jsxs(o.Fragment,{children:[o.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(l=>o.jsx(c1,{label:l==="errors"?`Errors${i.length>0?` (${i.length})`:""}`:`Logs (${e.queryLog.length})`,active:e.devPanelTab===l,onClick:()=>a(l),t:n},l)),o.jsx("div",{style:{flex:1}}),o.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"})]}),o.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[e.devPanelTab==="logs"&&(e.queryLog.length===0?o.jsx(tf,{t:n,message:"No queries executed yet."}):[...e.queryLog].reverse().map(l=>o.jsx(nf,{entry:l,t:n},l.id))),e.devPanelTab==="errors"&&(i.length===0?o.jsx(tf,{t:n,message:"No errors."}):[...i].reverse().map(l=>o.jsx(nf,{entry:l,t:n},l.id)))]})]}),o.jsxs("button",{onClick:()=>t({type:"TOGGLE_DEV_PANEL"}),onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!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:[o.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:o.jsx("path",{d:e.devPanelOpen?"M1 7l4-4 4 4":"M1 3l4 4 4-4",strokeWidth:"1.5",stroke:"currentColor",fill:"none"})}),"Dev"]})]})}function c1({label:e,active:t,onClick:n,t:r}){const[s,i]=p.useState(!1);return o.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:s?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 tf({t:e,message:t}){return o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:e.textMuted,fontSize:12,fontFamily:e.font,fontStyle:"italic"},children:t})}function nf({entry:e,t}){return o.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:[o.jsx("span",{style:{color:t.textMuted,flexShrink:0},children:i1(e.ts)}),o.jsx("span",{style:{flexShrink:0,color:t.textPrimary,maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.cellName}),e.error?o.jsx("span",{style:{color:t.error,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.error}):o.jsxs(o.Fragment,{children:[o.jsxs("span",{style:{color:t.textMuted},children:[e.rows.toLocaleString()," rows"]}),o.jsx("span",{style:{color:t.textMuted},children:a1(e.time)})]})]})}function d1({onOpenFile:e}){const{state:t,dispatch:n}=Re(),r=ce[t.themeMode],s=t.files.slice(0,3);return o.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",background:r.appBg,padding:40,overflow:"auto"},children:o.jsxs("div",{style:{maxWidth:720,width:"100%",display:"flex",flexDirection:"column",alignItems:"center",gap:48},children:[o.jsxs("div",{style:{textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[o.jsx("div",{style:{width:72,height:72,borderRadius:16,background:"linear-gradient(135deg, #5b8cff 0%, #7c5cff 60%, #4a34a8 100%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 8px 32px rgba(91,140,255,0.28)"},children:o.jsx("span",{style:{color:"#fff",fontSize:26,fontWeight:800,fontFamily:r.fontMono,letterSpacing:"-1px"},children:"DQL"})}),o.jsxs("div",{children:[o.jsx("h1",{style:{fontSize:32,fontWeight:700,color:r.textPrimary,fontFamily:r.font,marginBottom:8,letterSpacing:"-0.5px"},children:"DQL Notebook"}),o.jsx("p",{style:{fontSize:15,color:r.textSecondary,fontFamily:r.font,letterSpacing:"0.02em"},children:"Analytics as Code"})]})]}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:16,width:"100%"},children:[o.jsx(rf,{title:"New Notebook",description:"Start a fresh analysis with an empty notebook.",icon:o.jsx(f1,{}),accent:r.accent,onClick:()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}),t:r}),o.jsx(u1,{recentFiles:s,onOpenFile:e,t:r}),o.jsx(rf,{title:"New Block",description:"Create a reusable SQL block file.",icon:o.jsx(T1,{}),accent:"#ffc857",onClick:()=>n({type:"OPEN_NEW_BLOCK_MODAL"}),t:r})]}),o.jsxs("div",{style:{width:"100%",borderRadius:10,border:`1px solid ${r.cellBorder}`,padding:"16px 20px",background:r.cellBg},children:[o.jsx("div",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.08em",textTransform:"uppercase",color:r.textMuted,fontFamily:r.font,marginBottom:12},children:"Quick Tips"}),o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, 1fr)",gap:8},children:[["Shift + Enter","Run cell"],["⌘ + S","Save notebook"],["⌘ + B","Toggle sidebar"],["⌘ + D","Dashboard mode"],["⌘ + Shift + Enter","Run all cells"],["⌘ + J","Toggle dev panel"],["Click +","Add a new cell"],["Drag handle","Reorder cells"]].map(([i,a])=>o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsx("kbd",{style:{background:r.pillBg,border:`1px solid ${r.cellBorder}`,borderRadius:4,padding:"2px 6px",fontSize:11,fontFamily:r.fontMono,color:r.textSecondary,whiteSpace:"nowrap"},children:i}),o.jsx("span",{style:{fontSize:12,color:r.textMuted,fontFamily:r.font},children:a})]},i))})]})]})})}function rf({title:e,description:t,icon:n,accent:r,onClick:s,t:i}){const[a,l]=p.useState(!1);return o.jsxs("button",{onClick:s,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{background:a?i.cellBg:"transparent",border:`1px solid ${a?r:i.cellBorder}`,borderRadius:10,padding:"20px 16px",cursor:"pointer",textAlign:"left",display:"flex",flexDirection:"column",gap:10,transition:"border-color 0.2s, background 0.2s, box-shadow 0.2s",boxShadow:a?`0 0 0 1px ${r}30, 0 4px 16px rgba(0,0,0,0.15)`:"none"},children:[o.jsx("div",{style:{width:36,height:36,borderRadius:8,background:`${r}18`,display:"flex",alignItems:"center",justifyContent:"center",color:r},children:n}),o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:13,fontWeight:600,color:i.textPrimary,fontFamily:i.font,marginBottom:4},children:e}),o.jsx("div",{style:{fontSize:12,color:i.textSecondary,fontFamily:i.font,lineHeight:1.5},children:t})]})]})}function u1({recentFiles:e,onOpenFile:t,t:n}){const[r,s]=p.useState(!1);return o.jsxs("div",{onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),style:{background:r?n.cellBg:"transparent",border:`1px solid ${r?n.textMuted:n.cellBorder}`,borderRadius:10,padding:"20px 16px",textAlign:"left",display:"flex",flexDirection:"column",gap:10,transition:"border-color 0.2s, background 0.2s"},children:[o.jsx("div",{style:{width:36,height:36,borderRadius:8,background:`${n.warning}18`,display:"flex",alignItems:"center",justifyContent:"center",color:n.warning},children:o.jsx(p1,{})}),o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:13,fontWeight:600,color:n.textPrimary,fontFamily:n.font,marginBottom:8},children:"Open Recent"}),e.length===0?o.jsx("div",{style:{fontSize:12,color:n.textMuted,fontFamily:n.font,fontStyle:"italic"},children:"No recent files."}):o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:e.map(i=>o.jsx(E1,{file:i,onClick:()=>t(i),t:n},i.path))})]})]})}function E1({file:e,onClick:t,t:n}){const[r,s]=p.useState(!1);return o.jsx("button",{onClick:t,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),style:{background:"transparent",border:"none",cursor:"pointer",color:r?n.accent:n.textSecondary,fontSize:12,fontFamily:n.font,textAlign:"left",padding:"2px 0",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",transition:"color 0.15s"},children:e.name.replace(/\.(dqlnb|dql)$/,"")})}function f1(){return o.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 8.75 4.25V1.5ZM8.75 5.5h2.836L10.25 3.664V4.25c0 .138.112.25.25.25H8.75Zm.5 3.25a.75.75 0 0 1 .75.75v.75h.75a.75.75 0 0 1 0 1.5H10v.75a.75.75 0 0 1-1.5 0V11.5H7.75a.75.75 0 0 1 0-1.5H8.5V9.5a.75.75 0 0 1 .75-.75Z"})})}function p1(){return o.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Zm7-3.25v2.992l2.028.812a.75.75 0 0 1-.557 1.392l-2.5-1A.751.751 0 0 1 7 8.25v-3.5a.75.75 0 0 1 1.5 0Z"})})}function T1(){return o.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M8.75 1.75a.75.75 0 0 0-1.5 0V6.5H2.75a.75.75 0 0 0 0 1.5H7.25v4.75a.75.75 0 0 0 1.5 0V8H13.25a.75.75 0 0 0 0-1.5H8.75V1.75Z"})})}const of=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class ns{constructor(t,n,r=0,s=t.length,i,a){this.test=a,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=t.iterRange(r,s),this.bufferStart=r,this.normalize=i?l=>i(of(l)):of,this.query=this.normalize(n)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return EI(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let t=this.peek();if(t<0)return this.done=!0,this;let n=RI(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=fI(t);let s=this.normalize(n);if(s.length)for(let i=0,a=r;;i++){let l=s.charCodeAt(i),c=this.match(l,a,this.bufferPos+this.bufferStart);if(i==s.length-1){if(c)return this.value=c,this;break}a==r&&i<n.length&&n.charCodeAt(i)==l&&a++}}}match(t,n,r){let s=null;for(let i=0;i<this.matches.length;i+=2){let a=this.matches[i],l=!1;this.query.charCodeAt(a)==t&&(a==this.query.length-1?s={from:this.matches[i+1],to:r}:(this.matches[i]++,l=!0)),l||(this.matches.splice(i,2),i-=2)}return this.query.charCodeAt(0)==t&&(this.query.length==1?s={from:n,to:r}:this.matches.push(1,n)),s&&this.test&&!this.test(s.from,s.to,this.buffer,this.bufferStart)&&(s=null),s}}typeof Symbol<"u"&&(ns.prototype[Symbol.iterator]=function(){return this});const BR={from:-1,to:-1,match:/.*/.exec("")},pu="gm"+(/x/.unicode==null?"":"u");class jR{constructor(t,n,r,s=0,i=t.length){if(this.text=t,this.to=i,this.curLine="",this.done=!1,this.value=BR,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new kR(t,n,r,s,i);this.re=new RegExp(n,pu+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.iter=t.iter();let a=t.lineAt(s);this.curLineStart=a.from,this.matchPos=Qi(t,s),this.getLine(this.curLineStart)}getLine(t){this.iter.next(t),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let t=this.matchPos-this.curLineStart;;){this.re.lastIndex=t;let n=this.matchPos<=this.to&&this.re.exec(this.curLine);if(n){let r=this.curLineStart+n.index,s=r+n[0].length;if(this.matchPos=Qi(this.text,s+(r==s?1:0)),r==this.curLineStart+this.curLine.length&&this.nextLine(),(r<s||r>this.value.to)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,match:n},this;t=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),t=0;else return this.done=!0,this}}}const Vl=new WeakMap;class Qr{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=Vl.get(t);if(!s||s.from>=r||s.to<=n){let l=new Qr(n,t.sliceString(n,r));return Vl.set(t,l),l}if(s.from==n&&s.to==r)return s;let{text:i,from:a}=s;return a>n&&(i=t.sliceString(n,a)+i,a=n),s.to<r&&(i+=t.sliceString(s.to,r)),Vl.set(t,new Qr(a,i)),new Qr(n,i.slice(n-a,r-a))}}class kR{constructor(t,n,r,s,i){this.text=t,this.to=i,this.done=!1,this.value=BR,this.matchPos=Qi(t,s),this.re=new RegExp(n,pu+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.flat=Qr.get(t,s,this.chunkEnd(s+5e3))}chunkEnd(t){return t>=this.to?this.to:this.text.lineAt(t).to}next(){for(;;){let t=this.re.lastIndex=this.matchPos-this.flat.from,n=this.re.exec(this.flat.text);if(n&&!n[0]&&n.index==t&&(this.re.lastIndex=t+1,n=this.re.exec(this.flat.text)),n){let r=this.flat.from+n.index,s=r+n[0].length;if((this.flat.to>=this.to||n.index+n[0].length<=this.flat.text.length-10)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,match:n},this.matchPos=Qi(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Qr.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(jR.prototype[Symbol.iterator]=kR.prototype[Symbol.iterator]=function(){return this});function S1(e){try{return new RegExp(e,pu),!0}catch{return!1}}function Qi(e,t){if(t>=e.length)return t;let n=e.lineAt(t),r;for(;t<n.to&&(r=n.text.charCodeAt(t-n.from))>=56320&&r<57344;)t++;return t}const h1=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=cI(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return s.then(i=>{let a=i&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(i.elements.line.value);if(!a){e.dispatch({effects:r});return}let l=t.doc.lineAt(t.selection.main.head),[,c,d,u,E]=a,f=u?+u.slice(1):0,T=d?+d:l.number;if(d&&E){let S=T/100;c&&(S=S*(c=="-"?-1:1)+l.number/t.doc.lines),T=Math.round(t.doc.lines*S)}else d&&c&&(T=T*(c=="-"?-1:1)+l.number);let A=t.doc.line(Math.max(1,Math.min(t.doc.lines,T))),R=jt.cursor(A.from+Math.max(0,Math.min(f,A.length)));e.dispatch({effects:[r,Qe.scrollIntoView(R.from,{y:"center"})],selection:R})}),!0},R1=({state:e,dispatch:t})=>{let{selection:n}=e,r=jt.create(n.ranges.map(s=>e.wordAt(s.head)||jt.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function A1(e,t){let{main:n,ranges:r}=e.selection,s=e.wordAt(n.head),i=s&&s.from==n.from&&s.to==n.to;for(let a=!1,l=new ns(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(a)return null;l=new ns(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),a=!0}else{if(a&&r.some(c=>c.from==l.value.from))continue;if(i){let c=e.wordAt(l.value.from);if(!c||c.from!=l.value.from||c.to!=l.value.to)continue}return l.value}}const m1=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(i=>i.from===i.to))return R1({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(i=>e.sliceDoc(i.from,i.to)!=r))return!1;let s=A1(e,r);return s?(t(e.update({selection:e.selection.addRange(jt.range(s.from,s.to),!1),effects:Qe.scrollIntoView(s.to)})),!0):!1},xr=pI.define({combine(e){return TI(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new w1(t),scrollToMatch:t=>Qe.scrollIntoView(t)})}});function g1(e){return e?[xr.of(e),ad]:ad}class FR{constructor(t){this.search=t.search,this.caseSensitive=!!t.caseSensitive,this.literal=!!t.literal,this.regexp=!!t.regexp,this.replace=t.replace||"",this.valid=!!this.search&&(!this.regexp||S1(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!t.wholeWord,this.test=t.test}unquote(t){return this.literal?t:t.replace(/\\([nrt\\])/g,(n,r)=>r=="n"?`
|
|
617
|
+
`:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new C1(this):new N1(this)}getCursor(t,n=0,r){let s=t.doc?t:ES.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?zr(this,s,n,r):Vr(this,s,n,r)}}class GR{constructor(t){this.spec=t}}function I1(e,t,n){return(r,s,i,a)=>{if(n&&!n(r,s,i,a))return!1;let l=r>=a&&s<=a+i.length?i.slice(r-a,s-a):t.doc.sliceString(r,s);return e(l,t,r,s)}}function Vr(e,t,n,r){let s;return e.wholeWord&&(s=O1(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=I1(e.test,t,s)),new ns(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:i=>i.toLowerCase(),s)}function O1(e,t){return(n,r,s,i)=>((i>n||i+s.length<r)&&(i=Math.max(0,n-2),s=e.sliceString(i,Math.min(e.length,r+2))),(t(Zi(s,n-i))!=vn.Word||t(ea(s,n-i))!=vn.Word)&&(t(ea(s,r-i))!=vn.Word||t(Zi(s,r-i))!=vn.Word))}class N1 extends GR{constructor(t){super(t)}nextMatch(t,n,r){let s=Vr(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let i=Math.min(t.doc.length,n+this.spec.unquoted.length);s=Vr(this.spec,t,0,i).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let i=Math.max(n,s-1e4-this.spec.unquoted.length),a=Vr(this.spec,t,i,s),l=null;for(;!a.nextOverlapping().done;)l=a.value;if(l)return l;if(i==n)return null;s-=1e4}}prevMatch(t,n,r){let s=this.prevMatchInRange(t,0,n);return s||(s=this.prevMatchInRange(t,Math.max(0,r-this.spec.unquoted.length),t.doc.length)),s&&(s.from!=n||s.to!=r)?s:null}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,n){let r=Vr(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let i=Vr(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!i.next().done;)s(i.value.from,i.value.to)}}function x1(e,t,n){return(r,s,i)=>(!n||n(r,s,i))&&e(i[0],t,r,s)}function zr(e,t,n,r){let s;return e.wholeWord&&(s=y1(t.charCategorizer(t.selection.main.head))),e.test&&(s=x1(e.test,t,s)),new jR(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function Zi(e,t){return e.slice(fS(e,t,!1),t)}function ea(e,t){return e.slice(t,fS(e,t))}function y1(e){return(t,n,r)=>!r[0].length||(e(Zi(r.input,r.index))!=vn.Word||e(ea(r.input,r.index))!=vn.Word)&&(e(ea(r.input,r.index+r[0].length))!=vn.Word||e(Zi(r.input,r.index+r[0].length))!=vn.Word)}class C1 extends GR{nextMatch(t,n,r){let s=zr(this.spec,t,r,t.doc.length).next();return s.done&&(s=zr(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let i=Math.max(n,r-s*1e4),a=zr(this.spec,t,i,r),l=null;for(;!a.next().done;)l=a.value;if(l&&(i==n||l.from>i+10))return l;if(i==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let i=+r.slice(0,s);if(i>0&&i<t.match.length)return t.match[i]+r.slice(s)}return n})}matchAll(t,n){let r=zr(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let i=zr(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!i.next().done;)s(i.value.from,i.value.to)}}const rs=Na.define(),Tu=Na.define(),Mn=uS.define({create(e){return new zl(id(e).create(),null)},update(e,t){for(let n of t.effects)n.is(rs)?e=new zl(n.value.create(),e.panel):n.is(Tu)&&(e=new zl(e.query,n.value?Su:null));return e},provide:e=>dI.from(e,t=>t.panel)});class zl{constructor(t,n){this.query=t,this.panel=n}}const L1=ir.mark({class:"cm-searchMatch"}),_1=ir.mark({class:"cm-searchMatch cm-searchMatch-selected"}),b1=SI.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Mn))}update(e){let t=e.state.field(Mn);(t!=e.startState.field(Mn)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return ir.none;let{view:n}=this,r=new hI;for(let s=0,i=n.visibleRanges,a=i.length;s<a;s++){let{from:l,to:c}=i[s];for(;s<a-1&&c>i[s+1].from-500;)c=i[++s].to;e.highlight(n.state,l,c,(d,u)=>{let E=n.state.selection.ranges.some(f=>f.from==d&&f.to==u);r.add(d,u,E?_1:L1)})}return r.finish()}},{decorations:e=>e.decorations});function xs(e){return t=>{let n=t.state.field(Mn,!1);return n&&n.query.spec.valid?e(t,n):YR(t)}}const ta=xs((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=jt.single(r.from,r.to),i=e.state.facet(xr);return e.dispatch({selection:s,effects:[hu(e,r),i.scrollToMatch(s.main,e)],userEvent:"select.search"}),WR(e),!0}),na=xs((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let i=jt.single(s.from,s.to),a=e.state.facet(xr);return e.dispatch({selection:i,effects:[hu(e,s),a.scrollToMatch(i.main,e)],userEvent:"select.search"}),WR(e),!0}),v1=xs((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:jt.create(n.map(r=>jt.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),D1=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:s}=n.main,i=[],a=0;for(let l=new ns(e.doc,e.sliceDoc(r,s));!l.next().done;){if(i.length>1e3)return!1;l.value.from==r&&(a=i.length),i.push(jt.range(l.value.from,l.value.to))}return t(e.update({selection:jt.create(i,a),userEvent:"select.search.matches"})),!0},sf=xs((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let i=t.nextMatch(n,r,r);if(!i)return!1;let a=i,l=[],c,d,u=[];a.from==r&&a.to==s&&(d=n.toText(t.getReplacement(a)),l.push({from:a.from,to:a.to,insert:d}),a=t.nextMatch(n,a.from,a.to),u.push(Qe.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+".")));let E=e.state.changes(l);return a&&(c=jt.single(a.from,a.to).map(E),u.push(hu(e,a)),u.push(n.facet(xr).scrollToMatch(c.main,e))),e.dispatch({changes:E,selection:c,effects:u,userEvent:"input.replace"}),!0}),M1=xs((e,{query:t})=>{if(e.state.readOnly)return!1;let n=t.matchAll(e.state,1e9).map(s=>{let{from:i,to:a}=s;return{from:i,to:a,insert:t.getReplacement(s)}});if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:Qe.announce.of(r),userEvent:"input.replace.all"}),!0});function Su(e){return e.state.facet(xr).createPanel(e)}function id(e,t){var n,r,s,i,a;let l=e.selection.main,c=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!c)return t;let d=e.facet(xr);return new FR({search:((n=t==null?void 0:t.literal)!==null&&n!==void 0?n:d.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=t==null?void 0:t.caseSensitive)!==null&&r!==void 0?r:d.caseSensitive,literal:(s=t==null?void 0:t.literal)!==null&&s!==void 0?s:d.literal,regexp:(i=t==null?void 0:t.regexp)!==null&&i!==void 0?i:d.regexp,wholeWord:(a=t==null?void 0:t.wholeWord)!==null&&a!==void 0?a:d.wholeWord})}function HR(e){let t=dS(e,Su);return t&&t.dom.querySelector("[main-field]")}function WR(e){let t=HR(e);t&&t==e.root.activeElement&&t.select()}const YR=e=>{let t=e.state.field(Mn,!1);if(t&&t.panel){let n=HR(e);if(n&&n!=e.root.activeElement){let r=id(e.state,t.query.spec);r.valid&&e.dispatch({effects:rs.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[Tu.of(!0),t?rs.of(id(e.state,t.query.spec)):Na.appendConfig.of(ad)]});return!0},$R=e=>{let t=e.state.field(Mn,!1);if(!t||!t.panel)return!1;let n=dS(e,Su);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:Tu.of(!1)}),!0},P1=[{key:"Mod-f",run:YR,scope:"editor search-panel"},{key:"F3",run:ta,shift:na,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:ta,shift:na,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:$R,scope:"editor search-panel"},{key:"Mod-Shift-l",run:D1},{key:"Mod-Alt-g",run:h1},{key:"Mod-d",run:m1,preventDefault:!0}];class w1{constructor(t){this.view=t;let n=this.query=t.state.field(Mn).query.spec;this.commit=this.commit.bind(this),this.searchField=At("input",{value:n.search,placeholder:it(t,"Find"),"aria-label":it(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=At("input",{value:n.replace,placeholder:it(t,"Replace"),"aria-label":it(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=At("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=At("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=At("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,i,a){return At("button",{class:"cm-button",name:s,onclick:i,type:"button"},a)}this.dom=At("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>ta(t),[it(t,"next")]),r("prev",()=>na(t),[it(t,"previous")]),r("select",()=>v1(t),[it(t,"all")]),At("label",null,[this.caseField,it(t,"match case")]),At("label",null,[this.reField,it(t,"regexp")]),At("label",null,[this.wordField,it(t,"by word")]),...t.state.readOnly?[]:[At("br"),this.replaceField,r("replace",()=>sf(t),[it(t,"replace")]),r("replaceAll",()=>M1(t),[it(t,"replace all")])],At("button",{name:"close",onclick:()=>$R(t),"aria-label":it(t,"close"),type:"button"},["×"])])}commit(){let t=new FR({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});t.eq(this.query)||(this.query=t,this.view.dispatch({effects:rs.of(t)}))}keydown(t){AI(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?na:ta)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),sf(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(rs)&&!r.value.eq(this.query)&&this.setQuery(r.value)}setQuery(t){this.query=t,this.searchField.value=t.search,this.replaceField.value=t.replace,this.caseField.checked=t.caseSensitive,this.reField.checked=t.regexp,this.wordField.checked=t.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(xr).top}}function it(e,t){return e.state.phrase(t)}const ri=30,oi=/[\s\.,:;?!]/;function hu(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,i=Math.max(r.from,t-ri),a=Math.min(s,n+ri),l=e.state.sliceDoc(i,a);if(i!=r.from){for(let c=0;c<ri;c++)if(!oi.test(l[c+1])&&oi.test(l[c])){l=l.slice(c);break}}if(a!=s){for(let c=l.length-1;c>l.length-ri;c--)if(!oi.test(l[c-1])&&oi.test(l[c])){l=l.slice(0,c);break}}return Qe.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const U1=Qe.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),ad=[Mn,uI.low(b1),U1],B1=3e4,ra="application/dql-semantic-ref";let si=[],af=0;function j1(e){$.trackUsage(e),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:e}}))}async function lf(){if(Date.now()<af&&si.length>0)return si;const e=await fetch(`${window.location.origin}/api/semantic-completions`);if(!e.ok)throw new Error(`Failed to load semantic completions: HTTP ${e.status}`);const t=await e.json();return si=Array.isArray(t.completions)?t.completions:[],af=Date.now()+B1,si}function k1(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 F1(e,t,n){const r=n?e.posAtCoords(n)??e.state.selection.main.from:e.state.selection.main.from;k1(e,t,r)}function cf(e,t,n){return{label:e.name,detail:e.type==="metric"?"@metric":"@dim",type:e.type==="metric"?"function":"variable",info:`${e.label}${e.description?`
|
|
618
|
+
${e.description}`:""}${e.sql?`
|
|
619
|
+
${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}}),j1(e.name)}}}function G1(e){return{from:e,options:[{label:"@metric(",detail:"semantic metric",type:"function",apply(t,n,r,s){t.dispatch({changes:{from:r,to:s,insert:"@metric("},selection:{anchor:r+8}})}},{label:"@dim(",detail:"semantic dimension",type:"function",apply(t,n,r,s){t.dispatch({changes:{from:r,to:s,insert:"@dim("},selection:{anchor:r+5}})}}]}}const H1=async e=>{const{state:t,pos:n}=e,r=t.sliceDoc(Math.max(0,n-120),n),s=/@metric\(([^)]*)$/i.exec(r);if(s){const l=s[1].trim().toLowerCase(),c=n-s[1].length,d=(await lf()).filter(u=>u.type==="metric").filter(u=>!l||u.name.toLowerCase().includes(l)||u.label.toLowerCase().includes(l)||(u.domain??"").toLowerCase().includes(l)||u.tags.some(E=>E.toLowerCase().includes(l))).slice(0,50);return{from:c,options:d.map(u=>cf(u,c,n)),validFor:/^[\w-]*$/}}const i=/@dim\(([^)]*)$/i.exec(r);if(i){const l=i[1].trim().toLowerCase(),c=n-i[1].length,d=(await lf()).filter(u=>u.type==="dimension").filter(u=>!l||u.name.toLowerCase().includes(l)||u.label.toLowerCase().includes(l)||(u.domain??"").toLowerCase().includes(l)||u.tags.some(E=>E.toLowerCase().includes(l))).slice(0,50);return{from:c,options:d.map(u=>cf(u,c,n)),validFor:/^[\w-]*$/}}const a=/@([md][a-z_]*)?$/i.exec(r);return a?G1(n-a[0].length):(e.explicit,null)};function VR(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}}function W1(e){const t=e.match(/LINE\s+(\d+)/i);if(t){const s=parseInt(t[1],10),i=e.match(/\n(\s*)\^/),a=i?i[1].length+1:1;return{line:s,col:a}}const n=e.match(/at line\s+(\d+),?\s*column\s+(\d+)/i);if(n)return{line:parseInt(n[1],10),col:parseInt(n[2],10)};const r=e.match(/line\s+(\d+)/i);return r?{line:parseInt(r[1],10),col:1}:null}const Di=Na.define(),Y1=uS.define({create(){return ir.none},update(e,t){for(const n of t.effects)if(n.is(Di)){if(!n.value)return ir.none;const{from:r,to:s,message:i}=n.value;return ir.set([ir.mark({class:"cm-sql-error",attributes:{title:i}}).range(r,s)])}return e},provide:e=>Qe.decorations.from(e)}),$1=mI.define([{tag:be.keyword,color:"var(--sql-keyword)",fontWeight:"600"},{tag:[be.controlKeyword,be.moduleKeyword],color:"var(--sql-keyword)",fontWeight:"600"},{tag:[be.string,be.special(be.string)],color:"var(--sql-string)"},{tag:be.number,color:"var(--sql-number)"},{tag:be.bool,color:"var(--sql-number)",fontWeight:"600"},{tag:be.null,color:"var(--sql-number)",fontWeight:"600"},{tag:[be.comment,be.lineComment,be.blockComment,be.docComment],color:"var(--sql-comment)",fontStyle:"italic"},{tag:[be.function(be.variableName),be.function(be.propertyName)],color:"var(--sql-function)"},{tag:[be.typeName,be.className],color:"var(--sql-type)"},{tag:be.operator,color:"var(--sql-punctuation)"},{tag:be.punctuation,color:"var(--sql-punctuation)"},{tag:be.bracket,color:"var(--sql-punctuation)"},{tag:[be.variableName,be.name,be.propertyName,be.attributeName],color:"var(--sql-ident)"},{tag:be.invalid,color:"var(--color-status-error)"}]),V1=Qe.baseTheme({".cm-sql-error":{textDecoration:"underline wavy var(--color-status-error)",textUnderlineOffset:"3px",background:"color-mix(in srgb, var(--color-status-error) 10%, transparent)"}});function zR(e){return Qe.theme({"&":{background:"var(--color-bg-sunken)",color:"var(--color-text-primary)"},".cm-content":{caretColor:"var(--color-text-primary)"},".cm-cursor":{borderLeftColor:"var(--color-text-primary)"},".cm-selectionBackground":{background:"color-mix(in srgb, var(--color-accent-blue) 30%, transparent)"},"&.cm-focused .cm-selectionBackground":{background:"color-mix(in srgb, var(--color-accent-blue) 30%, transparent)"},".cm-gutters":{background:"var(--color-bg-sunken)",color:"var(--color-text-tertiary)",border:"none",borderRight:"1px solid var(--color-border-subtle)"},".cm-activeLineGutter":{background:"var(--color-bg-hover)"},".cm-activeLine":{background:"var(--color-bg-hover)"},".cm-matchingBracket":{background:"color-mix(in srgb, var(--color-accent-blue) 18%, transparent)",outline:"1px solid var(--color-accent-blue)"},".cm-foldPlaceholder":{background:"var(--color-bg-tertiary)",border:"1px solid var(--color-border-subtle)",color:"var(--color-text-secondary)",borderRadius:3,padding:"0 4px"},".cm-tooltip":{background:"var(--color-bg-card)",border:"1px solid var(--color-border-primary)",color:"var(--color-text-primary)",borderRadius:6,boxShadow:"0 4px 12px color-mix(in srgb, var(--color-bg-primary) 40%, transparent)"},".cm-tooltip.cm-tooltip-autocomplete":{"& > ul > li":{padding:"3px 8px"},"& > ul > li[aria-selected]":{background:"color-mix(in srgb, var(--color-accent-blue) 20%, transparent)",color:"var(--color-accent-blue)"}},".cm-searchMatch":{background:"color-mix(in srgb, var(--color-status-warning) 25%, transparent)",outline:"1px solid var(--color-status-warning)"},".cm-searchMatch.cm-searchMatch-selected":{background:"color-mix(in srgb, var(--color-status-warning) 50%, transparent)"},".cm-panels":{background:"var(--color-bg-secondary)",borderTop:"1px solid var(--color-border-subtle)"},".cm-panel":{padding:"6px 8px"},".cm-panel input":{background:"var(--color-bg-sunken)",border:"1px solid var(--color-border-subtle)",color:"var(--color-text-primary)",borderRadius:4,padding:"2px 6px",fontSize:12},".cm-panel button":{background:"var(--color-bg-tertiary)",border:"1px solid var(--color-border-subtle)",color:"var(--color-text-primary)",borderRadius:4,padding:"2px 8px",cursor:"pointer",fontSize:12,marginLeft:4}},{dark:e})}const z1=zR(!0),X1=zR(!1);function K1(e){return e==="midnight"||e==="obsidian"||e==="dark"}function Ru({value:e,onChange:t,onRun:n,themeMode:r,autoFocus:s,schema:i,errorMessage:a,editorRef:l,wrap:c=!0}){const d=ce[r],u=p.useRef(null),E=p.useRef(null),[f,T]=p.useState(!1),A=p.useRef(n),R=p.useRef(t),S=p.useRef(new gI);return A.current=n,R.current=t,p.useEffect(()=>{l&&(l.current={undo:()=>{E.current&&OI(E.current)},redo:()=>{E.current&&II(E.current)},resetTo:h=>{const g=E.current;g&&g.dispatch({changes:{from:0,to:g.state.doc.length,insert:h}})}})}),p.useEffect(()=>{if(!u.current)return;const h=NI.of([{key:"Shift-Enter",run:()=>(A.current(),!0)},{key:"Ctrl-Enter",mac:"Cmd-Enter",run:()=>(A.current(),!0)},{key:"Ctrl-/",mac:"Cmd-/",run:xI},yI,...CI,...LI,..._I,...P1,...bI,...vI]),g=Qe.updateListener.of(C=>{C.docChanged&&R.current(C.state.doc.toString())}),m=Qe.domEventHandlers({focus:(C,v)=>{},blur:(C,v)=>{}}),I=Qe.theme({"&":{background:"var(--color-bg-surface)",color:"var(--color-text-primary)",fontFamily:"var(--font-mono)",fontSize:"13px",minHeight:"80px",maxHeight:"480px"},".cm-scroller":{overflow:"auto",fontFamily:"inherit"},".cm-content":{padding:"10px 0",minHeight:"80px",color:"var(--color-text-primary)"},".cm-focused":{outline:"none"},".cm-editor":{border:"none"},".cm-gutters":{minWidth:40},".cm-foldGutter":{cursor:"pointer"}}),O=i?Xs({schema:i,upperCaseKeywords:!1}):Xs({upperCaseKeywords:!1}),N=[h,g,m,I,S.current.of(O),DI({closeOnBlur:!1,override:[H1]}),MI(),PI(),wI(),UI(),BI(),jI(),kI(),FI(),...c?[Qe.lineWrapping]:[],g1({top:!0}),Y1,V1,GI($1),K1(r)?z1:X1],x=ES.create({doc:e,extensions:N}),_=new Qe({state:x,parent:u.current});return E.current=_,s&&_.focus(),()=>{_.destroy(),E.current=null}},[r]),p.useEffect(()=>{const h=E.current;if(!h)return;const g=i?Xs({schema:i,upperCaseKeywords:!1}):Xs({upperCaseKeywords:!1});h.dispatch({effects:S.current.reconfigure(g)})},[i]),p.useEffect(()=>{const h=E.current;if(!h)return;const g=h.state.doc.toString();g!==e&&h.dispatch({changes:{from:0,to:g.length,insert:e}})},[e]),p.useEffect(()=>{const h=E.current;if(!h)return;if(!a){h.dispatch({effects:Di.of(null)});return}const g=W1(a),m=h.state.doc;if(g&&g.line>=1&&g.line<=m.lines){const I=m.line(g.line),O=I.from+Math.max(0,g.col-1),N=Math.max(O+1,I.to);h.dispatch({effects:Di.of({from:Math.min(O,m.length),to:Math.min(N,m.length),message:a})})}else if(m.lines>=1){const I=m.line(1);h.dispatch({effects:Di.of({from:I.from,to:Math.max(I.from+1,I.to),message:a})})}},[a]),o.jsx("div",{onDragOver:h=>{h.dataTransfer.types.includes(ra)&&(h.preventDefault(),T(!0))},onDragLeave:()=>T(!1),onDrop:h=>{const g=E.current;if(!g)return;const m=VR(h.dataTransfer.getData(ra));m&&(h.preventDefault(),T(!1),F1(g,m.reference,{x:h.clientX,y:h.clientY}),$.trackUsage(m.name),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:m.name}})))},style:{background:"var(--color-bg-surface)",minHeight:80,border:f?`1px solid ${d.accent}`:"1px solid transparent",borderRadius:6,transition:"border-color 0.15s"},children:o.jsx("div",{ref:u,style:{minHeight:80}})})}Ru.displayName="SQLCellEditor";function XR(e,t){const n=e.split(`
|
|
620
|
+
`),r=[];let s=0;for(;s<n.length;){const i=n[s],a=i.match(/^(#{1,6})\s+(.+)$/);if(a){const l=a[1].length,c=a[2],u=[28,22,18,16,14,13][l-1];r.push(o.jsx("div",{style:{fontSize:u,fontWeight:l<=2?700:600,color:t.textPrimary,fontFamily:t.font,lineHeight:1.3,marginBottom:l===1?12:8,marginTop:s>0?l===1?16:10:0,borderBottom:l===1?`1px solid ${t.cellBorder}`:void 0,paddingBottom:l===1?8:void 0},children:Uo(c,t)},s)),s++;continue}if(/^[-*_]{3,}$/.test(i.trim())){r.push(o.jsx("hr",{style:{border:"none",borderTop:`1px solid ${t.cellBorder}`,margin:"12px 0"}},s)),s++;continue}if(i.startsWith("> ")){r.push(o.jsx("div",{style:{borderLeft:`3px solid ${t.textMuted}`,paddingLeft:12,marginLeft:4,color:t.textSecondary,fontStyle:"italic",fontFamily:t.fontSerif,fontSize:14},children:Uo(i.slice(2),t)},s)),s++;continue}if(i.startsWith("```")){const l=[];for(s++;s<n.length&&!n[s].startsWith("```");)l.push(n[s]),s++;r.push(o.jsx("pre",{style:{background:"var(--color-bg-surface)",border:"1px solid var(--color-border-subtle)",borderRadius:6,padding:"10px 12px",fontSize:12,fontFamily:"var(--font-mono)",color:"var(--color-text-primary)",overflow:"auto",margin:"8px 0",lineHeight:1.6},children:l.join(`
|
|
621
|
+
`)},s)),s++;continue}if(/^[-*+]\s/.test(i)){const l=s,c=[];for(;s<n.length&&/^[-*+]\s/.test(n[s]);)c.push(n[s].replace(/^[-*+]\s/,"")),s++;r.push(o.jsx("ul",{style:{paddingLeft:20,marginBottom:8,color:t.textSecondary},children:c.map((d,u)=>o.jsx("li",{style:{fontSize:14,fontFamily:t.font,lineHeight:1.6,marginBottom:2},children:Uo(d,t)},u))},`ul-${l}`));continue}if(/^\d+\.\s/.test(i)){const l=s,c=[];for(;s<n.length&&/^\d+\.\s/.test(n[s]);)c.push(n[s].replace(/^\d+\.\s/,"")),s++;r.push(o.jsx("ol",{style:{paddingLeft:20,marginBottom:8,color:t.textSecondary},children:c.map((d,u)=>o.jsx("li",{style:{fontSize:14,fontFamily:t.font,lineHeight:1.6,marginBottom:2},children:Uo(d,t)},u))},`ol-${l}`));continue}if(!i.trim()){r.push(o.jsx("div",{style:{height:8}},s)),s++;continue}r.push(o.jsx("p",{style:{fontSize:14,lineHeight:1.7,fontFamily:t.fontSerif,color:t.textSecondary,marginBottom:6},children:Uo(i,t)},s)),s++}return r}function Uo(e,t){const n=[];let r=e,s=0;for(;r.length>0;){const i=r.match(/\*{3}(.+?)\*{3}/),a=r.match(/\*{2}(.+?)\*{2}/),l=r.match(/\*(.+?)\*/),c=r.match(/`(.+?)`/),d=r.match(/\[(.+?)\]\((.+?)\)/),u=[i?{match:i,type:"boldItalic"}:null,a?{match:a,type:"bold"}:null,l?{match:l,type:"italic"}:null,c?{match:c,type:"code"}:null,d?{match:d,type:"link"}:null].filter(Boolean);if(u.length===0){n.push(o.jsx(Be.Fragment,{children:r},s++));break}const E=u.reduce((T,A)=>(T.match.index??0)<(A.match.index??0)?T:A),f=E.match.index??0;switch(f>0&&n.push(o.jsx(Be.Fragment,{children:r.slice(0,f)},s++)),E.type){case"boldItalic":n.push(o.jsx("strong",{style:{fontStyle:"italic"},children:E.match[1]},s++));break;case"bold":n.push(o.jsx("strong",{children:E.match[1]},s++));break;case"italic":n.push(o.jsx("em",{children:E.match[1]},s++));break;case"code":n.push(o.jsx("code",{style:{background:"var(--color-bg-surface)",border:"1px solid var(--color-border-subtle)",borderRadius:4,padding:"1px 5px",fontSize:"0.9em",fontFamily:"var(--font-mono)",color:"var(--color-accent-blue)"},children:E.match[1]},s++));break;case"link":n.push(o.jsx("a",{href:E.match[2],target:"_blank",rel:"noopener noreferrer",style:{color:t.accent,textDecoration:"underline"},children:E.match[1]},s++));break}r=r.slice(f+E.match[0].length)}return o.jsx(o.Fragment,{children:n})}function q1({value:e,onChange:t,onRun:n,themeMode:r}){const s=ce[r],[i,a]=p.useState(!1),l=p.useRef(null);p.useEffect(()=>{if(i&&l.current){l.current.focus();const E=l.current;E.style.height="auto",E.style.height=`${Math.max(E.scrollHeight,80)}px`}},[i]);const c=()=>{a(!1)},d=E=>{if(E.key==="Escape"&&a(!1),E.key==="Enter"&&E.shiftKey&&(E.preventDefault(),a(!1),n==null||n()),E.key==="Tab"){E.preventDefault();const f=E.currentTarget,T=f.selectionStart,A=f.selectionEnd,R=e.slice(0,T)+" "+e.slice(A);t(R),requestAnimationFrame(()=>{f.selectionStart=f.selectionEnd=T+2})}},u=E=>{t(E.target.value);const f=E.target;f.style.height="auto",f.style.height=`${Math.max(f.scrollHeight,80)}px`};return i?o.jsx("textarea",{ref:l,value:e,onChange:u,onBlur:c,onKeyDown:d,placeholder:"Write markdown here...",spellCheck:!1,style:{display:"block",width:"100%",minHeight:80,padding:"12px 16px",background:s.editorBg,color:s.textPrimary,border:"none",outline:"none",resize:"none",fontFamily:s.fontMono,fontSize:13,lineHeight:"20px",borderRadius:0,caretColor:s.accent}}):e.trim()?o.jsx("div",{onDoubleClick:()=>a(!0),title:"Double-click to edit",style:{padding:"12px 16px",cursor:"text",minHeight:48},children:XR(e,s)}):o.jsx("div",{onDoubleClick:()=>a(!0),style:{padding:"12px 16px",color:s.textMuted,fontFamily:s.font,fontSize:13,fontStyle:"italic",cursor:"text",minHeight:48,display:"flex",alignItems:"center"},children:"Double-click to add markdown..."})}function J1({cell:e,themeMode:t,onApplyParam:n}){const{dispatch:r}=Re(),s=ce[t],[i,a]=p.useState(!1),l=e.paramConfig??{paramType:"text",label:"Parameter",defaultValue:"",options:[]},c=e.paramValue??l.defaultValue,d=T=>{r({type:"UPDATE_CELL",id:e.id,updates:{paramConfig:{...l,...T}}})},u=T=>{r({type:"SET_PARAM_VALUE",id:e.id,value:T})},E=(l.options??[]).map(T=>T.trim()).filter(Boolean),f=e.name?`{{${e.name}}}`:null;return o.jsxs("div",{style:{background:s.cellBg,border:`1px solid ${s.cellBorder}`,borderLeft:`3px solid ${s.warning}`,borderRadius:8,overflow:"hidden"},children:[i&&o.jsxs("div",{style:{background:s.tableHeaderBg,borderBottom:`1px solid ${s.cellBorder}`,padding:"12px 14px",display:"flex",flexDirection:"column",gap:10},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:2},children:[o.jsx("span",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.06em",color:s.warning,fontFamily:s.fontMono,textTransform:"uppercase"},children:"Configure Parameter"}),o.jsx("button",{onClick:()=>a(!1),title:"Done",style:{background:s.warning,border:"none",borderRadius:5,cursor:"pointer",color:"#000",fontSize:11,fontWeight:700,fontFamily:s.font,padding:"3px 10px",display:"flex",alignItems:"center",gap:4},children:"✓ Done"})]}),o.jsxs("div",{style:{display:"flex",gap:10,flexWrap:"wrap"},children:[o.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[o.jsx("span",{style:{fontSize:10,color:s.textMuted,fontFamily:s.font},children:"Variable name"}),o.jsx("input",{value:e.name??"",onChange:T=>r({type:"UPDATE_CELL",id:e.id,updates:{name:T.target.value||void 0}}),placeholder:"e.g. start_date",style:{background:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:4,color:s.textPrimary,fontSize:12,fontFamily:s.fontMono,padding:"4px 7px",outline:"none"}})]}),o.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[o.jsx("span",{style:{fontSize:10,color:s.textMuted,fontFamily:s.font},children:"Display label"}),o.jsx("input",{value:l.label,onChange:T=>d({label:T.target.value}),placeholder:"e.g. Start Date",style:{background:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:4,color:s.textPrimary,fontSize:12,fontFamily:s.font,padding:"4px 7px",outline:"none"}})]}),o.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 100px"},children:[o.jsx("span",{style:{fontSize:10,color:s.textMuted,fontFamily:s.font},children:"Type"}),o.jsxs("select",{value:l.paramType,onChange:T=>d({paramType:T.target.value}),style:{background:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:4,color:s.textPrimary,fontSize:12,fontFamily:s.font,padding:"4px 7px",outline:"none"},children:[o.jsx("option",{value:"text",children:"Text"}),o.jsx("option",{value:"number",children:"Number"}),o.jsx("option",{value:"date",children:"Date"}),o.jsx("option",{value:"select",children:"Select"})]})]}),o.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[o.jsx("span",{style:{fontSize:10,color:s.textMuted,fontFamily:s.font},children:"Default value"}),o.jsx("input",{type:l.paramType==="number"?"number":l.paramType==="date"?"date":"text",value:l.defaultValue,onChange:T=>d({defaultValue:T.target.value}),style:{background:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:4,color:s.textPrimary,fontSize:12,fontFamily:s.font,padding:"4px 7px",outline:"none"}})]})]}),l.paramType==="select"&&o.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3},children:[o.jsx("span",{style:{fontSize:10,color:s.textMuted,fontFamily:s.font},children:"Options (one per line)"}),o.jsx("textarea",{value:(l.options??[]).join(`
|
|
622
|
+
`),onChange:T=>d({options:T.target.value.split(`
|
|
623
|
+
`)}),rows:4,placeholder:`Option A
|
|
624
|
+
Option B
|
|
625
|
+
Option C`,style:{background:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:4,color:s.textPrimary,fontSize:12,fontFamily:s.fontMono,padding:"5px 7px",outline:"none",resize:"vertical"}})]})]}),o.jsxs("div",{style:{padding:"12px 14px",display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[o.jsx("button",{onClick:()=>a(T=>!T),title:i?"Close config":"Configure parameter",style:{background:i?`${s.warning}18`:"transparent",border:`1px solid ${i?s.warning:s.cellBorder}`,borderRadius:5,cursor:"pointer",color:i?s.warning:s.textMuted,width:26,height:26,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,transition:"all 0.15s"},children:i?o.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.749.749 0 1 1 1.06-1.06L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"})}):o.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M8 0a8.2 8.2 0 0 1 .701.031C9.444.095 9.99.645 10.16 1.29l.288 1.107c.018.066.079.158.212.224.231.114.454.243.668.386.123.082.233.09.299.071l1.103-.303c.644-.176 1.392.021 1.82.63.27.385.506.792.704 1.218.315.675.111 1.422-.364 1.891l-.814.806c-.049.048-.098.147-.088.294.016.257.016.515 0 .772-.01.147.038.246.088.294l.814.806c.475.469.679 1.216.364 1.891a7.977 7.977 0 0 1-.704 1.217c-.428.61-1.176.807-1.82.63l-1.102-.302c-.067-.019-.177-.011-.3.071a5.909 5.909 0 0 1-.668.386c-.133.066-.194.158-.211.224l-.29 1.106c-.168.646-.715 1.196-1.458 1.26a8.006 8.006 0 0 1-1.402 0c-.743-.064-1.289-.614-1.458-1.26l-.289-1.106c-.018-.066-.079-.158-.212-.224a5.738 5.738 0 0 1-.668-.386c-.123-.082-.233-.09-.299-.071l-1.103.303c-.644.176-1.392-.021-1.82-.63a8.12 8.12 0 0 1-.704-1.218c-.315-.675-.111-1.422.363-1.891l.815-.806c.05-.048.098-.147.088-.294a6.214 6.214 0 0 1 0-.772c.01-.147-.038-.246-.088-.294l-.815-.806C.635 6.045.431 5.298.746 4.623a7.92 7.92 0 0 1 .704-1.217c.428-.61 1.176-.807 1.82-.63l1.102.302c.067.019.177.011.3-.071.214-.143.437-.272.668-.386.133-.066.194-.158.211-.224l.29-1.106C6.009.645 6.556.095 7.299.03 7.53.01 7.764 0 8 0Zm-.571 1.525c-.036.003-.108.036-.137.146l-.289 1.105c-.147.561-.549.967-.998 1.189-.173.086-.34.183-.5.29-.417.278-.97.423-1.529.27l-1.103-.303c-.109-.03-.175.016-.195.045-.22.312-.412.644-.573.99-.014.031-.021.11.059.19l.815.806c.411.406.562.957.53 1.456a4.709 4.709 0 0 0 0 .582c.032.499-.119 1.05-.53 1.456l-.815.806c-.081.08-.073.159-.059.19.162.346.353.677.573.989.02.03.085.076.195.046l1.102-.303c.56-.153 1.113-.008 1.53.27.161.107.328.204.501.29.447.222.85.629.997 1.189l.289 1.105c.029.109.101.143.137.146a6.6 6.6 0 0 0 1.142 0c.036-.003.108-.036.137-.146l.289-1.105c.147-.561.549-.967.998-1.189.173-.086.34-.183.5-.29.417-.278.97-.423 1.529-.27l1.103.303c.109.029.175-.016.195-.045.22-.313.411-.644.573-.99.014-.031.021-.11-.059-.19l-.815-.806c-.411-.406-.562-.957-.53-1.456a4.709 4.709 0 0 0 0-.582c-.032-.499.119-1.05.53-1.456l.815-.806c.081-.08.073-.159.059-.19a6.464 6.464 0 0 0-.573-.989c-.02-.03-.085-.076-.195-.046l-1.102.303c-.56.153-1.113.008-1.53-.27a4.44 4.44 0 0 0-.501-.29c-.447-.222-.85-.629-.997-1.189l-.289-1.105c-.029-.11-.101-.143-.137-.146a6.6 6.6 0 0 0-1.142 0ZM8 5.5a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5ZM8 7a1 1 0 1 0 0 2 1 1 0 0 0 0-2Z"})})}),o.jsx("span",{style:{fontSize:13,fontWeight:500,fontFamily:s.font,color:s.textSecondary,flexShrink:0},children:l.label}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[l.paramType==="select"?o.jsx("select",{value:c,onChange:T=>u(T.target.value),style:{background:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:5,color:s.textPrimary,fontSize:13,fontFamily:s.font,padding:"5px 10px",outline:"none",minWidth:160},children:E.length===0?o.jsx("option",{value:"",children:"— no options configured —"}):E.map(T=>o.jsx("option",{value:T,children:T},T))}):o.jsx("input",{type:l.paramType,value:c,onChange:T=>u(T.target.value),style:{background:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:5,color:s.textPrimary,fontSize:13,fontFamily:l.paramType==="number"?s.fontMono:s.font,padding:"5px 10px",outline:"none",minWidth:160}}),f&&o.jsx("span",{style:{fontSize:10,fontFamily:s.fontMono,color:s.warning,opacity:.8},children:f})]}),c&&o.jsx("span",{style:{fontSize:12,fontFamily:s.fontMono,color:s.textPrimary,background:`${s.warning}18`,border:`1px solid ${s.warning}40`,borderRadius:4,padding:"2px 8px",flexShrink:0},children:c}),e.name&&n&&o.jsx("button",{onClick:()=>n(e.name),title:`Re-run cells that use {{${e.name}}}`,style:{background:s.warning,border:"none",borderRadius:5,cursor:"pointer",color:"#000",fontSize:11,fontWeight:600,fontFamily:s.font,padding:"4px 12px",flexShrink:0,transition:"opacity 0.15s"},children:"Apply"})]})]})}function Q1({cell:e,themeMode:t,title:n,subtitle:r,color:s,badge:i}){const a=ce[t];return o.jsx(ER,{typeLabel:n,typeColor:s,idleBorder:a.cellBorder,background:a.cellBg,headerBackground:`${a.tableHeaderBg}80`,title:e.name?o.jsx("span",{style:{fontSize:12,fontFamily:a.fontMono,color:a.textSecondary},children:e.name}):void 0,actions:i?o.jsx("span",{style:{fontSize:9,fontFamily:a.fontMono,fontWeight:600,letterSpacing:"0.1em",color:a.textMuted,textTransform:"uppercase",padding:"2px 6px",border:`1px solid ${a.cellBorder}`,borderRadius:3},children:i}):void 0,children:o.jsx("div",{style:{padding:"12px 14px",fontSize:12,color:a.textSecondary,lineHeight:1.5,fontFamily:a.font},children:r})})}function Z1(e){return e.type==="param"?"param":e.type.toUpperCase()}function ev({cells:e,index:t,content:n,themeMode:r,onInsertHandle:s}){const i=ce[r],[a,l]=p.useState(!1),c=p.useRef(null),d=p.useMemo(()=>e.slice(0,t).filter(f=>f.name&&f.name.trim().length>0),[e,t]),u=p.useMemo(()=>Pb(n),[n]);p.useEffect(()=>{if(!a)return;const f=T=>{var A;(A=c.current)!=null&&A.contains(T.target)||l(!1)};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[a]);const E=u.length===0?"df":u.length===1?`df: ${u[0]}`:`df: ${u[0]} +${u.length-1}`;return o.jsxs("div",{ref:c,style:{position:"relative",flexShrink:0},children:[o.jsxs("button",{onClick:()=>l(f=>!f),title:"Insert an upstream dataframe handle ({{name}})",style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:10,fontFamily:i.fontMono,fontWeight:600,letterSpacing:"0.04em",color:u.length>0?i.accent:i.textMuted,background:u.length>0?`${i.accent}14`:"transparent",border:`1px solid ${u.length>0?`${i.accent}55`:i.btnBorder}`,borderRadius:4,padding:"1px 6px",cursor:"pointer",textTransform:"lowercase",transition:"border-color 0.15s, color 0.15s"},children:[E,o.jsx("span",{style:{fontSize:8,opacity:.7},children:"▾"})]}),a&&o.jsxs("div",{style:{position:"absolute",top:"calc(100% + 4px)",left:0,zIndex:20,minWidth:220,maxWidth:280,background:i.cellBg,border:`1px solid ${i.cellBorder}`,borderRadius:6,boxShadow:"0 6px 16px rgba(0,0,0,0.25)",padding:4,display:"flex",flexDirection:"column",gap:2},children:[o.jsx("div",{style:{fontSize:9,fontFamily:i.font,fontWeight:700,letterSpacing:"0.1em",color:i.textMuted,textTransform:"uppercase",padding:"4px 8px 2px"},children:"Upstream dataframes"}),d.length===0&&o.jsx("div",{style:{fontSize:11,fontFamily:i.font,color:i.textMuted,padding:"6px 8px 8px",lineHeight:1.4},children:"No named upstream cells yet. Name a cell (click its header) to expose it here."}),d.map(f=>{const T=f.name?u.includes(f.name):!1;return o.jsxs("button",{onClick:()=>{f.name&&s(f.name),l(!1)},style:{display:"flex",alignItems:"center",gap:8,padding:"5px 8px",background:T?`${i.accent}14`:"transparent",border:"none",borderRadius:4,cursor:"pointer",textAlign:"left",color:i.textPrimary,fontFamily:i.fontMono,fontSize:11},onMouseEnter:A=>{T||(A.currentTarget.style.background=i.tableRowHover)},onMouseLeave:A=>{T||(A.currentTarget.style.background="transparent")},children:[o.jsx("span",{style:{fontSize:9,fontFamily:i.fontMono,fontWeight:700,color:i.textMuted,minWidth:36},children:Z1(f)}),o.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:f.name}),T&&o.jsx("span",{style:{fontSize:9,color:i.accent,fontWeight:700,letterSpacing:"0.08em"},children:"IN USE"})]},f.id)})]})]})}const tv=/date|time|_at$|_on$|timestamp/i;function nv(e){return typeof e=="number"||typeof e=="string"&&e!==""&&!isNaN(Number(e))}function Wa(e,t){if(tv.test(e))return"date";const n=t.slice(0,40).map(s=>s[e]).filter(s=>s!=null);return n.length===0?"string":n.every(s=>typeof s=="boolean")?"bool":n.every(s=>typeof s=="object")?"json":n.filter(nv).length/n.length>.8?"numeric":"string"}function Au(e){return e==="numeric"?"measure":e==="date"?"temporal":"dimension"}const rv=[25,50,100,500];function ld(e){return typeof e=="number"?!0:typeof e=="string"?!isNaN(Number(e))&&e.trim()!=="":!1}function ov(e){switch(e){case"numeric":return{icon:"#",color:"#79c0ff"};case"date":return{icon:"D",color:"#e3b341"};case"bool":return{icon:"B",color:"#a371f7"};case"json":return{icon:"{}",color:"#ff7b72"};case"string":default:return{icon:"A",color:"#56d364"}}}function KR(e){return e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}function sv(e,t){return e==null?1:t==null?-1:ld(e)&&ld(t)?Number(e)-Number(t):String(e).localeCompare(String(t))}function iv(e,t){const n=a=>a.includes(",")||a.includes('"')||a.includes(`
|
|
626
|
+
`)?`"${a.replace(/"/g,'""')}"`:a,r=e.columns.map(n).join(","),s=e.rows.map(a=>e.columns.map(l=>n(KR(a[l]))).join(",")),i=[r,...s].join(`
|
|
627
|
+
`);qR(i,"export.csv","text/csv")}function av(e,t){const n=JSON.stringify(e.rows,null,2);qR(n,"export.json","application/json")}function qR(e,t,n){const r=new Blob([e],{type:n}),s=URL.createObjectURL(r),i=document.createElement("a");i.href=s,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(s)}function lv({dir:e,color:t}){return e?o.jsx("svg",{width:"8",height:"10",viewBox:"0 0 8 10",fill:t,style:{marginLeft:3,flexShrink:0},children:e==="asc"?o.jsx("path",{d:"M4 0L7 4H1L4 0Z"}):o.jsx("path",{d:"M4 10L1 6H7L4 10Z"})}):o.jsxs("svg",{width:"8",height:"10",viewBox:"0 0 8 10",fill:t,opacity:.3,style:{marginLeft:3,flexShrink:0},children:[o.jsx("path",{d:"M4 0L7 3.5H1L4 0Z"}),o.jsx("path",{d:"M4 10L1 6.5H7L4 10Z"})]})}function Rn({result:e,themeMode:t}){const n=ce[t],[r,s]=p.useState(null),[i,a]=p.useState(null),[l,c]=p.useState(null),[d,u]=p.useState(""),[E,f]=p.useState(50),[T,A]=p.useState(0),R=p.useCallback(_=>{i===_?l==="asc"?c("desc"):l==="desc"?(a(null),c(null)):c("asc"):(a(_),c("asc")),A(0)},[i,l]),S=p.useMemo(()=>{if(!d.trim())return e.rows;const _=d.toLowerCase();return e.rows.filter(C=>e.columns.some(v=>{const b=C[v];return b==null?!1:String(b).toLowerCase().includes(_)}))},[e.rows,e.columns,d]),h=p.useMemo(()=>{if(!i||!l)return S;const _=[...S];return _.sort((C,v)=>{const b=sv(C[i],v[i]);return l==="desc"?-b:b}),_},[S,i,l]),g=p.useMemo(()=>{const _=new Map;for(const C of e.columns)_.set(C,Wa(C,e.rows));return _},[e.columns,e.rows]),[m,I]=p.useState(!1),O=Math.max(1,Math.ceil(h.length/E)),N=Math.min(T,O-1),x=h.slice(N*E,(N+1)*E);return e.columns.length===0?o.jsx("div",{style:{padding:"12px 16px",color:n.textMuted,fontSize:12,fontFamily:n.font,fontStyle:"italic"},children:"Query executed successfully. No columns to display."}):o.jsxs("div",{children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 8px",borderBottom:`1px solid ${n.tableBorder}`,background:`${n.tableHeaderBg}60`,flexWrap:"wrap"},children:[o.jsxs("div",{style:{position:"relative",flex:"0 1 200px",minWidth:120},children:[o.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:n.textMuted,style:{position:"absolute",left:6,top:6},children:o.jsx("path",{d:"M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"})}),o.jsx("input",{value:d,onChange:_=>{u(_.target.value),A(0)},placeholder:"Filter rows...",style:{width:"100%",background:n.inputBg,border:`1px solid ${n.inputBorder}`,borderRadius:4,color:n.textPrimary,fontSize:11,fontFamily:n.font,padding:"3px 8px 3px 22px",outline:"none"}}),d&&o.jsx("button",{onClick:()=>u(""),style:{position:"absolute",right:4,top:3,background:"none",border:"none",color:n.textMuted,cursor:"pointer",fontSize:12,padding:"0 2px"},children:"×"})]}),o.jsxs("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font},children:[d?`${h.length} of ${e.rows.length}`:`${e.rows.length}`," rows"]}),o.jsx("div",{style:{flex:1}}),o.jsx(df,{label:"CSV",onClick:()=>iv(e),t:n}),o.jsx(df,{label:"JSON",onClick:()=>av(e),t:n}),o.jsx("select",{value:E,onChange:_=>{f(Number(_.target.value)),A(0)},style:{background:n.inputBg,border:`1px solid ${n.inputBorder}`,borderRadius:3,color:n.textSecondary,fontSize:10,fontFamily:n.font,padding:"2px 4px",outline:"none"},children:rv.map(_=>o.jsxs("option",{value:_,children:[_," / page"]},_))}),O>1&&o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[o.jsx(Hr,{disabled:N===0,onClick:()=>A(0),t:n,children:"«"}),o.jsx(Hr,{disabled:N===0,onClick:()=>A(N-1),t:n,children:"‹"}),o.jsxs("span",{style:{fontSize:10,color:n.textSecondary,fontFamily:n.font,padding:"0 4px"},children:[N+1,"/",O]}),o.jsx(Hr,{disabled:N>=O-1,onClick:()=>A(N+1),t:n,children:"›"}),o.jsx(Hr,{disabled:N>=O-1,onClick:()=>A(O-1),t:n,children:"»"})]})]}),o.jsx("div",{style:{maxHeight:440,overflow:"auto",position:"relative"},onScroll:_=>I(_.target.scrollTop>0),children:o.jsxs("table",{style:{width:"100%",borderCollapse:"separate",borderSpacing:0,tableLayout:"auto",fontSize:12.5,fontFamily:n.fontMono},children:[o.jsx("thead",{children:o.jsx("tr",{children:e.columns.map(_=>{const C=g.get(_)??"string",v=C==="numeric";return o.jsx("th",{onClick:()=>R(_),style:{background:n.tableHeaderBg,color:n.textSecondary,fontWeight:600,fontSize:11,textAlign:v?"right":"left",padding:"8px 14px",borderBottom:`1px solid ${n.tableBorder}`,minWidth:80,maxWidth:320,whiteSpace:"nowrap",position:"sticky",top:0,zIndex:1,fontFamily:n.font,letterSpacing:"0.03em",overflow:"hidden",textOverflow:"ellipsis",cursor:"pointer",userSelect:"none",boxShadow:m?"0 2px 4px -2px rgba(0,0,0,0.18)":"none",transition:"background 0.1s, box-shadow 0.18s"},children:o.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6,justifyContent:v?"flex-end":"flex-start"},children:[(()=>{const b=ov(C);return o.jsx("span",{title:C,style:{fontSize:9,fontFamily:n.fontMono,fontWeight:700,color:b.color,background:`${b.color}15`,border:`1px solid ${b.color}40`,borderRadius:3,padding:"0 4px",minWidth:14,textAlign:"center",lineHeight:"14px",flexShrink:0},children:b.icon})})(),o.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:_}),o.jsx(lv,{dir:i===_?l:null,color:i===_?n.accent:n.textMuted})]})},_)})})}),o.jsx("tbody",{children:x.map((_,C)=>{const v=r===C,P=C%2===1?n.tableHeaderBg:"transparent";return o.jsx("tr",{onMouseEnter:()=>s(C),onMouseLeave:()=>s(null),style:{transition:"background 0.1s"},children:e.columns.map(j=>{const L=_[j],B=L==null,M=ld(L);return o.jsx("td",{style:{padding:"7px 14px",borderBottom:`1px solid ${n.tableBorder}`,background:v?n.tableRowHover:P,color:B?n.textMuted:n.textPrimary,fontStyle:B?"italic":"normal",fontVariantNumeric:M?"tabular-nums":"normal",textAlign:M?"right":"left",whiteSpace:"nowrap",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",transition:"background 0.1s"},children:B?"—":KR(L)},j)})},C)})})]})}),o.jsxs("div",{style:{padding:"5px 10px",color:n.textMuted,fontSize:10,fontFamily:n.font,borderTop:`1px solid ${n.tableBorder}`,background:`${n.tableHeaderBg}60`,display:"flex",alignItems:"center",gap:4},children:[O>1&&o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[o.jsx(Hr,{disabled:N===0,onClick:()=>A(N-1),t:n,children:"‹"}),cv(O,N).map((_,C)=>_==="…"?o.jsx("span",{style:{color:n.textMuted,fontSize:10,padding:"0 2px"},children:"…"},`gap-${C}`):o.jsx("button",{onClick:()=>A(_-1),style:{background:_-1===N?`${n.accent}20`:"transparent",border:"none",color:_-1===N?n.accent:n.textSecondary,fontSize:10,fontFamily:n.font,fontWeight:_-1===N?700:400,padding:"1px 6px",borderRadius:3,cursor:"pointer",minWidth:20},children:_},_)),o.jsx(Hr,{disabled:N>=O-1,onClick:()=>A(N+1),t:n,children:"›"})]}),o.jsx("div",{style:{flex:1}}),o.jsxs("span",{style:{fontSize:10,color:n.textSecondary,fontFamily:n.font,marginLeft:6,whiteSpace:"nowrap"},children:[h.length.toLocaleString()," ",h.length===1?"row":"rows",d&&e.rows.length!==h.length&&` of ${e.rows.length.toLocaleString()}`]})]})]})}function cv(e,t){if(e<=7)return Array.from({length:e},(s,i)=>i+1);const n=t+1,r=[1];n>3&&r.push("…");for(let s=Math.max(2,n-1);s<=Math.min(e-1,n+1);s++)r.push(s);return n<e-2&&r.push("…"),r.push(e),r}function df({label:e,onClick:t,t:n}){const[r,s]=p.useState(!1);return o.jsxs("button",{onClick:t,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),style:{background:r?n.btnHover:"transparent",border:`1px solid ${r?n.btnBorder:"transparent"}`,borderRadius:3,cursor:"pointer",color:r?n.textSecondary:n.textMuted,fontSize:10,fontFamily:n.font,fontWeight:600,padding:"2px 6px",transition:"all 0.15s",display:"flex",alignItems:"center",gap:3},children:[o.jsxs("svg",{width:"9",height:"9",viewBox:"0 0 16 16",fill:"currentColor",children:[o.jsx("path",{d:"M2.75 14A1.75 1.75 0 0 1 1 12.25v-2.5a.75.75 0 0 1 1.5 0v2.5c0 .138.112.25.25.25h10.5a.25.25 0 0 0 .25-.25v-2.5a.75.75 0 0 1 1.5 0v2.5A1.75 1.75 0 0 1 13.25 14Z"}),o.jsx("path",{d:"M7.25 7.689V2a.75.75 0 0 1 1.5 0v5.689l1.97-1.97a.749.749 0 1 1 1.06 1.06l-3.25 3.25a.749.749 0 0 1-1.06 0L4.22 6.779a.749.749 0 1 1 1.06-1.06l1.97 1.97Z"})]}),e]})}function Hr({disabled:e,onClick:t,children:n,t:r}){return o.jsx("button",{disabled:e,onClick:t,style:{background:"transparent",border:"none",cursor:e?"default":"pointer",color:e?r.textMuted:r.textSecondary,fontSize:12,fontFamily:r.font,padding:"0 3px",opacity:e?.4:1,transition:"opacity 0.1s"},children:n})}const zn=[{value:"bar",label:"Bar"},{value:"grouped-bar",label:"Grouped Bar"},{value:"stacked-bar",label:"Stacked Bar"},{value:"line",label:"Line"},{value:"area",label:"Area"},{value:"scatter",label:"Scatter"},{value:"pie",label:"Pie"},{value:"donut",label:"Donut"},{value:"heatmap",label:"Heatmap"},{value:"histogram",label:"Histogram"},{value:"funnel",label:"Funnel"},{value:"waterfall",label:"Waterfall"},{value:"gauge",label:"Gauge"},{value:"kpi",label:"KPI"}],dv=/date|time|at|day|month|year/i,JR=/^(label|name|category|status|type|group)$/i,QR=/^(value|count|total|revenue|amount|sum|avg|price|quantity|sales)$/i;function Pn(e){return typeof e=="number"?!0:typeof e=="string"?e.trim()!==""&&!isNaN(Number(e)):!1}function uv(e){return typeof e=="string"||typeof e=="number"}const Ev=new Set(["bar","line","area","pie","donut","scatter","heatmap","funnel","waterfall","histogram","gauge","stacked-bar","grouped-bar","kpi","table"]);function pr(e,t){if(t!=null&&t.chart){const n=t.chart.toLowerCase().replace(/_/g,"-");if(Ev.has(n))return n}return fv(e)}function fv(e){const{columns:t,rows:n}=e;if(t.length<2||n.length===0)return"table";const r=t[0],s=t[1],i=n.slice(0,5),a=i.every(E=>Pn(E[s])),l=i.every(E=>uv(E[r]));if(dv.test(r)&&a&&l)return"line";const c=t.find(E=>JR.test(E)),d=t.find(E=>QR.test(E));return c&&d&&i.every(f=>Pn(f[d]))?"bar":i.every(E=>Pn(E[r]))&&a&&t.length>=2?"scatter":t.length===2&&l&&a?"bar":"table"}const ZR={default:["#388bfd","#56d364","#e3b341","#f78166","#a371f7","#39c5cf","#ffa657","#ff7b72","#89d185","#d2a8ff","#58a6ff","#3fb950"],warm:["#f85149","#f78166","#ffa657","#e3b341","#d29922","#db6d28","#ff7b72","#ffa198","#ffdfb6","#e6c174","#c4a35a","#b08c3e"],cool:["#388bfd","#58a6ff","#79c0ff","#39c5cf","#56d364","#3fb950","#a371f7","#d2a8ff","#bc8cff","#6cb6ff","#2ea043","#1f6feb"],mono:["#c9d1d9","#b1bac4","#8b949e","#6e7681","#484f58","#30363d","#21262d","#161b22","#a0a8b2","#9e9e9e","#757575","#616161"],pastel:["#b8d8f8","#b4e6c8","#f4e6a0","#f8c4a4","#d2b8f0","#a8e0e0","#f8d8a0","#f4b8b4","#c0e8c0","#e0d0f8","#a8d8f8","#b0e8b0"]},qe=ZR.default;function Ke(e){return Math.abs(e)>=1e6?`${(e/1e6).toFixed(1)}M`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString(void 0,{maximumFractionDigits:2})}function pv(e){const t=new Date(e);if(!isNaN(t.getTime())){if(/^\d{4}-\d{2}-\d{2}/.test(e))return t.toLocaleDateString("en-US",{month:"short",day:"numeric"});if(/^\d{4}-\d{2}$/.test(e))return t.toLocaleDateString("en-US",{year:"numeric",month:"short"})}return String(e).length>8?String(e).slice(0,8):String(e)}function Ya(e,t){const n=(t!=null&&t.x&&e.columns.includes(t.x)?t.x:void 0)??e.columns.find(s=>JR.test(s))??e.columns[0],r=(t!=null&&t.y&&e.columns.includes(t.y)?t.y:void 0)??e.columns.find(s=>QR.test(s))??e.columns[1];return{labelCol:n,valueCol:r}}const Tr=20;function mu({result:e,themeMode:t,chartConfig:n}){const r=ce[t],[s,i]=p.useState(null),{labelCol:a,valueCol:l}=Ya(e,n),c=(n==null?void 0:n.maxItems)??Tr,d=e.rows.slice(0,c).map(h=>({label:String(h[a]??""),value:Number(h[l]??0)})),u=e.rows.length>c,E=Math.max(...d.map(h=>h.value),1),f=28,T=120,A=6,R=12,S=d.length*(f+A)+R*2;return o.jsxs("div",{style:{padding:"8px 0"},children:[o.jsx("svg",{width:"100%",height:S,viewBox:`0 0 600 ${S}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:d.map((h,g)=>{const m=R+g*(f+A),I=600-T-84,O=Math.max(h.value/E*I,2),N=s===g;return o.jsxs("g",{onMouseEnter:()=>i(g),onMouseLeave:()=>i(null),style:{cursor:"default"},children:[o.jsx("text",{x:T-8,y:m+f/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:h.label.length>16?h.label.slice(0,15)+"…":h.label}),o.jsx("rect",{x:T,y:m,width:O,height:f,rx:3,fill:N?r.accentHover:r.accent,style:{transition:"fill 0.15s"}}),o.jsx("text",{x:T+O+6,y:m+f/2+4,textAnchor:"start",fontSize:11,fontFamily:r.fontMono,fill:r.textMuted,children:Ke(h.value)})]},g)})}),u&&o.jsxs("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,fontStyle:"italic",padding:"4px 12px"},children:["Showing ",Tr," of ",e.rows.length," rows"]})]})}function Tv({result:e,themeMode:t,chartConfig:n}){const r=ce[t],[s,i]=p.useState(null),a=n!=null&&n.x&&e.columns.includes(n.x)?n.x:e.columns[0],l=e.rows.slice(0,5),c=e.columns.filter(h=>h!==a&&l.some(g=>Pn(g[h])));if(c.length===0)return o.jsx(mu,{result:e,themeMode:t,chartConfig:n});const d=e.rows.slice(0,Tr).map(h=>String(h[a]??"")),u=Math.max(...e.rows.slice(0,Tr).flatMap(h=>c.map(g=>Math.abs(Number(h[g]??0)))),1),E=24,f=E/c.length,T=120,A=12,R=8,S=d.length*(E+R)+A*2;return o.jsxs("div",{style:{padding:"8px 0"},children:[o.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:c.map((h,g)=>o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[o.jsx("div",{style:{width:10,height:10,borderRadius:2,background:qe[g%qe.length]}}),o.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:h})]},h))}),o.jsx("svg",{width:"100%",height:S,viewBox:`0 0 600 ${S}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:d.map((h,g)=>{const m=A+g*(E+R),I=e.rows[g];return o.jsxs("g",{children:[o.jsx("text",{x:T-8,y:m+E/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:h.length>16?h.slice(0,15)+"…":h}),c.map((O,N)=>{const x=Number(I[O]??0),_=600-T-60,C=Math.max(Math.abs(x)/u*_,1),v=m+N*f,b=`${g}-${N}`;return o.jsxs("g",{onMouseEnter:()=>i(b),onMouseLeave:()=>i(null),children:[o.jsx("rect",{x:T,y:v,width:C,height:f-1,rx:2,fill:qe[N%qe.length],opacity:s===b?1:.85,style:{transition:"opacity 0.15s"}}),s===b&&o.jsx("text",{x:T+C+4,y:v+f/2+3,fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Ke(x)})]},N)})]},g)})})]})}function Sv({result:e,themeMode:t,chartConfig:n}){const r=ce[t],[s,i]=p.useState(null),a=n!=null&&n.x&&e.columns.includes(n.x)?n.x:e.columns[0],l=e.rows.slice(0,5),c=e.columns.filter(h=>h!==a&&l.some(g=>Pn(g[h])));if(c.length===0)return o.jsx(mu,{result:e,themeMode:t,chartConfig:n});const d=e.rows.slice(0,Tr),u=d.map(h=>String(h[a]??"")),E=Math.max(...d.map(h=>c.reduce((g,m)=>g+Math.abs(Number(h[m]??0)),0)),1),f=28,T=120,A=12,R=6,S=u.length*(f+R)+A*2;return o.jsxs("div",{style:{padding:"8px 0"},children:[o.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:c.map((h,g)=>o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[o.jsx("div",{style:{width:10,height:10,borderRadius:2,background:qe[g%qe.length]}}),o.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:h})]},h))}),o.jsx("svg",{width:"100%",height:S,viewBox:`0 0 600 ${S}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:u.map((h,g)=>{const m=A+g*(f+R),I=d[g],O=600-T-60;let N=T;return o.jsxs("g",{children:[o.jsx("text",{x:T-8,y:m+f/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:h.length>16?h.slice(0,15)+"…":h}),c.map((x,_)=>{const C=Math.abs(Number(I[x]??0)),v=Math.max(C/E*O,0),b=N;N+=v;const P=`${g}-${_}`;return o.jsxs("g",{onMouseEnter:()=>i(P),onMouseLeave:()=>i(null),children:[o.jsx("rect",{x:b,y:m,width:v,height:f,rx:_===0?3:0,fill:qe[_%qe.length],opacity:s===P?1:.85,style:{transition:"opacity 0.15s"}}),s===P&&v>30&&o.jsx("text",{x:b+v/2,y:m+f/2+4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:"#fff",fontWeight:600,children:Ke(C)})]},_)})]},g)})})]})}function uf({result:e,themeMode:t,showArea:n}){const r=ce[t],[s,i]=p.useState(null),a=e.columns[0],l=e.columns[1],c=e.rows.map(L=>({label:String(L[a]??""),value:Number(L[l]??0)}));if(c.length<2)return null;const d=560,u=200,E=52,f=16,T=16,A=36,R=d-E-f,S=u-T-A,h=Math.min(...c.map(L=>L.value)),m=Math.max(...c.map(L=>L.value))-h||1,I=R/(c.length-1),O=L=>E+L*I,N=L=>T+S-(L-h)/m*S,x=c.map((L,B)=>({x:O(B),y:N(L.value)})),_=x.reduce((L,B,M)=>{if(M===0)return`M ${B.x},${B.y}`;const U=x[M-1],D=U.x+(B.x-U.x)/2;return`${L} C ${D},${U.y} ${D},${B.y} ${B.x},${B.y}`},""),C=`${_} L ${x[x.length-1].x},${T+S} L ${E},${T+S} Z`,v=5,b=Array.from({length:v+1},(L,B)=>{const M=h+m*B/v;return{val:M,y:N(M)}}),P=Math.ceil(c.length/8),j=c.filter((L,B)=>B%P===0||B===c.length-1);return o.jsx("div",{style:{position:"relative",padding:"8px 0"},children:o.jsxs("svg",{width:"100%",height:u,viewBox:`0 0 ${d} ${u}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},onMouseLeave:()=>i(null),children:[b.map((L,B)=>o.jsxs("g",{children:[o.jsx("line",{x1:E,y1:L.y,x2:E+R,y2:L.y,stroke:r.tableBorder,strokeWidth:.5}),o.jsx("text",{x:E-6,y:L.y+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Ke(L.val)})]},B)),o.jsx("path",{d:C,fill:r.accent,opacity:n?.3:.15}),o.jsx("path",{d:_,fill:"none",stroke:r.accent,strokeWidth:2,strokeLinejoin:"round"}),x.map((L,B)=>o.jsx("circle",{cx:L.x,cy:L.y,r:3,fill:r.accent,style:{cursor:"crosshair"},onMouseEnter:()=>i({x:L.x,y:L.y,label:c[B].label,value:c[B].value})},B)),j.map((L,B)=>{const M=c.indexOf(L);return o.jsx("text",{x:O(M),y:T+S+16,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:pv(L.label)},B)}),o.jsx("line",{x1:E,y1:T,x2:E,y2:T+S,stroke:r.tableBorder,strokeWidth:1}),o.jsx("line",{x1:E,y1:T+S,x2:E+R,y2:T+S,stroke:r.tableBorder,strokeWidth:1}),s&&o.jsxs("g",{children:[o.jsx("rect",{x:s.x+8,y:s.y-20,width:90,height:32,rx:4,fill:r.cellBg,stroke:r.cellBorder,strokeWidth:1}),o.jsx("text",{x:s.x+13,y:s.y-8,fontSize:10,fontFamily:r.font,fill:r.textSecondary,children:s.label.length>10?s.label.slice(0,10)+"…":s.label}),o.jsx("text",{x:s.x+13,y:s.y+6,fontSize:11,fontFamily:r.fontMono,fill:r.textPrimary,fontWeight:600,children:Ke(s.value)})]})]})})}function hv({result:e,themeMode:t,chartConfig:n}){const r=ce[t],[s,i]=p.useState(null),a=n!=null&&n.x&&e.columns.includes(n.x)?n.x:e.columns[0],l=n!=null&&n.y&&e.columns.includes(n.y)?n.y:e.columns[1],c=n!=null&&n.color&&e.columns.includes(n.color)?n.color:void 0,d=e.rows.slice(0,200).map(b=>({x:Number(b[a]??0),y:Number(b[l]??0),color:c?String(b[c]??""):void 0})),u=560,E=300,f=52,T=16,A=16,R=36,S=u-f-T,h=E-A-R,g=Math.min(...d.map(b=>b.x)),m=Math.max(...d.map(b=>b.x)),I=Math.min(...d.map(b=>b.y)),O=Math.max(...d.map(b=>b.y)),N=m-g||1,x=O-I||1,_=b=>f+(b-g)/N*S,C=b=>A+h-(b-I)/x*h,v=c?[...new Set(d.map(b=>b.color))]:[];return o.jsxs("div",{style:{padding:"8px 0"},children:[c&&v.length>0&&o.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:v.slice(0,12).map((b,P)=>o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[o.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:qe[P%qe.length]}}),o.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:b})]},b))}),o.jsxs("svg",{width:"100%",height:E,viewBox:`0 0 ${u} ${E}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:6},(b,P)=>{const j=I+x*P/5,L=C(j);return o.jsxs("g",{children:[o.jsx("line",{x1:f,y1:L,x2:f+S,y2:L,stroke:r.tableBorder,strokeWidth:.5}),o.jsx("text",{x:f-6,y:L+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Ke(j)})]},P)}),Array.from({length:6},(b,P)=>{const j=g+N*P/5,L=_(j);return o.jsx("text",{x:L,y:A+h+16,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Ke(j)},P)}),o.jsx("line",{x1:f,y1:A,x2:f,y2:A+h,stroke:r.tableBorder,strokeWidth:1}),o.jsx("line",{x1:f,y1:A+h,x2:f+S,y2:A+h,stroke:r.tableBorder,strokeWidth:1}),o.jsx("text",{x:f+S/2,y:E-2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:a}),o.jsx("text",{x:10,y:A+h/2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,transform:`rotate(-90, 10, ${A+h/2})`,children:l}),d.map((b,P)=>{const j=c?v.indexOf(b.color):0;return o.jsx("circle",{cx:_(b.x),cy:C(b.y),r:s===P?5:3.5,fill:qe[j%qe.length],opacity:s===P?1:.7,style:{cursor:"crosshair",transition:"r 0.1s, opacity 0.1s"},onMouseEnter:()=>i(P),onMouseLeave:()=>i(null)},P)}),s!==null&&o.jsxs("g",{children:[o.jsx("rect",{x:_(d[s].x)+8,y:C(d[s].y)-24,width:100,height:28,rx:4,fill:r.cellBg,stroke:r.cellBorder,strokeWidth:1}),o.jsxs("text",{x:_(d[s].x)+13,y:C(d[s].y)-8,fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:["(",Ke(d[s].x),", ",Ke(d[s].y),")"]})]})]})]})}const Rv=12;function Ef({result:e,themeMode:t,chartConfig:n,isDonut:r}){const s=ce[t],[i,a]=p.useState(null),{labelCol:l,valueCol:c}=Ya(e,n),d=e.rows.slice(0,Rv).map(g=>({label:String(g[l]??""),value:Math.abs(Number(g[c]??0))})),u=d.reduce((g,m)=>g+m.value,0)||1,E=90,f=90,T=70,A=r?40:0,R=[];let S=-Math.PI/2;d.forEach((g,m)=>{const I=g.value/u*2*Math.PI,O=S,N=S+I,x=E+T*Math.cos(O),_=f+T*Math.sin(O),C=E+T*Math.cos(N),v=f+T*Math.sin(N),b=I>Math.PI?1:0;let P;if(A>0){const j=E+A*Math.cos(O),L=f+A*Math.sin(O),B=E+A*Math.cos(N),M=f+A*Math.sin(N);P=`M ${x} ${_} A ${T} ${T} 0 ${b} 1 ${C} ${v} L ${B} ${M} A ${A} ${A} 0 ${b} 0 ${j} ${L} Z`}else P=`M ${E} ${f} L ${x} ${_} A ${T} ${T} 0 ${b} 1 ${C} ${v} Z`;R.push({path:P,color:qe[m%qe.length],label:g.label,value:g.value,pct:g.value/u*100}),S=N});const h=i!==null?R[i]:null;return o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:16,padding:"8px 12px",flexWrap:"wrap"},children:[o.jsxs("svg",{width:180,height:180,style:{flexShrink:0},onMouseLeave:()=>a(null),children:[R.map((g,m)=>o.jsx("path",{d:g.path,fill:g.color,opacity:i===null||i===m?1:.55,style:{cursor:"pointer",transition:"opacity 0.15s"},onMouseEnter:()=>a(m)},m)),r&&o.jsxs(o.Fragment,{children:[o.jsx("text",{x:E,y:f-5,textAnchor:"middle",fontSize:11,fontFamily:s.fontMono,fill:s.textSecondary,children:Ke(h?h.value:u)}),o.jsx("text",{x:E,y:f+9,textAnchor:"middle",fontSize:9,fontFamily:s.font,fill:s.textMuted,children:h?`${h.pct.toFixed(1)}%`:"total"})]})]}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4,maxHeight:180,overflowY:"auto",flex:1},children:R.map((g,m)=>o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,cursor:"default",opacity:i===null||i===m?1:.5},onMouseEnter:()=>a(m),onMouseLeave:()=>a(null),children:[o.jsx("div",{style:{width:10,height:10,borderRadius:2,background:g.color,flexShrink:0}}),o.jsx("span",{style:{fontSize:11,fontFamily:s.font,color:s.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g.label}),o.jsxs("span",{style:{fontSize:11,fontFamily:s.fontMono,color:s.textMuted,marginLeft:"auto",flexShrink:0},children:[g.pct.toFixed(1),"%"]})]},m))})]})}function Av({result:e,themeMode:t}){const n=ce[t],[r,s]=p.useState(null),i=e.columns[0],a=e.columns.slice(1),l=e.rows.slice(0,30),c=l.flatMap(S=>a.map(h=>Number(S[h]??0))),d=Math.min(...c),E=Math.max(...c)-d||1,f=Math.min(50,480/a.length),T=24,A=100;function R(S){const h=(S-d)/E,g=Math.round(56+h*192),m=Math.round(139+h*-58),I=Math.round(253+h*-180);return`rgb(${g},${m},${I})`}return o.jsx("div",{style:{padding:"8px 0",overflowX:"auto"},children:o.jsxs("svg",{width:A+a.length*f+20,height:l.length*T+T+16,style:{display:"block",overflow:"visible"},children:[a.map((S,h)=>o.jsx("text",{x:A+h*f+f/2,y:14,textAnchor:"middle",fontSize:9,fontFamily:n.font,fill:n.textMuted,transform:`rotate(-30, ${A+h*f+f/2}, 14)`,children:S.length>8?S.slice(0,7)+"…":S},h)),l.map((S,h)=>{const g=String(S[i]??""),m=T+h*T;return o.jsxs("g",{children:[o.jsx("text",{x:A-6,y:m+T/2+4,textAnchor:"end",fontSize:10,fontFamily:n.font,fill:n.textSecondary,children:g.length>14?g.slice(0,13)+"…":g}),a.map((I,O)=>{const N=Number(S[I]??0),x=(r==null?void 0:r.r)===h&&(r==null?void 0:r.c)===O;return o.jsxs("g",{onMouseEnter:()=>s({r:h,c:O}),onMouseLeave:()=>s(null),children:[o.jsx("rect",{x:A+O*f,y:m,width:f-1,height:T-1,rx:2,fill:R(N),opacity:x?1:.85,stroke:x?n.accent:"none",strokeWidth:x?1.5:0}),x&&o.jsx("text",{x:A+O*f+f/2,y:m+T/2+4,textAnchor:"middle",fontSize:10,fontFamily:n.fontMono,fill:"#fff",fontWeight:600,children:Ke(N)})]},O)})]},h)})]})})}function mv({result:e,themeMode:t,chartConfig:n}){const r=ce[t],[s,i]=p.useState(null),a=(n!=null&&n.x&&e.columns.includes(n.x)?n.x:void 0)??e.columns.find(_=>e.rows.slice(0,5).some(C=>Pn(C[_])))??e.columns[0],l=e.rows.map(_=>Number(_[a]??0)).filter(_=>!isNaN(_));if(l.length===0)return null;const c=Math.min(20,Math.max(5,Math.ceil(Math.sqrt(l.length)))),d=Math.min(...l),f=(Math.max(...l)-d||1)/c,T=Array.from({length:c},(_,C)=>({low:d+C*f,high:d+(C+1)*f,count:0}));l.forEach(_=>{const C=Math.min(Math.floor((_-d)/f),c-1);T[C].count++});const A=Math.max(...T.map(_=>_.count),1),R=560,S=200,h=52,g=16,m=16,I=36,O=R-h-g,N=S-m-I,x=O/c;return o.jsx("div",{style:{padding:"8px 0"},children:o.jsxs("svg",{width:"100%",height:S,viewBox:`0 0 ${R} ${S}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:5},(_,C)=>{const v=A*(C+1)/5,b=m+N-v/A*N;return o.jsxs("g",{children:[o.jsx("line",{x1:h,y1:b,x2:h+O,y2:b,stroke:r.tableBorder,strokeWidth:.5}),o.jsx("text",{x:h-6,y:b+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Math.round(v)})]},C)}),T.map((_,C)=>{const v=_.count/A*N,b=h+C*x,P=m+N-v,j=s===C;return o.jsxs("g",{onMouseEnter:()=>i(C),onMouseLeave:()=>i(null),children:[o.jsx("rect",{x:b+1,y:P,width:x-2,height:v,rx:1,fill:j?r.accentHover:r.accent,opacity:j?1:.85,style:{transition:"fill 0.1s"}}),j&&o.jsx("text",{x:b+x/2,y:P-4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:_.count})]},C)}),T.filter((_,C)=>C%Math.ceil(c/6)===0).map((_,C)=>{const v=T.indexOf(_);return o.jsx("text",{x:h+v*x+x/2,y:m+N+16,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Ke(_.low)},C)}),o.jsx("line",{x1:h,y1:m,x2:h,y2:m+N,stroke:r.tableBorder,strokeWidth:1}),o.jsx("line",{x1:h,y1:m+N,x2:h+O,y2:m+N,stroke:r.tableBorder,strokeWidth:1}),o.jsx("text",{x:h+O/2,y:S-2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:a})]})})}function gv({result:e,themeMode:t,chartConfig:n}){const r=ce[t],[s,i]=p.useState(null),{labelCol:a,valueCol:l}=Ya(e,n),c=e.rows.slice(0,10).map(S=>({label:String(S[a]??""),value:Math.abs(Number(S[l]??0))}));if(c.length===0)return null;const d=c[0].value||1,u=400,E=36,f=4,T=16,A=c.length*(E+f)+T*2,R=u/2;return o.jsx("div",{style:{padding:"8px 0",display:"flex",justifyContent:"center"},children:o.jsx("svg",{width:u,height:A,style:{display:"block"},children:c.map((S,h)=>{const g=T+h*(E+f),m=S.value/d,I=Math.max(m*(u-80),40),O=s===h,N=h<c.length-1?c[h+1].value/d:m*.8,x=Math.max(N*(u-80),40),_=R-I/2,C=R+I/2,v=R+x/2,b=R-x/2,P=`M ${_} ${g} L ${C} ${g} L ${v} ${g+E} L ${b} ${g+E} Z`;return o.jsxs("g",{onMouseEnter:()=>i(h),onMouseLeave:()=>i(null),style:{cursor:"default"},children:[o.jsx("path",{d:P,fill:qe[h%qe.length],opacity:O?1:.85,style:{transition:"opacity 0.15s"}}),o.jsx("text",{x:R,y:g+E/2+1,textAnchor:"middle",fontSize:11,fontFamily:r.font,fill:"#fff",fontWeight:500,children:S.label}),o.jsxs("text",{x:R,y:g+E/2+13,textAnchor:"middle",fontSize:9,fontFamily:r.fontMono,fill:"rgba(255,255,255,0.7)",children:[Ke(S.value)," (",(m*100).toFixed(0),"%)"]})]},h)})})})}function Iv({result:e,themeMode:t,chartConfig:n}){const r=ce[t],[s,i]=p.useState(null),{labelCol:a,valueCol:l}=Ya(e,n),c=e.rows.slice(0,15).map(C=>({label:String(C[a]??""),value:Number(C[l]??0)}));if(c.length===0)return null;let d=0;const u=c.map(C=>{const v=d;return d+=C.value,{...C,start:v,end:d}}),E=u.flatMap(C=>[C.start,C.end]),f=Math.min(0,...E),A=Math.max(0,...E)-f||1,R=560,S=240,h=52,g=16,m=16,I=44,O=R-h-g,N=S-m-I,x=O/u.length,_=C=>m+N-(C-f)/A*N;return o.jsx("div",{style:{padding:"8px 0"},children:o.jsxs("svg",{width:"100%",height:S,viewBox:`0 0 ${R} ${S}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:6},(C,v)=>{const b=f+A*v/5,P=_(b);return o.jsxs("g",{children:[o.jsx("line",{x1:h,y1:P,x2:h+O,y2:P,stroke:r.tableBorder,strokeWidth:.5}),o.jsx("text",{x:h-6,y:P+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Ke(b)})]},v)}),o.jsx("line",{x1:h,y1:_(0),x2:h+O,y2:_(0),stroke:r.textMuted,strokeWidth:1,strokeDasharray:"3,3"}),u.map((C,v)=>{const b=h+v*x,P=_(Math.max(C.start,C.end)),L=_(Math.min(C.start,C.end))-P,B=C.value>=0,M=s===v;return o.jsxs("g",{onMouseEnter:()=>i(v),onMouseLeave:()=>i(null),children:[v<u.length-1&&o.jsx("line",{x1:b+x-2,y1:_(C.end),x2:b+x+2,y2:_(C.end),stroke:r.textMuted,strokeWidth:1,strokeDasharray:"2,2"}),o.jsx("rect",{x:b+4,y:P,width:x-8,height:Math.max(L,1),rx:2,fill:B?r.success:r.error,opacity:M?1:.8,style:{transition:"opacity 0.1s"}}),M&&o.jsxs("text",{x:b+x/2,y:P-4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:[C.value>=0?"+":"",Ke(C.value)]})]},v)}),u.map((C,v)=>o.jsx("text",{x:h+v*x+x/2,y:S-6,textAnchor:"middle",fontSize:9,fontFamily:r.font,fill:r.textMuted,transform:`rotate(-20, ${h+v*x+x/2}, ${S-6})`,children:C.label.length>8?C.label.slice(0,7)+"…":C.label},v)),o.jsx("line",{x1:h,y1:m,x2:h,y2:m+N,stroke:r.tableBorder,strokeWidth:1}),o.jsx("line",{x1:h,y1:m+N,x2:h+O,y2:m+N,stroke:r.tableBorder,strokeWidth:1})]})})}function Ov({result:e,themeMode:t,chartConfig:n}){const r=ce[t],s=e.rows[0];if(!s)return null;const i=(n!=null&&n.y&&e.columns.includes(n.y)?n.y:void 0)??e.columns.find(_=>Pn(s[_]))??e.columns[0],a=Number(s[i]??0),l=(n==null?void 0:n.title)??i,c=a>100?a*1.2:100,d=Math.min(Math.max(a/c,0),1),u=120,E=110,f=80,T=Math.PI,A=0,R=T-(T-A)*d,S=u+f*Math.cos(T),h=E+f*Math.sin(T),g=u+f*Math.cos(R),m=E+f*Math.sin(R),I=d>.5?1:0,O=u+f*Math.cos(A),N=E+f*Math.sin(A),x=d<.33?r.error:d<.66?r.warning:r.success;return o.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",padding:"16px 24px"},children:o.jsxs("svg",{width:240,height:140,style:{display:"block",overflow:"visible"},children:[o.jsx("path",{d:`M ${S} ${h} A ${f} ${f} 0 1 1 ${O} ${N}`,fill:"none",stroke:r.tableBorder,strokeWidth:12,strokeLinecap:"round"}),d>0&&o.jsx("path",{d:`M ${S} ${h} A ${f} ${f} 0 ${I} 1 ${g} ${m}`,fill:"none",stroke:x,strokeWidth:12,strokeLinecap:"round"}),o.jsx("text",{x:u,y:E-4,textAnchor:"middle",fontSize:28,fontFamily:r.fontMono,fill:x,fontWeight:700,children:Ke(a)}),o.jsx("text",{x:u,y:E+16,textAnchor:"middle",fontSize:11,fontFamily:r.font,fill:r.textMuted,children:l})]})})}function eA({result:e,themeMode:t,chartConfig:n}){const r=ce[t],s=e.rows[0];if(!s)return null;const i=n!=null&&n.y&&e.columns.includes(n.y)?n.y:e.columns.find(u=>Pn(s[u]))??e.columns[0],a=s[i],l=Number(a),c=isNaN(l)?String(a):l.toLocaleString(void 0,{maximumFractionDigits:2}),d=(n==null?void 0:n.title)??(n!=null&&n.x&&s[n.x]?String(s[n.x]):i);return o.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"32px 24px",gap:8},children:[o.jsx("span",{style:{fontSize:40,fontWeight:700,fontFamily:r.fontMono,color:r.accent,lineHeight:1.1},children:c}),o.jsx("span",{style:{fontSize:13,fontFamily:r.font,color:r.textMuted,textTransform:"uppercase",letterSpacing:"0.08em",fontWeight:500},children:d})]})}function Nv({config:e,columns:t,onChange:n,onClose:r,t:s}){const i={background:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:4,color:s.textPrimary,fontSize:11,fontFamily:s.font,padding:"4px 8px",outline:"none",width:"100%",boxSizing:"border-box"};return o.jsxs("div",{style:{position:"absolute",top:4,right:4,zIndex:100,background:s.cellBg,border:`1px solid ${s.headerBorder}`,borderRadius:8,padding:12,width:240,boxShadow:"0 4px 16px rgba(0,0,0,0.3)",display:"grid",gap:8},onClick:a=>a.stopPropagation(),children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[o.jsx("span",{style:{fontSize:11,fontWeight:600,color:s.textPrimary,fontFamily:s.font},children:"Chart Settings"}),o.jsx("button",{onClick:r,style:{background:"none",border:"none",color:s.textMuted,cursor:"pointer",fontSize:14},children:"×"})]}),o.jsxs("label",{style:{fontSize:10,color:s.textMuted,fontFamily:s.font},children:["Title",o.jsx("input",{value:e.title??"",onChange:a=>n({title:a.target.value||void 0}),placeholder:"Chart title",style:{...i,marginTop:2}})]}),o.jsxs("label",{style:{fontSize:10,color:s.textMuted,fontFamily:s.font},children:["X-axis label",o.jsx("input",{value:e.xLabel??"",onChange:a=>n({xLabel:a.target.value||void 0}),placeholder:"Auto",style:{...i,marginTop:2}})]}),o.jsxs("label",{style:{fontSize:10,color:s.textMuted,fontFamily:s.font},children:["Y-axis label",o.jsx("input",{value:e.yLabel??"",onChange:a=>n({yLabel:a.target.value||void 0}),placeholder:"Auto",style:{...i,marginTop:2}})]}),o.jsxs("label",{style:{fontSize:10,color:s.textMuted,fontFamily:s.font},children:["Legend",o.jsxs("select",{value:e.legendPosition??"top",onChange:a=>n({legendPosition:a.target.value}),style:{...i,marginTop:2},children:[o.jsx("option",{value:"top",children:"Top"}),o.jsx("option",{value:"bottom",children:"Bottom"}),o.jsx("option",{value:"left",children:"Left"}),o.jsx("option",{value:"right",children:"Right"}),o.jsx("option",{value:"none",children:"Hidden"})]})]}),o.jsxs("label",{style:{fontSize:10,color:s.textMuted,fontFamily:s.font},children:["Color palette",o.jsx("select",{value:e.colorPalette??"default",onChange:a=>n({colorPalette:a.target.value}),style:{...i,marginTop:2},children:Object.keys(ZR).map(a=>o.jsx("option",{value:a,children:a.charAt(0).toUpperCase()+a.slice(1)},a))})]}),o.jsxs("label",{style:{fontSize:10,color:s.textMuted,fontFamily:s.font},children:["Max items",o.jsx("input",{type:"number",value:e.maxItems??Tr,min:5,max:200,onChange:a=>n({maxItems:parseInt(a.target.value)||Tr}),style:{...i,marginTop:2}})]})]})}function $a({result:e,themeMode:t,chartConfig:n,onConfigChange:r}){const s=ce[t],i=pr(e,n),[a,l]=p.useState(!1);return i==="kpi"?o.jsx(eA,{result:e,themeMode:t,chartConfig:n}):o.jsxs("div",{style:{position:"relative"},children:[(n==null?void 0:n.title)&&o.jsx("div",{style:{padding:"8px 12px 0",fontSize:13,fontWeight:600,color:s.textPrimary,fontFamily:s.font,textAlign:"center"},children:n.title}),r&&o.jsx("button",{onClick:()=>l(!a),title:"Chart settings",style:{position:"absolute",top:4,right:4,zIndex:50,background:a?`${s.accent}18`:"transparent",border:`1px solid ${a?s.accent:"transparent"}`,borderRadius:4,color:a?s.accent:s.textMuted,cursor:"pointer",fontSize:14,padding:"2px 6px",lineHeight:1},children:"⚙"}),a&&r&&o.jsx(Nv,{config:n??{},columns:e.columns,onChange:c=>r(c),onClose:()=>l(!1),t:s}),Va(i,e,t,n)]})}function Va(e,t,n,r){const s=r!=null&&r.x&&t.columns.includes(r.x)?r.x:void 0,i=r!=null&&r.y&&t.columns.includes(r.y)?r.y:void 0,a=s||i?xv(t,s,i):t;switch(e){case"line":return o.jsx(uf,{result:a,themeMode:n});case"area":return o.jsx(uf,{result:a,themeMode:n,showArea:!0});case"bar":return o.jsx(mu,{result:a,themeMode:n,chartConfig:r});case"grouped-bar":return o.jsx(Tv,{result:a,themeMode:n,chartConfig:r});case"stacked-bar":return o.jsx(Sv,{result:a,themeMode:n,chartConfig:r});case"scatter":return o.jsx(hv,{result:t,themeMode:n,chartConfig:r});case"pie":return o.jsx(Ef,{result:t,themeMode:n,chartConfig:r,isDonut:!1});case"donut":return o.jsx(Ef,{result:t,themeMode:n,chartConfig:r,isDonut:!0});case"heatmap":return o.jsx(Av,{result:t,themeMode:n});case"histogram":return o.jsx(mv,{result:t,themeMode:n,chartConfig:r});case"funnel":return o.jsx(gv,{result:t,themeMode:n,chartConfig:r});case"waterfall":return o.jsx(Iv,{result:t,themeMode:n,chartConfig:r});case"gauge":return o.jsx(Ov,{result:t,themeMode:n,chartConfig:r});case"kpi":return o.jsx(eA,{result:t,themeMode:n,chartConfig:r});default:return o.jsx(Rn,{result:t,themeMode:n})}}function xv(e,t,n){const r=e.columns,s=[];t&&r.includes(t)&&s.push(t),n&&r.includes(n)&&s.push(n);for(const i of r)s.includes(i)||s.push(i);return s.join(",")===r.join(",")?e:{...e,columns:s,rows:e.rows.map(i=>{const a={};for(const l of s)a[l]=i[l];return a})}}function ys(e){var c,d;if(!e)return{metrics:[],dimensions:[],columns:[],fields:[],hasSemanticBinding:!1};const t=new Set(((c=e.semanticRefs)==null?void 0:c.metrics)??[]),n=new Set(((d=e.semanticRefs)==null?void 0:d.dimensions)??[]),r=t.size>0||n.size>0,s=[],i=[],a=[],l=[];for(const u of e.columns)t.has(u)?(s.push(u),l.push({name:u,kind:"metric"})):n.has(u)&&(i.push(u),l.push({name:u,kind:"dimension"}));for(const u of e.columns)t.has(u)||n.has(u)||(a.push(u),l.push({name:u,kind:"column",chartRole:Au(Wa(u,e.rows))}));return{metrics:s,dimensions:i,columns:a,fields:l,hasSemanticBinding:r}}function os(e){return e==="metric"?"#":e==="dimension"?"∴":"A"}function ss(e,t){return e==="metric"?t:e==="dimension"?"#e3b341":"#56d364"}function ff(e){return e==="metric"?"metric":e==="dimension"?"dimension":"column"}function tA({theme:e,value:t,fields:n,allowKinds:r,placeholder:s="Select field",minWidth:i=180,onChange:a}){const[l,c]=p.useState(!1),[d,u]=p.useState(""),E=p.useRef(null),f=p.useRef(null);p.useEffect(()=>{if(!l)return;const S=h=>{var g;(g=E.current)!=null&&g.contains(h.target)||c(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[l]),p.useEffect(()=>{if(l){const S=setTimeout(()=>{var h;return(h=f.current)==null?void 0:h.focus()},20);return()=>clearTimeout(S)}u("")},[l]);const T=p.useMemo(()=>n.find(S=>S.name===t),[n,t]),A=p.useMemo(()=>{if(!d)return n;const S=d.toLowerCase();return n.filter(h=>h.name.toLowerCase().includes(S))},[n,d]),R=S=>r?r.includes(S):!0;return o.jsxs("div",{ref:E,style:{position:"relative",minWidth:i},children:[o.jsxs("button",{onClick:()=>c(S=>!S),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 8px",background:e.editorBg,border:`1px solid ${e.cellBorder}`,borderRadius:3,cursor:"pointer",color:T?e.textPrimary:e.textMuted,fontFamily:e.fontMono,fontSize:11,textAlign:"left"},children:[T?o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{color:ss(T.kind,e.accent),fontWeight:700,width:12},children:os(T.kind)}),o.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:T.name})]}):o.jsx("span",{style:{flex:1},children:s}),o.jsx("span",{style:{color:e.textMuted,fontSize:9},children:"▾"})]}),l&&o.jsxs("div",{style:{position:"absolute",top:"calc(100% + 2px)",left:0,right:0,zIndex:20,background:e.cellBg,border:`1px solid ${e.cellBorder}`,borderRadius:6,boxShadow:"0 6px 16px rgba(0,0,0,0.28)",padding:4,maxHeight:260,overflow:"auto",minWidth:Math.max(i,200)},children:[o.jsx("input",{ref:f,value:d,onChange:S=>u(S.target.value),placeholder:"Search fields...",style:{width:"100%",padding:"4px 6px",marginBottom:4,background:e.editorBg,border:`1px solid ${e.cellBorder}`,borderRadius:3,color:e.textPrimary,fontFamily:e.font,fontSize:11,outline:"none"}}),t&&o.jsx("button",{onClick:()=>{a(void 0),c(!1)},style:{width:"100%",textAlign:"left",padding:"3px 6px",background:"transparent",border:"none",borderRadius:3,color:e.textMuted,fontSize:10,fontFamily:e.font,cursor:"pointer",fontStyle:"italic"},children:"Clear selection"}),A.length===0&&o.jsx("div",{style:{padding:"6px 8px",fontSize:11,color:e.textMuted,fontFamily:e.font},children:"No matches"}),A.map(S=>{const h=R(S.kind);return o.jsxs("button",{onClick:()=>{h&&(a(S.name),c(!1))},disabled:!h,title:h?S.name:`${ff(S.kind)} — not selectable here`,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 6px",background:"transparent",border:"none",borderRadius:3,cursor:h?"pointer":"not-allowed",textAlign:"left",color:h?e.textPrimary:e.textMuted,fontFamily:e.fontMono,fontSize:11,opacity:h?1:.55},onMouseEnter:g=>{h&&(g.currentTarget.style.background=e.tableRowHover)},onMouseLeave:g=>{g.currentTarget.style.background="transparent"},children:[o.jsx("span",{style:{color:ss(S.kind,e.accent),fontWeight:700,width:12,textAlign:"center"},children:os(S.kind)}),o.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.name}),o.jsx("span",{style:{fontSize:9,color:e.textMuted,fontFamily:e.font,textTransform:"uppercase",letterSpacing:"0.06em"},children:ff(S.kind)})]},S.name)})]})]})}function za({theme:e}){return o.jsxs("div",{style:{fontSize:10,fontFamily:e.font,color:e.textMuted,background:`${e.cellBorder}60`,borderRadius:3,padding:"3px 8px",letterSpacing:"0.02em"},children:["No semantic binding — metrics and dimensions unavailable. Use ",o.jsx("code",{children:"@metric(...)"})," or ",o.jsx("code",{children:"@dim(...)"})," upstream to populate typed pickers."]})}function Cs({theme:e,accentColor:t,cellLabel:n,cellName:r,description:s,upstreamOptions:i,onPick:a}){return o.jsxs("div",{style:{background:e.cellBg,border:`1px solid ${e.cellBorder}`,borderLeft:`3px solid ${t}`,borderRadius:6,padding:"18px 20px",fontFamily:e.font},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[o.jsx("span",{style:{fontSize:10,fontFamily:e.fontMono,fontWeight:700,letterSpacing:"0.08em",color:t,background:`${t}18`,padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:n}),r&&o.jsx("span",{style:{fontSize:12,fontFamily:e.fontMono,color:e.textSecondary},children:r})]}),o.jsx("div",{style:{fontSize:12,color:e.textSecondary,marginBottom:8,lineHeight:1.5},children:s}),i.length===0?o.jsxs("div",{style:{fontSize:11,color:e.textMuted,background:`${t}0A`,border:`1px dashed ${e.cellBorder}`,borderRadius:4,padding:"10px 12px",lineHeight:1.6},children:[o.jsx("div",{style:{fontWeight:600,color:e.textSecondary,marginBottom:4},children:"No dataframe available yet"}),o.jsxs("div",{children:["1. Add a ",o.jsx("span",{style:{fontFamily:e.fontMono,color:e.textSecondary},children:"SQL"})," or"," ",o.jsx("span",{style:{fontFamily:e.fontMono,color:e.textSecondary},children:"Block"})," cell above this one.",o.jsx("br",{}),"2. Run it ",o.jsx("span",{style:{fontFamily:e.fontMono},children:"(⌘↵)"})," and give the cell a name.",o.jsx("br",{}),"3. Come back here — named upstream cells show up as chips you can pick."]}),o.jsxs("div",{style:{marginTop:8,fontSize:10,color:e.textMuted,fontStyle:"italic"},children:["Tip: use ",o.jsx("span",{style:{fontFamily:e.fontMono},children:"@metric(...)"})," and"," ",o.jsx("span",{style:{fontFamily:e.fontMono},children:"@dim(...)"})," in the upstream SQL and metrics / dimensions appear with typed icons in the pickers here."]})]}):o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{fontSize:10,color:e.textMuted,marginBottom:6,letterSpacing:"0.06em",textTransform:"uppercase",fontWeight:700},children:"Pick an upstream dataframe"}),o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:i.map(l=>o.jsx("button",{onClick:()=>l.name&&a(l.name),style:{fontSize:11,fontFamily:e.fontMono,color:t,background:`${t}14`,border:`1px solid ${t}55`,borderRadius:4,padding:"3px 10px",cursor:"pointer"},children:l.name},l.id))})]})]})}function cd(e){return e==="measure"?"#":e==="temporal"?"📅":"A"}function dd(e,t){return e==="measure"?t.accent:e==="temporal"?t.warning:t.success}const yv=[{key:"x",label:"X-axis"},{key:"y",label:"Y-axis"},{key:"color",label:"Color"},{key:"facet",label:"Faceting"}],Cv={chart:"bar"},gu="application/x-dql-chart-column";function nA(e,t){e.effectAllowed="move",e.setData(gu,JSON.stringify(t)),e.setData("text/plain",t.column)}function Lv(e){const t=e.getData(gu);if(!t)return null;try{return JSON.parse(t)}catch{return null}}function _v({cell:e,cells:t,index:n,themeMode:r,onUpdate:s}){const i=ce[r],a=e.chartConfig??Cv,l=a.chart??"bar",c=p.useMemo(()=>{const S=e.upstream;if(S)return t.find(h=>h.name===S)},[e.upstream,t]),d=p.useMemo(()=>t.slice(0,n).filter(S=>S.name&&S.result),[t,n]),u=c==null?void 0:c.result,E=p.useMemo(()=>ys(u),[u]),f=p.useMemo(()=>{if(!u)return new Map;const S=new Map,h=new Set(E.metrics),g=new Set(E.dimensions);for(const m of u.columns)h.has(m)?S.set(m,"measure"):g.has(m)?S.set(m,"dimension"):S.set(m,Au(Wa(m,u.rows)));return S},[u,E]),T=p.useMemo(()=>u?u.columns.filter(S=>f.get(S)==="measure"):[],[u,f]),A=p.useMemo(()=>u?u.columns.filter(S=>f.get(S)!=="measure"):[],[u,f]),R=S=>{s({chartConfig:{...a,...S}})};return!e.upstream||!u?o.jsx(Cs,{theme:i,accentColor:"#a371f7",cellLabel:"Chart",cellName:e.name,description:"Charts render from an upstream dataframe — the rows of a named SQL, DQL, or Block cell above. Drag measures to Y, dimensions to X.",upstreamOptions:d,onPick:S=>s({upstream:S})}):o.jsxs("div",{style:{display:"flex",flexDirection:"column",background:i.cellBg,borderTop:`1px solid ${i.cellBorder}`,borderRight:`1px solid ${i.cellBorder}`,borderBottom:`1px solid ${i.cellBorder}`,borderLeft:"3px solid #a371f7",borderRadius:6,overflow:"hidden",fontFamily:i.font},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${i.cellBorder}`,background:`${i.tableHeaderBg}60`},children:[o.jsx("span",{style:{fontSize:10,fontFamily:i.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#a371f7",background:"#a371f718",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Chart"}),e.name&&o.jsx("span",{style:{fontSize:12,fontFamily:i.fontMono,color:i.textSecondary},children:e.name}),o.jsxs("span",{style:{fontSize:11,color:i.textMuted,fontFamily:i.fontMono},children:["· df: ",e.upstream]}),o.jsx("button",{onClick:()=>s({upstream:void 0}),title:"Change upstream dataframe",style:{fontSize:10,background:"transparent",border:`1px solid ${i.btnBorder}`,borderRadius:3,color:i.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:i.fontMono},children:"change"}),o.jsx("div",{style:{flex:1}}),o.jsx("select",{value:l,onChange:S=>R({chart:S.target.value}),style:{fontSize:11,fontFamily:i.font,background:i.editorBg,color:i.textSecondary,border:`1px solid ${i.cellBorder}`,borderRadius:3,padding:"2px 6px",outline:"none"},children:zn.map(S=>o.jsx("option",{value:S.value,children:S.label},S.value))})]}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"200px 240px 1fr",minHeight:320},children:[o.jsxs("div",{style:{borderRight:`1px solid ${i.cellBorder}`,padding:10,display:"flex",flexDirection:"column",gap:12,overflow:"auto"},children:[!E.hasSemanticBinding&&o.jsx(za,{theme:i}),o.jsx(pf,{label:"Measures",columns:T,kinds:f,theme:i,onPick:S=>R({y:S}),pickHint:"Y-axis"}),o.jsx(pf,{label:"Dimensions",columns:A,kinds:f,theme:i,onPick:S=>R({x:S}),pickHint:"X-axis"})]}),o.jsxs("div",{style:{borderRight:`1px solid ${i.cellBorder}`,padding:10,display:"flex",flexDirection:"column",gap:8},children:[o.jsxs("div",{style:{display:"flex",gap:4,borderBottom:`1px solid ${i.cellBorder}`,paddingBottom:4},children:[o.jsx(Tf,{label:"Data",active:!0,theme:i}),o.jsx(Tf,{label:"Style",theme:i})]}),yv.map(S=>o.jsx(bv,{slotKey:S.key,label:S.label,value:a[S.key],columns:u.columns,kinds:f,theme:i,onAssign:(h,g)=>{const m={[S.key]:h};g&&g!==S.key&&(m[g]=void 0),R(m)},onClear:()=>R({[S.key]:void 0})},S.key))]}),o.jsx("div",{style:{padding:10,minWidth:0,overflow:"hidden"},children:Va(l,u,r,a)})]})]})}function pf({label:e,columns:t,kinds:n,theme:r,onPick:s,pickHint:i}){return o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[o.jsx("div",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.1em",color:r.textMuted,textTransform:"uppercase",fontFamily:r.font,padding:"0 2px"},children:e}),t.length===0&&o.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,padding:"2px 2px"},children:"None"}),t.map(a=>{const l=n.get(a)??"dimension";return o.jsxs("button",{onClick:()=>s(a),draggable:!0,onDragStart:c=>nA(c.dataTransfer,{column:a}),title:`Drag to an axis slot, or click to set as ${i}`,style:{display:"flex",alignItems:"center",gap:6,padding:"4px 6px",background:"transparent",border:"1px solid transparent",borderRadius:4,cursor:"grab",textAlign:"left",color:r.textPrimary,fontFamily:r.fontMono,fontSize:11,transition:"border-color 0.1s, background 0.1s"},onMouseEnter:c=>{c.currentTarget.style.borderColor=r.cellBorder,c.currentTarget.style.background=r.tableRowHover},onMouseLeave:c=>{c.currentTarget.style.borderColor="transparent",c.currentTarget.style.background="transparent"},children:[o.jsx("span",{style:{fontSize:9,fontFamily:r.fontMono,fontWeight:700,color:dd(l,r),width:14,textAlign:"center"},children:cd(l)}),o.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a})]},a)})]})}function Tf({label:e,active:t,theme:n}){return o.jsx("span",{style:{fontSize:11,fontFamily:n.font,fontWeight:600,color:t?n.textPrimary:n.textMuted,padding:"3px 10px",borderRadius:3,background:t?n.tableHeaderBg:"transparent",cursor:t?"default":"not-allowed"},children:e})}function bv({slotKey:e,label:t,value:n,columns:r,kinds:s,theme:i,onAssign:a,onClear:l}){const[c,d]=p.useState(!1),[u,E]=p.useState(!1),f=p.useRef(null);p.useEffect(()=>{if(!c)return;const g=m=>{var I;(I=f.current)!=null&&I.contains(m.target)||d(!1)};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[c]);const T=g=>{g.dataTransfer.types.includes(gu)&&(g.preventDefault(),g.dataTransfer.dropEffect="move",u||E(!0))},A=()=>E(!1),R=g=>{E(!1);const m=Lv(g.dataTransfer);m&&(g.preventDefault(),a(m.column,m.fromSlot),d(!1))},S=u?i.accent:n?`${i.accent}77`:i.cellBorder,h=u?`${i.accent}22`:n?`${i.accent}10`:i.editorBg;return o.jsxs("div",{ref:f,style:{position:"relative"},children:[o.jsx("div",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.1em",color:i.textMuted,textTransform:"uppercase",fontFamily:i.font,marginBottom:3},children:t}),o.jsx("button",{onClick:()=>d(g=>!g),onDragOver:T,onDragEnter:T,onDragLeave:A,onDrop:R,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"5px 8px",background:h,border:`1px dashed ${S}`,borderRadius:4,cursor:"pointer",color:n?i.textPrimary:i.textMuted,fontFamily:i.fontMono,fontSize:11,textAlign:"left",transition:"background 0.1s, border-color 0.1s"},children:n?o.jsxs(o.Fragment,{children:[o.jsxs("span",{draggable:!0,onDragStart:g=>{g.stopPropagation(),nA(g.dataTransfer,{column:n,fromSlot:e})},style:{display:"inline-flex",alignItems:"center",gap:6,flex:1,cursor:"grab",minWidth:0},children:[o.jsx("span",{style:{color:dd(s.get(n)??"dimension",i),fontWeight:700,width:14},children:cd(s.get(n)??"dimension")}),o.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})]}),o.jsx("span",{onClick:g=>{g.stopPropagation(),l(),d(!1)},title:"Clear",style:{color:i.textMuted,fontSize:10,padding:"0 4px"},children:"✕"})]}):o.jsx("span",{children:u?"drop to set":"+ drop column"})}),c&&o.jsx("div",{style:{position:"absolute",top:"calc(100% + 2px)",left:0,right:0,zIndex:10,background:i.cellBg,border:`1px solid ${i.cellBorder}`,borderRadius:6,boxShadow:"0 6px 16px rgba(0,0,0,0.25)",padding:4,maxHeight:220,overflow:"auto"},children:r.map(g=>o.jsxs("button",{onClick:()=>{a(g),d(!1)},style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 6px",background:"transparent",border:"none",borderRadius:3,cursor:"pointer",textAlign:"left",color:i.textPrimary,fontFamily:i.fontMono,fontSize:11},onMouseEnter:m=>{m.currentTarget.style.background=i.tableRowHover},onMouseLeave:m=>{m.currentTarget.style.background="transparent"},children:[o.jsx("span",{style:{color:dd(s.get(g)??"dimension",i),fontWeight:700,width:14},children:cd(s.get(g)??"dimension")}),o.jsx("span",{children:g})]},g))})]})}const Mi=[{value:"eq",label:"=",needsValue:!0},{value:"neq",label:"!=",needsValue:!0},{value:"gt",label:">",needsValue:!0},{value:"gte",label:">=",needsValue:!0},{value:"lt",label:"<",needsValue:!0},{value:"lte",label:"<=",needsValue:!0},{value:"contains",label:"contains",needsValue:!0},{value:"not_contains",label:"does not contain",needsValue:!0},{value:"starts_with",label:"starts with",needsValue:!0},{value:"ends_with",label:"ends with",needsValue:!0},{value:"in",label:"in (list)",needsValue:!0},{value:"not_in",label:"not in (list)",needsValue:!0},{value:"between",label:"between (a, b)",needsValue:!0},{value:"is_null",label:"is empty",needsValue:!1},{value:"is_not_null",label:"is not empty",needsValue:!1}];function ud(e){return`${e}_${Math.random().toString(36).slice(2,10)}`}function vv(){return{mode:"keep",groups:[{id:ud("g"),combinator:"and",rules:[]}]}}function Dv(e){const t=Mi.find(n=>n.value===e.operation);return t?e.column?t.needsValue?`${e.column} ${t.label} ${e.value||"…"}`:`${e.column} ${t.label}`:"…":""}function Mv({cell:e,cells:t,index:n,themeMode:r,onUpdate:s}){const i=ce[r],a=p.useMemo(vv,[e.id]),l=e.filterConfig??a,c=p.useMemo(()=>{const O=e.upstream??l.upstream;if(O)return t.find(N=>N.name===O)},[e.upstream,l.upstream,t]),d=p.useMemo(()=>t.slice(0,n).filter(O=>O.name&&O.result),[t,n]),u=c==null?void 0:c.result,E=(u==null?void 0:u.columns)??[],f=p.useMemo(()=>ys(u),[u]),T=O=>{s({filterConfig:O})},A=(O,N)=>{T({...l,groups:l.groups.map(x=>x.id===O?{...x,...N}:x)})},R=(O,N,x)=>{T({...l,groups:l.groups.map(_=>_.id===O?{..._,rules:_.rules.map(C=>C.id===N?{...C,...x}:C)}:_)})},S=O=>{T({...l,groups:l.groups.map(N=>N.id===O?{...N,rules:[...N.rules,{id:ud("r"),column:E[0]??"",operation:"eq",value:""}]}:N)})},h=(O,N)=>{T({...l,groups:l.groups.map(x=>x.id===O?{...x,rules:x.rules.filter(_=>_.id!==N)}:x)})},g=()=>{T({...l,groups:[...l.groups,{id:ud("g"),combinator:"and",rules:[]}]})},m=O=>{T({...l,groups:l.groups.filter(N=>N.id!==O)})};if(!c||!u)return o.jsx(Cs,{theme:i,accentColor:"#ff7b72",cellLabel:"Filter",cellName:e.name,description:"Filter cells keep or drop rows from an upstream dataframe using column-by-column rules — no SQL needed.",upstreamOptions:d,onPick:O=>s({upstream:O})});const I={background:i.editorBg,border:`1px solid ${i.cellBorder}`,borderRadius:3,color:i.textPrimary,fontSize:11,fontFamily:i.fontMono,padding:"3px 6px",outline:"none"};return o.jsxs("div",{style:{background:i.cellBg,border:`1px solid ${i.cellBorder}`,borderLeft:"3px solid #ff7b72",borderRadius:6,fontFamily:i.font,overflow:"hidden"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${i.cellBorder}`,background:`${i.tableHeaderBg}60`},children:[o.jsx("span",{style:{fontSize:10,fontFamily:i.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#ff7b72",background:"#ff7b7218",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Filter"}),e.name&&o.jsx("span",{style:{fontSize:12,fontFamily:i.fontMono,color:i.textSecondary},children:e.name}),o.jsxs("span",{style:{fontSize:11,color:i.textMuted,fontFamily:i.fontMono},children:["· df: ",c.name]}),o.jsx("button",{onClick:()=>s({upstream:void 0}),style:{fontSize:10,background:"transparent",border:`1px solid ${i.btnBorder}`,borderRadius:3,color:i.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:i.fontMono},children:"change"}),o.jsx("div",{style:{flex:1}}),o.jsx("div",{style:{display:"inline-flex",border:`1px solid ${i.cellBorder}`,borderRadius:3,overflow:"hidden"},children:["keep","drop"].map(O=>o.jsx("button",{onClick:()=>T({...l,mode:O}),style:{fontSize:10,fontFamily:i.font,fontWeight:600,letterSpacing:"0.04em",padding:"3px 10px",background:l.mode===O?`${i.accent}20`:"transparent",color:l.mode===O?i.accent:i.textMuted,border:"none",cursor:"pointer",textTransform:"uppercase"},children:O==="keep"?"Keep rows":"Drop rows"},O))})]}),o.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:10},children:[!f.hasSemanticBinding&&o.jsx(za,{theme:i}),l.groups.map((O,N)=>o.jsxs("div",{style:{border:`1px solid ${i.cellBorder}`,borderRadius:6,padding:10,background:`${i.tableHeaderBg}30`,display:"flex",flexDirection:"column",gap:8},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsxs("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.1em",color:i.textMuted,textTransform:"uppercase",fontFamily:i.font},children:["Group ",N+1]}),o.jsx("div",{style:{display:"inline-flex",border:`1px solid ${i.cellBorder}`,borderRadius:3,overflow:"hidden"},children:["and","or"].map(x=>o.jsx("button",{onClick:()=>A(O.id,{combinator:x}),style:{fontSize:10,fontFamily:i.fontMono,padding:"2px 8px",background:O.combinator===x?`${i.accent}20`:"transparent",color:O.combinator===x?i.accent:i.textMuted,border:"none",cursor:"pointer",textTransform:"uppercase",fontWeight:700},children:x},x))}),o.jsx("div",{style:{flex:1}}),l.groups.length>1&&o.jsx("button",{onClick:()=>m(O.id),style:{fontSize:10,background:"transparent",border:`1px solid ${i.btnBorder}`,borderRadius:3,color:i.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:i.font},children:"Remove group"})]}),O.rules.length===0&&o.jsx("div",{style:{fontSize:11,color:i.textMuted,fontFamily:i.font,padding:"4px 2px"},children:"No rules yet — add one below."}),O.rules.map(x=>{const _=Mi.find(C=>C.value===x.operation)??Mi[0];return o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[o.jsx(tA,{theme:i,value:x.column||void 0,fields:f.fields,placeholder:"Select field",minWidth:180,onChange:C=>R(O.id,x.id,{column:C??""})}),o.jsx("select",{value:x.operation,onChange:C=>R(O.id,x.id,{operation:C.target.value}),style:{...I,minWidth:120},children:Mi.map(C=>o.jsx("option",{value:C.value,children:C.label},C.value))}),_.needsValue&&o.jsx("input",{value:x.value,onChange:C=>R(O.id,x.id,{value:C.target.value}),placeholder:"Value",style:{...I,flex:1,minWidth:100}}),o.jsx("button",{onClick:()=>h(O.id,x.id),title:"Remove rule",style:{background:"transparent",border:`1px solid ${i.btnBorder}`,borderRadius:3,color:i.textMuted,fontSize:10,padding:"2px 6px",cursor:"pointer"},children:"✕"})]},x.id)}),o.jsx("div",{children:o.jsx("button",{onClick:()=>S(O.id),style:{fontSize:10,fontFamily:i.font,color:i.accent,background:"transparent",border:`1px dashed ${i.accent}55`,borderRadius:3,padding:"3px 10px",cursor:"pointer",letterSpacing:"0.04em"},children:"+ Add filter"})})]},O.id)),o.jsx("div",{children:o.jsx("button",{onClick:g,style:{fontSize:10,fontFamily:i.font,color:i.textMuted,background:"transparent",border:`1px dashed ${i.btnBorder}`,borderRadius:3,padding:"3px 10px",cursor:"pointer",letterSpacing:"0.04em"},children:"+ Add filter group"})})]}),o.jsxs("div",{style:{padding:"6px 12px",borderTop:`1px solid ${i.cellBorder}`,background:`${i.tableHeaderBg}40`,fontSize:10,fontFamily:i.fontMono,color:i.textMuted,letterSpacing:"0.04em",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},children:[l.mode==="keep"?"KEEP WHERE ":"DROP WHERE ",l.groups.map(O=>O.rules.map(Dv).join(` ${O.combinator.toUpperCase()} `)).filter(Boolean).map(O=>`(${O})`).join(" AND ")||"—"]})]})}function Sf(e){return typeof e=="number"?e:typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e))?Number(e):null}function ao(e,t){if(t==="count")return e.length;if(t==="count_distinct")return new Set(e.map(r=>String(r))).size;if(t==="last"){const r=e[e.length-1];return Sf(r)}const n=e.map(Sf).filter(r=>r!==null);if(n.length===0)return null;switch(t){case"sum":return n.reduce((r,s)=>r+s,0);case"avg":return n.reduce((r,s)=>r+s,0)/n.length;case"min":return n.reduce((r,s)=>s<r?s:r,n[0]);case"max":return n.reduce((r,s)=>s>r?s:r,n[0])}}const Pv=[{value:"sum",label:"Sum"},{value:"avg",label:"Average"},{value:"count",label:"Count"},{value:"min",label:"Min"},{value:"max",label:"Max"},{value:"last",label:"Last"}],wv=[{value:"number",label:"Number"},{value:"currency",label:"Currency"},{value:"percent",label:"Percent"},{value:"duration",label:"Duration"}],Uv={aggregation:"count",format:"number"};function Bv(e,t,n){return n==="count"?ao(e.rows,"count"):!t||!e.columns.includes(t)?null:ao(e.rows.map(r=>r[t]),n)}function jv(e,t){if(e===null)return"—";switch(t){case"currency":return e.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2});case"percent":return`${(e*100).toFixed(1)}%`;case"duration":return e<60?`${e.toFixed(1)}s`:e<3600?`${(e/60).toFixed(1)}m`:`${(e/3600).toFixed(1)}h`;case"number":default:return Math.abs(e)>=1e3?e.toLocaleString(void 0,{maximumFractionDigits:2}):e.toFixed(Number.isInteger(e)?0:2)}}function kv({cell:e,cells:t,index:n,themeMode:r,onUpdate:s}){const i=ce[r],a=e.singleValueConfig??Uv,l=a.aggregation??"count",c=a.format??"number",d=p.useMemo(()=>{const h=e.upstream??a.upstream;if(h)return t.find(g=>g.name===h)},[e.upstream,a.upstream,t]),u=p.useMemo(()=>t.slice(0,n).filter(h=>h.name&&h.result),[t,n]),E=d==null?void 0:d.result,f=p.useMemo(()=>ys(E),[E]),T=p.useMemo(()=>E?Bv(E,a.metric,l):null,[E,a.metric,l]),A=h=>{s({singleValueConfig:{...a,...h}})};if(!d||!E)return o.jsx(Cs,{theme:i,accentColor:"#a371f7",cellLabel:"Single value",cellName:e.name,description:"Single-value cards render one KPI from an upstream dataframe — sum, avg, count, min, max, or last — with a format of your choice.",upstreamOptions:u,onPick:h=>s({upstream:h})});const R=jv(T,c),S={background:i.editorBg,border:`1px solid ${i.cellBorder}`,borderRadius:3,color:i.textPrimary,fontSize:11,fontFamily:i.fontMono,padding:"3px 6px",outline:"none"};return o.jsxs("div",{style:{background:i.cellBg,border:`1px solid ${i.cellBorder}`,borderLeft:"3px solid #a371f7",borderRadius:6,fontFamily:i.font,overflow:"hidden"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${i.cellBorder}`,background:`${i.tableHeaderBg}60`},children:[o.jsx("span",{style:{fontSize:10,fontFamily:i.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#a371f7",background:"#a371f718",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Single value"}),e.name&&o.jsx("span",{style:{fontSize:12,fontFamily:i.fontMono,color:i.textSecondary},children:e.name}),o.jsxs("span",{style:{fontSize:11,color:i.textMuted,fontFamily:i.fontMono},children:["· df: ",d.name]}),o.jsx("button",{onClick:()=>s({upstream:void 0}),style:{fontSize:10,background:"transparent",border:`1px solid ${i.btnBorder}`,borderRadius:3,color:i.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:i.fontMono},children:"change"})]}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"280px 1fr"},children:[o.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:8,borderRight:`1px solid ${i.cellBorder}`},children:[o.jsx(ii,{label:"Aggregation",theme:i,children:o.jsx("select",{value:l,onChange:h=>A({aggregation:h.target.value}),style:{...S,width:"100%"},children:Pv.map(h=>o.jsx("option",{value:h.value,children:h.label},h.value))})}),l!=="count"&&o.jsxs(ii,{label:"Metric field",theme:i,children:[o.jsx(tA,{theme:i,value:a.metric,fields:f.fields,placeholder:"Select metric or column",minWidth:240,onChange:h=>A({metric:h})}),!f.hasSemanticBinding&&o.jsx(za,{theme:i})]}),o.jsx(ii,{label:"Format",theme:i,children:o.jsx("select",{value:c,onChange:h=>A({format:h.target.value}),style:{...S,width:"100%"},children:wv.map(h=>o.jsx("option",{value:h.value,children:h.label},h.value))})}),o.jsx(ii,{label:"Label",theme:i,children:o.jsx("input",{value:a.label??"",onChange:h=>A({label:h.target.value||void 0}),placeholder:"e.g. Total revenue",style:{...S,width:"100%"}})})]}),o.jsxs("div",{style:{padding:"24px 20px",display:"flex",flexDirection:"column",justifyContent:"center",gap:6},children:[o.jsx("div",{style:{fontSize:11,fontFamily:i.font,color:i.textMuted,letterSpacing:"0.06em",textTransform:"uppercase",fontWeight:600},children:a.label??`${l.toUpperCase()}${a.metric?` · ${a.metric}`:""}`}),o.jsx("div",{style:{fontSize:42,fontWeight:700,fontFamily:i.font,color:i.textPrimary,lineHeight:1.1,letterSpacing:"-0.02em"},children:R}),o.jsxs("div",{style:{fontSize:10,color:i.textMuted,fontFamily:i.fontMono},children:["from ",E.rows.length.toLocaleString()," rows"]})]})]})]})}function ii({label:e,theme:t,children:n}){return o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[o.jsx("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.1em",color:t.textMuted,textTransform:"uppercase",fontFamily:t.font},children:e}),n]})}const Fv=["sum","avg","count","min","max","count_distinct"],Gv={rows:[],columns:[],values:[]};function hf(e,t){return t.map(n=>String(e[n]??"")).join("|")}function Xl(e,t){return e.metrics.includes(t)?"metric":e.dimensions.includes(t)?"dimension":"column"}function Rf(e,t){const n=e.fields.filter(s=>s.kind===t),r=e.fields.filter(s=>s.kind!==t);return[...n,...r].map(s=>({name:s.name,kind:s.kind}))}function Hv({cell:e,cells:t,index:n,themeMode:r,onUpdate:s}){const i=ce[r],a=e.pivotConfig??Gv,l={upstream:a.upstream,rows:a.rows??[],columns:a.columns??[],values:a.values??[]},c=p.useMemo(()=>{const S=e.upstream??l.upstream;if(S)return t.find(h=>h.name===S)},[e.upstream,l.upstream,t]),d=p.useMemo(()=>t.slice(0,n).filter(S=>S.name&&S.result),[t,n]),u=c==null?void 0:c.result;u==null||u.columns;const E=p.useMemo(()=>ys(u),[u]),f=p.useMemo(()=>Rf(E,"dimension"),[E]),T=p.useMemo(()=>Rf(E,"metric"),[E]),A=S=>s({pivotConfig:S}),R=p.useMemo(()=>{if(!u||l.rows.length===0&&l.columns.length===0||l.values.length===0)return null;const S=new Set,h=new Map;for(const O of u.rows){const N=hf(O,l.rows),x=hf(O,l.columns);S.add(x);let _=h.get(N);if(!_){const v={};for(const b of l.rows)v[b]=O[b];_={row:v,groups:new Map},h.set(N,_)}const C=_.groups.get(x)??[];C.push(O),_.groups.set(x,C)}const g=[...S].sort(),m=g.map(O=>O===""?"value":O),I=[];for(const[,O]of h){const N=O,x=g.map(_=>{const C=N.groups.get(_)??[],v={};for(const b of l.values){const P=C.map(j=>j[b.column]);v[`${b.aggregation}(${b.column})`]=ao(P,b.aggregation)}return v});I.push({rowDims:N.row,values:x})}return{columnKeys:g,columnHeaders:m,body:I}},[l,u]);return!c||!u?o.jsx(Cs,{theme:i,accentColor:"#a371f7",cellLabel:"Pivot",cellName:e.name,description:"Pivots reshape an upstream dataframe into a rows × columns grid. Pick dimensions for rows/columns and a metric for values.",upstreamOptions:d,onPick:S=>s({upstream:S})}):o.jsxs("div",{style:{background:i.cellBg,border:`1px solid ${i.cellBorder}`,borderLeft:"3px solid #a371f7",borderRadius:6,fontFamily:i.font,overflow:"hidden"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${i.cellBorder}`,background:`${i.tableHeaderBg}60`},children:[o.jsx("span",{style:{fontSize:10,fontFamily:i.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#a371f7",background:"#a371f718",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Pivot"}),e.name&&o.jsx("span",{style:{fontSize:12,fontFamily:i.fontMono,color:i.textSecondary},children:e.name}),o.jsxs("span",{style:{fontSize:11,color:i.textMuted,fontFamily:i.fontMono},children:["· df: ",c.name]}),o.jsx("button",{onClick:()=>s({upstream:void 0}),style:{fontSize:10,background:"transparent",border:`1px solid ${i.btnBorder}`,borderRadius:3,color:i.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:i.fontMono},children:"change"})]}),!E.hasSemanticBinding&&o.jsx("div",{style:{padding:"8px 12px 0"},children:o.jsx(za,{theme:i})}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",padding:12,gap:10,borderBottom:`1px solid ${i.cellBorder}`},children:[o.jsx(Af,{label:"Rows",selected:l.rows,availableFields:f.filter(S=>!l.rows.includes(S.name)),kindFor:S=>Xl(E,S),theme:i,onAdd:S=>A({...l,rows:[...l.rows,S]}),onRemove:S=>A({...l,rows:l.rows.filter(h=>h!==S)})}),o.jsx(Af,{label:"Columns",selected:l.columns,availableFields:f.filter(S=>!l.columns.includes(S.name)),kindFor:S=>Xl(E,S),theme:i,onAdd:S=>A({...l,columns:[...l.columns,S]}),onRemove:S=>A({...l,columns:l.columns.filter(h=>h!==S)})}),o.jsx(Wv,{values:l.values,availableFields:T,kindFor:S=>Xl(E,S),theme:i,onAdd:S=>A({...l,values:[...l.values,{column:S,aggregation:"sum"}]}),onUpdate:(S,h)=>A({...l,values:l.values.map((g,m)=>m===S?{...g,...h}:g)}),onRemove:S=>A({...l,values:l.values.filter((h,g)=>g!==S)})})]}),o.jsx("div",{style:{padding:12,overflowX:"auto"},children:!R||R.body.length===0?o.jsx("div",{style:{fontSize:11,color:i.textMuted,fontFamily:i.font},children:"Pick at least one row/column dimension and one value to see a preview."}):o.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontFamily:i.fontMono,fontSize:11},children:[o.jsx("thead",{children:o.jsxs("tr",{children:[l.rows.map(S=>o.jsx("th",{style:{textAlign:"left",padding:"4px 8px",borderBottom:`1px solid ${i.cellBorder}`,color:i.textSecondary,fontWeight:600},children:S},S)),R.columnHeaders.map((S,h)=>o.jsx("th",{style:{textAlign:"right",padding:"4px 8px",borderBottom:`1px solid ${i.cellBorder}`,color:i.textSecondary,fontWeight:600},children:S},h))]})}),o.jsx("tbody",{children:R.body.slice(0,50).map((S,h)=>o.jsxs("tr",{children:[l.rows.map(g=>o.jsx("td",{style:{padding:"3px 8px",color:i.textPrimary,borderBottom:`1px solid ${i.cellBorder}30`},children:String(S.rowDims[g]??"")},g)),S.values.map((g,m)=>o.jsx("td",{style:{padding:"3px 8px",color:i.textPrimary,textAlign:"right",borderBottom:`1px solid ${i.cellBorder}30`},children:Object.values(g).map((I,O)=>o.jsx("div",{children:I===null?"—":typeof I=="number"?I.toLocaleString(void 0,{maximumFractionDigits:2}):String(I)},O))},m))]},h))})]})})]})}function Af({label:e,selected:t,availableFields:n,kindFor:r,theme:s,onAdd:i,onRemove:a}){return o.jsx(rA,{label:e,theme:s,availableFields:n,onAdd:i,children:t.length===0?o.jsx("span",{style:{fontSize:11,color:s.textMuted,fontFamily:s.font},children:"+ add field"}):t.map(l=>{const c=r(l);return o.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 6px",background:`${s.accent}14`,border:`1px solid ${s.accent}55`,borderRadius:3,fontSize:11,fontFamily:s.fontMono,color:s.textPrimary,margin:2},children:[o.jsx("span",{style:{color:ss(c,s.accent),fontWeight:700},children:os(c)}),l,o.jsx("span",{onClick:()=>a(l),style:{cursor:"pointer",color:s.textMuted,fontSize:10},title:"Remove",children:"✕"})]},l)})})}function Wv({values:e,availableFields:t,kindFor:n,theme:r,onAdd:s,onUpdate:i,onRemove:a}){return o.jsx(rA,{label:"Values",theme:r,availableFields:t,onAdd:s,children:e.length===0?o.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font},children:"+ add value"}):e.map((l,c)=>{const d=n(l.column);return o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,margin:2},children:[o.jsx("select",{value:l.aggregation,onChange:u=>i(c,{aggregation:u.target.value}),style:{background:r.editorBg,border:`1px solid ${r.cellBorder}`,borderRadius:3,color:r.textSecondary,fontSize:10,fontFamily:r.fontMono,padding:"1px 4px"},children:Fv.map(u=>o.jsx("option",{value:u,children:u},u))}),o.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 6px",background:`${r.accent}14`,border:`1px solid ${r.accent}55`,borderRadius:3,fontSize:11,fontFamily:r.fontMono,color:r.textPrimary},children:[o.jsx("span",{style:{color:ss(d,r.accent),fontWeight:700},children:os(d)}),l.column,o.jsx("span",{onClick:()=>a(c),style:{cursor:"pointer",color:r.textMuted,fontSize:10},children:"✕"})]})]},c)})})}function rA({label:e,theme:t,availableFields:n,onAdd:r,children:s}){const[i,a]=p.useState(!1),l=p.useRef(null);return p.useEffect(()=>{if(!i)return;const c=d=>{var u;(u=l.current)!=null&&u.contains(d.target)||a(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[i]),o.jsxs("div",{ref:l,style:{position:"relative",display:"flex",flexDirection:"column",gap:4},children:[o.jsx("div",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.1em",color:t.textMuted,textTransform:"uppercase",fontFamily:t.font},children:e}),o.jsx("div",{onClick:()=>a(c=>!c),style:{minHeight:42,border:`1px dashed ${t.cellBorder}`,borderRadius:4,padding:4,cursor:"pointer",display:"flex",flexWrap:"wrap",alignItems:"center"},children:s}),i&&n.length>0&&o.jsx("div",{style:{position:"absolute",top:"calc(100% + 2px)",left:0,right:0,zIndex:10,background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:6,boxShadow:"0 6px 16px rgba(0,0,0,0.25)",padding:4,maxHeight:200,overflow:"auto"},children:n.map(c=>o.jsxs("button",{onClick:()=>{r(c.name),a(!1)},style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 8px",background:"transparent",border:"none",borderRadius:3,cursor:"pointer",textAlign:"left",color:t.textPrimary,fontFamily:t.fontMono,fontSize:11},onMouseEnter:d=>{d.currentTarget.style.background=t.tableRowHover},onMouseLeave:d=>{d.currentTarget.style.background="transparent"},children:[o.jsx("span",{style:{color:ss(c.kind,t.accent),fontWeight:700,width:12},children:os(c.kind)}),o.jsx("span",{children:c.name})]},c.name))})]})}const ai="#79c0ff";function Yv({cell:e,cells:t,index:n,themeMode:r,onUpdate:s}){const i=ce[r],a=e.tableConfig??{},l=p.useMemo(()=>{const f=e.upstream??a.upstream;if(f)return t.find(T=>T.name===f)},[e.upstream,a.upstream,t]),c=p.useMemo(()=>t.slice(0,n).filter(f=>f.name&&f.result),[t,n]),d=l==null?void 0:l.result,u=a.visibleColumns,E=p.useMemo(()=>{if(!d)return;if(!u||u.length===0)return d;const f=new Set(d.columns),T=u.filter(A=>f.has(A));return T.length===0?d:{...d,columns:T}},[d,u]);return!l||!E?o.jsx(Cs,{theme:i,accentColor:ai,cellLabel:"Table",cellName:e.name,description:"Renders an upstream dataframe — the rows of a named SQL, DQL, or Block cell above — as a sortable, exportable table. Use visibleColumns in tableConfig to pin a subset.",upstreamOptions:c,onPick:f=>s({upstream:f})}):o.jsxs("div",{style:{display:"flex",flexDirection:"column",background:i.cellBg,border:`1px solid ${i.cellBorder}`,borderLeft:`3px solid ${ai}`,borderRadius:6,overflow:"hidden",fontFamily:i.font},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${i.cellBorder}`,background:`${i.tableHeaderBg}60`},children:[o.jsx("span",{style:{fontSize:10,fontFamily:i.fontMono,fontWeight:700,letterSpacing:"0.08em",color:ai,background:`${ai}18`,padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Table"}),e.name&&o.jsx("span",{style:{fontSize:12,fontFamily:i.fontMono,color:i.textSecondary},children:e.name}),o.jsxs("span",{style:{fontSize:11,color:i.textMuted,fontFamily:i.fontMono},children:["· df: ",e.upstream??a.upstream]}),o.jsx("button",{onClick:()=>s({upstream:void 0}),title:"Change upstream dataframe",style:{fontSize:10,background:"transparent",border:`1px solid ${i.btnBorder}`,borderRadius:3,color:i.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:i.fontMono},children:"change"}),o.jsx("div",{style:{flex:1}}),o.jsxs("span",{style:{fontSize:11,color:i.textMuted,fontFamily:i.fontMono},children:[E.rows.length.toLocaleString()," rows · ",E.columns.length," cols"]})]}),o.jsx(Rn,{result:E,themeMode:r})]})}async function oA(e,t){const n=await fetch("/api/llm/run",{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify({provider:e.provider,messages:e.messages,upstream:e.upstream}),signal:e.signal});if(!n.ok){const a=await n.text().catch(()=>n.statusText);throw new Error(a||`HTTP ${n.status}`)}if(!n.body)throw new Error("Response has no body");const r=n.body.getReader(),s=new TextDecoder;let i="";try{for(;;){const{value:a,done:l}=await r.read();if(l)break;i+=s.decode(a,{stream:!0});let c;for(;(c=i.indexOf(`
|
|
628
|
+
|
|
629
|
+
`))!==-1;){const d=i.slice(0,c);i=i.slice(c+2);const u=d.split(`
|
|
630
|
+
`).find(E=>E.startsWith("data: "));if(u)try{t(JSON.parse(u.slice(6)))}catch{}}}}finally{r.releaseLock()}}function li(){return o.jsx("span",{style:{color:"#ff7b72",marginLeft:2},children:"*"})}function Kl(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function $v(e){const t=new Set,n=/@(metric|dim)\(([^)]+)\)/gi;let r;for(;r=n.exec(e);)t.add(r[2].trim());return Array.from(t)}function sA({cell:e,onClose:t,onSaved:n,initialContent:r,initialName:s,initialDescription:i,initialTags:a}){const{state:l,dispatch:c}=Re(),d=ce[l.themeMode],u=p.useRef(null),[E,f]=p.useState(s||e.name||"new_block"),[T,A]=p.useState(""),[R,S]=p.useState(""),[h,g]=p.useState(i??l.notebookMetadata.description??""),[m,I]=p.useState((a??l.notebookMetadata.categories??[]).join(", ")),[O,N]=p.useState(r??e.content),[x,_]=p.useState(""),[C,v]=p.useState(""),[b,P]=p.useState([]),[j,L]=p.useState(!1),[B,M]=p.useState(null),U=p.useMemo(()=>$v(O),[O]),D=p.useMemo(()=>m.split(",").map(Y=>Y.trim()).filter(Boolean),[m]),y=[{id:"has-name",label:"Block has name",severity:"error",passed:!!E.trim()},{id:"has-description",label:"Block has description",severity:"error",passed:!!h.trim()},{id:"has-owner",label:"Block has owner",severity:"error",passed:!!R.trim()},{id:"has-domain",label:"Block has domain",severity:"error",passed:!!T.trim()},{id:"has-tags",label:"Has at least one tag",severity:"warning",passed:D.length>0},{id:"has-llm-context",label:"Has LLM context (for agents)",severity:"warning",passed:!!x.trim()}],w=y.some(Y=>Y.severity==="error"&&!Y.passed);p.useEffect(()=>{var Y;(Y=u.current)==null||Y.focus()},[]),p.useEffect(()=>{const Y=te=>{te.key==="Escape"&&t()};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[t]);const F=l.semanticLayer.domains,k=`${T.trim()?`blocks/${Kl(T)}/`:"blocks/"}${Kl(E)||"new-block"}.dql`,V=async()=>{var Y;if(w){M("Fix the required governance fields before saving.");return}if(!O.trim()){M("Block content is required.");return}L(!0),M(null);try{const te=C.split(`
|
|
631
|
+
`).map(ae=>ae.trim()).filter(Boolean),ne=b.map(ae=>({question:ae.question.trim(),sql:ae.sql.trim()||void 0})).filter(ae=>ae.question),z=await $.saveAsBlock({cellId:e.id,notebookPath:((Y=l.activeFile)==null?void 0:Y.path)??null,name:E.trim(),domain:T.trim()||void 0,owner:R.trim()||void 0,content:O,description:h.trim()||void 0,tags:D,metricRefs:U,llmContext:x.trim()||void 0,examples:ne.length>0?ne:void 0,invariants:te.length>0?te:void 0}),oe={name:`${Kl(E)||"new-block"}.dql`,path:z.path,type:"block",folder:"blocks"};l.files.some(ae=>ae.path===z.path)||c({type:"FILE_ADDED",file:oe});const le=await $.openBlockStudio(z.path);c({type:"OPEN_BLOCK_STUDIO",file:oe,payload:le}),n==null||n({...z,name:E.trim()}),t()}catch(te){M(te instanceof Error?te.message:String(te))}finally{L(!1)}},ee={width:"100%",background:d.inputBg,border:`1px solid ${B?d.error:d.inputBorder}`,borderRadius:6,color:d.textPrimary,fontSize:13,fontFamily:d.font,padding:"8px 12px",outline:"none",boxSizing:"border-box"};return o.jsx("div",{onClick:Y=>{Y.target===Y.currentTarget&&t()},style:{position:"fixed",inset:0,background:d.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1100,backdropFilter:"blur(4px)"},children:o.jsxs("div",{style:{width:760,maxWidth:"calc(100vw - 48px)",maxHeight:"calc(100vh - 48px)",overflow:"auto",background:d.modalBg,border:`1px solid ${d.cellBorder}`,borderRadius:12,boxShadow:"0 20px 60px rgba(0,0,0,0.5)"},children:[o.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsx("h2",{style:{margin:0,fontSize:16,fontWeight:600,color:d.textPrimary,fontFamily:d.font},children:"Save as Block"}),o.jsx("button",{onClick:t,style:{background:"transparent",border:"none",color:d.textMuted,cursor:"pointer",fontSize:18},children:"×"})]}),o.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:16},children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[o.jsxs("label",{style:{fontSize:12,color:d.textSecondary,fontFamily:d.font},children:["Block Name ",o.jsx(li,{})]}),o.jsx("input",{ref:u,value:E,onChange:Y=>f(Y.target.value),style:ee})]}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[o.jsxs("label",{style:{fontSize:12,color:d.textSecondary,fontFamily:d.font},children:["Domain ",o.jsx(li,{})]}),o.jsx("input",{value:T,onChange:Y=>A(Y.target.value),list:"semantic-domain-options",style:ee,placeholder:"finance"}),o.jsx("datalist",{id:"semantic-domain-options",children:F.map(Y=>o.jsx("option",{value:Y},Y))})]})]}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[o.jsxs("label",{style:{fontSize:12,color:d.textSecondary,fontFamily:d.font},children:["Owner ",o.jsx(li,{})]}),o.jsx("input",{value:R,onChange:Y=>S(Y.target.value),style:ee,placeholder:"data-platform@company.com"})]}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[o.jsx("label",{style:{fontSize:12,color:d.textSecondary,fontFamily:d.font},children:"Tags"}),o.jsx("input",{value:m,onChange:Y=>I(Y.target.value),style:ee,placeholder:"revenue, dashboard"})]})]}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[o.jsxs("label",{style:{fontSize:12,color:d.textSecondary,fontFamily:d.font},children:["Description ",o.jsx(li,{})]}),o.jsx("input",{value:h,onChange:Y=>g(Y.target.value),style:ee})]}),o.jsxs("details",{style:{border:`1px solid ${d.cellBorder}`,borderRadius:6,padding:"8px 12px"},children:[o.jsx("summary",{style:{fontSize:12,fontWeight:600,color:d.textSecondary,fontFamily:d.font,cursor:"pointer"},children:"Agent-facing metadata (optional — helps AI tools ground answers on this block)"}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10,paddingTop:10},children:[o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[o.jsx("label",{style:{fontSize:12,color:d.textSecondary,fontFamily:d.font},children:"How should an AI describe this block?"}),o.jsx("textarea",{value:x,onChange:Y=>_(Y.target.value),rows:3,placeholder:'One paragraph. E.g. "Monthly revenue recognized from closed-won deals, grouped by billing month. Excludes refunds."',style:{...ee,fontFamily:d.font,lineHeight:1.5,resize:"vertical"}})]}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[o.jsx("label",{style:{fontSize:12,color:d.textSecondary,fontFamily:d.font},children:"Invariants (one per line)"}),o.jsx("textarea",{value:C,onChange:Y=>v(Y.target.value),rows:2,placeholder:`Revenue is never negative
|
|
632
|
+
Each row is a unique month`,style:{...ee,fontFamily:d.fontMono,lineHeight:1.5,resize:"vertical"}})]}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[o.jsx("label",{style:{fontSize:12,color:d.textSecondary,fontFamily:d.font},children:"Example questions (grounding for chat cells)"}),b.map((Y,te)=>o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr auto",gap:6},children:[o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[o.jsx("input",{value:Y.question,onChange:ne=>{const z=[...b];z[te]={...z[te],question:ne.target.value},P(z)},placeholder:"What was revenue last month?",style:ee}),o.jsx("input",{value:Y.sql,onChange:ne=>{const z=[...b];z[te]={...z[te],sql:ne.target.value},P(z)},placeholder:"Optional SQL snippet",style:{...ee,fontFamily:d.fontMono,fontSize:12}})]}),o.jsx("button",{type:"button",onClick:()=>P(b.filter((ne,z)=>z!==te)),style:{background:"transparent",border:`1px solid ${d.cellBorder}`,borderRadius:6,color:d.textMuted,cursor:"pointer",fontSize:12,padding:"0 10px"},children:"×"})]},te)),o.jsx("button",{type:"button",onClick:()=>P([...b,{question:"",sql:""}]),style:{alignSelf:"flex-start",background:d.btnBg,border:`1px solid ${d.btnBorder}`,borderRadius:6,color:d.textSecondary,cursor:"pointer",fontSize:12,fontFamily:d.font,padding:"4px 10px"},children:"+ Add example"})]})]})]}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,padding:"10px 12px",background:d.pillBg,borderRadius:6,border:`1px solid ${d.cellBorder}`},children:[o.jsx("div",{style:{fontSize:11,fontWeight:700,color:d.textSecondary,fontFamily:d.font,letterSpacing:"0.06em",textTransform:"uppercase"},children:"Governance checks"}),o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:y.map(Y=>{const te=Y.passed?"#3fb950":Y.severity==="error"?"#ff7b72":"#e3b341",ne=Y.passed?"✓":Y.severity==="error"?"✕":"!";return o.jsxs("span",{title:Y.passed?`${Y.label} — passed`:`${Y.label} — ${Y.severity}`,style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,fontFamily:d.font,color:te,background:`${te}18`,border:`1px solid ${te}55`,borderRadius:999,padding:"2px 10px"},children:[o.jsx("span",{style:{fontWeight:700},children:ne}),Y.label]},Y.id)})})]}),o.jsx("div",{style:{fontSize:12,color:d.textMuted,fontFamily:d.fontMono,padding:"8px 12px",background:d.pillBg,borderRadius:6},children:k}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[o.jsx("label",{style:{fontSize:12,color:d.textSecondary,fontFamily:d.font},children:"Content Preview"}),o.jsx("textarea",{value:O,onChange:Y=>N(Y.target.value),style:{...ee,minHeight:220,resize:"vertical",fontFamily:d.fontMono,lineHeight:1.5}})]}),U.length>0&&o.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,padding:"10px 12px",background:d.pillBg,borderRadius:6},children:[o.jsx("span",{style:{fontSize:11,color:d.textMuted,fontFamily:d.font},children:"Detected semantic refs:"}),U.map(Y=>o.jsx("span",{style:{fontSize:11,color:d.accent,fontFamily:d.fontMono,background:`${d.accent}18`,borderRadius:999,padding:"2px 8px"},children:Y},Y))]}),B&&o.jsx("div",{style:{fontSize:12,color:d.error,fontFamily:d.font},children:B})]}),o.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${d.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[o.jsx("button",{onClick:t,style:{background:d.btnBg,border:`1px solid ${d.btnBorder}`,borderRadius:6,color:d.textSecondary,cursor:"pointer",fontSize:13,fontFamily:d.font,padding:"7px 16px"},children:"Cancel"}),o.jsx("button",{onClick:V,disabled:j||w,title:w?"Fix governance errors to enable Save":void 0,style:{background:d.accent,border:`1px solid ${d.accent}`,borderRadius:6,color:"#fff",cursor:j||w?"not-allowed":"pointer",fontSize:13,fontFamily:d.font,padding:"7px 20px",opacity:j||w?.5:1},children:j?"Saving...":"Save Block"})]})]})})}function Iu(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if(n.kind!=="tool_result"||n.id!=="governed_answer")continue;const r=n.output;if(r&&typeof r=="object"&&"kind"in r)return r}return null}function Vv(e){const t=e.result;if(!t||!Array.isArray(t.rows))return null;const r=(Array.isArray(t.columns)?t.columns:[]).map(i=>typeof i=="string"?i:i&&typeof i=="object"&&typeof i.name=="string"?String(i.name):String(i)),s=t.rows.filter(i=>!!(i&&typeof i=="object"&&!Array.isArray(i))).map(i=>i);return{columns:r,rows:s,rowCount:typeof t.rowCount=="number"?t.rowCount:s.length,executionTime:t.executionTime}}function zv(e,t){const n=e&&typeof e=="object"?e:{},r=typeof n.chart=="string"?n.chart:typeof t.suggestedViz=="string"?t.suggestedViz:void 0;return{...r?{chart:r}:{},...typeof n.x=="string"?{x:n.x}:{},...typeof n.y=="string"?{y:n.y}:{},...typeof n.color=="string"?{color:n.color}:{},...typeof n.title=="string"?{title:n.title}:{}}}function Ou({answer:e,themeMode:t,showSql:n=!0,compact:r=!1,addToAppTarget:s}){var L,B,M,U,D,y,w,F,k;const i=ce[t],a=Vv(e),l=zv((L=e.result)==null?void 0:L.chartConfig,e),c=!!(a&&pr(a,l)!=="table"),d=n?e.sql??((B=e.result)==null?void 0:B.sql)??e.proposedSql:void 0,u=((M=e.result)==null?void 0:M.blockPath)??((U=e.block)==null?void 0:U.sourcePath),E=!!(d||n&&u),f=!!e.evidence,[T,A]=p.useState("answer"),[R,S]=p.useState(!1),h=e.certification==="certified"?"Certified":e.kind==="no_answer"?"No answer":"AI generated",g=e.certification==="certified"?"#3fb950":e.kind==="no_answer"?"#ff7b72":"#f0883e",m=(e.answer??e.text??"").replace(/\n\n_Question:_[\s\S]*$/m,"").trim(),I=((D=e.result)==null?void 0:D.blockName)??((y=e.block)==null?void 0:y.name)??((F=(w=e.citations)==null?void 0:w.find(V=>V.kind==="block"))==null?void 0:F.name),[O,N]=p.useState(!1),[x,_]=p.useState(null),C=!!(s&&(a||d||m||I)),v=async(V="auto")=>{if(!s)return;const ee=V==="both"?["chart","data"]:V==="data"?["data"]:V==="chart"?["chart"]:a?[c?"chart":"data"]:[];N(!0),S(!1),_(null);try{if(e.certification==="certified"&&I){const Y=await $.getDashboard(s.appId,s.dashboardId);if(!Y)throw new Error("Dashboard could not be loaded.");const te=[...Y.dashboard.layout.items],ne=ee.length>0?ee:["chart"];for(const le of ne){const ae=ne.length>1?`${I}_${le}`:I,X={...Y.dashboard,layout:{...Y.dashboard.layout,items:te}},H=rD(X,ae);te.push({i:H,...nD(X),block:{blockId:I},viz:{type:le==="data"?"table":oD(l==null?void 0:l.chart)},title:ne.length>1?`${I} ${le==="data"?"data":"chart"}`:I})}const z={...Y.dashboard.layout,items:te},oe=await $.patchDashboardLayout(s.appId,s.dashboardId,z);if(!oe.ok)throw new Error(oe.error);_(ne.length>1?"Added certified chart and data tiles.":"Added certified block tile.")}else{const Y=!!(d&&window.confirm("Keep this AI result refreshed daily?")),te=I??(m.slice(0,60)||"AI result"),ne=ee.length>0?ee:["data"];for(const z of ne){const oe=z==="data"?{...l??{},chart:"table",title:`${te} data`}:l,le=await $.createAiPin(s.appId,{dashboardId:s.dashboardId,title:ne.length>1?`${te} ${z==="data"?"data":"chart"}`:te,answer:m||e.answer||e.text||"AI generated answer",sql:d,sourceTier:e.sourceTier,certification:e.certification==="certified"?"certified":"ai_generated",refreshCadence:Y?"daily":"none",chartConfig:oe,result:a??void 0,citations:e.citations});if(!le.ok)throw new Error(le.error)}_(ne.length>1?"Pinned chart and data tiles for review.":"Pinned AI result for review.")}window.dispatchEvent(new CustomEvent("dql-app-dashboard-updated",{detail:s}))}catch(Y){_(Y instanceof Error?Y.message:String(Y))}finally{N(!1)}},P=[{id:"answer",label:"Answer",visible:!0},{id:"visual",label:r?"Chart":"Visualization",visible:c},{id:"data",label:"Data",visible:!!a},{id:"lineage",label:"Lineage",visible:f},{id:"context",label:r?"Context":"Business Context",visible:f},{id:"sql",label:"SQL / Block",visible:n&&E},{id:"review",label:"Review",visible:f||!!((k=e.citations)!=null&&k.length)}].filter(V=>V.visible),j=P.some(V=>V.id===T)?T:"answer";return o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:r?8:10,whiteSpace:"normal"},children:[o.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[o.jsx("span",{style:{fontSize:10,fontFamily:i.fontMono,fontWeight:700,letterSpacing:"0.08em",color:g,textTransform:"uppercase",padding:"2px 6px",borderRadius:3,background:`${g}18`,border:`1px solid ${g}40`},children:h}),I&&o.jsxs("span",{style:{fontSize:12,fontFamily:i.fontMono,color:i.textSecondary},children:["block: ",I]}),a&&o.jsxs("span",{style:{fontSize:12,color:i.textMuted},children:[(a.rowCount??a.rows.length).toLocaleString()," rows",a.executionTime!==void 0&&o.jsxs(o.Fragment,{children:[" - ",Math.round(a.executionTime),"ms"]})]}),C&&o.jsx(eD,{t:i,adding:O,hasResult:!!a,hasChart:c,fallbackLabel:e.certification==="certified"&&I?"Add block":"Add summary",open:R,onToggle:()=>S(V=>!V),onAdd:V=>void v(V)})]}),x&&o.jsx("div",{style:{fontSize:11,color:x.toLowerCase().includes("added")||x.toLowerCase().includes("pinned")?"#3fb950":"#ff7b72"},children:x}),o.jsxs("div",{style:{border:`1px solid ${i.cellBorder}`,borderRadius:6,overflow:"hidden",background:i.cellBg},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px",borderBottom:`1px solid ${i.cellBorder}`,background:`${i.tableHeaderBg}70`,flexWrap:"wrap"},children:[P.map(V=>o.jsx(Zv,{active:j===V.id,label:V.label,onClick:()=>A(V.id),t:i},V.id)),!n&&u&&o.jsx("span",{style:{marginLeft:"auto",minWidth:0,fontSize:11,fontFamily:i.fontMono,color:i.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:u})]}),j==="answer"&&o.jsx(Xv,{summary:m,evidence:e.evidence,result:a,sourceTier:e.sourceTier,compact:r,t:i}),j==="visual"&&a&&c&&o.jsx("div",{style:{padding:r?"8px 10px":"10px 12px",minHeight:r?180:220},children:o.jsx($a,{result:a,themeMode:t,chartConfig:l})}),j==="data"&&a&&o.jsx("div",{style:{maxHeight:r?320:420,overflow:"auto"},children:o.jsx(Rn,{result:a,themeMode:t})}),j==="lineage"&&o.jsx(Kv,{evidence:e.evidence,t:i}),j==="context"&&o.jsx(qv,{evidence:e.evidence,t:i}),j==="sql"&&n&&E&&o.jsx(Qv,{sql:d,blockPath:u,t:i}),j==="review"&&o.jsx(Jv,{answer:e,t:i})]})]})}function Xv({summary:e,evidence:t,result:n,sourceTier:r,compact:s,t:i}){var a,l;return o.jsxs("div",{style:{padding:s?14:12,display:"flex",flexDirection:"column",gap:s?10:12},children:[e?o.jsx("div",{style:{fontSize:s?13.5:13,lineHeight:1.55,color:i.textPrimary,whiteSpace:"pre-wrap"},children:e}):o.jsx("div",{style:{fontSize:12,color:i.textMuted},children:"No summary text was returned."}),o.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[r&&o.jsx(Dn,{label:Sr(r),t:i}),n&&o.jsx(Dn,{label:`${(n.rowCount??n.rows.length).toLocaleString()} rows`,t:i}),((a=t==null?void 0:t.validation)==null?void 0:a.status)&&o.jsx(Dn,{label:`validation: ${t.validation.status}`,t:i}),((l=t==null?void 0:t.execution)==null?void 0:l.status)&&o.jsx(Dn,{label:`execution: ${t.execution.status}`,t:i})]}),!s&&(t==null?void 0:t.route)&&t.route.length>0&&o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[o.jsx(is,{t:i,children:"Route"}),t.route.map((c,d)=>o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"120px 1fr",gap:10,fontSize:12,alignItems:"baseline"},children:[o.jsx("span",{style:{fontFamily:i.fontMono,color:tD(c.status),minWidth:0},children:c.tool??"step"}),o.jsxs("span",{style:{color:i.textSecondary},children:[c.label??c.status,c.detail&&o.jsxs("span",{style:{color:i.textMuted},children:[" (",c.detail,")"]})]})]},`${c.tool}-${d}`))]}),(t==null?void 0:t.selectedAssets)&&t.selectedAssets.length>0&&o.jsx(Ed,{title:"Selected Assets",assets:t.selectedAssets,t:i})]})}function Kv({evidence:e,t}){const n=(e==null?void 0:e.lineage)??[];return n.length===0?o.jsx(iA,{t,children:"No lineage evidence was returned for this answer."}):o.jsx("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:10},children:n.map((r,s)=>o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"20px 1fr",gap:8},children:[o.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center"},children:[o.jsx("div",{style:{width:8,height:8,borderRadius:8,marginTop:5,background:r.role==="question"?t.accent:t.textMuted}}),s<n.length-1&&o.jsx("div",{style:{width:1,flex:1,minHeight:18,background:t.cellBorder}})]}),o.jsxs("div",{style:{minWidth:0},children:[o.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center",flexWrap:"wrap"},children:[o.jsx("span",{style:{fontSize:12,fontWeight:700,color:t.textPrimary},children:r.name??r.nodeId}),r.role&&o.jsx(Dn,{label:Sr(r.role),t}),r.kind&&o.jsx(Dn,{label:Sr(r.kind),t})]}),r.description&&o.jsx("div",{style:{fontSize:12,color:t.textSecondary,marginTop:3},children:r.description}),(r.sourcePath||r.provenance)&&o.jsxs("div",{style:{fontSize:11,color:t.textMuted,fontFamily:t.fontMono,marginTop:3,overflow:"hidden",textOverflow:"ellipsis"},children:[r.provenance??r.sourcePath,r.sourcePath&&r.provenance?` - ${r.sourcePath}`:""]})]})]},`${r.nodeId??r.name}-${s}`))})}function qv({evidence:e,t}){var s;const n=(e==null?void 0:e.businessContext)??[],r=e==null?void 0:e.outcome;return!r&&n.length===0?o.jsx(iA,{t,children:"No business context was returned for this answer."}):o.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:12},children:[r&&o.jsxs("div",{style:{display:"grid",gap:6},children:[o.jsx(is,{t,children:"Outcome"}),r.name&&o.jsx(gt,{label:"Outcome",value:r.name,t}),r.owner&&o.jsx(gt,{label:"Owner",value:r.owner,t}),r.decisionUse&&o.jsx(gt,{label:"Decision Use",value:r.decisionUse,t}),r.reviewCadence&&o.jsx(gt,{label:"Review Cadence",value:r.reviewCadence,t}),(s=r.caveats)==null?void 0:s.map((i,a)=>o.jsx(gt,{label:"Caveat",value:i,t},`caveat-${a}`))]}),n.length>0&&o.jsxs("div",{style:{display:"grid",gap:6},children:[o.jsx(is,{t,children:"Context"}),n.map((i,a)=>o.jsx(gt,{label:i.label??"Context",value:i.value??"",source:i.source,t},`${i.label}-${a}`))]}),(e==null?void 0:e.semanticObjects)&&e.semanticObjects.length>0&&o.jsx(Ed,{title:"Semantic Objects",assets:e.semanticObjects,t}),(e==null?void 0:e.sourceTables)&&e.sourceTables.length>0&&o.jsx(Ed,{title:"Source Tables",assets:e.sourceTables,t})]})}function Jv({answer:e,t}){var s,i;const n=e.evidence,r=(n==null?void 0:n.citations)??e.citations??[];return o.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:12},children:[o.jsxs("div",{style:{display:"grid",gap:6},children:[o.jsx(gt,{label:"Certification",value:Sr(e.certification??e.kind),t}),e.reviewStatus&&o.jsx(gt,{label:"Review Status",value:Sr(e.reviewStatus),t}),typeof e.confidence=="number"&&o.jsx(gt,{label:"Confidence",value:`${Math.round(e.confidence*100)}%`,t}),((s=n==null?void 0:n.validation)==null?void 0:s.message)&&o.jsx(gt,{label:`Validation ${n.validation.status??""}`.trim(),value:n.validation.message,t}),((i=n==null?void 0:n.execution)==null?void 0:i.message)&&o.jsx(gt,{label:`Execution ${n.execution.status??""}`.trim(),value:n.execution.message,t}),e.kind!=="certified"&&o.jsx(gt,{label:"Promotion Path",value:"Create draft block, edit SQL, attach tests, then certify after analyst approval.",t})]}),r.length>0&&o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[o.jsx(is,{t,children:"Citations"}),r.slice(0,8).map((a,l)=>o.jsxs("div",{style:{fontSize:12,color:t.textSecondary,fontFamily:t.fontMono},children:[a.kind??"source",": ",a.name??"unknown",a.provenance&&o.jsxs("span",{style:{color:t.textMuted},children:[" (",a.provenance,")"]})]},`${a.kind}-${a.name}-${l}`))]})]})}function Ed({title:e,assets:t,t:n}){return o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[o.jsx(is,{t:n,children:e}),t.map((r,s)=>o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,paddingBottom:4},children:[o.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center",flexWrap:"wrap"},children:[o.jsx("span",{style:{fontSize:12,fontWeight:700,color:n.textPrimary},children:r.name??r.nodeId}),r.kind&&o.jsx(Dn,{label:Sr(r.kind),t:n}),r.certification&&o.jsx(Dn,{label:Sr(r.certification),t:n})]}),r.description&&o.jsx("div",{style:{fontSize:12,color:n.textSecondary},children:r.description}),(r.sourcePath||r.owner||r.domain)&&o.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.fontMono},children:[r.domain,r.owner,r.sourcePath].filter(Boolean).join(" - ")})]},`${r.nodeId??r.name}-${s}`))]})}function Qv({sql:e,blockPath:t,t:n}){return o.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:8},children:[t&&o.jsxs("div",{style:{fontSize:12,color:n.textSecondary},children:["Source block: ",o.jsx("span",{style:{fontFamily:n.fontMono,color:n.textPrimary},children:t})]}),e?o.jsx("pre",{style:{margin:0,padding:10,overflow:"auto",maxHeight:260,borderRadius:4,background:n.editorBg,color:n.textPrimary,border:`1px solid ${n.cellBorder}`,fontSize:12,fontFamily:n.fontMono,whiteSpace:"pre"},children:e}):o.jsx("div",{style:{fontSize:12,color:n.textMuted},children:"No SQL text was returned for this answer."})]})}function gt({label:e,value:t,source:n,t:r}){return t?o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"130px 1fr",gap:10,fontSize:12,alignItems:"baseline"},children:[o.jsx("span",{style:{color:r.textMuted},children:e}),o.jsxs("span",{style:{color:r.textSecondary},children:[t,n&&o.jsxs("span",{style:{color:r.textMuted},children:[" (",n,")"]})]})]}):null}function is({children:e,t}){return o.jsx("div",{style:{fontSize:11,fontWeight:700,fontFamily:t.fontMono,color:t.textMuted,textTransform:"uppercase",letterSpacing:"0.08em"},children:e})}function iA({children:e,t}){return o.jsx("div",{style:{padding:12,fontSize:12,color:t.textMuted},children:e})}function Dn({label:e,t}){return o.jsx("span",{style:{fontSize:11,fontFamily:t.fontMono,color:t.textSecondary,padding:"2px 6px",borderRadius:4,background:t.editorBg,border:`1px solid ${t.cellBorder}`},children:e})}function Zv({active:e,label:t,onClick:n,t:r}){return o.jsx("button",{onClick:n,style:{padding:"3px 8px",fontSize:11,borderRadius:4,border:`1px solid ${e?r.accent:r.btnBorder}`,background:e?`${r.accent}18`:"transparent",color:e?r.accent:r.textSecondary,cursor:"pointer"},children:t})}function eD({t:e,adding:t,hasResult:n,hasChart:r,fallbackLabel:s,open:i,onToggle:a,onAdd:l}){if(!n)return o.jsx("button",{type:"button",onClick:()=>l("auto"),disabled:t,style:{...mf(e,t),marginLeft:"auto"},children:t?"Adding...":s});const c=r?[{mode:"both",label:"Chart + data",description:"Add chart and table tiles"},{mode:"chart",label:"Chart only",description:"Add the visualization tile"},{mode:"data",label:"Data table",description:"Add the rows as a table tile"}]:[{mode:"data",label:"Data table",description:"Add the rows as a table tile"}];return o.jsxs("div",{style:{marginLeft:"auto",position:"relative"},children:[o.jsxs("button",{type:"button",onClick:a,disabled:t,style:mf(e,t),children:[t?"Adding...":"Add to App",!t&&o.jsx("span",{style:{marginLeft:6,fontSize:10},children:"v"})]}),i&&!t&&o.jsx("div",{style:{position:"absolute",right:0,top:"calc(100% + 6px)",zIndex:30,width:190,border:`1px solid ${e.cellBorder}`,borderRadius:8,background:e.cellBg,boxShadow:"0 14px 34px rgba(0, 0, 0, 0.18)",padding:6},children:c.map(d=>o.jsxs("button",{type:"button",onClick:()=>l(d.mode),style:{width:"100%",border:0,borderRadius:6,background:"transparent",color:e.textPrimary,textAlign:"left",padding:"8px 9px",cursor:"pointer"},children:[o.jsx("div",{style:{fontSize:12,fontWeight:700},children:d.label}),o.jsx("div",{style:{fontSize:11,color:e.textMuted,marginTop:2},children:d.description})]},d.mode))})]})}function mf(e,t){return{border:`1px solid ${e.btnBorder}`,borderRadius:5,background:t?e.editorBg:`${e.accent}18`,color:t?e.textMuted:e.accent,padding:"4px 8px",fontSize:11,cursor:t?"default":"pointer"}}function Sr(e){return e.replace(/_/g," ")}function tD(e){return e==="selected"||e==="passed"||e==="executed"?"#3fb950":e==="failed"?"#ff7b72":e==="warning"||e==="checked"?"#f0883e":"#8b949e"}function nD(e){return{x:0,y:e.layout.items.reduce((n,r)=>Math.max(n,r.y+r.h),0),w:6,h:3}}function rD(e,t){const n=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"tile",r=new Set(e.layout.items.map(s=>s.i));if(!r.has(n))return n;for(let s=2;s<1e3;s++){const i=`${n}-${s}`;if(!r.has(i))return i}return`${n}-${Date.now()}`}function oD(e){const t=String(e??"table").toLowerCase().replace(/-/g,"_");return t==="single_value"||t==="kpi"||t==="line"||t==="bar"||t==="area"||t==="pie"||t==="pivot"||t==="map"||t==="funnel"?t:"table"}function gf(){return`m_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function sD(e,t,n){if(n){const r=e.find(s=>s.name===n);if(r!=null&&r.content)return r.content}for(let r=t-1;r>=0;r--){const s=e[r];if((s.type==="sql"||s.type==="dql")&&s.content)return s.content}}function iD({cell:e,cells:t,index:n,themeMode:r,onUpdate:s}){const{dispatch:i}=Re(),a=ce[r],l={history:[],...e.chatConfig},[c,d]=p.useState(""),[u,E]=p.useState(!1),[f,T]=p.useState(""),[A,R]=p.useState([]),[S,h]=p.useState(null),[g,m]=p.useState(!1),I=p.useRef(null),O=v=>{s({chatConfig:{...l,...v}})},N=async()=>{const v=c.trim();if(!v||u)return;const b={id:gf(),role:"user",content:v},P={id:gf(),role:"assistant",content:"",events:[]},j=[...l.history,b,P];O({history:j}),d(""),T(""),R([]),h(null),E(!0);const L=new AbortController;I.current=L;let B="";const M=[];let U;try{await oA({messages:[...l.history,b].map(D=>({role:D.role,content:D.content})),upstream:{cellId:e.id,sql:sD(t,n,l.upstream)},signal:L.signal},D=>{M.push(D),R([...M]),D.kind==="text"?(B+=D.text,T(B)):D.kind==="error"?h(D.message):D.kind==="proposal"&&(U={...D.proposal,certified:D.governance.certified,errors:D.governance.errors,warnings:D.governance.warnings})})}catch(D){h(D instanceof Error?D.message:String(D))}finally{const D=j.map(y=>y.id===P.id?{...y,content:B,events:M.map(w=>({kind:w.kind,payload:w}))}:y);s({chatConfig:{...l,history:D,lastProposal:U??l.lastProposal}}),E(!1),T(""),R([]),I.current=null}},x=()=>{var v;(v=I.current)==null||v.abort()},_=()=>{O({history:[],lastProposal:void 0})},C=l.lastProposal;return o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10,padding:"14px 16px",background:a.cellBg,fontFamily:a.font},children:[o.jsx(aD,{cell:e,onClear:l.history.length>0?_:void 0,t:a}),l.history.length===0&&!u&&o.jsx("div",{style:{fontSize:12,color:a.textSecondary,lineHeight:1.5},children:"Ask for a metric, a comparison, or a dashboard. The agent searches blocks, checks the semantic layer, and proposes a governed block when you're ready."}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[l.history.map(v=>o.jsx(lD,{msg:v,t:a,themeMode:r},v.id)),u&&o.jsx(cD,{streamingText:f,events:A,t:a,themeMode:r})]}),S&&o.jsx("div",{style:{fontSize:12,color:"#ff7b72",padding:"6px 10px",background:"#ff7b7218",borderRadius:4},children:S}),C&&o.jsx(uD,{proposal:C,t:a,onOpen:()=>m(!0),onDismiss:()=>O({lastProposal:void 0})}),o.jsx(dD,{value:c,onChange:d,onSend:N,onStop:x,running:u,t:a}),g&&C&&o.jsx(sA,{cell:e,initialContent:C.sql,initialName:C.name,initialDescription:C.description,initialTags:C.tags,onClose:()=>m(!1),onSaved:({path:v,name:b})=>{m(!1),O({lastProposal:void 0}),i({type:"FILE_ADDED",file:{name:b,path:v,type:"block",folder:"blocks"}})}})]})}function aD({cell:e,onClear:t,t:n}){return o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsx("span",{style:{fontSize:10,fontFamily:n.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#f0883e",textTransform:"uppercase",padding:"2px 6px",borderRadius:3,background:"#f0883e18"},children:"Chat"}),e.name&&o.jsx("span",{style:{fontSize:12,fontFamily:n.fontMono,color:n.textSecondary},children:e.name}),o.jsx("span",{title:"Configure the active AI provider in Settings",style:{marginLeft:"auto",fontSize:11,fontFamily:n.fontMono,color:n.textMuted},children:"Provider from Settings"}),t&&o.jsx("button",{onClick:t,style:{fontSize:11,padding:"3px 8px",background:"transparent",color:n.textSecondary,border:`1px solid ${n.cellBorder}`,borderRadius:4,cursor:"pointer"},children:"Clear"})]})}function lD({msg:e,t,themeMode:n}){const r=e.role==="user",s=(e.events??[]).map(a=>a.payload),i=r?null:Iu(s);return o.jsxs("div",{style:{padding:"8px 12px",borderRadius:6,background:r?`${t.accent}14`:t.cellBg,border:`1px solid ${r?`${t.accent}40`:t.cellBorder}`,fontSize:13,lineHeight:1.5,color:t.textPrimary,whiteSpace:"pre-wrap"},children:[o.jsx("div",{style:{fontSize:10,fontFamily:t.fontMono,color:t.textMuted,marginBottom:4,textTransform:"uppercase",letterSpacing:"0.08em"},children:r?"You":"Assistant"}),i?o.jsx(Ou,{answer:i,themeMode:n}):e.content||(s.length>0?o.jsx("em",{style:{color:t.textSecondary},children:"(tool calls only)"}):null),s.filter(a=>a.kind==="tool_call").map(a=>o.jsx(aA,{turn:a,t},`tc-${a.id}`))]})}function cD({streamingText:e,events:t,t:n,themeMode:r}){const s=Iu(t);return o.jsxs("div",{style:{padding:"8px 12px",borderRadius:6,background:n.cellBg,border:`1px solid ${n.cellBorder}`,fontSize:13,lineHeight:1.5,color:n.textPrimary,whiteSpace:"pre-wrap"},children:[o.jsxs("div",{style:{fontSize:10,fontFamily:n.fontMono,color:n.textMuted,marginBottom:4,textTransform:"uppercase",letterSpacing:"0.08em"},children:["Assistant ",o.jsx("span",{style:{color:n.accent},children:"●"})]}),s?o.jsx(Ou,{answer:s,themeMode:r}):e||o.jsx("em",{style:{color:n.textSecondary},children:"Thinking…"}),t.filter(i=>i.kind==="tool_call").map(i=>o.jsx(aA,{turn:i,t:n},`live-${i.id}`))]})}function aA({turn:e,t}){return e.kind!=="tool_call"?null:o.jsxs("div",{style:{marginTop:6,fontSize:11,fontFamily:t.fontMono,color:t.textSecondary,padding:"4px 8px",background:t.cellBorder,borderRadius:4,display:"inline-block"},children:["🔧 ",e.name,"(",JSON.stringify(e.input).slice(0,80),JSON.stringify(e.input).length>80?"…":"",")"]})}function dD({value:e,onChange:t,onSend:n,onStop:r,running:s,t:i}){return o.jsxs("div",{style:{display:"flex",gap:6,alignItems:"flex-end"},children:[o.jsx("textarea",{value:e,onChange:a=>t(a.target.value),onKeyDown:a=>{a.key==="Enter"&&(a.metaKey||a.ctrlKey)&&(a.preventDefault(),n())},placeholder:"Ask for a metric or dashboard — ⌘↵ to send",rows:2,style:{flex:1,resize:"vertical",minHeight:44,padding:"8px 10px",fontSize:13,fontFamily:i.font,background:i.cellBg,color:i.textPrimary,border:`1px solid ${i.cellBorder}`,borderRadius:6}}),s?o.jsx("button",{onClick:r,style:{padding:"8px 14px",fontSize:12,background:"#ff7b7218",color:"#ff7b72",border:"1px solid #ff7b72",borderRadius:6,cursor:"pointer"},children:"Stop"}):o.jsx("button",{onClick:n,disabled:!e.trim(),style:{padding:"8px 14px",fontSize:12,background:e.trim()?`${i.accent}28`:"transparent",color:e.trim()?i.accent:i.textMuted,border:`1px solid ${e.trim()?i.accent:i.cellBorder}`,borderRadius:6,cursor:e.trim()?"pointer":"not-allowed"},children:"Send"})]})}function uD({proposal:e,t,onOpen:n,onDismiss:r}){const s=[{id:"has-name",label:"Name",passed:!!e.name,severity:"error"},{id:"has-description",label:"Description",passed:!!e.description,severity:"error"},{id:"has-owner",label:"Owner",passed:!!e.owner,severity:"error"},{id:"has-domain",label:"Domain",passed:!!e.domain,severity:"error"},{id:"has-sql",label:"SQL",passed:!!e.sql,severity:"error"}];return o.jsxs("div",{style:{border:`1px solid ${e.certified?"#3fb950":t.cellBorder}`,borderLeft:`3px solid ${e.certified?"#3fb950":"#f0883e"}`,borderRadius:6,padding:"10px 12px",background:e.certified?"#3fb95010":"#f0883e10",display:"flex",flexDirection:"column",gap:8},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsx("span",{style:{fontSize:10,fontFamily:t.fontMono,fontWeight:700,letterSpacing:"0.08em",color:e.certified?"#3fb950":"#f0883e",textTransform:"uppercase"},children:"Block Proposal"}),o.jsx("span",{style:{fontSize:13,fontFamily:t.fontMono,color:t.textPrimary},children:e.name}),e.domain&&o.jsxs("span",{style:{fontSize:11,color:t.textSecondary},children:["· ",e.domain]}),o.jsx("button",{onClick:r,style:{marginLeft:"auto",fontSize:11,padding:"2px 6px",background:"transparent",color:t.textMuted,border:"none",cursor:"pointer"},children:"✕"})]}),o.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:s.map(i=>o.jsxs("span",{style:{fontSize:10,fontFamily:t.fontMono,padding:"2px 6px",borderRadius:3,background:i.passed?"#3fb95020":"#ff7b7220",color:i.passed?"#3fb950":"#ff7b72",border:`1px solid ${i.passed?"#3fb95040":"#ff7b7240"}`},children:[i.passed?"✓":"✕"," ",i.label]},i.id))}),e.description&&o.jsx("div",{style:{fontSize:12,color:t.textSecondary},children:e.description}),o.jsx("div",{children:o.jsx("button",{onClick:n,style:{padding:"6px 12px",fontSize:12,background:`${t.accent}28`,color:t.accent,border:`1px solid ${t.accent}`,borderRadius:4,cursor:"pointer"},children:"Review & Save as Block"})})]})}const ED=[{id:"select-all",label:"Select all rows",description:"Read all rows from a CSV file with a row limit",category:"SQL",code:"SELECT * FROM read_csv_auto('data/filename.csv') LIMIT 100"},{id:"group-by",label:"Group and aggregate",description:"Group rows and compute count + sum",category:"SQL",code:`SELECT
|
|
633
|
+
category,
|
|
634
|
+
COUNT(*) AS count,
|
|
635
|
+
SUM(amount) AS total
|
|
636
|
+
FROM read_csv_auto('data/filename.csv')
|
|
637
|
+
GROUP BY category
|
|
638
|
+
ORDER BY total DESC`},{id:"filter-date",label:"Filter by date range",description:"Filter rows between two dates",category:"SQL",code:`SELECT *
|
|
639
|
+
FROM read_csv_auto('data/filename.csv')
|
|
640
|
+
WHERE date_column >= '2024-01-01'
|
|
641
|
+
AND date_column < '2025-01-01'`},{id:"window-rank",label:"Window function: rank",description:"Rank rows within groups using ROW_NUMBER()",category:"SQL",code:`SELECT
|
|
642
|
+
*,
|
|
643
|
+
ROW_NUMBER() OVER (PARTITION BY category ORDER BY amount DESC) AS rank
|
|
644
|
+
FROM read_csv_auto('data/filename.csv')`},{id:"cte",label:"CTE (WITH clause)",description:"Define a named subquery with WITH",category:"SQL",code:`WITH base AS (
|
|
645
|
+
SELECT *
|
|
646
|
+
FROM read_csv_auto('data/filename.csv')
|
|
647
|
+
WHERE amount > 0
|
|
648
|
+
)
|
|
649
|
+
SELECT
|
|
650
|
+
category,
|
|
651
|
+
SUM(amount) AS total
|
|
652
|
+
FROM base
|
|
653
|
+
GROUP BY category`},{id:"join",label:"Join two tables",description:"Join two CSV files on a shared key",category:"SQL",code:`SELECT a.*, b.name
|
|
654
|
+
FROM read_csv_auto('data/table_a.csv') AS a
|
|
655
|
+
JOIN read_csv_auto('data/table_b.csv') AS b
|
|
656
|
+
ON a.id = b.id`},{id:"pivot",label:"Pivot / unpivot",description:"Pivot a column into multiple columns",category:"SQL",code:`SELECT *
|
|
657
|
+
FROM (
|
|
658
|
+
SELECT category, quarter, amount
|
|
659
|
+
FROM read_csv_auto('data/filename.csv')
|
|
660
|
+
) PIVOT (SUM(amount) FOR quarter IN ('Q1', 'Q2', 'Q3', 'Q4'))`},{id:"dql-block",label:"DQL block (basic)",description:"Minimal DQL block with a table visualization",category:"DQL",code:`block "My Block" {
|
|
661
|
+
domain = "analytics"
|
|
662
|
+
type = "custom"
|
|
663
|
+
description = "Describe what this block does"
|
|
664
|
+
owner = "data-team"
|
|
665
|
+
tags = ["analytics"]
|
|
666
|
+
|
|
667
|
+
query = """
|
|
668
|
+
SELECT *
|
|
669
|
+
FROM read_csv_auto('data/filename.csv')
|
|
670
|
+
LIMIT 100
|
|
671
|
+
"""
|
|
672
|
+
|
|
673
|
+
visualization {
|
|
674
|
+
chart = "table"
|
|
675
|
+
}
|
|
676
|
+
}`},{id:"dql-block-bar",label:"DQL block with bar chart",description:"DQL block with params, bar chart, and a test assertion",category:"DQL",code:`block "Revenue by Segment" {
|
|
677
|
+
domain = "revenue"
|
|
678
|
+
type = "custom"
|
|
679
|
+
description = "Revenue grouped by segment"
|
|
680
|
+
owner = "data-team"
|
|
681
|
+
tags = ["revenue"]
|
|
682
|
+
|
|
683
|
+
params {
|
|
684
|
+
period = "current_quarter"
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
query = """
|
|
688
|
+
SELECT
|
|
689
|
+
segment_tier AS segment,
|
|
690
|
+
SUM(amount) AS revenue
|
|
691
|
+
FROM read_csv_auto('data/revenue.csv')
|
|
692
|
+
WHERE fiscal_period = \${period}
|
|
693
|
+
GROUP BY segment_tier
|
|
694
|
+
ORDER BY revenue DESC
|
|
695
|
+
"""
|
|
696
|
+
|
|
697
|
+
visualization {
|
|
698
|
+
chart = "bar"
|
|
699
|
+
x = segment
|
|
700
|
+
y = revenue
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
tests {
|
|
704
|
+
assert row_count > 0
|
|
705
|
+
}
|
|
706
|
+
}`},{id:"dql-semantic-metric",label:"Semantic metric reference",description:"Reference a metric and dimension from the semantic layer in a SQL cell",category:"DQL",code:`SELECT @dim(segment), @metric(total_revenue)
|
|
707
|
+
FROM fct_revenue
|
|
708
|
+
GROUP BY @dim(segment)
|
|
709
|
+
ORDER BY @metric(total_revenue) DESC`},{id:"dql-semantic-block",label:"Semantic block (inline)",description:"DQL block that references a named metric from the semantic layer — no SQL duplication",category:"DQL",code:`block "ARR by Plan Tier" {
|
|
710
|
+
domain = "revenue"
|
|
711
|
+
type = "semantic"
|
|
712
|
+
owner = "data-team"
|
|
713
|
+
description = "Annual Recurring Revenue by subscription plan tier"
|
|
714
|
+
tags = ["arr", "revenue", "saas"]
|
|
715
|
+
|
|
716
|
+
metric = "arr"
|
|
717
|
+
dimensions = ["plan_tier"]
|
|
718
|
+
|
|
719
|
+
visualization {
|
|
720
|
+
chart = "bar"
|
|
721
|
+
x = plan_tier
|
|
722
|
+
y = arr
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
tests {
|
|
726
|
+
assert row_count > 0
|
|
727
|
+
}
|
|
728
|
+
}`},{id:"revenue-by-segment",label:"Revenue by segment",description:"Aggregate revenue totals, deal count, and average deal size per segment",category:"Analysis",code:`SELECT
|
|
729
|
+
segment_tier,
|
|
730
|
+
SUM(amount) AS total_revenue,
|
|
731
|
+
COUNT(*) AS deals,
|
|
732
|
+
ROUND(AVG(amount), 0) AS avg_deal
|
|
733
|
+
FROM read_csv_auto('data/revenue.csv')
|
|
734
|
+
GROUP BY segment_tier
|
|
735
|
+
ORDER BY total_revenue DESC`},{id:"quarterly-trend",label:"Quarterly trend",description:"Revenue totals grouped by fiscal year and quarter",category:"Analysis",code:`SELECT
|
|
736
|
+
fiscal_year || ' ' || fiscal_quarter AS period,
|
|
737
|
+
SUM(amount) AS revenue
|
|
738
|
+
FROM read_csv_auto('data/revenue.csv')
|
|
739
|
+
GROUP BY fiscal_year, fiscal_quarter
|
|
740
|
+
ORDER BY fiscal_year, fiscal_quarter`}];function fD({onInsert:e,themeMode:t,cellType:n}){const r=ce[t],[s,i]=p.useState(!1),[a,l]=p.useState(null),c=p.useRef(null),d=ED.filter(f=>n==="dql"?f.category==="DQL":f.category==="SQL"||f.category==="Analysis"),u=Array.from(new Set(d.map(f=>f.category)));p.useEffect(()=>{if(!s)return;function f(T){c.current&&!c.current.contains(T.target)&&i(!1)}return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[s]);function E(f){e(f),i(!1)}return o.jsxs("div",{ref:c,style:{position:"relative",display:"inline-block"},children:[o.jsxs("button",{title:"Insert template snippet",onClick:()=>i(f=>!f),style:{height:22,padding:"0 8px",fontSize:10,fontFamily:r.font,fontWeight:600,letterSpacing:"0.04em",color:s?r.accent:r.textMuted,background:s?`${r.accent}15`:"transparent",border:`1px solid ${s?r.accent+"50":r.btnBorder}`,borderRadius:4,cursor:"pointer",display:"flex",alignItems:"center",gap:4,transition:"all 0.15s",whiteSpace:"nowrap"},children:[o.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"})}),"Templates"]}),s&&o.jsx("div",{style:{position:"absolute",top:"calc(100% + 4px)",left:0,zIndex:300,width:300,maxHeight:360,overflowY:"auto",background:r.modalBg,border:`1px solid ${r.cellBorder}`,borderRadius:8,boxShadow:"0 8px 24px rgba(0,0,0,0.3)",padding:"6px 0"},children:u.map(f=>o.jsxs("div",{children:[o.jsx("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:700,fontFamily:r.font,letterSpacing:"0.08em",textTransform:"uppercase",color:r.textMuted},children:f}),d.filter(T=>T.category===f).map(T=>o.jsxs("button",{onMouseEnter:()=>l(T.id),onMouseLeave:()=>l(null),onClick:()=>E(T.code),style:{width:"100%",padding:"7px 12px",textAlign:"left",background:a===T.id?r.sidebarItemHover:"transparent",border:"none",cursor:"pointer",display:"flex",flexDirection:"column",gap:2,transition:"background 0.1s"},children:[o.jsx("span",{style:{fontSize:12,fontWeight:600,fontFamily:r.font,color:r.textPrimary,lineHeight:1.4},children:T.label}),o.jsx("span",{style:{fontSize:11,fontFamily:r.font,color:r.textMuted,lineHeight:1.4},children:T.description})]},T.id))]},f))})]})}function pD(e,t){var s,i,a,l;const n=e.upstream??((s=e.singleValueConfig)==null?void 0:s.upstream)??((i=e.filterConfig)==null?void 0:i.upstream)??((a=e.pivotConfig)==null?void 0:a.upstream)??((l=e.tableConfig)==null?void 0:l.upstream);if(!n)return null;const r=t.find(c=>c.name===n&&(c.type==="sql"||c.type==="dql"));return!r||!r.content.trim()?null:{name:r.name,sql:r.content.trim()}}function TD(e){if(!e||!e.chart)return"";const t=[`chart = "${e.chart}"`];return e.x&&t.push(`x = ${e.x}`),e.y&&t.push(`y = ${e.y}`),e.color&&t.push(`color = ${e.color}`),e.facet&&t.push(`facet = ${e.facet}`),`
|
|
741
|
+
visualization {
|
|
742
|
+
${t.join(`
|
|
743
|
+
`)}
|
|
744
|
+
}`}function SD(e){if(!e)return"";const t=['chart = "kpi"'];return e.metric&&t.push(`y = ${e.metric}`),e.format&&t.push(`format = "${e.format}"`),e.label&&t.push(`label = "${e.label.replace(/"/g,'\\"')}"`),`
|
|
745
|
+
visualization {
|
|
746
|
+
${t.join(`
|
|
747
|
+
`)}
|
|
748
|
+
}`}function hD(e,t){return` query = """
|
|
749
|
+
${e.replace(/^/gm," ")}
|
|
750
|
+
"""${t}`}function RD(e,t){var a,l,c,d;if(e.type==="sql"||e.type==="dql")return{content:e.content,suggestedName:e.name,derivedFromUpstream:!1,blocker:e.content.trim()?void 0:"Cell is empty — add a SQL query first."};if(e.type==="markdown"||e.type==="param"||e.type==="map"||e.type==="writeback"||e.type==="python")return{content:"",derivedFromUpstream:!1,blocker:`${e.type} cells cannot be promoted to blocks yet.`};const n=pD(e,t);if(!n)return{content:"",derivedFromUpstream:!0,blocker:"No upstream SQL cell is wired — pick an upstream dataframe before saving as a block."};let r="",s,i;switch(e.type){case"chart":r=TD(e.chartConfig),s=e.name??(n.name?`${n.name}_chart`:"chart_block"),i=((a=e.chartConfig)==null?void 0:a.title)??((l=e.chartConfig)!=null&&l.chart?`${e.chartConfig.chart} of ${n.name??"upstream"}`:void 0);break;case"single_value":r=SD(e.singleValueConfig),s=e.name??((c=e.singleValueConfig)!=null&&c.label?e.singleValueConfig.label:`${n.name??"metric"}_kpi`),i=(d=e.singleValueConfig)==null?void 0:d.label;break;case"filter":case"pivot":case"table":s=e.name??(n.name?`${n.name}_${e.type}`:`${e.type}_block`);break}return{content:hD(n.sql,r),suggestedName:s,suggestedDescription:i,derivedFromUpstream:!0}}function AD(e){let t=e;try{const d=JSON.parse(e);d&&typeof d.error=="string"&&(t=d.error)}catch{}t=t.replace(/^DuckDB query failed:\s*/i,"").trim();let n="Error";/Parser Error/i.test(t)?n="Syntax Error":/Binder Error/i.test(t)?n="Reference Error":/Conversion Error/i.test(t)?n="Type Error":/Invalid Input Error/i.test(t)?n="Input Error":/IO Error/i.test(t)?n="File Error":/Constraint Error/i.test(t)&&(n="Constraint Error");let r;const s=t.match(/LINE\s+(\d+):/i)??t.match(/\bline\s+(\d+)\b/i);s&&(r=parseInt(s[1],10));let i;const a=t.match(/at or near "([^"]+)"/i);a?i=a[1]:/at end of input/i.test(t)&&(i="end of input");let l;n==="Syntax Error"?i==='"""'||t.includes('"""')?l="Triple-quoted strings are DQL block syntax. Use a DQL cell for block syntax, or plain SQL in a SQL cell.":i==="end of input"||/at end of input/i.test(t)?l="Query is incomplete — check for unclosed parentheses, missing keywords, or a dangling comma.":(i===")"||i==="(")&&(l="Mismatched parentheses — check that every opening ( has a closing )."):n==="Reference Error"?/column.*not found|Referenced column/i.test(t)?l="Column not found — check the column name in the Schema panel (left sidebar).":/table.*not found|Table.*does not exist/i.test(t)&&(l="Table not found — make sure the file path is correct and the file exists in your data/ folder."):n==="Input Error"?/No files found/i.test(t)&&(l="File not found — use read_csv_auto('./data/filename.csv'). Open the Schema panel (left sidebar) to see all files available in your data/ folder."):n==="File Error"?l="File could not be read — use read_csv_auto('./data/filename.csv'). Open the Schema panel to browse available data files.":n==="Type Error"&&(l="Type mismatch — you may be comparing or casting incompatible types (e.g. text vs number).");const c=t.replace(/^(Parser Error|Binder Error|Conversion Error|Invalid Input Error|IO Error|Constraint Error):\s*/i,"").trim();return{type:n,message:c,line:r,near:i,hint:l}}function mD(e,t){const n=e.length,r=t.length,s=Array.from({length:n+1},(i,a)=>Array.from({length:r+1},(l,c)=>a===0?c:c===0?a:0));for(let i=1;i<=n;i++)for(let a=1;a<=r;a++)s[i][a]=e[i-1]===t[a-1]?s[i-1][a-1]:1+Math.min(s[i-1][a],s[i][a-1],s[i-1][a-1]);return s[n][r]}function If(e,t){const n=e.toLowerCase();let r=null,s=4;for(const i of t){const a=mD(n,i.toLowerCase());a<s&&(s=a,r=i)}return r}function gD({message:e,themeMode:t,onFix:n,schemaTables:r}){const s=ce[t],i=AD(e);let a=null;if(r&&r.length>0&&i.type==="Reference Error"){const c=/column.*not found|Referenced column/i.test(i.message),d=/table.*not found|Table.*does not exist/i.test(i.message);if(c&&i.near){const u=r.flatMap(f=>f.columns.map(T=>T.name)),E=If(i.near,u);E&&(a=`Did you mean column "${E}"?`)}else if(d&&i.near){const u=If(i.near,r.map(E=>E.name));u&&(a=`Did you mean table "${u}"?`)}}const l=n&&(i.type==="Syntax Error"||i.near===")"||i.near==="("||i.near==="end of input");return o.jsxs("div",{style:{padding:"12px 14px",background:`${s.error}10`,borderLeft:`3px solid ${s.error}`,display:"flex",flexDirection:"column",gap:8},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[o.jsx("div",{style:{flexShrink:0,color:s.error,display:"flex",alignItems:"center"},children:o.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M4.47.22A.749.749 0 0 1 5 0h6c.199 0 .389.079.53.22l4.25 4.25c.141.14.22.331.22.53v6a.749.749 0 0 1-.22.53l-4.25 4.25A.749.749 0 0 1 11 16H5a.749.749 0 0 1-.53-.22L.22 11.53A.749.749 0 0 1 0 11V5c0-.199.079-.389.22-.53Zm.84 1.28L1.5 5.31v5.38l3.81 3.81h5.38l3.81-3.81V5.31L10.69 1.5ZM8 4a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 4Zm0 8a1 1 0 1 1 0-2 1 1 0 0 1 0 2Z"})})}),o.jsx("span",{style:{fontSize:10,fontWeight:700,fontFamily:s.fontMono,letterSpacing:"0.06em",textTransform:"uppercase",color:s.error,background:`${s.error}18`,border:`1px solid ${s.error}40`,borderRadius:4,padding:"1px 7px",flexShrink:0},children:i.type}),i.line!==void 0&&o.jsxs("span",{style:{fontSize:10,fontWeight:600,fontFamily:s.fontMono,color:s.textSecondary,background:`${s.textMuted}18`,border:`1px solid ${s.textMuted}30`,borderRadius:4,padding:"1px 7px",flexShrink:0},children:["Line ",i.line]}),i.near&&o.jsxs("span",{style:{fontSize:11,fontFamily:s.fontMono,color:s.textSecondary,flexShrink:0},children:["near ",o.jsxs("span",{style:{color:s.error},children:["“",i.near,"”"]})]})]}),o.jsx("pre",{style:{margin:0,fontFamily:s.fontMono,fontSize:12,color:s.error,lineHeight:1.6,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:i.message}),a&&o.jsxs("div",{style:{fontSize:12,fontFamily:s.font,color:s.textSecondary,display:"flex",alignItems:"center",gap:6},children:[o.jsx("span",{style:{color:s.accent},children:"→"}),a]}),i.hint&&o.jsxs("div",{style:{marginTop:2,padding:"8px 12px",background:`${s.warning}12`,border:`1px solid ${s.warning}40`,borderRadius:6,display:"flex",alignItems:"flex-start",gap:8},children:[o.jsx("span",{style:{flexShrink:0,fontSize:13,lineHeight:1.5},children:"💡"}),o.jsx("span",{style:{fontSize:12,fontFamily:s.font,color:s.warning,lineHeight:1.6},children:i.hint})]}),l&&o.jsxs("button",{onClick:n,style:{alignSelf:"flex-start",marginTop:2,padding:"5px 12px",background:`${s.accent}15`,border:`1px solid ${s.accent}50`,borderRadius:6,color:s.accent,fontSize:12,fontFamily:s.font,fontWeight:500,cursor:"pointer",display:"flex",alignItems:"center",gap:6,transition:"all 0.15s"},onMouseEnter:c=>{c.currentTarget.style.background=`${s.accent}25`},onMouseLeave:c=>{c.currentTarget.style.background=`${s.accent}15`},children:[o.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M11.013 1.427a1.75 1.75 0 0 1 2.474 0l1.086 1.086a1.75 1.75 0 0 1 0 2.474l-8.61 8.61c-.21.21-.47.364-.756.445l-3.251.93a.75.75 0 0 1-.927-.928l.929-3.25c.081-.286.235-.547.445-.758l8.61-8.61Zm.176 4.823L9.75 4.81l-6.286 6.287a.253.253 0 0 0-.064.108l-.558 1.953 1.953-.558a.253.253 0 0 0 .108-.064Zm1.238-3.763a.25.25 0 0 0-.354 0L10.811 3.75l1.439 1.44 1.263-1.263a.25.25 0 0 0 0-.354Z"})}),"Format & Run"]})]})}function fd({path:e,onNodeClick:t,focalNodeId:n,t:r}){return e.nodes.length===0?null:o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,alignItems:"center"},children:e.nodes.map((s,i)=>o.jsxs(Be.Fragment,{children:[o.jsx(ID,{node:s,isFocal:s.id===n,onClick:t?()=>t(s.id):void 0,t:r}),i<e.nodes.length-1&&o.jsx("span",{style:{color:r.textMuted,fontSize:10,lineHeight:1},children:"→"})]},s.id))})}function Of({title:e,paths:t,onNodeClick:n,focalNodeId:r,maxVisible:s=4,t:i}){const[a,l]=Be.useState(!1),c=a?t:t.slice(0,s),d=t.length>s;return t.length===0?null:o.jsxs("div",{style:{border:`1px solid ${i.cellBorder}`,borderRadius:10,overflow:"hidden",background:i.inputBg},children:[o.jsxs("div",{style:{padding:"8px 12px",borderBottom:`1px solid ${i.cellBorder}`,fontSize:11,fontWeight:700,color:i.textMuted,fontFamily:i.font,textTransform:"uppercase",letterSpacing:"0.04em",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[o.jsx("span",{children:e}),o.jsxs("span",{style:{fontWeight:400,fontSize:10},children:[t.length," path",t.length!==1?"s":""]})]}),o.jsxs("div",{style:{display:"grid",gap:8,padding:10},children:[c.map((u,E)=>o.jsx(fd,{path:u,onNodeClick:n,focalNodeId:r,t:i},`path-${E}`)),d&&!a&&o.jsxs("button",{onClick:()=>l(!0),style:{background:"none",border:"none",color:i.accent,cursor:"pointer",fontSize:11,fontFamily:i.font,padding:"2px 0",textAlign:"left"},children:["Show ",t.length-s," more path",t.length-s!==1?"s":"","..."]})]})]})}function ID({node:e,isFocal:t,onClick:n,t:r}){const s=ze[e.type]??"#8b949e",i=Fa[e.type]??e.type.slice(0,3).toUpperCase();return o.jsxs("button",{onClick:n,disabled:!n,style:{display:"inline-flex",alignItems:"center",gap:4,background:t?`${s}18`:r.pillBg??`${r.cellBg}`,border:`1px solid ${t?s:r.cellBorder}`,borderRadius:999,color:r.textPrimary,cursor:n?"pointer":"default",fontSize:10,fontFamily:r.font,padding:"3px 8px",transition:"border-color 0.15s",whiteSpace:"nowrap",maxWidth:180},title:`${e.type}: ${e.name}${e.domain?` (${e.domain})`:""}`,children:[o.jsx("span",{style:{fontSize:8,fontWeight:700,color:"#0d1117",background:s,borderRadius:3,padding:"1px 3px",flexShrink:0},children:i}),o.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]})}function OD({layerSummary:e,t}){const n=["source","transform","answer","consumption"];if(Object.values(e).reduce((a,l)=>a+l,0)===0)return null;const s={source:"#79c0ff",transform:"#ff7b72",answer:"#56d364",consumption:"#d2a8ff"},i={source:"Sources",transform:"Transform",answer:"Answer",consumption:"Consumption"};return o.jsx("div",{style:{display:"flex",gap:10,fontSize:10,color:t.textMuted,fontFamily:t.font},children:n.map(a=>{const l=e[a]??0;return l===0?null:o.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3},children:[o.jsx("span",{style:{width:8,height:8,borderRadius:2,background:s[a],display:"inline-block"}}),i[a],": ",l]},a)})})}function He(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=He(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var ND={value:()=>{}};function Xa(){for(var e=0,t=arguments.length,n={},r;e<t;++e){if(!(r=arguments[e]+"")||r in n||/[\s.]/.test(r))throw new Error("illegal type: "+r);n[r]=[]}return new Pi(n)}function Pi(e){this._=e}function xD(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",s=n.indexOf(".");if(s>=0&&(r=n.slice(s+1),n=n.slice(0,s)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}Pi.prototype=Xa.prototype={constructor:Pi,on:function(e,t){var n=this._,r=xD(e+"",n),s,i=-1,a=r.length;if(arguments.length<2){for(;++i<a;)if((s=(e=r[i]).type)&&(s=yD(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++i<a;)if(s=(e=r[i]).type)n[s]=Nf(n[s],e.name,t);else if(t==null)for(s in n)n[s]=Nf(n[s],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new Pi(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,i;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(i=this._[e],r=0,s=i.length;r<s;++r)i[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],s=0,i=r.length;s<i;++s)r[s].value.apply(t,n)}};function yD(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function Nf(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=ND,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var pd="http://www.w3.org/1999/xhtml";const xf={svg:"http://www.w3.org/2000/svg",xhtml:pd,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Ka(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),xf.hasOwnProperty(t)?{space:xf[t],local:e}:e}function CD(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===pd&&t.documentElement.namespaceURI===pd?t.createElement(e):t.createElementNS(n,e)}}function LD(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function lA(e){var t=Ka(e);return(t.local?LD:CD)(t)}function _D(){}function Nu(e){return e==null?_D:function(){return this.querySelector(e)}}function bD(e){typeof e!="function"&&(e=Nu(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var i=t[s],a=i.length,l=r[s]=new Array(a),c,d,u=0;u<a;++u)(c=i[u])&&(d=e.call(c,c.__data__,u,i))&&("__data__"in c&&(d.__data__=c.__data__),l[u]=d);return new pt(r,this._parents)}function vD(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function DD(){return[]}function cA(e){return e==null?DD:function(){return this.querySelectorAll(e)}}function MD(e){return function(){return vD(e.apply(this,arguments))}}function PD(e){typeof e=="function"?e=MD(e):e=cA(e);for(var t=this._groups,n=t.length,r=[],s=[],i=0;i<n;++i)for(var a=t[i],l=a.length,c,d=0;d<l;++d)(c=a[d])&&(r.push(e.call(c,c.__data__,d,a)),s.push(c));return new pt(r,s)}function dA(e){return function(){return this.matches(e)}}function uA(e){return function(t){return t.matches(e)}}var wD=Array.prototype.find;function UD(e){return function(){return wD.call(this.children,e)}}function BD(){return this.firstElementChild}function jD(e){return this.select(e==null?BD:UD(typeof e=="function"?e:uA(e)))}var kD=Array.prototype.filter;function FD(){return Array.from(this.children)}function GD(e){return function(){return kD.call(this.children,e)}}function HD(e){return this.selectAll(e==null?FD:GD(typeof e=="function"?e:uA(e)))}function WD(e){typeof e!="function"&&(e=dA(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var i=t[s],a=i.length,l=r[s]=[],c,d=0;d<a;++d)(c=i[d])&&e.call(c,c.__data__,d,i)&&l.push(c);return new pt(r,this._parents)}function EA(e){return new Array(e.length)}function YD(){return new pt(this._enter||this._groups.map(EA),this._parents)}function oa(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}oa.prototype={constructor:oa,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};function $D(e){return function(){return e}}function VD(e,t,n,r,s,i){for(var a=0,l,c=t.length,d=i.length;a<d;++a)(l=t[a])?(l.__data__=i[a],r[a]=l):n[a]=new oa(e,i[a]);for(;a<c;++a)(l=t[a])&&(s[a]=l)}function zD(e,t,n,r,s,i,a){var l,c,d=new Map,u=t.length,E=i.length,f=new Array(u),T;for(l=0;l<u;++l)(c=t[l])&&(f[l]=T=a.call(c,c.__data__,l,t)+"",d.has(T)?s[l]=c:d.set(T,c));for(l=0;l<E;++l)T=a.call(e,i[l],l,i)+"",(c=d.get(T))?(r[l]=c,c.__data__=i[l],d.delete(T)):n[l]=new oa(e,i[l]);for(l=0;l<u;++l)(c=t[l])&&d.get(f[l])===c&&(s[l]=c)}function XD(e){return e.__data__}function KD(e,t){if(!arguments.length)return Array.from(this,XD);var n=t?zD:VD,r=this._parents,s=this._groups;typeof e!="function"&&(e=$D(e));for(var i=s.length,a=new Array(i),l=new Array(i),c=new Array(i),d=0;d<i;++d){var u=r[d],E=s[d],f=E.length,T=qD(e.call(u,u&&u.__data__,d,r)),A=T.length,R=l[d]=new Array(A),S=a[d]=new Array(A),h=c[d]=new Array(f);n(u,E,R,S,h,T,t);for(var g=0,m=0,I,O;g<A;++g)if(I=R[g]){for(g>=m&&(m=g+1);!(O=S[m])&&++m<A;);I._next=O||null}}return a=new pt(a,r),a._enter=l,a._exit=c,a}function qD(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function JD(){return new pt(this._exit||this._groups.map(EA),this._parents)}function QD(e,t,n){var r=this.enter(),s=this,i=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(s=t(s),s&&(s=s.selection())),n==null?i.remove():n(i),r&&s?r.merge(s).order():s}function ZD(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,i=r.length,a=Math.min(s,i),l=new Array(s),c=0;c<a;++c)for(var d=n[c],u=r[c],E=d.length,f=l[c]=new Array(E),T,A=0;A<E;++A)(T=d[A]||u[A])&&(f[A]=T);for(;c<s;++c)l[c]=n[c];return new pt(l,this._parents)}function eM(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,i=r[s],a;--s>=0;)(a=r[s])&&(i&&a.compareDocumentPosition(i)^4&&i.parentNode.insertBefore(a,i),i=a);return this}function tM(e){e||(e=nM);function t(E,f){return E&&f?e(E.__data__,f.__data__):!E-!f}for(var n=this._groups,r=n.length,s=new Array(r),i=0;i<r;++i){for(var a=n[i],l=a.length,c=s[i]=new Array(l),d,u=0;u<l;++u)(d=a[u])&&(c[u]=d);c.sort(t)}return new pt(s,this._parents).order()}function nM(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function rM(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function oM(){return Array.from(this)}function sM(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,i=r.length;s<i;++s){var a=r[s];if(a)return a}return null}function iM(){let e=0;for(const t of this)++e;return e}function aM(){return!this.node()}function lM(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var s=t[n],i=0,a=s.length,l;i<a;++i)(l=s[i])&&e.call(l,l.__data__,i,s);return this}function cM(e){return function(){this.removeAttribute(e)}}function dM(e){return function(){this.removeAttributeNS(e.space,e.local)}}function uM(e,t){return function(){this.setAttribute(e,t)}}function EM(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function fM(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function pM(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function TM(e,t){var n=Ka(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((t==null?n.local?dM:cM:typeof t=="function"?n.local?pM:fM:n.local?EM:uM)(n,t))}function fA(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function SM(e){return function(){this.style.removeProperty(e)}}function hM(e,t,n){return function(){this.style.setProperty(e,t,n)}}function RM(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function AM(e,t,n){return arguments.length>1?this.each((t==null?SM:typeof t=="function"?RM:hM)(e,t,n??"")):lo(this.node(),e)}function lo(e,t){return e.style.getPropertyValue(t)||fA(e).getComputedStyle(e,null).getPropertyValue(t)}function mM(e){return function(){delete this[e]}}function gM(e,t){return function(){this[e]=t}}function IM(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function OM(e,t){return arguments.length>1?this.each((t==null?mM:typeof t=="function"?IM:gM)(e,t)):this.node()[e]}function pA(e){return e.trim().split(/^|\s+/)}function xu(e){return e.classList||new TA(e)}function TA(e){this._node=e,this._names=pA(e.getAttribute("class")||"")}TA.prototype={add:function(e){var t=this._names.indexOf(e);t<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};function SA(e,t){for(var n=xu(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function hA(e,t){for(var n=xu(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function NM(e){return function(){SA(this,e)}}function xM(e){return function(){hA(this,e)}}function yM(e,t){return function(){(t.apply(this,arguments)?SA:hA)(this,e)}}function CM(e,t){var n=pA(e+"");if(arguments.length<2){for(var r=xu(this.node()),s=-1,i=n.length;++s<i;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?yM:t?NM:xM)(n,t))}function LM(){this.textContent=""}function _M(e){return function(){this.textContent=e}}function bM(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function vM(e){return arguments.length?this.each(e==null?LM:(typeof e=="function"?bM:_M)(e)):this.node().textContent}function DM(){this.innerHTML=""}function MM(e){return function(){this.innerHTML=e}}function PM(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function wM(e){return arguments.length?this.each(e==null?DM:(typeof e=="function"?PM:MM)(e)):this.node().innerHTML}function UM(){this.nextSibling&&this.parentNode.appendChild(this)}function BM(){return this.each(UM)}function jM(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function kM(){return this.each(jM)}function FM(e){var t=typeof e=="function"?e:lA(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function GM(){return null}function HM(e,t){var n=typeof e=="function"?e:lA(e),r=t==null?GM:typeof t=="function"?t:Nu(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function WM(){var e=this.parentNode;e&&e.removeChild(this)}function YM(){return this.each(WM)}function $M(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function VM(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function zM(e){return this.select(e?VM:$M)}function XM(e){return arguments.length?this.property("__data__",e):this.node().__data__}function KM(e){return function(t){e.call(this,t,this.__data__)}}function qM(e){return e.trim().split(/^|\s+/).map(function(t){var n="",r=t.indexOf(".");return r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),{type:t,name:n}})}function JM(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,i;n<s;++n)i=t[n],(!e.type||i.type===e.type)&&i.name===e.name?this.removeEventListener(i.type,i.listener,i.options):t[++r]=i;++r?t.length=r:delete this.__on}}}function QM(e,t,n){return function(){var r=this.__on,s,i=KM(t);if(r){for(var a=0,l=r.length;a<l;++a)if((s=r[a]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=i,s.options=n),s.value=t;return}}this.addEventListener(e.type,i,n),s={type:e.type,name:e.name,value:t,listener:i,options:n},r?r.push(s):this.__on=[s]}}function ZM(e,t,n){var r=qM(e+""),s,i=r.length,a;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,d=l.length,u;c<d;++c)for(s=0,u=l[c];s<i;++s)if((a=r[s]).type===u.type&&a.name===u.name)return u.value}return}for(l=t?QM:JM,s=0;s<i;++s)this.each(l(r[s],t,n));return this}function RA(e,t,n){var r=fA(e),s=r.CustomEvent;typeof s=="function"?s=new s(t,n):(s=r.document.createEvent("Event"),n?(s.initEvent(t,n.bubbles,n.cancelable),s.detail=n.detail):s.initEvent(t,!1,!1)),e.dispatchEvent(s)}function eP(e,t){return function(){return RA(this,e,t)}}function tP(e,t){return function(){return RA(this,e,t.apply(this,arguments))}}function nP(e,t){return this.each((typeof t=="function"?tP:eP)(e,t))}function*rP(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,i=r.length,a;s<i;++s)(a=r[s])&&(yield a)}var AA=[null];function pt(e,t){this._groups=e,this._parents=t}function Ls(){return new pt([[document.documentElement]],AA)}function oP(){return this}pt.prototype=Ls.prototype={constructor:pt,select:bD,selectAll:PD,selectChild:jD,selectChildren:HD,filter:WD,data:KD,enter:YD,exit:JD,join:QD,merge:ZD,selection:oP,order:eM,sort:tM,call:rM,nodes:oM,node:sM,size:iM,empty:aM,each:lM,attr:TM,style:AM,property:OM,classed:CM,text:vM,html:wM,raise:BM,lower:kM,append:FM,insert:HM,remove:YM,clone:zM,datum:XM,on:ZM,dispatch:nP,[Symbol.iterator]:rP};function Et(e){return typeof e=="string"?new pt([[document.querySelector(e)]],[document.documentElement]):new pt([[e]],AA)}function sP(e){let t;for(;t=e.sourceEvent;)e=t;return e}function bt(e,t){if(e=sP(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,r=r.matrixTransform(t.getScreenCTM().inverse()),[r.x,r.y]}if(t.getBoundingClientRect){var s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}}return[e.pageX,e.pageY]}const iP={passive:!1},as={capture:!0,passive:!1};function ql(e){e.stopImmediatePropagation()}function Zr(e){e.preventDefault(),e.stopImmediatePropagation()}function mA(e){var t=e.document.documentElement,n=Et(e).on("dragstart.drag",Zr,as);"onselectstart"in t?n.on("selectstart.drag",Zr,as):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function gA(e,t){var n=e.document.documentElement,r=Et(e).on("dragstart.drag",null);t&&(r.on("click.drag",Zr,as),setTimeout(function(){r.on("click.drag",null)},0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const ci=e=>()=>e;function Td(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:i,x:a,y:l,dx:c,dy:d,dispatch:u}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:s,enumerable:!0,configurable:!0},active:{value:i,enumerable:!0,configurable:!0},x:{value:a,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:d,enumerable:!0,configurable:!0},_:{value:u}})}Td.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function aP(e){return!e.ctrlKey&&!e.button}function lP(){return this.parentNode}function cP(e,t){return t??{x:e.x,y:e.y}}function dP(){return navigator.maxTouchPoints||"ontouchstart"in this}function IA(){var e=aP,t=lP,n=cP,r=dP,s={},i=Xa("start","drag","end"),a=0,l,c,d,u,E=0;function f(I){I.on("mousedown.drag",T).filter(r).on("touchstart.drag",S).on("touchmove.drag",h,iP).on("touchend.drag touchcancel.drag",g).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function T(I,O){if(!(u||!e.call(this,I,O))){var N=m(this,t.call(this,I,O),I,O,"mouse");N&&(Et(I.view).on("mousemove.drag",A,as).on("mouseup.drag",R,as),mA(I.view),ql(I),d=!1,l=I.clientX,c=I.clientY,N("start",I))}}function A(I){if(Zr(I),!d){var O=I.clientX-l,N=I.clientY-c;d=O*O+N*N>E}s.mouse("drag",I)}function R(I){Et(I.view).on("mousemove.drag mouseup.drag",null),gA(I.view,d),Zr(I),s.mouse("end",I)}function S(I,O){if(e.call(this,I,O)){var N=I.changedTouches,x=t.call(this,I,O),_=N.length,C,v;for(C=0;C<_;++C)(v=m(this,x,I,O,N[C].identifier,N[C]))&&(ql(I),v("start",I,N[C]))}}function h(I){var O=I.changedTouches,N=O.length,x,_;for(x=0;x<N;++x)(_=s[O[x].identifier])&&(Zr(I),_("drag",I,O[x]))}function g(I){var O=I.changedTouches,N=O.length,x,_;for(u&&clearTimeout(u),u=setTimeout(function(){u=null},500),x=0;x<N;++x)(_=s[O[x].identifier])&&(ql(I),_("end",I,O[x]))}function m(I,O,N,x,_,C){var v=i.copy(),b=bt(C||N,O),P,j,L;if((L=n.call(I,new Td("beforestart",{sourceEvent:N,target:f,identifier:_,active:a,x:b[0],y:b[1],dx:0,dy:0,dispatch:v}),x))!=null)return P=L.x-b[0]||0,j=L.y-b[1]||0,function B(M,U,D){var y=b,w;switch(M){case"start":s[_]=B,w=a++;break;case"end":delete s[_],--a;case"drag":b=bt(D||U,O),w=a;break}v.call(M,I,new Td(M,{sourceEvent:U,subject:L,target:f,identifier:_,active:w,x:b[0]+P,y:b[1]+j,dx:b[0]-y[0],dy:b[1]-y[1],dispatch:v}),x)}}return f.filter=function(I){return arguments.length?(e=typeof I=="function"?I:ci(!!I),f):e},f.container=function(I){return arguments.length?(t=typeof I=="function"?I:ci(I),f):t},f.subject=function(I){return arguments.length?(n=typeof I=="function"?I:ci(I),f):n},f.touchable=function(I){return arguments.length?(r=typeof I=="function"?I:ci(!!I),f):r},f.on=function(){var I=i.on.apply(i,arguments);return I===i?f:I},f.clickDistance=function(I){return arguments.length?(E=(I=+I)*I,f):Math.sqrt(E)},f}function yu(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function OA(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function _s(){}var ls=.7,sa=1/ls,eo="\\s*([+-]?\\d+)\\s*",cs="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",tn="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",uP=/^#([0-9a-f]{3,8})$/,EP=new RegExp(`^rgb\\(${eo},${eo},${eo}\\)$`),fP=new RegExp(`^rgb\\(${tn},${tn},${tn}\\)$`),pP=new RegExp(`^rgba\\(${eo},${eo},${eo},${cs}\\)$`),TP=new RegExp(`^rgba\\(${tn},${tn},${tn},${cs}\\)$`),SP=new RegExp(`^hsl\\(${cs},${tn},${tn}\\)$`),hP=new RegExp(`^hsla\\(${cs},${tn},${tn},${cs}\\)$`),yf={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};yu(_s,hr,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Cf,formatHex:Cf,formatHex8:RP,formatHsl:AP,formatRgb:Lf,toString:Lf});function Cf(){return this.rgb().formatHex()}function RP(){return this.rgb().formatHex8()}function AP(){return NA(this).formatHsl()}function Lf(){return this.rgb().formatRgb()}function hr(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=uP.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?_f(t):n===3?new ot(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?di(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?di(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=EP.exec(e))?new ot(t[1],t[2],t[3],1):(t=fP.exec(e))?new ot(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=pP.exec(e))?di(t[1],t[2],t[3],t[4]):(t=TP.exec(e))?di(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=SP.exec(e))?Df(t[1],t[2]/100,t[3]/100,1):(t=hP.exec(e))?Df(t[1],t[2]/100,t[3]/100,t[4]):yf.hasOwnProperty(e)?_f(yf[e]):e==="transparent"?new ot(NaN,NaN,NaN,0):null}function _f(e){return new ot(e>>16&255,e>>8&255,e&255,1)}function di(e,t,n,r){return r<=0&&(e=t=n=NaN),new ot(e,t,n,r)}function mP(e){return e instanceof _s||(e=hr(e)),e?(e=e.rgb(),new ot(e.r,e.g,e.b,e.opacity)):new ot}function Sd(e,t,n,r){return arguments.length===1?mP(e):new ot(e,t,n,r??1)}function ot(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}yu(ot,Sd,OA(_s,{brighter(e){return e=e==null?sa:Math.pow(sa,e),new ot(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?ls:Math.pow(ls,e),new ot(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new ot(cr(this.r),cr(this.g),cr(this.b),ia(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:bf,formatHex:bf,formatHex8:gP,formatRgb:vf,toString:vf}));function bf(){return`#${ar(this.r)}${ar(this.g)}${ar(this.b)}`}function gP(){return`#${ar(this.r)}${ar(this.g)}${ar(this.b)}${ar((isNaN(this.opacity)?1:this.opacity)*255)}`}function vf(){const e=ia(this.opacity);return`${e===1?"rgb(":"rgba("}${cr(this.r)}, ${cr(this.g)}, ${cr(this.b)}${e===1?")":`, ${e})`}`}function ia(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function cr(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function ar(e){return e=cr(e),(e<16?"0":"")+e.toString(16)}function Df(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new vt(e,t,n,r)}function NA(e){if(e instanceof vt)return new vt(e.h,e.s,e.l,e.opacity);if(e instanceof _s||(e=hr(e)),!e)return new vt;if(e instanceof vt)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,s=Math.min(t,n,r),i=Math.max(t,n,r),a=NaN,l=i-s,c=(i+s)/2;return l?(t===i?a=(n-r)/l+(n<r)*6:n===i?a=(r-t)/l+2:a=(t-n)/l+4,l/=c<.5?i+s:2-i-s,a*=60):l=c>0&&c<1?0:a,new vt(a,l,c,e.opacity)}function IP(e,t,n,r){return arguments.length===1?NA(e):new vt(e,t,n,r??1)}function vt(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}yu(vt,IP,OA(_s,{brighter(e){return e=e==null?sa:Math.pow(sa,e),new vt(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?ls:Math.pow(ls,e),new vt(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,s=2*n-r;return new ot(Jl(e>=240?e-240:e+120,s,r),Jl(e,s,r),Jl(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new vt(Mf(this.h),ui(this.s),ui(this.l),ia(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=ia(this.opacity);return`${e===1?"hsl(":"hsla("}${Mf(this.h)}, ${ui(this.s)*100}%, ${ui(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Mf(e){return e=(e||0)%360,e<0?e+360:e}function ui(e){return Math.max(0,Math.min(1,e||0))}function Jl(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const Cu=e=>()=>e;function OP(e,t){return function(n){return e+n*t}}function NP(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function xP(e){return(e=+e)==1?xA:function(t,n){return n-t?NP(t,n,e):Cu(isNaN(t)?n:t)}}function xA(e,t){var n=t-e;return n?OP(e,n):Cu(isNaN(e)?t:e)}const aa=(function e(t){var n=xP(t);function r(s,i){var a=n((s=Sd(s)).r,(i=Sd(i)).r),l=n(s.g,i.g),c=n(s.b,i.b),d=xA(s.opacity,i.opacity);return function(u){return s.r=a(u),s.g=l(u),s.b=c(u),s.opacity=d(u),s+""}}return r.gamma=e,r})(1);function yP(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),s;return function(i){for(s=0;s<n;++s)r[s]=e[s]*(1-i)+t[s]*i;return r}}function CP(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function LP(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),i=new Array(n),a;for(a=0;a<r;++a)s[a]=Xo(e[a],t[a]);for(;a<n;++a)i[a]=t[a];return function(l){for(a=0;a<r;++a)i[a]=s[a](l);return i}}function _P(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function Xt(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function bP(e,t){var n={},r={},s;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(s in t)s in e?n[s]=Xo(e[s],t[s]):r[s]=t[s];return function(i){for(s in n)r[s]=n[s](i);return r}}var hd=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Ql=new RegExp(hd.source,"g");function vP(e){return function(){return e}}function DP(e){return function(t){return e(t)+""}}function yA(e,t){var n=hd.lastIndex=Ql.lastIndex=0,r,s,i,a=-1,l=[],c=[];for(e=e+"",t=t+"";(r=hd.exec(e))&&(s=Ql.exec(t));)(i=s.index)>n&&(i=t.slice(n,i),l[a]?l[a]+=i:l[++a]=i),(r=r[0])===(s=s[0])?l[a]?l[a]+=s:l[++a]=s:(l[++a]=null,c.push({i:a,x:Xt(r,s)})),n=Ql.lastIndex;return n<t.length&&(i=t.slice(n),l[a]?l[a]+=i:l[++a]=i),l.length<2?c[0]?DP(c[0].x):vP(t):(t=c.length,function(d){for(var u=0,E;u<t;++u)l[(E=c[u]).i]=E.x(d);return l.join("")})}function Xo(e,t){var n=typeof t,r;return t==null||n==="boolean"?Cu(t):(n==="number"?Xt:n==="string"?(r=hr(t))?(t=r,aa):yA:t instanceof hr?aa:t instanceof Date?_P:CP(t)?yP:Array.isArray(t)?LP:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?bP:Xt)(e,t)}var Pf=180/Math.PI,Rd={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function CA(e,t,n,r,s,i){var a,l,c;return(a=Math.sqrt(e*e+t*t))&&(e/=a,t/=a),(c=e*n+t*r)&&(n-=e*c,r-=t*c),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,c/=l),e*r<t*n&&(e=-e,t=-t,c=-c,a=-a),{translateX:s,translateY:i,rotate:Math.atan2(t,e)*Pf,skewX:Math.atan(c)*Pf,scaleX:a,scaleY:l}}var Ei;function MP(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Rd:CA(t.a,t.b,t.c,t.d,t.e,t.f)}function PP(e){return e==null||(Ei||(Ei=document.createElementNS("http://www.w3.org/2000/svg","g")),Ei.setAttribute("transform",e),!(e=Ei.transform.baseVal.consolidate()))?Rd:(e=e.matrix,CA(e.a,e.b,e.c,e.d,e.e,e.f))}function LA(e,t,n,r){function s(d){return d.length?d.pop()+" ":""}function i(d,u,E,f,T,A){if(d!==E||u!==f){var R=T.push("translate(",null,t,null,n);A.push({i:R-4,x:Xt(d,E)},{i:R-2,x:Xt(u,f)})}else(E||f)&&T.push("translate("+E+t+f+n)}function a(d,u,E,f){d!==u?(d-u>180?u+=360:u-d>180&&(d+=360),f.push({i:E.push(s(E)+"rotate(",null,r)-2,x:Xt(d,u)})):u&&E.push(s(E)+"rotate("+u+r)}function l(d,u,E,f){d!==u?f.push({i:E.push(s(E)+"skewX(",null,r)-2,x:Xt(d,u)}):u&&E.push(s(E)+"skewX("+u+r)}function c(d,u,E,f,T,A){if(d!==E||u!==f){var R=T.push(s(T)+"scale(",null,",",null,")");A.push({i:R-4,x:Xt(d,E)},{i:R-2,x:Xt(u,f)})}else(E!==1||f!==1)&&T.push(s(T)+"scale("+E+","+f+")")}return function(d,u){var E=[],f=[];return d=e(d),u=e(u),i(d.translateX,d.translateY,u.translateX,u.translateY,E,f),a(d.rotate,u.rotate,E,f),l(d.skewX,u.skewX,E,f),c(d.scaleX,d.scaleY,u.scaleX,u.scaleY,E,f),d=u=null,function(T){for(var A=-1,R=f.length,S;++A<R;)E[(S=f[A]).i]=S.x(T);return E.join("")}}}var wP=LA(MP,"px, ","px)","deg)"),UP=LA(PP,", ",")",")"),BP=1e-12;function wf(e){return((e=Math.exp(e))+1/e)/2}function jP(e){return((e=Math.exp(e))-1/e)/2}function kP(e){return((e=Math.exp(2*e))-1)/(e+1)}const wi=(function e(t,n,r){function s(i,a){var l=i[0],c=i[1],d=i[2],u=a[0],E=a[1],f=a[2],T=u-l,A=E-c,R=T*T+A*A,S,h;if(R<BP)h=Math.log(f/d)/t,S=function(x){return[l+x*T,c+x*A,d*Math.exp(t*x*h)]};else{var g=Math.sqrt(R),m=(f*f-d*d+r*R)/(2*d*n*g),I=(f*f-d*d-r*R)/(2*f*n*g),O=Math.log(Math.sqrt(m*m+1)-m),N=Math.log(Math.sqrt(I*I+1)-I);h=(N-O)/t,S=function(x){var _=x*h,C=wf(O),v=d/(n*g)*(C*kP(t*_+O)-jP(O));return[l+v*T,c+v*A,d*C/wf(t*_+O)]}}return S.duration=h*1e3*t/Math.SQRT2,S}return s.rho=function(i){var a=Math.max(.001,+i),l=a*a,c=l*l;return e(a,l,c)},s})(Math.SQRT2,2,4);var co=0,Wo=0,Bo=0,_A=1e3,la,Yo,ca=0,Rr=0,qa=0,ds=typeof performance=="object"&&performance.now?performance:Date,bA=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Lu(){return Rr||(bA(FP),Rr=ds.now()+qa)}function FP(){Rr=0}function da(){this._call=this._time=this._next=null}da.prototype=vA.prototype={constructor:da,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?Lu():+n)+(t==null?0:+t),!this._next&&Yo!==this&&(Yo?Yo._next=this:la=this,Yo=this),this._call=e,this._time=n,Ad()},stop:function(){this._call&&(this._call=null,this._time=1/0,Ad())}};function vA(e,t,n){var r=new da;return r.restart(e,t,n),r}function GP(){Lu(),++co;for(var e=la,t;e;)(t=Rr-e._time)>=0&&e._call.call(void 0,t),e=e._next;--co}function Uf(){Rr=(ca=ds.now())+qa,co=Wo=0;try{GP()}finally{co=0,WP(),Rr=0}}function HP(){var e=ds.now(),t=e-ca;t>_A&&(qa-=t,ca=e)}function WP(){for(var e,t=la,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:la=n);Yo=e,Ad(r)}function Ad(e){if(!co){Wo&&(Wo=clearTimeout(Wo));var t=e-Rr;t>24?(e<1/0&&(Wo=setTimeout(Uf,e-ds.now()-qa)),Bo&&(Bo=clearInterval(Bo))):(Bo||(ca=ds.now(),Bo=setInterval(HP,_A)),co=1,bA(Uf))}}function Bf(e,t,n){var r=new da;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var YP=Xa("start","end","cancel","interrupt"),$P=[],DA=0,jf=1,md=2,Ui=3,kf=4,gd=5,Bi=6;function Ja(e,t,n,r,s,i){var a=e.__transition;if(!a)e.__transition={};else if(n in a)return;VP(e,n,{name:t,index:r,group:s,on:YP,tween:$P,time:i.time,delay:i.delay,duration:i.duration,ease:i.ease,timer:null,state:DA})}function _u(e,t){var n=Ht(e,t);if(n.state>DA)throw new Error("too late; already scheduled");return n}function sn(e,t){var n=Ht(e,t);if(n.state>Ui)throw new Error("too late; already running");return n}function Ht(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function VP(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=vA(i,0,n.time);function i(d){n.state=jf,n.timer.restart(a,n.delay,n.time),n.delay<=d&&a(d-n.delay)}function a(d){var u,E,f,T;if(n.state!==jf)return c();for(u in r)if(T=r[u],T.name===n.name){if(T.state===Ui)return Bf(a);T.state===kf?(T.state=Bi,T.timer.stop(),T.on.call("interrupt",e,e.__data__,T.index,T.group),delete r[u]):+u<t&&(T.state=Bi,T.timer.stop(),T.on.call("cancel",e,e.__data__,T.index,T.group),delete r[u])}if(Bf(function(){n.state===Ui&&(n.state=kf,n.timer.restart(l,n.delay,n.time),l(d))}),n.state=md,n.on.call("start",e,e.__data__,n.index,n.group),n.state===md){for(n.state=Ui,s=new Array(f=n.tween.length),u=0,E=-1;u<f;++u)(T=n.tween[u].value.call(e,e.__data__,n.index,n.group))&&(s[++E]=T);s.length=E+1}}function l(d){for(var u=d<n.duration?n.ease.call(null,d/n.duration):(n.timer.restart(c),n.state=gd,1),E=-1,f=s.length;++E<f;)s[E].call(e,u);n.state===gd&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=Bi,n.timer.stop(),delete r[t];for(var d in r)return;delete e.__transition}}function ji(e,t){var n=e.__transition,r,s,i=!0,a;if(n){t=t==null?null:t+"";for(a in n){if((r=n[a]).name!==t){i=!1;continue}s=r.state>md&&r.state<gd,r.state=Bi,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[a]}i&&delete e.__transition}}function zP(e){return this.each(function(){ji(this,e)})}function XP(e,t){var n,r;return function(){var s=sn(this,e),i=s.tween;if(i!==n){r=n=i;for(var a=0,l=r.length;a<l;++a)if(r[a].name===t){r=r.slice(),r.splice(a,1);break}}s.tween=r}}function KP(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var i=sn(this,e),a=i.tween;if(a!==r){s=(r=a).slice();for(var l={name:t,value:n},c=0,d=s.length;c<d;++c)if(s[c].name===t){s[c]=l;break}c===d&&s.push(l)}i.tween=s}}function qP(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Ht(this.node(),n).tween,s=0,i=r.length,a;s<i;++s)if((a=r[s]).name===e)return a.value;return null}return this.each((t==null?XP:KP)(n,e,t))}function bu(e,t,n){var r=e._id;return e.each(function(){var s=sn(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Ht(s,r).value[t]}}function MA(e,t){var n;return(typeof t=="number"?Xt:t instanceof hr?aa:(n=hr(t))?(t=n,aa):yA)(e,t)}function JP(e){return function(){this.removeAttribute(e)}}function QP(e){return function(){this.removeAttributeNS(e.space,e.local)}}function ZP(e,t,n){var r,s=n+"",i;return function(){var a=this.getAttribute(e);return a===s?null:a===r?i:i=t(r=a,n)}}function ew(e,t,n){var r,s=n+"",i;return function(){var a=this.getAttributeNS(e.space,e.local);return a===s?null:a===r?i:i=t(r=a,n)}}function tw(e,t,n){var r,s,i;return function(){var a,l=n(this),c;return l==null?void this.removeAttribute(e):(a=this.getAttribute(e),c=l+"",a===c?null:a===r&&c===s?i:(s=c,i=t(r=a,l)))}}function nw(e,t,n){var r,s,i;return function(){var a,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(a=this.getAttributeNS(e.space,e.local),c=l+"",a===c?null:a===r&&c===s?i:(s=c,i=t(r=a,l)))}}function rw(e,t){var n=Ka(e),r=n==="transform"?UP:MA;return this.attrTween(e,typeof t=="function"?(n.local?nw:tw)(n,r,bu(this,"attr."+e,t)):t==null?(n.local?QP:JP)(n):(n.local?ew:ZP)(n,r,t))}function ow(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function sw(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function iw(e,t){var n,r;function s(){var i=t.apply(this,arguments);return i!==r&&(n=(r=i)&&sw(e,i)),n}return s._value=t,s}function aw(e,t){var n,r;function s(){var i=t.apply(this,arguments);return i!==r&&(n=(r=i)&&ow(e,i)),n}return s._value=t,s}function lw(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var r=Ka(e);return this.tween(n,(r.local?iw:aw)(r,t))}function cw(e,t){return function(){_u(this,e).delay=+t.apply(this,arguments)}}function dw(e,t){return t=+t,function(){_u(this,e).delay=t}}function uw(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?cw:dw)(t,e)):Ht(this.node(),t).delay}function Ew(e,t){return function(){sn(this,e).duration=+t.apply(this,arguments)}}function fw(e,t){return t=+t,function(){sn(this,e).duration=t}}function pw(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?Ew:fw)(t,e)):Ht(this.node(),t).duration}function Tw(e,t){if(typeof t!="function")throw new Error;return function(){sn(this,e).ease=t}}function Sw(e){var t=this._id;return arguments.length?this.each(Tw(t,e)):Ht(this.node(),t).ease}function hw(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;sn(this,e).ease=n}}function Rw(e){if(typeof e!="function")throw new Error;return this.each(hw(this._id,e))}function Aw(e){typeof e!="function"&&(e=dA(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var i=t[s],a=i.length,l=r[s]=[],c,d=0;d<a;++d)(c=i[d])&&e.call(c,c.__data__,d,i)&&l.push(c);return new Sn(r,this._parents,this._name,this._id)}function mw(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,i=Math.min(r,s),a=new Array(r),l=0;l<i;++l)for(var c=t[l],d=n[l],u=c.length,E=a[l]=new Array(u),f,T=0;T<u;++T)(f=c[T]||d[T])&&(E[T]=f);for(;l<r;++l)a[l]=t[l];return new Sn(a,this._parents,this._name,this._id)}function gw(e){return(e+"").trim().split(/^|\s+/).every(function(t){var n=t.indexOf(".");return n>=0&&(t=t.slice(0,n)),!t||t==="start"})}function Iw(e,t,n){var r,s,i=gw(t)?_u:sn;return function(){var a=i(this,e),l=a.on;l!==r&&(s=(r=l).copy()).on(t,n),a.on=s}}function Ow(e,t){var n=this._id;return arguments.length<2?Ht(this.node(),n).on.on(e):this.each(Iw(n,e,t))}function Nw(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function xw(){return this.on("end.remove",Nw(this._id))}function yw(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Nu(e));for(var r=this._groups,s=r.length,i=new Array(s),a=0;a<s;++a)for(var l=r[a],c=l.length,d=i[a]=new Array(c),u,E,f=0;f<c;++f)(u=l[f])&&(E=e.call(u,u.__data__,f,l))&&("__data__"in u&&(E.__data__=u.__data__),d[f]=E,Ja(d[f],t,n,f,d,Ht(u,n)));return new Sn(i,this._parents,t,n)}function Cw(e){var t=this._name,n=this._id;typeof e!="function"&&(e=cA(e));for(var r=this._groups,s=r.length,i=[],a=[],l=0;l<s;++l)for(var c=r[l],d=c.length,u,E=0;E<d;++E)if(u=c[E]){for(var f=e.call(u,u.__data__,E,c),T,A=Ht(u,n),R=0,S=f.length;R<S;++R)(T=f[R])&&Ja(T,t,n,R,f,A);i.push(f),a.push(u)}return new Sn(i,a,t,n)}var Lw=Ls.prototype.constructor;function _w(){return new Lw(this._groups,this._parents)}function bw(e,t){var n,r,s;return function(){var i=lo(this,e),a=(this.style.removeProperty(e),lo(this,e));return i===a?null:i===n&&a===r?s:s=t(n=i,r=a)}}function PA(e){return function(){this.style.removeProperty(e)}}function vw(e,t,n){var r,s=n+"",i;return function(){var a=lo(this,e);return a===s?null:a===r?i:i=t(r=a,n)}}function Dw(e,t,n){var r,s,i;return function(){var a=lo(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),lo(this,e))),a===c?null:a===r&&c===s?i:(s=c,i=t(r=a,l))}}function Mw(e,t){var n,r,s,i="style."+t,a="end."+i,l;return function(){var c=sn(this,e),d=c.on,u=c.value[i]==null?l||(l=PA(t)):void 0;(d!==n||s!==u)&&(r=(n=d).copy()).on(a,s=u),c.on=r}}function Pw(e,t,n){var r=(e+="")=="transform"?wP:MA;return t==null?this.styleTween(e,bw(e,r)).on("end.style."+e,PA(e)):typeof t=="function"?this.styleTween(e,Dw(e,r,bu(this,"style."+e,t))).each(Mw(this._id,e)):this.styleTween(e,vw(e,r,t),n).on("end.style."+e,null)}function ww(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function Uw(e,t,n){var r,s;function i(){var a=t.apply(this,arguments);return a!==s&&(r=(s=a)&&ww(e,a,n)),r}return i._value=t,i}function Bw(e,t,n){var r="style."+(e+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(t==null)return this.tween(r,null);if(typeof t!="function")throw new Error;return this.tween(r,Uw(e,t,n??""))}function jw(e){return function(){this.textContent=e}}function kw(e){return function(){var t=e(this);this.textContent=t??""}}function Fw(e){return this.tween("text",typeof e=="function"?kw(bu(this,"text",e)):jw(e==null?"":e+""))}function Gw(e){return function(t){this.textContent=e.call(this,t)}}function Hw(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&Gw(s)),t}return r._value=e,r}function Ww(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(e==null)return this.tween(t,null);if(typeof e!="function")throw new Error;return this.tween(t,Hw(e))}function Yw(){for(var e=this._name,t=this._id,n=wA(),r=this._groups,s=r.length,i=0;i<s;++i)for(var a=r[i],l=a.length,c,d=0;d<l;++d)if(c=a[d]){var u=Ht(c,t);Ja(c,e,n,d,a,{time:u.time+u.delay+u.duration,delay:0,duration:u.duration,ease:u.ease})}return new Sn(r,this._parents,e,n)}function $w(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(i,a){var l={value:a},c={value:function(){--s===0&&i()}};n.each(function(){var d=sn(this,r),u=d.on;u!==e&&(t=(e=u).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),d.on=t}),s===0&&i()})}var Vw=0;function Sn(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function wA(){return++Vw}var cn=Ls.prototype;Sn.prototype={constructor:Sn,select:yw,selectAll:Cw,selectChild:cn.selectChild,selectChildren:cn.selectChildren,filter:Aw,merge:mw,selection:_w,transition:Yw,call:cn.call,nodes:cn.nodes,node:cn.node,size:cn.size,empty:cn.empty,each:cn.each,on:Ow,attr:rw,attrTween:lw,style:Pw,styleTween:Bw,text:Fw,textTween:Ww,remove:xw,tween:qP,delay:uw,duration:pw,ease:Sw,easeVarying:Rw,end:$w,[Symbol.iterator]:cn[Symbol.iterator]};function zw(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var Xw={time:null,delay:0,duration:250,ease:zw};function Kw(e,t){for(var n;!(n=e.__transition)||!(n=n[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return n}function qw(e){var t,n;e instanceof Sn?(t=e._id,e=e._name):(t=wA(),(n=Xw).time=Lu(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,i=0;i<s;++i)for(var a=r[i],l=a.length,c,d=0;d<l;++d)(c=a[d])&&Ja(c,e,t,d,a,n||Kw(c,t));return new Sn(r,this._parents,e,t)}Ls.prototype.interrupt=zP;Ls.prototype.transition=qw;const fi=e=>()=>e;function Jw(e,{sourceEvent:t,target:n,transform:r,dispatch:s}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:s}})}function un(e,t,n){this.k=e,this.x=t,this.y=n}un.prototype={constructor:un,scale:function(e){return e===1?this:new un(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new un(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var Qa=new un(1,0,0);UA.prototype=un.prototype;function UA(e){for(;!e.__zoom;)if(!(e=e.parentNode))return Qa;return e.__zoom}function Zl(e){e.stopImmediatePropagation()}function jo(e){e.preventDefault(),e.stopImmediatePropagation()}function Qw(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function Zw(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e,e.hasAttribute("viewBox")?(e=e.viewBox.baseVal,[[e.x,e.y],[e.x+e.width,e.y+e.height]]):[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]):[[0,0],[e.clientWidth,e.clientHeight]]}function Ff(){return this.__zoom||Qa}function eU(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function tU(){return navigator.maxTouchPoints||"ontouchstart"in this}function nU(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],i=e.invertY(t[0][1])-n[0][1],a=e.invertY(t[1][1])-n[1][1];return e.translate(s>r?(r+s)/2:Math.min(0,r)||Math.max(0,s),a>i?(i+a)/2:Math.min(0,i)||Math.max(0,a))}function BA(){var e=Qw,t=Zw,n=nU,r=eU,s=tU,i=[0,1/0],a=[[-1/0,-1/0],[1/0,1/0]],l=250,c=wi,d=Xa("start","zoom","end"),u,E,f,T=500,A=150,R=0,S=10;function h(L){L.property("__zoom",Ff).on("wheel.zoom",_,{passive:!1}).on("mousedown.zoom",C).on("dblclick.zoom",v).filter(s).on("touchstart.zoom",b).on("touchmove.zoom",P).on("touchend.zoom touchcancel.zoom",j).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}h.transform=function(L,B,M,U){var D=L.selection?L.selection():L;D.property("__zoom",Ff),L!==D?O(L,B,M,U):D.interrupt().each(function(){N(this,arguments).event(U).start().zoom(null,typeof B=="function"?B.apply(this,arguments):B).end()})},h.scaleBy=function(L,B,M,U){h.scaleTo(L,function(){var D=this.__zoom.k,y=typeof B=="function"?B.apply(this,arguments):B;return D*y},M,U)},h.scaleTo=function(L,B,M,U){h.transform(L,function(){var D=t.apply(this,arguments),y=this.__zoom,w=M==null?I(D):typeof M=="function"?M.apply(this,arguments):M,F=y.invert(w),k=typeof B=="function"?B.apply(this,arguments):B;return n(m(g(y,k),w,F),D,a)},M,U)},h.translateBy=function(L,B,M,U){h.transform(L,function(){return n(this.__zoom.translate(typeof B=="function"?B.apply(this,arguments):B,typeof M=="function"?M.apply(this,arguments):M),t.apply(this,arguments),a)},null,U)},h.translateTo=function(L,B,M,U,D){h.transform(L,function(){var y=t.apply(this,arguments),w=this.__zoom,F=U==null?I(y):typeof U=="function"?U.apply(this,arguments):U;return n(Qa.translate(F[0],F[1]).scale(w.k).translate(typeof B=="function"?-B.apply(this,arguments):-B,typeof M=="function"?-M.apply(this,arguments):-M),y,a)},U,D)};function g(L,B){return B=Math.max(i[0],Math.min(i[1],B)),B===L.k?L:new un(B,L.x,L.y)}function m(L,B,M){var U=B[0]-M[0]*L.k,D=B[1]-M[1]*L.k;return U===L.x&&D===L.y?L:new un(L.k,U,D)}function I(L){return[(+L[0][0]+ +L[1][0])/2,(+L[0][1]+ +L[1][1])/2]}function O(L,B,M,U){L.on("start.zoom",function(){N(this,arguments).event(U).start()}).on("interrupt.zoom end.zoom",function(){N(this,arguments).event(U).end()}).tween("zoom",function(){var D=this,y=arguments,w=N(D,y).event(U),F=t.apply(D,y),k=M==null?I(F):typeof M=="function"?M.apply(D,y):M,V=Math.max(F[1][0]-F[0][0],F[1][1]-F[0][1]),ee=D.__zoom,Y=typeof B=="function"?B.apply(D,y):B,te=c(ee.invert(k).concat(V/ee.k),Y.invert(k).concat(V/Y.k));return function(ne){if(ne===1)ne=Y;else{var z=te(ne),oe=V/z[2];ne=new un(oe,k[0]-z[0]*oe,k[1]-z[1]*oe)}w.zoom(null,ne)}})}function N(L,B,M){return!M&&L.__zooming||new x(L,B)}function x(L,B){this.that=L,this.args=B,this.active=0,this.sourceEvent=null,this.extent=t.apply(L,B),this.taps=0}x.prototype={event:function(L){return L&&(this.sourceEvent=L),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(L,B){return this.mouse&&L!=="mouse"&&(this.mouse[1]=B.invert(this.mouse[0])),this.touch0&&L!=="touch"&&(this.touch0[1]=B.invert(this.touch0[0])),this.touch1&&L!=="touch"&&(this.touch1[1]=B.invert(this.touch1[0])),this.that.__zoom=B,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(L){var B=Et(this.that).datum();d.call(L,this.that,new Jw(L,{sourceEvent:this.sourceEvent,target:h,transform:this.that.__zoom,dispatch:d}),B)}};function _(L,...B){if(!e.apply(this,arguments))return;var M=N(this,B).event(L),U=this.__zoom,D=Math.max(i[0],Math.min(i[1],U.k*Math.pow(2,r.apply(this,arguments)))),y=bt(L);if(M.wheel)(M.mouse[0][0]!==y[0]||M.mouse[0][1]!==y[1])&&(M.mouse[1]=U.invert(M.mouse[0]=y)),clearTimeout(M.wheel);else{if(U.k===D)return;M.mouse=[y,U.invert(y)],ji(this),M.start()}jo(L),M.wheel=setTimeout(w,A),M.zoom("mouse",n(m(g(U,D),M.mouse[0],M.mouse[1]),M.extent,a));function w(){M.wheel=null,M.end()}}function C(L,...B){if(f||!e.apply(this,arguments))return;var M=L.currentTarget,U=N(this,B,!0).event(L),D=Et(L.view).on("mousemove.zoom",k,!0).on("mouseup.zoom",V,!0),y=bt(L,M),w=L.clientX,F=L.clientY;mA(L.view),Zl(L),U.mouse=[y,this.__zoom.invert(y)],ji(this),U.start();function k(ee){if(jo(ee),!U.moved){var Y=ee.clientX-w,te=ee.clientY-F;U.moved=Y*Y+te*te>R}U.event(ee).zoom("mouse",n(m(U.that.__zoom,U.mouse[0]=bt(ee,M),U.mouse[1]),U.extent,a))}function V(ee){D.on("mousemove.zoom mouseup.zoom",null),gA(ee.view,U.moved),jo(ee),U.event(ee).end()}}function v(L,...B){if(e.apply(this,arguments)){var M=this.__zoom,U=bt(L.changedTouches?L.changedTouches[0]:L,this),D=M.invert(U),y=M.k*(L.shiftKey?.5:2),w=n(m(g(M,y),U,D),t.apply(this,B),a);jo(L),l>0?Et(this).transition().duration(l).call(O,w,U,L):Et(this).call(h.transform,w,U,L)}}function b(L,...B){if(e.apply(this,arguments)){var M=L.touches,U=M.length,D=N(this,B,L.changedTouches.length===U).event(L),y,w,F,k;for(Zl(L),w=0;w<U;++w)F=M[w],k=bt(F,this),k=[k,this.__zoom.invert(k),F.identifier],D.touch0?!D.touch1&&D.touch0[2]!==k[2]&&(D.touch1=k,D.taps=0):(D.touch0=k,y=!0,D.taps=1+!!u);u&&(u=clearTimeout(u)),y&&(D.taps<2&&(E=k[0],u=setTimeout(function(){u=null},T)),ji(this),D.start())}}function P(L,...B){if(this.__zooming){var M=N(this,B).event(L),U=L.changedTouches,D=U.length,y,w,F,k;for(jo(L),y=0;y<D;++y)w=U[y],F=bt(w,this),M.touch0&&M.touch0[2]===w.identifier?M.touch0[0]=F:M.touch1&&M.touch1[2]===w.identifier&&(M.touch1[0]=F);if(w=M.that.__zoom,M.touch1){var V=M.touch0[0],ee=M.touch0[1],Y=M.touch1[0],te=M.touch1[1],ne=(ne=Y[0]-V[0])*ne+(ne=Y[1]-V[1])*ne,z=(z=te[0]-ee[0])*z+(z=te[1]-ee[1])*z;w=g(w,Math.sqrt(ne/z)),F=[(V[0]+Y[0])/2,(V[1]+Y[1])/2],k=[(ee[0]+te[0])/2,(ee[1]+te[1])/2]}else if(M.touch0)F=M.touch0[0],k=M.touch0[1];else return;M.zoom("touch",n(m(w,F,k),M.extent,a))}}function j(L,...B){if(this.__zooming){var M=N(this,B).event(L),U=L.changedTouches,D=U.length,y,w;for(Zl(L),f&&clearTimeout(f),f=setTimeout(function(){f=null},T),y=0;y<D;++y)w=U[y],M.touch0&&M.touch0[2]===w.identifier?delete M.touch0:M.touch1&&M.touch1[2]===w.identifier&&delete M.touch1;if(M.touch1&&!M.touch0&&(M.touch0=M.touch1,delete M.touch1),M.touch0)M.touch0[1]=this.__zoom.invert(M.touch0[0]);else if(M.end(),M.taps===2&&(w=bt(w,this),Math.hypot(E[0]-w[0],E[1]-w[1])<S)){var F=Et(this).on("dblclick.zoom");F&&F.apply(this,arguments)}}}return h.wheelDelta=function(L){return arguments.length?(r=typeof L=="function"?L:fi(+L),h):r},h.filter=function(L){return arguments.length?(e=typeof L=="function"?L:fi(!!L),h):e},h.touchable=function(L){return arguments.length?(s=typeof L=="function"?L:fi(!!L),h):s},h.extent=function(L){return arguments.length?(t=typeof L=="function"?L:fi([[+L[0][0],+L[0][1]],[+L[1][0],+L[1][1]]]),h):t},h.scaleExtent=function(L){return arguments.length?(i[0]=+L[0],i[1]=+L[1],h):[i[0],i[1]]},h.translateExtent=function(L){return arguments.length?(a[0][0]=+L[0][0],a[1][0]=+L[1][0],a[0][1]=+L[0][1],a[1][1]=+L[1][1],h):[[a[0][0],a[0][1]],[a[1][0],a[1][1]]]},h.constrain=function(L){return arguments.length?(n=L,h):n},h.duration=function(L){return arguments.length?(l=+L,h):l},h.interpolate=function(L){return arguments.length?(c=L,h):c},h.on=function(){var L=d.on.apply(d,arguments);return L===d?h:L},h.clickDistance=function(L){return arguments.length?(R=(L=+L)*L,h):Math.sqrt(R)},h.tapDistance=function(L){return arguments.length?(S=+L,h):S},h}const rn={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${e==="source"?n:r}", edge id: ${t}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."},us=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],jA=["Enter"," ","Escape"],kA={"node.a11yDescription.default":"Press enter or space to select a node. Press delete to remove it and escape to cancel.","node.a11yDescription.keyboardDisabled":"Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.","node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:n})=>`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.","controls.ariaLabel":"Control Panel","controls.zoomIn.ariaLabel":"Zoom In","controls.zoomOut.ariaLabel":"Zoom Out","controls.fitView.ariaLabel":"Fit View","controls.interactive.ariaLabel":"Toggle Interactivity","minimap.ariaLabel":"Mini Map","handle.ariaLabel":"Handle"};var uo;(function(e){e.Strict="strict",e.Loose="loose"})(uo||(uo={}));var dr;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(dr||(dr={}));var Es;(function(e){e.Partial="partial",e.Full="full"})(Es||(Es={}));const FA={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var bn;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(bn||(bn={}));var Eo;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(Eo||(Eo={}));var pe;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(pe||(pe={}));const Gf={[pe.Left]:pe.Right,[pe.Right]:pe.Left,[pe.Top]:pe.Bottom,[pe.Bottom]:pe.Top};function GA(e){return e===null?null:e?"valid":"invalid"}const HA=e=>"id"in e&&"source"in e&&"target"in e,rU=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),vu=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),bs=(e,t=[0,0])=>{const{width:n,height:r}=An(e),s=e.origin??t,i=n*s[0],a=r*s[1];return{x:e.position.x-i,y:e.position.y-a}},oU=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,s)=>{const i=typeof s=="string";let a=!t.nodeLookup&&!i?s:void 0;t.nodeLookup&&(a=i?t.nodeLookup.get(s):vu(s)?s:t.nodeLookup.get(s.id));const l=a?ua(a,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return Za(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return el(n)},vs=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(s=>{(t.filter===void 0||t.filter(s))&&(n=Za(n,ua(s)),r=!0)}),r?el(n):{x:0,y:0,width:0,height:0}},Du=(e,t,[n,r,s]=[0,0,1],i=!1,a=!1)=>{const l={...Ms(t,[n,r,s]),width:t.width/s,height:t.height/s},c=[];for(const d of e.values()){const{measured:u,selectable:E=!0,hidden:f=!1}=d;if(a&&!E||f)continue;const T=u.width??d.width??d.initialWidth??null,A=u.height??d.height??d.initialHeight??null,R=fs(l,po(d)),S=(T??0)*(A??0),h=i&&R>0;(!d.internals.handleBounds||h||R>=S||d.dragging)&&c.push(d)}return c},sU=(e,t)=>{const n=new Set;return e.forEach(r=>{n.add(r.id)}),t.filter(r=>n.has(r.source)||n.has(r.target))};function iU(e,t){const n=new Map,r=t!=null&&t.nodes?new Set(t.nodes.map(s=>s.id)):null;return e.forEach(s=>{s.measured.width&&s.measured.height&&((t==null?void 0:t.includeHiddenNodes)||!s.hidden)&&(!r||r.has(s.id))&&n.set(s.id,s)}),n}async function aU({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:i},a){if(e.size===0)return Promise.resolve(!0);const l=iU(e,a),c=vs(l),d=Mu(c,t,n,(a==null?void 0:a.minZoom)??s,(a==null?void 0:a.maxZoom)??i,(a==null?void 0:a.padding)??.1);return await r.setViewport(d,{duration:a==null?void 0:a.duration,ease:a==null?void 0:a.ease,interpolate:a==null?void 0:a.interpolate}),Promise.resolve(!0)}function WA({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:i}){const a=n.get(e),l=a.parentId?n.get(a.parentId):void 0,{x:c,y:d}=l?l.internals.positionAbsolute:{x:0,y:0},u=a.origin??r;let E=a.extent||s;if(a.extent==="parent"&&!a.expandParent)if(!l)i==null||i("005",rn.error005());else{const T=l.measured.width,A=l.measured.height;T&&A&&(E=[[c,d],[c+T,d+A]])}else l&&To(a.extent)&&(E=[[a.extent[0][0]+c,a.extent[0][1]+d],[a.extent[1][0]+c,a.extent[1][1]+d]]);const f=To(E)?Ar(t,E,a.measured):t;return(a.measured.width===void 0||a.measured.height===void 0)&&(i==null||i("015",rn.error015())),{position:{x:f.x-c+(a.measured.width??0)*u[0],y:f.y-d+(a.measured.height??0)*u[1]},positionAbsolute:f}}async function lU({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const i=new Set(e.map(f=>f.id)),a=[];for(const f of n){if(f.deletable===!1)continue;const T=i.has(f.id),A=!T&&f.parentId&&a.find(R=>R.id===f.parentId);(T||A)&&a.push(f)}const l=new Set(t.map(f=>f.id)),c=r.filter(f=>f.deletable!==!1),u=sU(a,c);for(const f of c)l.has(f.id)&&!u.find(A=>A.id===f.id)&&u.push(f);if(!s)return{edges:u,nodes:a};const E=await s({nodes:a,edges:u});return typeof E=="boolean"?E?{edges:u,nodes:a}:{edges:[],nodes:[]}:E}const fo=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Ar=(e={x:0,y:0},t,n)=>({x:fo(e.x,t[0][0],t[1][0]-((n==null?void 0:n.width)??0)),y:fo(e.y,t[0][1],t[1][1]-((n==null?void 0:n.height)??0))});function YA(e,t,n){const{width:r,height:s}=An(n),{x:i,y:a}=n.internals.positionAbsolute;return Ar(e,[[i,a],[i+r,a+s]],t)}const Hf=(e,t,n)=>e<t?fo(Math.abs(e-t),1,t)/t:e>n?-fo(Math.abs(e-n),1,t)/t:0,$A=(e,t,n=15,r=40)=>{const s=Hf(e.x,r,t.width-r)*n,i=Hf(e.y,r,t.height-r)*n;return[s,i]},Za=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),Id=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),el=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),po=(e,t=[0,0])=>{var s,i;const{x:n,y:r}=vu(e)?e.internals.positionAbsolute:bs(e,t);return{x:n,y:r,width:((s=e.measured)==null?void 0:s.width)??e.width??e.initialWidth??0,height:((i=e.measured)==null?void 0:i.height)??e.height??e.initialHeight??0}},ua=(e,t=[0,0])=>{var s,i;const{x:n,y:r}=vu(e)?e.internals.positionAbsolute:bs(e,t);return{x:n,y:r,x2:n+(((s=e.measured)==null?void 0:s.width)??e.width??e.initialWidth??0),y2:r+(((i=e.measured)==null?void 0:i.height)??e.height??e.initialHeight??0)}},VA=(e,t)=>el(Za(Id(e),Id(t))),fs=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)},Wf=e=>wt(e.width)&&wt(e.height)&&wt(e.x)&&wt(e.y),wt=e=>!isNaN(e)&&isFinite(e),cU=(e,t)=>{},Ds=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),Ms=({x:e,y:t},[n,r,s],i=!1,a=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return i?Ds(l,a):l},Ea=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function Wr(e,t){if(typeof e=="number")return Math.floor((t-t/(1+e))*.5);if(typeof e=="string"&&e.endsWith("px")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(n)}if(typeof e=="string"&&e.endsWith("%")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`[React Flow] The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function dU(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=Wr(e,n),s=Wr(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=Wr(e.top??e.y??0,n),s=Wr(e.bottom??e.y??0,n),i=Wr(e.left??e.x??0,t),a=Wr(e.right??e.x??0,t);return{top:r,right:a,bottom:s,left:i,x:i+a,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function uU(e,t,n,r,s,i){const{x:a,y:l}=Ea(e,[t,n,r]),{x:c,y:d}=Ea({x:e.x+e.width,y:e.y+e.height},[t,n,r]),u=s-c,E=i-d;return{left:Math.floor(a),top:Math.floor(l),right:Math.floor(u),bottom:Math.floor(E)}}const Mu=(e,t,n,r,s,i)=>{const a=dU(i,t,n),l=(t-a.x)/e.width,c=(n-a.y)/e.height,d=Math.min(l,c),u=fo(d,r,s),E=e.x+e.width/2,f=e.y+e.height/2,T=t/2-E*u,A=n/2-f*u,R=uU(e,T,A,u,t,n),S={left:Math.min(R.left-a.left,0),top:Math.min(R.top-a.top,0),right:Math.min(R.right-a.right,0),bottom:Math.min(R.bottom-a.bottom,0)};return{x:T-S.left+S.right,y:A-S.top+S.bottom,zoom:u}},ps=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0};function To(e){return e!=null&&e!=="parent"}function An(e){var t,n;return{width:((t=e.measured)==null?void 0:t.width)??e.width??e.initialWidth??0,height:((n=e.measured)==null?void 0:n.height)??e.height??e.initialHeight??0}}function zA(e){var t,n;return(((t=e.measured)==null?void 0:t.width)??e.width??e.initialWidth)!==void 0&&(((n=e.measured)==null?void 0:n.height)??e.height??e.initialHeight)!==void 0}function XA(e,t={width:0,height:0},n,r,s){const i={...e},a=r.get(n);if(a){const l=a.origin||s;i.x+=a.internals.positionAbsolute.x-(t.width??0)*l[0],i.y+=a.internals.positionAbsolute.y-(t.height??0)*l[1]}return i}function Yf(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function EU(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function fU(e){return{...kA,...e||{}}}function Ko(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:i,y:a}=Ut(e),l=Ms({x:i-((s==null?void 0:s.left)??0),y:a-((s==null?void 0:s.top)??0)},r),{x:c,y:d}=n?Ds(l,t):l;return{xSnapped:c,ySnapped:d,...l}}const Pu=e=>({width:e.offsetWidth,height:e.offsetHeight}),KA=e=>{var t;return((t=e==null?void 0:e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},pU=["INPUT","SELECT","TEXTAREA"];function qA(e){var r,s;const t=((s=(r=e.composedPath)==null?void 0:r.call(e))==null?void 0:s[0])||e.target;return(t==null?void 0:t.nodeType)!==1?!1:pU.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const JA=e=>"clientX"in e,Ut=(e,t)=>{var i,a;const n=JA(e),r=n?e.clientX:(i=e.touches)==null?void 0:i[0].clientX,s=n?e.clientY:(a=e.touches)==null?void 0:a[0].clientY;return{x:r-((t==null?void 0:t.left)??0),y:s-((t==null?void 0:t.top)??0)}},$f=(e,t,n,r,s)=>{const i=t.querySelectorAll(`.${e}`);return!i||!i.length?null:Array.from(i).map(a=>{const l=a.getBoundingClientRect();return{id:a.getAttribute("data-handleid"),type:e,nodeId:s,position:a.getAttribute("data-handlepos"),x:(l.left-n.left)/r,y:(l.top-n.top)/r,...Pu(a)}})};function QA({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:i,targetControlX:a,targetControlY:l}){const c=e*.125+s*.375+a*.375+n*.125,d=t*.125+i*.375+l*.375+r*.125,u=Math.abs(c-e),E=Math.abs(d-t);return[c,d,u,E]}function pi(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Vf({pos:e,x1:t,y1:n,x2:r,y2:s,c:i}){switch(e){case pe.Left:return[t-pi(t-r,i),n];case pe.Right:return[t+pi(r-t,i),n];case pe.Top:return[t,n-pi(n-s,i)];case pe.Bottom:return[t,n+pi(s-n,i)]}}function ZA({sourceX:e,sourceY:t,sourcePosition:n=pe.Bottom,targetX:r,targetY:s,targetPosition:i=pe.Top,curvature:a=.25}){const[l,c]=Vf({pos:n,x1:e,y1:t,x2:r,y2:s,c:a}),[d,u]=Vf({pos:i,x1:r,y1:s,x2:e,y2:t,c:a}),[E,f,T,A]=QA({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:l,sourceControlY:c,targetControlX:d,targetControlY:u});return[`M${e},${t} C${l},${c} ${d},${u} ${r},${s}`,E,f,T,A]}function em({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,i=n<e?n+s:n-s,a=Math.abs(r-t)/2,l=r<t?r+a:r-a;return[i,l,s,a]}function TU({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:i="basic"}){if(i==="manual")return r;const a=s&&n?r+1e3:r,l=Math.max(e.parentId||s&&e.selected?e.internals.z:0,t.parentId||s&&t.selected?t.internals.z:0);return a+l}function SU({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const i=Za(ua(e),ua(t));i.x===i.x2&&(i.x2+=1),i.y===i.y2&&(i.y2+=1);const a={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return fs(a,el(i))>0}const hU=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,RU=(e,t)=>t.some(n=>n.source===e.source&&n.target===e.target&&(n.sourceHandle===e.sourceHandle||!n.sourceHandle&&!e.sourceHandle)&&(n.targetHandle===e.targetHandle||!n.targetHandle&&!e.targetHandle)),AU=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||hU;let s;return HA(e)?s={...e}:s={...e,id:r(e)},RU(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function tm({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,i,a,l]=em({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,i,a,l]}const zf={[pe.Left]:{x:-1,y:0},[pe.Right]:{x:1,y:0},[pe.Top]:{x:0,y:-1},[pe.Bottom]:{x:0,y:1}},mU=({source:e,sourcePosition:t=pe.Bottom,target:n})=>t===pe.Left||t===pe.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},Xf=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function gU({source:e,sourcePosition:t=pe.Bottom,target:n,targetPosition:r=pe.Top,center:s,offset:i,stepPosition:a}){const l=zf[t],c=zf[r],d={x:e.x+l.x*i,y:e.y+l.y*i},u={x:n.x+c.x*i,y:n.y+c.y*i},E=mU({source:d,sourcePosition:t,target:u}),f=E.x!==0?"x":"y",T=E[f];let A=[],R,S;const h={x:0,y:0},g={x:0,y:0},[,,m,I]=em({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[f]*c[f]===-1){f==="x"?(R=s.x??d.x+(u.x-d.x)*a,S=s.y??(d.y+u.y)/2):(R=s.x??(d.x+u.x)/2,S=s.y??d.y+(u.y-d.y)*a);const N=[{x:R,y:d.y},{x:R,y:u.y}],x=[{x:d.x,y:S},{x:u.x,y:S}];l[f]===T?A=f==="x"?N:x:A=f==="x"?x:N}else{const N=[{x:d.x,y:u.y}],x=[{x:u.x,y:d.y}];if(f==="x"?A=l.x===T?x:N:A=l.y===T?N:x,t===r){const P=Math.abs(e[f]-n[f]);if(P<=i){const j=Math.min(i-1,i-P);l[f]===T?h[f]=(d[f]>e[f]?-1:1)*j:g[f]=(u[f]>n[f]?-1:1)*j}}if(t!==r){const P=f==="x"?"y":"x",j=l[f]===c[P],L=d[P]>u[P],B=d[P]<u[P];(l[f]===1&&(!j&&L||j&&B)||l[f]!==1&&(!j&&B||j&&L))&&(A=f==="x"?N:x)}const _={x:d.x+h.x,y:d.y+h.y},C={x:u.x+g.x,y:u.y+g.y},v=Math.max(Math.abs(_.x-A[0].x),Math.abs(C.x-A[0].x)),b=Math.max(Math.abs(_.y-A[0].y),Math.abs(C.y-A[0].y));v>=b?(R=(_.x+C.x)/2,S=A[0].y):(R=A[0].x,S=(_.y+C.y)/2)}return[[e,{x:d.x+h.x,y:d.y+h.y},...A,{x:u.x+g.x,y:u.y+g.y},n],R,S,m,I]}function IU(e,t,n,r){const s=Math.min(Xf(e,t)/2,Xf(t,n)/2,r),{x:i,y:a}=t;if(e.x===i&&i===n.x||e.y===a&&a===n.y)return`L${i} ${a}`;if(e.y===a){const d=e.x<n.x?-1:1,u=e.y<n.y?1:-1;return`L ${i+s*d},${a}Q ${i},${a} ${i},${a+s*u}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${i},${a+s*c}Q ${i},${a} ${i+s*l},${a}`}function Od({sourceX:e,sourceY:t,sourcePosition:n=pe.Bottom,targetX:r,targetY:s,targetPosition:i=pe.Top,borderRadius:a=5,centerX:l,centerY:c,offset:d=20,stepPosition:u=.5}){const[E,f,T,A,R]=gU({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:i,center:{x:l,y:c},offset:d,stepPosition:u});return[E.reduce((h,g,m)=>{let I="";return m>0&&m<E.length-1?I=IU(E[m-1],g,E[m+1],a):I=`${m===0?"M":"L"}${g.x} ${g.y}`,h+=I,h},""),f,T,A,R]}function Kf(e){var t;return e&&!!(e.internals.handleBounds||(t=e.handles)!=null&&t.length)&&!!(e.measured.width||e.width||e.initialWidth)}function OU(e){var E;const{sourceNode:t,targetNode:n}=e;if(!Kf(t)||!Kf(n))return null;const r=t.internals.handleBounds||qf(t.handles),s=n.internals.handleBounds||qf(n.handles),i=Jf((r==null?void 0:r.source)??[],e.sourceHandle),a=Jf(e.connectionMode===uo.Strict?(s==null?void 0:s.target)??[]:((s==null?void 0:s.target)??[]).concat((s==null?void 0:s.source)??[]),e.targetHandle);if(!i||!a)return(E=e.onError)==null||E.call(e,"008",rn.error008(i?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=(i==null?void 0:i.position)||pe.Bottom,c=(a==null?void 0:a.position)||pe.Top,d=mr(t,i,l),u=mr(n,a,c);return{sourceX:d.x,sourceY:d.y,targetX:u.x,targetY:u.y,sourcePosition:l,targetPosition:c}}function qf(e){if(!e)return null;const t=[],n=[];for(const r of e)r.width=r.width??1,r.height=r.height??1,r.type==="source"?t.push(r):r.type==="target"&&n.push(r);return{source:t,target:n}}function mr(e,t,n=pe.Left,r=!1){const s=((t==null?void 0:t.x)??0)+e.internals.positionAbsolute.x,i=((t==null?void 0:t.y)??0)+e.internals.positionAbsolute.y,{width:a,height:l}=t??An(e);if(r)return{x:s+a/2,y:i+l/2};switch((t==null?void 0:t.position)??n){case pe.Top:return{x:s+a/2,y:i};case pe.Right:return{x:s+a,y:i+l/2};case pe.Bottom:return{x:s+a/2,y:i+l};case pe.Left:return{x:s,y:i+l/2}}}function Jf(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Nd(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function NU(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const i=new Set;return e.reduce((a,l)=>([l.markerStart||r,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const d=Nd(c,t);i.has(d)||(a.push({id:d,color:c.color||n,...c}),i.add(d))}}),a),[]).sort((a,l)=>a.id.localeCompare(l.id))}const nm=1e3,xU=10,wu={nodeOrigin:[0,0],nodeExtent:us,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},yU={...wu,checkEquality:!0};function Uu(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function CU(e,t,n){const r=Uu(wu,n);for(const s of e.values())if(s.parentId)ju(s,e,t,r);else{const i=bs(s,r.nodeOrigin),a=To(s.extent)?s.extent:r.nodeExtent,l=Ar(i,a,An(s));s.internals.positionAbsolute=l}}function LU(e,t){if(!e.handles)return e.measured?t==null?void 0:t.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const i={id:s.id,width:s.width??1,height:s.height??1,nodeId:e.id,x:s.x,y:s.y,position:s.position,type:s.type};s.type==="source"?n.push(i):s.type==="target"&&r.push(i)}return{source:n,target:r}}function Bu(e){return e==="manual"}function xd(e,t,n,r={}){var d,u;const s=Uu(yU,r),i={i:0},a=new Map(t),l=s!=null&&s.elevateNodesOnSelect&&!Bu(s.zIndexMode)?nm:0;let c=e.length>0;t.clear(),n.clear();for(const E of e){let f=a.get(E.id);if(s.checkEquality&&E===(f==null?void 0:f.internals.userNode))t.set(E.id,f);else{const T=bs(E,s.nodeOrigin),A=To(E.extent)?E.extent:s.nodeExtent,R=Ar(T,A,An(E));f={...s.defaults,...E,measured:{width:(d=E.measured)==null?void 0:d.width,height:(u=E.measured)==null?void 0:u.height},internals:{positionAbsolute:R,handleBounds:LU(E,f),z:rm(E,l,s.zIndexMode),userNode:E}},t.set(E.id,f)}(f.measured===void 0||f.measured.width===void 0||f.measured.height===void 0)&&!f.hidden&&(c=!1),E.parentId&&ju(f,t,n,r,i)}return c}function _U(e,t){if(!e.parentId)return;const n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}function ju(e,t,n,r,s){const{elevateNodesOnSelect:i,nodeOrigin:a,nodeExtent:l,zIndexMode:c}=Uu(wu,r),d=e.parentId,u=t.get(d);if(!u){console.warn(`Parent node ${d} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}_U(e,n),s&&!u.parentId&&u.internals.rootParentIndex===void 0&&c==="auto"&&(u.internals.rootParentIndex=++s.i,u.internals.z=u.internals.z+s.i*xU),s&&u.internals.rootParentIndex!==void 0&&(s.i=u.internals.rootParentIndex);const E=i&&!Bu(c)?nm:0,{x:f,y:T,z:A}=bU(e,u,a,l,E,c),{positionAbsolute:R}=e.internals,S=f!==R.x||T!==R.y;(S||A!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:S?{x:f,y:T}:R,z:A}})}function rm(e,t,n){const r=wt(e.zIndex)?e.zIndex:0;return Bu(n)?r:r+(e.selected?t:0)}function bU(e,t,n,r,s,i){const{x:a,y:l}=t.internals.positionAbsolute,c=An(e),d=bs(e,n),u=To(e.extent)?Ar(d,e.extent,c):d;let E=Ar({x:a+u.x,y:l+u.y},r,c);e.extent==="parent"&&(E=YA(E,c,t));const f=rm(e,s,i),T=t.internals.z??0;return{x:E.x,y:E.y,z:T>=f?T+1:f}}function ku(e,t,n,r=[0,0]){var a;const s=[],i=new Map;for(const l of e){const c=t.get(l.parentId);if(!c)continue;const d=((a=i.get(l.parentId))==null?void 0:a.expandedRect)??po(c),u=VA(d,l.rect);i.set(l.parentId,{expandedRect:u,parent:c})}return i.size>0&&i.forEach(({expandedRect:l,parent:c},d)=>{var m;const u=c.internals.positionAbsolute,E=An(c),f=c.origin??r,T=l.x<u.x?Math.round(Math.abs(u.x-l.x)):0,A=l.y<u.y?Math.round(Math.abs(u.y-l.y)):0,R=Math.max(E.width,Math.round(l.width)),S=Math.max(E.height,Math.round(l.height)),h=(R-E.width)*f[0],g=(S-E.height)*f[1];(T>0||A>0||h||g)&&(s.push({id:d,type:"position",position:{x:c.position.x-T+h,y:c.position.y-A+g}}),(m=n.get(d))==null||m.forEach(I=>{e.some(O=>O.id===I.id)||s.push({id:I.id,type:"position",position:{x:I.position.x+T,y:I.position.y+A}})})),(E.width<l.width||E.height<l.height||T||A)&&s.push({id:d,type:"dimensions",setAttributes:!0,dimensions:{width:R+(T?f[0]*T-h:0),height:S+(A?f[1]*A-g:0)}})}),s}function vU(e,t,n,r,s,i,a){const l=r==null?void 0:r.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const d=[],u=window.getComputedStyle(l),{m22:E}=new window.DOMMatrixReadOnly(u.transform),f=[];for(const T of e.values()){const A=t.get(T.id);if(!A)continue;if(A.hidden){t.set(A.id,{...A,internals:{...A.internals,handleBounds:void 0}}),c=!0;continue}const R=Pu(T.nodeElement),S=A.measured.width!==R.width||A.measured.height!==R.height;if(!!(R.width&&R.height&&(S||!A.internals.handleBounds||T.force))){const g=T.nodeElement.getBoundingClientRect(),m=To(A.extent)?A.extent:i;let{positionAbsolute:I}=A.internals;A.parentId&&A.extent==="parent"?I=YA(I,R,t.get(A.parentId)):m&&(I=Ar(I,m,R));const O={...A,measured:R,internals:{...A.internals,positionAbsolute:I,handleBounds:{source:$f("source",T.nodeElement,g,E,A.id),target:$f("target",T.nodeElement,g,E,A.id)}}};t.set(A.id,O),A.parentId&&ju(O,t,n,{nodeOrigin:s,zIndexMode:a}),c=!0,S&&(d.push({id:A.id,type:"dimensions",dimensions:R}),A.expandParent&&A.parentId&&f.push({id:A.id,parentId:A.parentId,rect:po(O,s)}))}}if(f.length>0){const T=ku(f,t,n,s);d.push(...T)}return{changes:d,updatedInternals:c}}async function DU({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:i}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const a=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,i]],r),l=!!a&&(a.x!==n[0]||a.y!==n[1]||a.k!==n[2]);return Promise.resolve(l)}function Qf(e,t,n,r,s,i){let a=s;const l=r.get(a)||new Map;r.set(a,l.set(n,t)),a=`${s}-${e}`;const c=r.get(a)||new Map;if(r.set(a,c.set(n,t)),i){a=`${s}-${e}-${i}`;const d=r.get(a)||new Map;r.set(a,d.set(n,t))}}function om(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:i,sourceHandle:a=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:i,sourceHandle:a,targetHandle:l},d=`${s}-${a}--${i}-${l}`,u=`${i}-${l}--${s}-${a}`;Qf("source",c,u,e,s,a),Qf("target",c,d,e,i,l),t.set(r.id,r)}}function sm(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:sm(n,t):!1}function Zf(e,t,n){var s;let r=e;do{if((s=r==null?void 0:r.matches)!=null&&s.call(r,t))return!0;if(r===n)return!1;r=r==null?void 0:r.parentElement}while(r);return!1}function MU(e,t,n,r){const s=new Map;for(const[i,a]of e)if((a.selected||a.id===r)&&(!a.parentId||!sm(a,e))&&(a.draggable||t&&typeof a.draggable>"u")){const l=e.get(i);l&&s.set(i,{id:i,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return s}function ec({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){var a,l,c;const s=[];for(const[d,u]of t){const E=(a=n.get(d))==null?void 0:a.internals.userNode;E&&s.push({...E,position:u.position,dragging:r})}if(!e)return[s[0],s];const i=(l=n.get(e))==null?void 0:l.internals.userNode;return[i?{...i,position:((c=t.get(e))==null?void 0:c.position)||i.position,dragging:r}:s[0],s]}function PU({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const i={x:n-s.distance.x,y:r-s.distance.y},a=Ds(i,t);return{x:a.x-i.x,y:a.y-i.y}}function wU({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let i={x:null,y:null},a=0,l=new Map,c=!1,d={x:0,y:0},u=null,E=!1,f=null,T=!1,A=!1,R=null;function S({noDragClassName:g,handleSelector:m,domNode:I,isSelectable:O,nodeId:N,nodeClickDistance:x=0}){f=Et(I);function _({x:P,y:j}){const{nodeLookup:L,nodeExtent:B,snapGrid:M,snapToGrid:U,nodeOrigin:D,onNodeDrag:y,onSelectionDrag:w,onError:F,updateNodePositions:k}=t();i={x:P,y:j};let V=!1;const ee=l.size>1,Y=ee&&B?Id(vs(l)):null,te=ee&&U?PU({dragItems:l,snapGrid:M,x:P,y:j}):null;for(const[ne,z]of l){if(!L.has(ne))continue;let oe={x:P-z.distance.x,y:j-z.distance.y};U&&(oe=te?{x:Math.round(oe.x+te.x),y:Math.round(oe.y+te.y)}:Ds(oe,M));let le=null;if(ee&&B&&!z.extent&&Y){const{positionAbsolute:H}=z.internals,re=H.x-Y.x+B[0][0],ie=H.x+z.measured.width-Y.x2+B[1][0],de=H.y-Y.y+B[0][1],se=H.y+z.measured.height-Y.y2+B[1][1];le=[[re,de],[ie,se]]}const{position:ae,positionAbsolute:X}=WA({nodeId:ne,nextPosition:oe,nodeLookup:L,nodeExtent:le||B,nodeOrigin:D,onError:F});V=V||z.position.x!==ae.x||z.position.y!==ae.y,z.position=ae,z.internals.positionAbsolute=X}if(A=A||V,!!V&&(k(l,!0),R&&(r||y||!N&&w))){const[ne,z]=ec({nodeId:N,dragItems:l,nodeLookup:L});r==null||r(R,l,ne,z),y==null||y(R,ne,z),N||w==null||w(R,z)}}async function C(){if(!u)return;const{transform:P,panBy:j,autoPanSpeed:L,autoPanOnNodeDrag:B}=t();if(!B){c=!1,cancelAnimationFrame(a);return}const[M,U]=$A(d,u,L);(M!==0||U!==0)&&(i.x=(i.x??0)-M/P[2],i.y=(i.y??0)-U/P[2],await j({x:M,y:U})&&_(i)),a=requestAnimationFrame(C)}function v(P){var ee;const{nodeLookup:j,multiSelectionActive:L,nodesDraggable:B,transform:M,snapGrid:U,snapToGrid:D,selectNodesOnDrag:y,onNodeDragStart:w,onSelectionDragStart:F,unselectNodesAndEdges:k}=t();E=!0,(!y||!O)&&!L&&N&&((ee=j.get(N))!=null&&ee.selected||k()),O&&y&&N&&(e==null||e(N));const V=Ko(P.sourceEvent,{transform:M,snapGrid:U,snapToGrid:D,containerBounds:u});if(i=V,l=MU(j,B,V,N),l.size>0&&(n||w||!N&&F)){const[Y,te]=ec({nodeId:N,dragItems:l,nodeLookup:j});n==null||n(P.sourceEvent,l,Y,te),w==null||w(P.sourceEvent,Y,te),N||F==null||F(P.sourceEvent,te)}}const b=IA().clickDistance(x).on("start",P=>{const{domNode:j,nodeDragThreshold:L,transform:B,snapGrid:M,snapToGrid:U}=t();u=(j==null?void 0:j.getBoundingClientRect())||null,T=!1,A=!1,R=P.sourceEvent,L===0&&v(P),i=Ko(P.sourceEvent,{transform:B,snapGrid:M,snapToGrid:U,containerBounds:u}),d=Ut(P.sourceEvent,u)}).on("drag",P=>{const{autoPanOnNodeDrag:j,transform:L,snapGrid:B,snapToGrid:M,nodeDragThreshold:U,nodeLookup:D}=t(),y=Ko(P.sourceEvent,{transform:L,snapGrid:B,snapToGrid:M,containerBounds:u});if(R=P.sourceEvent,(P.sourceEvent.type==="touchmove"&&P.sourceEvent.touches.length>1||N&&!D.has(N))&&(T=!0),!T){if(!c&&j&&E&&(c=!0,C()),!E){const w=Ut(P.sourceEvent,u),F=w.x-d.x,k=w.y-d.y;Math.sqrt(F*F+k*k)>U&&v(P)}(i.x!==y.xSnapped||i.y!==y.ySnapped)&&l&&E&&(d=Ut(P.sourceEvent,u),_(y))}}).on("end",P=>{if(!(!E||T)&&(c=!1,E=!1,cancelAnimationFrame(a),l.size>0)){const{nodeLookup:j,updateNodePositions:L,onNodeDragStop:B,onSelectionDragStop:M}=t();if(A&&(L(l,!1),A=!1),s||B||!N&&M){const[U,D]=ec({nodeId:N,dragItems:l,nodeLookup:j,dragging:!1});s==null||s(P.sourceEvent,l,U,D),B==null||B(P.sourceEvent,U,D),N||M==null||M(P.sourceEvent,D)}}}).filter(P=>{const j=P.target;return!P.button&&(!g||!Zf(j,`.${g}`,I))&&(!m||Zf(j,m,I))});f.call(b)}function h(){f==null||f.on(".drag",null)}return{update:S,destroy:h}}function UU(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const i of t.values())fs(s,po(i))>0&&r.push(i);return r}const BU=250;function jU(e,t,n,r){var l,c;let s=[],i=1/0;const a=UU(e,n,t+BU);for(const d of a){const u=[...((l=d.internals.handleBounds)==null?void 0:l.source)??[],...((c=d.internals.handleBounds)==null?void 0:c.target)??[]];for(const E of u){if(r.nodeId===E.nodeId&&r.type===E.type&&r.id===E.id)continue;const{x:f,y:T}=mr(d,E,E.position,!0),A=Math.sqrt(Math.pow(f-e.x,2)+Math.pow(T-e.y,2));A>t||(A<i?(s=[{...E,x:f,y:T}],i=A):A===i&&s.push({...E,x:f,y:T}))}}if(!s.length)return null;if(s.length>1){const d=r.type==="source"?"target":"source";return s.find(u=>u.type===d)??s[0]}return s[0]}function im(e,t,n,r,s,i=!1){var d,u,E;const a=r.get(e);if(!a)return null;const l=s==="strict"?(d=a.internals.handleBounds)==null?void 0:d[t]:[...((u=a.internals.handleBounds)==null?void 0:u.source)??[],...((E=a.internals.handleBounds)==null?void 0:E.target)??[]],c=(n?l==null?void 0:l.find(f=>f.id===n):l==null?void 0:l[0])??null;return c&&i?{...c,...mr(a,c,c.position,!0)}:c}function am(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function kU(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const lm=()=>!0;function FU(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:i,isTarget:a,domNode:l,nodeLookup:c,lib:d,autoPanOnConnect:u,flowId:E,panBy:f,cancelConnection:T,onConnectStart:A,onConnect:R,onConnectEnd:S,isValidConnection:h=lm,onReconnectEnd:g,updateConnection:m,getTransform:I,getFromHandle:O,autoPanSpeed:N,dragThreshold:x=1,handleDomNode:_}){const C=KA(e.target);let v=0,b;const{x:P,y:j}=Ut(e),L=am(i,_),B=l==null?void 0:l.getBoundingClientRect();let M=!1;if(!B||!L)return;const U=im(s,L,r,c,t);if(!U)return;let D=Ut(e,B),y=!1,w=null,F=!1,k=null;function V(){if(!u||!B)return;const[ae,X]=$A(D,B,N);f({x:ae,y:X}),v=requestAnimationFrame(V)}const ee={...U,nodeId:s,type:L,position:U.position},Y=c.get(s);let ne={inProgress:!0,isValid:null,from:mr(Y,ee,pe.Left,!0),fromHandle:ee,fromPosition:ee.position,fromNode:Y,to:D,toHandle:null,toPosition:Gf[ee.position],toNode:null,pointer:D};function z(){M=!0,m(ne),A==null||A(e,{nodeId:s,handleId:r,handleType:L})}x===0&&z();function oe(ae){if(!M){const{x:se,y:ge}=Ut(ae),xe=se-P,Fe=ge-j;if(!(xe*xe+Fe*Fe>x*x))return;z()}if(!O()||!ee){le(ae);return}const X=I();D=Ut(ae,B),b=jU(Ms(D,X,!1,[1,1]),n,c,ee),y||(V(),y=!0);const H=cm(ae,{handle:b,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:a?"target":"source",isValidConnection:h,doc:C,lib:d,flowId:E,nodeLookup:c});k=H.handleDomNode,w=H.connection,F=kU(!!b,H.isValid);const re=c.get(s),ie=re?mr(re,ee,pe.Left,!0):ne.from,de={...ne,from:ie,isValid:F,to:H.toHandle&&F?Ea({x:H.toHandle.x,y:H.toHandle.y},X):D,toHandle:H.toHandle,toPosition:F&&H.toHandle?H.toHandle.position:Gf[ee.position],toNode:H.toHandle?c.get(H.toHandle.nodeId):null,pointer:D};m(de),ne=de}function le(ae){if(!("touches"in ae&&ae.touches.length>0)){if(M){(b||k)&&w&&F&&(R==null||R(w));const{inProgress:X,...H}=ne,re={...H,toPosition:ne.toHandle?ne.toPosition:null};S==null||S(ae,re),i&&(g==null||g(ae,re))}T(),cancelAnimationFrame(v),y=!1,F=!1,w=null,k=null,C.removeEventListener("mousemove",oe),C.removeEventListener("mouseup",le),C.removeEventListener("touchmove",oe),C.removeEventListener("touchend",le)}}C.addEventListener("mousemove",oe),C.addEventListener("mouseup",le),C.addEventListener("touchmove",oe),C.addEventListener("touchend",le)}function cm(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:i,doc:a,lib:l,flowId:c,isValidConnection:d=lm,nodeLookup:u}){const E=i==="target",f=t?a.querySelector(`.${l}-flow__handle[data-id="${c}-${t==null?void 0:t.nodeId}-${t==null?void 0:t.id}-${t==null?void 0:t.type}"]`):null,{x:T,y:A}=Ut(e),R=a.elementFromPoint(T,A),S=R!=null&&R.classList.contains(`${l}-flow__handle`)?R:f,h={handleDomNode:S,isValid:!1,connection:null,toHandle:null};if(S){const g=am(void 0,S),m=S.getAttribute("data-nodeid"),I=S.getAttribute("data-handleid"),O=S.classList.contains("connectable"),N=S.classList.contains("connectableend");if(!m||!g)return h;const x={source:E?m:r,sourceHandle:E?I:s,target:E?r:m,targetHandle:E?s:I};h.connection=x;const C=O&&N&&(n===uo.Strict?E&&g==="source"||!E&&g==="target":m!==r||I!==s);h.isValid=C&&d(x),h.toHandle=im(m,g,I,u,n,!0)}return h}const yd={onPointerDown:FU,isValid:cm};function GU({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Et(e);function i({translateExtent:l,width:c,height:d,zoomStep:u=1,pannable:E=!0,zoomable:f=!0,inversePan:T=!1}){const A=m=>{if(m.sourceEvent.type!=="wheel"||!t)return;const I=n(),O=m.sourceEvent.ctrlKey&&ps()?10:1,N=-m.sourceEvent.deltaY*(m.sourceEvent.deltaMode===1?.05:m.sourceEvent.deltaMode?1:.002)*u,x=I[2]*Math.pow(2,N*O);t.scaleTo(x)};let R=[0,0];const S=m=>{(m.sourceEvent.type==="mousedown"||m.sourceEvent.type==="touchstart")&&(R=[m.sourceEvent.clientX??m.sourceEvent.touches[0].clientX,m.sourceEvent.clientY??m.sourceEvent.touches[0].clientY])},h=m=>{const I=n();if(m.sourceEvent.type!=="mousemove"&&m.sourceEvent.type!=="touchmove"||!t)return;const O=[m.sourceEvent.clientX??m.sourceEvent.touches[0].clientX,m.sourceEvent.clientY??m.sourceEvent.touches[0].clientY],N=[O[0]-R[0],O[1]-R[1]];R=O;const x=r()*Math.max(I[2],Math.log(I[2]))*(T?-1:1),_={x:I[0]-N[0]*x,y:I[1]-N[1]*x},C=[[0,0],[c,d]];t.setViewportConstrained({x:_.x,y:_.y,zoom:I[2]},C,l)},g=BA().on("start",S).on("zoom",E?h:null).on("zoom.wheel",f?A:null);s.call(g,{})}function a(){s.on("zoom",null)}return{update:i,destroy:a,pointer:bt}}const tl=e=>({x:e.x,y:e.y,zoom:e.k}),tc=({x:e,y:t,zoom:n})=>Qa.translate(e,t).scale(n),Xr=(e,t)=>e.target.closest(`.${t}`),dm=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),HU=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,nc=(e,t=0,n=HU,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},um=e=>{const t=e.ctrlKey&&ps()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function WU({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:i,zoomOnPinch:a,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:d}){return u=>{if(Xr(u,t))return u.ctrlKey&&u.preventDefault(),!1;u.preventDefault(),u.stopImmediatePropagation();const E=n.property("__zoom").k||1;if(u.ctrlKey&&a){const S=bt(u),h=um(u),g=E*Math.pow(2,h);r.scaleTo(n,g,S,u);return}const f=u.deltaMode===1?20:1;let T=s===dr.Vertical?0:u.deltaX*f,A=s===dr.Horizontal?0:u.deltaY*f;!ps()&&u.shiftKey&&s!==dr.Vertical&&(T=u.deltaY*f,A=0),r.translateBy(n,-(T/E)*i,-(A/E)*i,{internal:!0});const R=tl(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c==null||c(u,R),e.panScrollTimeout=setTimeout(()=>{d==null||d(u,R),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l==null||l(u,R))}}function YU({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const i=r.type==="wheel",a=!t&&i&&!r.ctrlKey,l=Xr(r,e);if(r.ctrlKey&&i&&l&&r.preventDefault(),a||l)return null;r.preventDefault(),n.call(this,r,s)}}function $U({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{var i,a,l;if((i=r.sourceEvent)!=null&&i.internal)return;const s=tl(r.transform);e.mouseButton=((a=r.sourceEvent)==null?void 0:a.button)||0,e.isZoomingOrPanning=!0,e.prevViewport=s,((l=r.sourceEvent)==null?void 0:l.type)==="mousedown"&&t(!0),n&&(n==null||n(r.sourceEvent,s))}}function VU({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return i=>{var a,l;e.usedRightMouseButton=!!(n&&dm(t,e.mouseButton??0)),(a=i.sourceEvent)!=null&&a.sync||r([i.transform.x,i.transform.y,i.transform.k]),s&&!((l=i.sourceEvent)!=null&&l.internal)&&(s==null||s(i.sourceEvent,tl(i.transform)))}}function zU({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:i}){return a=>{var l;if(!((l=a.sourceEvent)!=null&&l.internal)&&(e.isZoomingOrPanning=!1,i&&dm(t,e.mouseButton??0)&&!e.usedRightMouseButton&&a.sourceEvent&&i(a.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const c=tl(a.transform);e.prevViewport=c,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s==null||s(a.sourceEvent,c)},n?150:0)}}}function XU({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:s,zoomOnDoubleClick:i,userSelectionActive:a,noWheelClassName:l,noPanClassName:c,lib:d,connectionInProgress:u}){return E=>{var S;const f=e||t,T=n&&E.ctrlKey,A=E.type==="wheel";if(E.button===1&&E.type==="mousedown"&&(Xr(E,`${d}-flow__node`)||Xr(E,`${d}-flow__edge`)))return!0;if(!r&&!f&&!s&&!i&&!n||a||u&&!A||Xr(E,l)&&A||Xr(E,c)&&(!A||s&&A&&!e)||!n&&E.ctrlKey&&A)return!1;if(!n&&E.type==="touchstart"&&((S=E.touches)==null?void 0:S.length)>1)return E.preventDefault(),!1;if(!f&&!s&&!T&&A||!r&&(E.type==="mousedown"||E.type==="touchstart")||Array.isArray(r)&&!r.includes(E.button)&&E.type==="mousedown")return!1;const R=Array.isArray(r)&&r.includes(E.button)||!E.button||E.button<=1;return(!E.ctrlKey||A)&&R}}function KU({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:i,onPanZoomStart:a,onPanZoomEnd:l,onDraggingChange:c}){const d={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},u=e.getBoundingClientRect(),E=BA().scaleExtent([t,n]).translateExtent(r),f=Et(e).call(E);g({x:s.x,y:s.y,zoom:fo(s.zoom,t,n)},[[0,0],[u.width,u.height]],r);const T=f.on("wheel.zoom"),A=f.on("dblclick.zoom");E.wheelDelta(um);function R(b,P){return f?new Promise(j=>{E==null||E.interpolate((P==null?void 0:P.interpolate)==="linear"?Xo:wi).transform(nc(f,P==null?void 0:P.duration,P==null?void 0:P.ease,()=>j(!0)),b)}):Promise.resolve(!1)}function S({noWheelClassName:b,noPanClassName:P,onPaneContextMenu:j,userSelectionActive:L,panOnScroll:B,panOnDrag:M,panOnScrollMode:U,panOnScrollSpeed:D,preventScrolling:y,zoomOnPinch:w,zoomOnScroll:F,zoomOnDoubleClick:k,zoomActivationKeyPressed:V,lib:ee,onTransformChange:Y,connectionInProgress:te,paneClickDistance:ne,selectionOnDrag:z}){L&&!d.isZoomingOrPanning&&h();const oe=B&&!V&&!L;E.clickDistance(z?1/0:!wt(ne)||ne<0?0:ne);const le=oe?WU({zoomPanValues:d,noWheelClassName:b,d3Selection:f,d3Zoom:E,panOnScrollMode:U,panOnScrollSpeed:D,zoomOnPinch:w,onPanZoomStart:a,onPanZoom:i,onPanZoomEnd:l}):YU({noWheelClassName:b,preventScrolling:y,d3ZoomHandler:T});if(f.on("wheel.zoom",le,{passive:!1}),!L){const X=$U({zoomPanValues:d,onDraggingChange:c,onPanZoomStart:a});E.on("start",X);const H=VU({zoomPanValues:d,panOnDrag:M,onPaneContextMenu:!!j,onPanZoom:i,onTransformChange:Y});E.on("zoom",H);const re=zU({zoomPanValues:d,panOnDrag:M,panOnScroll:B,onPaneContextMenu:j,onPanZoomEnd:l,onDraggingChange:c});E.on("end",re)}const ae=XU({zoomActivationKeyPressed:V,panOnDrag:M,zoomOnScroll:F,panOnScroll:B,zoomOnDoubleClick:k,zoomOnPinch:w,userSelectionActive:L,noPanClassName:P,noWheelClassName:b,lib:ee,connectionInProgress:te});E.filter(ae),k?f.on("dblclick.zoom",A):f.on("dblclick.zoom",null)}function h(){E.on("zoom",null)}async function g(b,P,j){const L=tc(b),B=E==null?void 0:E.constrain()(L,P,j);return B&&await R(B),new Promise(M=>M(B))}async function m(b,P){const j=tc(b);return await R(j,P),new Promise(L=>L(j))}function I(b){if(f){const P=tc(b),j=f.property("__zoom");(j.k!==b.zoom||j.x!==b.x||j.y!==b.y)&&(E==null||E.transform(f,P,null,{sync:!0}))}}function O(){const b=f?UA(f.node()):{x:0,y:0,k:1};return{x:b.x,y:b.y,zoom:b.k}}function N(b,P){return f?new Promise(j=>{E==null||E.interpolate((P==null?void 0:P.interpolate)==="linear"?Xo:wi).scaleTo(nc(f,P==null?void 0:P.duration,P==null?void 0:P.ease,()=>j(!0)),b)}):Promise.resolve(!1)}function x(b,P){return f?new Promise(j=>{E==null||E.interpolate((P==null?void 0:P.interpolate)==="linear"?Xo:wi).scaleBy(nc(f,P==null?void 0:P.duration,P==null?void 0:P.ease,()=>j(!0)),b)}):Promise.resolve(!1)}function _(b){E==null||E.scaleExtent(b)}function C(b){E==null||E.translateExtent(b)}function v(b){const P=!wt(b)||b<0?0:b;E==null||E.clickDistance(P)}return{update:S,destroy:h,setViewport:m,setViewportConstrained:g,getViewport:O,scaleTo:N,scaleBy:x,setScaleExtent:_,setTranslateExtent:C,syncViewport:I,setClickDistance:v}}var So;(function(e){e.Line="line",e.Handle="handle"})(So||(So={}));function qU({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:i}){const a=e-t,l=n-r,c=[a>0?1:a<0?-1:0,l>0?1:l<0?-1:0];return a&&s&&(c[0]=c[0]*-1),l&&i&&(c[1]=c[1]*-1),c}function ep(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),r=e.includes("left"),s=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:r,affectsY:s}}function On(e,t){return Math.max(0,t-e)}function Nn(e,t){return Math.max(0,e-t)}function Ti(e,t,n){return Math.max(0,t-e,e-n)}function tp(e,t){return e?!t:t}function JU(e,t,n,r,s,i,a,l){let{affectsX:c,affectsY:d}=t;const{isHorizontal:u,isVertical:E}=t,f=u&&E,{xSnapped:T,ySnapped:A}=n,{minWidth:R,maxWidth:S,minHeight:h,maxHeight:g}=r,{x:m,y:I,width:O,height:N,aspectRatio:x}=e;let _=Math.floor(u?T-e.pointerX:0),C=Math.floor(E?A-e.pointerY:0);const v=O+(c?-_:_),b=N+(d?-C:C),P=-i[0]*O,j=-i[1]*N;let L=Ti(v,R,S),B=Ti(b,h,g);if(a){let D=0,y=0;c&&_<0?D=On(m+_+P,a[0][0]):!c&&_>0&&(D=Nn(m+v+P,a[1][0])),d&&C<0?y=On(I+C+j,a[0][1]):!d&&C>0&&(y=Nn(I+b+j,a[1][1])),L=Math.max(L,D),B=Math.max(B,y)}if(l){let D=0,y=0;c&&_>0?D=Nn(m+_,l[0][0]):!c&&_<0&&(D=On(m+v,l[1][0])),d&&C>0?y=Nn(I+C,l[0][1]):!d&&C<0&&(y=On(I+b,l[1][1])),L=Math.max(L,D),B=Math.max(B,y)}if(s){if(u){const D=Ti(v/x,h,g)*x;if(L=Math.max(L,D),a){let y=0;!c&&!d||c&&!d&&f?y=Nn(I+j+v/x,a[1][1])*x:y=On(I+j+(c?_:-_)/x,a[0][1])*x,L=Math.max(L,y)}if(l){let y=0;!c&&!d||c&&!d&&f?y=On(I+v/x,l[1][1])*x:y=Nn(I+(c?_:-_)/x,l[0][1])*x,L=Math.max(L,y)}}if(E){const D=Ti(b*x,R,S)/x;if(B=Math.max(B,D),a){let y=0;!c&&!d||d&&!c&&f?y=Nn(m+b*x+P,a[1][0])/x:y=On(m+(d?C:-C)*x+P,a[0][0])/x,B=Math.max(B,y)}if(l){let y=0;!c&&!d||d&&!c&&f?y=On(m+b*x,l[1][0])/x:y=Nn(m+(d?C:-C)*x,l[0][0])/x,B=Math.max(B,y)}}}C=C+(C<0?B:-B),_=_+(_<0?L:-L),s&&(f?v>b*x?C=(tp(c,d)?-_:_)/x:_=(tp(c,d)?-C:C)*x:u?(C=_/x,d=c):(_=C*x,c=d));const M=c?m+_:m,U=d?I+C:I;return{width:O+(c?-_:_),height:N+(d?-C:C),x:i[0]*_*(c?-1:1)+M,y:i[1]*C*(d?-1:1)+U}}const Em={width:0,height:0,x:0,y:0},QU={...Em,pointerX:0,pointerY:0,aspectRatio:1};function ZU(e){return[[0,0],[e.measured.width,e.measured.height]]}function eB(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,i=e.measured.width??0,a=e.measured.height??0,l=n[0]*i,c=n[1]*a;return[[r-l,s-c],[r+i-l,s+a-c]]}function tB({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const i=Et(e);let a={controlDirection:ep("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:d,boundaries:u,keepAspectRatio:E,resizeDirection:f,onResizeStart:T,onResize:A,onResizeEnd:R,shouldResize:S}){let h={...Em},g={...QU};a={boundaries:u,resizeDirection:f,keepAspectRatio:E,controlDirection:ep(d)};let m,I=null,O=[],N,x,_,C=!1;const v=IA().on("start",b=>{const{nodeLookup:P,transform:j,snapGrid:L,snapToGrid:B,nodeOrigin:M,paneDomNode:U}=n();if(m=P.get(t),!m)return;I=(U==null?void 0:U.getBoundingClientRect())??null;const{xSnapped:D,ySnapped:y}=Ko(b.sourceEvent,{transform:j,snapGrid:L,snapToGrid:B,containerBounds:I});h={width:m.measured.width??0,height:m.measured.height??0,x:m.position.x??0,y:m.position.y??0},g={...h,pointerX:D,pointerY:y,aspectRatio:h.width/h.height},N=void 0,m.parentId&&(m.extent==="parent"||m.expandParent)&&(N=P.get(m.parentId),x=N&&m.extent==="parent"?ZU(N):void 0),O=[],_=void 0;for(const[w,F]of P)if(F.parentId===t&&(O.push({id:w,position:{...F.position},extent:F.extent}),F.extent==="parent"||F.expandParent)){const k=eB(F,m,F.origin??M);_?_=[[Math.min(k[0][0],_[0][0]),Math.min(k[0][1],_[0][1])],[Math.max(k[1][0],_[1][0]),Math.max(k[1][1],_[1][1])]]:_=k}T==null||T(b,{...h})}).on("drag",b=>{const{transform:P,snapGrid:j,snapToGrid:L,nodeOrigin:B}=n(),M=Ko(b.sourceEvent,{transform:P,snapGrid:j,snapToGrid:L,containerBounds:I}),U=[];if(!m)return;const{x:D,y,width:w,height:F}=h,k={},V=m.origin??B,{width:ee,height:Y,x:te,y:ne}=JU(g,a.controlDirection,M,a.boundaries,a.keepAspectRatio,V,x,_),z=ee!==w,oe=Y!==F,le=te!==D&&z,ae=ne!==y&&oe;if(!le&&!ae&&!z&&!oe)return;if((le||ae||V[0]===1||V[1]===1)&&(k.x=le?te:h.x,k.y=ae?ne:h.y,h.x=k.x,h.y=k.y,O.length>0)){const ie=te-D,de=ne-y;for(const se of O)se.position={x:se.position.x-ie+V[0]*(ee-w),y:se.position.y-de+V[1]*(Y-F)},U.push(se)}if((z||oe)&&(k.width=z&&(!a.resizeDirection||a.resizeDirection==="horizontal")?ee:h.width,k.height=oe&&(!a.resizeDirection||a.resizeDirection==="vertical")?Y:h.height,h.width=k.width,h.height=k.height),N&&m.expandParent){const ie=V[0]*(k.width??0);k.x&&k.x<ie&&(h.x=ie,g.x=g.x-(k.x-ie));const de=V[1]*(k.height??0);k.y&&k.y<de&&(h.y=de,g.y=g.y-(k.y-de))}const X=qU({width:h.width,prevWidth:w,height:h.height,prevHeight:F,affectsX:a.controlDirection.affectsX,affectsY:a.controlDirection.affectsY}),H={...h,direction:X};(S==null?void 0:S(b,H))!==!1&&(C=!0,A==null||A(b,H),r(k,U))}).on("end",b=>{C&&(R==null||R(b,{...h}),s==null||s({...h}),C=!1)});i.call(v)}function c(){i.on(".drag",null)}return{update:l,destroy:c}}var rc={exports:{}},oc={},sc={exports:{}},ic={};/**
|
|
751
|
+
* @license React
|
|
752
|
+
* use-sync-external-store-shim.production.js
|
|
753
|
+
*
|
|
754
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
755
|
+
*
|
|
756
|
+
* This source code is licensed under the MIT license found in the
|
|
757
|
+
* LICENSE file in the root directory of this source tree.
|
|
758
|
+
*/var np;function nB(){if(np)return ic;np=1;var e=Ia();function t(E,f){return E===f&&(E!==0||1/E===1/f)||E!==E&&f!==f}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,s=e.useEffect,i=e.useLayoutEffect,a=e.useDebugValue;function l(E,f){var T=f(),A=r({inst:{value:T,getSnapshot:f}}),R=A[0].inst,S=A[1];return i(function(){R.value=T,R.getSnapshot=f,c(R)&&S({inst:R})},[E,T,f]),s(function(){return c(R)&&S({inst:R}),E(function(){c(R)&&S({inst:R})})},[E]),a(T),T}function c(E){var f=E.getSnapshot;E=E.value;try{var T=f();return!n(E,T)}catch{return!0}}function d(E,f){return f()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:l;return ic.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:u,ic}var rp;function rB(){return rp||(rp=1,sc.exports=nB()),sc.exports}/**
|
|
759
|
+
* @license React
|
|
760
|
+
* use-sync-external-store-shim/with-selector.production.js
|
|
761
|
+
*
|
|
762
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
763
|
+
*
|
|
764
|
+
* This source code is licensed under the MIT license found in the
|
|
765
|
+
* LICENSE file in the root directory of this source tree.
|
|
766
|
+
*/var op;function oB(){if(op)return oc;op=1;var e=Ia(),t=rB();function n(d,u){return d===u&&(d!==0||1/d===1/u)||d!==d&&u!==u}var r=typeof Object.is=="function"?Object.is:n,s=t.useSyncExternalStore,i=e.useRef,a=e.useEffect,l=e.useMemo,c=e.useDebugValue;return oc.useSyncExternalStoreWithSelector=function(d,u,E,f,T){var A=i(null);if(A.current===null){var R={hasValue:!1,value:null};A.current=R}else R=A.current;A=l(function(){function h(N){if(!g){if(g=!0,m=N,N=f(N),T!==void 0&&R.hasValue){var x=R.value;if(T(x,N))return I=x}return I=N}if(x=I,r(m,N))return x;var _=f(N);return T!==void 0&&T(x,_)?(m=N,x):(m=N,I=_)}var g=!1,m,I,O=E===void 0?null:E;return[function(){return h(u())},O===null?void 0:function(){return h(O())}]},[u,E,f,T]);var S=s(d,A[0],A[1]);return a(function(){R.hasValue=!0,R.value=S},[S]),c(S),S},oc}var sp;function sB(){return sp||(sp=1,rc.exports=oB()),rc.exports}var iB=sB();const aB=Oa(iB),lB={},ip=e=>{let t;const n=new Set,r=(u,E)=>{const f=typeof u=="function"?u(t):u;if(!Object.is(f,t)){const T=t;t=E??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(A=>A(t,T))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>d,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(lB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},d=t=e(r,s,c);return c},cB=e=>e?ip(e):ip,{useDebugValue:dB}=Be,{useSyncExternalStoreWithSelector:uB}=aB,EB=e=>e;function fm(e,t=EB,n){const r=uB(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return dB(r),r}const ap=(e,t)=>{const n=cB(e),r=(s,i=t)=>fm(n,s,i);return Object.assign(r,n),r},fB=(e,t)=>e?ap(e,t):ap;function Me(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,s]of e)if(!Object.is(s,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}const nl=p.createContext(null),pB=nl.Provider,pm=rn.error001();function Ne(e,t){const n=p.useContext(nl);if(n===null)throw new Error(pm);return fm(n,e,t)}function we(){const e=p.useContext(nl);if(e===null)throw new Error(pm);return p.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const lp={display:"none"},TB={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},Tm="react-flow__node-desc",Sm="react-flow__edge-desc",SB="react-flow__aria-live",hB=e=>e.ariaLiveMessage,RB=e=>e.ariaLabelConfig;function AB({rfId:e}){const t=Ne(hB);return o.jsx("div",{id:`${SB}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:TB,children:t})}function mB({rfId:e,disableKeyboardA11y:t}){const n=Ne(RB);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${Tm}-${e}`,style:lp,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${Sm}-${e}`,style:lp,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(AB,{rfId:e})]})}const ho=p.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},i)=>{const a=`${e}`.split("-");return o.jsx("div",{className:He(["react-flow__panel",n,...a]),style:r,ref:i,...s,children:t})});ho.displayName="Panel";function gB({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:o.jsx(ho,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:o.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const IB=e=>{const t=[],n=[];for(const[,r]of e.nodeLookup)r.selected&&t.push(r.internals.userNode);for(const[,r]of e.edgeLookup)r.selected&&n.push(r);return{selectedNodes:t,selectedEdges:n}},Si=e=>e.id;function OB(e,t){return Me(e.selectedNodes.map(Si),t.selectedNodes.map(Si))&&Me(e.selectedEdges.map(Si),t.selectedEdges.map(Si))}function NB({onSelectionChange:e}){const t=we(),{selectedNodes:n,selectedEdges:r}=Ne(IB,OB);return p.useEffect(()=>{const s={nodes:n,edges:r};e==null||e(s),t.getState().onSelectionChangeHandlers.forEach(i=>i(s))},[n,r,e]),null}const xB=e=>!!e.onSelectionChangeHandlers;function yB({onSelectionChange:e}){const t=Ne(xB);return e||t?o.jsx(NB,{onSelectionChange:e}):null}const hm=[0,0],CB={x:0,y:0,zoom:1},LB=["nodes","edges","defaultNodes","defaultEdges","onConnect","onConnectStart","onConnectEnd","onClickConnectStart","onClickConnectEnd","nodesDraggable","autoPanOnNodeFocus","nodesConnectable","nodesFocusable","edgesFocusable","edgesReconnectable","elevateNodesOnSelect","elevateEdgesOnSelect","minZoom","maxZoom","nodeExtent","onNodesChange","onEdgesChange","elementsSelectable","connectionMode","snapGrid","snapToGrid","translateExtent","connectOnClick","defaultEdgeOptions","fitView","fitViewOptions","onNodesDelete","onEdgesDelete","onDelete","onNodeDrag","onNodeDragStart","onNodeDragStop","onSelectionDrag","onSelectionDragStart","onSelectionDragStop","onMoveStart","onMove","onMoveEnd","noPanClassName","nodeOrigin","autoPanOnConnect","autoPanOnNodeDrag","onError","connectionRadius","isValidConnection","selectNodesOnDrag","nodeDragThreshold","connectionDragThreshold","onBeforeDelete","debug","autoPanSpeed","ariaLabelConfig","zIndexMode"],cp=[...LB,"rfId"],_B=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges}),dp={translateExtent:us,nodeOrigin:hm,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function bB(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:i,setNodeExtent:a,reset:l,setDefaultNodesAndEdges:c}=Ne(_B,Me),d=we();p.useEffect(()=>(c(e.defaultNodes,e.defaultEdges),()=>{u.current=dp,l()}),[]);const u=p.useRef(dp);return p.useEffect(()=>{for(const E of cp){const f=e[E],T=u.current[E];f!==T&&(typeof e[E]>"u"||(E==="nodes"?t(f):E==="edges"?n(f):E==="minZoom"?r(f):E==="maxZoom"?s(f):E==="translateExtent"?i(f):E==="nodeExtent"?a(f):E==="ariaLabelConfig"?d.setState({ariaLabelConfig:fU(f)}):E==="fitView"?d.setState({fitViewQueued:f}):E==="fitViewOptions"?d.setState({fitViewOptions:f}):d.setState({[E]:f})))}u.current=e},cp.map(E=>e[E])),null}function up(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function vB(e){var r;const[t,n]=p.useState(e==="system"?null:e);return p.useEffect(()=>{if(e!=="system"){n(e);return}const s=up(),i=()=>n(s!=null&&s.matches?"dark":"light");return i(),s==null||s.addEventListener("change",i),()=>{s==null||s.removeEventListener("change",i)}},[e]),t!==null?t:(r=up())!=null&&r.matches?"dark":"light"}const Ep=typeof document<"u"?document:null;function Ts(e=null,t={target:Ep,actInsideInputWithModifier:!0}){const[n,r]=p.useState(!1),s=p.useRef(!1),i=p.useRef(new Set([])),[a,l]=p.useMemo(()=>{if(e!==null){const d=(Array.isArray(e)?e:[e]).filter(E=>typeof E=="string").map(E=>E.replace("+",`
|
|
767
|
+
`).replace(`
|
|
768
|
+
|
|
769
|
+
`,`
|
|
770
|
+
+`).split(`
|
|
771
|
+
`)),u=d.reduce((E,f)=>E.concat(...f),[]);return[d,u]}return[[],[]]},[e]);return p.useEffect(()=>{const c=(t==null?void 0:t.target)??Ep,d=(t==null?void 0:t.actInsideInputWithModifier)??!0;if(e!==null){const u=T=>{var S,h;if(s.current=T.ctrlKey||T.metaKey||T.shiftKey||T.altKey,(!s.current||s.current&&!d)&&qA(T))return!1;const R=pp(T.code,l);if(i.current.add(T[R]),fp(a,i.current,!1)){const g=((h=(S=T.composedPath)==null?void 0:S.call(T))==null?void 0:h[0])||T.target,m=(g==null?void 0:g.nodeName)==="BUTTON"||(g==null?void 0:g.nodeName)==="A";t.preventDefault!==!1&&(s.current||!m)&&T.preventDefault(),r(!0)}},E=T=>{const A=pp(T.code,l);fp(a,i.current,!0)?(r(!1),i.current.clear()):i.current.delete(T[A]),T.key==="Meta"&&i.current.clear(),s.current=!1},f=()=>{i.current.clear(),r(!1)};return c==null||c.addEventListener("keydown",u),c==null||c.addEventListener("keyup",E),window.addEventListener("blur",f),window.addEventListener("contextmenu",f),()=>{c==null||c.removeEventListener("keydown",u),c==null||c.removeEventListener("keyup",E),window.removeEventListener("blur",f),window.removeEventListener("contextmenu",f)}}},[e,r]),n}function fp(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(s=>t.has(s)))}function pp(e,t){return t.includes(e)?"code":"key"}const DB=()=>{const e=we();return p.useMemo(()=>({zoomIn:t=>{const{panZoom:n}=e.getState();return n?n.scaleBy(1.2,{duration:t==null?void 0:t.duration}):Promise.resolve(!1)},zoomOut:t=>{const{panZoom:n}=e.getState();return n?n.scaleBy(1/1.2,{duration:t==null?void 0:t.duration}):Promise.resolve(!1)},zoomTo:(t,n)=>{const{panZoom:r}=e.getState();return r?r.scaleTo(t,{duration:n==null?void 0:n.duration}):Promise.resolve(!1)},getZoom:()=>e.getState().transform[2],setViewport:async(t,n)=>{const{transform:[r,s,i],panZoom:a}=e.getState();return a?(await a.setViewport({x:t.x??r,y:t.y??s,zoom:t.zoom??i},n),Promise.resolve(!0)):Promise.resolve(!1)},getViewport:()=>{const[t,n,r]=e.getState().transform;return{x:t,y:n,zoom:r}},setCenter:async(t,n,r)=>e.getState().setCenter(t,n,r),fitBounds:async(t,n)=>{const{width:r,height:s,minZoom:i,maxZoom:a,panZoom:l}=e.getState(),c=Mu(t,r,s,i,a,(n==null?void 0:n.padding)??.1);return l?(await l.setViewport(c,{duration:n==null?void 0:n.duration,ease:n==null?void 0:n.ease,interpolate:n==null?void 0:n.interpolate}),Promise.resolve(!0)):Promise.resolve(!1)},screenToFlowPosition:(t,n={})=>{const{transform:r,snapGrid:s,snapToGrid:i,domNode:a}=e.getState();if(!a)return t;const{x:l,y:c}=a.getBoundingClientRect(),d={x:t.x-l,y:t.y-c},u=n.snapGrid??s,E=n.snapToGrid??i;return Ms(d,r,E,u)},flowToScreenPosition:t=>{const{transform:n,domNode:r}=e.getState();if(!r)return t;const{x:s,y:i}=r.getBoundingClientRect(),a=Ea(t,n);return{x:a.x+s,y:a.y+i}}}),[])};function Rm(e,t){const n=[],r=new Map,s=[];for(const i of e)if(i.type==="add"){s.push(i);continue}else if(i.type==="remove"||i.type==="replace")r.set(i.id,[i]);else{const a=r.get(i.id);a?a.push(i):r.set(i.id,[i])}for(const i of t){const a=r.get(i.id);if(!a){n.push(i);continue}if(a[0].type==="remove")continue;if(a[0].type==="replace"){n.push({...a[0].item});continue}const l={...i};for(const c of a)MB(c,l);n.push(l)}return s.length&&s.forEach(i=>{i.index!==void 0?n.splice(i.index,0,{...i.item}):n.push({...i.item})}),n}function MB(e,t){switch(e.type){case"select":{t.selected=e.selected;break}case"position":{typeof e.position<"u"&&(t.position=e.position),typeof e.dragging<"u"&&(t.dragging=e.dragging);break}case"dimensions":{typeof e.dimensions<"u"&&(t.measured={...e.dimensions},e.setAttributes&&((e.setAttributes===!0||e.setAttributes==="width")&&(t.width=e.dimensions.width),(e.setAttributes===!0||e.setAttributes==="height")&&(t.height=e.dimensions.height))),typeof e.resizing=="boolean"&&(t.resizing=e.resizing);break}}}function Am(e,t){return Rm(e,t)}function mm(e,t){return Rm(e,t)}function or(e,t){return{id:e,type:"select",selected:t}}function Kr(e,t=new Set,n=!1){const r=[];for(const[s,i]of e){const a=t.has(s);!(i.selected===void 0&&!a)&&i.selected!==a&&(n&&(i.selected=a),r.push(or(i.id,a)))}return r}function Tp({items:e=[],lookup:t}){var s;const n=[],r=new Map(e.map(i=>[i.id,i]));for(const[i,a]of e.entries()){const l=t.get(a.id),c=((s=l==null?void 0:l.internals)==null?void 0:s.userNode)??l;c!==void 0&&c!==a&&n.push({id:a.id,item:a,type:"replace"}),c===void 0&&n.push({item:a,type:"add",index:i})}for(const[i]of t)r.get(i)===void 0&&n.push({id:i,type:"remove"});return n}function Sp(e){return{id:e.id,type:"remove"}}const hp=e=>rU(e),PB=e=>HA(e);function gm(e){return p.forwardRef(e)}const wB=typeof window<"u"?p.useLayoutEffect:p.useEffect;function Rp(e){const[t,n]=p.useState(BigInt(0)),[r]=p.useState(()=>UB(()=>n(s=>s+BigInt(1))));return wB(()=>{const s=r.get();s.length&&(e(s),r.reset())},[t]),r}function UB(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}const Im=p.createContext(null);function BB({children:e}){const t=we(),n=p.useCallback(l=>{const{nodes:c=[],setNodes:d,hasDefaultNodes:u,onNodesChange:E,nodeLookup:f,fitViewQueued:T,onNodesChangeMiddlewareMap:A}=t.getState();let R=c;for(const h of l)R=typeof h=="function"?h(R):h;let S=Tp({items:R,lookup:f});for(const h of A.values())S=h(S);u&&d(R),S.length>0?E==null||E(S):T&&window.requestAnimationFrame(()=>{const{fitViewQueued:h,nodes:g,setNodes:m}=t.getState();h&&m(g)})},[]),r=Rp(n),s=p.useCallback(l=>{const{edges:c=[],setEdges:d,hasDefaultEdges:u,onEdgesChange:E,edgeLookup:f}=t.getState();let T=c;for(const A of l)T=typeof A=="function"?A(T):A;u?d(T):E&&E(Tp({items:T,lookup:f}))},[]),i=Rp(s),a=p.useMemo(()=>({nodeQueue:r,edgeQueue:i}),[]);return o.jsx(Im.Provider,{value:a,children:e})}function jB(){const e=p.useContext(Im);if(!e)throw new Error("useBatchContext must be used within a BatchProvider");return e}const kB=e=>!!e.panZoom;function rl(){const e=DB(),t=we(),n=jB(),r=Ne(kB),s=p.useMemo(()=>{const i=E=>t.getState().nodeLookup.get(E),a=E=>{n.nodeQueue.push(E)},l=E=>{n.edgeQueue.push(E)},c=E=>{var h,g;const{nodeLookup:f,nodeOrigin:T}=t.getState(),A=hp(E)?E:f.get(E.id),R=A.parentId?XA(A.position,A.measured,A.parentId,f,T):A.position,S={...A,position:R,width:((h=A.measured)==null?void 0:h.width)??A.width,height:((g=A.measured)==null?void 0:g.height)??A.height};return po(S)},d=(E,f,T={replace:!1})=>{a(A=>A.map(R=>{if(R.id===E){const S=typeof f=="function"?f(R):f;return T.replace&&hp(S)?S:{...R,...S}}return R}))},u=(E,f,T={replace:!1})=>{l(A=>A.map(R=>{if(R.id===E){const S=typeof f=="function"?f(R):f;return T.replace&&PB(S)?S:{...R,...S}}return R}))};return{getNodes:()=>t.getState().nodes.map(E=>({...E})),getNode:E=>{var f;return(f=i(E))==null?void 0:f.internals.userNode},getInternalNode:i,getEdges:()=>{const{edges:E=[]}=t.getState();return E.map(f=>({...f}))},getEdge:E=>t.getState().edgeLookup.get(E),setNodes:a,setEdges:l,addNodes:E=>{const f=Array.isArray(E)?E:[E];n.nodeQueue.push(T=>[...T,...f])},addEdges:E=>{const f=Array.isArray(E)?E:[E];n.edgeQueue.push(T=>[...T,...f])},toObject:()=>{const{nodes:E=[],edges:f=[],transform:T}=t.getState(),[A,R,S]=T;return{nodes:E.map(h=>({...h})),edges:f.map(h=>({...h})),viewport:{x:A,y:R,zoom:S}}},deleteElements:async({nodes:E=[],edges:f=[]})=>{const{nodes:T,edges:A,onNodesDelete:R,onEdgesDelete:S,triggerNodeChanges:h,triggerEdgeChanges:g,onDelete:m,onBeforeDelete:I}=t.getState(),{nodes:O,edges:N}=await lU({nodesToRemove:E,edgesToRemove:f,nodes:T,edges:A,onBeforeDelete:I}),x=N.length>0,_=O.length>0;if(x){const C=N.map(Sp);S==null||S(N),g(C)}if(_){const C=O.map(Sp);R==null||R(O),h(C)}return(_||x)&&(m==null||m({nodes:O,edges:N})),{deletedNodes:O,deletedEdges:N}},getIntersectingNodes:(E,f=!0,T)=>{const A=Wf(E),R=A?E:c(E),S=T!==void 0;return R?(T||t.getState().nodes).filter(h=>{const g=t.getState().nodeLookup.get(h.id);if(g&&!A&&(h.id===E.id||!g.internals.positionAbsolute))return!1;const m=po(S?h:g),I=fs(m,R);return f&&I>0||I>=m.width*m.height||I>=R.width*R.height}):[]},isNodeIntersecting:(E,f,T=!0)=>{const R=Wf(E)?E:c(E);if(!R)return!1;const S=fs(R,f);return T&&S>0||S>=f.width*f.height||S>=R.width*R.height},updateNode:d,updateNodeData:(E,f,T={replace:!1})=>{d(E,A=>{const R=typeof f=="function"?f(A):f;return T.replace?{...A,data:R}:{...A,data:{...A.data,...R}}},T)},updateEdge:u,updateEdgeData:(E,f,T={replace:!1})=>{u(E,A=>{const R=typeof f=="function"?f(A):f;return T.replace?{...A,data:R}:{...A,data:{...A.data,...R}}},T)},getNodesBounds:E=>{const{nodeLookup:f,nodeOrigin:T}=t.getState();return oU(E,{nodeLookup:f,nodeOrigin:T})},getHandleConnections:({type:E,id:f,nodeId:T})=>{var A;return Array.from(((A=t.getState().connectionLookup.get(`${T}-${E}${f?`-${f}`:""}`))==null?void 0:A.values())??[])},getNodeConnections:({type:E,handleId:f,nodeId:T})=>{var A;return Array.from(((A=t.getState().connectionLookup.get(`${T}${E?f?`-${E}-${f}`:`-${E}`:""}`))==null?void 0:A.values())??[])},fitView:async E=>{const f=t.getState().fitViewResolver??EU();return t.setState({fitViewQueued:!0,fitViewOptions:E,fitViewResolver:f}),n.nodeQueue.push(T=>[...T]),f.promise}}},[]);return p.useMemo(()=>({...s,...e,viewportInitialized:r}),[r])}const Ap=e=>e.selected,FB=typeof window<"u"?window:void 0;function GB({deleteKeyCode:e,multiSelectionKeyCode:t}){const n=we(),{deleteElements:r}=rl(),s=Ts(e,{actInsideInputWithModifier:!1}),i=Ts(t,{target:FB});p.useEffect(()=>{if(s){const{edges:a,nodes:l}=n.getState();r({nodes:l.filter(Ap),edges:a.filter(Ap)}),n.setState({nodesSelectionActive:!1})}},[s]),p.useEffect(()=>{n.setState({multiSelectionActive:i})},[i])}function HB(e){const t=we();p.useEffect(()=>{const n=()=>{var s,i,a,l;if(!e.current||!(((i=(s=e.current).checkVisibility)==null?void 0:i.call(s))??!0))return!1;const r=Pu(e.current);(r.height===0||r.width===0)&&((l=(a=t.getState()).onError)==null||l.call(a,"004",rn.error004())),t.setState({width:r.width||500,height:r.height||500})};if(e.current){n(),window.addEventListener("resize",n);const r=new ResizeObserver(()=>n());return r.observe(e.current),()=>{window.removeEventListener("resize",n),r&&e.current&&r.unobserve(e.current)}}},[])}const ol={position:"absolute",width:"100%",height:"100%",top:0,left:0},WB=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function YB({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:r=!1,panOnScrollSpeed:s=.5,panOnScrollMode:i=dr.Free,zoomOnDoubleClick:a=!0,panOnDrag:l=!0,defaultViewport:c,translateExtent:d,minZoom:u,maxZoom:E,zoomActivationKeyCode:f,preventScrolling:T=!0,children:A,noWheelClassName:R,noPanClassName:S,onViewportChange:h,isControlledViewport:g,paneClickDistance:m,selectionOnDrag:I}){const O=we(),N=p.useRef(null),{userSelectionActive:x,lib:_,connectionInProgress:C}=Ne(WB,Me),v=Ts(f),b=p.useRef();HB(N);const P=p.useCallback(j=>{h==null||h({x:j[0],y:j[1],zoom:j[2]}),g||O.setState({transform:j})},[h,g]);return p.useEffect(()=>{if(N.current){b.current=KU({domNode:N.current,minZoom:u,maxZoom:E,translateExtent:d,viewport:c,onDraggingChange:M=>O.setState(U=>U.paneDragging===M?U:{paneDragging:M}),onPanZoomStart:(M,U)=>{const{onViewportChangeStart:D,onMoveStart:y}=O.getState();y==null||y(M,U),D==null||D(U)},onPanZoom:(M,U)=>{const{onViewportChange:D,onMove:y}=O.getState();y==null||y(M,U),D==null||D(U)},onPanZoomEnd:(M,U)=>{const{onViewportChangeEnd:D,onMoveEnd:y}=O.getState();y==null||y(M,U),D==null||D(U)}});const{x:j,y:L,zoom:B}=b.current.getViewport();return O.setState({panZoom:b.current,transform:[j,L,B],domNode:N.current.closest(".react-flow")}),()=>{var M;(M=b.current)==null||M.destroy()}}},[]),p.useEffect(()=>{var j;(j=b.current)==null||j.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:r,panOnScrollSpeed:s,panOnScrollMode:i,zoomOnDoubleClick:a,panOnDrag:l,zoomActivationKeyPressed:v,preventScrolling:T,noPanClassName:S,userSelectionActive:x,noWheelClassName:R,lib:_,onTransformChange:P,connectionInProgress:C,selectionOnDrag:I,paneClickDistance:m})},[e,t,n,r,s,i,a,l,v,T,S,x,R,_,P,C,I,m]),o.jsx("div",{className:"react-flow__renderer",ref:N,style:ol,children:A})}const $B=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function VB(){const{userSelectionActive:e,userSelectionRect:t}=Ne($B,Me);return e&&t?o.jsx("div",{className:"react-flow__selection react-flow__container",style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}const ac=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},zB=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,connectionInProgress:e.connection.inProgress,dragging:e.paneDragging});function XB({isSelecting:e,selectionKeyPressed:t,selectionMode:n=Es.Full,panOnDrag:r,paneClickDistance:s,selectionOnDrag:i,onSelectionStart:a,onSelectionEnd:l,onPaneClick:c,onPaneContextMenu:d,onPaneScroll:u,onPaneMouseEnter:E,onPaneMouseMove:f,onPaneMouseLeave:T,children:A}){const R=we(),{userSelectionActive:S,elementsSelectable:h,dragging:g,connectionInProgress:m}=Ne(zB,Me),I=h&&(e||S),O=p.useRef(null),N=p.useRef(),x=p.useRef(new Set),_=p.useRef(new Set),C=p.useRef(!1),v=D=>{if(C.current||m){C.current=!1;return}c==null||c(D),R.getState().resetSelectedElements(),R.setState({nodesSelectionActive:!1})},b=D=>{if(Array.isArray(r)&&(r!=null&&r.includes(2))){D.preventDefault();return}d==null||d(D)},P=u?D=>u(D):void 0,j=D=>{C.current&&(D.stopPropagation(),C.current=!1)},L=D=>{var Y,te;const{domNode:y}=R.getState();if(N.current=y==null?void 0:y.getBoundingClientRect(),!N.current)return;const w=D.target===O.current;if(!w&&!!D.target.closest(".nokey")||!e||!(i&&w||t)||D.button!==0||!D.isPrimary)return;(te=(Y=D.target)==null?void 0:Y.setPointerCapture)==null||te.call(Y,D.pointerId),C.current=!1;const{x:V,y:ee}=Ut(D.nativeEvent,N.current);R.setState({userSelectionRect:{width:0,height:0,startX:V,startY:ee,x:V,y:ee}}),w||(D.stopPropagation(),D.preventDefault())},B=D=>{const{userSelectionRect:y,transform:w,nodeLookup:F,edgeLookup:k,connectionLookup:V,triggerNodeChanges:ee,triggerEdgeChanges:Y,defaultEdgeOptions:te,resetSelectedElements:ne}=R.getState();if(!N.current||!y)return;const{x:z,y:oe}=Ut(D.nativeEvent,N.current),{startX:le,startY:ae}=y;if(!C.current){const de=t?0:s;if(Math.hypot(z-le,oe-ae)<=de)return;ne(),a==null||a(D)}C.current=!0;const X={startX:le,startY:ae,x:z<le?z:le,y:oe<ae?oe:ae,width:Math.abs(z-le),height:Math.abs(oe-ae)},H=x.current,re=_.current;x.current=new Set(Du(F,X,w,n===Es.Partial,!0).map(de=>de.id)),_.current=new Set;const ie=(te==null?void 0:te.selectable)??!0;for(const de of x.current){const se=V.get(de);if(se)for(const{edgeId:ge}of se.values()){const xe=k.get(ge);xe&&(xe.selectable??ie)&&_.current.add(ge)}}if(!Yf(H,x.current)){const de=Kr(F,x.current,!0);ee(de)}if(!Yf(re,_.current)){const de=Kr(k,_.current);Y(de)}R.setState({userSelectionRect:X,userSelectionActive:!0,nodesSelectionActive:!1})},M=D=>{var y,w;D.button===0&&((w=(y=D.target)==null?void 0:y.releasePointerCapture)==null||w.call(y,D.pointerId),!S&&D.target===O.current&&R.getState().userSelectionRect&&(v==null||v(D)),R.setState({userSelectionActive:!1,userSelectionRect:null}),C.current&&(l==null||l(D),R.setState({nodesSelectionActive:x.current.size>0})))},U=r===!0||Array.isArray(r)&&r.includes(0);return o.jsxs("div",{className:He(["react-flow__pane",{draggable:U,dragging:g,selection:e}]),onClick:I?void 0:ac(v,O),onContextMenu:ac(b,O),onWheel:ac(P,O),onPointerEnter:I?void 0:E,onPointerMove:I?B:f,onPointerUp:I?M:void 0,onPointerDownCapture:I?L:void 0,onClickCapture:I?j:void 0,onPointerLeave:T,ref:O,style:ol,children:[A,o.jsx(VB,{})]})}function Cd({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:s,unselectNodesAndEdges:i,multiSelectionActive:a,nodeLookup:l,onError:c}=t.getState(),d=l.get(e);if(!d){c==null||c("012",rn.error012(e));return}t.setState({nodesSelectionActive:!1}),d.selected?(n||d.selected&&a)&&(i({nodes:[d],edges:[]}),requestAnimationFrame(()=>{var u;return(u=r==null?void 0:r.current)==null?void 0:u.blur()})):s([e])}function Om({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:s,isSelectable:i,nodeClickDistance:a}){const l=we(),[c,d]=p.useState(!1),u=p.useRef();return p.useEffect(()=>{u.current=wU({getStoreItems:()=>l.getState(),onNodeMouseDown:E=>{Cd({id:E,store:l,nodeRef:e})},onDragStart:()=>{d(!0)},onDragStop:()=>{d(!1)}})},[]),p.useEffect(()=>{if(!(t||!e.current||!u.current))return u.current.update({noDragClassName:n,handleSelector:r,domNode:e.current,isSelectable:i,nodeId:s,nodeClickDistance:a}),()=>{var E;(E=u.current)==null||E.destroy()}},[n,r,t,i,e,s,a]),c}const KB=e=>t=>t.selected&&(t.draggable||e&&typeof t.draggable>"u");function Nm(){const e=we();return p.useCallback(n=>{const{nodeExtent:r,snapToGrid:s,snapGrid:i,nodesDraggable:a,onError:l,updateNodePositions:c,nodeLookup:d,nodeOrigin:u}=e.getState(),E=new Map,f=KB(a),T=s?i[0]:5,A=s?i[1]:5,R=n.direction.x*T*n.factor,S=n.direction.y*A*n.factor;for(const[,h]of d){if(!f(h))continue;let g={x:h.internals.positionAbsolute.x+R,y:h.internals.positionAbsolute.y+S};s&&(g=Ds(g,i));const{position:m,positionAbsolute:I}=WA({nodeId:h.id,nextPosition:g,nodeLookup:d,nodeExtent:r,nodeOrigin:u,onError:l});h.position=m,h.internals.positionAbsolute=I,E.set(h.id,h)}c(E)},[])}const Fu=p.createContext(null),qB=Fu.Provider;Fu.Consumer;const xm=()=>p.useContext(Fu),JB=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),QB=(e,t,n)=>r=>{const{connectionClickStartHandle:s,connectionMode:i,connection:a}=r,{fromHandle:l,toHandle:c,isValid:d}=a,u=(c==null?void 0:c.nodeId)===e&&(c==null?void 0:c.id)===t&&(c==null?void 0:c.type)===n;return{connectingFrom:(l==null?void 0:l.nodeId)===e&&(l==null?void 0:l.id)===t&&(l==null?void 0:l.type)===n,connectingTo:u,clickConnecting:(s==null?void 0:s.nodeId)===e&&(s==null?void 0:s.id)===t&&(s==null?void 0:s.type)===n,isPossibleEndHandle:i===uo.Strict?(l==null?void 0:l.type)!==n:e!==(l==null?void 0:l.nodeId)||t!==(l==null?void 0:l.id),connectionInProcess:!!l,clickConnectionInProcess:!!s,valid:u&&d}};function ZB({type:e="source",position:t=pe.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:s=!0,isConnectableEnd:i=!0,id:a,onConnect:l,children:c,className:d,onMouseDown:u,onTouchStart:E,...f},T){var B,M;const A=a||null,R=e==="target",S=we(),h=xm(),{connectOnClick:g,noPanClassName:m,rfId:I}=Ne(JB,Me),{connectingFrom:O,connectingTo:N,clickConnecting:x,isPossibleEndHandle:_,connectionInProcess:C,clickConnectionInProcess:v,valid:b}=Ne(QB(h,A,e),Me);h||(M=(B=S.getState()).onError)==null||M.call(B,"010",rn.error010());const P=U=>{const{defaultEdgeOptions:D,onConnect:y,hasDefaultEdges:w}=S.getState(),F={...D,...U};if(w){const{edges:k,setEdges:V}=S.getState();V(AU(F,k))}y==null||y(F),l==null||l(F)},j=U=>{if(!h)return;const D=JA(U.nativeEvent);if(s&&(D&&U.button===0||!D)){const y=S.getState();yd.onPointerDown(U.nativeEvent,{handleDomNode:U.currentTarget,autoPanOnConnect:y.autoPanOnConnect,connectionMode:y.connectionMode,connectionRadius:y.connectionRadius,domNode:y.domNode,nodeLookup:y.nodeLookup,lib:y.lib,isTarget:R,handleId:A,nodeId:h,flowId:y.rfId,panBy:y.panBy,cancelConnection:y.cancelConnection,onConnectStart:y.onConnectStart,onConnectEnd:(...w)=>{var F,k;return(k=(F=S.getState()).onConnectEnd)==null?void 0:k.call(F,...w)},updateConnection:y.updateConnection,onConnect:P,isValidConnection:n||((...w)=>{var F,k;return((k=(F=S.getState()).isValidConnection)==null?void 0:k.call(F,...w))??!0}),getTransform:()=>S.getState().transform,getFromHandle:()=>S.getState().connection.fromHandle,autoPanSpeed:y.autoPanSpeed,dragThreshold:y.connectionDragThreshold})}D?u==null||u(U):E==null||E(U)},L=U=>{const{onClickConnectStart:D,onClickConnectEnd:y,connectionClickStartHandle:w,connectionMode:F,isValidConnection:k,lib:V,rfId:ee,nodeLookup:Y,connection:te}=S.getState();if(!h||!w&&!s)return;if(!w){D==null||D(U.nativeEvent,{nodeId:h,handleId:A,handleType:e}),S.setState({connectionClickStartHandle:{nodeId:h,type:e,id:A}});return}const ne=KA(U.target),z=n||k,{connection:oe,isValid:le}=yd.isValid(U.nativeEvent,{handle:{nodeId:h,id:A,type:e},connectionMode:F,fromNodeId:w.nodeId,fromHandleId:w.id||null,fromType:w.type,isValidConnection:z,flowId:ee,doc:ne,lib:V,nodeLookup:Y});le&&oe&&P(oe);const ae=structuredClone(te);delete ae.inProgress,ae.toPosition=ae.toHandle?ae.toHandle.position:null,y==null||y(U,ae),S.setState({connectionClickStartHandle:null})};return o.jsx("div",{"data-handleid":A,"data-nodeid":h,"data-handlepos":t,"data-id":`${I}-${h}-${A}-${e}`,className:He(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",m,d,{source:!R,target:R,connectable:r,connectablestart:s,connectableend:i,clickconnecting:x,connectingfrom:O,connectingto:N,valid:b,connectionindicator:r&&(!C||_)&&(C||v?i:s)}]),onMouseDown:j,onTouchStart:j,onClick:g?L:void 0,ref:T,...f,children:c})}const Gn=p.memo(gm(ZB));function ej({data:e,isConnectable:t,sourcePosition:n=pe.Bottom}){return o.jsxs(o.Fragment,{children:[e==null?void 0:e.label,o.jsx(Gn,{type:"source",position:n,isConnectable:t})]})}function tj({data:e,isConnectable:t,targetPosition:n=pe.Top,sourcePosition:r=pe.Bottom}){return o.jsxs(o.Fragment,{children:[o.jsx(Gn,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,o.jsx(Gn,{type:"source",position:r,isConnectable:t})]})}function nj(){return null}function rj({data:e,isConnectable:t,targetPosition:n=pe.Top}){return o.jsxs(o.Fragment,{children:[o.jsx(Gn,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label]})}const fa={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},mp={input:ej,default:tj,output:rj,group:nj};function oj(e){var t,n,r,s;return e.internals.handleBounds===void 0?{width:e.width??e.initialWidth??((t=e.style)==null?void 0:t.width),height:e.height??e.initialHeight??((n=e.style)==null?void 0:n.height)}:{width:e.width??((r=e.style)==null?void 0:r.width),height:e.height??((s=e.style)==null?void 0:s.height)}}const sj=e=>{const{width:t,height:n,x:r,y:s}=vs(e.nodeLookup,{filter:i=>!!i.selected});return{width:wt(t)?t:null,height:wt(n)?n:null,userSelectionActive:e.userSelectionActive,transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]}) translate(${r}px,${s}px)`}};function ij({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=we(),{width:s,height:i,transformString:a,userSelectionActive:l}=Ne(sj,Me),c=Nm(),d=p.useRef(null);p.useEffect(()=>{var T;n||(T=d.current)==null||T.focus({preventScroll:!0})},[n]);const u=!l&&s!==null&&i!==null;if(Om({nodeRef:d,disabled:!u}),!u)return null;const E=e?T=>{const A=r.getState().nodes.filter(R=>R.selected);e(T,A)}:void 0,f=T=>{Object.prototype.hasOwnProperty.call(fa,T.key)&&(T.preventDefault(),c({direction:fa[T.key],factor:T.shiftKey?4:1}))};return o.jsx("div",{className:He(["react-flow__nodesselection","react-flow__container",t]),style:{transform:a},children:o.jsx("div",{ref:d,className:"react-flow__nodesselection-rect",onContextMenu:E,tabIndex:n?void 0:-1,onKeyDown:n?void 0:f,style:{width:s,height:i}})})}const gp=typeof window<"u"?window:void 0,aj=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function ym({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:s,onPaneContextMenu:i,onPaneScroll:a,paneClickDistance:l,deleteKeyCode:c,selectionKeyCode:d,selectionOnDrag:u,selectionMode:E,onSelectionStart:f,onSelectionEnd:T,multiSelectionKeyCode:A,panActivationKeyCode:R,zoomActivationKeyCode:S,elementsSelectable:h,zoomOnScroll:g,zoomOnPinch:m,panOnScroll:I,panOnScrollSpeed:O,panOnScrollMode:N,zoomOnDoubleClick:x,panOnDrag:_,defaultViewport:C,translateExtent:v,minZoom:b,maxZoom:P,preventScrolling:j,onSelectionContextMenu:L,noWheelClassName:B,noPanClassName:M,disableKeyboardA11y:U,onViewportChange:D,isControlledViewport:y}){const{nodesSelectionActive:w,userSelectionActive:F}=Ne(aj,Me),k=Ts(d,{target:gp}),V=Ts(R,{target:gp}),ee=V||_,Y=V||I,te=u&&ee!==!0,ne=k||F||te;return GB({deleteKeyCode:c,multiSelectionKeyCode:A}),o.jsx(YB,{onPaneContextMenu:i,elementsSelectable:h,zoomOnScroll:g,zoomOnPinch:m,panOnScroll:Y,panOnScrollSpeed:O,panOnScrollMode:N,zoomOnDoubleClick:x,panOnDrag:!k&&ee,defaultViewport:C,translateExtent:v,minZoom:b,maxZoom:P,zoomActivationKeyCode:S,preventScrolling:j,noWheelClassName:B,noPanClassName:M,onViewportChange:D,isControlledViewport:y,paneClickDistance:l,selectionOnDrag:te,children:o.jsxs(XB,{onSelectionStart:f,onSelectionEnd:T,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:s,onPaneContextMenu:i,onPaneScroll:a,panOnDrag:ee,isSelecting:!!ne,selectionMode:E,selectionKeyPressed:k,paneClickDistance:l,selectionOnDrag:te,children:[e,w&&o.jsx(ij,{onSelectionContextMenu:L,noPanClassName:M,disableKeyboardA11y:U})]})})}ym.displayName="FlowRenderer";const lj=p.memo(ym),cj=e=>t=>e?Du(t.nodeLookup,{x:0,y:0,width:t.width,height:t.height},t.transform,!0).map(n=>n.id):Array.from(t.nodeLookup.keys());function dj(e){return Ne(p.useCallback(cj(e),[e]),Me)}const uj=e=>e.updateNodeInternals;function Ej(){const e=Ne(uj),[t]=p.useState(()=>typeof ResizeObserver>"u"?null:new ResizeObserver(n=>{const r=new Map;n.forEach(s=>{const i=s.target.getAttribute("data-id");r.set(i,{id:i,nodeElement:s.target,force:!0})}),e(r)}));return p.useEffect(()=>()=>{t==null||t.disconnect()},[t]),t}function fj({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){const s=we(),i=p.useRef(null),a=p.useRef(null),l=p.useRef(e.sourcePosition),c=p.useRef(e.targetPosition),d=p.useRef(t),u=n&&!!e.internals.handleBounds;return p.useEffect(()=>{i.current&&!e.hidden&&(!u||a.current!==i.current)&&(a.current&&(r==null||r.unobserve(a.current)),r==null||r.observe(i.current),a.current=i.current)},[u,e.hidden]),p.useEffect(()=>()=>{a.current&&(r==null||r.unobserve(a.current),a.current=null)},[]),p.useEffect(()=>{if(i.current){const E=d.current!==t,f=l.current!==e.sourcePosition,T=c.current!==e.targetPosition;(E||f||T)&&(d.current=t,l.current=e.sourcePosition,c.current=e.targetPosition,s.getState().updateNodeInternals(new Map([[e.id,{id:e.id,nodeElement:i.current,force:!0}]])))}},[e.id,t,e.sourcePosition,e.targetPosition]),i}function pj({id:e,onClick:t,onMouseEnter:n,onMouseMove:r,onMouseLeave:s,onContextMenu:i,onDoubleClick:a,nodesDraggable:l,elementsSelectable:c,nodesConnectable:d,nodesFocusable:u,resizeObserver:E,noDragClassName:f,noPanClassName:T,disableKeyboardA11y:A,rfId:R,nodeTypes:S,nodeClickDistance:h,onError:g}){const{node:m,internals:I,isParent:O}=Ne(z=>{const oe=z.nodeLookup.get(e),le=z.parentLookup.has(e);return{node:oe,internals:oe.internals,isParent:le}},Me);let N=m.type||"default",x=(S==null?void 0:S[N])||mp[N];x===void 0&&(g==null||g("003",rn.error003(N)),N="default",x=(S==null?void 0:S.default)||mp.default);const _=!!(m.draggable||l&&typeof m.draggable>"u"),C=!!(m.selectable||c&&typeof m.selectable>"u"),v=!!(m.connectable||d&&typeof m.connectable>"u"),b=!!(m.focusable||u&&typeof m.focusable>"u"),P=we(),j=zA(m),L=fj({node:m,nodeType:N,hasDimensions:j,resizeObserver:E}),B=Om({nodeRef:L,disabled:m.hidden||!_,noDragClassName:f,handleSelector:m.dragHandle,nodeId:e,isSelectable:C,nodeClickDistance:h}),M=Nm();if(m.hidden)return null;const U=An(m),D=oj(m),y=C||_||t||n||r||s,w=n?z=>n(z,{...I.userNode}):void 0,F=r?z=>r(z,{...I.userNode}):void 0,k=s?z=>s(z,{...I.userNode}):void 0,V=i?z=>i(z,{...I.userNode}):void 0,ee=a?z=>a(z,{...I.userNode}):void 0,Y=z=>{const{selectNodesOnDrag:oe,nodeDragThreshold:le}=P.getState();C&&(!oe||!_||le>0)&&Cd({id:e,store:P,nodeRef:L}),t&&t(z,{...I.userNode})},te=z=>{if(!(qA(z.nativeEvent)||A)){if(jA.includes(z.key)&&C){const oe=z.key==="Escape";Cd({id:e,store:P,unselect:oe,nodeRef:L})}else if(_&&m.selected&&Object.prototype.hasOwnProperty.call(fa,z.key)){z.preventDefault();const{ariaLabelConfig:oe}=P.getState();P.setState({ariaLiveMessage:oe["node.a11yDescription.ariaLiveMessage"]({direction:z.key.replace("Arrow","").toLowerCase(),x:~~I.positionAbsolute.x,y:~~I.positionAbsolute.y})}),M({direction:fa[z.key],factor:z.shiftKey?4:1})}}},ne=()=>{var re;if(A||!((re=L.current)!=null&&re.matches(":focus-visible")))return;const{transform:z,width:oe,height:le,autoPanOnNodeFocus:ae,setCenter:X}=P.getState();if(!ae)return;Du(new Map([[e,m]]),{x:0,y:0,width:oe,height:le},z,!0).length>0||X(m.position.x+U.width/2,m.position.y+U.height/2,{zoom:z[2]})};return o.jsx("div",{className:He(["react-flow__node",`react-flow__node-${N}`,{[T]:_},m.className,{selected:m.selected,selectable:C,parent:O,draggable:_,dragging:B}]),ref:L,style:{zIndex:I.z,transform:`translate(${I.positionAbsolute.x}px,${I.positionAbsolute.y}px)`,pointerEvents:y?"all":"none",visibility:j?"visible":"hidden",...m.style,...D},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:w,onMouseMove:F,onMouseLeave:k,onContextMenu:V,onClick:Y,onDoubleClick:ee,onKeyDown:b?te:void 0,tabIndex:b?0:void 0,onFocus:b?ne:void 0,role:m.ariaRole??(b?"group":void 0),"aria-roledescription":"node","aria-describedby":A?void 0:`${Tm}-${R}`,"aria-label":m.ariaLabel,...m.domAttributes,children:o.jsx(qB,{value:e,children:o.jsx(x,{id:e,data:m.data,type:N,positionAbsoluteX:I.positionAbsolute.x,positionAbsoluteY:I.positionAbsolute.y,selected:m.selected??!1,selectable:C,draggable:_,deletable:m.deletable??!0,isConnectable:v,sourcePosition:m.sourcePosition,targetPosition:m.targetPosition,dragging:B,dragHandle:m.dragHandle,zIndex:I.z,parentId:m.parentId,...U})})})}var Tj=p.memo(pj);const Sj=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function Cm(e){const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:s,onError:i}=Ne(Sj,Me),a=dj(e.onlyRenderVisibleElements),l=Ej();return o.jsx("div",{className:"react-flow__nodes",style:ol,children:a.map(c=>o.jsx(Tj,{id:c,nodeTypes:e.nodeTypes,nodeExtent:e.nodeExtent,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,resizeObserver:l,nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:s,nodeClickDistance:e.nodeClickDistance,onError:i},c))})}Cm.displayName="NodeRenderer";const hj=p.memo(Cm);function Rj(e){return Ne(p.useCallback(n=>{if(!e)return n.edges.map(s=>s.id);const r=[];if(n.width&&n.height)for(const s of n.edges){const i=n.nodeLookup.get(s.source),a=n.nodeLookup.get(s.target);i&&a&&SU({sourceNode:i,targetNode:a,width:n.width,height:n.height,transform:n.transform})&&r.push(s.id)}return r},[e]),Me)}const Aj=({color:e="none",strokeWidth:t=1})=>{const n={strokeWidth:t,...e&&{stroke:e}};return o.jsx("polyline",{className:"arrow",style:n,strokeLinecap:"round",fill:"none",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4"})},mj=({color:e="none",strokeWidth:t=1})=>{const n={strokeWidth:t,...e&&{stroke:e,fill:e}};return o.jsx("polyline",{className:"arrowclosed",style:n,strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"})},Ip={[Eo.Arrow]:Aj,[Eo.ArrowClosed]:mj};function gj(e){const t=we();return p.useMemo(()=>{var s,i;return Object.prototype.hasOwnProperty.call(Ip,e)?Ip[e]:((i=(s=t.getState()).onError)==null||i.call(s,"009",rn.error009(e)),null)},[e])}const Ij=({id:e,type:t,color:n,width:r=12.5,height:s=12.5,markerUnits:i="strokeWidth",strokeWidth:a,orient:l="auto-start-reverse"})=>{const c=gj(t);return c?o.jsx("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${r}`,markerHeight:`${s}`,viewBox:"-10 -10 20 20",markerUnits:i,orient:l,refX:"0",refY:"0",children:o.jsx(c,{color:n,strokeWidth:a})}):null},Lm=({defaultColor:e,rfId:t})=>{const n=Ne(i=>i.edges),r=Ne(i=>i.defaultEdgeOptions),s=p.useMemo(()=>NU(n,{id:t,defaultColor:e,defaultMarkerStart:r==null?void 0:r.markerStart,defaultMarkerEnd:r==null?void 0:r.markerEnd}),[n,r,t,e]);return s.length?o.jsx("svg",{className:"react-flow__marker","aria-hidden":"true",children:o.jsx("defs",{children:s.map(i=>o.jsx(Ij,{id:i.id,type:i.type,color:i.color,width:i.width,height:i.height,markerUnits:i.markerUnits,strokeWidth:i.strokeWidth,orient:i.orient},i.id))})}):null};Lm.displayName="MarkerDefinitions";var Oj=p.memo(Lm);function _m({x:e,y:t,label:n,labelStyle:r,labelShowBg:s=!0,labelBgStyle:i,labelBgPadding:a=[2,4],labelBgBorderRadius:l=2,children:c,className:d,...u}){const[E,f]=p.useState({x:1,y:0,width:0,height:0}),T=He(["react-flow__edge-textwrapper",d]),A=p.useRef(null);return p.useEffect(()=>{if(A.current){const R=A.current.getBBox();f({x:R.x,y:R.y,width:R.width,height:R.height})}},[n]),n?o.jsxs("g",{transform:`translate(${e-E.width/2} ${t-E.height/2})`,className:T,visibility:E.width?"visible":"hidden",...u,children:[s&&o.jsx("rect",{width:E.width+2*a[0],x:-a[0],y:-a[1],height:E.height+2*a[1],className:"react-flow__edge-textbg",style:i,rx:l,ry:l}),o.jsx("text",{className:"react-flow__edge-text",y:E.height/2,dy:"0.3em",ref:A,style:r,children:n}),c]}):null}_m.displayName="EdgeText";const Nj=p.memo(_m);function sl({path:e,labelX:t,labelY:n,label:r,labelStyle:s,labelShowBg:i,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c,interactionWidth:d=20,...u}){return o.jsxs(o.Fragment,{children:[o.jsx("path",{...u,d:e,fill:"none",className:He(["react-flow__edge-path",u.className])}),d?o.jsx("path",{d:e,fill:"none",strokeOpacity:0,strokeWidth:d,className:"react-flow__edge-interaction"}):null,r&&wt(t)&&wt(n)?o.jsx(Nj,{x:t,y:n,label:r,labelStyle:s,labelShowBg:i,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c}):null]})}function Op({pos:e,x1:t,y1:n,x2:r,y2:s}){return e===pe.Left||e===pe.Right?[.5*(t+r),n]:[t,.5*(n+s)]}function bm({sourceX:e,sourceY:t,sourcePosition:n=pe.Bottom,targetX:r,targetY:s,targetPosition:i=pe.Top}){const[a,l]=Op({pos:n,x1:e,y1:t,x2:r,y2:s}),[c,d]=Op({pos:i,x1:r,y1:s,x2:e,y2:t}),[u,E,f,T]=QA({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:a,sourceControlY:l,targetControlX:c,targetControlY:d});return[`M${e},${t} C${a},${l} ${c},${d} ${r},${s}`,u,E,f,T]}function vm(e){return p.memo(({id:t,sourceX:n,sourceY:r,targetX:s,targetY:i,sourcePosition:a,targetPosition:l,label:c,labelStyle:d,labelShowBg:u,labelBgStyle:E,labelBgPadding:f,labelBgBorderRadius:T,style:A,markerEnd:R,markerStart:S,interactionWidth:h})=>{const[g,m,I]=bm({sourceX:n,sourceY:r,sourcePosition:a,targetX:s,targetY:i,targetPosition:l}),O=e.isInternal?void 0:t;return o.jsx(sl,{id:O,path:g,labelX:m,labelY:I,label:c,labelStyle:d,labelShowBg:u,labelBgStyle:E,labelBgPadding:f,labelBgBorderRadius:T,style:A,markerEnd:R,markerStart:S,interactionWidth:h})})}const xj=vm({isInternal:!1}),Dm=vm({isInternal:!0});xj.displayName="SimpleBezierEdge";Dm.displayName="SimpleBezierEdgeInternal";function Mm(e){return p.memo(({id:t,sourceX:n,sourceY:r,targetX:s,targetY:i,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:d,labelBgPadding:u,labelBgBorderRadius:E,style:f,sourcePosition:T=pe.Bottom,targetPosition:A=pe.Top,markerEnd:R,markerStart:S,pathOptions:h,interactionWidth:g})=>{const[m,I,O]=Od({sourceX:n,sourceY:r,sourcePosition:T,targetX:s,targetY:i,targetPosition:A,borderRadius:h==null?void 0:h.borderRadius,offset:h==null?void 0:h.offset,stepPosition:h==null?void 0:h.stepPosition}),N=e.isInternal?void 0:t;return o.jsx(sl,{id:N,path:m,labelX:I,labelY:O,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:d,labelBgPadding:u,labelBgBorderRadius:E,style:f,markerEnd:R,markerStart:S,interactionWidth:g})})}const Pm=Mm({isInternal:!1}),wm=Mm({isInternal:!0});Pm.displayName="SmoothStepEdge";wm.displayName="SmoothStepEdgeInternal";function Um(e){return p.memo(({id:t,...n})=>{var s;const r=e.isInternal?void 0:t;return o.jsx(Pm,{...n,id:r,pathOptions:p.useMemo(()=>{var i;return{borderRadius:0,offset:(i=n.pathOptions)==null?void 0:i.offset}},[(s=n.pathOptions)==null?void 0:s.offset])})})}const yj=Um({isInternal:!1}),Bm=Um({isInternal:!0});yj.displayName="StepEdge";Bm.displayName="StepEdgeInternal";function jm(e){return p.memo(({id:t,sourceX:n,sourceY:r,targetX:s,targetY:i,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:d,labelBgPadding:u,labelBgBorderRadius:E,style:f,markerEnd:T,markerStart:A,interactionWidth:R})=>{const[S,h,g]=tm({sourceX:n,sourceY:r,targetX:s,targetY:i}),m=e.isInternal?void 0:t;return o.jsx(sl,{id:m,path:S,labelX:h,labelY:g,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:d,labelBgPadding:u,labelBgBorderRadius:E,style:f,markerEnd:T,markerStart:A,interactionWidth:R})})}const Cj=jm({isInternal:!1}),km=jm({isInternal:!0});Cj.displayName="StraightEdge";km.displayName="StraightEdgeInternal";function Fm(e){return p.memo(({id:t,sourceX:n,sourceY:r,targetX:s,targetY:i,sourcePosition:a=pe.Bottom,targetPosition:l=pe.Top,label:c,labelStyle:d,labelShowBg:u,labelBgStyle:E,labelBgPadding:f,labelBgBorderRadius:T,style:A,markerEnd:R,markerStart:S,pathOptions:h,interactionWidth:g})=>{const[m,I,O]=ZA({sourceX:n,sourceY:r,sourcePosition:a,targetX:s,targetY:i,targetPosition:l,curvature:h==null?void 0:h.curvature}),N=e.isInternal?void 0:t;return o.jsx(sl,{id:N,path:m,labelX:I,labelY:O,label:c,labelStyle:d,labelShowBg:u,labelBgStyle:E,labelBgPadding:f,labelBgBorderRadius:T,style:A,markerEnd:R,markerStart:S,interactionWidth:g})})}const Lj=Fm({isInternal:!1}),Gm=Fm({isInternal:!0});Lj.displayName="BezierEdge";Gm.displayName="BezierEdgeInternal";const Np={default:Gm,straight:km,step:Bm,smoothstep:wm,simplebezier:Dm},xp={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},_j=(e,t,n)=>n===pe.Left?e-t:n===pe.Right?e+t:e,bj=(e,t,n)=>n===pe.Top?e-t:n===pe.Bottom?e+t:e,yp="react-flow__edgeupdater";function Cp({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:s,onMouseEnter:i,onMouseOut:a,type:l}){return o.jsx("circle",{onMouseDown:s,onMouseEnter:i,onMouseOut:a,className:He([yp,`${yp}-${l}`]),cx:_j(t,r,e),cy:bj(n,r,e),r,stroke:"transparent",fill:"transparent"})}function vj({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:r,sourceY:s,targetX:i,targetY:a,sourcePosition:l,targetPosition:c,onReconnect:d,onReconnectStart:u,onReconnectEnd:E,setReconnecting:f,setUpdateHover:T}){const A=we(),R=(I,O)=>{if(I.button!==0)return;const{autoPanOnConnect:N,domNode:x,connectionMode:_,connectionRadius:C,lib:v,onConnectStart:b,cancelConnection:P,nodeLookup:j,rfId:L,panBy:B,updateConnection:M}=A.getState(),U=O.type==="target",D=(F,k)=>{f(!1),E==null||E(F,n,O.type,k)},y=F=>d==null?void 0:d(n,F),w=(F,k)=>{f(!0),u==null||u(I,n,O.type),b==null||b(F,k)};yd.onPointerDown(I.nativeEvent,{autoPanOnConnect:N,connectionMode:_,connectionRadius:C,domNode:x,handleId:O.id,nodeId:O.nodeId,nodeLookup:j,isTarget:U,edgeUpdaterType:O.type,lib:v,flowId:L,cancelConnection:P,panBy:B,isValidConnection:(...F)=>{var k,V;return((V=(k=A.getState()).isValidConnection)==null?void 0:V.call(k,...F))??!0},onConnect:y,onConnectStart:w,onConnectEnd:(...F)=>{var k,V;return(V=(k=A.getState()).onConnectEnd)==null?void 0:V.call(k,...F)},onReconnectEnd:D,updateConnection:M,getTransform:()=>A.getState().transform,getFromHandle:()=>A.getState().connection.fromHandle,dragThreshold:A.getState().connectionDragThreshold,handleDomNode:I.currentTarget})},S=I=>R(I,{nodeId:n.target,id:n.targetHandle??null,type:"target"}),h=I=>R(I,{nodeId:n.source,id:n.sourceHandle??null,type:"source"}),g=()=>T(!0),m=()=>T(!1);return o.jsxs(o.Fragment,{children:[(e===!0||e==="source")&&o.jsx(Cp,{position:l,centerX:r,centerY:s,radius:t,onMouseDown:S,onMouseEnter:g,onMouseOut:m,type:"source"}),(e===!0||e==="target")&&o.jsx(Cp,{position:c,centerX:i,centerY:a,radius:t,onMouseDown:h,onMouseEnter:g,onMouseOut:m,type:"target"})]})}function Dj({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:r,onClick:s,onDoubleClick:i,onContextMenu:a,onMouseEnter:l,onMouseMove:c,onMouseLeave:d,reconnectRadius:u,onReconnect:E,onReconnectStart:f,onReconnectEnd:T,rfId:A,edgeTypes:R,noPanClassName:S,onError:h,disableKeyboardA11y:g}){let m=Ne(X=>X.edgeLookup.get(e));const I=Ne(X=>X.defaultEdgeOptions);m=I?{...I,...m}:m;let O=m.type||"default",N=(R==null?void 0:R[O])||Np[O];N===void 0&&(h==null||h("011",rn.error011(O)),O="default",N=(R==null?void 0:R.default)||Np.default);const x=!!(m.focusable||t&&typeof m.focusable>"u"),_=typeof E<"u"&&(m.reconnectable||n&&typeof m.reconnectable>"u"),C=!!(m.selectable||r&&typeof m.selectable>"u"),v=p.useRef(null),[b,P]=p.useState(!1),[j,L]=p.useState(!1),B=we(),{zIndex:M,sourceX:U,sourceY:D,targetX:y,targetY:w,sourcePosition:F,targetPosition:k}=Ne(p.useCallback(X=>{const H=X.nodeLookup.get(m.source),re=X.nodeLookup.get(m.target);if(!H||!re)return{zIndex:m.zIndex,...xp};const ie=OU({id:e,sourceNode:H,targetNode:re,sourceHandle:m.sourceHandle||null,targetHandle:m.targetHandle||null,connectionMode:X.connectionMode,onError:h});return{zIndex:TU({selected:m.selected,zIndex:m.zIndex,sourceNode:H,targetNode:re,elevateOnSelect:X.elevateEdgesOnSelect,zIndexMode:X.zIndexMode}),...ie||xp}},[m.source,m.target,m.sourceHandle,m.targetHandle,m.selected,m.zIndex]),Me),V=p.useMemo(()=>m.markerStart?`url('#${Nd(m.markerStart,A)}')`:void 0,[m.markerStart,A]),ee=p.useMemo(()=>m.markerEnd?`url('#${Nd(m.markerEnd,A)}')`:void 0,[m.markerEnd,A]);if(m.hidden||U===null||D===null||y===null||w===null)return null;const Y=X=>{var de;const{addSelectedEdges:H,unselectNodesAndEdges:re,multiSelectionActive:ie}=B.getState();C&&(B.setState({nodesSelectionActive:!1}),m.selected&&ie?(re({nodes:[],edges:[m]}),(de=v.current)==null||de.blur()):H([e])),s&&s(X,m)},te=i?X=>{i(X,{...m})}:void 0,ne=a?X=>{a(X,{...m})}:void 0,z=l?X=>{l(X,{...m})}:void 0,oe=c?X=>{c(X,{...m})}:void 0,le=d?X=>{d(X,{...m})}:void 0,ae=X=>{var H;if(!g&&jA.includes(X.key)&&C){const{unselectNodesAndEdges:re,addSelectedEdges:ie}=B.getState();X.key==="Escape"?((H=v.current)==null||H.blur(),re({edges:[m]})):ie([e])}};return o.jsx("svg",{style:{zIndex:M},children:o.jsxs("g",{className:He(["react-flow__edge",`react-flow__edge-${O}`,m.className,S,{selected:m.selected,animated:m.animated,inactive:!C&&!s,updating:b,selectable:C}]),onClick:Y,onDoubleClick:te,onContextMenu:ne,onMouseEnter:z,onMouseMove:oe,onMouseLeave:le,onKeyDown:x?ae:void 0,tabIndex:x?0:void 0,role:m.ariaRole??(x?"group":"img"),"aria-roledescription":"edge","data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":m.ariaLabel===null?void 0:m.ariaLabel||`Edge from ${m.source} to ${m.target}`,"aria-describedby":x?`${Sm}-${A}`:void 0,ref:v,...m.domAttributes,children:[!j&&o.jsx(N,{id:e,source:m.source,target:m.target,type:m.type,selected:m.selected,animated:m.animated,selectable:C,deletable:m.deletable??!0,label:m.label,labelStyle:m.labelStyle,labelShowBg:m.labelShowBg,labelBgStyle:m.labelBgStyle,labelBgPadding:m.labelBgPadding,labelBgBorderRadius:m.labelBgBorderRadius,sourceX:U,sourceY:D,targetX:y,targetY:w,sourcePosition:F,targetPosition:k,data:m.data,style:m.style,sourceHandleId:m.sourceHandle,targetHandleId:m.targetHandle,markerStart:V,markerEnd:ee,pathOptions:"pathOptions"in m?m.pathOptions:void 0,interactionWidth:m.interactionWidth}),_&&o.jsx(vj,{edge:m,isReconnectable:_,reconnectRadius:u,onReconnect:E,onReconnectStart:f,onReconnectEnd:T,sourceX:U,sourceY:D,targetX:y,targetY:w,sourcePosition:F,targetPosition:k,setUpdateHover:P,setReconnecting:L})]})})}var Mj=p.memo(Dj);const Pj=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function Hm({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:r,noPanClassName:s,onReconnect:i,onEdgeContextMenu:a,onEdgeMouseEnter:l,onEdgeMouseMove:c,onEdgeMouseLeave:d,onEdgeClick:u,reconnectRadius:E,onEdgeDoubleClick:f,onReconnectStart:T,onReconnectEnd:A,disableKeyboardA11y:R}){const{edgesFocusable:S,edgesReconnectable:h,elementsSelectable:g,onError:m}=Ne(Pj,Me),I=Rj(t);return o.jsxs("div",{className:"react-flow__edges",children:[o.jsx(Oj,{defaultColor:e,rfId:n}),I.map(O=>o.jsx(Mj,{id:O,edgesFocusable:S,edgesReconnectable:h,elementsSelectable:g,noPanClassName:s,onReconnect:i,onContextMenu:a,onMouseEnter:l,onMouseMove:c,onMouseLeave:d,onClick:u,reconnectRadius:E,onDoubleClick:f,onReconnectStart:T,onReconnectEnd:A,rfId:n,onError:m,edgeTypes:r,disableKeyboardA11y:R},O))]})}Hm.displayName="EdgeRenderer";const wj=p.memo(Hm),Uj=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function Bj({children:e}){const t=Ne(Uj);return o.jsx("div",{className:"react-flow__viewport xyflow__viewport react-flow__container",style:{transform:t},children:e})}function jj(e){const t=rl(),n=p.useRef(!1);p.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const kj=e=>{var t;return(t=e.panZoom)==null?void 0:t.syncViewport};function Fj(e){const t=Ne(kj),n=we();return p.useEffect(()=>{e&&(t==null||t(e),n.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function Gj(e){return e.connection.inProgress?{...e.connection,to:Ms(e.connection.to,e.transform)}:{...e.connection}}function Hj(e){return Gj}function Wj(e){const t=Hj();return Ne(t,Me)}const Yj=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function $j({containerStyle:e,style:t,type:n,component:r}){const{nodesConnectable:s,width:i,height:a,isValid:l,inProgress:c}=Ne(Yj,Me);return!(i&&s&&c)?null:o.jsx("svg",{style:e,width:i,height:a,className:"react-flow__connectionline react-flow__container",children:o.jsx("g",{className:He(["react-flow__connection",GA(l)]),children:o.jsx(Wm,{style:t,type:n,CustomComponent:r,isValid:l})})})}const Wm=({style:e,type:t=bn.Bezier,CustomComponent:n,isValid:r})=>{const{inProgress:s,from:i,fromNode:a,fromHandle:l,fromPosition:c,to:d,toNode:u,toHandle:E,toPosition:f,pointer:T}=Wj();if(!s)return;if(n)return o.jsx(n,{connectionLineType:t,connectionLineStyle:e,fromNode:a,fromHandle:l,fromX:i.x,fromY:i.y,toX:d.x,toY:d.y,fromPosition:c,toPosition:f,connectionStatus:GA(r),toNode:u,toHandle:E,pointer:T});let A="";const R={sourceX:i.x,sourceY:i.y,sourcePosition:c,targetX:d.x,targetY:d.y,targetPosition:f};switch(t){case bn.Bezier:[A]=ZA(R);break;case bn.SimpleBezier:[A]=bm(R);break;case bn.Step:[A]=Od({...R,borderRadius:0});break;case bn.SmoothStep:[A]=Od(R);break;default:[A]=tm(R)}return o.jsx("path",{d:A,fill:"none",className:"react-flow__connection-path",style:e})};Wm.displayName="ConnectionLine";const Vj={};function Lp(e=Vj){p.useRef(e),we(),p.useEffect(()=>{},[e])}function zj(){we(),p.useRef(!1),p.useEffect(()=>{},[])}function Ym({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:r,onEdgeClick:s,onNodeDoubleClick:i,onEdgeDoubleClick:a,onNodeMouseEnter:l,onNodeMouseMove:c,onNodeMouseLeave:d,onNodeContextMenu:u,onSelectionContextMenu:E,onSelectionStart:f,onSelectionEnd:T,connectionLineType:A,connectionLineStyle:R,connectionLineComponent:S,connectionLineContainerStyle:h,selectionKeyCode:g,selectionOnDrag:m,selectionMode:I,multiSelectionKeyCode:O,panActivationKeyCode:N,zoomActivationKeyCode:x,deleteKeyCode:_,onlyRenderVisibleElements:C,elementsSelectable:v,defaultViewport:b,translateExtent:P,minZoom:j,maxZoom:L,preventScrolling:B,defaultMarkerColor:M,zoomOnScroll:U,zoomOnPinch:D,panOnScroll:y,panOnScrollSpeed:w,panOnScrollMode:F,zoomOnDoubleClick:k,panOnDrag:V,onPaneClick:ee,onPaneMouseEnter:Y,onPaneMouseMove:te,onPaneMouseLeave:ne,onPaneScroll:z,onPaneContextMenu:oe,paneClickDistance:le,nodeClickDistance:ae,onEdgeContextMenu:X,onEdgeMouseEnter:H,onEdgeMouseMove:re,onEdgeMouseLeave:ie,reconnectRadius:de,onReconnect:se,onReconnectStart:ge,onReconnectEnd:xe,noDragClassName:Fe,noWheelClassName:Z,noPanClassName:Ee,disableKeyboardA11y:Oe,nodeExtent:ve,rfId:Le,viewport:Tt,onViewportChange:yt}){return Lp(e),Lp(t),zj(),jj(n),Fj(Tt),o.jsx(lj,{onPaneClick:ee,onPaneMouseEnter:Y,onPaneMouseMove:te,onPaneMouseLeave:ne,onPaneContextMenu:oe,onPaneScroll:z,paneClickDistance:le,deleteKeyCode:_,selectionKeyCode:g,selectionOnDrag:m,selectionMode:I,onSelectionStart:f,onSelectionEnd:T,multiSelectionKeyCode:O,panActivationKeyCode:N,zoomActivationKeyCode:x,elementsSelectable:v,zoomOnScroll:U,zoomOnPinch:D,zoomOnDoubleClick:k,panOnScroll:y,panOnScrollSpeed:w,panOnScrollMode:F,panOnDrag:V,defaultViewport:b,translateExtent:P,minZoom:j,maxZoom:L,onSelectionContextMenu:E,preventScrolling:B,noDragClassName:Fe,noWheelClassName:Z,noPanClassName:Ee,disableKeyboardA11y:Oe,onViewportChange:yt,isControlledViewport:!!Tt,children:o.jsxs(Bj,{children:[o.jsx(wj,{edgeTypes:t,onEdgeClick:s,onEdgeDoubleClick:a,onReconnect:se,onReconnectStart:ge,onReconnectEnd:xe,onlyRenderVisibleElements:C,onEdgeContextMenu:X,onEdgeMouseEnter:H,onEdgeMouseMove:re,onEdgeMouseLeave:ie,reconnectRadius:de,defaultMarkerColor:M,noPanClassName:Ee,disableKeyboardA11y:Oe,rfId:Le}),o.jsx($j,{style:R,type:A,component:S,containerStyle:h}),o.jsx("div",{className:"react-flow__edgelabel-renderer"}),o.jsx(hj,{nodeTypes:e,onNodeClick:r,onNodeDoubleClick:i,onNodeMouseEnter:l,onNodeMouseMove:c,onNodeMouseLeave:d,onNodeContextMenu:u,nodeClickDistance:ae,onlyRenderVisibleElements:C,noPanClassName:Ee,noDragClassName:Fe,disableKeyboardA11y:Oe,nodeExtent:ve,rfId:Le}),o.jsx("div",{className:"react-flow__viewport-portal"})]})})}Ym.displayName="GraphView";const Xj=p.memo(Ym),_p=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:s,height:i,fitView:a,fitViewOptions:l,minZoom:c=.5,maxZoom:d=2,nodeOrigin:u,nodeExtent:E,zIndexMode:f="basic"}={})=>{const T=new Map,A=new Map,R=new Map,S=new Map,h=r??t??[],g=n??e??[],m=u??[0,0],I=E??us;om(R,S,h);const O=xd(g,T,A,{nodeOrigin:m,nodeExtent:I,zIndexMode:f});let N=[0,0,1];if(a&&s&&i){const x=vs(T,{filter:b=>!!((b.width||b.initialWidth)&&(b.height||b.initialHeight))}),{x:_,y:C,zoom:v}=Mu(x,s,i,c,d,(l==null?void 0:l.padding)??.1);N=[_,C,v]}return{rfId:"1",width:s??0,height:i??0,transform:N,nodes:g,nodesInitialized:O,nodeLookup:T,parentLookup:A,edges:h,edgeLookup:S,connectionLookup:R,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:n!==void 0,hasDefaultEdges:r!==void 0,panZoom:null,minZoom:c,maxZoom:d,translateExtent:us,nodeExtent:I,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:uo.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:m,nodeDragThreshold:1,connectionDragThreshold:1,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesReconnectable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,elevateEdgesOnSelect:!0,selectNodesOnDrag:!0,multiSelectionActive:!1,fitViewQueued:a??!1,fitViewOptions:l,fitViewResolver:null,connection:{...FA},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:cU,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:"react",debug:!1,ariaLabelConfig:kA,zIndexMode:f,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}},Kj=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:s,height:i,fitView:a,fitViewOptions:l,minZoom:c,maxZoom:d,nodeOrigin:u,nodeExtent:E,zIndexMode:f})=>fB((T,A)=>{async function R(){const{nodeLookup:S,panZoom:h,fitViewOptions:g,fitViewResolver:m,width:I,height:O,minZoom:N,maxZoom:x}=A();h&&(await aU({nodes:S,width:I,height:O,panZoom:h,minZoom:N,maxZoom:x},g),m==null||m.resolve(!0),T({fitViewResolver:null}))}return{..._p({nodes:e,edges:t,width:s,height:i,fitView:a,fitViewOptions:l,minZoom:c,maxZoom:d,nodeOrigin:u,nodeExtent:E,defaultNodes:n,defaultEdges:r,zIndexMode:f}),setNodes:S=>{const{nodeLookup:h,parentLookup:g,nodeOrigin:m,elevateNodesOnSelect:I,fitViewQueued:O,zIndexMode:N}=A(),x=xd(S,h,g,{nodeOrigin:m,nodeExtent:E,elevateNodesOnSelect:I,checkEquality:!0,zIndexMode:N});O&&x?(R(),T({nodes:S,nodesInitialized:x,fitViewQueued:!1,fitViewOptions:void 0})):T({nodes:S,nodesInitialized:x})},setEdges:S=>{const{connectionLookup:h,edgeLookup:g}=A();om(h,g,S),T({edges:S})},setDefaultNodesAndEdges:(S,h)=>{if(S){const{setNodes:g}=A();g(S),T({hasDefaultNodes:!0})}if(h){const{setEdges:g}=A();g(h),T({hasDefaultEdges:!0})}},updateNodeInternals:S=>{const{triggerNodeChanges:h,nodeLookup:g,parentLookup:m,domNode:I,nodeOrigin:O,nodeExtent:N,debug:x,fitViewQueued:_,zIndexMode:C}=A(),{changes:v,updatedInternals:b}=vU(S,g,m,I,O,N,C);b&&(CU(g,m,{nodeOrigin:O,nodeExtent:N,zIndexMode:C}),_?(R(),T({fitViewQueued:!1,fitViewOptions:void 0})):T({}),(v==null?void 0:v.length)>0&&(x&&console.log("React Flow: trigger node changes",v),h==null||h(v)))},updateNodePositions:(S,h=!1)=>{const g=[];let m=[];const{nodeLookup:I,triggerNodeChanges:O,connection:N,updateConnection:x,onNodesChangeMiddlewareMap:_}=A();for(const[C,v]of S){const b=I.get(C),P=!!(b!=null&&b.expandParent&&(b!=null&&b.parentId)&&(v!=null&&v.position)),j={id:C,type:"position",position:P?{x:Math.max(0,v.position.x),y:Math.max(0,v.position.y)}:v.position,dragging:h};if(b&&N.inProgress&&N.fromNode.id===b.id){const L=mr(b,N.fromHandle,pe.Left,!0);x({...N,from:L})}P&&b.parentId&&g.push({id:C,parentId:b.parentId,rect:{...v.internals.positionAbsolute,width:v.measured.width??0,height:v.measured.height??0}}),m.push(j)}if(g.length>0){const{parentLookup:C,nodeOrigin:v}=A(),b=ku(g,I,C,v);m.push(...b)}for(const C of _.values())m=C(m);O(m)},triggerNodeChanges:S=>{const{onNodesChange:h,setNodes:g,nodes:m,hasDefaultNodes:I,debug:O}=A();if(S!=null&&S.length){if(I){const N=Am(S,m);g(N)}O&&console.log("React Flow: trigger node changes",S),h==null||h(S)}},triggerEdgeChanges:S=>{const{onEdgesChange:h,setEdges:g,edges:m,hasDefaultEdges:I,debug:O}=A();if(S!=null&&S.length){if(I){const N=mm(S,m);g(N)}O&&console.log("React Flow: trigger edge changes",S),h==null||h(S)}},addSelectedNodes:S=>{const{multiSelectionActive:h,edgeLookup:g,nodeLookup:m,triggerNodeChanges:I,triggerEdgeChanges:O}=A();if(h){const N=S.map(x=>or(x,!0));I(N);return}I(Kr(m,new Set([...S]),!0)),O(Kr(g))},addSelectedEdges:S=>{const{multiSelectionActive:h,edgeLookup:g,nodeLookup:m,triggerNodeChanges:I,triggerEdgeChanges:O}=A();if(h){const N=S.map(x=>or(x,!0));O(N);return}O(Kr(g,new Set([...S]))),I(Kr(m,new Set,!0))},unselectNodesAndEdges:({nodes:S,edges:h}={})=>{const{edges:g,nodes:m,nodeLookup:I,triggerNodeChanges:O,triggerEdgeChanges:N}=A(),x=S||m,_=h||g,C=[];for(const b of x){if(!b.selected)continue;const P=I.get(b.id);P&&(P.selected=!1),C.push(or(b.id,!1))}const v=[];for(const b of _)b.selected&&v.push(or(b.id,!1));O(C),N(v)},setMinZoom:S=>{const{panZoom:h,maxZoom:g}=A();h==null||h.setScaleExtent([S,g]),T({minZoom:S})},setMaxZoom:S=>{const{panZoom:h,minZoom:g}=A();h==null||h.setScaleExtent([g,S]),T({maxZoom:S})},setTranslateExtent:S=>{var h;(h=A().panZoom)==null||h.setTranslateExtent(S),T({translateExtent:S})},resetSelectedElements:()=>{const{edges:S,nodes:h,triggerNodeChanges:g,triggerEdgeChanges:m,elementsSelectable:I}=A();if(!I)return;const O=h.reduce((x,_)=>_.selected?[...x,or(_.id,!1)]:x,[]),N=S.reduce((x,_)=>_.selected?[...x,or(_.id,!1)]:x,[]);g(O),m(N)},setNodeExtent:S=>{const{nodes:h,nodeLookup:g,parentLookup:m,nodeOrigin:I,elevateNodesOnSelect:O,nodeExtent:N,zIndexMode:x}=A();S[0][0]===N[0][0]&&S[0][1]===N[0][1]&&S[1][0]===N[1][0]&&S[1][1]===N[1][1]||(xd(h,g,m,{nodeOrigin:I,nodeExtent:S,elevateNodesOnSelect:O,checkEquality:!1,zIndexMode:x}),T({nodeExtent:S}))},panBy:S=>{const{transform:h,width:g,height:m,panZoom:I,translateExtent:O}=A();return DU({delta:S,panZoom:I,transform:h,translateExtent:O,width:g,height:m})},setCenter:async(S,h,g)=>{const{width:m,height:I,maxZoom:O,panZoom:N}=A();if(!N)return Promise.resolve(!1);const x=typeof(g==null?void 0:g.zoom)<"u"?g.zoom:O;return await N.setViewport({x:m/2-S*x,y:I/2-h*x,zoom:x},{duration:g==null?void 0:g.duration,ease:g==null?void 0:g.ease,interpolate:g==null?void 0:g.interpolate}),Promise.resolve(!0)},cancelConnection:()=>{T({connection:{...FA}})},updateConnection:S=>{T({connection:S})},reset:()=>T({..._p()})}},Object.is);function $m({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:r,initialWidth:s,initialHeight:i,initialMinZoom:a,initialMaxZoom:l,initialFitViewOptions:c,fitView:d,nodeOrigin:u,nodeExtent:E,zIndexMode:f,children:T}){const[A]=p.useState(()=>Kj({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:s,height:i,fitView:d,minZoom:a,maxZoom:l,fitViewOptions:c,nodeOrigin:u,nodeExtent:E,zIndexMode:f}));return o.jsx(pB,{value:A,children:o.jsx(BB,{children:T})})}function qj({children:e,nodes:t,edges:n,defaultNodes:r,defaultEdges:s,width:i,height:a,fitView:l,fitViewOptions:c,minZoom:d,maxZoom:u,nodeOrigin:E,nodeExtent:f,zIndexMode:T}){return p.useContext(nl)?o.jsx(o.Fragment,{children:e}):o.jsx($m,{initialNodes:t,initialEdges:n,defaultNodes:r,defaultEdges:s,initialWidth:i,initialHeight:a,fitView:l,initialFitViewOptions:c,initialMinZoom:d,initialMaxZoom:u,nodeOrigin:E,nodeExtent:f,zIndexMode:T,children:e})}const Jj={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0};function Qj({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:s,nodeTypes:i,edgeTypes:a,onNodeClick:l,onEdgeClick:c,onInit:d,onMove:u,onMoveStart:E,onMoveEnd:f,onConnect:T,onConnectStart:A,onConnectEnd:R,onClickConnectStart:S,onClickConnectEnd:h,onNodeMouseEnter:g,onNodeMouseMove:m,onNodeMouseLeave:I,onNodeContextMenu:O,onNodeDoubleClick:N,onNodeDragStart:x,onNodeDrag:_,onNodeDragStop:C,onNodesDelete:v,onEdgesDelete:b,onDelete:P,onSelectionChange:j,onSelectionDragStart:L,onSelectionDrag:B,onSelectionDragStop:M,onSelectionContextMenu:U,onSelectionStart:D,onSelectionEnd:y,onBeforeDelete:w,connectionMode:F,connectionLineType:k=bn.Bezier,connectionLineStyle:V,connectionLineComponent:ee,connectionLineContainerStyle:Y,deleteKeyCode:te="Backspace",selectionKeyCode:ne="Shift",selectionOnDrag:z=!1,selectionMode:oe=Es.Full,panActivationKeyCode:le="Space",multiSelectionKeyCode:ae=ps()?"Meta":"Control",zoomActivationKeyCode:X=ps()?"Meta":"Control",snapToGrid:H,snapGrid:re,onlyRenderVisibleElements:ie=!1,selectNodesOnDrag:de,nodesDraggable:se,autoPanOnNodeFocus:ge,nodesConnectable:xe,nodesFocusable:Fe,nodeOrigin:Z=hm,edgesFocusable:Ee,edgesReconnectable:Oe,elementsSelectable:ve=!0,defaultViewport:Le=CB,minZoom:Tt=.5,maxZoom:yt=2,translateExtent:St=us,preventScrolling:Ct=!0,nodeExtent:mn,defaultMarkerColor:an="#b1b1b7",zoomOnScroll:ht=!0,zoomOnPinch:Wt=!0,panOnScroll:Xn=!1,panOnScrollSpeed:Yt=.5,panOnScrollMode:Kn=dr.Free,zoomOnDoubleClick:Lt=!0,panOnDrag:Lr=!0,onPaneClick:_r,onPaneMouseEnter:qn,onPaneMouseMove:br,onPaneMouseLeave:Jn,onPaneScroll:K,onPaneContextMenu:ue,paneClickDistance:Ye=1,nodeClickDistance:Ue=0,children:Co,onReconnect:vr,onReconnectStart:Dr,onReconnectEnd:Lo,onEdgeContextMenu:Mr,onEdgeDoubleClick:ws,onEdgeMouseEnter:Pr,onEdgeMouseMove:_o,onEdgeMouseLeave:_t,reconnectRadius:cl=10,onNodesChange:dl,onEdgesChange:ul,noDragClassName:wr="nodrag",noWheelClassName:Qn="nowheel",noPanClassName:Us="nopan",fitView:bo,fitViewOptions:$t,connectOnClick:El,attributionPosition:Bs,proOptions:Je,defaultEdgeOptions:gn,elevateNodesOnSelect:tE=!0,elevateEdgesOnSelect:Vt=!1,disableKeyboardA11y:js=!1,autoPanOnConnect:Rt,autoPanOnNodeDrag:ks,autoPanSpeed:fl,connectionRadius:pl,isValidConnection:Tl,onError:Sl,style:hl,id:vo,nodeDragThreshold:Rl,connectionDragThreshold:Al,viewport:Fs,onViewportChange:Gs,width:ml,height:gl,colorMode:Il="light",debug:Hs,onScroll:Zn,ariaLabelConfig:Ws,zIndexMode:Do="basic",...Ys},$s){const Ur=vo||"1",Vs=vB(Il),zs=p.useCallback(Mo=>{Mo.currentTarget.scrollTo({top:0,left:0,behavior:"instant"}),Zn==null||Zn(Mo)},[Zn]);return o.jsx("div",{"data-testid":"rf__wrapper",...Ys,onScroll:zs,style:{...hl,...Jj},ref:$s,className:He(["react-flow",s,Vs]),id:vo,role:"application",children:o.jsxs(qj,{nodes:e,edges:t,width:ml,height:gl,fitView:bo,fitViewOptions:$t,minZoom:Tt,maxZoom:yt,nodeOrigin:Z,nodeExtent:mn,zIndexMode:Do,children:[o.jsx(Xj,{onInit:d,onNodeClick:l,onEdgeClick:c,onNodeMouseEnter:g,onNodeMouseMove:m,onNodeMouseLeave:I,onNodeContextMenu:O,onNodeDoubleClick:N,nodeTypes:i,edgeTypes:a,connectionLineType:k,connectionLineStyle:V,connectionLineComponent:ee,connectionLineContainerStyle:Y,selectionKeyCode:ne,selectionOnDrag:z,selectionMode:oe,deleteKeyCode:te,multiSelectionKeyCode:ae,panActivationKeyCode:le,zoomActivationKeyCode:X,onlyRenderVisibleElements:ie,defaultViewport:Le,translateExtent:St,minZoom:Tt,maxZoom:yt,preventScrolling:Ct,zoomOnScroll:ht,zoomOnPinch:Wt,zoomOnDoubleClick:Lt,panOnScroll:Xn,panOnScrollSpeed:Yt,panOnScrollMode:Kn,panOnDrag:Lr,onPaneClick:_r,onPaneMouseEnter:qn,onPaneMouseMove:br,onPaneMouseLeave:Jn,onPaneScroll:K,onPaneContextMenu:ue,paneClickDistance:Ye,nodeClickDistance:Ue,onSelectionContextMenu:U,onSelectionStart:D,onSelectionEnd:y,onReconnect:vr,onReconnectStart:Dr,onReconnectEnd:Lo,onEdgeContextMenu:Mr,onEdgeDoubleClick:ws,onEdgeMouseEnter:Pr,onEdgeMouseMove:_o,onEdgeMouseLeave:_t,reconnectRadius:cl,defaultMarkerColor:an,noDragClassName:wr,noWheelClassName:Qn,noPanClassName:Us,rfId:Ur,disableKeyboardA11y:js,nodeExtent:mn,viewport:Fs,onViewportChange:Gs}),o.jsx(bB,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:T,onConnectStart:A,onConnectEnd:R,onClickConnectStart:S,onClickConnectEnd:h,nodesDraggable:se,autoPanOnNodeFocus:ge,nodesConnectable:xe,nodesFocusable:Fe,edgesFocusable:Ee,edgesReconnectable:Oe,elementsSelectable:ve,elevateNodesOnSelect:tE,elevateEdgesOnSelect:Vt,minZoom:Tt,maxZoom:yt,nodeExtent:mn,onNodesChange:dl,onEdgesChange:ul,snapToGrid:H,snapGrid:re,connectionMode:F,translateExtent:St,connectOnClick:El,defaultEdgeOptions:gn,fitView:bo,fitViewOptions:$t,onNodesDelete:v,onEdgesDelete:b,onDelete:P,onNodeDragStart:x,onNodeDrag:_,onNodeDragStop:C,onSelectionDrag:B,onSelectionDragStart:L,onSelectionDragStop:M,onMove:u,onMoveStart:E,onMoveEnd:f,noPanClassName:Us,nodeOrigin:Z,rfId:Ur,autoPanOnConnect:Rt,autoPanOnNodeDrag:ks,autoPanSpeed:fl,onError:Sl,connectionRadius:pl,isValidConnection:Tl,selectNodesOnDrag:de,nodeDragThreshold:Rl,connectionDragThreshold:Al,onBeforeDelete:w,debug:Hs,ariaLabelConfig:Ws,zIndexMode:Do}),o.jsx(yB,{onSelectionChange:j}),Co,o.jsx(gB,{proOptions:Je,position:Bs}),o.jsx(mB,{rfId:Ur,disableKeyboardA11y:js})]})})}var Vm=gm(Qj);function zm(e){const[t,n]=p.useState(e),r=p.useCallback(s=>n(i=>Am(s,i)),[]);return[t,n,r]}function Xm(e){const[t,n]=p.useState(e),r=p.useCallback(s=>n(i=>mm(s,i)),[]);return[t,n,r]}function Zj({dimensions:e,lineWidth:t,variant:n,className:r}){return o.jsx("path",{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:He(["react-flow__background-pattern",n,r])})}function ek({radius:e,className:t}){return o.jsx("circle",{cx:e,cy:e,r:e,className:He(["react-flow__background-pattern","dots",t])})}var wn;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(wn||(wn={}));const tk={[wn.Dots]:1,[wn.Lines]:1,[wn.Cross]:6},nk=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function Km({id:e,variant:t=wn.Dots,gap:n=20,size:r,lineWidth:s=1,offset:i=0,color:a,bgColor:l,style:c,className:d,patternClassName:u}){const E=p.useRef(null),{transform:f,patternId:T}=Ne(nk,Me),A=r||tk[t],R=t===wn.Dots,S=t===wn.Cross,h=Array.isArray(n)?n:[n,n],g=[h[0]*f[2]||1,h[1]*f[2]||1],m=A*f[2],I=Array.isArray(i)?i:[i,i],O=S?[m,m]:g,N=[I[0]*f[2]||1+O[0]/2,I[1]*f[2]||1+O[1]/2],x=`${T}${e||""}`;return o.jsxs("svg",{className:He(["react-flow__background",d]),style:{...c,...ol,"--xy-background-color-props":l,"--xy-background-pattern-color-props":a},ref:E,"data-testid":"rf__background",children:[o.jsx("pattern",{id:x,x:f[0]%g[0],y:f[1]%g[1],width:g[0],height:g[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${N[0]},-${N[1]})`,children:R?o.jsx(ek,{radius:m/2,className:u}):o.jsx(Zj,{dimensions:O,lineWidth:s,variant:t,className:u})}),o.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${x})`})]})}Km.displayName="Background";const qm=p.memo(Km);function rk(){return o.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",children:o.jsx("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"})})}function ok(){return o.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5",children:o.jsx("path",{d:"M0 0h32v4.2H0z"})})}function sk(){return o.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30",children:o.jsx("path",{d:"M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z"})})}function ik(){return o.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:o.jsx("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z"})})}function ak(){return o.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:o.jsx("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z"})})}function hi({children:e,className:t,...n}){return o.jsx("button",{type:"button",className:He(["react-flow__controls-button",t]),...n,children:e})}const lk=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function Jm({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:s,onZoomIn:i,onZoomOut:a,onFitView:l,onInteractiveChange:c,className:d,children:u,position:E="bottom-left",orientation:f="vertical","aria-label":T}){const A=we(),{isInteractive:R,minZoomReached:S,maxZoomReached:h,ariaLabelConfig:g}=Ne(lk,Me),{zoomIn:m,zoomOut:I,fitView:O}=rl(),N=()=>{m(),i==null||i()},x=()=>{I(),a==null||a()},_=()=>{O(s),l==null||l()},C=()=>{A.setState({nodesDraggable:!R,nodesConnectable:!R,elementsSelectable:!R}),c==null||c(!R)},v=f==="horizontal"?"horizontal":"vertical";return o.jsxs(ho,{className:He(["react-flow__controls",v,d]),position:E,style:e,"data-testid":"rf__controls","aria-label":T??g["controls.ariaLabel"],children:[t&&o.jsxs(o.Fragment,{children:[o.jsx(hi,{onClick:N,className:"react-flow__controls-zoomin",title:g["controls.zoomIn.ariaLabel"],"aria-label":g["controls.zoomIn.ariaLabel"],disabled:h,children:o.jsx(rk,{})}),o.jsx(hi,{onClick:x,className:"react-flow__controls-zoomout",title:g["controls.zoomOut.ariaLabel"],"aria-label":g["controls.zoomOut.ariaLabel"],disabled:S,children:o.jsx(ok,{})})]}),n&&o.jsx(hi,{className:"react-flow__controls-fitview",onClick:_,title:g["controls.fitView.ariaLabel"],"aria-label":g["controls.fitView.ariaLabel"],children:o.jsx(sk,{})}),r&&o.jsx(hi,{className:"react-flow__controls-interactive",onClick:C,title:g["controls.interactive.ariaLabel"],"aria-label":g["controls.interactive.ariaLabel"],children:R?o.jsx(ak,{}):o.jsx(ik,{})}),u]})}Jm.displayName="Controls";const ck=p.memo(Jm);function dk({id:e,x:t,y:n,width:r,height:s,style:i,color:a,strokeColor:l,strokeWidth:c,className:d,borderRadius:u,shapeRendering:E,selected:f,onClick:T}){const{background:A,backgroundColor:R}=i||{},S=a||A||R;return o.jsx("rect",{className:He(["react-flow__minimap-node",{selected:f},d]),x:t,y:n,rx:u,ry:u,width:r,height:s,style:{fill:S,stroke:l,strokeWidth:c},shapeRendering:E,onClick:T?h=>T(h,e):void 0})}const uk=p.memo(dk),Ek=e=>e.nodes.map(t=>t.id),lc=e=>e instanceof Function?e:()=>e;function fk({nodeStrokeColor:e,nodeColor:t,nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:s,nodeComponent:i=uk,onClick:a}){const l=Ne(Ek,Me),c=lc(t),d=lc(e),u=lc(n),E=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return o.jsx(o.Fragment,{children:l.map(f=>o.jsx(Tk,{id:f,nodeColorFunc:c,nodeStrokeColorFunc:d,nodeClassNameFunc:u,nodeBorderRadius:r,nodeStrokeWidth:s,NodeComponent:i,onClick:a,shapeRendering:E},f))})}function pk({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:r,nodeBorderRadius:s,nodeStrokeWidth:i,shapeRendering:a,NodeComponent:l,onClick:c}){const{node:d,x:u,y:E,width:f,height:T}=Ne(A=>{const R=A.nodeLookup.get(e);if(!R)return{node:void 0,x:0,y:0,width:0,height:0};const S=R.internals.userNode,{x:h,y:g}=R.internals.positionAbsolute,{width:m,height:I}=An(S);return{node:S,x:h,y:g,width:m,height:I}},Me);return!d||d.hidden||!zA(d)?null:o.jsx(l,{x:u,y:E,width:f,height:T,style:d.style,selected:!!d.selected,className:r(d),color:t(d),borderRadius:s,strokeColor:n(d),strokeWidth:i,shapeRendering:a,onClick:c,id:d.id})}const Tk=p.memo(pk);var Sk=p.memo(fk);const hk=200,Rk=150,Ak=e=>!e.hidden,mk=e=>{const t={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]};return{viewBB:t,boundingRect:e.nodeLookup.size>0?VA(vs(e.nodeLookup,{filter:Ak}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}},gk="react-flow__minimap-desc";function Qm({style:e,className:t,nodeStrokeColor:n,nodeColor:r,nodeClassName:s="",nodeBorderRadius:i=5,nodeStrokeWidth:a,nodeComponent:l,bgColor:c,maskColor:d,maskStrokeColor:u,maskStrokeWidth:E,position:f="bottom-right",onClick:T,onNodeClick:A,pannable:R=!1,zoomable:S=!1,ariaLabel:h,inversePan:g,zoomStep:m=1,offsetScale:I=5}){const O=we(),N=p.useRef(null),{boundingRect:x,viewBB:_,rfId:C,panZoom:v,translateExtent:b,flowWidth:P,flowHeight:j,ariaLabelConfig:L}=Ne(mk,Me),B=(e==null?void 0:e.width)??hk,M=(e==null?void 0:e.height)??Rk,U=x.width/B,D=x.height/M,y=Math.max(U,D),w=y*B,F=y*M,k=I*y,V=x.x-(w-x.width)/2-k,ee=x.y-(F-x.height)/2-k,Y=w+k*2,te=F+k*2,ne=`${gk}-${C}`,z=p.useRef(0),oe=p.useRef();z.current=y,p.useEffect(()=>{if(N.current&&v)return oe.current=GU({domNode:N.current,panZoom:v,getTransform:()=>O.getState().transform,getViewScale:()=>z.current}),()=>{var H;(H=oe.current)==null||H.destroy()}},[v]),p.useEffect(()=>{var H;(H=oe.current)==null||H.update({translateExtent:b,width:P,height:j,inversePan:g,pannable:R,zoomStep:m,zoomable:S})},[R,S,g,m,b,P,j]);const le=T?H=>{var de;const[re,ie]=((de=oe.current)==null?void 0:de.pointer(H))||[0,0];T(H,{x:re,y:ie})}:void 0,ae=A?p.useCallback((H,re)=>{const ie=O.getState().nodeLookup.get(re).internals.userNode;A(H,ie)},[]):void 0,X=h??L["minimap.ariaLabel"];return o.jsx(ho,{position:f,style:{...e,"--xy-minimap-background-color-props":typeof c=="string"?c:void 0,"--xy-minimap-mask-background-color-props":typeof d=="string"?d:void 0,"--xy-minimap-mask-stroke-color-props":typeof u=="string"?u:void 0,"--xy-minimap-mask-stroke-width-props":typeof E=="number"?E*y:void 0,"--xy-minimap-node-background-color-props":typeof r=="string"?r:void 0,"--xy-minimap-node-stroke-color-props":typeof n=="string"?n:void 0,"--xy-minimap-node-stroke-width-props":typeof a=="number"?a:void 0},className:He(["react-flow__minimap",t]),"data-testid":"rf__minimap",children:o.jsxs("svg",{width:B,height:M,viewBox:`${V} ${ee} ${Y} ${te}`,className:"react-flow__minimap-svg",role:"img","aria-labelledby":ne,ref:N,onClick:le,children:[X&&o.jsx("title",{id:ne,children:X}),o.jsx(Sk,{onClick:ae,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:i,nodeClassName:s,nodeStrokeWidth:a,nodeComponent:l}),o.jsx("path",{className:"react-flow__minimap-mask",d:`M${V-k},${ee-k}h${Y+k*2}v${te+k*2}h${-Y-k*2}z
|
|
772
|
+
M${_.x},${_.y}h${_.width}v${_.height}h${-_.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}Qm.displayName="MiniMap";const Ik=p.memo(Qm),Ok=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,Nk={[So.Line]:"right",[So.Handle]:"bottom-right"};function xk({nodeId:e,position:t,variant:n=So.Handle,className:r,style:s=void 0,children:i,color:a,minWidth:l=10,minHeight:c=10,maxWidth:d=Number.MAX_VALUE,maxHeight:u=Number.MAX_VALUE,keepAspectRatio:E=!1,resizeDirection:f,autoScale:T=!0,shouldResize:A,onResizeStart:R,onResize:S,onResizeEnd:h}){const g=xm(),m=typeof e=="string"?e:g,I=we(),O=p.useRef(null),N=n===So.Handle,x=Ne(p.useCallback(Ok(N&&T),[N,T]),Me),_=p.useRef(null),C=t??Nk[n];p.useEffect(()=>{if(!(!O.current||!m))return _.current||(_.current=tB({domNode:O.current,nodeId:m,getStoreItems:()=>{const{nodeLookup:b,transform:P,snapGrid:j,snapToGrid:L,nodeOrigin:B,domNode:M}=I.getState();return{nodeLookup:b,transform:P,snapGrid:j,snapToGrid:L,nodeOrigin:B,paneDomNode:M}},onChange:(b,P)=>{const{triggerNodeChanges:j,nodeLookup:L,parentLookup:B,nodeOrigin:M}=I.getState(),U=[],D={x:b.x,y:b.y},y=L.get(m);if(y&&y.expandParent&&y.parentId){const w=y.origin??M,F=b.width??y.measured.width??0,k=b.height??y.measured.height??0,V={id:y.id,parentId:y.parentId,rect:{width:F,height:k,...XA({x:b.x??y.position.x,y:b.y??y.position.y},{width:F,height:k},y.parentId,L,w)}},ee=ku([V],L,B,M);U.push(...ee),D.x=b.x?Math.max(w[0]*F,b.x):void 0,D.y=b.y?Math.max(w[1]*k,b.y):void 0}if(D.x!==void 0&&D.y!==void 0){const w={id:m,type:"position",position:{...D}};U.push(w)}if(b.width!==void 0&&b.height!==void 0){const F={id:m,type:"dimensions",resizing:!0,setAttributes:f?f==="horizontal"?"width":"height":!0,dimensions:{width:b.width,height:b.height}};U.push(F)}for(const w of P){const F={...w,type:"position"};U.push(F)}j(U)},onEnd:({width:b,height:P})=>{const j={id:m,type:"dimensions",resizing:!1,dimensions:{width:b,height:P}};I.getState().triggerNodeChanges([j])}})),_.current.update({controlPosition:C,boundaries:{minWidth:l,minHeight:c,maxWidth:d,maxHeight:u},keepAspectRatio:E,resizeDirection:f,onResizeStart:R,onResize:S,onResizeEnd:h,shouldResize:A}),()=>{var b;(b=_.current)==null||b.destroy()}},[C,l,c,d,u,E,R,S,h,A]);const v=C.split("-");return o.jsx("div",{className:He(["react-flow__resize-control","nodrag",...v,n,r]),ref:O,style:{...s,scale:x,...a&&{[N?"backgroundColor":"borderColor"]:a}},children:i})}p.memo(xk);var Zm=Object.defineProperty,yk=(e,t,n)=>t in e?Zm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ck=(e,t)=>{for(var n in t)Zm(e,n,{get:t[n],enumerable:!0})},Lk=(e,t,n)=>yk(e,t+"",n),eg={};Ck(eg,{Graph:()=>xt,alg:()=>Gu,json:()=>ng,version:()=>vk});var _k=Object.defineProperty,tg=(e,t)=>{for(var n in t)_k(e,n,{get:t[n],enumerable:!0})},xt=class{constructor(e){this._isDirected=!0,this._isMultigraph=!1,this._isCompound=!1,this._nodes={},this._in={},this._preds={},this._out={},this._sucs={},this._edgeObjs={},this._edgeLabels={},this._nodeCount=0,this._edgeCount=0,this._defaultNodeLabelFn=()=>{},this._defaultEdgeLabelFn=()=>{},e&&(this._isDirected="directed"in e?e.directed:!0,this._isMultigraph="multigraph"in e?e.multigraph:!1,this._isCompound="compound"in e?e.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children["\0"]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(e){return this._label=e,this}graph(){return this._label}setDefaultNodeLabel(e){return typeof e!="function"?this._defaultNodeLabelFn=()=>e:this._defaultNodeLabelFn=e,this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){return this.nodes().filter(e=>Object.keys(this._in[e]).length===0)}sinks(){return this.nodes().filter(e=>Object.keys(this._out[e]).length===0)}setNodes(e,t){return e.forEach(n=>{t!==void 0?this.setNode(n,t):this.setNode(n)}),this}setNode(e,t){return e in this._nodes?(arguments.length>1&&(this._nodes[e]=t),this):(this._nodes[e]=arguments.length>1?t:this._defaultNodeLabelFn(e),this._isCompound&&(this._parent[e]="\0",this._children[e]={},this._children["\0"][e]=!0),this._in[e]={},this._preds[e]={},this._out[e]={},this._sucs[e]={},++this._nodeCount,this)}node(e){return this._nodes[e]}hasNode(e){return e in this._nodes}removeNode(e){if(e in this._nodes){let t=n=>this.removeEdge(this._edgeObjs[n]);delete this._nodes[e],this._isCompound&&(this._removeFromParentsChildList(e),delete this._parent[e],this.children(e).forEach(n=>{this.setParent(n)}),delete this._children[e]),Object.keys(this._in[e]).forEach(t),delete this._in[e],delete this._preds[e],Object.keys(this._out[e]).forEach(t),delete this._out[e],delete this._sucs[e],--this._nodeCount}return this}setParent(e,t){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(t===void 0)t="\0";else{t+="";for(let n=t;n!==void 0;n=this.parent(n))if(n===e)throw new Error("Setting "+t+" as parent of "+e+" would create a cycle");this.setNode(t)}return this.setNode(e),this._removeFromParentsChildList(e),this._parent[e]=t,this._children[t][e]=!0,this}parent(e){if(this._isCompound){let t=this._parent[e];if(t!=="\0")return t}}children(e="\0"){if(this._isCompound){let t=this._children[e];if(t)return Object.keys(t)}else{if(e==="\0")return this.nodes();if(this.hasNode(e))return[]}return[]}predecessors(e){let t=this._preds[e];if(t)return Object.keys(t)}successors(e){let t=this._sucs[e];if(t)return Object.keys(t)}neighbors(e){let t=this.predecessors(e);if(t){let n=new Set(t);for(let r of this.successors(e))n.add(r);return Array.from(n.values())}}isLeaf(e){let t;return this.isDirected()?t=this.successors(e):t=this.neighbors(e),t.length===0}filterNodes(e){let t=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});t.setGraph(this.graph()),Object.entries(this._nodes).forEach(([s,i])=>{e(s)&&t.setNode(s,i)}),Object.values(this._edgeObjs).forEach(s=>{t.hasNode(s.v)&&t.hasNode(s.w)&&t.setEdge(s,this.edge(s))});let n={},r=s=>{let i=this.parent(s);return!i||t.hasNode(i)?(n[s]=i??void 0,i??void 0):i in n?n[i]:r(i)};return this._isCompound&&t.nodes().forEach(s=>t.setParent(s,r(s))),t}setDefaultEdgeLabel(e){return typeof e!="function"?this._defaultEdgeLabelFn=()=>e:this._defaultEdgeLabelFn=e,this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(e,t){return e.reduce((n,r)=>(t!==void 0?this.setEdge(n,r,t):this.setEdge(n,r),r)),this}setEdge(e,t,n,r){let s,i,a,l,c=!1;typeof e=="object"&&e!==null&&"v"in e?(s=e.v,i=e.w,a=e.name,arguments.length===2&&(l=t,c=!0)):(s=e,i=t,a=r,arguments.length>2&&(l=n,c=!0)),s=""+s,i=""+i,a!==void 0&&(a=""+a);let d=$o(this._isDirected,s,i,a);if(d in this._edgeLabels)return c&&(this._edgeLabels[d]=l),this;if(a!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(s),this.setNode(i),this._edgeLabels[d]=c?l:this._defaultEdgeLabelFn(s,i,a);let u=bk(this._isDirected,s,i,a);return s=u.v,i=u.w,Object.freeze(u),this._edgeObjs[d]=u,bp(this._preds[i],s),bp(this._sucs[s],i),this._in[i][d]=u,this._out[s][d]=u,this._edgeCount++,this}edge(e,t,n){let r=arguments.length===1?cc(this._isDirected,e):$o(this._isDirected,e,t,n);return this._edgeLabels[r]}edgeAsObj(e,t,n){let r=arguments.length===1?this.edge(e):this.edge(e,t,n);return typeof r!="object"?{label:r}:r}hasEdge(e,t,n){return(arguments.length===1?cc(this._isDirected,e):$o(this._isDirected,e,t,n))in this._edgeLabels}removeEdge(e,t,n){let r=arguments.length===1?cc(this._isDirected,e):$o(this._isDirected,e,t,n),s=this._edgeObjs[r];if(s){let i=s.v,a=s.w;delete this._edgeLabels[r],delete this._edgeObjs[r],vp(this._preds[a],i),vp(this._sucs[i],a),delete this._in[a][r],delete this._out[i][r],this._edgeCount--}return this}inEdges(e,t){return this.isDirected()?this.filterEdges(this._in[e],e,t):this.nodeEdges(e,t)}outEdges(e,t){return this.isDirected()?this.filterEdges(this._out[e],e,t):this.nodeEdges(e,t)}nodeEdges(e,t){if(e in this._nodes)return this.filterEdges({...this._in[e],...this._out[e]},e,t)}_removeFromParentsChildList(e){delete this._children[this._parent[e]][e]}filterEdges(e,t,n){if(!e)return;let r=Object.values(e);return n?r.filter(s=>s.v===t&&s.w===n||s.v===n&&s.w===t):r}};function bp(e,t){e[t]?e[t]++:e[t]=1}function vp(e,t){e[t]!==void 0&&!--e[t]&&delete e[t]}function $o(e,t,n,r){let s=""+t,i=""+n;if(!e&&s>i){let a=s;s=i,i=a}return s+""+i+""+(r===void 0?"\0":r)}function bk(e,t,n,r){let s=""+t,i=""+n;if(!e&&s>i){let l=s;s=i,i=l}let a={v:s,w:i};return r&&(a.name=r),a}function cc(e,t){return $o(e,t.v,t.w,t.name)}var vk="4.0.1",ng={};tg(ng,{read:()=>wk,write:()=>Dk});function Dk(e){let t={options:{directed:e.isDirected(),multigraph:e.isMultigraph(),compound:e.isCompound()},nodes:Mk(e),edges:Pk(e)},n=e.graph();return n!==void 0&&(t.value=structuredClone(n)),t}function Mk(e){return e.nodes().map(t=>{let n=e.node(t),r=e.parent(t),s={v:t};return n!==void 0&&(s.value=n),r!==void 0&&(s.parent=r),s})}function Pk(e){return e.edges().map(t=>{let n=e.edge(t),r={v:t.v,w:t.w};return t.name!==void 0&&(r.name=t.name),n!==void 0&&(r.value=n),r})}function wk(e){let t=new xt(e.options);return e.value!==void 0&&t.setGraph(e.value),e.nodes.forEach(n=>{t.setNode(n.v,n.value),n.parent&&t.setParent(n.v,n.parent)}),e.edges.forEach(n=>{t.setEdge({v:n.v,w:n.w,name:n.name},n.value)}),t}var Gu={};tg(Gu,{CycleException:()=>Ta,bellmanFord:()=>rg,components:()=>jk,dijkstra:()=>pa,dijkstraAll:()=>Gk,findCycles:()=>Hk,floydWarshall:()=>Yk,isAcyclic:()=>Vk,postorder:()=>Xk,preorder:()=>Kk,prim:()=>qk,shortestPaths:()=>Jk,tarjan:()=>sg,topsort:()=>ig});var Uk=()=>1;function rg(e,t,n,r){return Bk(e,String(t),n||Uk,r||function(s){return e.outEdges(s)})}function Bk(e,t,n,r){let s={},i,a=0,l=e.nodes(),c=function(E){let f=n(E);s[E.v].distance+f<s[E.w].distance&&(s[E.w]={distance:s[E.v].distance+f,predecessor:E.v},i=!0)},d=function(){l.forEach(function(E){r(E).forEach(function(f){let T=f.v===E?f.v:f.w,A=T===f.v?f.w:f.v;c({v:T,w:A})})})};l.forEach(function(E){let f=E===t?0:Number.POSITIVE_INFINITY;s[E]={distance:f,predecessor:""}});let u=l.length;for(let E=1;E<u&&(i=!1,a++,d(),!!i);E++);if(a===u-1&&(i=!1,d(),i))throw new Error("The graph contains a negative weight cycle");return s}function jk(e){let t={},n=[],r;function s(i){i in t||(t[i]=!0,r.push(i),e.successors(i).forEach(s),e.predecessors(i).forEach(s))}return e.nodes().forEach(function(i){r=[],s(i),r.length&&n.push(r)}),n}var og=class{constructor(){this._arr=[],this._keyIndices={}}size(){return this._arr.length}keys(){return this._arr.map(e=>e.key)}has(e){return e in this._keyIndices}priority(e){let t=this._keyIndices[e];if(t!==void 0)return this._arr[t].priority}min(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key}add(e,t){let n=this._keyIndices,r=String(e);if(!(r in n)){let s=this._arr,i=s.length;return n[r]=i,s.push({key:r,priority:t}),this._decrease(i),!0}return!1}removeMin(){this._swap(0,this._arr.length-1);let e=this._arr.pop();return delete this._keyIndices[e.key],this._heapify(0),e.key}decrease(e,t){let n=this._keyIndices[e];if(n===void 0)throw new Error(`Key not found: ${e}`);let r=this._arr[n].priority;if(t>r)throw new Error(`New priority is greater than current priority. Key: ${e} Old: ${r} New: ${t}`);this._arr[n].priority=t,this._decrease(n)}_heapify(e){let t=this._arr,n=2*e,r=n+1,s=e;n<t.length&&(s=t[n].priority<t[s].priority?n:s,r<t.length&&(s=t[r].priority<t[s].priority?r:s),s!==e&&(this._swap(e,s),this._heapify(s)))}_decrease(e){let t=this._arr,n=t[e].priority,r;for(;e!==0&&(r=e>>1,!(t[r].priority<n));)this._swap(e,r),e=r}_swap(e,t){let n=this._arr,r=this._keyIndices,s=n[e],i=n[t];n[e]=i,n[t]=s,r[i.key]=e,r[s.key]=t}},kk=()=>1;function pa(e,t,n,r){let s=function(i){return e.outEdges(i)};return Fk(e,String(t),n||kk,r||s)}function Fk(e,t,n,r){let s={},i=new og,a,l,c=function(d){let u=d.v!==a?d.v:d.w,E=s[u],f=n(d),T=l.distance+f;if(f<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+d+" Weight: "+f);T<E.distance&&(E.distance=T,E.predecessor=a,i.decrease(u,T))};for(e.nodes().forEach(function(d){let u=d===t?0:Number.POSITIVE_INFINITY;s[d]={distance:u,predecessor:""},i.add(d,u)});i.size()>0&&(a=i.removeMin(),l=s[a],l.distance!==Number.POSITIVE_INFINITY);)r(a).forEach(c);return s}function Gk(e,t,n){return e.nodes().reduce(function(r,s){return r[s]=pa(e,s,t,n),r},{})}function sg(e){let t=0,n=[],r={},s=[];function i(a){let l=r[a]={onStack:!0,lowlink:t,index:t++};if(n.push(a),e.successors(a).forEach(function(c){c in r?r[c].onStack&&(l.lowlink=Math.min(l.lowlink,r[c].index)):(i(c),l.lowlink=Math.min(l.lowlink,r[c].lowlink))}),l.lowlink===l.index){let c=[],d;do d=n.pop(),r[d].onStack=!1,c.push(d);while(a!==d);s.push(c)}}return e.nodes().forEach(function(a){a in r||i(a)}),s}function Hk(e){return sg(e).filter(function(t){return t.length>1||t.length===1&&e.hasEdge(t[0],t[0])})}var Wk=()=>1;function Yk(e,t,n){return $k(e,t||Wk,n||function(r){return e.outEdges(r)})}function $k(e,t,n){let r={},s=e.nodes();return s.forEach(function(i){r[i]={},r[i][i]={distance:0,predecessor:""},s.forEach(function(a){i!==a&&(r[i][a]={distance:Number.POSITIVE_INFINITY,predecessor:""})}),n(i).forEach(function(a){let l=a.v===i?a.w:a.v,c=t(a);r[i][l]={distance:c,predecessor:i}})}),s.forEach(function(i){let a=r[i];s.forEach(function(l){let c=r[l];s.forEach(function(d){let u=c[i],E=a[d],f=c[d],T=u.distance+E.distance;T<f.distance&&(f.distance=T,f.predecessor=E.predecessor)})})}),r}var Ta=class extends Error{constructor(...e){super(...e)}};function ig(e){let t={},n={},r=[];function s(i){if(i in n)throw new Ta;i in t||(n[i]=!0,t[i]=!0,e.predecessors(i).forEach(s),delete n[i],r.push(i))}if(e.sinks().forEach(s),Object.keys(t).length!==e.nodeCount())throw new Ta;return r}function Vk(e){try{ig(e)}catch(t){if(t instanceof Ta)return!1;throw t}return!0}function zk(e,t,n,r,s){Array.isArray(t)||(t=[t]);let i=(l=>{var c;return(c=e.isDirected()?e.successors(l):e.neighbors(l))!=null?c:[]}),a={};return t.forEach(function(l){if(!e.hasNode(l))throw new Error("Graph does not have node: "+l);s=ag(e,l,n==="post",a,i,r,s)}),s}function ag(e,t,n,r,s,i,a){return t in r||(r[t]=!0,n||(a=i(a,t)),s(t).forEach(function(l){a=ag(e,l,n,r,s,i,a)}),n&&(a=i(a,t))),a}function lg(e,t,n){return zk(e,t,n,function(r,s){return r.push(s),r},[])}function Xk(e,t){return lg(e,t,"post")}function Kk(e,t){return lg(e,t,"pre")}function qk(e,t){let n=new xt,r={},s=new og,i;function a(c){let d=c.v===i?c.w:c.v,u=s.priority(d);if(u!==void 0){let E=t(c);E<u&&(r[d]=i,s.decrease(d,E))}}if(e.nodeCount()===0)return n;e.nodes().forEach(function(c){s.add(c,Number.POSITIVE_INFINITY),n.setNode(c)}),s.decrease(e.nodes()[0],0);let l=!1;for(;s.size()>0;){if(i=s.removeMin(),i in r)n.setEdge(i,r[i]);else{if(l)throw new Error("Input graph is not connected: "+e);l=!0}e.nodeEdges(i).forEach(a)}return n}function Jk(e,t,n,r){return Qk(e,t,n,r??(s=>{let i=e.outEdges(s);return i??[]}))}function Qk(e,t,n,r){if(n===void 0)return pa(e,t,n,r);let s=!1,i=e.nodes();for(let a=0;a<i.length;a++){let l=r(i[a]);for(let c=0;c<l.length;c++){let d=l[c],u=d.v===i[a]?d.v:d.w,E=u===d.v?d.w:d.v;n({v:u,w:E})<0&&(s=!0)}if(s)return rg(e,t,n,r)}return pa(e,t,n,r)}function xo(e,t,n,r){let s=r;for(;e.hasNode(s);)s=Hu(r);return n.dummy=t,e.setNode(s,n),s}function Zk(e){let t=new xt().setGraph(e.graph());return e.nodes().forEach(n=>t.setNode(n,e.node(n))),e.edges().forEach(n=>{let r=t.edge(n.v,n.w)||{weight:0,minlen:1},s=e.edge(n);t.setEdge(n.v,n.w,{weight:r.weight+s.weight,minlen:Math.max(r.minlen,s.minlen)})}),t}function cg(e){let t=new xt({multigraph:e.isMultigraph()}).setGraph(e.graph());return e.nodes().forEach(n=>{e.children(n).length||t.setNode(n,e.node(n))}),e.edges().forEach(n=>{t.setEdge(n,e.edge(n))}),t}function Dp(e,t){let n=e.x,r=e.y,s=t.x-n,i=t.y-r,a=e.width/2,l=e.height/2;if(!s&&!i)throw new Error("Not possible to find intersection inside of the rectangle");let c,d;return Math.abs(i)*a>Math.abs(s)*l?(i<0&&(l=-l),c=l*s/i,d=l):(s<0&&(a=-a),c=a,d=a*i/s),{x:n+c,y:r+d}}function Ps(e){let t=Ss(ug(e)+1).map(()=>[]);return e.nodes().forEach(n=>{let r=e.node(n),s=r.rank;s!==void 0&&(t[s]||(t[s]=[]),t[s][r.order]=n)}),t}function eF(e){let t=e.nodes().map(r=>{let s=e.node(r).rank;return s===void 0?Number.MAX_VALUE:s}),n=Zt(Math.min,t);e.nodes().forEach(r=>{let s=e.node(r);Object.hasOwn(s,"rank")&&(s.rank-=n)})}function tF(e){let t=e.nodes().map(a=>e.node(a).rank).filter(a=>a!==void 0),n=Zt(Math.min,t),r=[];e.nodes().forEach(a=>{let l=e.node(a).rank-n;r[l]||(r[l]=[]),r[l].push(a)});let s=0,i=e.graph().nodeRankFactor;Array.from(r).forEach((a,l)=>{a===void 0&&l%i!==0?--s:a!==void 0&&s&&a.forEach(c=>e.node(c).rank+=s)})}function Mp(e,t,n,r){let s={width:0,height:0};return arguments.length>=4&&(s.rank=n,s.order=r),xo(e,"border",s,t)}function nF(e,t=dg){let n=[];for(let r=0;r<e.length;r+=t){let s=e.slice(r,r+t);n.push(s)}return n}var dg=65535;function Zt(e,t){if(t.length>dg){let n=nF(t);return e(...n.map(r=>e(...r)))}else return e(...t)}function ug(e){let t=e.nodes().map(n=>{let r=e.node(n).rank;return r===void 0?Number.MIN_VALUE:r});return Zt(Math.max,t)}function rF(e,t){let n={lhs:[],rhs:[]};return e.forEach(r=>{t(r)?n.lhs.push(r):n.rhs.push(r)}),n}function Eg(e,t){let n=Date.now();try{return t()}finally{console.log(e+" time: "+(Date.now()-n)+"ms")}}function fg(e,t){return t()}var oF=0;function Hu(e){let t=++oF;return e+(""+t)}function Ss(e,t,n=1){t==null&&(t=e,e=0);let r=i=>i<t;n<0&&(r=i=>t<i);let s=[];for(let i=e;r(i);i+=n)s.push(i);return s}function Sa(e,t){let n={};for(let r of t)e[r]!==void 0&&(n[r]=e[r]);return n}function il(e,t){let n;return typeof t=="string"?n=r=>r[t]:n=t,Object.entries(e).reduce((r,[s,i])=>(r[s]=n(i,s),r),{})}function sF(e,t){return e.reduce((n,r,s)=>(n[r]=t[s],n),{})}var al="\0",iF="3.0.0",aF=class{constructor(){Lk(this,"_sentinel");let e={};e._next=e._prev=e,this._sentinel=e}dequeue(){let e=this._sentinel,t=e._prev;if(t!==e)return Pp(t),t}enqueue(e){let t=this._sentinel;e._prev&&e._next&&Pp(e),e._next=t._next,t._next._prev=e,t._next=e,e._prev=t}toString(){let e=[],t=this._sentinel,n=t._prev;for(;n!==t;)e.push(JSON.stringify(n,lF)),n=n._prev;return"["+e.join(", ")+"]"}};function Pp(e){e._prev._next=e._next,e._next._prev=e._prev,delete e._next,delete e._prev}function lF(e,t){if(e!=="_next"&&e!=="_prev")return t}var cF=aF,dF=()=>1;function uF(e,t){if(e.nodeCount()<=1)return[];let n=fF(e,t||dF);return EF(n.graph,n.buckets,n.zeroIdx).flatMap(r=>e.outEdges(r.v,r.w)||[])}function EF(e,t,n){var r;let s=[],i=t[t.length-1],a=t[0],l;for(;e.nodeCount();){for(;l=a.dequeue();)dc(e,t,n,l);for(;l=i.dequeue();)dc(e,t,n,l);if(e.nodeCount()){for(let c=t.length-2;c>0;--c)if(l=(r=t[c])==null?void 0:r.dequeue(),l){s=s.concat(dc(e,t,n,l,!0)||[]);break}}}return s}function dc(e,t,n,r,s){let i=[],a=s?i:void 0;return(e.inEdges(r.v)||[]).forEach(l=>{let c=e.edge(l),d=e.node(l.v);s&&i.push({v:l.v,w:l.w}),d.out-=c,Ld(t,n,d)}),(e.outEdges(r.v)||[]).forEach(l=>{let c=e.edge(l),d=l.w,u=e.node(d);u.in-=c,Ld(t,n,u)}),e.removeNode(r.v),a}function fF(e,t){let n=new xt,r=0,s=0;e.nodes().forEach(l=>{n.setNode(l,{v:l,in:0,out:0})}),e.edges().forEach(l=>{let c=n.edge(l.v,l.w)||0,d=t(l),u=c+d;n.setEdge(l.v,l.w,u);let E=n.node(l.v),f=n.node(l.w);s=Math.max(s,E.out+=d),r=Math.max(r,f.in+=d)});let i=pF(s+r+3).map(()=>new cF),a=r+1;return n.nodes().forEach(l=>{Ld(i,a,n.node(l))}),{graph:n,buckets:i,zeroIdx:a}}function Ld(e,t,n){var r,s,i;n.out?n.in?(i=e[n.out-n.in+t])==null||i.enqueue(n):(s=e[e.length-1])==null||s.enqueue(n):(r=e[0])==null||r.enqueue(n)}function pF(e){let t=[];for(let n=0;n<e;n++)t.push(n);return t}function TF(e){(e.graph().acyclicer==="greedy"?uF(e,t(e)):SF(e)).forEach(n=>{let r=e.edge(n);e.removeEdge(n),r.forwardName=n.name,r.reversed=!0,e.setEdge(n.w,n.v,r,Hu("rev"))});function t(n){return r=>n.edge(r).weight}}function SF(e){let t=[],n={},r={};function s(i){Object.hasOwn(r,i)||(r[i]=!0,n[i]=!0,e.outEdges(i).forEach(a=>{Object.hasOwn(n,a.w)?t.push(a):s(a.w)}),delete n[i])}return e.nodes().forEach(s),t}function hF(e){e.edges().forEach(t=>{let n=e.edge(t);if(n.reversed){e.removeEdge(t);let r=n.forwardName;delete n.reversed,delete n.forwardName,e.setEdge(t.w,t.v,n,r)}})}function RF(e){e.graph().dummyChains=[],e.edges().forEach(t=>AF(e,t))}function AF(e,t){let n=t.v,r=e.node(n).rank,s=t.w,i=e.node(s).rank,a=t.name,l=e.edge(t),c=l.labelRank;if(i===r+1)return;e.removeEdge(t);let d,u,E;for(E=0,++r;r<i;++E,++r)l.points=[],u={width:0,height:0,edgeLabel:l,edgeObj:t,rank:r},d=xo(e,"edge",u,"_d"),r===c&&(u.width=l.width,u.height=l.height,u.dummy="edge-label",u.labelpos=l.labelpos),e.setEdge(n,d,{weight:l.weight},a),E===0&&e.graph().dummyChains.push(d),n=d;e.setEdge(n,s,{weight:l.weight},a)}function mF(e){e.graph().dummyChains.forEach(t=>{let n=e.node(t),r=n.edgeLabel,s;for(e.setEdge(n.edgeObj,r);n.dummy;)s=e.successors(t)[0],e.removeNode(t),r.points.push({x:n.x,y:n.y}),n.dummy==="edge-label"&&(r.x=n.x,r.y=n.y,r.width=n.width,r.height=n.height),t=s,n=e.node(t)})}function Wu(e){let t={};function n(r){let s=e.node(r);if(Object.hasOwn(t,r))return s.rank;t[r]=!0;let i=e.outEdges(r),a=i?i.map(c=>c==null?Number.POSITIVE_INFINITY:n(c.w)-e.edge(c).minlen):[],l=Zt(Math.min,a);return l===Number.POSITIVE_INFINITY&&(l=0),s.rank=l}e.sources().forEach(n)}function Ro(e,t){return e.node(t.w).rank-e.node(t.v).rank-e.edge(t).minlen}var pg=gF;function gF(e){let t=new xt({directed:!1}),n=e.nodes();if(n.length===0)throw new Error("Graph must have at least one node");let r=n[0],s=e.nodeCount();t.setNode(r,{});let i,a;for(;IF(t,e)<s&&(i=OF(t,e),!!i);)a=t.hasNode(i.v)?Ro(e,i):-Ro(e,i),NF(t,e,a);return t}function IF(e,t){function n(r){let s=t.nodeEdges(r);s&&s.forEach(i=>{let a=i.v,l=r===a?i.w:a;!e.hasNode(l)&&!Ro(t,i)&&(e.setNode(l,{}),e.setEdge(r,l,{}),n(l))})}return e.nodes().forEach(n),e.nodeCount()}function OF(e,t){return t.edges().reduce((n,r)=>{let s=Number.POSITIVE_INFINITY;return e.hasNode(r.v)!==e.hasNode(r.w)&&(s=Ro(t,r)),s<n[0]?[s,r]:n},[Number.POSITIVE_INFINITY,null])[1]}function NF(e,t,n){e.nodes().forEach(r=>t.node(r).rank+=n)}var{preorder:xF,postorder:yF}=Gu,CF=yr;yr.initLowLimValues=$u;yr.initCutValues=Yu;yr.calcCutValue=Tg;yr.leaveEdge=hg;yr.enterEdge=Rg;yr.exchangeEdges=Ag;function yr(e){e=Zk(e),Wu(e);let t=pg(e);$u(t),Yu(t,e);let n,r;for(;n=hg(t);)r=Rg(t,e,n),Ag(t,e,n,r)}function Yu(e,t){let n=yF(e,e.nodes());n=n.slice(0,n.length-1),n.forEach(r=>LF(e,t,r))}function LF(e,t,n){let r=e.node(n).parent,s=e.edge(n,r);s.cutvalue=Tg(e,t,n)}function Tg(e,t,n){let r=e.node(n).parent,s=!0,i=t.edge(n,r),a=0;i||(s=!1,i=t.edge(r,n)),a=i.weight;let l=t.nodeEdges(n);return l&&l.forEach(c=>{let d=c.v===n,u=d?c.w:c.v;if(u!==r){let E=d===s,f=t.edge(c).weight;if(a+=E?f:-f,bF(e,n,u)){let T=e.edge(n,u).cutvalue;a+=E?-T:T}}}),a}function $u(e,t){arguments.length<2&&(t=e.nodes()[0]),Sg(e,{},1,t)}function Sg(e,t,n,r,s){let i=n,a=e.node(r);t[r]=!0;let l=e.neighbors(r);return l&&l.forEach(c=>{Object.hasOwn(t,c)||(n=Sg(e,t,n,c,r))}),a.low=i,a.lim=n++,s?a.parent=s:delete a.parent,n}function hg(e){return e.edges().find(t=>e.edge(t).cutvalue<0)}function Rg(e,t,n){let r=n.v,s=n.w;t.hasEdge(r,s)||(r=n.w,s=n.v);let i=e.node(r),a=e.node(s),l=i,c=!1;return i.lim>a.lim&&(l=a,c=!0),t.edges().filter(d=>c===wp(e,e.node(d.v),l)&&c!==wp(e,e.node(d.w),l)).reduce((d,u)=>Ro(t,u)<Ro(t,d)?u:d)}function Ag(e,t,n,r){let s=n.v,i=n.w;e.removeEdge(s,i),e.setEdge(r.v,r.w,{}),$u(e),Yu(e,t),_F(e,t)}function _F(e,t){let n=e.nodes().find(s=>!e.node(s).parent);if(!n)return;let r=xF(e,[n]);r=r.slice(1),r.forEach(s=>{let i=e.node(s).parent,a=t.edge(s,i),l=!1;a||(a=t.edge(i,s),l=!0),t.node(s).rank=t.node(i).rank+(l?a.minlen:-a.minlen)})}function bF(e,t,n){return e.hasEdge(t,n)}function wp(e,t,n){return n.low<=t.lim&&t.lim<=n.lim}var vF=DF;function DF(e){let t=e.graph().ranker;if(typeof t=="function")return t(e);switch(t){case"network-simplex":Up(e);break;case"tight-tree":PF(e);break;case"longest-path":MF(e);break;case"none":break;default:Up(e)}}var MF=Wu;function PF(e){Wu(e),pg(e)}function Up(e){CF(e)}var wF=UF;function UF(e){let t=jF(e);e.graph().dummyChains.forEach(n=>{let r=e.node(n),s=r.edgeObj,i=BF(e,t,s.v,s.w),a=i.path,l=i.lca,c=0,d=a[c],u=!0;for(;n!==s.w;){if(r=e.node(n),u){for(;(d=a[c])!==l&&e.node(d).maxRank<r.rank;)c++;d===l&&(u=!1)}if(!u){for(;c<a.length-1&&e.node(a[c+1]).minRank<=r.rank;)c++;d=a[c]}d!==void 0&&e.setParent(n,d),n=e.successors(n)[0]}})}function BF(e,t,n,r){let s=[],i=[],a=Math.min(t[n].low,t[r].low),l=Math.max(t[n].lim,t[r].lim),c;c=n;do c=e.parent(c),s.push(c);while(c&&(t[c].low>a||l>t[c].lim));let d=c,u=r;for(;(u=e.parent(u))!==d;)i.push(u);return{path:s.concat(i.reverse()),lca:d}}function jF(e){let t={},n=0;function r(s){let i=n;e.children(s).forEach(r),t[s]={low:i,lim:n++}}return e.children(al).forEach(r),t}function kF(e){let t=xo(e,"root",{},"_root"),n=FF(e),r=Object.values(n),s=Zt(Math.max,r)-1,i=2*s+1;e.graph().nestingRoot=t,e.edges().forEach(l=>e.edge(l).minlen*=i);let a=GF(e)+1;e.children(al).forEach(l=>mg(e,t,i,a,s,n,l)),e.graph().nodeRankFactor=i}function mg(e,t,n,r,s,i,a){var l;let c=e.children(a);if(!c.length){a!==t&&e.setEdge(t,a,{weight:0,minlen:n});return}let d=Mp(e,"_bt"),u=Mp(e,"_bb"),E=e.node(a);e.setParent(d,a),E.borderTop=d,e.setParent(u,a),E.borderBottom=u,c.forEach(f=>{var T;mg(e,t,n,r,s,i,f);let A=e.node(f),R=A.borderTop?A.borderTop:f,S=A.borderBottom?A.borderBottom:f,h=A.borderTop?r:2*r,g=R!==S?1:s-((T=i[a])!=null?T:0)+1;e.setEdge(d,R,{weight:h,minlen:g,nestingEdge:!0}),e.setEdge(S,u,{weight:h,minlen:g,nestingEdge:!0})}),e.parent(a)||e.setEdge(t,d,{weight:0,minlen:s+((l=i[a])!=null?l:0)})}function FF(e){let t={};function n(r,s){let i=e.children(r);i&&i.length&&i.forEach(a=>n(a,s+1)),t[r]=s}return e.children(al).forEach(r=>n(r,1)),t}function GF(e){return e.edges().reduce((t,n)=>t+e.edge(n).weight,0)}function HF(e){let t=e.graph();e.removeNode(t.nestingRoot),delete t.nestingRoot,e.edges().forEach(n=>{e.edge(n).nestingEdge&&e.removeEdge(n)})}var WF=YF;function YF(e){function t(n){let r=e.children(n),s=e.node(n);if(r.length&&r.forEach(t),Object.hasOwn(s,"minRank")){s.borderLeft=[],s.borderRight=[];for(let i=s.minRank,a=s.maxRank+1;i<a;++i)Bp(e,"borderLeft","_bl",n,s,i),Bp(e,"borderRight","_br",n,s,i)}}e.children(al).forEach(t)}function Bp(e,t,n,r,s,i){let a={width:0,height:0,rank:i,borderType:t},l=s[t][i-1],c=xo(e,"border",a,n);s[t][i]=c,e.setParent(c,r),l&&e.setEdge(l,c,{weight:1})}function $F(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="lr"||n==="rl")&&gg(e)}function VF(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="bt"||n==="rl")&&zF(e),(n==="lr"||n==="rl")&&(XF(e),gg(e))}function gg(e){e.nodes().forEach(t=>jp(e.node(t))),e.edges().forEach(t=>jp(e.edge(t)))}function jp(e){let t=e.width;e.width=e.height,e.height=t}function zF(e){e.nodes().forEach(t=>uc(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(uc),Object.hasOwn(r,"y")&&uc(r)})}function uc(e){e.y=-e.y}function XF(e){e.nodes().forEach(t=>Ec(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(Ec),Object.hasOwn(r,"x")&&Ec(r)})}function Ec(e){let t=e.x;e.x=e.y,e.y=t}function KF(e){let t={},n=e.nodes().filter(l=>!e.children(l).length),r=n.map(l=>e.node(l).rank),s=Zt(Math.max,r),i=Ss(s+1).map(()=>[]);function a(l){if(t[l])return;t[l]=!0;let c=e.node(l);i[c.rank].push(l);let d=e.successors(l);d&&d.forEach(a)}return n.sort((l,c)=>e.node(l).rank-e.node(c).rank).forEach(a),i}function qF(e,t){let n=0;for(let r=1;r<t.length;++r)n+=JF(e,t[r-1],t[r]);return n}function JF(e,t,n){let r=sF(n,n.map((d,u)=>u)),s=t.flatMap(d=>{let u=e.outEdges(d);return u?u.map(E=>({pos:r[E.w],weight:e.edge(E).weight})).sort((E,f)=>E.pos-f.pos):[]}),i=1;for(;i<n.length;)i<<=1;let a=2*i-1;i-=1;let l=new Array(a).fill(0),c=0;return s.forEach(d=>{let u=d.pos+i;l[u]+=d.weight;let E=0;for(;u>0;)u%2&&(E+=l[u+1]),u=u-1>>1,l[u]+=d.weight;c+=d.weight*E}),c}function QF(e,t=[]){return t.map(n=>{let r=e.inEdges(n);if(!r||!r.length)return{v:n};{let s=r.reduce((i,a)=>{let l=e.edge(a),c=e.node(a.v);return{sum:i.sum+l.weight*c.order,weight:i.weight+l.weight}},{sum:0,weight:0});return{v:n,barycenter:s.sum/s.weight,weight:s.weight}}})}function ZF(e,t){let n={};e.forEach((s,i)=>{let a={indegree:0,in:[],out:[],vs:[s.v],i};s.barycenter!==void 0&&(a.barycenter=s.barycenter,a.weight=s.weight),n[s.v]=a}),t.edges().forEach(s=>{let i=n[s.v],a=n[s.w];i!==void 0&&a!==void 0&&(a.indegree++,i.out.push(a))});let r=Object.values(n).filter(s=>!s.indegree);return e2(r)}function e2(e){let t=[];function n(s){return i=>{i.merged||(i.barycenter===void 0||s.barycenter===void 0||i.barycenter>=s.barycenter)&&t2(s,i)}}function r(s){return i=>{i.in.push(s),--i.indegree===0&&e.push(i)}}for(;e.length;){let s=e.pop();t.push(s),s.in.reverse().forEach(n(s)),s.out.forEach(r(s))}return t.filter(s=>!s.merged).map(s=>Sa(s,["vs","i","barycenter","weight"]))}function t2(e,t){let n=0,r=0;e.weight&&(n+=e.barycenter*e.weight,r+=e.weight),t.weight&&(n+=t.barycenter*t.weight,r+=t.weight),e.vs=t.vs.concat(e.vs),e.barycenter=n/r,e.weight=r,e.i=Math.min(t.i,e.i),t.merged=!0}function n2(e,t){let n=rF(e,u=>Object.hasOwn(u,"barycenter")),r=n.lhs,s=n.rhs.sort((u,E)=>E.i-u.i),i=[],a=0,l=0,c=0;r.sort(r2(!!t)),c=kp(i,s,c),r.forEach(u=>{c+=u.vs.length,i.push(u.vs),a+=u.barycenter*u.weight,l+=u.weight,c=kp(i,s,c)});let d={vs:i.flat(1)};return l&&(d.barycenter=a/l,d.weight=l),d}function kp(e,t,n){let r;for(;t.length&&(r=t[t.length-1]).i<=n;)t.pop(),e.push(r.vs),n++;return n}function r2(e){return(t,n)=>t.barycenter<n.barycenter?-1:t.barycenter>n.barycenter?1:e?n.i-t.i:t.i-n.i}function Ig(e,t,n,r){let s=e.children(t),i=e.node(t),a=i?i.borderLeft:void 0,l=i?i.borderRight:void 0,c={};a&&(s=s.filter(f=>f!==a&&f!==l));let d=QF(e,s);d.forEach(f=>{if(e.children(f.v).length){let T=Ig(e,f.v,n,r);c[f.v]=T,Object.hasOwn(T,"barycenter")&&s2(f,T)}});let u=ZF(d,n);o2(u,c);let E=n2(u,r);if(a&&l){E.vs=[a,E.vs,l].flat(1);let f=e.predecessors(a);if(f&&f.length){let T=e.node(f[0]),A=e.predecessors(l),R=e.node(A[0]);Object.hasOwn(E,"barycenter")||(E.barycenter=0,E.weight=0),E.barycenter=(E.barycenter*E.weight+T.order+R.order)/(E.weight+2),E.weight+=2}}return E}function o2(e,t){e.forEach(n=>{n.vs=n.vs.flatMap(r=>t[r]?t[r].vs:r)})}function s2(e,t){e.barycenter!==void 0?(e.barycenter=(e.barycenter*e.weight+t.barycenter*t.weight)/(e.weight+t.weight),e.weight+=t.weight):(e.barycenter=t.barycenter,e.weight=t.weight)}function i2(e,t,n,r){r||(r=e.nodes());let s=a2(e),i=new xt({compound:!0}).setGraph({root:s}).setDefaultNodeLabel(a=>e.node(a));return r.forEach(a=>{let l=e.node(a),c=e.parent(a);if(l.rank===t||l.minRank<=t&&t<=l.maxRank){i.setNode(a),i.setParent(a,c||s);let d=e[n](a);d&&d.forEach(u=>{let E=u.v===a?u.w:u.v,f=i.edge(E,a),T=f!==void 0?f.weight:0;i.setEdge(E,a,{weight:e.edge(u).weight+T})}),Object.hasOwn(l,"minRank")&&i.setNode(a,{borderLeft:l.borderLeft[t],borderRight:l.borderRight[t]})}}),i}function a2(e){let t;for(;e.hasNode(t=Hu("_root")););return t}function l2(e,t,n){let r={},s;n.forEach(i=>{let a=e.parent(i),l,c;for(;a;){if(l=e.parent(a),l?(c=r[l],r[l]=a):(c=s,s=a),c&&c!==a){t.setEdge(c,a);return}a=l}})}function Og(e,t={}){if(typeof t.customOrder=="function"){t.customOrder(e,Og);return}let n=ug(e),r=Fp(e,Ss(1,n+1),"inEdges"),s=Fp(e,Ss(n-1,-1,-1),"outEdges"),i=KF(e);if(Gp(e,i),t.disableOptimalOrderHeuristic)return;let a=Number.POSITIVE_INFINITY,l,c=t.constraints||[];for(let d=0,u=0;u<4;++d,++u){c2(d%2?r:s,d%4>=2,c),i=Ps(e);let E=qF(e,i);E<a?(u=0,l=Object.assign({},i),a=E):E===a&&(l=structuredClone(i))}Gp(e,l)}function Fp(e,t,n){let r=new Map,s=(i,a)=>{r.has(i)||r.set(i,[]),r.get(i).push(a)};for(let i of e.nodes()){let a=e.node(i);if(typeof a.rank=="number"&&s(a.rank,i),typeof a.minRank=="number"&&typeof a.maxRank=="number")for(let l=a.minRank;l<=a.maxRank;l++)l!==a.rank&&s(l,i)}return t.map(function(i){return i2(e,i,n,r.get(i)||[])})}function c2(e,t,n){let r=new xt;e.forEach(function(s){n.forEach(l=>r.setEdge(l.left,l.right));let i=s.graph().root,a=Ig(s,i,r,t);a.vs.forEach((l,c)=>s.node(l).order=c),l2(s,r,a.vs)})}function Gp(e,t){Object.values(t).forEach(n=>n.forEach((r,s)=>e.node(r).order=s))}function d2(e,t){let n={};function r(s,i){let a=0,l=0,c=s.length,d=i[i.length-1];return i.forEach((u,E)=>{let f=E2(e,u),T=f?e.node(f).order:c;(f||u===d)&&(i.slice(l,E+1).forEach(A=>{let R=e.predecessors(A);R&&R.forEach(S=>{let h=e.node(S),g=h.order;(g<a||T<g)&&!(h.dummy&&e.node(A).dummy)&&Ng(n,S,A)})}),l=E+1,a=T)}),i}return t.length&&t.reduce(r),n}function u2(e,t){let n={};function r(i,a,l,c,d){Ss(a,l).forEach(u=>{let E=i[u];if(E!==void 0&&e.node(E).dummy){let f=e.predecessors(E);f&&f.forEach(T=>{if(T===void 0)return;let A=e.node(T);A.dummy&&(A.order<c||A.order>d)&&Ng(n,T,E)})}})}function s(i,a){let l=-1,c=-1,d=0;return a.forEach((u,E)=>{if(e.node(u).dummy==="border"){let f=e.predecessors(u);if(f&&f.length){let T=f[0];if(T===void 0)return;c=e.node(T).order,r(a,d,E,l,c),d=E,l=c}}r(a,d,a.length,c,i.length)}),a}return t.length&&t.reduce(s),n}function E2(e,t){if(e.node(t).dummy){let n=e.predecessors(t);if(n)return n.find(r=>e.node(r).dummy)}}function Ng(e,t,n){if(t>n){let s=t;t=n,n=s}let r=e[t];r||(e[t]=r={}),r[n]=!0}function f2(e,t,n){if(t>n){let s=t;t=n,n=s}let r=e[t];return r!==void 0&&Object.hasOwn(r,n)}function p2(e,t,n,r){let s={},i={},a={};return t.forEach(l=>{l.forEach((c,d)=>{s[c]=c,i[c]=c,a[c]=d})}),t.forEach(l=>{let c=-1;l.forEach(d=>{let u=r(d);if(u&&u.length){let E=u.sort((T,A)=>{let R=a[T],S=a[A];return(R!==void 0?R:0)-(S!==void 0?S:0)}),f=(E.length-1)/2;for(let T=Math.floor(f),A=Math.ceil(f);T<=A;++T){let R=E[T];if(R===void 0)continue;let S=a[R];if(S!==void 0&&i[d]===d&&c<S&&!f2(n,d,R)){let h=s[R];h!==void 0&&(i[R]=d,i[d]=s[d]=h,c=S)}}}})}),{root:s,align:i}}function T2(e,t,n,r,s=!1){let i={},a=S2(e,t,n,s),l=s?"borderLeft":"borderRight";function c(T,A){let R=a.nodes().slice(),S={},h=R.pop();for(;h;){if(S[h])T(h);else{S[h]=!0,R.push(h);for(let g of A(h))R.push(g)}h=R.pop()}}function d(T){let A=a.inEdges(T);A?i[T]=A.reduce((R,S)=>{var h;let g=(h=i[S.v])!=null?h:0,m=a.edge(S);return Math.max(R,g+(m!==void 0?m:0))},0):i[T]=0}function u(T){let A=a.outEdges(T),R=Number.POSITIVE_INFINITY;A&&(R=A.reduce((h,g)=>{let m=i[g.w],I=a.edge(g);return Math.min(h,(m!==void 0?m:0)-(I!==void 0?I:0))},Number.POSITIVE_INFINITY));let S=e.node(T);R!==Number.POSITIVE_INFINITY&&S.borderType!==l&&(i[T]=Math.max(i[T]!==void 0?i[T]:0,R))}function E(T){return a.predecessors(T)||[]}function f(T){return a.successors(T)||[]}return c(d,E),c(u,f),Object.keys(r).forEach(T=>{var A;let R=n[T];R!==void 0&&(i[T]=(A=i[R])!=null?A:0)}),i}function S2(e,t,n,r){let s=new xt,i=e.graph(),a=g2(i.nodesep,i.edgesep,r);return t.forEach(l=>{let c;l.forEach(d=>{let u=n[d];if(u!==void 0){if(s.setNode(u),c!==void 0){let E=n[c];if(E!==void 0){let f=s.edge(E,u);s.setEdge(E,u,Math.max(a(e,d,c),f||0))}}c=d}})}),s}function h2(e,t){return Object.values(t).reduce((n,r)=>{let s=Number.NEGATIVE_INFINITY,i=Number.POSITIVE_INFINITY;Object.entries(r).forEach(([l,c])=>{let d=I2(e,l)/2;s=Math.max(c+d,s),i=Math.min(c-d,i)});let a=s-i;return a<n[0]&&(n=[a,r]),n},[Number.POSITIVE_INFINITY,null])[1]}function R2(e,t){let n=Object.values(t),r=Zt(Math.min,n),s=Zt(Math.max,n);["u","d"].forEach(i=>{["l","r"].forEach(a=>{let l=i+a,c=e[l];if(!c||c===t)return;let d=Object.values(c),u=r-Zt(Math.min,d);a!=="l"&&(u=s-Zt(Math.max,d)),u&&(e[l]=il(c,E=>E+u))})})}function A2(e,t=void 0){let n=e.ul;return n?il(n,(r,s)=>{var i,a;if(t){let c=t.toLowerCase(),d=e[c];if(d&&d[s]!==void 0)return d[s]}let l=Object.values(e).map(c=>{let d=c[s];return d!==void 0?d:0}).sort((c,d)=>c-d);return(((i=l[1])!=null?i:0)+((a=l[2])!=null?a:0))/2}):{}}function m2(e){let t=Ps(e),n=Object.assign(d2(e,t),u2(e,t)),r={},s;["u","d"].forEach(a=>{s=a==="u"?t:Object.values(t).reverse(),["l","r"].forEach(l=>{l==="r"&&(s=s.map(u=>Object.values(u).reverse()));let c=p2(e,s,n,u=>(a==="u"?e.predecessors(u):e.successors(u))||[]),d=T2(e,s,c.root,c.align,l==="r");l==="r"&&(d=il(d,u=>-u)),r[a+l]=d})});let i=h2(e,r);return R2(r,i),A2(r,e.graph().align)}function g2(e,t,n){return(r,s,i)=>{let a=r.node(s),l=r.node(i),c=0,d;if(c+=a.width/2,Object.hasOwn(a,"labelpos"))switch(a.labelpos.toLowerCase()){case"l":d=-a.width/2;break;case"r":d=a.width/2;break}if(d&&(c+=n?d:-d),d=void 0,c+=(a.dummy?t:e)/2,c+=(l.dummy?t:e)/2,c+=l.width/2,Object.hasOwn(l,"labelpos"))switch(l.labelpos.toLowerCase()){case"l":d=l.width/2;break;case"r":d=-l.width/2;break}return d&&(c+=n?d:-d),c}}function I2(e,t){return e.node(t).width}function O2(e){e=cg(e),N2(e),Object.entries(m2(e)).forEach(([t,n])=>e.node(t).x=n)}function N2(e){let t=Ps(e),n=e.graph(),r=n.ranksep,s=n.rankalign,i=0;t.forEach(a=>{let l=a.reduce((c,d)=>{var u;let E=(u=e.node(d).height)!=null?u:0;return c>E?c:E},0);a.forEach(c=>{let d=e.node(c);s==="top"?d.y=i+d.height/2:s==="bottom"?d.y=i+l-d.height/2:d.y=i+l/2}),i+=l+r})}function x2(e,t={}){let n=t.debugTiming?Eg:fg;return n("layout",()=>{let r=n(" buildLayoutGraph",()=>w2(e));return n(" runLayout",()=>y2(r,n,t)),n(" updateInputGraph",()=>C2(e,r)),r})}function y2(e,t,n){t(" makeSpaceForEdgeLabels",()=>U2(e)),t(" removeSelfEdges",()=>$2(e)),t(" acyclic",()=>TF(e)),t(" nestingGraph.run",()=>kF(e)),t(" rank",()=>vF(cg(e))),t(" injectEdgeLabelProxies",()=>B2(e)),t(" removeEmptyRanks",()=>tF(e)),t(" nestingGraph.cleanup",()=>HF(e)),t(" normalizeRanks",()=>eF(e)),t(" assignRankMinMax",()=>j2(e)),t(" removeEdgeLabelProxies",()=>k2(e)),t(" normalize.run",()=>RF(e)),t(" parentDummyChains",()=>wF(e)),t(" addBorderSegments",()=>WF(e)),t(" order",()=>Og(e,n)),t(" insertSelfEdges",()=>V2(e)),t(" adjustCoordinateSystem",()=>$F(e)),t(" position",()=>O2(e)),t(" positionSelfEdges",()=>z2(e)),t(" removeBorderNodes",()=>Y2(e)),t(" normalize.undo",()=>mF(e)),t(" fixupEdgeLabelCoords",()=>H2(e)),t(" undoCoordinateSystem",()=>VF(e)),t(" translateGraph",()=>F2(e)),t(" assignNodeIntersects",()=>G2(e)),t(" reversePoints",()=>W2(e)),t(" acyclic.undo",()=>hF(e))}function C2(e,t){e.nodes().forEach(n=>{let r=e.node(n),s=t.node(n);r&&(r.x=s.x,r.y=s.y,r.order=s.order,r.rank=s.rank,t.children(n).length&&(r.width=s.width,r.height=s.height))}),e.edges().forEach(n=>{let r=e.edge(n),s=t.edge(n);r.points=s.points,Object.hasOwn(s,"x")&&(r.x=s.x,r.y=s.y)}),e.graph().width=t.graph().width,e.graph().height=t.graph().height}var L2=["nodesep","edgesep","ranksep","marginx","marginy"],_2={ranksep:50,edgesep:20,nodesep:50,rankdir:"TB",rankalign:"center"},b2=["acyclicer","ranker","rankdir","align","rankalign"],v2=["width","height","rank"],Hp={width:0,height:0},D2=["minlen","weight","width","height","labeloffset"],M2={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},P2=["labelpos"];function w2(e){let t=new xt({multigraph:!0,compound:!0}),n=pc(e.graph());return t.setGraph(Object.assign({},_2,fc(n,L2),Sa(n,b2))),e.nodes().forEach(r=>{let s=pc(e.node(r)),i=fc(s,v2);Object.keys(Hp).forEach(l=>{i[l]===void 0&&(i[l]=Hp[l])}),t.setNode(r,i);let a=e.parent(r);a!==void 0&&t.setParent(r,a)}),e.edges().forEach(r=>{let s=pc(e.edge(r));t.setEdge(r,Object.assign({},M2,fc(s,D2),Sa(s,P2)))}),t}function U2(e){let t=e.graph();t.ranksep/=2,e.edges().forEach(n=>{let r=e.edge(n);r.minlen*=2,r.labelpos.toLowerCase()!=="c"&&(t.rankdir==="TB"||t.rankdir==="BT"?r.width+=r.labeloffset:r.height+=r.labeloffset)})}function B2(e){e.edges().forEach(t=>{let n=e.edge(t);if(n.width&&n.height){let r=e.node(t.v),s={rank:(e.node(t.w).rank-r.rank)/2+r.rank,e:t};xo(e,"edge-proxy",s,"_ep")}})}function j2(e){let t=0;e.nodes().forEach(n=>{let r=e.node(n);r.borderTop&&(r.minRank=e.node(r.borderTop).rank,r.maxRank=e.node(r.borderBottom).rank,t=Math.max(t,r.maxRank))}),e.graph().maxRank=t}function k2(e){e.nodes().forEach(t=>{let n=e.node(t);if(n.dummy==="edge-proxy"){let r=n;e.edge(r.e).labelRank=n.rank,e.removeNode(t)}})}function F2(e){let t=Number.POSITIVE_INFINITY,n=0,r=Number.POSITIVE_INFINITY,s=0,i=e.graph(),a=i.marginx||0,l=i.marginy||0;function c(d){let u=d.x,E=d.y,f=d.width,T=d.height;t=Math.min(t,u-f/2),n=Math.max(n,u+f/2),r=Math.min(r,E-T/2),s=Math.max(s,E+T/2)}e.nodes().forEach(d=>c(e.node(d))),e.edges().forEach(d=>{let u=e.edge(d);Object.hasOwn(u,"x")&&c(u)}),t-=a,r-=l,e.nodes().forEach(d=>{let u=e.node(d);u.x-=t,u.y-=r}),e.edges().forEach(d=>{let u=e.edge(d);u.points.forEach(E=>{E.x-=t,E.y-=r}),Object.hasOwn(u,"x")&&(u.x-=t),Object.hasOwn(u,"y")&&(u.y-=r)}),i.width=n-t+a,i.height=s-r+l}function G2(e){e.edges().forEach(t=>{let n=e.edge(t),r=e.node(t.v),s=e.node(t.w),i,a;n.points?(i=n.points[0],a=n.points[n.points.length-1]):(n.points=[],i=s,a=r),n.points.unshift(Dp(r,i)),n.points.push(Dp(s,a))})}function H2(e){e.edges().forEach(t=>{let n=e.edge(t);if(Object.hasOwn(n,"x"))switch((n.labelpos==="l"||n.labelpos==="r")&&(n.width-=n.labeloffset),n.labelpos){case"l":n.x-=n.width/2+n.labeloffset;break;case"r":n.x+=n.width/2+n.labeloffset;break}})}function W2(e){e.edges().forEach(t=>{let n=e.edge(t);n.reversed&&n.points.reverse()})}function Y2(e){e.nodes().forEach(t=>{if(e.children(t).length){let n=e.node(t),r=e.node(n.borderTop),s=e.node(n.borderBottom),i=e.node(n.borderLeft[n.borderLeft.length-1]),a=e.node(n.borderRight[n.borderRight.length-1]);n.width=Math.abs(a.x-i.x),n.height=Math.abs(s.y-r.y),n.x=i.x+n.width/2,n.y=r.y+n.height/2}}),e.nodes().forEach(t=>{e.node(t).dummy==="border"&&e.removeNode(t)})}function $2(e){e.edges().forEach(t=>{if(t.v===t.w){let n=e.node(t.v);n.selfEdges||(n.selfEdges=[]),n.selfEdges.push({e:t,label:e.edge(t)}),e.removeEdge(t)}})}function V2(e){Ps(e).forEach(t=>{let n=0;t.forEach((r,s)=>{let i=e.node(r);i.order=s+n,(i.selfEdges||[]).forEach(a=>{xo(e,"selfedge",{width:a.label.width,height:a.label.height,rank:i.rank,order:s+ ++n,e:a.e,label:a.label},"_se")}),delete i.selfEdges})})}function z2(e){e.nodes().forEach(t=>{let n=e.node(t);if(n.dummy==="selfedge"){let r=n,s=e.node(r.e.v),i=s.x+s.width/2,a=s.y,l=n.x-i,c=s.height/2;e.setEdge(r.e,r.label),e.removeNode(t),r.label.points=[{x:i+2*l/3,y:a-c},{x:i+5*l/6,y:a-c},{x:i+l,y:a},{x:i+5*l/6,y:a+c},{x:i+2*l/3,y:a+c}],r.label.x=n.x,r.label.y=n.y}})}function fc(e,t){return il(Sa(e,t),Number)}function pc(e){let t={};return e&&Object.entries(e).forEach(([n,r])=>{typeof n=="string"&&(n=n.toLowerCase()),t[n]=r}),t}function X2(e){let t=Ps(e),n=new xt({compound:!0,multigraph:!0}).setGraph({});return e.nodes().forEach(r=>{n.setNode(r,{label:r}),n.setParent(r,"layer"+e.node(r).rank)}),e.edges().forEach(r=>n.setEdge(r.v,r.w,{},r.name)),t.forEach((r,s)=>{let i="layer"+s;n.setNode(i,{rank:"same"}),r.reduce((a,l)=>(n.setEdge(a,l,{style:"invis"}),l))}),n}var K2={graphlib:eg,version:iF,layout:x2,debug:X2,util:{time:Eg,notime:fg}},ha=K2;/*! For license information please see dagre.esm.js.LEGAL.txt */function q2(e,t,n={}){var s;if(e.length===0)return e;const r=new ha.graphlib.Graph().setDefaultEdgeLabel(()=>({}));r.setGraph({rankdir:"LR",ranksep:60,nodesep:30,marginx:20,marginy:20});for(const i of e){const a={width:170,height:52};if(n.mode==="layered"&&((s=i.data)!=null&&s.layer)){const l=Ji.indexOf(i.data.layer);l>=0&&(a.rank=l)}r.setNode(i.id,a)}for(const i of t)r.setEdge(i.source,i.target);return ha.layout(r),e.map(i=>{const a=r.node(i.id);return{...i,position:{x:a.x-85,y:a.y-26}}})}function J2({data:e,selected:t}){const n=e.nodeType,r=e.isFocal,s=ze[n]??"var(--color-text-tertiary)",i=Fa[n]??n.toUpperCase();return o.jsxs("div",{style:{minWidth:140,maxWidth:190,background:"var(--color-bg-card)",border:`2px solid ${r||t?"var(--color-accent-blue)":s}`,borderRadius:8,padding:"6px 8px",boxShadow:r?"0 0 0 2px color-mix(in srgb, var(--color-accent-blue) 25%, transparent)":"none"},children:[o.jsx(Gn,{type:"target",position:pe.Left,style:{width:6,height:6,background:s,border:"none"}}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginBottom:2},children:[o.jsx("span",{style:{fontSize:8,fontWeight:700,letterSpacing:"0.04em",color:"var(--color-bg-card)",background:s,borderRadius:3,padding:"1px 4px"},children:i}),e.domain&&o.jsx("span",{style:{color:"var(--color-text-tertiary)",fontSize:9},children:e.domain})]}),o.jsx("div",{style:{color:"var(--color-text-primary)",fontSize:10,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.label,children:e.label}),o.jsx(Gn,{type:"source",position:pe.Right,style:{width:6,height:6,background:s,border:"none"}})]})}const Q2={miniDagNode:J2};function Z2({nodes:e,edges:t,focalNodeId:n,height:r=250,onNodeClick:s,interactive:i=!0,layoutMode:a="flow"}){const[l,c,d]=zm([]),[u,E,f]=Xm([]),{fitView:T}=rl(),A=p.useRef(null);return p.useEffect(()=>{const R=e.map(h=>({id:h.id,type:"miniDagNode",position:{x:0,y:0},data:{label:h.name,nodeType:h.type,domain:h.domain,layer:uu(h),isFocal:h.id===n}})),S=t.map((h,g)=>({id:`mini-edge-${g}-${h.source}-${h.target}`,source:h.source,target:h.target,style:{stroke:zo[h.type]??"#8b949e",strokeWidth:1.4},markerEnd:{type:Eo.ArrowClosed,color:zo[h.type]??"#8b949e",width:10,height:10}}));c(q2(R,S,{mode:a})),E(S),requestAnimationFrame(()=>{T({padding:.15,duration:200})})},[e,t,n,a,c,E,T]),p.useEffect(()=>{if(!A.current)return;const R=A.current,S=new ResizeObserver(()=>{T({padding:.15,duration:0})});return S.observe(R),()=>S.disconnect()},[T]),e.length===0?o.jsx("div",{style:{height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--color-text-tertiary)",fontSize:11},children:"No lineage nodes to display"}):o.jsx("div",{ref:A,style:{height:r,width:"100%",borderRadius:8,overflow:"hidden",border:"1px solid var(--color-border-subtle)"},children:o.jsx(Vm,{nodes:l,edges:u,onNodesChange:i?d:void 0,onEdgesChange:i?f:void 0,onNodeClick:s?(R,S)=>s(S.id):void 0,nodeTypes:Q2,fitView:!0,fitViewOptions:{padding:.15},minZoom:.25,proOptions:{hideAttribution:!0},nodesDraggable:i,nodesConnectable:!1,zoomOnScroll:i,panOnDrag:i,style:{background:"var(--color-bg-sunken)"},children:o.jsx(qm,{color:"var(--color-border-subtle)",gap:20,size:1})})})}function Vu(e){return o.jsx($m,{children:o.jsx(Z2,{...e})})}function eG(e){const t=e.match(/^\s*block\s+"([^"]+)"/i);return t?t[1]:null}function tG(e){const t=[],n=/\b(?:FROM|JOIN)\s+([a-zA-Z_][\w.]*)/gi;for(const s of e.matchAll(n)){const i=s[1].toLowerCase();["select","where","group","order","having","limit","union","lateral"].includes(i)||t.push(i)}const r=/\bref\s*\(\s*"([^"]+)"\s*\)/gi;for(const s of e.matchAll(r))t.push(s[1]);return[...new Set(t)]}function nG(e){const t=[],n=[];for(const r of e.matchAll(/@metric\s*\(\s*([^)]+)\s*\)/gi))t.push(r[1].replace(/['"]/g,"").trim());for(const r of e.matchAll(/@dim\s*\(\s*([^)]+)\s*\)/gi))n.push(r[1].replace(/['"]/g,"").trim());return{metrics:t,dimensions:n}}function rG({cellContent:e,cellType:t,cellName:n,themeMode:r,t:s,onFocusNode:i}){const[a,l]=p.useState(!1),[c,d]=p.useState(380),u=p.useRef(c);u.current=c;const[E,f]=p.useState(!1),[T,A]=p.useState(!1),[R,S]=p.useState([]),[h,g]=p.useState([]),[m,I]=p.useState(),[O,N]=p.useState([]),[x,_]=p.useState({metrics:[],dimensions:[]}),[C,v]=p.useState(null),[b,P]=p.useState(null),L=(t==="dql"?eG(e):null)||n,B=p.useCallback(async()=>{if(!(!L&&t!=="sql")){A(!0),P(null);try{const U=tG(e);if(N(U),_(nG(e)),L){const D=`block:${L}`;I(D);const[y,w]=await Promise.all([$.queryLineage({focus:D,upstreamDepth:2,downstreamDepth:2}),$.fetchLineagePaths(D)]);y!=null&&y.graph&&(S(y.graph.nodes??[]),g(y.graph.edges??[])),w&&v(w)}else{I(void 0);const y=((await $.fetchLineage()).nodes??[]).filter(w=>U.some(F=>w.name===F||w.id===`table:${F}`));S(y),g([])}}catch{P("Failed to load lineage")}finally{A(!1)}}},[L,e,t]);p.useEffect(()=>{a&&B()},[a,B]);const M=O.length>0||x.metrics.length>0||x.dimensions.length>0;return e.trim()?o.jsxs("div",{style:{borderTop:`1px solid ${s.cellBorder}`},children:[o.jsxs("button",{onClick:()=>l(U=>!U),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 12px",background:a?`${s.tableHeaderBg}60`:"transparent",border:"none",cursor:"pointer",color:s.textMuted,fontSize:10,fontFamily:s.font,transition:"background 0.15s"},children:[o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",style:{flexShrink:0},children:[o.jsx("circle",{cx:"4",cy:"4",r:"2"}),o.jsx("circle",{cx:"12",cy:"8",r:"2"}),o.jsx("circle",{cx:"4",cy:"12",r:"2"}),o.jsx("line",{x1:"6",y1:"4",x2:"10",y2:"8"}),o.jsx("line",{x1:"6",y1:"12",x2:"10",y2:"8"})]}),o.jsx("span",{children:"Lineage"}),o.jsx("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:a?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.15s"},children:o.jsx("path",{d:"M1 3l4 4 4-4",stroke:"currentColor",fill:"none",strokeWidth:"1.5"})}),a&&L&&i&&o.jsx("span",{onClick:U=>{U.stopPropagation(),i(`block:${L}`)},style:{marginLeft:"auto",fontSize:9,color:s.accent,cursor:"pointer",textDecoration:"underline"},children:"View in DAG"})]}),a&&o.jsx("div",{style:{fontSize:11},children:T?o.jsx("div",{style:{color:s.textMuted,padding:"8px 12px"},children:"Loading lineage..."}):b?o.jsx("div",{style:{color:s.error,padding:"8px 12px"},children:b}):o.jsxs(o.Fragment,{children:[R.length>0&&m&&o.jsxs("div",{style:{borderBottom:`1px solid ${s.cellBorder}`,position:"relative"},children:[o.jsx(Vu,{nodes:R,edges:h,focalNodeId:m,height:c,onNodeClick:i,interactive:!0,layoutMode:"flow"}),o.jsx("div",{onMouseDown:U=>{U.preventDefault();const D=U.clientY,y=u.current;f(!0);const w=k=>{const V=Math.min(800,Math.max(160,y+(k.clientY-D)));u.current=V,d(V)},F=()=>{f(!1),window.removeEventListener("mousemove",w),window.removeEventListener("mouseup",F)};window.addEventListener("mousemove",w),window.addEventListener("mouseup",F)},title:"Drag to resize lineage view",style:{position:"absolute",left:0,right:0,bottom:-3,height:6,cursor:"row-resize",background:E?s.accent:"transparent",transition:E?"none":"background 0.15s",zIndex:5},onMouseEnter:U=>{E||(U.currentTarget.style.background=`${s.accent}40`)},onMouseLeave:U=>{E||(U.currentTarget.style.background="transparent")}})]}),o.jsxs("div",{style:{padding:"6px 12px 8px"},children:[C&&(C.upstreamPaths.length>0||C.downstreamPaths.length>0)&&o.jsxs("div",{style:{marginBottom:8},children:[o.jsx("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:s.textMuted,marginBottom:4},children:"Complete Paths"}),o.jsxs("div",{style:{display:"grid",gap:6},children:[C.upstreamPaths.slice(0,3).map((U,D)=>o.jsx(fd,{path:U,onNodeClick:i,focalNodeId:m,t:s},`up-${D}`)),C.downstreamPaths.slice(0,2).map((U,D)=>o.jsx(fd,{path:U,onNodeClick:i,focalNodeId:m,t:s},`down-${D}`))]})]}),O.length>0&&o.jsxs("div",{style:{marginBottom:6},children:[o.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:s.textMuted,marginBottom:3},children:["Reads From (",O.length,")"]}),O.map(U=>o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:s.textPrimary},children:[o.jsx("span",{style:{color:ze.source_table,fontSize:9,fontWeight:700,width:26},children:"TBL"}),o.jsx("span",{children:U})]},U))]}),x.metrics.length>0&&o.jsxs("div",{style:{marginBottom:6},children:[o.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:s.textMuted,marginBottom:3},children:["Metrics (",x.metrics.length,")"]}),x.metrics.map(U=>o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:s.textPrimary},children:[o.jsx("span",{style:{color:ze.metric,fontSize:9,fontWeight:700,width:26},children:"MET"}),o.jsx("span",{children:U})]},U))]}),x.dimensions.length>0&&o.jsxs("div",{style:{marginBottom:6},children:[o.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:s.textMuted,marginBottom:3},children:["Dimensions (",x.dimensions.length,")"]}),x.dimensions.map(U=>o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:s.textPrimary},children:[o.jsx("span",{style:{color:ze.dimension,fontSize:9,fontWeight:700,width:26},children:"DIM"}),o.jsx("span",{children:U})]},U))]}),!M&&R.length===0&&!C&&o.jsx("div",{style:{color:s.textMuted,padding:"2px 0"},children:"No lineage dependencies detected for this cell."})]})]})})]}):null}const W=e=>e.flatMap(oG),oG=e=>ki(iG(e)).map(sG),sG=e=>e.replace(/ +/g," ").trim(),iG=e=>({type:"mandatory_block",items:zu(e,0)[0]}),zu=(e,t,n)=>{const r=[];for(;e[t];){const[s,i]=aG(e,t);if(r.push(s),t=i,e[t]==="|")t++;else if(e[t]==="}"||e[t]==="]"){if(n!==e[t])throw new Error(`Unbalanced parenthesis in: ${e}`);return t++,[r,t]}else if(t===e.length){if(n)throw new Error(`Unbalanced parenthesis in: ${e}`);return[r,t]}else throw new Error(`Unexpected "${e[t]}"`)}return[r,t]},aG=(e,t)=>{const n=[];for(;;){const[r,s]=lG(e,t);if(r)n.push(r),t=s;else break}return n.length===1?[n[0],t]:[{type:"concatenation",items:n},t]},lG=(e,t)=>{if(e[t]==="{")return cG(e,t+1);if(e[t]==="[")return dG(e,t+1);{let n="";for(;e[t]&&/[A-Za-z0-9_ ]/.test(e[t]);)n+=e[t],t++;return[n,t]}},cG=(e,t)=>{const[n,r]=zu(e,t,"}");return[{type:"mandatory_block",items:n},r]},dG=(e,t)=>{const[n,r]=zu(e,t,"]");return[{type:"optional_block",items:n},r]},ki=e=>{if(typeof e=="string")return[e];if(e.type==="concatenation")return e.items.map(ki).reduce(uG,[""]);if(e.type==="mandatory_block")return e.items.flatMap(ki);if(e.type==="optional_block")return["",...e.items.flatMap(ki)];throw new Error(`Unknown node type: ${e}`)},uG=(e,t)=>{const n=[];for(const r of e)for(const s of t)n.push(r+s);return n};var J;(function(e){e.QUOTED_IDENTIFIER="QUOTED_IDENTIFIER",e.IDENTIFIER="IDENTIFIER",e.STRING="STRING",e.VARIABLE="VARIABLE",e.RESERVED_DATA_TYPE="RESERVED_DATA_TYPE",e.RESERVED_PARAMETERIZED_DATA_TYPE="RESERVED_PARAMETERIZED_DATA_TYPE",e.RESERVED_KEYWORD="RESERVED_KEYWORD",e.RESERVED_FUNCTION_NAME="RESERVED_FUNCTION_NAME",e.RESERVED_KEYWORD_PHRASE="RESERVED_KEYWORD_PHRASE",e.RESERVED_DATA_TYPE_PHRASE="RESERVED_DATA_TYPE_PHRASE",e.RESERVED_SET_OPERATION="RESERVED_SET_OPERATION",e.RESERVED_CLAUSE="RESERVED_CLAUSE",e.RESERVED_SELECT="RESERVED_SELECT",e.RESERVED_JOIN="RESERVED_JOIN",e.ARRAY_IDENTIFIER="ARRAY_IDENTIFIER",e.ARRAY_KEYWORD="ARRAY_KEYWORD",e.CASE="CASE",e.END="END",e.WHEN="WHEN",e.ELSE="ELSE",e.THEN="THEN",e.LIMIT="LIMIT",e.BETWEEN="BETWEEN",e.AND="AND",e.OR="OR",e.XOR="XOR",e.OPERATOR="OPERATOR",e.COMMA="COMMA",e.ASTERISK="ASTERISK",e.PROPERTY_ACCESS_OPERATOR="PROPERTY_ACCESS_OPERATOR",e.OPEN_PAREN="OPEN_PAREN",e.CLOSE_PAREN="CLOSE_PAREN",e.LINE_COMMENT="LINE_COMMENT",e.BLOCK_COMMENT="BLOCK_COMMENT",e.DISABLE_COMMENT="DISABLE_COMMENT",e.NUMBER="NUMBER",e.NAMED_PARAMETER="NAMED_PARAMETER",e.QUOTED_PARAMETER="QUOTED_PARAMETER",e.NUMBERED_PARAMETER="NUMBERED_PARAMETER",e.POSITIONAL_PARAMETER="POSITIONAL_PARAMETER",e.CUSTOM_PARAMETER="CUSTOM_PARAMETER",e.DELIMITER="DELIMITER",e.EOF="EOF"})(J=J||(J={}));const xg=e=>({type:J.EOF,raw:"«EOF»",text:"«EOF»",start:e}),Hn=xg(1/0),Yr=e=>t=>t.type===e.type&&t.text===e.text,Wn={ARRAY:Yr({text:"ARRAY",type:J.RESERVED_DATA_TYPE}),BY:Yr({text:"BY",type:J.RESERVED_KEYWORD}),SET:Yr({text:"SET",type:J.RESERVED_CLAUSE}),STRUCT:Yr({text:"STRUCT",type:J.RESERVED_DATA_TYPE}),WINDOW:Yr({text:"WINDOW",type:J.RESERVED_CLAUSE}),VALUES:Yr({text:"VALUES",type:J.RESERVED_CLAUSE})},yg=e=>e===J.RESERVED_DATA_TYPE||e===J.RESERVED_KEYWORD||e===J.RESERVED_FUNCTION_NAME||e===J.RESERVED_KEYWORD_PHRASE||e===J.RESERVED_DATA_TYPE_PHRASE||e===J.RESERVED_CLAUSE||e===J.RESERVED_SELECT||e===J.RESERVED_SET_OPERATION||e===J.RESERVED_JOIN||e===J.ARRAY_KEYWORD||e===J.CASE||e===J.END||e===J.WHEN||e===J.ELSE||e===J.THEN||e===J.LIMIT||e===J.BETWEEN||e===J.AND||e===J.OR||e===J.XOR,EG=e=>e===J.AND||e===J.OR||e===J.XOR,fG=["KEYS.NEW_KEYSET","KEYS.ADD_KEY_FROM_RAW_BYTES","AEAD.DECRYPT_BYTES","AEAD.DECRYPT_STRING","AEAD.ENCRYPT","KEYS.KEYSET_CHAIN","KEYS.KEYSET_FROM_JSON","KEYS.KEYSET_TO_JSON","KEYS.ROTATE_KEYSET","KEYS.KEYSET_LENGTH","ANY_VALUE","ARRAY_AGG","AVG","CORR","COUNT","COUNTIF","COVAR_POP","COVAR_SAMP","MAX","MIN","ST_CLUSTERDBSCAN","STDDEV_POP","STDDEV_SAMP","STRING_AGG","SUM","VAR_POP","VAR_SAMP","ANY_VALUE","ARRAY_AGG","ARRAY_CONCAT_AGG","AVG","BIT_AND","BIT_OR","BIT_XOR","COUNT","COUNTIF","LOGICAL_AND","LOGICAL_OR","MAX","MIN","STRING_AGG","SUM","APPROX_COUNT_DISTINCT","APPROX_QUANTILES","APPROX_TOP_COUNT","APPROX_TOP_SUM","ARRAY_CONCAT","ARRAY_LENGTH","ARRAY_TO_STRING","GENERATE_ARRAY","GENERATE_DATE_ARRAY","GENERATE_TIMESTAMP_ARRAY","ARRAY_REVERSE","OFFSET","SAFE_OFFSET","ORDINAL","SAFE_ORDINAL","BIT_COUNT","PARSE_BIGNUMERIC","PARSE_NUMERIC","SAFE_CAST","CURRENT_DATE","EXTRACT","DATE","DATE_ADD","DATE_SUB","DATE_DIFF","DATE_TRUNC","DATE_FROM_UNIX_DATE","FORMAT_DATE","LAST_DAY","PARSE_DATE","UNIX_DATE","CURRENT_DATETIME","DATETIME","EXTRACT","DATETIME_ADD","DATETIME_SUB","DATETIME_DIFF","DATETIME_TRUNC","FORMAT_DATETIME","LAST_DAY","PARSE_DATETIME","ERROR","EXTERNAL_QUERY","S2_CELLIDFROMPOINT","S2_COVERINGCELLIDS","ST_ANGLE","ST_AREA","ST_ASBINARY","ST_ASGEOJSON","ST_ASTEXT","ST_AZIMUTH","ST_BOUNDARY","ST_BOUNDINGBOX","ST_BUFFER","ST_BUFFERWITHTOLERANCE","ST_CENTROID","ST_CENTROID_AGG","ST_CLOSESTPOINT","ST_CLUSTERDBSCAN","ST_CONTAINS","ST_CONVEXHULL","ST_COVEREDBY","ST_COVERS","ST_DIFFERENCE","ST_DIMENSION","ST_DISJOINT","ST_DISTANCE","ST_DUMP","ST_DWITHIN","ST_ENDPOINT","ST_EQUALS","ST_EXTENT","ST_EXTERIORRING","ST_GEOGFROM","ST_GEOGFROMGEOJSON","ST_GEOGFROMTEXT","ST_GEOGFROMWKB","ST_GEOGPOINT","ST_GEOGPOINTFROMGEOHASH","ST_GEOHASH","ST_GEOMETRYTYPE","ST_INTERIORRINGS","ST_INTERSECTION","ST_INTERSECTS","ST_INTERSECTSBOX","ST_ISCOLLECTION","ST_ISEMPTY","ST_LENGTH","ST_MAKELINE","ST_MAKEPOLYGON","ST_MAKEPOLYGONORIENTED","ST_MAXDISTANCE","ST_NPOINTS","ST_NUMGEOMETRIES","ST_NUMPOINTS","ST_PERIMETER","ST_POINTN","ST_SIMPLIFY","ST_SNAPTOGRID","ST_STARTPOINT","ST_TOUCHES","ST_UNION","ST_UNION_AGG","ST_WITHIN","ST_X","ST_Y","FARM_FINGERPRINT","MD5","SHA1","SHA256","SHA512","HLL_COUNT.INIT","HLL_COUNT.MERGE","HLL_COUNT.MERGE_PARTIAL","HLL_COUNT.EXTRACT","MAKE_INTERVAL","EXTRACT","JUSTIFY_DAYS","JUSTIFY_HOURS","JUSTIFY_INTERVAL","JSON_EXTRACT","JSON_QUERY","JSON_EXTRACT_SCALAR","JSON_VALUE","JSON_EXTRACT_ARRAY","JSON_QUERY_ARRAY","JSON_EXTRACT_STRING_ARRAY","JSON_VALUE_ARRAY","TO_JSON_STRING","ABS","SIGN","IS_INF","IS_NAN","IEEE_DIVIDE","RAND","SQRT","POW","POWER","EXP","LN","LOG","LOG10","GREATEST","LEAST","DIV","SAFE_DIVIDE","SAFE_MULTIPLY","SAFE_NEGATE","SAFE_ADD","SAFE_SUBTRACT","MOD","ROUND","TRUNC","CEIL","CEILING","FLOOR","COS","COSH","ACOS","ACOSH","SIN","SINH","ASIN","ASINH","TAN","TANH","ATAN","ATANH","ATAN2","RANGE_BUCKET","FIRST_VALUE","LAST_VALUE","NTH_VALUE","LEAD","LAG","PERCENTILE_CONT","PERCENTILE_DISC","NET.IP_FROM_STRING","NET.SAFE_IP_FROM_STRING","NET.IP_TO_STRING","NET.IP_NET_MASK","NET.IP_TRUNC","NET.IPV4_FROM_INT64","NET.IPV4_TO_INT64","NET.HOST","NET.PUBLIC_SUFFIX","NET.REG_DOMAIN","RANK","DENSE_RANK","PERCENT_RANK","CUME_DIST","NTILE","ROW_NUMBER","SESSION_USER","CORR","COVAR_POP","COVAR_SAMP","STDDEV_POP","STDDEV_SAMP","STDDEV","VAR_POP","VAR_SAMP","VARIANCE","ASCII","BYTE_LENGTH","CHAR_LENGTH","CHARACTER_LENGTH","CHR","CODE_POINTS_TO_BYTES","CODE_POINTS_TO_STRING","CONCAT","CONTAINS_SUBSTR","ENDS_WITH","FORMAT","FROM_BASE32","FROM_BASE64","FROM_HEX","INITCAP","INSTR","LEFT","LENGTH","LPAD","LOWER","LTRIM","NORMALIZE","NORMALIZE_AND_CASEFOLD","OCTET_LENGTH","REGEXP_CONTAINS","REGEXP_EXTRACT","REGEXP_EXTRACT_ALL","REGEXP_INSTR","REGEXP_REPLACE","REGEXP_SUBSTR","REPLACE","REPEAT","REVERSE","RIGHT","RPAD","RTRIM","SAFE_CONVERT_BYTES_TO_STRING","SOUNDEX","SPLIT","STARTS_WITH","STRPOS","SUBSTR","SUBSTRING","TO_BASE32","TO_BASE64","TO_CODE_POINTS","TO_HEX","TRANSLATE","TRIM","UNICODE","UPPER","CURRENT_TIME","TIME","EXTRACT","TIME_ADD","TIME_SUB","TIME_DIFF","TIME_TRUNC","FORMAT_TIME","PARSE_TIME","CURRENT_TIMESTAMP","EXTRACT","STRING","TIMESTAMP","TIMESTAMP_ADD","TIMESTAMP_SUB","TIMESTAMP_DIFF","TIMESTAMP_TRUNC","FORMAT_TIMESTAMP","PARSE_TIMESTAMP","TIMESTAMP_SECONDS","TIMESTAMP_MILLIS","TIMESTAMP_MICROS","UNIX_SECONDS","UNIX_MILLIS","UNIX_MICROS","GENERATE_UUID","COALESCE","IF","IFNULL","NULLIF","AVG","BIT_AND","BIT_OR","BIT_XOR","CORR","COUNT","COVAR_POP","COVAR_SAMP","EXACT_COUNT_DISTINCT","FIRST","GROUP_CONCAT","GROUP_CONCAT_UNQUOTED","LAST","MAX","MIN","NEST","NTH","QUANTILES","STDDEV","STDDEV_POP","STDDEV_SAMP","SUM","TOP","UNIQUE","VARIANCE","VAR_POP","VAR_SAMP","BIT_COUNT","BOOLEAN","BYTES","CAST","FLOAT","HEX_STRING","INTEGER","STRING","COALESCE","GREATEST","IFNULL","IS_INF","IS_NAN","IS_EXPLICITLY_DEFINED","LEAST","NVL","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","DATE","DATE_ADD","DATEDIFF","DAY","DAYOFWEEK","DAYOFYEAR","FORMAT_UTC_USEC","HOUR","MINUTE","MONTH","MSEC_TO_TIMESTAMP","NOW","PARSE_UTC_USEC","QUARTER","SEC_TO_TIMESTAMP","SECOND","STRFTIME_UTC_USEC","TIME","TIMESTAMP","TIMESTAMP_TO_MSEC","TIMESTAMP_TO_SEC","TIMESTAMP_TO_USEC","USEC_TO_TIMESTAMP","UTC_USEC_TO_DAY","UTC_USEC_TO_HOUR","UTC_USEC_TO_MONTH","UTC_USEC_TO_WEEK","UTC_USEC_TO_YEAR","WEEK","YEAR","FORMAT_IP","PARSE_IP","FORMAT_PACKED_IP","PARSE_PACKED_IP","JSON_EXTRACT","JSON_EXTRACT_SCALAR","ABS","ACOS","ACOSH","ASIN","ASINH","ATAN","ATANH","ATAN2","CEIL","COS","COSH","DEGREES","EXP","FLOOR","LN","LOG","LOG2","LOG10","PI","POW","RADIANS","RAND","ROUND","SIN","SINH","SQRT","TAN","TANH","REGEXP_MATCH","REGEXP_EXTRACT","REGEXP_REPLACE","CONCAT","INSTR","LEFT","LENGTH","LOWER","LPAD","LTRIM","REPLACE","RIGHT","RPAD","RTRIM","SPLIT","SUBSTR","UPPER","TABLE_DATE_RANGE","TABLE_DATE_RANGE_STRICT","TABLE_QUERY","HOST","DOMAIN","TLD","AVG","COUNT","MAX","MIN","STDDEV","SUM","CUME_DIST","DENSE_RANK","FIRST_VALUE","LAG","LAST_VALUE","LEAD","NTH_VALUE","NTILE","PERCENT_RANK","PERCENTILE_CONT","PERCENTILE_DISC","RANK","RATIO_TO_REPORT","ROW_NUMBER","CURRENT_USER","EVERY","FROM_BASE64","HASH","FARM_FINGERPRINT","IF","POSITION","SHA1","SOME","TO_BASE64","BQ.JOBS.CANCEL","BQ.REFRESH_MATERIALIZED_VIEW","OPTIONS","PIVOT","UNPIVOT"],pG=["ALL","AND","ANY","AS","ASC","ASSERT_ROWS_MODIFIED","AT","BETWEEN","BY","CASE","CAST","COLLATE","CONTAINS","CREATE","CROSS","CUBE","CURRENT","DEFAULT","DEFINE","DESC","DISTINCT","ELSE","END","ENUM","ESCAPE","EXCEPT","EXCLUDE","EXISTS","EXTRACT","FALSE","FETCH","FOLLOWING","FOR","FROM","FULL","GROUP","GROUPING","GROUPS","HASH","HAVING","IF","IGNORE","IN","INNER","INTERSECT","INTO","IS","JOIN","LATERAL","LEFT","LIMIT","LOOKUP","MERGE","NATURAL","NEW","NO","NOT","NULL","NULLS","OF","ON","OR","ORDER","OUTER","OVER","PARTITION","PRECEDING","PROTO","RANGE","RECURSIVE","RESPECT","RIGHT","ROLLUP","ROWS","SELECT","SET","SOME","TABLE","TABLESAMPLE","THEN","TO","TREAT","TRUE","UNBOUNDED","UNION","UNNEST","USING","WHEN","WHERE","WINDOW","WITH","WITHIN","SAFE","LIKE","COPY","CLONE","IN","OUT","INOUT","RETURNS","LANGUAGE","CASCADE","RESTRICT","DETERMINISTIC"],TG=["ARRAY","BOOL","BYTES","DATE","DATETIME","GEOGRAPHY","INTERVAL","INT64","INT","SMALLINT","INTEGER","BIGINT","TINYINT","BYTEINT","NUMERIC","DECIMAL","BIGNUMERIC","BIGDECIMAL","FLOAT64","STRING","STRUCT","TIME","TIMEZONE"],SG=W(["SELECT [ALL | DISTINCT] [AS STRUCT | AS VALUE]"]),hG=W(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","QUALIFY","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","OMIT RECORD IF","INSERT [INTO]","VALUES","SET","MERGE [INTO]","WHEN [NOT] MATCHED [BY SOURCE | BY TARGET] [THEN]","UPDATE SET","CLUSTER BY","FOR SYSTEM_TIME AS OF","WITH CONNECTION","WITH PARTITION COLUMNS","REMOTE WITH CONNECTION"]),Wp=W(["CREATE [OR REPLACE] [TEMP|TEMPORARY|SNAPSHOT|EXTERNAL] TABLE [IF NOT EXISTS]"]),Tc=W(["CREATE [OR REPLACE] [MATERIALIZED] VIEW [IF NOT EXISTS]","UPDATE","DELETE [FROM]","DROP [SNAPSHOT | EXTERNAL] TABLE [IF EXISTS]","ALTER TABLE [IF EXISTS]","ADD COLUMN [IF NOT EXISTS]","DROP COLUMN [IF EXISTS]","RENAME TO","ALTER COLUMN [IF EXISTS]","SET DEFAULT COLLATE","SET OPTIONS","DROP NOT NULL","SET DATA TYPE","ALTER SCHEMA [IF EXISTS]","ALTER [MATERIALIZED] VIEW [IF EXISTS]","ALTER BI_CAPACITY","TRUNCATE TABLE","CREATE SCHEMA [IF NOT EXISTS]","DEFAULT COLLATE","CREATE [OR REPLACE] [TEMP|TEMPORARY|TABLE] FUNCTION [IF NOT EXISTS]","CREATE [OR REPLACE] PROCEDURE [IF NOT EXISTS]","CREATE [OR REPLACE] ROW ACCESS POLICY [IF NOT EXISTS]","GRANT TO","FILTER USING","CREATE CAPACITY","AS JSON","CREATE RESERVATION","CREATE ASSIGNMENT","CREATE SEARCH INDEX [IF NOT EXISTS]","DROP SCHEMA [IF EXISTS]","DROP [MATERIALIZED] VIEW [IF EXISTS]","DROP [TABLE] FUNCTION [IF EXISTS]","DROP PROCEDURE [IF EXISTS]","DROP ROW ACCESS POLICY","DROP ALL ROW ACCESS POLICIES","DROP CAPACITY [IF EXISTS]","DROP RESERVATION [IF EXISTS]","DROP ASSIGNMENT [IF EXISTS]","DROP SEARCH INDEX [IF EXISTS]","DROP [IF EXISTS]","GRANT","REVOKE","DECLARE","EXECUTE IMMEDIATE","LOOP","END LOOP","REPEAT","END REPEAT","WHILE","END WHILE","BREAK","LEAVE","CONTINUE","ITERATE","FOR","END FOR","BEGIN","BEGIN TRANSACTION","COMMIT TRANSACTION","ROLLBACK TRANSACTION","RAISE","RETURN","CALL","ASSERT","EXPORT DATA"]),RG=W(["UNION {ALL | DISTINCT}","EXCEPT DISTINCT","INTERSECT DISTINCT"]),AG=W(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN"]),mG=W(["TABLESAMPLE SYSTEM","ANY TYPE","ALL COLUMNS","NOT DETERMINISTIC","{ROWS | RANGE} BETWEEN","IS [NOT] DISTINCT FROM"]),gG=W([]),IG={name:"bigquery",tokenizerOptions:{reservedSelect:SG,reservedClauses:[...hG,...Tc,...Wp],reservedSetOperations:RG,reservedJoins:AG,reservedKeywordPhrases:mG,reservedDataTypePhrases:gG,reservedKeywords:pG,reservedDataTypes:TG,reservedFunctionNames:fG,extraParens:["[]"],stringTypes:[{quote:'""".."""',prefixes:["R","B","RB","BR"]},{quote:"'''..'''",prefixes:["R","B","RB","BR"]},'""-bs',"''-bs",{quote:'""-raw',prefixes:["R","B","RB","BR"],requirePrefix:!0},{quote:"''-raw",prefixes:["R","B","RB","BR"],requirePrefix:!0}],identTypes:["``"],identChars:{dashes:!0},paramTypes:{positional:!0,named:["@"],quoted:["@"]},variableTypes:[{regex:String.raw`@@\w+`}],lineCommentTypes:["--","#"],operators:["&","|","^","~",">>","<<","||","=>"],postProcess:OG},formatOptions:{onelineClauses:[...Wp,...Tc],tabularOnelineClauses:Tc}};function OG(e){return NG(xG(e))}function NG(e){let t=Hn;return e.map(n=>n.text==="OFFSET"&&t.text==="["?(t=n,Object.assign(Object.assign({},n),{type:J.RESERVED_FUNCTION_NAME})):(t=n,n))}function xG(e){var t;const n=[];for(let r=0;r<e.length;r++){const s=e[r];if((Wn.ARRAY(s)||Wn.STRUCT(s))&&((t=e[r+1])===null||t===void 0?void 0:t.text)==="<"){const i=yG(e,r+1),a=e.slice(r,i+1);n.push({type:J.IDENTIFIER,raw:a.map(Yp("raw")).join(""),text:a.map(Yp("text")).join(""),start:s.start}),r=i}else n.push(s)}return n}const Yp=e=>t=>t.type===J.IDENTIFIER||t.type===J.COMMA?t[e]+" ":t[e];function yG(e,t){let n=0;for(let r=t;r<e.length;r++){const s=e[r];if(s.text==="<"?n++:s.text===">"?n--:s.text===">>"&&(n-=2),n===0)return r}return e.length-1}const CG=["BIT_AND","BIT_OR","BIT_XOR","BLAKE3","CAST","CHARACTER_LENGTH","CHAR_LENGTH","COVAR_POP","COVAR_SAMP","CRC32","CRC32IEEE","CRC64","DATE","DATE_DIFF","DATE_FORMAT","DATE_TRUNC","DAY","DAYOFMONTH","DAYOFWEEK","DAYOFYEAR","FORMAT_BYTES","FQDN","FROM_BASE64","FROM_DAYS","FROM_UNIXTIME","HOUR","INET6_ATON","INET6_NTOA","INET_ATON","INET_NTOA","IPv4CIDRToRange","IPv4NumToString","IPv4NumToStringClassC","IPv4StringToNum","IPv4StringToNumOrDefault","IPv4StringToNumOrNull","IPv4ToIPv6","IPv6CIDRToRange","IPv6NumToString","IPv6StringToNum","IPv6StringToNumOrDefault","IPv6StringToNumOrNull","JSONAllPaths","JSONAllPathsWithTypes","JSONArrayLength","JSONDynamicPaths","JSONDynamicPathsWithTypes","JSONExtract","JSONExtractArrayRaw","JSONExtractArrayRawCaseInsensitive","JSONExtractBool","JSONExtractBoolCaseInsensitive","JSONExtractCaseInsensitive","JSONExtractFloat","JSONExtractFloatCaseInsensitive","JSONExtractInt","JSONExtractIntCaseInsensitive","JSONExtractKeys","JSONExtractKeysAndValues","JSONExtractKeysAndValuesCaseInsensitive","JSONExtractKeysAndValuesRaw","JSONExtractKeysAndValuesRawCaseInsensitive","JSONExtractKeysCaseInsensitive","JSONExtractRaw","JSONExtractRawCaseInsensitive","JSONExtractString","JSONExtractStringCaseInsensitive","JSONExtractUInt","JSONExtractUIntCaseInsensitive","JSONHas","JSONKey","JSONLength","JSONMergePatch","JSONSharedDataPaths","JSONSharedDataPathsWithTypes","JSONType","JSON_ARRAY_LENGTH","JSON_EXISTS","JSON_QUERY","JSON_VALUE","L1Distance","L1Norm","L1Normalize","L2Distance","L2Norm","L2Normalize","L2SquaredDistance","L2SquaredNorm","LAST_DAY","LinfDistance","LinfNorm","LinfNormalize","LpDistance","LpNorm","LpNormalize","MACNumToString","MACStringToNum","MACStringToOUI","MAP_FROM_ARRAYS","MD4","MD5","MILLISECOND","MINUTE","MONTH","OCTET_LENGTH","QUARTER","REGEXP_EXTRACT","REGEXP_MATCHES","REGEXP_REPLACE","RIPEMD160","SCHEMA","SECOND","SHA1","SHA224","SHA256","SHA384","SHA512","SHA512_256","STD","STDDEV_POP","STDDEV_SAMP","ST_LineFromWKB","ST_MLineFromWKB","ST_MPolyFromWKB","ST_PointFromWKB","ST_PolyFromWKB","SUBSTRING_INDEX","SVG","TIMESTAMP_DIFF","TO_BASE64","TO_DAYS","TO_UNIXTIME","ULIDStringToDateTime","URLHash","URLHierarchy","URLPathHierarchy","UTCTimestamp","UTC_timestamp","UUIDNumToString","UUIDStringToNum","UUIDToNum","UUIDv7ToDateTime","VAR_POP","VAR_SAMP","YEAR","YYYYMMDDToDate","YYYYMMDDToDate32","YYYYMMDDhhmmssToDateTime","YYYYMMDDhhmmssToDateTime64","_CAST","__actionName","__bitBoolMaskAnd","__bitBoolMaskOr","__bitSwapLastTwo","__bitWrapperFunc","__getScalar","__patchPartitionID","__scalarSubqueryResult","abs","accurateCast","accurateCastOrDefault","accurateCastOrNull","acos","acosh","addDate","addDays","addHours","addInterval","addMicroseconds","addMilliseconds","addMinutes","addMonths","addNanoseconds","addQuarters","addSeconds","addTupleOfIntervals","addWeeks","addYears","addressToLine","addressToLineWithInlines","addressToSymbol","aes_decrypt_mysql","aes_encrypt_mysql","age","aggThrow","alphaTokens","analysisOfVariance","anova","any","anyHeavy","anyLast","anyLastRespectNulls","anyLast_respect_nulls","anyRespectNulls","anyValueRespectNulls","any_respect_nulls","any_value","any_value_respect_nulls","appendTrailingCharIfAbsent","approx_top_count","approx_top_k","approx_top_sum","argMax","argMin","array","arrayAUC","arrayAUCPR","arrayAll","arrayAvg","arrayCompact","arrayConcat","arrayCount","arrayCumSum","arrayCumSumNonNegative","arrayDifference","arrayDistinct","arrayDotProduct","arrayElement","arrayElementOrNull","arrayEnumerate","arrayEnumerateDense","arrayEnumerateDenseRanked","arrayEnumerateUniq","arrayEnumerateUniqRanked","arrayExists","arrayFill","arrayFilter","arrayFirst","arrayFirstIndex","arrayFirstOrNull","arrayFlatten","arrayFold","arrayIntersect","arrayJaccardIndex","arrayJoin","arrayLast","arrayLastIndex","arrayLastOrNull","arrayLevenshteinDistance","arrayLevenshteinDistanceWeighted","arrayMap","arrayMax","arrayMin","arrayNormalizedGini","arrayPRAUC","arrayPartialReverseSort","arrayPartialShuffle","arrayPartialSort","arrayPopBack","arrayPopFront","arrayProduct","arrayPushBack","arrayPushFront","arrayROCAUC","arrayRandomSample","arrayReduce","arrayReduceInRanges","arrayResize","arrayReverse","arrayReverseFill","arrayReverseSort","arrayReverseSplit","arrayRotateLeft","arrayRotateRight","arrayShiftLeft","arrayShiftRight","arrayShingles","arrayShuffle","arraySimilarity","arraySlice","arraySort","arraySplit","arrayStringConcat","arraySum","arraySymmetricDifference","arrayUnion","arrayUniq","arrayWithConstant","arrayZip","arrayZipUnaligned","array_agg","array_concat_agg","ascii","asin","asinh","assumeNotNull","atan","atan2","atanh","authenticatedUser","avg","avgWeighted","bar","base32Decode","base32Encode","base58Decode","base58Encode","base64Decode","base64Encode","base64URLDecode","base64URLEncode","basename","bech32Decode","bech32Encode","bin","bitAnd","bitCount","bitHammingDistance","bitNot","bitOr","bitPositionsToArray","bitRotateLeft","bitRotateRight","bitShiftLeft","bitShiftRight","bitSlice","bitTest","bitTestAll","bitTestAny","bitXor","bitmapAnd","bitmapAndCardinality","bitmapAndnot","bitmapAndnotCardinality","bitmapBuild","bitmapCardinality","bitmapContains","bitmapHasAll","bitmapHasAny","bitmapMax","bitmapMin","bitmapOr","bitmapOrCardinality","bitmapSubsetInRange","bitmapSubsetLimit","bitmapToArray","bitmapTransform","bitmapXor","bitmapXorCardinality","bitmaskToArray","bitmaskToList","blockNumber","blockSerializedSize","blockSize","boundingRatio","buildId","byteHammingDistance","byteSize","byteSlice","byteSwap","caseWithExpr","caseWithExpression","caseWithoutExpr","caseWithoutExpression","catboostEvaluate","categoricalInformationValue","cbrt","ceil","ceiling","changeDay","changeHour","changeMinute","changeMonth","changeSecond","changeYear","char","cityHash64","clamp","coalesce","colorOKLCHToSRGB","colorSRGBToOKLCH","compareSubstrings","concat","concatAssumeInjective","concatWithSeparator","concatWithSeparatorAssumeInjective","concat_ws","connectionId","connection_id","contingency","convertCharset","corr","corrMatrix","corrStable","cos","cosh","cosineDistance","count","countDigits","countEqual","countMatches","countMatchesCaseInsensitive","countSubstrings","countSubstringsCaseInsensitive","countSubstringsCaseInsensitiveUTF8","covarPop","covarPopMatrix","covarPopStable","covarSamp","covarSampMatrix","covarSampStable","cramersV","cramersVBiasCorrected","curdate","currentDatabase","currentProfiles","currentQueryID","currentRoles","currentSchemas","currentUser","current_database","current_date","current_query_id","current_schemas","current_timestamp","current_user","cutFragment","cutIPv6","cutQueryString","cutQueryStringAndFragment","cutToFirstSignificantSubdomain","cutToFirstSignificantSubdomainCustom","cutToFirstSignificantSubdomainCustomRFC","cutToFirstSignificantSubdomainCustomWithWWW","cutToFirstSignificantSubdomainCustomWithWWWRFC","cutToFirstSignificantSubdomainRFC","cutToFirstSignificantSubdomainWithWWW","cutToFirstSignificantSubdomainWithWWWRFC","cutURLParameter","cutWWW","damerauLevenshteinDistance","dateDiff","dateName","dateTime64ToSnowflake","dateTime64ToSnowflakeID","dateTimeToSnowflake","dateTimeToSnowflakeID","dateTimeToUUIDv7","dateTrunc","date_bin","date_diff","decodeHTMLComponent","decodeURLComponent","decodeURLFormComponent","decodeXMLComponent","decrypt","defaultProfiles","defaultRoles","defaultValueOfArgumentType","defaultValueOfTypeName","degrees","deltaSum","deltaSumTimestamp","demangle","denseRank","dense_rank","detectCharset","detectLanguage","detectLanguageMixed","detectLanguageUnknown","detectProgrammingLanguage","detectTonality","dictGet","dictGetAll","dictGetChildren","dictGetDate","dictGetDateOrDefault","dictGetDateTime","dictGetDateTimeOrDefault","dictGetDescendants","dictGetFloat32","dictGetFloat32OrDefault","dictGetFloat64","dictGetFloat64OrDefault","dictGetHierarchy","dictGetIPv4","dictGetIPv4OrDefault","dictGetIPv6","dictGetIPv6OrDefault","dictGetInt16","dictGetInt16OrDefault","dictGetInt32","dictGetInt32OrDefault","dictGetInt64","dictGetInt64OrDefault","dictGetInt8","dictGetInt8OrDefault","dictGetOrDefault","dictGetOrNull","dictGetString","dictGetStringOrDefault","dictGetUInt16","dictGetUInt16OrDefault","dictGetUInt32","dictGetUInt32OrDefault","dictGetUInt64","dictGetUInt64OrDefault","dictGetUInt8","dictGetUInt8OrDefault","dictGetUUID","dictGetUUIDOrDefault","dictHas","dictIsIn","displayName","distanceL1","distanceL2","distanceL2Squared","distanceLinf","distanceLp","distinctDynamicTypes","distinctJSONPaths","distinctJSONPathsAndTypes","divide","divideDecimal","divideOrNull","domain","domainRFC","domainWithoutWWW","domainWithoutWWWRFC","dotProduct","dumpColumnStructure","dynamicElement","dynamicType","e","editDistance","editDistanceUTF8","empty","emptyArrayDate","emptyArrayDateTime","emptyArrayFloat32","emptyArrayFloat64","emptyArrayInt16","emptyArrayInt32","emptyArrayInt64","emptyArrayInt8","emptyArrayString","emptyArrayToSingle","emptyArrayUInt16","emptyArrayUInt32","emptyArrayUInt64","emptyArrayUInt8","enabledProfiles","enabledRoles","encodeURLComponent","encodeURLFormComponent","encodeXMLComponent","encrypt","endsWith","endsWithUTF8","entropy","equals","erf","erfc","errorCodeToName","estimateCompressionRatio","evalMLMethod","exp","exp10","exp2","exponentialMovingAverage","exponentialTimeDecayedAvg","exponentialTimeDecayedCount","exponentialTimeDecayedMax","exponentialTimeDecayedSum","extract","extractAll","extractAllGroups","extractAllGroupsHorizontal","extractAllGroupsVertical","extractGroups","extractKeyValuePairs","extractKeyValuePairsWithEscaping","extractTextFromHTML","extractURLParameter","extractURLParameterNames","extractURLParameters","factorial","farmFingerprint64","farmHash64","file","filesystemAvailable","filesystemCapacity","filesystemUnreserved","finalizeAggregation","financialInternalRateOfReturn","financialInternalRateOfReturnExtended","financialNetPresentValue","financialNetPresentValueExtended","firstLine","firstSignificantSubdomain","firstSignificantSubdomainCustom","firstSignificantSubdomainCustomRFC","firstSignificantSubdomainRFC","firstValueRespectNulls","first_value","first_value_respect_nulls","flameGraph","flatten","flattenTuple","floor","formatDateTime","formatDateTimeInJodaSyntax","formatQuery","formatQueryOrNull","formatQuerySingleLine","formatQuerySingleLineOrNull","formatReadableDecimalSize","formatReadableQuantity","formatReadableSize","formatReadableTimeDelta","formatRow","formatRowNoNewline","fragment","fromDaysSinceYearZero","fromDaysSinceYearZero32","fromModifiedJulianDay","fromModifiedJulianDayOrNull","fromUTCTimestamp","fromUnixTimestamp","fromUnixTimestamp64Micro","fromUnixTimestamp64Milli","fromUnixTimestamp64Nano","fromUnixTimestamp64Second","fromUnixTimestampInJodaSyntax","from_utc_timestamp","fullHostName","fuzzBits","gccMurmurHash","gcd","generateRandomStructure","generateSerialID","generateSnowflakeID","generateULID","generateUUIDv4","generateUUIDv7","geoDistance","geoToH3","geoToS2","geohashDecode","geohashEncode","geohashesInBox","getClientHTTPHeader","getMacro","getMaxTableNameLengthForDatabase","getMergeTreeSetting","getOSKernelVersion","getServerPort","getServerSetting","getSetting","getSettingOrDefault","getSizeOfEnumType","getSubcolumn","getTypeSerializationStreams","globalIn","globalInIgnoreSet","globalNotIn","globalNotInIgnoreSet","globalNotNullIn","globalNotNullInIgnoreSet","globalNullIn","globalNullInIgnoreSet","globalVariable","greatCircleAngle","greatCircleDistance","greater","greaterOrEquals","greatest","groupArray","groupArrayInsertAt","groupArrayIntersect","groupArrayLast","groupArrayMovingAvg","groupArrayMovingSum","groupArraySample","groupArraySorted","groupBitAnd","groupBitOr","groupBitXor","groupBitmap","groupBitmapAnd","groupBitmapOr","groupBitmapXor","groupConcat","groupNumericIndexedVector","groupUniqArray","group_concat","h3CellAreaM2","h3CellAreaRads2","h3Distance","h3EdgeAngle","h3EdgeLengthKm","h3EdgeLengthM","h3ExactEdgeLengthKm","h3ExactEdgeLengthM","h3ExactEdgeLengthRads","h3GetBaseCell","h3GetDestinationIndexFromUnidirectionalEdge","h3GetFaces","h3GetIndexesFromUnidirectionalEdge","h3GetOriginIndexFromUnidirectionalEdge","h3GetPentagonIndexes","h3GetRes0Indexes","h3GetResolution","h3GetUnidirectionalEdge","h3GetUnidirectionalEdgeBoundary","h3GetUnidirectionalEdgesFromHexagon","h3HexAreaKm2","h3HexAreaM2","h3HexRing","h3IndexesAreNeighbors","h3IsPentagon","h3IsResClassIII","h3IsValid","h3Line","h3NumHexagons","h3PointDistKm","h3PointDistM","h3PointDistRads","h3ToCenterChild","h3ToChildren","h3ToGeo","h3ToGeoBoundary","h3ToParent","h3ToString","h3UnidirectionalEdgeIsValid","h3kRing","halfMD5","has","hasAll","hasAny","hasColumnInTable","hasSubsequence","hasSubsequenceCaseInsensitive","hasSubsequenceCaseInsensitiveUTF8","hasSubsequenceUTF8","hasSubstr","hasThreadFuzzer","hasToken","hasTokenCaseInsensitive","hasTokenCaseInsensitiveOrNull","hasTokenOrNull","hex","hilbertDecode","hilbertEncode","histogram","hiveHash","hop","hopEnd","hopStart","hostName","hostname","hypot","icebergBucket","icebergHash","icebergTruncate","identity","idnaDecode","idnaEncode","if","ifNotFinite","ifNull","ignore","inIgnoreSet","indexHint","indexOf","indexOfAssumeSorted","initcap","initcapUTF8","initialQueryID","initialQueryStartTime","initial_query_id","initial_query_start_time","initializeAggregation","instr","intDiv","intDivOrNull","intDivOrZero","intExp10","intExp2","intHash32","intHash64","intervalLengthSum","isConstant","isDecimalOverflow","isDynamicElementInSharedData","isFinite","isIPAddressInRange","isIPv4String","isIPv6String","isInfinite","isMergeTreePartCoveredBy","isNaN","isNotDistinctFrom","isNotNull","isNull","isNullable","isValidJSON","isValidUTF8","isZeroOrNull","jaroSimilarity","jaroWinklerSimilarity","javaHash","javaHashUTF16LE","joinGet","joinGetOrNull","jsonMergePatch","jumpConsistentHash","kafkaMurmurHash","keccak256","kolmogorovSmirnovTest","kostikConsistentHash","kql_array_sort_asc","kql_array_sort_desc","kurtPop","kurtSamp","lag","lagInFrame","largestTriangleThreeBuckets","lastValueRespectNulls","last_value","last_value_respect_nulls","lcase","lcm","lead","leadInFrame","least","left","leftPad","leftPadUTF8","leftUTF8","lemmatize","length","lengthUTF8","less","lessOrEquals","levenshteinDistance","levenshteinDistanceUTF8","lgamma","ln","locate","log","log10","log1p","log2","logTrace","lowCardinalityIndices","lowCardinalityKeys","lower","lowerUTF8","lpad","ltrim","lttb","makeDate","makeDate32","makeDateTime","makeDateTime64","mannWhitneyUTest","map","mapAdd","mapAll","mapApply","mapConcat","mapContains","mapContainsKey","mapContainsKeyLike","mapContainsValue","mapContainsValueLike","mapExists","mapExtractKeyLike","mapExtractValueLike","mapFilter","mapFromArrays","mapFromString","mapKeys","mapPartialReverseSort","mapPartialSort","mapPopulateSeries","mapReverseSort","mapSort","mapSubtract","mapUpdate","mapValues","match","materialize","max","max2","maxIntersections","maxIntersectionsPosition","maxMappedArrays","meanZTest","median","medianBFloat16","medianBFloat16Weighted","medianDD","medianDeterministic","medianExact","medianExactHigh","medianExactLow","medianExactWeighted","medianExactWeightedInterpolated","medianGK","medianInterpolatedWeighted","medianTDigest","medianTDigestWeighted","medianTiming","medianTimingWeighted","mergeTreePartInfo","metroHash64","mid","min","min2","minMappedArrays","minSampleSizeContinous","minSampleSizeContinuous","minSampleSizeConversion","minus","mismatches","mod","modOrNull","modulo","moduloLegacy","moduloOrNull","moduloOrZero","monthName","mortonDecode","mortonEncode","multiFuzzyMatchAllIndices","multiFuzzyMatchAny","multiFuzzyMatchAnyIndex","multiIf","multiMatchAllIndices","multiMatchAny","multiMatchAnyIndex","multiSearchAllPositions","multiSearchAllPositionsCaseInsensitive","multiSearchAllPositionsCaseInsensitiveUTF8","multiSearchAllPositionsUTF8","multiSearchAny","multiSearchAnyCaseInsensitive","multiSearchAnyCaseInsensitiveUTF8","multiSearchAnyUTF8","multiSearchFirstIndex","multiSearchFirstIndexCaseInsensitive","multiSearchFirstIndexCaseInsensitiveUTF8","multiSearchFirstIndexUTF8","multiSearchFirstPosition","multiSearchFirstPositionCaseInsensitive","multiSearchFirstPositionCaseInsensitiveUTF8","multiSearchFirstPositionUTF8","multiply","multiplyDecimal","murmurHash2_32","murmurHash2_64","murmurHash3_128","murmurHash3_32","murmurHash3_64","negate","neighbor","nested","netloc","ngramDistance","ngramDistanceCaseInsensitive","ngramDistanceCaseInsensitiveUTF8","ngramDistanceUTF8","ngramMinHash","ngramMinHashArg","ngramMinHashArgCaseInsensitive","ngramMinHashArgCaseInsensitiveUTF8","ngramMinHashArgUTF8","ngramMinHashCaseInsensitive","ngramMinHashCaseInsensitiveUTF8","ngramMinHashUTF8","ngramSearch","ngramSearchCaseInsensitive","ngramSearchCaseInsensitiveUTF8","ngramSearchUTF8","ngramSimHash","ngramSimHashCaseInsensitive","ngramSimHashCaseInsensitiveUTF8","ngramSimHashUTF8","ngrams","nonNegativeDerivative","normL1","normL2","normL2Squared","normLinf","normLp","normalizeL1","normalizeL2","normalizeLinf","normalizeLp","normalizeQuery","normalizeQueryKeepNames","normalizeUTF8NFC","normalizeUTF8NFD","normalizeUTF8NFKC","normalizeUTF8NFKD","normalizedQueryHash","normalizedQueryHashKeepNames","notEmpty","notEquals","notILike","notIn","notInIgnoreSet","notLike","notNullIn","notNullInIgnoreSet","nothing","nothingNull","nothingUInt64","now","now64","nowInBlock","nowInBlock64","nth_value","ntile","nullIf","nullIn","nullInIgnoreSet","numbers","numericIndexedVectorAllValueSum","numericIndexedVectorBuild","numericIndexedVectorCardinality","numericIndexedVectorGetValue","numericIndexedVectorPointwiseAdd","numericIndexedVectorPointwiseDivide","numericIndexedVectorPointwiseEqual","numericIndexedVectorPointwiseGreater","numericIndexedVectorPointwiseGreaterEqual","numericIndexedVectorPointwiseLess","numericIndexedVectorPointwiseLessEqual","numericIndexedVectorPointwiseMultiply","numericIndexedVectorPointwiseNotEqual","numericIndexedVectorPointwiseSubtract","numericIndexedVectorShortDebugString","numericIndexedVectorToMap","overlay","overlayUTF8","parseDateTime","parseDateTime32BestEffort","parseDateTime32BestEffortOrNull","parseDateTime32BestEffortOrZero","parseDateTime64","parseDateTime64BestEffort","parseDateTime64BestEffortOrNull","parseDateTime64BestEffortOrZero","parseDateTime64BestEffortUS","parseDateTime64BestEffortUSOrNull","parseDateTime64BestEffortUSOrZero","parseDateTime64InJodaSyntax","parseDateTime64InJodaSyntaxOrNull","parseDateTime64InJodaSyntaxOrZero","parseDateTime64OrNull","parseDateTime64OrZero","parseDateTimeBestEffort","parseDateTimeBestEffortOrNull","parseDateTimeBestEffortOrZero","parseDateTimeBestEffortUS","parseDateTimeBestEffortUSOrNull","parseDateTimeBestEffortUSOrZero","parseDateTimeInJodaSyntax","parseDateTimeInJodaSyntaxOrNull","parseDateTimeInJodaSyntaxOrZero","parseDateTimeOrNull","parseDateTimeOrZero","parseReadableSize","parseReadableSizeOrNull","parseReadableSizeOrZero","parseTimeDelta","partitionID","partitionId","path","pathFull","percentRank","percent_rank","pi","plus","pmod","pmodOrNull","pointInEllipses","pointInPolygon","polygonAreaCartesian","polygonAreaSpherical","polygonConvexHullCartesian","polygonPerimeterCartesian","polygonPerimeterSpherical","polygonsDistanceCartesian","polygonsDistanceSpherical","polygonsEqualsCartesian","polygonsIntersectCartesian","polygonsIntersectSpherical","polygonsIntersectionCartesian","polygonsIntersectionSpherical","polygonsSymDifferenceCartesian","polygonsSymDifferenceSpherical","polygonsUnionCartesian","polygonsUnionSpherical","polygonsWithinCartesian","polygonsWithinSpherical","port","portRFC","position","positionCaseInsensitive","positionCaseInsensitiveUTF8","positionUTF8","positiveModulo","positiveModuloOrNull","positive_modulo","positive_modulo_or_null","pow","power","printf","proportionsZTest","protocol","punycodeDecode","punycodeEncode","quantile","quantileBFloat16","quantileBFloat16Weighted","quantileDD","quantileDeterministic","quantileExact","quantileExactExclusive","quantileExactHigh","quantileExactInclusive","quantileExactLow","quantileExactWeighted","quantileExactWeightedInterpolated","quantileGK","quantileInterpolatedWeighted","quantileTDigest","quantileTDigestWeighted","quantileTiming","quantileTimingWeighted","quantiles","quantilesBFloat16","quantilesBFloat16Weighted","quantilesDD","quantilesDeterministic","quantilesExact","quantilesExactExclusive","quantilesExactHigh","quantilesExactInclusive","quantilesExactLow","quantilesExactWeighted","quantilesExactWeightedInterpolated","quantilesGK","quantilesInterpolatedWeighted","quantilesTDigest","quantilesTDigestWeighted","quantilesTiming","quantilesTimingWeighted","queryID","queryString","queryStringAndFragment","query_id","radians","rand","rand32","rand64","randBernoulli","randBinomial","randCanonical","randChiSquared","randConstant","randExponential","randFisherF","randLogNormal","randNegativeBinomial","randNormal","randPoisson","randStudentT","randUniform","randomFixedString","randomPrintableASCII","randomString","randomStringUTF8","rank","rankCorr","readWKBLineString","readWKBMultiLineString","readWKBMultiPolygon","readWKBPoint","readWKBPolygon","readWKTLineString","readWKTMultiLineString","readWKTMultiPolygon","readWKTPoint","readWKTPolygon","readWKTRing","regexpExtract","regexpQuoteMeta","regionHierarchy","regionIn","regionToArea","regionToCity","regionToContinent","regionToCountry","regionToDistrict","regionToName","regionToPopulation","regionToTopContinent","reinterpret","reinterpretAsDate","reinterpretAsDateTime","reinterpretAsFixedString","reinterpretAsFloat32","reinterpretAsFloat64","reinterpretAsInt128","reinterpretAsInt16","reinterpretAsInt256","reinterpretAsInt32","reinterpretAsInt64","reinterpretAsInt8","reinterpretAsString","reinterpretAsUInt128","reinterpretAsUInt16","reinterpretAsUInt256","reinterpretAsUInt32","reinterpretAsUInt64","reinterpretAsUInt8","reinterpretAsUUID","repeat","replace","replaceAll","replaceOne","replaceRegexpAll","replaceRegexpOne","replicate","retention","reverse","reverseUTF8","revision","right","rightPad","rightPadUTF8","rightUTF8","round","roundAge","roundBankers","roundDown","roundDuration","roundToExp2","rowNumberInAllBlocks","rowNumberInBlock","row_number","rpad","rtrim","runningAccumulate","runningConcurrency","runningDifference","runningDifferenceStartingWithFirstValue","s2CapContains","s2CapUnion","s2CellsIntersect","s2GetNeighbors","s2RectAdd","s2RectContains","s2RectIntersection","s2RectUnion","s2ToGeo","scalarProduct","searchAll","searchAny","sequenceCount","sequenceMatch","sequenceMatchEvents","sequenceNextNode","seriesDecomposeSTL","seriesOutliersDetectTukey","seriesPeriodDetectFFT","serverTimeZone","serverTimezone","serverUUID","shardCount","shardNum","showCertificate","sigmoid","sign","simpleJSONExtractBool","simpleJSONExtractFloat","simpleJSONExtractInt","simpleJSONExtractRaw","simpleJSONExtractString","simpleJSONExtractUInt","simpleJSONHas","simpleLinearRegression","sin","singleValueOrNull","sinh","sipHash128","sipHash128Keyed","sipHash128Reference","sipHash128ReferenceKeyed","sipHash64","sipHash64Keyed","skewPop","skewSamp","sleep","sleepEachRow","snowflakeIDToDateTime","snowflakeIDToDateTime64","snowflakeToDateTime","snowflakeToDateTime64","soundex","space","sparkBar","sparkbar","sparseGrams","sparseGramsHashes","sparseGramsHashesUTF8","sparseGramsUTF8","splitByAlpha","splitByChar","splitByNonAlpha","splitByRegexp","splitByString","splitByWhitespace","sqid","sqidDecode","sqidEncode","sqrt","startsWith","startsWithUTF8","stddevPop","stddevPopStable","stddevSamp","stddevSampStable","stem","stochasticLinearRegression","stochasticLogisticRegression","str_to_date","str_to_map","stringBytesEntropy","stringBytesUniq","stringJaccardIndex","stringJaccardIndexUTF8","stringToH3","structureToCapnProtoSchema","structureToProtobufSchema","studentTTest","subBitmap","subDate","substr","substring","substringIndex","substringIndexUTF8","substringUTF8","subtractDays","subtractHours","subtractInterval","subtractMicroseconds","subtractMilliseconds","subtractMinutes","subtractMonths","subtractNanoseconds","subtractQuarters","subtractSeconds","subtractTupleOfIntervals","subtractWeeks","subtractYears","sum","sumCount","sumKahan","sumMapFiltered","sumMapFilteredWithOverflow","sumMapWithOverflow","sumMappedArrays","sumWithOverflow","svg","synonyms","tan","tanh","tcpPort","tgamma","theilsU","throwIf","tid","timeDiff","timeSeriesDeltaToGrid","timeSeriesDerivToGrid","timeSeriesFromGrid","timeSeriesGroupArray","timeSeriesIdToTags","timeSeriesIdToTagsGroup","timeSeriesIdeltaToGrid","timeSeriesInstantDeltaToGrid","timeSeriesInstantRateToGrid","timeSeriesIrateToGrid","timeSeriesLastToGrid","timeSeriesLastTwoSamples","timeSeriesPredictLinearToGrid","timeSeriesRange","timeSeriesRateToGrid","timeSeriesResampleToGridWithStaleness","timeSeriesStoreTags","timeSeriesTagsGroupToTags","timeSlot","timeSlots","timeZone","timeZoneOf","timeZoneOffset","time_bucket","timestamp","timestampDiff","timestamp_diff","timezone","timezoneOf","timezoneOffset","toBFloat16","toBFloat16OrNull","toBFloat16OrZero","toBool","toColumnTypeName","toDate","toDate32","toDate32OrDefault","toDate32OrNull","toDate32OrZero","toDateOrDefault","toDateOrNull","toDateOrZero","toDateTime","toDateTime32","toDateTime64","toDateTime64OrDefault","toDateTime64OrNull","toDateTime64OrZero","toDateTimeOrDefault","toDateTimeOrNull","toDateTimeOrZero","toDayOfMonth","toDayOfWeek","toDayOfYear","toDaysSinceYearZero","toDecimal128","toDecimal128OrDefault","toDecimal128OrNull","toDecimal128OrZero","toDecimal256","toDecimal256OrDefault","toDecimal256OrNull","toDecimal256OrZero","toDecimal32","toDecimal32OrDefault","toDecimal32OrNull","toDecimal32OrZero","toDecimal64","toDecimal64OrDefault","toDecimal64OrNull","toDecimal64OrZero","toDecimalString","toFixedString","toFloat32","toFloat32OrDefault","toFloat32OrNull","toFloat32OrZero","toFloat64","toFloat64OrDefault","toFloat64OrNull","toFloat64OrZero","toHour","toIPv4","toIPv4OrDefault","toIPv4OrNull","toIPv4OrZero","toIPv6","toIPv6OrDefault","toIPv6OrNull","toIPv6OrZero","toISOWeek","toISOYear","toInt128","toInt128OrDefault","toInt128OrNull","toInt128OrZero","toInt16","toInt16OrDefault","toInt16OrNull","toInt16OrZero","toInt256","toInt256OrDefault","toInt256OrNull","toInt256OrZero","toInt32","toInt32OrDefault","toInt32OrNull","toInt32OrZero","toInt64","toInt64OrDefault","toInt64OrNull","toInt64OrZero","toInt8","toInt8OrDefault","toInt8OrNull","toInt8OrZero","toInterval","toIntervalDay","toIntervalHour","toIntervalMicrosecond","toIntervalMillisecond","toIntervalMinute","toIntervalMonth","toIntervalNanosecond","toIntervalQuarter","toIntervalSecond","toIntervalWeek","toIntervalYear","toJSONString","toLastDayOfMonth","toLastDayOfWeek","toLowCardinality","toMillisecond","toMinute","toModifiedJulianDay","toModifiedJulianDayOrNull","toMonday","toMonth","toMonthNumSinceEpoch","toNullable","toQuarter","toRelativeDayNum","toRelativeHourNum","toRelativeMinuteNum","toRelativeMonthNum","toRelativeQuarterNum","toRelativeSecondNum","toRelativeWeekNum","toRelativeYearNum","toSecond","toStartOfDay","toStartOfFifteenMinutes","toStartOfFiveMinute","toStartOfFiveMinutes","toStartOfHour","toStartOfISOYear","toStartOfInterval","toStartOfMicrosecond","toStartOfMillisecond","toStartOfMinute","toStartOfMonth","toStartOfNanosecond","toStartOfQuarter","toStartOfSecond","toStartOfTenMinutes","toStartOfWeek","toStartOfYear","toString","toStringCutToZero","toTime","toTime64","toTime64OrNull","toTime64OrZero","toTimeOrNull","toTimeOrZero","toTimeWithFixedDate","toTimeZone","toTimezone","toTypeName","toUInt128","toUInt128OrDefault","toUInt128OrNull","toUInt128OrZero","toUInt16","toUInt16OrDefault","toUInt16OrNull","toUInt16OrZero","toUInt256","toUInt256OrDefault","toUInt256OrNull","toUInt256OrZero","toUInt32","toUInt32OrDefault","toUInt32OrNull","toUInt32OrZero","toUInt64","toUInt64OrDefault","toUInt64OrNull","toUInt64OrZero","toUInt8","toUInt8OrDefault","toUInt8OrNull","toUInt8OrZero","toUTCTimestamp","toUUID","toUUIDOrDefault","toUUIDOrNull","toUUIDOrZero","toUnixTimestamp","toUnixTimestamp64Micro","toUnixTimestamp64Milli","toUnixTimestamp64Nano","toUnixTimestamp64Second","toValidUTF8","toWeek","toYYYYMM","toYYYYMMDD","toYYYYMMDDhhmmss","toYear","toYearNumSinceEpoch","toYearWeek","to_utc_timestamp","today","tokens","topK","topKWeighted","topLevelDomain","topLevelDomainRFC","transactionID","transactionLatestSnapshot","transactionOldestSnapshot","transform","translate","translateUTF8","trim","trimBoth","trimLeft","trimRight","trunc","tryBase32Decode","tryBase58Decode","tryBase64Decode","tryBase64URLDecode","tryDecrypt","tryIdnaEncode","tryPunycodeDecode","tumble","tumbleEnd","tumbleStart","tuple","tupleConcat","tupleDivide","tupleDivideByNumber","tupleElement","tupleHammingDistance","tupleIntDiv","tupleIntDivByNumber","tupleIntDivOrZero","tupleIntDivOrZeroByNumber","tupleMinus","tupleModulo","tupleModuloByNumber","tupleMultiply","tupleMultiplyByNumber","tupleNames","tupleNegate","tuplePlus","tupleToNameValuePairs","ucase","unbin","unhex","uniq","uniqCombined","uniqCombined64","uniqExact","uniqHLL12","uniqTheta","uniqThetaIntersect","uniqThetaNot","uniqThetaUnion","uniqUpTo","upper","upperUTF8","uptime","user","validateNestedArraySizes","varPop","varPopStable","varSamp","varSampStable","variantElement","variantType","vectorDifference","vectorSum","version","visibleWidth","visitParamExtractBool","visitParamExtractFloat","visitParamExtractInt","visitParamExtractRaw","visitParamExtractString","visitParamExtractUInt","visitParamHas","week","welchTTest","widthBucket","width_bucket","windowFunnel","windowID","wkb","wkt","wordShingleMinHash","wordShingleMinHashArg","wordShingleMinHashArgCaseInsensitive","wordShingleMinHashArgCaseInsensitiveUTF8","wordShingleMinHashArgUTF8","wordShingleMinHashCaseInsensitive","wordShingleMinHashCaseInsensitiveUTF8","wordShingleMinHashUTF8","wordShingleSimHash","wordShingleSimHashCaseInsensitive","wordShingleSimHashCaseInsensitiveUTF8","wordShingleSimHashUTF8","wyHash64","xor","xxHash32","xxHash64","xxh3","yandexConsistentHash","yearweek","yesterday","zookeeperSessionUptime","MergeTree","ReplacingMergeTree","SummingMergeTree","AggregatingMergeTree","CollapsingMergeTree","VersionedCollapsingMergeTree","GraphiteMergeTree","CoalescingMergeTree","Atomic","Shared","Lazy","Replicated","PostgreSQL","MySQL","SQLite","MaterializedPostgreSQL","DataLakeCatalog"],LG=["ACCESS","ACTION","ADD","ADMIN","AFTER","ALGORITHM","ALIAS","ALL","ALLOWED_LATENESS","ALTER","AND","ANTI","APPEND","APPLY","AS","ASC","ASCENDING","ASOF","ASSUME","AST","ASYNC","ATTACH","AUTO_INCREMENT","AZURE","BACKUP","BAGEXPANSION","BASE_BACKUP","BCRYPT_HASH","BCRYPT_PASSWORD","BEGIN","BETWEEN","BIDIRECTIONAL","BOTH","BY","CACHE","CACHES","CASCADE","CASE","CHANGE","CHANGEABLE_IN_READONLY","CHANGED","CHARACTER","CHECK","CLEANUP","CLEAR","CLUSTER","CLUSTERS","CLUSTER_HOST_IDS","CN","CODEC","COLLATE","COLLECTION","COLUMN","COLUMNS","COMMENT","COMMIT","COMPRESSION","CONST","CONSTRAINT","CREATE","CROSS","CUBE","CURRENT","D","DATA","DATABASE","DATABASES","DAYS","DD","DDL","DEDUPLICATE","DEFAULT","DEFINER","DELAY","DELETE","DELETED","DEPENDS","DESC","DESCENDING","DESCRIBE","DETACH","DETACHED","DICTIONARIES","DICTIONARY","DISK","DISTINCT","DIV","DOUBLE_SHA1_HASH","DOUBLE_SHA1_PASSWORD","DROP","ELSE","ENABLED","END","ENFORCED","ENGINE","ENGINES","EPHEMERAL","ESTIMATE","EVENT","EVENTS","EVERY","EXCEPT","EXCHANGE","EXISTS","EXPLAIN","EXPRESSION","EXTENDED","EXTERNAL","FAKE","FALSE","FETCH","FIELDS","FILESYSTEM","FILL","FILTER","FINAL","FIRST","FOLLOWING","FOR","FOREIGN","FORMAT","FREEZE","FROM","FULL","FULLTEXT","FUNCTION","FUNCTIONS","GLOBAL","GRANT","GRANTEES","GRANTS","GRANULARITY","GROUP","GROUPING","GROUPS","H","HASH","HAVING","HDFS","HH","HIERARCHICAL","HOST","HOURS","HTTP","IDENTIFIED","ILIKE","IN","INDEX","INDEXES","INDICES","INFILE","INHERIT","INJECTIVE","INNER","INSERT","INTERPOLATE","INTERSECT","INTERVAL","INTO","INVISIBLE","INVOKER","IP","IS","IS_OBJECT_ID","JOIN","JWT","KERBEROS","KEY","KEYED","KEYS","KILL","KIND","LARGE","LAST","LAYOUT","LDAP","LEADING","LEVEL","LIFETIME","LIGHTWEIGHT","LIKE","LIMIT","LIMITS","LINEAR","LIST","LIVE","LOCAL","M","MASK","MATERIALIZED","MCS","MEMORY","MERGES","METRICS","MI","MICROSECOND","MICROSECONDS","MILLISECONDS","MINUTES","MM","MODIFY","MONTHS","MOVE","MS","MUTATION","N","NAME","NAMED","NANOSECOND","NANOSECONDS","NEXT","NO","NONE","NOT","NO_PASSWORD","NS","NULL","NULLS","OBJECT","OFFSET","ON","ONLY","OPTIMIZE","OPTION","OR","ORDER","OUTER","OUTFILE","OVER","OVERRIDABLE","OVERRIDE","PART","PARTIAL","PARTITION","PARTITIONS","PART_MOVE_TO_SHARD","PASTE","PERIODIC","PERMANENTLY","PERMISSIVE","PERSISTENT","PIPELINE","PLAINTEXT_PASSWORD","PLAN","POLICY","POPULATE","PRECEDING","PRECISION","PREWHERE","PRIMARY","PRIVILEGES","PROCESSLIST","PROFILE","PROJECTION","PROTOBUF","PULL","Q","QQ","QUALIFY","QUARTERS","QUERY","QUOTA","RANDOMIZE","RANDOMIZED","RANGE","READONLY","REALM","RECOMPRESS","RECURSIVE","REFERENCES","REFRESH","REGEXP","REMOVE","RENAME","RESET","RESPECT","RESTORE","RESTRICT","RESTRICTIVE","RESUME","REVOKE","ROLE","ROLES","ROLLBACK","ROLLUP","ROW","ROWS","S","S3","SALT","SAMPLE","SAN","SCHEME","SECONDS","SECURITY","SELECT","SEMI","SEQUENTIAL","SERVER","SET","SETS","SETTING","SETTINGS","SHA256_HASH","SHA256_PASSWORD","SHARD","SHOW","SIGNED","SIMPLE","SNAPSHOT","SOURCE","SPATIAL","SQL","SQL_TSI_DAY","SQL_TSI_HOUR","SQL_TSI_MICROSECOND","SQL_TSI_MILLISECOND","SQL_TSI_MINUTE","SQL_TSI_MONTH","SQL_TSI_NANOSECOND","SQL_TSI_QUARTER","SQL_TSI_SECOND","SQL_TSI_WEEK","SQL_TSI_YEAR","SS","SSH_KEY","SSL_CERTIFICATE","STALENESS","START","STATISTICS","STDOUT","STEP","STORAGE","STRICT","STRICTLY_ASCENDING","SUBPARTITION","SUBPARTITIONS","SUSPEND","SYNC","SYNTAX","SYSTEM","TABLE","TABLES","TAGS","TEMPORARY","TEST","THAN","THEN","TIES","TIME","TO","TOP","TOTALS","TRACKING","TRAILING","TRANSACTION","TREE","TRIGGER","TRUE","TRUNCATE","TTL","TYPE","TYPEOF","UNBOUNDED","UNDROP","UNFREEZE","UNION","UNIQUE","UNSET","UNSIGNED","UNTIL","UPDATE","URL","USE","USING","UUID","VALID","VALUES","VARYING","VIEW","VISIBLE","VOLUME","WATCH","WATERMARK","WEEKS","WHEN","WHERE","WINDOW","WITH","WITH_ITEMINDEX","WK","WRITABLE","WW","YEARS","YY","YYYY","ZKPATH"],_G=["AGGREGATEFUNCTION","ARRAY","BFLOAT16","BIGINT","BIGINT SIGNED","BIGINT UNSIGNED","BINARY","BINARY LARGE OBJECT","BINARY VARYING","BIT","BLOB","BYTE","BYTEA","BOOL","CHAR","CHAR LARGE OBJECT","CHAR VARYING","CHARACTER","CHARACTER LARGE OBJECT","CHARACTER VARYING","CLOB","DEC","DOUBLE","DOUBLE PRECISION","DATE","DATE32","DATETIME","DATETIME32","DATETIME64","DECIMAL","DECIMAL128","DECIMAL256","DECIMAL32","DECIMAL64","DYNAMIC","ENUM","ENUM","ENUM16","ENUM8","FIXED","FLOAT","FIXEDSTRING","FLOAT32","FLOAT64","GEOMETRY","INET4","INET6","INT","INT SIGNED","INT UNSIGNED","INT1","INT1 SIGNED","INT1 UNSIGNED","INTEGER","INTEGER SIGNED","INTEGER UNSIGNED","IPV4","IPV6","INT128","INT16","INT256","INT32","INT64","INT8","INTERVALDAY","INTERVALHOUR","INTERVALMICROSECOND","INTERVALMILLISECOND","INTERVALMINUTE","INTERVALMONTH","INTERVALNANOSECOND","INTERVALQUARTER","INTERVALSECOND","INTERVALWEEK","INTERVALYEAR","JSON","LONGBLOB","LONGTEXT","LINESTRING","LOWCARDINALITY","MEDIUMBLOB","MEDIUMINT","MEDIUMINT SIGNED","MEDIUMINT UNSIGNED","MEDIUMTEXT","MAP","MULTILINESTRING","MULTIPOLYGON","NATIONAL CHAR","NATIONAL CHAR VARYING","NATIONAL CHARACTER","NATIONAL CHARACTER LARGE OBJECT","NATIONAL CHARACTER VARYING","NCHAR","NCHAR LARGE OBJECT","NCHAR VARYING","NUMERIC","NVARCHAR","NESTED","NOTHING","NULLABLE","OBJECT","POINT","POLYGON","REAL","RING","SET","SIGNED","SINGLE","SMALLINT","SMALLINT SIGNED","SMALLINT UNSIGNED","SIMPLEAGGREGATEFUNCTION","STRING","TEXT","TIMESTAMP","TINYBLOB","TINYINT","TINYINT SIGNED","TINYINT UNSIGNED","TINYTEXT","TIME","TIME64","TUPLE","UINT128","UINT16","UINT256","UINT32","UINT64","UINT8","UNSIGNED","UUID","VARBINARY","VARCHAR","VARCHAR2","VARIANT","YEAR","BOOL","BOOLEAN"],bG=W(["SELECT [DISTINCT]","MODIFY QUERY SELECT [DISTINCT]"]),vG=W(["SET","WITH","FROM","SAMPLE","PREWHERE","WHERE","GROUP BY","HAVING","QUALIFY","ORDER BY","LIMIT","SETTINGS","INTO OUTFILE","FORMAT","WINDOW","PARTITION BY","INSERT INTO","VALUES","DEPENDS ON","MOVE {USER | ROLE | QUOTA | SETTINGS PROFILE | ROW POLICY}","GRANT","REVOKE","CHECK GRANT","SET [DEFAULT] ROLE [NONE | ALL | ALL EXCEPT]","DEDUPLICATE BY","MODIFY STATISTICS","TYPE","ALTER USER [IF EXISTS]","ALTER [ROW] POLICY [IF EXISTS]","DROP {USER | ROLE | QUOTA | PROFILE | SETTINGS PROFILE | ROW POLICY | POLICY} [IF EXISTS]"]),$p=W(["CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS]"]),Sc=W(["ALL EXCEPT","ON CLUSTER","UPDATE","SYSTEM RELOAD {DICTIONARIES | DICTIONARY | FUNCTIONS | FUNCTION | ASYNCHRONOUS METRICS}","SYSTEM DROP {DNS CACHE | MARK CACHE | ICEBERG METADATA CACHE | TEXT INDEX DICTIONARY CACHE | TEXT INDEX HEADER CACHE | TEXT INDEX POSTINGS CACHE | REPLICA | DATABASE REPLICA | UNCOMPRESSED CACHE | COMPILED EXPRESSION CACHE | QUERY CONDITION CACHE | QUERY CACHE | FORMAT SCHEMA CACHE | FILESYSTEM CACHE}","SYSTEM FLUSH LOGS","SYSTEM RELOAD {CONFIG | USERS}","SYSTEM SHUTDOWN","SYSTEM KILL","SYSTEM FLUSH DISTRIBUTED","SYSTEM START DISTRIBUTED SENDS","SYSTEM {STOP | START} {LISTEN | MERGES | TTL MERGES | MOVES | FETCHES | REPLICATED SENDS | REPLICATION QUEUES | PULLING REPLICATION LOG}","SYSTEM {SYNC | RESTART | RESTORE} REPLICA","SYSTEM {SYNC | RESTORE} DATABASE REPLICA","SYSTEM RESTART REPLICAS","SYSTEM UNFREEZE","SYSTEM WAIT LOADING PARTS","SYSTEM {LOAD | UNLOAD} PRIMARY KEY","SYSTEM {STOP | START} [REPLICATED] VIEW","SYSTEM {STOP | START} VIEWS","SYSTEM {REFRESH | CANCEL | WAIT} VIEW","WITH NAME","SHOW [CREATE] {TABLE | TEMPORARY TABLE | DICTIONARY | VIEW | DATABASE}","SHOW DATABASES [[NOT] {LIKE | ILIKE}]","SHOW [FULL] [TEMPORARY] TABLES [FROM | IN]","SHOW [EXTENDED] [FULL] COLUMNS {FROM | IN}","ATTACH {TABLE | DICTIONARY | DATABASE} [IF NOT EXISTS]","DETACH {TABLE | DICTIONARY | DATABASE} [IF EXISTS]","PERMANENTLY","SYNC","DROP {DICTIONARY | DATABASE | PROFILE | VIEW | FUNCTION | NAMED COLLECTION} [IF EXISTS]","DROP [TEMPORARY] TABLE [IF EXISTS] [IF EMPTY]","RENAME TO","EXISTS [TEMPORARY] {TABLE | DICTIONARY | DATABASE}","KILL QUERY","OPTIMIZE TABLE","RENAME {TABLE | DICTIONARY | DATABASE}","EXCHANGE {TABLES | DICTIONARIES}","TRUNCATE TABLE [IF EXISTS]","EXECUTE AS","USE","TO","UNDROP TABLE","CREATE {DATABASE | NAMED COLLECTION} [IF NOT EXISTS]","CREATE [OR REPLACE] {VIEW | DICTIONARY} [IF NOT EXISTS]","CREATE MATERIALIZED VIEW [IF NOT EXISTS]","CREATE FUNCTION","CREATE {USER | ROLE | QUOTA | SETTINGS PROFILE} [IF NOT EXISTS | OR REPLACE]","CREATE [ROW] POLICY [IF NOT EXISTS | OR REPLACE]","REPLACE [TEMPORARY] TABLE [IF NOT EXISTS]","ALTER {ROLE | QUOTA | SETTINGS PROFILE} [IF EXISTS]","ALTER [TEMPORARY] TABLE","ALTER NAMED COLLECTION [IF EXISTS]","GRANTEES","NOT IDENTIFIED","RESET AUTHENTICATION METHODS TO NEW","{IDENTIFIED | ADD IDENTIFIED} [WITH | BY]","[ADD | DROP] HOST {LOCAL | NAME | REGEXP | IP | LIKE}","VALID UNTIL","DROP [ALL] {PROFILES | SETTINGS}","{ADD | MODIFY} SETTINGS","ADD PROFILES","APPLY DELETED MASK","IN PARTITION","{ADD | DROP | RENAME | CLEAR | COMMENT | MODIFY | ALTER | MATERIALIZE} COLUMN","{DETACH | DROP | ATTACH | FETCH | MOVE} {PART | PARTITION}","DROP DETACHED {PART | PARTITION}","{FORGET | REPLACE} PARTITION","CLEAR COLUMN","{FREEZE | UNFREEZE} [PARTITION]","CLEAR INDEX","TO {DISK | VOLUME}","[DELETE | REWRITE PARTS] IN PARTITION","{MODIFY | RESET} SETTING","DELETE WHERE","MODIFY ORDER BY","{MODIFY | REMOVE} SAMPLE BY","{ADD | MATERIALIZE | CLEAR} INDEX [IF NOT EXISTS]","DROP INDEX [IF EXISTS]","GRANULARITY","AFTER","FIRST","ADD CONSTRAINT [IF NOT EXISTS]","DROP CONSTRAINT [IF EXISTS]","MODIFY TTL","REMOVE TTL","ADD STATISTICS [IF NOT EXISTS]","{DROP | CLEAR} STATISTICS [IF EXISTS]","MATERIALIZE STATISTICS [ALL | IF EXISTS]","KEYED BY","NOT KEYED","FOR [RANDOMIZED] INTERVAL","AS {PERMISSIVE | RESTRICTIVE}","FOR SELECT","ADD PROJECTION [IF NOT EXISTS]","{DROP | MATERIALIZE | CLEAR} PROJECTION [IF EXISTS]","REFRESH {EVERY | AFTER}","RANDOMIZE FOR","APPEND","APPEND TO","DELETE FROM","EXPLAIN [AST | SYNTAX | QUERY TREE | PLAN | PIPELINE | ESTIMATE | TABLE OVERRIDE]","GRANT ON CLUSTER","GRANT CURRENT GRANTS","WITH GRANT OPTION","REVOKE ON CLUSTER","ADMIN OPTION FOR","CHECK TABLE","PARTITION ID","{DESC | DESCRIBE} TABLE"]),DG=W(["UNION [ALL | DISTINCT]","PARALLEL WITH"]),MG=W(["[GLOBAL] [INNER|LEFT|RIGHT|FULL|CROSS] [OUTER|SEMI|ANTI|ANY|ALL|ASOF] JOIN","[LEFT] ARRAY JOIN"]),PG=W(["{ROWS | RANGE} BETWEEN","ALTER MATERIALIZE STATISTICS"]),wG={name:"clickhouse",tokenizerOptions:{reservedSelect:bG,reservedClauses:[...vG,...$p,...Sc],reservedSetOperations:DG,reservedJoins:MG,reservedKeywordPhrases:PG,reservedKeywords:LG,reservedDataTypes:_G,reservedFunctionNames:CG,extraParens:["[]","{}"],lineCommentTypes:["#","--"],nestedBlockComments:!1,underscoresInNumbers:!0,stringTypes:["$$","''-qq-bs"],identTypes:['""-qq-bs',"``"],paramTypes:{custom:[{regex:String.raw`\{[^:']+:[^}]+\}`,key:e=>{const t=/\{([^:]+):/.exec(e);return t?t[1].trim():e}}]},operators:["%","||","?",":","==","<=>","->"],postProcess:UG},formatOptions:{onelineClauses:[...$p,...Sc],tabularOnelineClauses:Sc}};function UG(e){return e.map((t,n)=>{const r=e[n+1]||Hn,s=e[n-1]||Hn;return t.type===J.RESERVED_SELECT&&(r.type===J.COMMA||s.type===J.RESERVED_CLAUSE||s.type===J.COMMA)?Object.assign(Object.assign({},t),{type:J.RESERVED_KEYWORD}):Wn.SET(t)&&r.type===J.OPEN_PAREN?Object.assign(Object.assign({},t),{type:J.RESERVED_FUNCTION_NAME}):t})}const BG=["ARRAY_AGG","AVG","CORRELATION","COUNT","COUNT_BIG","COVARIANCE","COVARIANCE_SAMP","CUME_DIST","GROUPING","LISTAGG","MAX","MEDIAN","MIN","PERCENTILE_CONT","PERCENTILE_DISC","PERCENT_RANK","REGR_AVGX","REGR_AVGY","REGR_COUNT","REGR_INTERCEPT","REGR_ICPT","REGR_R2","REGR_SLOPE","REGR_SXX","REGR_SXY","REGR_SYY","STDDEV","STDDEV_SAMP","SUM","VARIANCE","VARIANCE_SAMP","XMLAGG","XMLGROUP","ABS","ABSVAL","ACOS","ADD_DAYS","ADD_HOURS","ADD_MINUTES","ADD_MONTHS","ADD_SECONDS","ADD_YEARS","AGE","ARRAY_DELETE","ARRAY_FIRST","ARRAY_LAST","ARRAY_NEXT","ARRAY_PRIOR","ASCII","ASCII_STR","ASIN","ATAN","ATAN2","ATANH","BITAND","BITANDNOT","BITOR","BITXOR","BITNOT","BPCHAR","BSON_TO_JSON","BTRIM","CARDINALITY","CEILING","CEIL","CHARACTER_LENGTH","CHR","COALESCE","COLLATION_KEY","COLLATION_KEY_BIT","COMPARE_DECFLOAT","CONCAT","COS","COSH","COT","CURSOR_ROWCOUNT","DATAPARTITIONNUM","DATE_PART","DATE_TRUNC","DAY","DAYNAME","DAYOFMONTH","DAYOFWEEK","DAYOFWEEK_ISO","DAYOFYEAR","DAYS","DAYS_BETWEEN","DAYS_TO_END_OF_MONTH","DBPARTITIONNUM","DECFLOAT","DECFLOAT_FORMAT","DECODE","DECRYPT_BIN","DECRYPT_CHAR","DEGREES","DEREF","DIFFERENCE","DIGITS","DOUBLE_PRECISION","EMPTY_BLOB","EMPTY_CLOB","EMPTY_DBCLOB","EMPTY_NCLOB","ENCRYPT","EVENT_MON_STATE","EXP","EXTRACT","FIRST_DAY","FLOOR","FROM_UTC_TIMESTAMP","GENERATE_UNIQUE","GETHINT","GREATEST","HASH","HASH4","HASH8","HASHEDVALUE","HEX","HEXTORAW","HOUR","HOURS_BETWEEN","IDENTITY_VAL_LOCAL","IFNULL","INITCAP","INSERT","INSTR","INSTR2","INSTR4","INSTRB","INTNAND","INTNOR","INTNXOR","INTNNOT","ISNULL","JSON_ARRAY","JSON_OBJECT","JSON_QUERY","JSON_TO_BSON","JSON_VALUE","JULIAN_DAY","LAST_DAY","LCASE","LEAST","LEFT","LENGTH","LENGTH2","LENGTH4","LENGTHB","LN","LOCATE","LOCATE_IN_STRING","LOG10","LONG_VARCHAR","LONG_VARGRAPHIC","LOWER","LPAD","LTRIM","MAX","MAX_CARDINALITY","MICROSECOND","MIDNIGHT_SECONDS","MIN","MINUTE","MINUTES_BETWEEN","MOD","MONTH","MONTHNAME","MONTHS_BETWEEN","MULTIPLY_ALT","NEXT_DAY","NEXT_MONTH","NEXT_QUARTER","NEXT_WEEK","NEXT_YEAR","NORMALIZE_DECFLOAT","NOW","NULLIF","NVL","NVL2","OCTET_LENGTH","OVERLAY","PARAMETER","POSITION","POSSTR","POW","POWER","QUANTIZE","QUARTER","QUOTE_IDENT","QUOTE_LITERAL","RADIANS","RAISE_ERROR","RAND","RANDOM","RAWTOHEX","REC2XML","REGEXP_COUNT","REGEXP_EXTRACT","REGEXP_INSTR","REGEXP_LIKE","REGEXP_MATCH_COUNT","REGEXP_REPLACE","REGEXP_SUBSTR","REPEAT","REPLACE","RID","RID_BIT","RIGHT","ROUND","ROUND_TIMESTAMP","RPAD","RTRIM","SECLABEL","SECLABEL_BY_NAME","SECLABEL_TO_CHAR","SECOND","SECONDS_BETWEEN","SIGN","SIN","SINH","SOUNDEX","SPACE","SQRT","STRIP","STRLEFT","STRPOS","STRRIGHT","SUBSTR","SUBSTR2","SUBSTR4","SUBSTRB","SUBSTRING","TABLE_NAME","TABLE_SCHEMA","TAN","TANH","THIS_MONTH","THIS_QUARTER","THIS_WEEK","THIS_YEAR","TIMESTAMP_FORMAT","TIMESTAMP_ISO","TIMESTAMPDIFF","TIMEZONE","TO_CHAR","TO_CLOB","TO_DATE","TO_HEX","TO_MULTI_BYTE","TO_NCHAR","TO_NCLOB","TO_NUMBER","TO_SINGLE_BYTE","TO_TIMESTAMP","TO_UTC_TIMESTAMP","TOTALORDER","TRANSLATE","TRIM","TRIM_ARRAY","TRUNC_TIMESTAMP","TRUNCATE","TRUNC","TYPE_ID","TYPE_NAME","TYPE_SCHEMA","UCASE","UNICODE_STR","UPPER","VALUE","VARCHAR_BIT_FORMAT","VARCHAR_FORMAT","VARCHAR_FORMAT_BIT","VERIFY_GROUP_FOR_USER","VERIFY_ROLE_FOR_USER","VERIFY_TRUSTED_CONTEXT_ROLE_FOR_USER","WEEK","WEEK_ISO","WEEKS_BETWEEN","WIDTH_BUCKET","XMLATTRIBUTES","XMLCOMMENT","XMLCONCAT","XMLDOCUMENT","XMLELEMENT","XMLFOREST","XMLNAMESPACES","XMLPARSE","XMLPI","XMLQUERY","XMLROW","XMLSERIALIZE","XMLTEXT","XMLVALIDATE","XMLXSROBJECTID","XSLTRANSFORM","YEAR","YEARS_BETWEEN","YMD_BETWEEN","BASE_TABLE","JSON_TABLE","UNNEST","XMLTABLE","RANK","DENSE_RANK","NTILE","LAG","LEAD","ROW_NUMBER","FIRST_VALUE","LAST_VALUE","NTH_VALUE","RATIO_TO_REPORT","CAST"],jG=["ACTIVATE","ADD","AFTER","ALIAS","ALL","ALLOCATE","ALLOW","ALTER","AND","ANY","AS","ASENSITIVE","ASSOCIATE","ASUTIME","AT","ATTRIBUTES","AUDIT","AUTHORIZATION","AUX","AUXILIARY","BEFORE","BEGIN","BETWEEN","BINARY","BUFFERPOOL","BY","CACHE","CALL","CALLED","CAPTURE","CARDINALITY","CASCADED","CASE","CAST","CHECK","CLONE","CLOSE","CLUSTER","COLLECTION","COLLID","COLUMN","COMMENT","COMMIT","CONCAT","CONDITION","CONNECT","CONNECTION","CONSTRAINT","CONTAINS","CONTINUE","COUNT","COUNT_BIG","CREATE","CROSS","CURRENT","CURRENT_DATE","CURRENT_LC_CTYPE","CURRENT_PATH","CURRENT_SCHEMA","CURRENT_SERVER","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_TIMEZONE","CURRENT_USER","CURSOR","CYCLE","DATA","DATABASE","DATAPARTITIONNAME","DATAPARTITIONNUM","DAY","DAYS","DB2GENERAL","DB2GENRL","DB2SQL","DBINFO","DBPARTITIONNAME","DBPARTITIONNUM","DEALLOCATE","DECLARE","DEFAULT","DEFAULTS","DEFINITION","DELETE","DENSERANK","DENSE_RANK","DESCRIBE","DESCRIPTOR","DETERMINISTIC","DIAGNOSTICS","DISABLE","DISALLOW","DISCONNECT","DISTINCT","DO","DOCUMENT","DROP","DSSIZE","DYNAMIC","EACH","EDITPROC","ELSE","ELSEIF","ENABLE","ENCODING","ENCRYPTION","END","END-EXEC","ENDING","ERASE","ESCAPE","EVERY","EXCEPT","EXCEPTION","EXCLUDING","EXCLUSIVE","EXECUTE","EXISTS","EXIT","EXPLAIN","EXTENDED","EXTERNAL","EXTRACT","FENCED","FETCH","FIELDPROC","FILE","FINAL","FIRST1","FOR","FOREIGN","FREE","FROM","FULL","FUNCTION","GENERAL","GENERATED","GET","GLOBAL","GO","GOTO","GRANT","GRAPHIC","GROUP","HANDLER","HASH","HASHED_VALUE","HAVING","HINT","HOLD","HOUR","HOURS","IDENTITY","IF","IMMEDIATE","IMPORT","IN","INCLUDING","INCLUSIVE","INCREMENT","INDEX","INDICATOR","INDICATORS","INF","INFINITY","INHERIT","INNER","INOUT","INSENSITIVE","INSERT","INTEGRITY","INTERSECT","INTO","IS","ISNULL","ISOBID","ISOLATION","ITERATE","JAR","JAVA","JOIN","KEEP","KEY","LABEL","LANGUAGE","LAST3","LATERAL","LC_CTYPE","LEAVE","LEFT","LIKE","LIMIT","LINKTYPE","LOCAL","LOCALDATE","LOCALE","LOCALTIME","LOCALTIMESTAMP","LOCATOR","LOCATORS","LOCK","LOCKMAX","LOCKSIZE","LOOP","MAINTAINED","MATERIALIZED","MAXVALUE","MICROSECOND","MICROSECONDS","MINUTE","MINUTES","MINVALUE","MODE","MODIFIES","MONTH","MONTHS","NAN","NEW","NEW_TABLE","NEXTVAL","NO","NOCACHE","NOCYCLE","NODENAME","NODENUMBER","NOMAXVALUE","NOMINVALUE","NONE","NOORDER","NORMALIZED","NOT2","NOTNULL","NULL","NULLS","NUMPARTS","OBID","OF","OFF","OFFSET","OLD","OLD_TABLE","ON","OPEN","OPTIMIZATION","OPTIMIZE","OPTION","OR","ORDER","OUT","OUTER","OVER","OVERRIDING","PACKAGE","PADDED","PAGESIZE","PARAMETER","PART","PARTITION","PARTITIONED","PARTITIONING","PARTITIONS","PASSWORD","PATH","PERCENT","PIECESIZE","PLAN","POSITION","PRECISION","PREPARE","PREVVAL","PRIMARY","PRIQTY","PRIVILEGES","PROCEDURE","PROGRAM","PSID","PUBLIC","QUERY","QUERYNO","RANGE","RANK","READ","READS","RECOVERY","REFERENCES","REFERENCING","REFRESH","RELEASE","RENAME","REPEAT","RESET","RESIGNAL","RESTART","RESTRICT","RESULT","RESULT_SET_LOCATOR","RETURN","RETURNS","REVOKE","RIGHT","ROLE","ROLLBACK","ROUND_CEILING","ROUND_DOWN","ROUND_FLOOR","ROUND_HALF_DOWN","ROUND_HALF_EVEN","ROUND_HALF_UP","ROUND_UP","ROUTINE","ROW","ROWNUMBER","ROWS","ROWSET","ROW_NUMBER","RRN","RUN","SAVEPOINT","SCHEMA","SCRATCHPAD","SCROLL","SEARCH","SECOND","SECONDS","SECQTY","SECURITY","SELECT","SENSITIVE","SEQUENCE","SESSION","SESSION_USER","SET","SIGNAL","SIMPLE","SNAN","SOME","SOURCE","SPECIFIC","SQL","SQLID","STACKED","STANDARD","START","STARTING","STATEMENT","STATIC","STATMENT","STAY","STOGROUP","STORES","STYLE","SUBSTRING","SUMMARY","SYNONYM","SYSFUN","SYSIBM","SYSPROC","SYSTEM","SYSTEM_USER","TABLE","TABLESPACE","THEN","TO","TRANSACTION","TRIGGER","TRIM","TRUNCATE","TYPE","UNDO","UNION","UNIQUE","UNTIL","UPDATE","USAGE","USER","USING","VALIDPROC","VALUE","VALUES","VARIABLE","VARIANT","VCAT","VERSION","VIEW","VOLATILE","VOLUMES","WHEN","WHENEVER","WHERE","WHILE","WITH","WITHOUT","WLM","WRITE","XMLELEMENT","XMLEXISTS","XMLNAMESPACES","YEAR","YEARS"],kG=["ARRAY","BIGINT","BINARY","BLOB","BOOLEAN","CCSID","CHAR","CHARACTER","CLOB","DATE","DATETIME","DBCLOB","DEC","DECIMAL","DOUBLE","DOUBLE PRECISION","FLOAT","FLOAT4","FLOAT8","GRAPHIC","INT","INT2","INT4","INT8","INTEGER","INTERVAL","LONG VARCHAR","LONG VARGRAPHIC","NCHAR","NCHR","NCLOB","NVARCHAR","NUMERIC","SMALLINT","REAL","TIME","TIMESTAMP","VARBINARY","VARCHAR","VARGRAPHIC"],FG=W(["SELECT [ALL | DISTINCT]"]),GG=W(["WITH","FROM","WHERE","GROUP BY","HAVING","PARTITION BY","ORDER BY [INPUT SEQUENCE]","LIMIT","OFFSET","FETCH NEXT","FOR UPDATE [OF]","FOR {READ | FETCH} ONLY","FOR {RR | CS | UR | RS} [USE AND KEEP {SHARE | UPDATE | EXCLUSIVE} LOCKS]","WAIT FOR OUTCOME","SKIP LOCKED DATA","INTO","INSERT INTO","VALUES","SET","MERGE INTO","WHEN [NOT] MATCHED [THEN]","UPDATE SET","INSERT"]),Vp=W(["CREATE [GLOBAL TEMPORARY | EXTERNAL] TABLE [IF NOT EXISTS]"]),hc=W(["CREATE [OR REPLACE] VIEW","UPDATE","WHERE CURRENT OF","WITH {RR | RS | CS | UR}","DELETE FROM","DROP TABLE [IF EXISTS]","ALTER TABLE","ADD [COLUMN]","DROP [COLUMN]","RENAME COLUMN","ALTER [COLUMN]","SET DATA TYPE","SET NOT NULL","DROP {DEFAULT | GENERATED | NOT NULL}","TRUNCATE [TABLE]","ALLOCATE","ALTER AUDIT POLICY","ALTER BUFFERPOOL","ALTER DATABASE PARTITION GROUP","ALTER DATABASE","ALTER EVENT MONITOR","ALTER FUNCTION","ALTER HISTOGRAM TEMPLATE","ALTER INDEX","ALTER MASK","ALTER METHOD","ALTER MODULE","ALTER NICKNAME","ALTER PACKAGE","ALTER PERMISSION","ALTER PROCEDURE","ALTER SCHEMA","ALTER SECURITY LABEL COMPONENT","ALTER SECURITY POLICY","ALTER SEQUENCE","ALTER SERVER","ALTER SERVICE CLASS","ALTER STOGROUP","ALTER TABLESPACE","ALTER THRESHOLD","ALTER TRIGGER","ALTER TRUSTED CONTEXT","ALTER TYPE","ALTER USAGE LIST","ALTER USER MAPPING","ALTER VIEW","ALTER WORK ACTION SET","ALTER WORK CLASS SET","ALTER WORKLOAD","ALTER WRAPPER","ALTER XSROBJECT","ALTER STOGROUP","ALTER TABLESPACE","ALTER TRIGGER","ALTER TRUSTED CONTEXT","ALTER VIEW","ASSOCIATE [RESULT SET] {LOCATOR | LOCATORS}","AUDIT","BEGIN DECLARE SECTION","CALL","CLOSE","COMMENT ON","COMMIT [WORK]","CONNECT","CREATE [OR REPLACE] [PUBLIC] ALIAS","CREATE AUDIT POLICY","CREATE BUFFERPOOL","CREATE DATABASE PARTITION GROUP","CREATE EVENT MONITOR","CREATE [OR REPLACE] FUNCTION","CREATE FUNCTION MAPPING","CREATE HISTOGRAM TEMPLATE","CREATE [UNIQUE] INDEX","CREATE INDEX EXTENSION","CREATE [OR REPLACE] MASK","CREATE [SPECIFIC] METHOD","CREATE [OR REPLACE] MODULE","CREATE [OR REPLACE] NICKNAME","CREATE [OR REPLACE] PERMISSION","CREATE [OR REPLACE] PROCEDURE","CREATE ROLE","CREATE SCHEMA","CREATE SECURITY LABEL [COMPONENT]","CREATE SECURITY POLICY","CREATE [OR REPLACE] SEQUENCE","CREATE SERVICE CLASS","CREATE SERVER","CREATE STOGROUP","CREATE SYNONYM","CREATE [LARGE | REGULAR | {SYSTEM | USER} TEMPORARY] TABLESPACE","CREATE THRESHOLD","CREATE {TRANSFORM | TRANSFORMS} FOR","CREATE [OR REPLACE] TRIGGER","CREATE TRUSTED CONTEXT","CREATE [OR REPLACE] TYPE","CREATE TYPE MAPPING","CREATE USAGE LIST","CREATE USER MAPPING FOR","CREATE [OR REPLACE] VARIABLE","CREATE WORK ACTION SET","CREATE WORK CLASS SET","CREATE WORKLOAD","CREATE WRAPPER","DECLARE","DECLARE GLOBAL TEMPORARY TABLE","DESCRIBE [INPUT | OUTPUT]","DISCONNECT","DROP [PUBLIC] ALIAS","DROP AUDIT POLICY","DROP BUFFERPOOL","DROP DATABASE PARTITION GROUP","DROP EVENT MONITOR","DROP [SPECIFIC] FUNCTION","DROP FUNCTION MAPPING","DROP HISTOGRAM TEMPLATE","DROP INDEX [EXTENSION]","DROP MASK","DROP [SPECIFIC] METHOD","DROP MODULE","DROP NICKNAME","DROP PACKAGE","DROP PERMISSION","DROP [SPECIFIC] PROCEDURE","DROP ROLE","DROP SCHEMA","DROP SECURITY LABEL [COMPONENT]","DROP SECURITY POLICY","DROP SEQUENCE","DROP SERVER","DROP SERVICE CLASS","DROP STOGROUP","DROP TABLE HIERARCHY","DROP {TABLESPACE | TABLESPACES}","DROP {TRANSFORM | TRANSFORMS}","DROP THRESHOLD","DROP TRIGGER","DROP TRUSTED CONTEXT","DROP TYPE [MAPPING]","DROP USAGE LIST","DROP USER MAPPING FOR","DROP VARIABLE","DROP VIEW [HIERARCHY]","DROP WORK {ACTION | CLASS} SET","DROP WORKLOAD","DROP WRAPPER","DROP XSROBJECT","END DECLARE SECTION","EXECUTE [IMMEDIATE]","EXPLAIN {PLAN [SECTION] | ALL}","FETCH [FROM]","FLUSH {BUFFERPOOL | BUFFERPOOLS} ALL","FLUSH EVENT MONITOR","FLUSH FEDERATED CACHE","FLUSH OPTIMIZATION PROFILE CACHE","FLUSH PACKAGE CACHE [DYNAMIC]","FLUSH AUTHENTICATION CACHE [FOR ALL]","FREE LOCATOR","GET DIAGNOSTICS","GOTO","GRANT","INCLUDE","ITERATE","LEAVE","LOCK TABLE","LOOP","OPEN","PIPE","PREPARE","REFRESH TABLE","RELEASE","RELEASE [TO] SAVEPOINT","RENAME [TABLE | INDEX | STOGROUP | TABLESPACE]","REPEAT","RESIGNAL","RETURN","REVOKE","ROLLBACK [WORK] [TO SAVEPOINT]","SAVEPOINT","SET COMPILATION ENVIRONMENT","SET CONNECTION","SET CURRENT","SET ENCRYPTION PASSWORD","SET EVENT MONITOR STATE","SET INTEGRITY","SET PASSTHRU","SET PATH","SET ROLE","SET SCHEMA","SET SERVER OPTION","SET {SESSION AUTHORIZATION | SESSION_USER}","SET USAGE LIST","SIGNAL","TRANSFER OWNERSHIP OF","WHENEVER {NOT FOUND | SQLERROR | SQLWARNING}","WHILE"]),HG=W(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),WG=W(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN"]),YG=W(["ON DELETE","ON UPDATE","SET NULL","{ROWS | RANGE} BETWEEN"]),$G=W([]),VG={name:"db2",tokenizerOptions:{reservedSelect:FG,reservedClauses:[...GG,...Vp,...hc],reservedSetOperations:HG,reservedJoins:WG,reservedKeywordPhrases:YG,reservedDataTypePhrases:$G,reservedKeywords:jG,reservedDataTypes:kG,reservedFunctionNames:BG,extraParens:["[]"],stringTypes:[{quote:"''-qq",prefixes:["G","N","U&"]},{quote:"''-raw",prefixes:["X","BX","GX","UX"],requirePrefix:!0}],identTypes:['""-qq'],identChars:{first:"@#$",rest:"@#$"},paramTypes:{positional:!0,named:[":"]},paramChars:{first:"@#$",rest:"@#$"},operators:["**","%","|","&","^","~","¬=","¬>","¬<","!>","!<","^=","^>","^<","||","->","=>"]},formatOptions:{onelineClauses:[...Vp,...hc],tabularOnelineClauses:hc}},zG=["ARRAY_AGG","AVG","CORR","CORRELATION","COUNT","COUNT_BIG","COVAR_POP","COVARIANCE","COVAR","COVAR_SAMP","COVARIANCE_SAMP","EVERY","GROUPING","JSON_ARRAYAGG","JSON_OBJECTAGG","LISTAGG","MAX","MEDIAN","MIN","PERCENTILE_CONT","PERCENTILE_DISC","REGR_AVGX","REGR_AVGY","REGR_COUNT","REGR_INTERCEPT","REGR_R2","REGR_SLOPE","REGR_SXX","REGR_SXY","REGR_SYY","SOME","STDDEV_POP","STDDEV","STDDEV_SAMP","SUM","VAR_POP","VARIANCE","VAR","VAR_SAMP","VARIANCE_SAMP","XMLAGG","XMLGROUP","ABS","ABSVAL","ACOS","ADD_DAYS","ADD_HOURS","ADD_MINUTES","ADD_MONTHS","ADD_SECONDS","ADD_YEARS","ANTILOG","ARRAY_MAX_CARDINALITY","ARRAY_TRIM","ASCII","ASIN","ATAN","ATAN2","ATANH","BASE64_DECODE","BASE64_ENCODE","BIT_LENGTH","BITAND","BITANDNOT","BITNOT","BITOR","BITXOR","BSON_TO_JSON","CARDINALITY","CEIL","CEILING","CHAR_LENGTH","CHARACTER_LENGTH","CHR","COALESCE","COMPARE_DECFLOAT","CONCAT","CONTAINS","COS","COSH","COT","CURDATE","CURTIME","DATABASE","DATAPARTITIONNAME","DATAPARTITIONNUM","DAY","DAYNAME","DAYOFMONTH","DAYOFWEEK_ISO","DAYOFWEEK","DAYOFYEAR","DAYS","DBPARTITIONNAME","DBPARTITIONNUM","DECFLOAT_FORMAT","DECFLOAT_SORTKEY","DECRYPT_BINARY","DECRYPT_BIT","DECRYPT_CHAR","DECRYPT_DB","DEGREES","DIFFERENCE","DIGITS","DLCOMMENT","DLLINKTYPE","DLURLCOMPLETE","DLURLPATH","DLURLPATHONLY","DLURLSCHEME","DLURLSERVER","DLVALUE","DOUBLE_PRECISION","DOUBLE","ENCRPYT","ENCRYPT_AES","ENCRYPT_AES256","ENCRYPT_RC2","ENCRYPT_TDES","EXP","EXTRACT","FIRST_DAY","FLOOR","GENERATE_UNIQUE","GET_BLOB_FROM_FILE","GET_CLOB_FROM_FILE","GET_DBCLOB_FROM_FILE","GET_XML_FILE","GETHINT","GREATEST","HASH_MD5","HASH_ROW","HASH_SHA1","HASH_SHA256","HASH_SHA512","HASH_VALUES","HASHED_VALUE","HEX","HEXTORAW","HOUR","HTML_ENTITY_DECODE","HTML_ENTITY_ENCODE","HTTP_DELETE_BLOB","HTTP_DELETE","HTTP_GET_BLOB","HTTP_GET","HTTP_PATCH_BLOB","HTTP_PATCH","HTTP_POST_BLOB","HTTP_POST","HTTP_PUT_BLOB","HTTP_PUT","IDENTITY_VAL_LOCAL","IFNULL","INSERT","INSTR","INTERPRET","ISFALSE","ISNOTFALSE","ISNOTTRUE","ISTRUE","JSON_ARRAY","JSON_OBJECT","JSON_QUERY","JSON_TO_BSON","JSON_UPDATE","JSON_VALUE","JULIAN_DAY","LAND","LAST_DAY","LCASE","LEAST","LEFT","LENGTH","LN","LNOT","LOCATE_IN_STRING","LOCATE","LOG10","LOR","LOWER","LPAD","LTRIM","MAX_CARDINALITY","MAX","MICROSECOND","MIDNIGHT_SECONDS","MIN","MINUTE","MOD","MONTH","MONTHNAME","MONTHS_BETWEEN","MQREAD","MQREADCLOB","MQRECEIVE","MQRECEIVECLOB","MQSEND","MULTIPLY_ALT","NEXT_DAY","NORMALIZE_DECFLOAT","NOW","NULLIF","NVL","OCTET_LENGTH","OVERLAY","PI","POSITION","POSSTR","POW","POWER","QUANTIZE","QUARTER","RADIANS","RAISE_ERROR","RANDOM","RAND","REGEXP_COUNT","REGEXP_INSTR","REGEXP_REPLACE","REGEXP_SUBSTR","REPEAT","REPLACE","RID","RIGHT","ROUND_TIMESTAMP","ROUND","RPAD","RRN","RTRIM","SCORE","SECOND","SIGN","SIN","SINH","SOUNDEX","SPACE","SQRT","STRIP","STRLEFT","STRPOS","STRRIGHT","SUBSTR","SUBSTRING","TABLE_NAME","TABLE_SCHEMA","TAN","TANH","TIMESTAMP_FORMAT","TIMESTAMP_ISO","TIMESTAMPDIFF_BIG","TIMESTAMPDIFF","TO_CHAR","TO_CLOB","TO_DATE","TO_NUMBER","TO_TIMESTAMP","TOTALORDER","TRANSLATE","TRIM_ARRAY","TRIM","TRUNC_TIMESTAMP","TRUNC","TRUNCATE","UCASE","UPPER","URL_DECODE","URL_ENCODE","VALUE","VARBINARY_FORMAT","VARCHAR_BIT_FORMAT","VARCHAR_FORMAT_BINARY","VARCHAR_FORMAT","VERIFY_GROUP_FOR_USER","WEEK_ISO","WEEK","WRAP","XMLATTRIBUTES","XMLCOMMENT","XMLCONCAT","XMLDOCUMENT","XMLELEMENT","XMLFOREST","XMLNAMESPACES","XMLPARSE","XMLPI","XMLROW","XMLSERIALIZE","XMLTEXT","XMLVALIDATE","XOR","XSLTRANSFORM","YEAR","ZONED","BASE_TABLE","HTTP_DELETE_BLOB_VERBOSE","HTTP_DELETE_VERBOSE","HTTP_GET_BLOB_VERBOSE","HTTP_GET_VERBOSE","HTTP_PATCH_BLOB_VERBOSE","HTTP_PATCH_VERBOSE","HTTP_POST_BLOB_VERBOSE","HTTP_POST_VERBOSE","HTTP_PUT_BLOB_VERBOSE","HTTP_PUT_VERBOSE","JSON_TABLE","MQREADALL","MQREADALLCLOB","MQRECEIVEALL","MQRECEIVEALLCLOB","XMLTABLE","UNPACK","CUME_DIST","DENSE_RANK","FIRST_VALUE","LAG","LAST_VALUE","LEAD","NTH_VALUE","NTILE","PERCENT_RANK","RANK","RATIO_TO_REPORT","ROW_NUMBER","CAST"],XG=["ABSENT","ACCORDING","ACCTNG","ACTION","ACTIVATE","ADD","ALIAS","ALL","ALLOCATE","ALLOW","ALTER","AND","ANY","APPEND","APPLNAME","ARRAY","ARRAY_AGG","ARRAY_TRIM","AS","ASC","ASENSITIVE","ASSOCIATE","ATOMIC","ATTACH","ATTRIBUTES","AUTHORIZATION","AUTONOMOUS","BEFORE","BEGIN","BETWEEN","BIND","BSON","BUFFERPOOL","BY","CACHE","CALL","CALLED","CARDINALITY","CASE","CAST","CHECK","CL","CLOSE","CLUSTER","COLLECT","COLLECTION","COLUMN","COMMENT","COMMIT","COMPACT","COMPARISONS","COMPRESS","CONCAT","CONCURRENT","CONDITION","CONNECT","CONNECT_BY_ROOT","CONNECTION","CONSTANT","CONSTRAINT","CONTAINS","CONTENT","CONTINUE","COPY","COUNT","COUNT_BIG","CREATE","CREATEIN","CROSS","CUBE","CUME_DIST","CURRENT","CURRENT_DATE","CURRENT_PATH","CURRENT_SCHEMA","CURRENT_SERVER","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_TIMEZONE","CURRENT_USER","CURSOR","CYCLE","DATABASE","DATAPARTITIONNAME","DATAPARTITIONNUM","DAY","DAYS","DB2GENERAL","DB2GENRL","DB2SQL","DBINFO","DBPARTITIONNAME","DBPARTITIONNUM","DEACTIVATE","DEALLOCATE","DECLARE","DEFAULT","DEFAULTS","DEFER","DEFINE","DEFINITION","DELETE","DELETING","DENSE_RANK","DENSERANK","DESC","DESCRIBE","DESCRIPTOR","DETACH","DETERMINISTIC","DIAGNOSTICS","DISABLE","DISALLOW","DISCONNECT","DISTINCT","DO","DOCUMENT","DROP","DYNAMIC","EACH","ELSE","ELSEIF","EMPTY","ENABLE","ENCODING","ENCRYPTION","END","END-EXEC","ENDING","ENFORCED","ERROR","ESCAPE","EVERY","EXCEPT","EXCEPTION","EXCLUDING","EXCLUSIVE","EXECUTE","EXISTS","EXIT","EXTEND","EXTERNAL","EXTRACT","FALSE","FENCED","FETCH","FIELDPROC","FILE","FINAL","FIRST_VALUE","FOR","FOREIGN","FORMAT","FREE","FREEPAGE","FROM","FULL","FUNCTION","GBPCACHE","GENERAL","GENERATED","GET","GLOBAL","GO","GOTO","GRANT","GROUP","HANDLER","HASH","HASH_ROW","HASHED_VALUE","HAVING","HINT","HOLD","HOUR","HOURS","IDENTITY","IF","IGNORE","IMMEDIATE","IMPLICITLY","IN","INCLUDE","INCLUDING","INCLUSIVE","INCREMENT","INDEX","INDEXBP","INDICATOR","INF","INFINITY","INHERIT","INLINE","INNER","INOUT","INSENSITIVE","INSERT","INSERTING","INTEGRITY","INTERPRET","INTERSECT","INTO","IS","ISNULL","ISOLATION","ITERATE","JAVA","JOIN","JSON","JSON_ARRAY","JSON_ARRAYAGG","JSON_EXISTS","JSON_OBJECT","JSON_OBJECTAGG","JSON_QUERY","JSON_TABLE","JSON_VALUE","KEEP","KEY","KEYS","LABEL","LAG","LANGUAGE","LAST_VALUE","LATERAL","LEAD","LEAVE","LEFT","LEVEL2","LIKE","LIMIT","LINKTYPE","LISTAGG","LOCAL","LOCALDATE","LOCALTIME","LOCALTIMESTAMP","LOCATION","LOCATOR","LOCK","LOCKSIZE","LOG","LOGGED","LOOP","MAINTAINED","MASK","MATCHED","MATERIALIZED","MAXVALUE","MERGE","MICROSECOND","MICROSECONDS","MINPCTUSED","MINUTE","MINUTES","MINVALUE","MIRROR","MIXED","MODE","MODIFIES","MONTH","MONTHS","NAMESPACE","NAN","NATIONAL","NCHAR","NCLOB","NESTED","NEW","NEW_TABLE","NEXTVAL","NO","NOCACHE","NOCYCLE","NODENAME","NODENUMBER","NOMAXVALUE","NOMINVALUE","NONE","NOORDER","NORMALIZED","NOT","NOTNULL","NTH_VALUE","NTILE","NULL","NULLS","NVARCHAR","OBID","OBJECT","OF","OFF","OFFSET","OLD","OLD_TABLE","OMIT","ON","ONLY","OPEN","OPTIMIZE","OPTION","OR","ORDER","ORDINALITY","ORGANIZE","OUT","OUTER","OVER","OVERLAY","OVERRIDING","PACKAGE","PADDED","PAGE","PAGESIZE","PARAMETER","PART","PARTITION","PARTITIONED","PARTITIONING","PARTITIONS","PASSING","PASSWORD","PATH","PCTFREE","PERCENT_RANK","PERCENTILE_CONT","PERCENTILE_DISC","PERIOD","PERMISSION","PIECESIZE","PIPE","PLAN","POSITION","PREPARE","PREVVAL","PRIMARY","PRIOR","PRIQTY","PRIVILEGES","PROCEDURE","PROGRAM","PROGRAMID","QUERY","RANGE","RANK","RATIO_TO_REPORT","RCDFMT","READ","READS","RECOVERY","REFERENCES","REFERENCING","REFRESH","REGEXP_LIKE","RELEASE","RENAME","REPEAT","RESET","RESIGNAL","RESTART","RESULT","RESULT_SET_LOCATOR","RETURN","RETURNING","RETURNS","REVOKE","RID","RIGHT","ROLLBACK","ROLLUP","ROUTINE","ROW","ROW_NUMBER","ROWNUMBER","ROWS","RRN","RUN","SAVEPOINT","SBCS","SCALAR","SCHEMA","SCRATCHPAD","SCROLL","SEARCH","SECOND","SECONDS","SECQTY","SECURED","SELECT","SENSITIVE","SEQUENCE","SESSION","SESSION_USER","SET","SIGNAL","SIMPLE","SKIP","SNAN","SOME","SOURCE","SPECIFIC","SQL","SQLID","SQLIND_DEFAULT","SQLIND_UNASSIGNED","STACKED","START","STARTING","STATEMENT","STATIC","STOGROUP","SUBSTRING","SUMMARY","SYNONYM","SYSTEM_TIME","SYSTEM_USER","TABLE","TABLESPACE","TABLESPACES","TAG","THEN","THREADSAFE","TO","TRANSACTION","TRANSFER","TRIGGER","TRIM","TRIM_ARRAY","TRUE","TRUNCATE","TRY_CAST","TYPE","UNDO","UNION","UNIQUE","UNIT","UNKNOWN","UNNEST","UNTIL","UPDATE","UPDATING","URI","USAGE","USE","USER","USERID","USING","VALUE","VALUES","VARIABLE","VARIANT","VCAT","VERSION","VERSIONING","VIEW","VOLATILE","WAIT","WHEN","WHENEVER","WHERE","WHILE","WITH","WITHIN","WITHOUT","WRAPPED","WRAPPER","WRITE","WRKSTNNAME","XMLAGG","XMLATTRIBUTES","XMLCAST","XMLCOMMENT","XMLCONCAT","XMLDOCUMENT","XMLELEMENT","XMLFOREST","XMLGROUP","XMLNAMESPACES","XMLPARSE","XMLPI","XMLROW","XMLSERIALIZE","XMLTABLE","XMLTEXT","XMLVALIDATE","XSLTRANSFORM","XSROBJECT","YEAR","YEARS","YES","ZONE"],KG=["ARRAY","BIGINT","BINARY","BIT","BLOB","BOOLEAN","CCSID","CHAR","CHARACTER","CLOB","DATA","DATALINK","DATE","DBCLOB","DECFLOAT","DECIMAL","DEC","DOUBLE","DOUBLE PRECISION","FLOAT","GRAPHIC","INT","INTEGER","LONG","NUMERIC","REAL","ROWID","SMALLINT","TIME","TIMESTAMP","VARBINARY","VARCHAR","VARGRAPHIC","XML"],qG=W(["SELECT [ALL | DISTINCT]"]),JG=W(["WITH [RECURSIVE]","INTO","FROM","WHERE","GROUP BY","HAVING","PARTITION BY","ORDER [SIBLINGS] BY [INPUT SEQUENCE]","LIMIT","OFFSET","FETCH {FIRST | NEXT}","FOR UPDATE [OF]","FOR READ ONLY","OPTIMIZE FOR","INSERT INTO","VALUES","SET","MERGE INTO","WHEN [NOT] MATCHED [THEN]","UPDATE SET","DELETE","INSERT","FOR SYSTEM NAME"]),zp=W(["CREATE [OR REPLACE] TABLE"]),Rc=W(["CREATE [OR REPLACE] [RECURSIVE] VIEW","UPDATE","WHERE CURRENT OF","WITH {NC | RR | RS | CS | UR}","DELETE FROM","DROP TABLE","ALTER TABLE","ADD [COLUMN]","ALTER [COLUMN]","DROP [COLUMN]","SET DATA TYPE","SET {GENERATED ALWAYS | GENERATED BY DEFAULT}","SET NOT NULL","SET {NOT HIDDEN | IMPLICITLY HIDDEN}","SET FIELDPROC","DROP {DEFAULT | NOT NULL | GENERATED | IDENTITY | ROW CHANGE TIMESTAMP | FIELDPROC}","TRUNCATE [TABLE]","SET [CURRENT] SCHEMA","SET CURRENT_SCHEMA","ALLOCATE CURSOR","ALLOCATE [SQL] DESCRIPTOR [LOCAL | GLOBAL] SQL","ALTER [SPECIFIC] {FUNCTION | PROCEDURE}","ALTER {MASK | PERMISSION | SEQUENCE | TRIGGER}","ASSOCIATE [RESULT SET] {LOCATOR | LOCATORS}","BEGIN DECLARE SECTION","CALL","CLOSE","COMMENT ON {ALIAS | COLUMN | CONSTRAINT | INDEX | MASK | PACKAGE | PARAMETER | PERMISSION | SEQUENCE | TABLE | TRIGGER | VARIABLE | XSROBJECT}","COMMENT ON [SPECIFIC] {FUNCTION | PROCEDURE | ROUTINE}","COMMENT ON PARAMETER SPECIFIC {FUNCTION | PROCEDURE | ROUTINE}","COMMENT ON [TABLE FUNCTION] RETURN COLUMN","COMMENT ON [TABLE FUNCTION] RETURN COLUMN SPECIFIC [PROCEDURE | ROUTINE]","COMMIT [WORK] [HOLD]","CONNECT [TO | RESET] USER","CREATE [OR REPLACE] {ALIAS | FUNCTION | MASK | PERMISSION | PROCEDURE | SEQUENCE | TRIGGER | VARIABLE}","CREATE [ENCODED VECTOR] INDEX","CREATE UNIQUE [WHERE NOT NULL] INDEX","CREATE SCHEMA","CREATE TYPE","DEALLOCATE [SQL] DESCRIPTOR [LOCAL | GLOBAL]","DECLARE CURSOR","DECLARE GLOBAL TEMPORARY TABLE","DECLARE","DESCRIBE CURSOR","DESCRIBE INPUT","DESCRIBE [OUTPUT]","DESCRIBE {PROCEDURE | ROUTINE}","DESCRIBE TABLE","DISCONNECT ALL [SQL]","DISCONNECT [CURRENT]","DROP {ALIAS | INDEX | MASK | PACKAGE | PERMISSION | SCHEMA | SEQUENCE | TABLE | TYPE | VARIABLE | XSROBJECT} [IF EXISTS]","DROP [SPECIFIC] {FUNCTION | PROCEDURE | ROUTINE} [IF EXISTS]","END DECLARE SECTION","EXECUTE [IMMEDIATE]","FREE LOCATOR","GET [SQL] DESCRIPTOR [LOCAL | GLOBAL]","GET [CURRENT | STACKED] DIAGNOSTICS","GRANT {ALL [PRIVILEGES] | ALTER | EXECUTE} ON {FUNCTION | PROCEDURE | ROUTINE | PACKAGE | SCHEMA | SEQUENCE | TABLE | TYPE | VARIABLE | XSROBJECT}","HOLD LOCATOR","INCLUDE","LABEL ON {ALIAS | COLUMN | CONSTRAINT | INDEX | MASK | PACKAGE | PERMISSION | SEQUENCE | TABLE | TRIGGER | VARIABLE | XSROBJECT}","LABEL ON [SPECIFIC] {FUNCTION | PROCEDURE | ROUTINE}","LOCK TABLE","OPEN","PREPARE","REFRESH TABLE","RELEASE","RELEASE [TO] SAVEPOINT","RENAME [TABLE | INDEX] TO","REVOKE {ALL [PRIVILEGES] | ALTER | EXECUTE} ON {FUNCTION | PROCEDURE | ROUTINE | PACKAGE | SCHEMA | SEQUENCE | TABLE | TYPE | VARIABLE | XSROBJECT}","ROLLBACK [WORK] [HOLD | TO SAVEPOINT]","SAVEPOINT","SET CONNECTION","SET CURRENT {DEBUG MODE | DECFLOAT ROUNDING MODE | DEGREE | IMPLICIT XMLPARSE OPTION | TEMPORAL SYSTEM_TIME}","SET [SQL] DESCRIPTOR [LOCAL | GLOBAL]","SET ENCRYPTION PASSWORD","SET OPTION","SET {[CURRENT [FUNCTION]] PATH | CURRENT_PATH}","SET RESULT SETS [WITH RETURN [TO CALLER | TO CLIENT]]","SET SESSION AUTHORIZATION","SET SESSION_USER","SET TRANSACTION","SIGNAL SQLSTATE [VALUE]","TAG","TRANSFER OWNERSHIP OF","WHENEVER {NOT FOUND | SQLERROR | SQLWARNING}"]),QG=W(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),ZG=W(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","[LEFT | RIGHT] EXCEPTION JOIN","{INNER | CROSS} JOIN"]),eH=W(["ON DELETE","ON UPDATE","SET NULL","{ROWS | RANGE} BETWEEN"]),tH=W([]),nH={name:"db2i",tokenizerOptions:{reservedSelect:qG,reservedClauses:[...JG,...zp,...Rc],reservedSetOperations:QG,reservedJoins:ZG,reservedKeywordPhrases:eH,reservedDataTypePhrases:tH,reservedKeywords:XG,reservedDataTypes:KG,reservedFunctionNames:zG,nestedBlockComments:!0,extraParens:["[]"],stringTypes:[{quote:"''-qq",prefixes:["G","N"]},{quote:"''-raw",prefixes:["X","BX","GX","UX"],requirePrefix:!0}],identTypes:['""-qq'],identChars:{first:"@#$",rest:"@#$"},paramTypes:{positional:!0,named:[":"]},paramChars:{first:"@#$",rest:"@#$"},operators:["**","¬=","¬>","¬<","!>","!<","||","=>"]},formatOptions:{onelineClauses:[...zp,...Rc],tabularOnelineClauses:Rc}},rH=["ABS","ACOS","ADD","ADD_PARQUET_KEY","AGE","AGGREGATE","ALIAS","ALL_PROFILING_OUTPUT","ANY_VALUE","APPLY","APPROX_COUNT_DISTINCT","APPROX_QUANTILE","ARBITRARY","ARGMAX","ARGMIN","ARG_MAX","ARG_MAX_NULL","ARG_MIN","ARG_MIN_NULL","ARRAY_AGG","ARRAY_AGGR","ARRAY_AGGREGATE","ARRAY_APPEND","ARRAY_APPLY","ARRAY_CAT","ARRAY_CONCAT","ARRAY_CONTAINS","ARRAY_COSINE_SIMILARITY","ARRAY_CROSS_PRODUCT","ARRAY_DISTANCE","ARRAY_DISTINCT","ARRAY_DOT_PRODUCT","ARRAY_EXTRACT","ARRAY_FILTER","ARRAY_GRADE_UP","ARRAY_HAS","ARRAY_HAS_ALL","ARRAY_HAS_ANY","ARRAY_INDEXOF","ARRAY_INNER_PRODUCT","ARRAY_INTERSECT","ARRAY_LENGTH","ARRAY_POP_BACK","ARRAY_POP_FRONT","ARRAY_POSITION","ARRAY_PREPEND","ARRAY_PUSH_BACK","ARRAY_PUSH_FRONT","ARRAY_REDUCE","ARRAY_RESIZE","ARRAY_REVERSE","ARRAY_REVERSE_SORT","ARRAY_SELECT","ARRAY_SLICE","ARRAY_SORT","ARRAY_TO_JSON","ARRAY_TO_STRING","ARRAY_TRANSFORM","ARRAY_UNIQUE","ARRAY_VALUE","ARRAY_WHERE","ARRAY_ZIP","ARROW_SCAN","ARROW_SCAN_DUMB","ASCII","ASIN","ATAN","ATAN2","AVG","BASE64","BIN","BITSTRING","BITSTRING_AGG","BIT_AND","BIT_COUNT","BIT_LENGTH","BIT_OR","BIT_POSITION","BIT_XOR","BOOL_AND","BOOL_OR","CARDINALITY","CBRT","CEIL","CEILING","CENTURY","CHECKPOINT","CHR","COLLATIONS","COL_DESCRIPTION","COMBINE","CONCAT","CONCAT_WS","CONSTANT_OR_NULL","CONTAINS","COPY_DATABASE","CORR","COS","COT","COUNT","COUNT_IF","COUNT_STAR","COVAR_POP","COVAR_SAMP","CREATE_SORT_KEY","CURRENT_CATALOG","CURRENT_DATABASE","CURRENT_DATE","CURRENT_LOCALTIME","CURRENT_LOCALTIMESTAMP","CURRENT_QUERY","CURRENT_ROLE","CURRENT_SCHEMA","CURRENT_SCHEMAS","CURRENT_SETTING","CURRENT_USER","CURRVAL","DAMERAU_LEVENSHTEIN","DATABASE_LIST","DATABASE_SIZE","DATEDIFF","DATEPART","DATESUB","DATETRUNC","DATE_ADD","DATE_DIFF","DATE_PART","DATE_SUB","DATE_TRUNC","DAY","DAYNAME","DAYOFMONTH","DAYOFWEEK","DAYOFYEAR","DECADE","DECODE","DEGREES","DISABLE_CHECKPOINT_ON_SHUTDOWN","DISABLE_OBJECT_CACHE","DISABLE_OPTIMIZER","DISABLE_PRINT_PROGRESS_BAR","DISABLE_PROFILE","DISABLE_PROFILING","DISABLE_PROGRESS_BAR","DISABLE_VERIFICATION","DISABLE_VERIFY_EXTERNAL","DISABLE_VERIFY_FETCH_ROW","DISABLE_VERIFY_PARALLELISM","DISABLE_VERIFY_SERIALIZER","DIVIDE","DUCKDB_COLUMNS","DUCKDB_CONSTRAINTS","DUCKDB_DATABASES","DUCKDB_DEPENDENCIES","DUCKDB_EXTENSIONS","DUCKDB_FUNCTIONS","DUCKDB_INDEXES","DUCKDB_KEYWORDS","DUCKDB_MEMORY","DUCKDB_OPTIMIZERS","DUCKDB_SCHEMAS","DUCKDB_SECRETS","DUCKDB_SEQUENCES","DUCKDB_SETTINGS","DUCKDB_TABLES","DUCKDB_TEMPORARY_FILES","DUCKDB_TYPES","DUCKDB_VIEWS","EDIT","EDITDIST3","ELEMENT_AT","ENABLE_CHECKPOINT_ON_SHUTDOWN","ENABLE_OBJECT_CACHE","ENABLE_OPTIMIZER","ENABLE_PRINT_PROGRESS_BAR","ENABLE_PROFILE","ENABLE_PROFILING","ENABLE_PROGRESS_BAR","ENABLE_VERIFICATION","ENCODE","ENDS_WITH","ENTROPY","ENUM_CODE","ENUM_FIRST","ENUM_LAST","ENUM_RANGE","ENUM_RANGE_BOUNDARY","EPOCH","EPOCH_MS","EPOCH_NS","EPOCH_US","ERA","ERROR","EVEN","EXP","FACTORIAL","FAVG","FDIV","FILTER","FINALIZE","FIRST","FLATTEN","FLOOR","FMOD","FORCE_CHECKPOINT","FORMAT","FORMATREADABLEDECIMALSIZE","FORMATREADABLESIZE","FORMAT_BYTES","FORMAT_PG_TYPE","FORMAT_TYPE","FROM_BASE64","FROM_BINARY","FROM_HEX","FROM_JSON","FROM_JSON_STRICT","FSUM","FUNCTIONS","GAMMA","GCD","GENERATE_SERIES","GENERATE_SUBSCRIPTS","GEN_RANDOM_UUID","GEOMEAN","GEOMETRIC_MEAN","GETENV","GET_BIT","GET_BLOCK_SIZE","GET_CURRENT_TIME","GET_CURRENT_TIMESTAMP","GLOB","GRADE_UP","GREATEST","GREATEST_COMMON_DIVISOR","GROUP_CONCAT","HAMMING","HASH","HAS_ANY_COLUMN_PRIVILEGE","HAS_COLUMN_PRIVILEGE","HAS_DATABASE_PRIVILEGE","HAS_FOREIGN_DATA_WRAPPER_PRIVILEGE","HAS_FUNCTION_PRIVILEGE","HAS_LANGUAGE_PRIVILEGE","HAS_SCHEMA_PRIVILEGE","HAS_SEQUENCE_PRIVILEGE","HAS_SERVER_PRIVILEGE","HAS_TABLESPACE_PRIVILEGE","HAS_TABLE_PRIVILEGE","HEX","HISTOGRAM","HOUR","ICU_CALENDAR_NAMES","ICU_SORT_KEY","ILIKE_ESCAPE","IMPORT_DATABASE","INDEX_SCAN","INET_CLIENT_ADDR","INET_CLIENT_PORT","INET_SERVER_ADDR","INET_SERVER_PORT","INSTR","IN_SEARCH_PATH","ISFINITE","ISINF","ISNAN","ISODOW","ISOYEAR","JACCARD","JARO_SIMILARITY","JARO_WINKLER_SIMILARITY","JSON_ARRAY","JSON_ARRAY_LENGTH","JSON_CONTAINS","JSON_DESERIALIZE_SQL","JSON_EXECUTE_SERIALIZED_SQL","JSON_EXTRACT","JSON_EXTRACT_PATH","JSON_EXTRACT_PATH_TEXT","JSON_EXTRACT_STRING","JSON_GROUP_ARRAY","JSON_GROUP_OBJECT","JSON_GROUP_STRUCTURE","JSON_KEYS","JSON_MERGE_PATCH","JSON_OBJECT","JSON_QUOTE","JSON_SERIALIZE_PLAN","JSON_SERIALIZE_SQL","JSON_STRUCTURE","JSON_TRANSFORM","JSON_TRANSFORM_STRICT","JSON_TYPE","JSON_VALID","JULIAN","KAHAN_SUM","KURTOSIS","KURTOSIS_POP","LAST","LAST_DAY","LCASE","LCM","LEAST","LEAST_COMMON_MULTIPLE","LEFT","LEFT_GRAPHEME","LEN","LENGTH","LENGTH_GRAPHEME","LEVENSHTEIN","LGAMMA","LIKE_ESCAPE","LIST","LISTAGG","LIST_AGGR","LIST_AGGREGATE","LIST_ANY_VALUE","LIST_APPEND","LIST_APPLY","LIST_APPROX_COUNT_DISTINCT","LIST_AVG","LIST_BIT_AND","LIST_BIT_OR","LIST_BIT_XOR","LIST_BOOL_AND","LIST_BOOL_OR","LIST_CAT","LIST_CONCAT","LIST_CONTAINS","LIST_COSINE_SIMILARITY","LIST_COUNT","LIST_DISTANCE","LIST_DISTINCT","LIST_DOT_PRODUCT","LIST_ELEMENT","LIST_ENTROPY","LIST_EXTRACT","LIST_FILTER","LIST_FIRST","LIST_GRADE_UP","LIST_HAS","LIST_HAS_ALL","LIST_HAS_ANY","LIST_HISTOGRAM","LIST_INDEXOF","LIST_INNER_PRODUCT","LIST_INTERSECT","LIST_KURTOSIS","LIST_KURTOSIS_POP","LIST_LAST","LIST_MAD","LIST_MAX","LIST_MEDIAN","LIST_MIN","LIST_MODE","LIST_PACK","LIST_POSITION","LIST_PREPEND","LIST_PRODUCT","LIST_REDUCE","LIST_RESIZE","LIST_REVERSE","LIST_REVERSE_SORT","LIST_SELECT","LIST_SEM","LIST_SKEWNESS","LIST_SLICE","LIST_SORT","LIST_STDDEV_POP","LIST_STDDEV_SAMP","LIST_STRING_AGG","LIST_SUM","LIST_TRANSFORM","LIST_UNIQUE","LIST_VALUE","LIST_VAR_POP","LIST_VAR_SAMP","LIST_WHERE","LIST_ZIP","LN","LOG","LOG10","LOG2","LOWER","LPAD","LSMODE","LTRIM","MAD","MAKE_DATE","MAKE_TIME","MAKE_TIMESTAMP","MAKE_TIMESTAMPTZ","MAP","MAP_CONCAT","MAP_ENTRIES","MAP_EXTRACT","MAP_FROM_ENTRIES","MAP_KEYS","MAP_VALUES","MAX","MAX_BY","MD5","MD5_NUMBER","MD5_NUMBER_LOWER","MD5_NUMBER_UPPER","MEAN","MEDIAN","METADATA_INFO","MICROSECOND","MILLENNIUM","MILLISECOND","MIN","MINUTE","MIN_BY","MISMATCHES","MOD","MODE","MONTH","MONTHNAME","MULTIPLY","NEXTAFTER","NEXTVAL","NFC_NORMALIZE","NOT_ILIKE_ESCAPE","NOT_LIKE_ESCAPE","NOW","NULLIF","OBJ_DESCRIPTION","OCTET_LENGTH","ORD","PARQUET_FILE_METADATA","PARQUET_KV_METADATA","PARQUET_METADATA","PARQUET_SCAN","PARQUET_SCHEMA","PARSE_DIRNAME","PARSE_DIRPATH","PARSE_FILENAME","PARSE_PATH","PG_COLLATION_IS_VISIBLE","PG_CONF_LOAD_TIME","PG_CONVERSION_IS_VISIBLE","PG_FUNCTION_IS_VISIBLE","PG_GET_CONSTRAINTDEF","PG_GET_EXPR","PG_GET_VIEWDEF","PG_HAS_ROLE","PG_IS_OTHER_TEMP_SCHEMA","PG_MY_TEMP_SCHEMA","PG_OPCLASS_IS_VISIBLE","PG_OPERATOR_IS_VISIBLE","PG_OPFAMILY_IS_VISIBLE","PG_POSTMASTER_START_TIME","PG_SIZE_PRETTY","PG_TABLE_IS_VISIBLE","PG_TIMEZONE_NAMES","PG_TS_CONFIG_IS_VISIBLE","PG_TS_DICT_IS_VISIBLE","PG_TS_PARSER_IS_VISIBLE","PG_TS_TEMPLATE_IS_VISIBLE","PG_TYPEOF","PG_TYPE_IS_VISIBLE","PI","PLATFORM","POSITION","POW","POWER","PRAGMA_COLLATIONS","PRAGMA_DATABASE_SIZE","PRAGMA_METADATA_INFO","PRAGMA_PLATFORM","PRAGMA_SHOW","PRAGMA_STORAGE_INFO","PRAGMA_TABLE_INFO","PRAGMA_USER_AGENT","PRAGMA_VERSION","PREFIX","PRINTF","PRODUCT","QUANTILE","QUANTILE_CONT","QUANTILE_DISC","QUARTER","RADIANS","RANDOM","RANGE","READFILE","READ_BLOB","READ_CSV","READ_CSV_AUTO","READ_JSON","READ_JSON_AUTO","READ_JSON_OBJECTS","READ_JSON_OBJECTS_AUTO","READ_NDJSON","READ_NDJSON_AUTO","READ_NDJSON_OBJECTS","READ_PARQUET","READ_TEXT","REDUCE","REGEXP_ESCAPE","REGEXP_EXTRACT","REGEXP_EXTRACT_ALL","REGEXP_FULL_MATCH","REGEXP_MATCHES","REGEXP_REPLACE","REGEXP_SPLIT_TO_ARRAY","REGEXP_SPLIT_TO_TABLE","REGR_AVGX","REGR_AVGY","REGR_COUNT","REGR_INTERCEPT","REGR_R2","REGR_SLOPE","REGR_SXX","REGR_SXY","REGR_SYY","REPEAT","REPEAT_ROW","REPLACE","RESERVOIR_QUANTILE","REVERSE","RIGHT","RIGHT_GRAPHEME","ROUND","ROUNDBANKERS","ROUND_EVEN","ROW","ROW_TO_JSON","RPAD","RTRIM","SECOND","SEM","SEQ_SCAN","SESSION_USER","SETSEED","SET_BIT","SHA256","SHA3","SHELL_ADD_SCHEMA","SHELL_ESCAPE_CRNL","SHELL_IDQUOTE","SHELL_MODULE_SCHEMA","SHELL_PUTSNL","SHOBJ_DESCRIPTION","SHOW","SHOW_DATABASES","SHOW_TABLES","SHOW_TABLES_EXPANDED","SIGN","SIGNBIT","SIN","SKEWNESS","SNIFF_CSV","SPLIT","SPLIT_PART","SQL_AUTO_COMPLETE","SQRT","STARTS_WITH","STATS","STDDEV","STDDEV_POP","STDDEV_SAMP","STORAGE_INFO","STRFTIME","STRING_AGG","STRING_SPLIT","STRING_SPLIT_REGEX","STRING_TO_ARRAY","STRIP_ACCENTS","STRLEN","STRPOS","STRPTIME","STRUCT_EXTRACT","STRUCT_INSERT","STRUCT_PACK","STR_SPLIT","STR_SPLIT_REGEX","SUBSTR","SUBSTRING","SUBSTRING_GRAPHEME","SUBTRACT","SUFFIX","SUM","SUMKAHAN","SUMMARY","SUM_NO_OVERFLOW","TABLE_INFO","TAN","TEST_ALL_TYPES","TEST_VECTOR_TYPES","TIMEZONE","TIMEZONE_HOUR","TIMEZONE_MINUTE","TIME_BUCKET","TODAY","TO_BASE","TO_BASE64","TO_BINARY","TO_CENTURIES","TO_DAYS","TO_DECADES","TO_HEX","TO_HOURS","TO_JSON","TO_MICROSECONDS","TO_MILLENNIA","TO_MILLISECONDS","TO_MINUTES","TO_MONTHS","TO_SECONDS","TO_TIMESTAMP","TO_WEEKS","TO_YEARS","TRANSACTION_TIMESTAMP","TRANSLATE","TRIM","TRUNC","TRY_STRPTIME","TXID_CURRENT","TYPEOF","UCASE","UNBIN","UNHEX","UNICODE","UNION_EXTRACT","UNION_TAG","UNION_VALUE","UNNEST","UNPIVOT_LIST","UPPER","USER","USER_AGENT","UUID","VARIANCE","VAR_POP","VAR_SAMP","VECTOR_TYPE","VERIFY_EXTERNAL","VERIFY_FETCH_ROW","VERIFY_PARALLELISM","VERIFY_SERIALIZER","VERSION","WEEK","WEEKDAY","WEEKOFYEAR","WHICH_SECRET","WRITEFILE","XOR","YEAR","YEARWEEK","CAST","COALESCE","RANK","ROW_NUMBER"],oH=["ALL","ANALYSE","ANALYZE","AND","ANY","AS","ASC","ATTACH","ASYMMETRIC","BOTH","CASE","CAST","CHECK","COLLATE","COLUMN","CONSTRAINT","CREATE","DEFAULT","DEFERRABLE","DESC","DESCRIBE","DETACH","DISTINCT","DO","ELSE","END","EXCEPT","FALSE","FETCH","FOR","FOREIGN","FROM","GRANT","GROUP","HAVING","IN","INITIALLY","INTERSECT","INTO","IS","LATERAL","LEADING","LIMIT","NOT","NULL","OFFSET","ON","ONLY","OR","ORDER","PIVOT","PIVOT_LONGER","PIVOT_WIDER","PLACING","PRIMARY","REFERENCES","RETURNING","SELECT","SHOW","SOME","SUMMARIZE","SYMMETRIC","TABLE","THEN","TO","TRAILING","TRUE","UNION","UNIQUE","UNPIVOT","USING","VARIADIC","WHEN","WHERE","WINDOW","WITH"],sH=["ARRAY","BIGINT","BINARY","BIT","BITSTRING","BLOB","BOOL","BOOLEAN","BPCHAR","BYTEA","CHAR","DATE","DATETIME","DEC","DECIMAL","DOUBLE","ENUM","FLOAT","FLOAT4","FLOAT8","GUID","HUGEINT","INET","INT","INT1","INT128","INT16","INT2","INT32","INT4","INT64","INT8","INTEGER","INTEGRAL","INTERVAL","JSON","LIST","LOGICAL","LONG","MAP","NUMERIC","NVARCHAR","OID","REAL","ROW","SHORT","SIGNED","SMALLINT","STRING","STRUCT","TEXT","TIME","TIMESTAMP_MS","TIMESTAMP_NS","TIMESTAMP_S","TIMESTAMP_US","TIMESTAMP","TIMESTAMPTZ","TIMETZ","TINYINT","UBIGINT","UHUGEINT","UINT128","UINT16","UINT32","UINT64","UINT8","UINTEGER","UNION","USMALLINT","UTINYINT","UUID","VARBINARY","VARCHAR"],iH=W(["SELECT [ALL | DISTINCT]"]),aH=W(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY [ALL]","HAVING","WINDOW","PARTITION BY","ORDER BY [ALL]","LIMIT","OFFSET","USING SAMPLE","QUALIFY","INSERT [OR REPLACE] INTO","VALUES","DEFAULT VALUES","SET","RETURNING"]),Xp=W(["CREATE [OR REPLACE] [TEMPORARY | TEMP] TABLE [IF NOT EXISTS]"]),Ac=W(["UPDATE","ON CONFLICT","DELETE FROM","DROP TABLE [IF EXISTS]","TRUNCATE","ALTER TABLE","ADD [COLUMN] [IF NOT EXISTS]","ADD PRIMARY KEY","DROP [COLUMN] [IF EXISTS]","ALTER [COLUMN]","RENAME [COLUMN]","RENAME TO","SET [DATA] TYPE","{SET | DROP} DEFAULT","{SET | DROP} NOT NULL","CREATE [OR REPLACE] [TEMPORARY | TEMP] {MACRO | FUNCTION}","DROP MACRO [TABLE] [IF EXISTS]","DROP FUNCTION [IF EXISTS]","CREATE [UNIQUE] INDEX [IF NOT EXISTS]","DROP INDEX [IF EXISTS]","CREATE [OR REPLACE] SCHEMA [IF NOT EXISTS]","DROP SCHEMA [IF EXISTS]","CREATE [OR REPLACE] [PERSISTENT | TEMPORARY] SECRET [IF NOT EXISTS]","DROP [PERSISTENT | TEMPORARY] SECRET [IF EXISTS]","CREATE [OR REPLACE] [TEMPORARY | TEMP] SEQUENCE","DROP SEQUENCE [IF EXISTS]","CREATE [OR REPLACE] [TEMPORARY | TEMP] VIEW [IF NOT EXISTS]","DROP VIEW [IF EXISTS]","ALTER VIEW","CREATE TYPE","DROP TYPE [IF EXISTS]","ANALYZE","ATTACH [DATABASE] [IF NOT EXISTS]","DETACH [DATABASE] [IF EXISTS]","CALL","[FORCE] CHECKPOINT","COMMENT ON [TABLE | COLUMN | VIEW | INDEX | SEQUENCE | TYPE | MACRO | MACRO TABLE]","COPY [FROM DATABASE]","DESCRIBE","EXPORT DATABASE","IMPORT DATABASE","INSTALL","LOAD","PIVOT","PIVOT_WIDER","UNPIVOT","EXPLAIN [ANALYZE]","SET {LOCAL | SESSION | GLOBAL}","RESET [LOCAL | SESSION | GLOBAL]","{SET | RESET} VARIABLE","SUMMARIZE","BEGIN TRANSACTION","ROLLBACK","COMMIT","ABORT","USE","VACUUM [ANALYZE]","PREPARE","EXECUTE","DEALLOCATE [PREPARE]"]),lH=W(["UNION [ALL | BY NAME]","EXCEPT [ALL]","INTERSECT [ALL]"]),cH=W(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","{NATURAL | ASOF} [INNER] JOIN","{NATURAL | ASOF} {LEFT | RIGHT | FULL} [OUTER] JOIN","POSITIONAL JOIN","ANTI JOIN","SEMI JOIN"]),dH=W(["{ROWS | RANGE | GROUPS} BETWEEN","SIMILAR TO","IS [NOT] DISTINCT FROM"]),uH=W(["TIMESTAMP WITH TIME ZONE"]),EH={name:"duckdb",tokenizerOptions:{reservedSelect:iH,reservedClauses:[...aH,...Xp,...Ac],reservedSetOperations:lH,reservedJoins:cH,reservedKeywordPhrases:dH,reservedDataTypePhrases:uH,supportsXor:!0,reservedKeywords:oH,reservedDataTypes:sH,reservedFunctionNames:rH,nestedBlockComments:!0,extraParens:["[]","{}"],underscoresInNumbers:!0,stringTypes:["$$","''-qq",{quote:"''-qq-bs",prefixes:["E"],requirePrefix:!0},{quote:"''-raw",prefixes:["B","X"],requirePrefix:!0}],identTypes:['""-qq'],identChars:{rest:"$"},paramTypes:{positional:!0,numbered:["$"],quoted:["$"]},operators:["//","%","**","^","!","&","|","~","<<",">>","::","==","->","->>",":",":=","=>","~~","!~~","~~*","!~~*","~~~","~","!~","~*","!~*","^@","||",">>=","<<="]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...Xp,...Ac],tabularOnelineClauses:Ac}},fH=["ABS","ACOS","ASIN","ATAN","BIN","BROUND","CBRT","CEIL","CEILING","CONV","COS","DEGREES","EXP","FACTORIAL","FLOOR","GREATEST","HEX","LEAST","LN","LOG","LOG10","LOG2","NEGATIVE","PI","PMOD","POSITIVE","POW","POWER","RADIANS","RAND","ROUND","SHIFTLEFT","SHIFTRIGHT","SHIFTRIGHTUNSIGNED","SIGN","SIN","SQRT","TAN","UNHEX","WIDTH_BUCKET","ARRAY_CONTAINS","MAP_KEYS","MAP_VALUES","SIZE","SORT_ARRAY","BINARY","CAST","ADD_MONTHS","DATE","DATE_ADD","DATE_FORMAT","DATE_SUB","DATEDIFF","DAY","DAYNAME","DAYOFMONTH","DAYOFYEAR","EXTRACT","FROM_UNIXTIME","FROM_UTC_TIMESTAMP","HOUR","LAST_DAY","MINUTE","MONTH","MONTHS_BETWEEN","NEXT_DAY","QUARTER","SECOND","TIMESTAMP","TO_DATE","TO_UTC_TIMESTAMP","TRUNC","UNIX_TIMESTAMP","WEEKOFYEAR","YEAR","ASSERT_TRUE","COALESCE","IF","ISNOTNULL","ISNULL","NULLIF","NVL","ASCII","BASE64","CHARACTER_LENGTH","CHR","CONCAT","CONCAT_WS","CONTEXT_NGRAMS","DECODE","ELT","ENCODE","FIELD","FIND_IN_SET","FORMAT_NUMBER","GET_JSON_OBJECT","IN_FILE","INITCAP","INSTR","LCASE","LENGTH","LEVENSHTEIN","LOCATE","LOWER","LPAD","LTRIM","NGRAMS","OCTET_LENGTH","PARSE_URL","PRINTF","QUOTE","REGEXP_EXTRACT","REGEXP_REPLACE","REPEAT","REVERSE","RPAD","RTRIM","SENTENCES","SOUNDEX","SPACE","SPLIT","STR_TO_MAP","SUBSTR","SUBSTRING","TRANSLATE","TRIM","UCASE","UNBASE64","UPPER","MASK","MASK_FIRST_N","MASK_HASH","MASK_LAST_N","MASK_SHOW_FIRST_N","MASK_SHOW_LAST_N","AES_DECRYPT","AES_ENCRYPT","CRC32","CURRENT_DATABASE","CURRENT_USER","HASH","JAVA_METHOD","LOGGED_IN_USER","MD5","REFLECT","SHA","SHA1","SHA2","SURROGATE_KEY","VERSION","AVG","COLLECT_LIST","COLLECT_SET","CORR","COUNT","COVAR_POP","COVAR_SAMP","HISTOGRAM_NUMERIC","MAX","MIN","NTILE","PERCENTILE","PERCENTILE_APPROX","REGR_AVGX","REGR_AVGY","REGR_COUNT","REGR_INTERCEPT","REGR_R2","REGR_SLOPE","REGR_SXX","REGR_SXY","REGR_SYY","STDDEV_POP","STDDEV_SAMP","SUM","VAR_POP","VAR_SAMP","VARIANCE","EXPLODE","INLINE","JSON_TUPLE","PARSE_URL_TUPLE","POSEXPLODE","STACK","LEAD","LAG","FIRST_VALUE","LAST_VALUE","RANK","ROW_NUMBER","DENSE_RANK","CUME_DIST","PERCENT_RANK","NTILE"],pH=["ADD","ADMIN","AFTER","ANALYZE","ARCHIVE","ASC","BEFORE","BUCKET","BUCKETS","CASCADE","CHANGE","CLUSTER","CLUSTERED","CLUSTERSTATUS","COLLECTION","COLUMNS","COMMENT","COMPACT","COMPACTIONS","COMPUTE","CONCATENATE","CONTINUE","DATA","DATABASES","DATETIME","DAY","DBPROPERTIES","DEFERRED","DEFINED","DELIMITED","DEPENDENCY","DESC","DIRECTORIES","DIRECTORY","DISABLE","DISTRIBUTE","ELEM_TYPE","ENABLE","ESCAPED","EXCLUSIVE","EXPLAIN","EXPORT","FIELDS","FILE","FILEFORMAT","FIRST","FORMAT","FORMATTED","FUNCTIONS","HOLD_DDLTIME","HOUR","IDXPROPERTIES","IGNORE","INDEX","INDEXES","INPATH","INPUTDRIVER","INPUTFORMAT","ITEMS","JAR","KEYS","KEY_TYPE","LIMIT","LINES","LOAD","LOCATION","LOCK","LOCKS","LOGICAL","LONG","MAPJOIN","MATERIALIZED","METADATA","MINUS","MINUTE","MONTH","MSCK","NOSCAN","NO_DROP","OFFLINE","OPTION","OUTPUTDRIVER","OUTPUTFORMAT","OVERWRITE","OWNER","PARTITIONED","PARTITIONS","PLUS","PRETTY","PRINCIPALS","PROTECTION","PURGE","READ","READONLY","REBUILD","RECORDREADER","RECORDWRITER","RELOAD","RENAME","REPAIR","REPLACE","REPLICATION","RESTRICT","REWRITE","ROLE","ROLES","SCHEMA","SCHEMAS","SECOND","SEMI","SERDE","SERDEPROPERTIES","SERVER","SETS","SHARED","SHOW","SHOW_DATABASE","SKEWED","SORT","SORTED","SSL","STATISTICS","STORED","STREAMTABLE","STRING","TABLES","TBLPROPERTIES","TEMPORARY","TERMINATED","TINYINT","TOUCH","TRANSACTIONS","UNARCHIVE","UNDO","UNIONTYPE","UNLOCK","UNSET","UNSIGNED","URI","USE","UTC","UTCTIMESTAMP","VALUE_TYPE","VIEW","WHILE","YEAR","AUTOCOMMIT","ISOLATION","LEVEL","OFFSET","SNAPSHOT","TRANSACTION","WORK","WRITE","ABORT","KEY","LAST","NORELY","NOVALIDATE","NULLS","RELY","VALIDATE","DETAIL","DOW","EXPRESSION","OPERATOR","QUARTER","SUMMARY","VECTORIZATION","WEEK","YEARS","MONTHS","WEEKS","DAYS","HOURS","MINUTES","SECONDS","TIMESTAMPTZ","ZONE","ALL","ALTER","AND","AS","AUTHORIZATION","BETWEEN","BOTH","BY","CASE","CAST","COLUMN","CONF","CREATE","CROSS","CUBE","CURRENT","CURRENT_DATE","CURRENT_TIMESTAMP","CURSOR","DATABASE","DELETE","DESCRIBE","DISTINCT","DROP","ELSE","END","EXCHANGE","EXISTS","EXTENDED","EXTERNAL","FALSE","FETCH","FOLLOWING","FOR","FROM","FULL","FUNCTION","GRANT","GROUP","GROUPING","HAVING","IF","IMPORT","IN","INNER","INSERT","INTERSECT","INTO","IS","JOIN","LATERAL","LEFT","LESS","LIKE","LOCAL","MACRO","MORE","NONE","NOT","NULL","OF","ON","OR","ORDER","OUT","OUTER","OVER","PARTIALSCAN","PARTITION","PERCENT","PRECEDING","PRESERVE","PROCEDURE","RANGE","READS","REDUCE","REVOKE","RIGHT","ROLLUP","ROW","ROWS","SELECT","SET","TABLE","TABLESAMPLE","THEN","TO","TRANSFORM","TRIGGER","TRUE","TRUNCATE","UNBOUNDED","UNION","UNIQUEJOIN","UPDATE","USER","USING","UTC_TMESTAMP","VALUES","WHEN","WHERE","WINDOW","WITH","COMMIT","ONLY","REGEXP","RLIKE","ROLLBACK","START","CACHE","CONSTRAINT","FOREIGN","PRIMARY","REFERENCES","DAYOFWEEK","EXTRACT","FLOOR","VIEWS","TIME","SYNC","TEXTFILE","SEQUENCEFILE","ORC","CSV","TSV","PARQUET","AVRO","RCFILE","JSONFILE","INPUTFORMAT","OUTPUTFORMAT"],TH=["ARRAY","BIGINT","BINARY","BOOLEAN","CHAR","DATE","DECIMAL","DOUBLE","FLOAT","INT","INTEGER","INTERVAL","MAP","NUMERIC","PRECISION","SMALLINT","STRUCT","TIMESTAMP","VARCHAR"],SH=W(["SELECT [ALL | DISTINCT]"]),hH=W(["WITH","FROM","WHERE","GROUP BY","HAVING","WINDOW","PARTITION BY","ORDER BY","SORT BY","CLUSTER BY","DISTRIBUTE BY","LIMIT","INSERT INTO [TABLE]","VALUES","SET","MERGE INTO","WHEN [NOT] MATCHED [THEN]","UPDATE SET","INSERT [VALUES]","INSERT OVERWRITE [LOCAL] DIRECTORY","LOAD DATA [LOCAL] INPATH","[OVERWRITE] INTO TABLE"]),Kp=W(["CREATE [TEMPORARY] [EXTERNAL] TABLE [IF NOT EXISTS]"]),mc=W(["CREATE [MATERIALIZED] VIEW [IF NOT EXISTS]","UPDATE","DELETE FROM","DROP TABLE [IF EXISTS]","ALTER TABLE","RENAME TO","TRUNCATE [TABLE]","ALTER","CREATE","USE","DESCRIBE","DROP","FETCH","SHOW","STORED AS","STORED BY","ROW FORMAT"]),RH=W(["UNION [ALL | DISTINCT]"]),AH=W(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","LEFT SEMI JOIN"]),mH=W(["{ROWS | RANGE} BETWEEN"]),gH=W([]),IH={name:"hive",tokenizerOptions:{reservedSelect:SH,reservedClauses:[...hH,...Kp,...mc],reservedSetOperations:RH,reservedJoins:AH,reservedKeywordPhrases:mH,reservedDataTypePhrases:gH,reservedKeywords:pH,reservedDataTypes:TH,reservedFunctionNames:fH,extraParens:["[]"],stringTypes:['""-bs',"''-bs"],identTypes:["``"],variableTypes:[{quote:"{}",prefixes:["$"],requirePrefix:!0}],operators:["%","~","^","|","&","<=>","==","!","||"]},formatOptions:{onelineClauses:[...Kp,...mc],tabularOnelineClauses:mc}};function ll(e){return e.map((t,n)=>{const r=e[n+1]||Hn;if(Wn.SET(t)&&r.text==="(")return Object.assign(Object.assign({},t),{type:J.RESERVED_FUNCTION_NAME});const s=e[n-1]||Hn;return Wn.VALUES(t)&&s.text==="="?Object.assign(Object.assign({},t),{type:J.RESERVED_FUNCTION_NAME}):t})}const OH=["ACCESSIBLE","ADD","ALL","ALTER","ANALYZE","AND","AS","ASC","ASENSITIVE","BEFORE","BETWEEN","BOTH","BY","CALL","CASCADE","CASE","CHANGE","CHECK","COLLATE","COLUMN","CONDITION","CONSTRAINT","CONTINUE","CONVERT","CREATE","CROSS","CURRENT_DATE","CURRENT_ROLE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURSOR","DATABASE","DATABASES","DAY_HOUR","DAY_MICROSECOND","DAY_MINUTE","DAY_SECOND","DECLARE","DEFAULT","DELAYED","DELETE","DELETE_DOMAIN_ID","DESC","DESCRIBE","DETERMINISTIC","DISTINCT","DISTINCTROW","DIV","DO_DOMAIN_IDS","DROP","DUAL","EACH","ELSE","ELSEIF","ENCLOSED","ESCAPED","EXCEPT","EXISTS","EXIT","EXPLAIN","FALSE","FETCH","FOR","FORCE","FOREIGN","FROM","FULLTEXT","GENERAL","GRANT","GROUP","HAVING","HIGH_PRIORITY","HOUR_MICROSECOND","HOUR_MINUTE","HOUR_SECOND","IF","IGNORE","IGNORE_DOMAIN_IDS","IGNORE_SERVER_IDS","IN","INDEX","INFILE","INNER","INOUT","INSENSITIVE","INSERT","INTERSECT","INTERVAL","INTO","IS","ITERATE","JOIN","KEY","KEYS","KILL","LEADING","LEAVE","LEFT","LIKE","LIMIT","LINEAR","LINES","LOAD","LOCALTIME","LOCALTIMESTAMP","LOCK","LOOP","LOW_PRIORITY","MASTER_HEARTBEAT_PERIOD","MASTER_SSL_VERIFY_SERVER_CERT","MATCH","MAXVALUE","MINUTE_MICROSECOND","MINUTE_SECOND","MOD","MODIFIES","NATURAL","NOT","NO_WRITE_TO_BINLOG","NULL","OFFSET","ON","OPTIMIZE","OPTION","OPTIONALLY","OR","ORDER","OUT","OUTER","OUTFILE","OVER","PAGE_CHECKSUM","PARSE_VCOL_EXPR","PARTITION","POSITION","PRIMARY","PROCEDURE","PURGE","RANGE","READ","READS","READ_WRITE","RECURSIVE","REF_SYSTEM_ID","REFERENCES","REGEXP","RELEASE","RENAME","REPEAT","REPLACE","REQUIRE","RESIGNAL","RESTRICT","RETURN","RETURNING","REVOKE","RIGHT","RLIKE","ROW_NUMBER","ROWS","SCHEMA","SCHEMAS","SECOND_MICROSECOND","SELECT","SENSITIVE","SEPARATOR","SET","SHOW","SIGNAL","SLOW","SPATIAL","SPECIFIC","SQL","SQLEXCEPTION","SQLSTATE","SQLWARNING","SQL_BIG_RESULT","SQL_CALC_FOUND_ROWS","SQL_SMALL_RESULT","SSL","STARTING","STATS_AUTO_RECALC","STATS_PERSISTENT","STATS_SAMPLE_PAGES","STRAIGHT_JOIN","TABLE","TERMINATED","THEN","TO","TRAILING","TRIGGER","TRUE","UNDO","UNION","UNIQUE","UNLOCK","UNSIGNED","UPDATE","USAGE","USE","USING","UTC_DATE","UTC_TIME","UTC_TIMESTAMP","VALUES","WHEN","WHERE","WHILE","WINDOW","WITH","WRITE","XOR","YEAR_MONTH","ZEROFILL"],NH=["BIGINT","BINARY","BIT","BLOB","CHAR BYTE","CHAR","CHARACTER","DATETIME","DEC","DECIMAL","DOUBLE PRECISION","DOUBLE","ENUM","FIXED","FLOAT","FLOAT4","FLOAT8","INT","INT1","INT2","INT3","INT4","INT8","INTEGER","LONG","LONGBLOB","LONGTEXT","MEDIUMBLOB","MEDIUMINT","MEDIUMTEXT","MIDDLEINT","NATIONAL CHAR","NATIONAL VARCHAR","NUMERIC","PRECISION","REAL","SMALLINT","TEXT","TIMESTAMP","TINYBLOB","TINYINT","TINYTEXT","VARBINARY","VARCHAR","VARCHARACTER","VARYING","YEAR"],xH=["ADDDATE","ADD_MONTHS","BIT_AND","BIT_OR","BIT_XOR","CAST","COUNT","CUME_DIST","CURDATE","CURTIME","DATE_ADD","DATE_SUB","DATE_FORMAT","DECODE","DENSE_RANK","EXTRACT","FIRST_VALUE","GROUP_CONCAT","JSON_ARRAYAGG","JSON_OBJECTAGG","LAG","LEAD","MAX","MEDIAN","MID","MIN","NOW","NTH_VALUE","NTILE","POSITION","PERCENT_RANK","PERCENTILE_CONT","PERCENTILE_DISC","RANK","ROW_NUMBER","SESSION_USER","STD","STDDEV","STDDEV_POP","STDDEV_SAMP","SUBDATE","SUBSTR","SUBSTRING","SUM","SYSTEM_USER","TRIM","TRIM_ORACLE","VARIANCE","VAR_POP","VAR_SAMP","ABS","ACOS","ADDTIME","AES_DECRYPT","AES_ENCRYPT","ASIN","ATAN","ATAN2","BENCHMARK","BIN","BINLOG_GTID_POS","BIT_COUNT","BIT_LENGTH","CEIL","CEILING","CHARACTER_LENGTH","CHAR_LENGTH","CHR","COERCIBILITY","COLUMN_CHECK","COLUMN_EXISTS","COLUMN_LIST","COLUMN_JSON","COMPRESS","CONCAT","CONCAT_OPERATOR_ORACLE","CONCAT_WS","CONNECTION_ID","CONV","CONVERT_TZ","COS","COT","CRC32","DATEDIFF","DAYNAME","DAYOFMONTH","DAYOFWEEK","DAYOFYEAR","DEGREES","DECODE_HISTOGRAM","DECODE_ORACLE","DES_DECRYPT","DES_ENCRYPT","ELT","ENCODE","ENCRYPT","EXP","EXPORT_SET","EXTRACTVALUE","FIELD","FIND_IN_SET","FLOOR","FORMAT","FOUND_ROWS","FROM_BASE64","FROM_DAYS","FROM_UNIXTIME","GET_LOCK","GREATEST","HEX","IFNULL","INSTR","ISNULL","IS_FREE_LOCK","IS_USED_LOCK","JSON_ARRAY","JSON_ARRAY_APPEND","JSON_ARRAY_INSERT","JSON_COMPACT","JSON_CONTAINS","JSON_CONTAINS_PATH","JSON_DEPTH","JSON_DETAILED","JSON_EXISTS","JSON_EXTRACT","JSON_INSERT","JSON_KEYS","JSON_LENGTH","JSON_LOOSE","JSON_MERGE","JSON_MERGE_PATCH","JSON_MERGE_PRESERVE","JSON_QUERY","JSON_QUOTE","JSON_OBJECT","JSON_REMOVE","JSON_REPLACE","JSON_SET","JSON_SEARCH","JSON_TYPE","JSON_UNQUOTE","JSON_VALID","JSON_VALUE","LAST_DAY","LAST_INSERT_ID","LCASE","LEAST","LENGTH","LENGTHB","LN","LOAD_FILE","LOCATE","LOG","LOG10","LOG2","LOWER","LPAD","LPAD_ORACLE","LTRIM","LTRIM_ORACLE","MAKEDATE","MAKETIME","MAKE_SET","MASTER_GTID_WAIT","MASTER_POS_WAIT","MD5","MONTHNAME","NAME_CONST","NVL","NVL2","OCT","OCTET_LENGTH","ORD","PERIOD_ADD","PERIOD_DIFF","PI","POW","POWER","QUOTE","REGEXP_INSTR","REGEXP_REPLACE","REGEXP_SUBSTR","RADIANS","RAND","RELEASE_ALL_LOCKS","RELEASE_LOCK","REPLACE_ORACLE","REVERSE","ROUND","RPAD","RPAD_ORACLE","RTRIM","RTRIM_ORACLE","SEC_TO_TIME","SHA","SHA1","SHA2","SIGN","SIN","SLEEP","SOUNDEX","SPACE","SQRT","STRCMP","STR_TO_DATE","SUBSTR_ORACLE","SUBSTRING_INDEX","SUBTIME","SYS_GUID","TAN","TIMEDIFF","TIME_FORMAT","TIME_TO_SEC","TO_BASE64","TO_CHAR","TO_DAYS","TO_SECONDS","UCASE","UNCOMPRESS","UNCOMPRESSED_LENGTH","UNHEX","UNIX_TIMESTAMP","UPDATEXML","UPPER","UUID","UUID_SHORT","VERSION","WEEKDAY","WEEKOFYEAR","WSREP_LAST_WRITTEN_GTID","WSREP_LAST_SEEN_GTID","WSREP_SYNC_WAIT_UPTO_GTID","YEARWEEK","COALESCE","NULLIF"],yH=W(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),CH=W(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","PARTITION BY","ORDER BY","LIMIT","OFFSET","FETCH {FIRST | NEXT}","INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE] [INTO]","REPLACE [LOW_PRIORITY | DELAYED] [INTO]","VALUES","ON DUPLICATE KEY UPDATE","SET","RETURNING"]),qp=W(["CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS]"]),gc=W(["CREATE [OR REPLACE] [SQL SECURITY DEFINER | SQL SECURITY INVOKER] VIEW [IF NOT EXISTS]","UPDATE [LOW_PRIORITY] [IGNORE]","DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM","DROP [TEMPORARY] TABLE [IF EXISTS]","ALTER [ONLINE] [IGNORE] TABLE [IF EXISTS]","ADD [COLUMN] [IF NOT EXISTS]","{CHANGE | MODIFY} [COLUMN] [IF EXISTS]","DROP [COLUMN] [IF EXISTS]","RENAME [TO]","RENAME COLUMN","ALTER [COLUMN]","{SET | DROP} DEFAULT","SET {VISIBLE | INVISIBLE}","TRUNCATE [TABLE]","ALTER DATABASE","ALTER DATABASE COMMENT","ALTER EVENT","ALTER FUNCTION","ALTER PROCEDURE","ALTER SCHEMA","ALTER SCHEMA COMMENT","ALTER SEQUENCE","ALTER SERVER","ALTER USER","ALTER VIEW","ANALYZE","ANALYZE TABLE","BACKUP LOCK","BACKUP STAGE","BACKUP UNLOCK","BEGIN","BINLOG","CACHE INDEX","CALL","CHANGE MASTER TO","CHECK TABLE","CHECK VIEW","CHECKSUM TABLE","COMMIT","CREATE AGGREGATE FUNCTION","CREATE DATABASE","CREATE EVENT","CREATE FUNCTION","CREATE INDEX","CREATE PROCEDURE","CREATE ROLE","CREATE SEQUENCE","CREATE SERVER","CREATE SPATIAL INDEX","CREATE TRIGGER","CREATE UNIQUE INDEX","CREATE USER","DEALLOCATE PREPARE","DESCRIBE","DROP DATABASE","DROP EVENT","DROP FUNCTION","DROP INDEX","DROP PREPARE","DROP PROCEDURE","DROP ROLE","DROP SEQUENCE","DROP SERVER","DROP TRIGGER","DROP USER","DROP VIEW","EXECUTE","EXPLAIN","FLUSH","GET DIAGNOSTICS","GET DIAGNOSTICS CONDITION","GRANT","HANDLER","HELP","INSTALL PLUGIN","INSTALL SONAME","KILL","LOAD DATA INFILE","LOAD INDEX INTO CACHE","LOAD XML INFILE","LOCK TABLE","OPTIMIZE TABLE","PREPARE","PURGE BINARY LOGS","PURGE MASTER LOGS","RELEASE SAVEPOINT","RENAME TABLE","RENAME USER","REPAIR TABLE","REPAIR VIEW","RESET MASTER","RESET QUERY CACHE","RESET REPLICA","RESET SLAVE","RESIGNAL","REVOKE","ROLLBACK","SAVEPOINT","SET CHARACTER SET","SET DEFAULT ROLE","SET GLOBAL TRANSACTION","SET NAMES","SET PASSWORD","SET ROLE","SET STATEMENT","SET TRANSACTION","SHOW","SHOW ALL REPLICAS STATUS","SHOW ALL SLAVES STATUS","SHOW AUTHORS","SHOW BINARY LOGS","SHOW BINLOG EVENTS","SHOW BINLOG STATUS","SHOW CHARACTER SET","SHOW CLIENT_STATISTICS","SHOW COLLATION","SHOW COLUMNS","SHOW CONTRIBUTORS","SHOW CREATE DATABASE","SHOW CREATE EVENT","SHOW CREATE FUNCTION","SHOW CREATE PACKAGE","SHOW CREATE PACKAGE BODY","SHOW CREATE PROCEDURE","SHOW CREATE SEQUENCE","SHOW CREATE TABLE","SHOW CREATE TRIGGER","SHOW CREATE USER","SHOW CREATE VIEW","SHOW DATABASES","SHOW ENGINE","SHOW ENGINE INNODB STATUS","SHOW ENGINES","SHOW ERRORS","SHOW EVENTS","SHOW EXPLAIN","SHOW FUNCTION CODE","SHOW FUNCTION STATUS","SHOW GRANTS","SHOW INDEX","SHOW INDEXES","SHOW INDEX_STATISTICS","SHOW KEYS","SHOW LOCALES","SHOW MASTER LOGS","SHOW MASTER STATUS","SHOW OPEN TABLES","SHOW PACKAGE BODY CODE","SHOW PACKAGE BODY STATUS","SHOW PACKAGE STATUS","SHOW PLUGINS","SHOW PLUGINS SONAME","SHOW PRIVILEGES","SHOW PROCEDURE CODE","SHOW PROCEDURE STATUS","SHOW PROCESSLIST","SHOW PROFILE","SHOW PROFILES","SHOW QUERY_RESPONSE_TIME","SHOW RELAYLOG EVENTS","SHOW REPLICA","SHOW REPLICA HOSTS","SHOW REPLICA STATUS","SHOW SCHEMAS","SHOW SLAVE","SHOW SLAVE HOSTS","SHOW SLAVE STATUS","SHOW STATUS","SHOW STORAGE ENGINES","SHOW TABLE STATUS","SHOW TABLES","SHOW TRIGGERS","SHOW USER_STATISTICS","SHOW VARIABLES","SHOW WARNINGS","SHOW WSREP_MEMBERSHIP","SHOW WSREP_STATUS","SHUTDOWN","SIGNAL","START ALL REPLICAS","START ALL SLAVES","START REPLICA","START SLAVE","START TRANSACTION","STOP ALL REPLICAS","STOP ALL SLAVES","STOP REPLICA","STOP SLAVE","UNINSTALL PLUGIN","UNINSTALL SONAME","UNLOCK TABLE","USE","XA BEGIN","XA COMMIT","XA END","XA PREPARE","XA RECOVER","XA ROLLBACK","XA START"]),LH=W(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]","MINUS [ALL | DISTINCT]"]),_H=W(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),bH=W(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),vH=W([]),DH={name:"mariadb",tokenizerOptions:{reservedSelect:yH,reservedClauses:[...CH,...qp,...gc],reservedSetOperations:LH,reservedJoins:_H,reservedKeywordPhrases:bH,reservedDataTypePhrases:vH,supportsXor:!0,reservedKeywords:OH,reservedDataTypes:NH,reservedFunctionNames:xH,stringTypes:['""-qq-bs',"''-qq-bs",{quote:"''-raw",prefixes:["B","X"],requirePrefix:!0}],identTypes:["``"],identChars:{first:"$",rest:"$",allowFirstCharNumber:!0},variableTypes:[{regex:"@@?[A-Za-z0-9_.$]+"},{quote:'""-qq-bs',prefixes:["@"],requirePrefix:!0},{quote:"''-qq-bs",prefixes:["@"],requirePrefix:!0},{quote:"``",prefixes:["@"],requirePrefix:!0}],paramTypes:{positional:!0},lineCommentTypes:["--","#"],operators:["%",":=","&","|","^","~","<<",">>","<=>","&&","||","!","*.*"],postProcess:ll},formatOptions:{onelineClauses:[...qp,...gc],tabularOnelineClauses:gc}},MH=["ACCESSIBLE","ADD","ALL","ALTER","ANALYZE","AND","AS","ASC","ASENSITIVE","BEFORE","BETWEEN","BOTH","BY","CALL","CASCADE","CASE","CHANGE","CHECK","COLLATE","COLUMN","CONDITION","CONSTRAINT","CONTINUE","CONVERT","CREATE","CROSS","CUBE","CUME_DIST","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURSOR","DATABASE","DATABASES","DAY_HOUR","DAY_MICROSECOND","DAY_MINUTE","DAY_SECOND","DECLARE","DEFAULT","DELAYED","DELETE","DENSE_RANK","DESC","DESCRIBE","DETERMINISTIC","DISTINCT","DISTINCTROW","DIV","DROP","DUAL","EACH","ELSE","ELSEIF","EMPTY","ENCLOSED","ESCAPED","EXCEPT","EXISTS","EXIT","EXPLAIN","FALSE","FETCH","FIRST_VALUE","FOR","FORCE","FOREIGN","FROM","FULLTEXT","FUNCTION","GENERATED","GET","GRANT","GROUP","GROUPING","GROUPS","HAVING","HIGH_PRIORITY","HOUR_MICROSECOND","HOUR_MINUTE","HOUR_SECOND","IF","IGNORE","IN","INDEX","INFILE","INNER","INOUT","INSENSITIVE","INSERT","IN","INTERSECT","INTERVAL","INTO","IO_AFTER_GTIDS","IO_BEFORE_GTIDS","IS","ITERATE","JOIN","JSON_TABLE","KEY","KEYS","KILL","LAG","LAST_VALUE","LATERAL","LEAD","LEADING","LEAVE","LEFT","LIKE","LIMIT","LINEAR","LINES","LOAD","LOCALTIME","LOCALTIMESTAMP","LOCK","LONG","LOOP","LOW_PRIORITY","MASTER_BIND","MASTER_SSL_VERIFY_SERVER_CERT","MATCH","MAXVALUE","MINUTE_MICROSECOND","MINUTE_SECOND","MOD","MODIFIES","NATURAL","NOT","NO_WRITE_TO_BINLOG","NTH_VALUE","NTILE","NULL","OF","ON","OPTIMIZE","OPTIMIZER_COSTS","OPTION","OPTIONALLY","OR","ORDER","OUT","OUTER","OUTFILE","OVER","PARTITION","PERCENT_RANK","PRIMARY","PROCEDURE","PURGE","RANGE","RANK","READ","READS","READ_WRITE","RECURSIVE","REFERENCES","REGEXP","RELEASE","RENAME","REPEAT","REPLACE","REQUIRE","RESIGNAL","RESTRICT","RETURN","REVOKE","RIGHT","RLIKE","ROW","ROWS","ROW_NUMBER","SCHEMA","SCHEMAS","SECOND_MICROSECOND","SELECT","SENSITIVE","SEPARATOR","SET","SHOW","SIGNAL","SPATIAL","SPECIFIC","SQL","SQLEXCEPTION","SQLSTATE","SQLWARNING","SQL_BIG_RESULT","SQL_CALC_FOUND_ROWS","SQL_SMALL_RESULT","SSL","STARTING","STORED","STRAIGHT_JOIN","SYSTEM","TABLE","TERMINATED","THEN","TO","TRAILING","TRIGGER","TRUE","UNDO","UNION","UNIQUE","UNLOCK","UNSIGNED","UPDATE","USAGE","USE","USING","UTC_DATE","UTC_TIME","UTC_TIMESTAMP","VALUES","VIRTUAL","WHEN","WHERE","WHILE","WINDOW","WITH","WRITE","XOR","YEAR_MONTH","ZEROFILL"],PH=["BIGINT","BINARY","BIT","BLOB","BOOL","BOOLEAN","CHAR","CHARACTER","DATE","DATETIME","DEC","DECIMAL","DOUBLE PRECISION","DOUBLE","ENUM","FIXED","FLOAT","FLOAT4","FLOAT8","INT","INT1","INT2","INT3","INT4","INT8","INTEGER","LONGBLOB","LONGTEXT","MEDIUMBLOB","MEDIUMINT","MEDIUMTEXT","MIDDLEINT","NATIONAL CHAR","NATIONAL VARCHAR","NUMERIC","PRECISION","REAL","SMALLINT","TEXT","TIME","TIMESTAMP","TINYBLOB","TINYINT","TINYTEXT","VARBINARY","VARCHAR","VARCHARACTER","VARYING","YEAR"],wH=["ABS","ACOS","ADDDATE","ADDTIME","AES_DECRYPT","AES_ENCRYPT","ANY_VALUE","ASCII","ASIN","ATAN","ATAN2","AVG","BENCHMARK","BIN","BIN_TO_UUID","BINARY","BIT_AND","BIT_COUNT","BIT_LENGTH","BIT_OR","BIT_XOR","CAN_ACCESS_COLUMN","CAN_ACCESS_DATABASE","CAN_ACCESS_TABLE","CAN_ACCESS_USER","CAN_ACCESS_VIEW","CAST","CEIL","CEILING","CHAR","CHAR_LENGTH","CHARACTER_LENGTH","CHARSET","COALESCE","COERCIBILITY","COLLATION","COMPRESS","CONCAT","CONCAT_WS","CONNECTION_ID","CONV","CONVERT","CONVERT_TZ","COS","COT","COUNT","CRC32","CUME_DIST","CURDATE","CURRENT_DATE","CURRENT_ROLE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURTIME","DATABASE","DATE","DATE_ADD","DATE_FORMAT","DATE_SUB","DATEDIFF","DAY","DAYNAME","DAYOFMONTH","DAYOFWEEK","DAYOFYEAR","DEFAULT","DEGREES","DENSE_RANK","DIV","ELT","EXP","EXPORT_SET","EXTRACT","EXTRACTVALUE","FIELD","FIND_IN_SET","FIRST_VALUE","FLOOR","FORMAT","FORMAT_BYTES","FORMAT_PICO_TIME","FOUND_ROWS","FROM_BASE64","FROM_DAYS","FROM_UNIXTIME","GEOMCOLLECTION","GEOMETRYCOLLECTION","GET_DD_COLUMN_PRIVILEGES","GET_DD_CREATE_OPTIONS","GET_DD_INDEX_SUB_PART_LENGTH","GET_FORMAT","GET_LOCK","GREATEST","GROUP_CONCAT","GROUPING","GTID_SUBSET","GTID_SUBTRACT","HEX","HOUR","ICU_VERSION","IF","IFNULL","INET_ATON","INET_NTOA","INET6_ATON","INET6_NTOA","INSERT","INSTR","INTERNAL_AUTO_INCREMENT","INTERNAL_AVG_ROW_LENGTH","INTERNAL_CHECK_TIME","INTERNAL_CHECKSUM","INTERNAL_DATA_FREE","INTERNAL_DATA_LENGTH","INTERNAL_DD_CHAR_LENGTH","INTERNAL_GET_COMMENT_OR_ERROR","INTERNAL_GET_ENABLED_ROLE_JSON","INTERNAL_GET_HOSTNAME","INTERNAL_GET_USERNAME","INTERNAL_GET_VIEW_WARNING_OR_ERROR","INTERNAL_INDEX_COLUMN_CARDINALITY","INTERNAL_INDEX_LENGTH","INTERNAL_IS_ENABLED_ROLE","INTERNAL_IS_MANDATORY_ROLE","INTERNAL_KEYS_DISABLED","INTERNAL_MAX_DATA_LENGTH","INTERNAL_TABLE_ROWS","INTERNAL_UPDATE_TIME","INTERVAL","IS","IS_FREE_LOCK","IS_IPV4","IS_IPV4_COMPAT","IS_IPV4_MAPPED","IS_IPV6","IS NOT","IS NOT NULL","IS NULL","IS_USED_LOCK","IS_UUID","ISNULL","JSON_ARRAY","JSON_ARRAY_APPEND","JSON_ARRAY_INSERT","JSON_ARRAYAGG","JSON_CONTAINS","JSON_CONTAINS_PATH","JSON_DEPTH","JSON_EXTRACT","JSON_INSERT","JSON_KEYS","JSON_LENGTH","JSON_MERGE","JSON_MERGE_PATCH","JSON_MERGE_PRESERVE","JSON_OBJECT","JSON_OBJECTAGG","JSON_OVERLAPS","JSON_PRETTY","JSON_QUOTE","JSON_REMOVE","JSON_REPLACE","JSON_SCHEMA_VALID","JSON_SCHEMA_VALIDATION_REPORT","JSON_SEARCH","JSON_SET","JSON_STORAGE_FREE","JSON_STORAGE_SIZE","JSON_TABLE","JSON_TYPE","JSON_UNQUOTE","JSON_VALID","JSON_VALUE","LAG","LAST_DAY","LAST_INSERT_ID","LAST_VALUE","LCASE","LEAD","LEAST","LEFT","LENGTH","LIKE","LINESTRING","LN","LOAD_FILE","LOCALTIME","LOCALTIMESTAMP","LOCATE","LOG","LOG10","LOG2","LOWER","LPAD","LTRIM","MAKE_SET","MAKEDATE","MAKETIME","MASTER_POS_WAIT","MATCH","MAX","MBRCONTAINS","MBRCOVEREDBY","MBRCOVERS","MBRDISJOINT","MBREQUALS","MBRINTERSECTS","MBROVERLAPS","MBRTOUCHES","MBRWITHIN","MD5","MICROSECOND","MID","MIN","MINUTE","MOD","MONTH","MONTHNAME","MULTILINESTRING","MULTIPOINT","MULTIPOLYGON","NAME_CONST","NOW","NTH_VALUE","NTILE","NULLIF","OCT","OCTET_LENGTH","ORD","PERCENT_RANK","PERIOD_ADD","PERIOD_DIFF","PI","POINT","POLYGON","POSITION","POW","POWER","PS_CURRENT_THREAD_ID","PS_THREAD_ID","QUARTER","QUOTE","RADIANS","RAND","RANDOM_BYTES","RANK","REGEXP","REGEXP_INSTR","REGEXP_LIKE","REGEXP_REPLACE","REGEXP_SUBSTR","RELEASE_ALL_LOCKS","RELEASE_LOCK","REPEAT","REPLACE","REVERSE","RIGHT","RLIKE","ROLES_GRAPHML","ROUND","ROW_COUNT","ROW_NUMBER","RPAD","RTRIM","SCHEMA","SEC_TO_TIME","SECOND","SESSION_USER","SHA1","SHA2","SIGN","SIN","SLEEP","SOUNDEX","SOUNDS LIKE","SOURCE_POS_WAIT","SPACE","SQRT","ST_AREA","ST_ASBINARY","ST_ASGEOJSON","ST_ASTEXT","ST_BUFFER","ST_BUFFER_STRATEGY","ST_CENTROID","ST_COLLECT","ST_CONTAINS","ST_CONVEXHULL","ST_CROSSES","ST_DIFFERENCE","ST_DIMENSION","ST_DISJOINT","ST_DISTANCE","ST_DISTANCE_SPHERE","ST_ENDPOINT","ST_ENVELOPE","ST_EQUALS","ST_EXTERIORRING","ST_FRECHETDISTANCE","ST_GEOHASH","ST_GEOMCOLLFROMTEXT","ST_GEOMCOLLFROMWKB","ST_GEOMETRYN","ST_GEOMETRYTYPE","ST_GEOMFROMGEOJSON","ST_GEOMFROMTEXT","ST_GEOMFROMWKB","ST_HAUSDORFFDISTANCE","ST_INTERIORRINGN","ST_INTERSECTION","ST_INTERSECTS","ST_ISCLOSED","ST_ISEMPTY","ST_ISSIMPLE","ST_ISVALID","ST_LATFROMGEOHASH","ST_LATITUDE","ST_LENGTH","ST_LINEFROMTEXT","ST_LINEFROMWKB","ST_LINEINTERPOLATEPOINT","ST_LINEINTERPOLATEPOINTS","ST_LONGFROMGEOHASH","ST_LONGITUDE","ST_MAKEENVELOPE","ST_MLINEFROMTEXT","ST_MLINEFROMWKB","ST_MPOINTFROMTEXT","ST_MPOINTFROMWKB","ST_MPOLYFROMTEXT","ST_MPOLYFROMWKB","ST_NUMGEOMETRIES","ST_NUMINTERIORRING","ST_NUMPOINTS","ST_OVERLAPS","ST_POINTATDISTANCE","ST_POINTFROMGEOHASH","ST_POINTFROMTEXT","ST_POINTFROMWKB","ST_POINTN","ST_POLYFROMTEXT","ST_POLYFROMWKB","ST_SIMPLIFY","ST_SRID","ST_STARTPOINT","ST_SWAPXY","ST_SYMDIFFERENCE","ST_TOUCHES","ST_TRANSFORM","ST_UNION","ST_VALIDATE","ST_WITHIN","ST_X","ST_Y","STATEMENT_DIGEST","STATEMENT_DIGEST_TEXT","STD","STDDEV","STDDEV_POP","STDDEV_SAMP","STR_TO_DATE","STRCMP","SUBDATE","SUBSTR","SUBSTRING","SUBSTRING_INDEX","SUBTIME","SUM","SYSDATE","SYSTEM_USER","TAN","TIME","TIME_FORMAT","TIME_TO_SEC","TIMEDIFF","TIMESTAMP","TIMESTAMPADD","TIMESTAMPDIFF","TO_BASE64","TO_DAYS","TO_SECONDS","TRIM","TRUNCATE","UCASE","UNCOMPRESS","UNCOMPRESSED_LENGTH","UNHEX","UNIX_TIMESTAMP","UPDATEXML","UPPER","UTC_DATE","UTC_TIME","UTC_TIMESTAMP","UUID","UUID_SHORT","UUID_TO_BIN","VALIDATE_PASSWORD_STRENGTH","VALUES","VAR_POP","VAR_SAMP","VARIANCE","VERSION","WAIT_FOR_EXECUTED_GTID_SET","WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS","WEEK","WEEKDAY","WEEKOFYEAR","WEIGHT_STRING","YEAR","YEARWEEK"],UH=W(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),BH=W(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE] [INTO]","REPLACE [LOW_PRIORITY | DELAYED] [INTO]","VALUES","ON DUPLICATE KEY UPDATE","SET"]),Jp=W(["CREATE [TEMPORARY] TABLE [IF NOT EXISTS]"]),Ic=W(["CREATE [OR REPLACE] [SQL SECURITY DEFINER | SQL SECURITY INVOKER] VIEW [IF NOT EXISTS]","UPDATE [LOW_PRIORITY] [IGNORE]","DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM","DROP [TEMPORARY] TABLE [IF EXISTS]","ALTER TABLE","ADD [COLUMN]","{CHANGE | MODIFY} [COLUMN]","DROP [COLUMN]","RENAME [TO | AS]","RENAME COLUMN","ALTER [COLUMN]","{SET | DROP} DEFAULT","TRUNCATE [TABLE]","ALTER DATABASE","ALTER EVENT","ALTER FUNCTION","ALTER INSTANCE","ALTER LOGFILE GROUP","ALTER PROCEDURE","ALTER RESOURCE GROUP","ALTER SERVER","ALTER TABLESPACE","ALTER USER","ALTER VIEW","ANALYZE TABLE","BINLOG","CACHE INDEX","CALL","CHANGE MASTER TO","CHANGE REPLICATION FILTER","CHANGE REPLICATION SOURCE TO","CHECK TABLE","CHECKSUM TABLE","CLONE","COMMIT","CREATE DATABASE","CREATE EVENT","CREATE FUNCTION","CREATE FUNCTION","CREATE INDEX","CREATE LOGFILE GROUP","CREATE PROCEDURE","CREATE RESOURCE GROUP","CREATE ROLE","CREATE SERVER","CREATE SPATIAL REFERENCE SYSTEM","CREATE TABLESPACE","CREATE TRIGGER","CREATE USER","DEALLOCATE PREPARE","DESCRIBE","DROP DATABASE","DROP EVENT","DROP FUNCTION","DROP FUNCTION","DROP INDEX","DROP LOGFILE GROUP","DROP PROCEDURE","DROP RESOURCE GROUP","DROP ROLE","DROP SERVER","DROP SPATIAL REFERENCE SYSTEM","DROP TABLESPACE","DROP TRIGGER","DROP USER","DROP VIEW","EXECUTE","EXPLAIN","FLUSH","GRANT","HANDLER","HELP","IMPORT TABLE","INSTALL COMPONENT","INSTALL PLUGIN","KILL","LOAD DATA","LOAD INDEX INTO CACHE","LOAD XML","LOCK INSTANCE FOR BACKUP","LOCK TABLES","MASTER_POS_WAIT","OPTIMIZE TABLE","PREPARE","PURGE BINARY LOGS","RELEASE SAVEPOINT","RENAME TABLE","RENAME USER","REPAIR TABLE","RESET","RESET MASTER","RESET PERSIST","RESET REPLICA","RESET SLAVE","RESTART","REVOKE","ROLLBACK","ROLLBACK TO SAVEPOINT","SAVEPOINT","SET CHARACTER SET","SET DEFAULT ROLE","SET NAMES","SET PASSWORD","SET RESOURCE GROUP","SET ROLE","SET TRANSACTION","SHOW","SHOW BINARY LOGS","SHOW BINLOG EVENTS","SHOW CHARACTER SET","SHOW COLLATION","SHOW COLUMNS","SHOW CREATE DATABASE","SHOW CREATE EVENT","SHOW CREATE FUNCTION","SHOW CREATE PROCEDURE","SHOW CREATE TABLE","SHOW CREATE TRIGGER","SHOW CREATE USER","SHOW CREATE VIEW","SHOW DATABASES","SHOW ENGINE","SHOW ENGINES","SHOW ERRORS","SHOW EVENTS","SHOW FUNCTION CODE","SHOW FUNCTION STATUS","SHOW GRANTS","SHOW INDEX","SHOW MASTER STATUS","SHOW OPEN TABLES","SHOW PLUGINS","SHOW PRIVILEGES","SHOW PROCEDURE CODE","SHOW PROCEDURE STATUS","SHOW PROCESSLIST","SHOW PROFILE","SHOW PROFILES","SHOW RELAYLOG EVENTS","SHOW REPLICA STATUS","SHOW REPLICAS","SHOW SLAVE","SHOW SLAVE HOSTS","SHOW STATUS","SHOW TABLE STATUS","SHOW TABLES","SHOW TRIGGERS","SHOW VARIABLES","SHOW WARNINGS","SHUTDOWN","SOURCE_POS_WAIT","START GROUP_REPLICATION","START REPLICA","START SLAVE","START TRANSACTION","STOP GROUP_REPLICATION","STOP REPLICA","STOP SLAVE","TABLE","UNINSTALL COMPONENT","UNINSTALL PLUGIN","UNLOCK INSTANCE","UNLOCK TABLES","USE","XA","ITERATE","LEAVE","LOOP","REPEAT","RETURN","WHILE"]),jH=W(["UNION [ALL | DISTINCT]"]),kH=W(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),FH=W(["ON {UPDATE | DELETE} [SET NULL]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),GH=W([]),HH={name:"mysql",tokenizerOptions:{reservedSelect:UH,reservedClauses:[...BH,...Jp,...Ic],reservedSetOperations:jH,reservedJoins:kH,reservedKeywordPhrases:FH,reservedDataTypePhrases:GH,supportsXor:!0,reservedKeywords:MH,reservedDataTypes:PH,reservedFunctionNames:wH,stringTypes:['""-qq-bs',{quote:"''-qq-bs",prefixes:["N"]},{quote:"''-raw",prefixes:["B","X"],requirePrefix:!0}],identTypes:["``"],identChars:{first:"$",rest:"$",allowFirstCharNumber:!0},variableTypes:[{regex:"@@?[A-Za-z0-9_.$]+"},{quote:'""-qq-bs',prefixes:["@"],requirePrefix:!0},{quote:"''-qq-bs",prefixes:["@"],requirePrefix:!0},{quote:"``",prefixes:["@"],requirePrefix:!0}],paramTypes:{positional:!0},lineCommentTypes:["--","#"],operators:["%",":=","&","|","^","~","<<",">>","<=>","->","->>","&&","||","!","*.*"],postProcess:ll},formatOptions:{onelineClauses:[...Jp,...Ic],tabularOnelineClauses:Ic}},WH=["ADD","ALL","ALTER","ANALYZE","AND","ARRAY","AS","ASC","BETWEEN","BOTH","BY","CALL","CASCADE","CASE","CHANGE","CHECK","COLLATE","COLUMN","CONSTRAINT","CONTINUE","CONVERT","CREATE","CROSS","CURRENT_DATE","CURRENT_ROLE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURSOR","DATABASE","DATABASES","DAY_HOUR","DAY_MICROSECOND","DAY_MINUTE","DAY_SECOND","DEFAULT","DELAYED","DELETE","DESC","DESCRIBE","DISTINCT","DISTINCTROW","DIV","DOUBLE","DROP","DUAL","ELSE","ELSEIF","ENCLOSED","ESCAPED","EXCEPT","EXISTS","EXIT","EXPLAIN","FALSE","FETCH","FOR","FORCE","FOREIGN","FROM","FULLTEXT","GENERATED","GRANT","GROUP","GROUPS","HAVING","HIGH_PRIORITY","HOUR_MICROSECOND","HOUR_MINUTE","HOUR_SECOND","IF","IGNORE","ILIKE","IN","INDEX","INFILE","INNER","INOUT","INSERT","INTERSECT","INTERVAL","INTO","IS","ITERATE","JOIN","KEY","KEYS","KILL","LEADING","LEAVE","LEFT","LIKE","LIMIT","LINEAR","LINES","LOAD","LOCALTIME","LOCALTIMESTAMP","LOCK","LONG","LOW_PRIORITY","MATCH","MAXVALUE","MINUTE_MICROSECOND","MINUTE_SECOND","MOD","NATURAL","NOT","NO_WRITE_TO_BINLOG","NULL","OF","ON","OPTIMIZE","OPTION","OPTIONALLY","OR","ORDER","OUT","OUTER","OUTFILE","OVER","PARTITION","PRIMARY","PROCEDURE","RANGE","READ","RECURSIVE","REFERENCES","REGEXP","RELEASE","RENAME","REPEAT","REPLACE","REQUIRE","RESTRICT","REVOKE","RIGHT","RLIKE","ROW","ROWS","SECOND_MICROSECOND","SELECT","SET","SHOW","SPATIAL","SQL","SQLEXCEPTION","SQLSTATE","SQLWARNING","SQL_BIG_RESULT","SQL_CALC_FOUND_ROWS","SQL_SMALL_RESULT","SSL","STARTING","STATS_EXTENDED","STORED","STRAIGHT_JOIN","TABLE","TABLESAMPLE","TERMINATED","THEN","TO","TRAILING","TRIGGER","TRUE","TiDB_CURRENT_TSO","UNION","UNIQUE","UNLOCK","UNSIGNED","UNTIL","UPDATE","USAGE","USE","USING","UTC_DATE","UTC_TIME","UTC_TIMESTAMP","VALUES","VIRTUAL","WHEN","WHERE","WHILE","WINDOW","WITH","WRITE","XOR","YEAR_MONTH","ZEROFILL"],YH=["BIGINT","BINARY","BIT","BLOB","BOOL","BOOLEAN","CHAR","CHARACTER","DATE","DATETIME","DEC","DECIMAL","DOUBLE PRECISION","DOUBLE","ENUM","FIXED","INT","INT1","INT2","INT3","INT4","INT8","INTEGER","LONGBLOB","LONGTEXT","MEDIUMBLOB","MEDIUMINT","MIDDLEINT","NATIONAL CHAR","NATIONAL VARCHAR","NUMERIC","PRECISION","SMALLINT","TEXT","TIME","TIMESTAMP","TINYBLOB","TINYINT","TINYTEXT","VARBINARY","VARCHAR","VARCHARACTER","VARYING","YEAR"],$H=["ABS","ACOS","ADDDATE","ADDTIME","AES_DECRYPT","AES_ENCRYPT","ANY_VALUE","ASCII","ASIN","ATAN","ATAN2","AVG","BENCHMARK","BIN","BIN_TO_UUID","BIT_AND","BIT_COUNT","BIT_LENGTH","BIT_OR","BIT_XOR","BITAND","BITNEG","BITOR","BITXOR","CASE","CAST","CEIL","CEILING","CHAR_FUNC","CHAR_LENGTH","CHARACTER_LENGTH","CHARSET","COALESCE","COERCIBILITY","COLLATION","COMPRESS","CONCAT","CONCAT_WS","CONNECTION_ID","CONV","CONVERT","CONVERT_TZ","COS","COT","COUNT","CRC32","CUME_DIST","CURDATE","CURRENT_DATE","CURRENT_RESOURCE_GROUP","CURRENT_ROLE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURTIME","DATABASE","DATE","DATE_ADD","DATE_FORMAT","DATE_SUB","DATEDIFF","DAY","DAYNAME","DAYOFMONTH","DAYOFWEEK","DAYOFYEAR","DECODE","DEFAULT_FUNC","DEGREES","DENSE_RANK","DES_DECRYPT","DES_ENCRYPT","DIV","ELT","ENCODE","ENCRYPT","EQ","EXP","EXPORT_SET","EXTRACT","FIELD","FIND_IN_SET","FIRST_VALUE","FLOOR","FORMAT","FORMAT_BYTES","FORMAT_NANO_TIME","FOUND_ROWS","FROM_BASE64","FROM_DAYS","FROM_UNIXTIME","GE","GET_FORMAT","GET_LOCK","GETPARAM","GREATEST","GROUP_CONCAT","GROUPING","GT","HEX","HOUR","IF","IFNULL","ILIKE","INET6_ATON","INET6_NTOA","INET_ATON","INET_NTOA","INSERT_FUNC","INSTR","INTDIV","INTERVAL","IS_FREE_LOCK","IS_IPV4","IS_IPV4_COMPAT","IS_IPV4_MAPPED","IS_IPV6","IS_USED_LOCK","IS_UUID","ISFALSE","ISNULL","ISTRUE","JSON_ARRAY","JSON_ARRAYAGG","JSON_ARRAY_APPEND","JSON_ARRAY_INSERT","JSON_CONTAINS","JSON_CONTAINS_PATH","JSON_DEPTH","JSON_EXTRACT","JSON_INSERT","JSON_KEYS","JSON_LENGTH","JSON_MEMBEROF","JSON_MERGE","JSON_MERGE_PATCH","JSON_MERGE_PRESERVE","JSON_OBJECT","JSON_OBJECTAGG","JSON_OVERLAPS","JSON_PRETTY","JSON_QUOTE","JSON_REMOVE","JSON_REPLACE","JSON_SEARCH","JSON_SET","JSON_STORAGE_FREE","JSON_STORAGE_SIZE","JSON_TYPE","JSON_UNQUOTE","JSON_VALID","LAG","LAST_DAY","LAST_INSERT_ID","LAST_VALUE","LASTVAL","LCASE","LE","LEAD","LEAST","LEFT","LEFTSHIFT","LENGTH","LIKE","LN","LOAD_FILE","LOCALTIME","LOCALTIMESTAMP","LOCATE","LOG","LOG10","LOG2","LOWER","LPAD","LT","LTRIM","MAKE_SET","MAKEDATE","MAKETIME","MASTER_POS_WAIT","MAX","MD5","MICROSECOND","MID","MIN","MINUS","MINUTE","MOD","MONTH","MONTHNAME","MUL","NAME_CONST","NE","NEXTVAL","NOT","NOW","NTH_VALUE","NTILE","NULLEQ","OCT","OCTET_LENGTH","OLD_PASSWORD","ORD","PASSWORD_FUNC","PERCENT_RANK","PERIOD_ADD","PERIOD_DIFF","PI","PLUS","POSITION","POW","POWER","QUARTER","QUOTE","RADIANS","RAND","RANDOM_BYTES","RANK","REGEXP","REGEXP_INSTR","REGEXP_LIKE","REGEXP_REPLACE","REGEXP_SUBSTR","RELEASE_ALL_LOCKS","RELEASE_LOCK","REPEAT","REPLACE","REVERSE","RIGHT","RIGHTSHIFT","ROUND","ROW_COUNT","ROW_NUMBER","RPAD","RTRIM","SCHEMA","SEC_TO_TIME","SECOND","SESSION_USER","SETVAL","SETVAR","SHA","SHA1","SHA2","SIGN","SIN","SLEEP","SM3","SPACE","SQRT","STD","STDDEV","STDDEV_POP","STDDEV_SAMP","STR_TO_DATE","STRCMP","SUBDATE","SUBSTR","SUBSTRING","SUBSTRING_INDEX","SUBTIME","SUM","SYSDATE","SYSTEM_USER","TAN","TIDB_BOUNDED_STALENESS","TIDB_CURRENT_TSO","TIDB_DECODE_BINARY_PLAN","TIDB_DECODE_KEY","TIDB_DECODE_PLAN","TIDB_DECODE_SQL_DIGESTS","TIDB_ENCODE_SQL_DIGEST","TIDB_IS_DDL_OWNER","TIDB_PARSE_TSO","TIDB_PARSE_TSO_LOGICAL","TIDB_ROW_CHECKSUM","TIDB_SHARD","TIDB_VERSION","TIME","TIME_FORMAT","TIME_TO_SEC","TIMEDIFF","TIMESTAMP","TIMESTAMPADD","TIMESTAMPDIFF","TO_BASE64","TO_DAYS","TO_SECONDS","TRANSLATE","TRIM","TRUNCATE","UCASE","UNARYMINUS","UNCOMPRESS","UNCOMPRESSED_LENGTH","UNHEX","UNIX_TIMESTAMP","UPPER","UTC_DATE","UTC_TIME","UTC_TIMESTAMP","UUID","UUID_SHORT","UUID_TO_BIN","VALIDATE_PASSWORD_STRENGTH","VAR_POP","VAR_SAMP","VARIANCE","VERSION","VITESS_HASH","WEEK","WEEKDAY","WEEKOFYEAR","WEIGHT_STRING","YEAR","YEARWEEK"],VH=W(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),zH=W(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE] [INTO]","REPLACE [LOW_PRIORITY | DELAYED] [INTO]","VALUES","ON DUPLICATE KEY UPDATE","SET"]),Qp=W(["CREATE [TEMPORARY] TABLE [IF NOT EXISTS]"]),Oc=W(["CREATE [OR REPLACE] [SQL SECURITY DEFINER | SQL SECURITY INVOKER] VIEW [IF NOT EXISTS]","UPDATE [LOW_PRIORITY] [IGNORE]","DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM","DROP [TEMPORARY] TABLE [IF EXISTS]","ALTER TABLE","ADD [COLUMN]","{CHANGE | MODIFY} [COLUMN]","DROP [COLUMN]","RENAME [TO | AS]","RENAME COLUMN","ALTER [COLUMN]","{SET | DROP} DEFAULT","TRUNCATE [TABLE]","ALTER DATABASE","ALTER INSTANCE","ALTER RESOURCE GROUP","ALTER SEQUENCE","ALTER USER","ALTER VIEW","ANALYZE TABLE","CHECK TABLE","CHECKSUM TABLE","COMMIT","CREATE DATABASE","CREATE INDEX","CREATE RESOURCE GROUP","CREATE ROLE","CREATE SEQUENCE","CREATE USER","DEALLOCATE PREPARE","DESCRIBE","DROP DATABASE","DROP INDEX","DROP RESOURCE GROUP","DROP ROLE","DROP TABLESPACE","DROP USER","DROP VIEW","EXPLAIN","FLUSH","GRANT","IMPORT TABLE","INSTALL COMPONENT","INSTALL PLUGIN","KILL","LOAD DATA","LOCK INSTANCE FOR BACKUP","LOCK TABLES","OPTIMIZE TABLE","PREPARE","RELEASE SAVEPOINT","RENAME TABLE","RENAME USER","REPAIR TABLE","RESET","REVOKE","ROLLBACK","ROLLBACK TO SAVEPOINT","SAVEPOINT","SET CHARACTER SET","SET DEFAULT ROLE","SET NAMES","SET PASSWORD","SET RESOURCE GROUP","SET ROLE","SET TRANSACTION","SHOW","SHOW BINARY LOGS","SHOW BINLOG EVENTS","SHOW CHARACTER SET","SHOW COLLATION","SHOW COLUMNS","SHOW CREATE DATABASE","SHOW CREATE TABLE","SHOW CREATE USER","SHOW CREATE VIEW","SHOW DATABASES","SHOW ENGINE","SHOW ENGINES","SHOW ERRORS","SHOW EVENTS","SHOW GRANTS","SHOW INDEX","SHOW MASTER STATUS","SHOW OPEN TABLES","SHOW PLUGINS","SHOW PRIVILEGES","SHOW PROCESSLIST","SHOW PROFILE","SHOW PROFILES","SHOW STATUS","SHOW TABLE STATUS","SHOW TABLES","SHOW TRIGGERS","SHOW VARIABLES","SHOW WARNINGS","TABLE","UNINSTALL COMPONENT","UNINSTALL PLUGIN","UNLOCK INSTANCE","UNLOCK TABLES","USE"]),XH=W(["UNION [ALL | DISTINCT]"]),KH=W(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),qH=W(["ON {UPDATE | DELETE} [SET NULL]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),JH=W([]),QH={name:"tidb",tokenizerOptions:{reservedSelect:VH,reservedClauses:[...zH,...Qp,...Oc],reservedSetOperations:XH,reservedJoins:KH,reservedKeywordPhrases:qH,reservedDataTypePhrases:JH,supportsXor:!0,reservedKeywords:WH,reservedDataTypes:YH,reservedFunctionNames:$H,stringTypes:['""-qq-bs',{quote:"''-qq-bs",prefixes:["N"]},{quote:"''-raw",prefixes:["B","X"],requirePrefix:!0}],identTypes:["``"],identChars:{first:"$",rest:"$",allowFirstCharNumber:!0},variableTypes:[{regex:"@@?[A-Za-z0-9_.$]+"},{quote:'""-qq-bs',prefixes:["@"],requirePrefix:!0},{quote:"''-qq-bs",prefixes:["@"],requirePrefix:!0},{quote:"``",prefixes:["@"],requirePrefix:!0}],paramTypes:{positional:!0},lineCommentTypes:["--","#"],operators:["%",":=","&","|","^","~","<<",">>","<=>","->","->>","&&","||","!","*.*"],postProcess:ll},formatOptions:{onelineClauses:[...Qp,...Oc],tabularOnelineClauses:Oc}},ZH=["ABORT","ABS","ACOS","ADVISOR","ARRAY_AGG","ARRAY_AGG","ARRAY_APPEND","ARRAY_AVG","ARRAY_BINARY_SEARCH","ARRAY_CONCAT","ARRAY_CONTAINS","ARRAY_COUNT","ARRAY_DISTINCT","ARRAY_EXCEPT","ARRAY_FLATTEN","ARRAY_IFNULL","ARRAY_INSERT","ARRAY_INTERSECT","ARRAY_LENGTH","ARRAY_MAX","ARRAY_MIN","ARRAY_MOVE","ARRAY_POSITION","ARRAY_PREPEND","ARRAY_PUT","ARRAY_RANGE","ARRAY_REMOVE","ARRAY_REPEAT","ARRAY_REPLACE","ARRAY_REVERSE","ARRAY_SORT","ARRAY_STAR","ARRAY_SUM","ARRAY_SYMDIFF","ARRAY_SYMDIFF1","ARRAY_SYMDIFFN","ARRAY_UNION","ASIN","ATAN","ATAN2","AVG","BASE64","BASE64_DECODE","BASE64_ENCODE","BITAND ","BITCLEAR ","BITNOT ","BITOR ","BITSET ","BITSHIFT ","BITTEST ","BITXOR ","CEIL","CLOCK_LOCAL","CLOCK_MILLIS","CLOCK_STR","CLOCK_TZ","CLOCK_UTC","COALESCE","CONCAT","CONCAT2","CONTAINS","CONTAINS_TOKEN","CONTAINS_TOKEN_LIKE","CONTAINS_TOKEN_REGEXP","COS","COUNT","COUNT","COUNTN","CUME_DIST","CURL","DATE_ADD_MILLIS","DATE_ADD_STR","DATE_DIFF_MILLIS","DATE_DIFF_STR","DATE_FORMAT_STR","DATE_PART_MILLIS","DATE_PART_STR","DATE_RANGE_MILLIS","DATE_RANGE_STR","DATE_TRUNC_MILLIS","DATE_TRUNC_STR","DECODE","DECODE_JSON","DEGREES","DENSE_RANK","DURATION_TO_STR","ENCODED_SIZE","ENCODE_JSON","EXP","FIRST_VALUE","FLOOR","GREATEST","HAS_TOKEN","IFINF","IFMISSING","IFMISSINGORNULL","IFNAN","IFNANORINF","IFNULL","INITCAP","ISARRAY","ISATOM","ISBITSET","ISBOOLEAN","ISNUMBER","ISOBJECT","ISSTRING","LAG","LAST_VALUE","LEAD","LEAST","LENGTH","LN","LOG","LOWER","LTRIM","MAX","MEAN","MEDIAN","META","MILLIS","MILLIS_TO_LOCAL","MILLIS_TO_STR","MILLIS_TO_TZ","MILLIS_TO_UTC","MILLIS_TO_ZONE_NAME","MIN","MISSINGIF","NANIF","NEGINFIF","NOW_LOCAL","NOW_MILLIS","NOW_STR","NOW_TZ","NOW_UTC","NTH_VALUE","NTILE","NULLIF","NVL","NVL2","OBJECT_ADD","OBJECT_CONCAT","OBJECT_INNER_PAIRS","OBJECT_INNER_VALUES","OBJECT_LENGTH","OBJECT_NAMES","OBJECT_PAIRS","OBJECT_PUT","OBJECT_REMOVE","OBJECT_RENAME","OBJECT_REPLACE","OBJECT_UNWRAP","OBJECT_VALUES","PAIRS","PERCENT_RANK","PI","POLY_LENGTH","POSINFIF","POSITION","POWER","RADIANS","RANDOM","RANK","RATIO_TO_REPORT","REGEXP_CONTAINS","REGEXP_LIKE","REGEXP_MATCHES","REGEXP_POSITION","REGEXP_REPLACE","REGEXP_SPLIT","REGEX_CONTAINS","REGEX_LIKE","REGEX_MATCHES","REGEX_POSITION","REGEX_REPLACE","REGEX_SPLIT","REPEAT","REPLACE","REVERSE","ROUND","ROW_NUMBER","RTRIM","SEARCH","SEARCH_META","SEARCH_SCORE","SIGN","SIN","SPLIT","SQRT","STDDEV","STDDEV_POP","STDDEV_SAMP","STR_TO_DURATION","STR_TO_MILLIS","STR_TO_TZ","STR_TO_UTC","STR_TO_ZONE_NAME","SUBSTR","SUFFIXES","SUM","TAN","TITLE","TOARRAY","TOATOM","TOBOOLEAN","TOKENS","TOKENS","TONUMBER","TOOBJECT","TOSTRING","TRIM","TRUNC","UPPER","UUID","VARIANCE","VARIANCE_POP","VARIANCE_SAMP","VAR_POP","VAR_SAMP","WEEKDAY_MILLIS","WEEKDAY_STR","CAST"],eW=["ADVISE","ALL","ALTER","ANALYZE","AND","ANY","ARRAY","AS","ASC","AT","BEGIN","BETWEEN","BINARY","BOOLEAN","BREAK","BUCKET","BUILD","BY","CALL","CASE","CAST","CLUSTER","COLLATE","COLLECTION","COMMIT","COMMITTED","CONNECT","CONTINUE","CORRELATED","COVER","CREATE","CURRENT","DATABASE","DATASET","DATASTORE","DECLARE","DECREMENT","DELETE","DERIVED","DESC","DESCRIBE","DISTINCT","DO","DROP","EACH","ELEMENT","ELSE","END","EVERY","EXCEPT","EXCLUDE","EXECUTE","EXISTS","EXPLAIN","FALSE","FETCH","FILTER","FIRST","FLATTEN","FLUSH","FOLLOWING","FOR","FORCE","FROM","FTS","FUNCTION","GOLANG","GRANT","GROUP","GROUPS","GSI","HASH","HAVING","IF","IGNORE","ILIKE","IN","INCLUDE","INCREMENT","INDEX","INFER","INLINE","INNER","INSERT","INTERSECT","INTO","IS","ISOLATION","JAVASCRIPT","JOIN","KEY","KEYS","KEYSPACE","KNOWN","LANGUAGE","LAST","LEFT","LET","LETTING","LEVEL","LIKE","LIMIT","LSM","MAP","MAPPING","MATCHED","MATERIALIZED","MERGE","MINUS","MISSING","NAMESPACE","NEST","NL","NO","NOT","NTH_VALUE","NULL","NULLS","NUMBER","OBJECT","OFFSET","ON","OPTION","OPTIONS","OR","ORDER","OTHERS","OUTER","OVER","PARSE","PARTITION","PASSWORD","PATH","POOL","PRECEDING","PREPARE","PRIMARY","PRIVATE","PRIVILEGE","PROBE","PROCEDURE","PUBLIC","RANGE","RAW","REALM","REDUCE","RENAME","RESPECT","RETURN","RETURNING","REVOKE","RIGHT","ROLE","ROLLBACK","ROW","ROWS","SATISFIES","SAVEPOINT","SCHEMA","SCOPE","SELECT","SELF","SEMI","SET","SHOW","SOME","START","STATISTICS","STRING","SYSTEM","THEN","TIES","TO","TRAN","TRANSACTION","TRIGGER","TRUE","TRUNCATE","UNBOUNDED","UNDER","UNION","UNIQUE","UNKNOWN","UNNEST","UNSET","UPDATE","UPSERT","USE","USER","USING","VALIDATE","VALUE","VALUED","VALUES","VIA","VIEW","WHEN","WHERE","WHILE","WINDOW","WITH","WITHIN","WORK","XOR"],tW=[],nW=W(["SELECT [ALL | DISTINCT]"]),rW=W(["WITH","FROM","WHERE","GROUP BY","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","INSERT INTO","VALUES","SET","MERGE INTO","WHEN [NOT] MATCHED THEN","UPDATE SET","INSERT","NEST","UNNEST","RETURNING"]),Zp=W(["UPDATE","DELETE FROM","SET SCHEMA","ADVISE","ALTER INDEX","BEGIN TRANSACTION","BUILD INDEX","COMMIT TRANSACTION","CREATE COLLECTION","CREATE FUNCTION","CREATE INDEX","CREATE PRIMARY INDEX","CREATE SCOPE","DROP COLLECTION","DROP FUNCTION","DROP INDEX","DROP PRIMARY INDEX","DROP SCOPE","EXECUTE","EXECUTE FUNCTION","EXPLAIN","GRANT","INFER","PREPARE","REVOKE","ROLLBACK TRANSACTION","SAVEPOINT","SET TRANSACTION","UPDATE STATISTICS","UPSERT","LET","SET CURRENT SCHEMA","SHOW","USE [PRIMARY] KEYS"]),oW=W(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),sW=W(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","INNER JOIN"]),iW=W(["{ROWS | RANGE | GROUPS} BETWEEN"]),aW=W([]),lW={name:"n1ql",tokenizerOptions:{reservedSelect:nW,reservedClauses:[...rW,...Zp],reservedSetOperations:oW,reservedJoins:sW,reservedKeywordPhrases:iW,reservedDataTypePhrases:aW,supportsXor:!0,reservedKeywords:eW,reservedDataTypes:tW,reservedFunctionNames:ZH,stringTypes:['""-bs',"''-bs"],identTypes:["``"],extraParens:["[]","{}"],paramTypes:{positional:!0,numbered:["$"],named:["$"]},lineCommentTypes:["#","--"],operators:["%","==",":","||"]},formatOptions:{onelineClauses:Zp}},cW=["ADD","AGENT","AGGREGATE","ALL","ALTER","AND","ANY","ARROW","AS","ASC","AT","ATTRIBUTE","AUTHID","AVG","BEGIN","BETWEEN","BLOCK","BODY","BOTH","BOUND","BULK","BY","BYTE","CALL","CALLING","CASCADE","CASE","CHARSET","CHARSETFORM","CHARSETID","CHECK","CLOSE","CLUSTER","CLUSTERS","COLAUTH","COLLECT","COLUMNS","COMMENT","COMMIT","COMMITTED","COMPILED","COMPRESS","CONNECT","CONSTANT","CONSTRUCTOR","CONTEXT","CONVERT","COUNT","CRASH","CREATE","CURRENT","CURSOR","CUSTOMDATUM","DANGLING","DATA","DAY","DECLARE","DEFAULT","DEFINE","DELETE","DESC","DETERMINISTIC","DISTINCT","DROP","DURATION","ELEMENT","ELSE","ELSIF","EMPTY","END","ESCAPE","EXCEPT","EXCEPTION","EXCEPTIONS","EXCLUSIVE","EXECUTE","EXISTS","EXIT","EXTERNAL","FETCH","FINAL","FIXED","FOR","FORALL","FORCE","FORM","FROM","FUNCTION","GENERAL","GOTO","GRANT","GROUP","HASH","HAVING","HEAP","HIDDEN","HOUR","IDENTIFIED","IF","IMMEDIATE","IN","INCLUDING","INDEX","INDEXES","INDICATOR","INDICES","INFINITE","INSERT","INSTANTIABLE","INTERFACE","INTERSECT","INTERVAL","INTO","INVALIDATE","IS","ISOLATION","JAVA","LANGUAGE","LARGE","LEADING","LENGTH","LEVEL","LIBRARY","LIKE","LIKE2","LIKE4","LIKEC","LIMIT","LIMITED","LOCAL","LOCK","LOOP","MAP","MAX","MAXLEN","MEMBER","MERGE","MIN","MINUS","MINUTE","MOD","MODE","MODIFY","MONTH","MULTISET","NAME","NAN","NATIONAL","NATIVE","NEW","NOCOMPRESS","NOCOPY","NOT","NOWAIT","NULL","OBJECT","OCICOLL","OCIDATE","OCIDATETIME","OCIDURATION","OCIINTERVAL","OCILOBLOCATOR","OCINUMBER","OCIRAW","OCIREF","OCIREFCURSOR","OCIROWID","OCISTRING","OCITYPE","OF","ON","ONLY","OPAQUE","OPEN","OPERATOR","OPTION","OR","ORACLE","ORADATA","ORDER","OVERLAPS","ORGANIZATION","ORLANY","ORLVARY","OTHERS","OUT","OVERRIDING","PACKAGE","PARALLEL_ENABLE","PARAMETER","PARAMETERS","PARTITION","PASCAL","PIPE","PIPELINED","PRAGMA","PRIOR","PRIVATE","PROCEDURE","PUBLIC","RAISE","RANGE","READ","RECORD","REF","REFERENCE","REM","REMAINDER","RENAME","RESOURCE","RESULT","RETURN","RETURNING","REVERSE","REVOKE","ROLLBACK","ROW","SAMPLE","SAVE","SAVEPOINT","SB1","SB2","SB4","SECOND","SEGMENT","SELECT","SELF","SEPARATE","SEQUENCE","SERIALIZABLE","SET","SHARE","SHORT","SIZE","SIZE_T","SOME","SPARSE","SQL","SQLCODE","SQLDATA","SQLNAME","SQLSTATE","STANDARD","START","STATIC","STDDEV","STORED","STRING","STRUCT","STYLE","SUBMULTISET","SUBPARTITION","SUBSTITUTABLE","SUBTYPE","SUM","SYNONYM","TABAUTH","TABLE","TDO","THE","THEN","TIME","TIMEZONE_ABBR","TIMEZONE_HOUR","TIMEZONE_MINUTE","TIMEZONE_REGION","TO","TRAILING","TRANSAC","TRANSACTIONAL","TRUSTED","TYPE","UB1","UB2","UB4","UNDER","UNION","UNIQUE","UNSIGNED","UNTRUSTED","UPDATE","USE","USING","VALIST","VALUE","VALUES","VARIABLE","VARIANCE","VARRAY","VIEW","VIEWS","VOID","WHEN","WHERE","WHILE","WITH","WORK","WRAPPED","WRITE","YEAR","ZONE"],dW=["ARRAY","BFILE_BASE","BINARY","BLOB_BASE","CHAR VARYING","CHAR_BASE","CHAR","CHARACTER VARYING","CHARACTER","CLOB_BASE","DATE_BASE","DATE","DECIMAL","DOUBLE","FLOAT","INT","INTERVAL DAY","INTERVAL YEAR","LONG","NATIONAL CHAR VARYING","NATIONAL CHAR","NATIONAL CHARACTER VARYING","NATIONAL CHARACTER","NCHAR VARYING","NCHAR","NCHAR","NUMBER_BASE","NUMBER","NUMBERIC","NVARCHAR","PRECISION","RAW","TIMESTAMP","UROWID","VARCHAR","VARCHAR2"],uW=["ABS","ACOS","ASIN","ATAN","ATAN2","BITAND","CEIL","COS","COSH","EXP","FLOOR","LN","LOG","MOD","NANVL","POWER","REMAINDER","ROUND","SIGN","SIN","SINH","SQRT","TAN","TANH","TRUNC","WIDTH_BUCKET","CHR","CONCAT","INITCAP","LOWER","LPAD","LTRIM","NLS_INITCAP","NLS_LOWER","NLSSORT","NLS_UPPER","REGEXP_REPLACE","REGEXP_SUBSTR","REPLACE","RPAD","RTRIM","SOUNDEX","SUBSTR","TRANSLATE","TREAT","TRIM","UPPER","NLS_CHARSET_DECL_LEN","NLS_CHARSET_ID","NLS_CHARSET_NAME","ASCII","INSTR","LENGTH","REGEXP_INSTR","ADD_MONTHS","CURRENT_DATE","CURRENT_TIMESTAMP","DBTIMEZONE","EXTRACT","FROM_TZ","LAST_DAY","LOCALTIMESTAMP","MONTHS_BETWEEN","NEW_TIME","NEXT_DAY","NUMTODSINTERVAL","NUMTOYMINTERVAL","ROUND","SESSIONTIMEZONE","SYS_EXTRACT_UTC","SYSDATE","SYSTIMESTAMP","TO_CHAR","TO_TIMESTAMP","TO_TIMESTAMP_TZ","TO_DSINTERVAL","TO_YMINTERVAL","TRUNC","TZ_OFFSET","GREATEST","LEAST","ASCIISTR","BIN_TO_NUM","CAST","CHARTOROWID","COMPOSE","CONVERT","DECOMPOSE","HEXTORAW","NUMTODSINTERVAL","NUMTOYMINTERVAL","RAWTOHEX","RAWTONHEX","ROWIDTOCHAR","ROWIDTONCHAR","SCN_TO_TIMESTAMP","TIMESTAMP_TO_SCN","TO_BINARY_DOUBLE","TO_BINARY_FLOAT","TO_CHAR","TO_CLOB","TO_DATE","TO_DSINTERVAL","TO_LOB","TO_MULTI_BYTE","TO_NCHAR","TO_NCLOB","TO_NUMBER","TO_DSINTERVAL","TO_SINGLE_BYTE","TO_TIMESTAMP","TO_TIMESTAMP_TZ","TO_YMINTERVAL","TO_YMINTERVAL","TRANSLATE","UNISTR","BFILENAME","EMPTY_BLOB,","EMPTY_CLOB","CARDINALITY","COLLECT","POWERMULTISET","POWERMULTISET_BY_CARDINALITY","SET","SYS_CONNECT_BY_PATH","CLUSTER_ID","CLUSTER_PROBABILITY","CLUSTER_SET","FEATURE_ID","FEATURE_SET","FEATURE_VALUE","PREDICTION","PREDICTION_COST","PREDICTION_DETAILS","PREDICTION_PROBABILITY","PREDICTION_SET","APPENDCHILDXML","DELETEXML","DEPTH","EXTRACT","EXISTSNODE","EXTRACTVALUE","INSERTCHILDXML","INSERTXMLBEFORE","PATH","SYS_DBURIGEN","SYS_XMLAGG","SYS_XMLGEN","UPDATEXML","XMLAGG","XMLCDATA","XMLCOLATTVAL","XMLCOMMENT","XMLCONCAT","XMLFOREST","XMLPARSE","XMLPI","XMLQUERY","XMLROOT","XMLSEQUENCE","XMLSERIALIZE","XMLTABLE","XMLTRANSFORM","DECODE","DUMP","ORA_HASH","VSIZE","COALESCE","LNNVL","NULLIF","NVL","NVL2","SYS_CONTEXT","SYS_GUID","SYS_TYPEID","UID","USER","USERENV","AVG","COLLECT","CORR","CORR_S","CORR_K","COUNT","COVAR_POP","COVAR_SAMP","CUME_DIST","DENSE_RANK","FIRST","GROUP_ID","GROUPING","GROUPING_ID","LAST","MAX","MEDIAN","MIN","PERCENTILE_CONT","PERCENTILE_DISC","PERCENT_RANK","RANK","REGR_SLOPE","REGR_INTERCEPT","REGR_COUNT","REGR_R2","REGR_AVGX","REGR_AVGY","REGR_SXX","REGR_SYY","REGR_SXY","STATS_BINOMIAL_TEST","STATS_CROSSTAB","STATS_F_TEST","STATS_KS_TEST","STATS_MODE","STATS_MW_TEST","STATS_ONE_WAY_ANOVA","STATS_T_TEST_ONE","STATS_T_TEST_PAIRED","STATS_T_TEST_INDEP","STATS_T_TEST_INDEPU","STATS_WSR_TEST","STDDEV","STDDEV_POP","STDDEV_SAMP","SUM","VAR_POP","VAR_SAMP","VARIANCE","FIRST_VALUE","LAG","LAST_VALUE","LEAD","NTILE","RATIO_TO_REPORT","ROW_NUMBER","DEREF","MAKE_REF","REF","REFTOHEX","VALUE","CV","ITERATION_NUMBER","PRESENTNNV","PRESENTV","PREVIOUS"],EW=W(["SELECT [ALL | DISTINCT | UNIQUE]"]),fW=W(["WITH","FROM","WHERE","GROUP BY","HAVING","PARTITION BY","ORDER [SIBLINGS] BY","OFFSET","FETCH {FIRST | NEXT}","FOR UPDATE [OF]","INSERT [INTO | ALL INTO]","VALUES","SET","MERGE [INTO]","WHEN [NOT] MATCHED [THEN]","UPDATE SET","RETURNING"]),eT=W(["CREATE [GLOBAL TEMPORARY | PRIVATE TEMPORARY | SHARDED | DUPLICATED | IMMUTABLE BLOCKCHAIN | BLOCKCHAIN | IMMUTABLE] TABLE"]),Nc=W(["CREATE [OR REPLACE] [NO FORCE | FORCE] [EDITIONING | EDITIONABLE | EDITIONABLE EDITIONING | NONEDITIONABLE] VIEW","CREATE MATERIALIZED VIEW","UPDATE [ONLY]","DELETE FROM [ONLY]","DROP TABLE","ALTER TABLE","ADD","DROP {COLUMN | UNUSED COLUMNS | COLUMNS CONTINUE}","MODIFY","RENAME TO","RENAME COLUMN","TRUNCATE TABLE","SET SCHEMA","BEGIN","CONNECT BY","DECLARE","EXCEPT","EXCEPTION","LOOP","START WITH"]),pW=W(["UNION [ALL]","MINUS","INTERSECT"]),TW=W(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN","{CROSS | OUTER} APPLY"]),SW=W(["ON {UPDATE | DELETE} [SET NULL]","ON COMMIT","{ROWS | RANGE} BETWEEN"]),hW=W([]),RW={name:"plsql",tokenizerOptions:{reservedSelect:EW,reservedClauses:[...fW,...eT,...Nc],reservedSetOperations:pW,reservedJoins:TW,reservedKeywordPhrases:SW,reservedDataTypePhrases:hW,supportsXor:!0,reservedKeywords:cW,reservedDataTypes:dW,reservedFunctionNames:uW,stringTypes:[{quote:"''-qq",prefixes:["N"]},{quote:"q''",prefixes:["N"]}],identTypes:['""-qq'],identChars:{rest:"$#"},variableTypes:[{regex:"&{1,2}[A-Za-z][A-Za-z0-9_$#]*"}],paramTypes:{numbered:[":"],named:[":"]},operators:["**",":=","%","~=","^=",">>","<<","=>","@","||"],postProcess:AW},formatOptions:{alwaysDenseOperators:["@"],onelineClauses:[...eT,...Nc],tabularOnelineClauses:Nc}};function AW(e){let t=Hn;return e.map(n=>Wn.SET(n)&&Wn.BY(t)?Object.assign(Object.assign({},n),{type:J.RESERVED_KEYWORD}):(yg(n.type)&&(t=n),n))}const mW=["ABS","ACOS","ACOSD","ACOSH","ASIN","ASIND","ASINH","ATAN","ATAN2","ATAN2D","ATAND","ATANH","CBRT","CEIL","CEILING","COS","COSD","COSH","COT","COTD","DEGREES","DIV","EXP","FACTORIAL","FLOOR","GCD","LCM","LN","LOG","LOG10","MIN_SCALE","MOD","PI","POWER","RADIANS","RANDOM","ROUND","SCALE","SETSEED","SIGN","SIN","SIND","SINH","SQRT","TAN","TAND","TANH","TRIM_SCALE","TRUNC","WIDTH_BUCKET","ABS","ASCII","BIT_LENGTH","BTRIM","CHARACTER_LENGTH","CHAR_LENGTH","CHR","CONCAT","CONCAT_WS","FORMAT","INITCAP","LEFT","LENGTH","LOWER","LPAD","LTRIM","MD5","NORMALIZE","OCTET_LENGTH","OVERLAY","PARSE_IDENT","PG_CLIENT_ENCODING","POSITION","QUOTE_IDENT","QUOTE_LITERAL","QUOTE_NULLABLE","REGEXP_MATCH","REGEXP_MATCHES","REGEXP_REPLACE","REGEXP_SPLIT_TO_ARRAY","REGEXP_SPLIT_TO_TABLE","REPEAT","REPLACE","REVERSE","RIGHT","RPAD","RTRIM","SPLIT_PART","SPRINTF","STARTS_WITH","STRING_AGG","STRING_TO_ARRAY","STRING_TO_TABLE","STRPOS","SUBSTR","SUBSTRING","TO_ASCII","TO_HEX","TRANSLATE","TRIM","UNISTR","UPPER","BIT_COUNT","BIT_LENGTH","BTRIM","CONVERT","CONVERT_FROM","CONVERT_TO","DECODE","ENCODE","GET_BIT","GET_BYTE","LENGTH","LTRIM","MD5","OCTET_LENGTH","OVERLAY","POSITION","RTRIM","SET_BIT","SET_BYTE","SHA224","SHA256","SHA384","SHA512","STRING_AGG","SUBSTR","SUBSTRING","TRIM","BIT_COUNT","BIT_LENGTH","GET_BIT","LENGTH","OCTET_LENGTH","OVERLAY","POSITION","SET_BIT","SUBSTRING","REGEXP_MATCH","REGEXP_MATCHES","REGEXP_REPLACE","REGEXP_SPLIT_TO_ARRAY","REGEXP_SPLIT_TO_TABLE","TO_CHAR","TO_DATE","TO_NUMBER","TO_TIMESTAMP","CLOCK_TIMESTAMP","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","DATE_BIN","DATE_PART","DATE_TRUNC","EXTRACT","ISFINITE","JUSTIFY_DAYS","JUSTIFY_HOURS","JUSTIFY_INTERVAL","LOCALTIME","LOCALTIMESTAMP","MAKE_DATE","MAKE_INTERVAL","MAKE_TIME","MAKE_TIMESTAMP","MAKE_TIMESTAMPTZ","NOW","PG_SLEEP","PG_SLEEP_FOR","PG_SLEEP_UNTIL","STATEMENT_TIMESTAMP","TIMEOFDAY","TO_TIMESTAMP","TRANSACTION_TIMESTAMP","ENUM_FIRST","ENUM_LAST","ENUM_RANGE","AREA","BOUND_BOX","BOX","CENTER","CIRCLE","DIAGONAL","DIAMETER","HEIGHT","ISCLOSED","ISOPEN","LENGTH","LINE","LSEG","NPOINTS","PATH","PCLOSE","POINT","POLYGON","POPEN","RADIUS","SLOPE","WIDTH","ABBREV","BROADCAST","FAMILY","HOST","HOSTMASK","INET_MERGE","INET_SAME_FAMILY","MACADDR8_SET7BIT","MASKLEN","NETMASK","NETWORK","SET_MASKLEN","TRUNC","ARRAY_TO_TSVECTOR","GET_CURRENT_TS_CONFIG","JSONB_TO_TSVECTOR","JSON_TO_TSVECTOR","LENGTH","NUMNODE","PHRASETO_TSQUERY","PLAINTO_TSQUERY","QUERYTREE","SETWEIGHT","STRIP","TO_TSQUERY","TO_TSVECTOR","TSQUERY_PHRASE","TSVECTOR_TO_ARRAY","TS_DEBUG","TS_DELETE","TS_FILTER","TS_HEADLINE","TS_LEXIZE","TS_PARSE","TS_RANK","TS_RANK_CD","TS_REWRITE","TS_STAT","TS_TOKEN_TYPE","WEBSEARCH_TO_TSQUERY","GEN_RANDOM_UUID","UUIDV4","UUIDV7","UUID_EXTRACT_TIMESTAMP","UUID_EXTRACT_VERSION","CURSOR_TO_XML","CURSOR_TO_XMLSCHEMA","DATABASE_TO_XML","DATABASE_TO_XMLSCHEMA","DATABASE_TO_XML_AND_XMLSCHEMA","NEXTVAL","QUERY_TO_XML","QUERY_TO_XMLSCHEMA","QUERY_TO_XML_AND_XMLSCHEMA","SCHEMA_TO_XML","SCHEMA_TO_XMLSCHEMA","SCHEMA_TO_XML_AND_XMLSCHEMA","STRING","TABLE_TO_XML","TABLE_TO_XMLSCHEMA","TABLE_TO_XML_AND_XMLSCHEMA","XMLAGG","XMLCOMMENT","XMLCONCAT","XMLELEMENT","XMLEXISTS","XMLFOREST","XMLPARSE","XMLPI","XMLROOT","XMLSERIALIZE","XMLTABLE","XML_IS_WELL_FORMED","XML_IS_WELL_FORMED_CONTENT","XML_IS_WELL_FORMED_DOCUMENT","XPATH","XPATH_EXISTS","ARRAY_TO_JSON","JSONB_AGG","JSONB_ARRAY_ELEMENTS","JSONB_ARRAY_ELEMENTS_TEXT","JSONB_ARRAY_LENGTH","JSONB_BUILD_ARRAY","JSONB_BUILD_OBJECT","JSONB_EACH","JSONB_EACH_TEXT","JSONB_EXTRACT_PATH","JSONB_EXTRACT_PATH_TEXT","JSONB_INSERT","JSONB_OBJECT","JSONB_OBJECT_AGG","JSONB_OBJECT_KEYS","JSONB_PATH_EXISTS","JSONB_PATH_EXISTS_TZ","JSONB_PATH_MATCH","JSONB_PATH_MATCH_TZ","JSONB_PATH_QUERY","JSONB_PATH_QUERY_ARRAY","JSONB_PATH_QUERY_ARRAY_TZ","JSONB_PATH_QUERY_FIRST","JSONB_PATH_QUERY_FIRST_TZ","JSONB_PATH_QUERY_TZ","JSONB_POPULATE_RECORD","JSONB_POPULATE_RECORDSET","JSONB_PRETTY","JSONB_SET","JSONB_SET_LAX","JSONB_STRIP_NULLS","JSONB_TO_RECORD","JSONB_TO_RECORDSET","JSONB_TYPEOF","JSON_AGG","JSON_ARRAY_ELEMENTS","JSON_ARRAY_ELEMENTS_TEXT","JSON_ARRAY_LENGTH","JSON_BUILD_ARRAY","JSON_BUILD_OBJECT","JSON_EACH","JSON_EACH_TEXT","JSON_EXTRACT_PATH","JSON_EXTRACT_PATH_TEXT","JSON_OBJECT","JSON_OBJECT_AGG","JSON_OBJECT_KEYS","JSON_POPULATE_RECORD","JSON_POPULATE_RECORDSET","JSON_STRIP_NULLS","JSON_TO_RECORD","JSON_TO_RECORDSET","JSON_TYPEOF","ROW_TO_JSON","TO_JSON","TO_JSONB","TO_TIMESTAMP","CURRVAL","LASTVAL","NEXTVAL","SETVAL","COALESCE","GREATEST","LEAST","NULLIF","ARRAY_AGG","ARRAY_APPEND","ARRAY_CAT","ARRAY_DIMS","ARRAY_FILL","ARRAY_LENGTH","ARRAY_LOWER","ARRAY_NDIMS","ARRAY_POSITION","ARRAY_POSITIONS","ARRAY_PREPEND","ARRAY_REMOVE","ARRAY_REPLACE","ARRAY_TO_STRING","ARRAY_UPPER","CARDINALITY","STRING_TO_ARRAY","TRIM_ARRAY","UNNEST","ISEMPTY","LOWER","LOWER_INC","LOWER_INF","MULTIRANGE","RANGE_MERGE","UPPER","UPPER_INC","UPPER_INF","ARRAY_AGG","AVG","BIT_AND","BIT_OR","BIT_XOR","BOOL_AND","BOOL_OR","COALESCE","CORR","COUNT","COVAR_POP","COVAR_SAMP","CUME_DIST","DENSE_RANK","EVERY","GROUPING","JSONB_AGG","JSONB_OBJECT_AGG","JSON_AGG","JSON_OBJECT_AGG","MAX","MIN","MODE","PERCENTILE_CONT","PERCENTILE_DISC","PERCENT_RANK","RANGE_AGG","RANGE_INTERSECT_AGG","RANK","REGR_AVGX","REGR_AVGY","REGR_COUNT","REGR_INTERCEPT","REGR_R2","REGR_SLOPE","REGR_SXX","REGR_SXY","REGR_SYY","STDDEV","STDDEV_POP","STDDEV_SAMP","STRING_AGG","SUM","TO_JSON","TO_JSONB","VARIANCE","VAR_POP","VAR_SAMP","XMLAGG","CUME_DIST","DENSE_RANK","FIRST_VALUE","LAG","LAST_VALUE","LEAD","NTH_VALUE","NTILE","PERCENT_RANK","RANK","ROW_NUMBER","GENERATE_SERIES","GENERATE_SUBSCRIPTS","ACLDEFAULT","ACLEXPLODE","COL_DESCRIPTION","CURRENT_CATALOG","CURRENT_DATABASE","CURRENT_QUERY","CURRENT_ROLE","CURRENT_SCHEMA","CURRENT_SCHEMAS","CURRENT_USER","FORMAT_TYPE","HAS_ANY_COLUMN_PRIVILEGE","HAS_COLUMN_PRIVILEGE","HAS_DATABASE_PRIVILEGE","HAS_FOREIGN_DATA_WRAPPER_PRIVILEGE","HAS_FUNCTION_PRIVILEGE","HAS_LANGUAGE_PRIVILEGE","HAS_SCHEMA_PRIVILEGE","HAS_SEQUENCE_PRIVILEGE","HAS_SERVER_PRIVILEGE","HAS_TABLESPACE_PRIVILEGE","HAS_TABLE_PRIVILEGE","HAS_TYPE_PRIVILEGE","INET_CLIENT_ADDR","INET_CLIENT_PORT","INET_SERVER_ADDR","INET_SERVER_PORT","MAKEACLITEM","OBJ_DESCRIPTION","PG_BACKEND_PID","PG_BLOCKING_PIDS","PG_COLLATION_IS_VISIBLE","PG_CONF_LOAD_TIME","PG_CONTROL_CHECKPOINT","PG_CONTROL_INIT","PG_CONTROL_SYSTEM","PG_CONVERSION_IS_VISIBLE","PG_CURRENT_LOGFILE","PG_CURRENT_SNAPSHOT","PG_CURRENT_XACT_ID","PG_CURRENT_XACT_ID_IF_ASSIGNED","PG_DESCRIBE_OBJECT","PG_FUNCTION_IS_VISIBLE","PG_GET_CATALOG_FOREIGN_KEYS","PG_GET_CONSTRAINTDEF","PG_GET_EXPR","PG_GET_FUNCTIONDEF","PG_GET_FUNCTION_ARGUMENTS","PG_GET_FUNCTION_IDENTITY_ARGUMENTS","PG_GET_FUNCTION_RESULT","PG_GET_INDEXDEF","PG_GET_KEYWORDS","PG_GET_OBJECT_ADDRESS","PG_GET_OWNED_SEQUENCE","PG_GET_RULEDEF","PG_GET_SERIAL_SEQUENCE","PG_GET_STATISTICSOBJDEF","PG_GET_TRIGGERDEF","PG_GET_USERBYID","PG_GET_VIEWDEF","PG_HAS_ROLE","PG_IDENTIFY_OBJECT","PG_IDENTIFY_OBJECT_AS_ADDRESS","PG_INDEXAM_HAS_PROPERTY","PG_INDEX_COLUMN_HAS_PROPERTY","PG_INDEX_HAS_PROPERTY","PG_IS_OTHER_TEMP_SCHEMA","PG_JIT_AVAILABLE","PG_LAST_COMMITTED_XACT","PG_LISTENING_CHANNELS","PG_MY_TEMP_SCHEMA","PG_NOTIFICATION_QUEUE_USAGE","PG_OPCLASS_IS_VISIBLE","PG_OPERATOR_IS_VISIBLE","PG_OPFAMILY_IS_VISIBLE","PG_OPTIONS_TO_TABLE","PG_POSTMASTER_START_TIME","PG_SAFE_SNAPSHOT_BLOCKING_PIDS","PG_SNAPSHOT_XIP","PG_SNAPSHOT_XMAX","PG_SNAPSHOT_XMIN","PG_STATISTICS_OBJ_IS_VISIBLE","PG_TABLESPACE_DATABASES","PG_TABLESPACE_LOCATION","PG_TABLE_IS_VISIBLE","PG_TRIGGER_DEPTH","PG_TS_CONFIG_IS_VISIBLE","PG_TS_DICT_IS_VISIBLE","PG_TS_PARSER_IS_VISIBLE","PG_TS_TEMPLATE_IS_VISIBLE","PG_TYPEOF","PG_TYPE_IS_VISIBLE","PG_VISIBLE_IN_SNAPSHOT","PG_XACT_COMMIT_TIMESTAMP","PG_XACT_COMMIT_TIMESTAMP_ORIGIN","PG_XACT_STATUS","PQSERVERVERSION","ROW_SECURITY_ACTIVE","SESSION_USER","SHOBJ_DESCRIPTION","TO_REGCLASS","TO_REGCOLLATION","TO_REGNAMESPACE","TO_REGOPER","TO_REGOPERATOR","TO_REGPROC","TO_REGPROCEDURE","TO_REGROLE","TO_REGTYPE","TXID_CURRENT","TXID_CURRENT_IF_ASSIGNED","TXID_CURRENT_SNAPSHOT","TXID_SNAPSHOT_XIP","TXID_SNAPSHOT_XMAX","TXID_SNAPSHOT_XMIN","TXID_STATUS","TXID_VISIBLE_IN_SNAPSHOT","USER","VERSION","BRIN_DESUMMARIZE_RANGE","BRIN_SUMMARIZE_NEW_VALUES","BRIN_SUMMARIZE_RANGE","CONVERT_FROM","CURRENT_SETTING","GIN_CLEAN_PENDING_LIST","PG_ADVISORY_LOCK","PG_ADVISORY_LOCK_SHARED","PG_ADVISORY_UNLOCK","PG_ADVISORY_UNLOCK_ALL","PG_ADVISORY_UNLOCK_SHARED","PG_ADVISORY_XACT_LOCK","PG_ADVISORY_XACT_LOCK_SHARED","PG_BACKUP_START_TIME","PG_CANCEL_BACKEND","PG_COLLATION_ACTUAL_VERSION","PG_COLUMN_COMPRESSION","PG_COLUMN_SIZE","PG_COPY_LOGICAL_REPLICATION_SLOT","PG_COPY_PHYSICAL_REPLICATION_SLOT","PG_CREATE_LOGICAL_REPLICATION_SLOT","PG_CREATE_PHYSICAL_REPLICATION_SLOT","PG_CREATE_RESTORE_POINT","PG_CURRENT_WAL_FLUSH_LSN","PG_CURRENT_WAL_INSERT_LSN","PG_CURRENT_WAL_LSN","PG_DATABASE_SIZE","PG_DROP_REPLICATION_SLOT","PG_EXPORT_SNAPSHOT","PG_FILENODE_RELATION","PG_GET_WAL_REPLAY_PAUSE_STATE","PG_IMPORT_SYSTEM_COLLATIONS","PG_INDEXES_SIZE","PG_IS_IN_BACKUP","PG_IS_IN_RECOVERY","PG_IS_WAL_REPLAY_PAUSED","PG_LAST_WAL_RECEIVE_LSN","PG_LAST_WAL_REPLAY_LSN","PG_LAST_XACT_REPLAY_TIMESTAMP","PG_LOGICAL_EMIT_MESSAGE","PG_LOGICAL_SLOT_GET_BINARY_CHANGES","PG_LOGICAL_SLOT_GET_CHANGES","PG_LOGICAL_SLOT_PEEK_BINARY_CHANGES","PG_LOGICAL_SLOT_PEEK_CHANGES","PG_LOG_BACKEND_MEMORY_CONTEXTS","PG_LS_ARCHIVE_STATUSDIR","PG_LS_DIR","PG_LS_LOGDIR","PG_LS_TMPDIR","PG_LS_WALDIR","PG_PARTITION_ANCESTORS","PG_PARTITION_ROOT","PG_PARTITION_TREE","PG_PROMOTE","PG_READ_BINARY_FILE","PG_READ_FILE","PG_RELATION_FILENODE","PG_RELATION_FILEPATH","PG_RELATION_SIZE","PG_RELOAD_CONF","PG_REPLICATION_ORIGIN_ADVANCE","PG_REPLICATION_ORIGIN_CREATE","PG_REPLICATION_ORIGIN_DROP","PG_REPLICATION_ORIGIN_OID","PG_REPLICATION_ORIGIN_PROGRESS","PG_REPLICATION_ORIGIN_SESSION_IS_SETUP","PG_REPLICATION_ORIGIN_SESSION_PROGRESS","PG_REPLICATION_ORIGIN_SESSION_RESET","PG_REPLICATION_ORIGIN_SESSION_SETUP","PG_REPLICATION_ORIGIN_XACT_RESET","PG_REPLICATION_ORIGIN_XACT_SETUP","PG_REPLICATION_SLOT_ADVANCE","PG_ROTATE_LOGFILE","PG_SIZE_BYTES","PG_SIZE_PRETTY","PG_START_BACKUP","PG_STAT_FILE","PG_STOP_BACKUP","PG_SWITCH_WAL","PG_TABLESPACE_SIZE","PG_TABLE_SIZE","PG_TERMINATE_BACKEND","PG_TOTAL_RELATION_SIZE","PG_TRY_ADVISORY_LOCK","PG_TRY_ADVISORY_LOCK_SHARED","PG_TRY_ADVISORY_XACT_LOCK","PG_TRY_ADVISORY_XACT_LOCK_SHARED","PG_WALFILE_NAME","PG_WALFILE_NAME_OFFSET","PG_WAL_LSN_DIFF","PG_WAL_REPLAY_PAUSE","PG_WAL_REPLAY_RESUME","SET_CONFIG","SUPPRESS_REDUNDANT_UPDATES_TRIGGER","TSVECTOR_UPDATE_TRIGGER","TSVECTOR_UPDATE_TRIGGER_COLUMN","PG_EVENT_TRIGGER_DDL_COMMANDS","PG_EVENT_TRIGGER_DROPPED_OBJECTS","PG_EVENT_TRIGGER_TABLE_REWRITE_OID","PG_EVENT_TRIGGER_TABLE_REWRITE_REASON","PG_GET_OBJECT_ADDRESS","PG_MCV_LIST_ITEMS","CAST"],gW=["ALL","ANALYSE","ANALYZE","AND","ANY","AS","ASC","ASYMMETRIC","AUTHORIZATION","BETWEEN","BINARY","BOTH","CASE","CAST","CHECK","COLLATE","COLLATION","COLUMN","CONCURRENTLY","CONSTRAINT","CREATE","CROSS","CURRENT_CATALOG","CURRENT_DATE","CURRENT_ROLE","CURRENT_SCHEMA","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","DAY","DEFAULT","DEFERRABLE","DESC","DISTINCT","DO","ELSE","END","EXCEPT","EXISTS","FALSE","FETCH","FILTER","FOR","FOREIGN","FREEZE","FROM","FULL","GRANT","GROUP","HAVING","HOUR","ILIKE","IN","INITIALLY","INNER","INOUT","INTERSECT","INTO","IS","ISNULL","JOIN","LATERAL","LEADING","LEFT","LIKE","LIMIT","LOCALTIME","LOCALTIMESTAMP","MINUTE","MONTH","NATURAL","NOT","NOTNULL","NULL","NULLIF","OFFSET","ON","ONLY","OR","ORDER","OUT","OUTER","OVER","OVERLAPS","PLACING","PRIMARY","REFERENCES","RETURNING","RIGHT","ROW","SECOND","SELECT","SESSION_USER","SIMILAR","SOME","SYMMETRIC","TABLE","TABLESAMPLE","THEN","TO","TRAILING","TRUE","UNION","UNIQUE","USER","USING","VALUES","VARIADIC","VERBOSE","WHEN","WHERE","WINDOW","WITH","WITHIN","WITHOUT","YEAR"],IW=["ARRAY","BIGINT","BIT","BIT VARYING","BOOL","BOOLEAN","CHAR","CHARACTER","CHARACTER VARYING","DECIMAL","DEC","DOUBLE","ENUM","FLOAT","INT","INTEGER","INTERVAL","NCHAR","NUMERIC","JSON","JSONB","PRECISION","REAL","SMALLINT","TEXT","TIME","TIMESTAMP","TIMESTAMPTZ","UUID","VARCHAR","XML","ZONE"],OW=W(["SELECT [ALL | DISTINCT]"]),NW=W(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY [ALL | DISTINCT]","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","FETCH {FIRST | NEXT}","FOR {UPDATE | NO KEY UPDATE | SHARE | KEY SHARE} [OF]","INSERT INTO","VALUES","DEFAULT VALUES","SET","RETURNING"]),tT=W(["CREATE [GLOBAL | LOCAL] [TEMPORARY | TEMP | UNLOGGED] TABLE [IF NOT EXISTS]"]),xc=W(["CREATE [OR REPLACE] [TEMP | TEMPORARY] [RECURSIVE] VIEW","CREATE [MATERIALIZED] VIEW [IF NOT EXISTS]","UPDATE [ONLY]","WHERE CURRENT OF","ON CONFLICT","DELETE FROM [ONLY]","DROP TABLE [IF EXISTS]","ALTER TABLE [IF EXISTS] [ONLY]","ALTER TABLE ALL IN TABLESPACE","RENAME [COLUMN]","RENAME TO","ADD [COLUMN] [IF NOT EXISTS]","DROP [COLUMN] [IF EXISTS]","ALTER [COLUMN]","SET DATA TYPE","{SET | DROP} DEFAULT","{SET | DROP} NOT NULL","TRUNCATE [TABLE] [ONLY]","SET SCHEMA","AFTER","ABORT","ALTER AGGREGATE","ALTER COLLATION","ALTER CONVERSION","ALTER DATABASE","ALTER DEFAULT PRIVILEGES","ALTER DOMAIN","ALTER EVENT TRIGGER","ALTER EXTENSION","ALTER FOREIGN DATA WRAPPER","ALTER FOREIGN TABLE","ALTER FUNCTION","ALTER GROUP","ALTER INDEX","ALTER LANGUAGE","ALTER LARGE OBJECT","ALTER MATERIALIZED VIEW","ALTER OPERATOR","ALTER OPERATOR CLASS","ALTER OPERATOR FAMILY","ALTER POLICY","ALTER PROCEDURE","ALTER PUBLICATION","ALTER ROLE","ALTER ROUTINE","ALTER RULE","ALTER SCHEMA","ALTER SEQUENCE","ALTER SERVER","ALTER STATISTICS","ALTER SUBSCRIPTION","ALTER SYSTEM","ALTER TABLESPACE","ALTER TEXT SEARCH CONFIGURATION","ALTER TEXT SEARCH DICTIONARY","ALTER TEXT SEARCH PARSER","ALTER TEXT SEARCH TEMPLATE","ALTER TRIGGER","ALTER TYPE","ALTER USER","ALTER USER MAPPING","ALTER VIEW","ANALYZE","BEGIN","CALL","CHECKPOINT","CLOSE","CLUSTER","COMMENT ON","COMMIT","COMMIT PREPARED","COPY","CREATE ACCESS METHOD","CREATE [OR REPLACE] AGGREGATE","CREATE CAST","CREATE COLLATION","CREATE [DEFAULT] CONVERSION","CREATE DATABASE","CREATE DOMAIN","CREATE EVENT TRIGGER","CREATE EXTENSION","CREATE FOREIGN DATA WRAPPER","CREATE FOREIGN TABLE","CREATE [OR REPLACE] FUNCTION","CREATE GROUP","CREATE [UNIQUE] INDEX","CREATE [OR REPLACE] [TRUSTED] [PROCEDURAL] LANGUAGE","CREATE OPERATOR","CREATE OPERATOR CLASS","CREATE OPERATOR FAMILY","CREATE POLICY","CREATE [OR REPLACE] PROCEDURE","CREATE PUBLICATION","CREATE ROLE","CREATE [OR REPLACE] RULE","CREATE SCHEMA [AUTHORIZATION]","CREATE [TEMPORARY | TEMP | UNLOGGED] SEQUENCE","CREATE SERVER","CREATE STATISTICS","CREATE SUBSCRIPTION","CREATE TABLESPACE","CREATE TEXT SEARCH CONFIGURATION","CREATE TEXT SEARCH DICTIONARY","CREATE TEXT SEARCH PARSER","CREATE TEXT SEARCH TEMPLATE","CREATE [OR REPLACE] TRANSFORM","CREATE [OR REPLACE] [CONSTRAINT] TRIGGER","CREATE TYPE","CREATE USER","CREATE USER MAPPING","DEALLOCATE","DECLARE","DISCARD","DROP ACCESS METHOD","DROP AGGREGATE","DROP CAST","DROP COLLATION","DROP CONVERSION","DROP DATABASE","DROP DOMAIN","DROP EVENT TRIGGER","DROP EXTENSION","DROP FOREIGN DATA WRAPPER","DROP FOREIGN TABLE","DROP FUNCTION","DROP GROUP","DROP IDENTITY","DROP INDEX","DROP LANGUAGE","DROP MATERIALIZED VIEW [IF EXISTS]","DROP OPERATOR","DROP OPERATOR CLASS","DROP OPERATOR FAMILY","DROP OWNED","DROP POLICY","DROP PROCEDURE","DROP PUBLICATION","DROP ROLE","DROP ROUTINE","DROP RULE","DROP SCHEMA","DROP SEQUENCE","DROP SERVER","DROP STATISTICS","DROP SUBSCRIPTION","DROP TABLESPACE","DROP TEXT SEARCH CONFIGURATION","DROP TEXT SEARCH DICTIONARY","DROP TEXT SEARCH PARSER","DROP TEXT SEARCH TEMPLATE","DROP TRANSFORM","DROP TRIGGER","DROP TYPE","DROP USER","DROP USER MAPPING","DROP VIEW","EXECUTE","EXPLAIN","FETCH","GRANT","IMPORT FOREIGN SCHEMA","LISTEN","LOAD","LOCK","MOVE","NOTIFY","OVERRIDING SYSTEM VALUE","PREPARE","PREPARE TRANSACTION","REASSIGN OWNED","REFRESH MATERIALIZED VIEW","REINDEX","RELEASE SAVEPOINT","RESET [ALL|ROLE|SESSION AUTHORIZATION]","REVOKE","ROLLBACK","ROLLBACK PREPARED","ROLLBACK TO SAVEPOINT","SAVEPOINT","SECURITY LABEL","SELECT INTO","SET CONSTRAINTS","SET ROLE","SET SESSION AUTHORIZATION","SET TRANSACTION","SHOW","START TRANSACTION","UNLISTEN","VACUUM"]),xW=W(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),yW=W(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),CW=W(["PRIMARY KEY","GENERATED {ALWAYS | BY DEFAULT} AS IDENTITY","ON {UPDATE | DELETE} [NO ACTION | RESTRICT | CASCADE | SET NULL | SET DEFAULT]","DO {NOTHING | UPDATE}","AS MATERIALIZED","{ROWS | RANGE | GROUPS} BETWEEN","IS [NOT] DISTINCT FROM","NULLS {FIRST | LAST}","WITH ORDINALITY"]),LW=W(["[TIMESTAMP | TIME] {WITH | WITHOUT} TIME ZONE"]),_W={name:"postgresql",tokenizerOptions:{reservedSelect:OW,reservedClauses:[...NW,...tT,...xc],reservedSetOperations:xW,reservedJoins:yW,reservedKeywordPhrases:CW,reservedDataTypePhrases:LW,reservedKeywords:gW,reservedDataTypes:IW,reservedFunctionNames:mW,nestedBlockComments:!0,extraParens:["[]"],underscoresInNumbers:!0,stringTypes:["$$",{quote:"''-qq",prefixes:["U&"]},{quote:"''-qq-bs",prefixes:["E"],requirePrefix:!0},{quote:"''-raw",prefixes:["B","X"],requirePrefix:!0}],identTypes:[{quote:'""-qq',prefixes:["U&"]}],identChars:{rest:"$"},paramTypes:{numbered:["$"]},operators:["%","^","|/","||/","@",":=","&","|","#","~","<<",">>","~>~","~<~","~>=~","~<=~","@-@","@@","##","<->","&&","&<","&>","<<|","&<|","|>>","|&>","<^","^>","?#","?-","?|","?-|","?||","@>","<@","~=","?","@?","?&","->","->>","#>","#>>","#-","=>",">>=","<<=","~~","~~*","!~~","!~~*","~","~*","!~","!~*","-|-","||","@@@","!!","^@","<%","%>","<<%","%>>","<<->","<->>","<<<->","<->>>","::",":","<#>","<=>","<+>","<~>","<%>"],operatorKeyword:!0},formatOptions:{alwaysDenseOperators:["::",":"],onelineClauses:[...tT,...xc],tabularOnelineClauses:xc}},bW=["ANY_VALUE","APPROXIMATE PERCENTILE_DISC","AVG","COUNT","LISTAGG","MAX","MEDIAN","MIN","PERCENTILE_CONT","STDDEV_SAMP","STDDEV_POP","SUM","VAR_SAMP","VAR_POP","array_concat","array_flatten","get_array_length","split_to_array","subarray","BIT_AND","BIT_OR","BOOL_AND","BOOL_OR","COALESCE","DECODE","GREATEST","LEAST","NVL","NVL2","NULLIF","ADD_MONTHS","AT TIME ZONE","CONVERT_TIMEZONE","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","DATE_CMP","DATE_CMP_TIMESTAMP","DATE_CMP_TIMESTAMPTZ","DATE_PART_YEAR","DATEADD","DATEDIFF","DATE_PART","DATE_TRUNC","EXTRACT","GETDATE","INTERVAL_CMP","LAST_DAY","MONTHS_BETWEEN","NEXT_DAY","SYSDATE","TIMEOFDAY","TIMESTAMP_CMP","TIMESTAMP_CMP_DATE","TIMESTAMP_CMP_TIMESTAMPTZ","TIMESTAMPTZ_CMP","TIMESTAMPTZ_CMP_DATE","TIMESTAMPTZ_CMP_TIMESTAMP","TIMEZONE","TO_TIMESTAMP","TRUNC","AddBBox","DropBBox","GeometryType","ST_AddPoint","ST_Angle","ST_Area","ST_AsBinary","ST_AsEWKB","ST_AsEWKT","ST_AsGeoJSON","ST_AsText","ST_Azimuth","ST_Boundary","ST_Collect","ST_Contains","ST_ContainsProperly","ST_ConvexHull","ST_CoveredBy","ST_Covers","ST_Crosses","ST_Dimension","ST_Disjoint","ST_Distance","ST_DistanceSphere","ST_DWithin","ST_EndPoint","ST_Envelope","ST_Equals","ST_ExteriorRing","ST_Force2D","ST_Force3D","ST_Force3DM","ST_Force3DZ","ST_Force4D","ST_GeometryN","ST_GeometryType","ST_GeomFromEWKB","ST_GeomFromEWKT","ST_GeomFromText","ST_GeomFromWKB","ST_InteriorRingN","ST_Intersects","ST_IsPolygonCCW","ST_IsPolygonCW","ST_IsClosed","ST_IsCollection","ST_IsEmpty","ST_IsSimple","ST_IsValid","ST_Length","ST_LengthSphere","ST_Length2D","ST_LineFromMultiPoint","ST_LineInterpolatePoint","ST_M","ST_MakeEnvelope","ST_MakeLine","ST_MakePoint","ST_MakePolygon","ST_MemSize","ST_MMax","ST_MMin","ST_Multi","ST_NDims","ST_NPoints","ST_NRings","ST_NumGeometries","ST_NumInteriorRings","ST_NumPoints","ST_Perimeter","ST_Perimeter2D","ST_Point","ST_PointN","ST_Points","ST_Polygon","ST_RemovePoint","ST_Reverse","ST_SetPoint","ST_SetSRID","ST_Simplify","ST_SRID","ST_StartPoint","ST_Touches","ST_Within","ST_X","ST_XMax","ST_XMin","ST_Y","ST_YMax","ST_YMin","ST_Z","ST_ZMax","ST_ZMin","SupportsBBox","CHECKSUM","FUNC_SHA1","FNV_HASH","MD5","SHA","SHA1","SHA2","HLL","HLL_CREATE_SKETCH","HLL_CARDINALITY","HLL_COMBINE","IS_VALID_JSON","IS_VALID_JSON_ARRAY","JSON_ARRAY_LENGTH","JSON_EXTRACT_ARRAY_ELEMENT_TEXT","JSON_EXTRACT_PATH_TEXT","JSON_PARSE","JSON_SERIALIZE","ABS","ACOS","ASIN","ATAN","ATAN2","CBRT","CEILING","CEIL","COS","COT","DEGREES","DEXP","DLOG1","DLOG10","EXP","FLOOR","LN","LOG","MOD","PI","POWER","RADIANS","RANDOM","ROUND","SIN","SIGN","SQRT","TAN","TO_HEX","TRUNC","EXPLAIN_MODEL","ASCII","BPCHARCMP","BTRIM","BTTEXT_PATTERN_CMP","CHAR_LENGTH","CHARACTER_LENGTH","CHARINDEX","CHR","COLLATE","CONCAT","CRC32","DIFFERENCE","INITCAP","LEFT","RIGHT","LEN","LENGTH","LOWER","LPAD","RPAD","LTRIM","OCTETINDEX","OCTET_LENGTH","POSITION","QUOTE_IDENT","QUOTE_LITERAL","REGEXP_COUNT","REGEXP_INSTR","REGEXP_REPLACE","REGEXP_SUBSTR","REPEAT","REPLACE","REPLICATE","REVERSE","RTRIM","SOUNDEX","SPLIT_PART","STRPOS","STRTOL","SUBSTRING","TEXTLEN","TRANSLATE","TRIM","UPPER","decimal_precision","decimal_scale","is_array","is_bigint","is_boolean","is_char","is_decimal","is_float","is_integer","is_object","is_scalar","is_smallint","is_varchar","json_typeof","AVG","COUNT","CUME_DIST","DENSE_RANK","FIRST_VALUE","LAST_VALUE","LAG","LEAD","LISTAGG","MAX","MEDIAN","MIN","NTH_VALUE","NTILE","PERCENT_RANK","PERCENTILE_CONT","PERCENTILE_DISC","RANK","RATIO_TO_REPORT","ROW_NUMBER","STDDEV_SAMP","STDDEV_POP","SUM","VAR_SAMP","VAR_POP","CAST","CONVERT","TO_CHAR","TO_DATE","TO_NUMBER","TEXT_TO_INT_ALT","TEXT_TO_NUMERIC_ALT","CHANGE_QUERY_PRIORITY","CHANGE_SESSION_PRIORITY","CHANGE_USER_PRIORITY","CURRENT_SETTING","PG_CANCEL_BACKEND","PG_TERMINATE_BACKEND","REBOOT_CLUSTER","SET_CONFIG","CURRENT_AWS_ACCOUNT","CURRENT_DATABASE","CURRENT_NAMESPACE","CURRENT_SCHEMA","CURRENT_SCHEMAS","CURRENT_USER","CURRENT_USER_ID","HAS_ASSUMEROLE_PRIVILEGE","HAS_DATABASE_PRIVILEGE","HAS_SCHEMA_PRIVILEGE","HAS_TABLE_PRIVILEGE","PG_BACKEND_PID","PG_GET_COLS","PG_GET_GRANTEE_BY_IAM_ROLE","PG_GET_IAM_ROLE_BY_USER","PG_GET_LATE_BINDING_VIEW_COLS","PG_LAST_COPY_COUNT","PG_LAST_COPY_ID","PG_LAST_UNLOAD_ID","PG_LAST_QUERY_ID","PG_LAST_UNLOAD_COUNT","SESSION_USER","SLICE_NUM","USER","VERSION"],vW=["AES128","AES256","ALL","ALLOWOVERWRITE","ANY","AS","ASC","AUTHORIZATION","BACKUP","BETWEEN","BINARY","BOTH","CHECK","COLUMN","CONSTRAINT","CREATE","CROSS","DEFAULT","DEFERRABLE","DEFLATE","DEFRAG","DESC","DISABLE","DISTINCT","DO","ENABLE","ENCODE","ENCRYPT","ENCRYPTION","EXPLICIT","FALSE","FOR","FOREIGN","FREEZE","FROM","FULL","GLOBALDICT256","GLOBALDICT64K","GROUP","IDENTITY","IGNORE","ILIKE","IN","INITIALLY","INNER","INTO","IS","ISNULL","LANGUAGE","LEADING","LIKE","LIMIT","LOCALTIME","LOCALTIMESTAMP","LUN","LUNS","MINUS","NATURAL","NEW","NOT","NOTNULL","NULL","NULLS","OFF","OFFLINE","OFFSET","OID","OLD","ON","ONLY","OPEN","ORDER","OUTER","OVERLAPS","PARALLEL","PARTITION","PERCENT","PERMISSIONS","PLACING","PRIMARY","RECOVER","REFERENCES","REJECTLOG","RESORT","RESPECT","RESTORE","SIMILAR","SNAPSHOT","SOME","SYSTEM","TABLE","TAG","TDES","THEN","TIMESTAMP","TO","TOP","TRAILING","TRUE","UNIQUE","USING","VERBOSE","WALLET","WITHOUT","ACCEPTANYDATE","ACCEPTINVCHARS","BLANKSASNULL","DATEFORMAT","EMPTYASNULL","ENCODING","ESCAPE","EXPLICIT_IDS","FILLRECORD","IGNOREBLANKLINES","IGNOREHEADER","REMOVEQUOTES","ROUNDEC","TIMEFORMAT","TRIMBLANKS","TRUNCATECOLUMNS","COMPROWS","COMPUPDATE","MAXERROR","NOLOAD","STATUPDATE","FORMAT","CSV","DELIMITER","FIXEDWIDTH","SHAPEFILE","AVRO","JSON","PARQUET","ORC","ACCESS_KEY_ID","CREDENTIALS","ENCRYPTED","IAM_ROLE","MASTER_SYMMETRIC_KEY","SECRET_ACCESS_KEY","SESSION_TOKEN","BZIP2","GZIP","LZOP","ZSTD","MANIFEST","READRATIO","REGION","SSH","RAW","AZ64","BYTEDICT","DELTA","DELTA32K","LZO","MOSTLY8","MOSTLY16","MOSTLY32","RUNLENGTH","TEXT255","TEXT32K","CATALOG_ROLE","SECRET_ARN","EXTERNAL","AUTO","EVEN","KEY","PREDICATE","COMPRESSION"],DW=["ARRAY","BIGINT","BPCHAR","CHAR","CHARACTER VARYING","CHARACTER","DECIMAL","INT","INT2","INT4","INT8","INTEGER","NCHAR","NUMERIC","NVARCHAR","SMALLINT","TEXT","VARBYTE","VARCHAR"],MW=W(["SELECT [ALL | DISTINCT]"]),PW=W(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","QUALIFY","PARTITION BY","ORDER BY","LIMIT","OFFSET","INSERT INTO","VALUES","SET"]),nT=W(["CREATE [TEMPORARY | TEMP | LOCAL TEMPORARY | LOCAL TEMP] TABLE [IF NOT EXISTS]"]),yc=W(["CREATE [OR REPLACE | MATERIALIZED] VIEW","UPDATE","DELETE [FROM]","DROP TABLE [IF EXISTS]","ALTER TABLE","ALTER TABLE APPEND","ADD [COLUMN]","DROP [COLUMN]","RENAME TO","RENAME COLUMN","ALTER COLUMN","TYPE","ENCODE","TRUNCATE [TABLE]","ABORT","ALTER DATABASE","ALTER DATASHARE","ALTER DEFAULT PRIVILEGES","ALTER GROUP","ALTER MATERIALIZED VIEW","ALTER PROCEDURE","ALTER SCHEMA","ALTER USER","ANALYSE","ANALYZE","ANALYSE COMPRESSION","ANALYZE COMPRESSION","BEGIN","CALL","CANCEL","CLOSE","COMMIT","COPY","CREATE DATABASE","CREATE DATASHARE","CREATE EXTERNAL FUNCTION","CREATE EXTERNAL SCHEMA","CREATE EXTERNAL TABLE","CREATE FUNCTION","CREATE GROUP","CREATE LIBRARY","CREATE MODEL","CREATE PROCEDURE","CREATE SCHEMA","CREATE USER","DEALLOCATE","DECLARE","DESC DATASHARE","DROP DATABASE","DROP DATASHARE","DROP FUNCTION","DROP GROUP","DROP LIBRARY","DROP MODEL","DROP MATERIALIZED VIEW","DROP PROCEDURE","DROP SCHEMA","DROP USER","DROP VIEW","DROP","EXECUTE","EXPLAIN","FETCH","GRANT","LOCK","PREPARE","REFRESH MATERIALIZED VIEW","RESET","REVOKE","ROLLBACK","SELECT INTO","SET SESSION AUTHORIZATION","SET SESSION CHARACTERISTICS","SHOW","SHOW EXTERNAL TABLE","SHOW MODEL","SHOW DATASHARES","SHOW PROCEDURE","SHOW TABLE","SHOW VIEW","START TRANSACTION","UNLOAD","VACUUM"]),wW=W(["UNION [ALL]","EXCEPT","INTERSECT","MINUS"]),UW=W(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),BW=W(["NULL AS","DATA CATALOG","HIVE METASTORE","{ROWS | RANGE} BETWEEN"]),jW=W([]),kW={name:"redshift",tokenizerOptions:{reservedSelect:MW,reservedClauses:[...PW,...nT,...yc],reservedSetOperations:wW,reservedJoins:UW,reservedKeywordPhrases:BW,reservedDataTypePhrases:jW,reservedKeywords:vW,reservedDataTypes:DW,reservedFunctionNames:bW,extraParens:["[]"],stringTypes:["''-qq"],identTypes:['""-qq'],identChars:{first:"#"},paramTypes:{numbered:["$"]},operators:["^","%","@","|/","||/","&","|","~","<<",">>","||","::"]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...nT,...yc],tabularOnelineClauses:yc}},FW=["ADD","AFTER","ALL","ALTER","ANALYZE","AND","ANTI","ANY","ARCHIVE","AS","ASC","AT","AUTHORIZATION","BETWEEN","BOTH","BUCKET","BUCKETS","BY","CACHE","CASCADE","CAST","CHANGE","CHECK","CLEAR","CLUSTER","CLUSTERED","CODEGEN","COLLATE","COLLECTION","COLUMN","COLUMNS","COMMENT","COMMIT","COMPACT","COMPACTIONS","COMPUTE","CONCATENATE","CONSTRAINT","COST","CREATE","CROSS","CUBE","CURRENT","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","DATA","DATABASE","DATABASES","DAY","DBPROPERTIES","DEFINED","DELETE","DELIMITED","DESC","DESCRIBE","DFS","DIRECTORIES","DIRECTORY","DISTINCT","DISTRIBUTE","DIV","DROP","ESCAPE","ESCAPED","EXCEPT","EXCHANGE","EXISTS","EXPORT","EXTENDED","EXTERNAL","EXTRACT","FALSE","FETCH","FIELDS","FILTER","FILEFORMAT","FIRST","FIRST_VALUE","FOLLOWING","FOR","FOREIGN","FORMAT","FORMATTED","FULL","FUNCTION","FUNCTIONS","GLOBAL","GRANT","GROUP","GROUPING","HOUR","IF","IGNORE","IMPORT","IN","INDEX","INDEXES","INNER","INPATH","INPUTFORMAT","INTERSECT","INTO","IS","ITEMS","KEYS","LAST","LAST_VALUE","LATERAL","LAZY","LEADING","LEFT","LIKE","LINES","LIST","LOCAL","LOCATION","LOCK","LOCKS","LOGICAL","MACRO","MATCHED","MERGE","MINUTE","MONTH","MSCK","NAMESPACE","NAMESPACES","NATURAL","NO","NOT","NULL","NULLS","OF","ONLY","OPTION","OPTIONS","OR","ORDER","OUT","OUTER","OUTPUTFORMAT","OVER","OVERLAPS","OVERLAY","OVERWRITE","OWNER","PARTITION","PARTITIONED","PARTITIONS","PERCENT","PLACING","POSITION","PRECEDING","PRIMARY","PRINCIPALS","PROPERTIES","PURGE","QUERY","RANGE","RECORDREADER","RECORDWRITER","RECOVER","REDUCE","REFERENCES","RENAME","REPAIR","REPLACE","RESPECT","RESTRICT","REVOKE","RIGHT","RLIKE","ROLE","ROLES","ROLLBACK","ROLLUP","ROW","ROWS","SCHEMA","SECOND","SELECT","SEMI","SEPARATED","SERDE","SERDEPROPERTIES","SESSION_USER","SETS","SHOW","SKEWED","SOME","SORT","SORTED","START","STATISTICS","STORED","STRATIFY","SUBSTR","SUBSTRING","TABLE","TABLES","TBLPROPERTIES","TEMPORARY","TERMINATED","THEN","TO","TOUCH","TRAILING","TRANSACTION","TRANSACTIONS","TRIM","TRUE","TRUNCATE","UNARCHIVE","UNBOUNDED","UNCACHE","UNIQUE","UNKNOWN","UNLOCK","UNSET","USE","USER","USING","VIEW","WINDOW","YEAR","ANALYSE","ARRAY_ZIP","COALESCE","CONTAINS","CONVERT","DAYS","DAY_HOUR","DAY_MINUTE","DAY_SECOND","DECODE","DEFAULT","DISTINCTROW","ENCODE","EXPLODE","EXPLODE_OUTER","FIXED","GREATEST","GROUP_CONCAT","HOURS","HOUR_MINUTE","HOUR_SECOND","IFNULL","LEAST","LEVEL","MINUTE_SECOND","NULLIF","OFFSET","ON","OPTIMIZE","REGEXP","SEPARATOR","SIZE","TYPE","TYPES","UNSIGNED","VARIABLES","YEAR_MONTH"],GW=["ARRAY","BIGINT","BINARY","BOOLEAN","BYTE","CHAR","DATE","DEC","DECIMAL","DOUBLE","FLOAT","INT","INTEGER","INTERVAL","LONG","MAP","NUMERIC","REAL","SHORT","SMALLINT","STRING","STRUCT","TIMESTAMP_LTZ","TIMESTAMP_NTZ","TIMESTAMP","TINYINT","VARCHAR"],HW=["APPROX_COUNT_DISTINCT","APPROX_PERCENTILE","AVG","BIT_AND","BIT_OR","BIT_XOR","BOOL_AND","BOOL_OR","COLLECT_LIST","COLLECT_SET","CORR","COUNT","COUNT","COUNT","COUNT_IF","COUNT_MIN_SKETCH","COVAR_POP","COVAR_SAMP","EVERY","FIRST","FIRST_VALUE","GROUPING","GROUPING_ID","KURTOSIS","LAST","LAST_VALUE","MAX","MAX_BY","MEAN","MIN","MIN_BY","PERCENTILE","PERCENTILE","PERCENTILE_APPROX","SKEWNESS","STD","STDDEV","STDDEV_POP","STDDEV_SAMP","SUM","VAR_POP","VAR_SAMP","VARIANCE","CUME_DIST","DENSE_RANK","LAG","LEAD","NTH_VALUE","NTILE","PERCENT_RANK","RANK","ROW_NUMBER","ARRAY","ARRAY_CONTAINS","ARRAY_DISTINCT","ARRAY_EXCEPT","ARRAY_INTERSECT","ARRAY_JOIN","ARRAY_MAX","ARRAY_MIN","ARRAY_POSITION","ARRAY_REMOVE","ARRAY_REPEAT","ARRAY_UNION","ARRAYS_OVERLAP","ARRAYS_ZIP","FLATTEN","SEQUENCE","SHUFFLE","SLICE","SORT_ARRAY","ELEMENT_AT","ELEMENT_AT","MAP_CONCAT","MAP_ENTRIES","MAP_FROM_ARRAYS","MAP_FROM_ENTRIES","MAP_KEYS","MAP_VALUES","STR_TO_MAP","ADD_MONTHS","CURRENT_DATE","CURRENT_DATE","CURRENT_TIMESTAMP","CURRENT_TIMESTAMP","CURRENT_TIMEZONE","DATE_ADD","DATE_FORMAT","DATE_FROM_UNIX_DATE","DATE_PART","DATE_SUB","DATE_TRUNC","DATEDIFF","DAY","DAYOFMONTH","DAYOFWEEK","DAYOFYEAR","EXTRACT","FROM_UNIXTIME","FROM_UTC_TIMESTAMP","HOUR","LAST_DAY","MAKE_DATE","MAKE_DT_INTERVAL","MAKE_INTERVAL","MAKE_TIMESTAMP","MAKE_YM_INTERVAL","MINUTE","MONTH","MONTHS_BETWEEN","NEXT_DAY","NOW","QUARTER","SECOND","SESSION_WINDOW","TIMESTAMP_MICROS","TIMESTAMP_MILLIS","TIMESTAMP_SECONDS","TO_DATE","TO_TIMESTAMP","TO_UNIX_TIMESTAMP","TO_UTC_TIMESTAMP","TRUNC","UNIX_DATE","UNIX_MICROS","UNIX_MILLIS","UNIX_SECONDS","UNIX_TIMESTAMP","WEEKDAY","WEEKOFYEAR","WINDOW","YEAR","FROM_JSON","GET_JSON_OBJECT","JSON_ARRAY_LENGTH","JSON_OBJECT_KEYS","JSON_TUPLE","SCHEMA_OF_JSON","TO_JSON","ABS","ACOS","ACOSH","AGGREGATE","ARRAY_SORT","ASCII","ASIN","ASINH","ASSERT_TRUE","ATAN","ATAN2","ATANH","BASE64","BIN","BIT_COUNT","BIT_GET","BIT_LENGTH","BROUND","BTRIM","CARDINALITY","CBRT","CEIL","CEILING","CHAR_LENGTH","CHARACTER_LENGTH","CHR","CONCAT","CONCAT_WS","CONV","COS","COSH","COT","CRC32","CURRENT_CATALOG","CURRENT_DATABASE","CURRENT_USER","DEGREES","ELT","EXP","EXPM1","FACTORIAL","FIND_IN_SET","FLOOR","FORALL","FORMAT_NUMBER","FORMAT_STRING","FROM_CSV","GETBIT","HASH","HEX","HYPOT","INITCAP","INLINE","INLINE_OUTER","INPUT_FILE_BLOCK_LENGTH","INPUT_FILE_BLOCK_START","INPUT_FILE_NAME","INSTR","ISNAN","ISNOTNULL","ISNULL","JAVA_METHOD","LCASE","LEFT","LENGTH","LEVENSHTEIN","LN","LOCATE","LOG","LOG10","LOG1P","LOG2","LOWER","LPAD","LTRIM","MAP_FILTER","MAP_ZIP_WITH","MD5","MOD","MONOTONICALLY_INCREASING_ID","NAMED_STRUCT","NANVL","NEGATIVE","NVL","NVL2","OCTET_LENGTH","OVERLAY","PARSE_URL","PI","PMOD","POSEXPLODE","POSEXPLODE_OUTER","POSITION","POSITIVE","POW","POWER","PRINTF","RADIANS","RAISE_ERROR","RAND","RANDN","RANDOM","REFLECT","REGEXP_EXTRACT","REGEXP_EXTRACT_ALL","REGEXP_LIKE","REGEXP_REPLACE","REPEAT","REPLACE","REVERSE","RIGHT","RINT","ROUND","RPAD","RTRIM","SCHEMA_OF_CSV","SENTENCES","SHA","SHA1","SHA2","SHIFTLEFT","SHIFTRIGHT","SHIFTRIGHTUNSIGNED","SIGN","SIGNUM","SIN","SINH","SOUNDEX","SPACE","SPARK_PARTITION_ID","SPLIT","SQRT","STACK","SUBSTR","SUBSTRING","SUBSTRING_INDEX","TAN","TANH","TO_CSV","TRANSFORM_KEYS","TRANSFORM_VALUES","TRANSLATE","TRIM","TRY_ADD","TRY_DIVIDE","TYPEOF","UCASE","UNBASE64","UNHEX","UPPER","UUID","VERSION","WIDTH_BUCKET","XPATH","XPATH_BOOLEAN","XPATH_DOUBLE","XPATH_FLOAT","XPATH_INT","XPATH_LONG","XPATH_NUMBER","XPATH_SHORT","XPATH_STRING","XXHASH64","ZIP_WITH","CAST","COALESCE","NULLIF"],WW=W(["SELECT [ALL | DISTINCT]"]),YW=W(["WITH","FROM","WHERE","GROUP BY","HAVING","WINDOW","PARTITION BY","ORDER BY","SORT BY","CLUSTER BY","DISTRIBUTE BY","LIMIT","INSERT [INTO | OVERWRITE] [TABLE]","VALUES","INSERT OVERWRITE [LOCAL] DIRECTORY","LOAD DATA [LOCAL] INPATH","[OVERWRITE] INTO TABLE"]),rT=W(["CREATE [EXTERNAL] TABLE [IF NOT EXISTS]"]),Cc=W(["CREATE [OR REPLACE] [GLOBAL TEMPORARY | TEMPORARY] VIEW [IF NOT EXISTS]","DROP TABLE [IF EXISTS]","ALTER TABLE","ADD COLUMNS","DROP {COLUMN | COLUMNS}","RENAME TO","RENAME COLUMN","ALTER COLUMN","TRUNCATE TABLE","LATERAL VIEW","ALTER DATABASE","ALTER VIEW","CREATE DATABASE","CREATE FUNCTION","DROP DATABASE","DROP FUNCTION","DROP VIEW","REPAIR TABLE","USE DATABASE","TABLESAMPLE","PIVOT","TRANSFORM","EXPLAIN","ADD FILE","ADD JAR","ANALYZE TABLE","CACHE TABLE","CLEAR CACHE","DESCRIBE DATABASE","DESCRIBE FUNCTION","DESCRIBE QUERY","DESCRIBE TABLE","LIST FILE","LIST JAR","REFRESH","REFRESH TABLE","REFRESH FUNCTION","RESET","SHOW COLUMNS","SHOW CREATE TABLE","SHOW DATABASES","SHOW FUNCTIONS","SHOW PARTITIONS","SHOW TABLE EXTENDED","SHOW TABLES","SHOW TBLPROPERTIES","SHOW VIEWS","UNCACHE TABLE"]),$W=W(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),VW=W(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN","[LEFT] {ANTI | SEMI} JOIN","NATURAL [LEFT] {ANTI | SEMI} JOIN"]),zW=W(["ON DELETE","ON UPDATE","CURRENT ROW","{ROWS | RANGE} BETWEEN"]),XW=W([]),KW={name:"spark",tokenizerOptions:{reservedSelect:WW,reservedClauses:[...YW,...rT,...Cc],reservedSetOperations:$W,reservedJoins:VW,reservedKeywordPhrases:zW,reservedDataTypePhrases:XW,supportsXor:!0,reservedKeywords:FW,reservedDataTypes:GW,reservedFunctionNames:HW,extraParens:["[]"],stringTypes:["''-bs",'""-bs',{quote:"''-raw",prefixes:["R","X"],requirePrefix:!0},{quote:'""-raw',prefixes:["R","X"],requirePrefix:!0}],identTypes:["``"],identChars:{allowFirstCharNumber:!0},variableTypes:[{quote:"{}",prefixes:["$"],requirePrefix:!0}],operators:["%","~","^","|","&","<=>","==","!","||","->"],postProcess:qW},formatOptions:{onelineClauses:[...rT,...Cc],tabularOnelineClauses:Cc}};function qW(e){return e.map((t,n)=>{const r=e[n-1]||Hn,s=e[n+1]||Hn;return Wn.WINDOW(t)&&s.type===J.OPEN_PAREN?Object.assign(Object.assign({},t),{type:J.RESERVED_FUNCTION_NAME}):t.text==="ITEMS"&&t.type===J.RESERVED_KEYWORD&&!(r.text==="COLLECTION"&&s.text==="TERMINATED")?Object.assign(Object.assign({},t),{type:J.IDENTIFIER,text:t.raw}):t})}const JW=["ABS","CHANGES","CHAR","COALESCE","FORMAT","GLOB","HEX","IFNULL","IIF","INSTR","LAST_INSERT_ROWID","LENGTH","LIKE","LIKELIHOOD","LIKELY","LOAD_EXTENSION","LOWER","LTRIM","NULLIF","PRINTF","QUOTE","RANDOM","RANDOMBLOB","REPLACE","ROUND","RTRIM","SIGN","SOUNDEX","SQLITE_COMPILEOPTION_GET","SQLITE_COMPILEOPTION_USED","SQLITE_OFFSET","SQLITE_SOURCE_ID","SQLITE_VERSION","SUBSTR","SUBSTRING","TOTAL_CHANGES","TRIM","TYPEOF","UNICODE","UNLIKELY","UPPER","ZEROBLOB","AVG","COUNT","GROUP_CONCAT","MAX","MIN","SUM","TOTAL","DATE","TIME","DATETIME","JULIANDAY","UNIXEPOCH","STRFTIME","row_number","rank","dense_rank","percent_rank","cume_dist","ntile","lag","lead","first_value","last_value","nth_value","ACOS","ACOSH","ASIN","ASINH","ATAN","ATAN2","ATANH","CEIL","CEILING","COS","COSH","DEGREES","EXP","FLOOR","LN","LOG","LOG","LOG10","LOG2","MOD","PI","POW","POWER","RADIANS","SIN","SINH","SQRT","TAN","TANH","TRUNC","JSON","JSON_ARRAY","JSON_ARRAY_LENGTH","JSON_ARRAY_LENGTH","JSON_EXTRACT","JSON_INSERT","JSON_OBJECT","JSON_PATCH","JSON_REMOVE","JSON_REPLACE","JSON_SET","JSON_TYPE","JSON_TYPE","JSON_VALID","JSON_QUOTE","JSON_GROUP_ARRAY","JSON_GROUP_OBJECT","JSON_EACH","JSON_TREE","CAST"],QW=["ABORT","ACTION","ADD","AFTER","ALL","ALTER","AND","ARE","ALWAYS","ANALYZE","AS","ASC","ATTACH","AUTOINCREMENT","BEFORE","BEGIN","BETWEEN","BY","CASCADE","CASE","CAST","CHECK","COLLATE","COLUMN","COMMIT","CONFLICT","CONSTRAINT","CREATE","CROSS","CURRENT","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","DATABASE","DEFAULT","DEFERRABLE","DEFERRED","DELETE","DESC","DETACH","DISTINCT","DO","DROP","EACH","ELSE","END","ESCAPE","EXCEPT","EXCLUDE","EXCLUSIVE","EXISTS","EXPLAIN","FAIL","FILTER","FIRST","FOLLOWING","FOR","FOREIGN","FROM","FULL","GENERATED","GLOB","GROUP","HAVING","IF","IGNORE","IMMEDIATE","IN","INDEX","INDEXED","INITIALLY","INNER","INSERT","INSTEAD","INTERSECT","INTO","IS","ISNULL","JOIN","KEY","LAST","LEFT","LIKE","LIMIT","MATCH","MATERIALIZED","NATURAL","NO","NOT","NOTHING","NOTNULL","NULL","NULLS","OF","OFFSET","ON","ONLY","OPEN","OR","ORDER","OTHERS","OUTER","OVER","PARTITION","PLAN","PRAGMA","PRECEDING","PRIMARY","QUERY","RAISE","RANGE","RECURSIVE","REFERENCES","REGEXP","REINDEX","RELEASE","RENAME","REPLACE","RESTRICT","RETURNING","RIGHT","ROLLBACK","ROW","ROWS","SAVEPOINT","SELECT","SET","TABLE","TEMP","TEMPORARY","THEN","TIES","TO","TRANSACTION","TRIGGER","UNBOUNDED","UNION","UNIQUE","UPDATE","USING","VACUUM","VALUES","VIEW","VIRTUAL","WHEN","WHERE","WINDOW","WITH","WITHOUT"],ZW=["ANY","ARRAY","BLOB","CHARACTER","DECIMAL","INT","INTEGER","NATIVE CHARACTER","NCHAR","NUMERIC","NVARCHAR","REAL","TEXT","VARCHAR","VARYING CHARACTER"],eY=W(["SELECT [ALL | DISTINCT]"]),tY=W(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","INSERT [OR ABORT | OR FAIL | OR IGNORE | OR REPLACE | OR ROLLBACK] INTO","REPLACE INTO","VALUES","SET","RETURNING"]),oT=W(["CREATE [TEMPORARY | TEMP] TABLE [IF NOT EXISTS]"]),Lc=W(["CREATE [TEMPORARY | TEMP] VIEW [IF NOT EXISTS]","UPDATE [OR ABORT | OR FAIL | OR IGNORE | OR REPLACE | OR ROLLBACK]","ON CONFLICT","DELETE FROM","DROP TABLE [IF EXISTS]","ALTER TABLE","ADD [COLUMN]","DROP [COLUMN]","RENAME [COLUMN]","RENAME TO","SET SCHEMA"]),nY=W(["UNION [ALL]","EXCEPT","INTERSECT"]),rY=W(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),oY=W(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE | GROUPS} BETWEEN","DO UPDATE"]),sY=W([]),iY={name:"sqlite",tokenizerOptions:{reservedSelect:eY,reservedClauses:[...tY,...oT,...Lc],reservedSetOperations:nY,reservedJoins:rY,reservedKeywordPhrases:oY,reservedDataTypePhrases:sY,reservedKeywords:QW,reservedDataTypes:ZW,reservedFunctionNames:JW,stringTypes:["''-qq",{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq',"``","[]"],paramTypes:{positional:!0,numbered:["?"],named:[":","@","$"]},operators:["%","~","&","|","<<",">>","==","->","->>","||"]},formatOptions:{onelineClauses:[...oT,...Lc],tabularOnelineClauses:Lc}},aY=["GROUPING","RANK","DENSE_RANK","PERCENT_RANK","CUME_DIST","ROW_NUMBER","POSITION","OCCURRENCES_REGEX","POSITION_REGEX","EXTRACT","CHAR_LENGTH","CHARACTER_LENGTH","OCTET_LENGTH","CARDINALITY","ABS","MOD","LN","EXP","POWER","SQRT","FLOOR","CEIL","CEILING","WIDTH_BUCKET","SUBSTRING","SUBSTRING_REGEX","UPPER","LOWER","CONVERT","TRANSLATE","TRANSLATE_REGEX","TRIM","OVERLAY","NORMALIZE","SPECIFICTYPE","CURRENT_DATE","CURRENT_TIME","LOCALTIME","CURRENT_TIMESTAMP","LOCALTIMESTAMP","COUNT","AVG","MAX","MIN","SUM","STDDEV_POP","STDDEV_SAMP","VAR_SAMP","VAR_POP","COLLECT","FUSION","INTERSECTION","COVAR_POP","COVAR_SAMP","CORR","REGR_SLOPE","REGR_INTERCEPT","REGR_COUNT","REGR_R2","REGR_AVGX","REGR_AVGY","REGR_SXX","REGR_SYY","REGR_SXY","PERCENTILE_CONT","PERCENTILE_DISC","CAST","COALESCE","NULLIF","ROUND","SIN","COS","TAN","ASIN","ACOS","ATAN"],lY=["ALL","ALLOCATE","ALTER","ANY","ARE","AS","ASC","ASENSITIVE","ASYMMETRIC","AT","ATOMIC","AUTHORIZATION","BEGIN","BETWEEN","BOTH","BY","CALL","CALLED","CASCADED","CAST","CHECK","CLOSE","COALESCE","COLLATE","COLUMN","COMMIT","CONDITION","CONNECT","CONSTRAINT","CORRESPONDING","CREATE","CROSS","CUBE","CURRENT","CURRENT_CATALOG","CURRENT_DEFAULT_TRANSFORM_GROUP","CURRENT_PATH","CURRENT_ROLE","CURRENT_SCHEMA","CURRENT_TRANSFORM_GROUP_FOR_TYPE","CURRENT_USER","CURSOR","CYCLE","DEALLOCATE","DAY","DECLARE","DEFAULT","DELETE","DEREF","DESC","DESCRIBE","DETERMINISTIC","DISCONNECT","DISTINCT","DROP","DYNAMIC","EACH","ELEMENT","END-EXEC","ESCAPE","EVERY","EXCEPT","EXEC","EXECUTE","EXISTS","EXTERNAL","FALSE","FETCH","FILTER","FOR","FOREIGN","FREE","FROM","FULL","FUNCTION","GET","GLOBAL","GRANT","GROUP","HAVING","HOLD","HOUR","IDENTITY","IN","INDICATOR","INNER","INOUT","INSENSITIVE","INSERT","INTERSECT","INTO","IS","LANGUAGE","LARGE","LATERAL","LEADING","LEFT","LIKE","LIKE_REGEX","LOCAL","MATCH","MEMBER","MERGE","METHOD","MINUTE","MODIFIES","MODULE","MONTH","NATURAL","NEW","NO","NONE","NOT","NULL","NULLIF","OF","OLD","ON","ONLY","OPEN","ORDER","OUT","OUTER","OVER","OVERLAPS","PARAMETER","PARTITION","PRECISION","PREPARE","PRIMARY","PROCEDURE","RANGE","READS","REAL","RECURSIVE","REF","REFERENCES","REFERENCING","RELEASE","RESULT","RETURN","RETURNS","REVOKE","RIGHT","ROLLBACK","ROLLUP","ROW","ROWS","SAVEPOINT","SCOPE","SCROLL","SEARCH","SECOND","SELECT","SENSITIVE","SESSION_USER","SET","SIMILAR","SOME","SPECIFIC","SQL","SQLEXCEPTION","SQLSTATE","SQLWARNING","START","STATIC","SUBMULTISET","SYMMETRIC","SYSTEM","SYSTEM_USER","TABLE","TABLESAMPLE","THEN","TIMEZONE_HOUR","TIMEZONE_MINUTE","TO","TRAILING","TRANSLATION","TREAT","TRIGGER","TRUE","UESCAPE","UNION","UNIQUE","UNKNOWN","UNNEST","UPDATE","USER","USING","VALUE","VALUES","WHENEVER","WINDOW","WITHIN","WITHOUT","YEAR"],cY=["ARRAY","BIGINT","BINARY LARGE OBJECT","BINARY VARYING","BINARY","BLOB","BOOLEAN","CHAR LARGE OBJECT","CHAR VARYING","CHAR","CHARACTER LARGE OBJECT","CHARACTER VARYING","CHARACTER","CLOB","DATE","DEC","DECIMAL","DOUBLE","FLOAT","INT","INTEGER","INTERVAL","MULTISET","NATIONAL CHAR VARYING","NATIONAL CHAR","NATIONAL CHARACTER LARGE OBJECT","NATIONAL CHARACTER VARYING","NATIONAL CHARACTER","NCHAR LARGE OBJECT","NCHAR VARYING","NCHAR","NCLOB","NUMERIC","SMALLINT","TIME","TIMESTAMP","VARBINARY","VARCHAR"],dY=W(["SELECT [ALL | DISTINCT]"]),uY=W(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY [ALL | DISTINCT]","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","FETCH {FIRST | NEXT}","INSERT INTO","VALUES","SET"]),sT=W(["CREATE [GLOBAL TEMPORARY | LOCAL TEMPORARY] TABLE"]),_c=W(["CREATE [RECURSIVE] VIEW","UPDATE","WHERE CURRENT OF","DELETE FROM","DROP TABLE","ALTER TABLE","ADD COLUMN","DROP [COLUMN]","RENAME COLUMN","RENAME TO","ALTER [COLUMN]","{SET | DROP} DEFAULT","ADD SCOPE","DROP SCOPE {CASCADE | RESTRICT}","RESTART WITH","TRUNCATE TABLE","SET SCHEMA"]),EY=W(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),fY=W(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),pY=W(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE} BETWEEN"]),TY=W([]),SY={name:"sql",tokenizerOptions:{reservedSelect:dY,reservedClauses:[...uY,...sT,..._c],reservedSetOperations:EY,reservedJoins:fY,reservedKeywordPhrases:pY,reservedDataTypePhrases:TY,reservedKeywords:lY,reservedDataTypes:cY,reservedFunctionNames:aY,stringTypes:[{quote:"''-qq-bs",prefixes:["N","U&"]},{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq',"``"],paramTypes:{positional:!0},operators:["||"]},formatOptions:{onelineClauses:[...sT,..._c],tabularOnelineClauses:_c}},hY=["ABS","ACOS","ALL_MATCH","ANY_MATCH","APPROX_DISTINCT","APPROX_MOST_FREQUENT","APPROX_PERCENTILE","APPROX_SET","ARBITRARY","ARRAYS_OVERLAP","ARRAY_AGG","ARRAY_DISTINCT","ARRAY_EXCEPT","ARRAY_INTERSECT","ARRAY_JOIN","ARRAY_MAX","ARRAY_MIN","ARRAY_POSITION","ARRAY_REMOVE","ARRAY_SORT","ARRAY_UNION","ASIN","ATAN","ATAN2","AT_TIMEZONE","AVG","BAR","BETA_CDF","BING_TILE","BING_TILES_AROUND","BING_TILE_AT","BING_TILE_COORDINATES","BING_TILE_POLYGON","BING_TILE_QUADKEY","BING_TILE_ZOOM_LEVEL","BITWISE_AND","BITWISE_AND_AGG","BITWISE_LEFT_SHIFT","BITWISE_NOT","BITWISE_OR","BITWISE_OR_AGG","BITWISE_RIGHT_SHIFT","BITWISE_RIGHT_SHIFT_ARITHMETIC","BITWISE_XOR","BIT_COUNT","BOOL_AND","BOOL_OR","CARDINALITY","CAST","CBRT","CEIL","CEILING","CHAR2HEXINT","CHECKSUM","CHR","CLASSIFY","COALESCE","CODEPOINT","COLOR","COMBINATIONS","CONCAT","CONCAT_WS","CONTAINS","CONTAINS_SEQUENCE","CONVEX_HULL_AGG","CORR","COS","COSH","COSINE_SIMILARITY","COUNT","COUNT_IF","COVAR_POP","COVAR_SAMP","CRC32","CUME_DIST","CURRENT_CATALOG","CURRENT_DATE","CURRENT_GROUPS","CURRENT_SCHEMA","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_TIMEZONE","CURRENT_USER","DATE","DATE_ADD","DATE_DIFF","DATE_FORMAT","DATE_PARSE","DATE_TRUNC","DAY","DAY_OF_MONTH","DAY_OF_WEEK","DAY_OF_YEAR","DEGREES","DENSE_RANK","DOW","DOY","E","ELEMENT_AT","EMPTY_APPROX_SET","EVALUATE_CLASSIFIER_PREDICTIONS","EVERY","EXP","EXTRACT","FEATURES","FILTER","FIRST_VALUE","FLATTEN","FLOOR","FORMAT","FORMAT_DATETIME","FORMAT_NUMBER","FROM_BASE","FROM_BASE32","FROM_BASE64","FROM_BASE64URL","FROM_BIG_ENDIAN_32","FROM_BIG_ENDIAN_64","FROM_ENCODED_POLYLINE","FROM_GEOJSON_GEOMETRY","FROM_HEX","FROM_IEEE754_32","FROM_IEEE754_64","FROM_ISO8601_DATE","FROM_ISO8601_TIMESTAMP","FROM_ISO8601_TIMESTAMP_NANOS","FROM_UNIXTIME","FROM_UNIXTIME_NANOS","FROM_UTF8","GEOMETRIC_MEAN","GEOMETRY_FROM_HADOOP_SHAPE","GEOMETRY_INVALID_REASON","GEOMETRY_NEAREST_POINTS","GEOMETRY_TO_BING_TILES","GEOMETRY_UNION","GEOMETRY_UNION_AGG","GREATEST","GREAT_CIRCLE_DISTANCE","HAMMING_DISTANCE","HASH_COUNTS","HISTOGRAM","HMAC_MD5","HMAC_SHA1","HMAC_SHA256","HMAC_SHA512","HOUR","HUMAN_READABLE_SECONDS","IF","INDEX","INFINITY","INTERSECTION_CARDINALITY","INVERSE_BETA_CDF","INVERSE_NORMAL_CDF","IS_FINITE","IS_INFINITE","IS_JSON_SCALAR","IS_NAN","JACCARD_INDEX","JSON_ARRAY_CONTAINS","JSON_ARRAY_GET","JSON_ARRAY_LENGTH","JSON_EXISTS","JSON_EXTRACT","JSON_EXTRACT_SCALAR","JSON_FORMAT","JSON_PARSE","JSON_QUERY","JSON_SIZE","JSON_VALUE","KURTOSIS","LAG","LAST_DAY_OF_MONTH","LAST_VALUE","LEAD","LEARN_CLASSIFIER","LEARN_LIBSVM_CLASSIFIER","LEARN_LIBSVM_REGRESSOR","LEARN_REGRESSOR","LEAST","LENGTH","LEVENSHTEIN_DISTANCE","LINE_INTERPOLATE_POINT","LINE_INTERPOLATE_POINTS","LINE_LOCATE_POINT","LISTAGG","LN","LOCALTIME","LOCALTIMESTAMP","LOG","LOG10","LOG2","LOWER","LPAD","LTRIM","LUHN_CHECK","MAKE_SET_DIGEST","MAP","MAP_AGG","MAP_CONCAT","MAP_ENTRIES","MAP_FILTER","MAP_FROM_ENTRIES","MAP_KEYS","MAP_UNION","MAP_VALUES","MAP_ZIP_WITH","MAX","MAX_BY","MD5","MERGE","MERGE_SET_DIGEST","MILLISECOND","MIN","MINUTE","MIN_BY","MOD","MONTH","MULTIMAP_AGG","MULTIMAP_FROM_ENTRIES","MURMUR3","NAN","NGRAMS","NONE_MATCH","NORMALIZE","NORMAL_CDF","NOW","NTH_VALUE","NTILE","NULLIF","NUMERIC_HISTOGRAM","OBJECTID","OBJECTID_TIMESTAMP","PARSE_DATA_SIZE","PARSE_DATETIME","PARSE_DURATION","PERCENT_RANK","PI","POSITION","POW","POWER","QDIGEST_AGG","QUARTER","RADIANS","RAND","RANDOM","RANK","REDUCE","REDUCE_AGG","REGEXP_COUNT","REGEXP_EXTRACT","REGEXP_EXTRACT_ALL","REGEXP_LIKE","REGEXP_POSITION","REGEXP_REPLACE","REGEXP_SPLIT","REGRESS","REGR_INTERCEPT","REGR_SLOPE","RENDER","REPEAT","REPLACE","REVERSE","RGB","ROUND","ROW_NUMBER","RPAD","RTRIM","SECOND","SEQUENCE","SHA1","SHA256","SHA512","SHUFFLE","SIGN","SIMPLIFY_GEOMETRY","SIN","SKEWNESS","SLICE","SOUNDEX","SPATIAL_PARTITIONING","SPATIAL_PARTITIONS","SPLIT","SPLIT_PART","SPLIT_TO_MAP","SPLIT_TO_MULTIMAP","SPOOKY_HASH_V2_32","SPOOKY_HASH_V2_64","SQRT","STARTS_WITH","STDDEV","STDDEV_POP","STDDEV_SAMP","STRPOS","ST_AREA","ST_ASBINARY","ST_ASTEXT","ST_BOUNDARY","ST_BUFFER","ST_CENTROID","ST_CONTAINS","ST_CONVEXHULL","ST_COORDDIM","ST_CROSSES","ST_DIFFERENCE","ST_DIMENSION","ST_DISJOINT","ST_DISTANCE","ST_ENDPOINT","ST_ENVELOPE","ST_ENVELOPEASPTS","ST_EQUALS","ST_EXTERIORRING","ST_GEOMETRIES","ST_GEOMETRYFROMTEXT","ST_GEOMETRYN","ST_GEOMETRYTYPE","ST_GEOMFROMBINARY","ST_INTERIORRINGN","ST_INTERIORRINGS","ST_INTERSECTION","ST_INTERSECTS","ST_ISCLOSED","ST_ISEMPTY","ST_ISRING","ST_ISSIMPLE","ST_ISVALID","ST_LENGTH","ST_LINEFROMTEXT","ST_LINESTRING","ST_MULTIPOINT","ST_NUMGEOMETRIES","ST_NUMINTERIORRING","ST_NUMPOINTS","ST_OVERLAPS","ST_POINT","ST_POINTN","ST_POINTS","ST_POLYGON","ST_RELATE","ST_STARTPOINT","ST_SYMDIFFERENCE","ST_TOUCHES","ST_UNION","ST_WITHIN","ST_X","ST_XMAX","ST_XMIN","ST_Y","ST_YMAX","ST_YMIN","SUBSTR","SUBSTRING","SUM","TAN","TANH","TDIGEST_AGG","TIMESTAMP_OBJECTID","TIMEZONE_HOUR","TIMEZONE_MINUTE","TO_BASE","TO_BASE32","TO_BASE64","TO_BASE64URL","TO_BIG_ENDIAN_32","TO_BIG_ENDIAN_64","TO_CHAR","TO_DATE","TO_ENCODED_POLYLINE","TO_GEOJSON_GEOMETRY","TO_GEOMETRY","TO_HEX","TO_IEEE754_32","TO_IEEE754_64","TO_ISO8601","TO_MILLISECONDS","TO_SPHERICAL_GEOGRAPHY","TO_TIMESTAMP","TO_UNIXTIME","TO_UTF8","TRANSFORM","TRANSFORM_KEYS","TRANSFORM_VALUES","TRANSLATE","TRIM","TRIM_ARRAY","TRUNCATE","TRY","TRY_CAST","TYPEOF","UPPER","URL_DECODE","URL_ENCODE","URL_EXTRACT_FRAGMENT","URL_EXTRACT_HOST","URL_EXTRACT_PARAMETER","URL_EXTRACT_PATH","URL_EXTRACT_PORT","URL_EXTRACT_PROTOCOL","URL_EXTRACT_QUERY","UUID","VALUES_AT_QUANTILES","VALUE_AT_QUANTILE","VARIANCE","VAR_POP","VAR_SAMP","VERSION","WEEK","WEEK_OF_YEAR","WIDTH_BUCKET","WILSON_INTERVAL_LOWER","WILSON_INTERVAL_UPPER","WITH_TIMEZONE","WORD_STEM","XXHASH64","YEAR","YEAR_OF_WEEK","YOW","ZIP","ZIP_WITH","CLASSIFIER","FIRST","LAST","MATCH_NUMBER","NEXT","PERMUTE","PREV"],RY=["ABSENT","ADD","ADMIN","AFTER","ALL","ALTER","ANALYZE","AND","ANY","AS","ASC","AT","AUTHORIZATION","BERNOULLI","BETWEEN","BOTH","BY","CALL","CASCADE","CASE","CATALOGS","COLUMN","COLUMNS","COMMENT","COMMIT","COMMITTED","CONDITIONAL","CONSTRAINT","COPARTITION","CREATE","CROSS","CUBE","CURRENT","CURRENT_PATH","CURRENT_ROLE","DATA","DEALLOCATE","DEFAULT","DEFINE","DEFINER","DELETE","DENY","DESC","DESCRIBE","DESCRIPTOR","DISTINCT","DISTRIBUTED","DOUBLE","DROP","ELSE","EMPTY","ENCODING","END","ERROR","ESCAPE","EXCEPT","EXCLUDING","EXECUTE","EXISTS","EXPLAIN","FALSE","FETCH","FINAL","FIRST","FOLLOWING","FOR","FROM","FULL","FUNCTIONS","GRANT","GRANTED","GRANTS","GRAPHVIZ","GROUP","GROUPING","GROUPS","HAVING","IGNORE","IN","INCLUDING","INITIAL","INNER","INPUT","INSERT","INTERSECT","INTERVAL","INTO","INVOKER","IO","IS","ISOLATION","JOIN","JSON","JSON_ARRAY","JSON_OBJECT","KEEP","KEY","KEYS","LAST","LATERAL","LEADING","LEFT","LEVEL","LIKE","LIMIT","LOCAL","LOGICAL","MATCH","MATCHED","MATCHES","MATCH_RECOGNIZE","MATERIALIZED","MEASURES","NATURAL","NEXT","NFC","NFD","NFKC","NFKD","NO","NONE","NOT","NULL","NULLS","OBJECT","OF","OFFSET","OMIT","ON","ONE","ONLY","OPTION","OR","ORDER","ORDINALITY","OUTER","OUTPUT","OVER","OVERFLOW","PARTITION","PARTITIONS","PASSING","PAST","PATH","PATTERN","PER","PERMUTE","PRECEDING","PRECISION","PREPARE","PRIVILEGES","PROPERTIES","PRUNE","QUOTES","RANGE","READ","RECURSIVE","REFRESH","RENAME","REPEATABLE","RESET","RESPECT","RESTRICT","RETURNING","REVOKE","RIGHT","ROLE","ROLES","ROLLBACK","ROLLUP","ROW","ROWS","RUNNING","SCALAR","SCHEMA","SCHEMAS","SECURITY","SEEK","SELECT","SERIALIZABLE","SESSION","SET","SETS","SHOW","SKIP","SOME","START","STATS","STRING","SUBSET","SYSTEM","TABLE","TABLES","TABLESAMPLE","TEXT","THEN","TIES","TIME","TIMESTAMP","TO","TRAILING","TRANSACTION","TRUE","TYPE","UESCAPE","UNBOUNDED","UNCOMMITTED","UNCONDITIONAL","UNION","UNIQUE","UNKNOWN","UNMATCHED","UNNEST","UPDATE","USE","USER","USING","UTF16","UTF32","UTF8","VALIDATE","VALUE","VALUES","VERBOSE","VIEW","WHEN","WHERE","WINDOW","WITH","WITHIN","WITHOUT","WORK","WRAPPER","WRITE","ZONE"],AY=["BIGINT","INT","INTEGER","SMALLINT","TINYINT","BOOLEAN","DATE","DECIMAL","REAL","DOUBLE","HYPERLOGLOG","QDIGEST","TDIGEST","P4HYPERLOGLOG","INTERVAL","TIMESTAMP","TIME","VARBINARY","VARCHAR","CHAR","ROW","ARRAY","MAP","JSON","JSON2016","IPADDRESS","GEOMETRY","UUID","SETDIGEST","JONIREGEXP","RE2JREGEXP","LIKEPATTERN","COLOR","CODEPOINTS","FUNCTION","JSONPATH"],mY=W(["SELECT [ALL | DISTINCT]"]),gY=W(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY [ALL | DISTINCT]","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","FETCH {FIRST | NEXT}","INSERT INTO","VALUES","SET","MATCH_RECOGNIZE","MEASURES","ONE ROW PER MATCH","ALL ROWS PER MATCH","AFTER MATCH","PATTERN","SUBSET","DEFINE"]),iT=W(["CREATE TABLE [IF NOT EXISTS]"]),bc=W(["CREATE [OR REPLACE] [MATERIALIZED] VIEW","UPDATE","DELETE FROM","DROP TABLE [IF EXISTS]","ALTER TABLE [IF EXISTS]","ADD COLUMN [IF NOT EXISTS]","DROP COLUMN [IF EXISTS]","RENAME COLUMN [IF EXISTS]","RENAME TO","SET AUTHORIZATION [USER | ROLE]","SET PROPERTIES","EXECUTE","TRUNCATE TABLE","ALTER SCHEMA","ALTER MATERIALIZED VIEW","ALTER VIEW","CREATE SCHEMA","CREATE ROLE","DROP SCHEMA","DROP MATERIALIZED VIEW","DROP VIEW","DROP ROLE","EXPLAIN","ANALYZE","EXPLAIN ANALYZE","EXPLAIN ANALYZE VERBOSE","USE","DESCRIBE INPUT","DESCRIBE OUTPUT","REFRESH MATERIALIZED VIEW","RESET SESSION","SET SESSION","SET PATH","SET TIME ZONE","SHOW GRANTS","SHOW CREATE TABLE","SHOW CREATE SCHEMA","SHOW CREATE VIEW","SHOW CREATE MATERIALIZED VIEW","SHOW TABLES","SHOW SCHEMAS","SHOW CATALOGS","SHOW COLUMNS","SHOW STATS FOR","SHOW ROLES","SHOW CURRENT ROLES","SHOW ROLE GRANTS","SHOW FUNCTIONS","SHOW SESSION"]),IY=W(["UNION [ALL | DISTINCT] [CORRESPONDING]","EXCEPT [ALL | DISTINCT] [CORRESPONDING]","INTERSECT [ALL | DISTINCT] [CORRESPONDING]"]),OY=W(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),NY=W(["{ROWS | RANGE | GROUPS} BETWEEN","IS [NOT] DISTINCT FROM"]),xY=W([]),yY={name:"trino",tokenizerOptions:{reservedSelect:mY,reservedClauses:[...gY,...iT,...bc],reservedSetOperations:IY,reservedJoins:OY,reservedKeywordPhrases:NY,reservedDataTypePhrases:xY,reservedKeywords:RY,reservedDataTypes:AY,reservedFunctionNames:hY,extraParens:["[]","{}"],stringTypes:[{quote:"''-qq",prefixes:["U&"]},{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq'],paramTypes:{positional:!0},operators:["%","->","=>",":","||","|","^","$"]},formatOptions:{onelineClauses:[...iT,...bc],tabularOnelineClauses:bc}},CY=["APPROX_COUNT_DISTINCT","AVG","CHECKSUM_AGG","COUNT","COUNT_BIG","GROUPING","GROUPING_ID","MAX","MIN","STDEV","STDEVP","SUM","VAR","VARP","CUME_DIST","FIRST_VALUE","LAG","LAST_VALUE","LEAD","PERCENTILE_CONT","PERCENTILE_DISC","PERCENT_RANK","Collation - COLLATIONPROPERTY","Collation - TERTIARY_WEIGHTS","@@DBTS","@@LANGID","@@LANGUAGE","@@LOCK_TIMEOUT","@@MAX_CONNECTIONS","@@MAX_PRECISION","@@NESTLEVEL","@@OPTIONS","@@REMSERVER","@@SERVERNAME","@@SERVICENAME","@@SPID","@@TEXTSIZE","@@VERSION","CAST","CONVERT","PARSE","TRY_CAST","TRY_CONVERT","TRY_PARSE","ASYMKEY_ID","ASYMKEYPROPERTY","CERTPROPERTY","CERT_ID","CRYPT_GEN_RANDOM","DECRYPTBYASYMKEY","DECRYPTBYCERT","DECRYPTBYKEY","DECRYPTBYKEYAUTOASYMKEY","DECRYPTBYKEYAUTOCERT","DECRYPTBYPASSPHRASE","ENCRYPTBYASYMKEY","ENCRYPTBYCERT","ENCRYPTBYKEY","ENCRYPTBYPASSPHRASE","HASHBYTES","IS_OBJECTSIGNED","KEY_GUID","KEY_ID","KEY_NAME","SIGNBYASYMKEY","SIGNBYCERT","SYMKEYPROPERTY","VERIFYSIGNEDBYCERT","VERIFYSIGNEDBYASYMKEY","@@CURSOR_ROWS","@@FETCH_STATUS","CURSOR_STATUS","DATALENGTH","IDENT_CURRENT","IDENT_INCR","IDENT_SEED","IDENTITY","SQL_VARIANT_PROPERTY","@@DATEFIRST","CURRENT_TIMESTAMP","CURRENT_TIMEZONE","CURRENT_TIMEZONE_ID","DATEADD","DATEDIFF","DATEDIFF_BIG","DATEFROMPARTS","DATENAME","DATEPART","DATETIME2FROMPARTS","DATETIMEFROMPARTS","DATETIMEOFFSETFROMPARTS","DAY","EOMONTH","GETDATE","GETUTCDATE","ISDATE","MONTH","SMALLDATETIMEFROMPARTS","SWITCHOFFSET","SYSDATETIME","SYSDATETIMEOFFSET","SYSUTCDATETIME","TIMEFROMPARTS","TODATETIMEOFFSET","YEAR","JSON","ISJSON","JSON_VALUE","JSON_QUERY","JSON_MODIFY","ABS","ACOS","ASIN","ATAN","ATN2","CEILING","COS","COT","DEGREES","EXP","FLOOR","LOG","LOG10","PI","POWER","RADIANS","RAND","ROUND","SIGN","SIN","SQRT","SQUARE","TAN","CHOOSE","GREATEST","IIF","LEAST","@@PROCID","APP_NAME","APPLOCK_MODE","APPLOCK_TEST","ASSEMBLYPROPERTY","COL_LENGTH","COL_NAME","COLUMNPROPERTY","DATABASEPROPERTYEX","DB_ID","DB_NAME","FILE_ID","FILE_IDEX","FILE_NAME","FILEGROUP_ID","FILEGROUP_NAME","FILEGROUPPROPERTY","FILEPROPERTY","FILEPROPERTYEX","FULLTEXTCATALOGPROPERTY","FULLTEXTSERVICEPROPERTY","INDEX_COL","INDEXKEY_PROPERTY","INDEXPROPERTY","NEXT VALUE FOR","OBJECT_DEFINITION","OBJECT_ID","OBJECT_NAME","OBJECT_SCHEMA_NAME","OBJECTPROPERTY","OBJECTPROPERTYEX","ORIGINAL_DB_NAME","PARSENAME","SCHEMA_ID","SCHEMA_NAME","SCOPE_IDENTITY","SERVERPROPERTY","STATS_DATE","TYPE_ID","TYPE_NAME","TYPEPROPERTY","DENSE_RANK","NTILE","RANK","ROW_NUMBER","PUBLISHINGSERVERNAME","CERTENCODED","CERTPRIVATEKEY","CURRENT_USER","DATABASE_PRINCIPAL_ID","HAS_DBACCESS","HAS_PERMS_BY_NAME","IS_MEMBER","IS_ROLEMEMBER","IS_SRVROLEMEMBER","LOGINPROPERTY","ORIGINAL_LOGIN","PERMISSIONS","PWDENCRYPT","PWDCOMPARE","SESSION_USER","SESSIONPROPERTY","SUSER_ID","SUSER_NAME","SUSER_SID","SUSER_SNAME","SYSTEM_USER","USER","USER_ID","USER_NAME","ASCII","CHARINDEX","CONCAT","CONCAT_WS","DIFFERENCE","FORMAT","LEFT","LEN","LOWER","LTRIM","PATINDEX","QUOTENAME","REPLACE","REPLICATE","REVERSE","RIGHT","RTRIM","SOUNDEX","SPACE","STR","STRING_AGG","STRING_ESCAPE","STUFF","SUBSTRING","TRANSLATE","TRIM","UNICODE","UPPER","$PARTITION","@@ERROR","@@IDENTITY","@@PACK_RECEIVED","@@ROWCOUNT","@@TRANCOUNT","BINARY_CHECKSUM","CHECKSUM","COMPRESS","CONNECTIONPROPERTY","CONTEXT_INFO","CURRENT_REQUEST_ID","CURRENT_TRANSACTION_ID","DECOMPRESS","ERROR_LINE","ERROR_MESSAGE","ERROR_NUMBER","ERROR_PROCEDURE","ERROR_SEVERITY","ERROR_STATE","FORMATMESSAGE","GET_FILESTREAM_TRANSACTION_CONTEXT","GETANSINULL","HOST_ID","HOST_NAME","ISNULL","ISNUMERIC","MIN_ACTIVE_ROWVERSION","NEWID","NEWSEQUENTIALID","ROWCOUNT_BIG","SESSION_CONTEXT","XACT_STATE","@@CONNECTIONS","@@CPU_BUSY","@@IDLE","@@IO_BUSY","@@PACK_SENT","@@PACKET_ERRORS","@@TIMETICKS","@@TOTAL_ERRORS","@@TOTAL_READ","@@TOTAL_WRITE","TEXTPTR","TEXTVALID","COLUMNS_UPDATED","EVENTDATA","TRIGGER_NESTLEVEL","UPDATE","COALESCE","NULLIF"],LY=["ADD","ALL","ALTER","AND","ANY","AS","ASC","AUTHORIZATION","BACKUP","BEGIN","BETWEEN","BREAK","BROWSE","BULK","BY","CASCADE","CHECK","CHECKPOINT","CLOSE","CLUSTERED","COALESCE","COLLATE","COLUMN","COMMIT","COMPUTE","CONSTRAINT","CONTAINS","CONTAINSTABLE","CONTINUE","CONVERT","CREATE","CROSS","CURRENT","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURSOR","DATABASE","DBCC","DEALLOCATE","DECLARE","DEFAULT","DELETE","DENY","DESC","DISK","DISTINCT","DISTRIBUTED","DROP","DUMP","ERRLVL","ESCAPE","EXEC","EXECUTE","EXISTS","EXIT","EXTERNAL","FETCH","FILE","FILLFACTOR","FOR","FOREIGN","FREETEXT","FREETEXTTABLE","FROM","FULL","FUNCTION","GOTO","GRANT","GROUP","HAVING","HOLDLOCK","IDENTITY","IDENTITYCOL","IDENTITY_INSERT","IF","IN","INDEX","INNER","INSERT","INTERSECT","INTO","IS","JOIN","KEY","KILL","LEFT","LIKE","LINENO","LOAD","MERGE","NOCHECK","NONCLUSTERED","NOT","NULL","NULLIF","OF","OFF","OFFSETS","ON","OPEN","OPENDATASOURCE","OPENQUERY","OPENROWSET","OPENXML","OPTION","OR","ORDER","OUTER","OVER","PERCENT","PIVOT","PLAN","PRIMARY","PRINT","PROC","PROCEDURE","PUBLIC","RAISERROR","READ","READTEXT","RECONFIGURE","REFERENCES","REPLICATION","RESTORE","RESTRICT","RETURN","REVERT","REVOKE","RIGHT","ROLLBACK","ROWCOUNT","ROWGUIDCOL","RULE","SAVE","SCHEMA","SECURITYAUDIT","SELECT","SEMANTICKEYPHRASETABLE","SEMANTICSIMILARITYDETAILSTABLE","SEMANTICSIMILARITYTABLE","SESSION_USER","SET","SETUSER","SHUTDOWN","SOME","STATISTICS","SYSTEM_USER","TABLE","TABLESAMPLE","TEXTSIZE","THEN","TO","TOP","TRAN","TRANSACTION","TRIGGER","TRUNCATE","TRY_CONVERT","TSEQUAL","UNION","UNIQUE","UNPIVOT","UPDATE","UPDATETEXT","USE","USER","VALUES","VIEW","WAITFOR","WHERE","WHILE","WITH","WITHIN GROUP","WRITETEXT","$ACTION"],_Y=["BINARY","BIT","CHAR","CHAR","CHARACTER","DATE","DATETIME2","DATETIMEOFFSET","DEC","DECIMAL","DOUBLE","FLOAT","INT","INTEGER","NATIONAL","NCHAR","NUMERIC","NVARCHAR","PRECISION","REAL","SMALLINT","TIME","TIMESTAMP","VARBINARY","VARCHAR"],bY=W(["SELECT [ALL | DISTINCT]"]),vY=W(["WITH","INTO","FROM","WHERE","GROUP BY","HAVING","WINDOW","PARTITION BY","ORDER BY","OFFSET","FETCH {FIRST | NEXT}","FOR {BROWSE | XML | JSON}","OPTION","INSERT [INTO]","VALUES","SET","MERGE [INTO]","WHEN [NOT] MATCHED [BY TARGET | BY SOURCE] [THEN]","UPDATE SET"]),aT=W(["CREATE TABLE"]),vc=W(["CREATE [OR ALTER] [MATERIALIZED] VIEW","UPDATE","WHERE CURRENT OF","DELETE [FROM]","DROP TABLE [IF EXISTS]","ALTER TABLE","ADD","DROP COLUMN [IF EXISTS]","ALTER COLUMN","TRUNCATE TABLE","CREATE [UNIQUE] [CLUSTERED] INDEX","CREATE DATABASE","ALTER DATABASE","DROP DATABASE [IF EXISTS]","CREATE [OR ALTER] [PARTITION] {FUNCTION | PROCEDURE | PROC}","ALTER [PARTITION] {FUNCTION | PROCEDURE | PROC}","DROP [PARTITION] {FUNCTION | PROCEDURE | PROC} [IF EXISTS]","GO","USE","ADD SENSITIVITY CLASSIFICATION","ADD SIGNATURE","AGGREGATE","ANSI_DEFAULTS","ANSI_NULLS","ANSI_NULL_DFLT_OFF","ANSI_NULL_DFLT_ON","ANSI_PADDING","ANSI_WARNINGS","APPLICATION ROLE","ARITHABORT","ARITHIGNORE","ASSEMBLY","ASYMMETRIC KEY","AUTHORIZATION","AVAILABILITY GROUP","BACKUP","BACKUP CERTIFICATE","BACKUP MASTER KEY","BACKUP SERVICE MASTER KEY","BEGIN CONVERSATION TIMER","BEGIN DIALOG CONVERSATION","BROKER PRIORITY","BULK INSERT","CERTIFICATE","CLOSE MASTER KEY","CLOSE SYMMETRIC KEY","COLUMN ENCRYPTION KEY","COLUMN MASTER KEY","COLUMNSTORE INDEX","CONCAT_NULL_YIELDS_NULL","CONTEXT_INFO","CONTRACT","CREDENTIAL","CRYPTOGRAPHIC PROVIDER","CURSOR_CLOSE_ON_COMMIT","DATABASE","DATABASE AUDIT SPECIFICATION","DATABASE ENCRYPTION KEY","DATABASE HADR","DATABASE SCOPED CONFIGURATION","DATABASE SCOPED CREDENTIAL","DATABASE SET","DATEFIRST","DATEFORMAT","DEADLOCK_PRIORITY","DENY","DENY XML","DISABLE TRIGGER","ENABLE TRIGGER","END CONVERSATION","ENDPOINT","EVENT NOTIFICATION","EVENT SESSION","EXECUTE AS","EXTERNAL DATA SOURCE","EXTERNAL FILE FORMAT","EXTERNAL LANGUAGE","EXTERNAL LIBRARY","EXTERNAL RESOURCE POOL","EXTERNAL TABLE","FIPS_FLAGGER","FMTONLY","FORCEPLAN","FULLTEXT CATALOG","FULLTEXT INDEX","FULLTEXT STOPLIST","GET CONVERSATION GROUP","GET_TRANSMISSION_STATUS","GRANT","GRANT XML","IDENTITY_INSERT","IMPLICIT_TRANSACTIONS","INDEX","LANGUAGE","LOCK_TIMEOUT","LOGIN","MASTER KEY","MESSAGE TYPE","MOVE CONVERSATION","NOCOUNT","NOEXEC","NUMERIC_ROUNDABORT","OFFSETS","OPEN MASTER KEY","OPEN SYMMETRIC KEY","PARSEONLY","PARTITION SCHEME","QUERY_GOVERNOR_COST_LIMIT","QUEUE","QUOTED_IDENTIFIER","RECEIVE","REMOTE SERVICE BINDING","REMOTE_PROC_TRANSACTIONS","RESOURCE GOVERNOR","RESOURCE POOL","RESTORE","RESTORE FILELISTONLY","RESTORE HEADERONLY","RESTORE LABELONLY","RESTORE MASTER KEY","RESTORE REWINDONLY","RESTORE SERVICE MASTER KEY","RESTORE VERIFYONLY","REVERT","REVOKE","REVOKE XML","ROLE","ROUTE","ROWCOUNT","RULE","SCHEMA","SEARCH PROPERTY LIST","SECURITY POLICY","SELECTIVE XML INDEX","SEND","SENSITIVITY CLASSIFICATION","SEQUENCE","SERVER AUDIT","SERVER AUDIT SPECIFICATION","SERVER CONFIGURATION","SERVER ROLE","SERVICE","SERVICE MASTER KEY","SETUSER","SHOWPLAN_ALL","SHOWPLAN_TEXT","SHOWPLAN_XML","SIGNATURE","SPATIAL INDEX","STATISTICS","STATISTICS IO","STATISTICS PROFILE","STATISTICS TIME","STATISTICS XML","SYMMETRIC KEY","SYNONYM","TABLE","TABLE IDENTITY","TEXTSIZE","TRANSACTION ISOLATION LEVEL","TRIGGER","TYPE","UPDATE STATISTICS","USER","WORKLOAD GROUP","XACT_ABORT","XML INDEX","XML SCHEMA COLLECTION"]),DY=W(["UNION [ALL]","EXCEPT","INTERSECT"]),MY=W(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","{CROSS | OUTER} APPLY"]),PY=W(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE} BETWEEN"]),wY=W([]),UY={name:"transactsql",tokenizerOptions:{reservedSelect:bY,reservedClauses:[...vY,...aT,...vc],reservedSetOperations:DY,reservedJoins:MY,reservedKeywordPhrases:PY,reservedDataTypePhrases:wY,reservedKeywords:LY,reservedDataTypes:_Y,reservedFunctionNames:CY,nestedBlockComments:!0,stringTypes:[{quote:"''-qq",prefixes:["N"]},"{}"],identTypes:['""-qq',"[]"],identChars:{first:"#@",rest:"#@$"},paramTypes:{named:["@"],quoted:["@"]},operators:["%","&","|","^","~","!<","!>","+=","-=","*=","/=","%=","|=","&=","^=","::",":"],propertyAccessOperators:[".."]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...aT,...vc],tabularOnelineClauses:vc}},BY=["ADD","ALL","ALTER","ANALYZE","AND","AS","ASC","ASENSITIVE","BEFORE","BETWEEN","_BINARY","BOTH","BY","CALL","CASCADE","CASE","CHANGE","CHECK","COLLATE","COLUMN","CONDITION","CONSTRAINT","CONTINUE","CONVERT","CREATE","CROSS","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURSOR","DATABASE","DATABASES","DAY_HOUR","DAY_MICROSECOND","DAY_MINUTE","DAY_SECOND","DECLARE","DEFAULT","DELAYED","DELETE","DESC","DESCRIBE","DETERMINISTIC","DISTINCT","DISTINCTROW","DIV","DROP","DUAL","EACH","ELSE","ELSEIF","ENCLOSED","ESCAPED","EXCEPT","EXISTS","EXIT","EXPLAIN","EXTRA_JOIN","FALSE","FETCH","FOR","FORCE","FORCE_COMPILED_MODE","FORCE_INTERPRETER_MODE","FOREIGN","FROM","FULL","FULLTEXT","GRANT","GROUP","HAVING","HEARTBEAT_NO_LOGGING","HIGH_PRIORITY","HOUR_MICROSECOND","HOUR_MINUTE","HOUR_SECOND","IF","IGNORE","IN","INDEX","INFILE","INNER","INOUT","INSENSITIVE","INSERT","IN","_INTERNAL_DYNAMIC_TYPECAST","INTERSECT","INTERVAL","INTO","ITERATE","JOIN","KEY","KEYS","KILL","LEADING","LEAVE","LEFT","LIKE","LIMIT","LINES","LOAD","LOCALTIME","LOCALTIMESTAMP","LOCK","LOOP","LOW_PRIORITY","MATCH","MAXVALUE","MINUS","MINUTE_MICROSECOND","MINUTE_SECOND","MOD","MODIFIES","NATURAL","NO_QUERY_REWRITE","NOT","NO_WRITE_TO_BINLOG","NO_QUERY_REWRITE","NULL","ON","OPTIMIZE","OPTION","OPTIONALLY","OR","ORDER","OUT","OUTER","OUTFILE","OVER","PRIMARY","PROCEDURE","PURGE","RANGE","READ","READS","REFERENCES","REGEXP","RELEASE","RENAME","REPEAT","REPLACE","REQUIRE","RESTRICT","RETURN","REVOKE","RIGHT","RIGHT_ANTI_JOIN","RIGHT_SEMI_JOIN","RIGHT_STRAIGHT_JOIN","RLIKE","SCHEMA","SCHEMAS","SECOND_MICROSECOND","SELECT","SEMI_JOIN","SENSITIVE","SEPARATOR","SET","SHOW","SIGNAL","SPATIAL","SPECIFIC","SQL","SQL_BIG_RESULT","SQL_BUFFER_RESULT","SQL_CACHE","SQL_CALC_FOUND_ROWS","SQLEXCEPTION","SQL_NO_CACHE","SQL_NO_LOGGING","SQL_SMALL_RESULT","SQLSTATE","SQLWARNING","STRAIGHT_JOIN","TABLE","TERMINATED","THEN","TO","TRAILING","TRIGGER","TRUE","UNBOUNDED","UNDO","UNION","UNIQUE","UNLOCK","UPDATE","USAGE","USE","USING","UTC_DATE","UTC_TIME","UTC_TIMESTAMP","_UTF8","VALUES","WHEN","WHERE","WHILE","WINDOW","WITH","WITHIN","WRITE","XOR","YEAR_MONTH","ZEROFILL"],jY=["BIGINT","BINARY","BIT","BLOB","CHAR","CHARACTER","DATETIME","DEC","DECIMAL","DOUBLE PRECISION","DOUBLE","ENUM","FIXED","FLOAT","FLOAT4","FLOAT8","INT","INT1","INT2","INT3","INT4","INT8","INTEGER","LONG","LONGBLOB","LONGTEXT","MEDIUMBLOB","MEDIUMINT","MEDIUMTEXT","MIDDLEINT","NATIONAL CHAR","NATIONAL VARCHAR","NUMERIC","PRECISION","REAL","SMALLINT","TEXT","TIME","TIMESTAMP","TINYBLOB","TINYINT","TINYTEXT","UNSIGNED","VARBINARY","VARCHAR","VARCHARACTER","YEAR"],kY=["ABS","ACOS","ADDDATE","ADDTIME","AES_DECRYPT","AES_ENCRYPT","ANY_VALUE","APPROX_COUNT_DISTINCT","APPROX_COUNT_DISTINCT_ACCUMULATE","APPROX_COUNT_DISTINCT_COMBINE","APPROX_COUNT_DISTINCT_ESTIMATE","APPROX_GEOGRAPHY_INTERSECTS","APPROX_PERCENTILE","ASCII","ASIN","ATAN","ATAN2","AVG","BIN","BINARY","BIT_AND","BIT_COUNT","BIT_OR","BIT_XOR","CAST","CEIL","CEILING","CHAR","CHARACTER_LENGTH","CHAR_LENGTH","CHARSET","COALESCE","COERCIBILITY","COLLATION","COLLECT","CONCAT","CONCAT_WS","CONNECTION_ID","CONV","CONVERT","CONVERT_TZ","COS","COT","COUNT","CUME_DIST","CURDATE","CURRENT_DATE","CURRENT_ROLE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURTIME","DATABASE","DATE","DATE_ADD","DATEDIFF","DATE_FORMAT","DATE_SUB","DATE_TRUNC","DAY","DAYNAME","DAYOFMONTH","DAYOFWEEK","DAYOFYEAR","DECODE","DEFAULT","DEGREES","DENSE_RANK","DIV","DOT_PRODUCT","ELT","EUCLIDEAN_DISTANCE","EXP","EXTRACT","FIELD","FIRST","FIRST_VALUE","FLOOR","FORMAT","FOUND_ROWS","FROM_BASE64","FROM_DAYS","FROM_UNIXTIME","GEOGRAPHY_AREA","GEOGRAPHY_CONTAINS","GEOGRAPHY_DISTANCE","GEOGRAPHY_INTERSECTS","GEOGRAPHY_LATITUDE","GEOGRAPHY_LENGTH","GEOGRAPHY_LONGITUDE","GEOGRAPHY_POINT","GEOGRAPHY_WITHIN_DISTANCE","GEOMETRY_AREA","GEOMETRY_CONTAINS","GEOMETRY_DISTANCE","GEOMETRY_FILTER","GEOMETRY_INTERSECTS","GEOMETRY_LENGTH","GEOMETRY_POINT","GEOMETRY_WITHIN_DISTANCE","GEOMETRY_X","GEOMETRY_Y","GREATEST","GROUPING","GROUP_CONCAT","HEX","HIGHLIGHT","HOUR","ICU_VERSION","IF","IFNULL","INET_ATON","INET_NTOA","INET6_ATON","INET6_NTOA","INITCAP","INSERT","INSTR","INTERVAL","IS","IS NULL","JSON_AGG","JSON_ARRAY_CONTAINS_DOUBLE","JSON_ARRAY_CONTAINS_JSON","JSON_ARRAY_CONTAINS_STRING","JSON_ARRAY_PUSH_DOUBLE","JSON_ARRAY_PUSH_JSON","JSON_ARRAY_PUSH_STRING","JSON_DELETE_KEY","JSON_EXTRACT_DOUBLE","JSON_EXTRACT_JSON","JSON_EXTRACT_STRING","JSON_EXTRACT_BIGINT","JSON_GET_TYPE","JSON_LENGTH","JSON_SET_DOUBLE","JSON_SET_JSON","JSON_SET_STRING","JSON_SPLICE_DOUBLE","JSON_SPLICE_JSON","JSON_SPLICE_STRING","LAG","LAST_DAY","LAST_VALUE","LCASE","LEAD","LEAST","LEFT","LENGTH","LIKE","LN","LOCALTIME","LOCALTIMESTAMP","LOCATE","LOG","LOG10","LOG2","LPAD","LTRIM","MATCH","MAX","MD5","MEDIAN","MICROSECOND","MIN","MINUTE","MOD","MONTH","MONTHNAME","MONTHS_BETWEEN","NOT","NOW","NTH_VALUE","NTILE","NULLIF","OCTET_LENGTH","PERCENT_RANK","PERCENTILE_CONT","PERCENTILE_DISC","PI","PIVOT","POSITION","POW","POWER","QUARTER","QUOTE","RADIANS","RAND","RANK","REGEXP","REPEAT","REPLACE","REVERSE","RIGHT","RLIKE","ROUND","ROW_COUNT","ROW_NUMBER","RPAD","RTRIM","SCALAR","SCHEMA","SEC_TO_TIME","SHA1","SHA2","SIGMOID","SIGN","SIN","SLEEP","SPLIT","SOUNDEX","SOUNDS LIKE","SOURCE_POS_WAIT","SPACE","SQRT","STDDEV","STDDEV_POP","STDDEV_SAMP","STR_TO_DATE","SUBDATE","SUBSTR","SUBSTRING","SUBSTRING_INDEX","SUM","SYS_GUID","TAN","TIME","TIMEDIFF","TIME_BUCKET","TIME_FORMAT","TIMESTAMP","TIMESTAMPADD","TIMESTAMPDIFF","TIME_TO_SEC","TO_BASE64","TO_CHAR","TO_DAYS","TO_JSON","TO_NUMBER","TO_SECONDS","TO_TIMESTAMP","TRIM","TRUNC","TRUNCATE","UCASE","UNHEX","UNIX_TIMESTAMP","UPDATEXML","UPPER","UTC_DATE","UTC_TIME","UTC_TIMESTAMP","UUID","VALUES","VARIANCE","VAR_POP","VAR_SAMP","VECTOR_SUB","VERSION","WEEK","WEEKDAY","WEEKOFYEAR","YEAR"],FY=W(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),GY=W(["WITH","FROM","WHERE","GROUP BY","HAVING","PARTITION BY","ORDER BY","LIMIT","OFFSET","INSERT [IGNORE] [INTO]","VALUES","REPLACE [INTO]","ON DUPLICATE KEY UPDATE","SET","CREATE [OR REPLACE] [TEMPORARY] PROCEDURE [IF NOT EXISTS]","CREATE [OR REPLACE] [EXTERNAL] FUNCTION"]),lT=W(["CREATE [ROWSTORE] [REFERENCE | TEMPORARY | GLOBAL TEMPORARY] TABLE [IF NOT EXISTS]"]),Dc=W(["CREATE VIEW","UPDATE","DELETE [FROM]","DROP [TEMPORARY] TABLE [IF EXISTS]","ALTER [ONLINE] TABLE","ADD [COLUMN]","ADD [UNIQUE] {INDEX | KEY}","DROP [COLUMN]","MODIFY [COLUMN]","CHANGE","RENAME [TO | AS]","TRUNCATE [TABLE]","ADD AGGREGATOR","ADD LEAF","AGGREGATOR SET AS MASTER","ALTER DATABASE","ALTER PIPELINE","ALTER RESOURCE POOL","ALTER USER","ALTER VIEW","ANALYZE TABLE","ATTACH DATABASE","ATTACH LEAF","ATTACH LEAF ALL","BACKUP DATABASE","BINLOG","BOOTSTRAP AGGREGATOR","CACHE INDEX","CALL","CHANGE","CHANGE MASTER TO","CHANGE REPLICATION FILTER","CHANGE REPLICATION SOURCE TO","CHECK BLOB CHECKSUM","CHECK TABLE","CHECKSUM TABLE","CLEAR ORPHAN DATABASES","CLONE","COMMIT","CREATE DATABASE","CREATE GROUP","CREATE INDEX","CREATE LINK","CREATE MILESTONE","CREATE PIPELINE","CREATE RESOURCE POOL","CREATE ROLE","CREATE USER","DEALLOCATE PREPARE","DESCRIBE","DETACH DATABASE","DETACH PIPELINE","DROP DATABASE","DROP FUNCTION","DROP INDEX","DROP LINK","DROP PIPELINE","DROP PROCEDURE","DROP RESOURCE POOL","DROP ROLE","DROP USER","DROP VIEW","EXECUTE","EXPLAIN","FLUSH","FORCE","GRANT","HANDLER","HELP","KILL CONNECTION","KILLALL QUERIES","LOAD DATA","LOAD INDEX INTO CACHE","LOAD XML","LOCK INSTANCE FOR BACKUP","LOCK TABLES","MASTER_POS_WAIT","OPTIMIZE TABLE","PREPARE","PURGE BINARY LOGS","REBALANCE PARTITIONS","RELEASE SAVEPOINT","REMOVE AGGREGATOR","REMOVE LEAF","REPAIR TABLE","REPLACE","REPLICATE DATABASE","RESET","RESET MASTER","RESET PERSIST","RESET REPLICA","RESET SLAVE","RESTART","RESTORE DATABASE","RESTORE REDUNDANCY","REVOKE","ROLLBACK","ROLLBACK TO SAVEPOINT","SAVEPOINT","SET CHARACTER SET","SET DEFAULT ROLE","SET NAMES","SET PASSWORD","SET RESOURCE GROUP","SET ROLE","SET TRANSACTION","SHOW","SHOW CHARACTER SET","SHOW COLLATION","SHOW COLUMNS","SHOW CREATE DATABASE","SHOW CREATE FUNCTION","SHOW CREATE PIPELINE","SHOW CREATE PROCEDURE","SHOW CREATE TABLE","SHOW CREATE USER","SHOW CREATE VIEW","SHOW DATABASES","SHOW ENGINE","SHOW ENGINES","SHOW ERRORS","SHOW FUNCTION CODE","SHOW FUNCTION STATUS","SHOW GRANTS","SHOW INDEX","SHOW MASTER STATUS","SHOW OPEN TABLES","SHOW PLUGINS","SHOW PRIVILEGES","SHOW PROCEDURE CODE","SHOW PROCEDURE STATUS","SHOW PROCESSLIST","SHOW PROFILE","SHOW PROFILES","SHOW RELAYLOG EVENTS","SHOW REPLICA STATUS","SHOW REPLICAS","SHOW SLAVE","SHOW SLAVE HOSTS","SHOW STATUS","SHOW TABLE STATUS","SHOW TABLES","SHOW VARIABLES","SHOW WARNINGS","SHUTDOWN","SNAPSHOT DATABASE","SOURCE_POS_WAIT","START GROUP_REPLICATION","START PIPELINE","START REPLICA","START SLAVE","START TRANSACTION","STOP GROUP_REPLICATION","STOP PIPELINE","STOP REPLICA","STOP REPLICATING","STOP SLAVE","TEST PIPELINE","UNLOCK INSTANCE","UNLOCK TABLES","USE","XA","ITERATE","LEAVE","LOOP","REPEAT","RETURN","WHILE"]),HY=W(["UNION [ALL | DISTINCT]","EXCEPT","INTERSECT","MINUS"]),WY=W(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),YY=W(["ON DELETE","ON UPDATE","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),$Y=W([]),VY={name:"singlestoredb",tokenizerOptions:{reservedSelect:FY,reservedClauses:[...GY,...lT,...Dc],reservedSetOperations:HY,reservedJoins:WY,reservedKeywordPhrases:YY,reservedDataTypePhrases:$Y,reservedKeywords:BY,reservedDataTypes:jY,reservedFunctionNames:kY,stringTypes:['""-qq-bs',"''-qq-bs",{quote:"''-raw",prefixes:["B","X"],requirePrefix:!0}],identTypes:["``"],identChars:{first:"$",rest:"$",allowFirstCharNumber:!0},variableTypes:[{regex:"@@?[A-Za-z0-9_$]+"},{quote:"``",prefixes:["@"],requirePrefix:!0}],lineCommentTypes:["--","#"],operators:[":=","&","|","^","~","<<",">>","<=>","&&","||","::","::$","::%",":>","!:>","*.*"],postProcess:ll},formatOptions:{alwaysDenseOperators:["::","::$","::%"],onelineClauses:[...lT,...Dc],tabularOnelineClauses:Dc}},zY=["ABS","ACOS","ACOSH","ADD_MONTHS","ALL_USER_NAMES","ANY_VALUE","APPROX_COUNT_DISTINCT","APPROX_PERCENTILE","APPROX_PERCENTILE_ACCUMULATE","APPROX_PERCENTILE_COMBINE","APPROX_PERCENTILE_ESTIMATE","APPROX_TOP_K","APPROX_TOP_K_ACCUMULATE","APPROX_TOP_K_COMBINE","APPROX_TOP_K_ESTIMATE","APPROXIMATE_JACCARD_INDEX","APPROXIMATE_SIMILARITY","ARRAY_AGG","ARRAY_APPEND","ARRAY_CAT","ARRAY_COMPACT","ARRAY_CONSTRUCT","ARRAY_CONSTRUCT_COMPACT","ARRAY_CONTAINS","ARRAY_INSERT","ARRAY_INTERSECTION","ARRAY_POSITION","ARRAY_PREPEND","ARRAY_SIZE","ARRAY_SLICE","ARRAY_TO_STRING","ARRAY_UNION_AGG","ARRAY_UNIQUE_AGG","ARRAYS_OVERLAP","AS_ARRAY","AS_BINARY","AS_BOOLEAN","AS_CHAR","AS_VARCHAR","AS_DATE","AS_DECIMAL","AS_NUMBER","AS_DOUBLE","AS_REAL","AS_INTEGER","AS_OBJECT","AS_TIME","AS_TIMESTAMP_LTZ","AS_TIMESTAMP_NTZ","AS_TIMESTAMP_TZ","ASCII","ASIN","ASINH","ATAN","ATAN2","ATANH","AUTO_REFRESH_REGISTRATION_HISTORY","AUTOMATIC_CLUSTERING_HISTORY","AVG","BASE64_DECODE_BINARY","BASE64_DECODE_STRING","BASE64_ENCODE","BIT_LENGTH","BITAND","BITAND_AGG","BITMAP_BIT_POSITION","BITMAP_BUCKET_NUMBER","BITMAP_CONSTRUCT_AGG","BITMAP_COUNT","BITMAP_OR_AGG","BITNOT","BITOR","BITOR_AGG","BITSHIFTLEFT","BITSHIFTRIGHT","BITXOR","BITXOR_AGG","BOOLAND","BOOLAND_AGG","BOOLNOT","BOOLOR","BOOLOR_AGG","BOOLXOR","BOOLXOR_AGG","BUILD_SCOPED_FILE_URL","BUILD_STAGE_FILE_URL","CASE","CAST","CBRT","CEIL","CHARINDEX","CHECK_JSON","CHECK_XML","CHR","CHAR","COALESCE","COLLATE","COLLATION","COMPLETE_TASK_GRAPHS","COMPRESS","CONCAT","CONCAT_WS","CONDITIONAL_CHANGE_EVENT","CONDITIONAL_TRUE_EVENT","CONTAINS","CONVERT_TIMEZONE","COPY_HISTORY","CORR","COS","COSH","COT","COUNT","COUNT_IF","COVAR_POP","COVAR_SAMP","CUME_DIST","CURRENT_ACCOUNT","CURRENT_AVAILABLE_ROLES","CURRENT_CLIENT","CURRENT_DATABASE","CURRENT_DATE","CURRENT_IP_ADDRESS","CURRENT_REGION","CURRENT_ROLE","CURRENT_SCHEMA","CURRENT_SCHEMAS","CURRENT_SECONDARY_ROLES","CURRENT_SESSION","CURRENT_STATEMENT","CURRENT_TASK_GRAPHS","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_TRANSACTION","CURRENT_USER","CURRENT_VERSION","CURRENT_WAREHOUSE","DATA_TRANSFER_HISTORY","DATABASE_REFRESH_HISTORY","DATABASE_REFRESH_PROGRESS","DATABASE_REFRESH_PROGRESS_BY_JOB","DATABASE_STORAGE_USAGE_HISTORY","DATE_FROM_PARTS","DATE_PART","DATE_TRUNC","DATEADD","DATEDIFF","DAYNAME","DECODE","DECOMPRESS_BINARY","DECOMPRESS_STRING","DECRYPT","DECRYPT_RAW","DEGREES","DENSE_RANK","DIV0","EDITDISTANCE","ENCRYPT","ENCRYPT_RAW","ENDSWITH","EQUAL_NULL","EXP","EXPLAIN_JSON","EXTERNAL_FUNCTIONS_HISTORY","EXTERNAL_TABLE_FILES","EXTERNAL_TABLE_FILE_REGISTRATION_HISTORY","EXTRACT","EXTRACT_SEMANTIC_CATEGORIES","FACTORIAL","FILTER","FIRST_VALUE","FLATTEN","FLOOR","GENERATE_COLUMN_DESCRIPTION","GENERATOR","GET","GET_ABSOLUTE_PATH","GET_DDL","GET_IGNORE_CASE","GET_OBJECT_REFERENCES","GET_PATH","GET_PRESIGNED_URL","GET_RELATIVE_PATH","GET_STAGE_LOCATION","GETBIT","GREATEST","GREATEST_IGNORE_NULLS","GROUPING","GROUPING_ID","HASH","HASH_AGG","HAVERSINE","HEX_DECODE_BINARY","HEX_DECODE_STRING","HEX_ENCODE","HLL","HLL_ACCUMULATE","HLL_COMBINE","HLL_ESTIMATE","HLL_EXPORT","HLL_IMPORT","HOUR","MINUTE","SECOND","IDENTIFIER","IFF","IFNULL","ILIKE","ILIKE ANY","INFER_SCHEMA","INITCAP","INSERT","INVOKER_ROLE","INVOKER_SHARE","IS_ARRAY","IS_BINARY","IS_BOOLEAN","IS_CHAR","IS_VARCHAR","IS_DATE","IS_DATE_VALUE","IS_DECIMAL","IS_DOUBLE","IS_REAL","IS_GRANTED_TO_INVOKER_ROLE","IS_INTEGER","IS_NULL_VALUE","IS_OBJECT","IS_ROLE_IN_SESSION","IS_TIME","IS_TIMESTAMP_LTZ","IS_TIMESTAMP_NTZ","IS_TIMESTAMP_TZ","JAROWINKLER_SIMILARITY","JSON_EXTRACT_PATH_TEXT","KURTOSIS","LAG","LAST_DAY","LAST_QUERY_ID","LAST_TRANSACTION","LAST_VALUE","LEAD","LEAST","LEFT","LENGTH","LEN","LIKE","LIKE ALL","LIKE ANY","LISTAGG","LN","LOCALTIME","LOCALTIMESTAMP","LOG","LOGIN_HISTORY","LOGIN_HISTORY_BY_USER","LOWER","LPAD","LTRIM","MATERIALIZED_VIEW_REFRESH_HISTORY","MD5","MD5_HEX","MD5_BINARY","MD5_NUMBER — Obsoleted","MD5_NUMBER_LOWER64","MD5_NUMBER_UPPER64","MEDIAN","MIN","MAX","MINHASH","MINHASH_COMBINE","MOD","MODE","MONTHNAME","MONTHS_BETWEEN","NEXT_DAY","NORMAL","NTH_VALUE","NTILE","NULLIF","NULLIFZERO","NVL","NVL2","OBJECT_AGG","OBJECT_CONSTRUCT","OBJECT_CONSTRUCT_KEEP_NULL","OBJECT_DELETE","OBJECT_INSERT","OBJECT_KEYS","OBJECT_PICK","OCTET_LENGTH","PARSE_IP","PARSE_JSON","PARSE_URL","PARSE_XML","PERCENT_RANK","PERCENTILE_CONT","PERCENTILE_DISC","PI","PIPE_USAGE_HISTORY","POLICY_CONTEXT","POLICY_REFERENCES","POSITION","POW","POWER","PREVIOUS_DAY","QUERY_ACCELERATION_HISTORY","QUERY_HISTORY","QUERY_HISTORY_BY_SESSION","QUERY_HISTORY_BY_USER","QUERY_HISTORY_BY_WAREHOUSE","RADIANS","RANDOM","RANDSTR","RANK","RATIO_TO_REPORT","REGEXP","REGEXP_COUNT","REGEXP_INSTR","REGEXP_LIKE","REGEXP_REPLACE","REGEXP_SUBSTR","REGEXP_SUBSTR_ALL","REGR_AVGX","REGR_AVGY","REGR_COUNT","REGR_INTERCEPT","REGR_R2","REGR_SLOPE","REGR_SXX","REGR_SXY","REGR_SYY","REGR_VALX","REGR_VALY","REPEAT","REPLACE","REPLICATION_GROUP_REFRESH_HISTORY","REPLICATION_GROUP_REFRESH_PROGRESS","REPLICATION_GROUP_REFRESH_PROGRESS_BY_JOB","REPLICATION_GROUP_USAGE_HISTORY","REPLICATION_USAGE_HISTORY","REST_EVENT_HISTORY","RESULT_SCAN","REVERSE","RIGHT","RLIKE","ROUND","ROW_NUMBER","RPAD","RTRIM","RTRIMMED_LENGTH","SEARCH_OPTIMIZATION_HISTORY","SEQ1","SEQ2","SEQ4","SEQ8","SERVERLESS_TASK_HISTORY","SHA1","SHA1_HEX","SHA1_BINARY","SHA2","SHA2_HEX","SHA2_BINARY","SIGN","SIN","SINH","SKEW","SOUNDEX","SPACE","SPLIT","SPLIT_PART","SPLIT_TO_TABLE","SQRT","SQUARE","ST_AREA","ST_ASEWKB","ST_ASEWKT","ST_ASGEOJSON","ST_ASWKB","ST_ASBINARY","ST_ASWKT","ST_ASTEXT","ST_AZIMUTH","ST_CENTROID","ST_COLLECT","ST_CONTAINS","ST_COVEREDBY","ST_COVERS","ST_DIFFERENCE","ST_DIMENSION","ST_DISJOINT","ST_DISTANCE","ST_DWITHIN","ST_ENDPOINT","ST_ENVELOPE","ST_GEOGFROMGEOHASH","ST_GEOGPOINTFROMGEOHASH","ST_GEOGRAPHYFROMWKB","ST_GEOGRAPHYFROMWKT","ST_GEOHASH","ST_GEOMETRYFROMWKB","ST_GEOMETRYFROMWKT","ST_HAUSDORFFDISTANCE","ST_INTERSECTION","ST_INTERSECTS","ST_LENGTH","ST_MAKEGEOMPOINT","ST_GEOM_POINT","ST_MAKELINE","ST_MAKEPOINT","ST_POINT","ST_MAKEPOLYGON","ST_POLYGON","ST_NPOINTS","ST_NUMPOINTS","ST_PERIMETER","ST_POINTN","ST_SETSRID","ST_SIMPLIFY","ST_SRID","ST_STARTPOINT","ST_SYMDIFFERENCE","ST_UNION","ST_WITHIN","ST_X","ST_XMAX","ST_XMIN","ST_Y","ST_YMAX","ST_YMIN","STAGE_DIRECTORY_FILE_REGISTRATION_HISTORY","STAGE_STORAGE_USAGE_HISTORY","STARTSWITH","STDDEV","STDDEV_POP","STDDEV_SAMP","STRIP_NULL_VALUE","STRTOK","STRTOK_SPLIT_TO_TABLE","STRTOK_TO_ARRAY","SUBSTR","SUBSTRING","SUM","SYSDATE","SYSTEM$ABORT_SESSION","SYSTEM$ABORT_TRANSACTION","SYSTEM$AUTHORIZE_PRIVATELINK","SYSTEM$AUTHORIZE_STAGE_PRIVATELINK_ACCESS","SYSTEM$BEHAVIOR_CHANGE_BUNDLE_STATUS","SYSTEM$CANCEL_ALL_QUERIES","SYSTEM$CANCEL_QUERY","SYSTEM$CLUSTERING_DEPTH","SYSTEM$CLUSTERING_INFORMATION","SYSTEM$CLUSTERING_RATIO ","SYSTEM$CURRENT_USER_TASK_NAME","SYSTEM$DATABASE_REFRESH_HISTORY ","SYSTEM$DATABASE_REFRESH_PROGRESS","SYSTEM$DATABASE_REFRESH_PROGRESS_BY_JOB ","SYSTEM$DISABLE_BEHAVIOR_CHANGE_BUNDLE","SYSTEM$DISABLE_DATABASE_REPLICATION","SYSTEM$ENABLE_BEHAVIOR_CHANGE_BUNDLE","SYSTEM$ESTIMATE_QUERY_ACCELERATION","SYSTEM$ESTIMATE_SEARCH_OPTIMIZATION_COSTS","SYSTEM$EXPLAIN_JSON_TO_TEXT","SYSTEM$EXPLAIN_PLAN_JSON","SYSTEM$EXTERNAL_TABLE_PIPE_STATUS","SYSTEM$GENERATE_SAML_CSR","SYSTEM$GENERATE_SCIM_ACCESS_TOKEN","SYSTEM$GET_AWS_SNS_IAM_POLICY","SYSTEM$GET_PREDECESSOR_RETURN_VALUE","SYSTEM$GET_PRIVATELINK","SYSTEM$GET_PRIVATELINK_AUTHORIZED_ENDPOINTS","SYSTEM$GET_PRIVATELINK_CONFIG","SYSTEM$GET_SNOWFLAKE_PLATFORM_INFO","SYSTEM$GET_TAG","SYSTEM$GET_TAG_ALLOWED_VALUES","SYSTEM$GET_TAG_ON_CURRENT_COLUMN","SYSTEM$GET_TAG_ON_CURRENT_TABLE","SYSTEM$GLOBAL_ACCOUNT_SET_PARAMETER","SYSTEM$LAST_CHANGE_COMMIT_TIME","SYSTEM$LINK_ACCOUNT_OBJECTS_BY_NAME","SYSTEM$MIGRATE_SAML_IDP_REGISTRATION","SYSTEM$PIPE_FORCE_RESUME","SYSTEM$PIPE_STATUS","SYSTEM$REVOKE_PRIVATELINK","SYSTEM$REVOKE_STAGE_PRIVATELINK_ACCESS","SYSTEM$SET_RETURN_VALUE","SYSTEM$SHOW_OAUTH_CLIENT_SECRETS","SYSTEM$STREAM_GET_TABLE_TIMESTAMP","SYSTEM$STREAM_HAS_DATA","SYSTEM$TASK_DEPENDENTS_ENABLE","SYSTEM$TYPEOF","SYSTEM$USER_TASK_CANCEL_ONGOING_EXECUTIONS","SYSTEM$VERIFY_EXTERNAL_OAUTH_TOKEN","SYSTEM$WAIT","SYSTEM$WHITELIST","SYSTEM$WHITELIST_PRIVATELINK","TAG_REFERENCES","TAG_REFERENCES_ALL_COLUMNS","TAG_REFERENCES_WITH_LINEAGE","TAN","TANH","TASK_DEPENDENTS","TASK_HISTORY","TIME_FROM_PARTS","TIME_SLICE","TIMEADD","TIMEDIFF","TIMESTAMP_FROM_PARTS","TIMESTAMPADD","TIMESTAMPDIFF","TO_ARRAY","TO_BINARY","TO_BOOLEAN","TO_CHAR","TO_VARCHAR","TO_DATE","DATE","TO_DECIMAL","TO_NUMBER","TO_NUMERIC","TO_DOUBLE","TO_GEOGRAPHY","TO_GEOMETRY","TO_JSON","TO_OBJECT","TO_TIME","TIME","TO_TIMESTAMP","TO_TIMESTAMP_LTZ","TO_TIMESTAMP_NTZ","TO_TIMESTAMP_TZ","TO_VARIANT","TO_XML","TRANSLATE","TRIM","TRUNCATE","TRUNC","TRUNC","TRY_BASE64_DECODE_BINARY","TRY_BASE64_DECODE_STRING","TRY_CAST","TRY_HEX_DECODE_BINARY","TRY_HEX_DECODE_STRING","TRY_PARSE_JSON","TRY_TO_BINARY","TRY_TO_BOOLEAN","TRY_TO_DATE","TRY_TO_DECIMAL","TRY_TO_NUMBER","TRY_TO_NUMERIC","TRY_TO_DOUBLE","TRY_TO_GEOGRAPHY","TRY_TO_GEOMETRY","TRY_TO_TIME","TRY_TO_TIMESTAMP","TRY_TO_TIMESTAMP_LTZ","TRY_TO_TIMESTAMP_NTZ","TRY_TO_TIMESTAMP_TZ","TYPEOF","UNICODE","UNIFORM","UPPER","UUID_STRING","VALIDATE","VALIDATE_PIPE_LOAD","VAR_POP","VAR_SAMP","VARIANCE","VARIANCE_SAMP","VARIANCE_POP","WAREHOUSE_LOAD_HISTORY","WAREHOUSE_METERING_HISTORY","WIDTH_BUCKET","XMLGET","YEAR","YEAROFWEEK","YEAROFWEEKISO","DAY","DAYOFMONTH","DAYOFWEEK","DAYOFWEEKISO","DAYOFYEAR","WEEK","WEEK","WEEKOFYEAR","WEEKISO","MONTH","QUARTER","ZEROIFNULL","ZIPF"],XY=["ACCOUNT","ALL","ALTER","AND","ANY","AS","BETWEEN","BY","CASE","CAST","CHECK","COLUMN","CONNECT","CONNECTION","CONSTRAINT","CREATE","CROSS","CURRENT","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","DATABASE","DELETE","DISTINCT","DROP","ELSE","EXISTS","FALSE","FOLLOWING","FOR","FROM","FULL","GRANT","GROUP","GSCLUSTER","HAVING","ILIKE","IN","INCREMENT","INNER","INSERT","INTERSECT","INTO","IS","ISSUE","JOIN","LATERAL","LEFT","LIKE","LOCALTIME","LOCALTIMESTAMP","MINUS","NATURAL","NOT","NULL","OF","ON","OR","ORDER","ORGANIZATION","QUALIFY","REGEXP","REVOKE","RIGHT","RLIKE","ROW","ROWS","SAMPLE","SCHEMA","SELECT","SET","SOME","START","TABLE","TABLESAMPLE","THEN","TO","TRIGGER","TRUE","TRY_CAST","UNION","UNIQUE","UPDATE","USING","VALUES","VIEW","WHEN","WHENEVER","WHERE","WITH","COMMENT"],KY=["NUMBER","DECIMAL","NUMERIC","INT","INTEGER","BIGINT","SMALLINT","TINYINT","BYTEINT","FLOAT","FLOAT4","FLOAT8","DOUBLE","DOUBLE PRECISION","REAL","VARCHAR","CHAR","CHARACTER","STRING","TEXT","BINARY","VARBINARY","BOOLEAN","DATE","DATETIME","TIME","TIMESTAMP","TIMESTAMP_LTZ","TIMESTAMP_NTZ","TIMESTAMP","TIMESTAMP_TZ","VARIANT","OBJECT","ARRAY","GEOGRAPHY","GEOMETRY"],qY=W(["SELECT [ALL | DISTINCT]"]),JY=W(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","PARTITION BY","ORDER BY","QUALIFY","LIMIT","OFFSET","FETCH [FIRST | NEXT]","INSERT [OVERWRITE] [ALL INTO | INTO | ALL | FIRST]","{THEN | ELSE} INTO","VALUES","SET","CLUSTER BY","[WITH] {MASKING POLICY | TAG | ROW ACCESS POLICY}","COPY GRANTS","USING TEMPLATE","MERGE INTO","WHEN MATCHED [AND]","THEN {UPDATE SET | DELETE}","WHEN NOT MATCHED THEN INSERT"]),cT=W(["CREATE [OR REPLACE] [VOLATILE] TABLE [IF NOT EXISTS]","CREATE [OR REPLACE] [LOCAL | GLOBAL] {TEMP|TEMPORARY} TABLE [IF NOT EXISTS]"]),Mc=W(["CREATE [OR REPLACE] [SECURE] [RECURSIVE] VIEW [IF NOT EXISTS]","UPDATE","DELETE FROM","DROP TABLE [IF EXISTS]","ALTER TABLE [IF EXISTS]","RENAME TO","SWAP WITH","[SUSPEND | RESUME] RECLUSTER","DROP CLUSTERING KEY","ADD [COLUMN]","RENAME COLUMN","{ALTER | MODIFY} [COLUMN]","DROP [COLUMN]","{ADD | ALTER | MODIFY | DROP} [CONSTRAINT]","RENAME CONSTRAINT","{ADD | DROP} SEARCH OPTIMIZATION","{SET | UNSET} TAG","{ADD | DROP} ROW ACCESS POLICY","DROP ALL ROW ACCESS POLICIES","{SET | DROP} DEFAULT","{SET | DROP} NOT NULL","SET DATA TYPE","UNSET COMMENT","{SET | UNSET} MASKING POLICY","TRUNCATE [TABLE] [IF EXISTS]","ALTER ACCOUNT","ALTER API INTEGRATION","ALTER CONNECTION","ALTER DATABASE","ALTER EXTERNAL TABLE","ALTER FAILOVER GROUP","ALTER FILE FORMAT","ALTER FUNCTION","ALTER INTEGRATION","ALTER MASKING POLICY","ALTER MATERIALIZED VIEW","ALTER NETWORK POLICY","ALTER NOTIFICATION INTEGRATION","ALTER PIPE","ALTER PROCEDURE","ALTER REPLICATION GROUP","ALTER RESOURCE MONITOR","ALTER ROLE","ALTER ROW ACCESS POLICY","ALTER SCHEMA","ALTER SECURITY INTEGRATION","ALTER SEQUENCE","ALTER SESSION","ALTER SESSION POLICY","ALTER SHARE","ALTER STAGE","ALTER STORAGE INTEGRATION","ALTER STREAM","ALTER TAG","ALTER TASK","ALTER USER","ALTER VIEW","ALTER WAREHOUSE","BEGIN","CALL","COMMIT","COPY INTO","CREATE ACCOUNT","CREATE API INTEGRATION","CREATE CONNECTION","CREATE DATABASE","CREATE EXTERNAL FUNCTION","CREATE EXTERNAL TABLE","CREATE FAILOVER GROUP","CREATE FILE FORMAT","CREATE FUNCTION","CREATE INTEGRATION","CREATE MANAGED ACCOUNT","CREATE MASKING POLICY","CREATE MATERIALIZED VIEW","CREATE NETWORK POLICY","CREATE NOTIFICATION INTEGRATION","CREATE PIPE","CREATE PROCEDURE","CREATE REPLICATION GROUP","CREATE RESOURCE MONITOR","CREATE ROLE","CREATE ROW ACCESS POLICY","CREATE SCHEMA","CREATE SECURITY INTEGRATION","CREATE SEQUENCE","CREATE SESSION POLICY","CREATE SHARE","CREATE STAGE","CREATE STORAGE INTEGRATION","CREATE STREAM","CREATE TAG","CREATE TASK","CREATE USER","CREATE WAREHOUSE","DELETE","DESCRIBE DATABASE","DESCRIBE EXTERNAL TABLE","DESCRIBE FILE FORMAT","DESCRIBE FUNCTION","DESCRIBE INTEGRATION","DESCRIBE MASKING POLICY","DESCRIBE MATERIALIZED VIEW","DESCRIBE NETWORK POLICY","DESCRIBE PIPE","DESCRIBE PROCEDURE","DESCRIBE RESULT","DESCRIBE ROW ACCESS POLICY","DESCRIBE SCHEMA","DESCRIBE SEQUENCE","DESCRIBE SESSION POLICY","DESCRIBE SHARE","DESCRIBE STAGE","DESCRIBE STREAM","DESCRIBE TABLE","DESCRIBE TASK","DESCRIBE TRANSACTION","DESCRIBE USER","DESCRIBE VIEW","DESCRIBE WAREHOUSE","DROP CONNECTION","DROP DATABASE","DROP EXTERNAL TABLE","DROP FAILOVER GROUP","DROP FILE FORMAT","DROP FUNCTION","DROP INTEGRATION","DROP MANAGED ACCOUNT","DROP MASKING POLICY","DROP MATERIALIZED VIEW","DROP NETWORK POLICY","DROP PIPE","DROP PROCEDURE","DROP REPLICATION GROUP","DROP RESOURCE MONITOR","DROP ROLE","DROP ROW ACCESS POLICY","DROP SCHEMA","DROP SEQUENCE","DROP SESSION POLICY","DROP SHARE","DROP STAGE","DROP STREAM","DROP TAG","DROP TASK","DROP USER","DROP VIEW","DROP WAREHOUSE","EXECUTE IMMEDIATE","EXECUTE TASK","EXPLAIN","GET","GRANT OWNERSHIP","GRANT ROLE","INSERT","LIST","MERGE","PUT","REMOVE","REVOKE ROLE","ROLLBACK","SHOW COLUMNS","SHOW CONNECTIONS","SHOW DATABASES","SHOW DATABASES IN FAILOVER GROUP","SHOW DATABASES IN REPLICATION GROUP","SHOW DELEGATED AUTHORIZATIONS","SHOW EXTERNAL FUNCTIONS","SHOW EXTERNAL TABLES","SHOW FAILOVER GROUPS","SHOW FILE FORMATS","SHOW FUNCTIONS","SHOW GLOBAL ACCOUNTS","SHOW GRANTS","SHOW INTEGRATIONS","SHOW LOCKS","SHOW MANAGED ACCOUNTS","SHOW MASKING POLICIES","SHOW MATERIALIZED VIEWS","SHOW NETWORK POLICIES","SHOW OBJECTS","SHOW ORGANIZATION ACCOUNTS","SHOW PARAMETERS","SHOW PIPES","SHOW PRIMARY KEYS","SHOW PROCEDURES","SHOW REGIONS","SHOW REPLICATION ACCOUNTS","SHOW REPLICATION DATABASES","SHOW REPLICATION GROUPS","SHOW RESOURCE MONITORS","SHOW ROLES","SHOW ROW ACCESS POLICIES","SHOW SCHEMAS","SHOW SEQUENCES","SHOW SESSION POLICIES","SHOW SHARES","SHOW SHARES IN FAILOVER GROUP","SHOW SHARES IN REPLICATION GROUP","SHOW STAGES","SHOW STREAMS","SHOW TABLES","SHOW TAGS","SHOW TASKS","SHOW TRANSACTIONS","SHOW USER FUNCTIONS","SHOW USERS","SHOW VARIABLES","SHOW VIEWS","SHOW WAREHOUSES","TRUNCATE MATERIALIZED VIEW","UNDROP DATABASE","UNDROP SCHEMA","UNDROP TABLE","UNDROP TAG","UNSET","USE DATABASE","USE ROLE","USE SCHEMA","USE SECONDARY ROLES","USE WAREHOUSE"]),QY=W(["UNION [ALL]","MINUS","EXCEPT","INTERSECT"]),ZY=W(["[INNER] JOIN","[NATURAL] {LEFT | RIGHT | FULL} [OUTER] JOIN","{CROSS | NATURAL} JOIN"]),e$=W(["{ROWS | RANGE} BETWEEN","ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]"]),t$=W([]),n$={name:"snowflake",tokenizerOptions:{reservedSelect:qY,reservedClauses:[...JY,...cT,...Mc],reservedSetOperations:QY,reservedJoins:ZY,reservedKeywordPhrases:e$,reservedDataTypePhrases:t$,reservedKeywords:XY,reservedDataTypes:KY,reservedFunctionNames:zY,stringTypes:["$$","''-qq-bs"],identTypes:['""-qq'],variableTypes:[{regex:"[$][1-9]\\d*"},{regex:"[$][_a-zA-Z][_a-zA-Z0-9$]*"}],extraParens:["[]"],identChars:{rest:"$"},lineCommentTypes:["--","//"],operators:["%","::","||","=>",":=","->"],propertyAccessOperators:[":"]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...cT,...Mc],tabularOnelineClauses:Mc}},r$=Object.freeze(Object.defineProperty({__proto__:null,bigquery:IG,clickhouse:wG,db2:VG,db2i:nH,duckdb:EH,hive:IH,mariadb:DH,mysql:HH,n1ql:lW,plsql:RW,postgresql:_W,redshift:kW,singlestoredb:VY,snowflake:n$,spark:KW,sql:SY,sqlite:iY,tidb:QH,transactsql:UY,trino:yY},Symbol.toStringTag,{value:"Module"})),qo=e=>e[e.length-1],Cg=e=>e.sort((t,n)=>n.length-t.length||t.localeCompare(n)),Fi=e=>e.replace(/\s+/gu," "),Pc=e=>/\n/.test(e),Bt=e=>e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),dT=/\s+/uy,Cr=e=>new RegExp(`(?:${e})`,"uy"),o$=e=>e.split("").map(t=>/ /gu.test(t)?"\\s+":`[${t.toUpperCase()}${t.toLowerCase()}]`).join(""),s$=e=>e+"(?:-"+e+")*",i$=({prefixes:e,requirePrefix:t})=>`(?:${e.map(o$).join("|")}${t?"":"|"})`,a$=e=>new RegExp(`(?:${e.map(Bt).join("|")}).*?(?=\r
|
|
773
|
+
|\r|
|
|
774
|
+
|$)`,"uy"),uT=(e,t=[])=>{const n=e==="open"?0:1,r=["()",...t].map(s=>s[n]);return Cr(r.map(Bt).join("|"))},ET=e=>Cr(`${Cg(e).map(Bt).join("|")}`),l$=({rest:e,dashes:t})=>e||t?`(?![${e||""}${t?"-":""}])`:"",dn=(e,t={})=>{if(e.length===0)return/^\b$/u;const n=l$(t),r=Cg(e).map(Bt).join("|").replace(/ /gu,"\\s+");return new RegExp(`(?:${r})${n}\\b`,"iuy")},wc=(e,t)=>{if(!e.length)return;const n=e.map(Bt).join("|");return Cr(`(?:${n})(?:${t})`)},c$=()=>{const e={"<":">","[":"]","(":")","{":"}"},t="{left}(?:(?!{right}').)*?{right}",n=Object.entries(e).map(([a,l])=>t.replace(/{left}/g,Bt(a)).replace(/{right}/g,Bt(l))),r=Bt(Object.keys(e).join(""));return`[Qq]'(?:${String.raw`(?<tag>[^\s${r}])(?:(?!\k<tag>').)*?\k<tag>`}|${n.join("|")})'`},fT={"``":"(?:`[^`]*`)+","[]":String.raw`(?:\[[^\]]*\])(?:\][^\]]*\])*`,'""-qq':String.raw`(?:"[^"]*")+`,'""-bs':String.raw`(?:"[^"\\]*(?:\\.[^"\\]*)*")`,'""-qq-bs':String.raw`(?:"[^"\\]*(?:\\.[^"\\]*)*")+`,'""-raw':String.raw`(?:"[^"]*")`,"''-qq":String.raw`(?:'[^']*')+`,"''-bs":String.raw`(?:'[^'\\]*(?:\\.[^'\\]*)*')`,"''-qq-bs":String.raw`(?:'[^'\\]*(?:\\.[^'\\]*)*')+`,"''-raw":String.raw`(?:'[^']*')`,$$:String.raw`(?<tag>\$\w*\$)[\s\S]*?\k<tag>`,"'''..'''":String.raw`'''[^\\]*?(?:\\.[^\\]*?)*?'''`,'""".."""':String.raw`"""[^\\]*?(?:\\.[^\\]*?)*?"""`,"{}":String.raw`(?:\{[^\}]*\})`,"q''":c$()},Lg=e=>typeof e=="string"?fT[e]:"regex"in e?e.regex:i$(e)+fT[e.quote],d$=e=>Cr(e.map(t=>"regex"in t?t.regex:Lg(t)).join("|")),_g=e=>e.map(Lg).join("|"),pT=e=>Cr(_g(e)),u$=(e={})=>Cr(bg(e)),bg=({first:e,rest:t,dashes:n,allowFirstCharNumber:r}={})=>{const s="\\p{Alphabetic}\\p{Mark}_",i="\\p{Decimal_Number}",a=Bt(e??""),l=Bt(t??""),c=r?`[${s}${i}${a}][${s}${i}${l}]*`:`[${s}${a}][${s}${i}${l}]*`;return n?s$(c):c};function vg(e,t){const n=e.slice(0,t).split(/\n/);return{line:n.length,col:n[n.length-1].length+1}}class E${constructor(t,n){this.rules=t,this.dialectName=n,this.input="",this.index=0}tokenize(t){this.input=t,this.index=0;const n=[];let r;for(;this.index<this.input.length;){const s=this.getWhitespace();if(this.index<this.input.length){if(r=this.getNextToken(),!r)throw this.createParseError();n.push(Object.assign(Object.assign({},r),{precedingWhitespace:s}))}}return n}createParseError(){const t=this.input.slice(this.index,this.index+10),{line:n,col:r}=vg(this.input,this.index);return new Error(`Parse error: Unexpected "${t}" at line ${n} column ${r}.
|
|
775
|
+
${this.dialectInfo()}`)}dialectInfo(){return this.dialectName==="sql"?`This likely happens because you're using the default "sql" dialect.
|
|
776
|
+
If possible, please select a more specific dialect (like sqlite, postgresql, etc).`:`SQL dialect used: "${this.dialectName}".`}getWhitespace(){dT.lastIndex=this.index;const t=dT.exec(this.input);if(t)return this.index+=t[0].length,t[0]}getNextToken(){for(const t of this.rules){const n=this.match(t);if(n)return n}}match(t){t.regex.lastIndex=this.index;const n=t.regex.exec(this.input);if(n){const r=n[0],s={type:t.type,raw:r,text:t.text?t.text(r):r,start:this.index};return t.key&&(s.key=t.key(r)),this.index+=r.length,s}}}const TT=/\/\*/uy,f$=/[\s\S]/uy,p$=/\*\//uy;class T${constructor(){this.lastIndex=0}exec(t){let n="",r,s=0;if(r=this.matchSection(TT,t))n+=r,s++;else return null;for(;s>0;)if(r=this.matchSection(TT,t))n+=r,s++;else if(r=this.matchSection(p$,t))n+=r,s--;else if(r=this.matchSection(f$,t))n+=r;else return null;return[n]}matchSection(t,n){t.lastIndex=this.lastIndex;const r=t.exec(n);return r&&(this.lastIndex+=r[0].length),r?r[0]:null}}class S${constructor(t,n){this.cfg=t,this.dialectName=n,this.rulesBeforeParams=this.buildRulesBeforeParams(t),this.rulesAfterParams=this.buildRulesAfterParams(t)}tokenize(t,n){const r=[...this.rulesBeforeParams,...this.buildParamRules(this.cfg,n),...this.rulesAfterParams],s=new E$(r,this.dialectName).tokenize(t);return this.cfg.postProcess?this.cfg.postProcess(s):s}buildRulesBeforeParams(t){var n,r,s;return this.validRules([{type:J.DISABLE_COMMENT,regex:/(\/\* *sql-formatter-disable *\*\/[\s\S]*?(?:\/\* *sql-formatter-enable *\*\/|$))/uy},{type:J.BLOCK_COMMENT,regex:t.nestedBlockComments?new T$:/(\/\*[^]*?\*\/)/uy},{type:J.LINE_COMMENT,regex:a$((n=t.lineCommentTypes)!==null&&n!==void 0?n:["--"])},{type:J.QUOTED_IDENTIFIER,regex:pT(t.identTypes)},{type:J.NUMBER,regex:t.underscoresInNumbers?/(?:0x[0-9a-fA-F_]+|0b[01_]+|(?:-\s*)?(?:[0-9_]*\.[0-9_]+|[0-9_]+(?:\.[0-9_]*)?)(?:[eE][-+]?[0-9_]+(?:\.[0-9_]+)?)?)(?![\w\p{Alphabetic}])/uy:/(?:0x[0-9a-fA-F]+|0b[01]+|(?:-\s*)?(?:[0-9]*\.[0-9]+|[0-9]+(?:\.[0-9]*)?)(?:[eE][-+]?[0-9]+(?:\.[0-9]+)?)?)(?![\w\p{Alphabetic}])/uy},{type:J.RESERVED_KEYWORD_PHRASE,regex:dn((r=t.reservedKeywordPhrases)!==null&&r!==void 0?r:[],t.identChars),text:We},{type:J.RESERVED_DATA_TYPE_PHRASE,regex:dn((s=t.reservedDataTypePhrases)!==null&&s!==void 0?s:[],t.identChars),text:We},{type:J.CASE,regex:/CASE\b/iuy,text:We},{type:J.END,regex:/END\b/iuy,text:We},{type:J.BETWEEN,regex:/BETWEEN\b/iuy,text:We},{type:J.LIMIT,regex:t.reservedClauses.includes("LIMIT")?/LIMIT\b/iuy:void 0,text:We},{type:J.RESERVED_CLAUSE,regex:dn(t.reservedClauses,t.identChars),text:We},{type:J.RESERVED_SELECT,regex:dn(t.reservedSelect,t.identChars),text:We},{type:J.RESERVED_SET_OPERATION,regex:dn(t.reservedSetOperations,t.identChars),text:We},{type:J.WHEN,regex:/WHEN\b/iuy,text:We},{type:J.ELSE,regex:/ELSE\b/iuy,text:We},{type:J.THEN,regex:/THEN\b/iuy,text:We},{type:J.RESERVED_JOIN,regex:dn(t.reservedJoins,t.identChars),text:We},{type:J.AND,regex:/AND\b/iuy,text:We},{type:J.OR,regex:/OR\b/iuy,text:We},{type:J.XOR,regex:t.supportsXor?/XOR\b/iuy:void 0,text:We},...t.operatorKeyword?[{type:J.OPERATOR,regex:/OPERATOR *\([^)]+\)/iuy}]:[],{type:J.RESERVED_FUNCTION_NAME,regex:dn(t.reservedFunctionNames,t.identChars),text:We},{type:J.RESERVED_DATA_TYPE,regex:dn(t.reservedDataTypes,t.identChars),text:We},{type:J.RESERVED_KEYWORD,regex:dn(t.reservedKeywords,t.identChars),text:We}])}buildRulesAfterParams(t){var n,r;return this.validRules([{type:J.VARIABLE,regex:t.variableTypes?d$(t.variableTypes):void 0},{type:J.STRING,regex:pT(t.stringTypes)},{type:J.IDENTIFIER,regex:u$(t.identChars)},{type:J.DELIMITER,regex:/[;]/uy},{type:J.COMMA,regex:/[,]/y},{type:J.OPEN_PAREN,regex:uT("open",t.extraParens)},{type:J.CLOSE_PAREN,regex:uT("close",t.extraParens)},{type:J.OPERATOR,regex:ET(["+","-","/",">","<","=","<>","<=",">=","!=",...(n=t.operators)!==null&&n!==void 0?n:[]])},{type:J.ASTERISK,regex:/[*]/uy},{type:J.PROPERTY_ACCESS_OPERATOR,regex:ET([".",...(r=t.propertyAccessOperators)!==null&&r!==void 0?r:[]])}])}buildParamRules(t,n){var r,s,i,a,l;const c={named:(n==null?void 0:n.named)||((r=t.paramTypes)===null||r===void 0?void 0:r.named)||[],quoted:(n==null?void 0:n.quoted)||((s=t.paramTypes)===null||s===void 0?void 0:s.quoted)||[],numbered:(n==null?void 0:n.numbered)||((i=t.paramTypes)===null||i===void 0?void 0:i.numbered)||[],positional:typeof(n==null?void 0:n.positional)=="boolean"?n.positional:(a=t.paramTypes)===null||a===void 0?void 0:a.positional,custom:(n==null?void 0:n.custom)||((l=t.paramTypes)===null||l===void 0?void 0:l.custom)||[]};return this.validRules([{type:J.NAMED_PARAMETER,regex:wc(c.named,bg(t.paramChars||t.identChars)),key:d=>d.slice(1)},{type:J.QUOTED_PARAMETER,regex:wc(c.quoted,_g(t.identTypes)),key:d=>(({tokenKey:u,quoteChar:E})=>u.replace(new RegExp(Bt("\\"+E),"gu"),E))({tokenKey:d.slice(2,-1),quoteChar:d.slice(-1)})},{type:J.NUMBERED_PARAMETER,regex:wc(c.numbered,"[0-9]+"),key:d=>d.slice(1)},{type:J.POSITIONAL_PARAMETER,regex:c.positional?/[?]/y:void 0},...c.custom.map(d=>{var u;return{type:J.CUSTOM_PARAMETER,regex:Cr(d.regex),key:(u=d.key)!==null&&u!==void 0?u:(E=>E)}})])}validRules(t){return t.filter(n=>!!n.regex)}}const We=e=>Fi(e.toUpperCase()),ST=new Map,h$=e=>{let t=ST.get(e);return t||(t=R$(e),ST.set(e,t)),t},R$=e=>({tokenizer:new S$(e.tokenizerOptions,e.name),formatOptions:A$(e.formatOptions)}),A$=e=>{var t;return{alwaysDenseOperators:e.alwaysDenseOperators||[],onelineClauses:Object.fromEntries(e.onelineClauses.map(n=>[n,!0])),tabularOnelineClauses:Object.fromEntries(((t=e.tabularOnelineClauses)!==null&&t!==void 0?t:e.onelineClauses).map(n=>[n,!0]))}};function m$(e){return e.indentStyle==="tabularLeft"||e.indentStyle==="tabularRight"?" ".repeat(10):e.useTabs?" ":" ".repeat(e.tabWidth)}function $r(e){return e.indentStyle==="tabularLeft"||e.indentStyle==="tabularRight"}class g${constructor(t){this.params=t,this.index=0}get({key:t,text:n}){return this.params?t?this.params[t]:this.params[this.index++]:n}getPositionalParameterIndex(){return this.index}setPositionalParameterIndex(t){this.index=t}}var Gi={exports:{}},I$=Gi.exports,hT;function O$(){return hT||(hT=1,(function(e){(function(t,n){e.exports?e.exports=n():t.nearley=n()})(I$,function(){function t(d,u,E){return this.id=++t.highestId,this.name=d,this.symbols=u,this.postprocess=E,this}t.highestId=0,t.prototype.toString=function(d){var u=typeof d>"u"?this.symbols.map(c).join(" "):this.symbols.slice(0,d).map(c).join(" ")+" ● "+this.symbols.slice(d).map(c).join(" ");return this.name+" → "+u};function n(d,u,E,f){this.rule=d,this.dot=u,this.reference=E,this.data=[],this.wantedBy=f,this.isComplete=this.dot===d.symbols.length}n.prototype.toString=function(){return"{"+this.rule.toString(this.dot)+"}, from: "+(this.reference||0)},n.prototype.nextState=function(d){var u=new n(this.rule,this.dot+1,this.reference,this.wantedBy);return u.left=this,u.right=d,u.isComplete&&(u.data=u.build(),u.right=void 0),u},n.prototype.build=function(){var d=[],u=this;do d.push(u.right.data),u=u.left;while(u.left);return d.reverse(),d},n.prototype.finish=function(){this.rule.postprocess&&(this.data=this.rule.postprocess(this.data,this.reference,a.fail))};function r(d,u){this.grammar=d,this.index=u,this.states=[],this.wants={},this.scannable=[],this.completed={}}r.prototype.process=function(d){for(var u=this.states,E=this.wants,f=this.completed,T=0;T<u.length;T++){var A=u[T];if(A.isComplete){if(A.finish(),A.data!==a.fail){for(var R=A.wantedBy,S=R.length;S--;){var h=R[S];this.complete(h,A)}if(A.reference===this.index){var g=A.rule.name;(this.completed[g]=this.completed[g]||[]).push(A)}}}else{var g=A.rule.symbols[A.dot];if(typeof g!="string"){this.scannable.push(A);continue}if(E[g]){if(E[g].push(A),f.hasOwnProperty(g))for(var m=f[g],S=0;S<m.length;S++){var I=m[S];this.complete(A,I)}}else E[g]=[A],this.predict(g)}}},r.prototype.predict=function(d){for(var u=this.grammar.byName[d]||[],E=0;E<u.length;E++){var f=u[E],T=this.wants[d],A=new n(f,0,this.index,T);this.states.push(A)}},r.prototype.complete=function(d,u){var E=d.nextState(u);this.states.push(E)};function s(d,u){this.rules=d,this.start=u||this.rules[0].name;var E=this.byName={};this.rules.forEach(function(f){E.hasOwnProperty(f.name)||(E[f.name]=[]),E[f.name].push(f)})}s.fromCompiled=function(f,u){var E=f.Lexer;f.ParserStart&&(u=f.ParserStart,f=f.ParserRules);var f=f.map(function(A){return new t(A.name,A.symbols,A.postprocess)}),T=new s(f,u);return T.lexer=E,T};function i(){this.reset("")}i.prototype.reset=function(d,u){this.buffer=d,this.index=0,this.line=u?u.line:1,this.lastLineBreak=u?-u.col:0},i.prototype.next=function(){if(this.index<this.buffer.length){var d=this.buffer[this.index++];return d===`
|
|
777
|
+
`&&(this.line+=1,this.lastLineBreak=this.index),{value:d}}},i.prototype.save=function(){return{line:this.line,col:this.index-this.lastLineBreak}},i.prototype.formatError=function(d,u){var E=this.buffer;if(typeof E=="string"){var f=E.split(`
|
|
778
|
+
`).slice(Math.max(0,this.line-5),this.line),T=E.indexOf(`
|
|
779
|
+
`,this.index);T===-1&&(T=E.length);var A=this.index-this.lastLineBreak,R=String(this.line).length;return u+=" at line "+this.line+" col "+A+`:
|
|
780
|
+
|
|
781
|
+
`,u+=f.map(function(h,g){return S(this.line-f.length+g+1,R)+" "+h},this).join(`
|
|
782
|
+
`),u+=`
|
|
783
|
+
`+S("",R+A)+`^
|
|
784
|
+
`,u}else return u+" at index "+(this.index-1);function S(h,g){var m=String(h);return Array(g-m.length+1).join(" ")+m}};function a(d,u,E){if(d instanceof s)var f=d,E=u;else var f=s.fromCompiled(d,u);this.grammar=f,this.options={keepHistory:!1,lexer:f.lexer||new i};for(var T in E||{})this.options[T]=E[T];this.lexer=this.options.lexer,this.lexerState=void 0;var A=new r(f,0);this.table=[A],A.wants[f.start]=[],A.predict(f.start),A.process(),this.current=0}a.fail={},a.prototype.feed=function(d){var u=this.lexer;u.reset(d,this.lexerState);for(var E;;){try{if(E=u.next(),!E)break}catch(x){var R=new r(this.grammar,this.current+1);this.table.push(R);var f=new Error(this.reportLexerError(x));throw f.offset=this.current,f.token=x.token,f}var T=this.table[this.current];this.options.keepHistory||delete this.table[this.current-1];var A=this.current+1,R=new r(this.grammar,A);this.table.push(R);for(var S=E.text!==void 0?E.text:E.value,h=u.constructor===i?E.value:E,g=T.scannable,m=g.length;m--;){var I=g[m],O=I.rule.symbols[I.dot];if(O.test?O.test(h):O.type?O.type===E.type:O.literal===S){var N=I.nextState({data:h,token:E,isToken:!0,reference:A-1});R.states.push(N)}}if(R.process(),R.states.length===0){var f=new Error(this.reportError(E));throw f.offset=this.current,f.token=E,f}this.options.keepHistory&&(T.lexerState=u.save()),this.current++}return T&&(this.lexerState=u.save()),this.results=this.finish(),this},a.prototype.reportLexerError=function(d){var u,E,f=d.token;return f?(u="input "+JSON.stringify(f.text[0])+" (lexer error)",E=this.lexer.formatError(f,"Syntax error")):(u="input (lexer error)",E=d.message),this.reportErrorCommon(E,u)},a.prototype.reportError=function(d){var u=(d.type?d.type+" token: ":"")+JSON.stringify(d.value!==void 0?d.value:d),E=this.lexer.formatError(d,"Syntax error");return this.reportErrorCommon(E,u)},a.prototype.reportErrorCommon=function(d,u){var E=[];E.push(d);var f=this.table.length-2,T=this.table[f],A=T.states.filter(function(S){var h=S.rule.symbols[S.dot];return h&&typeof h!="string"});if(A.length===0)E.push("Unexpected "+u+`. I did not expect any more input. Here is the state of my parse table:
|
|
785
|
+
`),this.displayStateStack(T.states,E);else{E.push("Unexpected "+u+`. Instead, I was expecting to see one of the following:
|
|
786
|
+
`);var R=A.map(function(S){return this.buildFirstStateStack(S,[])||[S]},this);R.forEach(function(S){var h=S[0],g=h.rule.symbols[h.dot],m=this.getSymbolDisplay(g);E.push("A "+m+" based on:"),this.displayStateStack(S,E)},this)}return E.push(""),E.join(`
|
|
787
|
+
`)},a.prototype.displayStateStack=function(d,u){for(var E,f=0,T=0;T<d.length;T++){var A=d[T],R=A.rule.toString(A.dot);R===E?f++:(f>0&&u.push(" ^ "+f+" more lines identical to this"),f=0,u.push(" "+R)),E=R}},a.prototype.getSymbolDisplay=function(d){return l(d)},a.prototype.buildFirstStateStack=function(d,u){if(u.indexOf(d)!==-1)return null;if(d.wantedBy.length===0)return[d];var E=d.wantedBy[0],f=[d].concat(u),T=this.buildFirstStateStack(E,f);return T===null?null:[d].concat(T)},a.prototype.save=function(){var d=this.table[this.current];return d.lexerState=this.lexerState,d},a.prototype.restore=function(d){var u=d.index;this.current=u,this.table[u]=d,this.table.splice(u+1),this.lexerState=d.lexerState,this.results=this.finish()},a.prototype.rewind=function(d){if(!this.options.keepHistory)throw new Error("set option `keepHistory` to enable rewinding");this.restore(this.table[d])},a.prototype.finish=function(){var d=[],u=this.grammar.start,E=this.table[this.table.length-1];return E.states.forEach(function(f){f.rule.name===u&&f.dot===f.rule.symbols.length&&f.reference===0&&f.data!==a.fail&&d.push(f)}),d.map(function(f){return f.data})};function l(d){var u=typeof d;if(u==="string")return d;if(u==="object"){if(d.literal)return JSON.stringify(d.literal);if(d instanceof RegExp)return"character matching "+d;if(d.type)return d.type+" token";if(d.test)return"token matching "+String(d.test);throw new Error("Unknown symbol type: "+d)}}function c(d){var u=typeof d;if(u==="string")return d;if(u==="object"){if(d.literal)return JSON.stringify(d.literal);if(d instanceof RegExp)return d.toString();if(d.type)return"%"+d.type;if(d.test)return"<"+String(d.test)+">";throw new Error("Unknown symbol type: "+d)}}return{Parser:a,Grammar:s,Rule:t}})})(Gi)),Gi.exports}var N$=O$();const x$=Oa(N$);function y$(e){return e.map(C$).map(L$).map(_$).map(b$).map(v$)}const C$=(e,t,n)=>{if(yg(e.type)){const r=D$(n,t);if(r&&r.type===J.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:J.IDENTIFIER,text:e.raw});const s=yo(n,t);if(s&&s.type===J.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:J.IDENTIFIER,text:e.raw})}return e},L$=(e,t,n)=>{if(e.type===J.RESERVED_FUNCTION_NAME){const r=yo(n,t);if(!r||!Dg(r))return Object.assign(Object.assign({},e),{type:J.IDENTIFIER,text:e.raw})}return e},_$=(e,t,n)=>{if(e.type===J.RESERVED_DATA_TYPE){const r=yo(n,t);if(r&&Dg(r))return Object.assign(Object.assign({},e),{type:J.RESERVED_PARAMETERIZED_DATA_TYPE})}return e},b$=(e,t,n)=>{if(e.type===J.IDENTIFIER){const r=yo(n,t);if(r&&Mg(r))return Object.assign(Object.assign({},e),{type:J.ARRAY_IDENTIFIER})}return e},v$=(e,t,n)=>{if(e.type===J.RESERVED_DATA_TYPE){const r=yo(n,t);if(r&&Mg(r))return Object.assign(Object.assign({},e),{type:J.ARRAY_KEYWORD})}return e},D$=(e,t)=>yo(e,t,-1),yo=(e,t,n=1)=>{let r=1;for(;e[t+r*n]&&M$(e[t+r*n]);)r++;return e[t+r*n]},Dg=e=>e.type===J.OPEN_PAREN&&e.text==="(",Mg=e=>e.type===J.OPEN_PAREN&&e.text==="[",M$=e=>e.type===J.BLOCK_COMMENT||e.type===J.LINE_COMMENT;class Pg{constructor(t){this.tokenize=t,this.index=0,this.tokens=[],this.input=""}reset(t,n){this.input=t,this.index=0,this.tokens=this.tokenize(t)}next(){return this.tokens[this.index++]}save(){}formatError(t){const{line:n,col:r}=vg(this.input,t.start);return`Parse error at token: ${t.text} at line ${n} column ${r}`}has(t){return t in J}}var fe;(function(e){e.statement="statement",e.clause="clause",e.set_operation="set_operation",e.function_call="function_call",e.parameterized_data_type="parameterized_data_type",e.array_subscript="array_subscript",e.property_access="property_access",e.parenthesis="parenthesis",e.between_predicate="between_predicate",e.case_expression="case_expression",e.case_when="case_when",e.case_else="case_else",e.limit_clause="limit_clause",e.all_columns_asterisk="all_columns_asterisk",e.literal="literal",e.identifier="identifier",e.keyword="keyword",e.data_type="data_type",e.parameter="parameter",e.operator="operator",e.comma="comma",e.line_comment="line_comment",e.block_comment="block_comment",e.disable_comment="disable_comment"})(fe=fe||(fe={}));function Uc(e){return e[0]}const Se=new Pg(e=>[]),rr=([[e]])=>e,$e=e=>({type:fe.keyword,tokenType:e.type,text:e.text,raw:e.raw}),RT=e=>({type:fe.data_type,text:e.text,raw:e.raw}),Ve=(e,{leading:t,trailing:n})=>(t!=null&&t.length&&(e=Object.assign(Object.assign({},e),{leadingComments:t})),n!=null&&n.length&&(e=Object.assign(Object.assign({},e),{trailingComments:n})),e),P$=(e,{leading:t,trailing:n})=>{if(t!=null&&t.length){const[r,...s]=e;e=[Ve(r,{leading:t}),...s]}if(n!=null&&n.length){const r=e.slice(0,-1),s=e[e.length-1];e=[...r,Ve(s,{trailing:n})]}return e},w$={Lexer:Se,ParserRules:[{name:"main$ebnf$1",symbols:[]},{name:"main$ebnf$1",symbols:["main$ebnf$1","statement"],postprocess:e=>e[0].concat([e[1]])},{name:"main",symbols:["main$ebnf$1"],postprocess:([e])=>{const t=e[e.length-1];return t&&!t.hasSemicolon?t.children.length>0?e:e.slice(0,-1):e}},{name:"statement$subexpression$1",symbols:[Se.has("DELIMITER")?{type:"DELIMITER"}:DELIMITER]},{name:"statement$subexpression$1",symbols:[Se.has("EOF")?{type:"EOF"}:EOF]},{name:"statement",symbols:["expressions_or_clauses","statement$subexpression$1"],postprocess:([e,[t]])=>({type:fe.statement,children:e,hasSemicolon:t.type===J.DELIMITER})},{name:"expressions_or_clauses$ebnf$1",symbols:[]},{name:"expressions_or_clauses$ebnf$1",symbols:["expressions_or_clauses$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"expressions_or_clauses$ebnf$2",symbols:[]},{name:"expressions_or_clauses$ebnf$2",symbols:["expressions_or_clauses$ebnf$2","clause"],postprocess:e=>e[0].concat([e[1]])},{name:"expressions_or_clauses",symbols:["expressions_or_clauses$ebnf$1","expressions_or_clauses$ebnf$2"],postprocess:([e,t])=>[...e,...t]},{name:"clause$subexpression$1",symbols:["limit_clause"]},{name:"clause$subexpression$1",symbols:["select_clause"]},{name:"clause$subexpression$1",symbols:["other_clause"]},{name:"clause$subexpression$1",symbols:["set_operation"]},{name:"clause",symbols:["clause$subexpression$1"],postprocess:rr},{name:"limit_clause$ebnf$1$subexpression$1$ebnf$1",symbols:["free_form_sql"]},{name:"limit_clause$ebnf$1$subexpression$1$ebnf$1",symbols:["limit_clause$ebnf$1$subexpression$1$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"limit_clause$ebnf$1$subexpression$1",symbols:[Se.has("COMMA")?{type:"COMMA"}:COMMA,"limit_clause$ebnf$1$subexpression$1$ebnf$1"]},{name:"limit_clause$ebnf$1",symbols:["limit_clause$ebnf$1$subexpression$1"],postprocess:Uc},{name:"limit_clause$ebnf$1",symbols:[],postprocess:()=>null},{name:"limit_clause",symbols:[Se.has("LIMIT")?{type:"LIMIT"}:LIMIT,"_","expression_chain_","limit_clause$ebnf$1"],postprocess:([e,t,n,r])=>{if(r){const[s,i]=r;return{type:fe.limit_clause,limitKw:Ve($e(e),{trailing:t}),offset:n,count:i}}else return{type:fe.limit_clause,limitKw:Ve($e(e),{trailing:t}),count:n}}},{name:"select_clause$subexpression$1$ebnf$1",symbols:[]},{name:"select_clause$subexpression$1$ebnf$1",symbols:["select_clause$subexpression$1$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"select_clause$subexpression$1",symbols:["all_columns_asterisk","select_clause$subexpression$1$ebnf$1"]},{name:"select_clause$subexpression$1$ebnf$2",symbols:[]},{name:"select_clause$subexpression$1$ebnf$2",symbols:["select_clause$subexpression$1$ebnf$2","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"select_clause$subexpression$1",symbols:["asteriskless_free_form_sql","select_clause$subexpression$1$ebnf$2"]},{name:"select_clause",symbols:[Se.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT,"select_clause$subexpression$1"],postprocess:([e,[t,n]])=>({type:fe.clause,nameKw:$e(e),children:[t,...n]})},{name:"select_clause",symbols:[Se.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT],postprocess:([e])=>({type:fe.clause,nameKw:$e(e),children:[]})},{name:"all_columns_asterisk",symbols:[Se.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK],postprocess:()=>({type:fe.all_columns_asterisk})},{name:"other_clause$ebnf$1",symbols:[]},{name:"other_clause$ebnf$1",symbols:["other_clause$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"other_clause",symbols:[Se.has("RESERVED_CLAUSE")?{type:"RESERVED_CLAUSE"}:RESERVED_CLAUSE,"other_clause$ebnf$1"],postprocess:([e,t])=>({type:fe.clause,nameKw:$e(e),children:t})},{name:"set_operation$ebnf$1",symbols:[]},{name:"set_operation$ebnf$1",symbols:["set_operation$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"set_operation",symbols:[Se.has("RESERVED_SET_OPERATION")?{type:"RESERVED_SET_OPERATION"}:RESERVED_SET_OPERATION,"set_operation$ebnf$1"],postprocess:([e,t])=>({type:fe.set_operation,nameKw:$e(e),children:t})},{name:"expression_chain_$ebnf$1",symbols:["expression_with_comments_"]},{name:"expression_chain_$ebnf$1",symbols:["expression_chain_$ebnf$1","expression_with_comments_"],postprocess:e=>e[0].concat([e[1]])},{name:"expression_chain_",symbols:["expression_chain_$ebnf$1"],postprocess:Uc},{name:"expression_chain$ebnf$1",symbols:[]},{name:"expression_chain$ebnf$1",symbols:["expression_chain$ebnf$1","_expression_with_comments"],postprocess:e=>e[0].concat([e[1]])},{name:"expression_chain",symbols:["expression","expression_chain$ebnf$1"],postprocess:([e,t])=>[e,...t]},{name:"andless_expression_chain$ebnf$1",symbols:[]},{name:"andless_expression_chain$ebnf$1",symbols:["andless_expression_chain$ebnf$1","_andless_expression_with_comments"],postprocess:e=>e[0].concat([e[1]])},{name:"andless_expression_chain",symbols:["andless_expression","andless_expression_chain$ebnf$1"],postprocess:([e,t])=>[e,...t]},{name:"expression_with_comments_",symbols:["expression","_"],postprocess:([e,t])=>Ve(e,{trailing:t})},{name:"_expression_with_comments",symbols:["_","expression"],postprocess:([e,t])=>Ve(t,{leading:e})},{name:"_andless_expression_with_comments",symbols:["_","andless_expression"],postprocess:([e,t])=>Ve(t,{leading:e})},{name:"free_form_sql$subexpression$1",symbols:["asteriskless_free_form_sql"]},{name:"free_form_sql$subexpression$1",symbols:["asterisk"]},{name:"free_form_sql",symbols:["free_form_sql$subexpression$1"],postprocess:rr},{name:"asteriskless_free_form_sql$subexpression$1",symbols:["asteriskless_andless_expression"]},{name:"asteriskless_free_form_sql$subexpression$1",symbols:["logic_operator"]},{name:"asteriskless_free_form_sql$subexpression$1",symbols:["comma"]},{name:"asteriskless_free_form_sql$subexpression$1",symbols:["comment"]},{name:"asteriskless_free_form_sql$subexpression$1",symbols:["other_keyword"]},{name:"asteriskless_free_form_sql",symbols:["asteriskless_free_form_sql$subexpression$1"],postprocess:rr},{name:"expression$subexpression$1",symbols:["andless_expression"]},{name:"expression$subexpression$1",symbols:["logic_operator"]},{name:"expression",symbols:["expression$subexpression$1"],postprocess:rr},{name:"andless_expression$subexpression$1",symbols:["asteriskless_andless_expression"]},{name:"andless_expression$subexpression$1",symbols:["asterisk"]},{name:"andless_expression",symbols:["andless_expression$subexpression$1"],postprocess:rr},{name:"asteriskless_andless_expression$subexpression$1",symbols:["atomic_expression"]},{name:"asteriskless_andless_expression$subexpression$1",symbols:["between_predicate"]},{name:"asteriskless_andless_expression$subexpression$1",symbols:["case_expression"]},{name:"asteriskless_andless_expression",symbols:["asteriskless_andless_expression$subexpression$1"],postprocess:rr},{name:"atomic_expression$subexpression$1",symbols:["array_subscript"]},{name:"atomic_expression$subexpression$1",symbols:["function_call"]},{name:"atomic_expression$subexpression$1",symbols:["property_access"]},{name:"atomic_expression$subexpression$1",symbols:["parenthesis"]},{name:"atomic_expression$subexpression$1",symbols:["curly_braces"]},{name:"atomic_expression$subexpression$1",symbols:["square_brackets"]},{name:"atomic_expression$subexpression$1",symbols:["operator"]},{name:"atomic_expression$subexpression$1",symbols:["identifier"]},{name:"atomic_expression$subexpression$1",symbols:["parameter"]},{name:"atomic_expression$subexpression$1",symbols:["literal"]},{name:"atomic_expression$subexpression$1",symbols:["data_type"]},{name:"atomic_expression$subexpression$1",symbols:["keyword"]},{name:"atomic_expression",symbols:["atomic_expression$subexpression$1"],postprocess:rr},{name:"array_subscript",symbols:[Se.has("ARRAY_IDENTIFIER")?{type:"ARRAY_IDENTIFIER"}:ARRAY_IDENTIFIER,"_","square_brackets"],postprocess:([e,t,n])=>({type:fe.array_subscript,array:Ve({type:fe.identifier,quoted:!1,text:e.text},{trailing:t}),parenthesis:n})},{name:"array_subscript",symbols:[Se.has("ARRAY_KEYWORD")?{type:"ARRAY_KEYWORD"}:ARRAY_KEYWORD,"_","square_brackets"],postprocess:([e,t,n])=>({type:fe.array_subscript,array:Ve($e(e),{trailing:t}),parenthesis:n})},{name:"function_call",symbols:[Se.has("RESERVED_FUNCTION_NAME")?{type:"RESERVED_FUNCTION_NAME"}:RESERVED_FUNCTION_NAME,"_","parenthesis"],postprocess:([e,t,n])=>({type:fe.function_call,nameKw:Ve($e(e),{trailing:t}),parenthesis:n})},{name:"parenthesis",symbols:[{literal:"("},"expressions_or_clauses",{literal:")"}],postprocess:([e,t,n])=>({type:fe.parenthesis,children:t,openParen:"(",closeParen:")"})},{name:"curly_braces$ebnf$1",symbols:[]},{name:"curly_braces$ebnf$1",symbols:["curly_braces$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"curly_braces",symbols:[{literal:"{"},"curly_braces$ebnf$1",{literal:"}"}],postprocess:([e,t,n])=>({type:fe.parenthesis,children:t,openParen:"{",closeParen:"}"})},{name:"square_brackets$ebnf$1",symbols:[]},{name:"square_brackets$ebnf$1",symbols:["square_brackets$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"square_brackets",symbols:[{literal:"["},"square_brackets$ebnf$1",{literal:"]"}],postprocess:([e,t,n])=>({type:fe.parenthesis,children:t,openParen:"[",closeParen:"]"})},{name:"property_access$subexpression$1",symbols:["identifier"]},{name:"property_access$subexpression$1",symbols:["array_subscript"]},{name:"property_access$subexpression$1",symbols:["all_columns_asterisk"]},{name:"property_access$subexpression$1",symbols:["parameter"]},{name:"property_access",symbols:["atomic_expression","_",Se.has("PROPERTY_ACCESS_OPERATOR")?{type:"PROPERTY_ACCESS_OPERATOR"}:PROPERTY_ACCESS_OPERATOR,"_","property_access$subexpression$1"],postprocess:([e,t,n,r,[s]])=>({type:fe.property_access,object:Ve(e,{trailing:t}),operator:n.text,property:Ve(s,{leading:r})})},{name:"between_predicate",symbols:[Se.has("BETWEEN")?{type:"BETWEEN"}:BETWEEN,"_","andless_expression_chain","_",Se.has("AND")?{type:"AND"}:AND,"_","andless_expression"],postprocess:([e,t,n,r,s,i,a])=>({type:fe.between_predicate,betweenKw:$e(e),expr1:P$(n,{leading:t,trailing:r}),andKw:$e(s),expr2:[Ve(a,{leading:i})]})},{name:"case_expression$ebnf$1",symbols:["expression_chain_"],postprocess:Uc},{name:"case_expression$ebnf$1",symbols:[],postprocess:()=>null},{name:"case_expression$ebnf$2",symbols:[]},{name:"case_expression$ebnf$2",symbols:["case_expression$ebnf$2","case_clause"],postprocess:e=>e[0].concat([e[1]])},{name:"case_expression",symbols:[Se.has("CASE")?{type:"CASE"}:CASE,"_","case_expression$ebnf$1","case_expression$ebnf$2",Se.has("END")?{type:"END"}:END],postprocess:([e,t,n,r,s])=>({type:fe.case_expression,caseKw:Ve($e(e),{trailing:t}),endKw:$e(s),expr:n||[],clauses:r})},{name:"case_clause",symbols:[Se.has("WHEN")?{type:"WHEN"}:WHEN,"_","expression_chain_",Se.has("THEN")?{type:"THEN"}:THEN,"_","expression_chain_"],postprocess:([e,t,n,r,s,i])=>({type:fe.case_when,whenKw:Ve($e(e),{trailing:t}),thenKw:Ve($e(r),{trailing:s}),condition:n,result:i})},{name:"case_clause",symbols:[Se.has("ELSE")?{type:"ELSE"}:ELSE,"_","expression_chain_"],postprocess:([e,t,n])=>({type:fe.case_else,elseKw:Ve($e(e),{trailing:t}),result:n})},{name:"comma$subexpression$1",symbols:[Se.has("COMMA")?{type:"COMMA"}:COMMA]},{name:"comma",symbols:["comma$subexpression$1"],postprocess:([[e]])=>({type:fe.comma})},{name:"asterisk$subexpression$1",symbols:[Se.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK]},{name:"asterisk",symbols:["asterisk$subexpression$1"],postprocess:([[e]])=>({type:fe.operator,text:e.text})},{name:"operator$subexpression$1",symbols:[Se.has("OPERATOR")?{type:"OPERATOR"}:OPERATOR]},{name:"operator",symbols:["operator$subexpression$1"],postprocess:([[e]])=>({type:fe.operator,text:e.text})},{name:"identifier$subexpression$1",symbols:[Se.has("IDENTIFIER")?{type:"IDENTIFIER"}:IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[Se.has("QUOTED_IDENTIFIER")?{type:"QUOTED_IDENTIFIER"}:QUOTED_IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[Se.has("VARIABLE")?{type:"VARIABLE"}:VARIABLE]},{name:"identifier",symbols:["identifier$subexpression$1"],postprocess:([[e]])=>({type:fe.identifier,quoted:e.type!=="IDENTIFIER",text:e.text})},{name:"parameter$subexpression$1",symbols:[Se.has("NAMED_PARAMETER")?{type:"NAMED_PARAMETER"}:NAMED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[Se.has("QUOTED_PARAMETER")?{type:"QUOTED_PARAMETER"}:QUOTED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[Se.has("NUMBERED_PARAMETER")?{type:"NUMBERED_PARAMETER"}:NUMBERED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[Se.has("POSITIONAL_PARAMETER")?{type:"POSITIONAL_PARAMETER"}:POSITIONAL_PARAMETER]},{name:"parameter$subexpression$1",symbols:[Se.has("CUSTOM_PARAMETER")?{type:"CUSTOM_PARAMETER"}:CUSTOM_PARAMETER]},{name:"parameter",symbols:["parameter$subexpression$1"],postprocess:([[e]])=>({type:fe.parameter,key:e.key,text:e.text})},{name:"literal$subexpression$1",symbols:[Se.has("NUMBER")?{type:"NUMBER"}:NUMBER]},{name:"literal$subexpression$1",symbols:[Se.has("STRING")?{type:"STRING"}:STRING]},{name:"literal",symbols:["literal$subexpression$1"],postprocess:([[e]])=>({type:fe.literal,text:e.text})},{name:"keyword$subexpression$1",symbols:[Se.has("RESERVED_KEYWORD")?{type:"RESERVED_KEYWORD"}:RESERVED_KEYWORD]},{name:"keyword$subexpression$1",symbols:[Se.has("RESERVED_KEYWORD_PHRASE")?{type:"RESERVED_KEYWORD_PHRASE"}:RESERVED_KEYWORD_PHRASE]},{name:"keyword$subexpression$1",symbols:[Se.has("RESERVED_JOIN")?{type:"RESERVED_JOIN"}:RESERVED_JOIN]},{name:"keyword",symbols:["keyword$subexpression$1"],postprocess:([[e]])=>$e(e)},{name:"data_type$subexpression$1",symbols:[Se.has("RESERVED_DATA_TYPE")?{type:"RESERVED_DATA_TYPE"}:RESERVED_DATA_TYPE]},{name:"data_type$subexpression$1",symbols:[Se.has("RESERVED_DATA_TYPE_PHRASE")?{type:"RESERVED_DATA_TYPE_PHRASE"}:RESERVED_DATA_TYPE_PHRASE]},{name:"data_type",symbols:["data_type$subexpression$1"],postprocess:([[e]])=>RT(e)},{name:"data_type",symbols:[Se.has("RESERVED_PARAMETERIZED_DATA_TYPE")?{type:"RESERVED_PARAMETERIZED_DATA_TYPE"}:RESERVED_PARAMETERIZED_DATA_TYPE,"_","parenthesis"],postprocess:([e,t,n])=>({type:fe.parameterized_data_type,dataType:Ve(RT(e),{trailing:t}),parenthesis:n})},{name:"logic_operator$subexpression$1",symbols:[Se.has("AND")?{type:"AND"}:AND]},{name:"logic_operator$subexpression$1",symbols:[Se.has("OR")?{type:"OR"}:OR]},{name:"logic_operator$subexpression$1",symbols:[Se.has("XOR")?{type:"XOR"}:XOR]},{name:"logic_operator",symbols:["logic_operator$subexpression$1"],postprocess:([[e]])=>$e(e)},{name:"other_keyword$subexpression$1",symbols:[Se.has("WHEN")?{type:"WHEN"}:WHEN]},{name:"other_keyword$subexpression$1",symbols:[Se.has("THEN")?{type:"THEN"}:THEN]},{name:"other_keyword$subexpression$1",symbols:[Se.has("ELSE")?{type:"ELSE"}:ELSE]},{name:"other_keyword$subexpression$1",symbols:[Se.has("END")?{type:"END"}:END]},{name:"other_keyword",symbols:["other_keyword$subexpression$1"],postprocess:([[e]])=>$e(e)},{name:"_$ebnf$1",symbols:[]},{name:"_$ebnf$1",symbols:["_$ebnf$1","comment"],postprocess:e=>e[0].concat([e[1]])},{name:"_",symbols:["_$ebnf$1"],postprocess:([e])=>e},{name:"comment",symbols:[Se.has("LINE_COMMENT")?{type:"LINE_COMMENT"}:LINE_COMMENT],postprocess:([e])=>({type:fe.line_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[Se.has("BLOCK_COMMENT")?{type:"BLOCK_COMMENT"}:BLOCK_COMMENT],postprocess:([e])=>({type:fe.block_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[Se.has("DISABLE_COMMENT")?{type:"DISABLE_COMMENT"}:DISABLE_COMMENT],postprocess:([e])=>({type:fe.disable_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})}],ParserStart:"main"},{Parser:U$,Grammar:B$}=x$;function j$(e){let t={};const n=new Pg(s=>[...y$(e.tokenize(s,t)),xg(s.length)]),r=new U$(B$.fromCompiled(w$),{lexer:n});return{parse:(s,i)=>{t=i;const{results:a}=r.feed(s);if(a.length===1)return a[0];throw a.length===0?new Error("Parse error: Invalid SQL"):new Error(`Parse error: Ambiguous grammar
|
|
788
|
+
${JSON.stringify(a,void 0,2)}`)}}}var q;(function(e){e[e.SPACE=0]="SPACE",e[e.NO_SPACE=1]="NO_SPACE",e[e.NO_NEWLINE=2]="NO_NEWLINE",e[e.NEWLINE=3]="NEWLINE",e[e.MANDATORY_NEWLINE=4]="MANDATORY_NEWLINE",e[e.INDENT=5]="INDENT",e[e.SINGLE_INDENT=6]="SINGLE_INDENT"})(q=q||(q={}));class wg{constructor(t){this.indentation=t,this.items=[]}add(...t){for(const n of t)switch(n){case q.SPACE:this.items.push(q.SPACE);break;case q.NO_SPACE:this.trimHorizontalWhitespace();break;case q.NO_NEWLINE:this.trimWhitespace();break;case q.NEWLINE:this.trimHorizontalWhitespace(),this.addNewline(q.NEWLINE);break;case q.MANDATORY_NEWLINE:this.trimHorizontalWhitespace(),this.addNewline(q.MANDATORY_NEWLINE);break;case q.INDENT:this.addIndentation();break;case q.SINGLE_INDENT:this.items.push(q.SINGLE_INDENT);break;default:this.items.push(n)}}trimHorizontalWhitespace(){for(;k$(qo(this.items));)this.items.pop()}trimWhitespace(){for(;F$(qo(this.items));)this.items.pop()}addNewline(t){if(this.items.length>0)switch(qo(this.items)){case q.NEWLINE:this.items.pop(),this.items.push(t);break;case q.MANDATORY_NEWLINE:break;default:this.items.push(t);break}}addIndentation(){for(let t=0;t<this.indentation.getLevel();t++)this.items.push(q.SINGLE_INDENT)}toString(){return this.items.map(t=>this.itemToString(t)).join("")}getLayoutItems(){return this.items}itemToString(t){switch(t){case q.SPACE:return" ";case q.NEWLINE:case q.MANDATORY_NEWLINE:return`
|
|
789
|
+
`;case q.SINGLE_INDENT:return this.indentation.getSingleIndent();default:return t}}}const k$=e=>e===q.SPACE||e===q.SINGLE_INDENT,F$=e=>e===q.SPACE||e===q.SINGLE_INDENT||e===q.NEWLINE;function AT(e,t){if(t==="standard")return e;let n=[];return e.length>=10&&e.includes(" ")&&([e,...n]=e.split(" ")),t==="tabularLeft"?e=e.padEnd(9," "):e=e.padStart(9," "),e+["",...n].join(" ")}function mT(e){return EG(e)||e===J.RESERVED_CLAUSE||e===J.RESERVED_SELECT||e===J.RESERVED_SET_OPERATION||e===J.RESERVED_JOIN||e===J.LIMIT}const Bc="top-level",G$="block-level";class Ug{constructor(t){this.indent=t,this.indentTypes=[]}getSingleIndent(){return this.indent}getLevel(){return this.indentTypes.length}increaseTopLevel(){this.indentTypes.push(Bc)}increaseBlockLevel(){this.indentTypes.push(G$)}decreaseTopLevel(){this.indentTypes.length>0&&qo(this.indentTypes)===Bc&&this.indentTypes.pop()}decreaseBlockLevel(){for(;this.indentTypes.length>0&&this.indentTypes.pop()===Bc;);}}class H$ extends wg{constructor(t){super(new Ug("")),this.expressionWidth=t,this.length=0,this.trailingSpace=!1}add(...t){if(t.forEach(n=>this.addToLength(n)),this.length>this.expressionWidth)throw new _d;super.add(...t)}addToLength(t){if(typeof t=="string")this.length+=t.length,this.trailingSpace=!1;else{if(t===q.MANDATORY_NEWLINE||t===q.NEWLINE)throw new _d;t===q.INDENT||t===q.SINGLE_INDENT||t===q.SPACE?this.trailingSpace||(this.length++,this.trailingSpace=!0):(t===q.NO_NEWLINE||t===q.NO_SPACE)&&this.trailingSpace&&(this.trailingSpace=!1,this.length--)}}}class _d extends Error{}class Ra{constructor({cfg:t,dialectCfg:n,params:r,layout:s,inline:i=!1}){this.inline=!1,this.nodes=[],this.index=-1,this.cfg=t,this.dialectCfg=n,this.inline=i,this.params=r,this.layout=s}format(t){for(this.nodes=t,this.index=0;this.index<this.nodes.length;this.index++)this.formatNode(this.nodes[this.index]);return this.layout}formatNode(t){this.formatComments(t.leadingComments),this.formatNodeWithoutComments(t),this.formatComments(t.trailingComments)}formatNodeWithoutComments(t){switch(t.type){case fe.function_call:return this.formatFunctionCall(t);case fe.parameterized_data_type:return this.formatParameterizedDataType(t);case fe.array_subscript:return this.formatArraySubscript(t);case fe.property_access:return this.formatPropertyAccess(t);case fe.parenthesis:return this.formatParenthesis(t);case fe.between_predicate:return this.formatBetweenPredicate(t);case fe.case_expression:return this.formatCaseExpression(t);case fe.case_when:return this.formatCaseWhen(t);case fe.case_else:return this.formatCaseElse(t);case fe.clause:return this.formatClause(t);case fe.set_operation:return this.formatSetOperation(t);case fe.limit_clause:return this.formatLimitClause(t);case fe.all_columns_asterisk:return this.formatAllColumnsAsterisk(t);case fe.literal:return this.formatLiteral(t);case fe.identifier:return this.formatIdentifier(t);case fe.parameter:return this.formatParameter(t);case fe.operator:return this.formatOperator(t);case fe.comma:return this.formatComma(t);case fe.line_comment:return this.formatLineComment(t);case fe.block_comment:return this.formatBlockComment(t);case fe.disable_comment:return this.formatBlockComment(t);case fe.data_type:return this.formatDataType(t);case fe.keyword:return this.formatKeywordNode(t)}}formatFunctionCall(t){this.withComments(t.nameKw,()=>{this.layout.add(this.showFunctionKw(t.nameKw))}),this.formatNode(t.parenthesis)}formatParameterizedDataType(t){this.withComments(t.dataType,()=>{this.layout.add(this.showDataType(t.dataType))}),this.formatNode(t.parenthesis)}formatArraySubscript(t){let n;switch(t.array.type){case fe.data_type:n=this.showDataType(t.array);break;case fe.keyword:n=this.showKw(t.array);break;default:n=this.showIdentifier(t.array);break}this.withComments(t.array,()=>{this.layout.add(n)}),this.formatNode(t.parenthesis)}formatPropertyAccess(t){this.formatNode(t.object),this.layout.add(q.NO_SPACE,t.operator),this.formatNode(t.property)}formatParenthesis(t){const n=this.formatInlineExpression(t.children);n?(this.layout.add(t.openParen),this.layout.add(...n.getLayoutItems()),this.layout.add(q.NO_SPACE,t.closeParen,q.SPACE)):(this.layout.add(t.openParen,q.NEWLINE),$r(this.cfg)?(this.layout.add(q.INDENT),this.layout=this.formatSubExpression(t.children)):(this.layout.indentation.increaseBlockLevel(),this.layout.add(q.INDENT),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseBlockLevel()),this.layout.add(q.NEWLINE,q.INDENT,t.closeParen,q.SPACE))}formatBetweenPredicate(t){this.layout.add(this.showKw(t.betweenKw),q.SPACE),this.layout=this.formatSubExpression(t.expr1),this.layout.add(q.NO_SPACE,q.SPACE,this.showNonTabularKw(t.andKw),q.SPACE),this.layout=this.formatSubExpression(t.expr2),this.layout.add(q.SPACE)}formatCaseExpression(t){this.formatNode(t.caseKw),this.layout.indentation.increaseBlockLevel(),this.layout=this.formatSubExpression(t.expr),this.layout=this.formatSubExpression(t.clauses),this.layout.indentation.decreaseBlockLevel(),this.layout.add(q.NEWLINE,q.INDENT),this.formatNode(t.endKw)}formatCaseWhen(t){this.layout.add(q.NEWLINE,q.INDENT),this.formatNode(t.whenKw),this.layout=this.formatSubExpression(t.condition),this.formatNode(t.thenKw),this.layout=this.formatSubExpression(t.result)}formatCaseElse(t){this.layout.add(q.NEWLINE,q.INDENT),this.formatNode(t.elseKw),this.layout=this.formatSubExpression(t.result)}formatClause(t){this.isOnelineClause(t)?this.formatClauseInOnelineStyle(t):$r(this.cfg)?this.formatClauseInTabularStyle(t):this.formatClauseInIndentedStyle(t)}isOnelineClause(t){return $r(this.cfg)?this.dialectCfg.tabularOnelineClauses[t.nameKw.text]:this.dialectCfg.onelineClauses[t.nameKw.text]}formatClauseInIndentedStyle(t){this.layout.add(q.NEWLINE,q.INDENT,this.showKw(t.nameKw),q.NEWLINE),this.layout.indentation.increaseTopLevel(),this.layout.add(q.INDENT),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseTopLevel()}formatClauseInOnelineStyle(t){this.layout.add(q.NEWLINE,q.INDENT,this.showKw(t.nameKw),q.SPACE),this.layout=this.formatSubExpression(t.children)}formatClauseInTabularStyle(t){this.layout.add(q.NEWLINE,q.INDENT,this.showKw(t.nameKw),q.SPACE),this.layout.indentation.increaseTopLevel(),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseTopLevel()}formatSetOperation(t){this.layout.add(q.NEWLINE,q.INDENT,this.showKw(t.nameKw),q.NEWLINE),this.layout.add(q.INDENT),this.layout=this.formatSubExpression(t.children)}formatLimitClause(t){this.withComments(t.limitKw,()=>{this.layout.add(q.NEWLINE,q.INDENT,this.showKw(t.limitKw))}),this.layout.indentation.increaseTopLevel(),$r(this.cfg)?this.layout.add(q.SPACE):this.layout.add(q.NEWLINE,q.INDENT),t.offset?(this.layout=this.formatSubExpression(t.offset),this.layout.add(q.NO_SPACE,",",q.SPACE),this.layout=this.formatSubExpression(t.count)):this.layout=this.formatSubExpression(t.count),this.layout.indentation.decreaseTopLevel()}formatAllColumnsAsterisk(t){this.layout.add("*",q.SPACE)}formatLiteral(t){this.layout.add(t.text,q.SPACE)}formatIdentifier(t){this.layout.add(this.showIdentifier(t),q.SPACE)}formatParameter(t){this.layout.add(this.params.get(t),q.SPACE)}formatOperator({text:t}){this.cfg.denseOperators||this.dialectCfg.alwaysDenseOperators.includes(t)?this.layout.add(q.NO_SPACE,t):t===":"?this.layout.add(q.NO_SPACE,t,q.SPACE):this.layout.add(t,q.SPACE)}formatComma(t){this.inline?this.layout.add(q.NO_SPACE,",",q.SPACE):this.layout.add(q.NO_SPACE,",",q.NEWLINE,q.INDENT)}withComments(t,n){this.formatComments(t.leadingComments),n(),this.formatComments(t.trailingComments)}formatComments(t){t&&t.forEach(n=>{n.type===fe.line_comment?this.formatLineComment(n):this.formatBlockComment(n)})}formatLineComment(t){Pc(t.precedingWhitespace||"")?this.layout.add(q.NEWLINE,q.INDENT,t.text,q.MANDATORY_NEWLINE,q.INDENT):this.layout.getLayoutItems().length>0?this.layout.add(q.NO_NEWLINE,q.SPACE,t.text,q.MANDATORY_NEWLINE,q.INDENT):this.layout.add(t.text,q.MANDATORY_NEWLINE,q.INDENT)}formatBlockComment(t){t.type===fe.block_comment&&this.isMultilineBlockComment(t)?(this.splitBlockComment(t.text).forEach(n=>{this.layout.add(q.NEWLINE,q.INDENT,n)}),this.layout.add(q.NEWLINE,q.INDENT)):this.layout.add(t.text,q.SPACE)}isMultilineBlockComment(t){return Pc(t.text)||Pc(t.precedingWhitespace||"")}isDocComment(t){const n=t.split(/\n/);return/^\/\*\*?$/.test(n[0])&&n.slice(1,n.length-1).every(r=>/^\s*\*/.test(r))&&/^\s*\*\/$/.test(qo(n))}splitBlockComment(t){return this.isDocComment(t)?t.split(/\n/).map(n=>/^\s*\*/.test(n)?" "+n.replace(/^\s*/,""):n):t.split(/\n/).map(n=>n.replace(/^\s*/,""))}formatSubExpression(t){return new Ra({cfg:this.cfg,dialectCfg:this.dialectCfg,params:this.params,layout:this.layout,inline:this.inline}).format(t)}formatInlineExpression(t){const n=this.params.getPositionalParameterIndex();try{return new Ra({cfg:this.cfg,dialectCfg:this.dialectCfg,params:this.params,layout:new H$(this.cfg.expressionWidth),inline:!0}).format(t)}catch(r){if(r instanceof _d){this.params.setPositionalParameterIndex(n);return}else throw r}}formatKeywordNode(t){switch(t.tokenType){case J.RESERVED_JOIN:return this.formatJoin(t);case J.AND:case J.OR:case J.XOR:return this.formatLogicalOperator(t);default:return this.formatKeyword(t)}}formatJoin(t){$r(this.cfg)?(this.layout.indentation.decreaseTopLevel(),this.layout.add(q.NEWLINE,q.INDENT,this.showKw(t),q.SPACE),this.layout.indentation.increaseTopLevel()):this.layout.add(q.NEWLINE,q.INDENT,this.showKw(t),q.SPACE)}formatKeyword(t){this.layout.add(this.showKw(t),q.SPACE)}formatLogicalOperator(t){this.cfg.logicalOperatorNewline==="before"?$r(this.cfg)?(this.layout.indentation.decreaseTopLevel(),this.layout.add(q.NEWLINE,q.INDENT,this.showKw(t),q.SPACE),this.layout.indentation.increaseTopLevel()):this.layout.add(q.NEWLINE,q.INDENT,this.showKw(t),q.SPACE):this.layout.add(this.showKw(t),q.NEWLINE,q.INDENT)}formatDataType(t){this.layout.add(this.showDataType(t),q.SPACE)}showKw(t){return mT(t.tokenType)?AT(this.showNonTabularKw(t),this.cfg.indentStyle):this.showNonTabularKw(t)}showNonTabularKw(t){switch(this.cfg.keywordCase){case"preserve":return Fi(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}showFunctionKw(t){return mT(t.tokenType)?AT(this.showNonTabularFunctionKw(t),this.cfg.indentStyle):this.showNonTabularFunctionKw(t)}showNonTabularFunctionKw(t){switch(this.cfg.functionCase){case"preserve":return Fi(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}showIdentifier(t){if(t.quoted)return t.text;switch(this.cfg.identifierCase){case"preserve":return t.text;case"upper":return t.text.toUpperCase();case"lower":return t.text.toLowerCase()}}showDataType(t){switch(this.cfg.dataTypeCase){case"preserve":return Fi(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}}class W${constructor(t,n){this.dialect=t,this.cfg=n,this.params=new g$(this.cfg.params)}format(t){const n=this.parse(t);return this.formatAst(n).trimEnd()}parse(t){return j$(this.dialect.tokenizer).parse(t,this.cfg.paramTypes||{})}formatAst(t){return t.map(n=>this.formatStatement(n)).join(`
|
|
790
|
+
`.repeat(this.cfg.linesBetweenQueries+1))}formatStatement(t){const n=new Ra({cfg:this.cfg,dialectCfg:this.dialect.formatOptions,params:this.params,layout:new wg(new Ug(m$(this.cfg)))}).format(t.children);return t.hasSemicolon&&(this.cfg.newlineBeforeSemicolon?n.add(q.NEWLINE,";"):n.add(q.NO_NEWLINE,";")),n.toString()}}class Hi extends Error{}function Y$(e){const t=["multilineLists","newlineBeforeOpenParen","newlineBeforeCloseParen","aliasAs","commaPosition","tabulateAlias"];for(const n of t)if(n in e)throw new Hi(`${n} config is no more supported.`);if(e.expressionWidth<=0)throw new Hi(`expressionWidth config must be positive number. Received ${e.expressionWidth} instead.`);if(e.params&&!$$(e.params)&&console.warn('WARNING: All "params" option values should be strings.'),e.paramTypes&&!V$(e.paramTypes))throw new Hi("Empty regex given in custom paramTypes. That would result in matching infinite amount of parameters.");return e}function $$(e){return(e instanceof Array?e:Object.values(e)).every(n=>typeof n=="string")}function V$(e){return e.custom&&Array.isArray(e.custom)?e.custom.every(t=>t.regex!==""):!0}var z$=function(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 s=0,r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]]);return n};const Bg={bigquery:"bigquery",clickhouse:"clickhouse",db2:"db2",db2i:"db2i",duckdb:"duckdb",hive:"hive",mariadb:"mariadb",mysql:"mysql",n1ql:"n1ql",plsql:"plsql",postgresql:"postgresql",redshift:"redshift",spark:"spark",sqlite:"sqlite",sql:"sql",tidb:"tidb",trino:"trino",transactsql:"transactsql",tsql:"transactsql",singlestoredb:"singlestoredb",snowflake:"snowflake"},X$=Object.keys(Bg),K$={tabWidth:2,useTabs:!1,keywordCase:"preserve",identifierCase:"preserve",dataTypeCase:"preserve",functionCase:"preserve",indentStyle:"standard",logicalOperatorNewline:"before",expressionWidth:50,linesBetweenQueries:1,denseOperators:!1,newlineBeforeSemicolon:!1},q$=(e,t={})=>{if(typeof t.language=="string"&&!X$.includes(t.language))throw new Hi(`Unsupported SQL dialect: ${t.language}`);const n=Bg[t.language||"sql"];return J$(e,Object.assign(Object.assign({},t),{dialect:r$[n]}))},J$=(e,t)=>{var{dialect:n}=t,r=z$(t,["dialect"]);if(typeof e!="string")throw new Error("Invalid query argument. Expected string, instead got "+typeof e);const s=Y$(Object.assign(Object.assign({},K$),r));return new W$(h$(n),s).format(e)};function xn({cell:e,t,onRun:n,onMoveUp:r,onMoveDown:s,onDelete:i,children:a}){const[l,c]=p.useState(!1),d=Fg(e,t),u=kg[e.type]??t.accent,E=e.name?o.jsx("span",{style:{color:t.textSecondary,fontSize:12,fontFamily:t.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:200},children:e.name}):void 0,f=l?o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[n&&o.jsx(Kt,{title:"Run cell (Shift+Enter)",onClick:n,t,accent:!0,children:o.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:o.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})})}),o.jsx(Kt,{title:"Move up",onClick:r,t,children:o.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M3.47 7.78a.75.75 0 0 1 0-1.06l4.25-4.25a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1-1.06 1.06L8.75 4.81v7.44a.75.75 0 0 1-1.5 0V4.81L4.53 7.78a.75.75 0 0 1-1.06 0Z"})})}),o.jsx(Kt,{title:"Move down",onClick:s,t,children:o.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M12.53 8.22a.75.75 0 0 1 0 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L2.97 9.28a.75.75 0 0 1 1.06-1.06l2.72 2.97V3.75a.75.75 0 0 1 1.5 0v7.44l2.72-2.97a.75.75 0 0 1 1.06 0Z"})})}),o.jsx(Kt,{title:"Delete cell",onClick:i,t,danger:!0,children:o.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M11 1.75V3h2.25a.75.75 0 0 1 0 1.5H2.75a.75.75 0 0 1 0-1.5H5V1.75C5 .784 5.784 0 6.75 0h2.5C10.216 0 11 .784 11 1.75ZM4.496 6.675l.66 6.6a.25.25 0 0 0 .249.225h5.19a.25.25 0 0 0 .249-.225l.66-6.6a.75.75 0 0 1 1.492.149l-.66 6.6A1.748 1.748 0 0 1 10.595 15h-5.19a1.75 1.75 0 0 1-1.741-1.575l-.66-6.6a.75.75 0 1 1 1.492-.15ZM6.5 1.75V3h3V1.75a.25.25 0 0 0-.25-.25h-2.5a.25.25 0 0 0-.25.25Z"})})})]}):void 0;return o.jsx(ER,{typeLabel:jg[e.type]??e.type.toUpperCase(),typeColor:u,accent:d,idleBorder:t.cellBorder,background:t.cellBg,headerBackground:`${t.tableHeaderBg}80`,active:l||e.status!=="idle",title:E,actions:f,status:o.jsx(Gg,{cell:e,t}),onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:a})}const jg={sql:"SQL",markdown:"MD",dql:"DQL",param:"PARAM",chart:"CHART",pivot:"PIVOT",single_value:"SINGLE VALUE",filter:"FILTER",table:"TABLE",map:"MAP",writeback:"WRITEBACK",python:"PYTHON",chat:"CHAT"};function at(e,t){return typeof window>"u"?t:getComputedStyle(document.documentElement).getPropertyValue(e).trim()||t}function Q$(){return{sql:at("--cell-sql","#3b8ef0"),markdown:at("--cell-md","#2fb97a"),dql:at("--cell-insight","#ffc857"),param:at("--cell-inputs","#9aa0ae"),chart:at("--cell-chart","#b067f7"),pivot:at("--cell-pivot","#e5a84d"),single_value:at("--cell-single","#b067f7"),filter:at("--cell-filter","#f26a6a"),table:at("--cell-table","#5dd1c8"),map:at("--cell-goal","#61d095"),writeback:at("--cell-callout","#ff7ac6"),python:at("--cell-sql","#3b8ef0"),chat:at("--cell-chat","#8a8f9b")}}const kg=new Proxy({},{get(e,t){return Q$()[t]}}),Z$={map:{title:"Map",subtitle:"Geospatial visualization — lat/lon points and choropleths from an upstream dataframe. Lands in v0.11 on the dql-compiler geo pipeline.",color:"#7ce38b",badge:"v0.11"},writeback:{title:"Writeback",subtitle:"Governed output sink — writes a dataframe back to your warehouse with block tests gating the commit. Lands in v0.11.",color:"#d2a8ff",badge:"v0.11"},python:{title:"Python",subtitle:"Python cell via Pyodide sidecar.",color:"#3572a5",badge:"v0.11"}};function Fg(e,t){if(e.blockBinding)return e.blockBinding.state==="forked"?t.warning:t.success;switch(e.status){case"running":return t.cellBorderRunning;case"success":return t.success;case"error":return t.error;default:return t.cellBorder}}function Gg({cell:e,t}){var i;const{status:n}=e;if(n==="idle"&&e.executionCount===void 0)return null;let r=t.textMuted,s="";if(n==="running")r=t.cellBorderRunning,s="Running…";else if(n==="error")r=t.error,s="Error";else if(e.executionCount!==void 0)if(r=t.success,((i=e.result)==null?void 0:i.executionTime)!==void 0){const a=e.result.executionTime;s=a<1e3?`${Math.max(1,Math.round(a))}ms`:`${(a/1e3).toFixed(1)}s`}else s=`[${e.executionCount}]`;return o.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:10,fontFamily:t.font,color:t.textMuted,flexShrink:0},children:[o.jsx("span",{"aria-hidden":!0,style:{width:6,height:6,borderRadius:999,background:r,boxShadow:n==="running"?`0 0 0 3px ${r}33`:void 0,animation:n==="running"?"pulse 1.2s ease-in-out infinite":void 0,flexShrink:0}}),s,o.jsx("style",{children:"@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.5} }"})]})}function e5(e){if(!/^\s*block\s+"/i.test(e.trim()))return null;const t=s=>{var i;return((i=e.match(new RegExp(`\\b${s}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:i[1])??""},n=e.match(/\btags\s*=\s*\[([^\]]*)\]/i),r=n?(n[1].match(/"([^"]*)"/g)??[]).map(s=>s.slice(1,-1)):[];return{domain:t("domain"),owner:t("owner"),description:t("description"),blockType:t("type")||"custom",tags:r}}function jc(e,t,n){const r=new RegExp(`(\\b${t}\\s*=\\s*)"[^"]*"`,"i");return r.test(e)?e.replace(r,`$1"${n.replace(/"/g,'\\"')}"`):e}function t5(e,t){const n=t.map(s=>`"${s}"`).join(", "),r=/(\btags\s*=\s*)\[[^\]]*\]/i;return r.test(e)?e.replace(r,`$1[${n}]`):e}function n5({binding:e,t,onRevert:n,onUnbind:r}){const s=e.state==="forked",i=s?t.warning:t.success,a=s?"FORKED":"BOUND",l=s?"Local edits have diverged from the block file — Revert to discard, or Save as Block to promote as a new version.":"This cell mirrors the block file. Edit to fork locally.";return o.jsxs("div",{title:l,style:{display:"flex",alignItems:"center",gap:8,padding:"4px 10px",borderBottom:`1px solid ${t.cellBorder}`,background:`${i}10`,fontFamily:t.fontMono,fontSize:11},children:[o.jsx("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.08em",color:i,background:`${i}24`,border:`1px solid ${i}55`,borderRadius:3,padding:"1px 5px"},children:a}),o.jsx("span",{style:{color:t.textSecondary},children:e.path}),e.version&&o.jsxs("span",{style:{color:t.textMuted},children:["· v",e.version]}),!s&&o.jsx("span",{title:"Bound cells track the block file — edits fork locally",style:{color:t.textMuted},children:"🔒"}),o.jsx("div",{style:{flex:1}}),s&&o.jsx("button",{onClick:n,title:"Discard local edits and restore the block file body",style:gT(t,i),children:"Revert"}),o.jsx("button",{onClick:r,title:"Detach this cell from the block file",style:gT(t,t.btnBorder),children:"Unbind"})]})}function gT(e,t){return{background:"transparent",border:`1px solid ${t}`,borderRadius:4,color:e.textSecondary,fontSize:10,fontFamily:e.font,fontWeight:600,letterSpacing:"0.04em",padding:"1px 7px",cursor:"pointer"}}function r5({content:e,onChange:t,t:n}){const r=e5(e);if(!r)return null;const s={background:n.editorBg,border:`1px solid ${n.cellBorder}`,borderRadius:3,color:n.textSecondary,fontSize:11,fontFamily:n.fontMono,padding:"2px 6px",outline:"none"},i={fontSize:9,fontWeight:700,color:n.textMuted,fontFamily:n.font,letterSpacing:"0.05em",textTransform:"uppercase",marginRight:4,flexShrink:0},a={display:"flex",alignItems:"center",gap:4};return o.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 12px",padding:"5px 10px",borderBottom:`1px solid ${n.cellBorder}`,background:`${n.tableHeaderBg}40`},children:[o.jsxs("div",{style:a,children:[o.jsx("span",{style:i,children:"domain"}),o.jsx("input",{style:{...s,width:80},value:r.domain,placeholder:"e.g. finance",onChange:l=>t(jc(e,"domain",l.target.value))})]}),o.jsxs("div",{style:a,children:[o.jsx("span",{style:i,children:"owner"}),o.jsx("input",{style:{...s,width:90},value:r.owner,placeholder:"e.g. data-team",onChange:l=>t(jc(e,"owner",l.target.value))})]}),o.jsxs("div",{style:a,children:[o.jsx("span",{style:i,children:"tags"}),o.jsx("input",{style:{...s,width:110},value:r.tags.join(", "),placeholder:"revenue, kpi",onChange:l=>{const c=l.target.value.split(",").map(d=>d.trim()).filter(Boolean);t(t5(e,c))}})]}),o.jsxs("div",{style:{...a,flex:1},children:[o.jsx("span",{style:i,children:"description"}),o.jsx("input",{style:{...s,flex:1,minWidth:120},value:r.description,placeholder:"What this block measures",onChange:l=>t(jc(e,"description",l.target.value))})]})]})}const o5=new Set(["sql","dql","param","writeback","python","chat"]);function s5({cell:e,index:t}){var X;const{state:n,dispatch:r}=Re(),s=ce[n.themeMode],{executeCell:i,executeDependents:a,cancelCell:l}=Ha(),[c,d]=p.useState(!1),[u,E]=p.useState(!1),[f,T]=p.useState(e.name??""),[A,R]=p.useState(!0),[S,h]=p.useState("table"),[g,m]=p.useState(null),[I,O]=p.useState(!1),[N,x]=p.useState(!1),[_,C]=p.useState(!1),v=p.useMemo(()=>_?RD(e,n.cells):null,[_,e,n.cells]),b=e.type==="sql"||e.type==="dql"||e.type==="chart"||e.type==="pivot"||e.type==="single_value"||e.type==="filter"||e.type==="table",P=Fg(e,s),j=e.type!=="markdown"&&e.type!=="param",L=p.useRef(null),B=p.useRef(e.content),[M,U]=p.useState(!1),D=p.useMemo(()=>n.schemaTables.length>0?Object.fromEntries(n.schemaTables.map(H=>[H.name,H.columns.map(re=>re.name)])):void 0,[n.schemaTables]);p.useEffect(()=>{if(e.status==="success"&&e.result){const H=pr(e.result,e.chartConfig);m(H!=="table"?H:null),h(H!=="table"?"chart":"table")}},[e.status,e.result,e.chartConfig]);const y=p.useCallback(()=>{j&&i(e.id)},[e.id,i,j]),w=p.useCallback(H=>{const re={content:H},ie=e.blockBinding;if((ie==null?void 0:ie.originalContent)!==void 0){const se=H.trim()!==ie.originalContent.trim()?"forked":"bound";se!==ie.state&&(re.blockBinding={...ie,state:se})}r({type:"UPDATE_CELL",id:e.id,updates:re}),U(H!==B.current)},[e.id,e.blockBinding,r]),F=p.useCallback(()=>{var re;const H=B.current;r({type:"UPDATE_CELL",id:e.id,updates:{content:H}}),(re=L.current)==null||re.resetTo(H),U(!1)},[e.id,r]),k=p.useCallback(()=>{if(e.content.trim())try{const H=q$(e.content,{language:"sql",tabWidth:2,keywordCase:"upper",linesBetweenQueries:1});r({type:"UPDATE_CELL",id:e.id,updates:{content:H}})}catch{}},[e.content,e.id,r]),V=p.useCallback(()=>{k(),setTimeout(()=>i(e.id),80)},[k,i,e.id]),ee=p.useCallback(H=>r({type:"UPDATE_CELL",id:e.id,updates:H}),[r,e.id]),Y=()=>{r({type:"DELETE_CELL",id:e.id})},te=()=>{r({type:"MOVE_CELL",id:e.id,direction:"up"})},ne=()=>{r({type:"MOVE_CELL",id:e.id,direction:"down"})},z={cell:e,t:s,onMoveUp:te,onMoveDown:ne,onDelete:Y};if(n.appMode!=="studio"&&o5.has(e.type))return o.jsxs("div",{style:{marginTop:8,marginBottom:8,padding:"6px 10px",borderRadius:6,border:`1px dashed ${s.cellBorder}`,background:s.cellBg,color:s.textMuted,fontSize:11,fontFamily:s.font,display:"flex",alignItems:"center",gap:8},children:[o.jsx("span",{style:{opacity:.7},children:"◎"}),o.jsxs("span",{children:[e.type.toUpperCase()," cell hidden in App view",e.name?` · ${e.name}`:""]})]});if(e.type==="param")return o.jsx(xn,{...z,onRun:()=>a(e.id),children:o.jsx(J1,{cell:e,themeMode:n.themeMode,onApplyParam:a})});if(e.type==="pivot")return o.jsx(xn,{...z,children:o.jsx(Hv,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:ee})});if(e.type==="single_value")return o.jsx(xn,{...z,children:o.jsx(kv,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:ee})});if(e.type==="filter")return o.jsx(xn,{...z,children:o.jsx(Mv,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:ee})});if(e.type==="chart")return o.jsx(xn,{...z,children:o.jsx(_v,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:ee})});if(e.type==="table")return o.jsx(xn,{...z,children:o.jsx(Yv,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:ee})});if(e.type==="chat")return o.jsx(xn,{...z,children:o.jsx(iD,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:ee})});const oe=Z$[e.type];if(oe)return o.jsx(xn,{...z,children:o.jsx(Q1,{cell:e,themeMode:n.themeMode,title:oe.title,subtitle:oe.subtitle,color:oe.color,badge:oe.badge})});const le=()=>{E(!1),r({type:"UPDATE_CELL",id:e.id,updates:{name:f.trim()||void 0}})},ae=(e.result||e.error)&&e.type!=="markdown";return e.result&&pr(e.result,e.chartConfig),o.jsxs("div",{onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),style:{display:"flex",gap:0,marginBottom:2},children:[_&&v&&o.jsx(sA,{cell:e,initialContent:v.derivedFromUpstream?v.content:void 0,initialName:v.suggestedName,initialDescription:v.suggestedDescription,onClose:()=>C(!1),onSaved:({path:H,name:re})=>{r({type:"FILE_ADDED",file:{name:re,path:H,type:"block",folder:"blocks"}})}}),o.jsxs("div",{style:{flex:1,minWidth:0,borderRadius:8,border:`1px solid ${c||e.status!=="idle"?P:s.cellBorder}`,background:s.cellBg,boxShadow:e.status!=="idle"?`0 0 0 3px ${P}14, 0 1px 2px rgba(0,0,0,0.04)`:"0 1px 2px rgba(0,0,0,0.02)",overflow:"hidden",transition:"border-color 0.2s"},children:[o.jsxs("div",{style:{minHeight:32,display:"flex",alignItems:"center",padding:"8px 14px",gap:8,background:"transparent"},children:[o.jsx("span",{"aria-hidden":!0,style:{width:6,height:6,borderRadius:999,background:kg[e.type]??s.accent,flexShrink:0}}),o.jsx("span",{title:e.type==="dql"?"DQL cell — write a governed block (type, owner, description, tests) or use @metric()/@dim() refs":e.type==="sql"?"SQL cell — write raw SQL, reference other cells with {{name}}":void 0,style:{fontSize:11,fontWeight:500,letterSpacing:"0.2px",color:s.textSecondary,flexShrink:0,whiteSpace:"nowrap"},children:jg[e.type]}),c&&(e.type==="sql"||e.type==="dql")&&o.jsx(fD,{themeMode:n.themeMode,cellType:e.type,onInsert:H=>w(H)}),c&&(e.type==="sql"||e.type==="dql")&&o.jsx("button",{title:"Format SQL (clean up whitespace & keywords)",onClick:k,style:{background:"transparent",border:`1px solid ${s.btnBorder}`,borderRadius:4,color:s.textMuted,fontSize:10,fontFamily:s.font,fontWeight:600,letterSpacing:"0.04em",padding:"1px 7px",cursor:"pointer",transition:"color 0.15s, border-color 0.15s"},onMouseEnter:H=>{H.currentTarget.style.color=s.textSecondary,H.currentTarget.style.borderColor=s.accent},onMouseLeave:H=>{H.currentTarget.style.color=s.textMuted,H.currentTarget.style.borderColor=s.btnBorder},children:"Format"}),M&&(e.type==="sql"||e.type==="dql")&&o.jsx("button",{title:"Reset to last saved version (discard changes)",onClick:F,style:{background:"transparent",border:`1px solid ${s.btnBorder}`,borderRadius:4,color:s.error,fontSize:10,fontFamily:s.font,fontWeight:600,letterSpacing:"0.04em",padding:"1px 7px",cursor:"pointer",transition:"color 0.15s, border-color 0.15s"},onMouseEnter:H=>{H.currentTarget.style.borderColor=s.error},onMouseLeave:H=>{H.currentTarget.style.borderColor=s.btnBorder},children:"↺ Reset"}),c&&b&&o.jsx("button",{title:"Save this cell as a reusable block",onClick:()=>C(!0),style:{background:"transparent",border:`1px solid ${s.btnBorder}`,borderRadius:4,color:s.textMuted,fontSize:10,fontFamily:s.font,fontWeight:600,letterSpacing:"0.04em",padding:"1px 7px",cursor:"pointer",transition:"color 0.15s, border-color 0.15s"},onMouseEnter:H=>{H.currentTarget.style.color=s.textSecondary,H.currentTarget.style.borderColor=s.accent},onMouseLeave:H=>{H.currentTarget.style.color=s.textMuted,H.currentTarget.style.borderColor=s.btnBorder},children:"Save as Block"}),(e.type==="sql"||e.type==="dql")&&o.jsx(ev,{cells:n.cells,index:t,content:e.content,themeMode:n.themeMode,onInsertHandle:H=>{const re=`{{${H}}}`,ie=e.content??"";if(ie.includes(re))return;const de=ie.trim().length===0?`SELECT * FROM ${re}`:`${ie.replace(/\s*$/,"")} ${re}`;w(de)}}),u?o.jsx("input",{autoFocus:!0,value:f,onChange:H=>T(H.target.value),onBlur:le,onKeyDown:H=>{H.key==="Enter"&&le(),H.key==="Escape"&&E(!1)},style:{background:"transparent",border:`1px solid ${s.cellBorderActive}`,borderRadius:4,color:s.textSecondary,fontSize:12,fontFamily:s.fontMono,padding:"1px 6px",outline:"none",width:140}}):e.name&&o.jsx("span",{onClick:()=>{T(e.name??""),E(!0)},title:"Click to rename",style:{color:s.textSecondary,fontSize:12,fontFamily:s.fontMono,cursor:"text",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:200},children:e.name}),o.jsx("div",{style:{flex:1}}),o.jsx(Gg,{cell:e,t:s}),c&&o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[!e.name&&!u&&o.jsx(Kt,{title:"Name this cell",onClick:()=>{T(""),E(!0)},t:s,children:o.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M11.013 1.427a1.75 1.75 0 0 1 2.474 0l1.086 1.086a1.75 1.75 0 0 1 0 2.474l-8.61 8.61c-.21.21-.47.364-.756.445l-3.251.93a.75.75 0 0 1-.927-.928l.929-3.25c.081-.286.235-.547.445-.758l8.61-8.61Zm.176 4.823L9.75 4.81l-6.286 6.287a.253.253 0 0 0-.064.108l-.558 1.953 1.953-.558a.253.253 0 0 0 .108-.064Zm1.238-3.763a.25.25 0 0 0-.354 0L10.811 3.75l1.439 1.44 1.263-1.263a.25.25 0 0 0 0-.354Z"})})}),j&&e.status==="running"?o.jsx(Kt,{title:"Cancel execution",onClick:()=>l(e.id),t:s,danger:!0,children:o.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:o.jsx("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1"})})}):j?o.jsx(Kt,{title:"Run cell (Shift+Enter)",onClick:y,t:s,accent:!0,children:o.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:o.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})})}):null,o.jsx(Kt,{title:"Move up",onClick:te,t:s,children:o.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M3.47 7.78a.75.75 0 0 1 0-1.06l4.25-4.25a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1-1.06 1.06L8.75 4.81v7.44a.75.75 0 0 1-1.5 0V4.81L4.53 7.78a.75.75 0 0 1-1.06 0Z"})})}),o.jsx(Kt,{title:"Move down",onClick:ne,t:s,children:o.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M12.53 8.22a.75.75 0 0 1 0 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L2.97 9.28a.75.75 0 0 1 1.06-1.06l2.72 2.97V3.75a.75.75 0 0 1 1.5 0v7.44l2.72-2.97a.75.75 0 0 1 1.06 0Z"})})}),o.jsx(Kt,{title:"Delete cell",onClick:Y,t:s,danger:!0,children:o.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M11 1.75V3h2.25a.75.75 0 0 1 0 1.5H2.75a.75.75 0 0 1 0-1.5H5V1.75C5 .784 5.784 0 6.75 0h2.5C10.216 0 11 .784 11 1.75ZM4.496 6.675l.66 6.6a.25.25 0 0 0 .249.225h5.19a.25.25 0 0 0 .249-.225l.66-6.6a.75.75 0 0 1 1.492.149l-.66 6.6A1.748 1.748 0 0 1 10.595 15h-5.19a1.75 1.75 0 0 1-1.741-1.575l-.66-6.6a.75.75 0 1 1 1.492-.15ZM6.5 1.75V3h3V1.75a.25.25 0 0 0-.25-.25h-2.5a.25.25 0 0 0-.25.25Z"})})})]})]}),e.type==="dql"&&o.jsx(r5,{content:e.content,onChange:w,t:s}),e.blockBinding&&o.jsx(n5,{binding:e.blockBinding,t:s,onRevert:async()=>{var re;const H=e.blockBinding;if(H)try{const ie=await $.openBlockStudio(H.path),de=Eu(ie.source)??ie.source;r({type:"UPDATE_CELL",id:e.id,updates:{content:de,blockBinding:{...H,state:"bound",originalContent:de}}}),(re=L.current)==null||re.resetTo(de)}catch(ie){console.error("Failed to revert bound cell",ie)}},onUnbind:()=>{r({type:"UPDATE_CELL",id:e.id,updates:{blockBinding:void 0}})}}),e.type==="markdown"?o.jsx(q1,{value:e.content,onChange:w,themeMode:n.themeMode}):o.jsx(Ru,{value:e.content,onChange:w,onRun:y,themeMode:n.themeMode,schema:D,errorMessage:e.status==="error"?e.error:void 0,editorRef:L}),ae&&o.jsxs("div",{style:{borderTop:`1px solid ${s.cellBorder}`},children:[o.jsxs("div",{style:{height:28,display:"flex",alignItems:"center",padding:"0 12px",gap:10,borderBottom:e.result&&A?`1px solid ${s.cellBorder}`:"none",background:`${s.tableHeaderBg}60`},children:[e.result&&o.jsxs("span",{style:{fontSize:11,fontFamily:s.font,color:s.textMuted},children:[(e.result.rowCount??e.result.rows.length).toLocaleString()," rows",e.result.executionTime!==void 0&&o.jsxs(o.Fragment,{children:[" · ",e.result.executionTime<1e3?`${e.result.executionTime}ms`:`${(e.result.executionTime/1e3).toFixed(2)}s`]})]}),e.fromSnapshot&&e.result&&o.jsx("span",{title:"Result loaded from the last saved run; re-run to refresh.",style:{fontSize:10,fontFamily:s.font,color:s.textMuted,border:`1px solid ${s.btnBorder}`,borderRadius:3,padding:"0 6px",lineHeight:"16px"},children:"cached"}),e.error&&o.jsx("span",{style:{fontSize:11,fontFamily:s.font,color:s.error},children:"Error"}),o.jsx("div",{style:{flex:1}}),e.result&&A&&o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:3,position:"relative"},children:[o.jsx("button",{onClick:()=>{h("table"),O(!1)},style:{padding:"1px 7px",fontSize:10,fontFamily:s.font,borderRadius:3,border:`1px solid ${S==="table"?s.accent:s.btnBorder}`,background:S==="table"?`${s.accent}20`:"transparent",color:S==="table"?s.accent:s.textMuted,cursor:"pointer",transition:"all 0.15s"},children:"Table"}),o.jsxs("div",{style:{position:"relative"},children:[o.jsxs("button",{onClick:()=>{S==="chart"&&I?O(!1):(h("chart"),O(H=>!H))},style:{padding:"1px 7px",fontSize:10,fontFamily:s.font,borderRadius:3,border:`1px solid ${S==="chart"?s.accent:s.btnBorder}`,background:S==="chart"?`${s.accent}20`:"transparent",color:S==="chart"?s.accent:s.textMuted,cursor:"pointer",transition:"all 0.15s",display:"flex",alignItems:"center",gap:3},children:[g?((X=zn.find(H=>H.value===g))==null?void 0:X.label)??"Chart":"Chart",o.jsx("svg",{width:"6",height:"6",viewBox:"0 0 8 8",fill:"currentColor",children:o.jsx("path",{d:"M1 2.5l3 3 3-3",stroke:"currentColor",fill:"none",strokeWidth:"1.2",strokeLinecap:"round"})})]}),I&&o.jsx(i5,{selected:g,onSelect:H=>{m(H),h("chart"),O(!1)},onClose:()=>O(!1),t:s})]}),S==="chart"&&o.jsx("button",{onClick:()=>x(H=>!H),title:"Chart configuration",style:{padding:"1px 5px",fontSize:11,borderRadius:3,cursor:"pointer",border:`1px solid ${N?s.accent:s.btnBorder}`,background:N?`${s.accent}20`:"transparent",color:N?s.accent:s.textMuted,transition:"all 0.15s",display:"flex",alignItems:"center"},children:o.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M8 0a8.2 8.2 0 0 1 .701.031C9.444.095 9.99.645 10.16 1.29l.288 1.107c.018.066.079.158.212.224.231.114.454.243.668.386.123.082.233.09.299.071l1.103-.303c.644-.176 1.392.021 1.82.63.27.386.506.798.704 1.23.315.698.043 1.44-.476 1.89l-.815.806a.338.338 0 0 0-.079.262c.02.267.02.538 0 .805a.338.338 0 0 0 .079.262l.815.806c.52.45.79 1.192.476 1.89a7.22 7.22 0 0 1-.704 1.23c-.428.609-1.176.806-1.82.63l-1.103-.303c-.066-.019-.176-.011-.299.071a5.09 5.09 0 0 1-.668.386c-.133.066-.194.158-.212.224l-.288 1.107c-.169.645-.715 1.196-1.458 1.26a8.006 8.006 0 0 1-1.402 0c-.743-.064-1.29-.614-1.458-1.26l-.289-1.106c-.018-.066-.079-.158-.212-.224a5.09 5.09 0 0 1-.668-.387c-.123-.082-.233-.09-.299-.071l-1.103.303c-.644.176-1.392-.021-1.82-.63a7.12 7.12 0 0 1-.704-1.23c-.315-.698-.043-1.44.476-1.89l.815-.806a.338.338 0 0 0 .079-.262 6.08 6.08 0 0 1 0-.805.338.338 0 0 0-.079-.262l-.815-.806c-.52-.45-.79-1.192-.476-1.89a7.22 7.22 0 0 1 .704-1.23c.428-.609 1.176-.806 1.82-.63l1.103.303c.066.019.176.011.299-.071.214-.143.437-.272.668-.386.133-.066.194-.158.212-.224L6.54 1.29C6.71.645 7.256.095 7.999.031 8.236.01 8.474 0 8.713 0H8ZM8 5a3 3 0 1 0 0 6 3 3 0 0 0 0-6Z"})})})]}),o.jsxs("button",{onClick:()=>R(H=>!H),style:{background:"transparent",border:"none",cursor:"pointer",color:s.textMuted,fontSize:11,fontFamily:s.font,padding:"2px 4px",display:"flex",alignItems:"center",gap:4},children:[o.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:A?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.15s"},children:o.jsx("path",{d:"M1 3l4 4 4-4",stroke:"currentColor",fill:"none",strokeWidth:"1.5"})}),A?"Hide":"Show"]})]}),A&&o.jsxs(o.Fragment,{children:[e.error&&o.jsx(gD,{message:e.error,themeMode:n.themeMode,onFix:j?V:void 0,schemaTables:n.schemaTables}),e.result&&!e.error&&(S==="chart"&&g?o.jsxs(o.Fragment,{children:[Va(g,e.result,n.themeMode,e.chartConfig),N&&o.jsx(a5,{columns:e.result.columns,chartConfig:e.chartConfig,onChange:H=>r({type:"UPDATE_CELL",id:e.id,updates:{chartConfig:{...e.chartConfig,...H}}}),t:s})]}):o.jsx(Rn,{result:e.result,themeMode:n.themeMode}))]})]}),j&&o.jsx(rG,{cellContent:e.content,cellType:e.type,cellName:e.name,themeMode:n.themeMode,t:s,onFocusNode:H=>{r({type:"SET_LINEAGE_FOCUS",nodeId:H}),n.lineageFullscreen||r({type:"TOGGLE_LINEAGE_FULLSCREEN"})}})]})]})}function Kt({title:e,onClick:t,children:n,t:r,accent:s,danger:i}){const[a,l]=p.useState(!1);return o.jsx("button",{title:e,onClick:t,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center",background:a?i?`${r.error}18`:s?`${r.accent}18`:r.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:a?i?r.error:s?r.accent:r.textSecondary:r.textMuted,transition:"all 0.15s",padding:0},children:n})}function i5({selected:e,onSelect:t,onClose:n,t:r}){const[s,i]=p.useState(null);return Be.useEffect(()=>{const a=l=>{setTimeout(()=>n(),0)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[n]),o.jsx("div",{onMouseDown:a=>a.stopPropagation(),style:{position:"absolute",top:24,right:0,zIndex:200,background:r.cellBg,border:`1px solid ${r.cellBorder}`,borderRadius:6,boxShadow:"0 8px 24px rgba(0,0,0,0.3)",padding:4,minWidth:130,maxHeight:280,overflowY:"auto",display:"flex",flexDirection:"column",gap:1},children:zn.map(({value:a,label:l})=>o.jsx("button",{onClick:()=>t(a),onMouseEnter:()=>i(a),onMouseLeave:()=>i(null),style:{background:e===a?`${r.accent}20`:s===a?r.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:e===a?r.accent:r.textSecondary,fontSize:11,fontFamily:r.font,fontWeight:e===a?600:400,padding:"4px 10px",textAlign:"left",transition:"background 0.1s"},children:l},a))})}function a5({columns:e,chartConfig:t,onChange:n,t:r}){const s={background:r.inputBg,border:`1px solid ${r.inputBorder}`,borderRadius:4,color:r.textPrimary,fontSize:11,fontFamily:r.fontMono,padding:"3px 6px",outline:"none",minWidth:100,flex:1},i={fontSize:9,fontWeight:700,color:r.textMuted,fontFamily:r.font,letterSpacing:"0.05em",textTransform:"uppercase",minWidth:40,flexShrink:0};return o.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px 16px",padding:"8px 12px",borderTop:`1px solid ${r.cellBorder}`,background:`${r.tableHeaderBg}40`},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[o.jsx("span",{style:i,children:"X axis"}),o.jsxs("select",{style:s,value:(t==null?void 0:t.x)??"",onChange:a=>n({x:a.target.value||void 0}),children:[o.jsx("option",{value:"",children:"Auto"}),e.map(a=>o.jsx("option",{value:a,children:a},a))]})]}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[o.jsx("span",{style:i,children:"Y axis"}),o.jsxs("select",{style:s,value:(t==null?void 0:t.y)??"",onChange:a=>n({y:a.target.value||void 0}),children:[o.jsx("option",{value:"",children:"Auto"}),e.map(a=>o.jsx("option",{value:a,children:a},a))]})]}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[o.jsx("span",{style:i,children:"Color"}),o.jsxs("select",{style:s,value:(t==null?void 0:t.color)??"",onChange:a=>n({color:a.target.value||void 0}),children:[o.jsx("option",{value:"",children:"None"}),e.map(a=>o.jsx("option",{value:a,children:a},a))]})]}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:150},children:[o.jsx("span",{style:i,children:"Title"}),o.jsx("input",{style:{...s,fontFamily:r.font},value:(t==null?void 0:t.title)??"",placeholder:"Chart title",onChange:a=>n({title:a.target.value||void 0})})]})]})}const l5={draft:"#8b949e",review:"#d29922",certified:"#3fb950",deprecated:"#f85149",pending_recertification:"#db6d28"};function c5({themeMode:e,onPick:t,autoFocus:n=!0,compact:r=!0}){const s=ce[e],[i,a]=p.useState([]),[l,c]=p.useState(!0),[d,u]=p.useState(""),[E,f]=p.useState(""),[T,A]=p.useState(""),R=p.useRef(null);p.useEffect(()=>{let I=!1;return c(!0),$.getBlockLibrary().then(O=>{I||a(O.blocks)}).finally(()=>{I||c(!1)}),()=>{I=!0}},[]),p.useEffect(()=>{if(n){const I=setTimeout(()=>{var O;return(O=R.current)==null?void 0:O.focus()},30);return()=>clearTimeout(I)}},[n]);const S=p.useMemo(()=>[...new Set(i.map(I=>I.domain))].sort(),[i]),h=p.useMemo(()=>[...new Set(i.map(I=>I.status))].sort(),[i]),g=p.useMemo(()=>i.filter(I=>{if(d){const O=d.toLowerCase();if(!I.name.toLowerCase().includes(O)&&!I.description.toLowerCase().includes(O))return!1}return!(E&&I.domain!==E||T&&I.status!==T)}),[i,d,E,T]),m={background:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:4,color:s.textPrimary,fontSize:11,fontFamily:s.font,padding:"4px 6px",outline:"none"};return o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:r?340:void 0},children:[o.jsxs("div",{style:{display:"flex",gap:4,alignItems:"center"},children:[o.jsx("input",{ref:R,value:d,onChange:I=>u(I.target.value),placeholder:"Search blocks...",style:{...m,flex:1,padding:"6px 8px"}}),o.jsxs("select",{value:E,onChange:I=>f(I.target.value),style:m,children:[o.jsx("option",{value:"",children:"All domains"}),S.map(I=>o.jsx("option",{value:I,children:I},I))]}),o.jsxs("select",{value:T,onChange:I=>A(I.target.value),style:m,children:[o.jsx("option",{value:"",children:"Any"}),h.map(I=>o.jsx("option",{value:I,children:I},I))]})]}),o.jsx("div",{style:{maxHeight:r?220:420,overflowY:"auto",display:"flex",flexDirection:"column",border:`1px solid ${s.cellBorder}`,borderRadius:4},children:l?o.jsx(IT,{t:s,children:"Loading blocks..."}):g.length===0?o.jsx(IT,{t:s,children:i.length===0?"No blocks yet. Save a cell as a block to get started.":"No blocks match your filters."}):g.map(I=>o.jsx(d5,{block:I,onClick:()=>t(I),t:s,compact:r},I.path))})]})}function IT({children:e,t}){return o.jsx("div",{style:{padding:16,textAlign:"center",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:e})}function d5({block:e,onClick:t,t:n,compact:r}){const[s,i]=p.useState(!1),a=l5[e.status]??n.textMuted;return o.jsxs("button",{onClick:t,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{background:s?`${n.accent}14`:"transparent",border:"none",borderBottom:`1px solid ${n.cellBorder}`,cursor:"pointer",padding:r?"8px 10px":"10px 12px",textAlign:"left",fontFamily:n.font},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:3},children:[o.jsx("span",{style:{fontSize:12,fontWeight:600,color:n.textPrimary},children:e.name}),o.jsx("span",{style:{fontSize:9,fontWeight:600,color:a,background:`${a}18`,padding:"1px 6px",borderRadius:4,textTransform:"uppercase",letterSpacing:"0.04em"},children:e.status})]}),e.description&&o.jsx("div",{style:{fontSize:11,color:n.textMuted,lineHeight:1.3,marginBottom:3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.description}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:10,color:n.textMuted},children:[o.jsx("span",{style:{background:n.pillBg,padding:"1px 6px",borderRadius:4},children:e.domain||"no domain"}),e.owner&&o.jsxs("span",{children:["by ",e.owner]})]})]})}const u5=[{type:"block",label:"Block",Icon:NR,color:"#6b8afd",group:"library"},{type:"chat",label:"Chat",Icon:f0,color:"#8a8f9b",group:"compute"},{type:"sql",label:"SQL",Icon:a0,color:"#3b8ef0",group:"compute"},{type:"markdown",label:"Text",Icon:AR,color:"#2fb97a",group:"compute"},{type:"chart",label:"Chart",Icon:l0,color:"#b067f7",group:"viz"},{type:"pivot",label:"Pivot",Icon:c0,color:"#e5a84d",group:"viz"},{type:"single_value",label:"Single value",Icon:d0,color:"#b067f7",group:"viz"},{type:"table",label:"Table",Icon:W_,color:"#5dd1c8",group:"viz"},{type:"param",label:"Inputs",Icon:u0,color:"#9aa0ae",group:"io"},{type:"filter",label:"Filter",Icon:E0,color:"#f26a6a",group:"transform"}];function kc({afterId:e}){const{state:t,dispatch:n}=Re(),r=ce[t.themeMode],[s,i]=p.useState(!1),[a,l]=p.useState(!1),[c,d]=p.useState(!1),[u,E]=p.useState(!1),f=p.useRef(null);p.useEffect(()=>{if(!a)return;function S(h){f.current&&!f.current.contains(h.target)&&(l(!1),d(!1))}return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[a]);const T=()=>{l(!1),d(!1)},A=S=>{const h=ct(S);n({type:"ADD_CELL",cell:h,afterId:e}),S==="sql"&&n({type:"SET_SIDEBAR_PANEL",panel:"schema"}),T()},R=async S=>{let h;try{h=await $.openBlockStudio(S.path)}catch(I){console.error("Failed to bind block cell",I),window.alert(`Couldn't load block ${S.path}. Check the console for details.`),T();return}const g=Eu(h.source)??h.source,m=ct("sql",g);m.name=S.name,m.blockBinding={path:S.path,state:"bound",originalContent:g},n({type:"ADD_CELL",cell:m,afterId:e}),T()};return o.jsxs("div",{ref:f,onDragOver:S=>{S.dataTransfer.types.includes(ra)&&(S.preventDefault(),E(!0))},onDragLeave:()=>E(!1),onDrop:S=>{const h=VR(S.dataTransfer.getData(ra));if(!h)return;S.preventDefault(),E(!1);const g=ct("sql",h.reference);n({type:"ADD_CELL",cell:g,afterId:e}),$.trackUsage(h.name),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:h.name}}))},onMouseEnter:()=>i(!0),onMouseLeave:()=>{i(!1),E(!1)},style:{position:"relative",height:28,display:"flex",alignItems:"center",justifyContent:"center",cursor:"default"},children:[(s||a||u)&&o.jsxs("button",{onClick:()=>l(S=>!S),style:{position:"relative",zIndex:2,height:22,padding:"0 10px",borderRadius:11,border:`1px solid ${u?r.accent:r.cellBorderActive}`,background:u?`${r.accent}28`:`${r.accent}18`,color:r.accent,cursor:"pointer",fontSize:12,fontFamily:r.font,fontWeight:500,display:"flex",alignItems:"center",gap:4,transition:"background 0.15s"},children:[o.jsx("span",{style:{fontSize:14,lineHeight:1,marginTop:-1},children:"+"}),"Add cell"]}),a&&o.jsxs("div",{style:{position:"absolute",top:26,left:"50%",transform:"translateX(-50%)",zIndex:100,background:r.modalBg,border:`1px solid ${r.cellBorder}`,borderRadius:10,boxShadow:"0 12px 32px rgba(0,0,0,0.35)",padding:10,display:"flex",flexDirection:"column",gap:8,minWidth:760},children:[o.jsx("div",{style:{display:"flex",gap:6,flexWrap:"nowrap",alignItems:"center",justifyContent:"space-between"},children:u5.map(S=>o.jsx(E5,{entry:S,active:S.type==="block"&&c,onClick:()=>{if(S.type==="block"){d(h=>!h);return}A(S.type)},t:r},S.type))}),c&&o.jsx("div",{style:{padding:"6px 2px 2px",borderTop:`1px solid ${r.cellBorder}`},children:o.jsx(c5,{themeMode:t.themeMode,onPick:S=>void R(S)})})]})]})}function E5({entry:e,onClick:t,t:n,active:r=!1}){const[s,i]=p.useState(!1),a=r||s,l=e.Icon;return o.jsxs("button",{onClick:t,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),title:e.label,style:{background:a?`${e.color}18`:"transparent",border:`1px solid ${a?e.color:n.cellBorder}`,borderRadius:8,cursor:"pointer",color:a?e.color:n.textSecondary,fontSize:11,fontFamily:n.font,fontWeight:500,padding:"10px 6px",minWidth:76,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:6,transition:"all 0.12s"},children:[o.jsx("span",{style:{color:e.color,display:"flex",alignItems:"center",justifyContent:"center"},children:o.jsx(l,{size:18,strokeWidth:1.75})}),o.jsx("span",{style:{letterSpacing:"0.02em"},children:e.label})]})}function f5({registerCellRef:e}){const{state:t,dispatch:n}=Re(),{executeCell:r}=Ha(),s=ce[t.themeMode],[i,a]=p.useState(null),l=p.useRef(0),[c,d]=p.useState(null),[u,E]=p.useState(null);p.useCallback(S=>{a(S)},[]),p.useEffect(()=>{i&&t.inspectorOpen&&n({type:"SET_INSPECTOR_CONTEXT",context:{kind:"cell",cellId:i}})},[i,t.inspectorOpen,n]),p.useEffect(()=>{function S(h){var O;if(!i)return;const g=h.target;if(g.tagName==="TEXTAREA"||g.tagName==="INPUT"||g.isContentEditable||g.closest(".cm-editor")){a(null);return}const m=t.cells,I=m.findIndex(N=>N.id===i);if(I!==-1)switch(h.key){case"a":{h.preventDefault();const N=ct("sql");if(I===0)n({type:"ADD_CELL",cell:N,afterId:m[0].id}),n({type:"MOVE_CELL",id:N.id,direction:"up"});else{const x=m[I-1].id;n({type:"ADD_CELL",cell:N,afterId:x})}a(N.id);break}case"b":{h.preventDefault();const N=ct("sql");n({type:"ADD_CELL",cell:N,afterId:i}),a(N.id);break}case"d":{h.preventDefault();const N=Date.now();if(N-l.current<=500){if(n({type:"DELETE_CELL",id:i}),m.length>1){const x=I>0?I-1:1;a(((O=m[x])==null?void 0:O.id)??null)}else a(null);l.current=0}else l.current=N;break}case"Enter":{if(h.shiftKey){h.preventDefault();const N=m[I];N&&N.type!=="markdown"&&r(N.id)}break}}}return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[i,t.cells,n,r]),p.useEffect(()=>{function S(h){h.target.closest("[data-cell-id]")||a(null)}return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[]);const f=p.useCallback((S,h)=>{d(h),S.dataTransfer.effectAllowed="move",S.dataTransfer.setData("text/plain",String(h));const g=S.currentTarget;setTimeout(()=>{g.style.opacity="0.4"},0)},[]),T=p.useCallback(S=>{S.currentTarget.style.opacity="1",d(null),E(null)},[]),A=p.useCallback((S,h)=>{S.preventDefault(),S.dataTransfer.dropEffect="move",E(h)},[]),R=p.useCallback((S,h)=>{S.preventDefault(),c!==null&&c!==h&&n({type:"REORDER_CELL",fromIndex:c,toIndex:h}),d(null),E(null)},[c,n]);return t.cells.length===0?o.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[t.appMode==="studio"&&o.jsx(kc,{}),o.jsx(p5,{t:s})]}):o.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[t.appMode==="studio"&&o.jsx(kc,{afterId:void 0}),t.cells.map((S,h)=>o.jsxs(Be.Fragment,{children:[o.jsxs("div",{ref:g=>e(S.id,g),"data-cell-id":S.id,draggable:t.appMode==="studio",onDragStart:t.appMode==="studio"?g=>f(g,h):void 0,onDragEnd:t.appMode==="studio"?T:void 0,onDragOver:t.appMode==="studio"?g=>A(g,h):void 0,onDrop:t.appMode==="studio"?g=>R(g,h):void 0,onClick:g=>{const m=g.target;!m.closest(".cm-editor")&&!m.closest("textarea")&&!m.closest("input")&&a(S.id)},style:{outline:i===S.id?`2px solid ${s.accent}40`:"none",outlineOffset:2,borderRadius:10,transition:"outline 0.1s, transform 0.15s",position:"relative",...u===h&&c!==null&&c!==h?{borderTop:`2px solid ${s.accent}`}:{}},children:[o.jsx("div",{style:{position:"absolute",left:-20,top:8,width:16,height:24,display:"flex",alignItems:"center",justifyContent:"center",cursor:"grab",color:s.textMuted,opacity:0,transition:"opacity 0.15s",zIndex:5},className:"drag-handle",children:o.jsxs("svg",{width:"8",height:"14",viewBox:"0 0 8 14",fill:"currentColor",children:[o.jsx("circle",{cx:"2",cy:"2",r:"1.2"}),o.jsx("circle",{cx:"6",cy:"2",r:"1.2"}),o.jsx("circle",{cx:"2",cy:"7",r:"1.2"}),o.jsx("circle",{cx:"6",cy:"7",r:"1.2"}),o.jsx("circle",{cx:"2",cy:"12",r:"1.2"}),o.jsx("circle",{cx:"6",cy:"12",r:"1.2"})]})}),o.jsx(s5,{cell:S,index:h})]}),t.appMode==="studio"&&o.jsx(kc,{afterId:S.id})]},S.id)),o.jsx("style",{children:`
|
|
791
|
+
[data-cell-id]:hover .drag-handle { opacity: 0.5 !important; }
|
|
792
|
+
[data-cell-id]:hover .drag-handle:hover { opacity: 1 !important; }
|
|
793
|
+
`})]})}function p5({t:e}){return o.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"48px 0",gap:12,color:e.textMuted},children:[o.jsx("svg",{width:"40",height:"40",viewBox:"0 0 16 16",fill:"currentColor",style:{opacity:.3},children:o.jsx("path",{d:"M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 8.75 4.25V1.5ZM8.75 5.5h2.836L10.25 3.664V4.25c0 .138.112.25.25.25H8.75Z"})}),o.jsx("span",{style:{fontSize:13,fontFamily:e.font},children:"Empty notebook. Click + to add your first cell."})]})}function T5(){const{state:e}=Re(),t=ce[e.themeMode],n=e.cells.filter(r=>r.type==="markdown"||r.result&&r.status!=="running"||r.error);return o.jsx("div",{style:{flex:1,overflow:"auto",background:t.appBg,padding:"32px 24px 48px"},children:o.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",display:"flex",flexDirection:"column",gap:24},children:[o.jsxs("div",{style:{textAlign:"center",marginBottom:8},children:[o.jsx("h1",{style:{fontSize:28,fontWeight:700,color:t.textPrimary,fontFamily:t.font,letterSpacing:"-0.3px",margin:0},children:e.notebookTitle||"Untitled"}),o.jsxs("p",{style:{fontSize:12,color:t.textMuted,fontFamily:t.font,marginTop:6},children:[e.cells.filter(r=>r.result).length," results",e.activeFile?` · ${e.activeFile.path}`:""]})]}),n.length===0?o.jsx("div",{style:{textAlign:"center",padding:48,color:t.textMuted,fontSize:14,fontFamily:t.font},children:"No outputs to display. Run some cells first, then switch to dashboard mode."}):n.map(r=>o.jsx(S5,{cell:r},r.id))]})})}function S5({cell:e}){const{state:t}=Re(),n=ce[t.themeMode];if(e.type==="markdown")return o.jsx("div",{style:{background:n.cellBg,borderRadius:10,border:`1px solid ${n.cellBorder}`,padding:"16px 24px",fontSize:14,lineHeight:1.7,fontFamily:n.font,color:n.textSecondary,whiteSpace:"pre-wrap"},dangerouslySetInnerHTML:{__html:R5(e.content,n)}});if(e.error)return o.jsxs("div",{style:{background:n.cellBg,borderRadius:10,border:`1px solid ${n.error}40`,padding:"16px 24px"},children:[e.name&&o.jsx(h5,{name:e.name,t:n}),o.jsx("div",{style:{color:n.error,fontSize:12,fontFamily:n.fontMono,whiteSpace:"pre-wrap"},children:e.error})]});if(!e.result)return null;const r=pr(e.result,e.chartConfig),s=r!=="table";return o.jsxs("div",{style:{background:n.cellBg,borderRadius:10,border:`1px solid ${n.cellBorder}`,overflow:"hidden"},children:[o.jsxs("div",{style:{padding:"10px 20px",borderBottom:`1px solid ${n.cellBorder}`,display:"flex",alignItems:"center",gap:8},children:[e.name?o.jsx("span",{style:{fontSize:13,fontWeight:600,color:n.textPrimary,fontFamily:n.font,flex:1},children:e.name}):o.jsx("span",{style:{flex:1}}),o.jsxs("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.fontMono},children:[e.result.rowCount??e.result.rows.length," rows",e.result.executionTime!=null&&o.jsxs(o.Fragment,{children:[" · ",e.result.executionTime<1e3?`${e.result.executionTime}ms`:`${(e.result.executionTime/1e3).toFixed(1)}s`]})]})]}),o.jsx("div",{style:{padding:s?"16px 20px":0},children:s?Va(r,e.result,t.themeMode,e.chartConfig):o.jsx(Rn,{result:e.result,themeMode:t.themeMode})})]})}function h5({name:e,t}){return o.jsx("div",{style:{fontSize:13,fontWeight:600,color:t.textPrimary,fontFamily:t.font,marginBottom:8},children:e})}function R5(e,t){const n=r=>r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");return e.split(`
|
|
794
|
+
`).map(r=>{const s=r.trim(),i=s.match(/^(#{1,6})\s+(.+)$/);if(i){const l=i[1].length;return`<div style="font-size:${["28px","22px","18px","16px","14px","13px"][l-1]};font-weight:${l<=2?700:600};color:${t.textPrimary};margin:8px 0 4px">${n(i[2])}</div>`}if(/^[-*_]{3,}$/.test(s))return`<hr style="border:none;border-top:1px solid ${t.cellBorder};margin:8px 0"/>`;if(!s)return'<div style="height:6px"></div>';let a=n(s);return a=a.replace(/\*{2}(.+?)\*{2}/g,"<strong>$1</strong>"),a=a.replace(/\*(.+?)\*/g,"<em>$1</em>"),a=a.replace(/`(.+?)`/g,`<code style="background:${t.editorBg};padding:1px 4px;border-radius:3px;font-size:0.9em">$1</code>`),`<div style="margin-bottom:4px">${a}</div>`}).join("")}const Hg=[{value:"draft",label:"Draft",dot:"#f59e0b"},{value:"in_review",label:"In review",dot:"#5b8def"},{value:"certified",label:"Certified",dot:"#4ade80"},{value:"deprecated",label:"Deprecated",dot:"#ef4444"}];function A5(e){return e?Hg.find(t=>t.value===e)??{value:e,label:e,dot:"#888"}:null}function m5(){const{state:e,dispatch:t}=Re(),n=ce[e.themeMode],[r,s]=p.useState(null),i=p.useRef(null);if(p.useEffect(()=>{if(!r)return;const T=R=>{i.current&&!i.current.contains(R.target)&&s(null)},A=R=>{R.key==="Escape"&&s(null)};return document.addEventListener("mousedown",T),document.addEventListener("keydown",A),()=>{document.removeEventListener("mousedown",T),document.removeEventListener("keydown",A)}},[r]),!e.activeFile)return null;const a=e.activeFile.name.replace(/\.dqlnb$/,""),l=e.notebookMetadata,c=T=>{t({type:"UPDATE_NOTEBOOK_METADATA",updates:T})},d=A5(l.status),u=(l.categories??[]).length>0,E=!!l.description,f=!!l.projectFilter;return o.jsxs("div",{ref:i,style:{maxWidth:1080,margin:"0 auto",padding:"32px 48px 8px",display:"flex",flexDirection:"column",gap:12},children:[o.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,alignItems:"center",position:"relative"},children:[o.jsx(Ri,{t:n,active:r==="status",filled:!!d,icon:o.jsx("span",{style:{color:(d==null?void 0:d.dot)??n.textMuted,fontSize:12},children:"●"}),label:(d==null?void 0:d.label)??"Add status",onClick:()=>s(r==="status"?null:"status"),children:r==="status"&&o.jsxs(Ai,{t:n,children:[Hg.map(T=>o.jsxs("button",{onClick:()=>{c({status:T.value}),s(null)},style:xT(n,l.status===T.value),children:[o.jsx("span",{style:{color:T.dot,fontSize:12},children:"●"}),o.jsx("span",{children:T.label})]},T.value)),l.status&&o.jsx("button",{onClick:()=>{c({status:void 0}),s(null)},style:{...xT(n,!1),color:n.textMuted},children:o.jsx("span",{children:"Clear"})})]})}),o.jsx(Ri,{t:n,active:r==="categories",filled:u,icon:o.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10},children:"#"}),label:u?(l.categories??[]).slice(0,3).join(", ")+((l.categories??[]).length>3?"…":""):"Add categories",onClick:()=>s(r==="categories"?null:"categories"),children:r==="categories"&&o.jsx(Ai,{t:n,width:260,children:o.jsx(I5,{t:n,value:l.categories??[],onChange:T=>c({categories:T.length?T:void 0})})})}),o.jsx(Ri,{t:n,active:r==="description",filled:E,icon:o.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10},children:"✎"}),label:E?OT(l.description,48):"Add description",onClick:()=>s(r==="description"?null:"description"),children:r==="description"&&o.jsx(Ai,{t:n,width:320,children:o.jsx(NT,{multiline:!0,initial:l.description??"",onCommit:T=>c({description:T||void 0}),placeholder:"What does this notebook answer?",style:g5(n)})})}),o.jsx(Ri,{t:n,active:r==="projectFilter",filled:f,icon:o.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10},children:"⌕"}),label:f?OT(l.projectFilter,32):"Add project filter",onClick:()=>s(r==="projectFilter"?null:"projectFilter"),children:r==="projectFilter"&&o.jsx(Ai,{t:n,width:280,children:o.jsx(NT,{initial:l.projectFilter??"",onCommit:T=>c({projectFilter:T||void 0}),placeholder:"e.g. team:analytics",style:Wg(n)})})})]}),o.jsx("div",{style:{fontSize:22,fontWeight:600,color:n.textPrimary,fontFamily:n.font,letterSpacing:"-0.01em"},children:a})]})}function OT(e,t){return e.length>t?`${e.slice(0,t-1)}…`:e}function NT({initial:e,onCommit:t,multiline:n,placeholder:r,style:s}){const[i,a]=p.useState(e),l=p.useRef(i);l.current=i;const c=()=>{const d=l.current.trim();d!==e.trim()&&t(d)};return p.useEffect(()=>()=>c(),[]),n?o.jsx("textarea",{autoFocus:!0,value:i,onChange:d=>a(d.target.value),onBlur:c,placeholder:r,rows:4,style:s}):o.jsx("input",{autoFocus:!0,value:i,onChange:d=>a(d.target.value),onBlur:c,onKeyDown:d=>{d.key==="Enter"&&(d.preventDefault(),d.target.blur())},placeholder:r,style:s})}function Ri({t:e,active:t,filled:n,icon:r,label:s,onClick:i,children:a}){return o.jsxs("div",{style:{position:"relative"},children:[o.jsxs("button",{className:"dql-meta-pill",onClick:i,style:{display:"inline-flex",alignItems:"center",gap:6,padding:"3px 9px",borderRadius:12,border:n?`1px solid ${e.cellBorder}`:`1px dashed ${e.cellBorder}`,background:t?`${e.accent}12`:n?e.pillBg:"transparent",color:n?e.textPrimary:e.textMuted,fontSize:11,fontFamily:e.font,cursor:"pointer",transition:"background-color 80ms, border-color 80ms","--dql-pill-hover-bg":`${e.accent}10`,"--dql-pill-hover-border":e.textMuted},children:[r,o.jsx("span",{children:s})]}),a]})}function Ai({t:e,width:t=200,children:n}){return o.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,zIndex:20,width:t,background:e.modalBg,border:`1px solid ${e.cellBorder}`,borderRadius:6,padding:6,boxShadow:"0 8px 24px rgba(0,0,0,0.35)",display:"flex",flexDirection:"column",gap:4},children:n})}function xT(e,t){return{display:"inline-flex",alignItems:"center",gap:8,padding:"6px 8px",borderRadius:4,border:"none",background:t?`${e.accent}18`:"transparent",color:e.textPrimary,fontSize:12,fontFamily:e.font,textAlign:"left",cursor:"pointer"}}function g5(e){return{width:"100%",background:e.editorBg,border:`1px solid ${e.cellBorder}`,borderRadius:4,color:e.textPrimary,fontSize:12,fontFamily:e.font,padding:8,outline:"none",resize:"vertical"}}function Wg(e){return{width:"100%",background:e.editorBg,border:`1px solid ${e.cellBorder}`,borderRadius:4,color:e.textPrimary,fontSize:12,fontFamily:e.fontMono,padding:"6px 8px",outline:"none"}}function I5({t:e,value:t,onChange:n}){const[r,s]=p.useState(""),i=()=>{const a=r.trim();if(a){if(t.includes(a)){s("");return}n([...t,a]),s("")}};return o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.length>0&&o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:t.map(a=>o.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 6px",borderRadius:10,background:e.pillBg,border:`1px solid ${e.cellBorder}`,color:e.textPrimary,fontSize:11,fontFamily:e.font},children:[a,o.jsx("button",{onClick:()=>n(t.filter(l=>l!==a)),style:{background:"transparent",border:"none",color:e.textMuted,cursor:"pointer",padding:0,fontSize:12,lineHeight:1},"aria-label":`Remove ${a}`,children:"×"})]},a))}),o.jsx("input",{autoFocus:!0,value:r,onChange:a=>s(a.target.value),onKeyDown:a=>{a.key==="Enter"||a.key===","?(a.preventDefault(),i()):a.key==="Backspace"&&!r&&t.length>0&&n(t.slice(0,-1))},placeholder:"Add category, press Enter",style:Wg(e)})]})}function O5({onOpenFile:e,registerCellRef:t}){const{state:n}=Re(),r=ce[n.themeMode];return n.activeFile?n.dashboardMode?o.jsx(T5,{}):o.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",background:r.appBg},children:[o.jsx(N5,{t:r}),o.jsxs("div",{style:{flex:1,overflow:"auto",padding:"0 0 40px"},children:[o.jsx(m5,{}),o.jsx(f5,{registerCellRef:t})]})]}):o.jsx(d1,{onOpenFile:e})}function N5({t:e}){const{state:t}=Re(),n=t.cells.length;return o.jsxs("div",{style:{height:32,flexShrink:0,borderBottom:`1px solid ${e.headerBorder}`,background:e.cellBg,display:"flex",alignItems:"center",padding:"0 16px",gap:12},children:[o.jsx(x5,{t:e}),o.jsx("div",{style:{flex:1}}),o.jsxs("span",{style:{fontSize:11,color:e.textMuted,fontFamily:e.font,display:"flex",alignItems:"center",gap:12},children:[o.jsxs("span",{children:[n," ",n===1?"cell":"cells"]}),t.notebookDirty&&o.jsx("span",{style:{color:e.warning},children:"● unsaved"})]})]})}function x5({t:e}){const{state:t}=Re();if(!t.activeFile)return null;const n=t.activeFile.path.split("/").filter(Boolean);return o.jsx("div",{style:{display:"flex",alignItems:"center",gap:4,fontSize:12,fontFamily:e.fontMono,color:e.textMuted,overflow:"hidden"},children:n.map((r,s)=>o.jsxs(Be.Fragment,{children:[s>0&&o.jsx("span",{style:{color:e.textMuted,opacity:.5},children:"/"}),o.jsx("span",{style:{color:s===n.length-1?e.textSecondary:e.textMuted,fontWeight:s===n.length-1?500:400,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:s===n.length-1?200:100},children:r})]},s))})}const yT={blank:"Blank",revenue:"Revenue Analysis",pipeline:"Pipeline Health"},y5={blank:"Start with an empty notebook.",revenue:"Pre-built queries for revenue metrics and trends.",pipeline:"Templates for data pipeline health monitoring."};function CT(e){return e.toLowerCase().replace(/[^a-z0-9\-_\s]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,64)}function C5(e){return e.trim()?/^[a-zA-Z0-9\-_ ]+$/.test(e)?null:"Only letters, numbers, hyphens, underscores, and spaces allowed.":"Name is required."}function L5(e){switch(e){case"revenue":return[ct("markdown",`# Revenue Analysis
|
|
795
|
+
|
|
796
|
+
This notebook analyzes revenue metrics and trends over time.`),{...ct("sql",`SELECT
|
|
797
|
+
DATE_TRUNC('month', order_date) AS month,
|
|
798
|
+
SUM(amount) AS revenue
|
|
799
|
+
FROM orders
|
|
800
|
+
GROUP BY 1
|
|
801
|
+
ORDER BY 1`),name:"monthly_revenue"},{...ct("sql",`SELECT
|
|
802
|
+
product_category,
|
|
803
|
+
SUM(amount) AS total_revenue,
|
|
804
|
+
COUNT(*) AS orders
|
|
805
|
+
FROM orders
|
|
806
|
+
GROUP BY 1
|
|
807
|
+
ORDER BY 2 DESC`),name:"revenue_by_category"}];case"pipeline":return[ct("markdown",`# Pipeline Health
|
|
808
|
+
|
|
809
|
+
Monitor data pipeline performance, SLA compliance, and error rates.`),{...ct("sql",`SELECT
|
|
810
|
+
pipeline_name,
|
|
811
|
+
COUNT(*) AS runs,
|
|
812
|
+
AVG(duration_seconds) AS avg_duration,
|
|
813
|
+
SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failures
|
|
814
|
+
FROM pipeline_runs
|
|
815
|
+
GROUP BY 1
|
|
816
|
+
ORDER BY 4 DESC`),name:"pipeline_summary"},{...ct("sql",`SELECT
|
|
817
|
+
*
|
|
818
|
+
FROM pipeline_runs
|
|
819
|
+
WHERE status = 'failed'
|
|
820
|
+
AND run_date >= CURRENT_DATE - INTERVAL '7 days'
|
|
821
|
+
ORDER BY run_date DESC`),name:"recent_failures"}];default:return[ct("sql")]}}function _5({onFileOpened:e}){const{state:t,dispatch:n}=Re(),r=ce[t.themeMode],[s,i]=p.useState(""),[a,l]=p.useState("blank"),[c,d]=p.useState(null),[u,E]=p.useState(!1),f=p.useRef(null);p.useEffect(()=>{var R;(R=f.current)==null||R.focus()},[]),p.useEffect(()=>{const R=S=>{S.key==="Escape"&&n({type:"CLOSE_NEW_NOTEBOOK_MODAL"})};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[n]);const T=async()=>{const R=C5(s);if(R){d(R);return}E(!0),d(null);const S=CT(s),h=L5(a);try{const g=await $.createNotebook(S,a),m={name:`${S}.dqlnb`,path:g.path,type:"notebook",folder:"notebooks",isNew:!0};n({type:"FILE_ADDED",file:m}),n({type:"OPEN_FILE",file:m,cells:h,title:s.trim()}),n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),e(m)}catch{const g=`notebooks/${S}.dqlnb`,m={name:`${S}.dqlnb`,path:g,type:"notebook",folder:"notebooks",isNew:!0};n({type:"FILE_ADDED",file:m}),n({type:"OPEN_FILE",file:m,cells:h,title:s.trim()}),n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),e(m)}finally{E(!1)}},A=R=>{R.target===R.currentTarget&&n({type:"CLOSE_NEW_NOTEBOOK_MODAL"})};return o.jsx("div",{onClick:A,style:{position:"fixed",inset:0,background:r.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(4px)"},children:o.jsxs("div",{style:{background:r.modalBg,border:`1px solid ${r.cellBorder}`,borderRadius:12,width:480,maxWidth:"calc(100vw - 48px)",boxShadow:"0 20px 60px rgba(0,0,0,0.5)",overflow:"hidden"},children:[o.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsx("h2",{style:{fontSize:16,fontWeight:600,color:r.textPrimary,fontFamily:r.font,margin:0},children:"New Notebook"}),o.jsx("button",{onClick:()=>n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),style:{background:"transparent",border:"none",cursor:"pointer",color:r.textMuted,fontSize:18,lineHeight:1,padding:"2px 4px",borderRadius:4},children:"×"})]}),o.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:20},children:[o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[o.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Name"}),o.jsx("input",{ref:f,value:s,onChange:R=>{i(R.target.value),d(null)},onKeyDown:R=>{R.key==="Enter"&&T()},placeholder:"my-analysis",style:{background:r.inputBg,border:`1px solid ${c?r.error:r.inputBorder}`,borderRadius:6,color:r.textPrimary,fontSize:13,fontFamily:r.font,padding:"8px 12px",outline:"none",transition:"border-color 0.15s"}}),c&&o.jsx("span",{style:{fontSize:11,color:r.error,fontFamily:r.font},children:c}),s&&!c&&o.jsxs("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.fontMono},children:["File: ",CT(s),".dqlnb"]})]}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[o.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Template"}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:Object.keys(yT).map(R=>o.jsx(b5,{value:R,selected:a===R,onSelect:()=>l(R),label:yT[R],description:y5[R],t:r},R))})]})]}),o.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${r.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[o.jsx("button",{onClick:()=>n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),style:{background:r.btnBg,border:`1px solid ${r.btnBorder}`,borderRadius:6,color:r.textSecondary,cursor:"pointer",fontSize:13,fontFamily:r.font,fontWeight:500,padding:"7px 16px"},children:"Cancel"}),o.jsx("button",{onClick:T,disabled:u||!s.trim(),style:{background:r.accent,border:`1px solid ${r.accent}`,borderRadius:6,color:"#ffffff",cursor:u||!s.trim()?"not-allowed":"pointer",fontSize:13,fontFamily:r.font,fontWeight:500,padding:"7px 20px",opacity:u||!s.trim()?.6:1,display:"flex",alignItems:"center",gap:6},children:u?"Creating…":"Create Notebook"})]})]})})}function b5({value:e,selected:t,onSelect:n,label:r,description:s,t:i}){const[a,l]=p.useState(!1);return o.jsxs("div",{onClick:n,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{display:"flex",alignItems:"flex-start",gap:10,padding:"10px 12px",borderRadius:8,border:`1px solid ${t?i.cellBorderActive:a?i.textMuted:i.inputBorder}`,background:t?`${i.cellBorderActive}10`:a?i.sidebarItemHover:"transparent",cursor:"pointer",transition:"all 0.15s"},children:[o.jsx("div",{style:{width:16,height:16,borderRadius:8,border:`2px solid ${t?i.accent:i.textMuted}`,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:1,transition:"border-color 0.15s"},children:t&&o.jsx("div",{style:{width:8,height:8,borderRadius:4,background:i.accent}})}),o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:13,fontWeight:500,color:i.textPrimary,fontFamily:i.font,marginBottom:2},children:r}),o.jsx("div",{style:{fontSize:12,color:i.textSecondary,fontFamily:i.font},children:s})]})]})}function LT(e){return e.toLowerCase().replace(/[^a-z0-9\-_\s]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,64)}function v5(e){return e.trim()?/^[a-zA-Z0-9\-_ ]+$/.test(e)?null:"Only letters, numbers, hyphens, underscores, and spaces allowed.":"Name is required."}function D5({onFileOpened:e}){const{state:t,dispatch:n}=Re(),r=ce[t.themeMode],[s,i]=p.useState(""),[a,l]=p.useState(t.newBlockModalDefaultType),[c,d]=p.useState(null),[u,E]=p.useState(!1),f=p.useRef(null);p.useEffect(()=>{var R;(R=f.current)==null||R.focus()},[]),p.useEffect(()=>{l(t.newBlockModalDefaultType)},[t.newBlockModalDefaultType]),p.useEffect(()=>{const R=S=>{S.key==="Escape"&&n({type:"CLOSE_NEW_BLOCK_MODAL"})};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[n]);const T=async()=>{var h;const R=v5(s);if(R){d(R);return}E(!0),d(null);const S=LT(s);try{const g=await $.createBlock(s.trim(),{blockType:a}),m={name:`${S}.dql`,path:g.path,type:"block",folder:"blocks",isNew:!0};n({type:"FILE_ADDED",file:m}),n({type:"CLOSE_NEW_BLOCK_MODAL"}),e(m)}catch(g){(h=g.message)!=null&&h.includes("already exists")?d("A block with this name already exists."):d(g.message??"Failed to create block.")}finally{E(!1)}},A=R=>{R.target===R.currentTarget&&n({type:"CLOSE_NEW_BLOCK_MODAL"})};return o.jsx("div",{onClick:A,style:{position:"fixed",inset:0,background:r.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(4px)"},children:o.jsxs("div",{style:{background:r.modalBg,border:`1px solid ${r.cellBorder}`,borderRadius:12,width:420,maxWidth:"calc(100vw - 48px)",boxShadow:"0 20px 60px rgba(0,0,0,0.5)",overflow:"hidden"},children:[o.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsx("h2",{style:{fontSize:16,fontWeight:600,color:r.textPrimary,fontFamily:r.font,margin:0},children:"New Block"}),o.jsx("button",{onClick:()=>n({type:"CLOSE_NEW_BLOCK_MODAL"}),style:{background:"transparent",border:"none",cursor:"pointer",color:r.textMuted,fontSize:18,lineHeight:1,padding:"2px 4px",borderRadius:4},children:"×"})]}),o.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:16},children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[o.jsxs("button",{type:"button",onClick:()=>l("custom"),style:{background:a==="custom"?`${r.accent}18`:r.btnBg,border:`1px solid ${a==="custom"?r.accent:r.btnBorder}`,borderRadius:8,color:a==="custom"?r.accent:r.textSecondary,cursor:"pointer",fontSize:12,fontWeight:700,fontFamily:r.font,padding:"10px 12px",textAlign:"left"},children:["SQL Block",o.jsx("span",{style:{display:"block",marginTop:3,color:r.textMuted,fontWeight:400,fontSize:11},children:"Build from dbt models, tables, and SELECT queries."})]}),o.jsxs("button",{type:"button",onClick:()=>l("semantic"),style:{background:a==="semantic"?`${r.accent}18`:r.btnBg,border:`1px solid ${a==="semantic"?r.accent:r.btnBorder}`,borderRadius:8,color:a==="semantic"?r.accent:r.textSecondary,cursor:"pointer",fontSize:12,fontWeight:700,fontFamily:r.font,padding:"10px 12px",textAlign:"left"},children:["Semantic Block",o.jsx("span",{style:{display:"block",marginTop:3,color:r.textMuted,fontWeight:400,fontSize:11},children:"Build from dbt/DQL metrics and dimensions."})]})]}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[o.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Block Name"}),o.jsx("input",{ref:f,value:s,onChange:R=>{i(R.target.value),d(null)},onKeyDown:R=>{R.key==="Enter"&&T()},placeholder:"revenue-summary",style:{background:r.inputBg,border:`1px solid ${c?r.error:r.inputBorder}`,borderRadius:6,color:r.textPrimary,fontSize:13,fontFamily:r.font,padding:"8px 12px",outline:"none",transition:"border-color 0.15s"}}),c&&o.jsx("span",{style:{fontSize:11,color:r.error,fontFamily:r.font},children:c}),s&&!c&&o.jsxs("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.fontMono},children:["blocks/",LT(s),".dql"]})]}),o.jsx("div",{style:{fontSize:12,color:r.textMuted,fontFamily:r.font,lineHeight:1.5,padding:"8px 12px",background:r.pillBg,borderRadius:6},children:a==="semantic"?"Semantic blocks use governed metrics, dimensions, and chart intent. They do not start with raw SQL.":"SQL blocks are reusable SELECT queries stored in the blocks/ folder. Use them for dbt models, tables, and imported SQL."})]}),o.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${r.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[o.jsx("button",{onClick:()=>n({type:"CLOSE_NEW_BLOCK_MODAL"}),style:{background:r.btnBg,border:`1px solid ${r.btnBorder}`,borderRadius:6,color:r.textSecondary,cursor:"pointer",fontSize:13,fontFamily:r.font,fontWeight:500,padding:"7px 16px"},children:"Cancel"}),o.jsx("button",{onClick:T,disabled:u||!s.trim(),style:{background:r.accent,border:`1px solid ${r.accent}`,borderRadius:6,color:"#ffffff",cursor:u||!s.trim()?"not-allowed":"pointer",fontSize:13,fontFamily:r.font,fontWeight:500,padding:"7px 20px",opacity:u||!s.trim()?.6:1,display:"flex",alignItems:"center",gap:6},children:u?"Creating...":"Create Block"})]})]})})}function M5({item:e,favorite:t,onInsert:n,onPreview:r,onCopySql:s,onToggleFavorite:i,t:a}){if(!e)return null;const l=e.kind==="metric"||e.kind==="dimension",c=!!e.sql,d=e.source?`${e.source.provider} · ${e.source.objectType}`:null;return o.jsxs("div",{style:{borderTop:`1px solid ${a.headerBorder}`,padding:"12px 10px",display:"flex",flexDirection:"column",gap:10,background:`${a.cellBg}cc`},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsx("div",{style:{fontSize:12,fontWeight:600,color:a.textPrimary,fontFamily:a.font},children:e.label||e.name}),o.jsxs("div",{style:{fontSize:10,color:a.textMuted,fontFamily:a.fontMono},children:[e.kind," · ",e.name]})]}),o.jsx("button",{onClick:i,style:{background:t?"#e3b34122":"transparent",border:`1px solid ${t?"#e3b34166":a.cellBorder}`,borderRadius:6,color:t?"#e3b341":a.textMuted,cursor:"pointer",fontSize:11,fontFamily:a.font,padding:"4px 8px"},children:t?"Favorited":"Favorite"})]}),e.description&&o.jsx("div",{style:{fontSize:12,color:a.textSecondary,fontFamily:a.font,lineHeight:1.5},children:e.description}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,fontSize:11,fontFamily:a.fontMono,color:a.textMuted},children:[o.jsxs("div",{children:["domain: ",e.domain||"uncategorized"]}),o.jsxs("div",{children:["owner: ",e.owner??"unassigned"]}),e.table?o.jsxs("div",{children:["table: ",e.table]}):o.jsx("div",{}),e.cube?o.jsxs("div",{children:["cube: ",e.cube]}):o.jsx("div",{}),e.type?o.jsxs("div",{children:["type: ",e.type]}):o.jsx("div",{}),d?o.jsxs("div",{children:["source: ",d]}):o.jsx("div",{})]}),e.tags.length>0&&o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:e.tags.map(u=>o.jsx("span",{style:{fontSize:10,color:a.textMuted,background:a.pillBg,borderRadius:999,padding:"2px 8px",fontFamily:a.font},children:u},u))}),e.sql&&o.jsxs("div",{style:{position:"relative"},children:[o.jsx("pre",{style:{margin:0,padding:"8px 10px",paddingRight:32,background:a.editorBg,border:`1px solid ${a.cellBorder}`,borderRadius:6,fontSize:10,fontFamily:a.fontMono,color:a.textSecondary,overflowX:"auto",whiteSpace:"pre-wrap"},children:e.sql}),o.jsx("button",{onClick:s,title:"Copy SQL",style:{position:"absolute",top:6,right:6,background:a.btnBg,border:`1px solid ${a.cellBorder}`,borderRadius:4,color:a.textMuted,cursor:"pointer",fontSize:10,fontFamily:a.font,padding:"2px 6px",opacity:.7,lineHeight:1},children:"Copy"})]}),e.joins&&e.joins.length>0&&o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[o.jsx("div",{style:{fontSize:11,fontWeight:600,color:a.textSecondary,fontFamily:a.font},children:"Joins"}),e.joins.map(u=>o.jsxs("div",{style:{fontSize:10,color:a.textMuted,fontFamily:a.fontMono},children:[u.left," ",u.type," ",u.right]},u.name))]}),e.levels&&e.levels.length>0&&o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[o.jsx("div",{style:{fontSize:11,fontWeight:600,color:a.textSecondary,fontFamily:a.font},children:"Levels"}),e.levels.map(u=>o.jsxs("div",{style:{fontSize:10,color:a.textMuted,fontFamily:a.fontMono},children:[u.order,". ",u.label," → ",u.dimension]},u.name))]}),o.jsxs("div",{style:{display:"flex",gap:8},children:[o.jsx("button",{onClick:r,disabled:!c,style:{flex:1,background:a.btnBg,border:`1px solid ${a.btnBorder}`,borderRadius:6,color:a.textSecondary,cursor:"pointer",fontSize:11,fontFamily:a.font,padding:"6px 10px"},children:"Preview Data"}),o.jsx("button",{onClick:s,disabled:!e.sql,style:{flex:1,background:a.btnBg,border:`1px solid ${a.btnBorder}`,borderRadius:6,color:a.textSecondary,cursor:"pointer",fontSize:11,fontFamily:a.font,padding:"6px 10px"},children:"Copy SQL"}),o.jsx("button",{onClick:n,disabled:!l,style:{flex:1,background:a.accent,border:`1px solid ${a.accent}`,borderRadius:6,color:"#fff",cursor:"pointer",fontSize:11,fontFamily:a.font,padding:"6px 10px"},children:l?"Insert":"Inspect"})]})]})}function P5({query:e,provider:t,cube:n,owner:r,domain:s,tag:i,type:a,providers:l,cubes:c,owners:d,domains:u,tags:E,onQueryChange:f,onProviderChange:T,onCubeChange:A,onOwnerChange:R,onDomainChange:S,onTagChange:h,onTypeChange:g,t:m}){const I=(t?1:0)+(s?1:0)+(n?1:0)+(r?1:0)+(i?1:0)+(a?1:0),[O,N]=p.useState(I>0),x={width:"100%",background:m.inputBg,border:`1px solid ${m.inputBorder}`,borderRadius:6,color:m.textPrimary,fontSize:12,fontFamily:m.font,padding:"7px 10px",outline:"none",boxSizing:"border-box"},_=()=>{T(""),S(""),A(""),R(""),h(""),g("")};return o.jsxs("div",{style:{padding:"10px",display:"flex",flexDirection:"column",gap:8,borderBottom:`1px solid ${m.headerBorder}`},children:[o.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[o.jsx("input",{value:e,onChange:C=>f(C.target.value),placeholder:"Search labels, cubes, owners, tags...",style:{...x,flex:1}}),o.jsxs("button",{onClick:()=>N(C=>!C),style:{background:I>0?`${m.accent}18`:"transparent",border:`1px solid ${I>0?m.accent:m.inputBorder}`,borderRadius:6,color:I>0?m.accent:m.textMuted,cursor:"pointer",fontSize:11,fontFamily:m.font,padding:"6px 10px",whiteSpace:"nowrap"},title:O?"Hide filters":"Show filters",children:["Filters",I>0?` · ${I}`:""]})]}),O&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:6},children:[o.jsxs("select",{value:t,onChange:C=>T(C.target.value),style:x,children:[o.jsx("option",{value:"",children:"All providers"}),l.map(C=>o.jsx("option",{value:C,children:C},C))]}),o.jsxs("select",{value:s,onChange:C=>S(C.target.value),style:x,children:[o.jsx("option",{value:"",children:"All domains"}),u.map(C=>o.jsx("option",{value:C,children:C},C))]}),o.jsxs("select",{value:n,onChange:C=>A(C.target.value),style:x,children:[o.jsx("option",{value:"",children:"All cubes"}),c.map(C=>o.jsx("option",{value:C,children:C},C))]}),o.jsxs("select",{value:r,onChange:C=>R(C.target.value),style:x,children:[o.jsx("option",{value:"",children:"All owners"}),d.map(C=>o.jsx("option",{value:C,children:C},C))]}),o.jsxs("select",{value:i,onChange:C=>h(C.target.value),style:x,children:[o.jsx("option",{value:"",children:"All tags"}),E.map(C=>o.jsx("option",{value:C,children:C},C))]}),o.jsxs("select",{value:a,onChange:C=>g(C.target.value),style:x,children:[o.jsx("option",{value:"",children:"All types"}),o.jsx("option",{value:"cube",children:"Cubes"}),o.jsx("option",{value:"metric",children:"Metrics"}),o.jsx("option",{value:"dimension",children:"Dimensions"}),o.jsx("option",{value:"hierarchy",children:"Hierarchies"}),o.jsx("option",{value:"segment",children:"Segments"}),o.jsx("option",{value:"pre_aggregation",children:"Pre-aggregations"})]})]}),I>0&&o.jsx("button",{onClick:_,style:{alignSelf:"flex-start",background:"transparent",border:"none",color:m.textMuted,cursor:"pointer",fontSize:11,fontFamily:m.font,padding:0,textDecoration:"underline"},children:"Clear filters"})]})]})}function bd({label:e,depth:t=0,badge:n,badgeColor:r,count:s,expanded:i,favorite:a,selected:l,onClick:c,onDoubleClick:d,onToggle:u,onFavoriteToggle:E,onDragStart:f,title:T,muted:A,t:R}){const[S,h]=p.useState(!1);return o.jsxs("button",{draggable:!!f,onDragStart:f,onClick:c,onDoubleClick:d,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),title:T,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:`5px 8px 5px ${10+t*14}px`,background:l?`${R.accent}18`:S?R.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:A?R.textMuted:R.textPrimary,fontSize:12,fontFamily:R.font,textAlign:"left"},children:[u?o.jsx("span",{onClick:g=>{g.stopPropagation(),u()},style:{display:"inline-flex",transform:i?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.15s",color:R.textMuted},children:o.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:o.jsx("path",{d:"M3 2l4 3-4 3V2Z"})})}):o.jsx("span",{style:{width:10,flexShrink:0}}),o.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e}),n&&o.jsx("span",{style:{fontSize:9,fontFamily:R.fontMono,color:r??R.accent,background:`${r??R.accent}18`,borderRadius:4,padding:"1px 4px",flexShrink:0},children:n}),typeof s=="number"&&o.jsx("span",{style:{fontSize:10,color:R.textMuted,background:R.pillBg,borderRadius:999,padding:"1px 6px",flexShrink:0},children:s}),typeof a=="boolean"&&o.jsx("span",{onClick:g=>{g.stopPropagation(),E==null||E()},style:{color:a?"#e3b341":R.textMuted,display:"inline-flex",flexShrink:0},children:o.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M8 1.25l1.938 3.927 4.335.63-3.136 3.056.74 4.318L8 11.143l-3.877 2.038.74-4.318L1.727 5.807l4.335-.63L8 1.25Z"})})})]})}const mi=31,_T=10;function w5(){var Hs,Zn,Ws,Do,Ys,$s,Ur,Vs,zs,Mo,nE;const{state:e,dispatch:t}=Re(),n=ce[e.themeMode],[r,s]=p.useState("semantic"),[i,a]=p.useState("validate"),[l,c]=p.useState(""),[d,u]=p.useState(""),[E,f]=p.useState(""),[T,A]=p.useState(""),[R,S]=p.useState(""),[h,g]=p.useState(""),[m,I]=p.useState(""),[O,N]=p.useState({}),[x,_]=p.useState(null),[C,v]=p.useState(null),[b,P]=p.useState([]),[j,L]=p.useState({}),[B,M]=p.useState(""),[U,D]=p.useState(new Set),[y,w]=p.useState(!1),[F,k]=p.useState(!1),[V,ee]=p.useState(null),[Y,te]=p.useState(null),[ne,z]=p.useState([]),[oe,le]=p.useState(!1),[ae,X]=p.useState(null),[H,re]=p.useState(!1),[ie,de]=p.useState(!1),[se,ge]=p.useState(null),[xe,Fe]=p.useState(null),[Z,Ee]=p.useState(null),[Oe,ve]=p.useState(!1),[Le,Tt]=p.useState(0),[yt,St]=p.useState(400),[Ct,mn]=p.useState(300),[an,ht]=p.useState(420),[Wt,Xn]=p.useState(!1),[Yt,Kn]=p.useState(!1),[Lt,Lr]=p.useState(null),[_r,qn]=p.useState([]),[br,Jn]=p.useState(!1),[K,ue]=p.useState(null),[Ye,Ue]=p.useState(null),[Co,vr]=p.useState(!1),[Dr,Lo]=p.useState(null),Mr=p.useRef(null),ws=p.useRef(e.activeBlockPath);p.useEffect(()=>{t({type:"SET_BLOCK_STUDIO_CATALOG_LOADING",loading:!0}),te(null),Promise.allSettled([$.getBlockStudioCatalog(),$.getBlockStudioDbtStatus()]).then(([G,Te])=>{G.status==="fulfilled"?(t({type:"SET_BLOCK_STUDIO_CATALOG",catalog:G.value}),P(G.value.databaseTree)):te("Failed to load schema. Check your connection and try refreshing."),t({type:"SET_BLOCK_STUDIO_DBT_STATUS",status:Te.status==="fulfilled"?Te.value:null})}).finally(()=>t({type:"SET_BLOCK_STUDIO_CATALOG_LOADING",loading:!1}))},[t]);const Pr=p.useCallback(async()=>{Jn(!0);try{const G=await $.listBlockStudioImports();qn(G.sessions??[])}catch{qn([])}finally{Jn(!1)}},[]);p.useEffect(()=>{Pr()},[Pr]),p.useEffect(()=>{const G=ws.current,Te=e.activeBlockPath;Te&&Te!==G&&t({type:"CLOSE_BLOCK_IMPORT"}),ws.current=Te},[e.activeBlockPath,t]),p.useEffect(()=>{if(!x||x.startsWith("provider:")||x.startsWith("domain:")||x.startsWith("group:")){v(null);return}$.getSemanticObject(x).then(v).catch(()=>v(null))},[x]),p.useEffect(()=>{const G=window.setTimeout(()=>{e.blockStudioDraft.trim()&&$.validateBlockStudio(e.blockStudioDraft,e.activeBlockPath).then(Te=>t({type:"SET_BLOCK_STUDIO_VALIDATION",validation:Te})).catch(()=>{})},250);return()=>window.clearTimeout(G)},[e.blockStudioDraft,e.activeBlockPath,t]);const _o=((Hs=e.blockStudioCatalog)==null?void 0:Hs.semanticTree)??null,_t=p.useMemo(()=>aV(_o)?_o:lV(e.semanticLayer),[_o,e.semanticLayer]),cl=p.useMemo(()=>Gc(_t,"provider"),[_t]),dl=p.useMemo(()=>Gc(_t,"cube"),[_t]),ul=p.useMemo(()=>Gc(_t,"owner"),[_t]),wr=p.useMemo(()=>_t?$g(_t,{query:l,provider:d,domain:E,cube:T,owner:R,tag:h,type:m}):null,[_t,l,d,E,T,R,h,m]),Qn=p.useMemo(()=>Vg((wr==null?void 0:wr.children)??[],O),[wr,O]),Us=p.useMemo(()=>sV(b,B),[b,B]),bo=p.useMemo(()=>iV(b),[b]),$t={metrics:e.semanticLayer.metrics.length,measures:e.semanticLayer.measures.length,dimensions:e.semanticLayer.dimensions.length,timeDimensions:e.semanticLayer.timeDimensions.length,entities:e.semanticLayer.entities.length,hierarchies:e.semanticLayer.hierarchies.length,savedQueries:e.semanticLayer.savedQueries.length},El=Qn.length*mi,Bs=p.useMemo(()=>{const G=Math.max(0,Math.floor(Le/mi)-_T),Te=Math.min(Qn.length,Math.ceil((Le+yt)/mi)+_T);return{offsetTop:G*mi,rows:Qn.slice(G,Te)}},[Qn,Le,yt]);p.useEffect(()=>{const G=Mr.current;if(!G)return;const Te=()=>St(G.clientHeight||400);if(Te(),typeof ResizeObserver>"u")return window.addEventListener("resize",Te),()=>window.removeEventListener("resize",Te);const je=new ResizeObserver(()=>Te());return je.observe(G),()=>je.disconnect()},[]),p.useEffect(()=>{Tt(0),Mr.current&&(Mr.current.scrollTop=0)},[l,d,E,T,R,h,m]);const Je=p.useMemo(()=>{var Te;const G=Fb(e.blockStudioDraft);return e.blockStudioMetadata?{...G,name:(G==null?void 0:G.name)||e.blockStudioMetadata.name,domain:(G==null?void 0:G.domain)||e.blockStudioMetadata.domain,description:(G==null?void 0:G.description)||e.blockStudioMetadata.description,owner:(G==null?void 0:G.owner)||e.blockStudioMetadata.owner,tags:(Te=G==null?void 0:G.tags)!=null&&Te.length?G.tags:e.blockStudioMetadata.tags,blockType:(G==null?void 0:G.blockType)||"custom",status:(G==null?void 0:G.status)||e.blockStudioMetadata.reviewStatus||"draft"}:G},[e.blockStudioDraft,e.blockStudioMetadata]),gn=(Je==null?void 0:Je.name)??((Zn=e.blockStudioMetadata)==null?void 0:Zn.name)??null,Vt=((Je==null?void 0:Je.blockType)??"custom")==="semantic",js=!!(e.blockStudioDraft.trim()||e.blockStudioMetadata||e.activeBlockPath);p.useEffect(()=>{if(!gn)return;const G=`block:${gn}`;t({type:"SET_LINEAGE_FOCUS",nodeId:G}),de(!0),Promise.all([$.fetchLineageNode(G),$.queryLineage({focus:G}),$.fetchLineagePaths(G)]).then(([Te,je,De])=>{ge(Te),Fe(je.graph??null),Ee(De)}).catch(()=>{ge(null),Fe(null),Ee(null)}).finally(()=>de(!1))},[gn,t]);const Rt=G=>{t({type:"SET_BLOCK_STUDIO_DRAFT",draft:G})},ks=async()=>{var G,Te,je;w(!0);try{const De=await $.runBlockStudio(e.blockStudioDraft,e.activeBlockPath);t({type:"SET_BLOCK_STUDIO_PREVIEW",preview:De}),a("results")}catch(De){t({type:"SET_BLOCK_STUDIO_VALIDATION",validation:{valid:!1,chartConfig:(G=e.blockStudioValidation)==null?void 0:G.chartConfig,executableSql:((Te=e.blockStudioValidation)==null?void 0:Te.executableSql)??null,semanticRefs:((je=e.blockStudioValidation)==null?void 0:je.semanticRefs)??{metrics:[],dimensions:[],segments:[]},diagnostics:[{severity:"error",code:"block_run_failed",message:De instanceof Error?De.message:String(De)}]}}),a("validate")}finally{w(!1)}},fl=async()=>{if(!e.blockStudioMetadata){t({type:"OPEN_NEW_BLOCK_MODAL"});return}k(!0),ee(null);try{const G=await $.saveBlockStudio({path:e.activeBlockPath,source:e.blockStudioDraft,metadata:{name:e.blockStudioMetadata.name,domain:e.blockStudioMetadata.domain,description:e.blockStudioMetadata.description,owner:e.blockStudioMetadata.owner,tags:e.blockStudioMetadata.tags,sourceKind:e.blockStudioMetadata.sourceKind,sourcePath:e.blockStudioMetadata.sourcePath,importId:e.blockStudioMetadata.importId,candidateId:e.blockStudioMetadata.candidateId,lineage:e.blockStudioMetadata.lineage}});t({type:"OPEN_BLOCK_STUDIO",file:{name:`${G.metadata.name}.dql`,path:G.path,type:"block",folder:"blocks"},payload:G}),e.files.some(je=>je.path===G.path)||t({type:"FILE_ADDED",file:{name:`${G.metadata.name}.dql`,path:G.path,type:"block",folder:"blocks"}}),a("save")}catch(G){const Te=(G==null?void 0:G.message)??"Save failed";ee(Te.includes("409")||Te.includes("BLOCK_EXISTS")?"A block with this name already exists. Rename and try again.":Te),setTimeout(()=>ee(null),5e3)}finally{k(!1)}},pl=async()=>{if(!(!e.activeBlockPath||!e.blockStudioMetadata)){ve(!0);try{const G=await $.updateBlockStatus(e.activeBlockPath,"review");G.ok&&G.status&&(t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,reviewStatus:G.status}}),t({type:"SET_BLOCK_STUDIO_DRAFT",draft:Gr(e.blockStudioDraft,"status",G.status)}),Lo(null))}finally{ve(!1)}}},Tl=async()=>{if(!(!e.activeBlockPath||!e.blockStudioDraft.trim())){vr(!0);try{const G=await $.certifyBlockStudio({source:e.blockStudioDraft,path:e.activeBlockPath});Lo(G),G.ok&&G.status&&e.blockStudioMetadata&&(t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,reviewStatus:G.status}}),t({type:"SET_BLOCK_STUDIO_DRAFT",draft:Gr(e.blockStudioDraft,"status",G.status)})),a("save")}catch(G){let Te=null;try{Te=JSON.parse((G==null?void 0:G.message)??"")}catch{}Lo(Te??{ok:!1,error:(G==null?void 0:G.message)??"Certification failed"}),a("save")}finally{vr(!1)}}},Sl=G=>{var je,De;const Te={path:"",source:G.dqlSource,metadata:{name:G.name,path:null,domain:G.domain,description:G.description,owner:G.owner,tags:G.tags,reviewStatus:G.reviewStatus,sourceKind:G.sourceKind,sourcePath:G.sourcePath,importId:Lt==null?void 0:Lt.id,candidateId:G.id,lineage:G.lineage.sourceTables},companionPath:null,validation:G.validation??{valid:!0,diagnostics:[],semanticRefs:{metrics:[],dimensions:[],segments:[]},executableSql:null}};t({type:"OPEN_BLOCK_STUDIO",file:{name:`${G.name}.dql`,path:"",type:"block",folder:"blocks",isNew:!0},payload:Te}),t({type:"SET_BLOCK_STUDIO_PREVIEW",preview:G.preview}),a((De=(je=G.validation)==null?void 0:je.diagnostics)!=null&&De.length?"validate":"results"),t({type:"CLOSE_BLOCK_IMPORT"})},hl=(G,Te)=>{e.files.some(De=>De.path===Te.path)||t({type:"FILE_ADDED",file:{name:`${Te.metadata.name}.dql`,path:Te.path,type:"block",folder:"blocks"}}),Lt&&Lr({...Lt,candidates:Lt.candidates.map(De=>De.id===G.id?G:De)}),Pr()},vo=G=>{if(Ue(null),G.kind==="metric"||G.kind==="dimension"){Vt?(Rt(Wb(e.blockStudioDraft,{kind:G.kind==="metric"?"metric":"dimension",name:G.name})),ue(null)):ue(G),t({type:"ADD_SEMANTIC_RECENT",name:G.name});return}if(!Vt){ue(G);return}if(G.kind==="segment"&&G.sql){Rt(gi(e.blockStudioDraft,`/* segment:${G.name} */ (${G.sql})`));return}G.kind==="pre_aggregation"&&Rt(gi(e.blockStudioDraft,`/* pre_aggregation:${G.name} */`))},Rl=G=>{if(ue(null),Vt){Ue("Database tables and SELECT snippets belong in SQL blocks. Use a SQL Block for raw SELECT work, or keep this Semantic Block on metrics and dimensions.");return}Rt(gi(e.blockStudioDraft,G))},Al=async G=>{if(!(!G.path||G.kind!=="table"||G.children&&G.children.length>0)){D(Te=>new Set(Te).add(G.id));try{const Te=await $.describeTable(G.path);P(je=>zg(je,G.id,{...G,children:Te.map(De=>({id:`db-column:${G.path}:${De.name}`,label:De.name,kind:"column",path:G.path,type:De.type}))}))}finally{D(Te=>{const je=new Set(Te);return je.delete(G.id),je})}}},Fs=p.useCallback(async()=>{try{const G=await $.getBlockStudioCatalog();G!=null&&G.databaseTree&&P(G.databaseTree),t({type:"SET_BLOCK_STUDIO_CATALOG",catalog:G})}catch{}},[t]),Gs=((Ws=e.blockStudioValidation)==null?void 0:Ws.chartConfig)??((Do=e.blockStudioPreview)==null?void 0:Do.chartConfig)??{chart:"table"},ml=e.blockStudioPreview?pr(e.blockStudioPreview.result,e.blockStudioPreview.chartConfig):"table",gl=G=>{G.preventDefault();const Te=G.clientX,je=Ct,De=Ol=>{const Nl=Math.min(520,Math.max(280,je+Ol.clientX-Te));mn(Nl)},Po=()=>{window.removeEventListener("mousemove",De),window.removeEventListener("mouseup",Po)};window.addEventListener("mousemove",De),window.addEventListener("mouseup",Po)},Il=G=>{G.preventDefault();const Te=G.clientY,je=an,De=Ol=>{const Nl=Math.min(520,Math.max(180,je-(Ol.clientY-Te)));ht(Nl)},Po=()=>{window.removeEventListener("mousemove",De),window.removeEventListener("mouseup",Po)};window.addEventListener("mousemove",De),window.addEventListener("mouseup",Po)};return o.jsxs("div",{style:{flex:1,position:"relative",display:"grid",gridTemplateColumns:Wt?"0 0 minmax(0, 1fr)":`${Ct}px 6px minmax(0, 1fr)`,gridTemplateRows:Yt?"minmax(0, 1fr) 0 0":`minmax(0, 1fr) 6px ${an}px`,overflow:"hidden",background:n.appBg},children:[o.jsxs("div",{style:{borderRight:Wt?"none":`1px solid ${n.headerBorder}`,display:Wt?"none":"flex",flexDirection:"column",overflow:"hidden",background:n.sidebarBg,minWidth:0},children:[o.jsxs("div",{style:{padding:"10px 14px",display:"flex",alignItems:"center",gap:10,borderBottom:`1px solid ${n.headerBorder}`},children:[o.jsx("span",{style:{fontSize:10,fontWeight:600,letterSpacing:"0.06em",color:n.textMuted,textTransform:"uppercase",fontFamily:n.font},children:"Explorer"}),o.jsxs("span",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:[$t.metrics," metrics · ",$t.measures," measures · ",$t.dimensions+$t.timeDimensions," dims · ",$t.entities," entities · ",$t.savedQueries," saved queries"]}),o.jsx("div",{style:{flex:1}}),e.semanticLayer.provider&&o.jsx("span",{style:{fontSize:9,fontWeight:700,color:n.accent,background:`${n.accent}18`,borderRadius:999,padding:"2px 7px",textTransform:"uppercase",letterSpacing:"0.04em"},children:e.semanticLayer.provider}),o.jsx("button",{onClick:()=>Xn(!0),style:{background:"transparent",border:"none",color:n.textMuted,cursor:"pointer",fontSize:14,fontFamily:n.font,padding:0,lineHeight:1},title:"Collapse explorer",children:"‹"})]}),o.jsxs("div",{style:{display:"flex",padding:"0 14px",gap:16,borderBottom:`1px solid ${n.headerBorder}`},children:[o.jsx(bT,{active:r==="semantic",onClick:()=>s("semantic"),label:"Semantic",t:n}),o.jsx(bT,{active:r==="database",onClick:()=>s("database"),label:"Database",t:n})]}),r==="semantic"?o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{padding:12,borderBottom:`1px solid ${n.headerBorder}`,background:`${n.cellBg}66`},children:o.jsx(P5,{query:l,provider:d,cube:T,owner:R,domain:E,tag:h,type:m,providers:cl,cubes:dl,owners:ul,domains:e.semanticLayer.domains,tags:e.semanticLayer.tags,onQueryChange:c,onProviderChange:u,onCubeChange:A,onOwnerChange:S,onDomainChange:f,onTagChange:g,onTypeChange:I,t:n})}),o.jsx("div",{ref:Mr,onScroll:G=>Tt(G.currentTarget.scrollTop),style:{flex:1,overflowY:"auto",borderBottom:`1px solid ${n.headerBorder}`,background:n.cellBg},children:Y?o.jsxs("div",{style:{padding:16,display:"grid",gap:8,textAlign:"center"},children:[o.jsx("div",{style:{fontSize:12,color:"#f85149",fontFamily:n.font},children:Y}),o.jsx("button",{onClick:()=>{te(null),Fs()},style:{fontSize:11,color:n.accent,background:`${n.accent}18`,border:"none",borderRadius:6,padding:"6px 12px",cursor:"pointer",fontFamily:n.font},children:"Retry"})]}):e.blockStudioCatalogLoading?o.jsx(nn,{message:"Loading semantic catalog…"}):Qn.length===0?o.jsx(nn,{message:"No semantic objects match the current filters."}):o.jsx("div",{style:{height:El,position:"relative"},children:o.jsx("div",{style:{position:"absolute",top:Bs.offsetTop,left:0,right:0},children:Bs.rows.map(G=>o.jsx(tV,{row:G,selectedId:x,setSelectedId:_,expanded:O,setExpanded:N,onInsert:vo,favorites:new Set(e.semanticLayer.favorites),dispatch:t,t:n},G.node.id))})})}),o.jsx(M5,{item:C,favorite:!!(C&&e.semanticLayer.favorites.includes(C.name)),onInsert:()=>C&&vo(C),onPreview:()=>{C!=null&&C.sql&&Rt(gi(e.blockStudioDraft,C.sql))},onCopySql:()=>{C!=null&&C.sql&&navigator.clipboard.writeText(C.sql)},onToggleFavorite:()=>{!C||C.kind!=="metric"&&C.kind!=="dimension"||$.toggleFavorite(C.name).then(G=>t({type:"SET_SEMANTIC_FAVORITES",favorites:G}))},t:n})]}):o.jsx(eV,{tree:Us,totalTree:b,expanded:j,setExpanded:L,onEnsureColumns:Al,onInsert:Rl,query:B,onQueryChange:M,stats:bo,connectionName:((Ys=e.blockStudioCatalog)==null?void 0:Ys.connection.current)??"default",loadingNodes:U,onRefresh:Fs,t:n})]}),o.jsx("div",{onMouseDown:Wt?void 0:gl,style:{display:Wt?"none":"block",cursor:"col-resize",background:n.headerBorder}}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0,overflow:"hidden",gridColumn:"3",gridRow:"1"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 14px",borderBottom:`1px solid ${n.headerBorder}`,background:n.cellBg},children:[Wt&&o.jsx("button",{onClick:()=>Xn(!1),style:{background:"transparent",border:"none",color:n.textMuted,cursor:"pointer",fontSize:14,fontFamily:n.font,padding:0,lineHeight:1},title:"Open explorer",children:"›"}),o.jsx("span",{style:{fontSize:10,fontWeight:600,letterSpacing:"0.06em",color:n.textMuted,textTransform:"uppercase",fontFamily:n.font},children:Vt?"Semantic Builder":"SQL Builder"}),o.jsx("span",{style:{fontSize:10,fontWeight:700,color:Vt?"#2ea043":n.accent,background:`${Vt?"#2ea043":n.accent}18`,borderRadius:999,padding:"3px 8px",textTransform:"uppercase",letterSpacing:"0.04em"},children:Vt?"metric block":"sql block"}),(($s=e.blockStudioMetadata)==null?void 0:$s.reviewStatus)&&o.jsx("span",{style:{fontSize:10,fontWeight:700,color:Aa[e.blockStudioMetadata.reviewStatus]??n.textMuted,background:`${Aa[e.blockStudioMetadata.reviewStatus]??n.textMuted}18`,borderRadius:999,padding:"3px 8px",textTransform:"uppercase",letterSpacing:"0.04em"},children:e.blockStudioMetadata.reviewStatus}),o.jsx("div",{style:{flex:1}}),o.jsx(ko,{label:"Import SQL",onClick:()=>t({type:"OPEN_BLOCK_IMPORT"})}),o.jsx(ko,{label:"Run",onClick:()=>void ks(),busy:y}),o.jsx(ko,{label:"Save Draft",onClick:()=>void fl(),busy:F}),e.activeBlockPath&&o.jsxs(o.Fragment,{children:[o.jsx(ko,{label:"Move to Review",onClick:()=>void pl(),busy:Oe}),o.jsx(ko,{label:"Certify",onClick:()=>void Tl(),busy:Co})]}),V&&o.jsx("span",{style:{fontSize:11,color:"#f85149",fontFamily:n.font,padding:"4px 8px",background:"#f8514918",borderRadius:6},children:V})]}),o.jsx("div",{style:{flex:1,overflow:"hidden"},children:js?Vt?o.jsx(k5,{source:e.blockStudioDraft,semanticLayer:e.semanticLayer,chartConfig:Gs,onChange:Rt,t:n}):o.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column",overflow:"hidden"},children:[(K||Ye)&&o.jsx(F5,{semanticChoice:K,databaseWarning:Ye,onDismiss:()=>{ue(null),Ue(null)},onInsertAdvanced:()=>{if(!K)return;const G=Hb(K.kind==="metric"?"metric":"dimension",K.name);Rt(Yb(e.blockStudioDraft,G)),ue(null)},onCreateSemantic:()=>t({type:"OPEN_NEW_BLOCK_MODAL",blockType:"semantic"}),t:n}),o.jsx("div",{style:{flex:1,minHeight:0},children:o.jsx(Ru,{value:e.blockStudioDraft,onChange:Rt,onRun:()=>void ks(),themeMode:e.themeMode,autoFocus:!0,wrap:!1,errorMessage:(Vs=(Ur=e.blockStudioValidation)==null?void 0:Ur.diagnostics.find(G=>G.severity==="error"))==null?void 0:Vs.message})})]}):o.jsx(B5,{dbtStatus:e.blockStudioDbtStatus,semanticStats:$t,databaseStats:bo,onCreateSql:()=>t({type:"OPEN_NEW_BLOCK_MODAL",blockType:"custom"}),onCreateSemantic:()=>t({type:"OPEN_NEW_BLOCK_MODAL",blockType:"semantic"}),onImport:()=>t({type:"OPEN_BLOCK_IMPORT"}),onAskAi:()=>{a("validate"),t({type:"SET_BLOCK_STUDIO_VALIDATION",validation:{valid:!0,diagnostics:[{severity:"info",message:"AI block generation will use the selected dbt model, semantic metric, or current prompt context when provider settings are configured."}],semanticRefs:{metrics:[],dimensions:[],segments:[]},executableSql:null}})},t:n})})]}),o.jsx("div",{onMouseDown:Yt?void 0:Il,style:{gridColumn:"1 / -1",gridRow:"2",display:Yt?"none":"block",cursor:"row-resize",background:n.headerBorder}}),o.jsxs("div",{style:{gridColumn:"1 / -1",gridRow:"3",borderTop:Yt?"none":`1px solid ${n.headerBorder}`,display:Yt?"none":"flex",flexDirection:"column",overflow:"hidden",background:n.cellBg},children:[o.jsxs("div",{style:{padding:"10px 14px",display:"flex",gap:6,alignItems:"center",borderBottom:`1px solid ${n.headerBorder}`,flexWrap:"wrap"},children:[o.jsx("span",{style:{fontSize:10,fontWeight:600,letterSpacing:"0.06em",color:n.textMuted,textTransform:"uppercase",fontFamily:n.font,marginRight:4},children:"Output"}),o.jsx(Ln,{active:i==="results",onClick:()=>a("results"),label:"Results"}),o.jsx(Ln,{active:i==="visualization",onClick:()=>a("visualization"),label:"Visualization"}),o.jsx(Ln,{active:i==="lineage",onClick:()=>a("lineage"),label:"Lineage"}),o.jsx("span",{style:{width:1,height:18,background:n.headerBorder,margin:"0 6px"}}),o.jsx("span",{style:{fontSize:10,fontWeight:600,letterSpacing:"0.06em",color:n.textMuted,textTransform:"uppercase",fontFamily:n.font,marginRight:4},children:"Governance"}),o.jsx(Ln,{active:i==="validate",onClick:()=>a("validate"),label:"Validate"}),o.jsx(Ln,{active:i==="tests",onClick:()=>a("tests"),label:"Tests"}),o.jsx(Ln,{active:i==="history",onClick:()=>{a("history"),!oe&&e.activeBlockPath&&$.getBlockHistory(e.activeBlockPath).then(G=>{z(G.entries),le(!0)})},label:"History"}),o.jsx(Ln,{active:i==="save",onClick:()=>a("save"),label:"Metadata"}),o.jsx("div",{style:{flex:1}}),o.jsx("button",{onClick:()=>Kn(!0),style:{background:"transparent",border:`1px solid ${n.btnBorder}`,borderRadius:6,color:n.textMuted,cursor:"pointer",fontSize:11,fontFamily:n.font,padding:"4px 8px"},title:"Hide pane",children:"▾ Hide"})]}),o.jsxs("div",{style:{flex:1,overflow:"auto"},children:[i==="results"&&(e.blockStudioPreview?o.jsxs("div",{style:{display:"grid",gap:12,padding:12},children:[o.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.fontMono},children:e.blockStudioPreview.sql}),ml==="table"?o.jsx(Rn,{result:e.blockStudioPreview.result,themeMode:e.themeMode}):o.jsx($a,{result:e.blockStudioPreview.result,chartConfig:e.blockStudioPreview.chartConfig,themeMode:e.themeMode})]}):o.jsx(nn,{message:"Run the block to preview results and visualization."})),i==="visualization"&&o.jsx(V5,{chartConfig:Gs,onChange:G=>Rt(sd(e.blockStudioDraft,G)),t:n}),i==="lineage"&&o.jsx(z5,{blockName:gn,loading:ie,detail:se,graph:xe,paths:Z,onSelectNode:G=>{t({type:"SET_LINEAGE_FOCUS",nodeId:G}),e.lineageFullscreen||t({type:"TOGGLE_LINEAGE_FULLSCREEN"})},onOpenFull:()=>{gn&&(t({type:"SET_LINEAGE_FOCUS",nodeId:`block:${gn}`}),e.lineageFullscreen||t({type:"TOGGLE_LINEAGE_FULLSCREEN"}))},t:n}),i==="tests"&&o.jsx(Q5,{source:e.blockStudioDraft,blockPath:e.activeBlockPath,testResults:ae,running:H,onRunTests:async()=>{if(e.activeBlockPath){re(!0);try{const G=await $.runBlockTests(e.blockStudioDraft,e.activeBlockPath);X(G.assertions??[])}catch{X([])}finally{re(!1)}}},t:n}),i==="validate"&&o.jsx($5,{diagnostics:((zs=e.blockStudioValidation)==null?void 0:zs.diagnostics)??[],t:n}),i==="history"&&o.jsx(Z5,{entries:ne,t:n}),i==="save"&&o.jsxs("div",{style:{display:"grid",gap:12},children:[e.activeBlockPath&&e.blockStudioMetadata&&o.jsx("div",{style:{padding:"12px 12px 0"},children:o.jsx(q5,{currentStatus:e.blockStudioMetadata.reviewStatus??"draft",blockPath:e.activeBlockPath,onStatusChanged:G=>{e.blockStudioMetadata&&(t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,reviewStatus:G}}),t({type:"SET_BLOCK_STUDIO_DRAFT",draft:Gr(e.blockStudioDraft,"status",G)}))},t:n})}),Dr&&o.jsx(J5,{result:Dr,t:n}),o.jsx(X5,{metadata:e.blockStudioMetadata,draftMetadata:Je,onChange:G=>{if(!e.blockStudioMetadata)return;t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,...G}});let Te=e.blockStudioDraft;typeof G.name=="string"&&(Te=UR(Te,G.name)),typeof G.domain=="string"&&(Te=Gr(Te,"domain",G.domain)),typeof G.owner=="string"&&(Te=Gr(Te,"owner",G.owner)),typeof G.description=="string"&&(Te=Gr(Te,"description",G.description)),G.tags&&(Te=Gb(Te,G.tags)),Rt(Te)},t:n})]})]})]}),Yt&&o.jsx("div",{style:{position:"absolute",right:16,bottom:16},children:o.jsx("button",{onClick:()=>Kn(!1),style:{background:n.btnBg,border:`1px solid ${n.btnBorder}`,borderRadius:6,color:n.textSecondary,cursor:"pointer",fontSize:12,fontFamily:n.font,padding:"8px 12px"},children:"Open Results"})}),e.blockStudioImportOpen&&o.jsx(U5,{t:n,onClose:()=>t({type:"CLOSE_BLOCK_IMPORT"}),children:o.jsx(G5,{session:Lt,sessions:_r,sessionsLoading:br,onSessionChange:Lr,onRefreshSessions:Pr,onClose:()=>t({type:"CLOSE_BLOCK_IMPORT"}),onSelectCandidate:Sl,onSavedCandidate:hl,defaultDomain:(Je==null?void 0:Je.domain)||((Mo=e.blockStudioMetadata)==null?void 0:Mo.domain)||"imported",defaultOwner:(Je==null?void 0:Je.owner)||((nE=e.blockStudioMetadata)==null?void 0:nE.owner)||"",t:n})})]})}function Ln({active:e,onClick:t,label:n,busy:r}){const{state:s}=Re(),i=ce[s.themeMode];return o.jsx("button",{onClick:t,style:{background:e?`${i.accent}18`:i.btnBg,border:`1px solid ${e?i.accent:i.btnBorder}`,borderRadius:6,color:e?i.accent:i.textSecondary,cursor:"pointer",fontSize:11,fontFamily:i.font,padding:"6px 10px",opacity:r?.7:1},children:r?`${n}…`:n})}function ko(e){return o.jsx(Ln,{active:!1,...e})}function U5({children:e,onClose:t,t:n}){return o.jsx("div",{style:{position:"absolute",inset:0,zIndex:40,background:"rgba(0, 0, 0, 0.28)",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:o.jsxs("div",{style:{width:"min(1180px, calc(100vw - 64px))",height:"min(760px, calc(100vh - 96px))",background:n.appBg,border:`1px solid ${n.headerBorder}`,borderRadius:10,boxShadow:"0 24px 80px rgba(0,0,0,0.36)",overflow:"hidden",position:"relative"},children:[o.jsx("button",{onClick:t,title:"Close import",style:{position:"absolute",top:10,right:12,zIndex:4,background:n.btnBg,border:`1px solid ${n.btnBorder}`,borderRadius:6,color:n.textSecondary,cursor:"pointer",fontSize:16,lineHeight:1,width:30,height:30},children:"×"}),e]})})}function B5({dbtStatus:e,semanticStats:t,databaseStats:n,onCreateSql:r,onCreateSemantic:s,onImport:i,onAskAi:a,t:l}){const c=[{title:"Create SQL Block from dbt Model",detail:"Pick dbt models or database tables, then author a SELECT block with validation, tests, and chart intent.",action:r,label:"Create SQL Block"},{title:"Create Semantic Block from dbt Metric",detail:"Use governed metrics, dimensions, time grain, filters, and chart intent without raw SELECT editing.",action:s,label:"Create Semantic Block"},{title:"Import SQL",detail:"One-time SQL migration flow: split, review, run, save drafts, then certify useful blocks.",action:i,label:"Import SQL"},{title:"Ask AI to Generate Block",detail:"Generate or fix a block from bounded dbt/model context. Suggestions stay review-gated.",action:a,label:"Ask AI"}];return o.jsxs("div",{style:{height:"100%",overflow:"auto",padding:24,display:"grid",gap:18,alignContent:"start",background:l.appBg},children:[o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:22,fontWeight:800,color:l.textPrimary,fontFamily:l.font},children:"Build trusted DQL blocks from dbt"}),o.jsx("div",{style:{fontSize:13,color:l.textMuted,lineHeight:1.5,marginTop:6,maxWidth:900,fontFamily:l.font},children:"dbt remains the source of truth for models and semantic metrics. DQL turns those assets into reusable answer blocks, visualizations, notebooks, Apps, and certification labels."})]}),o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, minmax(0, 1fr))",gap:12},children:c.map(d=>o.jsxs("button",{onClick:d.action,style:{textAlign:"left",background:l.cellBg,border:`1px solid ${l.headerBorder}`,borderRadius:8,padding:14,cursor:"pointer",color:l.textPrimary,display:"grid",gap:9,minHeight:160,fontFamily:l.font},children:[o.jsx("span",{style:{fontSize:14,fontWeight:800},children:d.title}),o.jsx("span",{style:{fontSize:12,color:l.textMuted,lineHeight:1.45},children:d.detail}),o.jsx("span",{style:{marginTop:"auto",color:l.accent,fontSize:12,fontWeight:800},children:d.label})]},d.title))}),o.jsxs("section",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1.3fr) minmax(300px, 0.7fr)",gap:12},children:[o.jsx(Dt,{title:"dbt connection",t:l,children:o.jsx(j5,{status:e,t:l})}),o.jsxs(Dt,{title:"DQL basics",t:l,children:[o.jsx(ut,{label:"SQL Block",value:'type = "custom" + query = """ SELECT ... """',t:l}),o.jsx(ut,{label:"Semantic Block",value:"metric, dimensions, time_dimension, granularity",t:l}),o.jsx(ut,{label:"Schema",value:`${n.tables} database tables available for SQL blocks`,t:l}),o.jsx(ut,{label:"Metrics",value:`${t.metrics} metrics and ${t.dimensions+t.timeDimensions} dimensions available for semantic blocks`,t:l}),o.jsx(ut,{label:"Certify",value:"Run, validate, test, review lineage, then certify.",t:l})]})]})]})}function j5({status:e,t}){if(!e)return o.jsx("div",{style:{fontSize:12,color:t.textMuted,fontFamily:t.font},children:"Checking dbt project status…"});const n=[["manifest.json",e.artifacts.manifest],["catalog.json",e.artifacts.catalog],["semantic_manifest.json",e.artifacts.semanticManifest],["run_results.json",e.artifacts.runResults]];return o.jsxs("div",{style:{display:"grid",gap:9},children:[o.jsx(ut,{label:"Project",value:e.projectName||e.projectPath||"not detected",t}),o.jsx(ut,{label:"Provider",value:e.provider||"none",t}),o.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[o.jsx(tt,{label:`${e.counts.models} models`,tone:"info",t}),o.jsx(tt,{label:`${e.counts.sources} sources`,tone:"info",t}),o.jsx(tt,{label:`${e.counts.metrics} metrics`,tone:"info",t}),o.jsx(tt,{label:`${e.counts.savedQueries} saved queries`,tone:"info",t})]}),o.jsx("div",{style:{display:"grid",gap:6},children:n.map(([r,s])=>o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"180px 70px minmax(0, 1fr)",gap:8,alignItems:"center",fontSize:12,fontFamily:t.font},children:[o.jsx("span",{style:{color:t.textSecondary},children:r}),o.jsx("span",{style:{color:s.exists?"#2ea043":"#d29922",fontWeight:800},children:s.exists?"ready":"missing"}),o.jsx("span",{style:{color:t.textMuted,fontFamily:t.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.path})]},r))}),o.jsx("div",{style:{fontSize:12,color:e.artifacts.manifest.exists?t.textMuted:"#d29922",lineHeight:1.45,fontFamily:t.font},children:e.setupHint})]})}function k5({source:e,semanticLayer:t,chartConfig:n,onChange:r,t:s}){const i=nV(e),a=[...t.dimensions,...t.timeDimensions],l=_n(s),c=E=>r(rV(e,E)),d=E=>r(oV(e,"dimensions",E)),u=E=>{const f=i.dimensions.includes(E)?i.dimensions.filter(T=>T!==E):[...i.dimensions,E];d(f)};return o.jsxs("div",{style:{height:"100%",overflow:"auto",padding:16,display:"grid",gap:14,alignContent:"start",background:s.appBg},children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(280px, 0.6fr)",gap:12},children:[o.jsxs(Dt,{title:"Metric and grain",t:s,children:[o.jsx(Ze,{label:"Metric",t:s,children:o.jsxs("select",{value:i.metric,onChange:E=>c(E.target.value),style:l,children:[o.jsx("option",{value:"",children:"Select a governed metric…"}),t.metrics.map(E=>o.jsx("option",{value:E.name,children:E.label||E.name},E.name))]})}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 150px",gap:8},children:[o.jsx(Ze,{label:"Time dimension",t:s,children:o.jsxs("select",{value:i.timeDimension,onChange:E=>r(vd(e,"time_dimension",E.target.value)),style:l,children:[o.jsx("option",{value:"",children:"None"}),t.timeDimensions.map(E=>o.jsx("option",{value:E.name,children:E.label||E.name},E.name))]})}),o.jsx(Ze,{label:"Grain",t:s,children:o.jsxs("select",{value:i.granularity,onChange:E=>r(vd(e,"granularity",E.target.value)),style:l,children:[o.jsx("option",{value:"",children:"None"}),["day","week","month","quarter","year"].map(E=>o.jsx("option",{value:E,children:E},E))]})})]}),t.metrics.length===0&&o.jsx("div",{style:{fontSize:12,color:"#d29922",lineHeight:1.45},children:"No semantic metrics are loaded. Run `dbt parse` or import a semantic layer, then refresh Block Studio."})]}),o.jsxs(Dt,{title:"Chart intent",t:s,children:[o.jsx(Ze,{label:"Chart type",t:s,children:o.jsxs("select",{value:n.chart??"table",onChange:E=>r(sd(e,{...n,chart:E.target.value})),style:l,children:[o.jsx("option",{value:"table",children:"Table"}),zn.map(E=>o.jsx("option",{value:E.value,children:E.label},E.value))]})}),o.jsx(Ze,{label:"Title",t:s,children:o.jsx("input",{value:n.title??"",onChange:E=>r(sd(e,{...n,title:E.target.value})),placeholder:"Chart title",style:l})})]})]}),o.jsx(Dt,{title:"Dimensions",t:s,children:a.length===0?o.jsx("div",{style:{fontSize:12,color:s.textMuted},children:"No dimensions are loaded yet."}):o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:7},children:a.slice(0,80).map(E=>{const f=i.dimensions.includes(E.name);return o.jsx("button",{onClick:()=>u(E.name),style:{background:f?`${s.accent}18`:s.btnBg,border:`1px solid ${f?s.accent:s.btnBorder}`,borderRadius:999,color:f?s.accent:s.textSecondary,cursor:"pointer",fontSize:11,fontFamily:s.font,padding:"5px 9px"},children:E.label||E.name},E.name)})})}),o.jsx(Dt,{title:"Generated DQL",t:s,children:o.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",color:s.textSecondary,fontSize:11,lineHeight:1.45,fontFamily:s.fontMono},children:e})})]})}function F5({semanticChoice:e,databaseWarning:t,onDismiss:n,onInsertAdvanced:r,onCreateSemantic:s,t:i}){const a=e?`${e.kind==="metric"?"Metric":"Dimension"} "${e.name}" belongs in a Semantic Block. SQL Blocks can still use advanced @metric/@dim refs when you choose that explicitly.`:t??"";return o.jsxs("div",{style:{padding:"10px 12px",borderBottom:`1px solid ${i.headerBorder}`,background:`${i.accent}10`,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[o.jsx("span",{style:{fontSize:12,color:i.textSecondary,lineHeight:1.4,flex:1,minWidth:260},children:a}),e&&o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:s,style:nt(i),children:"Create Semantic Block"}),o.jsx("button",{onClick:r,style:ur(i),children:"Insert advanced ref"})]}),o.jsx("button",{onClick:n,style:nt(i),children:"Dismiss"})]})}function bT({active:e,onClick:t,label:n,t:r}){return o.jsx("button",{onClick:t,style:{background:"transparent",border:"none",borderBottom:`2px solid ${e?r.accent:"transparent"}`,color:e?r.textPrimary:r.textMuted,cursor:"pointer",fontSize:12,fontWeight:e?600:500,fontFamily:r.font,padding:"10px 2px",marginBottom:-1},children:n})}function G5({session:e,sessions:t,sessionsLoading:n,onSessionChange:r,onRefreshSessions:s,onClose:i,onSelectCandidate:a,onSavedCandidate:l,defaultDomain:c,defaultOwner:d,t:u}){const[E,f]=p.useState("path"),[T,A]=p.useState(""),[R,S]=p.useState(""),[h,g]=p.useState([]),[m,I]=p.useState(c),[O,N]=p.useState(d),[x,_]=p.useState(null),[C,v]=p.useState(!1),[b,P]=p.useState(!1),[j,L]=p.useState(null),[B,M]=p.useState(null),[U,D]=p.useState(!1),[y,w]=p.useState(""),[F,k]=p.useState(!1),V=p.useMemo(()=>e?e.candidates.find(Z=>Z.id===x)??e.candidates[0]??null:null,[e,x]);p.useEffect(()=>{if(!(e!=null&&e.candidates.length)){_(null);return}(!x||!e.candidates.some(Z=>Z.id===x))&&_(e.candidates[0].id)},[e,x]);const ee=(e==null?void 0:e.candidates.filter(Z=>{var Ee;return((Ee=Z.validation)==null?void 0:Ee.valid)!==!1&&Z.reviewStatus!=="rejected"}).length)??0,Y=(e==null?void 0:e.candidates.filter(Z=>Z.reviewStatus==="saved").length)??0,te=(e==null?void 0:e.candidates.reduce((Z,Ee)=>Z+(Ee.warnings??Ee.lineage.warnings).length,0))??0,ne=p.useMemo(()=>{const Z=y.trim().toLowerCase(),Ee=(e==null?void 0:e.candidates)??[];return Z?Ee.filter(Oe=>[Oe.name,Oe.domain,Oe.sourcePath,Oe.description,...Oe.lineage.sourceTables].some(ve=>ve.toLowerCase().includes(Z))):Ee},[y,e]),z=F||y.trim()?ne:ne.slice(0,10),oe=async()=>{var Z;v(!0),L(null);try{if(E==="tableau"||E==="powerbi"){L(E==="tableau"?"Tableau local file import is designed for the next migration-helper pass. SQL import is the active OSS path now.":"Power BI PBIP/PBIR/TMDL import is designed for the next migration-helper pass. SQL import is the active OSS path now.");return}const Ee=E==="path"?{path:T,inputMode:"path",sourceKind:"raw-sql",domain:m,owner:O}:{inputMode:E,sourceKind:"raw-sql",domain:m,owner:O,sources:E==="paste"?[{path:"pasted.sql",content:R}]:h},Oe=await $.createBlockStudioImport(Ee);r(Oe),_(((Z=Oe.candidates[0])==null?void 0:Z.id)??null),await s()}catch(Ee){L((Ee==null?void 0:Ee.message)??"Import session failed.")}finally{v(!1)}},le=async Z=>{var Ee,Oe;v(!0),L(null);try{const ve=await $.getBlockStudioImport(Z);r(ve),_(((Ee=ve.candidates.find(Le=>Le.reviewStatus!=="saved"&&Le.reviewStatus!=="rejected"))==null?void 0:Ee.id)??((Oe=ve.candidates[0])==null?void 0:Oe.id)??null)}catch(ve){L((ve==null?void 0:ve.message)??"Failed to resume import session.")}finally{v(!1)}},ae=async Z=>{M({kind:"one",id:Z})},X=async()=>{t.length!==0&&M({kind:"all"})},H=async()=>{if(!B)return;const Z=B;v(!0),L(null);try{Z.kind==="one"?await $.deleteBlockStudioImport(Z.id):await $.clearBlockStudioImports(),(Z.kind==="all"||(e==null?void 0:e.id)===Z.id)&&(r(null),_(null)),M(null),await s()}catch(Ee){L((Ee==null?void 0:Ee.message)??"Failed to update import history.")}finally{v(!1)}},re=Z=>{e&&r({...e,candidates:e.candidates.map(Ee=>Ee.id===Z.id?Z:Ee)})},ie=async Z=>{if(e){v(!0),L(null);try{const Ee=await $.runBlockStudioImportCandidate(e.id,Z.id);re(Ee),_(Ee.id)}catch(Ee){L((Ee==null?void 0:Ee.message)??"Candidate run failed.")}finally{v(!1)}}},de=async Z=>{if(e){v(!0),L(null);try{const Ee=await $.saveBlockStudioImportCandidate(e.id,Z.id);re(Ee.candidate),l(Ee.candidate,Ee.block),await s()}catch(Ee){const Oe=(Ee==null?void 0:Ee.message)??"Candidate save failed.";L(Oe.includes("409")||Oe.includes("already exists")?"A block with this name already exists. Rename this candidate, then save again.":Oe)}finally{v(!1)}}},se=async()=>{if(e){P(!0),L(null);try{const Z=await $.saveAllBlockStudioImportCandidates(e.id);r(Z.session),await s(),Z.errors.length>0&&L(`${Z.saved.length} saved. ${Z.errors.length} candidate(s) need attention.`)}catch(Z){L((Z==null?void 0:Z.message)??"Save all failed.")}finally{P(!1)}}},ge=async Z=>{if(!e)return;const Ee=await $.updateBlockStudioImportCandidate(e.id,Z.id,{reviewStatus:"rejected"});re(Ee),s()},xe=()=>{if(!e)return;const Z=e.candidates.find(Ee=>Ee.reviewStatus!=="saved"&&Ee.reviewStatus!=="rejected");Z&&_(Z.id)},Fe=async Z=>{const Oe=Array.from(Z??[]).filter(Le=>Le.name.toLowerCase().endsWith(".sql")),ve=await Promise.all(Oe.map(async Le=>({path:Le.name,content:await Le.text()})));g(ve)};return o.jsxs("div",{style:{position:"relative",height:"100%",display:"grid",gridTemplateColumns:"320px minmax(0, 1fr)",minHeight:0,background:u.appBg},children:[o.jsxs("aside",{style:{borderRight:`1px solid ${u.headerBorder}`,display:"flex",flexDirection:"column",minHeight:0,background:u.cellBg},children:[o.jsxs("div",{style:{padding:16,borderBottom:`1px solid ${u.headerBorder}`,display:"grid",gap:10},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsx("span",{style:{fontSize:14,fontWeight:800,color:u.textPrimary,fontFamily:u.font},children:"Import SQL"}),o.jsx("span",{style:{flex:1}}),o.jsx("button",{onClick:i,style:nt(u),children:"Close"})]}),o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:4},children:["path","paste","upload"].map(Z=>o.jsx("button",{onClick:()=>f(Z),style:{...nt(u),padding:"6px 4px",color:E===Z?u.accent:u.textSecondary,borderColor:E===Z?u.accent:u.btnBorder,background:E===Z?`${u.accent}14`:u.btnBg},children:Z==="path"?"File / folder":Z[0].toUpperCase()+Z.slice(1)},Z))}),E==="path"&&o.jsx(Ze,{label:"SQL file or folder path",t:u,children:o.jsx("input",{value:T,onChange:Z=>A(Z.target.value),placeholder:"./queries or ./legacy.sql",style:_n(u)})}),E==="paste"&&o.jsx(Ze,{label:"Paste SQL",t:u,children:o.jsx("textarea",{value:R,onChange:Z=>S(Z.target.value),placeholder:`select ...; go
|
|
822
|
+
select ...`,style:{..._n(u),minHeight:108,resize:"vertical",fontFamily:u.fontMono}})}),E==="upload"&&o.jsxs(Ze,{label:"Upload .sql files",t:u,children:[o.jsx("input",{type:"file",multiple:!0,accept:".sql,text/sql,text/plain",onChange:Z=>void Fe(Z.target.files),style:_n(u)}),o.jsxs("span",{style:{fontSize:11,color:u.textMuted,fontFamily:u.font},children:[h.length," SQL file(s) ready"]})]}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[o.jsx(Ze,{label:"Domain",t:u,children:o.jsx("input",{value:m,onChange:Z=>I(Z.target.value),placeholder:"imported",style:_n(u)})}),o.jsx(Ze,{label:"Owner",t:u,children:o.jsx("input",{value:O,onChange:Z=>N(Z.target.value),placeholder:"analytics",style:_n(u)})})]}),o.jsx("button",{onClick:()=>void oe(),disabled:C||E==="tableau"||E==="powerbi"||E==="path"&&!T.trim()||E==="paste"&&!R.trim()||E==="upload"&&h.length===0,style:{...ur(u),padding:"8px 12px",opacity:C?.65:1},children:C?"Working...":"Preview SQL"}),o.jsx("div",{style:{fontSize:11,color:u.textMuted,fontFamily:u.font,lineHeight:1.45},children:"Flow: choose SQL, review each detected query, then save draft blocks. Split uses semicolon and GO batch separators."}),o.jsxs("details",{style:{fontSize:11,color:u.textMuted,fontFamily:u.font,border:`1px dashed ${u.headerBorder}`,borderRadius:8,padding:"8px 10px"},children:[o.jsx("summary",{style:{cursor:"pointer",color:u.textSecondary,fontWeight:700},children:"Tableau / Power BI migration helpers"}),o.jsx("div",{style:{marginTop:8,lineHeight:1.45},children:"Local Tableau `.twb/.twbx` and Power BI PBIP/PBIR/TMDL import are planned. OSS v1 keeps SQL import active first and preserves unsupported BI formulas as future warnings."})]})]}),o.jsxs("div",{style:{padding:12,borderBottom:`1px solid ${u.headerBorder}`,display:"grid",gap:8},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsx("button",{onClick:()=>D(Z=>!Z),style:{...nt(u),padding:"5px 8px"},children:U?"Hide recent imports":"Recent imports"}),o.jsx("span",{style:{flex:1}}),U&&o.jsx("button",{onClick:()=>void s(),style:nt(u),children:"Refresh"}),U&&t.length>0&&o.jsx("button",{onClick:()=>void X(),style:nt(u),children:"Clear all"})]}),U&&(n?o.jsx("div",{style:{fontSize:12,color:u.textMuted},children:"Loading sessions..."}):t.length===0?o.jsx("div",{style:{fontSize:12,color:u.textMuted},children:"No saved import previews yet."}):o.jsx("div",{style:{display:"grid",gap:6,maxHeight:190,overflow:"auto"},children:t.slice(0,8).map(Z=>o.jsxs("div",{style:{border:`1px solid ${(e==null?void 0:e.id)===Z.id?u.accent:u.btnBorder}`,borderRadius:8,background:(e==null?void 0:e.id)===Z.id?`${u.accent}10`:u.btnBg,display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",alignItems:"stretch",overflow:"hidden"},children:[o.jsxs("button",{onClick:()=>void le(Z.id),style:{background:"transparent",border:"none",color:u.textSecondary,cursor:"pointer",fontFamily:u.font,padding:"8px 9px",textAlign:"left",display:"grid",gap:3,minWidth:0},children:[o.jsx("span",{style:{fontFamily:u.fontMono,fontSize:10},children:Z.id}),o.jsxs("span",{style:{fontSize:11},children:[Z.candidateCount," candidates · ",Z.savedCount," saved · ",Z.warningCount," warnings"]}),o.jsx("span",{style:{fontSize:10,color:u.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Z.inputPath})]}),o.jsx("button",{onClick:()=>void ae(Z.id),title:"Delete local import preview",style:{background:"transparent",border:"none",borderLeft:`1px solid ${u.headerBorder}`,color:u.textMuted,cursor:"pointer",fontFamily:u.font,padding:"0 8px",fontSize:11,fontWeight:700},children:"Delete"})]},Z.id))}))]}),o.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto",padding:12,display:"grid",alignContent:"start",gap:8},children:e?o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",alignItems:"center"},children:[o.jsx(tt,{label:`${e.candidates.length} candidates`,tone:"info",t:u}),o.jsx(tt,{label:`${ee} ready`,tone:"ok",t:u}),o.jsx(tt,{label:`${Y} saved`,tone:"ok",t:u}),te>0&&o.jsx(tt,{label:`${te} warnings`,tone:"warn",t:u})]}),o.jsxs("div",{style:{display:"flex",gap:6},children:[o.jsx("button",{onClick:xe,style:nt(u),children:"Open next unsaved"}),o.jsx("button",{onClick:()=>void se(),disabled:b,style:ur(u),children:b?"Saving...":"Save all valid"})]}),o.jsx("input",{value:y,onChange:Z=>w(Z.target.value),placeholder:"Search candidates, tables, files...",style:_n(u)}),z.map(Z=>{var ve,Le;const Ee=Z.id===(V==null?void 0:V.id),Oe=Z.warnings??Z.lineage.warnings;return o.jsxs("button",{onClick:()=>_(Z.id),style:{border:`1px solid ${Ee?u.accent:u.headerBorder}`,borderRadius:8,background:Ee?`${u.accent}10`:u.appBg,color:u.textPrimary,padding:10,display:"grid",gap:6,textAlign:"left",cursor:"pointer"},children:[o.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6},children:[o.jsx("span",{style:{minWidth:0,flex:1,fontSize:12,fontWeight:800,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Z.name}),o.jsx(tt,{label:Z.reviewStatus,tone:Z.reviewStatus==="saved"?"ok":Z.reviewStatus==="rejected"?"warn":"info",t:u})]}),o.jsxs("span",{style:{fontSize:10,color:u.textMuted,fontFamily:u.fontMono},children:[Z.lineage.statementIndex,"/",Z.lineage.totalStatements," · ",Z.sourcePath]}),o.jsxs("span",{style:{display:"flex",gap:5,flexWrap:"wrap"},children:[o.jsx(tt,{label:`${Math.round(Z.confidence*100)}%`,tone:"info",t:u}),o.jsx(tt,{label:((ve=Z.validation)==null?void 0:ve.valid)===!1?"review":"valid",tone:((Le=Z.validation)==null?void 0:Le.valid)===!1?"warn":"ok",t:u}),Oe.length>0&&o.jsx(tt,{label:`${Oe.length} warning`,tone:"warn",t:u})]})]},Z.id)}),!F&&!y.trim()&&ne.length>10&&o.jsxs("button",{onClick:()=>k(!0),style:nt(u),children:["Show all ",ne.length," candidates"]})]}):o.jsx("div",{style:{fontSize:12,color:u.textMuted,lineHeight:1.5},children:"Create or open an import preview to review detected SQL queries."})})]}),o.jsxs("section",{style:{minWidth:0,minHeight:0,overflow:"auto",padding:14},children:[j&&o.jsx("div",{style:{padding:"10px 12px",color:"#f85149",background:"#f8514914",border:"1px solid #f8514933",borderRadius:8,marginBottom:12,fontSize:12},children:j}),!e||!V?o.jsx(Y5,{t:u}):o.jsx(W5,{session:e,candidate:V,loading:C,onCandidateUpdated:re,onRun:ie,onSave:de,onReject:ge,onReviewInEditor:a,t:u})]}),B&&o.jsx(H5,{t:u,busy:C,title:B.kind==="all"?"Clear import history?":"Delete import preview?",message:B.kind==="all"?`This removes ${t.length} local import preview${t.length===1?"":"s"} from .dql/imports. Saved draft blocks stay in the project.`:"This removes the selected local import preview from .dql/imports. Saved draft blocks stay in the project.",confirmLabel:B.kind==="all"?"Clear history":"Delete preview",onCancel:()=>M(null),onConfirm:()=>void H()})]})}function H5({title:e,message:t,confirmLabel:n,busy:r,onCancel:s,onConfirm:i,t:a}){return o.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0, 0, 0, 0.22)",display:"flex",alignItems:"center",justifyContent:"center",padding:20,zIndex:20},children:o.jsxs("div",{style:{width:"min(420px, 92vw)",background:a.cellBg,color:a.textPrimary,border:`1px solid ${a.headerBorder}`,borderRadius:8,boxShadow:"0 18px 48px rgba(0, 0, 0, 0.30)",padding:16,display:"grid",gap:12},children:[o.jsx("div",{style:{fontSize:15,fontWeight:800,fontFamily:a.font},children:e}),o.jsx("div",{style:{fontSize:12,color:a.textMuted,lineHeight:1.5,fontFamily:a.font},children:t}),o.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[o.jsx("button",{onClick:s,disabled:r,style:nt(a),children:"Cancel"}),o.jsx("button",{onClick:i,disabled:r,style:{...ur(a),opacity:r?.65:1},children:r?"Working...":n})]})]})})}function W5({session:e,candidate:t,loading:n,onCandidateUpdated:r,onRun:s,onSave:i,onReject:a,onReviewInEditor:l,t:c}){const[d,u]=p.useState(t.name),[E,f]=p.useState(t.domain),[T,A]=p.useState(t.owner),[R,S]=p.useState(t.description),[h,g]=p.useState(t.tags.join(", ")),[m,I]=p.useState(t.sql),[O,N]=p.useState(null),[x,_]=p.useState(null);p.useEffect(()=>{u(t.name),f(t.domain),A(t.owner),S(t.description),g(t.tags.join(", ")),I(t.sql),_(null)},[t.id,t.name,t.domain,t.owner,t.description,t.tags,t.sql]);const C=async()=>{_(null);try{const j=await $.updateBlockStudioImportCandidate(e.id,t.id,{name:d,domain:E,owner:T,description:R,tags:h.split(",").map(L=>L.trim()).filter(Boolean),sql:m});r(j)}catch(j){_((j==null?void 0:j.message)??"Could not update candidate.")}},v=async j=>{N(j),_(null);try{const L=await $.assistBlockStudioImportCandidate(e.id,t.id,j);r(L)}catch(L){_((L==null?void 0:L.message)??"AI assist failed.")}finally{N(null)}},b=t.warnings??t.lineage.warnings,P=_n(c);return o.jsxs("div",{style:{display:"grid",gap:12},children:[o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:10,flexWrap:"wrap"},children:[o.jsxs("div",{style:{minWidth:0,flex:1},children:[o.jsx("div",{style:{fontSize:18,fontWeight:800,color:c.textPrimary},children:t.name}),o.jsxs("div",{style:{fontSize:11,color:c.textMuted,fontFamily:c.fontMono,marginTop:3},children:[t.sourcePath," · statement ",t.lineage.statementIndex,"/",t.lineage.totalStatements]})]}),o.jsx("button",{onClick:()=>void s(t),disabled:n,style:nt(c),children:"Run preview"}),o.jsx("button",{onClick:()=>l(t),style:ur(c),children:"Review in editor"}),o.jsx("button",{onClick:()=>void i(t),disabled:n||t.reviewStatus==="saved",style:ur(c),children:t.reviewStatus==="saved"?"Saved":"Save draft"}),o.jsx("button",{onClick:()=>void a(t),disabled:t.reviewStatus==="rejected",style:nt(c),children:"Reject"})]}),x&&o.jsx("div",{style:{fontSize:12,color:"#f85149",background:"#f8514914",borderRadius:8,padding:10},children:x}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(300px, 38%)",gap:12,alignItems:"start"},children:[o.jsxs("div",{style:{display:"grid",gap:12},children:[o.jsxs(Dt,{title:"Block Details",t:c,children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[o.jsx(Ze,{label:"Name",t:c,children:o.jsx("input",{value:d,onChange:j=>u(j.target.value),style:P})}),o.jsx(Ze,{label:"Domain",t:c,children:o.jsx("input",{value:E,onChange:j=>f(j.target.value),style:P})}),o.jsx(Ze,{label:"Owner",t:c,children:o.jsx("input",{value:T,onChange:j=>A(j.target.value),style:P})}),o.jsx(Ze,{label:"Tags",t:c,children:o.jsx("input",{value:h,onChange:j=>g(j.target.value),style:P})})]}),o.jsx(Ze,{label:"Description",t:c,children:o.jsx("input",{value:R,onChange:j=>S(j.target.value),style:P})}),o.jsx("button",{onClick:()=>void C(),style:ur(c),children:"Apply edits"})]}),o.jsx(Dt,{title:"Original SQL",t:c,children:o.jsx("textarea",{value:m,onChange:j=>I(j.target.value),style:{...P,minHeight:210,fontFamily:c.fontMono,resize:"vertical"}})}),o.jsx(Dt,{title:"Draft DQL Block",t:c,children:o.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",fontSize:11,lineHeight:1.45,color:c.textSecondary,fontFamily:c.fontMono},children:t.dqlSource})})]}),o.jsxs("div",{style:{display:"grid",gap:12},children:[o.jsxs(Dt,{title:"How DQL Was Generated",t:c,children:[o.jsx("div",{style:{fontSize:12,color:c.textMuted,lineHeight:1.45},children:"This is an audit view for the selected SQL query. It explains what DQL created locally before you save the draft block."}),o.jsx(ut,{label:"Method",value:"Deterministic local conversion",t:c}),o.jsx(ut,{label:"Block",value:t.name,t:c}),o.jsx(ut,{label:"Domain",value:t.domain,t:c}),o.jsx(ut,{label:"Visualization",value:"table",t:c}),o.jsx(ut,{label:"Default test",value:"assert row_count > 0",t:c}),o.jsx(ut,{label:"Split strategy",value:t.splitStrategy??"semicolon-go",t:c}),o.jsxs("div",{style:{display:"grid",gap:5},children:[o.jsx("div",{style:{fontSize:10,color:c.textMuted,textTransform:"uppercase",fontWeight:800},children:"Detected tables"}),o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:t.lineage.sourceTables.length?t.lineage.sourceTables.map(j=>o.jsx(tt,{label:j,tone:"info",t:c},j)):o.jsx("span",{style:{fontSize:12,color:c.textMuted},children:"None detected"})})]}),o.jsxs("div",{style:{display:"grid",gap:5},children:[o.jsx("div",{style:{fontSize:10,color:c.textMuted,textTransform:"uppercase",fontWeight:800},children:"Parameters"}),o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:t.lineage.parameters.length?t.lineage.parameters.map(j=>o.jsx(tt,{label:j,tone:"warn",t:c},j)):o.jsx("span",{style:{fontSize:12,color:c.textMuted},children:"None detected"})})]}),b.length>0&&o.jsxs("div",{style:{display:"grid",gap:6},children:[o.jsx("div",{style:{fontSize:10,color:"#d29922",textTransform:"uppercase",fontWeight:800},children:"Warnings"}),b.map((j,L)=>o.jsx("div",{style:{fontSize:12,color:"#d29922",lineHeight:1.4},children:j},L))]}),o.jsxs("div",{style:{display:"grid",gap:6},children:[o.jsx("div",{style:{fontSize:10,color:c.textMuted,textTransform:"uppercase",fontWeight:800},children:"Notes"}),(t.conversionNotes??[]).map((j,L)=>o.jsx("div",{style:{fontSize:12,color:c.textMuted,lineHeight:1.4},children:j},L))]})]}),o.jsxs(Dt,{title:"Optional AI Suggestions",t:c,children:[o.jsx("div",{style:{fontSize:12,color:c.textMuted,lineHeight:1.45},children:"Optional helper for naming, explanation, validation fixes, chart ideas, and stronger tests. It only uses this selected candidate context and records suggestions for review."}),o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[["explain","Explain"],["fix-validation","Fix validation"],["infer-chart","Infer chart"],["propose-tests","Propose tests"]].map(([j,L])=>o.jsx("button",{onClick:()=>void v(j),disabled:!!O,style:nt(c),children:O===j?"Working...":L},j))}),(t.aiAssistance??[]).length>0&&o.jsx("div",{style:{display:"grid",gap:8},children:(t.aiAssistance??[]).slice().reverse().map((j,L)=>o.jsxs("div",{style:{border:`1px solid ${c.headerBorder}`,borderRadius:8,padding:9,background:c.appBg},children:[o.jsxs("div",{style:{fontSize:10,color:c.textMuted,fontWeight:800,textTransform:"uppercase"},children:[j.action," · ",j.status]}),o.jsx("div",{style:{fontSize:12,color:c.textSecondary,lineHeight:1.45,marginTop:5},children:j.summary})]},`${j.createdAt}-${L}`))})]})]})]})]})}function Y5({t:e}){const t=[["1","Choose source","Enter a local .sql file or a folder with SQL files."],["2","Review candidates","DQL detects statements, tables, parameters, and draft metadata."],["3","Save draft blocks","Open in Block Studio for edits or save directly as draft blocks."]];return o.jsxs("div",{style:{display:"grid",gap:12},children:[o.jsx(nn,{message:"Choose a SQL file or folder to create import candidates."}),o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:10},children:t.map(([n,r,s])=>o.jsxs("div",{style:{border:`1px solid ${e.headerBorder}`,borderRadius:8,background:e.appBg,padding:12,display:"grid",gap:6},children:[o.jsx("span",{style:{width:22,height:22,borderRadius:999,display:"inline-grid",placeItems:"center",background:`${e.accent}18`,color:e.accent,fontSize:11,fontWeight:800,fontFamily:e.font},children:n}),o.jsx("span",{style:{fontSize:12,fontWeight:700,color:e.textPrimary,fontFamily:e.font},children:r}),o.jsx("span",{style:{fontSize:11,color:e.textMuted,fontFamily:e.font,lineHeight:1.4},children:s})]},r))})]})}function Ze({label:e,children:t,t:n}){return o.jsxs("label",{style:{display:"grid",gap:5},children:[o.jsx("span",{style:{fontSize:10,fontWeight:700,color:n.textMuted,letterSpacing:"0.05em",textTransform:"uppercase",fontFamily:n.font},children:e}),t]})}function Dt({title:e,children:t,t:n}){return o.jsxs("section",{style:{border:`1px solid ${n.headerBorder}`,borderRadius:8,background:n.cellBg,padding:12,display:"grid",gap:10},children:[o.jsx("div",{style:{fontSize:11,fontWeight:800,color:n.textMuted,textTransform:"uppercase",letterSpacing:"0.05em",fontFamily:n.font},children:e}),t]})}function ut({label:e,value:t,t:n}){return o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"110px minmax(0, 1fr)",gap:8,fontSize:12,fontFamily:n.font},children:[o.jsx("span",{style:{color:n.textMuted},children:e}),o.jsx("span",{style:{color:n.textSecondary,overflowWrap:"anywhere"},children:t})]})}function tt({label:e,tone:t,t:n}){const r=t==="ok"?"#2ea043":t==="warn"?"#d29922":n.accent;return o.jsx("span",{style:{fontSize:10,fontWeight:700,color:r,background:`${r}18`,borderRadius:999,padding:"3px 7px",fontFamily:n.font,textTransform:"uppercase"},children:e})}function _n(e){return{background:e.inputBg,border:`1px solid ${e.inputBorder}`,borderRadius:6,color:e.textPrimary,fontSize:12,fontFamily:e.font,padding:"8px 10px",outline:"none",minWidth:0}}function nt(e){return{background:e.btnBg,border:`1px solid ${e.btnBorder}`,borderRadius:6,color:e.textSecondary,cursor:"pointer",fontSize:11,fontFamily:e.font,padding:"6px 10px"}}function ur(e){return{...nt(e),background:`${e.accent}18`,border:`1px solid ${e.accent}`,color:e.accent,fontWeight:700}}function Fc({label:e,value:t,t:n}){return o.jsxs("div",{style:{background:n.cellBg,border:`1px solid ${n.headerBorder}`,borderRadius:10,padding:"10px 12px"},children:[o.jsx("div",{style:{fontSize:10,fontWeight:700,color:n.textMuted,fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.05em"},children:e}),o.jsx("div",{style:{fontSize:20,fontWeight:700,color:n.textPrimary,fontFamily:n.font,marginTop:4},children:t})]})}function $5({diagnostics:e,t}){return e.length===0?o.jsx(nn,{message:"No validation messages."}):o.jsx("div",{style:{display:"grid",gap:8,padding:12},children:e.map((n,r)=>o.jsxs("div",{style:{padding:"10px 12px",borderRadius:8,border:`1px solid ${n.severity==="error"?t.error:n.severity==="warning"?t.warning:t.cellBorder}`,background:n.severity==="error"?`${t.error}12`:n.severity==="warning"?`${t.warning}12`:t.pillBg},children:[o.jsx("div",{style:{fontSize:10,fontWeight:700,color:n.severity==="error"?t.error:n.severity==="warning"?t.warning:t.textMuted,textTransform:"uppercase",letterSpacing:"0.04em"},children:n.severity}),o.jsx("div",{style:{fontSize:12,color:t.textPrimary,marginTop:4},children:n.message})]},`${n.code??n.message}-${r}`))})}function V5({chartConfig:e,onChange:t,t:n}){const r={width:"100%",background:n.inputBg,border:`1px solid ${n.inputBorder}`,borderRadius:6,color:n.textPrimary,fontSize:12,fontFamily:n.font,padding:"8px 10px",outline:"none"};return o.jsxs("div",{style:{display:"grid",gap:10,padding:12},children:[o.jsxs("select",{value:e.chart??"table",onChange:s=>t({...e,chart:s.target.value}),style:r,children:[o.jsx("option",{value:"table",children:"Table"}),zn.map(s=>o.jsx("option",{value:s.value,children:s.label},s.value))]}),o.jsx("input",{value:e.x??"",onChange:s=>t({...e,x:s.target.value}),placeholder:"x binding",style:r}),o.jsx("input",{value:e.y??"",onChange:s=>t({...e,y:s.target.value}),placeholder:"y binding",style:r}),o.jsx("input",{value:e.color??"",onChange:s=>t({...e,color:s.target.value}),placeholder:"color binding",style:r}),o.jsx("input",{value:e.title??"",onChange:s=>t({...e,title:s.target.value}),placeholder:"title",style:r})]})}function z5({blockName:e,loading:t,detail:n,graph:r,paths:s,onSelectNode:i,onOpenFull:a,t:l}){if(!e)return o.jsx(nn,{message:"Lineage will appear once the block has a name."});if(t)return o.jsx(nn,{message:"Loading block lineage…"});if(!(n!=null&&n.node))return o.jsxs("div",{style:{padding:12,display:"grid",gap:12},children:[o.jsx("div",{style:{fontSize:12,color:l.textMuted,fontFamily:l.font},children:"No lineage node was found for this block yet. Save the block or compile the project if you expect it to appear in the graph."}),o.jsx("div",{children:o.jsx("button",{onClick:a,style:{background:l.btnBg,border:`1px solid ${l.btnBorder}`,borderRadius:6,color:l.textPrimary,cursor:"pointer",fontSize:11,fontFamily:l.font,padding:"6px 10px"},children:"Open Full Lineage"})})]});const c=`block:${e}`;return o.jsxs("div",{style:{padding:12,display:"grid",gap:12,overflowY:"auto"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:12,fontWeight:700,color:l.textPrimary,fontFamily:l.font},children:n.node.name}),o.jsx("div",{style:{fontSize:11,color:l.textMuted,fontFamily:l.font},children:n.node.domain?`Domain: ${n.node.domain}`:"Block lineage focus"})]}),o.jsx("div",{style:{flex:1}}),o.jsx("button",{onClick:a,style:{background:l.btnBg,border:`1px solid ${l.btnBorder}`,borderRadius:6,color:l.textPrimary,cursor:"pointer",fontSize:11,fontFamily:l.font,padding:"6px 10px"},children:"Open Full Lineage"})]}),(s==null?void 0:s.layerSummary)&&o.jsx(OD,{layerSummary:s.layerSummary,t:l}),r&&r.nodes.length>0&&o.jsx(Vu,{nodes:r.nodes,edges:r.edges,focalNodeId:c,height:360,onNodeClick:i,layoutMode:"flow"}),s&&(s.upstreamPaths.length>0||s.downstreamPaths.length>0)&&o.jsxs("div",{style:{display:"grid",gap:10},children:[s.upstreamPaths.length>0&&o.jsx(Of,{title:"Source to Block",paths:s.upstreamPaths,onNodeClick:i,focalNodeId:c,t:l}),s.downstreamPaths.length>0&&o.jsx(Of,{title:"Block to Consumption",paths:s.downstreamPaths,onNodeClick:i,focalNodeId:c,t:l})]})]})}function X5({metadata:e,draftMetadata:t,onChange:n,t:r}){const s={width:"100%",background:r.inputBg,border:`1px solid ${r.inputBorder}`,borderRadius:6,color:r.textPrimary,fontSize:12,fontFamily:r.font,padding:"8px 10px",outline:"none"},i={name:(t==null?void 0:t.name)||(e==null?void 0:e.name)||"",domain:(t==null?void 0:t.domain)||(e==null?void 0:e.domain)||"uncategorized",description:(t==null?void 0:t.description)||(e==null?void 0:e.description)||"",owner:(t==null?void 0:t.owner)||(e==null?void 0:e.owner)||"",tags:(t==null?void 0:t.tags)||(e==null?void 0:e.tags)||[]};return o.jsxs("div",{style:{display:"grid",gap:10,padding:12},children:[o.jsx("input",{value:i.name,onChange:a=>n({name:a.target.value}),placeholder:"Block name",style:s}),o.jsx("input",{value:i.domain,onChange:a=>n({domain:a.target.value}),placeholder:"Domain",style:s}),o.jsx("input",{value:i.owner,onChange:a=>n({owner:a.target.value}),placeholder:"Owner",style:s}),o.jsx("input",{value:i.description,onChange:a=>n({description:a.target.value}),placeholder:"Description",style:s}),o.jsx("input",{value:i.tags.join(", "),onChange:a=>n({tags:a.target.value.split(",").map(l=>l.trim()).filter(Boolean)}),placeholder:"Tags",style:s})]})}function nn({message:e}){const{state:t}=Re(),n=ce[t.themeMode];return o.jsx("div",{style:{padding:16,fontSize:12,color:n.textMuted},children:e})}const Aa={draft:"#8b949e",review:"#d29922",certified:"#3fb950",deprecated:"#f85149"},K5={draft:["review"],review:["draft"],certified:["deprecated"],deprecated:["draft"]};function q5({currentStatus:e,blockPath:t,onStatusChanged:n,t:r}){const[s,i]=p.useState(!1),a=K5[e]??[],l=async c=>{if(t){i(!0);try{const d=await $.updateBlockStatus(t,c);d.ok&&d.status&&n(d.status)}finally{i(!1)}}};return o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 12px",background:r.pillBg,borderRadius:8},children:[o.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font},children:"Status:"}),o.jsx("span",{style:{fontSize:11,fontWeight:600,color:Aa[e]??r.textMuted,background:`${Aa[e]??r.textMuted}18`,padding:"2px 8px",borderRadius:4,textTransform:"uppercase",letterSpacing:"0.04em",fontFamily:r.font},children:e}),o.jsx("span",{style:{flex:1}}),a.map(c=>o.jsx("button",{onClick:()=>void l(c),disabled:s,style:{background:c==="certified"?"#3fb950":c==="deprecated"?"#f85149":r.btnBg,border:`1px solid ${c==="certified"?"#3fb950":c==="deprecated"?"#f85149":r.btnBorder}`,borderRadius:4,color:c==="certified"||c==="deprecated"?"#fff":r.textSecondary,cursor:s?"not-allowed":"pointer",fontSize:10,fontWeight:600,fontFamily:r.font,padding:"3px 10px",textTransform:"capitalize",opacity:s?.5:1},children:s?"...":c==="certified"?"Certify":c==="deprecated"?"Deprecate":`Move to ${c}`},c))]})}function J5({result:e,t}){var s,i,a;const n=e.checklist,r=n?[["Metadata",n.metadata],["Validation",n.validation],["Run",n.run],["Tests",n.tests],["Chart",n.chart],["Lineage",n.lineage],["AI reviewed",n.aiReviewed]]:[];return o.jsxs("div",{style:{margin:"12px 12px 0",border:`1px solid ${e.ok?"#3fb95055":"#d2992255"}`,borderRadius:8,background:e.ok?"#3fb9500d":"#d299220d",padding:12,display:"grid",gap:10},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsx("span",{style:{fontSize:12,fontWeight:800,color:e.ok?"#3fb950":"#d29922",fontFamily:t.font},children:e.ok?"Certification passed":"Certification needs attention"}),(n==null?void 0:n.checkedAt)&&o.jsx("span",{style:{fontSize:10,color:t.textMuted,fontFamily:t.fontMono},children:n.checkedAt})]}),r.length>0&&o.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:r.map(([l,c])=>o.jsxs("span",{style:{fontSize:11,fontWeight:700,color:c?"#3fb950":"#d29922",background:c?"#3fb95018":"#d2992218",borderRadius:999,padding:"4px 8px"},children:[c?"✓":"!"," ",l]},l))}),e.error&&o.jsx("div",{style:{fontSize:12,color:"#f85149"},children:e.error}),(((s=n==null?void 0:n.blockers)==null?void 0:s.length)??0)>0&&o.jsx("div",{style:{display:"grid",gap:5},children:n.blockers.map((l,c)=>o.jsx("div",{style:{fontSize:12,color:"#d29922",lineHeight:1.4},children:l},c))}),(((a=(i=e.certification)==null?void 0:i.warnings)==null?void 0:a.length)??0)>0&&o.jsx("div",{style:{display:"grid",gap:5},children:e.certification.warnings.map(l=>o.jsxs("div",{style:{fontSize:12,color:t.textMuted},children:[l.rule,": ",l.message]},`${l.rule}-${l.message}`))})]})}function Q5({source:e,blockPath:t,testResults:n,running:r,onRunTests:s,t:i}){const l=[...e.matchAll(/assert\s+(\w+)\s*(>=?|<=?|==|!=|IN)\s*(\S+)/g)].map(c=>({field:c[1],operator:c[2],expected:c[3]}));return o.jsxs("div",{style:{padding:12,display:"grid",gap:10},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsx("span",{style:{fontSize:12,fontWeight:600,color:i.textPrimary,fontFamily:i.font},children:"Test Assertions"}),o.jsx("span",{style:{flex:1}}),o.jsx("button",{onClick:s,disabled:r||!t,style:{background:i.accent,border:"none",borderRadius:6,color:"#fff",cursor:r||!t?"not-allowed":"pointer",fontSize:11,fontWeight:600,fontFamily:i.font,padding:"5px 14px",opacity:r||!t?.5:1},children:r?"Running...":"Run Tests"})]}),l.length===0&&o.jsxs("div",{style:{fontSize:12,color:i.textMuted,fontFamily:i.font,lineHeight:1.5},children:["No test assertions found. Add assertions in your block:",o.jsx("pre",{style:{margin:"8px 0 0",padding:"8px 10px",background:i.editorBg,border:`1px solid ${i.cellBorder}`,borderRadius:6,fontSize:10,fontFamily:i.fontMono,color:i.textSecondary},children:`tests {
|
|
823
|
+
assert row_count > 0
|
|
824
|
+
assert max_value <= 1000000
|
|
825
|
+
}`})]}),l.map((c,d)=>{const u=n==null?void 0:n[d],E=u==null?void 0:u.passed;return o.jsxs("div",{style:{padding:"8px 12px",borderRadius:8,border:`1px solid ${u?E?"#3fb95040":"#f8514940":i.cellBorder}`,background:u?E?"#3fb95008":"#f8514908":"transparent",display:"flex",alignItems:"center",gap:8},children:[u&&o.jsx("span",{style:{fontSize:14,color:E?"#3fb950":"#f85149",fontWeight:700},children:E?"✓":"✗"}),o.jsxs("div",{style:{flex:1},children:[o.jsxs("div",{style:{fontSize:12,color:i.textPrimary,fontFamily:i.fontMono},children:[c.field," ",c.operator," ",c.expected]}),u&&!E&&u.actual&&o.jsxs("div",{style:{fontSize:11,color:"#f85149",fontFamily:i.font,marginTop:2},children:["Actual: ",u.actual]})]})]},d)}),n&&n.length>0&&o.jsxs("div",{style:{padding:"8px 12px",background:i.pillBg,borderRadius:8,fontSize:12,fontFamily:i.font,color:i.textSecondary},children:[n.filter(c=>c.passed).length,"/",n.length," passed"]})]})}function Z5({entries:e,t}){return e.length===0?o.jsx(nn,{message:"No version history available. Commit changes to build history."}):o.jsxs("div",{style:{padding:12,display:"grid",gap:8},children:[o.jsx("div",{style:{fontSize:12,fontWeight:600,color:t.textPrimary,fontFamily:t.font},children:"Version History"}),e.map(n=>o.jsxs("div",{style:{padding:"8px 12px",border:`1px solid ${t.cellBorder}`,borderRadius:8,background:t.inputBg},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:[o.jsx("span",{style:{fontSize:10,fontFamily:t.fontMono,color:t.accent,background:`${t.accent}12`,padding:"1px 6px",borderRadius:4},children:n.hash.slice(0,7)}),o.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.font},children:new Date(n.date).toLocaleDateString()}),o.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.font,marginLeft:"auto"},children:n.author})]}),o.jsx("div",{style:{fontSize:12,color:t.textPrimary,fontFamily:t.font},children:n.message})]},n.hash))]})}function eV({tree:e,totalTree:t,expanded:n,setExpanded:r,onEnsureColumns:s,onInsert:i,query:a,onQueryChange:l,stats:c,connectionName:d,loadingNodes:u,onRefresh:E,t:f}){const T={width:"100%",background:f.inputBg,border:`1px solid ${f.inputBorder}`,borderRadius:8,color:f.textPrimary,fontSize:12,fontFamily:f.font,padding:"8px 10px",outline:"none",boxSizing:"border-box"},A=(R,S=0)=>{var x,_,C;const h=R.kind!=="column",g=n[R.id]??S<1,m=u.has(R.id),I=R.kind==="schema"?(x=R.children)==null?void 0:x.length:R.kind==="table"?(_=R.children)==null?void 0:_.length:void 0,O=R.kind==="column"?R.type:R.kind,N=R.kind==="column"&&R.type?LR(R.type,f.accent):void 0;return o.jsxs("div",{children:[o.jsx(bd,{label:m?`${R.label} …`:R.label,depth:S,count:I,expanded:h?g:void 0,onToggle:h?()=>{r(v=>({...v,[R.id]:!g})),g||s(R)}:void 0,badge:O,badgeColor:N,onClick:()=>{if(R.kind==="table"&&R.path&&i(R.path),R.kind==="column"){const v=R.path?R.path.split(".").pop():"";i(v?`${v}.${R.label}`:R.label)}},onDoubleClick:()=>{R.kind==="table"&&R.path&&i(`SELECT *
|
|
826
|
+
FROM ${R.path}
|
|
827
|
+
LIMIT 100`)},t:f}),h&&g&&((C=R.children)==null?void 0:C.map(v=>A(v,S+1)))]},R.id)};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{padding:12,display:"grid",gap:12,borderBottom:`1px solid ${f.headerBorder}`,background:`${f.cellBg}66`},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:12,fontWeight:700,color:f.textPrimary,fontFamily:f.font},children:"Database Browser"}),o.jsx("div",{style:{fontSize:11,color:f.textMuted,fontFamily:f.font},children:"Browse the active connection, inspect schemas and columns, then insert tables or starter queries into the block."})]}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[o.jsx("button",{onClick:E,title:"Refresh schema",style:{background:"none",border:"none",cursor:"pointer",padding:4,borderRadius:6,color:f.textMuted,fontSize:14,lineHeight:1},children:"↻"}),o.jsx("span",{style:{fontSize:10,fontWeight:700,color:f.accent,background:`${f.accent}18`,borderRadius:999,padding:"5px 9px",textTransform:"uppercase",letterSpacing:"0.04em"},children:d})]})]}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:8},children:[o.jsx(Fc,{label:"Schemas",value:c.schemas,t:f}),o.jsx(Fc,{label:"Tables",value:c.tables,t:f}),o.jsx(Fc,{label:"Columns",value:c.columns,t:f})]}),o.jsx("input",{value:a,onChange:R=>l(R.target.value),placeholder:"Search schemas, tables, columns...",style:T})]}),o.jsx("div",{style:{flex:1,overflowY:"auto",padding:e.length>0?"6px 0 0":0},children:t.length===0?o.jsx(nn,{message:"No schemas were found for the active connection yet."}):e.length===0?o.jsx(nn,{message:"No database objects match the current search."}):e.map(R=>A(R))})]})}function tV({row:e,selectedId:t,setSelectedId:n,expanded:r,setExpanded:s,onInsert:i,favorites:a,dispatch:l,t:c}){var A;const{node:d,depth:u,hasChildren:E,isExpanded:f}=e,T=d.id.split(":").slice(1).join(":");return E?o.jsx(bd,{label:d.label,depth:u,count:(A=d.children)==null?void 0:A.length,expanded:f,onToggle:()=>s(R=>({...R,[d.id]:!f})),onClick:()=>n(d.id),selected:t===d.id,t:c}):o.jsx(bd,{label:d.label,depth:u,badge:d.kind,selected:t===d.id,onClick:()=>n(d.id),onDoubleClick:()=>{$.getSemanticObject(d.id).then(i).catch(()=>{})},onFavoriteToggle:d.kind==="metric"||d.kind==="dimension"?()=>void $.toggleFavorite(T).then(R=>l({type:"SET_SEMANTIC_FAVORITES",favorites:R})):void 0,favorite:d.kind==="metric"||d.kind==="dimension"?a.has(T):void 0,t:c})}function gi(e,t){const n=e.match(/query\s*=\s*"""([\s\S]*?)"""/i);return n?e.replace(n[0],`query = """${n[1].trimEnd()}
|
|
828
|
+
${t}
|
|
829
|
+
"""`):/^\s*block\s+"/i.test(e.trim())?e.replace(/\n\}\s*$/,`
|
|
830
|
+
|
|
831
|
+
query = """
|
|
832
|
+
${t}
|
|
833
|
+
"""
|
|
834
|
+
}
|
|
835
|
+
`):`${e.trimEnd()}
|
|
836
|
+
${t}
|
|
837
|
+
`}function nV(e){const t=n=>{var r;return((r=e.match(new RegExp(`\\b${n}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:r[1])??""};return{metric:t("metric")||vT(e,"metrics")[0]||"",dimensions:vT(e,"dimensions"),timeDimension:t("time_dimension"),granularity:t("granularity")}}function vT(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 rV(e,t){let n=e.replace(/\n\s*metrics\s*=\s*\[[\s\S]*?\]/i,"");return vd(n,"metric",t)}function vd(e,t,n){const r=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),s=new RegExp(`(\\b${t}\\s*=\\s*)"[^"]*"`,"i");return s.test(e)?e.replace(s,`$1"${r}"`):Yg(e,` ${t} = "${r}"`)}function oV(e,t,n){const r=Array.from(new Set(n.filter(Boolean))),s=`${t} = [${r.map(a=>`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(", ")}]`,i=new RegExp(`\\b${t}\\s*=\\s*\\[[\\s\\S]*?\\]`,"i");return i.test(e)?e.replace(i,s):Yg(e,` ${s}`)}function Yg(e,t){return/visualization\s*\{/i.test(e)?e.replace(/\n\s*visualization\s*\{/i,`
|
|
838
|
+
${t}
|
|
839
|
+
|
|
840
|
+
visualization {`):e.replace(/\n\}\s*$/,`
|
|
841
|
+
${t}
|
|
842
|
+
}
|
|
843
|
+
`)}function Gc(e,t){if(!e)return[];const n=new Set,r=s=>{var a;const i=(a=s.meta)==null?void 0:a[t];typeof i=="string"&&i.trim()&&n.add(i.trim());for(const l of s.children??[])r(l)};return r(e),Array.from(n).sort((s,i)=>s.localeCompare(i))}function $g(e,t){var f,T,A,R,S;const n=t.query.trim().toLowerCase(),r=Object.values(e.meta??{}).filter(h=>h!=null).map(h=>String(h).toLowerCase()),s=!n||e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)||r.some(h=>h.includes(n)),i=!t.type||e.kind===t.type||e.kind==="provider"||e.kind==="domain"||e.kind==="group",a=!t.domain||e.kind==="provider"||e.kind==="group"||((f=e.meta)==null?void 0:f.domain)===t.domain||e.kind==="domain"&&e.label===t.domain,l=!t.provider||((T=e.meta)==null?void 0:T.provider)===t.provider||e.id===`provider:${t.provider}`,c=!t.cube||((A=e.meta)==null?void 0:A.cube)===t.cube,d=!t.owner||((R=e.meta)==null?void 0:R.owner)===t.owner,u=!t.tag||String(((S=e.meta)==null?void 0:S.tags)??"").split(",").filter(Boolean).includes(t.tag),E=(e.children??[]).map(h=>$g(h,t)).filter(h=>!!h);return E.length>0?{...e,children:E,count:e.kind==="provider"||e.kind==="domain"||e.kind==="group"?E.length:e.count}:s&&i&&a&&l&&c&&d&&u?{...e,children:[]}:null}function Vg(e,t,n=0){const r=[];for(const s of e){const i=!!(s.children&&s.children.length>0),a=t[s.id]??n<3;r.push({node:s,depth:n,hasChildren:i,isExpanded:a}),i&&a&&r.push(...Vg(s.children??[],t,n+1))}return r}function zg(e,t,n){return e.map(r=>r.id===t?n:r.children?{...r,children:zg(r.children,t,n)}:r)}function sV(e,t){const n=t.trim().toLowerCase();if(!n)return e;const r=s=>{const i=[s.label,s.path,s.type].filter(l=>!!l).some(l=>l.toLowerCase().includes(n)),a=(s.children??[]).map(l=>r(l)).filter(l=>!!l);return i||a.length>0?{...s,children:a}:null};return e.map(s=>r(s)).filter(s=>!!s)}function iV(e){let t=0,n=0,r=0;const s=i=>{i.kind==="schema"&&(t+=1),i.kind==="table"&&(n+=1),i.kind==="column"&&(r+=1);for(const a of i.children??[])s(a)};for(const i of e)s(i);return{schemas:t,tables:n,columns:r}}function aV(e){return!!(e&&e.children&&e.children.length>0)}function lV(e){if(e.metrics.length===0&&e.measures.length===0&&e.dimensions.length===0&&e.timeDimensions.length===0&&e.entities.length===0&&e.hierarchies.length===0&&e.semanticModels.length===0&&e.savedQueries.length===0)return null;const t=e.provider??"dql",n=new Map,r=(i,a)=>{const l=n.get(i)??[];l.push(a),n.set(i,l)};for(const i of e.metrics){const a=i.domain||"uncategorized";r(a,{id:`metric:${i.name}`,label:i.label||i.name,kind:"metric",meta:{provider:t,domain:a,cube:i.table,owner:i.owner??"",tags:i.tags.join(",")}})}for(const i of e.measures){const a=i.domain||"uncategorized";r(a,{id:`measure:${i.name}`,label:i.label||i.name,kind:"measure",meta:{provider:t,domain:a,cube:i.cube??i.table,owner:i.owner??"",tags:i.tags.join(","),agg:i.agg}})}for(const i of e.dimensions){const a=i.domain||"uncategorized";r(a,{id:`dimension:${i.name}`,label:i.label||i.name,kind:"dimension",meta:{provider:t,domain:a,cube:i.table,owner:i.owner??"",tags:i.tags.join(",")}})}for(const i of e.timeDimensions){const a=i.domain||"uncategorized";r(a,{id:`time_dimension:${i.name}`,label:i.label||i.name,kind:"time_dimension",meta:{provider:t,domain:a,cube:i.cube??i.table,owner:i.owner??"",tags:i.tags.join(",")}})}for(const i of e.entities){const a=i.domain||"uncategorized";r(a,{id:`entity:${i.name}`,label:i.label||i.name,kind:"entity",meta:{provider:t,domain:a,cube:i.cube??i.table,owner:i.owner??"",tags:i.tags.join(","),type:i.type}})}for(const i of e.semanticModels){const a=i.domain||"uncategorized";r(a,{id:`semantic_model:${i.name}`,label:i.label||i.name,kind:"semantic_model",meta:{provider:t,domain:a,table:i.table,owner:i.owner??"",tags:i.tags.join(",")}})}for(const i of e.savedQueries){const a=i.domain||"uncategorized";r(a,{id:`saved_query:${i.name}`,label:i.label||i.name,kind:"saved_query",meta:{provider:t,domain:a,owner:i.owner??"",tags:i.tags.join(",")}})}for(const i of e.hierarchies){const a=i.domain||"uncategorized";r(a,{id:`hierarchy:${i.name}`,label:i.label||i.name,kind:"hierarchy",meta:{provider:t,domain:a}})}const s=Array.from(n.entries()).sort((i,a)=>i[0].localeCompare(a[0])).map(([i,a])=>{const l=a.filter(h=>h.kind==="metric"),c=a.filter(h=>h.kind==="measure"),d=a.filter(h=>h.kind==="dimension"),u=a.filter(h=>h.kind==="time_dimension"),E=a.filter(h=>h.kind==="entity"),f=a.filter(h=>h.kind==="hierarchy"),T=a.filter(h=>h.kind==="semantic_model"),A=a.filter(h=>h.kind==="saved_query"),R=[],S=(h,g,m)=>{m.length!==0&&R.push({id:`group:${i}:${g.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,label:g,kind:"group",count:m.length,meta:{provider:t,domain:i,objectKind:h},children:m.sort((I,O)=>I.label.localeCompare(O.label))})};return l.length>0&&S("metric","Metrics",l),S("measure","Measures",c),d.length>0&&S("dimension","Dimensions",d),S("time_dimension","Time Dimensions",u),S("entity","Entities",E),f.length>0&&S("hierarchy","Hierarchies",f),S("semantic_model","Semantic Models",T),S("saved_query","Saved Queries",A),{id:`domain:${t}:${i}`,label:i,kind:"domain",count:R.length,meta:{provider:t,domain:i},children:R}});return{id:"root:semantic",label:"Semantic Layer",kind:"group",children:[{id:`provider:${t}`,label:t.toUpperCase(),kind:"provider",count:s.length,meta:{provider:t},children:s}]}}const Xg={source_table:"TABLE",dbt_model:"DBT",dbt_source:"SOURCE",block:"BLOCK",metric:"METRIC",dimension:"DIM",domain:"DOMAIN",chart:"CHART",dashboard:"NOTEBOOK"};function cV(e,t,n="flow",r="LR"){var a;const s=new ha.graphlib.Graph().setDefaultEdgeLabel(()=>({})),i=r==="LR";s.setGraph({rankdir:r,ranksep:n==="layered"?120:i?80:60,nodesep:i?40:50,marginx:32,marginy:32});for(const l of e){const c={width:190,height:58};if(n==="layered"&&((a=l.data)!=null&&a.layer)){const d=Ji.indexOf(l.data.layer);d>=0&&(c.rank=d)}s.setNode(l.id,c)}for(const l of t)s.setEdge(l.source,l.target);return ha.layout(s),e.map(l=>{const c=s.node(l.id);return{...l,position:{x:c.x-95,y:c.y-29},data:{...l.data,direction:r}}})}function dV({data:e,selected:t}){const n=e.nodeType,r=ze[n]??"var(--color-text-tertiary)",s=Xg[n]??n.toUpperCase(),i=e.direction??"LR",a=i==="LR"?pe.Left:pe.Top,l=i==="LR"?pe.Right:pe.Bottom;return o.jsxs("div",{style:{minWidth:156,maxWidth:220,background:"var(--color-bg-card)",border:`2px solid ${t?"var(--color-accent-blue)":r}`,borderRadius:10,padding:"8px 10px",boxShadow:t?"0 0 0 1px color-mix(in srgb, var(--color-accent-blue) 25%, transparent)":"none"},children:[o.jsx(Gn,{type:"target",position:a,style:{width:7,height:7,background:r,border:"none"}}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[o.jsx("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.04em",color:"var(--color-bg-primary)",background:r,borderRadius:4,padding:"2px 6px"},children:s}),e.domain&&o.jsx("span",{style:{color:"var(--color-text-tertiary)",fontSize:10},children:e.domain})]}),o.jsx("div",{style:{color:"var(--color-text-primary)",fontSize:11,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.label,children:e.label}),o.jsx("div",{style:{color:"var(--color-text-tertiary)",fontSize:10,marginTop:3},children:Ga[n]??n}),o.jsx(Gn,{type:"source",position:l,style:{width:7,height:7,background:r,border:"none"}})]})}const uV={dagNode:dV};function yn({label:e,active:t,color:n,onClick:r}){return o.jsx("button",{onClick:r,style:{borderRadius:999,border:`1px solid ${t?n:"var(--color-border-primary)"}`,background:t?`color-mix(in srgb, ${n} 13%, transparent)`:"transparent",color:t?n:"var(--color-text-tertiary)",fontSize:10,fontWeight:700,padding:"4px 8px",cursor:"pointer"},children:e})}function EV(){const{state:e,dispatch:t}=Re(),n=ce[e.themeMode],[r,s]=p.useState(!0),[i,a]=p.useState({nodes:[],edges:[]}),[l,c]=p.useState({nodes:[],edges:[]}),[d,u]=p.useState(null),[E,f]=p.useState(null),[T,A]=p.useState(""),[R,S]=p.useState([]),[h,g]=p.useState({source_table:!0,dbt_model:!0,dbt_source:!0,block:!0,notebook:!0,dashboard:!0,app:!0,domain:!0}),[m,I]=p.useState("flow"),[O,N]=p.useState("LR"),[x,_,C]=zm([]),[v,b,P]=Xm([]),j=p.useCallback(async()=>{s(!0);const y=await $.fetchLineage(),w={nodes:y.nodes??[],edges:y.edges??[]};a(w),c(w),s(!1)},[]);p.useEffect(()=>{j()},[j]),p.useEffect(()=>{let y=!1;if(T.trim().length<2){S([]);return}return $.searchLineage(T.trim()).then(w=>{y||S(w.matches??[])}),()=>{y=!0}},[T]);const L=p.useMemo(()=>{const y=new Set(l.nodes.filter(w=>h[w.type]??!1).map(w=>w.id));return{nodes:l.nodes.filter(w=>y.has(w.id)),edges:l.edges.filter(w=>y.has(w.source)&&y.has(w.target))}},[l,h]);p.useEffect(()=>{const y=L.nodes.map(F=>({id:F.id,type:"dagNode",position:{x:0,y:0},data:{label:F.name,nodeType:F.type,domain:F.domain,layer:uu(F)}})),w=L.edges.map((F,k)=>({id:`edge-${k}-${F.source}-${F.target}-${F.type}`,source:F.source,target:F.target,style:{stroke:zo[F.type]??"var(--color-text-tertiary)",strokeWidth:1.6},markerEnd:{type:Eo.ArrowClosed,color:zo[F.type]??"var(--color-text-tertiary)",width:12,height:12}}));_(cV(y,w,m,O)),b(w)},[L,m,O,b,_]);const B=p.useCallback(async y=>{const w=await $.queryLineage({focus:y});c(w.graph??{nodes:[],edges:[]}),u(w.focalNode??null),f(w.focalNode??null),t({type:"SET_LINEAGE_FOCUS",nodeId:y}),A(""),S([])},[t]);p.useEffect(()=>{e.lineageFocusNodeId&&B(e.lineageFocusNodeId)},[B,e.lineageFocusNodeId]);const M=p.useCallback(()=>{c(i),u(null),f(null),t({type:"SET_LINEAGE_FOCUS",nodeId:null})},[t,i]),U=p.useCallback(async(y,w)=>{await B(w.id)},[B]),D=p.useMemo(()=>{if(!E)return null;const y=l.edges.filter(F=>F.target===E.id).length,w=l.edges.filter(F=>F.source===E.id).length;return{incoming:y,outgoing:w}},[l.edges,E]);return r?o.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"Loading lineage graph..."}):i.nodes.length===0?o.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"No lineage graph available yet."}):o.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",background:"var(--color-bg-primary)"},children:[o.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`,background:n.sidebarBg},children:[o.jsxs("div",{style:{display:"flex",gap:6,marginBottom:8,flexWrap:"wrap",alignItems:"center"},children:[o.jsxs("div",{style:{display:"flex",borderRadius:6,border:`1px solid ${n.headerBorder}`,overflow:"hidden"},children:[o.jsx("button",{onClick:()=>I("flow"),style:{padding:"4px 8px",fontSize:10,fontWeight:700,border:"none",cursor:"pointer",background:m==="flow"?"var(--color-bg-tertiary)":"transparent",color:m==="flow"?"var(--color-text-primary)":"var(--color-text-tertiary)"},children:"Flow"}),o.jsx("button",{onClick:()=>I("layered"),style:{padding:"4px 8px",fontSize:10,fontWeight:700,border:"none",borderLeft:`1px solid ${n.headerBorder}`,cursor:"pointer",background:m==="layered"?"var(--color-bg-tertiary)":"transparent",color:m==="layered"?"var(--color-text-primary)":"var(--color-text-tertiary)"},children:"Layered"})]}),o.jsxs("div",{style:{display:"flex",borderRadius:6,border:`1px solid ${n.headerBorder}`,overflow:"hidden",marginRight:4},children:[o.jsxs("button",{title:"Horizontal layout (left → right)",onClick:()=>N("LR"),style:{padding:"4px 8px",fontSize:10,fontWeight:700,border:"none",cursor:"pointer",background:O==="LR"?"var(--color-bg-tertiary)":"transparent",color:O==="LR"?"var(--color-text-primary)":"var(--color-text-tertiary)",display:"flex",alignItems:"center",gap:3},children:[o.jsxs("svg",{width:"14",height:"10",viewBox:"0 0 14 10",fill:"none",children:[o.jsx("rect",{x:"0",y:"2",width:"4",height:"6",rx:"1",fill:"currentColor",opacity:"0.7"}),o.jsx("line",{x1:"4",y1:"5",x2:"10",y2:"5",stroke:"currentColor",strokeWidth:"1.2"}),o.jsx("path",{d:"M9 3l2 2-2 2",stroke:"currentColor",strokeWidth:"1.2",fill:"none"}),o.jsx("rect",{x:"10",y:"2",width:"4",height:"6",rx:"1",fill:"currentColor"})]}),"LR"]}),o.jsxs("button",{title:"Vertical layout (top → bottom)",onClick:()=>N("TB"),style:{padding:"4px 8px",fontSize:10,fontWeight:700,border:"none",borderLeft:`1px solid ${n.headerBorder}`,cursor:"pointer",background:O==="TB"?"var(--color-bg-tertiary)":"transparent",color:O==="TB"?"var(--color-text-primary)":"var(--color-text-tertiary)",display:"flex",alignItems:"center",gap:3},children:[o.jsxs("svg",{width:"10",height:"14",viewBox:"0 0 10 14",fill:"none",children:[o.jsx("rect",{x:"2",y:"0",width:"6",height:"4",rx:"1",fill:"currentColor",opacity:"0.7"}),o.jsx("line",{x1:"5",y1:"4",x2:"5",y2:"10",stroke:"currentColor",strokeWidth:"1.2"}),o.jsx("path",{d:"M3 9l2 2 2-2",stroke:"currentColor",strokeWidth:"1.2",fill:"none"}),o.jsx("rect",{x:"2",y:"10",width:"6",height:"4",rx:"1",fill:"currentColor"})]}),"TB"]})]}),o.jsx(yn,{label:"Tables",active:h.source_table,color:ze.source_table,onClick:()=>g(y=>({...y,source_table:!y.source_table}))}),o.jsx(yn,{label:"dbt Models",active:h.dbt_model,color:ze.dbt_model,onClick:()=>g(y=>({...y,dbt_model:!y.dbt_model}))}),o.jsx(yn,{label:"dbt Sources",active:h.dbt_source,color:ze.dbt_source,onClick:()=>g(y=>({...y,dbt_source:!y.dbt_source}))}),o.jsx(yn,{label:"DQL Blocks",active:h.block,color:ze.block,onClick:()=>g(y=>({...y,block:!y.block}))}),o.jsx(yn,{label:"Notebooks",active:h.notebook,color:ze.notebook,onClick:()=>g(y=>({...y,notebook:!y.notebook}))}),o.jsx(yn,{label:"Dashboards",active:h.dashboard,color:ze.dashboard,onClick:()=>g(y=>({...y,dashboard:!y.dashboard}))}),o.jsx(yn,{label:"Apps",active:h.app,color:ze.app,onClick:()=>g(y=>({...y,app:!y.app}))}),o.jsx(yn,{label:"Domains",active:h.domain,color:ze.domain,onClick:()=>g(y=>({...y,domain:!y.domain}))})]}),o.jsxs("div",{style:{display:"flex",gap:8},children:[o.jsx("input",{value:T,onChange:y=>A(y.target.value),placeholder:"Search lineage and focus the graph...",style:{flex:1,padding:"8px 10px",borderRadius:6,border:`1px solid ${n.headerBorder}`,background:"var(--color-bg-sunken)",color:n.textPrimary,fontSize:12,outline:"none"}}),d&&o.jsx("button",{onClick:M,style:{borderRadius:6,border:`1px solid ${n.headerBorder}`,background:"transparent",color:n.textPrimary,cursor:"pointer",fontSize:12,fontWeight:600,padding:"8px 10px"},children:"Show All"})]}),o.jsx("div",{style:{marginTop:8,color:n.textMuted,fontSize:11,lineHeight:1.5},children:"This graph connects raw source tables and dbt DAGs to DQL blocks and the notebooks that consume them. Search to focus on a single path instead of scanning the full project graph."}),R.length>0&&o.jsx("div",{style:{marginTop:8,border:`1px solid ${n.headerBorder}`,borderRadius:8,overflow:"hidden"},children:R.slice(0,8).map(y=>o.jsxs("button",{onClick:()=>void B(y.node.id),style:{width:"100%",textAlign:"left",padding:"8px 10px",background:"transparent",border:"none",borderTop:`1px solid ${n.headerBorder}`,color:n.textPrimary,cursor:"pointer"},children:[o.jsx("span",{style:{color:ze[y.node.type]??"var(--color-text-tertiary)",fontSize:10,fontWeight:700,marginRight:8},children:Xg[y.node.type]??y.node.type.toUpperCase()}),y.node.name]},y.node.id))})]}),o.jsx("div",{style:{flex:1,position:"relative"},children:o.jsxs(Vm,{nodes:x,edges:v,onNodesChange:C,onEdgesChange:P,onNodeClick:U,nodeTypes:uV,fitView:!0,fitViewOptions:{padding:.18},proOptions:{hideAttribution:!0},style:{background:"var(--color-bg-primary)"},children:[o.jsx(qm,{color:"var(--color-border-secondary)",gap:24,size:1}),o.jsx(ck,{showInteractive:!1}),o.jsx(Ik,{nodeColor:y=>{var w;return ze[((w=y.data)==null?void 0:w.nodeType)??"source_table"]??"var(--color-text-tertiary)"},maskColor:"color-mix(in srgb, var(--color-bg-primary) 55%, transparent)",style:{background:"var(--color-bg-sunken)",border:"1px solid var(--color-border-primary)"}}),o.jsx(ho,{position:"top-left",children:o.jsxs("div",{style:{background:"color-mix(in srgb, var(--color-bg-card) 92%, transparent)",border:"1px solid var(--color-border-primary)",borderRadius:8,padding:"8px 10px",minWidth:220,color:"var(--color-text-primary)",fontSize:12},children:[o.jsx("div",{style:{fontWeight:700,marginBottom:4},children:d?d.name:"Full Lineage View"}),o.jsxs("div",{style:{color:"var(--color-text-tertiary)",fontSize:11},children:[l.nodes.length," node(s), ",l.edges.length," edge(s)"]}),o.jsx("div",{style:{color:"var(--color-text-tertiary)",fontSize:11,marginTop:6,lineHeight:1.5},children:d?`Focused on ${Ga[d.type]??d.type}. Upstream shows provenance from tables/dbt; downstream shows DQL and notebook consumption.`:"Full project lineage across source tables, dbt, DQL blocks, and notebooks."}),E&&D&&o.jsxs("div",{style:{marginTop:8,color:"var(--color-text-tertiary)",fontSize:11},children:[D.incoming," upstream, ",D.outgoing," downstream"]})]})}),o.jsx(ho,{position:"bottom-left",children:o.jsx("div",{style:{display:"flex",gap:10,background:"color-mix(in srgb, var(--color-bg-card) 92%, transparent)",border:"1px solid var(--color-border-primary)",borderRadius:8,padding:"6px 10px",color:"var(--color-text-tertiary)",fontSize:10},children:Object.entries(zo).map(([y,w])=>o.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[o.jsx("span",{style:{width:10,height:2,background:w,display:"inline-block"}}),eb[y]??y]},y))})})]})})]})}const fV=[{key:"all",label:"All changes"},{key:"M",label:"Modified"},{key:"A",label:"Added"},{key:"D",label:"Deleted"},{key:"R",label:"Renamed"},{key:"?",label:"Untracked"}];function pV(e){const t=e;return t.trim()==="??"?"?":t[0]==="R"||t[1]==="R"?"R":t.includes("A")?"A":t.includes("D")?"D":"M"}function TV(e){const t=[];for(const n of e){const r=n.status[0]??" ",s=n.status[1]??" ",i=pV(n.status);if(n.status==="??"){t.push({path:n.path,status:"?",staged:!1,partiallyStaged:!1});continue}const a=r!==" "&&r!=="?";a&&(s!==" "&&s!=="?")?(t.push({path:n.path,status:i,staged:!0,partiallyStaged:!0}),t.push({path:n.path,status:i,staged:!1,partiallyStaged:!0})):a?t.push({path:n.path,status:i,staged:!0,partiallyStaged:!1}):t.push({path:n.path,status:i,staged:!1,partiallyStaged:!1})}return t}function SV(){const{state:e}=Re(),t=ce[e.themeMode],[n,r]=p.useState(null),[s,i]=p.useState({current:null,branches:[]}),[a,l]=p.useState({url:null,name:null}),[c,d]=p.useState(null),[u,E]=p.useState(!1),[f,T]=p.useState(null),[A,R]=p.useState(""),[S,h]=p.useState("all"),[g,m]=p.useState(""),[I,O]=p.useState(null),[N,x]=p.useState(null),[_,C]=p.useState(!1),[v,b]=p.useState(!1),[P,j]=p.useState(!1),[L,B]=p.useState(""),M=p.useRef(null),U=p.useCallback(async()=>{C(!0);try{const[se,ge,xe]=await Promise.all([$.fetchGitStatus(),$.fetchGitBranches(),$.fetchGitRemote()]);r(se),i({current:ge.current,branches:ge.branches}),l({url:xe.url,name:xe.name})}finally{window.setTimeout(()=>C(!1),350)}},[]);p.useEffect(()=>{U()},[U]),p.useEffect(()=>{const se=window.setInterval(()=>{U()},4e3);return()=>window.clearInterval(se)},[U]),p.useEffect(()=>{if(!v)return;const se=ge=>{M.current&&!M.current.contains(ge.target)&&(b(!1),j(!1))};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[v]),p.useEffect(()=>{if(!c){T(null);return}let se=!1;return $.fetchGitDiff(c,u).then(ge=>{se||T(ge)}),()=>{se=!0}},[c,u,n]);const D=p.useMemo(()=>TV((n==null?void 0:n.changes)??[]),[n==null?void 0:n.changes]),y=D.filter(se=>se.staged),w=D.filter(se=>!se.staged),F=p.useCallback(se=>!(S!=="all"&&se.status!==S||A&&!se.path.toLowerCase().includes(A.toLowerCase())),[S,A]),k=y.filter(F),V=w.filter(F);p.useEffect(()=>{if(c&&D.some(xe=>xe.path===c&&xe.staged===u))return;const se=V[0]??k[0];se?(d(se.path),E(se.staged)):d(null)},[D,c,u,k,V]);const ee=p.useCallback((se,ge)=>{x({kind:se,text:ge}),window.setTimeout(()=>x(null),3e3)},[]),Y=p.useCallback(async(se,ge,xe)=>{O(se);try{const Fe=await ge();return Fe.ok?(xe&&ee("ok",xe),await U()):ee("err",Fe.error??`${se} failed`),Fe}finally{O(null)}},[ee,U]),te=se=>Y("stage",()=>$.gitStage([se])),ne=se=>Y("unstage",()=>$.gitUnstage([se])),z=se=>{window.confirm(`Discard local changes to ${se}? This cannot be undone.`)&&Y("discard",()=>$.gitDiscard([se]),"Discarded local changes")},oe=()=>Y("stage",async()=>{const se=w.map(ge=>ge.path);return se.length===0?{ok:!0}:$.gitStage(se)}),le=async()=>{const se=g.trim();if(!se)return ee("err","Commit message required");const ge=y.length===0;(await Y("commit",()=>$.gitCommit(se,ge),"Committed")).ok&&m("")},ae=async()=>{const se=g.trim();if(!se)return ee("err","Commit message required");const ge=y.length===0;(await Y("commit",()=>$.gitCommit(se,ge))).ok&&(m(""),await Y("push",()=>$.gitPush(),"Pushed to remote"))},X=()=>Y("pull",()=>$.gitPull(),"Pulled from remote"),H=()=>Y("push",()=>$.gitPush(),"Pushed to remote"),re=se=>{b(!1),Y("checkout",()=>$.gitCheckout(se),`Switched to ${se}`)},ie=async()=>{const se=L.trim();se&&(b(!1),j(!1),B(""),Y("branch",()=>$.gitCreateBranch(se,!0),`Created and switched to ${se}`))},de=D.find(se=>se.path===c&&se.staged===u)??null;return n&&!n.inRepo?o.jsx(CV,{t}):o.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,background:t.appBg},children:[o.jsx(hV,{t,branchCurrent:s.current,branches:s.branches,ahead:(n==null?void 0:n.ahead)??0,behind:(n==null?void 0:n.behind)??0,remoteUrl:a.url,refreshing:_,busy:I,onPull:X,onPush:H,onRefresh:()=>void U(),onCheckout:re,branchMenuOpen:v,setBranchMenuOpen:b,newBranchOpen:P,setNewBranchOpen:j,newBranchName:L,setNewBranchName:B,onCreateBranch:ie,branchMenuRef:M}),o.jsxs("div",{style:{display:"flex",flex:1,minHeight:0,overflow:"hidden"},children:[o.jsx(AV,{t,stagedFiles:k,unstagedFiles:V,totalCount:D.length,selectedPath:c,selectedStaged:u,onSelect:(se,ge)=>{d(se),E(ge)},query:A,setQuery:R,statusFilter:S,setStatusFilter:h,onStage:te,onUnstage:ne,onStageAll:oe,ahead:(n==null?void 0:n.ahead)??0,behind:(n==null?void 0:n.behind)??0,branchCurrent:s.current}),o.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",overflow:"hidden",background:t.appBg},children:[de&&f?o.jsxs(o.Fragment,{children:[o.jsx(mV,{t,entry:de,onStage:()=>te(de.path),onUnstage:()=>ne(de.path),onDiscard:()=>z(de.path),stagedView:u}),o.jsx(gV,{t,diff:f.diff})]}):o.jsx(NV,{t,hasFiles:D.length>0}),o.jsx(xV,{t,commitMsg:g,setCommitMsg:m,stagedCount:y.length,unstagedCount:w.length,onCommit:le,onCommitAndPush:ae,busy:I})]})]}),N&&o.jsx(yV,{t,kind:N.kind,text:N.text})]})}function hV(e){const{t}=e;return o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 20px",borderBottom:`1px solid ${t.headerBorder}`,background:t.appBg,flexShrink:0,whiteSpace:"nowrap"},children:[o.jsx("span",{style:{fontFamily:t.fontMono,fontSize:10,fontWeight:700,letterSpacing:"0.08em",padding:"3px 7px",borderRadius:3,background:`${t.accent}1f`,color:t.accent,border:`1px solid ${t.accent}40`},children:"GIT"}),o.jsx("span",{style:{fontSize:14,fontWeight:500,color:t.textPrimary},children:"Source control"}),o.jsxs("div",{ref:e.branchMenuRef,style:{position:"relative"},children:[o.jsxs("button",{onClick:()=>e.setBranchMenuOpen(!e.branchMenuOpen),style:{display:"inline-flex",alignItems:"center",gap:5,background:t.cellBg,border:`1px solid ${t.cellBorder}`,color:t.textPrimary,padding:"3px 8px",borderRadius:4,fontSize:11,fontFamily:t.fontMono,cursor:"pointer"},children:[o.jsx(Oo,{size:11,strokeWidth:1.75}),e.branchCurrent??"detached",o.jsx(UL,{size:10,strokeWidth:1.75,style:{opacity:.6}})]}),e.branchMenuOpen&&o.jsxs("div",{style:{position:"absolute",top:"calc(100% + 4px)",left:0,minWidth:220,maxHeight:360,overflow:"auto",background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:6,boxShadow:"0 8px 24px rgba(0,0,0,0.18)",padding:"6px 0",zIndex:100},children:[e.branches.map(n=>o.jsxs("button",{onClick:()=>e.onCheckout(n),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"5px 10px",background:"transparent",border:"none",fontFamily:t.fontMono,fontSize:12,color:t.textPrimary,cursor:"pointer",textAlign:"left"},onMouseEnter:r=>r.currentTarget.style.background=t.btnHover,onMouseLeave:r=>r.currentTarget.style.background="transparent",children:[n===e.branchCurrent?o.jsx(hR,{size:11,strokeWidth:2,color:t.success}):o.jsx("span",{style:{width:11,display:"inline-block"}}),n]},n)),o.jsx("div",{style:{borderTop:`1px solid ${t.cellBorder}`,margin:"4px 0"}}),e.newBranchOpen?o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 8px"},children:[o.jsx("input",{autoFocus:!0,value:e.newBranchName,onChange:n=>e.setNewBranchName(n.target.value),onKeyDown:n=>{n.key==="Enter"&&e.onCreateBranch(),n.key==="Escape"&&(e.setNewBranchOpen(!1),e.setNewBranchName(""))},placeholder:"new-branch-name",style:{flex:1,background:t.appBg,color:t.textPrimary,border:`1px solid ${t.cellBorder}`,borderRadius:4,padding:"4px 7px",fontSize:12,fontFamily:t.fontMono,outline:"none"}}),o.jsx("button",{onClick:e.onCreateBranch,style:to(t,"primary"),children:"Create"})]}):o.jsxs("button",{onClick:()=>e.setNewBranchOpen(!0),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"6px 10px",background:"transparent",border:"none",fontSize:12,color:t.accent,cursor:"pointer",textAlign:"left"},onMouseEnter:n=>n.currentTarget.style.background=t.btnHover,onMouseLeave:n=>n.currentTarget.style.background="transparent",children:[o.jsx(D_,{size:11,strokeWidth:1.75}),"Create new branch…"]})]})]}),e.remoteUrl&&o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{fontSize:11,color:t.textMuted},children:"·"}),o.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.fontMono,maxWidth:360,overflow:"hidden",textOverflow:"ellipsis"},title:e.remoteUrl,children:RV(e.remoteUrl)})]}),o.jsx("span",{style:{fontSize:11,color:t.textMuted},children:"·"}),o.jsxs("span",{style:{fontSize:11,color:t.success,display:"inline-flex",alignItems:"center",gap:5},children:[o.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:t.success}}),"ready"]}),o.jsx("div",{style:{flex:1}}),o.jsx("button",{onClick:e.onRefresh,title:"Refresh",style:{background:"transparent",border:`1px solid ${t.btnBorder}`,padding:"6px 8px",borderRadius:5,cursor:"pointer",color:t.textMuted},children:o.jsx(IR,{size:12,strokeWidth:1.75,style:{animation:e.refreshing?"dql-spin 0.6s linear":void 0}})}),o.jsx("style",{children:"@keyframes dql-spin { to { transform: rotate(360deg); } }"}),o.jsxs("button",{onClick:e.onPull,disabled:!!e.busy,style:DT(t),children:[o.jsx(pR,{size:12,strokeWidth:1.75,color:t.warning}),"Pull",e.behind>0&&o.jsx("span",{style:{fontFamily:t.fontMono,fontSize:10,color:t.textMuted,marginLeft:2},children:e.behind})]}),o.jsxs("button",{onClick:e.onPush,disabled:!!e.busy,style:DT(t,!0),children:[o.jsx(TR,{size:12,strokeWidth:1.75}),"Push",e.ahead>0&&o.jsx("span",{style:{fontFamily:t.fontMono,fontSize:10,opacity:.75,marginLeft:2},children:e.ahead})]})]})}function DT(e,t=!1){return{display:"inline-flex",alignItems:"center",gap:5,background:t?e.accent:e.cellBg,color:t?"#fff":e.textPrimary,border:`1px solid ${t?e.accent:e.btnBorder}`,padding:"5px 12px",borderRadius:6,fontSize:12,fontFamily:e.font,fontWeight:t?500:400,cursor:"pointer",whiteSpace:"nowrap"}}function to(e,t="default"){return{background:t==="primary"?e.accent:e.cellBg,color:t==="primary"?"#fff":e.textPrimary,border:`1px solid ${t==="primary"?e.accent:e.btnBorder}`,padding:"4px 9px",borderRadius:4,fontSize:11,cursor:"pointer",whiteSpace:"nowrap",fontFamily:e.font}}function RV(e){return e.replace(/^git@([^:]+):/,"$1/").replace(/^https?:\/\//,"").replace(/\.git$/,"")}function AV(e){const{t}=e;return o.jsxs("div",{style:{width:300,flexShrink:0,background:t.sidebarBg,borderRight:`1px solid ${t.headerBorder}`,display:"flex",flexDirection:"column",overflow:"hidden"},children:[o.jsxs("div",{style:{padding:"12px 14px 10px",borderBottom:`1px solid ${t.headerBorder}`},children:[o.jsx("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:8,fontSize:10,fontWeight:600,letterSpacing:"0.08em",textTransform:"uppercase",color:t.textMuted},children:"Source control"}),o.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[o.jsx("span",{style:{fontSize:18,fontWeight:700,letterSpacing:"-0.01em",color:t.textPrimary},children:"Changes"}),o.jsxs("span",{style:{fontSize:11,color:t.textMuted},children:[e.totalCount," files"]}),o.jsx("div",{style:{flex:1}}),e.unstagedFiles.length>0&&o.jsx("button",{onClick:e.onStageAll,style:to(t),children:"Stage all"})]}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:6,padding:"5px 9px",marginBottom:7},children:[o.jsx(w_,{size:11,strokeWidth:1.75,color:t.textMuted}),o.jsx("input",{value:e.query,onChange:n=>e.setQuery(n.target.value),placeholder:"Filter by path…",style:{background:"transparent",border:"none",outline:"none",color:t.textPrimary,fontSize:12,flex:1,width:"100%",fontFamily:t.font}}),e.query&&o.jsx("button",{onClick:()=>e.setQuery(""),style:{background:"transparent",border:"none",color:t.textMuted,cursor:"pointer",padding:0},children:o.jsx(du,{size:11,strokeWidth:1.75})})]}),o.jsx("select",{value:e.statusFilter,onChange:n=>e.setStatusFilter(n.target.value),style:{width:"100%",background:t.cellBg,color:t.textPrimary,border:`1px solid ${t.cellBorder}`,borderRadius:6,padding:"5px 9px",fontSize:12,cursor:"pointer",fontFamily:t.font},children:fV.map(n=>o.jsx("option",{value:n.key,children:n.label},n.key))})]}),o.jsxs("div",{style:{flex:1,overflow:"auto",padding:"6px 8px"},children:[o.jsx(MT,{t,label:"Staged",count:e.stagedFiles.length}),e.stagedFiles.length===0?o.jsx("div",{style:{fontSize:11,color:t.textMuted,padding:"4px 10px",fontStyle:"italic"},children:"No staged changes"}):e.stagedFiles.map(n=>o.jsx(PT,{t,file:n,active:e.selectedPath===n.path&&e.selectedStaged===!0,onClick:()=>e.onSelect(n.path,!0),actionLabel:"Unstage",onAction:()=>e.onUnstage(n.path)},`staged-${n.path}`)),o.jsx("div",{style:{height:8}}),o.jsx(MT,{t,label:"Changes",count:e.unstagedFiles.length}),e.unstagedFiles.length===0?o.jsx("div",{style:{fontSize:11,color:t.textMuted,padding:"4px 10px",fontStyle:"italic"},children:e.totalCount===0?"Working tree clean":"No unstaged changes"}):e.unstagedFiles.map(n=>o.jsx(PT,{t,file:n,active:e.selectedPath===n.path&&e.selectedStaged===!1,onClick:()=>e.onSelect(n.path,!1),actionLabel:"Stage",onAction:()=>e.onStage(n.path)},`unstaged-${n.path}`))]}),o.jsxs("div",{style:{padding:"10px 14px",borderTop:`1px solid ${t.headerBorder}`,fontSize:10,color:t.textMuted,display:"flex",alignItems:"center",gap:6},children:[o.jsx(Oo,{size:11,strokeWidth:1.75}),o.jsx("span",{style:{fontFamily:t.fontMono,color:t.textPrimary},children:e.branchCurrent??"detached"}),o.jsx("span",{children:"·"}),e.behind>0&&o.jsxs("span",{style:{color:t.warning},children:["↓",e.behind]}),e.ahead>0&&o.jsxs("span",{style:{color:t.success},children:["↑",e.ahead]}),e.behind===0&&e.ahead===0&&o.jsx("span",{children:"up to date"})]})]})}function MT({t:e,label:t,count:n}){return o.jsxs("div",{style:{fontSize:10,color:e.textMuted,fontWeight:600,letterSpacing:"0.07em",textTransform:"uppercase",padding:"6px 8px 4px",display:"flex",alignItems:"center",gap:6},children:[o.jsx("span",{children:t}),o.jsx("span",{style:{color:e.textMuted,opacity:.7},children:"·"}),o.jsx("span",{style:{color:e.textMuted},children:n})]})}function PT({t:e,file:t,active:n,onClick:r,actionLabel:s,onAction:i}){const[a,l]=p.useState(!1),c=t.path.split("/").slice(0,-1).join("/"),d=t.path.split("/").pop()??t.path;return o.jsxs("div",{onClick:r,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",borderRadius:5,marginBottom:1,cursor:"pointer",background:n?`${e.accent}18`:a?e.btnHover:"transparent",border:n?`1px solid ${e.accent}45`:"1px solid transparent"},children:[o.jsx(Kg,{t:e,status:t.status}),o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsx("div",{style:{fontSize:12,color:e.textPrimary,fontFamily:e.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d}),c&&o.jsx("div",{style:{fontSize:10,color:e.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c})]}),a&&o.jsx("button",{onClick:u=>{u.stopPropagation(),i()},style:{background:e.cellBg,border:`1px solid ${e.btnBorder}`,color:e.textPrimary,padding:"2px 7px",borderRadius:3,fontSize:10,cursor:"pointer",flexShrink:0,fontFamily:e.font},children:s})]})}function Kg({t:e,status:t}){const r={M:e.warning,A:e.success,D:e.error,R:e.accent,"?":e.textMuted}[t];return o.jsx("span",{style:{width:18,height:18,borderRadius:3,flexShrink:0,background:`${r}1a`,color:r,border:`1px solid ${r}40`,display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:10,fontWeight:700,fontFamily:e.fontMono},children:t})}function mV({t:e,entry:t,stagedView:n,onStage:r,onUnstage:s,onDiscard:i}){return o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"12px 20px",borderBottom:`1px solid ${e.headerBorder}`,background:e.cellBg,flexShrink:0},children:[o.jsx(Kg,{t:e,status:t.status}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,minWidth:0,flex:1},children:[o.jsx("div",{style:{fontSize:13,fontWeight:500,color:e.textPrimary,fontFamily:e.fontMono},children:t.path}),o.jsxs("div",{style:{fontSize:11,color:e.textMuted,display:"flex",gap:8},children:[o.jsx("span",{children:n?"Staged changes":"Unstaged changes"}),t.partiallyStaged&&o.jsxs(o.Fragment,{children:[o.jsx("span",{children:"·"}),o.jsx("span",{style:{color:e.warning},children:"partially staged"})]})]})]}),!n&&o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:i,style:to(e),children:"Discard"}),o.jsx("button",{onClick:r,style:to(e,"primary"),children:"Stage"})]}),n&&o.jsx("button",{onClick:s,style:to(e),children:"Unstage"})]})}function gV({t:e,diff:t}){return t.trim()?o.jsx("div",{style:{flex:1,overflow:"auto",background:e.cellBg,fontFamily:e.fontMono,fontSize:12,lineHeight:"20px"},children:IV(t).map((n,r)=>o.jsx(OV,{t:e,line:n},r))}):o.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",color:e.textMuted,fontSize:13,background:e.appBg},children:"No textual diff (binary file or empty change)"})}function IV(e){const t=[];let n=0,r=0;const s=e.split(`
|
|
844
|
+
`);let i=0;for(const a of s){if(i++>1e3){t.push({kind:"meta",text:"… diff truncated (over 1000 lines)",oldNum:null,newNum:null});break}if(!(a.startsWith("diff --git")||a.startsWith("index ")||a.startsWith("+++ ")||a.startsWith("--- "))){if(a.startsWith("@@")){const l=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(a);l&&(n=Number(l[1]),r=Number(l[2])),t.push({kind:"hunk",text:a,oldNum:null,newNum:null});continue}a.startsWith("+")?t.push({kind:"add",text:a.slice(1),oldNum:null,newNum:r++}):a.startsWith("-")?t.push({kind:"del",text:a.slice(1),oldNum:n++,newNum:null}):a.startsWith("\\")?t.push({kind:"meta",text:a,oldNum:null,newNum:null}):t.push({kind:"ctx",text:a.startsWith(" ")?a.slice(1):a,oldNum:n++,newNum:r++})}}return t}function OV({t:e,line:t}){if(t.kind==="hunk")return o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"80px 1fr",background:`${e.accent}14`,borderTop:`1px solid ${e.accent}30`,borderBottom:`1px solid ${e.accent}30`,color:e.accent},children:[o.jsx("div",{style:{padding:"2px 10px",textAlign:"right",borderRight:`1px solid ${e.accent}30`,color:e.textMuted},children:"⋯"}),o.jsx("div",{style:{padding:"2px 12px",whiteSpace:"pre"},children:t.text})]});if(t.kind==="meta")return o.jsx("div",{style:{padding:"2px 12px",color:e.textMuted,fontStyle:"italic"},children:t.text});const n={add:{bg:`${e.success}18`,gutter:`${e.success}55`,ch:"+",chColor:e.success},del:{bg:`${e.error}18`,gutter:`${e.error}55`,ch:"−",chColor:e.error},ctx:{bg:"transparent",gutter:e.cellBorder,ch:" ",chColor:e.textMuted}}[t.kind];return o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"40px 40px 20px 1fr",background:n.bg,borderLeft:`3px solid ${n.gutter}`},children:[o.jsx("div",{style:{padding:"0 6px",color:e.textMuted,textAlign:"right",userSelect:"none"},children:t.oldNum??""}),o.jsx("div",{style:{padding:"0 6px",color:e.textMuted,textAlign:"right",userSelect:"none",borderRight:`1px solid ${e.cellBorder}`},children:t.newNum??""}),o.jsx("div",{style:{padding:"0 4px",color:n.chColor,textAlign:"center",userSelect:"none"},children:n.ch}),o.jsx("div",{style:{padding:"0 10px",whiteSpace:"pre",color:e.textPrimary,overflow:"hidden"},children:t.text})]})}function NV({t:e,hasFiles:t}){return o.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:8,color:e.textMuted,fontSize:13,background:e.appBg},children:[o.jsx(mR,{size:28,strokeWidth:1.5,color:e.textMuted,style:{opacity:.4}}),t?"Select a file to view its diff":"Working tree clean — no changes to review"]})}function xV({t:e,commitMsg:t,setCommitMsg:n,stagedCount:r,unstagedCount:s,onCommit:i,onCommitAndPush:a,busy:l}){const c=r===0&&s>0,d=r===0&&s===0,u=c?`Will stage all ${s} change${s===1?"":"s"} and commit`:r>0?`Committing ${r} staged file${r===1?"":"s"}`:"Nothing to commit";return o.jsxs("div",{style:{padding:"12px 20px",borderTop:`1px solid ${e.headerBorder}`,background:e.cellBg,flexShrink:0,display:"flex",flexDirection:"column",gap:6},children:[o.jsx("div",{style:{fontSize:10,color:e.textMuted,letterSpacing:"0.04em"},children:u}),o.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center"},children:[o.jsx("input",{value:t,onChange:E=>n(E.target.value),onKeyDown:E=>{(E.metaKey||E.ctrlKey)&&E.key==="Enter"&&(E.preventDefault(),i())},placeholder:"Commit message (⌘↵ to commit)…",style:{flex:1,background:e.appBg,color:e.textPrimary,border:`1px solid ${e.cellBorder}`,borderRadius:6,padding:"7px 10px",fontSize:12,outline:"none",fontFamily:e.font}}),o.jsx("button",{onClick:i,disabled:!!l||d||!t.trim(),style:{...to(e),padding:"7px 12px",fontSize:12,opacity:d||!t.trim()?.45:1},children:"Commit"}),o.jsx("button",{onClick:a,disabled:!!l||d||!t.trim(),style:{background:e.success,color:"#fff",border:`1px solid ${e.success}`,padding:"7px 14px",borderRadius:6,fontSize:12,fontWeight:500,cursor:"pointer",opacity:d||!t.trim()?.5:1,fontFamily:e.font},children:"Commit & Push"})]})]})}function yV({t:e,kind:t,text:n}){const r=t==="ok"?e.success:e.error;return o.jsx("div",{style:{position:"absolute",bottom:80,right:24,background:e.cellBg,border:`1px solid ${r}55`,borderLeft:`3px solid ${r}`,borderRadius:6,padding:"8px 14px",fontSize:12,color:e.textPrimary,boxShadow:"0 8px 24px rgba(0,0,0,0.18)",maxWidth:420,zIndex:200},children:n})}function CV({t:e}){return o.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:12,padding:40,background:e.appBg},children:[o.jsx(Oo,{size:36,strokeWidth:1.5,color:e.textMuted,style:{opacity:.5}}),o.jsx("div",{style:{fontSize:16,fontWeight:600,color:e.textPrimary},children:"Not a git repository"}),o.jsxs("div",{style:{fontSize:13,color:e.textMuted,maxWidth:420,textAlign:"center"},children:["Initialize this folder with ",o.jsx("code",{style:{fontFamily:e.fontMono},children:"git init"})," to start tracking changes."]})]})}function LV({app:e}){var l,c;const{state:t,dispatch:n}=Re(),[r,s]=p.useState(!1),i=p.useRef(null);p.useEffect(()=>{if(!r)return;const d=u=>{var E;(E=i.current)!=null&&E.contains(u.target)||s(!1)};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[r]);const a=t.activePersona?`${t.activePersona.displayName??t.activePersona.userId} [${t.activePersona.roles.join(", ")}]`:"View as: Owner";return!e||e.members.length===0?o.jsx("span",{style:{fontSize:12,opacity:.6},children:a}):o.jsxs("div",{ref:i,style:{position:"relative"},children:[o.jsxs("button",{onClick:()=>s(d=>!d),style:{padding:"6px 12px",fontSize:12,background:"var(--surface, rgba(0,0,0,0.04))",border:"1px solid var(--border-color, rgba(0,0,0,0.1))",borderRadius:6,cursor:"pointer",color:"inherit",display:"inline-flex",alignItems:"center",gap:6},"aria-haspopup":"menu","aria-expanded":r,children:[o.jsx("span",{style:{fontSize:11,opacity:.65},children:"View as:"}),o.jsx("span",{style:{fontWeight:600},children:((l=t.activePersona)==null?void 0:l.displayName)??((c=t.activePersona)==null?void 0:c.userId)??"Owner"}),t.activePersona&&o.jsxs("span",{style:{fontSize:11,opacity:.7},children:["[",t.activePersona.roles.join(", "),"]"]}),o.jsx("span",{style:{fontSize:10,opacity:.6},children:"▾"})]}),r&&o.jsxs("div",{role:"menu",style:{position:"absolute",top:"100%",right:0,marginTop:4,minWidth:240,background:"var(--surface-elevated, #fff)",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,boxShadow:"0 4px 12px rgba(0,0,0,0.08)",zIndex:50},children:[o.jsxs("button",{role:"menuitem",onClick:async()=>{await $.clearPersona(),n({type:"SET_ACTIVE_PERSONA",persona:null}),s(!1)},style:wT(t.activePersona===null),children:[o.jsx("div",{style:{fontWeight:500},children:"Owner (local)"}),o.jsx("div",{style:{fontSize:11,opacity:.65},children:"Default — no RLS narrowing"})]}),o.jsx("div",{style:{height:1,background:"var(--border-color, rgba(0,0,0,0.08))",margin:"4px 0"}}),e.members.map(d=>{var u;return o.jsxs("button",{role:"menuitem",onClick:async()=>{const E=await $.setPersona(d.userId,e.id);n({type:"SET_ACTIVE_PERSONA",persona:E}),s(!1)},style:wT(((u=t.activePersona)==null?void 0:u.userId)===d.userId),children:[o.jsx("div",{style:{fontWeight:500},children:d.displayName??d.userId}),o.jsxs("div",{style:{fontSize:11,opacity:.65},children:["[",d.roles.join(", "),"]",d.attributes&&Object.keys(d.attributes).length>0?` · ${Object.entries(d.attributes).map(([E,f])=>`${E}=${f}`).join(", ")}`:""]})]},d.userId)})]})]})}function wT(e){return{display:"block",width:"100%",textAlign:"left",padding:"8px 12px",background:e?"var(--surface-hover, rgba(0,0,0,0.06))":"transparent",border:"none",cursor:"pointer",color:"inherit",fontSize:13}}function _V({title:e,scopeHint:t,upstreamContext:n,themeMode:r,hideSqlByDefault:s=!1,addToAppTarget:i,conversationTarget:a,onConversationUpdated:l,expanded:c=!1,onToggleExpanded:d,onClose:u}){const E=ce[r],[f,T]=p.useState([]),[A,R]=p.useState(""),[S,h]=p.useState(!1),[g,m]=p.useState(""),[I,O]=p.useState([]),[N,x]=p.useState(null),[_,C]=p.useState(null),v=p.useRef(null),b=async()=>{const P=A.trim();if(!P||S)return;const j={id:UT(),role:"user",content:P,createdAt:new Date().toISOString()},L=[...f,j];T(L),R(""),x(null),m(""),O([]),h(!0);const B=new AbortController;v.current=B;let M="";const U=[];let D=_;try{if(a&&!D){const w=await $.createAppConversation(a.appId,{title:P.slice(0,80),dashboardId:a.dashboardId,notebookPath:a.notebookPath,messages:BT(L)});w.ok&&(D=w.conversation.id,C(D),l==null||l())}await oA({messages:L.map(w=>({role:w.role,content:w.content})),upstream:{cellId:`scope:${e}`,sql:n},signal:B.signal},w=>{U.push(w),O([...U]),w.kind==="text"&&(M+=s?bV(w.text):w.text,m(M)),w.kind==="error"&&x(w.message)});const y=[...L,{id:UT(),role:"assistant",content:M,events:U,createdAt:new Date().toISOString()}];T(y),a&&D&&(await $.updateAppConversation(a.appId,D,{messages:BT(y)}),l==null||l())}catch(y){x(y instanceof Error?y.message:String(y))}finally{h(!1),m(""),O([]),v.current=null}};return o.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,background:E.cellBg},children:[o.jsx("div",{style:{padding:12,borderBottom:`1px solid ${E.headerBorder}`},children:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsx("div",{style:{fontSize:13,fontWeight:700},children:e}),o.jsxs("div",{style:{fontSize:11,color:E.textSecondary,marginTop:2},children:[t," · Provider from Settings"]})]}),d&&o.jsx("button",{type:"button",onClick:d,title:c?"Collapse chat":"Expand chat",style:kT(E),children:c?o.jsx(m_,{size:14}):o.jsx(gR,{size:14})}),u&&o.jsx("button",{type:"button",onClick:u,title:"Close chat",style:kT(E),children:o.jsx(du,{size:14})})]})}),o.jsxs("div",{style:{flex:1,minHeight:0,overflow:"auto",padding:12,display:"flex",flexDirection:"column",gap:10},children:[f.length===0&&!S?o.jsx("div",{style:{fontSize:12,color:E.textSecondary,lineHeight:1.45},children:"Ask about metric definitions, filters, tile results, or where to find certified analysis."}):null,f.map((P,j)=>o.jsx(jT,{message:P,t:E,themeMode:r,hideSqlByDefault:s,addToAppTarget:i},j)),S&&o.jsx(jT,{message:{role:"assistant",content:g||"Thinking...",events:I},t:E,live:!0,themeMode:r,hideSqlByDefault:s,addToAppTarget:i})]}),N&&o.jsx("div",{style:{margin:"0 12px 8px",color:"#ff7b72",fontSize:12},children:N}),o.jsxs("div",{style:{padding:12,borderTop:`1px solid ${E.headerBorder}`,display:"flex",gap:8,alignItems:"flex-end"},children:[o.jsx("textarea",{value:A,onChange:P=>R(P.target.value),rows:2,placeholder:"Ask this context...",onKeyDown:P=>{P.key==="Enter"&&(P.metaKey||P.ctrlKey)&&(P.preventDefault(),b())},style:{flex:1,resize:"vertical",minHeight:42,...vV(E)}}),S?o.jsx("button",{type:"button",onClick:()=>{var P;return(P=v.current)==null?void 0:P.abort()},style:FT(E,!1),children:"Stop"}):o.jsx("button",{type:"button",onClick:()=>void b(),disabled:!A.trim(),style:FT(E,!0),children:"Ask"})]})]})}function UT(){return`msg_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function BT(e){return e.map(t=>({id:t.id,role:t.role,content:t.content,events:t.events,createdAt:t.createdAt}))}function jT({message:e,t,live:n,themeMode:r,hideSqlByDefault:s,addToAppTarget:i}){const a=e.role==="user",l=a?null:Iu(e.events??[]);return l?o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[o.jsx("div",{style:{fontSize:10,color:n?t.accent:t.textMuted,textTransform:"uppercase",fontWeight:700},children:"DQL Agent"}),o.jsx(Ou,{answer:l,themeMode:r,showSql:!s,compact:!0,addToAppTarget:i})]}):o.jsxs("div",{style:{border:`1px solid ${a?`${t.accent}55`:t.headerBorder}`,borderRadius:8,padding:10,background:a?`${t.accent}12`:t.appBg,whiteSpace:l?"normal":"pre-wrap",fontSize:12,lineHeight:1.5},children:[o.jsx("div",{style:{fontSize:10,color:n?t.accent:t.textMuted,textTransform:"uppercase",fontWeight:700,marginBottom:4},children:a?"You":"DQL Agent"}),e.content]})}function bV(e){return e.replace(/Proposed SQL:\s*```sql[\s\S]*?```/gi,"Proposed SQL hidden in dashboard mode. Send to analyst review to inspect.")}function vV(e){return{border:`1px solid ${e.headerBorder}`,borderRadius:6,background:e.appBg,color:e.textPrimary,fontSize:12,padding:"7px 8px",fontFamily:e.font}}function kT(e){return{width:28,height:28,border:`1px solid ${e.headerBorder}`,borderRadius:6,background:e.appBg,color:e.textPrimary,cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:0}}function FT(e,t){return{border:`1px solid ${t?e.accent:e.headerBorder}`,borderRadius:6,background:t?`${e.accent}22`:e.appBg,color:t?e.accent:e.textPrimary,padding:"8px 12px",cursor:"pointer",fontSize:12}}const GT="clamp(320px, calc(100vh - 220px), 760px)",qg=[{value:"table",label:"Table"},...zn],Jg=[{id:"auto",label:"Auto fit",description:"Choose a practical size from the tile content"},{id:"compact",label:"Compact",description:"Small KPI or short summary"},{id:"standard",label:"Standard",description:"Default chart or table card"},{id:"wide",label:"Wide",description:"Full-row trend or comparison"},{id:"tall",label:"Tall",description:"More vertical room for tables and dense charts"},{id:"full",label:"Full page",description:"Large focused view across the page"}];function DV({appId:e,dashboard:t,editable:n=!1,onDashboardChanged:r}){var ae;const{state:s}=Re(),[i,a]=p.useState(null),[l,c]=p.useState(!1),[d,u]=p.useState(null),[E,f]=p.useState(!1),[T,A]=p.useState(!1),[R,S]=p.useState([]),[h,g]=p.useState(""),[m,I]=p.useState(!1),[O,N]=p.useState(null),[x,_]=p.useState(!1),[C,v]=p.useState(!1),[b,P]=p.useState(!1),[j,L]=p.useState(null),[B,M]=p.useState(""),U=p.useRef(null),D=t.layout.cols,y=t.layout.rowHeight,w=p.useMemo(()=>{const X=new Map;for(const H of(i==null?void 0:i.tiles)??[])X.set(H.tileId,H);return X},[i]);p.useEffect(()=>{let X=!1;return c(!0),u(null),$.runDashboard(e,t.id).then(H=>{X||(a(H),H||u("Dashboard run failed."))}).catch(H=>{X||u(H instanceof Error?H.message:String(H))}).finally(()=>{X||c(!1)}),()=>{X=!0}},[e,t.id,t.layout.items.length,(ae=s.activePersona)==null?void 0:ae.userId]),p.useEffect(()=>{const X=H=>{const re=H.detail;(re==null?void 0:re.appId)!==e||re.dashboardId!==t.id||($.getDashboard(e,t.id).then(ie=>{ie!=null&&ie.dashboard&&(r==null||r(ie.dashboard))}),$.runDashboard(e,t.id).then(ie=>{ie&&a(ie)}))};return window.addEventListener("dql-app-dashboard-updated",X),()=>window.removeEventListener("dql-app-dashboard-updated",X)},[e,t.id,r]);const F=p.useMemo(()=>{const X=t.layout.items.map(H=>{var de;const re=w.get(H.i),ie=H.block?"blockId"in H.block?H.block.blockId:H.block.ref:H.aiPin?`aiPin:${H.aiPin.id}`:"text";return{title:H.title,blockRef:ie,viz:H.viz.type,certificationStatus:re==null?void 0:re.certificationStatus,status:re==null?void 0:re.status,rowCount:(de=re==null?void 0:re.result)==null?void 0:de.rowCount}});return JSON.stringify({scope:"dashboard",appId:e,dashboardId:t.id,title:t.metadata.title,description:t.metadata.description,domain:t.metadata.domain,filters:t.filters,tiles:X},null,2)},[e,t,w]),k=p.useCallback(async X=>{_(!0);const H={...t,layout:{...t.layout,items:X}},re=await $.patchDashboardLayout(e,t.id,H.layout);_(!1),re.ok?r==null||r(re.dashboard):u(re.error)},[e,t,r]),V=p.useCallback(async()=>{A(!0);const X=await $.getAppEditorCatalog(e);S((X==null?void 0:X.blocks)??[])},[e]),ee=p.useCallback(async X=>{const H=tI(X.chartType),re=Ku(H,D),ie={i:Wc(t,X.name),...Hc(t,re),block:{blockId:X.name},viz:{type:H},title:X.name};await k([...t.layout.items,ie]),A(!1)},[D,t,k]),Y=p.useCallback(async()=>{L("text"),M("")},[]),te=p.useCallback(async()=>{L("heading"),M("")},[]),ne=p.useCallback(async()=>{var H;const X=B.trim();if(!(!X||!j)){if(j==="heading")await k([...t.layout.items,{i:Wc(t,"section"),...Hc(t,qt("wide",D,"heading")),text:{markdown:X},viz:{type:"heading"},title:X}]);else{const re=((H=X.split(/\r?\n/)[0])==null?void 0:H.slice(0,60))||"Summary";await k([...t.layout.items,{i:Wc(t,"text"),...Hc(t,qt("standard",D,"text")),text:{markdown:X},viz:{type:"text"},title:re}])}L(null),M("")}},[D,t,k,j,B]),z=p.useCallback(async(X,H)=>{const re=H===null?t.layout.items.filter(ie=>ie.i!==X):t.layout.items.map(ie=>ie.i===X?{...ie,...H}:ie);await k(XT(re,D))},[D,t.layout.items,k]),oe=p.useCallback(async(X,H)=>{const re=U.current,ie=t.layout.items.find(Le=>Le.i===X);if(!re||!ie)return;const de=re.getBoundingClientRect(),se=12,xe=(de.width-se*(D-1))/D+se,Fe=y+se,Z=Math.round((H.clientX-de.left)/xe),Ee=Math.round((H.clientY-de.top)/Fe),Oe={...ie,x:qu(Z,0,Math.max(0,D-ie.w)),y:Math.max(0,Ee)},ve=t6(t.layout.items,Oe,D);await k(XT(ve,D))},[D,t.layout.items,y,k]),le=p.useCallback(async()=>{if(I(X=>!X),!O){const X=await $.fetchScopedLineage({domain:t.metadata.domain,appId:e,dashboardId:t.id});N(X)}},[e,t.id,t.metadata.domain,O]);return o.jsxs("div",{style:{display:"flex",gap:16,minHeight:0,alignItems:"flex-start"},children:[o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,marginBottom:16},children:[o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsx("h2",{style:{margin:0,fontSize:18},children:t.metadata.title}),t.metadata.description?o.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:4},children:t.metadata.description}):null]}),n&&t.layout.items.length>0&&o.jsx(WT,{open:C,onToggle:()=>v(X=>!X),onCertifiedBlock:()=>{v(!1),V()},onText:()=>{v(!1),Y()},onHeading:()=>{v(!1),te()},onAi:()=>{v(!1),f(!0)}}),o.jsx("button",{type:"button",onClick:()=>{v(!1),f(X=>!X)},style:hs(E),children:E?"Hide AI":"Ask AI"}),o.jsx("button",{type:"button",onClick:()=>void le(),style:hs(m),children:"Lineage"})]}),n&&o.jsxs("div",{style:{marginBottom:12,display:"flex",gap:8,alignItems:"center",fontSize:12,color:"var(--color-text-secondary, rgba(0,0,0,0.64))"},children:[o.jsx("span",{children:x?"Saving layout...":"Edit layout"}),o.jsxs("span",{children:[t.layout.items.length," tile",t.layout.items.length===1?"":"s"]})]}),t.layout.items.length===0?o.jsxs("div",{style:{border:"1px dashed var(--border-color, rgba(0,0,0,0.15))",borderRadius:8,padding:36,textAlign:"center",fontSize:13,minHeight:260,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},children:[o.jsx("div",{style:{fontSize:16,fontWeight:700,marginBottom:6},children:"Build this dashboard page"}),o.jsx("div",{style:{maxWidth:520,opacity:.68,lineHeight:1.45},children:"Add certified domain blocks, narrative text, or use the scoped AI drawer and pin an answer into this layout."}),o.jsx("div",{style:{marginTop:18,display:"flex",gap:8,flexWrap:"wrap",justifyContent:"center"},children:o.jsx(WT,{open:C,onToggle:()=>v(X=>!X),buttonLabel:"+ Add",buttonStyle:Zg,onCertifiedBlock:()=>{v(!1),V()},onText:()=>{v(!1),Y()},onHeading:()=>{v(!1),te()},onAi:()=>{v(!1),f(!0)}})})]}):o.jsx("div",{ref:U,style:{display:"grid",gridTemplateColumns:`repeat(${D}, 1fr)`,gridAutoRows:`${y}px`,gap:12},children:t.layout.items.map(X=>o.jsx(MV,{item:X,tile:w.get(X.i),loading:l,error:d,themeMode:s.themeMode,editable:n,cols:D,onMove:H=>void oe(X.i,H),onPatch:H=>void z(X.i,H)},X.i))})]}),m&&o.jsx("aside",{style:{width:340,minWidth:300,maxWidth:"34vw",border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:8,overflow:"auto",alignSelf:"flex-start",height:GT,position:"sticky",top:12,padding:12},children:o.jsx(HV,{lineage:O})}),E&&o.jsx("aside",{style:{width:b?"min(720px, 52vw)":390,minWidth:b?520:340,maxWidth:b?"58vw":"40vw",border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:8,overflow:"hidden",alignSelf:"flex-start",height:GT,position:"sticky",top:12},children:o.jsx(_V,{title:"Dashboard AI",scopeHint:"Scoped to this App dashboard first",upstreamContext:F,themeMode:s.themeMode,hideSqlByDefault:!0,addToAppTarget:{appId:e,dashboardId:t.id},conversationTarget:{appId:e,dashboardId:t.id},expanded:b,onToggleExpanded:()=>P(X=>!X),onClose:()=>{f(!1),P(!1)}})}),T&&o.jsx(GV,{blocks:R,search:h,onSearch:g,onClose:()=>A(!1),onAdd:X=>void ee(X)}),j&&o.jsx(FV,{kind:j,value:B,onChange:M,onClose:()=>{L(null),M("")},onSave:()=>void ne()})]})}function MV({item:e,tile:t,loading:n,error:r,themeMode:s,editable:i,cols:a,onMove:l,onPatch:c}){const d=p.useRef(null),[u,E]=p.useState(null),[f,T]=p.useState(!1),A=e.block?"blockId"in e.block?`block:${e.block.blockId}`:e.block.ref??"(unknown)":e.aiPin?`aiPin:${e.aiPin.id}`:"text",R=S=>{const h=d.current;if(!h)return;S.preventDefault(),S.stopPropagation();const g=h.getBoundingClientRect(),m={x:S.clientX-g.left,y:S.clientY-g.top},I={x:S.clientX,y:S.clientY},O=x=>{E({x:x.clientX-I.x,y:x.clientY-I.y})},N=x=>{window.removeEventListener("pointermove",O),window.removeEventListener("pointerup",N),E(null),l({clientX:x.clientX-m.x,clientY:x.clientY-m.y})};window.addEventListener("pointermove",O),window.addEventListener("pointerup",N,{once:!0})};return o.jsxs("div",{ref:d,style:{gridColumn:`${e.x+1} / span ${e.w}`,gridRow:`${e.y+1} / span ${e.h}`,transform:u?`translate(${u.x}px, ${u.y}px)`:void 0,opacity:u?.72:1,zIndex:u?20:void 0,position:"relative",background:"var(--surface, rgba(0,0,0,0.02))",border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:8,padding:12,display:"flex",flexDirection:"column",gap:6,minHeight:0,overflow:"auto"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,minWidth:0},children:[i?o.jsx("button",{type:"button",title:"Drag to move tile",onPointerDown:R,style:KV,children:o.jsx(T_,{size:14,strokeWidth:2.2})}):null,o.jsx("div",{style:{fontSize:13,fontWeight:600,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title??A})]}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[o.jsx("span",{style:{fontSize:10,padding:"2px 8px",borderRadius:999,background:"var(--surface-hover, rgba(0,0,0,0.06))",opacity:.85},children:e.viz.type}),i&&o.jsx(wV,{item:e,cols:a,settingsOpen:f,onToggleSettings:()=>T(S=>!S),onPatch:c})]})]}),o.jsx("div",{style:{fontSize:11,opacity:.6,fontFamily:"monospace"},children:A}),i&&f?o.jsx(BV,{item:e,tile:t,cols:a,onPatch:c}):null,o.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,opacity:(t==null?void 0:t.status)==="ok"?1:.7,fontStyle:(t==null?void 0:t.status)==="ok"?"normal":"italic"},children:o.jsx(PV,{item:e,tile:t,loading:n,error:r,themeMode:s})})]})}function PV({item:e,tile:t,loading:n,error:r,themeMode:s}){var l,c,d;if(n&&!t)return o.jsx("span",{children:"Loading data..."});if((t==null?void 0:t.tileType)==="text")return o.jsx(jV,{markdown:((l=t.text)==null?void 0:l.markdown)??"",variant:((c=t.viz)==null?void 0:c.type)==="heading"?"heading":"text"});if((t==null?void 0:t.tileType)==="aiPin"&&t.aiPin&&!t.result)return o.jsx(kV,{pin:t.aiPin});if(r&&!t)return o.jsx("span",{children:r});if(!t)return o.jsx("span",{children:"No run result."});if(t.status==="unauthorized")return o.jsx("span",{children:"Not authorized."});if(t.status==="unresolved")return o.jsx("span",{children:t.error??"Block reference unresolved."});if(t.status==="error")return o.jsx("span",{children:t.error??"Tile failed."});if(!t.result)return o.jsx("span",{children:"No result."});const i=Qg(e,t.chartConfig);return String(i.chart??((d=t.viz)==null?void 0:d.type)??"").toLowerCase()==="table"||e.viz.type==="table"?o.jsx("div",{style:{width:"100%",alignSelf:"stretch"},children:o.jsx(Rn,{result:t.result,themeMode:s})}):o.jsx("div",{style:{width:"100%",alignSelf:"stretch"},children:o.jsx($a,{result:t.result,themeMode:s,chartConfig:i})})}function wV({item:e,cols:t,settingsOpen:n,onToggleSettings:r,onPatch:s}){const[i,a]=p.useState(!1),l=c=>{a(!1),s(eI(e,t,c))};return o.jsxs("div",{style:{display:"flex",gap:4,alignItems:"center",flexWrap:"wrap",justifyContent:"flex-end"},children:[o.jsxs("div",{style:{position:"relative"},children:[o.jsx("button",{type:"button",title:"Choose tile size",onClick:()=>a(c=>!c),style:qV,children:"Size"}),i?o.jsx(UV,{onPick:l,onClose:()=>a(!1)}):null]}),o.jsx("button",{type:"button",title:"Chart and field settings",onClick:r,style:VT,children:o.jsx(k_,{size:13,strokeWidth:2,color:n?"var(--accent, #4f46e5)":void 0})}),o.jsx("button",{type:"button",title:"Remove tile",onClick:()=>s(null),style:VT,children:o.jsx(z_,{size:13,strokeWidth:2})})]})}function UV({onPick:e,onClose:t}){return o.jsx("div",{style:JV,onMouseLeave:t,children:Jg.map(n=>o.jsxs("button",{type:"button",onClick:()=>e(n.id),style:QV,children:[o.jsx("span",{style:{fontSize:12,fontWeight:750},children:n.label}),o.jsx("span",{style:{fontSize:11,opacity:.66},children:n.description})]},n.id))})}function BV({item:e,tile:t,cols:n,onPatch:r}){const s=t==null?void 0:t.result,i=Qg(e,t==null?void 0:t.chartConfig),a=Xu(i.chart),l=p.useMemo(()=>ys(s),[s]),c=p.useMemo(()=>{const f=new Map;if(!s)return f;const T=new Set(l.metrics),A=new Set(l.dimensions);for(const R of s.columns)T.has(R)?f.set(R,"measure"):A.has(R)?f.set(R,"dimension"):f.set(R,Au(Wa(R,s.rows)));return f},[s,l]),d=(s==null?void 0:s.columns.filter(f=>c.get(f)==="measure"))??[],u=(s==null?void 0:s.columns.filter(f=>c.get(f)!=="measure"))??[],E=f=>{const T=YV({...i,...f});r({title:T.title||e.title,viz:{...e.viz,type:WV(T.chart),options:T}})};return o.jsxs("div",{style:VV,children:[o.jsxs("div",{style:{display:"grid",gap:6},children:[o.jsx("div",{style:{fontSize:10,fontWeight:800,textTransform:"uppercase",opacity:.58},children:"Tile size"}),o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:Jg.map(f=>o.jsx("button",{type:"button",title:f.description,onClick:()=>r(eI(e,n,f.id)),style:ZV(e6(e,n,f.id)),children:f.label},f.id))})]}),o.jsxs("div",{style:zV,children:[o.jsxs("label",{style:Dd,children:["Title",o.jsx("input",{value:i.title??e.title??"",onChange:f=>E({title:f.target.value||void 0}),style:Md})]}),o.jsxs("label",{style:Dd,children:["Chart",o.jsx("select",{value:a,onChange:f=>E({chart:f.target.value}),style:Md,children:qg.map(f=>o.jsx("option",{value:f.value,children:f.label},f.value))})]}),o.jsx(Ii,{label:"X",value:i.x,columns:(s==null?void 0:s.columns)??[],onChange:f=>E({x:f})}),o.jsx(Ii,{label:"Y",value:i.y,columns:(s==null?void 0:s.columns)??[],onChange:f=>E({y:f})}),o.jsx(Ii,{label:"Color",value:i.color,columns:(s==null?void 0:s.columns)??[],onChange:f=>E({color:f})}),o.jsx(Ii,{label:"Facet",value:i.facet,columns:(s==null?void 0:s.columns)??[],onChange:f=>E({facet:f})})]}),s?o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[o.jsx(HT,{title:"Measures",columns:d,onPick:f=>E({y:f})}),o.jsx(HT,{title:"Dimensions",columns:u,onPick:f=>E({x:f})})]}):o.jsx("div",{style:{fontSize:11,opacity:.64},children:"Run results are needed before field slots can be inferred."})]})}function Ii({label:e,value:t,columns:n,onChange:r}){return o.jsxs("label",{style:Dd,children:[e,o.jsxs("select",{value:t??"",onChange:s=>r(s.target.value||void 0),style:Md,children:[o.jsx("option",{value:"",children:"Auto"}),n.map(s=>o.jsx("option",{value:s,children:s},s))]})]})}function HT({title:e,columns:t,onPick:n}){return o.jsxs("div",{style:{display:"grid",gap:4,minWidth:0},children:[o.jsx("div",{style:{fontSize:10,fontWeight:800,textTransform:"uppercase",opacity:.58},children:e}),o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:t.length===0?o.jsx("span",{style:{fontSize:11,opacity:.55},children:"None"}):t.slice(0,10).map(r=>o.jsx("button",{type:"button",onClick:()=>n(r),style:XV,children:r},r))})]})}function WT({open:e,onToggle:t,onCertifiedBlock:n,onText:r,onHeading:s,onAi:i,buttonLabel:a="+ Add",buttonStyle:l}){return o.jsxs("div",{style:{position:"relative",display:"inline-flex"},children:[o.jsx("button",{type:"button",onClick:t,style:l??hs(e),children:a}),e&&o.jsxs("div",{style:{position:"absolute",top:"calc(100% + 6px)",right:0,zIndex:30,width:260,border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:8,background:"var(--color-bg, #fff)",boxShadow:"0 14px 38px rgba(0,0,0,0.16)",padding:6,display:"grid",gap:4,textAlign:"left"},children:[o.jsx(Oi,{title:"Certified block",description:"Chart, table, or KPI from this App domain",onClick:n}),o.jsx(Oi,{title:"Text / summary",description:"Narrative, notes, caveats, or CXO context",onClick:r}),o.jsx(Oi,{title:"Section heading",description:"Separate an App page into readable groups",onClick:s}),o.jsx(Oi,{title:"AI answer",description:"Open scoped AI, then pin the answer to this App",onClick:i})]})]})}function Oi({title:e,description:t,onClick:n}){return o.jsxs("button",{type:"button",onClick:n,style:$V,children:[o.jsx("span",{style:{fontSize:12,fontWeight:700},children:e}),o.jsx("span",{style:{fontSize:11,opacity:.66},children:t})]})}function jV({markdown:e,variant:t="text"}){return o.jsx("div",{style:{width:"100%",alignSelf:"stretch",overflow:"auto",whiteSpace:"pre-wrap",lineHeight:1.45,fontStyle:"normal",opacity:1,fontSize:t==="heading"?18:void 0,fontWeight:t==="heading"?800:void 0,display:t==="heading"?"flex":void 0,alignItems:t==="heading"?"center":void 0},children:e})}function kV({pin:e}){const[t,n]=p.useState(null),r=async()=>{n("Refreshing...");const i=await $.refreshAiPin(e.appId,e.id);n(i.ok?"Refreshed.":i.error??"Refresh failed."),window.dispatchEvent(new CustomEvent("dql-app-dashboard-updated",{detail:{appId:e.appId,dashboardId:e.dashboardId}}))},s=async()=>{n("Creating draft...");const i=await $.promoteAiPin(e.appId,e.id);n(i.ok?`Draft created: ${i.blockPath}`:i.error??"Promotion failed."),window.dispatchEvent(new CustomEvent("dql-app-dashboard-updated",{detail:{appId:e.appId,dashboardId:e.dashboardId}}))};return o.jsxs("div",{style:{width:"100%",alignSelf:"stretch",overflow:"auto",fontStyle:"normal",lineHeight:1.45},children:[o.jsx("div",{style:{fontSize:11,fontWeight:700,color:e.certification==="certified"?"#3fb950":"#f0883e",marginBottom:6},children:e.certification==="certified"?"Certified":"AI generated / needs review"}),o.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e.answer}),o.jsxs("div",{style:{display:"flex",gap:6,marginTop:8,flexWrap:"wrap"},children:[e.sql&&o.jsx("button",{type:"button",onClick:()=>void r(),style:zT,children:"Refresh"}),e.sql&&e.reviewStatus==="needs_review"&&o.jsx("button",{type:"button",onClick:()=>void s(),style:zT,children:"Promote"}),e.refreshCadence==="daily"&&o.jsx("span",{style:{fontSize:11,opacity:.62},children:"daily"})]}),t&&o.jsx("div",{style:{marginTop:6,fontSize:11,opacity:.72},children:t}),e.lastRefreshError&&o.jsx("div",{style:{marginTop:8,color:"#f85149"},children:e.lastRefreshError})]})}function FV({kind:e,value:t,onChange:n,onClose:r,onSave:s}){const i=e==="heading";return o.jsx("div",{style:{position:"fixed",inset:0,zIndex:90,background:"rgba(0,0,0,0.36)",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:o.jsxs("div",{style:{width:"min(520px, 92vw)",display:"grid",gap:12,background:"var(--color-bg, #fff)",color:"inherit",borderRadius:8,boxShadow:"0 18px 60px rgba(0,0,0,0.35)",padding:16},children:[o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:16,fontWeight:800},children:i?"Add heading":"Add text tile"}),o.jsx("div",{style:{fontSize:12,opacity:.65,marginTop:4},children:i?"Create a section heading on this dashboard page.":"Create a narrative text tile on this dashboard page."})]}),i?o.jsx("input",{value:t,onChange:a=>n(a.target.value),onKeyDown:a=>{a.key==="Enter"&&s(),a.key==="Escape"&&r()},placeholder:"Executive summary",autoFocus:!0,style:$T}):o.jsx("textarea",{value:t,onChange:a=>n(a.target.value),onKeyDown:a=>{a.key==="Escape"&&r(),a.key==="Enter"&&(a.metaKey||a.ctrlKey)&&s()},placeholder:"Add context, assumptions, or decisions...",rows:6,autoFocus:!0,style:{...$T,resize:"vertical",lineHeight:1.45}}),o.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[o.jsx("button",{type:"button",onClick:r,style:hs(!1),children:"Cancel"}),o.jsx("button",{type:"button",onClick:s,disabled:!t.trim(),style:{...Zg,opacity:t.trim()?1:.65},children:"Add"})]})]})})}function GV({blocks:e,search:t,onSearch:n,onClose:r,onAdd:s}){const i=e.filter(a=>{const l=t.trim().toLowerCase();return l?[a.name,a.description,a.domain,...a.tags??[]].join(" ").toLowerCase().includes(l):!0});return o.jsx("div",{style:{position:"fixed",inset:0,zIndex:90,background:"rgba(0,0,0,0.36)",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:o.jsxs("div",{style:{width:"min(860px, 94vw)",maxHeight:"86vh",display:"flex",flexDirection:"column",background:"var(--color-bg, #fff)",color:"inherit",borderRadius:8,overflow:"hidden",boxShadow:"0 18px 60px rgba(0,0,0,0.35)"},children:[o.jsxs("div",{style:{padding:14,borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.1))",display:"flex",gap:10,alignItems:"center"},children:[o.jsx("div",{style:{fontSize:15,fontWeight:700,flex:1},children:"Add Certified Block"}),o.jsx("button",{type:"button",onClick:r,style:hs(!1),children:"Close"})]}),o.jsx("div",{style:{padding:14,borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.08))"},children:o.jsx("input",{value:t,onChange:a=>n(a.target.value),placeholder:"Search domain blocks...",style:{width:"100%",boxSizing:"border-box",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,padding:"8px 10px",background:"var(--surface, transparent)",color:"inherit"}})}),o.jsx("div",{style:{overflow:"auto",padding:12,display:"grid",gap:8},children:i.length===0?o.jsx("div",{style:{padding:18,fontSize:12,opacity:.66},children:"No certified blocks match this App scope."}):i.map(a=>o.jsxs("button",{type:"button",onClick:()=>s(a),style:{textAlign:"left",border:"1px solid var(--border-color, rgba(0,0,0,0.1))",borderRadius:7,background:"transparent",color:"inherit",padding:10,cursor:"pointer"},children:[o.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:4},children:[o.jsx("span",{style:{fontSize:13,fontWeight:700},children:a.name}),o.jsx("span",{style:{fontSize:10,padding:"2px 6px",borderRadius:999,background:"rgba(63,185,80,0.14)",color:"#2ea043"},children:a.status}),o.jsx("span",{style:{fontSize:10,opacity:.68},children:a.domain}),o.jsx("span",{style:{fontSize:10,opacity:.68},children:a.chartType??"table"})]}),o.jsx("div",{style:{fontSize:12,opacity:.72},children:a.description||a.path})]},a.id))})]})})}function HV({lineage:e}){var s,i;const t=((s=e==null?void 0:e.graph)==null?void 0:s.nodes)??[],n=((i=e==null?void 0:e.graph)==null?void 0:i.edges)??[],r=(e==null?void 0:e.breadcrumbs)??[];return o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:12,fontWeight:800,textTransform:"uppercase",opacity:.62,marginBottom:6},children:"App Lineage"}),o.jsx("div",{style:{fontSize:12,opacity:.72},children:"Domain > App > Dashboard page > Tile > Block > dbt/source"})]}),r.length>0&&o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:r.map((a,l)=>o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"64px 1fr",gap:8,fontSize:12},children:[o.jsx("span",{style:{fontFamily:"monospace",opacity:.6},children:a.type}),o.jsx("span",{children:a.name})]},`${a.id}-${l}`))}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[o.jsx(YT,{label:"Nodes",value:t.length}),o.jsx(YT,{label:"Edges",value:n.length})]}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t.slice(0,18).map(a=>o.jsxs("div",{style:{border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6,padding:8},children:[o.jsx("div",{style:{fontSize:12,fontWeight:700},children:a.name}),o.jsxs("div",{style:{fontSize:11,opacity:.62,fontFamily:"monospace"},children:[a.type," · ",a.id]})]},a.id))})]})}function YT({label:e,value:t}){return o.jsxs("div",{style:{border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6,padding:8},children:[o.jsx("div",{style:{fontSize:11,opacity:.62},children:e}),o.jsx("div",{style:{fontSize:18,fontWeight:800},children:t})]})}function Qg(e,t){const n=e.viz.options??{};return{...t??{},...n,chart:Xu(String(n.chart??(t==null?void 0:t.chart)??e.viz.type)),title:n.title??(t==null?void 0:t.title)??e.title}}function Xu(e){const t=String(e??"table").toLowerCase().replace(/_/g,"-");return t==="single-value"?"kpi":qg.some(n=>n.value===t)?t:"table"}function WV(e){const t=Xu(e);return t==="table"?"table":t.replace(/-/g,"_")}function YV(e){const t={};for(const[n,r]of Object.entries(e))r===void 0||r===""||(t[n]=r);return t.chart||(t.chart="table"),t}function hs(e){return{border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,background:e?"var(--surface-hover, rgba(0,0,0,0.06))":"var(--surface, rgba(0,0,0,0.02))",color:"inherit",padding:"7px 10px",cursor:"pointer",fontSize:12}}const $T={width:"100%",boxSizing:"border-box",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,background:"var(--surface, transparent)",color:"inherit",fontSize:12,padding:"8px 10px"},Zg={border:"1px solid var(--accent, #4f46e5)",borderRadius:6,background:"var(--accent, #4f46e5)",color:"var(--color-text-on-accent, #fff)",padding:"7px 11px",cursor:"pointer",fontSize:12,fontWeight:700},$V={border:"none",borderRadius:6,background:"transparent",color:"inherit",padding:"9px 10px",cursor:"pointer",textAlign:"left",display:"grid",gap:2},VV={border:"1px solid var(--border-color, rgba(0,0,0,0.10))",borderRadius:6,padding:8,background:"var(--color-bg, rgba(255,255,255,0.72))",display:"grid",gap:8,fontStyle:"normal"},zV={display:"grid",gridTemplateColumns:"repeat(4, minmax(0, 1fr))",gap:6},Dd={display:"grid",gap:3,fontSize:10,fontWeight:700,opacity:.78},Md={width:"100%",minWidth:0,boxSizing:"border-box",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:5,background:"var(--surface, transparent)",color:"inherit",padding:"5px 6px",fontSize:11},XV={border:"1px solid var(--border-color, rgba(0,0,0,0.10))",borderRadius:4,background:"var(--surface, rgba(0,0,0,0.02))",color:"inherit",padding:"2px 5px",fontSize:10,cursor:"pointer",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},VT={width:24,height:24,borderRadius:5,border:"1px solid var(--border-color, rgba(0,0,0,0.12))",background:"var(--surface, rgba(255,255,255,0.72))",color:"inherit",cursor:"pointer",padding:0,display:"inline-flex",alignItems:"center",justifyContent:"center"},KV={width:26,height:26,borderRadius:6,border:"1px solid var(--border-color, rgba(0,0,0,0.12))",background:"var(--surface, rgba(255,255,255,0.72))",color:"inherit",cursor:"grab",padding:0,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},qV={height:24,borderRadius:5,border:"1px solid var(--border-color, rgba(0,0,0,0.12))",background:"var(--surface, rgba(255,255,255,0.72))",color:"inherit",cursor:"pointer",padding:"0 8px",fontSize:11,fontWeight:700},JV={position:"absolute",top:"calc(100% + 6px)",right:0,zIndex:40,width:240,border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:8,background:"var(--color-bg, #fff)",boxShadow:"0 14px 38px rgba(0,0,0,0.16)",padding:6,display:"grid",gap:4},QV={border:"none",borderRadius:6,background:"transparent",color:"inherit",padding:"8px 9px",cursor:"pointer",textAlign:"left",display:"grid",gap:2};function ZV(e){return{border:`1px solid ${e?"var(--accent, #4f46e5)":"var(--border-color, rgba(0,0,0,0.12))"}`,borderRadius:999,background:e?"var(--color-bg-active, rgba(79,70,229,0.12))":"var(--surface, rgba(0,0,0,0.02))",color:e?"var(--accent, #4f46e5)":"inherit",padding:"4px 8px",fontSize:11,fontWeight:e?750:600,cursor:"pointer"}}const zT={border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:4,background:"var(--surface, rgba(0,0,0,0.02))",color:"inherit",padding:"3px 7px",cursor:"pointer",fontSize:11};function Ku(e,t){const n=tI(e);return n==="heading"?qt("wide",t,"heading"):n==="text"?qt("standard",t,"text"):qt(n==="single_value"||n==="kpi"||n==="gauge"?"compact":n==="table"||n==="pivot"?"tall":n==="line"||n==="area"?"wide":"standard",t,n)}function qt(e,t,n="table"){const r=Math.max(1,t),s=Math.max(1,Math.ceil(r/2)),i=Math.max(1,Math.ceil(r/3));return e==="auto"?Ku(n,r):e==="compact"?{w:i,h:2}:e==="wide"?{w:r,h:n==="heading"?1:4}:e==="tall"?{w:s,h:6}:e==="full"?{w:r,h:7}:{w:s,h:n==="text"?2:4}}function eI(e,t,n){const r=String(e.viz.type??"table"),s=n==="auto"?Ku(r,t):qt(n,t,r);return{w:s.w,h:s.h,x:qu(e.x,0,Math.max(0,t-s.w))}}function e6(e,t,n){if(n==="auto")return!1;const r=qt(n,t,String(e.viz.type??"table"));return e.w===r.w&&e.h===r.h}function Hc(e,t={w:6,h:3}){return{x:0,y:e.layout.items.reduce((r,s)=>Math.max(r,s.y+s.h),0),w:t.w,h:t.h}}function Wc(e,t){const n=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"tile",r=new Set(e.layout.items.map(s=>s.i));if(!r.has(n))return n;for(let s=2;s<1e3;s++){const i=`${n}-${s}`;if(!r.has(i))return i}return`${n}-${Date.now()}`}function XT(e,t){let n=0,r=0,s=0;return e.map(i=>{const a=qu(Math.round(i.w||1),1,t),l=Math.max(1,Math.round(i.h||1));n>0&&n+a>t&&(r+=s,n=0,s=0);const c={...i,x:n,y:r,w:a,h:l};return n+=a,s=Math.max(s,l),n>=t&&(r+=s,n=0,s=0),c})}function t6(e,t,n){const r=e.filter(a=>a.i!==t.i).sort((a,l)=>Ni(a,n)-Ni(l,n)),s=Ni(t,n),i=r.findIndex(a=>Ni(a,n)>s);return i===-1?[...r,t]:[...r.slice(0,i),t,...r.slice(i)]}function Ni(e,t){return e.y*t+e.x}function tI(e){const t=(e??"table").toLowerCase().replace(/-/g,"_");return t==="single_value"||t==="kpi"||t==="gauge"||t==="line"||t==="bar"||t==="area"||t==="pie"||t==="pivot"||t==="map"||t==="funnel"||t==="heading"||t==="text"?t:"table"}function qu(e,t,n){return Math.min(n,Math.max(t,e))}const KT={sql:"SQL",dql:"DQL",markdown:"Markdown",chart:"Chart",table:"Table",pivot:"Pivot",single_value:"Single value",filter:"Filter",param:"Parameter",python:"Python",chat:"Chat",writeback:"Writeback"},n6={sql:"#5b9cf6",dql:"#4f46e5",markdown:"#6f7785",chart:"#b067f7",table:"#79c0ff",pivot:"#a371f7",single_value:"#a371f7",filter:"#39d353",param:"#f0b429",python:"#3572A5",chat:"#f78166",writeback:"#e36209"};function r6(){var _r,qn,br,Jn;const{state:e,dispatch:t}=Re(),[n,r]=p.useState(null),[s,i]=p.useState(null),[a,l]=p.useState(!1),[c,d]=p.useState(!1),[u,E]=p.useState(""),[f,T]=p.useState(""),[A,R]=p.useState(""),[S,h]=p.useState(""),[g,m]=p.useState(""),[I,O]=p.useState(""),[N,x]=p.useState(""),[_,C]=p.useState(""),[v,b]=p.useState(""),[P,j]=p.useState("all"),[L,B]=p.useState("dashboards"),[M,U]=p.useState("view"),[D,y]=p.useState(!1),[w,F]=p.useState(""),[k,V]=p.useState(null),[ee,Y]=p.useState(!1),[te,ne]=p.useState(!1),[z,oe]=p.useState("existing"),[le,ae]=p.useState(""),[X,H]=p.useState(""),[re,ie]=p.useState("supporting"),[de,se]=p.useState("shared"),[ge,xe]=p.useState([]),[Fe,Z]=p.useState(""),[Ee,Oe]=p.useState(""),[ve,Le]=p.useState(null),[Tt,yt]=p.useState(!1),St=async(K,ue)=>{t({type:"SET_APPS_LOADING",loading:!0});const Ye=await $.listApps();t({type:"SET_APPS",apps:Ye}),t({type:"SET_APPS_LOADING",loading:!1}),K?t({type:"OPEN_APP",appId:K,dashboardId:ue??void 0}):Ye.length>0&&!e.activeAppId&&t({type:"OPEN_APP",appId:Ye[0].id})};p.useEffect(()=>{let K=!1;return t({type:"SET_APPS_LOADING",loading:!0}),$.listApps().then(ue=>{K||(t({type:"SET_APPS",apps:ue}),t({type:"SET_APPS_LOADING",loading:!1}),ue.length>0&&!e.activeAppId&&t({type:"OPEN_APP",appId:ue[0].id}))}),()=>{K=!0}},[]),p.useEffect(()=>{if(!e.activeAppId){r(null),i(null);return}let K=!1;return l(!0),$.getApp(e.activeAppId).then(ue=>{K||r(ue)}),e.activeDashboardId?$.getDashboard(e.activeAppId,e.activeDashboardId).then(ue=>{K||(i(ue),l(!1))}):(i(null),l(!1)),()=>{K=!0}},[e.activeAppId,e.activeDashboardId]),p.useEffect(()=>{$.getPersona().then(K=>t({type:"SET_ACTIVE_PERSONA",persona:K}))},[]);const Ct=p.useMemo(()=>({domains:sr(e.apps.map(K=>K.domain).filter(Boolean)),subdomains:sr(e.apps.map(K=>K.subdomain).filter(Boolean)),groups:sr(e.apps.flatMap(K=>K.groups??[])),tags:sr(e.apps.flatMap(K=>K.tags??[]).filter(K=>!K.startsWith("audience:"))),owners:sr(e.apps.flatMap(K=>K.owners??[])),audiences:sr(e.apps.map(K=>K.audience).filter(Boolean))}),[e.apps]),mn=p.useMemo(()=>{const K=u.trim().toLowerCase();return e.apps.filter(ue=>!(K&&![ue.name,ue.description??"",ue.domain,ue.subdomain??"",...ue.groups??[],...ue.tags??[],...ue.owners??[],...ue.dashboards.map(Ue=>Ue.title),...(ue.notebooks??[]).flatMap(Ue=>[Ue.title??"",Ue.path]),...(ue.drafts??[]).flatMap(Ue=>[Ue.name,Ue.path])].join(" ").toLowerCase().includes(K)||f&&ue.domain!==f||A&&ue.subdomain!==A||S&&!(ue.groups??[]).includes(S)||g&&!(ue.tags??[]).includes(g)||I&&!(ue.owners??[]).includes(I)||N&&ue.audience!==N||_&&ue.lifecycle!==_||v&&ue.certification!==v||P==="review"&&ue.lifecycle!=="review"||P!=="all"&&P!=="review"&&(ue.storage??"shared")!==P))},[e.apps,u,f,A,S,g,I,N,_,v,P]),an=p.useMemo(()=>e.apps.find(K=>K.id===e.activeAppId)??null,[e.apps,e.activeAppId]),ht=M==="build",Wt=K=>{U(K),K==="view"&&(L==="drafts"||L==="settings")&&B("dashboards")},Xn=()=>{F(""),V(null),y(!0)},Yt=async()=>{if(!e.activeAppId)return;const K=w.trim();if(!K){V("Enter a dashboard page name.");return}Y(!0),V(null);try{const ue=await $.createAppDashboard(e.activeAppId,{title:K});ue.ok?(U("build"),B("dashboards"),y(!1),F(""),n&&i({app:n.app,dashboard:ue.dashboard}),t({type:"OPEN_APP",appId:e.activeAppId,dashboardId:ue.dashboard.id}),await St(e.activeAppId,ue.dashboard.id),t({type:"OPEN_DASHBOARD",dashboardId:ue.dashboard.id})):V(ue.error??"Could not create dashboard page.")}catch(ue){V(ue instanceof Error?ue.message:String(ue))}finally{Y(!1)}},Kn=async K=>{const Ye={name:K.split("/").pop()||K,path:K,type:"notebook",folder:K.split("/").slice(0,-1).join("/")||"notebooks"},{content:Ue}=await $.readNotebook(K),{title:Co,cells:vr,metadata:Dr}=PR(K,Ue);t({type:"FILE_ADDED",file:Ye}),t({type:"OPEN_FILE",file:Ye,cells:vr,title:Co,metadata:Dr})},Lt=async()=>{e.activeAppId&&(oe("existing"),ae(""),H(""),ie("supporting"),se("shared"),Z(""),Oe(""),Le(null),ne(!0),xe(await $.listAppNotebookCandidates(e.activeAppId)))},Lr=async()=>{if(!e.activeAppId)return;const K=le.trim(),ue=Ee.trim()||X.trim();if(z==="existing"&&!K){Le("Choose a notebook or enter a project-relative path.");return}if(z==="new"&&!ue){Le("Enter a notebook name.");return}yt(!0),Le(null);try{if(z==="new"){const Ue=await $.createAppNotebook(e.activeAppId,{name:ue,title:X.trim()||ue,role:re,visibility:de});if(!Ue.ok){Le(Ue.error??"Could not create notebook.");return}await St(e.activeAppId,e.activeDashboardId),B("notebooks"),ne(!1),await Kn(Ue.path);return}else{const Ue=await $.attachAppNotebook(e.activeAppId,{path:K,title:X.trim()||void 0,role:re,visibility:de});if("ok"in Ue&&Ue.ok===!1){Le(Ue.error??"Could not attach notebook.");return}}const Ye=await $.getApp(e.activeAppId);r(Ye),await St(e.activeAppId,e.activeDashboardId),B("notebooks"),ne(!1),ae(""),H(""),Oe("")}catch(Ye){Le(Ye instanceof Error?Ye.message:String(Ye))}finally{yt(!1)}};return e.appsLoading&&e.apps.length===0?o.jsx(Fo,{message:"Loading apps...",onCreate:()=>d(!0)}):e.apps.length===0?o.jsxs(o.Fragment,{children:[o.jsx(Fo,{message:"Create your first local App.",hint:"Package dashboard pages, notebooks, AI pins, and drafts into a single OSS App.",onCreate:()=>d(!0)}),c&&o.jsx(eS,{onClose:()=>d(!1),onCreated:(K,ue)=>void St(K,ue)})]}):o.jsxs("div",{style:{display:"flex",height:"100%",minHeight:0,background:"var(--color-bg-primary)",color:"var(--color-text-primary)"},children:[o.jsxs("aside",{style:{width:292,borderRight:"1px solid var(--border-color, rgba(0,0,0,0.08))",background:"var(--color-bg-secondary)",display:"flex",flexDirection:"column",minHeight:0},children:[o.jsxs("div",{style:{padding:12,borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.06))"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[o.jsx("div",{style:{fontSize:11,fontWeight:700,opacity:.65,textTransform:"uppercase",letterSpacing:.5,flex:1},children:"Apps Library"}),o.jsx("button",{onClick:()=>d(!0),style:gr,children:"Create App"})]}),o.jsxs("div",{style:{display:"grid",gap:6},children:[o.jsx("input",{value:u,onChange:K=>E(K.target.value),placeholder:"Search apps, dashboard pages, notebooks...",style:_e}),o.jsxs("select",{value:f,onChange:K=>T(K.target.value),style:_e,children:[o.jsx("option",{value:"",children:"All domains"}),Ct.domains.map(K=>o.jsx("option",{value:K,children:K},K))]}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:6},children:[o.jsxs("select",{value:A,onChange:K=>R(K.target.value),style:_e,children:[o.jsx("option",{value:"",children:"Subdomain"}),Ct.subdomains.map(K=>o.jsx("option",{value:K,children:K},K))]}),o.jsxs("select",{value:S,onChange:K=>h(K.target.value),style:_e,children:[o.jsx("option",{value:"",children:"Group"}),Ct.groups.map(K=>o.jsx("option",{value:K,children:K},K))]})]}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:6},children:[o.jsxs("select",{value:g,onChange:K=>m(K.target.value),style:_e,children:[o.jsx("option",{value:"",children:"All tags"}),Ct.tags.map(K=>o.jsx("option",{value:K,children:K},K))]}),o.jsxs("select",{value:I,onChange:K=>O(K.target.value),style:_e,children:[o.jsx("option",{value:"",children:"All owners"}),Ct.owners.map(K=>o.jsx("option",{value:K,children:K},K))]})]}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:6},children:[o.jsxs("select",{value:N,onChange:K=>x(K.target.value),style:_e,children:[o.jsx("option",{value:"",children:"Audience"}),Ct.audiences.map(K=>o.jsx("option",{value:K,children:K},K))]}),o.jsxs("select",{value:_,onChange:K=>C(K.target.value),style:_e,children:[o.jsx("option",{value:"",children:"Lifecycle"}),o.jsx("option",{value:"draft",children:"draft"}),o.jsx("option",{value:"review",children:"review"}),o.jsx("option",{value:"certified",children:"certified"}),o.jsx("option",{value:"deprecated",children:"deprecated"})]})]}),o.jsxs("select",{value:v,onChange:K=>b(K.target.value),style:_e,children:[o.jsx("option",{value:"",children:"All certification"}),o.jsx("option",{value:"certified",children:"certified"}),o.jsx("option",{value:"uncertified",children:"uncertified"})]}),o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:4},children:["all","mine","shared","template","review"].map(K=>o.jsx("button",{onClick:()=>j(K),style:w6(P===K),children:K==="all"?"All":K==="template"?"Templates":K==="mine"?"Local":K==="review"?"Review":"Shared"},K))}),o.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",fontSize:10,opacity:.62},children:[o.jsx("span",{children:"My Local"}),o.jsx("span",{children:"Shared"}),o.jsx("span",{children:"Templates"}),o.jsx("span",{children:"Review Queue"})]})]})]}),o.jsx("div",{style:{overflowY:"auto",minHeight:0,padding:"8px 0"},children:mn.length===0?o.jsx("div",{style:{padding:16,fontSize:12,opacity:.65},children:"No Apps match the current filters."}):mn.map(K=>o.jsx(D6,{app:K,active:K.id===e.activeAppId,onClick:()=>{B("dashboards"),t({type:"OPEN_APP",appId:K.id})}},K.id))})]}),o.jsxs("main",{style:{flex:1,display:"flex",flexDirection:"column",minWidth:0,overflow:"hidden",background:"var(--color-bg)"},children:[o.jsx(s6,{activeApp:an,appDoc:n,experience:M,isBuild:ht,onExperienceChange:Wt,onAddPage:Xn}),n&&o.jsx(a6,{section:L,experience:M,dashboardCount:n.dashboards.length,notebookCount:((_r=n.notebooks)==null?void 0:_r.length)??((qn=n.app.notebooks)==null?void 0:qn.length)??0,aiCount:((br=n.aiPins)==null?void 0:br.length)??0,draftCount:((Jn=n.drafts)==null?void 0:Jn.length)??0,onChange:B}),n&&L==="dashboards"&&n.dashboards.length>0&&o.jsx(l6,{dashboards:n.dashboards,activeDashboardId:e.activeDashboardId,isBuild:ht,onAddPage:Xn,onOpen:K=>{B("dashboards"),t({type:"OPEN_DASHBOARD",dashboardId:K})}}),o.jsx("div",{style:{flex:1,overflow:"auto",padding:L==="notebooks"?"12px 16px 18px":"14px 16px 18px",minHeight:0},children:a?o.jsx(Fo,{message:"Loading dashboard..."}):n&&L==="notebooks"?o.jsx(c6,{appDoc:n,editable:ht,onAttach:()=>void Lt(),onOpenNotebook:K=>void Kn(K)}):n&&L==="ai"?o.jsx(L6,{appDoc:n,editable:ht,onPromoted:async()=>{e.activeAppId&&(r(await $.getApp(e.activeAppId)),await St(e.activeAppId,e.activeDashboardId))}}):n&&ht&&L==="drafts"?o.jsx(_6,{drafts:n.drafts??[]}):n&&ht&&L==="settings"?o.jsx(b6,{appDoc:n}):s&&e.activeAppId?o.jsx(DV,{appId:e.activeAppId,dashboard:s.dashboard,editable:ht,onDashboardChanged:K=>{i(ue=>ue&&{...ue,dashboard:K}),St(e.activeAppId??void 0,K.id)}}):n&&n.dashboards.length===0?o.jsx(Fo,{message:"This App has no dashboard pages.",hint:ht?"Add a dashboard page from Build mode.":"No dashboard page has been published for this App."}):o.jsx(Fo,{message:"Select a dashboard."})})]}),c&&o.jsx(eS,{onClose:()=>d(!1),onCreated:(K,ue)=>void St(K,ue)}),D&&o.jsx(o6,{title:w,error:k,saving:ee,appName:(an==null?void 0:an.name)??"this App",onChange:F,onCancel:()=>{ee||(y(!1),V(null))},onCreate:()=>void Yt()}),te&&o.jsx(i6,{mode:z,path:le,title:X,role:re,visibility:de,candidates:ge,search:Fe,newName:Ee,error:ve,saving:Tt,onModeChange:oe,onPathChange:ae,onTitleChange:H,onRoleChange:ie,onVisibilityChange:se,onSearchChange:Z,onNewNameChange:Oe,onCancel:()=>{Tt||(ne(!1),Le(null))},onAttach:()=>void Lr()})]})}function o6({title:e,error:t,saving:n,appName:r,onChange:s,onCancel:i,onCreate:a}){return o.jsx("div",{style:Zu,children:o.jsxs("div",{style:{...eE,gap:12},children:[o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:16,fontWeight:800},children:"Add dashboard page"}),o.jsxs("div",{style:{fontSize:12,opacity:.65,marginTop:4},children:["Create a new dashboard page inside ",r,"."]})]}),o.jsx(Ge,{label:"Page name",children:o.jsx("input",{value:e,onChange:l=>s(l.target.value),onKeyDown:l=>{l.key==="Enter"&&a(),l.key==="Escape"&&i()},placeholder:"Overview, Fraud Ops, Executive Summary",autoFocus:!0,style:_e})}),t?o.jsx("div",{style:{color:"#f85149",fontSize:12},children:t}):null,o.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[o.jsx("button",{onClick:i,disabled:n,style:Ao,children:"Cancel"}),o.jsx("button",{onClick:a,disabled:n||!e.trim(),style:{...gr,opacity:n||!e.trim()?.65:1},children:n?"Creating...":"Create page"})]})]})})}function s6({activeApp:e,appDoc:t,experience:n,isBuild:r,onExperienceChange:s,onAddPage:i}){var d;const a=(e==null?void 0:e.dashboards.length)??0,l=((d=e==null?void 0:e.notebooks)==null?void 0:d.length)??0,c=(e==null?void 0:e.tags)??[];return o.jsxs("header",{style:{display:"flex",alignItems:"flex-start",gap:16,padding:"13px 16px 12px",borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.08))",background:"var(--color-bg, #fff)"},children:[o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsx("h1",{style:{margin:0,fontSize:20,lineHeight:1.15,fontWeight:750,letterSpacing:0},children:(e==null?void 0:e.name)??"Apps"}),o.jsxs("div",{style:{marginTop:5,fontSize:12,lineHeight:1.45,color:"var(--color-text-secondary, rgba(0,0,0,0.62))"},children:[e?Qu(e):"Select an App",e?` · ${a} dashboard${a===1?"":"s"}`:"",e?` · ${l} notebook${l===1?"":"s"}`:"",e!=null&&e.description?` · ${e.description}`:""]}),c.length?o.jsx("div",{style:{display:"flex",gap:5,flexWrap:"wrap",marginTop:7},children:c.slice(0,8).map(u=>o.jsx(Mt,{children:u},u))}):null]}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap",justifyContent:"flex-end"},children:[o.jsx(LV,{app:(t==null?void 0:t.app)??null}),o.jsxs("div",{style:{display:"flex",alignItems:"center",background:"var(--surface, rgba(0,0,0,0.04))",border:"1px solid var(--border-color, rgba(0,0,0,0.10))",borderRadius:7,padding:3,gap:3},children:[o.jsx("button",{onClick:()=>s("view"),style:nS(n==="view"),children:"View"}),o.jsx("button",{onClick:()=>s("build"),style:nS(n==="build"),children:"Build"})]}),r?o.jsx("button",{type:"button",onClick:i,disabled:!e,style:Ao,children:"+ Add page"}):null]})]})}function i6({mode:e,path:t,title:n,role:r,visibility:s,candidates:i,search:a,newName:l,error:c,saving:d,onModeChange:u,onPathChange:E,onTitleChange:f,onRoleChange:T,onVisibilityChange:A,onSearchChange:R,onNewNameChange:S,onCancel:h,onAttach:g}){const m=i.filter(I=>{const O=a.trim().toLowerCase();return O?[I.title,I.path,I.role??"",I.visibility??""].join(" ").toLowerCase().includes(O):!0});return o.jsx("div",{style:Zu,children:o.jsxs("div",{style:{...eE,width:720,maxWidth:"calc(100vw - 48px)",gap:12},children:[o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:16,fontWeight:800},children:"Add notebook"}),o.jsx("div",{style:{fontSize:12,opacity:.65,marginTop:4},children:"Attach an existing notebook or create a new App notebook."})]}),o.jsxs("div",{style:{display:"flex",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,overflow:"hidden",width:"fit-content"},children:[o.jsx("button",{type:"button",onClick:()=>u("existing"),style:ma(e==="existing"),children:"Existing"}),o.jsx("button",{type:"button",onClick:()=>u("new"),style:ma(e==="new"),children:"New notebook"})]}),e==="existing"?o.jsxs(o.Fragment,{children:[o.jsx(Ge,{label:"Search notebooks",children:o.jsx("input",{value:a,onChange:I=>R(I.target.value),placeholder:"Search by title or path",autoFocus:!0,style:_e})}),o.jsx("div",{style:{display:"grid",gap:6,maxHeight:220,overflow:"auto",border:"1px solid var(--border-color, rgba(0,0,0,0.10))",borderRadius:6,padding:6},children:m.length===0?o.jsx("div",{style:Un,children:"No notebooks found. Use the path field below or create a new notebook."}):m.map(I=>o.jsxs("button",{type:"button",onClick:()=>{E(I.path),f(I.title),I.role&&T(I.role),I.visibility&&A(I.visibility)},style:{...no,textAlign:"left",borderColor:I.path===t?"var(--accent, #4f46e5)":"var(--border-color, rgba(0,0,0,0.10))",background:I.path===t?"var(--color-bg-active, rgba(79,70,229,0.08))":no.background,cursor:"pointer"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsx("div",{style:{fontWeight:700,flex:1},children:I.title}),I.attached?o.jsx(Mt,{children:"attached"}):null]}),o.jsx("div",{style:{fontSize:11,opacity:.68,marginTop:4,fontFamily:"monospace"},children:I.path})]},I.path))}),o.jsx(Ge,{label:"Advanced path",children:o.jsx("input",{value:t,onChange:I=>E(I.target.value),onKeyDown:I=>{I.key==="Enter"&&g(),I.key==="Escape"&&h()},placeholder:"notebooks/cards_fraud_ops.dqlnb",style:_e})})]}):o.jsx(Ge,{label:"New notebook name",children:o.jsx("input",{value:l,onChange:I=>S(I.target.value),onKeyDown:I=>{I.key==="Enter"&&g(),I.key==="Escape"&&h()},placeholder:"fraud investigation notes",autoFocus:!0,style:_e})}),o.jsx(Ge,{label:"Optional title",children:o.jsx("input",{value:n,onChange:I=>f(I.target.value),placeholder:"Fraud investigation notebook",style:_e})}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[o.jsx(Ge,{label:"Role",children:o.jsxs("select",{value:r,onChange:I=>T(I.target.value),style:_e,children:[o.jsx("option",{value:"source",children:"Source"}),o.jsx("option",{value:"analysis",children:"Analysis"}),o.jsx("option",{value:"supporting",children:"Supporting"})]})}),o.jsx(Ge,{label:"Visibility",children:o.jsxs("select",{value:s,onChange:I=>A(I.target.value),style:_e,children:[o.jsx("option",{value:"shared",children:"Shared"}),o.jsx("option",{value:"private",children:"Private"}),o.jsx("option",{value:"template",children:"Template"})]})})]}),c?o.jsx("div",{style:{color:"#f85149",fontSize:12},children:c}):null,o.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[o.jsx("button",{onClick:h,disabled:d,style:Ao,children:"Cancel"}),o.jsx("button",{onClick:g,disabled:d||(e==="existing"?!t.trim():!l.trim()&&!n.trim()),style:{...gr,opacity:d||(e==="existing"?!t.trim():!l.trim()&&!n.trim())?.65:1},children:d?"Saving...":e==="new"?"Create notebook":"Attach notebook"})]})]})})}function a6({section:e,experience:t,dashboardCount:n,notebookCount:r,aiCount:s,draftCount:i,onChange:a}){const l=[{id:"dashboards",label:"Dashboards",count:n},{id:"notebooks",label:"Notebooks",count:r},{id:"ai",label:"AI",count:s},...t==="build"?[{id:"drafts",label:"Drafts",count:i},{id:"settings",label:"Settings"}]:[]];return o.jsx("nav",{style:{display:"flex",gap:8,padding:"12px 16px 0",borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.08))",overflowX:"auto",background:"var(--color-bg, #fff)"},children:l.map(c=>o.jsxs("button",{onClick:()=>a(c.id),style:M6(e===c.id),children:[c.label,c.count!==void 0?o.jsx("span",{style:{opacity:.65,marginLeft:6},children:c.count}):null]},c.id))})}function l6({dashboards:e,activeDashboardId:t,isBuild:n,onOpen:r,onAddPage:s}){return o.jsxs("nav",{style:{display:"flex",gap:8,padding:"12px 16px",borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.06))",overflowX:"auto",background:"var(--color-bg, #fff)"},children:[e.map(i=>o.jsxs("button",{onClick:()=>r(i.id),style:aI(i.id===t),children:[i.title,i.itemCount>0?o.jsxs("span",{style:{opacity:.72,marginLeft:6},children:["· ",i.itemCount]}):null]},i.id)),n?o.jsx("button",{type:"button",onClick:s,style:lI,children:"+"}):null]})}function c6({appDoc:e,editable:t,onAttach:n,onOpenNotebook:r}){var h;const s=e.notebooks??e.app.notebooks??[],{state:i}=Re(),[a,l]=p.useState(((h=s[0])==null?void 0:h.path)??null),[c,d]=p.useState(null),[u,E]=p.useState(!1),[f,T]=p.useState(!1),[A,R]=p.useState(null);p.useEffect(()=>{var g;(!a||!s.some(m=>m.path===a))&&l(((g=s[0])==null?void 0:g.path)??null)},[a,s]),p.useEffect(()=>{if(!a){d(null);return}let g=!1;return E(!0),$.previewAppNotebook(e.app.id,a).then(m=>{g||d(m)}).finally(()=>{g||E(!1)}),()=>{g=!0}},[e.app.id,a]);const S=async()=>{if(!a)return;T(!0),R(null);const g=await $.runAppNotebook(e.app.id,a);if(T(!1),!g.ok){R(g.error??"Notebook run failed.");return}d(g.preview)};return o.jsxs("section",{style:{display:"grid",gap:12,width:"100%"},children:[o.jsx("div",{style:{display:"flex",alignItems:"center",gap:10},children:o.jsxs("div",{style:{minWidth:0,flex:1},children:[o.jsx("h2",{style:{margin:0,fontSize:18,lineHeight:1.2},children:"Notebooks"}),o.jsx("div",{style:{fontSize:12,opacity:.65,marginTop:3},children:"Attached analysis workbooks for this App."})]})}),s.length===0&&!t?o.jsx("div",{style:Un,children:"No notebooks are attached to this App yet."}):o.jsxs("div",{style:{display:"grid",gap:12},children:[o.jsxs("div",{style:{display:"flex",gap:8,overflowX:"auto",paddingBottom:2},children:[s.map(g=>o.jsxs("button",{type:"button",onClick:()=>l(g.path),title:g.path,style:P6(g.path===a),children:[o.jsx("span",{children:g.title??g.path}),g.role?o.jsxs("span",{style:{opacity:.72,marginLeft:6},children:["· ",g.role]}):null]},g.path)),t?o.jsx("button",{type:"button",onClick:n,title:"Add notebook",style:lI,children:"+"}):null]}),s.length===0?o.jsx("div",{style:Un,children:"No notebooks are attached yet. Use + to attach or create one."}):o.jsx("div",{children:u?o.jsx(nI,{title:"Loading notebook...",path:a??"",themeMode:i.themeMode,cellCount:0,running:f,error:A,onRun:()=>void S(),onOpen:()=>a?r(a):void 0,children:o.jsx("div",{style:{maxWidth:1200,margin:"0 auto",padding:"32px 24px",color:ce[i.themeMode].textMuted},children:"Loading notebook..."})}):c?o.jsx(d6,{preview:c,themeMode:i.themeMode,running:f,error:A,onRun:()=>void S(),onOpen:()=>r(c.path)}):o.jsx("div",{style:Un,children:"Select a notebook to view it."})})]})]})}function d6({preview:e,themeMode:t,running:n,error:r,onRun:s,onOpen:i}){const a=ce[t];return o.jsxs(nI,{title:e.title,path:e.path,themeMode:t,cellCount:e.cells.length,capturedAt:e.capturedAt,running:n,error:r,onRun:s,onOpen:i,children:[r?o.jsx("div",{style:{color:"#f85149",fontSize:12},children:r}):null,e.metadata?o.jsx(f6,{metadata:e.metadata,theme:a}):null,o.jsx("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px 40px",display:"flex",flexDirection:"column",gap:8},children:e.cells.length===0?o.jsx("div",{style:Un,children:"This notebook has no cells."}):e.cells.map(l=>o.jsx(u6,{cell:l,themeMode:t},l.id))})]})}function u6({cell:e,themeMode:t}){const n=ce[t];e.name??KT[e.type]??e.type.toUpperCase();const r=e.type==="sql"||e.type==="dql"||e.type==="python"||e.type==="param"||e.type==="writeback",s=n6[e.type]??n.accent;return o.jsxs("div",{"data-readonly-notebook-cell":!0,style:{borderRadius:8,border:`1px solid ${n.cellBorder}`,background:n.cellBg,boxShadow:"0 1px 2px rgba(0,0,0,0.02)",overflow:"hidden"},children:[o.jsxs("div",{style:{minHeight:32,display:"flex",alignItems:"center",gap:8,padding:"8px 14px"},children:[o.jsx("span",{"aria-hidden":!0,style:{width:6,height:6,borderRadius:999,background:s,flexShrink:0}}),o.jsx("span",{style:{fontSize:11,fontWeight:500,color:n.textSecondary,whiteSpace:"nowrap"},children:KT[e.type]??e.type}),e.name?o.jsx("span",{style:{color:n.textSecondary,fontSize:12,fontFamily:n.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:260},children:e.name}):null,o.jsx("div",{style:{flex:1}}),o.jsx(S6,{cell:e,theme:n})]}),o.jsxs("div",{children:[e.type==="markdown"?o.jsx(C6,{source:e.content,theme:n}):null,r?o.jsx(p6,{content:e.content,theme:n}):null,e.error?o.jsx("div",{style:{borderTop:`1px solid ${n.cellBorder}`,padding:12,color:n.error,fontSize:12},children:e.error}):null,e.result?o.jsx(T6,{cell:e,theme:n,themeMode:t}):null]})]})}function nI({title:e,path:t,themeMode:n,cellCount:r,capturedAt:s,running:i,error:a,onRun:l,onOpen:c,children:d}){const u=ce[n];return o.jsxs("div",{style:{border:`1px solid ${u.headerBorder}`,borderRadius:8,overflow:"hidden",background:u.appBg,minHeight:520},children:[o.jsxs("div",{style:{minHeight:34,borderBottom:`1px solid ${u.headerBorder}`,background:u.cellBg,display:"flex",alignItems:"center",padding:"0 12px 0 16px",gap:12},children:[o.jsx(E6,{title:e,path:t,theme:u}),o.jsx("div",{style:{flex:1}}),o.jsxs("span",{style:{fontSize:11,color:u.textMuted,fontFamily:u.font,whiteSpace:"nowrap"},children:[r," ",r===1?"cell":"cells",s?` · Last run ${iI(s)}`:" · No saved run yet"]}),a?o.jsx("span",{style:{fontSize:11,color:u.error},children:"Run failed"}):null,o.jsx("button",{type:"button",onClick:l,disabled:i,style:{...gr,padding:"5px 9px",opacity:i?.65:1},children:i?"Running...":"Run notebook"}),o.jsx("button",{type:"button",onClick:c,style:{...Ao,padding:"5px 9px"},children:"Open / Edit"})]}),o.jsx("div",{style:{paddingTop:14},children:d})]})}function E6({title:e,path:t,theme:n}){const r=t.split("/").filter(Boolean);return o.jsxs("div",{style:{minWidth:0,display:"flex",alignItems:"center",gap:4,fontSize:12,fontFamily:n.fontMono,color:n.textMuted,overflow:"hidden"},children:[o.jsx("span",{style:{color:n.textSecondary,fontWeight:600,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:220},children:e}),r.length>0?o.jsx("span",{style:{color:n.textMuted,opacity:.45},children:"/"}):null,r.slice(-2).map((s,i,a)=>o.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,minWidth:0},children:[i>0?o.jsx("span",{style:{color:n.textMuted,opacity:.45},children:"/"}):null,o.jsx("span",{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:i===a.length-1?220:120},children:s})]},`${s}:${i}`))]})}function f6({metadata:e,theme:t}){const r=[["Status",e.status],["Owner",e.owner??e.author],["Description",e.description],["Categories",Array.isArray(e.categories)?e.categories.join(", "):e.categories]].filter(([,s])=>s!=null&&String(s).trim()!=="");return r.length===0?null:o.jsx("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px 12px"},children:o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8,color:t.textMuted},children:r.map(([s,i])=>o.jsxs("span",{style:{fontSize:11,fontFamily:t.font,border:`1px solid ${t.cellBorder}`,borderRadius:4,padding:"3px 7px",background:t.cellBg},children:[o.jsxs("strong",{style:{color:t.textSecondary},children:[s,":"]})," ",String(i)]},s))})})}function p6({content:e,theme:t}){return o.jsx("pre",{style:{margin:0,padding:"10px 14px 12px",borderTop:`1px solid ${t.cellBorder}`,background:t.editorBg,color:t.textPrimary,fontFamily:t.fontMono,fontSize:12,lineHeight:1.55,whiteSpace:"pre-wrap",overflowX:"auto"},children:e})}function T6({cell:e,theme:t,themeMode:n}){const r=e.result,[s,i]=p.useState(()=>A6(e)),a=h6(e,n,s),[l,c]=p.useState(()=>R6(e)),d=r&&e.type==="table"?O6(r,e.tableConfig):r,u=g6(e);return o.jsxs("div",{style:{borderTop:`1px solid ${t.cellBorder}`},children:[r?o.jsxs("div",{style:{minHeight:28,display:"flex",alignItems:"center",padding:"0 12px",gap:10,borderBottom:`1px solid ${t.cellBorder}`,background:`${t.tableHeaderBg}60`},children:[o.jsxs("span",{style:{fontSize:11,fontFamily:t.font,color:t.textMuted},children:[(r.rowCount??r.rows.length).toLocaleString()," rows",r.executionTime!==void 0?` · ${y6(r.executionTime)}`:""]}),e.executedAt?o.jsx("span",{style:{fontSize:10,color:t.textMuted},children:"cached"}):null,o.jsx("div",{style:{flex:1}}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:3},children:[o.jsx("button",{type:"button",onClick:()=>c("table"),style:rI(l==="table",t),children:"Table"}),o.jsx("select",{value:s,onChange:E=>{i(E.target.value),c("visualization")},onClick:()=>c("visualization"),title:"Choose visualization type",style:I6(l==="visualization",t),children:u.map(E=>o.jsx("option",{value:E.value,children:E.label},E.value))})]})]}):null,o.jsx("div",{children:l==="visualization"&&a?a:d?o.jsx(Rn,{result:d,themeMode:n}):null})]})}function S6({cell:e,theme:t}){if(!e.status||e.status==="idle")return null;const n=e.status==="success"?t.success:e.status==="error"?t.error:t.warning;return o.jsx("span",{style:{fontSize:10,fontFamily:t.font,color:n,border:`1px solid ${n}55`,borderRadius:3,padding:"1px 6px",lineHeight:"16px"},children:e.status})}function h6(e,t,n){const r=e.result;return r?n==="pivot"&&e.type==="pivot"?o.jsx(x6,{result:r,config:e.pivotConfig,themeMode:t}):n==="kpi"&&e.type==="single_value"?o.jsx(N6,{result:r,config:e.singleValueConfig}):o.jsx($a,{result:r,themeMode:t,chartConfig:{...e.chartConfig??{},chart:n}}):null}function R6(e){var n;if(e.type==="chart"||e.type==="single_value"||e.type==="pivot")return"visualization";const t=String(((n=e.chartConfig)==null?void 0:n.chart)??"").toLowerCase();return t&&t!=="table"?"visualization":"table"}function A6(e){var n;if(e.type==="pivot")return"pivot";if(e.type==="single_value")return"kpi";const t=m6((n=e.chartConfig)==null?void 0:n.chart);if(t)return t;if(e.result){const r=pr(e.result,e.chartConfig);if(r!=="table")return r}return"bar"}function m6(e){if(typeof e!="string")return null;const t=e.toLowerCase().replace(/_/g,"-");return t==="pivot"?"pivot":zn.some(n=>n.value===t)?t:null}function g6(e){const t=zn.map(n=>({value:n.value,label:n.label}));return e.type==="pivot"?[{value:"pivot",label:"Pivot"},...t]:t}function rI(e,t){return{padding:"1px 7px",fontSize:10,fontFamily:t.font,borderRadius:3,border:`1px solid ${e?t.accent:t.btnBorder}`,background:e?`${t.accent}20`:"transparent",color:e?t.accent:t.textMuted,cursor:"pointer",transition:"all 0.15s"}}function I6(e,t){return{...rI(e,t),minWidth:118,padding:"1px 22px 1px 7px",outline:"none"}}function O6(e,t){const n=Array.isArray(t==null?void 0:t.visibleColumns)?t.visibleColumns.filter(i=>typeof i=="string"):[];if(n.length===0)return e;const r=new Set(e.columns),s=n.filter(i=>r.has(i));return s.length===0?e:{...e,columns:s,rows:e.rows.map(i=>Object.fromEntries(s.map(a=>[a,i[a]])))}}function N6({result:e,config:t}){const n=oI(t==null?void 0:t.aggregation,"count"),r=typeof(t==null?void 0:t.metric)=="string"?t.metric:void 0,s=typeof(t==null?void 0:t.label)=="string"&&t.label.trim()?t.label:`${n.toUpperCase()}${r?` · ${r}`:""}`,i=typeof(t==null?void 0:t.format)=="string"?t.format:"number",a=n==="count"?ao(e.rows,"count"):r&&e.columns.includes(r)?ao(e.rows.map(l=>l[r]),n):null;return o.jsxs("div",{style:{border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6,padding:"18px 20px",display:"grid",gap:6,background:"var(--surface-subtle, rgba(0,0,0,0.02))"},children:[o.jsx("div",{style:{fontSize:11,opacity:.62,textTransform:"uppercase",fontWeight:700},children:s}),o.jsx("div",{style:{fontSize:34,lineHeight:1.1,fontWeight:800},children:sI(a,i)}),o.jsxs("div",{style:{fontSize:11,opacity:.6},children:[e.rows.length.toLocaleString()," rows"]})]})}function x6({result:e,config:t,themeMode:n}){const r=qT(t==null?void 0:t.rows).filter(u=>e.columns.includes(u)),s=qT(t==null?void 0:t.columns).filter(u=>e.columns.includes(u)),i=Array.isArray(t==null?void 0:t.values)?t.values.map(u=>{if(!u||typeof u!="object")return null;const E=u,f=typeof E.column=="string"?E.column:"";return e.columns.includes(f)?{column:f,aggregation:oI(E.aggregation,"sum")}:null}).filter(u=>!!u):[];if(r.length===0&&s.length===0||i.length===0)return o.jsx(Rn,{result:e,themeMode:n});const a=new Set,l=new Map;for(const u of e.rows){const E=JT(u,r),f=JT(u,s);a.add(f);const T=l.get(E)??{rowDims:Object.fromEntries(r.map(R=>[R,u[R]])),buckets:new Map},A=T.buckets.get(f)??[];A.push(u),T.buckets.set(f,A),l.set(E,T)}const c=[...a].sort(),d=c.length>0?c:[""];return o.jsx("div",{style:{overflowX:"auto"},children:o.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11},children:[o.jsx("thead",{children:o.jsxs("tr",{children:[r.map(u=>o.jsx("th",{style:QT("left"),children:u},u)),d.map(u=>o.jsx("th",{style:QT("right"),children:u||"value"},u||"value"))]})}),o.jsx("tbody",{children:[...l.values()].slice(0,50).map((u,E)=>o.jsxs("tr",{children:[r.map(f=>o.jsx("td",{style:ZT("left"),children:String(u.rowDims[f]??"")},f)),d.map(f=>{const T=u.buckets.get(f)??[];return o.jsx("td",{style:ZT("right"),children:i.map(A=>{const R=ao(T.map(S=>S[A.column]),A.aggregation);return o.jsx("div",{children:sI(R,"number")},`${A.aggregation}:${A.column}`)})},f||"value")})]},E))})]})})}function qT(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function oI(e,t){return e==="sum"||e==="avg"||e==="count"||e==="count_distinct"||e==="min"||e==="max"||e==="last"?e:t}function JT(e,t){return t.map(n=>String(e[n]??"")).join("|")}function sI(e,t){return e===null?"-":t==="currency"?e.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):t==="percent"?`${(e*100).toFixed(1)}%`:t==="duration"?e<60?`${e.toFixed(1)}s`:e<3600?`${(e/60).toFixed(1)}m`:`${(e/3600).toFixed(1)}h`:e.toLocaleString(void 0,{maximumFractionDigits:2})}function y6(e){return e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(2)}s`}function QT(e){return{textAlign:e,padding:"6px 8px",borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.1))",opacity:.72,fontWeight:700}}function ZT(e){return{textAlign:e,padding:"5px 8px",borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.06))"}}function C6({source:e,theme:t}){return o.jsx("div",{style:{padding:"10px 14px 14px",display:"grid",gap:6,lineHeight:1.45,color:t.textPrimary},children:XR(e,t)})}function L6({appDoc:e,editable:t,onPromoted:n}){var h;const r=e.aiPins??[],[s,i]=p.useState("conversations"),[a,l]=p.useState([]),[c,d]=p.useState(null),[u,E]=p.useState(null),[f,T]=p.useState(null);p.useEffect(()=>{let g=!1;return $.listAppConversations(e.app.id).then(m=>{g||l(m)}),d(null),()=>{g=!0}},[e.app.id]);const A=async g=>{T(null),E(g);const m=await $.promoteAiPin(e.app.id,g);if(E(null),!m.ok){T(m.error??"Promotion failed.");return}await n()},R=async g=>{E(g);const m=await $.deleteAppConversation(e.app.id,g);if(E(null),!m.ok){T(m.error??"Could not delete conversation.");return}(c==null?void 0:c.id)===g&&d(null),l(I=>I.filter(O=>O.id!==g))},S=async g=>{const m=await $.getAppConversation(e.app.id,g);d(m)};return o.jsxs(Ju,{title:"AI",children:[o.jsxs("div",{style:{display:"flex",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,overflow:"hidden",width:"fit-content"},children:[o.jsxs("button",{type:"button",onClick:()=>i("conversations"),style:ma(s==="conversations"),children:["Conversations ",o.jsx("span",{style:{opacity:.65,marginLeft:4},children:a.length})]}),o.jsxs("button",{type:"button",onClick:()=>i("pins"),style:ma(s==="pins"),children:["Pinned summaries ",o.jsx("span",{style:{opacity:.65,marginLeft:4},children:r.length})]})]}),f?o.jsx("div",{style:{color:"#f85149",fontSize:12},children:f}):null,s==="conversations"?c?o.jsxs("div",{style:no,children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[o.jsx("button",{type:"button",onClick:()=>d(null),style:xi,children:"Back"}),o.jsx("div",{style:{fontWeight:700,flex:1},children:c.title}),o.jsx(Mt,{children:`${((h=c.messages)==null?void 0:h.length)??c.messageCount} messages`})]}),o.jsx("div",{style:{display:"grid",gap:8,marginTop:12},children:(c.messages??[]).map((g,m)=>o.jsxs("div",{style:{border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6,padding:10,background:g.role==="user"?"var(--color-bg-active, rgba(79,70,229,0.08))":"var(--surface, rgba(0,0,0,0.02))"},children:[o.jsx("div",{style:{fontSize:10,textTransform:"uppercase",fontWeight:800,opacity:.62,marginBottom:4},children:g.role==="user"?"You":"DQL Agent"}),o.jsx("div",{style:{whiteSpace:"pre-wrap",fontSize:12,lineHeight:1.45},children:g.content})]},g.id??m))})]}):a.length===0?o.jsx("div",{style:Un,children:"Dashboard AI conversations are saved locally and will appear here after you ask AI from a dashboard page."}):a.map(g=>o.jsxs("div",{style:no,children:[o.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[o.jsx("div",{style:{fontWeight:700,flex:1},children:g.title}),o.jsx(Mt,{children:`${g.messageCount} messages`}),g.dashboardId?o.jsx(Mt,{children:g.dashboardId}):null]}),g.lastMessage?o.jsx("div",{style:{marginTop:8,whiteSpace:"pre-wrap",lineHeight:1.45,fontSize:12,opacity:.78},children:g.lastMessage}):null,o.jsxs("div",{style:{marginTop:8,display:"flex",alignItems:"center",gap:8},children:[o.jsxs("span",{style:{fontSize:11,opacity:.64},children:["Private local history · ",iI(g.updatedAt)]}),o.jsx("div",{style:{flex:1}}),o.jsx("button",{type:"button",onClick:()=>void S(g.id),style:xi,children:"Open"}),t?o.jsx("button",{type:"button",onClick:()=>void R(g.id),style:xi,disabled:u===g.id,children:u===g.id?"Deleting...":"Delete"}):null]})]},g.id)):r.length===0?o.jsx("div",{style:Un,children:"Pinned AI summaries for this App will appear here."}):r.map(g=>o.jsxs("div",{style:no,children:[o.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[o.jsx("div",{style:{fontWeight:700,flex:1},children:g.title}),o.jsx(Mt,{children:g.reviewStatus}),o.jsx(Mt,{children:g.certification})]}),o.jsx("div",{style:{marginTop:8,whiteSpace:"pre-wrap",lineHeight:1.45,fontSize:12},children:g.answer}),o.jsxs("div",{style:{marginTop:8,display:"flex",gap:8,alignItems:"center"},children:[o.jsxs("span",{style:{fontSize:11,opacity:.64},children:[g.dashboardId,g.tileId?` · ${g.tileId}`:""]}),o.jsx("div",{style:{flex:1}}),t&&g.sql&&g.reviewStatus==="needs_review"?o.jsx("button",{type:"button",onClick:()=>void A(g.id),style:xi,disabled:u===g.id,children:u===g.id?"Promoting...":"Promote to draft"}):null]})]},g.id))]})}function _6({drafts:e}){return o.jsx(Ju,{title:"Draft Blocks",children:e.length===0?o.jsx("div",{style:Un,children:"AI-generated or imported DQL drafts promoted into this App appear here."}):e.map(t=>o.jsx(v6,{title:t.name,meta:t.reviewStatus??"review",detail:t.path},t.path))})}function b6({appDoc:e}){var n;const t=[["Domain path",Qu(e.app)],["Visibility",e.app.visibility??"shared"],["Lifecycle",e.app.lifecycle??"draft"],["Audience",e.app.audience??"-"],["Owners",e.app.owners.join(", ")||"-"],["Roles",String(e.app.roles.length)],["Policies",String(e.app.policies.length)],["Schedules",String(((n=e.app.schedules)==null?void 0:n.length)??0)]];return o.jsx(Ju,{title:"App Settings",children:o.jsx("div",{style:{border:"1px solid var(--border-color, rgba(0,0,0,0.10))",borderRadius:6,overflow:"hidden"},children:t.map(([r,s])=>o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"160px 1fr",borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.06))"},children:[o.jsx("div",{style:{padding:9,fontSize:11,opacity:.62},children:r}),o.jsx("div",{style:{padding:9,fontSize:12},children:s})]},r))})})}function Ju({title:e,action:t,children:n}){return o.jsxs("section",{style:{display:"grid",gap:12,maxWidth:920},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[o.jsx("h2",{style:{margin:0,fontSize:18},children:e}),o.jsx("div",{style:{flex:1}}),t]}),n]})}function v6({title:e,meta:t,detail:n}){return o.jsxs("div",{style:no,children:[o.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[o.jsx("div",{style:{fontWeight:700},children:e}),o.jsx(Mt,{children:t})]}),o.jsx("div",{style:{fontSize:12,opacity:.7,marginTop:5,fontFamily:"monospace"},children:n})]})}function eS({onClose:e,onCreated:t}){const{dispatch:n}=Re(),[r,s]=p.useState("empty"),[i,a]=p.useState(""),[l,c]=p.useState(""),[d,u]=p.useState("Overview"),[E,f]=p.useState(""),[T,A]=p.useState(""),[R,S]=p.useState(""),[h,g]=p.useState(""),[m,I]=p.useState(""),[O,N]=p.useState(""),[x,_]=p.useState("draft"),[C,v]=p.useState("shared"),[b,P]=p.useState(""),[j,L]=p.useState(`${window.DQL_USER??"owner"}@local`),[B,M]=p.useState(!1),[U,D]=p.useState(null),y=p.useMemo(()=>b.split(",").map(k=>k.trim()).filter(Boolean),[b]),w=!!(i.trim()&&l.trim()&&d.trim()&&(r!=="notebook"||h.trim())),F=async()=>{if(!(!w||r==="import")){M(!0),D(null);try{const k=await $.createApp({name:i,domain:l,dashboardTitle:d,subdomain:E.trim()||void 0,groups:T.split(",").map(V=>V.trim()).filter(Boolean),purpose:R,audience:O.trim()||void 0,visibility:C,lifecycle:x,tags:sr([...y,...r==="empty"?[]:[`source:${r}`]]),owners:[j],selectedBlockIds:[]});if(r==="notebook"&&h.trim()){const V=await $.attachAppNotebook(k.app.id,{path:h.trim(),title:m.trim()||void 0,role:"analysis",visibility:"shared"});if("ok"in V&&V.ok===!1){t(k.app.id,k.dashboardId),D(`App created, but notebook attach failed: ${V.error}`);return}}t(k.app.id,k.dashboardId),e()}catch(k){D(k instanceof Error?k.message:String(k))}finally{M(!1)}}};return o.jsx("div",{style:Zu,children:o.jsxs("div",{style:{...eE,width:760,maxWidth:"calc(100vw - 48px)",maxHeight:"calc(100vh - 48px)",overflow:"auto"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.08))",padding:16},children:[o.jsxs("div",{style:{flex:1},children:[o.jsx("div",{style:{fontSize:18,fontWeight:700},children:"Create App"}),o.jsx("div",{style:{fontSize:12,opacity:.65},children:"Create one App with an Overview dashboard page. Add blocks, notebooks, AI pins, and drafts after creation."})]}),o.jsx("button",{onClick:e,style:Ao,children:"Close"})]}),o.jsxs("div",{style:{padding:16,display:"grid",gap:14},children:[o.jsxs("div",{style:{display:"grid",gap:6},children:[o.jsx("div",{style:{fontSize:12,fontWeight:600},children:"Start from"}),o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, minmax(0, 1fr))",gap:8},children:[["empty","Empty App"],["notebook","From Notebook"],["template","From Template"],["import","From Import"]].map(([k,V])=>o.jsx("button",{type:"button",onClick:()=>s(k),style:U6(r===k),children:V},k))})]}),r==="import"?o.jsx(tS,{title:"Use Block Studio Imports",text:"Import SQL files in Block Studio first, review and save draft blocks, then return here to create an App and add those blocks from the Build catalog."}):null,o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[o.jsx(Ge,{label:"App name",children:o.jsx("input",{value:i,onChange:k=>a(k.target.value),placeholder:"Daily Fraud Ops App",style:_e})}),o.jsx(Ge,{label:"First dashboard page",children:o.jsx("input",{value:d,onChange:k=>u(k.target.value),placeholder:"Overview",style:_e})})]}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[o.jsx(Ge,{label:"Domain",children:o.jsx("input",{value:l,onChange:k=>c(k.target.value),placeholder:"cards",style:_e})}),o.jsx(Ge,{label:"Subdomain",children:o.jsx("input",{value:E,onChange:k=>f(k.target.value),placeholder:"fraud",style:_e})})]}),o.jsx(Ge,{label:"Group / use case",children:o.jsx("input",{value:T,onChange:k=>A(k.target.value),placeholder:"daily-ops, executive-review",style:_e})}),r==="notebook"?o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[o.jsx(Ge,{label:"Notebook path",children:o.jsx("input",{value:h,onChange:k=>g(k.target.value),placeholder:"notebooks/cards_fraud_ops.dqlnb",style:_e})}),o.jsx(Ge,{label:"Notebook title",children:o.jsx("input",{value:m,onChange:k=>I(k.target.value),placeholder:"Fraud investigation notebook",style:_e})})]}):null,o.jsx(Ge,{label:"Purpose",children:o.jsx("textarea",{value:R,onChange:k=>S(k.target.value),placeholder:"Daily operating view for monitoring fraud risk, investigation queues, and trend movement.",style:{..._e,minHeight:76,resize:"vertical"}})}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[o.jsx(Ge,{label:"Audience",children:o.jsx("input",{value:O,onChange:k=>N(k.target.value),placeholder:"ops, executive, analyst",style:_e})}),o.jsx(Ge,{label:"Owner",children:o.jsx("input",{value:j,onChange:k=>L(k.target.value),placeholder:"owner@local",style:_e})})]}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[o.jsx(Ge,{label:"Visibility",children:o.jsxs("select",{value:C,onChange:k=>v(k.target.value),style:_e,children:[o.jsx("option",{value:"shared",children:"shared"}),o.jsx("option",{value:"private",children:"private"}),o.jsx("option",{value:"template",children:"template"})]})}),o.jsx(Ge,{label:"Lifecycle",children:o.jsxs("select",{value:x,onChange:k=>_(k.target.value),style:_e,children:[o.jsx("option",{value:"draft",children:"draft"}),o.jsx("option",{value:"review",children:"review"}),o.jsx("option",{value:"certified",children:"certified"}),o.jsx("option",{value:"deprecated",children:"deprecated"})]})})]}),o.jsx(Ge,{label:"Tags",children:o.jsx("input",{value:b,onChange:k=>P(k.target.value),placeholder:"fraud, daily, ops",style:_e})}),o.jsx(tS,{title:"After create",text:"Open Build mode to add blocks from the catalog, add more dashboard pages, attach notebooks, and pin AI answers."}),U&&o.jsx("div",{style:{color:"#f85149",fontSize:12},children:U})]}),o.jsxs("footer",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:16,borderTop:"1px solid var(--border-color, rgba(0,0,0,0.08))"},children:[o.jsx("button",{onClick:e,disabled:B,style:Ao,children:"Cancel"}),r==="import"?o.jsx("button",{type:"button",onClick:()=>{e(),n({type:"OPEN_BLOCK_IMPORT"})},style:gr,children:"Open Import"}):o.jsx("button",{onClick:F,disabled:B||!w,style:{...gr,opacity:B||!w?.65:1},children:B?"Creating...":"Create App"})]})]})})}function D6({app:e,active:t,onClick:n}){return o.jsxs("button",{onClick:n,style:{display:"block",width:"100%",textAlign:"left",padding:"10px 14px",background:t?"var(--surface-hover, rgba(0,0,0,0.06))":"transparent",border:"none",borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.04))",cursor:"pointer",color:"inherit",fontSize:13},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[o.jsx("span",{style:{fontWeight:t?700:600,flex:1},children:e.name}),o.jsx("span",{style:{fontSize:10,opacity:.65},children:e.lifecycle??e.status??"ready"})]}),o.jsxs("div",{style:{fontSize:11,opacity:.65,marginTop:3},children:[Qu(e)," · ",e.dashboards.length," dashboard",e.dashboards.length===1?"":"s"," · ",(e.notebooks??[]).length," notebook",(e.notebooks??[]).length===1?"":"s"]}),o.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap",marginTop:6},children:[o.jsx(Mt,{children:e.storage??"shared"}),o.jsx(Mt,{children:e.certification??"uncertified"}),(e.tags??[]).filter(r=>!r.startsWith("audience:")).slice(0,3).map(r=>o.jsx(Mt,{children:r},r))]})]})}function Fo({message:e,hint:t,onCreate:n}){return o.jsxs("div",{style:{display:"flex",flex:1,minHeight:260,alignItems:"center",justifyContent:"center",flexDirection:"column",gap:10,opacity:.8,fontSize:14},children:[o.jsx("div",{children:e}),t?o.jsx("div",{style:{fontSize:12,opacity:.7},children:t}):null,n?o.jsx("button",{onClick:n,style:gr,children:"Create App"}):null]})}function Ge({label:e,children:t}){return o.jsxs("label",{style:{display:"grid",gap:5,fontSize:12,fontWeight:600},children:[e,t]})}function tS({title:e,text:t}){return o.jsxs("div",{style:{border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,padding:12},children:[o.jsx("div",{style:{fontSize:13,fontWeight:700,marginBottom:4},children:e}),o.jsx("div",{style:{fontSize:12,opacity:.72,lineHeight:1.45},children:t})]})}function Mt({children:e}){return o.jsx("span",{style:{fontSize:10,padding:"1px 6px",borderRadius:4,background:"var(--surface-hover, rgba(0,0,0,0.06))",opacity:.82},children:e})}function sr(e){return Array.from(new Set(e.filter(Boolean))).sort((t,n)=>t.localeCompare(n))}function Qu(e){return[e.domain,e.subdomain,...e.groups??[]].filter(Boolean).join(" / ")}function iI(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}const _e={width:"100%",boxSizing:"border-box",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:5,background:"var(--surface, transparent)",color:"inherit",fontSize:12,padding:"7px 8px"},gr={border:"1px solid var(--accent, #4f46e5)",background:"var(--accent, #4f46e5)",color:"var(--color-text-on-accent, #fff)",borderRadius:5,padding:"6px 10px",fontSize:12,fontWeight:600,cursor:"pointer"},Ao={border:"1px solid var(--border-color, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",borderRadius:5,padding:"6px 10px",fontSize:12,cursor:"pointer"},Un={fontSize:12,opacity:.65,padding:12},Zu={position:"fixed",inset:0,zIndex:80,background:"rgba(0,0,0,0.36)",display:"flex",alignItems:"center",justifyContent:"center",padding:24},eE={width:"min(420px, 92vw)",display:"grid",background:"var(--color-bg, #fff)",color:"inherit",borderRadius:8,boxShadow:"0 18px 60px rgba(0,0,0,0.35)",padding:16},no={border:"1px solid var(--border-color, rgba(0,0,0,0.10))",borderRadius:7,background:"var(--surface, rgba(0,0,0,0.02))",padding:12},xi={border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:5,background:"var(--surface, rgba(0,0,0,0.02))",color:"inherit",padding:"4px 8px",fontSize:11,cursor:"pointer"};function M6(e){return{padding:"8px 13px",marginBottom:-1,background:e?"var(--accent, #4f46e5)":"transparent",color:e?"var(--color-text-on-accent, #fff)":"var(--color-text-secondary, rgba(0,0,0,0.72))",border:e?"1px solid var(--accent, #4f46e5)":"1px solid transparent",borderRadius:"6px 6px 0 0",fontSize:13,fontWeight:e?700:500,cursor:"pointer"}}function aI(e){return{padding:"6px 12px",background:e?"var(--accent, #4f46e5)":"var(--surface, rgba(0,0,0,0.015))",color:e?"var(--color-text-on-accent, #fff)":"inherit",border:`1px solid ${e?"var(--accent, #4f46e5)":"var(--border-color, rgba(0,0,0,0.12))"}`,borderRadius:6,fontSize:13,fontWeight:e?700:500,cursor:"pointer",whiteSpace:"nowrap"}}function P6(e){return{...aI(e),maxWidth:340,overflow:"hidden",textOverflow:"ellipsis"}}const lI={padding:"5px 10px",minWidth:34,background:"transparent",color:"inherit",border:"1px dashed var(--border-color, rgba(0,0,0,0.22))",borderRadius:6,fontSize:15,lineHeight:1,cursor:"pointer"};function nS(e){return{border:"none",borderRadius:5,background:e?"var(--accent, #4f46e5)":"transparent",color:e?"var(--color-text-on-accent, #fff)":"var(--color-text-secondary, rgba(0,0,0,0.66))",padding:"5px 11px",fontSize:12,fontWeight:e?700:500,cursor:"pointer"}}function ma(e){return{border:"none",borderRight:"1px solid var(--border-color, rgba(0,0,0,0.10))",background:e?"var(--accent, #4f46e5)":"transparent",color:e?"var(--color-text-on-accent, #fff)":"inherit",padding:"6px 10px",fontSize:12,fontWeight:e?700:500,cursor:"pointer"}}function w6(e){return{border:"1px solid var(--border-color, rgba(0,0,0,0.10))",borderRadius:5,background:e?"var(--accent, #4f46e5)":"transparent",color:e?"var(--color-text-on-accent, #fff)":"inherit",padding:"5px 4px",fontSize:11,cursor:"pointer"}}function U6(e){return{minHeight:38,border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,background:e?"var(--accent, #4f46e5)":"var(--surface, transparent)",color:e?"var(--color-text-on-accent, #fff)":"inherit",padding:"7px 8px",fontSize:12,fontWeight:e?700:600,cursor:"pointer"}}function B6(){const{state:e,dispatch:t}=Re();p.useEffect(()=>{let r=!1;if(!(e.apps.length>0))return t({type:"SET_APPS_LOADING",loading:!0}),$.listApps().then(s=>{r||(t({type:"SET_APPS",apps:s}),t({type:"SET_APPS_LOADING",loading:!1}))}),()=>{r=!0}},[t,e.apps.length]);const n=p.useMemo(()=>e.apps.filter(r=>{var s;return r.lifecycle==="review"||(((s=r.drafts)==null?void 0:s.length)??0)>0||(r.aiPins??0)>0}).sort((r,s)=>oS(s)-oS(r)||r.name.localeCompare(s.name)),[e.apps]);return o.jsxs("div",{style:{padding:20,display:"grid",gap:14},children:[o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, minmax(0, 1fr))",gap:10},children:[o.jsx(yi,{label:"Apps in review",value:e.apps.filter(r=>r.lifecycle==="review").length}),o.jsx(yi,{label:"Draft blocks",value:e.apps.reduce((r,s)=>{var i;return r+(((i=s.drafts)==null?void 0:i.length)??0)},0)}),o.jsx(yi,{label:"AI pins",value:e.apps.reduce((r,s)=>r+(s.aiPins??0),0)}),o.jsx(yi,{label:"Certified Apps",value:e.apps.filter(r=>r.lifecycle==="certified").length})]}),o.jsx("div",{style:{display:"grid",gap:8},children:e.appsLoading&&e.apps.length===0?o.jsx("div",{style:sS,children:"Loading review queue..."}):n.length===0?o.jsx("div",{style:sS,children:"No Apps or drafts are waiting for review."}):n.map(r=>o.jsx(j6,{app:r,onOpen:()=>t({type:"OPEN_APP",appId:r.id})},r.id))})]})}function j6({app:e,onOpen:t}){var n,r;return o.jsxs("button",{type:"button",onClick:t,style:k6,children:[o.jsxs("div",{style:{display:"grid",gap:5,minWidth:0},children:[o.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[o.jsx("span",{style:{fontSize:14,fontWeight:750},children:e.name}),o.jsx(rS,{children:e.lifecycle??"draft"}),o.jsx(rS,{children:e.visibility??e.storage??"shared"})]}),o.jsxs("div",{style:{fontSize:12,opacity:.68},children:[[e.domain,e.subdomain,...e.groups??[]].filter(Boolean).join(" / "),e.audience?` · ${e.audience}`:""]})]}),o.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",justifyContent:"flex-end",flexWrap:"wrap"},children:[o.jsx(Ci,{label:"dashboards",value:e.dashboards.length}),o.jsx(Ci,{label:"notebooks",value:((n=e.notebooks)==null?void 0:n.length)??0}),o.jsx(Ci,{label:"drafts",value:((r=e.drafts)==null?void 0:r.length)??0}),o.jsx(Ci,{label:"AI pins",value:e.aiPins??0})]})]})}function yi({label:e,value:t}){return o.jsxs("div",{style:F6,children:[o.jsx("div",{style:{fontSize:11,opacity:.62},children:e}),o.jsx("div",{style:{fontSize:24,fontWeight:800},children:t})]})}function Ci({label:e,value:t}){return o.jsxs("span",{style:{fontSize:11,opacity:.72},children:[o.jsx("strong",{style:{fontSize:13,opacity:1},children:t})," ",e]})}function rS({children:e}){return o.jsx("span",{style:{fontSize:10,padding:"2px 7px",borderRadius:4,background:"var(--surface-hover, rgba(0,0,0,0.06))",opacity:.82},children:e})}function oS(e){var t;return(e.lifecycle==="review"?100:0)+(((t=e.drafts)==null?void 0:t.length)??0)*10+(e.aiPins??0)}const k6={width:"100%",border:"1px solid var(--border-color, rgba(0,0,0,0.10))",borderRadius:7,background:"var(--surface, rgba(0,0,0,0.02))",color:"inherit",padding:12,display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",gap:12,textAlign:"left",cursor:"pointer"},F6={border:"1px solid var(--border-color, rgba(0,0,0,0.10))",borderRadius:7,background:"var(--surface, rgba(0,0,0,0.02))",padding:12},sS={border:"1px dashed var(--border-color, rgba(0,0,0,0.16))",borderRadius:8,padding:24,fontSize:13,opacity:.7},iS=["anthropic","openai","gemini","ollama","custom-openai"];function G6(){const{state:e}=Re(),t=ce[e.themeMode],[n,r]=p.useState([]),[s,i]=p.useState([]),[a,l]=p.useState([]),[c,d]=p.useState(!0),[u,E]=p.useState(null),f=async()=>{d(!0);try{const[A,R,S]=await Promise.all([$.getSettingsEnvStatus(),$.getProviderSettings(),$.listAgentMemory()]);r(A.groups),i(R.providers),l(S.memories)}finally{d(!1)}};p.useEffect(()=>{f()},[]);const T=p.useMemo(()=>s.filter(A=>A.enabled&&(A.hasApiKey||A.id==="ollama")).length,[s]);return o.jsxs("div",{style:{padding:24,maxWidth:1180},children:[o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:16},children:[o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:18,fontWeight:700},children:"AI & Memory Settings"}),o.jsxs("div",{style:{color:t.textSecondary,fontSize:13,marginTop:6,lineHeight:1.5,maxWidth:820},children:["Configure local AI providers and the project memory used by governed analytics chat. Secrets stay under ",o.jsx("code",{children:".dql/"})," and are never returned raw."]})]}),o.jsx($6,{configured:T,total:s.length||iS.length,t})]}),u&&o.jsx("div",{style:{marginTop:14,border:`1px solid ${t.headerBorder}`,borderRadius:8,padding:"10px 12px",fontSize:12,color:t.textSecondary,background:t.cellBg},children:u}),c?o.jsx("div",{style:{marginTop:24,color:t.textSecondary},children:"Loading settings..."}):o.jsxs(o.Fragment,{children:[o.jsxs("section",{style:{marginTop:22},children:[o.jsx(Yc,{title:"Provider Setup",detail:"Use env vars or save project-local provider settings.",t}),o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:14},children:iS.map(A=>{const R=s.find(S=>S.id===A);return R?o.jsx(H6,{provider:R,t,onSaved:S=>i(S),onStatus:E},A):null})})]}),o.jsxs("section",{style:{marginTop:22},children:[o.jsx(Yc,{title:"Local Agent Memory",detail:"Memory helps interpret business language but never overrides certified metadata.",t}),o.jsx(W6,{memories:a,t,onChange:l,onStatus:E})]}),o.jsxs("section",{style:{marginTop:22},children:[o.jsx(Yc,{title:"Environment Status",detail:"Runtime variables remain supported for Docker, CI, and shell-based setup.",t}),o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:14},children:n.map(A=>o.jsx(Y6,{group:A,t},A.id))})]})]})]})}function H6({provider:e,t,onSaved:n,onStatus:r}){const[s,i]=p.useState(e.enabled),[a,l]=p.useState(""),[c,d]=p.useState(e.baseUrl??""),[u,E]=p.useState(e.model??""),[f,T]=p.useState(!1);p.useEffect(()=>{i(e.enabled),d(e.baseUrl??""),E(e.model??""),l("")},[e.id,e.enabled,e.baseUrl,e.model]);const A=async()=>{T(!0);try{const S=await $.saveProviderSettings({id:e.id,enabled:s,apiKey:a||void 0,baseUrl:c,model:u});n(S.providers),r(`${e.label} settings saved.`)}catch(S){r(S instanceof Error?S.message:String(S))}finally{T(!1)}},R=async()=>{T(!0);try{const S=await $.testProviderSettings(e.id);r(S.message)}catch(S){r(S instanceof Error?S.message:String(S))}finally{T(!1)}};return o.jsxs("section",{style:{border:`1px solid ${t.headerBorder}`,borderRadius:8,background:t.cellBg,padding:14},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[o.jsxs("div",{style:{flex:1},children:[o.jsx("div",{style:{fontSize:14,fontWeight:700},children:e.label}),o.jsxs("div",{style:{fontSize:11,color:t.textSecondary,marginTop:3},children:[e.source==="local"?"Project local":e.source==="env"?"Environment":"Not configured",e.apiKeyPreview?` · ${e.apiKeyPreview}`:""]})]}),o.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:12,color:t.textSecondary},children:[o.jsx("input",{type:"checkbox",checked:s,onChange:S=>i(S.target.checked)}),"Enabled"]})]}),o.jsxs("div",{style:{display:"grid",gap:8,marginTop:12},children:[e.id!=="ollama"&&o.jsx("input",{value:a,onChange:S=>l(S.target.value),type:"password",placeholder:e.hasApiKey?"Leave blank to keep existing key":"API key",style:lr(t)}),(e.id==="openai"||e.id==="ollama"||e.id==="custom-openai")&&o.jsx("input",{value:c,onChange:S=>d(S.target.value),placeholder:e.id==="ollama"?"http://host.docker.internal:11434 or http://127.0.0.1:11434":"Base URL",style:lr(t)}),o.jsx("input",{value:u,onChange:S=>E(S.target.value),placeholder:"Default model",style:lr(t)})]}),o.jsxs("div",{style:{display:"flex",gap:8,marginTop:12},children:[o.jsx("button",{type:"button",onClick:A,disabled:f,style:ga(t,!0),children:"Save"}),o.jsx("button",{type:"button",onClick:R,disabled:f,style:ga(t,!1),children:"Test"})]}),e.envVars.length>0&&o.jsxs("div",{style:{marginTop:10,color:t.textSecondary,fontSize:11,lineHeight:1.4},children:["Env: ",e.envVars.join(", ")]})]})}function W6({memories:e,t,onChange:n,onStatus:r}){const[s,i]=p.useState("project"),[a,l]=p.useState(""),[c,d]=p.useState(""),[u,E]=p.useState(""),f=async()=>{const S=await $.listAgentMemory();n(S.memories)},T=async()=>{!a.trim()||!c.trim()||(await $.saveAgentMemory({scope:s,title:a,content:c,tags:u.split(",").map(S=>S.trim()).filter(Boolean),source:"settings-ui",confidence:.8,importance:s==="project"?.7:.5,enabled:!0}),l(""),d(""),E(""),await f(),r("Memory saved."))},A=async()=>{const S=await $.ensureAgentMemoryFiles();r(`Memory files ready: ${S.files.join(", ")}`)},R=async S=>{await $.deleteAgentMemory(S),await f(),r("Memory deleted.")};return o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:14},children:[o.jsxs("section",{style:{border:`1px solid ${t.headerBorder}`,borderRadius:8,background:t.cellBg,padding:14},children:[o.jsxs("div",{style:{display:"grid",gap:8},children:[o.jsxs("select",{value:s,onChange:S=>i(S.target.value),style:lr(t),children:[o.jsx("option",{value:"project",children:"Project context"}),o.jsx("option",{value:"user",children:"User preference"}),o.jsx("option",{value:"artifact",children:"Artifact note"}),o.jsx("option",{value:"notebook",children:"Notebook context"}),o.jsx("option",{value:"thread",children:"Thread summary"})]}),o.jsx("input",{value:a,onChange:S=>l(S.target.value),placeholder:"Memory title",style:lr(t)}),o.jsx("textarea",{value:c,onChange:S=>d(S.target.value),placeholder:"Business context, glossary term, rule, or analyst correction",rows:5,style:{...lr(t),resize:"vertical"}}),o.jsx("input",{value:u,onChange:S=>E(S.target.value),placeholder:"Tags, comma separated",style:lr(t)})]}),o.jsxs("div",{style:{display:"flex",gap:8,marginTop:12},children:[o.jsx("button",{type:"button",onClick:T,disabled:!a.trim()||!c.trim(),style:ga(t,!0),children:"Save Memory"}),o.jsx("button",{type:"button",onClick:A,style:ga(t,!1),children:"Create .dql/memory"})]})]}),o.jsx("section",{style:{border:`1px solid ${t.headerBorder}`,borderRadius:8,background:t.cellBg,overflow:"hidden"},children:e.length===0?o.jsx("div",{style:{padding:14,color:t.textSecondary,fontSize:12},children:"No local memory yet."}):e.slice(0,20).map(S=>o.jsxs("div",{style:{padding:12,borderBottom:`1px solid ${t.headerBorder}`},children:[o.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[o.jsx("span",{style:{fontSize:10,fontFamily:t.fontMono,color:t.accent,textTransform:"uppercase"},children:S.scope}),o.jsx("strong",{style:{fontSize:13},children:S.title}),o.jsx("button",{type:"button",onClick:()=>R(S.id),style:{marginLeft:"auto",border:0,background:"transparent",color:t.textMuted,cursor:"pointer"},children:"Delete"})]}),o.jsx("div",{style:{marginTop:6,fontSize:12,color:t.textSecondary,whiteSpace:"pre-wrap",lineHeight:1.45},children:S.content}),S.tags.length>0&&o.jsx("div",{style:{marginTop:6,fontSize:11,color:t.textMuted},children:S.tags.join(", ")})]},S.id))})]})}function Y6({group:e,t}){return o.jsxs("section",{style:{border:`1px solid ${t.headerBorder}`,borderRadius:8,background:t.cellBg,overflow:"hidden"},children:[o.jsxs("div",{style:{padding:"14px 14px 10px",borderBottom:`1px solid ${t.headerBorder}`},children:[o.jsx("div",{style:{fontSize:14,fontWeight:700},children:e.title}),o.jsx("div",{style:{color:t.textSecondary,fontSize:12,lineHeight:1.45,marginTop:4},children:e.description})]}),e.vars.map(n=>o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr auto",gap:10,padding:"11px 14px",borderBottom:`1px solid ${t.headerBorder}`},children:[o.jsxs("div",{style:{minWidth:0},children:[o.jsx("code",{style:{fontSize:12,color:t.textPrimary},children:n.key}),o.jsx("div",{style:{color:t.textSecondary,fontSize:12,lineHeight:1.4,marginTop:4},children:n.description})]}),o.jsx(V6,{present:n.present})]},n.key))]})}function Yc({title:e,detail:t,t:n}){return o.jsxs("div",{style:{marginBottom:10},children:[o.jsx("div",{style:{fontSize:14,fontWeight:700},children:e}),o.jsx("div",{style:{fontSize:12,color:n.textSecondary,marginTop:3},children:t})]})}function $6({configured:e,total:t,t:n}){return o.jsxs("div",{style:{border:`1px solid ${n.headerBorder}`,borderRadius:8,padding:"10px 12px",minWidth:132,textAlign:"right",background:n.cellBg},children:[o.jsxs("div",{style:{fontSize:20,fontWeight:700},children:[e,"/",t]}),o.jsx("div",{style:{fontSize:12,color:n.textSecondary},children:"providers ready"})]})}function V6({present:e}){return o.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 lr(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 ga(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}}const z6=380;function X6(){var g;const{state:e,dispatch:t}=Re(),n=ce[e.themeMode],r=e.lineageDrawerNodeId,[s,i]=p.useState({nodes:[],edges:[],focalNode:null}),[a,l]=p.useState(!1),c=p.useRef(null),[d,u]=p.useState(360);if(p.useEffect(()=>{const m=c.current;if(!m)return;const I=new ResizeObserver(O=>{for(const N of O){const x=Math.max(160,N.contentRect.height);u(x)}});return I.observe(m),()=>I.disconnect()},[]),p.useEffect(()=>{if(!r)return;let m=!1;return l(!0),$.queryLineage({focus:r,upstreamDepth:2,downstreamDepth:2}).then(I=>{var O,N;m||(i({nodes:((O=I.graph)==null?void 0:O.nodes)??[],edges:((N=I.graph)==null?void 0:N.edges)??[],focalNode:I.focalNode??null}),l(!1))}).catch(()=>{m||l(!1)}),()=>{m=!0}},[r]),!r)return null;const E=s.focalNode,f=E?s.edges.filter(m=>m.target===E.id).length:0,T=E?s.edges.filter(m=>m.source===E.id).length:0,A=E?ze[E.type]??n.textSecondary:n.textSecondary,R=E?Fa[E.type]??E.type.toUpperCase():"",S=m=>{m!==r&&t({type:"OPEN_LINEAGE_DRAWER",nodeId:m})},h=()=>{t({type:"SET_LINEAGE_FOCUS",nodeId:r}),t({type:"CLOSE_LINEAGE_DRAWER"}),e.lineageFullscreen||t({type:"TOGGLE_LINEAGE_FULLSCREEN"})};return o.jsxs("aside",{"aria-label":"Lineage drawer",style:{width:z6,flexShrink:0,borderLeft:`1px solid ${n.headerBorder}`,background:n.appBg,color:n.textPrimary,display:"flex",flexDirection:"column",overflow:"hidden",animation:"dql-drawer-slide-in 180ms cubic-bezier(0.22, 0.61, 0.36, 1)"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 14px",borderBottom:`1px solid ${n.headerBorder}`},children:[o.jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:38,padding:"2px 6px",background:A,color:n.appBg,fontSize:10,fontWeight:700,letterSpacing:"0.04em",borderRadius:4},title:E?Ga[E.type]??E.type:"",children:R||"NODE"}),o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsx("div",{style:{fontSize:13,fontWeight:600,color:n.textPrimary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:(E==null?void 0:E.name)??r,children:(E==null?void 0:E.name)??r}),o.jsxs("div",{style:{fontSize:11,color:n.textMuted,marginTop:2},children:["Lineage · ↑ ",f," · ↓ ",T]})]}),o.jsx(aS,{title:"Open full graph",onClick:h,t:n,children:o.jsx(gR,{size:14,strokeWidth:1.75})}),o.jsx(aS,{title:"Close",onClick:()=>t({type:"CLOSE_LINEAGE_DRAWER"}),t:n,children:o.jsx(du,{size:14,strokeWidth:2})})]}),o.jsx("div",{ref:c,style:{flex:1,minHeight:0,padding:12,overflow:"hidden",display:"flex"},children:a?o.jsx("div",{style:{color:n.textMuted,fontSize:12,padding:8},children:"Loading lineage…"}):s.nodes.length===0?o.jsx("div",{style:{color:n.textMuted,fontSize:12,padding:8},children:"No lineage available for this node."}):o.jsx("div",{style:{flex:1,minWidth:0},children:o.jsx(Vu,{nodes:s.nodes,edges:s.edges,focalNodeId:r,height:Math.max(0,d-24),onNodeClick:S,interactive:!0})})}),((g=E==null?void 0:E.metadata)==null?void 0:g.path)!=null&&typeof E.metadata.path=="string"&&o.jsxs("div",{style:{padding:"8px 14px",borderTop:`1px solid ${n.headerBorder}`,fontSize:11,color:n.textMuted,display:"flex",alignItems:"center",gap:6},children:[o.jsx(zL,{size:11,strokeWidth:1.75}),o.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:E.metadata.path,children:E.metadata.path})]})]})}function aS({title:e,onClick:t,children:n,t:r}){return o.jsx("button",{"aria-label":e,title:e,onClick:t,style:{width:26,height:26,display:"inline-flex",alignItems:"center",justifyContent:"center",background:"transparent",border:`1px solid ${r.headerBorder}`,borderRadius:5,color:r.textSecondary,cursor:"pointer"},onMouseEnter:s=>{s.currentTarget.style.color=r.textPrimary,s.currentTarget.style.background=r.textPrimary+"0f"},onMouseLeave:s=>{s.currentTarget.style.color=r.textSecondary,s.currentTarget.style.background="transparent"},children:n})}function K6(){const{state:e,dispatch:t}=Re(),{executeAll:n}=Ha();p.useEffect(()=>{const r=s=>{const i=s.metaKey||s.ctrlKey;if(i&&s.key==="b"&&!s.shiftKey){s.preventDefault(),t({type:"TOGGLE_SIDEBAR"});return}if(i&&s.shiftKey&&s.key==="Enter"){s.preventDefault(),e.activeFile&&n();return}if(i&&s.key==="j"&&!s.shiftKey){s.preventDefault(),t({type:"TOGGLE_DEV_PANEL"});return}if(i&&s.key==="d"&&!s.shiftKey){s.preventDefault(),e.activeFile&&t({type:"TOGGLE_DASHBOARD_MODE"});return}if(s.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 q6=600;function J6(e,t){const n=t.filter(r=>r.result||r.error||(r.executionCount??0)>0).map(r=>({cellId:r.id,status:r.status,result:r.result,error:r.error,executionCount:r.executionCount,executedAt:new Date().toISOString()}));return{version:1,notebookPath:e,capturedAt:new Date().toISOString(),cells:n}}function lS(e){return e.map(t=>{var n;return`${t.id}:${t.executionCount??0}:${((n=t.result)==null?void 0:n.rowCount)??-1}:${(t.error??"").length}`}).join("|")}function Q6(){var s;const{state:e}=Re(),t=p.useRef(null),n=p.useRef(""),r=p.useRef(null);p.useEffect(()=>{var l;const i=((l=e.activeFile)==null?void 0:l.path)??null;if(!i)return;if(i!==r.current){r.current=i,n.current=lS(e.cells);return}const a=lS(e.cells);return a!==n.current&&(n.current=a,t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{const c=J6(i,e.cells);$.saveRunSnapshot(i,c).catch(()=>{})},q6)),()=>{t.current&&(clearTimeout(t.current),t.current=null)}},[e.cells,(s=e.activeFile)==null?void 0:s.path])}function Z6(){const{state:e,dispatch:t}=Re(),n=ce[e.themeMode],r=p.useRef({}),[s,i]=p.useState(!1);K6(),Q6(),p.useEffect(()=>{const c=d=>{(d.metaKey||d.ctrlKey)&&d.key.toLowerCase()==="k"&&!d.shiftKey&&(d.preventDefault(),i(u=>!u)),(d.metaKey||d.ctrlKey)&&d.shiftKey&&d.key.toLowerCase()==="i"&&(d.preventDefault(),t({type:"TOGGLE_INSPECTOR"}))};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[t]);const a=p.useCallback(async c=>{try{if(c.type==="block"){const R=await $.openBlockStudio(c.path);t({type:"OPEN_BLOCK_STUDIO",file:c,payload:R});return}const{content:d}=await $.readNotebook(c.path),{title:u,cells:E,metadata:f}=PR(c.path,d),T=c.path.endsWith(".dqlnb")?await $.fetchRunSnapshot(c.path):null;let A=E;if(T!=null&&T.found&&T.snapshot){const R=new Map(T.snapshot.cells.map(S=>[S.cellId,S]));A=E.map(S=>{const h=R.get(S.id);return h?{...S,status:h.status??S.status,result:h.result??S.result,error:h.error??S.error,executionCount:h.executionCount??S.executionCount,fromSnapshot:h.result!=null}:S})}t({type:"OPEN_FILE",file:c,cells:A,title:u,metadata:f}),e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"})}catch(d){if(console.error("Failed to open file:",d),c.type==="block")try{const{content:u}=await $.readNotebook(c.path);t({type:"OPEN_BLOCK_STUDIO",file:c,payload:{path:c.path,source:u,companionPath:null,metadata:{name:c.name.replace(/\.dql$/i,""),path:c.path,domain:c.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(u){console.error("Failed to open block fallback:",u)}else t({type:"OPEN_FILE",file:c,cells:[ct("sql")],title:c.name})}},[t,e.sidebarPanel]);p.useCallback(c=>{const d=r.current[c];d&&d.scrollIntoView({behavior:"smooth",block:"start"})},[]);const l=p.useCallback((c,d)=>{d?r.current[c]=d:delete r.current[c]},[]);return o.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100vh",width:"100vw",background:n.appBg,fontFamily:n.font,color:n.textPrimary,overflow:"hidden"},children:[o.jsx(r1,{}),o.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[e.appMode==="studio"&&o.jsx(S0,{}),e.appMode==="studio"&&e.sidebarOpen&&o.jsx(Lb,{onOpenFile:a}),o.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:e.lineageFullscreen?o.jsx(EV,{}):e.mainView==="connection"?o.jsx(Li,{title:"Connections",description:"Manage database connections, edit driver settings, and test connectivity in a full-page workspace.",children:o.jsx(_R,{})}):e.mainView==="reference"?o.jsx(Li,{title:"Quick Reference",description:"Browse the complete DQL guide, semantic workflows, and authoring patterns in a documentation-style view.",children:o.jsx(bR,{themeMode:e.themeMode})}):e.mainView==="git"?o.jsx(SV,{}):e.mainView==="apps"?o.jsx(r6,{}):e.mainView==="review"?o.jsx(Li,{title:"Review",description:"Review Apps, AI pins, and draft DQL blocks before promoting them into trusted shared work.",children:o.jsx(B6,{})}):e.mainView==="settings"?o.jsx(Li,{title:"Settings",description:"Check local environment keys for AI chat, Slack, email schedules, and Docker/native runtime setup.",children:o.jsx(G6,{})}):o.jsx(o.Fragment,{children:e.mainView==="imports"||e.mainView==="block_studio"?o.jsx(w5,{},"block-editor"):o.jsxs(o.Fragment,{children:[o.jsx(O5,{onOpenFile:a,registerCellRef:l}),e.appMode==="studio"&&o.jsx(l1,{})]})})}),e.appMode==="studio"&&e.lineageDrawerOpen&&!e.lineageFullscreen&&!e.dashboardMode&&o.jsx(X6,{}),e.appMode==="studio"&&e.inspectorOpen&&!e.lineageFullscreen&&!e.lineageDrawerOpen&&!e.dashboardMode&&o.jsx(Q_,{})]}),e.newNotebookModalOpen&&o.jsx(_5,{onFileOpened:a}),e.newBlockModalOpen&&o.jsx(D5,{onFileOpened:a}),o.jsx(J_,{open:s,onClose:()=>i(!1)})]})}function Li({title:e,description:t,children:n}){return o.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",minWidth:0,overflow:"hidden"},children:[o.jsxs("div",{style:{padding:"18px 24px 12px",borderBottom:"1px solid rgba(127, 127, 127, 0.16)"},children:[o.jsx("div",{style:{fontSize:22,fontWeight:700},children:e}),o.jsx("div",{style:{fontSize:13,opacity:.72,marginTop:6,maxWidth:760,lineHeight:1.5},children:t})]}),o.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto"},children:n})]})}function e4(){const{state:e,dispatch:t}=Re(),n=p.useRef(null),r=p.useRef(null);p.useEffect(()=>{var s;n.current=((s=e.activeFile)==null?void 0:s.path)??null},[e.activeFile]),p.useEffect(()=>{if(typeof EventSource>"u")return;const s=()=>{const i=new EventSource(`${window.location.origin}/api/watch`);r.current=i,i.addEventListener("change",a=>{try{const l=JSON.parse(a.data);(l.type==="file-added"||l.type==="file-deleted")&&$.listNotebooks().then(c=>{t({type:"SET_FILES",files:c})}),l.type==="file-changed"&&$.listNotebooks().then(c=>{t({type:"SET_FILES",files:c})}),l.type==="semantic-reload"&&(t({type:"SET_SEMANTIC_LOADING",loading:!0}),$.getSemanticLayer().then(c=>{t({type:"SET_SEMANTIC_LAYER",layer:c})}))}catch{}}),i.addEventListener("error",()=>{i.close(),setTimeout(s,5e3)})};return s(),()=>{var i;(i=r.current)==null||i.close(),r.current=null}},[t])}function t4(){const{state:e,dispatch:t}=Re(),n=ce[e.themeMode];return p.useEffect(()=>{const r="dql-global-styles";let s=document.getElementById(r);s||(s=document.createElement("style"),s.id=r,document.head.appendChild(s)),s.textContent=`
|
|
845
|
+
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
846
|
+
body {
|
|
847
|
+
font-family: var(--font-ui, ${n.font});
|
|
848
|
+
overflow: hidden;
|
|
849
|
+
background: var(--color-bg-primary);
|
|
850
|
+
color: var(--color-text-primary);
|
|
851
|
+
}
|
|
852
|
+
::-webkit-scrollbar { width: 6px; height: 6px; }
|
|
853
|
+
::-webkit-scrollbar-track { background: transparent; }
|
|
854
|
+
::-webkit-scrollbar-thumb {
|
|
855
|
+
background: var(--color-border-secondary);
|
|
856
|
+
border-radius: 3px;
|
|
857
|
+
}
|
|
858
|
+
::-webkit-scrollbar-thumb:hover {
|
|
859
|
+
background: var(--color-text-tertiary);
|
|
860
|
+
}
|
|
861
|
+
::selection {
|
|
862
|
+
background: color-mix(in srgb, var(--color-accent-blue) 25%, transparent);
|
|
863
|
+
color: var(--color-text-primary);
|
|
864
|
+
}
|
|
865
|
+
.dql-meta-pill:hover {
|
|
866
|
+
background: var(--dql-pill-hover-bg) !important;
|
|
867
|
+
border-color: var(--dql-pill-hover-border) !important;
|
|
868
|
+
}
|
|
869
|
+
`},[n]),p.useEffect(()=>{const r=e.themeMode==="dark"||e.themeMode==="midnight"?"obsidian":e.themeMode==="light"?"paper":e.themeMode==="arctic"?"white":e.themeMode;document.documentElement.setAttribute("data-theme",r)},[e.themeMode]),p.useEffect(()=>{t({type:"SET_FILES_LOADING",loading:!0}),$.listNotebooks().then(r=>{t({type:"SET_FILES",files:r}),t({type:"SET_FILES_LOADING",loading:!1})})},[t]),p.useEffect(()=>{t({type:"SET_SCHEMA_LOADING",loading:!0}),$.getSchema().then(r=>{t({type:"SET_SCHEMA",tables:r}),t({type:"SET_SCHEMA_LOADING",loading:!1})})},[t]),e4(),o.jsx(KI,{theme:e.themeMode,applyGlobal:!0,children:o.jsx(ix,{delayDuration:200,skipDelayDuration:400,children:o.jsx(Z6,{})})})}function n4(){return o.jsx(AL,{children:o.jsx(t4,{})})}VI.createRoot(document.getElementById("root")).render(o.jsx(n4,{}));
|