@duckcodeailabs/dql-cli 1.3.2 → 1.3.5
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/assets/dql-notebook/assets/{codemirror-BqWuFwtC.js → codemirror-DJYUkPr1.js} +10 -10
- package/dist/assets/dql-notebook/assets/index-DrhoZmtv.css +1 -0
- package/dist/assets/dql-notebook/assets/index-t1D8YGzD.js +847 -0
- package/dist/assets/dql-notebook/index.html +5 -5
- package/dist/local-runtime.d.ts.map +1 -1
- package/dist/local-runtime.js +250 -4
- package/dist/local-runtime.js.map +1 -1
- package/package.json +8 -8
- package/dist/assets/dql-notebook/assets/index-BOO4KPgS.js +0 -793
- package/dist/assets/dql-notebook/assets/index-BlLkkJvL.css +0 -1
|
@@ -1,793 +0,0 @@
|
|
|
1
|
-
import{r as hi,a as iS,g as Ii}from"./react-CRB3T2We.js";import{S as Ni,g as aS,E as ct,s as Qh,a as Be,b as lS,c as Zh,P as eI,d as tI,e as nI,F as rI,f as oI,h as cS,V as sI,D as In,R as iI,i as aI,C as Qt,j as ES,k as qe,r as lI,l as cI,m as EI,u as dI,n as uI,t as TI,o as SI,p as fI,q as RI,v as AI,w as pI,x as hI,y as Qo,z as II,A as NI,B as OI,G as mI,H as CI,I as gI,J as LI,K as _I,L as xI,M as yI,N as DI,O as MI}from"./codemirror-BqWuFwtC.js";function PI(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const o in r)if(o!=="default"&&!(o in e)){const s=Object.getOwnPropertyDescriptor(r,o);s&&Object.defineProperty(e,o,s.get?s:{enumerable:!0,get:()=>r[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const a of s.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(o){if(o.ep)return;o.ep=!0;const s=n(o);fetch(o.href,s)}})();var Ra={exports:{}},Pr={};/**
|
|
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 yE;function bI(){if(yE)return Pr;yE=1;var e=hi(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function a(l,c,E){var d,u={},T=null,S=null;E!==void 0&&(T=""+E),c.key!==void 0&&(T=""+c.key),c.ref!==void 0&&(S=c.ref);for(d in c)r.call(c,d)&&!s.hasOwnProperty(d)&&(u[d]=c[d]);if(l&&l.defaultProps)for(d in c=l.defaultProps,c)u[d]===void 0&&(u[d]=c[d]);return{$$typeof:t,type:l,key:T,ref:S,props:u,_owner:o.current}}return Pr.Fragment=n,Pr.jsx=a,Pr.jsxs=a,Pr}var DE;function vI(){return DE||(DE=1,Ra.exports=bI()),Ra.exports}var i=vI(),Zo={},ME;function UI(){if(ME)return Zo;ME=1;var e=iS();return Zo.createRoot=e.createRoot,Zo.hydrateRoot=e.hydrateRoot,Zo}var wI=UI(),f=hi();const ge=Ii(f),dS=PI({__proto__:null,default:ge},[f]),Ae={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"},pe={1:"4px",2:"8px",3:"12px",4:"16px"},En={sm:"4px",md:"6px",lg:"8px"},Fe={xs:"11px",sm:"12px",md:"14px"},Sc={medium:"500",semibold:"600"},Xr={overlay:1e3,modal:1100,popover:1200,tooltip:1300},Aa={surfaceBase:Ae.gray1000,surfaceRaised:Ae.gray975,surfaceElevated:Ae.gray950,surfaceOverlay:"rgba(0,0,0,0.7)",surfaceHover:Ae.gray900,surfaceActive:"#1f2d3d",surfaceSunken:Ae.gray1000,borderSubtle:"#21262d",borderDefault:"#30363d",borderStrong:"#484f58",borderFocus:Ae.blue500,textPrimary:"#e6edf3",textSecondary:"#8b949e",textMuted:"#484f58",textDisabled:"#32383f",textInverse:Ae.gray1000,accent:Ae.blue500,accentHover:Ae.blue400,accentMuted:"rgba(56,139,253,0.15)",accentContrast:"#ffffff",success:Ae.green500,warning:Ae.yellow500,danger:Ae.red500,info:Ae.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)"},es={surfaceBase:Ae.gray0,surfaceRaised:Ae.gray50,surfaceElevated:Ae.gray0,surfaceOverlay:"rgba(0,0,0,0.4)",surfaceHover:Ae.gray100,surfaceActive:"#dbeafe",surfaceSunken:Ae.gray50,borderSubtle:Ae.gray100,borderDefault:Ae.gray200,borderStrong:Ae.gray300,borderFocus:Ae.blue600,textPrimary:"#1f2328",textSecondary:Ae.gray600,textMuted:Ae.gray400,textDisabled:Ae.gray300,textInverse:Ae.gray0,accent:Ae.blue600,accentHover:Ae.blue700,accentMuted:"rgba(9,105,218,0.12)",accentContrast:"#ffffff",success:Ae.green600,warning:Ae.yellow600,danger:Ae.red600,info:Ae.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)"},BI={obsidian:Aa,paper:es,white:es,dark:Aa,light:es,midnight:Aa,arctic:es};function uS(e){return`--dql-${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function PE(e){const t={};for(const[n,r]of Object.entries(e))t[uS(n)]=r;return t}function Se(e){return`var(${uS(e)})`}const FI=f.createContext(null);function GI({theme:e,defaultTheme:t="dark",onThemeChange:n,applyGlobal:r=!1,children:o}){const[s,a]=f.useState(t),l=e??s,c=BI[l],E=f.useCallback(T=>{e===void 0&&a(T),n==null||n(T)},[e,n]);f.useEffect(()=>{if(!r)return;const T=PE(c),S=document.documentElement;for(const[h,A]of Object.entries(T))S.style.setProperty(h,A);return S.setAttribute("data-theme",l),()=>{for(const h of Object.keys(T))S.style.removeProperty(h);S.removeAttribute("data-theme")}},[r,l,c]);const d=f.useMemo(()=>({theme:l,tokens:c,setTheme:E}),[l,c,E]),u=r?void 0:PE(c);return i.jsx(FI.Provider,{value:d,children:i.jsx("div",{"data-theme":l,style:u,children:o})})}function ce(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function bE(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Oi(...e){return t=>{let n=!1;const r=e.map(o=>{const s=bE(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():bE(e[o],null)}}}}function Le(...e){return f.useCallback(Oi(...e),e)}function HI(e,t){const n=f.createContext(t),r=s=>{const{children:a,...l}=s,c=f.useMemo(()=>l,Object.values(l));return i.jsx(n.Provider,{value:c,children:a})};r.displayName=e+"Provider";function o(s){const a=f.useContext(n);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function dn(e,t=[]){let n=[];function r(s,a){const l=f.createContext(a),c=n.length;n=[...n,a];const E=u=>{var p;const{scope:T,children:S,...h}=u,A=((p=T==null?void 0:T[e])==null?void 0:p[c])||l,R=f.useMemo(()=>h,Object.values(h));return i.jsx(A.Provider,{value:R,children:S})};E.displayName=s+"Provider";function d(u,T){var A;const S=((A=T==null?void 0:T[e])==null?void 0:A[c])||l,h=f.useContext(S);if(h)return h;if(a!==void 0)return a;throw new Error(`\`${u}\` must be used within \`${s}\``)}return[E,d]}const o=()=>{const s=n.map(a=>f.createContext(a));return function(l){const c=(l==null?void 0:l[e])||s;return f.useMemo(()=>({[`__scope${e}`]:{...l,[e]:c}}),[l,c])}};return o.scopeName=e,[r,kI(o,...t)]}function kI(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const a=r.reduce((l,{useScope:c,scopeName:E})=>{const u=c(s)[`__scope${E}`];return{...l,...u}},{});return f.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}var fc=iS();const jI=Ii(fc);function sr(e){const t=YI(e),n=f.forwardRef((r,o)=>{const{children:s,...a}=r,l=f.Children.toArray(s),c=l.find(VI);if(c){const E=c.props.children,d=l.map(u=>u===c?f.Children.count(E)>1?f.Children.only(null):f.isValidElement(E)?E.props.children:null:u);return i.jsx(t,{...a,ref:o,children:f.isValidElement(E)?f.cloneElement(E,void 0,d):null})}return i.jsx(t,{...a,ref:o,children:s})});return n.displayName=`${e}.Slot`,n}function YI(e){const t=f.forwardRef((n,r)=>{const{children:o,...s}=n;if(f.isValidElement(o)){const a=XI(o),l=$I(s,o.props);return o.type!==f.Fragment&&(l.ref=r?Oi(r,a):a),f.cloneElement(o,l)}return f.Children.count(o)>1?f.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var TS=Symbol("radix.slottable");function WI(e){const t=({children:n})=>i.jsx(i.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=TS,t}function VI(e){return f.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===TS}function $I(e,t){const n={...t};for(const r in t){const o=e[r],s=t[r];/^on[A-Z]/.test(r)?o&&s?n[r]=(...l)=>{const c=s(...l);return o(...l),c}:o&&(n[r]=o):r==="style"?n[r]={...o,...s}:r==="className"&&(n[r]=[o,s].filter(Boolean).join(" "))}return{...e,...n}}function XI(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var KI=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ne=KI.reduce((e,t)=>{const n=sr(`Primitive.${t}`),r=f.forwardRef((o,s)=>{const{asChild:a,...l}=o,c=a?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),i.jsx(c,{...l,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function SS(e,t){e&&fc.flushSync(()=>e.dispatchEvent(t))}function nn(e){const t=f.useRef(e);return f.useEffect(()=>{t.current=e}),f.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function zI(e,t=globalThis==null?void 0:globalThis.document){const n=nn(e);f.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var JI="DismissableLayer",Ml="dismissableLayer.update",qI="dismissableLayer.pointerDownOutside",QI="dismissableLayer.focusOutside",vE,fS=f.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),fo=f.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:a,onDismiss:l,...c}=e,E=f.useContext(fS),[d,u]=f.useState(null),T=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,S]=f.useState({}),h=Le(t,g=>u(g)),A=Array.from(E.layers),[R]=[...E.layersWithOutsidePointerEventsDisabled].slice(-1),p=A.indexOf(R),N=d?A.indexOf(d):-1,I=E.layersWithOutsidePointerEventsDisabled.size>0,O=N>=p,m=tN(g=>{const y=g.target,_=[...E.branches].some(P=>P.contains(y));!O||_||(o==null||o(g),a==null||a(g),g.defaultPrevented||l==null||l())},T),C=nN(g=>{const y=g.target;[...E.branches].some(P=>P.contains(y))||(s==null||s(g),a==null||a(g),g.defaultPrevented||l==null||l())},T);return zI(g=>{N===E.layers.size-1&&(r==null||r(g),!g.defaultPrevented&&l&&(g.preventDefault(),l()))},T),f.useEffect(()=>{if(d)return n&&(E.layersWithOutsidePointerEventsDisabled.size===0&&(vE=T.body.style.pointerEvents,T.body.style.pointerEvents="none"),E.layersWithOutsidePointerEventsDisabled.add(d)),E.layers.add(d),UE(),()=>{n&&E.layersWithOutsidePointerEventsDisabled.size===1&&(T.body.style.pointerEvents=vE)}},[d,T,n,E]),f.useEffect(()=>()=>{d&&(E.layers.delete(d),E.layersWithOutsidePointerEventsDisabled.delete(d),UE())},[d,E]),f.useEffect(()=>{const g=()=>S({});return document.addEventListener(Ml,g),()=>document.removeEventListener(Ml,g)},[]),i.jsx(Ne.div,{...c,ref:h,style:{pointerEvents:I?O?"auto":"none":void 0,...e.style},onFocusCapture:ce(e.onFocusCapture,C.onFocusCapture),onBlurCapture:ce(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:ce(e.onPointerDownCapture,m.onPointerDownCapture)})});fo.displayName=JI;var ZI="DismissableLayerBranch",eN=f.forwardRef((e,t)=>{const n=f.useContext(fS),r=f.useRef(null),o=Le(t,r);return f.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),i.jsx(Ne.div,{...e,ref:o})});eN.displayName=ZI;function tN(e,t=globalThis==null?void 0:globalThis.document){const n=nn(e),r=f.useRef(!1),o=f.useRef(()=>{});return f.useEffect(()=>{const s=l=>{if(l.target&&!r.current){let c=function(){RS(qI,n,E,{discrete:!0})};const E={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=c,t.addEventListener("click",o.current,{once:!0})):c()}else t.removeEventListener("click",o.current);r.current=!1},a=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(a),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function nN(e,t=globalThis==null?void 0:globalThis.document){const n=nn(e),r=f.useRef(!1);return f.useEffect(()=>{const o=s=>{s.target&&!r.current&&RS(QI,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function UE(){const e=new CustomEvent(Ml);document.dispatchEvent(e)}function RS(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?SS(o,s):o.dispatchEvent(s)}var rn=globalThis!=null&&globalThis.document?f.useLayoutEffect:()=>{},rN=dS[" useId ".trim().toString()]||(()=>{}),oN=0;function jr(e){const[t,n]=f.useState(rN());return rn(()=>{n(r=>r??String(oN++))},[e]),t?`radix-${t}`:""}const sN=["top","right","bottom","left"],on=Math.min,Xe=Math.max,Ys=Math.round,ts=Math.floor,Nt=e=>({x:e,y:e}),iN={left:"right",right:"left",bottom:"top",top:"bottom"};function Pl(e,t,n){return Xe(e,on(t,n))}function Ut(e,t){return typeof e=="function"?e(t):e}function wt(e){return e.split("-")[0]}function hr(e){return e.split("-")[1]}function Rc(e){return e==="x"?"y":"x"}function Ac(e){return e==="y"?"height":"width"}function ht(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function pc(e){return Rc(ht(e))}function aN(e,t,n){n===void 0&&(n=!1);const r=hr(e),o=pc(e),s=Ac(o);let a=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(a=Ws(a)),[a,Ws(a)]}function lN(e){const t=Ws(e);return[bl(e),t,bl(t)]}function bl(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const wE=["left","right"],BE=["right","left"],cN=["top","bottom"],EN=["bottom","top"];function dN(e,t,n){switch(e){case"top":case"bottom":return n?t?BE:wE:t?wE:BE;case"left":case"right":return t?cN:EN;default:return[]}}function uN(e,t,n,r){const o=hr(e);let s=dN(wt(e),n==="start",r);return o&&(s=s.map(a=>a+"-"+o),t&&(s=s.concat(s.map(bl)))),s}function Ws(e){const t=wt(e);return iN[t]+e.slice(t.length)}function TN(e){return{top:0,right:0,bottom:0,left:0,...e}}function AS(e){return typeof e!="number"?TN(e):{top:e,right:e,bottom:e,left:e}}function Vs(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function FE(e,t,n){let{reference:r,floating:o}=e;const s=ht(t),a=pc(t),l=Ac(a),c=wt(t),E=s==="y",d=r.x+r.width/2-o.width/2,u=r.y+r.height/2-o.height/2,T=r[l]/2-o[l]/2;let S;switch(c){case"top":S={x:d,y:r.y-o.height};break;case"bottom":S={x:d,y:r.y+r.height};break;case"right":S={x:r.x+r.width,y:u};break;case"left":S={x:r.x-o.width,y:u};break;default:S={x:r.x,y:r.y}}switch(hr(t)){case"start":S[a]-=T*(n&&E?-1:1);break;case"end":S[a]+=T*(n&&E?-1:1);break}return S}async function SN(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:a,elements:l,strategy:c}=e,{boundary:E="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:T=!1,padding:S=0}=Ut(t,e),h=AS(S),R=l[T?u==="floating"?"reference":"floating":u],p=Vs(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(R)))==null||n?R:R.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(l.floating)),boundary:E,rootBoundary:d,strategy:c})),N=u==="floating"?{x:r,y:o,width:a.floating.width,height:a.floating.height}:a.reference,I=await(s.getOffsetParent==null?void 0:s.getOffsetParent(l.floating)),O=await(s.isElement==null?void 0:s.isElement(I))?await(s.getScale==null?void 0:s.getScale(I))||{x:1,y:1}:{x:1,y:1},m=Vs(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:N,offsetParent:I,strategy:c}):N);return{top:(p.top-m.top+h.top)/O.y,bottom:(m.bottom-p.bottom+h.bottom)/O.y,left:(p.left-m.left+h.left)/O.x,right:(m.right-p.right+h.right)/O.x}}const fN=50,RN=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:a}=n,l=a.detectOverflow?a:{...a,detectOverflow:SN},c=await(a.isRTL==null?void 0:a.isRTL(t));let E=await a.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:u}=FE(E,r,c),T=r,S=0;const h={};for(let A=0;A<s.length;A++){const R=s[A];if(!R)continue;const{name:p,fn:N}=R,{x:I,y:O,data:m,reset:C}=await N({x:d,y:u,initialPlacement:r,placement:T,strategy:o,middlewareData:h,rects:E,platform:l,elements:{reference:e,floating:t}});d=I??d,u=O??u,h[p]={...h[p],...m},C&&S<fN&&(S++,typeof C=="object"&&(C.placement&&(T=C.placement),C.rects&&(E=C.rects===!0?await a.getElementRects({reference:e,floating:t,strategy:o}):C.rects),{x:d,y:u}=FE(E,T,c)),A=-1)}return{x:d,y:u,placement:T,strategy:o,middlewareData:h}},AN=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:a,elements:l,middlewareData:c}=t,{element:E,padding:d=0}=Ut(e,t)||{};if(E==null)return{};const u=AS(d),T={x:n,y:r},S=pc(o),h=Ac(S),A=await a.getDimensions(E),R=S==="y",p=R?"top":"left",N=R?"bottom":"right",I=R?"clientHeight":"clientWidth",O=s.reference[h]+s.reference[S]-T[S]-s.floating[h],m=T[S]-s.reference[S],C=await(a.getOffsetParent==null?void 0:a.getOffsetParent(E));let g=C?C[I]:0;(!g||!await(a.isElement==null?void 0:a.isElement(C)))&&(g=l.floating[I]||s.floating[h]);const y=O/2-m/2,_=g/2-A[h]/2-1,P=on(u[p],_),D=on(u[N],_),b=P,F=g-A[h]-D,x=g/2-A[h]/2+y,w=Pl(b,x,F),M=!c.arrow&&hr(o)!=null&&x!==w&&s.reference[h]/2-(x<b?P:D)-A[h]/2<0,B=M?x<b?x-b:x-F:0;return{[S]:T[S]+B,data:{[S]:w,centerOffset:x-w-B,...M&&{alignmentOffset:B}},reset:M}}}),pN=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:a,initialPlacement:l,platform:c,elements:E}=t,{mainAxis:d=!0,crossAxis:u=!0,fallbackPlacements:T,fallbackStrategy:S="bestFit",fallbackAxisSideDirection:h="none",flipAlignment:A=!0,...R}=Ut(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const p=wt(o),N=ht(l),I=wt(l)===l,O=await(c.isRTL==null?void 0:c.isRTL(E.floating)),m=T||(I||!A?[Ws(l)]:lN(l)),C=h!=="none";!T&&C&&m.push(...uN(l,A,h,O));const g=[l,...m],y=await c.detectOverflow(t,R),_=[];let P=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&_.push(y[p]),u){const x=aN(o,a,O);_.push(y[x[0]],y[x[1]])}if(P=[...P,{placement:o,overflows:_}],!_.every(x=>x<=0)){var D,b;const x=(((D=s.flip)==null?void 0:D.index)||0)+1,w=g[x];if(w&&(!(u==="alignment"?N!==ht(w):!1)||P.every(v=>ht(v.placement)===N?v.overflows[0]>0:!0)))return{data:{index:x,overflows:P},reset:{placement:w}};let M=(b=P.filter(B=>B.overflows[0]<=0).sort((B,v)=>B.overflows[1]-v.overflows[1])[0])==null?void 0:b.placement;if(!M)switch(S){case"bestFit":{var F;const B=(F=P.filter(v=>{if(C){const L=ht(v.placement);return L===N||L==="y"}return!0}).map(v=>[v.placement,v.overflows.filter(L=>L>0).reduce((L,U)=>L+U,0)]).sort((v,L)=>v[1]-L[1])[0])==null?void 0:F[0];B&&(M=B);break}case"initialPlacement":M=l;break}if(o!==M)return{reset:{placement:M}}}return{}}}};function GE(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function HE(e){return sN.some(t=>e[t]>=0)}const hN=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:o="referenceHidden",...s}=Ut(e,t);switch(o){case"referenceHidden":{const a=await r.detectOverflow(t,{...s,elementContext:"reference"}),l=GE(a,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:HE(l)}}}case"escaped":{const a=await r.detectOverflow(t,{...s,altBoundary:!0}),l=GE(a,n.floating);return{data:{escapedOffsets:l,escaped:HE(l)}}}default:return{}}}}},pS=new Set(["left","top"]);async function IN(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),a=wt(n),l=hr(n),c=ht(n)==="y",E=pS.has(a)?-1:1,d=s&&c?-1:1,u=Ut(t,e);let{mainAxis:T,crossAxis:S,alignmentAxis:h}=typeof u=="number"?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return l&&typeof h=="number"&&(S=l==="end"?h*-1:h),c?{x:S*d,y:T*E}:{x:T*E,y:S*d}}const NN=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:a,middlewareData:l}=t,c=await IN(t,e);return a===((n=l.offset)==null?void 0:n.placement)&&(r=l.arrow)!=null&&r.alignmentOffset?{}:{x:o+c.x,y:s+c.y,data:{...c,placement:a}}}}},ON=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o,platform:s}=t,{mainAxis:a=!0,crossAxis:l=!1,limiter:c={fn:p=>{let{x:N,y:I}=p;return{x:N,y:I}}},...E}=Ut(e,t),d={x:n,y:r},u=await s.detectOverflow(t,E),T=ht(wt(o)),S=Rc(T);let h=d[S],A=d[T];if(a){const p=S==="y"?"top":"left",N=S==="y"?"bottom":"right",I=h+u[p],O=h-u[N];h=Pl(I,h,O)}if(l){const p=T==="y"?"top":"left",N=T==="y"?"bottom":"right",I=A+u[p],O=A-u[N];A=Pl(I,A,O)}const R=c.fn({...t,[S]:h,[T]:A});return{...R,data:{x:R.x-n,y:R.y-r,enabled:{[S]:a,[T]:l}}}}}},mN=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:a}=t,{offset:l=0,mainAxis:c=!0,crossAxis:E=!0}=Ut(e,t),d={x:n,y:r},u=ht(o),T=Rc(u);let S=d[T],h=d[u];const A=Ut(l,t),R=typeof A=="number"?{mainAxis:A,crossAxis:0}:{mainAxis:0,crossAxis:0,...A};if(c){const I=T==="y"?"height":"width",O=s.reference[T]-s.floating[I]+R.mainAxis,m=s.reference[T]+s.reference[I]-R.mainAxis;S<O?S=O:S>m&&(S=m)}if(E){var p,N;const I=T==="y"?"width":"height",O=pS.has(wt(o)),m=s.reference[u]-s.floating[I]+(O&&((p=a.offset)==null?void 0:p[u])||0)+(O?0:R.crossAxis),C=s.reference[u]+s.reference[I]+(O?0:((N=a.offset)==null?void 0:N[u])||0)-(O?R.crossAxis:0);h<m?h=m:h>C&&(h=C)}return{[T]:S,[u]:h}}}},CN=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:s,platform:a,elements:l}=t,{apply:c=()=>{},...E}=Ut(e,t),d=await a.detectOverflow(t,E),u=wt(o),T=hr(o),S=ht(o)==="y",{width:h,height:A}=s.floating;let R,p;u==="top"||u==="bottom"?(R=u,p=T===(await(a.isRTL==null?void 0:a.isRTL(l.floating))?"start":"end")?"left":"right"):(p=u,R=T==="end"?"top":"bottom");const N=A-d.top-d.bottom,I=h-d.left-d.right,O=on(A-d[R],N),m=on(h-d[p],I),C=!t.middlewareData.shift;let g=O,y=m;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(y=I),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(g=N),C&&!T){const P=Xe(d.left,0),D=Xe(d.right,0),b=Xe(d.top,0),F=Xe(d.bottom,0);S?y=h-2*(P!==0||D!==0?P+D:Xe(d.left,d.right)):g=A-2*(b!==0||F!==0?b+F:Xe(d.top,d.bottom))}await c({...t,availableWidth:y,availableHeight:g});const _=await a.getDimensions(l.floating);return h!==_.width||A!==_.height?{reset:{rects:!0}}:{}}}};function mi(){return typeof window<"u"}function Ir(e){return hS(e)?(e.nodeName||"").toLowerCase():"#document"}function ze(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ct(e){var t;return(t=(hS(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function hS(e){return mi()?e instanceof Node||e instanceof ze(e).Node:!1}function Et(e){return mi()?e instanceof Element||e instanceof ze(e).Element:!1}function Gt(e){return mi()?e instanceof HTMLElement||e instanceof ze(e).HTMLElement:!1}function kE(e){return!mi()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof ze(e).ShadowRoot}function Ro(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=dt(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&o!=="inline"&&o!=="contents"}function gN(e){return/^(table|td|th)$/.test(Ir(e))}function Ci(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const LN=/transform|translate|scale|rotate|perspective|filter/,_N=/paint|layout|strict|content/,Rn=e=>!!e&&e!=="none";let pa;function hc(e){const t=Et(e)?dt(e):e;return Rn(t.transform)||Rn(t.translate)||Rn(t.scale)||Rn(t.rotate)||Rn(t.perspective)||!Ic()&&(Rn(t.backdropFilter)||Rn(t.filter))||LN.test(t.willChange||"")||_N.test(t.contain||"")}function xN(e){let t=sn(e);for(;Gt(t)&&!ir(t);){if(hc(t))return t;if(Ci(t))return null;t=sn(t)}return null}function Ic(){return pa==null&&(pa=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),pa}function ir(e){return/^(html|body|#document)$/.test(Ir(e))}function dt(e){return ze(e).getComputedStyle(e)}function gi(e){return Et(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function sn(e){if(Ir(e)==="html")return e;const t=e.assignedSlot||e.parentNode||kE(e)&&e.host||Ct(e);return kE(t)?t.host:t}function IS(e){const t=sn(e);return ir(t)?e.ownerDocument?e.ownerDocument.body:e.body:Gt(t)&&Ro(t)?t:IS(t)}function Kr(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=IS(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),a=ze(o);if(s){const l=vl(a);return t.concat(a,a.visualViewport||[],Ro(o)?o:[],l&&n?Kr(l):[])}else return t.concat(o,Kr(o,[],n))}function vl(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function NS(e){const t=dt(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Gt(e),s=o?e.offsetWidth:n,a=o?e.offsetHeight:r,l=Ys(n)!==s||Ys(r)!==a;return l&&(n=s,r=a),{width:n,height:r,$:l}}function Nc(e){return Et(e)?e:e.contextElement}function Zn(e){const t=Nc(e);if(!Gt(t))return Nt(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=NS(t);let a=(s?Ys(n.width):n.width)/r,l=(s?Ys(n.height):n.height)/o;return(!a||!Number.isFinite(a))&&(a=1),(!l||!Number.isFinite(l))&&(l=1),{x:a,y:l}}const yN=Nt(0);function OS(e){const t=ze(e);return!Ic()||!t.visualViewport?yN:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function DN(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==ze(e)?!1:t}function Cn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=Nc(e);let a=Nt(1);t&&(r?Et(r)&&(a=Zn(r)):a=Zn(e));const l=DN(s,n,r)?OS(s):Nt(0);let c=(o.left+l.x)/a.x,E=(o.top+l.y)/a.y,d=o.width/a.x,u=o.height/a.y;if(s){const T=ze(s),S=r&&Et(r)?ze(r):r;let h=T,A=vl(h);for(;A&&r&&S!==h;){const R=Zn(A),p=A.getBoundingClientRect(),N=dt(A),I=p.left+(A.clientLeft+parseFloat(N.paddingLeft))*R.x,O=p.top+(A.clientTop+parseFloat(N.paddingTop))*R.y;c*=R.x,E*=R.y,d*=R.x,u*=R.y,c+=I,E+=O,h=ze(A),A=vl(h)}}return Vs({width:d,height:u,x:c,y:E})}function Li(e,t){const n=gi(e).scrollLeft;return t?t.left+n:Cn(Ct(e)).left+n}function mS(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Li(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function MN(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",a=Ct(r),l=t?Ci(t.floating):!1;if(r===a||l&&s)return n;let c={scrollLeft:0,scrollTop:0},E=Nt(1);const d=Nt(0),u=Gt(r);if((u||!u&&!s)&&((Ir(r)!=="body"||Ro(a))&&(c=gi(r)),u)){const S=Cn(r);E=Zn(r),d.x=S.x+r.clientLeft,d.y=S.y+r.clientTop}const T=a&&!u&&!s?mS(a,c):Nt(0);return{width:n.width*E.x,height:n.height*E.y,x:n.x*E.x-c.scrollLeft*E.x+d.x+T.x,y:n.y*E.y-c.scrollTop*E.y+d.y+T.y}}function PN(e){return Array.from(e.getClientRects())}function bN(e){const t=Ct(e),n=gi(e),r=e.ownerDocument.body,o=Xe(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Xe(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let a=-n.scrollLeft+Li(e);const l=-n.scrollTop;return dt(r).direction==="rtl"&&(a+=Xe(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:a,y:l}}const jE=25;function vN(e,t){const n=ze(e),r=Ct(e),o=n.visualViewport;let s=r.clientWidth,a=r.clientHeight,l=0,c=0;if(o){s=o.width,a=o.height;const d=Ic();(!d||d&&t==="fixed")&&(l=o.offsetLeft,c=o.offsetTop)}const E=Li(r);if(E<=0){const d=r.ownerDocument,u=d.body,T=getComputedStyle(u),S=d.compatMode==="CSS1Compat"&&parseFloat(T.marginLeft)+parseFloat(T.marginRight)||0,h=Math.abs(r.clientWidth-u.clientWidth-S);h<=jE&&(s-=h)}else E<=jE&&(s+=E);return{width:s,height:a,x:l,y:c}}function UN(e,t){const n=Cn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=Gt(e)?Zn(e):Nt(1),a=e.clientWidth*s.x,l=e.clientHeight*s.y,c=o*s.x,E=r*s.y;return{width:a,height:l,x:c,y:E}}function YE(e,t,n){let r;if(t==="viewport")r=vN(e,n);else if(t==="document")r=bN(Ct(e));else if(Et(t))r=UN(t,n);else{const o=OS(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Vs(r)}function CS(e,t){const n=sn(e);return n===t||!Et(n)||ir(n)?!1:dt(n).position==="fixed"||CS(n,t)}function wN(e,t){const n=t.get(e);if(n)return n;let r=Kr(e,[],!1).filter(l=>Et(l)&&Ir(l)!=="body"),o=null;const s=dt(e).position==="fixed";let a=s?sn(e):e;for(;Et(a)&&!ir(a);){const l=dt(a),c=hc(a);!c&&l.position==="fixed"&&(o=null),(s?!c&&!o:!c&&l.position==="static"&&!!o&&(o.position==="absolute"||o.position==="fixed")||Ro(a)&&!c&&CS(e,a))?r=r.filter(d=>d!==a):o=l,a=sn(a)}return t.set(e,r),r}function BN(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const a=[...n==="clippingAncestors"?Ci(t)?[]:wN(t,this._c):[].concat(n),r],l=YE(t,a[0],o);let c=l.top,E=l.right,d=l.bottom,u=l.left;for(let T=1;T<a.length;T++){const S=YE(t,a[T],o);c=Xe(S.top,c),E=on(S.right,E),d=on(S.bottom,d),u=Xe(S.left,u)}return{width:E-u,height:d-c,x:u,y:c}}function FN(e){const{width:t,height:n}=NS(e);return{width:t,height:n}}function GN(e,t,n){const r=Gt(t),o=Ct(t),s=n==="fixed",a=Cn(e,!0,s,t);let l={scrollLeft:0,scrollTop:0};const c=Nt(0);function E(){c.x=Li(o)}if(r||!r&&!s)if((Ir(t)!=="body"||Ro(o))&&(l=gi(t)),r){const S=Cn(t,!0,s,t);c.x=S.x+t.clientLeft,c.y=S.y+t.clientTop}else o&&E();s&&!r&&o&&E();const d=o&&!r&&!s?mS(o,l):Nt(0),u=a.left+l.scrollLeft-c.x-d.x,T=a.top+l.scrollTop-c.y-d.y;return{x:u,y:T,width:a.width,height:a.height}}function ha(e){return dt(e).position==="static"}function WE(e,t){if(!Gt(e)||dt(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Ct(e)===n&&(n=n.ownerDocument.body),n}function gS(e,t){const n=ze(e);if(Ci(e))return n;if(!Gt(e)){let o=sn(e);for(;o&&!ir(o);){if(Et(o)&&!ha(o))return o;o=sn(o)}return n}let r=WE(e,t);for(;r&&gN(r)&&ha(r);)r=WE(r,t);return r&&ir(r)&&ha(r)&&!hc(r)?n:r||xN(e)||n}const HN=async function(e){const t=this.getOffsetParent||gS,n=this.getDimensions,r=await n(e.floating);return{reference:GN(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function kN(e){return dt(e).direction==="rtl"}const jN={convertOffsetParentRelativeRectToViewportRelativeRect:MN,getDocumentElement:Ct,getClippingRect:BN,getOffsetParent:gS,getElementRects:HN,getClientRects:PN,getDimensions:FN,getScale:Zn,isElement:Et,isRTL:kN};function LS(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function YN(e,t){let n=null,r;const o=Ct(e);function s(){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),s();const E=e.getBoundingClientRect(),{left:d,top:u,width:T,height:S}=E;if(l||t(),!T||!S)return;const h=ts(u),A=ts(o.clientWidth-(d+T)),R=ts(o.clientHeight-(u+S)),p=ts(d),I={rootMargin:-h+"px "+-A+"px "+-R+"px "+-p+"px",threshold:Xe(0,on(1,c))||1};let O=!0;function m(C){const g=C[0].intersectionRatio;if(g!==c){if(!O)return a();g?a(!1,g):r=setTimeout(()=>{a(!1,1e-7)},1e3)}g===1&&!LS(E,e.getBoundingClientRect())&&a(),O=!1}try{n=new IntersectionObserver(m,{...I,root:o.ownerDocument})}catch{n=new IntersectionObserver(m,I)}n.observe(e)}return a(!0),s}function WN(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:c=!1}=r,E=Nc(e),d=o||s?[...E?Kr(E):[],...t?Kr(t):[]]:[];d.forEach(p=>{o&&p.addEventListener("scroll",n,{passive:!0}),s&&p.addEventListener("resize",n)});const u=E&&l?YN(E,n):null;let T=-1,S=null;a&&(S=new ResizeObserver(p=>{let[N]=p;N&&N.target===E&&S&&t&&(S.unobserve(t),cancelAnimationFrame(T),T=requestAnimationFrame(()=>{var I;(I=S)==null||I.observe(t)})),n()}),E&&!c&&S.observe(E),t&&S.observe(t));let h,A=c?Cn(e):null;c&&R();function R(){const p=Cn(e);A&&!LS(A,p)&&n(),A=p,h=requestAnimationFrame(R)}return n(),()=>{var p;d.forEach(N=>{o&&N.removeEventListener("scroll",n),s&&N.removeEventListener("resize",n)}),u==null||u(),(p=S)==null||p.disconnect(),S=null,c&&cancelAnimationFrame(h)}}const VN=NN,$N=ON,XN=pN,KN=CN,zN=hN,VE=AN,JN=mN,qN=(e,t,n)=>{const r=new Map,o={platform:jN,...n},s={...o.platform,_c:r};return RN(e,t,{...o,platform:s})};var QN=typeof document<"u",ZN=function(){},xs=QN?f.useLayoutEffect:ZN;function $s(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!$s(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&e.$$typeof)&&!$s(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function _S(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function $E(e,t){const n=_S(e);return Math.round(t*n)/n}function Ia(e){const t=f.useRef(e);return xs(()=>{t.current=e}),t}function eO(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:a}={},transform:l=!0,whileElementsMounted:c,open:E}=e,[d,u]=f.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[T,S]=f.useState(r);$s(T,r)||S(r);const[h,A]=f.useState(null),[R,p]=f.useState(null),N=f.useCallback(v=>{v!==C.current&&(C.current=v,A(v))},[]),I=f.useCallback(v=>{v!==g.current&&(g.current=v,p(v))},[]),O=s||h,m=a||R,C=f.useRef(null),g=f.useRef(null),y=f.useRef(d),_=c!=null,P=Ia(c),D=Ia(o),b=Ia(E),F=f.useCallback(()=>{if(!C.current||!g.current)return;const v={placement:t,strategy:n,middleware:T};D.current&&(v.platform=D.current),qN(C.current,g.current,v).then(L=>{const U={...L,isPositioned:b.current!==!1};x.current&&!$s(y.current,U)&&(y.current=U,fc.flushSync(()=>{u(U)}))})},[T,t,n,D,b]);xs(()=>{E===!1&&y.current.isPositioned&&(y.current.isPositioned=!1,u(v=>({...v,isPositioned:!1})))},[E]);const x=f.useRef(!1);xs(()=>(x.current=!0,()=>{x.current=!1}),[]),xs(()=>{if(O&&(C.current=O),m&&(g.current=m),O&&m){if(P.current)return P.current(O,m,F);F()}},[O,m,F,P,_]);const w=f.useMemo(()=>({reference:C,floating:g,setReference:N,setFloating:I}),[N,I]),M=f.useMemo(()=>({reference:O,floating:m}),[O,m]),B=f.useMemo(()=>{const v={position:n,left:0,top:0};if(!M.floating)return v;const L=$E(M.floating,d.x),U=$E(M.floating,d.y);return l?{...v,transform:"translate("+L+"px, "+U+"px)",..._S(M.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:L,top:U}},[n,l,M.floating,d.x,d.y]);return f.useMemo(()=>({...d,update:F,refs:w,elements:M,floatingStyles:B}),[d,F,w,M,B])}const tO=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?VE({element:r.current,padding:o}).fn(n):{}:r?VE({element:r,padding:o}).fn(n):{}}}},nO=(e,t)=>{const n=VN(e);return{name:n.name,fn:n.fn,options:[e,t]}},rO=(e,t)=>{const n=$N(e);return{name:n.name,fn:n.fn,options:[e,t]}},oO=(e,t)=>({fn:JN(e).fn,options:[e,t]}),sO=(e,t)=>{const n=XN(e);return{name:n.name,fn:n.fn,options:[e,t]}},iO=(e,t)=>{const n=KN(e);return{name:n.name,fn:n.fn,options:[e,t]}},aO=(e,t)=>{const n=zN(e);return{name:n.name,fn:n.fn,options:[e,t]}},lO=(e,t)=>{const n=tO(e);return{name:n.name,fn:n.fn,options:[e,t]}};var cO="Arrow",xS=f.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return i.jsx(Ne.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:i.jsx("polygon",{points:"0,0 30,0 15,10"})})});xS.displayName=cO;var EO=xS;function dO(e){const[t,n]=f.useState(void 0);return rn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let a,l;if("borderBoxSize"in s){const c=s.borderBoxSize,E=Array.isArray(c)?c[0]:c;a=E.inlineSize,l=E.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 Oc="Popper",[yS,Nr]=dn(Oc),[uO,DS]=yS(Oc),MS=e=>{const{__scopePopper:t,children:n}=e,[r,o]=f.useState(null);return i.jsx(uO,{scope:t,anchor:r,onAnchorChange:o,children:n})};MS.displayName=Oc;var PS="PopperAnchor",bS=f.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=DS(PS,n),a=f.useRef(null),l=Le(t,a),c=f.useRef(null);return f.useEffect(()=>{const E=c.current;c.current=(r==null?void 0:r.current)||a.current,E!==c.current&&s.onAnchorChange(c.current)}),r?null:i.jsx(Ne.div,{...o,ref:l})});bS.displayName=PS;var mc="PopperContent",[TO,SO]=yS(mc),vS=f.forwardRef((e,t)=>{var q,X,Q,ae,ne,re;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:a=0,arrowPadding:l=0,avoidCollisions:c=!0,collisionBoundary:E=[],collisionPadding:d=0,sticky:u="partial",hideWhenDetached:T=!1,updatePositionStrategy:S="optimized",onPlaced:h,...A}=e,R=DS(mc,n),[p,N]=f.useState(null),I=Le(t,Y=>N(Y)),[O,m]=f.useState(null),C=dO(O),g=(C==null?void 0:C.width)??0,y=(C==null?void 0:C.height)??0,_=r+(s!=="center"?"-"+s:""),P=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},D=Array.isArray(E)?E:[E],b=D.length>0,F={padding:P,boundary:D.filter(RO),altBoundary:b},{refs:x,floatingStyles:w,placement:M,isPositioned:B,middlewareData:v}=eO({strategy:"fixed",placement:_,whileElementsMounted:(...Y)=>WN(...Y,{animationFrame:S==="always"}),elements:{reference:R.anchor},middleware:[nO({mainAxis:o+y,alignmentAxis:a}),c&&rO({mainAxis:!0,crossAxis:!1,limiter:u==="partial"?oO():void 0,...F}),c&&sO({...F}),iO({...F,apply:({elements:Y,rects:se,availableWidth:de,availableHeight:ue})=>{const{width:me,height:je}=se.reference,ve=Y.floating.style;ve.setProperty("--radix-popper-available-width",`${de}px`),ve.setProperty("--radix-popper-available-height",`${ue}px`),ve.setProperty("--radix-popper-anchor-width",`${me}px`),ve.setProperty("--radix-popper-anchor-height",`${je}px`)}}),O&&lO({element:O,padding:l}),AO({arrowWidth:g,arrowHeight:y}),T&&aO({strategy:"referenceHidden",...F})]}),[L,U]=BS(M),G=nn(h);rn(()=>{B&&(G==null||G())},[B,G]);const k=(q=v.arrow)==null?void 0:q.x,J=(X=v.arrow)==null?void 0:X.y,K=((Q=v.arrow)==null?void 0:Q.centerOffset)!==0,[$,z]=f.useState();return rn(()=>{p&&z(window.getComputedStyle(p).zIndex)},[p]),i.jsx("div",{ref:x.setFloating,"data-radix-popper-content-wrapper":"",style:{...w,transform:B?w.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:$,"--radix-popper-transform-origin":[(ae=v.transformOrigin)==null?void 0:ae.x,(ne=v.transformOrigin)==null?void 0:ne.y].join(" "),...((re=v.hide)==null?void 0:re.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:i.jsx(TO,{scope:n,placedSide:L,onArrowChange:m,arrowX:k,arrowY:J,shouldHideArrow:K,children:i.jsx(Ne.div,{"data-side":L,"data-align":U,...A,ref:I,style:{...A.style,animation:B?void 0:"none"}})})})});vS.displayName=mc;var US="PopperArrow",fO={top:"bottom",right:"left",bottom:"top",left:"right"},wS=f.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=SO(US,r),a=fO[s.placedSide];return i.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[a]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:i.jsx(EO,{...o,ref:n,style:{...o.style,display:"block"}})})});wS.displayName=US;function RO(e){return e!==null}var AO=e=>({name:"transformOrigin",options:e,fn(t){var R,p,N;const{placement:n,rects:r,middlewareData:o}=t,a=((R=o.arrow)==null?void 0:R.centerOffset)!==0,l=a?0:e.arrowWidth,c=a?0:e.arrowHeight,[E,d]=BS(n),u={start:"0%",center:"50%",end:"100%"}[d],T=(((p=o.arrow)==null?void 0:p.x)??0)+l/2,S=(((N=o.arrow)==null?void 0:N.y)??0)+c/2;let h="",A="";return E==="bottom"?(h=a?u:`${T}px`,A=`${-c}px`):E==="top"?(h=a?u:`${T}px`,A=`${r.floating.height+c}px`):E==="right"?(h=`${-c}px`,A=a?u:`${S}px`):E==="left"&&(h=`${r.floating.width+c}px`,A=a?u:`${S}px`),{data:{x:h,y:A}}}});function BS(e){const[t,n="center"]=e.split("-");return[t,n]}var pO=MS,_i=bS,Cc=vS,gc=wS,hO="Portal",Ao=f.forwardRef((e,t)=>{var l;const{container:n,...r}=e,[o,s]=f.useState(!1);rn(()=>s(!0),[]);const a=n||o&&((l=globalThis==null?void 0:globalThis.document)==null?void 0:l.body);return a?jI.createPortal(i.jsx(Ne.div,{...r,ref:t}),a):null});Ao.displayName=hO;function IO(e,t){return f.useReducer((n,r)=>t[n][r]??n,e)}var Ze=e=>{const{present:t,children:n}=e,r=NO(t),o=typeof n=="function"?n({present:r.isPresent}):f.Children.only(n),s=Le(r.ref,OO(o));return typeof n=="function"||r.isPresent?f.cloneElement(o,{ref:s}):null};Ze.displayName="Presence";function NO(e){const[t,n]=f.useState(),r=f.useRef(null),o=f.useRef(e),s=f.useRef("none"),a=e?"mounted":"unmounted",[l,c]=IO(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return f.useEffect(()=>{const E=ns(r.current);s.current=l==="mounted"?E:"none"},[l]),rn(()=>{const E=r.current,d=o.current;if(d!==e){const T=s.current,S=ns(E);e?c("MOUNT"):S==="none"||(E==null?void 0:E.display)==="none"?c("UNMOUNT"):c(d&&T!==S?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,c]),rn(()=>{if(t){let E;const d=t.ownerDocument.defaultView??window,u=S=>{const A=ns(r.current).includes(CSS.escape(S.animationName));if(S.target===t&&A&&(c("ANIMATION_END"),!o.current)){const R=t.style.animationFillMode;t.style.animationFillMode="forwards",E=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=R)})}},T=S=>{S.target===t&&(s.current=ns(r.current))};return t.addEventListener("animationstart",T),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{d.clearTimeout(E),t.removeEventListener("animationstart",T),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:f.useCallback(E=>{r.current=E?getComputedStyle(E):null,n(E)},[])}}function ns(e){return(e==null?void 0:e.animationName)||"none"}function OO(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var mO=dS[" useInsertionEffect ".trim().toString()]||rn;function Lc({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,a]=CO({defaultProp:t,onChange:n}),l=e!==void 0,c=l?e:o;{const d=f.useRef(e!==void 0);f.useEffect(()=>{const u=d.current;u!==l&&console.warn(`${r} is changing from ${u?"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.`),d.current=l},[l,r])}const E=f.useCallback(d=>{var u;if(l){const T=gO(d)?d(e):d;T!==e&&((u=a.current)==null||u.call(a,T))}else s(d)},[l,e,s,a]);return[c,E]}function CO({defaultProp:e,onChange:t}){const[n,r]=f.useState(e),o=f.useRef(n),s=f.useRef(t);return mO(()=>{s.current=t},[t]),f.useEffect(()=>{var a;o.current!==n&&((a=s.current)==null||a.call(s,n),o.current=n)},[n,o]),[n,r,s]}function gO(e){return typeof e=="function"}var LO=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"}),_O="VisuallyHidden",FS=f.forwardRef((e,t)=>i.jsx(Ne.span,{...e,ref:t,style:{...LO,...e.style}}));FS.displayName=_O;var xO=FS,[xi]=dn("Tooltip",[Nr]),yi=Nr(),GS="TooltipProvider",yO=700,Ul="tooltip.open",[DO,_c]=xi(GS),HS=e=>{const{__scopeTooltip:t,delayDuration:n=yO,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:s}=e,a=f.useRef(!0),l=f.useRef(!1),c=f.useRef(0);return f.useEffect(()=>{const E=c.current;return()=>window.clearTimeout(E)},[]),i.jsx(DO,{scope:t,isOpenDelayedRef:a,delayDuration:n,onOpen:f.useCallback(()=>{window.clearTimeout(c.current),a.current=!1},[]),onClose:f.useCallback(()=>{window.clearTimeout(c.current),c.current=window.setTimeout(()=>a.current=!0,r)},[r]),isPointerInTransitRef:l,onPointerInTransitChange:f.useCallback(E=>{l.current=E},[]),disableHoverableContent:o,children:s})};HS.displayName=GS;var zr="Tooltip",[MO,po]=xi(zr),kS=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o,onOpenChange:s,disableHoverableContent:a,delayDuration:l}=e,c=_c(zr,e.__scopeTooltip),E=yi(t),[d,u]=f.useState(null),T=jr(),S=f.useRef(0),h=a??c.disableHoverableContent,A=l??c.delayDuration,R=f.useRef(!1),[p,N]=Lc({prop:r,defaultProp:o??!1,onChange:g=>{g?(c.onOpen(),document.dispatchEvent(new CustomEvent(Ul))):c.onClose(),s==null||s(g)},caller:zr}),I=f.useMemo(()=>p?R.current?"delayed-open":"instant-open":"closed",[p]),O=f.useCallback(()=>{window.clearTimeout(S.current),S.current=0,R.current=!1,N(!0)},[N]),m=f.useCallback(()=>{window.clearTimeout(S.current),S.current=0,N(!1)},[N]),C=f.useCallback(()=>{window.clearTimeout(S.current),S.current=window.setTimeout(()=>{R.current=!0,N(!0),S.current=0},A)},[A,N]);return f.useEffect(()=>()=>{S.current&&(window.clearTimeout(S.current),S.current=0)},[]),i.jsx(pO,{...E,children:i.jsx(MO,{scope:t,contentId:T,open:p,stateAttribute:I,trigger:d,onTriggerChange:u,onTriggerEnter:f.useCallback(()=>{c.isOpenDelayedRef.current?C():O()},[c.isOpenDelayedRef,C,O]),onTriggerLeave:f.useCallback(()=>{h?m():(window.clearTimeout(S.current),S.current=0)},[m,h]),onOpen:O,onClose:m,disableHoverableContent:h,children:n})})};kS.displayName=zr;var wl="TooltipTrigger",jS=f.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=po(wl,n),s=_c(wl,n),a=yi(n),l=f.useRef(null),c=Le(t,l,o.onTriggerChange),E=f.useRef(!1),d=f.useRef(!1),u=f.useCallback(()=>E.current=!1,[]);return f.useEffect(()=>()=>document.removeEventListener("pointerup",u),[u]),i.jsx(_i,{asChild:!0,...a,children:i.jsx(Ne.button,{"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute,...r,ref:c,onPointerMove:ce(e.onPointerMove,T=>{T.pointerType!=="touch"&&!d.current&&!s.isPointerInTransitRef.current&&(o.onTriggerEnter(),d.current=!0)}),onPointerLeave:ce(e.onPointerLeave,()=>{o.onTriggerLeave(),d.current=!1}),onPointerDown:ce(e.onPointerDown,()=>{o.open&&o.onClose(),E.current=!0,document.addEventListener("pointerup",u,{once:!0})}),onFocus:ce(e.onFocus,()=>{E.current||o.onOpen()}),onBlur:ce(e.onBlur,o.onClose),onClick:ce(e.onClick,o.onClose)})})});jS.displayName=wl;var xc="TooltipPortal",[PO,bO]=xi(xc,{forceMount:void 0}),YS=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:o}=e,s=po(xc,t);return i.jsx(PO,{scope:t,forceMount:n,children:i.jsx(Ze,{present:n||s.open,children:i.jsx(Ao,{asChild:!0,container:o,children:r})})})};YS.displayName=xc;var ar="TooltipContent",WS=f.forwardRef((e,t)=>{const n=bO(ar,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...s}=e,a=po(ar,e.__scopeTooltip);return i.jsx(Ze,{present:r||a.open,children:a.disableHoverableContent?i.jsx(VS,{side:o,...s,ref:t}):i.jsx(vO,{side:o,...s,ref:t})})}),vO=f.forwardRef((e,t)=>{const n=po(ar,e.__scopeTooltip),r=_c(ar,e.__scopeTooltip),o=f.useRef(null),s=Le(t,o),[a,l]=f.useState(null),{trigger:c,onClose:E}=n,d=o.current,{onPointerInTransitChange:u}=r,T=f.useCallback(()=>{l(null),u(!1)},[u]),S=f.useCallback((h,A)=>{const R=h.currentTarget,p={x:h.clientX,y:h.clientY},N=GO(p,R.getBoundingClientRect()),I=HO(p,N),O=kO(A.getBoundingClientRect()),m=YO([...I,...O]);l(m),u(!0)},[u]);return f.useEffect(()=>()=>T(),[T]),f.useEffect(()=>{if(c&&d){const h=R=>S(R,d),A=R=>S(R,c);return c.addEventListener("pointerleave",h),d.addEventListener("pointerleave",A),()=>{c.removeEventListener("pointerleave",h),d.removeEventListener("pointerleave",A)}}},[c,d,S,T]),f.useEffect(()=>{if(a){const h=A=>{const R=A.target,p={x:A.clientX,y:A.clientY},N=(c==null?void 0:c.contains(R))||(d==null?void 0:d.contains(R)),I=!jO(p,a);N?T():I&&(T(),E())};return document.addEventListener("pointermove",h),()=>document.removeEventListener("pointermove",h)}},[c,d,a,E,T]),i.jsx(VS,{...e,ref:s})}),[UO,wO]=xi(zr,{isInside:!1}),BO=WI("TooltipContent"),VS=f.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:s,onPointerDownOutside:a,...l}=e,c=po(ar,n),E=yi(n),{onClose:d}=c;return f.useEffect(()=>(document.addEventListener(Ul,d),()=>document.removeEventListener(Ul,d)),[d]),f.useEffect(()=>{if(c.trigger){const u=T=>{const S=T.target;S!=null&&S.contains(c.trigger)&&d()};return window.addEventListener("scroll",u,{capture:!0}),()=>window.removeEventListener("scroll",u,{capture:!0})}},[c.trigger,d]),i.jsx(fo,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:a,onFocusOutside:u=>u.preventDefault(),onDismiss:d,children:i.jsxs(Cc,{"data-state":c.stateAttribute,...E,...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:[i.jsx(BO,{children:r}),i.jsx(UO,{scope:n,isInside:!0,children:i.jsx(xO,{id:c.contentId,role:"tooltip",children:o||r})})]})})});WS.displayName=ar;var $S="TooltipArrow",FO=f.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=yi(n);return wO($S,n).isInside?null:i.jsx(gc,{...o,...r,ref:t})});FO.displayName=$S;function GO(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),s=Math.abs(t.left-e.x);switch(Math.min(n,r,o,s)){case s:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function HO(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 kO(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function jO(e,t){const{x:n,y:r}=e;let o=!1;for(let s=0,a=t.length-1;s<t.length;a=s++){const l=t[s],c=t[a],E=l.x,d=l.y,u=c.x,T=c.y;d>r!=T>r&&n<(u-E)*(r-d)/(T-d)+E&&(o=!o)}return o}function YO(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),WO(t)}function WO(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const o=e[r];for(;t.length>=2;){const s=t[t.length-1],a=t[t.length-2];if((s.x-a.x)*(o.y-a.y)>=(s.y-a.y)*(o.x-a.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const s=n[n.length-1],a=n[n.length-2];if((s.x-a.x)*(o.y-a.y)>=(s.y-a.y)*(o.x-a.x))n.pop();else break}n.push(o)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var VO=HS,$O=kS,XO=jS,KO=YS,zO=WS;function XS({content:e,children:t,side:n="right",align:r="center",sideOffset:o=6,delayMs:s=200,container:a}){return i.jsxs($O,{delayDuration:s,children:[i.jsx(XO,{asChild:!0,children:t}),i.jsx(KO,{container:a,children:i.jsx(zO,{side:n,align:r,sideOffset:o,style:{background:Se("surfaceElevated"),color:Se("textPrimary"),border:`1px solid ${Se("borderDefault")}`,borderRadius:En.sm,padding:`${pe[1]} ${pe[2]}`,fontSize:Fe.sm,boxShadow:Se("shadowMd"),zIndex:Xr.tooltip,userSelect:"none"},children:e})})]})}const JO=VO;var Na="focusScope.autoFocusOnMount",Oa="focusScope.autoFocusOnUnmount",XE={bubbles:!1,cancelable:!0},qO="FocusScope",Di=f.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...a}=e,[l,c]=f.useState(null),E=nn(o),d=nn(s),u=f.useRef(null),T=Le(t,A=>c(A)),S=f.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;f.useEffect(()=>{if(r){let A=function(I){if(S.paused||!l)return;const O=I.target;l.contains(O)?u.current=O:Jt(u.current,{select:!0})},R=function(I){if(S.paused||!l)return;const O=I.relatedTarget;O!==null&&(l.contains(O)||Jt(u.current,{select:!0}))},p=function(I){if(document.activeElement===document.body)for(const m of I)m.removedNodes.length>0&&Jt(l)};document.addEventListener("focusin",A),document.addEventListener("focusout",R);const N=new MutationObserver(p);return l&&N.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",A),document.removeEventListener("focusout",R),N.disconnect()}}},[r,l,S.paused]),f.useEffect(()=>{if(l){zE.add(S);const A=document.activeElement;if(!l.contains(A)){const p=new CustomEvent(Na,XE);l.addEventListener(Na,E),l.dispatchEvent(p),p.defaultPrevented||(QO(rm(KS(l)),{select:!0}),document.activeElement===A&&Jt(l))}return()=>{l.removeEventListener(Na,E),setTimeout(()=>{const p=new CustomEvent(Oa,XE);l.addEventListener(Oa,d),l.dispatchEvent(p),p.defaultPrevented||Jt(A??document.body,{select:!0}),l.removeEventListener(Oa,d),zE.remove(S)},0)}}},[l,E,d,S]);const h=f.useCallback(A=>{if(!n&&!r||S.paused)return;const R=A.key==="Tab"&&!A.altKey&&!A.ctrlKey&&!A.metaKey,p=document.activeElement;if(R&&p){const N=A.currentTarget,[I,O]=ZO(N);I&&O?!A.shiftKey&&p===O?(A.preventDefault(),n&&Jt(I,{select:!0})):A.shiftKey&&p===I&&(A.preventDefault(),n&&Jt(O,{select:!0})):p===N&&A.preventDefault()}},[n,r,S.paused]);return i.jsx(Ne.div,{tabIndex:-1,...a,ref:T,onKeyDown:h})});Di.displayName=qO;function QO(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Jt(r,{select:t}),document.activeElement!==n)return}function ZO(e){const t=KS(e),n=KE(t,e),r=KE(t.reverse(),e);return[n,r]}function KS(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function KE(e,t){for(const n of e)if(!em(n,{upTo:t}))return n}function em(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 tm(e){return e instanceof HTMLInputElement&&"select"in e}function Jt(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&tm(e)&&t&&e.select()}}var zE=nm();function nm(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=JE(e,t),e.unshift(t)},remove(t){var n;e=JE(e,t),(n=e[0])==null||n.resume()}}}function JE(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function rm(e){return e.filter(t=>t.tagName!=="A")}var ma=0;function yc(){f.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??qE()),document.body.insertAdjacentElement("beforeend",e[1]??qE()),ma++,()=>{ma===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),ma--}},[])}function qE(){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 pt=function(){return pt=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},pt.apply(this,arguments)};function zS(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function om(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}var ys="right-scroll-bar-position",Ds="width-before-scroll-bar",sm="with-scroll-bars-hidden",im="--removed-body-scroll-bar-size";function Ca(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function am(e,t){var n=f.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var lm=typeof window<"u"?f.useLayoutEffect:f.useEffect,QE=new WeakMap;function cm(e,t){var n=am(null,function(r){return e.forEach(function(o){return Ca(o,r)})});return lm(function(){var r=QE.get(n);if(r){var o=new Set(r),s=new Set(e),a=n.current;o.forEach(function(l){s.has(l)||Ca(l,null)}),s.forEach(function(l){o.has(l)||Ca(l,a)})}QE.set(n,e)},[e]),n}function Em(e){return e}function dm(e,t){t===void 0&&(t=Em);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(s){var a=t(s,r);return n.push(a),function(){n=n.filter(function(l){return l!==a})}},assignSyncMedium:function(s){for(r=!0;n.length;){var a=n;n=[],a.forEach(s)}n={push:function(l){return s(l)},filter:function(){return n}}},assignMedium:function(s){r=!0;var a=[];if(n.length){var l=n;n=[],l.forEach(s),a=n}var c=function(){var d=a;a=[],d.forEach(s)},E=function(){return Promise.resolve().then(c)};E(),n={push:function(d){a.push(d),E()},filter:function(d){return a=a.filter(d),n}}}};return o}function um(e){e===void 0&&(e={});var t=dm(null);return t.options=pt({async:!0,ssr:!1},e),t}var JS=function(e){var t=e.sideCar,n=zS(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 f.createElement(r,pt({},n))};JS.isSideCarExport=!0;function Tm(e,t){return e.useMedium(t),JS}var qS=um(),ga=function(){},Mi=f.forwardRef(function(e,t){var n=f.useRef(null),r=f.useState({onScrollCapture:ga,onWheelCapture:ga,onTouchMoveCapture:ga}),o=r[0],s=r[1],a=e.forwardProps,l=e.children,c=e.className,E=e.removeScrollBar,d=e.enabled,u=e.shards,T=e.sideCar,S=e.noRelative,h=e.noIsolation,A=e.inert,R=e.allowPinchZoom,p=e.as,N=p===void 0?"div":p,I=e.gapMode,O=zS(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),m=T,C=cm([n,t]),g=pt(pt({},O),o);return f.createElement(f.Fragment,null,d&&f.createElement(m,{sideCar:qS,removeScrollBar:E,shards:u,noRelative:S,noIsolation:h,inert:A,setCallbacks:s,allowPinchZoom:!!R,lockRef:n,gapMode:I}),a?f.cloneElement(f.Children.only(l),pt(pt({},g),{ref:C})):f.createElement(N,pt({},g,{className:c,ref:C}),l))});Mi.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Mi.classNames={fullWidth:Ds,zeroRight:ys};var Sm=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function fm(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Sm();return t&&e.setAttribute("nonce",t),e}function Rm(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Am(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var pm=function(){var e=0,t=null;return{add:function(n){e==0&&(t=fm())&&(Rm(t,n),Am(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},hm=function(){var e=pm();return function(t,n){f.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},QS=function(){var e=hm(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Im={left:0,top:0,right:0,gap:0},La=function(e){return parseInt(e||"",10)||0},Nm=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[La(n),La(r),La(o)]},Om=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Im;var t=Nm(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])}},mm=QS(),er="data-scroll-locked",Cm=function(e,t,n,r){var o=e.left,s=e.top,a=e.right,l=e.gap;return n===void 0&&(n="margin"),`
|
|
10
|
-
.`.concat(sm,` {
|
|
11
|
-
overflow: hidden `).concat(r,`;
|
|
12
|
-
padding-right: `).concat(l,"px ").concat(r,`;
|
|
13
|
-
}
|
|
14
|
-
body[`).concat(er,`] {
|
|
15
|
-
overflow: hidden `).concat(r,`;
|
|
16
|
-
overscroll-behavior: contain;
|
|
17
|
-
`).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&`
|
|
18
|
-
padding-left: `.concat(o,`px;
|
|
19
|
-
padding-top: `).concat(s,`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(ys,` {
|
|
28
|
-
right: `).concat(l,"px ").concat(r,`;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
.`).concat(Ds,` {
|
|
32
|
-
margin-right: `).concat(l,"px ").concat(r,`;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
.`).concat(ys," .").concat(ys,` {
|
|
36
|
-
right: 0 `).concat(r,`;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
.`).concat(Ds," .").concat(Ds,` {
|
|
40
|
-
margin-right: 0 `).concat(r,`;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
body[`).concat(er,`] {
|
|
44
|
-
`).concat(im,": ").concat(l,`px;
|
|
45
|
-
}
|
|
46
|
-
`)},ZE=function(){var e=parseInt(document.body.getAttribute(er)||"0",10);return isFinite(e)?e:0},gm=function(){f.useEffect(function(){return document.body.setAttribute(er,(ZE()+1).toString()),function(){var e=ZE()-1;e<=0?document.body.removeAttribute(er):document.body.setAttribute(er,e.toString())}},[])},Lm=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r;gm();var s=f.useMemo(function(){return Om(o)},[o]);return f.createElement(mm,{styles:Cm(s,!t,o,n?"":"!important")})},Bl=!1;if(typeof window<"u")try{var rs=Object.defineProperty({},"passive",{get:function(){return Bl=!0,!0}});window.addEventListener("test",rs,rs),window.removeEventListener("test",rs,rs)}catch{Bl=!1}var kn=Bl?{passive:!1}:!1,_m=function(e){return e.tagName==="TEXTAREA"},ZS=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!_m(e)&&n[t]==="visible")},xm=function(e){return ZS(e,"overflowY")},ym=function(e){return ZS(e,"overflowX")},ed=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=ef(e,r);if(o){var s=tf(e,r),a=s[1],l=s[2];if(a>l)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Dm=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},Mm=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},ef=function(e,t){return e==="v"?xm(t):ym(t)},tf=function(e,t){return e==="v"?Dm(t):Mm(t)},Pm=function(e,t){return e==="h"&&t==="rtl"?-1:1},bm=function(e,t,n,r,o){var s=Pm(e,window.getComputedStyle(t).direction),a=s*r,l=n.target,c=t.contains(l),E=!1,d=a>0,u=0,T=0;do{if(!l)break;var S=tf(e,l),h=S[0],A=S[1],R=S[2],p=A-R-s*h;(h||p)&&ef(e,l)&&(u+=p,T+=h);var N=l.parentNode;l=N&&N.nodeType===Node.DOCUMENT_FRAGMENT_NODE?N.host:N}while(!c&&l!==document.body||c&&(t.contains(l)||t===l));return(d&&Math.abs(u)<1||!d&&Math.abs(T)<1)&&(E=!0),E},os=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},td=function(e){return[e.deltaX,e.deltaY]},nd=function(e){return e&&"current"in e?e.current:e},vm=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Um=function(e){return`
|
|
47
|
-
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
48
|
-
.allow-interactivity-`).concat(e,` {pointer-events: all;}
|
|
49
|
-
`)},wm=0,jn=[];function Bm(e){var t=f.useRef([]),n=f.useRef([0,0]),r=f.useRef(),o=f.useState(wm++)[0],s=f.useState(QS)[0],a=f.useRef(e);f.useEffect(function(){a.current=e},[e]),f.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var A=om([e.lockRef.current],(e.shards||[]).map(nd),!0).filter(Boolean);return A.forEach(function(R){return R.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),A.forEach(function(R){return R.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=f.useCallback(function(A,R){if("touches"in A&&A.touches.length===2||A.type==="wheel"&&A.ctrlKey)return!a.current.allowPinchZoom;var p=os(A),N=n.current,I="deltaX"in A?A.deltaX:N[0]-p[0],O="deltaY"in A?A.deltaY:N[1]-p[1],m,C=A.target,g=Math.abs(I)>Math.abs(O)?"h":"v";if("touches"in A&&g==="h"&&C.type==="range")return!1;var y=window.getSelection(),_=y&&y.anchorNode,P=_?_===C||_.contains(C):!1;if(P)return!1;var D=ed(g,C);if(!D)return!0;if(D?m=g:(m=g==="v"?"h":"v",D=ed(g,C)),!D)return!1;if(!r.current&&"changedTouches"in A&&(I||O)&&(r.current=m),!m)return!0;var b=r.current||m;return bm(b,R,A,b==="h"?I:O)},[]),c=f.useCallback(function(A){var R=A;if(!(!jn.length||jn[jn.length-1]!==s)){var p="deltaY"in R?td(R):os(R),N=t.current.filter(function(m){return m.name===R.type&&(m.target===R.target||R.target===m.shadowParent)&&vm(m.delta,p)})[0];if(N&&N.should){R.cancelable&&R.preventDefault();return}if(!N){var I=(a.current.shards||[]).map(nd).filter(Boolean).filter(function(m){return m.contains(R.target)}),O=I.length>0?l(R,I[0]):!a.current.noIsolation;O&&R.cancelable&&R.preventDefault()}}},[]),E=f.useCallback(function(A,R,p,N){var I={name:A,delta:R,target:p,should:N,shadowParent:Fm(p)};t.current.push(I),setTimeout(function(){t.current=t.current.filter(function(O){return O!==I})},1)},[]),d=f.useCallback(function(A){n.current=os(A),r.current=void 0},[]),u=f.useCallback(function(A){E(A.type,td(A),A.target,l(A,e.lockRef.current))},[]),T=f.useCallback(function(A){E(A.type,os(A),A.target,l(A,e.lockRef.current))},[]);f.useEffect(function(){return jn.push(s),e.setCallbacks({onScrollCapture:u,onWheelCapture:u,onTouchMoveCapture:T}),document.addEventListener("wheel",c,kn),document.addEventListener("touchmove",c,kn),document.addEventListener("touchstart",d,kn),function(){jn=jn.filter(function(A){return A!==s}),document.removeEventListener("wheel",c,kn),document.removeEventListener("touchmove",c,kn),document.removeEventListener("touchstart",d,kn)}},[]);var S=e.removeScrollBar,h=e.inert;return f.createElement(f.Fragment,null,h?f.createElement(s,{styles:Um(o)}):null,S?f.createElement(Lm,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Fm(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Gm=Tm(qS,Bm);var Pi=f.forwardRef(function(e,t){return f.createElement(Mi,pt({},e,{ref:t,sideCar:Gm}))});Pi.classNames=Mi.classNames;var Hm=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Yn=new WeakMap,ss=new WeakMap,is={},_a=0,nf=function(e){return e&&(e.host||nf(e.parentNode))},km=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=nf(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})},jm=function(e,t,n,r){var o=km(t,Array.isArray(e)?e:[e]);is[n]||(is[n]=new WeakMap);var s=is[n],a=[],l=new Set,c=new Set(o),E=function(u){!u||l.has(u)||(l.add(u),E(u.parentNode))};o.forEach(E);var d=function(u){!u||c.has(u)||Array.prototype.forEach.call(u.children,function(T){if(l.has(T))d(T);else try{var S=T.getAttribute(r),h=S!==null&&S!=="false",A=(Yn.get(T)||0)+1,R=(s.get(T)||0)+1;Yn.set(T,A),s.set(T,R),a.push(T),A===1&&h&&ss.set(T,!0),R===1&&T.setAttribute(n,"true"),h||T.setAttribute(r,"true")}catch(p){console.error("aria-hidden: cannot operate on ",T,p)}})};return d(t),l.clear(),_a++,function(){a.forEach(function(u){var T=Yn.get(u)-1,S=s.get(u)-1;Yn.set(u,T),s.set(u,S),T||(ss.has(u)||u.removeAttribute(r),ss.delete(u)),S||u.removeAttribute(n)}),_a--,_a||(Yn=new WeakMap,Yn=new WeakMap,ss=new WeakMap,is={})}},Dc=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=Hm(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),jm(r,o,n,"aria-hidden")):function(){return null}},bi="Dialog",[rf]=dn(bi),[Ym,ut]=rf(bi),of=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:s,modal:a=!0}=e,l=f.useRef(null),c=f.useRef(null),[E,d]=Lc({prop:r,defaultProp:o??!1,onChange:s,caller:bi});return i.jsx(Ym,{scope:t,triggerRef:l,contentRef:c,contentId:jr(),titleId:jr(),descriptionId:jr(),open:E,onOpenChange:d,onOpenToggle:f.useCallback(()=>d(u=>!u),[d]),modal:a,children:n})};of.displayName=bi;var sf="DialogTrigger",Wm=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ut(sf,n),s=Le(t,o.triggerRef);return i.jsx(Ne.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":bc(o.open),...r,ref:s,onClick:ce(e.onClick,o.onOpenToggle)})});Wm.displayName=sf;var Mc="DialogPortal",[Vm,af]=rf(Mc,{forceMount:void 0}),lf=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,s=ut(Mc,t);return i.jsx(Vm,{scope:t,forceMount:n,children:f.Children.map(r,a=>i.jsx(Ze,{present:n||s.open,children:i.jsx(Ao,{asChild:!0,container:o,children:a})}))})};lf.displayName=Mc;var Xs="DialogOverlay",cf=f.forwardRef((e,t)=>{const n=af(Xs,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=ut(Xs,e.__scopeDialog);return s.modal?i.jsx(Ze,{present:r||s.open,children:i.jsx(Xm,{...o,ref:t})}):null});cf.displayName=Xs;var $m=sr("DialogOverlay.RemoveScroll"),Xm=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ut(Xs,n);return i.jsx(Pi,{as:$m,allowPinchZoom:!0,shards:[o.contentRef],children:i.jsx(Ne.div,{"data-state":bc(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),gn="DialogContent",Ef=f.forwardRef((e,t)=>{const n=af(gn,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=ut(gn,e.__scopeDialog);return i.jsx(Ze,{present:r||s.open,children:s.modal?i.jsx(Km,{...o,ref:t}):i.jsx(zm,{...o,ref:t})})});Ef.displayName=gn;var Km=f.forwardRef((e,t)=>{const n=ut(gn,e.__scopeDialog),r=f.useRef(null),o=Le(t,n.contentRef,r);return f.useEffect(()=>{const s=r.current;if(s)return Dc(s)},[]),i.jsx(df,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ce(e.onCloseAutoFocus,s=>{var a;s.preventDefault(),(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:ce(e.onPointerDownOutside,s=>{const a=s.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0;(a.button===2||l)&&s.preventDefault()}),onFocusOutside:ce(e.onFocusOutside,s=>s.preventDefault())})}),zm=f.forwardRef((e,t)=>{const n=ut(gn,e.__scopeDialog),r=f.useRef(!1),o=f.useRef(!1);return i.jsx(df,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var a,l;(a=e.onCloseAutoFocus)==null||a.call(e,s),s.defaultPrevented||(r.current||(l=n.triggerRef.current)==null||l.focus(),s.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:s=>{var c,E;(c=e.onInteractOutside)==null||c.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const a=s.target;((E=n.triggerRef.current)==null?void 0:E.contains(a))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),df=f.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:s,...a}=e,l=ut(gn,n),c=f.useRef(null),E=Le(t,c);return yc(),i.jsxs(i.Fragment,{children:[i.jsx(Di,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:s,children:i.jsx(fo,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":bc(l.open),...a,ref:E,onDismiss:()=>l.onOpenChange(!1)})}),i.jsxs(i.Fragment,{children:[i.jsx(Qm,{titleId:l.titleId}),i.jsx(eC,{contentRef:c,descriptionId:l.descriptionId})]})]})}),Pc="DialogTitle",uf=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ut(Pc,n);return i.jsx(Ne.h2,{id:o.titleId,...r,ref:t})});uf.displayName=Pc;var Tf="DialogDescription",Jm=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ut(Tf,n);return i.jsx(Ne.p,{id:o.descriptionId,...r,ref:t})});Jm.displayName=Tf;var Sf="DialogClose",qm=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ut(Sf,n);return i.jsx(Ne.button,{type:"button",...r,ref:t,onClick:ce(e.onClick,()=>o.onOpenChange(!1))})});qm.displayName=Sf;function bc(e){return e?"open":"closed"}var ff="DialogTitleWarning",[nW,Rf]=HI(ff,{contentName:gn,titleName:Pc,docsSlug:"dialog"}),Qm=({titleId:e})=>{const t=Rf(ff),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 f.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},Zm="DialogDescriptionWarning",eC=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Rf(Zm).contentName}}.`;return f.useEffect(()=>{var s;const o=(s=e.current)==null?void 0:s.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},tC=of,nC=lf,rC=cf,oC=Ef,sC=uf;function Af(e){const t=e+"CollectionProvider",[n,r]=dn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),a=A=>{const{scope:R,children:p}=A,N=ge.useRef(null),I=ge.useRef(new Map).current;return i.jsx(o,{scope:R,itemMap:I,collectionRef:N,children:p})};a.displayName=t;const l=e+"CollectionSlot",c=sr(l),E=ge.forwardRef((A,R)=>{const{scope:p,children:N}=A,I=s(l,p),O=Le(R,I.collectionRef);return i.jsx(c,{ref:O,children:N})});E.displayName=l;const d=e+"CollectionItemSlot",u="data-radix-collection-item",T=sr(d),S=ge.forwardRef((A,R)=>{const{scope:p,children:N,...I}=A,O=ge.useRef(null),m=Le(R,O),C=s(d,p);return ge.useEffect(()=>(C.itemMap.set(O,{ref:O,...I}),()=>void C.itemMap.delete(O))),i.jsx(T,{[u]:"",ref:m,children:N})});S.displayName=d;function h(A){const R=s(e+"CollectionConsumer",A);return ge.useCallback(()=>{const N=R.collectionRef.current;if(!N)return[];const I=Array.from(N.querySelectorAll(`[${u}]`));return Array.from(R.itemMap.values()).sort((C,g)=>I.indexOf(C.ref.current)-I.indexOf(g.ref.current))},[R.collectionRef,R.itemMap])}return[{Provider:a,Slot:E,ItemSlot:S},h,r]}var iC=f.createContext(void 0);function aC(e){const t=f.useContext(iC);return e||t||"ltr"}var xa="rovingFocusGroup.onEntryFocus",lC={bubbles:!1,cancelable:!0},ho="RovingFocusGroup",[Fl,pf,cC]=Af(ho),[EC,hf]=dn(ho,[cC]),[dC,uC]=EC(ho),If=f.forwardRef((e,t)=>i.jsx(Fl.Provider,{scope:e.__scopeRovingFocusGroup,children:i.jsx(Fl.Slot,{scope:e.__scopeRovingFocusGroup,children:i.jsx(TC,{...e,ref:t})})}));If.displayName=ho;var TC=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:a,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:c,onEntryFocus:E,preventScrollOnEntryFocus:d=!1,...u}=e,T=f.useRef(null),S=Le(t,T),h=aC(s),[A,R]=Lc({prop:a,defaultProp:l??null,onChange:c,caller:ho}),[p,N]=f.useState(!1),I=nn(E),O=pf(n),m=f.useRef(!1),[C,g]=f.useState(0);return f.useEffect(()=>{const y=T.current;if(y)return y.addEventListener(xa,I),()=>y.removeEventListener(xa,I)},[I]),i.jsx(dC,{scope:n,orientation:r,dir:h,loop:o,currentTabStopId:A,onItemFocus:f.useCallback(y=>R(y),[R]),onItemShiftTab:f.useCallback(()=>N(!0),[]),onFocusableItemAdd:f.useCallback(()=>g(y=>y+1),[]),onFocusableItemRemove:f.useCallback(()=>g(y=>y-1),[]),children:i.jsx(Ne.div,{tabIndex:p||C===0?-1:0,"data-orientation":r,...u,ref:S,style:{outline:"none",...e.style},onMouseDown:ce(e.onMouseDown,()=>{m.current=!0}),onFocus:ce(e.onFocus,y=>{const _=!m.current;if(y.target===y.currentTarget&&_&&!p){const P=new CustomEvent(xa,lC);if(y.currentTarget.dispatchEvent(P),!P.defaultPrevented){const D=O().filter(M=>M.focusable),b=D.find(M=>M.active),F=D.find(M=>M.id===A),w=[b,F,...D].filter(Boolean).map(M=>M.ref.current);mf(w,d)}}m.current=!1}),onBlur:ce(e.onBlur,()=>N(!1))})})}),Nf="RovingFocusGroupItem",Of=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:a,...l}=e,c=jr(),E=s||c,d=uC(Nf,n),u=d.currentTabStopId===E,T=pf(n),{onFocusableItemAdd:S,onFocusableItemRemove:h,currentTabStopId:A}=d;return f.useEffect(()=>{if(r)return S(),()=>h()},[r,S,h]),i.jsx(Fl.ItemSlot,{scope:n,id:E,focusable:r,active:o,children:i.jsx(Ne.span,{tabIndex:u?0:-1,"data-orientation":d.orientation,...l,ref:t,onMouseDown:ce(e.onMouseDown,R=>{r?d.onItemFocus(E):R.preventDefault()}),onFocus:ce(e.onFocus,()=>d.onItemFocus(E)),onKeyDown:ce(e.onKeyDown,R=>{if(R.key==="Tab"&&R.shiftKey){d.onItemShiftTab();return}if(R.target!==R.currentTarget)return;const p=RC(R,d.orientation,d.dir);if(p!==void 0){if(R.metaKey||R.ctrlKey||R.altKey||R.shiftKey)return;R.preventDefault();let I=T().filter(O=>O.focusable).map(O=>O.ref.current);if(p==="last")I.reverse();else if(p==="prev"||p==="next"){p==="prev"&&I.reverse();const O=I.indexOf(R.currentTarget);I=d.loop?AC(I,O+1):I.slice(O+1)}setTimeout(()=>mf(I))}}),children:typeof a=="function"?a({isCurrentTabStop:u,hasTabStop:A!=null}):a})})});Of.displayName=Nf;var SC={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function fC(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function RC(e,t,n){const r=fC(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return SC[r]}function mf(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function AC(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var pC=If,hC=Of,Gl=["Enter"," "],IC=["ArrowDown","PageUp","Home"],Cf=["ArrowUp","PageDown","End"],NC=[...IC,...Cf],OC={ltr:[...Gl,"ArrowRight"],rtl:[...Gl,"ArrowLeft"]},mC={ltr:["ArrowLeft"],rtl:["ArrowRight"]},vi="Menu",[Jr,CC,gC]=Af(vi),[Mn,gf]=dn(vi,[gC,Nr,hf]),vc=Nr(),Lf=hf(),[rW,Pn]=Mn(vi),[oW,Io]=Mn(vi),LC="MenuAnchor",Uc=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=vc(n);return i.jsx(_i,{...o,...r,ref:t})});Uc.displayName=LC;var wc="MenuPortal",[_C,_f]=Mn(wc,{forceMount:void 0}),xf=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,s=Pn(wc,t);return i.jsx(_C,{scope:t,forceMount:n,children:i.jsx(Ze,{present:n||s.open,children:i.jsx(Ao,{asChild:!0,container:o,children:r})})})};xf.displayName=wc;var Qe="MenuContent",[xC,Bc]=Mn(Qe),yf=f.forwardRef((e,t)=>{const n=_f(Qe,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=Pn(Qe,e.__scopeMenu),a=Io(Qe,e.__scopeMenu);return i.jsx(Jr.Provider,{scope:e.__scopeMenu,children:i.jsx(Ze,{present:r||s.open,children:i.jsx(Jr.Slot,{scope:e.__scopeMenu,children:a.modal?i.jsx(yC,{...o,ref:t}):i.jsx(DC,{...o,ref:t})})})})}),yC=f.forwardRef((e,t)=>{const n=Pn(Qe,e.__scopeMenu),r=f.useRef(null),o=Le(t,r);return f.useEffect(()=>{const s=r.current;if(s)return Dc(s)},[]),i.jsx(Fc,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ce(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),DC=f.forwardRef((e,t)=>{const n=Pn(Qe,e.__scopeMenu);return i.jsx(Fc,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),MC=sr("MenuContent.ScrollLock"),Fc=f.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:s,onCloseAutoFocus:a,disableOutsidePointerEvents:l,onEntryFocus:c,onEscapeKeyDown:E,onPointerDownOutside:d,onFocusOutside:u,onInteractOutside:T,onDismiss:S,disableOutsideScroll:h,...A}=e,R=Pn(Qe,n),p=Io(Qe,n),N=vc(n),I=Lf(n),O=CC(n),[m,C]=f.useState(null),g=f.useRef(null),y=Le(t,g,R.onContentChange),_=f.useRef(0),P=f.useRef(""),D=f.useRef(0),b=f.useRef(null),F=f.useRef("right"),x=f.useRef(0),w=h?Pi:f.Fragment,M=h?{as:MC,allowPinchZoom:!0}:void 0,B=L=>{var q,X;const U=P.current+L,G=O().filter(Q=>!Q.disabled),k=document.activeElement,J=(q=G.find(Q=>Q.ref.current===k))==null?void 0:q.textValue,K=G.map(Q=>Q.textValue),$=YC(K,U,J),z=(X=G.find(Q=>Q.textValue===$))==null?void 0:X.ref.current;(function Q(ae){P.current=ae,window.clearTimeout(_.current),ae!==""&&(_.current=window.setTimeout(()=>Q(""),1e3))})(U),z&&setTimeout(()=>z.focus())};f.useEffect(()=>()=>window.clearTimeout(_.current),[]),yc();const v=f.useCallback(L=>{var G,k;return F.current===((G=b.current)==null?void 0:G.side)&&VC(L,(k=b.current)==null?void 0:k.area)},[]);return i.jsx(xC,{scope:n,searchRef:P,onItemEnter:f.useCallback(L=>{v(L)&&L.preventDefault()},[v]),onItemLeave:f.useCallback(L=>{var U;v(L)||((U=g.current)==null||U.focus(),C(null))},[v]),onTriggerLeave:f.useCallback(L=>{v(L)&&L.preventDefault()},[v]),pointerGraceTimerRef:D,onPointerGraceIntentChange:f.useCallback(L=>{b.current=L},[]),children:i.jsx(w,{...M,children:i.jsx(Di,{asChild:!0,trapped:o,onMountAutoFocus:ce(s,L=>{var U;L.preventDefault(),(U=g.current)==null||U.focus({preventScroll:!0})}),onUnmountAutoFocus:a,children:i.jsx(fo,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:E,onPointerDownOutside:d,onFocusOutside:u,onInteractOutside:T,onDismiss:S,children:i.jsx(pC,{asChild:!0,...I,dir:p.dir,orientation:"vertical",loop:r,currentTabStopId:m,onCurrentTabStopIdChange:C,onEntryFocus:ce(c,L=>{p.isUsingKeyboardRef.current||L.preventDefault()}),preventScrollOnEntryFocus:!0,children:i.jsx(Cc,{role:"menu","aria-orientation":"vertical","data-state":Vf(R.open),"data-radix-menu-content":"",dir:p.dir,...N,...A,ref:y,style:{outline:"none",...A.style},onKeyDown:ce(A.onKeyDown,L=>{const G=L.target.closest("[data-radix-menu-content]")===L.currentTarget,k=L.ctrlKey||L.altKey||L.metaKey,J=L.key.length===1;G&&(L.key==="Tab"&&L.preventDefault(),!k&&J&&B(L.key));const K=g.current;if(L.target!==K||!NC.includes(L.key))return;L.preventDefault();const z=O().filter(q=>!q.disabled).map(q=>q.ref.current);Cf.includes(L.key)&&z.reverse(),kC(z)}),onBlur:ce(e.onBlur,L=>{L.currentTarget.contains(L.target)||(window.clearTimeout(_.current),P.current="")}),onPointerMove:ce(e.onPointerMove,qr(L=>{const U=L.target,G=x.current!==L.clientX;if(L.currentTarget.contains(U)&&G){const k=L.clientX>x.current?"right":"left";F.current=k,x.current=L.clientX}}))})})})})})})});yf.displayName=Qe;var PC="MenuGroup",Gc=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return i.jsx(Ne.div,{role:"group",...r,ref:t})});Gc.displayName=PC;var bC="MenuLabel",Df=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return i.jsx(Ne.div,{...r,ref:t})});Df.displayName=bC;var Ks="MenuItem",rd="menu.itemSelect",Ui=f.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,s=f.useRef(null),a=Io(Ks,e.__scopeMenu),l=Bc(Ks,e.__scopeMenu),c=Le(t,s),E=f.useRef(!1),d=()=>{const u=s.current;if(!n&&u){const T=new CustomEvent(rd,{bubbles:!0,cancelable:!0});u.addEventListener(rd,S=>r==null?void 0:r(S),{once:!0}),SS(u,T),T.defaultPrevented?E.current=!1:a.onClose()}};return i.jsx(Mf,{...o,ref:c,disabled:n,onClick:ce(e.onClick,d),onPointerDown:u=>{var T;(T=e.onPointerDown)==null||T.call(e,u),E.current=!0},onPointerUp:ce(e.onPointerUp,u=>{var T;E.current||(T=u.currentTarget)==null||T.click()}),onKeyDown:ce(e.onKeyDown,u=>{const T=l.searchRef.current!=="";n||T&&u.key===" "||Gl.includes(u.key)&&(u.currentTarget.click(),u.preventDefault())})})});Ui.displayName=Ks;var Mf=f.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...s}=e,a=Bc(Ks,n),l=Lf(n),c=f.useRef(null),E=Le(t,c),[d,u]=f.useState(!1),[T,S]=f.useState("");return f.useEffect(()=>{const h=c.current;h&&S((h.textContent??"").trim())},[s.children]),i.jsx(Jr.ItemSlot,{scope:n,disabled:r,textValue:o??T,children:i.jsx(hC,{asChild:!0,...l,focusable:!r,children:i.jsx(Ne.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:E,onPointerMove:ce(e.onPointerMove,qr(h=>{r?a.onItemLeave(h):(a.onItemEnter(h),h.defaultPrevented||h.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:ce(e.onPointerLeave,qr(h=>a.onItemLeave(h))),onFocus:ce(e.onFocus,()=>u(!0)),onBlur:ce(e.onBlur,()=>u(!1))})})})}),vC="MenuCheckboxItem",Pf=f.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return i.jsx(Bf,{scope:e.__scopeMenu,checked:n,children:i.jsx(Ui,{role:"menuitemcheckbox","aria-checked":zs(n)?"mixed":n,...o,ref:t,"data-state":kc(n),onSelect:ce(o.onSelect,()=>r==null?void 0:r(zs(n)?!0:!n),{checkForDefaultPrevented:!1})})})});Pf.displayName=vC;var bf="MenuRadioGroup",[UC,wC]=Mn(bf,{value:void 0,onValueChange:()=>{}}),vf=f.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,s=nn(r);return i.jsx(UC,{scope:e.__scopeMenu,value:n,onValueChange:s,children:i.jsx(Gc,{...o,ref:t})})});vf.displayName=bf;var Uf="MenuRadioItem",wf=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=wC(Uf,e.__scopeMenu),s=n===o.value;return i.jsx(Bf,{scope:e.__scopeMenu,checked:s,children:i.jsx(Ui,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":kc(s),onSelect:ce(r.onSelect,()=>{var a;return(a=o.onValueChange)==null?void 0:a.call(o,n)},{checkForDefaultPrevented:!1})})})});wf.displayName=Uf;var Hc="MenuItemIndicator",[Bf,BC]=Mn(Hc,{checked:!1}),Ff=f.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,s=BC(Hc,n);return i.jsx(Ze,{present:r||zs(s.checked)||s.checked===!0,children:i.jsx(Ne.span,{...o,ref:t,"data-state":kc(s.checked)})})});Ff.displayName=Hc;var FC="MenuSeparator",Gf=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return i.jsx(Ne.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});Gf.displayName=FC;var GC="MenuArrow",Hf=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=vc(n);return i.jsx(gc,{...o,...r,ref:t})});Hf.displayName=GC;var HC="MenuSub",[sW,kf]=Mn(HC),Br="MenuSubTrigger",jf=f.forwardRef((e,t)=>{const n=Pn(Br,e.__scopeMenu),r=Io(Br,e.__scopeMenu),o=kf(Br,e.__scopeMenu),s=Bc(Br,e.__scopeMenu),a=f.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:c}=s,E={__scopeMenu:e.__scopeMenu},d=f.useCallback(()=>{a.current&&window.clearTimeout(a.current),a.current=null},[]);return f.useEffect(()=>d,[d]),f.useEffect(()=>{const u=l.current;return()=>{window.clearTimeout(u),c(null)}},[l,c]),i.jsx(Uc,{asChild:!0,...E,children:i.jsx(Mf,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":Vf(n.open),...e,ref:Oi(t,o.onTriggerChange),onClick:u=>{var T;(T=e.onClick)==null||T.call(e,u),!(e.disabled||u.defaultPrevented)&&(u.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ce(e.onPointerMove,qr(u=>{s.onItemEnter(u),!u.defaultPrevented&&!e.disabled&&!n.open&&!a.current&&(s.onPointerGraceIntentChange(null),a.current=window.setTimeout(()=>{n.onOpenChange(!0),d()},100))})),onPointerLeave:ce(e.onPointerLeave,qr(u=>{var S,h;d();const T=(S=n.content)==null?void 0:S.getBoundingClientRect();if(T){const A=(h=n.content)==null?void 0:h.dataset.side,R=A==="right",p=R?-5:5,N=T[R?"left":"right"],I=T[R?"right":"left"];s.onPointerGraceIntentChange({area:[{x:u.clientX+p,y:u.clientY},{x:N,y:T.top},{x:I,y:T.top},{x:I,y:T.bottom},{x:N,y:T.bottom}],side:A}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(u),u.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:ce(e.onKeyDown,u=>{var S;const T=s.searchRef.current!=="";e.disabled||T&&u.key===" "||OC[r.dir].includes(u.key)&&(n.onOpenChange(!0),(S=n.content)==null||S.focus(),u.preventDefault())})})})});jf.displayName=Br;var Yf="MenuSubContent",Wf=f.forwardRef((e,t)=>{const n=_f(Qe,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=Pn(Qe,e.__scopeMenu),a=Io(Qe,e.__scopeMenu),l=kf(Yf,e.__scopeMenu),c=f.useRef(null),E=Le(t,c);return i.jsx(Jr.Provider,{scope:e.__scopeMenu,children:i.jsx(Ze,{present:r||s.open,children:i.jsx(Jr.Slot,{scope:e.__scopeMenu,children:i.jsx(Fc,{id:l.contentId,"aria-labelledby":l.triggerId,...o,ref:E,align:"start",side:a.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:d=>{var u;a.isUsingKeyboardRef.current&&((u=c.current)==null||u.focus()),d.preventDefault()},onCloseAutoFocus:d=>d.preventDefault(),onFocusOutside:ce(e.onFocusOutside,d=>{d.target!==l.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:ce(e.onEscapeKeyDown,d=>{a.onClose(),d.preventDefault()}),onKeyDown:ce(e.onKeyDown,d=>{var S;const u=d.currentTarget.contains(d.target),T=mC[a.dir].includes(d.key);u&&T&&(s.onOpenChange(!1),(S=l.trigger)==null||S.focus(),d.preventDefault())})})})})})});Wf.displayName=Yf;function Vf(e){return e?"open":"closed"}function zs(e){return e==="indeterminate"}function kc(e){return zs(e)?"indeterminate":e?"checked":"unchecked"}function kC(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function jC(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function YC(e,t,n){const o=t.length>1&&Array.from(t).every(E=>E===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let a=jC(e,Math.max(s,0));o.length===1&&(a=a.filter(E=>E!==n));const c=a.find(E=>E.toLowerCase().startsWith(o.toLowerCase()));return c!==n?c:void 0}function WC(e,t){const{x:n,y:r}=e;let o=!1;for(let s=0,a=t.length-1;s<t.length;a=s++){const l=t[s],c=t[a],E=l.x,d=l.y,u=c.x,T=c.y;d>r!=T>r&&n<(u-E)*(r-d)/(T-d)+E&&(o=!o)}return o}function VC(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return WC(n,t)}function qr(e){return t=>t.pointerType==="mouse"?e(t):void 0}var $C=Uc,XC=xf,KC=yf,zC=Gc,JC=Df,qC=Ui,QC=Pf,ZC=vf,eg=wf,tg=Ff,ng=Gf,rg=Hf,og=jf,sg=Wf,$f="DropdownMenu",[ig]=dn($f,[gf]),ke=gf(),[iW,Xf]=ig($f),Kf="DropdownMenuTrigger",ag=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,s=Xf(Kf,n),a=ke(n);return i.jsx($C,{asChild:!0,...a,children:i.jsx(Ne.button,{type:"button",id:s.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":s.open?s.contentId:void 0,"data-state":s.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...o,ref:Oi(t,s.triggerRef),onPointerDown:ce(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(s.onOpenToggle(),s.open||l.preventDefault())}),onKeyDown:ce(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&s.onOpenToggle(),l.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});ag.displayName=Kf;var lg="DropdownMenuPortal",zf=e=>{const{__scopeDropdownMenu:t,...n}=e,r=ke(t);return i.jsx(XC,{...r,...n})};zf.displayName=lg;var Jf="DropdownMenuContent",qf=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Xf(Jf,n),s=ke(n),a=f.useRef(!1);return i.jsx(KC,{id:o.contentId,"aria-labelledby":o.triggerId,...s,...r,ref:t,onCloseAutoFocus:ce(e.onCloseAutoFocus,l=>{var c;a.current||(c=o.triggerRef.current)==null||c.focus(),a.current=!1,l.preventDefault()}),onInteractOutside:ce(e.onInteractOutside,l=>{const c=l.detail.originalEvent,E=c.button===0&&c.ctrlKey===!0,d=c.button===2||E;(!o.modal||d)&&(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)"}})});qf.displayName=Jf;var cg="DropdownMenuGroup",Eg=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=ke(n);return i.jsx(zC,{...o,...r,ref:t})});Eg.displayName=cg;var dg="DropdownMenuLabel",Qf=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=ke(n);return i.jsx(JC,{...o,...r,ref:t})});Qf.displayName=dg;var ug="DropdownMenuItem",Zf=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=ke(n);return i.jsx(qC,{...o,...r,ref:t})});Zf.displayName=ug;var Tg="DropdownMenuCheckboxItem",Sg=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=ke(n);return i.jsx(QC,{...o,...r,ref:t})});Sg.displayName=Tg;var fg="DropdownMenuRadioGroup",Rg=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=ke(n);return i.jsx(ZC,{...o,...r,ref:t})});Rg.displayName=fg;var Ag="DropdownMenuRadioItem",pg=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=ke(n);return i.jsx(eg,{...o,...r,ref:t})});pg.displayName=Ag;var hg="DropdownMenuItemIndicator",Ig=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=ke(n);return i.jsx(tg,{...o,...r,ref:t})});Ig.displayName=hg;var Ng="DropdownMenuSeparator",eR=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=ke(n);return i.jsx(ng,{...o,...r,ref:t})});eR.displayName=Ng;var Og="DropdownMenuArrow",mg=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=ke(n);return i.jsx(rg,{...o,...r,ref:t})});mg.displayName=Og;var Cg="DropdownMenuSubTrigger",gg=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=ke(n);return i.jsx(og,{...o,...r,ref:t})});gg.displayName=Cg;var Lg="DropdownMenuSubContent",_g=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=ke(n);return i.jsx(sg,{...o,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});_g.displayName=Lg;var xg=zf,yg=qf,Dg=Qf,Mg=Zf,Pg=eR;const bg=f.forwardRef(({container:e,style:t,sideOffset:n=4,...r},o)=>i.jsx(xg,{container:e,children:i.jsx(yg,{ref:o,sideOffset:n,style:{minWidth:180,background:Se("surfaceElevated"),color:Se("textPrimary"),border:`1px solid ${Se("borderDefault")}`,borderRadius:En.md,boxShadow:Se("shadowMd"),padding:pe[1],zIndex:Xr.popover,...t},...r})}));bg.displayName="DropdownMenuContent";const vg=f.forwardRef(({style:e,...t},n)=>i.jsx(Mg,{ref:n,style:{display:"flex",alignItems:"center",gap:pe[2],padding:`${pe[1]} ${pe[2]}`,fontSize:Fe.sm,borderRadius:En.sm,cursor:"default",outline:"none",userSelect:"none",...e},...t}));vg.displayName="DropdownMenuItem";const Ug=f.forwardRef(({style:e,...t},n)=>i.jsx(Pg,{ref:n,style:{height:1,background:Se("borderSubtle"),margin:`${pe[1]} 0`,...e},...t}));Ug.displayName="DropdownMenuSeparator";const wg=f.forwardRef(({style:e,...t},n)=>i.jsx(Dg,{ref:n,style:{padding:`${pe[1]} ${pe[2]}`,fontSize:Fe.xs,color:Se("textMuted"),textTransform:"uppercase",letterSpacing:"0.04em",...e},...t}));wg.displayName="DropdownMenuLabel";var tR="Popover",[nR]=dn(tR,[Nr]),wi=Nr(),[aW,un]=nR(tR),rR="PopoverAnchor",Bg=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=un(rR,n),s=wi(n),{onCustomAnchorAdd:a,onCustomAnchorRemove:l}=o;return f.useEffect(()=>(a(),()=>l()),[a,l]),i.jsx(_i,{...s,...r,ref:t})});Bg.displayName=rR;var oR="PopoverTrigger",Fg=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=un(oR,n),s=wi(n),a=Le(t,o.triggerRef),l=i.jsx(Ne.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":cR(o.open),...r,ref:a,onClick:ce(e.onClick,o.onOpenToggle)});return o.hasCustomAnchor?l:i.jsx(_i,{asChild:!0,...s,children:l})});Fg.displayName=oR;var jc="PopoverPortal",[Gg,Hg]=nR(jc,{forceMount:void 0}),sR=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,s=un(jc,t);return i.jsx(Gg,{scope:t,forceMount:n,children:i.jsx(Ze,{present:n||s.open,children:i.jsx(Ao,{asChild:!0,container:o,children:r})})})};sR.displayName=jc;var lr="PopoverContent",iR=f.forwardRef((e,t)=>{const n=Hg(lr,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,s=un(lr,e.__scopePopover);return i.jsx(Ze,{present:r||s.open,children:s.modal?i.jsx(jg,{...o,ref:t}):i.jsx(Yg,{...o,ref:t})})});iR.displayName=lr;var kg=sr("PopoverContent.RemoveScroll"),jg=f.forwardRef((e,t)=>{const n=un(lr,e.__scopePopover),r=f.useRef(null),o=Le(t,r),s=f.useRef(!1);return f.useEffect(()=>{const a=r.current;if(a)return Dc(a)},[]),i.jsx(Pi,{as:kg,allowPinchZoom:!0,children:i.jsx(aR,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ce(e.onCloseAutoFocus,a=>{var l;a.preventDefault(),s.current||(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:ce(e.onPointerDownOutside,a=>{const l=a.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,E=l.button===2||c;s.current=E},{checkForDefaultPrevented:!1}),onFocusOutside:ce(e.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1})})})}),Yg=f.forwardRef((e,t)=>{const n=un(lr,e.__scopePopover),r=f.useRef(!1),o=f.useRef(!1);return i.jsx(aR,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var a,l;(a=e.onCloseAutoFocus)==null||a.call(e,s),s.defaultPrevented||(r.current||(l=n.triggerRef.current)==null||l.focus(),s.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:s=>{var c,E;(c=e.onInteractOutside)==null||c.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const a=s.target;((E=n.triggerRef.current)==null?void 0:E.contains(a))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),aR=f.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:s,disableOutsidePointerEvents:a,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:E,onInteractOutside:d,...u}=e,T=un(lr,n),S=wi(n);return yc(),i.jsx(Di,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:s,children:i.jsx(fo,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:d,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:E,onDismiss:()=>T.onOpenChange(!1),children:i.jsx(Cc,{"data-state":cR(T.open),role:"dialog",id:T.contentId,...S,...u,ref:t,style:{...u.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)"}})})})}),lR="PopoverClose",Wg=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=un(lR,n);return i.jsx(Ne.button,{type:"button",...r,ref:t,onClick:ce(e.onClick,()=>o.onOpenChange(!1))})});Wg.displayName=lR;var Vg="PopoverArrow",$g=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=wi(n);return i.jsx(gc,{...o,...r,ref:t})});$g.displayName=Vg;function cR(e){return e?"open":"closed"}var Xg=sR,Kg=iR;const zg=f.forwardRef(({container:e,style:t,sideOffset:n=6,...r},o)=>i.jsx(Xg,{container:e,children:i.jsx(Kg,{ref:o,sideOffset:n,style:{background:Se("surfaceElevated"),color:Se("textPrimary"),border:`1px solid ${Se("borderDefault")}`,borderRadius:En.md,boxShadow:Se("shadowMd"),padding:pe[3],zIndex:Xr.popover,minWidth:220,...t},...r})}));zg.displayName="PopoverContent";function Bt({icon:e,eyebrow:t,title:n,subtitle:r,status:o,actions:s,toolbar:a,bodyPadding:l=14,children:c}){return i.jsxs("div",{className:"panel-frame",children:[i.jsxs("div",{className:"panel-frame-header",children:[i.jsxs("div",{className:"panel-frame-heading",children:[e&&i.jsx("span",{className:"panel-frame-icon",children:e}),i.jsxs("div",{className:"panel-frame-title-col",children:[t&&i.jsx("div",{className:"panel-frame-eyebrow",children:t}),i.jsxs("div",{className:"panel-frame-title-row",children:[n&&i.jsx("h2",{className:"panel-frame-title",children:n}),o&&i.jsx("span",{className:"panel-frame-status",children:o})]}),r&&i.jsx("div",{className:"panel-frame-subtitle",children:r})]})]}),s&&i.jsx("div",{className:"panel-frame-actions",children:s})]}),a&&i.jsx("div",{className:"panel-frame-toolbar",children:a}),i.jsx("div",{className:"panel-frame-body",style:{padding:l},children:c})]})}function Yc({tone:e="neutral",icon:t,children:n,className:r="",...o}){return i.jsxs("span",{className:`status-pill tone-${e} ${r}`,...o,children:[t&&i.jsx("span",{className:"status-pill-icon",children:t}),n]})}function bt({icon:e,title:t,description:n,action:r}){return i.jsxs("div",{className:"panel-empty",children:[e&&i.jsx("span",{className:"panel-empty-icon",children:e}),t&&i.jsx("p",{className:"panel-empty-title",children:t}),n&&i.jsx("p",{className:"panel-empty-desc",children:n}),r]})}function No({left:e,right:t,children:n,className:r=""}){return i.jsxs("div",{className:`panel-toolbar ${r}`,children:[e&&i.jsx("div",{className:"panel-toolbar-left",children:e}),n&&i.jsx("div",{className:"panel-toolbar-center",children:n}),t&&i.jsx("div",{className:"panel-toolbar-right",children:t})]})}function Jg({options:e,value:t,onChange:n,size:r="md",ariaLabel:o}){const s=r==="sm"?"4px 10px":"6px 12px",a=r==="sm"?11:12;return i.jsx("div",{role:"tablist","aria-label":o,style:{display:"inline-flex",padding:2,gap:2,background:"var(--bg-2)",border:"1px solid var(--border-default)",borderRadius:8},children:e.map(l=>{const c=l.value===t;return i.jsxs("button",{role:"tab","aria-selected":c,disabled:l.disabled,onClick:()=>n(l.value),style:{display:"inline-flex",alignItems:"center",gap:6,padding:s,border:"none",borderRadius:6,background:c?"var(--bg-0)":"transparent",color:c?"var(--text-primary)":"var(--text-tertiary)",fontSize:a,fontWeight:c?600:500,cursor:l.disabled?"not-allowed":"pointer",opacity:l.disabled?.5:1,boxShadow:c?"0 1px 2px rgba(0,0,0,0.12)":"none",transition:"background 120ms var(--ease), color 120ms var(--ease)",whiteSpace:"nowrap"},children:[l.icon&&i.jsx("span",{style:{display:"inline-flex"},children:l.icon}),l.label]},l.value)})})}function ER({typeLabel:e,typeColor:t,accent:n,idleBorder:r,background:o,headerBackground:s,active:a=!1,title:l,status:c,actions:E,toolbar:d,subheader:u,footer:T,children:S,onMouseEnter:h,onMouseLeave:A,onClick:R,gutter:p,className:N,style:I}){const O=t??"var(--color-accent-blue, #388bfd)",m=n??r??"var(--color-border-subtle, rgba(148,163,184,0.18))",C=r??"var(--color-border-subtle, rgba(148,163,184,0.18))",g=o??"var(--color-bg-1, rgba(22,27,34,0.5))",y=s??"transparent";return i.jsxs("div",{onMouseEnter:h,onMouseLeave:A,onClick:R,className:N,style:{display:"flex",gap:0,marginBottom:2,...I},children:[p!==void 0&&p,i.jsxs("div",{style:{flex:1,minWidth:0,borderRadius:8,border:`1px solid ${a?m:C}`,borderLeft:`2px solid ${m}`,background:g,overflow:"hidden",transition:"border-color 0.2s"},children:[i.jsxs("div",{style:{height:32,display:"flex",alignItems:"center",padding:"0 8px 0 10px",gap:8,borderBottom:`1px solid ${C}`,background:y},children:[i.jsx("span",{style:{fontSize:10,fontWeight:700,fontFamily:'var(--font-mono, "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace)',letterSpacing:"0.08em",color:O,background:`${O}18`,border:`1px solid ${O}40`,borderRadius:4,padding:"1px 6px",flexShrink:0,textTransform:"uppercase"},children:e}),l!==void 0&&l,d!==void 0&&d,i.jsx("span",{style:{flex:1}}),c!==void 0&&c,E!==void 0&&E]}),u!==void 0&&u,S,T!==void 0&&T]})]})}function qg({shortcut:e,children:t,style:n,...r}){return i.jsx("kbd",{...r,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:18,height:18,padding:`0 ${pe[1]}px`,borderRadius:En.sm,border:`1px solid ${Se("borderSubtle")}`,background:Se("surfaceRaised"),color:Se("textSecondary"),fontFamily:"var(--dql-font-mono, monospace)",fontSize:Fe.xs,fontWeight:Sc.medium,lineHeight:1,whiteSpace:"nowrap",...n},children:e??t})}const od=e=>{let t;const n=new Set,r=(E,d)=>{const u=typeof E=="function"?E(t):E;if(!Object.is(u,t)){const T=t;t=d??(typeof u!="object"||u===null)?u:Object.assign({},t,u),n.forEach(S=>S(t,T))}},o=()=>t,l={setState:r,getState:o,getInitialState:()=>c,subscribe:E=>(n.add(E),()=>n.delete(E))},c=t=e(r,o,l);return l},Qg=(e=>e?od(e):od),Zg=e=>e;function eL(e,t=Zg){const n=ge.useSyncExternalStore(e.subscribe,ge.useCallback(()=>t(e.getState()),[e,t]),ge.useCallback(()=>t(e.getInitialState()),[e,t]));return ge.useDebugValue(n),n}const sd=e=>{const t=Qg(e),n=r=>eL(t,r);return Object.assign(n,t),n},tL=(e=>e?sd(e):sd),id=e=>Symbol.iterator in e,ad=e=>"entries"in e,ld=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(const[o,s]of n)if(!r.has(o)||!Object.is(s,r.get(o)))return!1;return!0},nL=(e,t)=>{const n=e[Symbol.iterator](),r=t[Symbol.iterator]();let o=n.next(),s=r.next();for(;!o.done&&!s.done;){if(!Object.is(o.value,s.value))return!1;o=n.next(),s=r.next()}return!!o.done&&!!s.done};function rL(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:id(e)&&id(t)?ad(e)&&ad(t)?ld(e,t):nL(e,t):ld({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function oL(e){const t=ge.useRef(void 0);return n=>{const r=e(n);return rL(t.current,r)?t.current:t.current=r}}function sL(){var t;return typeof window>"u"?"studio":((t=window.localStorage)==null?void 0:t.getItem("dql-app-mode"))==="app"?"app":"studio"}function iL(){var t;if(typeof window>"u")return"obsidian";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":e==="light"?"paper":"obsidian"}const aL={mainView:"notebook",themeMode:iL(),appMode:sL(),sidebarPanel:"files",sidebarOpen:!0,files:[],filesLoading:!1,activeFile:null,cells:[],notebookTitle:"",notebookMetadata:{},notebookDirty:!1,schemaTables:[],schemaLoading:!1,semanticLayer:{available:!1,provider:null,metrics:[],dimensions:[],hierarchies:[],domains:[],tags:[],favorites:[],recentlyUsed:[],loading:!1,lastSyncTime:null},devPanelOpen:!1,devPanelTab:"logs",queryLog:[],newNotebookModalOpen:!1,newBlockModalOpen:!1,autoSave:!1,executionCounter:0,savingFile:!1,lineageFullscreen:!1,lineageFocusNodeId:null,dashboardMode:!1,activeBlockPath:null,blockStudioDraft:"",blockStudioDirty:!1,blockStudioPreview:null,blockStudioValidation:null,blockStudioMetadata:null,blockStudioCatalog:null,blockStudioCatalogLoading:!1,inspectorOpen:!1,inspectorContext:null};function lL(e,t){var n,r,o,s;switch(t.type){case"SET_MAIN_VIEW":return{...e,mainView:t.view,lineageFullscreen:!1,lineageFocusNodeId:null};case"SET_THEME":{if(typeof document<"u"){const a=t.mode==="dark"||t.mode==="midnight"?"obsidian":t.mode==="light"?"paper":t.mode==="arctic"?"white":t.mode;document.documentElement.setAttribute("data-theme",a);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.setItem("dql-app-mode",t.mode)}catch{}return{...e,appMode:t.mode}}case"SET_SIDEBAR_PANEL":return{...e,sidebarPanel:t.panel,sidebarOpen:t.panel!==null&&t.panel!=="connection"&&t.panel!=="reference",lineageFullscreen:!1,lineageFocusNodeId:null,mainView:t.panel==="connection"?"connection":t.panel==="reference"?"reference":((o=e.activeFile)==null?void 0:o.type)==="block"?"block_studio":"notebook"};case"TOGGLE_SIDEBAR":return{...e,sidebarOpen:!e.sidebarOpen};case"SET_FILES":return{...e,files:t.files};case"SET_FILES_LOADING":return{...e,filesLoading:t.loading};case"OPEN_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,lineageFullscreen:!1,lineageFocusNodeId:(s=t.payload.metadata)!=null&&s.name?`block:${t.payload.metadata.name}`:null};case"SET_CELLS":return{...e,cells:t.cells,notebookDirty:!0};case"UPDATE_NOTEBOOK_METADATA":{const a=e.notebookMetadata;let l=!1;for(const c of Object.keys(t.updates))if(a[c]!==t.updates[c]){l=!0;break}return l?{...e,notebookMetadata:{...a,...t.updates},notebookDirty:!0}:e}case"ADD_CELL":{if(!t.afterId)return{...e,cells:[...e.cells,t.cell],notebookDirty:!0};const a=e.cells.findIndex(c=>c.id===t.afterId);if(a===-1)return{...e,cells:[...e.cells,t.cell],notebookDirty:!0};const l=[...e.cells];return l.splice(a+1,0,t.cell),{...e,cells:l,notebookDirty:!0}}case"UPDATE_CELL":{const a=e.cells.map(c=>c.id===t.id?{...c,...t.updates}:c),l=t.updates.executionCount!==void 0?e.executionCounter+1:e.executionCounter;return{...e,cells:a,notebookDirty:!0,executionCounter:l}}case"DELETE_CELL":return{...e,cells:e.cells.filter(a=>a.id!==t.id),notebookDirty:!0};case"MOVE_CELL":{const a=e.cells.findIndex(c=>c.id===t.id);if(a===-1)return e;const l=[...e.cells];return t.direction==="up"&&a>0?[l[a-1],l[a]]=[l[a],l[a-1]]:t.direction==="down"&&a<l.length-1&&([l[a],l[a+1]]=[l[a+1],l[a]]),{...e,cells:l,notebookDirty:!0}}case"REORDER_CELL":{const{fromIndex:a,toIndex:l}=t;if(a===l||a<0||l<0||a>=e.cells.length||l>=e.cells.length)return e;const c=[...e.cells],[E]=c.splice(a,1);return c.splice(l,0,E),{...e,cells:c,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(a=>a.name===t.tableName?{...a,expanded:!a.expanded}:a)};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};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(a=>a.name===t.tableName?{...a,columns:t.columns}:a)};case"SET_PARAM_VALUE":return{...e,cells:e.cells.map(a=>a.id===t.id?{...a,paramValue:t.value}:a),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 a=[t.name,...e.semanticLayer.recentlyUsed.filter(l=>l!==t.name)].slice(0,12);return{...e,semanticLayer:{...e.semanticLayer,recentlyUsed:a}}}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"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"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};default:return e}}const Hl=tL((e,t)=>({...aL,dispatch:n=>{const r=lL(t(),n);e(r)}})),cL=f.createContext(null);function EL({children:e}){return ge.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")&&Hl.getState().dispatch({type:"SET_THEME",mode:r})};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]),i.jsx(i.Fragment,{children:e})}function Te(){const e=Hl(oL(r=>{const{dispatch:o,...s}=r;return s})),t=Hl(r=>r.dispatch);return f.useContext(cL)??{state:e,dispatch:t}}function Mt(){return`cell_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function $e(e,t=""){const n={id:Mt(),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={provider:"claude-agent-sdk",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 dR=(...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 dL=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 uL=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 cd=e=>{const t=uL(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 TL={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 SL=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 fL=f.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:s,iconNode:a,...l},c)=>f.createElement("svg",{ref:c,...TL,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:dR("lucide",o),...!s&&!SL(l)&&{"aria-hidden":"true"},...l},[...a.map(([E,d])=>f.createElement(E,d)),...Array.isArray(s)?s:[s]]));/**
|
|
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 he=(e,t)=>{const n=f.forwardRef(({className:r,...o},s)=>f.createElement(fL,{ref:s,iconNode:t,className:dR(`lucide-${dL(cd(e))}`,`lucide-${e}`,r),...o}));return n.displayName=cd(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 RL=[["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"}]],AL=he("activity",RL);/**
|
|
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 pL=[["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"}]],hL=he("blocks",pL);/**
|
|
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 IL=[["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"}]],uR=he("book-open",IL);/**
|
|
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 NL=[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]],OL=he("chevrons-left",NL);/**
|
|
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 mL=[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]],CL=he("chevrons-right",mL);/**
|
|
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 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"}]],LL=he("circle-question-mark",gL);/**
|
|
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 _L=[["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"}]],xL=he("command",_L);/**
|
|
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 yL=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],TR=he("database",yL);/**
|
|
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 DL=[["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"}]],ML=he("eye-off",DL);/**
|
|
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 PL=[["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"}]],Ed=he("eye",PL);/**
|
|
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 bL=[["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"}]],vL=he("file-plus",bL);/**
|
|
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 UL=[["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"}]],wL=he("file-text",UL);/**
|
|
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 BL=[["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"}]],SR=he("files",BL);/**
|
|
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 FL=[["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"}]],fR=he("git-branch",FL);/**
|
|
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 GL=[["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"}]],HL=he("git-fork",GL);/**
|
|
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 kL=[["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"}]],jL=he("layout-dashboard",kL);/**
|
|
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 YL=[["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"}]],WL=he("network",YL);/**
|
|
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 VL=[["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"}]],$L=he("package",VL);/**
|
|
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 XL=[["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"}]],KL=he("palette",XL);/**
|
|
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 zL=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],JL=he("panel-left",zL);/**
|
|
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 qL=[["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"}]],RR=he("plug",qL);/**
|
|
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 QL=[["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"}]],ZL=he("settings",QL);/**
|
|
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 e_=[["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"}]],t_=he("square-dashed",e_);/**
|
|
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 n_=[["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"}]],r_=he("table",n_);/**
|
|
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 o_=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],s_=he("terminal",o_);/**
|
|
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 i_=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],a_=he("wrench",i_);function l_(e,t){if(!t)return 1;const n=(e.label+" "+e.group+" "+(e.keywords||"")).toLowerCase(),r=t.toLowerCase();if(n.includes(r))return 100-n.indexOf(r);let o=0;for(const s of n)if(s===r[o]&&o++,o===r.length)return 10;return 0}function c_(e,t){const n=e.mode??"both";return n==="both"||n===t}function E_({open:e,onClose:t}){const{state:n,dispatch:r}=Te(),[o,s]=f.useState(""),[a,l]=f.useState(0),c=f.useRef(null);f.useEffect(()=>{e&&(s(""),l(0))},[e]);const E=f.useMemo(()=>{const S=O=>r(O),h=()=>t(),A=O=>()=>{O(),h()},R=[["Files","files",SR],["Schema","schema",TR],["Lineage","lineage",HL],["Git","git",fR],["Block Library","block_library",hL],["Apps","apps",WL],["Connections","connection",RR],["Reference","reference",uR]],p=[{mode:"obsidian",label:"Obsidian"},{mode:"paper",label:"Paper"},{mode:"white",label:"White"}],N=[];N.push({id:"mode.toggle",label:n.appMode==="studio"?"Switch to App mode":"Switch to Studio",group:"Mode",icon:n.appMode==="studio"?Ed:a_,keywords:"studio app preview publish read-only editor",shortcut:"⌘⇧M",run:A(()=>S({type:"SET_APP_MODE",mode:n.appMode==="studio"?"app":"studio"}))}),N.push({id:"sidebar.toggle",label:n.sidebarOpen?"Hide sidebar":"Show sidebar",group:"View",icon:JL,shortcut:"⌘B",mode:"studio",run:A(()=>S({type:"TOGGLE_SIDEBAR"}))},{id:"inspector.toggle",label:n.inspectorOpen?"Hide inspector":"Show inspector",group:"View",icon:n.inspectorOpen?ML:Ed,shortcut:"⌘⇧I",mode:"studio",run:A(()=>S({type:"TOGGLE_INSPECTOR"}))},{id:"dashboard.toggle",label:n.dashboardMode?"Exit dashboard mode":"Enter dashboard mode",group:"View",icon:jL,shortcut:"⌘D",run:A(()=>S({type:"TOGGLE_DASHBOARD_MODE"}))},{id:"dev.toggle",label:"Toggle dev panel",group:"View",icon:s_,shortcut:"⌘J",mode:"studio",run:A(()=>S({type:"TOGGLE_DEV_PANEL"}))},{id:"lineage.fullscreen",label:n.lineageFullscreen?"Exit full-screen lineage":"Open full-screen lineage",group:"Lineage",icon:AL,keywords:"graph dag",run:A(()=>S({type:"TOGGLE_LINEAGE_FULLSCREEN"}))});for(const[O,m,C]of R)N.push({id:`panel.${m}`,label:`Go to ${O}`,group:"Navigate",icon:C,mode:"studio",run:A(()=>{S({type:"SET_SIDEBAR_PANEL",panel:m}),n.sidebarOpen||S({type:"TOGGLE_SIDEBAR"})})});N.push({id:"notebook.new",label:"New notebook…",group:"Create",icon:vL,mode:"studio",run:A(()=>S({type:"OPEN_NEW_NOTEBOOK_MODAL"}))},{id:"block.new",label:"New block…",group:"Create",icon:t_,mode:"studio",run:A(()=>S({type:"OPEN_NEW_BLOCK_MODAL"}))});const I=n.themeMode==="dark"||n.themeMode==="midnight"?"obsidian":n.themeMode==="light"?"paper":n.themeMode==="arctic"?"white":n.themeMode;for(const O of p)O.mode!==I&&N.push({id:`theme.${O.mode}`,label:`Switch to ${O.label}`,group:"Theme",icon:KL,keywords:"appearance color",run:A(()=>S({type:"SET_THEME",mode:O.mode}))});return N},[n.sidebarOpen,n.inspectorOpen,n.themeMode,n.dashboardMode,n.lineageFullscreen,n.appMode,n.sidebarPanel,r,t]),d=f.useMemo(()=>{const h=E.filter(A=>c_(A,n.appMode)).map(A=>({a:A,s:l_(A,o)})).filter(A=>A.s>0);return h.sort((A,R)=>R.s-A.s),h.map(A=>A.a)},[E,o,n.appMode]);f.useEffect(()=>{l(0)},[o]),f.useEffect(()=>{var h;const S=(h=c.current)==null?void 0:h.querySelector(`[data-palette-idx="${a}"]`);S==null||S.scrollIntoView({block:"nearest"})},[a]);const u=S=>{var h;S.key==="ArrowDown"?(S.preventDefault(),l(A=>Math.min(d.length-1,A+1))):S.key==="ArrowUp"?(S.preventDefault(),l(A=>Math.max(0,A-1))):S.key==="Enter"&&(S.preventDefault(),(h=d[a])==null||h.run())};let T="";return i.jsx(tC,{open:e,onOpenChange:S=>!S&&t(),children:i.jsxs(nC,{children:[i.jsx(rC,{style:{position:"fixed",inset:0,background:Se("surfaceOverlay"),zIndex:Xr.overlay}}),i.jsxs(oC,{"aria-label":"Command palette",style:{position:"fixed",top:"18vh",left:"50%",transform:"translateX(-50%)",width:"92vw",maxWidth:620,background:Se("surfaceRaised"),color:Se("textPrimary"),border:`1px solid ${Se("borderDefault")}`,borderRadius:En.lg,boxShadow:Se("shadowLg"),zIndex:Xr.modal,display:"flex",flexDirection:"column",overflow:"hidden"},onKeyDown:u,children:[i.jsx(sC,{style:{position:"absolute",left:-9999},children:"Command palette"}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:pe[2],padding:`${pe[3]}px ${pe[4]}px`,borderBottom:`1px solid ${Se("borderSubtle")}`},children:[i.jsx(xL,{size:14,strokeWidth:1.75,color:Se("textMuted")}),i.jsx("input",{autoFocus:!0,value:o,onChange:S=>s(S.target.value),placeholder:"Type a command…",style:{flex:1,border:"none",outline:"none",background:"transparent",color:Se("textPrimary"),fontSize:Fe.md}})]}),i.jsxs("div",{ref:c,style:{maxHeight:360,overflowY:"auto",padding:`${pe[1]}px 0`},children:[d.length===0&&i.jsx("div",{style:{padding:pe[4],fontSize:Fe.sm,color:Se("textMuted"),textAlign:"center"},children:"No matching commands"}),d.map((S,h)=>{const A=S.group!==T;T=S.group;const R=h===a,p=S.icon;return i.jsxs(ge.Fragment,{children:[A&&i.jsx("div",{style:{padding:`${pe[2]}px ${pe[4]}px ${pe[1]}px`},children:i.jsx(Yc,{tone:"neutral",children:S.group})}),i.jsxs("div",{"data-palette-idx":h,role:"option","aria-selected":R,onMouseEnter:()=>l(h),onMouseDown:N=>{N.preventDefault(),S.run()},style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:pe[3],padding:`${pe[2]}px ${pe[4]}px`,fontSize:Fe.sm,cursor:"pointer",background:R?Se("surfaceHover"):"transparent",color:Se("textPrimary")},children:[i.jsxs("span",{style:{display:"flex",alignItems:"center",gap:pe[2],minWidth:0,flex:1},children:[p&&i.jsx(p,{size:14,strokeWidth:1.75}),i.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.label})]}),S.shortcut&&i.jsx(qg,{shortcut:S.shortcut})]})]},S.id)})]})]})]})})}const AR=window.location.origin;async function ie(e,t){const n=await fetch(`${AR}${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()}const Z={async listNotebooks(){try{return await ie("/api/notebooks")}catch{return[]}},async readNotebook(e){return ie(`/api/notebook-content?path=${encodeURIComponent(e)}`)},async createNotebook(e,t){return ie("/api/notebooks",{method:"POST",body:JSON.stringify({name:e,template:t})})},async createBlock(e){return ie("/api/blocks",{method:"POST",body:JSON.stringify({name:e})})},async getBlockLibrary(){try{return await ie("/api/blocks/library")}catch{return{blocks:[]}}},async getApps(){try{return await ie("/api/apps")}catch{return{apps:[]}}},async updateBlockStatus(e,t){return ie("/api/blocks/status",{method:"POST",body:JSON.stringify({path:e,newStatus:t})})},async getBlockHistory(e){try{return await ie(`/api/blocks/history?path=${encodeURIComponent(e)}`)}catch{return{entries:[]}}},async runBlockTests(e,t){return ie("/api/blocks/run-tests",{method:"POST",body:JSON.stringify({source:e,path:t})})},async getBlockStudioCatalog(){return ie("/api/block-studio/catalog")},async openBlockStudio(e){return ie(`/api/block-studio/open?path=${encodeURIComponent(e)}`)},async getBlockBody(e){return ie(`/api/blocks/body?path=${encodeURIComponent(e)}`)},async validateBlockStudio(e,t){return ie("/api/block-studio/validate",{method:"POST",body:JSON.stringify({source:e,path:t})})},async runBlockStudio(e,t){return ie("/api/block-studio/run",{method:"POST",body:JSON.stringify({source:e,path:t})})},async saveBlockStudio(e){return ie("/api/block-studio/save",{method:"POST",body:JSON.stringify(e)})},async saveAsBlock(e){return ie("/api/blocks/save-from-cell",{method:"POST",body:JSON.stringify(e)})},async getBlockTemplates(){try{return(await ie("/api/blocks/templates")).templates}catch{return[]}},async listBlocks(e){try{return(await ie("/api/notebooks")).filter(n=>n.type==="block"&&(!e||n.path.startsWith(`blocks/${e}/`)))}catch{return[]}},async saveNotebook(e,t){return ie("/api/notebook-content",{method:"PUT",body:JSON.stringify({path:e,content:t})})},async executeQuery(e,t){var s;const n=await ie("/api/query",{method:"POST",body:JSON.stringify({sql:e}),signal:t}),r=Array.isArray(n==null?void 0:n.columns)?n.columns.map(a=>typeof a=="string"?a:typeof(a==null?void 0:a.name)=="string"?a.name:String(a)):[],o=n!=null&&n.semanticRefs&&typeof n.semanticRefs=="object"?{metrics:Array.isArray(n.semanticRefs.metrics)?n.semanticRefs.metrics.map(String):[],dimensions:Array.isArray(n.semanticRefs.dimensions)?n.semanticRefs.dimensions.map(String):[]}:void 0;return{columns:r,rows:Array.isArray(n==null?void 0:n.rows)?n.rows:[],rowCount:(n==null?void 0:n.rowCount)??((s=n==null?void 0:n.rows)==null?void 0:s.length)??0,executionTime:(n==null?void 0:n.executionTime)??(n==null?void 0:n.executionTimeMs)??0,...o?{semanticRefs:o}:{}}},async getSchema(){try{const e=await fetch(`${AR}/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 ie("/api/connections")}catch{return{default:"unknown",connections:{}}}},async saveConnections(e){return ie("/api/connections",{method:"PUT",body:JSON.stringify({connections:e})})},async testConnection(){try{return await ie("/api/test-connection",{method:"POST",body:JSON.stringify({})})}catch(e){return{ok:!1,message:e.message??"Connection failed"}}},async getSemanticLayer(){try{return await ie("/api/semantic-layer")}catch{return{available:!1,provider:null,metrics:[],dimensions:[],hierarchies:[],domains:[],tags:[],favorites:[],recentlyUsed:[],lastSyncTime:null}}},async getSemanticTree(){return(await ie("/api/semantic-layer/tree")).tree},async getSemanticObject(e){return ie(`/api/semantic-layer/object/${encodeURIComponent(e)}`)},async importSemanticLayer(e){return ie("/api/semantic-layer/import",{method:"POST",body:JSON.stringify(e)})},async syncSemanticLayer(){return ie("/api/semantic-layer/sync",{method:"POST",body:JSON.stringify({})})},async previewSemanticImport(e){return ie("/api/semantic-layer/import-preview",{method:"POST",body:JSON.stringify(e)})},async previewSyncDiff(){return ie("/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 ie(`/api/semantic-layer/search?${t.toString()}`)}catch{return{metrics:[],dimensions:[],hierarchies:[]}}},async getFavorites(){try{return(await ie("/api/user-prefs/favorites")).favorites}catch{return[]}},async toggleFavorite(e){return(await ie("/api/user-prefs/favorites",{method:"POST",body:JSON.stringify({name:e})})).favorites},async getRecentlyUsed(){try{return(await ie("/api/user-prefs/recent")).recentlyUsed}catch{return[]}},async trackUsage(e){try{return(await ie("/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 ie(`/api/semantic-layer/compatible-dims?${t.toString()}`)).dimensions}catch{return[]}},async composeQuery(e,t,n){try{return await ie("/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 ie("/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 ie("/api/semantic-builder/save",{method:"POST",body:JSON.stringify(e)})},async createMetric(e){try{return await ie("/api/semantic-layer/metric",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t.message??"Failed to create metric"}}},async describeTable(e){const t=e.split("."),n=t.length>1?t[t.length-1]:e,r=t.length>1?t.slice(0,-1).join("."):"",o=new URLSearchParams({table:n});r&&o.set("schema",r);try{return await ie(`/api/describe-table?${o.toString()}`)}catch{return[]}},async fetchLineage(){try{return await ie("/api/lineage")}catch{return{nodes:[],edges:[]}}},async searchLineage(e){try{return await ie(`/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 ie(`/api/lineage/query?${t.toString()}`)}catch{return{graph:{nodes:[],edges:[]},matches:[]}}},async fetchLineageNode(e){try{return await ie(`/api/lineage/node/${encodeURIComponent(e)}`)}catch{return null}},async fetchBlockLineage(e){try{return await ie(`/api/lineage/block/${encodeURIComponent(e)}`)}catch{return null}},async fetchImpactAnalysis(e){try{return await ie(`/api/lineage/impact/${encodeURIComponent(e)}`)}catch{return null}},async fetchLineagePaths(e,t){try{const n=new URLSearchParams;t!=null&&t.maxDepth&&n.set("maxDepth",String(t.maxDepth)),t!=null&&t.maxPaths&&n.set("maxPaths",String(t.maxPaths));const r=n.toString(),o=`/api/lineage/paths/${encodeURIComponent(e)}${r?`?${r}`:""}`;return await ie(o)}catch{return null}},async fetchGitStatus(){try{return await ie("/api/git/status")}catch{return{inRepo:!1,branch:null,ahead:0,behind:0,changes:[]}}},async fetchGitLog(e=20){try{return await ie(`/api/git/log?limit=${e}`)}catch{return{inRepo:!1,commits:[]}}},async fetchRunSnapshot(e){try{return await ie(`/api/run-snapshot?path=${encodeURIComponent(e)}`)}catch{return{found:!1,snapshot:null}}},async saveRunSnapshot(e,t){await ie("/api/run-snapshot",{method:"PUT",body:JSON.stringify({path:e,snapshot:t})})},async fetchGitDiff(e){try{const t=e?`?path=${encodeURIComponent(e)}`:"";return await ie(`/api/git/diff${t}`)}catch{return{inRepo:!1,diff:"",before:null,after:null,diffReport:null}}}};function d_(){const{state:e,dispatch:t}=Te(),n=e.inspectorContext;return i.jsxs("aside",{"aria-label":"Inspector",style:{width:320,borderLeft:`1px solid ${Se("borderSubtle")}`,background:Se("surfaceBase"),color:Se("textPrimary"),display:"flex",flexDirection:"column",overflow:"hidden",flexShrink:0},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:`${pe[3]}px ${pe[4]}px`,borderBottom:`1px solid ${Se("borderSubtle")}`},children:[i.jsx("div",{style:{fontSize:Fe.sm,fontWeight:Sc.semibold},children:n?u_(n):"Inspector"}),i.jsx("button",{onClick:()=>t({type:"SET_INSPECTOR",open:!1}),"aria-label":"Close inspector",style:{background:"transparent",border:"none",color:Se("textMuted"),cursor:"pointer",fontSize:Fe.md,padding:2,borderRadius:En.sm},children:"×"})]}),i.jsx("div",{style:{flex:1,overflow:"auto",padding:pe[4]},children:n?i.jsx(T_,{context:n}):i.jsx(A_,{})})]})}function u_(e){switch(e.kind){case"cell":return"Cell";case"lineage-node":return"Lineage node";case"metric":return"Metric"}}function T_({context:e}){return e.kind==="cell"?i.jsx(S_,{cellId:e.cellId}):e.kind==="lineage-node"?i.jsx(f_,{nodeId:e.nodeId}):i.jsx(R_,{name:e.name})}function S_({cellId:e}){const{state:t}=Te(),n=t.cells.find(r=>r.id===e);return n?i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:pe[3],fontSize:Fe.sm},children:[i.jsx(Ve,{label:"Type",children:n.type}),i.jsx(Ve,{label:"ID",children:i.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:n.id})}),i.jsxs(Ve,{label:"Length",children:[n.content.length," chars"]}),n.status&&i.jsx(Ve,{label:"Status",children:n.status})]}):i.jsx(Js,{children:"No matching cell in the active notebook."})}function f_({nodeId:e}){const[t,n]=f.useState(null),[r,o]=f.useState(!0);if(f.useEffect(()=>{let a=!1;return o(!0),Z.fetchLineageNode(e).then(l=>{a||(n(l),o(!1))}).catch(()=>{a||o(!1)}),()=>{a=!0}},[e]),r)return i.jsx(Js,{children:"Loading node…"});if(!t||!t.node)return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:pe[3]},children:[i.jsx(Ve,{label:"Node ID",children:i.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:e})}),i.jsx(Js,{children:"No metadata available for this node."})]});const s=t.node;return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:pe[3]},children:[i.jsx(Ve,{label:"Name",children:s.name??e}),i.jsx(Ve,{label:"Type",children:s.type}),s.domain&&i.jsx(Ve,{label:"Domain",children:s.domain}),s.layer&&i.jsx(Ve,{label:"Layer",children:s.layer}),i.jsx(Ve,{label:"Upstream",children:t.incoming.length}),i.jsx(Ve,{label:"Downstream",children:t.outgoing.length}),s.path&&i.jsx(Ve,{label:"Path",children:i.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)",fontSize:Fe.xs},children:s.path})})]})}function R_({name:e}){return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:pe[3]},children:[i.jsx(Ve,{label:"Metric",children:e}),i.jsx(Js,{children:"Definition, dimensions, and governance surface will render here."})]})}function Ve({label:e,children:t}){return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[i.jsx("div",{style:{fontSize:Fe.xs,color:Se("textMuted"),textTransform:"uppercase",letterSpacing:.5,fontWeight:Sc.medium},children:e}),i.jsx("div",{style:{fontSize:Fe.sm,color:Se("textPrimary")},children:t})]})}function Js({children:e}){return i.jsx("div",{style:{fontSize:Fe.sm,color:Se("textSecondary"),lineHeight:1.5,background:Se("surfaceSunken"),border:`1px solid ${Se("borderSubtle")}`,borderRadius:En.md,padding:pe[3]},children:e})}function A_(){return i.jsx("div",{style:{fontSize:Fe.sm,color:Se("textMuted"),lineHeight:1.5},children:"Select a cell, lineage node, or metric to inspect its details here."})}const Fr={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-sunken",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"},dd={appBg:"#0f1219",sidebarBg:"#151922",activityBarBg:"#0a0c11",headerBg:"#0f1219",headerBorder:"rgba(255,255,255,0.08)",cellBg:"#151922",cellBorder:"rgba(255,255,255,0.05)",cellBorderActive:"#5b8cff",cellBorderRunning:"#10b981",textPrimary:"#e7ebf2",textSecondary:"#9aa3b4",textMuted:"#6b7385",editorBg:"#0a0c11",editorBorder:"rgba(255,255,255,0.05)",tableBorder:"rgba(255,255,255,0.05)",tableHeaderBg:"#151922",tableRowHover:"#1c212d",accent:"#5b8cff",accentHover:"#5b8cff",success:"#10b981",error:"#ef4444",warning:"#f5b544",btnBg:"#1c212d",btnBorder:"rgba(255,255,255,0.08)",btnHover:"#1c212d",sidebarItemHover:"#1c212d",sidebarItemActive:"rgba(91,140,255,0.14)",scrollbarThumb:"rgba(255,255,255,0.14)",modalBg:"#151922",modalOverlay:"rgba(0,0,0,0.5)",inputBg:"#0a0c11",inputBorder:"rgba(255,255,255,0.05)",pillBg:"#1c212d",font:"'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontMono:"'JetBrains Mono', 'SFMono-Regular', Menlo, Monaco, Consolas, monospace",fontSerif:"'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, sans-serif"};function ud(e){if(typeof document>"u")return dd[e];const t=Fr[e];return getComputedStyle(document.documentElement).getPropertyValue(t).trim()||dd[e]}function p_(){return new Proxy({},{get(e,t){if(typeof t=="string"&&t in Fr)return ud(t)},has(e,t){return typeof t=="string"&&t in Fr},ownKeys(){return Object.keys(Fr)},getOwnPropertyDescriptor(e,t){if(!(typeof t!="string"||!(t in Fr)))return{enumerable:!0,configurable:!0,value:ud(t)}}})}const An=p_(),oe={obsidian:An,paper:An,white:An,dark:An,light:An,midnight:An,arctic:An};function et(e,t="0 0 24 24"){return function({size:r=16,strokeWidth:o=1.75,...s}){return i.jsx("svg",{width:r,height:r,viewBox:t,fill:"none",stroke:"currentColor",strokeWidth:o,strokeLinecap:"round",strokeLinejoin:"round",...s,children:e})}}const pR=et(i.jsxs(i.Fragment,{children:[i.jsx("rect",{x:"3",y:"3",width:"8",height:"8",rx:"1.5"}),i.jsx("rect",{x:"13",y:"3",width:"8",height:"8",rx:"1.5"}),i.jsx("rect",{x:"3",y:"13",width:"8",height:"8",rx:"1.5"}),i.jsx("rect",{x:"13",y:"13",width:"8",height:"8",rx:"1.5"})]}));et(i.jsxs(i.Fragment,{children:[i.jsx("path",{d:"M12 2l8 3v6c0 5-3.5 9-8 11-4.5-2-8-6-8-11V5l8-3z"}),i.jsx("path",{d:"M9 12l2 2 4-4"})]}));const h_=et(i.jsxs(i.Fragment,{children:[i.jsx("circle",{cx:"5",cy:"12",r:"2"}),i.jsx("circle",{cx:"19",cy:"5",r:"2"}),i.jsx("circle",{cx:"19",cy:"19",r:"2"}),i.jsx("path",{d:"M7 12l10-6M7 12l10 6"})]})),I_=et(i.jsxs(i.Fragment,{children:[i.jsx("ellipse",{cx:"12",cy:"5",rx:"8",ry:"3"}),i.jsx("path",{d:"M4 5v6c0 1.66 3.58 3 8 3s8-1.34 8-3V5"}),i.jsx("path",{d:"M4 11v6c0 1.66 3.58 3 8 3s8-1.34 8-3v-6"})]}));et(i.jsxs(i.Fragment,{children:[i.jsx("path",{d:"M4 4h8a8 8 0 010 16H4z"}),i.jsx("path",{d:"M16 20l4 4"})]}));const N_=et(i.jsxs(i.Fragment,{children:[i.jsx("path",{d:"M3 3v18h18"}),i.jsx("path",{d:"M7 15l4-4 4 4 5-7"})]})),O_=et(i.jsxs(i.Fragment,{children:[i.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),i.jsx("path",{d:"M3 9h18M9 3v18"})]})),m_=et(i.jsxs(i.Fragment,{children:[i.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),i.jsx("path",{d:"M8 12h8M12 8v8"})]})),C_=et(i.jsxs(i.Fragment,{children:[i.jsx("path",{d:"M4 7h16M4 12h16M4 17h10"}),i.jsx("circle",{cx:"18",cy:"17",r:"2"})]})),g_=et(i.jsx(i.Fragment,{children:i.jsx("path",{d:"M3 5h18l-7 9v5l-4-2v-3L3 5z"})}));et(i.jsxs(i.Fragment,{children:[i.jsx("path",{d:"M4 4h10l6 6v10H4z"}),i.jsx("path",{d:"M14 4v6h6"}),i.jsx("path",{d:"M8 14l3 3 5-5"})]}));const L_=et(i.jsx(i.Fragment,{children:i.jsx("path",{d:"M21 12a8 8 0 01-11.5 7.2L4 21l1.8-5.5A8 8 0 1121 12z"})})),hR=44,IR=188,NR="dql-activitybar-expanded";function __(){var e;if(typeof window>"u")return!1;try{return((e=window.localStorage)==null?void 0:e.getItem(NR))==="1"}catch{return!1}}function x_(e){var t;try{(t=window.localStorage)==null||t.setItem(NR,e?"1":"0")}catch{}}function Td({title:e,icon:t,active:n,expanded:r,onClick:o,t:s}){const[a,l]=f.useState(!1),c=i.jsxs("button",{"aria-label":e,onClick:o,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{width:r?IR-12:hR-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?s.accent+"1f":a?s.textPrimary+"0f":"transparent",border:"none",borderRadius:6,cursor:"pointer",color:n?s.accent:a?s.textPrimary:s.textSecondary,transition:"background 0.15s, color 0.15s",fontFamily:s.font,fontSize:13,fontWeight:n?500:400,textAlign:"left",overflow:"hidden",whiteSpace:"nowrap"},children:[i.jsx("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,width:18,height:18},children:t}),r&&i.jsx("span",{style:{flex:1,textOverflow:"ellipsis",overflow:"hidden"},children:e})]});return r?c:i.jsx(XS,{content:e,side:"right",children:c})}function y_(){const{state:e,dispatch:t}=Te(),n=oe[e.themeMode],[r,o]=f.useState(__);f.useEffect(()=>{x_(r)},[r]);function s(c){if(c==="connection"||c==="reference"){t({type:"SET_SIDEBAR_PANEL",panel:c});return}e.sidebarPanel===c&&e.sidebarOpen?t({type:"TOGGLE_SIDEBAR"}):t({type:"SET_SIDEBAR_PANEL",panel:c})}const a=[{key:"files",title:"Files",icon:i.jsx(SR,{size:16,strokeWidth:1.75}),active:e.sidebarPanel==="files"&&e.sidebarOpen},{key:"schema",title:"Schema",icon:i.jsx(TR,{size:16,strokeWidth:1.75}),active:e.sidebarPanel==="schema"&&e.sidebarOpen},{key:"block_library",title:"Block Library",icon:i.jsx(pR,{size:16}),active:e.sidebarPanel==="block_library"&&e.sidebarOpen},{key:"apps",title:"Apps",icon:i.jsx($L,{size:16,strokeWidth:1.75}),active:e.sidebarPanel==="apps"&&e.sidebarOpen},{key:"lineage",title:"Lineage",icon:i.jsx(h_,{size:16}),active:e.sidebarPanel==="lineage"&&e.sidebarOpen},{key:"git",title:"Git",icon:i.jsx(fR,{size:16,strokeWidth:1.75}),active:e.sidebarPanel==="git"&&e.sidebarOpen},{key:"connection",title:"Connections",icon:i.jsx(RR,{size:16,strokeWidth:1.75}),active:e.mainView==="connection"}],l=[{key:"reference",title:"Reference",icon:i.jsx(uR,{size:16,strokeWidth:1.75}),active:e.mainView==="reference",onClick:()=>s("reference")},{key:"help",title:"Help",icon:i.jsx(LL,{size:16,strokeWidth:1.75}),active:!1,onClick:()=>s("reference")},{key:"settings",title:"Settings",icon:i.jsx(ZL,{size:16,strokeWidth:1.75}),active:!1,onClick:()=>{}}];return i.jsxs("div",{style:{width:r?IR:hR,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:[i.jsx("div",{style:{display:"flex",justifyContent:r?"flex-end":"center",paddingLeft:r?6:0,paddingRight:r?6:0,marginBottom:4},children:i.jsx(XS,{content:r?"Collapse":"Expand",side:"right",children:i.jsx("button",{"aria-label":r?"Collapse sidebar rail":"Expand sidebar rail",onClick:()=>o(c=>!c),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:c=>{c.currentTarget.style.color=n.textPrimary,c.currentTarget.style.background=n.textPrimary+"0f"},onMouseLeave:c=>{c.currentTarget.style.color=n.textMuted,c.currentTarget.style.background="transparent"},children:r?i.jsx(OL,{size:14,strokeWidth:2}):i.jsx(CL,{size:14,strokeWidth:2})})})}),a.map(c=>i.jsx(Td,{title:c.title,icon:c.icon,active:c.active,expanded:r,onClick:()=>s(c.key),t:n},c.key)),i.jsx("div",{style:{flex:1}}),l.map(c=>i.jsx(Td,{title:c.title,icon:c.icon,active:c.active,expanded:r,onClick:c.onClick,t:n},c.key))]})}const ya={notebooks:"Notebooks",blocks:"Blocks",dashboards:"Dashboards"},D_={notebooks:!1,blocks:!1,dashboards:!0};function M_({type:e}){switch(e){case"notebook":return i.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:i.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 i.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:i.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 i.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:i.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 P_({expanded:e}){return i.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:e?i.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"}):i.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 b_(e){return e.name.replace(/\.(dqlnb|dql)$/,"")}function v_({onOpenFile:e}){const{state:t,dispatch:n}=Te(),r=oe[t.themeMode],[o,s]=f.useState({notebooks:!0,blocks:!1,dashboards:!1}),[a,l]=f.useState(!1),c={notebooks:[],blocks:[],dashboards:[]};for(const u of t.files){const T=u.folder.toLowerCase();T in c&&c[T].push(u)}const E=u=>{s(T=>({...T,[u]:!T[u]}))},d=i.jsx("div",{style:{padding:"0 8px 8px"},children:i.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:[i.jsx("span",{style:{fontSize:16,lineHeight:1},children:"+"}),"New Notebook"]})});return i.jsxs(Bt,{title:"Files",bodyPadding:0,children:[d,t.filesLoading&&i.jsx("div",{style:{padding:"8px 14px",color:r.textMuted,fontSize:12,fontFamily:r.font},children:"Loading files…"}),Object.keys(ya).map(u=>{const T=c[u];if(D_[u]&&T.length===0)return null;const S=o[u],h=u==="notebooks"?()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}):u==="blocks"?()=>n({type:"OPEN_NEW_BLOCK_MODAL"}):void 0;return i.jsxs("div",{children:[i.jsx(U_,{label:ya[u],count:T.length,expanded:S,onToggle:()=>E(u),onAdd:h,t:r}),S&&i.jsx("div",{children:T.length===0?i.jsxs("div",{style:{padding:"4px 14px 4px 32px",fontSize:12,color:r.textMuted,fontFamily:r.font,fontStyle:"italic"},children:["No ",ya[u].toLowerCase()]}):T.map(A=>{var R;return i.jsx(w_,{file:A,active:((R=t.activeFile)==null?void 0:R.path)===A.path,onClick:()=>e(A),t:r},A.path)})})]},u)})]})}function U_({label:e,count:t,expanded:n,onToggle:r,onAdd:o,t:s}){const[a,l]=f.useState(!1),[c,E]=f.useState(!1);return i.jsxs("div",{onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{display:"flex",alignItems:"center",background:a?s.sidebarItemHover:"transparent",transition:"background 0.1s"},children:[i.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:s.textSecondary,fontSize:11,fontWeight:600,fontFamily:s.font,letterSpacing:"0.04em",textTransform:"uppercase",textAlign:"left"},children:[i.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:i.jsx("path",{d:"M3 2l4 3-4 3V2Z"})}),i.jsx(P_,{expanded:n}),i.jsx("span",{style:{flex:1},children:e}),t>0&&i.jsx("span",{style:{background:s.pillBg,color:s.textMuted,borderRadius:10,padding:"0 5px",fontSize:10,fontWeight:500},children:t})]}),o&&a&&i.jsx("button",{onClick:d=>{d.stopPropagation(),o()},onMouseEnter:()=>E(!0),onMouseLeave:()=>E(!1),title:`New ${e.slice(0,-1)}`,style:{background:c?s.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:c?s.accent:s.textMuted,fontSize:14,lineHeight:1,padding:"2px 8px",marginRight:4,flexShrink:0,transition:"color 0.1s"},children:"+"})]})}function w_({file:e,active:t,onClick:n,t:r}){const[o,s]=f.useState(!1);return i.jsxs("button",{onClick:n,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 8px 4px 26px",background:t?r.sidebarItemActive:o?r.sidebarItemHover:"transparent",border:"none",borderLeft:t?`2px solid ${r.accent}`:"2px solid transparent",cursor:"pointer",color:t||o?r.textPrimary:r.textSecondary,fontSize:13,fontFamily:r.font,textAlign:"left",transition:"background 0.1s, color 0.1s",overflow:"hidden"},children:[i.jsx("span",{style:{flexShrink:0,color:t?r.accent:r.textMuted},children:i.jsx(M_,{type:e.type})}),i.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:b_(e)}),e.isNew&&i.jsx("span",{style:{fontSize:9,fontWeight:600,color:r.accent,background:r.sidebarItemActive,borderRadius:4,padding:"1px 4px",flexShrink:0},children:"NEW"})]})}const B_={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 kl(e,t){const n=e.toLowerCase().split("(")[0].trim();return B_[n]??t}function F_({t:e}){return i.jsxs("div",{style:{padding:"8px 12px",display:"flex",flexDirection:"column",gap:8},children:[[1,2,3].map(t=>i.jsx("div",{style:{height:28,borderRadius:4,background:e.pillBg,opacity:.6,animation:"pulse 1.5s ease-in-out infinite"}},t)),i.jsx("style",{children:"@keyframes pulse { 0%,100%{opacity:.6} 50%{opacity:.3} }"})]})}function G_(){const{state:e,dispatch:t}=Te(),n=oe[e.themeMode],[r,o]=f.useState(!1),[s,a]=f.useState(""),l=async()=>{t({type:"SET_SCHEMA_LOADING",loading:!0});try{const h=await Z.getSchema();t({type:"SET_SCHEMA",tables:h})}catch(h){console.error("Schema refresh failed:",h)}finally{t({type:"SET_SCHEMA_LOADING",loading:!1})}},c=f.useMemo(()=>{const h=s.trim().toLowerCase();return h?e.schemaTables.filter(A=>{const R=[A.name,A.path,A.objectType].filter(N=>!!N).some(N=>N.toLowerCase().includes(h)),p=A.columns.some(N=>N.name.toLowerCase().includes(h)||N.type.toLowerCase().includes(h));return R||p}):e.schemaTables},[s,e.schemaTables]),E=f.useMemo(()=>{const h=new Map;for(const A of c){const[R,...p]=A.name.split("."),N=p.length>0?R:A.source==="file"?"files":"default",I=h.get(N)??[];I.push(A),h.set(N,I)}return Array.from(h.entries()).sort((A,R)=>A[0].localeCompare(R[0]))},[c]),d={schemas:E.length,tables:e.schemaTables.length,columns:e.schemaTables.reduce((h,A)=>h+A.columns.length,0)},u={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"},T=i.jsxs("button",{onClick:l,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!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:[i.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"]}),S=i.jsx(No,{children:i.jsx("input",{value:s,onChange:h=>a(h.target.value),placeholder:"Search schemas, tables, columns...",style:{...u,flex:1,minWidth:100}})});return i.jsxs(Bt,{title:"Database Catalog",subtitle:"Schemas, tables, views, and columns from the active connection.",actions:T,toolbar:S,bodyPadding:0,children:[i.jsxs("div",{style:{padding:10,borderBottom:`1px solid ${n.headerBorder}`,display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:8},children:[i.jsx(Da,{label:"Schemas",value:d.schemas,t:n}),i.jsx(Da,{label:"Tables",value:d.tables,t:n}),i.jsx(Da,{label:"Columns",value:d.columns,t:n})]}),e.schemaLoading?i.jsx(F_,{t:n}):e.schemaTables.length===0?i.jsx(bt,{title:"No tables found",description:"Connect a data source to explore schema."}):c.length===0?i.jsx(bt,{title:"No matches",description:"No database objects match the current search."}):i.jsx("div",{style:{overflow:"auto",flex:1},children:E.map(([h,A])=>i.jsxs("div",{children:[i.jsxs("div",{style:{padding:"8px 10px 4px",fontSize:10,fontWeight:700,color:n.textMuted,fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.05em"},children:[h," · ",A.length]}),A.map(R=>i.jsx(H_,{table:R,t:n},R.name))]},h))})]})}function Da({label:e,value:t,t:n}){return i.jsxs("div",{style:{background:n.cellBg,border:`1px solid ${n.headerBorder}`,borderRadius:8,padding:"8px 10px"},children:[i.jsx("div",{style:{fontSize:9,fontWeight:700,color:n.textMuted,fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.05em"},children:e}),i.jsx("div",{style:{fontSize:18,fontWeight:700,color:n.textPrimary,fontFamily:n.font,marginTop:2},children:t})]})}function H_({table:e,t}){var c;const{dispatch:n}=Te(),[r,o]=f.useState(!1),[s,a]=f.useState(!1),l=async()=>{if(n({type:"TOGGLE_SCHEMA_TABLE",tableName:e.name}),!e.expanded&&e.columns.length===0){a(!0);try{const E=await Z.describeTable(e.path);E.length>0&&n({type:"SET_TABLE_COLUMNS",tableName:e.name,columns:E})}catch(E){console.error("describeTable failed:",E)}finally{a(!1)}}};return i.jsxs("div",{children:[i.jsxs("button",{onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onClick:l,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"5px 10px",background:r?t.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:t.textPrimary,fontSize:12,fontFamily:t.font,fontWeight:500,textAlign:"left",transition:"background 0.1s"},children:[i.jsx("svg",{width:"10",height:"10",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:i.jsx("path",{d:"M3 2l4 3-4 3V2Z"})}),e.source==="database"?i.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",style:{color:"#56d364",flexShrink:0},children:i.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"})}):i.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",style:{color:t.accent,flexShrink:0},children:i.jsx("path",{d:"M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v1.5A1.75 1.75 0 0 1 14.25 5H1.75A1.75 1.75 0 0 1 0 3.25Zm1.75-.25a.25.25 0 0 0-.25.25v1.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25v-1.5a.25.25 0 0 0-.25-.25Zm-1.75 6C0 6.784.784 6 1.75 6h12.5c.966 0 1.75.784 1.75 1.75v1.5A1.75 1.75 0 0 1 14.25 11H1.75A1.75 1.75 0 0 1 0 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v1.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25v-1.5a.25.25 0 0 0-.25-.25Zm-1.75 6c0-.966.784-1.75 1.75-1.75h12.5c.966 0 1.75.784 1.75 1.75v1.5A1.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.25v1.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25v-1.5a.25.25 0 0 0-.25-.25Z"})}),i.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),e.objectType&&i.jsx("span",{style:{fontSize:9,fontFamily:t.fontMono,color:t.accent,background:`${t.accent}18`,borderRadius:4,padding:"1px 4px",flexShrink:0},children:e.objectType.toLowerCase().includes("view")?"view":"table"}),((c=e.governance)==null?void 0:c.status)&&i.jsx(Y_,{status:e.governance.status,t}),e.columns.length>0&&i.jsx("span",{style:{fontSize:10,color:t.textMuted,background:t.pillBg,borderRadius:8,padding:"1px 5px",flexShrink:0},children:e.columns.length})]}),e.expanded&&i.jsxs("div",{style:{paddingLeft:26},children:[e.governance&&(e.governance.owner||e.governance.domain)&&i.jsxs("div",{style:{padding:"3px 10px",display:"flex",gap:8,flexWrap:"wrap"},children:[e.governance.domain&&i.jsxs("span",{style:{fontSize:9,fontFamily:t.font,color:t.textMuted},children:[i.jsx("span",{style:{fontWeight:600},children:"domain:"})," ",e.governance.domain]}),e.governance.owner&&i.jsxs("span",{style:{fontSize:9,fontFamily:t.font,color:t.textMuted},children:[i.jsx("span",{style:{fontWeight:600},children:"owner:"})," ",e.governance.owner]})]}),s?i.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:"..."}):e.columns.length===0?i.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:"No columns"}):e.columns.map(E=>i.jsx(k_,{col:E,t},E.name))]})]})}function k_({col:e,t}){const[n,r]=f.useState(!1);return i.jsxs("div",{onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),style:{display:"flex",alignItems:"center",gap:8,padding:"3px 10px 3px 8px",background:n?t.sidebarItemHover:"transparent",cursor:"default",transition:"background 0.1s"},children:[i.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",style:{color:t.textMuted,flexShrink:0},children:i.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"})}),i.jsx("span",{style:{flex:1,fontSize:11,fontFamily:t.fontMono,color:t.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),i.jsx("span",{style:{fontSize:10,fontFamily:t.fontMono,color:kl(e.type,t.accent),background:`${kl(e.type,t.accent)}18`,borderRadius:4,padding:"1px 5px",flexShrink:0},children:e.type.toLowerCase()})]})}const j_={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 Y_({status:e,t}){const n=j_[e];return n?i.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 jl={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"},Ma={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"},W_={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"]},V_=[{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 mR(){const{state:e}=Te(),t=oe[e.themeMode],[n,r]=f.useState(null),[o,s]=f.useState(!1),[a,l]=f.useState(null),[c,E]=f.useState(null),[d,u]=f.useState(!1),[T,S]=f.useState(!1),[h,A]=f.useState(null),[R,p]=f.useState(""),[N,I]=f.useState("duckdb"),[O,m]=f.useState({});f.useEffect(()=>{Z.getConnections().then(M=>{r(M),Object.keys(M.connections).length>0&&Z.testConnection().then(l)})},[]);const C=async()=>{s(!0),l(null);const M=await Z.testConnection();l(M),s(!1)},g=(M,B)=>{E(M),u(!1),p(M),I((B==null?void 0:B.driver)??"duckdb");const v={};Object.entries(B??{}).forEach(([L,U])=>{L!=="driver"&&L!=="type"&&(v[L]=String(U??""))}),m(v)},y=()=>{u(!0),E(null),p(""),I("duckdb"),m({})},_=()=>{E(null),u(!1)},P=async()=>{if(!n)return;S(!0),A(null);const M=R.trim()||(c??"default"),B={driver:N};Object.entries(O).forEach(([L,U])=>{U.trim()&&(L==="port"&&!isNaN(Number(U))?B[L]=Number(U):B[L]=U)});const v={...n.connections};c&&c!==M&&delete v[c],v[M]=B;try{await Z.saveConnections(v);const L=await Z.getConnections();r(L),A("Saved"),setTimeout(()=>A(null),2e3),E(null),u(!1);try{s(!0);const U=await Z.testConnection();l(U)}catch{}finally{s(!1)}}catch(L){A(`Error: ${L.message}`)}finally{S(!1)}},D=async M=>{if(!n)return;const B={...n.connections};delete B[M],S(!0);try{await Z.saveConnections(B);const v=await Z.getConnections();r(v),E(null)}finally{S(!1)}},b={fontSize:10,fontWeight:600,letterSpacing:"0.07em",textTransform:"uppercase",color:t.textMuted,fontFamily:t.font,marginBottom:6},F={background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:7,padding:"10px 12px",marginBottom:10},x=(n==null?void 0:n.connections)??{},w=(n==null?void 0:n.default)??"";return i.jsxs(Bt,{title:"Connections",bodyPadding:12,children:[a&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"6px 10px",marginBottom:10,borderRadius:6,background:a.ok?`${t.success}12`:`${t.error}12`,border:`1px solid ${a.ok?t.success:t.error}30`},children:[i.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:a.ok?t.success:t.error,flexShrink:0}}),i.jsx("span",{style:{fontSize:11,fontFamily:t.font,color:a.ok?t.success:t.error},children:a.ok?"Connected":"Disconnected"})]}),i.jsx("div",{style:b,children:"Connections"}),n===null?i.jsx("div",{style:{fontSize:12,color:t.textMuted,fontFamily:t.font},children:"Loading…"}):Object.entries(x).map(([M,B])=>{const v=(B==null?void 0:B.driver)??(B==null?void 0:B.type)??"unknown",L=M===w||Object.keys(x).length===1,U=Ma[v]??t.accent;return c===M?i.jsx(Sd,{t,editName:R,setEditName:p,editDriver:N,setEditDriver:I,editFields:O,setEditFields:m,onSave:P,onCancel:_,onDelete:()=>D(M),saving:T,isNew:!1},M):i.jsxs("div",{style:{...F,borderLeft:L?`3px solid ${U}`:`1px solid ${t.cellBorder}`},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6},children:[i.jsx("span",{style:{fontSize:10,fontWeight:700,fontFamily:t.fontMono,color:U,background:`${U}18`,border:`1px solid ${U}40`,borderRadius:4,padding:"1px 6px",letterSpacing:"0.05em",textTransform:"uppercase"},children:jl[v]??v}),i.jsx("span",{style:{fontSize:11,fontFamily:t.fontMono,color:t.textSecondary,fontWeight:500},children:M}),L&&i.jsx("span",{style:{fontSize:9,color:t.accent,fontFamily:t.font,fontWeight:600},children:"DEFAULT"}),i.jsx("div",{style:{flex:1}}),i.jsx("button",{onClick:()=>g(M,B),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"})]}),i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:3},children:Object.entries(B??{}).filter(([G])=>G!=="driver"&&G!=="type").map(([G,k])=>i.jsxs("div",{style:{display:"flex",gap:6,alignItems:"baseline"},children:[i.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.fontMono,minWidth:70,flexShrink:0},children:G}),i.jsx("span",{style:{fontSize:11,color:t.textSecondary,fontFamily:t.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:G.toLowerCase().includes("password")||G.toLowerCase().includes("token")?"••••••••":String(k)})]},G))})]},M)}),!d&&!c&&Object.keys(x).length===0&&i.jsxs(i.Fragment,{children:[i.jsx("div",{style:{...b,marginTop:8},children:"Quick Connect"}),i.jsx("div",{style:{display:"grid",gap:6,marginBottom:12},children:V_.map(M=>i.jsxs("button",{onClick:async()=>{S(!0);try{const B={...x,[M.name]:M.config};await Z.saveConnections(B);const v=await Z.getConnections();r(v),s(!0);const L=await Z.testConnection();l(L),s(!1)}finally{S(!1)}},disabled:T,style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:7,cursor:T?"not-allowed":"pointer",textAlign:"left",transition:"border-color 0.15s"},children:[i.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:Ma[M.config.driver]??t.accent,flexShrink:0}}),i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:12,fontWeight:600,color:t.textPrimary,fontFamily:t.font},children:M.label}),i.jsx("div",{style:{fontSize:10,color:t.textMuted,fontFamily:t.font},children:M.description})]})]},M.name))})]}),d?i.jsx(Sd,{t,editName:R,setEditName:p,editDriver:N,setEditDriver:I,editFields:O,setEditFields:m,onSave:P,onCancel:_,saving:T,isNew:!0}):i.jsxs("button",{onClick:y,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:[i.jsx("span",{style:{fontSize:16,lineHeight:1},children:"+"}),"Add Connection"]}),h&&i.jsx("div",{style:{fontSize:11,fontFamily:t.font,padding:"4px 10px",borderRadius:4,marginBottom:8,color:h.startsWith("Error")?t.error:t.success,background:h.startsWith("Error")?`${t.error}12`:`${t.success}12`},children:h}),i.jsx("button",{onClick:C,disabled:o,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:o?"not-allowed":"pointer",marginBottom:8,opacity:o?.7:1,transition:"all 0.15s"},children:o?"Testing…":"Test Connection"}),a&&i.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]}),i.jsx("div",{style:{...b,marginTop:4},children:"Supported Drivers"}),i.jsx("div",{style:{...F,display:"flex",flexDirection:"column",gap:4},children:Object.entries(jl).map(([M,B])=>i.jsxs("div",{style:{display:"flex",gap:8,alignItems:"baseline"},children:[i.jsx("code",{style:{fontSize:10,fontFamily:t.fontMono,color:Ma[M]??t.textMuted,minWidth:80,flexShrink:0},children:M}),i.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.font},children:B})]},M))})]})}function Sd({t:e,editName:t,setEditName:n,editDriver:r,setEditDriver:o,editFields:s,setEditFields:a,onSave:l,onCancel:c,onDelete:E,saving:d,isNew:u}){const T=W_[r]??[],S={background:e.inputBg,border:`1px solid ${e.inputBorder}`,borderRadius:4,color:e.textPrimary,fontSize:11,fontFamily:e.fontMono,padding:"4px 8px",outline:"none",width:"100%"},h={fontSize:9,fontWeight:600,color:e.textMuted,fontFamily:e.font,letterSpacing:"0.05em",textTransform:"uppercase",marginBottom:2};return i.jsxs("div",{style:{background:e.cellBg,border:`1px solid ${e.accent}40`,borderRadius:7,padding:"10px 12px",marginBottom:10},children:[i.jsx("div",{style:{fontSize:11,fontWeight:600,color:e.accent,fontFamily:e.font,marginBottom:8},children:u?"New Connection":"Edit Connection"}),i.jsxs("div",{style:{marginBottom:6},children:[i.jsx("div",{style:h,children:"Name"}),i.jsx("input",{style:S,value:t,onChange:A=>n(A.target.value),placeholder:"e.g. production"})]}),i.jsxs("div",{style:{marginBottom:6},children:[i.jsx("div",{style:h,children:"Driver"}),i.jsx("select",{style:{...S,fontFamily:e.font},value:r,onChange:A=>{o(A.target.value),a({})},children:Object.entries(jl).map(([A,R])=>i.jsx("option",{value:A,children:R},A))})]}),T.map(A=>i.jsxs("div",{style:{marginBottom:6},children:[i.jsx("div",{style:h,children:A}),i.jsx("input",{style:S,type:A.toLowerCase().includes("password")||A.toLowerCase().includes("token")?"password":"text",value:s[A]??"",placeholder:A==="port"?"5432":A==="filepath"?":memory:":"",onChange:R=>a({...s,[A]:R.target.value})})]},A)),i.jsxs("div",{style:{display:"flex",gap:6,marginTop:8},children:[i.jsx("button",{onClick:l,disabled:d,style:{flex:1,padding:"5px 0",borderRadius:5,border:"none",background:e.accent,color:"#fff",fontSize:11,fontFamily:e.font,fontWeight:600,cursor:d?"not-allowed":"pointer",opacity:d?.6:1},children:d?"Saving…":"Save"}),i.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"}),E&&!u&&i.jsx("button",{onClick:E,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 _t({title:e,defaultOpen:t=!1,children:n,t:r}){const[o,s]=f.useState(t),[a,l]=f.useState(!1);return i.jsxs("div",{style:{borderBottom:`1px solid ${r.headerBorder}`},children:[i.jsxs("button",{onClick:()=>s(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:[i.jsx("span",{style:{fontSize:9,color:r.textMuted,display:"inline-block",transition:"transform 0.15s",transform:o?"rotate(90deg)":"rotate(0deg)",lineHeight:1},children:"▶"}),i.jsx("span",{style:{fontSize:11,fontWeight:600,fontFamily:r.font,color:r.textSecondary,letterSpacing:"0.04em"},children:e})]}),o&&i.jsx("div",{style:{padding:"4px 12px 10px"},children:n})]})}function $_({code:e,t}){const[n,r]=f.useState(!1);async function o(){try{await navigator.clipboard.writeText(e)}catch{const s=document.createElement("textarea");s.value=e,document.body.appendChild(s),s.select(),document.execCommand("copy"),document.body.removeChild(s)}r(!0),setTimeout(()=>r(!1),1500)}return i.jsx("button",{onClick:o,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 Pe({code:e,t}){return i.jsxs("div",{style:{position:"relative",marginTop:6},children:[i.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}),i.jsx($_,{code:e,t})]})}function fd({rows:e,t}){return i.jsx("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11,fontFamily:t.font,marginTop:6},children:i.jsx("tbody",{children:e.map(([n,r],o)=>i.jsxs("tr",{style:{borderBottom:`1px solid ${t.tableBorder}`},children:[i.jsx("td",{style:{padding:"5px 6px 5px 0",fontFamily:t.fontMono,fontSize:11,color:t.accent,whiteSpace:"nowrap",verticalAlign:"top",width:"45%"},children:n}),i.jsx("td",{style:{padding:"5px 0",color:t.textSecondary,verticalAlign:"top",lineHeight:1.5},children:r})]},o))})})}const X_=`block "Revenue by Channel" {
|
|
224
|
-
domain = "revenue"
|
|
225
|
-
type = "custom"
|
|
226
|
-
description = "Revenue grouped by sales channel"
|
|
227
|
-
owner = "data-team"
|
|
228
|
-
tags = ["revenue"]
|
|
229
|
-
|
|
230
|
-
params {
|
|
231
|
-
period = "current_quarter"
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
query = """
|
|
235
|
-
SELECT channel,
|
|
236
|
-
SUM(order_total) AS revenue
|
|
237
|
-
FROM read_csv_auto('data/orders.csv')
|
|
238
|
-
WHERE fiscal_period = \${period}
|
|
239
|
-
GROUP BY channel
|
|
240
|
-
ORDER BY revenue DESC
|
|
241
|
-
"""
|
|
242
|
-
|
|
243
|
-
visualization {
|
|
244
|
-
chart = "bar"
|
|
245
|
-
x = channel
|
|
246
|
-
y = revenue
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
tests {
|
|
250
|
-
assert row_count > 0
|
|
251
|
-
}
|
|
252
|
-
}`,K_=`# semantic-layer/metrics/total_revenue.yaml
|
|
253
|
-
name: total_revenue
|
|
254
|
-
label: Total Revenue
|
|
255
|
-
description: Sum of all recognized revenue.
|
|
256
|
-
domain: finance
|
|
257
|
-
sql: SUM(amount)
|
|
258
|
-
type: sum # sum|count|count_distinct|avg|min|max|custom
|
|
259
|
-
table: fct_revenue
|
|
260
|
-
tags:
|
|
261
|
-
- revenue
|
|
262
|
-
- kpi`,z_=`# semantic-layer/dimensions/segment.yaml
|
|
263
|
-
name: segment
|
|
264
|
-
label: Customer Segment
|
|
265
|
-
description: Customer segment tier.
|
|
266
|
-
sql: segment_tier
|
|
267
|
-
type: string # string|number|date|boolean
|
|
268
|
-
table: fct_revenue`,J_=`# semantic-layer/hierarchies/time.yaml
|
|
269
|
-
name: fiscal_time
|
|
270
|
-
label: Fiscal Time
|
|
271
|
-
description: Drill from year to quarter.
|
|
272
|
-
domain: finance
|
|
273
|
-
levels:
|
|
274
|
-
- name: fiscal_year
|
|
275
|
-
dimension: fiscal_year
|
|
276
|
-
order: 1
|
|
277
|
-
- name: fiscal_quarter
|
|
278
|
-
dimension: fiscal_quarter
|
|
279
|
-
order: 2
|
|
280
|
-
defaultRollup: sum`,q_=`# semantic-layer/cubes/revenue_cube.yaml
|
|
281
|
-
name: revenue
|
|
282
|
-
label: Revenue Cube
|
|
283
|
-
table: fct_revenue
|
|
284
|
-
domain: finance
|
|
285
|
-
|
|
286
|
-
measures:
|
|
287
|
-
- name: total_revenue
|
|
288
|
-
sql: SUM(amount)
|
|
289
|
-
type: sum
|
|
290
|
-
- name: deal_count
|
|
291
|
-
sql: COUNT(*)
|
|
292
|
-
type: count
|
|
293
|
-
|
|
294
|
-
dimensions:
|
|
295
|
-
- name: segment_tier
|
|
296
|
-
sql: segment_tier
|
|
297
|
-
type: string
|
|
298
|
-
|
|
299
|
-
time_dimensions:
|
|
300
|
-
- name: recognized_at
|
|
301
|
-
sql: recognized_at
|
|
302
|
-
primary_time: true
|
|
303
|
-
granularities: [day, month, quarter, year]
|
|
304
|
-
|
|
305
|
-
joins:
|
|
306
|
-
- name: customers
|
|
307
|
-
type: left
|
|
308
|
-
sql: "\${left}.customer_id = \${right}.id"`,Q_=`{
|
|
309
|
-
"semanticLayer": {
|
|
310
|
-
"provider": "dql"
|
|
311
|
-
}
|
|
312
|
-
}`,Z_=`{
|
|
313
|
-
"semanticLayer": {
|
|
314
|
-
"provider": "dbt",
|
|
315
|
-
"projectPath": "/path/to/your/dbt-project"
|
|
316
|
-
}
|
|
317
|
-
}`,ex=`{
|
|
318
|
-
"semanticLayer": {
|
|
319
|
-
"provider": "cubejs",
|
|
320
|
-
"projectPath": "/path/to/your/cube-project"
|
|
321
|
-
}
|
|
322
|
-
}`,tx=`{
|
|
323
|
-
"defaultConnection": {
|
|
324
|
-
"driver": "file",
|
|
325
|
-
"filepath": ":memory:"
|
|
326
|
-
}
|
|
327
|
-
}`,nx=`{
|
|
328
|
-
"defaultConnection": {
|
|
329
|
-
"driver": "snowflake",
|
|
330
|
-
"account": "acme.snowflakecomputing.com",
|
|
331
|
-
"username": "your_user",
|
|
332
|
-
"password": "\${SNOWFLAKE_PASSWORD}",
|
|
333
|
-
"database": "ANALYTICS",
|
|
334
|
-
"schema": "PUBLIC",
|
|
335
|
-
"warehouse": "COMPUTE_WH",
|
|
336
|
-
"role": "ANALYST"
|
|
337
|
-
}
|
|
338
|
-
}`,rx=`{
|
|
339
|
-
"defaultConnection": {
|
|
340
|
-
"driver": "bigquery",
|
|
341
|
-
"project": "your-gcp-project-id",
|
|
342
|
-
"dataset": "analytics",
|
|
343
|
-
"keyFilename": "./service-account.json"
|
|
344
|
-
}
|
|
345
|
-
}`,ox=`{
|
|
346
|
-
"defaultConnection": {
|
|
347
|
-
"driver": "postgres",
|
|
348
|
-
"host": "localhost",
|
|
349
|
-
"port": 5432,
|
|
350
|
-
"database": "analytics",
|
|
351
|
-
"username": "your_user",
|
|
352
|
-
"password": "\${POSTGRES_PASSWORD}"
|
|
353
|
-
}
|
|
354
|
-
}`,sx=`-- Primary workflow: use Compose Query in the Semantic Layer panel
|
|
355
|
-
-- 1. Pick metrics + dimensions (+ optional time dimension)
|
|
356
|
-
-- 2. Click "Compose SQL"
|
|
357
|
-
-- 3. Click "+ Insert as Cell" → edit and run
|
|
358
|
-
|
|
359
|
-
-- Advanced: reference metrics inline in any SQL cell
|
|
360
|
-
-- DQL resolves @metric() and @dim() at query time
|
|
361
|
-
SELECT
|
|
362
|
-
@dim(segment_tier),
|
|
363
|
-
@metric(total_revenue)
|
|
364
|
-
FROM fct_revenue
|
|
365
|
-
GROUP BY @dim(segment_tier)
|
|
366
|
-
ORDER BY @metric(total_revenue) DESC`,ix=`{
|
|
367
|
-
"semanticLayer": {
|
|
368
|
-
"provider": "snowflake",
|
|
369
|
-
"projectPath": "MY_DATABASE"
|
|
370
|
-
}
|
|
371
|
-
}`;function CR({themeMode:e}){const t=oe[e];return i.jsxs(Bt,{title:"Reference",subtitle:"Quick syntax, operators, and cell reference.",bodyPadding:0,children:[i.jsx(_t,{title:"SQL Essentials",defaultOpen:!0,t,children:i.jsx(Pe,{t,code:`-- Basic select
|
|
372
|
-
SELECT col1, col2
|
|
373
|
-
FROM table_name
|
|
374
|
-
WHERE condition
|
|
375
|
-
ORDER BY col1 DESC
|
|
376
|
-
LIMIT 100
|
|
377
|
-
|
|
378
|
-
-- GROUP BY
|
|
379
|
-
SELECT col, COUNT(*), SUM(val)
|
|
380
|
-
FROM table_name
|
|
381
|
-
GROUP BY col
|
|
382
|
-
|
|
383
|
-
-- JOIN
|
|
384
|
-
SELECT a.*, b.col
|
|
385
|
-
FROM table_a AS a
|
|
386
|
-
JOIN table_b AS b ON a.id = b.id
|
|
387
|
-
|
|
388
|
-
-- CTE (WITH)
|
|
389
|
-
WITH cte AS (
|
|
390
|
-
SELECT * FROM table_name WHERE val > 0
|
|
391
|
-
)
|
|
392
|
-
SELECT * FROM cte
|
|
393
|
-
|
|
394
|
-
-- Window function
|
|
395
|
-
SELECT *,
|
|
396
|
-
ROW_NUMBER() OVER (
|
|
397
|
-
PARTITION BY group_col
|
|
398
|
-
ORDER BY val DESC
|
|
399
|
-
) AS rank
|
|
400
|
-
FROM table_name`})}),i.jsx(_t,{title:"DuckDB Functions",defaultOpen:!1,t,children:i.jsx(fd,{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"]]})}),i.jsxs(_t,{title:"DQL Block Structure",defaultOpen:!0,t,children:[i.jsx(Pe,{t,code:X_}),i.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.6},children:["Run ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql certify <file> --connection duckdb"})," to execute ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"tests {}"})," assertions against live data. Use ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"--skip-tests"})," to check governance fields only."]})]}),i.jsxs(_t,{title:"DQL Chart Types",defaultOpen:!1,t,children:[i.jsx(fd,{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)"]]}),i.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.6},children:["Set chart type inside the"," ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:'visualization { chart = "pie"; x = label_col; y = value_col }'})," ","block."]})]}),i.jsxs(_t,{title:"Semantic Layer Usage",defaultOpen:!1,t,children:[i.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:6},children:["Primary workflow: open the ",i.jsx("strong",{children:"Semantic Layer"})," panel → Compose Query → pick metrics and dimensions → Compose SQL → + Insert as Cell. Advanced: use ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"@metric(name)"})," and ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"@dim(name)"})," refs directly in any SQL cell."]}),i.jsx(Pe,{t,code:sx})]}),i.jsxs(_t,{title:"Semantic Layer",defaultOpen:!1,t,children:[i.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"," ",i.jsx("strong",{style:{color:t.textPrimary},children:"Semantic Layer"})," sidebar panel."]}),i.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"10px 0 4px",letterSpacing:"0.03em"},children:"Directory Structure"}),i.jsx(Pe,{t,code:`my-project/
|
|
401
|
-
├── dql.config.json
|
|
402
|
-
└── semantic-layer/
|
|
403
|
-
├── metrics/ ← one YAML per metric
|
|
404
|
-
├── dimensions/ ← one YAML per dimension
|
|
405
|
-
├── hierarchies/ ← optional drill paths
|
|
406
|
-
└── cubes/ ← optional (groups all into one)`}),i.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:[i.jsx("strong",{style:{color:t.textPrimary},children:"Recommended:"})," For multi-table projects, use a ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"cubes/"})," file — it keeps metrics, dimensions, and joins together. Use standalone ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"metrics/"})," and ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dimensions/"})," files only for simple single-table projects."]}),i.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Metric YAML"}),i.jsx(Pe,{t,code:K_}),i.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Dimension YAML"}),i.jsx(Pe,{t,code:z_}),i.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Hierarchy YAML"}),i.jsx(Pe,{t,code:J_}),i.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)"}),i.jsx(Pe,{t,code:q_})]}),i.jsxs(_t,{title:"Semantic Layer Providers",defaultOpen:!1,t,children:[i.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Add to your ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql.config.json"})," to connect a semantic layer provider."]}),i.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/)"}),i.jsx(Pe,{t,code:Q_}),i.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)"}),i.jsx(Pe,{t,code:Z_}),i.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 ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dbt_project.yml"}),"). Reads ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"semantic_models"})," and"," ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"metrics"})," blocks (dbt 1.6+)."]}),i.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/)"}),i.jsx(Pe,{t,code:ex}),i.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"," ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"cubes:"})," blocks from YAML schema files."]}),i.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)"}),i.jsx(Pe,{t,code:ix}),i.jsxs("div",{style:{marginTop:4,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:["Introspects Snowflake semantic views via"," ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"SHOW SEMANTIC VIEWS"}),". Set ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"projectPath"})," to your database name to scope discovery. Requires a Snowflake connection in ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"defaultConnection"}),"."]})]}),i.jsxs(_t,{title:"Connection Setup",defaultOpen:!1,t,children:[i.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Configure ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"defaultConnection"})," in"," ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql.config.json"}),"."]}),i.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)"}),i.jsx(Pe,{t,code:tx}),i.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Snowflake"}),i.jsx(Pe,{t,code:nx}),i.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"BigQuery"}),i.jsx(Pe,{t,code:rx}),i.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"PostgreSQL"}),i.jsx(Pe,{t,code:ox}),i.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:["Use ",i.jsxs("code",{style:{fontFamily:t.fontMono,fontSize:10},children:["$","${ENV_VAR}"]})," syntax for secrets. Run ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dql doctor"})," to verify your connection."]})]}),i.jsxs(_t,{title:"Variable References",defaultOpen:!1,t,children:[i.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Use"," ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"{{cell_name}}"})," ","to reference other cells:",i.jsxs("ul",{style:{margin:"6px 0 0",paddingLeft:18},children:[i.jsxs("li",{children:[i.jsx("strong",{children:"Param cell"})," → substituted as a SQL literal value"]}),i.jsxs("li",{children:[i.jsx("strong",{children:"SQL cell"})," → injected as a CTE"]})]})]}),i.jsx(Pe,{t,code:`-- Param cell named "start_date" holds '2024-01-01'
|
|
407
|
-
SELECT *
|
|
408
|
-
FROM read_csv_auto('data/sales.csv')
|
|
409
|
-
WHERE date >= {{start_date}}
|
|
410
|
-
|
|
411
|
-
-- SQL cell named "base_query" used as CTE
|
|
412
|
-
SELECT segment, SUM(revenue) AS total
|
|
413
|
-
FROM {{base_query}}
|
|
414
|
-
GROUP BY segment`})]})]})}const we={source_table:"#8b949e",dbt_model:"#ff7b72",dbt_source:"#79c0ff",block:"#56d364",metric:"#388bfd",dimension:"#e3b341",domain:"#d2a8ff",chart:"#f778ba",dashboard:"#d2a8ff"},Wc={source_table:"TBL",dbt_model:"DBT",dbt_source:"SRC",block:"BLK",metric:"MET",dimension:"DIM",domain:"DOM",chart:"CHT",dashboard:"DASH"},Bi={source_table:"Source Table",dbt_model:"dbt Model",dbt_source:"dbt Source",block:"DQL Block",metric:"Metric",dimension:"Dimension",domain:"Domain",chart:"Chart",dashboard:"Notebook"},Yr={reads_from:"#8b949e",feeds_into:"#56d364",aggregates:"#388bfd",visualizes:"#f778ba",depends_on:"#ff7b72",contains:"#d2a8ff",crosses_domain:"#d2a8ff"},ax={reads_from:"reads from",feeds_into:"feeds into",aggregates:"aggregates into",visualizes:"visualizes",depends_on:"dbt depends on",contains:"contains",crosses_domain:"crosses domain"},lx={source:"#79c0ff",transform:"#ff7b72",answer:"#56d364",consumption:"#d2a8ff"},Rd={source:"Sources",transform:"Transform",answer:"Answer",consumption:"Consumption"},qs=["source","transform","answer","consumption"];function Vc(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"dashboard":return"consumption";default:return"answer"}}function gR({type:e}){const t=we[e]??"#8b949e";return i.jsx("span",{style:{color:t,fontSize:10,fontWeight:700,textTransform:"uppercase",minWidth:34},title:Bi[e]??e,children:Wc[e]??e.slice(0,4).toUpperCase()})}function cx({value:e,onChange:t,placeholder:n,t:r}){return i.jsx("input",{value:e,onChange:o=>t(o.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 LR({node:e,t,onClick:n,secondary:r}){return i.jsxs("button",{onClick:n,style:{width:"100%",textAlign:"left",background:"transparent",border:"none",borderRadius:6,padding:"6px 8px",cursor:"pointer",color:t.textPrimary},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsx(gR,{type:e.type}),i.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12},title:e.name,children:e.name})]}),(r||e.domain)&&i.jsx("div",{style:{marginLeft:40,marginTop:2,color:t.textMuted,fontSize:11},children:r??e.domain})]})}const Ex=30,Pa=200;function xt({title:e,nodes:t,t:n,onSelect:r}){const o=t.length>Ex,[s,a]=f.useState(!o),[l,c]=f.useState(Pa);if(t.length===0)return null;const E=s?Math.min(l,t.length):0,d=Math.max(0,t.length-E);return i.jsxs("div",{style:{padding:"8px 0",borderTop:`1px solid ${n.headerBorder}`},children:[i.jsxs("button",{onClick:()=>a(u=>!u),"aria-expanded":s,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:[i.jsx("span",{style:{display:"inline-block",width:10},children:s?"▾":"▸"}),i.jsx("span",{children:e}),i.jsx("span",{style:{marginLeft:"auto",fontWeight:500},children:t.length})]}),s&&t.slice(0,E).map(u=>i.jsx(LR,{node:u,t:n,onClick:()=>r(u)},u.id)),s&&d>0&&i.jsxs("button",{onClick:()=>c(u=>u+Pa),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(Pa,d)," more (",d," hidden)"]})]})}function dx(){const{state:e,dispatch:t}=Te(),n=oe[e.themeMode],[r,o]=f.useState(!0),[s,a]=f.useState([]),[l,c]=f.useState([]),[E,d]=f.useState(""),[u,T]=f.useState([]),[S,h]=f.useState(null),[A,R]=f.useState(null),p=f.useCallback(async()=>{o(!0);const P=await Z.fetchLineage();a(P.nodes??[]),c(P.edges??[]),o(!1)},[]);f.useEffect(()=>{p()},[p]),f.useEffect(()=>{let P=!1;if(E.trim().length<2){T([]);return}return Z.searchLineage(E.trim()).then(D=>{P||T(D.matches??[])}),()=>{P=!0}},[E]);const N=f.useCallback(async P=>{const D=await Z.queryLineage({focus:P.id});h(D.focalNode??P),R(D.graph??{nodes:[],edges:[]}),t({type:"SET_LINEAGE_FOCUS",nodeId:P.id}),t({type:"SET_INSPECTOR_CONTEXT",context:{kind:"lineage-node",nodeId:P.id}}),e.lineageFullscreen||t({type:"TOGGLE_LINEAGE_FULLSCREEN"})},[t,e.lineageFullscreen]),I=f.useCallback(()=>{h(null),R(null),d(""),T([]),t({type:"SET_LINEAGE_FOCUS",nodeId:null})},[t]),[O,m]=f.useState("type"),C=f.useMemo(()=>({dashboards:s.filter(P=>P.type==="dashboard"),blocks:s.filter(P=>P.type==="block"),dbtModels:s.filter(P=>P.type==="dbt_model"),dbtSources:s.filter(P=>P.type==="dbt_source"),tables:s.filter(P=>P.type==="source_table"),domains:s.filter(P=>P.type==="domain")}),[s]),g=f.useMemo(()=>{const P={source:[],transform:[],answer:[],consumption:[]};for(const D of s){const b=Vc(D);P[b].push(D)}return P},[s]),y=f.useMemo(()=>{if(!S||!A)return{upstream:[],downstream:[]};const P=new Set(A.edges.filter(b=>b.target===S.id).map(b=>b.source)),D=new Set(A.edges.filter(b=>b.source===S.id).map(b=>b.target));return{upstream:A.nodes.filter(b=>P.has(b.id)),downstream:A.nodes.filter(b=>D.has(b.id))}},[A,S]);if(r)return i.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"Loading lineage..."});if(s.length===0)return i.jsx(Bt,{title:"Lineage",bodyPadding:0,children:i.jsx(bt,{title:"No lineage data",description:"Run `dql compile` or add notebooks/blocks first."})});const _=i.jsx(No,{children:i.jsx(cx,{value:E,onChange:d,placeholder:"Search blocks, tables, dbt models, notebooks...",t:n})});return i.jsxs(Bt,{title:"Lineage",toolbar:_,bodyPadding:0,children:[i.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`},children:[i.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"}),i.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."})]}),i.jsxs("div",{style:{flex:1,overflow:"auto"},children:[E.trim().length>=2&&u.length>0&&i.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`},children:[i.jsx("div",{style:{color:n.textMuted,fontSize:11,fontWeight:700,textTransform:"uppercase",marginBottom:6},children:"Search Results"}),u.slice(0,8).map(P=>i.jsx(LR,{node:P.node,t:n,onClick:()=>N(P.node),secondary:P.node.domain},P.node.id))]}),S&&A&&i.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[i.jsx(gR,{type:S.type}),i.jsxs("div",{style:{flex:1,minWidth:0},children:[i.jsx("div",{style:{color:n.textPrimary,fontSize:13,fontWeight:700},children:S.name}),i.jsx("div",{style:{color:n.textMuted,fontSize:11},children:S.domain??Bi[S.type]??S.type})]}),i.jsx("button",{onClick:I,style:{border:`1px solid ${n.headerBorder}`,background:"transparent",color:n.textPrimary,borderRadius:6,padding:"6px 8px",cursor:"pointer",fontSize:11},children:"Show All"})]}),i.jsxs("div",{style:{color:n.textMuted,fontSize:11,marginBottom:6},children:[A.nodes.length," node(s), ",A.edges.length," edge(s)"]}),i.jsx("div",{style:{color:n.textMuted,fontSize:11,marginBottom:6,lineHeight:1.5},children:"Focused lineage shows the path into this item from raw tables/dbt and the downstream notebooks or analytics objects that consume it."}),i.jsx(xt,{title:"Upstream",nodes:y.upstream,t:n,onSelect:N}),i.jsx(xt,{title:"Downstream",nodes:y.downstream,t:n,onSelect:N})]}),!S&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:{padding:"6px 8px",display:"flex",gap:8,flexWrap:"wrap",borderBottom:`1px solid ${n.headerBorder}`},children:[qs.map(P=>{const D=g[P].length;return D===0?null:i.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:10,color:n.textMuted},children:[i.jsx("span",{style:{width:8,height:8,borderRadius:2,background:lx[P],display:"inline-block"}}),Rd[P],": ",D]},P)}),i.jsx("span",{style:{flex:1}}),i.jsxs("div",{style:{display:"flex",borderRadius:4,border:`1px solid ${n.headerBorder}`,overflow:"hidden"},children:[i.jsx("button",{onClick:()=>m("type"),style:{padding:"2px 6px",fontSize:9,fontWeight:700,border:"none",cursor:"pointer",background:O==="type"?`${n.headerBorder}`:"transparent",color:O==="type"?n.textPrimary:n.textMuted},children:"Type"}),i.jsx("button",{onClick:()=>m("layer"),style:{padding:"2px 6px",fontSize:9,fontWeight:700,border:"none",cursor:"pointer",borderLeft:`1px solid ${n.headerBorder}`,background:O==="layer"?`${n.headerBorder}`:"transparent",color:O==="layer"?n.textPrimary:n.textMuted},children:"Layer"})]})]}),O==="type"?i.jsxs(i.Fragment,{children:[i.jsx(xt,{title:"Notebooks",nodes:C.dashboards,t:n,onSelect:N}),i.jsx(xt,{title:"DQL Blocks",nodes:C.blocks,t:n,onSelect:N}),i.jsx(xt,{title:"dbt Models",nodes:C.dbtModels,t:n,onSelect:N}),i.jsx(xt,{title:"dbt Sources",nodes:C.dbtSources,t:n,onSelect:N}),i.jsx(xt,{title:"Source Tables",nodes:C.tables,t:n,onSelect:N}),i.jsx(xt,{title:"Business Domains",nodes:C.domains,t:n,onSelect:N})]}):i.jsx(i.Fragment,{children:qs.map(P=>i.jsx(xt,{title:Rd[P],nodes:g[P],t:n,onSelect:N},P))})]})]})]})}const ux={certified:"success",published:"success",deprecated:"error",draft:"warning",pending:"warning",review:"accent"};function Tx(){const{state:e,dispatch:t}=Te(),n=oe[e.themeMode],[r,o]=f.useState([]),[s,a]=f.useState(!0),[l,c]=f.useState(""),[E,d]=f.useState(""),[u,T]=f.useState("");f.useEffect(()=>{a(!0),Z.getBlockLibrary().then(m=>o(m.blocks)).finally(()=>a(!1))},[]);const S=[...new Set(r.map(m=>m.domain))].sort(),h=[...new Set(r.map(m=>m.status))].sort(),A=r.filter(m=>!(l&&!m.name.toLowerCase().includes(l.toLowerCase())&&!m.description.toLowerCase().includes(l.toLowerCase())||E&&m.domain!==E||u&&m.status!==u)),R=m=>{const C={name:m.path.split("/").pop()??m.name,path:m.path,type:"block",folder:"blocks"};e.files.some(g=>g.path===m.path)||t({type:"FILE_ADDED",file:C}),Z.openBlockStudio(m.path).then(g=>{t({type:"OPEN_BLOCK_STUDIO",file:C,payload:g})})},p=()=>{a(!0),Z.getBlockLibrary().then(m=>o(m.blocks)).finally(()=>a(!1))},N={background:n.inputBg,border:`1px solid ${n.inputBorder}`,borderRadius:4,color:n.textPrimary,fontSize:11,fontFamily:n.font,padding:"4px 6px",outline:"none"},I=i.jsxs(i.Fragment,{children:[i.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"}),i.jsx("button",{onClick:p,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"})]}),O=i.jsxs(No,{children:[i.jsx("input",{value:l,onChange:m=>c(m.target.value),placeholder:"Search blocks...",style:{...N,flex:1,minWidth:100}}),i.jsxs("select",{value:E,onChange:m=>d(m.target.value),style:N,children:[i.jsx("option",{value:"",children:"All domains"}),S.map(m=>i.jsx("option",{value:m,children:m},m))]}),i.jsxs("select",{value:u,onChange:m=>T(m.target.value),style:N,children:[i.jsx("option",{value:"",children:"All statuses"}),h.map(m=>i.jsx("option",{value:m,children:m},m))]})]});return i.jsx(Bt,{title:"Blocks",status:i.jsx("span",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:A.length}),actions:I,toolbar:O,bodyPadding:0,children:s?i.jsx(bt,{title:"Loading blocks…"}):A.length===0?i.jsx(bt,{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."}):A.map(m=>i.jsxs("button",{onClick:()=>R(m),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:C=>{C.currentTarget.style.background=`${n.accent}0a`},onMouseLeave:C=>{C.currentTarget.style.background="transparent"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[i.jsx("span",{style:{fontSize:12,fontWeight:600,color:n.textPrimary,fontFamily:n.font},children:m.name}),i.jsx(Yc,{tone:ux[m.status]??"neutral",children:m.status})]}),m.description&&i.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font,lineHeight:1.3,marginBottom:4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.description}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:10,color:n.textMuted,fontFamily:n.font},children:[i.jsx("span",{style:{background:n.pillBg,padding:"1px 6px",borderRadius:4},children:m.domain}),m.owner&&i.jsxs("span",{children:["by ",m.owner]}),m.llmContext&&i.jsx("span",{title:m.llmContext,style:{color:n.accent,fontWeight:600,letterSpacing:"0.04em"},children:"AI"}),i.jsx("span",{style:{marginLeft:"auto"},children:new Date(m.lastModified).toLocaleDateString()})]})]},m.path))})}function Sx({diff:e,diffReport:t,activeFilePath:n,diffPath:r,onScopeToFile:o,onClearScope:s,t:a}){const l=t!==null&&!t.identical,c=e.trim()!=="";return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[i.jsxs("div",{style:{display:"flex",gap:6,fontSize:11},children:[i.jsx("button",{onClick:s,style:pd(r==null,a),children:"All"}),n&&i.jsx("button",{onClick:o,style:pd(r===n,a),children:"Active file"}),r&&i.jsx("span",{style:{color:a.textMuted,fontSize:10,alignSelf:"center",fontFamily:a.fontMono},children:r})]}),l&&i.jsx(fx,{report:t,t:a}),!l&&c&&i.jsx(px,{diff:e,t:a}),!l&&!c&&i.jsx("div",{style:{color:a.textMuted},children:t&&t.identical?"No semantic changes.":"No unstaged changes."})]})}function fx({report:e,t}){return i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.changes.map((n,r)=>i.jsx(Rx,{change:n,t},r))})}function Rx({change:e,t}){const{marker:n,color:r,label:o}=hx(e),s="fields"in e?e.fields:null;return i.jsxs("div",{style:{border:`1px solid ${t.editorBorder}`,borderRadius:6,padding:"6px 10px",background:t.editorBg},children:[i.jsxs("div",{style:{display:"flex",gap:8,alignItems:"baseline"},children:[i.jsx("span",{style:{color:r,fontFamily:t.fontMono,fontWeight:700,width:14},children:n}),i.jsx("span",{style:{color:t.textPrimary,fontSize:12,fontFamily:t.fontMono},children:o})]}),s&&s.length>0&&i.jsx("div",{style:{marginTop:4,display:"flex",flexDirection:"column",gap:2},children:s.map((a,l)=>i.jsx(Ax,{field:a,t},l))})]})}function Ax({field:e,t}){return i.jsxs("div",{style:{fontSize:11,fontFamily:t.fontMono,color:t.textPrimary,paddingLeft:22},children:[i.jsx("span",{style:{color:t.accent},children:e.path}),i.jsx("span",{style:{color:t.textMuted},children:": "}),i.jsx("span",{style:{color:t.error,textDecoration:"line-through"},children:Ad(e.before)}),i.jsx("span",{style:{color:t.textMuted},children:" → "}),i.jsx("span",{style:{color:t.success},children:Ad(e.after)})]})}function px({diff:e,t}){return i.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(`
|
|
415
|
-
`).map((n,r)=>i.jsx("div",{style:{color:Ix(n,t)},children:n||" "},r))})}function hx(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 ${ba(e.id,e.name)} [${e.cellType}]`};case"cell-removed":return{...n,label:`cell ${ba(e.id,e.name)} [${e.cellType}]`};case"cell-changed":return{...r,label:`cell ${ba(e.id,e.name)}`};case"notebook-changed":return{...r,label:"notebook"}}}function ba(e,t){return t?`"${t}" (${e.slice(0,8)})`:e.slice(0,8)}function Ad(e,t=60){if(e==null)return"∅";const n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}…`:n}function pd(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 Ix(e,t){return e.startsWith("+++")||e.startsWith("---")?t.textMuted:e.startsWith("+")?t.success:e.startsWith("-")?t.error:e.startsWith("@@")?t.accent:t.textPrimary}const Nx=2e3;function Ox(){var O;const{state:e}=Te(),t=oe[e.themeMode],[n,r]=f.useState("status"),[o,s]=f.useState(null),[a,l]=f.useState(null),[c,E]=f.useState(""),[d,u]=f.useState(null),[T,S]=f.useState(null),[h,A]=f.useState(!1),R=f.useCallback(async()=>{A(!0);try{if(n==="status")s(await Z.fetchGitStatus());else if(n==="log")l(await Z.fetchGitLog(30));else{const m=await Z.fetchGitDiff(T??void 0);E(m.diff),u(m.diffReport)}}finally{A(!1)}},[n,T]);f.useEffect(()=>{R()},[R]),f.useEffect(()=>{if(n!=="status")return;const m=window.setInterval(()=>{Z.fetchGitStatus().then(C=>{s(g=>mx(g,C)?g:C)})},Nx);return()=>window.clearInterval(m)},[n]);const p=((O=e.activeFile)==null?void 0:O.path)??null,N=i.jsx("button",{onClick:()=>void R(),title:"Refresh",style:{background:"transparent",border:"none",cursor:"pointer",color:t.textMuted,padding:"2px 6px",borderRadius:4,fontSize:12},children:"↻"}),I=i.jsxs(No,{children:[i.jsx(va,{t,active:n==="status",onClick:()=>r("status"),children:"Status"}),i.jsx(va,{t,active:n==="log",onClick:()=>r("log"),children:"Log"}),i.jsx(va,{t,active:n==="diff",onClick:()=>r("diff"),children:"Diff"})]});return i.jsxs(Bt,{title:"Git",actions:N,toolbar:I,bodyPadding:10,children:[h&&!o&&!a&&i.jsx(bt,{title:"Loading…"}),n==="status"&&o&&i.jsx(Cx,{status:o,t}),n==="log"&&a&&i.jsx(gx,{log:a,t}),n==="diff"&&i.jsx(Sx,{diff:c,diffReport:d,activeFilePath:p,diffPath:T,onScopeToFile:()=>S(p),onClearScope:()=>S(null),t})]})}function mx(e,t){if(!e||e.inRepo!==t.inRepo||e.branch!==t.branch||e.ahead!==t.ahead||e.behind!==t.behind||e.changes.length!==t.changes.length)return!1;const n=e.changes.map(o=>`${o.path}\0${o.status}`).sort(),r=t.changes.map(o=>`${o.path}\0${o.status}`).sort();for(let o=0;o<n.length;o++)if(n[o]!==r[o])return!1;return!0}function Cx({status:e,t}){return e.inRepo?i.jsxs("div",{children:[i.jsxs("div",{style:{marginBottom:10},children:[i.jsx("span",{style:{color:t.textMuted},children:"Branch"})," ",i.jsx("span",{style:{color:t.accent,fontWeight:600},children:e.branch??"detached"}),e.ahead>0&&i.jsxs("span",{style:{marginLeft:8,color:t.textMuted},children:["↑ ",e.ahead]}),e.behind>0&&i.jsxs("span",{style:{marginLeft:8,color:t.textMuted},children:["↓ ",e.behind]})]}),e.changes.length===0?i.jsx("div",{style:{color:t.textMuted},children:"Working tree clean."}):i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:2,fontFamily:t.fontMono,fontSize:11},children:e.changes.map(n=>i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsx("span",{style:{color:Lx(n.status,t),width:22},children:n.status.trim()||"??"}),i.jsx("span",{style:{color:t.textPrimary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.path})]},n.path))})]}):i.jsx("div",{style:{color:t.textMuted},children:"Not a git repository."})}function gx({log:e,t}){return e.inRepo?e.commits.length===0?i.jsx("div",{style:{color:t.textMuted},children:"No commits."}):i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:e.commits.map(n=>i.jsxs("div",{style:{borderLeft:`2px solid ${t.headerBorder}`,paddingLeft:8},children:[i.jsx("div",{style:{color:t.textPrimary,fontSize:12},children:n.subject}),i.jsxs("div",{style:{color:t.textMuted,fontSize:10,marginTop:2,fontFamily:t.fontMono},children:[n.hash.slice(0,7)," · ",n.author," · ",n.date]})]},n.hash))}):i.jsx("div",{style:{color:t.textMuted},children:"Not a git repository."})}function va({active:e,onClick:t,children:n,t:r}){return i.jsx("button",{onClick:t,style:{background:e?r.btnHover:"transparent",color:e?r.textPrimary:r.textMuted,border:"none",padding:"3px 10px",borderRadius:4,fontSize:11,fontWeight:600,cursor:"pointer"},children:n})}function Lx(e,t){const n=e.trim();return n==="M"||n==="MM"?t.warning:n==="A"||n==="??"?t.success:n==="D"?t.error:n.startsWith("R")?t.accent:t.textMuted}function _x({onOpenFile:e}){const{state:t}=Te(),n=oe[t.themeMode],[r,o]=f.useState([]),[s,a]=f.useState(!0),[l,c]=f.useState(""),[E,d]=f.useState(""),[u,T]=f.useState(new Set),S=()=>{a(!0),Z.getApps().then(C=>o(C.apps)).finally(()=>a(!1))};f.useEffect(()=>{S()},[]);const h=[...new Set(r.map(C=>C.manifest.domain))].sort(),A=r.filter(C=>{const g=l.toLowerCase();return!(g&&!C.manifest.name.toLowerCase().includes(g)&&!(C.manifest.description??"").toLowerCase().includes(g)||E&&C.manifest.domain!==E)}),R=C=>{T(g=>{const y=new Set(g);return y.has(C)?y.delete(C):y.add(C),y})},p=(C,g)=>{const y=`${C.path}/notebooks/${g}`;e({name:g,path:y,type:"notebook",folder:"notebooks"})},N=(C,g)=>{const y=`${C.path}/dashboards/${g}`;e({name:g,path:y,type:"dashboard",folder:"dashboards"})},I={background:n.inputBg,border:`1px solid ${n.inputBorder}`,borderRadius:4,color:n.textPrimary,fontSize:11,fontFamily:n.font,padding:"4px 6px",outline:"none"},O=i.jsx("button",{onClick:S,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"}),m=i.jsxs(No,{children:[i.jsx("input",{value:l,onChange:C=>c(C.target.value),placeholder:"Search apps...",style:{...I,flex:1,minWidth:100}}),i.jsxs("select",{value:E,onChange:C=>d(C.target.value),style:I,children:[i.jsx("option",{value:"",children:"All domains"}),h.map(C=>i.jsx("option",{value:C,children:C},C))]})]});return i.jsx(Bt,{title:"Apps",status:i.jsx("span",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:A.length}),actions:O,toolbar:m,bodyPadding:0,children:s?i.jsx(bt,{title:"Loading apps…"}):A.length===0?r.length===0?i.jsx(bt,{title:"No apps yet",description:i.jsxs(i.Fragment,{children:["Create one from the CLI:",i.jsx("br",{}),i.jsx("code",{style:{display:"inline-block",marginTop:6,padding:"2px 6px",background:n.inputBg,borderRadius:3,fontSize:10},children:"dql app new <name> --domain <domain>"})]})}):i.jsx(bt,{title:"No matches",description:"No apps match your filters."}):A.map(C=>{const g=u.has(C.manifest.name);return i.jsxs("div",{style:{borderBottom:`1px solid ${n.cellBorder}`},children:[i.jsxs("button",{onClick:()=>R(C.manifest.name),style:{display:"block",width:"100%",textAlign:"left",background:"transparent",border:"none",cursor:"pointer",padding:"10px 12px",transition:"background 0.1s"},onMouseEnter:y=>{y.currentTarget.style.background=`${n.accent}0a`},onMouseLeave:y=>{y.currentTarget.style.background="transparent"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[i.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font,width:10},children:g?"▾":"▸"}),i.jsx("span",{style:{fontSize:12,fontWeight:600,color:n.textPrimary,fontFamily:n.font},children:C.manifest.name}),i.jsx(Yc,{tone:"accent",children:C.manifest.domain})]}),C.manifest.description&&i.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font,lineHeight:1.3,marginBottom:4,marginLeft:16},children:C.manifest.description}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:10,color:n.textMuted,fontFamily:n.font,marginLeft:16},children:[C.manifest.owner&&i.jsxs("span",{children:["by ",C.manifest.owner]}),i.jsxs("span",{children:[C.notebooks.length," notebook",C.notebooks.length===1?"":"s"]}),i.jsxs("span",{children:[C.dashboards.length," dashboard",C.dashboards.length===1?"":"s"]}),C.hasDigest&&i.jsx("span",{style:{color:n.accent},children:"digest"})]})]}),g&&i.jsxs("div",{style:{padding:"4px 0 10px 28px",background:`${n.accent}04`},children:[C.notebooks.length===0&&C.dashboards.length===0&&!C.hasDigest&&i.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font,padding:"4px 0"},children:"(empty app scaffold)"}),C.notebooks.map(y=>i.jsxs("button",{onClick:()=>p(C,y),style:{display:"block",width:"100%",textAlign:"left",background:"transparent",border:"none",padding:"3px 12px",cursor:"pointer",fontSize:11,color:n.textSecondary,fontFamily:n.font},children:["📓 ",y]},y)),C.dashboards.map(y=>i.jsxs("button",{onClick:()=>N(C,y),style:{display:"block",width:"100%",textAlign:"left",background:"transparent",border:"none",padding:"3px 12px",cursor:"pointer",fontSize:11,color:n.textSecondary,fontFamily:n.font},children:["📊 ",y]},y)),C.hasDigest&&i.jsx("div",{style:{padding:"3px 12px",fontSize:11,color:n.textMuted,fontFamily:n.font},children:"📰 digest.dql"})]})]},C.path)})})}const xx={files:"Explorer",schema:"Schema",block_library:"Block Library",lineage:"Lineage",connection:"Connection",reference:"Quick Reference",git:"Git",apps:"Apps"};function yx({onOpenFile:e}){const{state:t,dispatch:n}=Te(),r=oe[t.themeMode],[o,s]=f.useState(!1),a=t.sidebarPanel;return i.jsxs("div",{style:{width:240,flexShrink:0,background:r.sidebarBg,borderRight:`1px solid ${r.headerBorder}`,display:"flex",flexDirection:"column",overflow:"hidden"},children:[i.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:[i.jsx("span",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.06em",textTransform:"uppercase",color:r.textSecondary,fontFamily:r.font},children:xx[a??""]??""}),i.jsx("button",{title:"Collapse sidebar",onClick:()=>n({type:"TOGGLE_SIDEBAR"}),onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),style:{background:"transparent",border:"none",cursor:"pointer",color:o?r.textPrimary:r.textMuted,padding:"2px 4px",borderRadius:4,fontSize:14,lineHeight:1,transition:"color 0.15s",display:"flex",alignItems:"center"},children:"‹"})]}),i.jsxs("div",{style:{flex:1,overflow:"hidden",display:"flex",flexDirection:"column"},children:[a==="files"&&i.jsx(v_,{onOpenFile:e}),a==="schema"&&i.jsx(G_,{}),a==="block_library"&&i.jsx(Tx,{}),a==="lineage"&&i.jsx(dx,{}),a==="connection"&&i.jsx(mR,{}),a==="reference"&&i.jsx(CR,{themeMode:t.themeMode}),a==="git"&&i.jsx(Ox,{}),a==="apps"&&i.jsx(_x,{onOpenFile:e})]})]})}var hd;(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"})(hd||(hd={}));var Id;(function(e){e.Error="error",e.Warning="warning",e.Info="info"})(Id||(Id={}));var fe;(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"})(fe||(fe={}));fe.DashboardKeyword,fe.WorkbookKeyword,fe.PageKeyword,fe.LetKeyword,fe.ParamKeyword,fe.ChartKeyword,fe.FilterKeyword,fe.BooleanLiteral,fe.BooleanLiteral,fe.IntervalKeyword,fe.ImportKeyword,fe.FromKeyword,fe.UseKeyword,fe.LayoutKeyword,fe.RowKeyword,fe.BlockKeyword,fe.DomainKeyword,fe.TypeKeyword,fe.DescriptionKeyword,fe.TagsKeyword,fe.OwnerKeyword,fe.QueryKeyword,fe.VisualizationKeyword,fe.TestsKeyword,fe.ParamsKeyword,fe.AssertKeyword,fe.VarKeyword,fe.DefaultKeyword,fe.InKeyword,fe.MetricKeyword,fe.MetricsKeyword,fe.DigestKeyword,fe.NarrativeKeyword;const _R=1;function Dx(e,t={}){const n=t.version??_R,r=JSON.parse(e),{dqlnbVersion:o,...s}=r,a={dqlnbVersion:n,...s};return JSON.stringify(a,Mx(),2)+`
|
|
416
|
-
`}function Mx(){return function(t,n){if(n===null||typeof n!="object"||Array.isArray(n))return n;const r=n,o=Object.keys(r);o.sort((a,l)=>{const c=Nd[a],E=Nd[l];return c!==void 0&&E!==void 0?c-E:c!==void 0?-1:E!==void 0?1:a<l?-1:a>l?1:0});const s={};for(const a of o)s[a]=r[a];return s}}const Nd={dqlnbVersion:0,version:1,title:2,metadata:3,cells:4,id:10,type:11,name:12,content:13};function Px(e){try{const t=e.match(/workbook\s+"([^"]+)"/i),n=t?t[1]:"Untitled Workbook",r=[],o=/page\s+"([^"]+)"\s*\{([\s\S]*?)\}/gi;let s;for(;(s=o.exec(e))!==null;){const a=s[1],l=s[2].trim();r.push({id:Mt(),type:"markdown",content:`# ${a}`,status:"idle"}),l&&r.push({id:Mt(),type:"dql",name:a.toLowerCase().replace(/\s+/g,"_"),content:l,status:"idle"})}return r.length===0&&r.push({id:Mt(),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:Mt(),type:"dql",content:e.trim(),status:"idle"}]}}}function bx(e){var t;try{const n=JSON.parse(e),r=n.title||((t=n.metadata)==null?void 0:t.title)||"Untitled",o=(n.cells||[]).map(l=>({id:l.id||Mt(),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:s,...a}=n.metadata??{};return{title:r,cells:o,metadata:a}}catch(n){return console.warn("parse-workbook: falling back after error",n),{title:"Untitled",cells:[{id:Mt(),type:"sql",content:e,status:"idle"}]}}}function vx(e,t,n){const r={dqlnbVersion:_R,version:1,title:e,metadata:{...n,modifiedAt:new Date().toISOString(),...n!=null&&n.createdAt?{}:{createdAt:new Date().toISOString()}},cells:t.map(o=>({id:o.id,type:o.type,content:o.content,...o.name?{name:o.name}:{},...o.paramConfig?{paramConfig:o.paramConfig}:{},...o.paramValue!==void 0?{paramValue:o.paramValue}:{},...o.chartConfig?{chartConfig:o.chartConfig}:{},...o.filterConfig?{filterConfig:o.filterConfig}:{},...o.pivotConfig?{pivotConfig:o.pivotConfig}:{},...o.singleValueConfig?{singleValueConfig:o.singleValueConfig}:{},...o.tableConfig?{tableConfig:o.tableConfig}:{},...o.upstream?{upstream:o.upstream}:{},...o.blockBinding?{blockBinding:o.blockBinding}:{}}))};return Dx(JSON.stringify(r))}function Ux(e,t){return e.endsWith(".dql")?Px(t):bx(t)}const xR=/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g;function wx(e){const t=new Set;for(const n of e.matchAll(xR))t.add(n[1]);return[...t]}function Bx(e,t){if(!t.columns.length||!t.rows.length)return`${e} AS (SELECT 1 WHERE 1=0)`;const n=t.columns,o=t.rows.slice(0,5e3).map(a=>`(${n.map(c=>{const E=a[c];return E==null?"NULL":typeof E=="number"?String(E):typeof E=="boolean"?E?"TRUE":"FALSE":`'${String(E).replace(/'/g,"''")}'`}).join(", ")})`).join(`,
|
|
417
|
-
`),s=n.map(a=>`"${a.replace(/"/g,'""')}"`).join(", ");return`${e} AS (
|
|
418
|
-
SELECT * FROM (VALUES
|
|
419
|
-
${o}
|
|
420
|
-
) AS _t(${s})
|
|
421
|
-
)`}function Fx(e,t){if(t==="number"){const n=Number(e);return isNaN(n)?`'${e.replace(/'/g,"''")}'`:String(n)}return`'${e.replace(/'/g,"''")}'`}function Gx(){const{state:e}=Te();return{substituteVariables:f.useCallback(n=>{var E;const r=[...n.matchAll(xR)];if(r.length===0)return{sql:n,substituted:[]};const o=[],s=[];let a=n;const l=new Map,c=new Map;for(const d of e.cells){const u=(E=d.name)==null?void 0:E.trim();u&&(d.type==="param"?l.set(u,d):d.status==="success"&&d.result&&c.set(u,d.result))}for(const d of r){const u=d[1];if(l.has(u)){const T=l.get(u),S=T.paramConfig,h=T.paramValue??(S==null?void 0:S.defaultValue)??"",A=(S==null?void 0:S.paramType)??"text",R=Fx(h,A);a=a.replace(d[0],R),o.push(u)}else c.has(u)&&(s.push(Bx(u,c.get(u))),a=a.replace(d[0],`"${u}"`),o.push(u))}if(s.length===0&&o.length===0)return{sql:n,substituted:[]};if(s.length>0){const d=a.trimStart();/^WITH\s+/i.test(d)?a=a.replace(/^(\s*WITH\s+)/i,`$1${s.join(`,
|
|
422
|
-
`)},
|
|
423
|
-
`):a=`WITH ${s.join(`,
|
|
424
|
-
`)}
|
|
425
|
-
${a}`}return{sql:a,substituted:o}},[e.cells])}}function Hx(e){var s;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]},o=r("chart");if(o)return{chart:o,x:r("x"),y:r("y"),color:r("color"),title:(s=n.match(/\btitle\s*=\s*"([^"]+)"/i))==null?void 0:s[1]}}function $c(e){const t=e.trim();if(!t)return null;const n=t.match(/query\s*=\s*"""([\s\S]*?)"""/i);if(n)return n[1].trim()||null;const r=t.match(/"""([\s\S]*?)"""/);if(r)return r[1].trim()||null;if(/^\s*(dashboard|workbook)\s+"/i.test(t))return null;const o=t.match(/\b(SELECT|WITH|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|SHOW|DESCRIBE|EXPLAIN)\b([\s\S]*)/i);if(o){let s=o[0];const a=s.search(/\b(visualization|tests|block)\s*\{/i);return a>0&&(s=s.slice(0,a)),s=kx(s),s.trim()||null}return null}function kx(e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];if(r==="("){t++;continue}if(r===")"){t>0&&t--;continue}if(r==="'"||r==='"'){for(n++;n<e.length&&e[n]!==r;)e[n]==="\\"&&n++,n++;continue}if(r===","&&t===0){let o=n+1;for(;o<e.length&&/\s/.test(e[o]);)o++;if(o<e.length&&/[a-zA-Z_]/.test(e[o])){for(;o<e.length&&/[a-zA-Z0-9_]/.test(e[o]);)o++;let s=o;for(;s<e.length&&/\s/.test(e[s]);)s++;if(s<e.length&&e[s]==="="&&e[s+1]!=="=")return e.slice(0,n)}}}return e}function Od(e){const t=bn(e);return t?{name:t.name,domain:t.domain,owner:t.owner,description:t.description,blockType:t.blockType,tags:t.tags}:null}function Ua(e,t,n){const r=bn(e);if(!r){const s=n.replace(/"/g,'\\"'),a=new RegExp(`(\\b${t}\\s*=\\s*)"[^"]*"`,"i");return a.test(e)?e.replace(a,`$1"${s}"`):Xc(e,` ${t} = "${s}"`)}const o={...r};return t==="domain"&&(o.domain=n),t==="owner"&&(o.owner=n),t==="description"&&(o.description=n),t==="type"&&(o.blockType=n),Or(o)}function yR(e,t){const n=bn(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 Or({...n,name:t})}function jx(e,t){const n=bn(e);if(!n){const r=t.map(s=>`"${s.replace(/"/g,'\\"')}"`).join(", "),o=/(\btags\s*=\s*)\[[^\]]*\]/i;return o.test(e)?e.replace(o,`$1[${r}]`):Xc(e,` tags = [${r}]`)}return Or({...n,tags:t})}function Yx(e,t){const n=bn(e),r=Xx(t);return n?Or({...n,visualization:r}):/visualization\s*\{[\s\S]*?\n\s*\}/i.test(e)?e.replace(/visualization\s*\{[\s\S]*?\n\s*\}/i,r):Xc(e,` ${r.replace(/\n/g,`
|
|
426
|
-
`)}`,!0)}function Wx(e,t){return e==="metric"?`@metric(${t})`:`@dim(${t})`}function Vx(e,t){const n=bn(e);if(!n||n.blockType!=="semantic")return e;const r={...n,metrics:[...n.metrics],dimensions:[...n.dimensions]};if(t.kind==="metric"){const o=new Set;r.metric&&o.add(r.metric);for(const a of r.metrics)o.add(a);o.add(t.name);const s=Array.from(o);r.metric=s.length===1?s[0]:"",r.metrics=s.length>1?s:[]}else r.dimensions.includes(t.name)||(r.dimensions=[...r.dimensions,t.name]);return Or(r)}function $x(e,t){const n=bn(e);if(!n||n.blockType!=="custom")return`${e.trimEnd()}
|
|
427
|
-
${t}
|
|
428
|
-
`;const r=n.query.trimEnd(),o=r?`${r}
|
|
429
|
-
${t}`:t;return Or({...n,query:o})}function bn(e){var s,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=((s=e.match(/^\s*block\s+"([^"]+)"/i))==null?void 0:s[1])??"",r=e.match(/\btags\s*=\s*\[([^\]]*)\]/i),o=e.match(/query\s*=\s*"""([\s\S]*?)"""/i);return{name:n,domain:t("domain"),owner:t("owner"),description:t("description"),blockType:(t("type")||"custom").toLowerCase()==="semantic"?"semantic":"custom",tags:r?(r[1].match(/"([^"]*)"/g)??[]).map(l=>l.slice(1,-1)):[],metric:t("metric"),metrics:md(e,"metrics"),dimensions:md(e,"dimensions"),timeDimension:t("time_dimension"),granularity:t("granularity"),query:((a=o==null?void 0:o[1])==null?void 0:a.trim())??"",visualization:Cd(e,"visualization"),tests:Cd(e,"tests")}}function md(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 Cd(e,t){const n=new RegExp(`\\b${t}\\s*\\{`,"i").exec(e);if(!n||n.index==null)return"";let r=0,o=-1;for(let s=n.index;s<e.length;s++){const a=e[s];if(a==="{")r===0&&(o=s),r++;else if(a==="}"&&(r--,r===0&&o>=0))return e.slice(n.index,s+1).trim()}return""}function Or(e){const t=[`block "${rt(e.name||"New Block")}" {`,` domain = "${rt(e.domain||"uncategorized")}"`,` type = "${e.blockType}"`,` description = "${rt(e.description)}"`,` owner = "${rt(e.owner)}"`,` tags = [${e.tags.map(n=>`"${rt(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 = "${rt(n[0])}"`):n.length>1&&t.push(` metrics = [${n.map(r=>`"${rt(r)}"`).join(", ")}]`),e.dimensions.length>0&&t.push(` dimensions = [${Array.from(new Set(e.dimensions)).map(r=>`"${rt(r)}"`).join(", ")}]`),e.timeDimension&&t.push(` time_dimension = "${rt(e.timeDimension)}"`),e.granularity&&t.push(` granularity = "${rt(e.granularity)}"`)}return e.blockType==="custom"&&(t.push(""),t.push(' query = """'),t.push(...Kx(e.query.trim(),4)),t.push(' """')),e.visualization&&(t.push(""),t.push(...gd(e.visualization,2))),e.tests&&(t.push(""),t.push(...gd(e.tests,2))),t.push("}"),t.join(`
|
|
430
|
-
`)+`
|
|
431
|
-
`}function Xx(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 = "${rt(e.title)}"`),t.push("}"),t.join(`
|
|
432
|
-
`)}function Kx(e,t){const n=" ".repeat(t);return(e?e.split(`
|
|
433
|
-
`):[""]).map(o=>`${n}${o}`)}function gd(e,t){const n=" ".repeat(t);return e.split(`
|
|
434
|
-
`).map(r=>`${n}${r.trimEnd()}`)}function rt(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Xc(e,t,n=!1){const r=e.trimEnd();if(!/^\s*block\s+"/i.test(r))return`${r}
|
|
435
|
-
${t}
|
|
436
|
-
`;const o=n?`
|
|
437
|
-
|
|
438
|
-
${t}
|
|
439
|
-
`:`
|
|
440
|
-
${t}`;return r.replace(/\n\}\s*$/,`${o}
|
|
441
|
-
}`)}const br=new Map;function zx(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?$c(t):null}function Fi(){const{state:e,dispatch:t}=Te(),{substituteVariables:n}=Gx(),r=f.useCallback(async l=>{const c=e.cells.find(h=>h.id===l);if(!c)return;const E=zx(c);if(!E)return;if(c.type==="dql"){const h=Hx(c.content);h&&JSON.stringify(h)!==JSON.stringify(c.chartConfig)&&t({type:"UPDATE_CELL",id:l,updates:{chartConfig:h}})}const{sql:d}=n(E),u=Date.now(),T=br.get(l);T&&T.abort();const S=new AbortController;br.set(l,S),t({type:"UPDATE_CELL",id:l,updates:{status:"running",error:void 0,result:void 0,fromSnapshot:!1}});try{const h=await Z.executeQuery(d,S.signal),A=Date.now()-u,R=(c.executionCount??0)+1;t({type:"UPDATE_CELL",id:l,updates:{status:"success",result:{...h,executionTime:h.executionTime??A,rowCount:h.rowCount??h.rows.length},executionCount:R}}),t({type:"APPEND_QUERY_LOG",entry:{id:Mt(),cellName:c.name??c.id,rows:h.rowCount??h.rows.length,time:h.executionTime??A,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 A=Date.now()-u,R=h instanceof Error?h.message:String(h);t({type:"UPDATE_CELL",id:l,updates:{status:"error",error:R,executionCount:(c.executionCount??0)+1}}),t({type:"APPEND_QUERY_LOG",entry:{id:Mt(),cellName:c.name??c.id,rows:0,time:A,ts:new Date,error:R}})}finally{br.delete(l)}},[e.cells,t]),o=f.useCallback(async()=>{for(const l of e.cells)l.type!=="markdown"&&await r(l.id)},[e.cells,r]),s=f.useCallback(async l=>{if(!l)return;const c=`{{${l}}}`;for(const E of e.cells)E.type==="markdown"||E.type==="param"||E.content.includes(c)&&await r(E.id)},[e.cells,r]),a=f.useCallback(l=>{const c=br.get(l);c&&(c.abort(),br.delete(l)),t({type:"UPDATE_CELL",id:l,updates:{status:"idle"}})},[t]);return{executeCell:r,executeAll:o,executeDependents:s,cancelCell:a}}function Ge(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Jx(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 qx(e){const t=e.split(`
|
|
442
|
-
`),n=[];let r=!1,o=!1;for(const s of t){const a=s;if(a.startsWith("```")){o&&(n.push("</ul>"),o=!1),r?(n.push("</code></pre>"),r=!1):(n.push("<pre><code>"),r=!0);continue}if(r){n.push(Ge(a));continue}if(a.startsWith("### ")){o&&(n.push("</ul>"),o=!1),n.push(`<h3>${Ge(a.slice(4))}</h3>`);continue}if(a.startsWith("## ")){o&&(n.push("</ul>"),o=!1),n.push(`<h2>${Ge(a.slice(3))}</h2>`);continue}if(a.startsWith("# ")){o&&(n.push("</ul>"),o=!1),n.push(`<h1>${Ge(a.slice(2))}</h1>`);continue}if(a.startsWith("> ")){o&&(n.push("</ul>"),o=!1),n.push(`<blockquote><p>${Ge(a.slice(2))}</p></blockquote>`);continue}if(a.startsWith("- ")||a.startsWith("* ")){o||(n.push("<ul>"),o=!0),n.push(`<li>${Ld(a.slice(2))}</li>`);continue}if(o&&(n.push("</ul>"),o=!1),a.trim()===""){n.push("<br>");continue}n.push(`<p>${Ld(a)}</p>`)}return o&&n.push("</ul>"),r&&n.push("</code></pre>"),n.join(`
|
|
443
|
-
`)}function Ld(e){return Ge(e).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/`(.+?)`/g,"<code>$1</code>")}function Qx(e){const{columns:t,rows:n}=e,r=n.slice(0,200),o=n.length>200,s=t.map(l=>`<th>${Ge(l)}</th>`).join(""),a=r.map(l=>`<tr>${t.map(E=>{const d=l[E],u=typeof d=="number",T=d==null?"—":String(d);return`<td${u?' class="num"':""}>${Ge(T)}</td>`}).join("")}</tr>`).join("");return`
|
|
444
|
-
<div class="table-wrap">
|
|
445
|
-
<table>
|
|
446
|
-
<thead><tr>${s}</tr></thead>
|
|
447
|
-
<tbody>${a}</tbody>
|
|
448
|
-
</table>
|
|
449
|
-
${o?`<p class="truncated">Showing first 200 of ${n.length.toLocaleString()} rows</p>`:""}
|
|
450
|
-
</div>`}function Zx(e){const{columns:t,rows:n}=e;if(t.length<2||n.length===0)return null;const r=t.find(s=>typeof n[0][s]=="number"),o=t.find(s=>s!==r);return!r||!o?null:{labelCol:o,valueCol:r}}function ey(e){const t=Zx(e);if(!t)return null;const n=e.rows.slice(0,20).map(d=>({label:String(d[t.labelCol]??""),value:Number(d[t.valueCol]??0)})),r=Math.max(...n.map(d=>d.value),1),o=28,s=6,a=140,l=440,c=n.length*(o+s)+40,E=n.map((d,u)=>{const T=u*(o+s)+20,S=Math.max(d.value/r*l,2);return`
|
|
451
|
-
<text x="${a-6}" y="${T+o/2+4}" text-anchor="end" font-size="11" fill="#8b949e">${Ge(d.label.slice(0,20))}</text>
|
|
452
|
-
<rect x="${a}" y="${T}" width="${S}" height="${o}" rx="3" fill="#388bfd" />
|
|
453
|
-
<text x="${a+S+5}" y="${T+o/2+4}" font-size="11" fill="#e6edf3">${Jx(d.value)}</text>`}).join("");return`<svg xmlns="http://www.w3.org/2000/svg" width="${a+l+80}" height="${c}" style="max-width:100%">${E}</svg>`}function ty(e,t){const n=t.map(r=>{if(r.type==="markdown")return`<section class="cell md-cell">${qx(r.content)}</section>`;const o=r.name?`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span><span class="cell-name">${Ge(r.name)}</span></div>`:`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span></div>`,s=`<pre class="cell-code"><code>${Ge(r.content)}</code></pre>`;let a="";if(r.result&&r.result.rows.length>0){const l=ey(r.result),c=Qx(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">⚠ ${Ge(r.error)}</div>`);return`<section class="cell sql-cell">${o}${s}${a}</section>`}).join(`
|
|
454
|
-
`);return`<!DOCTYPE html>
|
|
455
|
-
<html lang="en">
|
|
456
|
-
<head>
|
|
457
|
-
<meta charset="UTF-8">
|
|
458
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
459
|
-
<title>${Ge(e)}</title>
|
|
460
|
-
<style>
|
|
461
|
-
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
|
462
|
-
body {
|
|
463
|
-
font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
464
|
-
background: #0d1117; color: #e6edf3;
|
|
465
|
-
line-height: 1.6; padding: 0;
|
|
466
|
-
}
|
|
467
|
-
.page-header {
|
|
468
|
-
background: #161b22; border-bottom: 1px solid #21262d;
|
|
469
|
-
padding: 16px 32px; display: flex; align-items: center; gap: 12px;
|
|
470
|
-
}
|
|
471
|
-
.logo {
|
|
472
|
-
width: 28px; height: 28px; border-radius: 6px;
|
|
473
|
-
background: linear-gradient(135deg, #388bfd, #1f6feb);
|
|
474
|
-
display: flex; align-items: center; justify-content: center;
|
|
475
|
-
font-size: 10px; font-weight: 700; color: #fff;
|
|
476
|
-
font-family: monospace; letter-spacing: -0.5px; flex-shrink: 0;
|
|
477
|
-
}
|
|
478
|
-
.page-title { font-size: 18px; font-weight: 600; color: #e6edf3; }
|
|
479
|
-
.page-meta { font-size: 12px; color: #8b949e; margin-left: auto; }
|
|
480
|
-
.content { max-width: 900px; margin: 0 auto; padding: 32px 24px; display: flex; flex-direction: column; gap: 24px; }
|
|
481
|
-
.cell { border-radius: 8px; overflow: hidden; }
|
|
482
|
-
.md-cell { padding: 4px 0; }
|
|
483
|
-
.md-cell h1 { font-size: 26px; font-weight: 700; color: #e6edf3; margin: 0 0 12px; }
|
|
484
|
-
.md-cell h2 { font-size: 20px; font-weight: 600; color: #e6edf3; margin: 20px 0 10px; }
|
|
485
|
-
.md-cell h3 { font-size: 16px; font-weight: 600; color: #e6edf3; margin: 16px 0 8px; }
|
|
486
|
-
.md-cell p { color: #c9d1d9; margin-bottom: 8px; }
|
|
487
|
-
.md-cell ul { padding-left: 20px; color: #c9d1d9; margin-bottom: 8px; }
|
|
488
|
-
.md-cell code { background: #21262d; padding: 2px 6px; border-radius: 4px; font-family: monospace; font-size: 13px; }
|
|
489
|
-
.md-cell pre { background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 14px; overflow-x: auto; margin-bottom: 8px; }
|
|
490
|
-
.md-cell pre code { background: none; padding: 0; }
|
|
491
|
-
.md-cell blockquote { border-left: 3px solid #388bfd; padding-left: 14px; color: #8b949e; }
|
|
492
|
-
.sql-cell { background: #161b22; border: 1px solid #30363d; }
|
|
493
|
-
.cell-header { display: flex; align-items: center; gap: 8px; padding: 8px 14px; border-bottom: 1px solid #21262d; background: #1c2128; }
|
|
494
|
-
.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; }
|
|
495
|
-
.cell-name { font-size: 12px; color: #388bfd; font-family: monospace; }
|
|
496
|
-
.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; }
|
|
497
|
-
.cell-output { padding: 14px; }
|
|
498
|
-
.output-meta { font-size: 11px; color: #8b949e; margin-bottom: 10px; }
|
|
499
|
-
.table-wrap { overflow-x: auto; }
|
|
500
|
-
table { width: 100%; border-collapse: collapse; font-size: 12px; }
|
|
501
|
-
th { background: #1c2128; color: #8b949e; font-weight: 600; text-align: left; padding: 7px 12px; border-bottom: 1px solid #30363d; white-space: nowrap; }
|
|
502
|
-
td { padding: 6px 12px; border-bottom: 1px solid #21262d; color: #e6edf3; }
|
|
503
|
-
td.num { text-align: right; font-family: monospace; }
|
|
504
|
-
tr:last-child td { border-bottom: none; }
|
|
505
|
-
.truncated { font-size: 11px; color: #8b949e; margin-top: 8px; }
|
|
506
|
-
.cell-error { padding: 12px 14px; background: #3d1a1a; border-top: 1px solid #f85149; color: #f85149; font-size: 13px; }
|
|
507
|
-
.exported-by { text-align: center; color: #484f58; font-size: 11px; padding: 40px 0 24px; }
|
|
508
|
-
</style>
|
|
509
|
-
</head>
|
|
510
|
-
<body>
|
|
511
|
-
<div class="page-header">
|
|
512
|
-
<div class="logo">DQL</div>
|
|
513
|
-
<span class="page-title">${Ge(e)}</span>
|
|
514
|
-
<span class="page-meta">Exported ${new Date().toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}</span>
|
|
515
|
-
</div>
|
|
516
|
-
<div class="content">
|
|
517
|
-
${n}
|
|
518
|
-
</div>
|
|
519
|
-
<p class="exported-by">Built with DQL Notebook</p>
|
|
520
|
-
</body>
|
|
521
|
-
</html>`}function _d(e,t){const n=ty(e,t),r=new Blob([n],{type:"text/html;charset=utf-8"}),o=URL.createObjectURL(r),s=document.createElement("a");s.href=o,s.download=`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}-dashboard.html`,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(o)}function ny({t:e}){return i.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"linear-gradient(135deg, #388bfd 0%, #1f6feb 100%)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:i.jsx("span",{style:{color:"#ffffff",fontSize:10,fontWeight:700,fontFamily:e.fontMono,letterSpacing:"-0.5px"},children:"DQL"})})}function ry(){const{state:e,dispatch:t}=Te(),n=oe[e.themeMode],{executeAll:r}=Fi(),[o,s]=f.useState(!1),[a,l]=f.useState(""),[c,E]=f.useState(!1),[d,u]=f.useState(!1),[T,S]=f.useState(!1),[h,A]=f.useState(!1),[R,p]=f.useState(!1),N=f.useRef(null),[I,O]=f.useState(!1),[m,C]=f.useState(!1),g=f.useRef(null),y=f.useRef(null),_=e.mainView==="block_studio"?e.blockStudioDirty:e.notebookDirty,P=e.mainView==="notebook",D=e.mainView==="connection"?"Connections":e.mainView==="reference"?"Quick Reference":e.notebookTitle||"Untitled";f.useEffect(()=>{o&&y.current&&(y.current.focus(),y.current.select())},[o]),f.useEffect(()=>{if(!m)return;function L(U){g.current&&!g.current.contains(U.target)&&C(!1)}return document.addEventListener("mousedown",L),()=>document.removeEventListener("mousedown",L)},[m]);const b=()=>{l(e.notebookTitle),s(!0)},F=()=>{s(!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:yR(e.blockStudioDraft,a.trim())})):t({type:"SET_NOTEBOOK_DIRTY",dirty:!0}))},x=f.useCallback(async()=>{var L;if(e.activeFile){t({type:"SET_SAVING",saving:!0});try{if(e.mainView==="block_studio"){if(!e.blockStudioMetadata)return;const U=await Z.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:`${U.metadata.name}.dql`,path:U.path,type:"block",folder:"blocks"},payload:U}),e.files.some(G=>G.path===U.path)||t({type:"FILE_ADDED",file:{name:`${U.metadata.name}.dql`,path:U.path,type:"block",folder:"blocks"}})}else{const U=e.activeFile.type==="block"?((L=e.cells[0])==null?void 0:L.content)??"":vx(e.notebookTitle,e.cells,e.notebookMetadata);await Z.saveNotebook(e.activeFile.path,U),t({type:"SET_NOTEBOOK_DIRTY",dirty:!1})}E(!0),setTimeout(()=>E(!1),2e3)}catch(U){console.error("Save failed:",U)}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]);f.useEffect(()=>{const L=U=>{(U.metaKey||U.ctrlKey)&&U.key==="s"&&(U.preventDefault(),x())};return document.addEventListener("keydown",L),()=>document.removeEventListener("keydown",L)},[x]),f.useEffect(()=>{if(!e.autoSave||!_||!e.activeFile)return;const L=setTimeout(()=>{x()},2e3);return()=>clearTimeout(L)},[e.autoSave,_,e.activeFile,e.cells,e.blockStudioDraft,x]);const w=[{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,B=w.find(L=>L.mode===M)??w[0];f.useEffect(()=>{if(!R)return;const L=G=>{N.current&&!N.current.contains(G.target)&&p(!1)},U=G=>{G.key==="Escape"&&p(!1)};return document.addEventListener("mousedown",L),document.addEventListener("keydown",U),()=>{document.removeEventListener("mousedown",L),document.removeEventListener("keydown",U)}},[R]);const v={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 i.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:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[i.jsx(ny,{t:n}),i.jsx("div",{style:{width:1,height:20,background:n.headerBorder,flexShrink:0}}),e.activeFile&&i.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"?o?i.jsx("input",{ref:y,value:a,onChange:L=>l(L.target.value),onBlur:F,onKeyDown:L=>{L.key==="Enter"&&F(),L.key==="Escape"&&s(!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}}):i.jsxs("span",{onClick:b,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:[D,_&&i.jsx("span",{style:{color:n.textMuted,marginLeft:4},children:"●"})]}):i.jsx("span",{style:{color:n.textSecondary,fontSize:13,fontFamily:n.font,padding:"2px 4px"},children:D})]}),i.jsx("div",{style:{flex:1}}),i.jsx(Jg,{options:[{value:"studio",label:"Studio"},{value:"app",label:"App"}],value:e.appMode,onChange:L=>t({type:"SET_APP_MODE",mode:L}),size:"sm",ariaLabel:"View mode"}),i.jsx("div",{style:{flex:1}}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.appMode==="studio"&&i.jsxs(i.Fragment,{children:[i.jsxs("button",{onClick:P?r:void 0,disabled:!e.activeFile||!P,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),style:{...v,background:(d&&e.activeFile,n.accent),color:"#ffffff",border:`1px solid ${n.accent}`,opacity:!e.activeFile||!P?.4:d?.9:1},children:[i.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:i.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})}),"Run All"]}),i.jsx("div",{style:{width:1,height:20,background:n.headerBorder}})]}),e.appMode==="app"&&i.jsxs(i.Fragment,{children:[i.jsxs("button",{onClick:()=>_d(e.notebookTitle||"dashboard",e.cells),disabled:!e.activeFile,title:"Publish dashboard (standalone HTML)",style:{...v,background:n.accent,color:"#ffffff",border:`1px solid ${n.accent}`,opacity:e.activeFile?1:.4},children:[i.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:[i.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"}),i.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"})]}),"Publish"]}),i.jsx("div",{style:{width:1,height:20,background:n.headerBorder}})]}),i.jsxs("div",{ref:N,style:{position:"relative"},children:[i.jsxs("button",{onClick:()=>p(L=>!L),onMouseEnter:()=>A(!0),onMouseLeave:()=>A(!1),title:`Theme: ${B.label}`,"aria-haspopup":"true","aria-expanded":R,style:{...v,background:h||R?n.btnHover:n.btnBg,color:n.textSecondary,padding:"0 10px",fontSize:12,display:"flex",alignItems:"center",gap:6},children:[i.jsx("span",{style:{width:12,height:12,borderRadius:3,background:B.swatch,border:`1px solid ${n.headerBorder}`,flexShrink:0}}),i.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10,letterSpacing:"0.04em"},children:B.label}),i.jsx("span",{style:{fontSize:8,color:n.textMuted},children:"▾"})]}),R&&i.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:w.map(L=>{const U=L.mode===M;return i.jsxs("button",{role:"menuitemradio","aria-checked":U,onClick:()=>{t({type:"SET_THEME",mode:L.mode}),p(!1)},style:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",background:U?n.btnHover:"transparent",color:n.textPrimary,cursor:"pointer",borderRadius:4,fontSize:12,fontFamily:n.font,textAlign:"left"},onMouseEnter:G=>{U||(G.currentTarget.style.background=n.btnHover)},onMouseLeave:G=>{U||(G.currentTarget.style.background="transparent")},children:[i.jsx("span",{style:{width:14,height:14,borderRadius:3,background:L.swatch,border:`1px solid ${n.headerBorder}`,flexShrink:0}}),i.jsx("span",{style:{flex:1},children:L.label}),U&&i.jsx("span",{style:{color:n.accent,fontSize:11},children:"✓"})]},L.mode)})})]}),e.appMode==="studio"&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:x,disabled:!e.activeFile||e.savingFile,onMouseEnter:()=>S(!0),onMouseLeave:()=>S(!1),title:"Save (Cmd+S)",style:{...v,background:T&&e.activeFile?n.btnHover:n.btnBg,color:c?n.success:n.textSecondary,opacity:e.activeFile?1:.4},children:e.savingFile?i.jsxs(i.Fragment,{children:[i.jsx(sy,{}),"Saving…"]}):c?i.jsx(i.Fragment,{children:"✓ Saved"}):i.jsx(i.Fragment,{children:"Save"})}),i.jsx("button",{onClick:()=>t({type:"SET_AUTO_SAVE",enabled:!e.autoSave}),title:e.autoSave?"Auto-save on":"Auto-save off",style:{...v,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"}),i.jsxs("button",{onClick:()=>t({type:"TOGGLE_DASHBOARD_MODE"}),disabled:!e.activeFile,title:e.dashboardMode?"Switch to editor mode":"Switch to dashboard mode",style:{...v,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:[i.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:e.dashboardMode?i.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"}):i.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"]}),i.jsx("div",{style:{width:1,height:20,background:n.headerBorder}}),i.jsxs("div",{ref:g,style:{position:"relative"},children:[i.jsxs("button",{onClick:()=>{e.activeFile&&C(L=>!L)},disabled:!e.activeFile,onMouseEnter:()=>O(!0),onMouseLeave:()=>O(!1),title:"Export options",style:{...v,background:(I||m)&&e.activeFile?n.btnHover:n.btnBg,color:n.textSecondary,opacity:e.activeFile?1:.4},children:[i.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:[i.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"}),i.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"})]}),"Export",i.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"currentColor",style:{marginLeft:1},children:i.jsx("path",{d:"M1 2.5l3 3 3-3",stroke:"currentColor",fill:"none",strokeWidth:"1.2",strokeLinecap:"round"})})]}),m&&i.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:i.jsx(oy,{label:"Export HTML",description:"Standalone dashboard",t:n,onClick:()=>{_d(e.notebookTitle||"dashboard",e.cells),C(!1)}})})]})]})]})]})}function oy({label:e,description:t,t:n,onClick:r}){const[o,s]=f.useState(!1);return i.jsxs("button",{onClick:r,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),style:{background:o?n.btnHover:"transparent",border:"none",borderRadius:5,cursor:"pointer",padding:"6px 10px",textAlign:"left",display:"flex",flexDirection:"column",gap:1,transition:"background 0.12s"},children:[i.jsx("span",{style:{fontSize:12,fontWeight:500,color:n.textPrimary,fontFamily:n.font},children:e}),i.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font},children:t})]})}function sy(){return i.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",style:{animation:"spin 0.8s linear infinite"},children:[i.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"}),i.jsx("circle",{cx:"6",cy:"6",r:"4.5",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"14 7"})]})}function iy(e){return e.toTimeString().slice(0,8)}function ay(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}function ly(){const{state:e,dispatch:t}=Te(),n=oe[e.themeMode],[r,o]=f.useState(!1),s=e.queryLog.filter(l=>l.error),a=l=>t({type:"SET_DEV_PANEL_TAB",tab:l});return i.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&&i.jsxs(i.Fragment,{children:[i.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=>i.jsx(cy,{label:l==="errors"?`Errors${s.length>0?` (${s.length})`:""}`:`Logs (${e.queryLog.length})`,active:e.devPanelTab===l,onClick:()=>a(l),t:n},l)),i.jsx("div",{style:{flex:1}}),i.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"})]}),i.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[e.devPanelTab==="logs"&&(e.queryLog.length===0?i.jsx(xd,{t:n,message:"No queries executed yet."}):[...e.queryLog].reverse().map(l=>i.jsx(yd,{entry:l,t:n},l.id))),e.devPanelTab==="errors"&&(s.length===0?i.jsx(xd,{t:n,message:"No errors."}):[...s].reverse().map(l=>i.jsx(yd,{entry:l,t:n},l.id)))]})]}),i.jsxs("button",{onClick:()=>t({type:"TOGGLE_DEV_PANEL"}),onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),title:e.devPanelOpen?"Close panel":"Open dev panel",style:{position:"absolute",bottom:e.devPanelOpen?4:-28,right:8,height:22,padding:"0 8px",borderRadius:"4px 4px 0 0",borderTop:`1px solid ${n.headerBorder}`,borderLeft:`1px solid ${n.headerBorder}`,borderRight:`1px solid ${n.headerBorder}`,borderBottom:e.devPanelOpen?`1px solid ${n.sidebarBg}`:`1px solid ${n.headerBorder}`,background:r?n.btnHover:n.sidebarBg,color:n.textMuted,cursor:"pointer",fontSize:11,fontFamily:n.font,display:"flex",alignItems:"center",gap:4,transition:"background 0.15s, bottom 0.2s ease",zIndex:10},children:[i.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:i.jsx("path",{d:e.devPanelOpen?"M1 7l4-4 4 4":"M1 3l4 4 4-4",strokeWidth:"1.5",stroke:"currentColor",fill:"none"})}),"Dev"]})]})}function cy({label:e,active:t,onClick:n,t:r}){const[o,s]=f.useState(!1);return i.jsx("button",{onClick:n,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),style:{background:"transparent",borderTop:"none",borderLeft:"none",borderRight:"none",borderBottom:t?`2px solid ${r.accent}`:"2px solid transparent",cursor:"pointer",color:t?r.textPrimary:o?r.textSecondary:r.textMuted,fontSize:12,fontFamily:r.font,fontWeight:t?500:400,padding:"4px 8px",height:32,transition:"color 0.15s"},children:e})}function xd({t:e,message:t}){return i.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:e.textMuted,fontSize:12,fontFamily:e.font,fontStyle:"italic"},children:t})}function yd({entry:e,t}){return i.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:[i.jsx("span",{style:{color:t.textMuted,flexShrink:0},children:iy(e.ts)}),i.jsx("span",{style:{flexShrink:0,color:t.textPrimary,maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.cellName}),e.error?i.jsx("span",{style:{color:t.error,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.error}):i.jsxs(i.Fragment,{children:[i.jsxs("span",{style:{color:t.textMuted},children:[e.rows.toLocaleString()," rows"]}),i.jsx("span",{style:{color:t.textMuted},children:ay(e.time)})]})]})}function Ey({onOpenFile:e}){const{state:t,dispatch:n}=Te(),r=oe[t.themeMode],o=t.files.slice(0,3);return i.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",background:r.appBg,padding:40,overflow:"auto"},children:i.jsxs("div",{style:{maxWidth:720,width:"100%",display:"flex",flexDirection:"column",alignItems:"center",gap:48},children:[i.jsxs("div",{style:{textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[i.jsx("div",{style:{width:72,height:72,borderRadius:16,background:"linear-gradient(135deg, #388bfd 0%, #1f6feb 60%, #0d419d 100%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 8px 32px rgba(56,139,253,0.3)"},children:i.jsx("span",{style:{color:"#fff",fontSize:26,fontWeight:800,fontFamily:r.fontMono,letterSpacing:"-1px"},children:"DQL"})}),i.jsxs("div",{children:[i.jsx("h1",{style:{fontSize:32,fontWeight:700,color:r.textPrimary,fontFamily:r.font,marginBottom:8,letterSpacing:"-0.5px"},children:"DQL Notebook"}),i.jsx("p",{style:{fontSize:15,color:r.textSecondary,fontFamily:r.font,letterSpacing:"0.02em"},children:"Analytics as Code"})]})]}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:16,width:"100%"},children:[i.jsx(Dd,{title:"New Notebook",description:"Start a fresh analysis with an empty notebook.",icon:i.jsx(Ty,{}),accent:r.accent,onClick:()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}),t:r}),i.jsx(dy,{recentFiles:o,onOpenFile:e,t:r}),i.jsx(Dd,{title:"New Block",description:"Create a reusable SQL block file.",icon:i.jsx(fy,{}),accent:"#e3b341",onClick:()=>n({type:"OPEN_NEW_BLOCK_MODAL"}),t:r})]}),i.jsxs("div",{style:{width:"100%",borderRadius:10,border:`1px solid ${r.cellBorder}`,padding:"16px 20px",background:r.cellBg},children:[i.jsx("div",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.08em",textTransform:"uppercase",color:r.textMuted,fontFamily:r.font,marginBottom:12},children:"Quick Tips"}),i.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(([s,a])=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.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:s}),i.jsx("span",{style:{fontSize:12,color:r.textMuted,fontFamily:r.font},children:a})]},s))})]})]})})}function Dd({title:e,description:t,icon:n,accent:r,onClick:o,t:s}){const[a,l]=f.useState(!1);return i.jsxs("button",{onClick:o,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{background:a?s.cellBg:"transparent",border:`1px solid ${a?r:s.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:[i.jsx("div",{style:{width:36,height:36,borderRadius:8,background:`${r}18`,display:"flex",alignItems:"center",justifyContent:"center",color:r},children:n}),i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:13,fontWeight:600,color:s.textPrimary,fontFamily:s.font,marginBottom:4},children:e}),i.jsx("div",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font,lineHeight:1.5},children:t})]})]})}function dy({recentFiles:e,onOpenFile:t,t:n}){const[r,o]=f.useState(!1);return i.jsxs("div",{onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!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:[i.jsx("div",{style:{width:36,height:36,borderRadius:8,background:`${n.warning}18`,display:"flex",alignItems:"center",justifyContent:"center",color:n.warning},children:i.jsx(Sy,{})}),i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:13,fontWeight:600,color:n.textPrimary,fontFamily:n.font,marginBottom:8},children:"Open Recent"}),e.length===0?i.jsx("div",{style:{fontSize:12,color:n.textMuted,fontFamily:n.font,fontStyle:"italic"},children:"No recent files."}):i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:e.map(s=>i.jsx(uy,{file:s,onClick:()=>t(s),t:n},s.path))})]})]})}function uy({file:e,onClick:t,t:n}){const[r,o]=f.useState(!1);return i.jsx("button",{onClick:t,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!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 Ty(){return i.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:i.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 Sy(){return i.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:i.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 fy(){return i.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:i.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 Md=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class Qr{constructor(t,n,r=0,o=t.length,s,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,o),this.bufferStart=r,this.normalize=s?l=>s(Md(l)):Md,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 tI(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=aI(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=nI(t);let o=this.normalize(n);if(o.length)for(let s=0,a=r;;s++){let l=o.charCodeAt(s),c=this.match(l,a,this.bufferPos+this.bufferStart);if(s==o.length-1){if(c)return this.value=c,this;break}a==r&&s<n.length&&n.charCodeAt(s)==l&&a++}}}match(t,n,r){let o=null;for(let s=0;s<this.matches.length;s+=2){let a=this.matches[s],l=!1;this.query.charCodeAt(a)==t&&(a==this.query.length-1?o={from:this.matches[s+1],to:r}:(this.matches[s]++,l=!0)),l||(this.matches.splice(s,2),s-=2)}return this.query.charCodeAt(0)==t&&(this.query.length==1?o={from:n,to:r}:this.matches.push(1,n)),o&&this.test&&!this.test(o.from,o.to,this.buffer,this.bufferStart)&&(o=null),o}}typeof Symbol<"u"&&(Qr.prototype[Symbol.iterator]=function(){return this});const DR={from:-1,to:-1,match:/.*/.exec("")},Kc="gm"+(/x/.unicode==null?"":"u");class MR{constructor(t,n,r,o=0,s=t.length){if(this.text=t,this.to=s,this.curLine="",this.done=!1,this.value=DR,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new PR(t,n,r,o,s);this.re=new RegExp(n,Kc+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.iter=t.iter();let a=t.lineAt(o);this.curLineStart=a.from,this.matchPos=Qs(t,o),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,o=r+n[0].length;if(this.matchPos=Qs(this.text,o+(r==o?1:0)),r==this.curLineStart+this.curLine.length&&this.nextLine(),(r<o||r>this.value.to)&&(!this.test||this.test(r,o,n)))return this.value={from:r,to:o,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 wa=new WeakMap;class tr{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let o=wa.get(t);if(!o||o.from>=r||o.to<=n){let l=new tr(n,t.sliceString(n,r));return wa.set(t,l),l}if(o.from==n&&o.to==r)return o;let{text:s,from:a}=o;return a>n&&(s=t.sliceString(n,a)+s,a=n),o.to<r&&(s+=t.sliceString(o.to,r)),wa.set(t,new tr(a,s)),new tr(n,s.slice(n-a,r-a))}}class PR{constructor(t,n,r,o,s){this.text=t,this.to=s,this.done=!1,this.value=DR,this.matchPos=Qs(t,o),this.re=new RegExp(n,Kc+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.flat=tr.get(t,o,this.chunkEnd(o+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,o=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,o,n)))return this.value={from:r,to:o,match:n},this.matchPos=Qs(this.text,o+(r==o?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=tr.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(MR.prototype[Symbol.iterator]=PR.prototype[Symbol.iterator]=function(){return this});function Ry(e){try{return new RegExp(e,Kc),!0}catch{return!1}}function Qs(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 Ay=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:o}=Qh(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return o.then(s=>{let a=s&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(s.elements.line.value);if(!a){e.dispatch({effects:r});return}let l=t.doc.lineAt(t.selection.main.head),[,c,E,d,u]=a,T=d?+d.slice(1):0,S=E?+E:l.number;if(E&&u){let R=S/100;c&&(R=R*(c=="-"?-1:1)+l.number/t.doc.lines),S=Math.round(t.doc.lines*R)}else E&&c&&(S=S*(c=="-"?-1:1)+l.number);let h=t.doc.line(Math.max(1,Math.min(t.doc.lines,S))),A=ct.cursor(h.from+Math.max(0,Math.min(T,h.length)));e.dispatch({effects:[r,Be.scrollIntoView(A.from,{y:"center"})],selection:A})}),!0},py=({state:e,dispatch:t})=>{let{selection:n}=e,r=ct.create(n.ranges.map(o=>e.wordAt(o.head)||ct.cursor(o.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function hy(e,t){let{main:n,ranges:r}=e.selection,o=e.wordAt(n.head),s=o&&o.from==n.from&&o.to==n.to;for(let a=!1,l=new Qr(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(a)return null;l=new Qr(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(s){let c=e.wordAt(l.value.from);if(!c||c.from!=l.value.from||c.to!=l.value.to)continue}return l.value}}const Iy=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(s=>s.from===s.to))return py({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(s=>e.sliceDoc(s.from,s.to)!=r))return!1;let o=hy(e,r);return o?(t(e.update({selection:e.selection.addRange(ct.range(o.from,o.to),!1),effects:Be.scrollIntoView(o.to)})),!0):!1},vn=rI.define({combine(e){return oI(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new Uy(t),scrollToMatch:t=>Be.scrollIntoView(t)})}});function Ny(e){return e?[vn.of(e),Wl]:Wl}class bR{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||Ry(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"?`
|
|
522
|
-
`: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 _y(this):new Cy(this)}getCursor(t,n=0,r){let o=t.doc?t:cS.create({doc:t});return r==null&&(r=o.doc.length),this.regexp?Jn(this,o,n,r):zn(this,o,n,r)}}class vR{constructor(t){this.spec=t}}function Oy(e,t,n){return(r,o,s,a)=>{if(n&&!n(r,o,s,a))return!1;let l=r>=a&&o<=a+s.length?s.slice(r-a,o-a):t.doc.sliceString(r,o);return e(l,t,r,o)}}function zn(e,t,n,r){let o;return e.wholeWord&&(o=my(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(o=Oy(e.test,t,o)),new Qr(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:s=>s.toLowerCase(),o)}function my(e,t){return(n,r,o,s)=>((s>n||s+o.length<r)&&(s=Math.max(0,n-2),o=e.sliceString(s,Math.min(e.length,r+2))),(t(Zs(o,n-s))!=Qt.Word||t(ei(o,n-s))!=Qt.Word)&&(t(ei(o,r-s))!=Qt.Word||t(Zs(o,r-s))!=Qt.Word))}class Cy extends vR{constructor(t){super(t)}nextMatch(t,n,r){let o=zn(this.spec,t,r,t.doc.length).nextOverlapping();if(o.done){let s=Math.min(t.doc.length,n+this.spec.unquoted.length);o=zn(this.spec,t,0,s).nextOverlapping()}return o.done||o.value.from==n&&o.value.to==r?null:o.value}prevMatchInRange(t,n,r){for(let o=r;;){let s=Math.max(n,o-1e4-this.spec.unquoted.length),a=zn(this.spec,t,s,o),l=null;for(;!a.nextOverlapping().done;)l=a.value;if(l)return l;if(s==n)return null;o-=1e4}}prevMatch(t,n,r){let o=this.prevMatchInRange(t,0,n);return o||(o=this.prevMatchInRange(t,Math.max(0,r-this.spec.unquoted.length),t.doc.length)),o&&(o.from!=n||o.to!=r)?o:null}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,n){let r=zn(this.spec,t,0,t.doc.length),o=[];for(;!r.next().done;){if(o.length>=n)return null;o.push(r.value)}return o}highlight(t,n,r,o){let s=zn(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!s.next().done;)o(s.value.from,s.value.to)}}function gy(e,t,n){return(r,o,s)=>(!n||n(r,o,s))&&e(s[0],t,r,o)}function Jn(e,t,n,r){let o;return e.wholeWord&&(o=Ly(t.charCategorizer(t.selection.main.head))),e.test&&(o=gy(e.test,t,o)),new MR(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:o},n,r)}function Zs(e,t){return e.slice(ES(e,t,!1),t)}function ei(e,t){return e.slice(t,ES(e,t))}function Ly(e){return(t,n,r)=>!r[0].length||(e(Zs(r.input,r.index))!=Qt.Word||e(ei(r.input,r.index))!=Qt.Word)&&(e(ei(r.input,r.index+r[0].length))!=Qt.Word||e(Zs(r.input,r.index+r[0].length))!=Qt.Word)}class _y extends vR{nextMatch(t,n,r){let o=Jn(this.spec,t,r,t.doc.length).next();return o.done&&(o=Jn(this.spec,t,0,n).next()),o.done?null:o.value}prevMatchInRange(t,n,r){for(let o=1;;o++){let s=Math.max(n,r-o*1e4),a=Jn(this.spec,t,s,r),l=null;for(;!a.next().done;)l=a.value;if(l&&(s==n||l.from>s+10))return l;if(s==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 o=r.length;o>0;o--){let s=+r.slice(0,o);if(s>0&&s<t.match.length)return t.match[s]+r.slice(o)}return n})}matchAll(t,n){let r=Jn(this.spec,t,0,t.doc.length),o=[];for(;!r.next().done;){if(o.length>=n)return null;o.push(r.value)}return o}highlight(t,n,r,o){let s=Jn(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!s.next().done;)o(s.value.from,s.value.to)}}const Zr=Ni.define(),zc=Ni.define(),Zt=lS.define({create(e){return new Ba(Yl(e).create(),null)},update(e,t){for(let n of t.effects)n.is(Zr)?e=new Ba(n.value.create(),e.panel):n.is(zc)&&(e=new Ba(e.query,n.value?Jc:null));return e},provide:e=>Zh.from(e,t=>t.panel)});class Ba{constructor(t,n){this.query=t,this.panel=n}}const xy=In.mark({class:"cm-searchMatch"}),yy=In.mark({class:"cm-searchMatch cm-searchMatch-selected"}),Dy=sI.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Zt))}update(e){let t=e.state.field(Zt);(t!=e.startState.field(Zt)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return In.none;let{view:n}=this,r=new iI;for(let o=0,s=n.visibleRanges,a=s.length;o<a;o++){let{from:l,to:c}=s[o];for(;o<a-1&&c>s[o+1].from-500;)c=s[++o].to;e.highlight(n.state,l,c,(E,d)=>{let u=n.state.selection.ranges.some(T=>T.from==E&&T.to==d);r.add(E,d,u?yy:xy)})}return r.finish()}},{decorations:e=>e.decorations});function Oo(e){return t=>{let n=t.state.field(Zt,!1);return n&&n.query.spec.valid?e(t,n):BR(t)}}const ti=Oo((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let o=ct.single(r.from,r.to),s=e.state.facet(vn);return e.dispatch({selection:o,effects:[qc(e,r),s.scrollToMatch(o.main,e)],userEvent:"select.search"}),wR(e),!0}),ni=Oo((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,o=t.prevMatch(n,r,r);if(!o)return!1;let s=ct.single(o.from,o.to),a=e.state.facet(vn);return e.dispatch({selection:s,effects:[qc(e,o),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),wR(e),!0}),My=Oo((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:ct.create(n.map(r=>ct.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),Py=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:o}=n.main,s=[],a=0;for(let l=new Qr(e.doc,e.sliceDoc(r,o));!l.next().done;){if(s.length>1e3)return!1;l.value.from==r&&(a=s.length),s.push(ct.range(l.value.from,l.value.to))}return t(e.update({selection:ct.create(s,a),userEvent:"select.search.matches"})),!0},Pd=Oo((e,{query:t})=>{let{state:n}=e,{from:r,to:o}=n.selection.main;if(n.readOnly)return!1;let s=t.nextMatch(n,r,r);if(!s)return!1;let a=s,l=[],c,E,d=[];a.from==r&&a.to==o&&(E=n.toText(t.getReplacement(a)),l.push({from:a.from,to:a.to,insert:E}),a=t.nextMatch(n,a.from,a.to),d.push(Be.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+".")));let u=e.state.changes(l);return a&&(c=ct.single(a.from,a.to).map(u),d.push(qc(e,a)),d.push(n.facet(vn).scrollToMatch(c.main,e))),e.dispatch({changes:u,selection:c,effects:d,userEvent:"input.replace"}),!0}),by=Oo((e,{query:t})=>{if(e.state.readOnly)return!1;let n=t.matchAll(e.state,1e9).map(o=>{let{from:s,to:a}=o;return{from:s,to:a,insert:t.getReplacement(o)}});if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:Be.announce.of(r),userEvent:"input.replace.all"}),!0});function Jc(e){return e.state.facet(vn).createPanel(e)}function Yl(e,t){var n,r,o,s,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 E=e.facet(vn);return new bR({search:((n=t==null?void 0:t.literal)!==null&&n!==void 0?n:E.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=t==null?void 0:t.caseSensitive)!==null&&r!==void 0?r:E.caseSensitive,literal:(o=t==null?void 0:t.literal)!==null&&o!==void 0?o:E.literal,regexp:(s=t==null?void 0:t.regexp)!==null&&s!==void 0?s:E.regexp,wholeWord:(a=t==null?void 0:t.wholeWord)!==null&&a!==void 0?a:E.wholeWord})}function UR(e){let t=aS(e,Jc);return t&&t.dom.querySelector("[main-field]")}function wR(e){let t=UR(e);t&&t==e.root.activeElement&&t.select()}const BR=e=>{let t=e.state.field(Zt,!1);if(t&&t.panel){let n=UR(e);if(n&&n!=e.root.activeElement){let r=Yl(e.state,t.query.spec);r.valid&&e.dispatch({effects:Zr.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[zc.of(!0),t?Zr.of(Yl(e.state,t.query.spec)):Ni.appendConfig.of(Wl)]});return!0},FR=e=>{let t=e.state.field(Zt,!1);if(!t||!t.panel)return!1;let n=aS(e,Jc);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:zc.of(!1)}),!0},vy=[{key:"Mod-f",run:BR,scope:"editor search-panel"},{key:"F3",run:ti,shift:ni,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:ti,shift:ni,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:FR,scope:"editor search-panel"},{key:"Mod-Shift-l",run:Py},{key:"Mod-Alt-g",run:Ay},{key:"Mod-d",run:Iy,preventDefault:!0}];class Uy{constructor(t){this.view=t;let n=this.query=t.state.field(Zt).query.spec;this.commit=this.commit.bind(this),this.searchField=qe("input",{value:n.search,placeholder:We(t,"Find"),"aria-label":We(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=qe("input",{value:n.replace,placeholder:We(t,"Replace"),"aria-label":We(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=qe("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=qe("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=qe("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(o,s,a){return qe("button",{class:"cm-button",name:o,onclick:s,type:"button"},a)}this.dom=qe("div",{onkeydown:o=>this.keydown(o),class:"cm-search"},[this.searchField,r("next",()=>ti(t),[We(t,"next")]),r("prev",()=>ni(t),[We(t,"previous")]),r("select",()=>My(t),[We(t,"all")]),qe("label",null,[this.caseField,We(t,"match case")]),qe("label",null,[this.reField,We(t,"regexp")]),qe("label",null,[this.wordField,We(t,"by word")]),...t.state.readOnly?[]:[qe("br"),this.replaceField,r("replace",()=>Pd(t),[We(t,"replace")]),r("replaceAll",()=>by(t),[We(t,"replace all")])],qe("button",{name:"close",onclick:()=>FR(t),"aria-label":We(t,"close"),type:"button"},["×"])])}commit(){let t=new bR({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:Zr.of(t)}))}keydown(t){lI(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?ni:ti)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),Pd(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(Zr)&&!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(vn).top}}function We(e,t){return e.state.phrase(t)}const as=30,ls=/[\s\.,:;?!]/;function qc(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),o=e.state.doc.lineAt(n).to,s=Math.max(r.from,t-as),a=Math.min(o,n+as),l=e.state.sliceDoc(s,a);if(s!=r.from){for(let c=0;c<as;c++)if(!ls.test(l[c+1])&&ls.test(l[c])){l=l.slice(c);break}}if(a!=o){for(let c=l.length-1;c>l.length-as;c--)if(!ls.test(l[c-1])&&ls.test(l[c])){l=l.slice(0,c);break}}return Be.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const wy=Be.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"}}),Wl=[Zt,eI.low(Dy),wy],By=3e4,ri="application/dql-semantic-ref";let cs=[],bd=0,eo=null;function Fy(e){Z.trackUsage(e),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:e}}))}async function vd(){if(Date.now()<bd&&cs.length>0)return cs;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 cs=Array.isArray(t.completions)?t.completions:[],bd=Date.now()+By,cs}function GR(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 Gy(e){eo=e}function Hy(e){eo===e&&(eo=null)}function ky(e){return eo?(GR(eo,e),!0):!1}function jy(e,t,n){const r=n?e.posAtCoords(n)??e.state.selection.main.from:e.state.selection.main.from;GR(e,t,r)}function Ud(e,t,n){return{label:e.name,detail:e.type==="metric"?"@metric":"@dim",type:e.type==="metric"?"function":"variable",info:`${e.label}${e.description?`
|
|
523
|
-
${e.description}`:""}${e.sql?`
|
|
524
|
-
${e.sql}`:""}`,apply(r){const s=r.state.sliceDoc(n,n+1)===")"?e.name:`${e.name})`;r.dispatch({changes:{from:t,to:n,insert:s},selection:{anchor:t+s.length}}),Fy(e.name)}}}function Yy(e){return{from:e,options:[{label:"@metric(",detail:"semantic metric",type:"function",apply(t,n,r,o){t.dispatch({changes:{from:r,to:o,insert:"@metric("},selection:{anchor:r+8}})}},{label:"@dim(",detail:"semantic dimension",type:"function",apply(t,n,r,o){t.dispatch({changes:{from:r,to:o,insert:"@dim("},selection:{anchor:r+5}})}}]}}const Wy=async e=>{const{state:t,pos:n}=e,r=t.sliceDoc(Math.max(0,n-120),n),o=/@metric\(([^)]*)$/i.exec(r);if(o){const l=o[1].trim().toLowerCase(),c=n-o[1].length,E=(await vd()).filter(d=>d.type==="metric").filter(d=>!l||d.name.toLowerCase().includes(l)||d.label.toLowerCase().includes(l)||(d.domain??"").toLowerCase().includes(l)||d.tags.some(u=>u.toLowerCase().includes(l))).slice(0,50);return{from:c,options:E.map(d=>Ud(d,c,n)),validFor:/^[\w-]*$/}}const s=/@dim\(([^)]*)$/i.exec(r);if(s){const l=s[1].trim().toLowerCase(),c=n-s[1].length,E=(await vd()).filter(d=>d.type==="dimension").filter(d=>!l||d.name.toLowerCase().includes(l)||d.label.toLowerCase().includes(l)||(d.domain??"").toLowerCase().includes(l)||d.tags.some(u=>u.toLowerCase().includes(l))).slice(0,50);return{from:c,options:E.map(d=>Ud(d,c,n)),validFor:/^[\w-]*$/}}const a=/@([md][a-z_]*)?$/i.exec(r);return a?Yy(n-a[0].length):(e.explicit,null)};function HR(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 Vy(e){const t=e.match(/LINE\s+(\d+)/i);if(t){const o=parseInt(t[1],10),s=e.match(/\n(\s*)\^/),a=s?s[1].length+1:1;return{line:o,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 Ms=Ni.define(),$y=lS.define({create(){return In.none},update(e,t){for(const n of t.effects)if(n.is(Ms)){if(!n.value)return In.none;const{from:r,to:o,message:s}=n.value;return In.set([In.mark({class:"cm-sql-error",attributes:{title:s}}).range(r,o)])}return e},provide:e=>Be.decorations.from(e)}),Xy=Be.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 kR(e){return Be.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 Ky=kR(!0),zy=kR(!1);function Jy(e){return e==="midnight"||e==="obsidian"||e==="dark"}function Qc({value:e,onChange:t,onRun:n,themeMode:r,autoFocus:o,schema:s,errorMessage:a,editorRef:l}){const c=oe[r],E=f.useRef(null),d=f.useRef(null),[u,T]=f.useState(!1),S=f.useRef(n),h=f.useRef(t),A=f.useRef(new cI);return S.current=n,h.current=t,f.useEffect(()=>{l&&(l.current={undo:()=>{d.current&&dI(d.current)},redo:()=>{d.current&&EI(d.current)},resetTo:R=>{const p=d.current;p&&p.dispatch({changes:{from:0,to:p.state.doc.length,insert:R}})}})}),f.useEffect(()=>{if(!E.current)return;const R=uI.of([{key:"Shift-Enter",run:()=>(S.current(),!0)},{key:"Ctrl-Enter",mac:"Cmd-Enter",run:()=>(S.current(),!0)},{key:"Ctrl-/",mac:"Cmd-/",run:TI},SI,...fI,...RI,...AI,...vy,...pI,...hI]),p=Be.updateListener.of(y=>{y.docChanged&&h.current(y.state.doc.toString())}),N=Be.domEventHandlers({focus:(y,_)=>{Gy(_)},blur:(y,_)=>{Hy(_)}}),I=Be.theme({"&":{background:c.editorBg,fontFamily:c.fontMono,fontSize:"13px",minHeight:"80px",maxHeight:"480px"},".cm-scroller":{overflow:"auto",fontFamily:"inherit"},".cm-content":{padding:"10px 0",minHeight:"80px"},".cm-focused":{outline:"none"},".cm-editor":{border:"none"},".cm-gutters":{minWidth:40},".cm-foldGutter":{cursor:"pointer"}}),O=s?Qo({schema:s,upperCaseKeywords:!1}):Qo({upperCaseKeywords:!1}),m=[R,p,N,I,A.current.of(O),NI({closeOnBlur:!1,override:[Wy]}),OI(),mI(),CI(),gI(),LI(),_I(),xI(),yI(),Be.lineWrapping,Ny({top:!0}),$y,Xy,...Jy(r)?[II,Ky]:[DI(MI),zy]],C=cS.create({doc:e,extensions:m}),g=new Be({state:C,parent:E.current});return d.current=g,o&&g.focus(),()=>{g.destroy(),d.current=null}},[r]),f.useEffect(()=>{const R=d.current;if(!R)return;const p=s?Qo({schema:s,upperCaseKeywords:!1}):Qo({upperCaseKeywords:!1});R.dispatch({effects:A.current.reconfigure(p)})},[s]),f.useEffect(()=>{const R=d.current;if(!R)return;const p=R.state.doc.toString();p!==e&&R.dispatch({changes:{from:0,to:p.length,insert:e}})},[e]),f.useEffect(()=>{const R=d.current;if(!R)return;if(!a){R.dispatch({effects:Ms.of(null)});return}const p=Vy(a),N=R.state.doc;if(p&&p.line>=1&&p.line<=N.lines){const I=N.line(p.line),O=I.from+Math.max(0,p.col-1),m=Math.max(O+1,I.to);R.dispatch({effects:Ms.of({from:Math.min(O,N.length),to:Math.min(m,N.length),message:a})})}else if(N.lines>=1){const I=N.line(1);R.dispatch({effects:Ms.of({from:I.from,to:Math.max(I.from+1,I.to),message:a})})}},[a]),i.jsx("div",{onDragOver:R=>{R.dataTransfer.types.includes(ri)&&(R.preventDefault(),T(!0))},onDragLeave:()=>T(!1),onDrop:R=>{const p=d.current;if(!p)return;const N=HR(R.dataTransfer.getData(ri));N&&(R.preventDefault(),T(!1),jy(p,N.reference,{x:R.clientX,y:R.clientY}),Z.trackUsage(N.name),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:N.name}})))},style:{background:c.editorBg,minHeight:80,border:u?`1px solid ${c.accent}`:"1px solid transparent",borderRadius:6,transition:"border-color 0.15s"},children:i.jsx("div",{ref:E,style:{minHeight:80}})})}Qc.displayName="SQLCellEditor";function qy(e,t){const n=e.split(`
|
|
525
|
-
`),r=[];let o=0;for(;o<n.length;){const s=n[o],a=s.match(/^(#{1,6})\s+(.+)$/);if(a){const l=a[1].length,c=a[2],d=[28,22,18,16,14,13][l-1];r.push(i.jsx("div",{style:{fontSize:d,fontWeight:l<=2?700:600,color:t.textPrimary,fontFamily:t.font,lineHeight:1.3,marginBottom:l===1?12:8,marginTop:o>0?l===1?16:10:0,borderBottom:l===1?`1px solid ${t.cellBorder}`:void 0,paddingBottom:l===1?8:void 0},children:vr(c,t)},o)),o++;continue}if(/^[-*_]{3,}$/.test(s.trim())){r.push(i.jsx("hr",{style:{border:"none",borderTop:`1px solid ${t.cellBorder}`,margin:"12px 0"}},o)),o++;continue}if(s.startsWith("> ")){r.push(i.jsx("div",{style:{borderLeft:`3px solid ${t.textMuted}`,paddingLeft:12,marginLeft:4,color:t.textSecondary,fontStyle:"italic",fontFamily:t.fontSerif,fontSize:14},children:vr(s.slice(2),t)},o)),o++;continue}if(s.startsWith("```")){const l=[];for(o++;o<n.length&&!n[o].startsWith("```");)l.push(n[o]),o++;r.push(i.jsx("pre",{style:{background:t.editorBg,border:`1px solid ${t.cellBorder}`,borderRadius:6,padding:"10px 12px",fontSize:12,fontFamily:t.fontMono,color:t.textPrimary,overflow:"auto",margin:"8px 0",lineHeight:1.6},children:l.join(`
|
|
526
|
-
`)},o)),o++;continue}if(/^[-*+]\s/.test(s)){const l=o,c=[];for(;o<n.length&&/^[-*+]\s/.test(n[o]);)c.push(n[o].replace(/^[-*+]\s/,"")),o++;r.push(i.jsx("ul",{style:{paddingLeft:20,marginBottom:8,color:t.textSecondary},children:c.map((E,d)=>i.jsx("li",{style:{fontSize:14,fontFamily:t.font,lineHeight:1.6,marginBottom:2},children:vr(E,t)},d))},`ul-${l}`));continue}if(/^\d+\.\s/.test(s)){const l=o,c=[];for(;o<n.length&&/^\d+\.\s/.test(n[o]);)c.push(n[o].replace(/^\d+\.\s/,"")),o++;r.push(i.jsx("ol",{style:{paddingLeft:20,marginBottom:8,color:t.textSecondary},children:c.map((E,d)=>i.jsx("li",{style:{fontSize:14,fontFamily:t.font,lineHeight:1.6,marginBottom:2},children:vr(E,t)},d))},`ol-${l}`));continue}if(!s.trim()){r.push(i.jsx("div",{style:{height:8}},o)),o++;continue}r.push(i.jsx("p",{style:{fontSize:14,lineHeight:1.7,fontFamily:t.fontSerif,color:t.textSecondary,marginBottom:6},children:vr(s,t)},o)),o++}return r}function vr(e,t){const n=[];let r=e,o=0;for(;r.length>0;){const s=r.match(/\*{3}(.+?)\*{3}/),a=r.match(/\*{2}(.+?)\*{2}/),l=r.match(/\*(.+?)\*/),c=r.match(/`(.+?)`/),E=r.match(/\[(.+?)\]\((.+?)\)/),d=[s?{match:s,type:"boldItalic"}:null,a?{match:a,type:"bold"}:null,l?{match:l,type:"italic"}:null,c?{match:c,type:"code"}:null,E?{match:E,type:"link"}:null].filter(Boolean);if(d.length===0){n.push(i.jsx(ge.Fragment,{children:r},o++));break}const u=d.reduce((S,h)=>(S.match.index??0)<(h.match.index??0)?S:h),T=u.match.index??0;switch(T>0&&n.push(i.jsx(ge.Fragment,{children:r.slice(0,T)},o++)),u.type){case"boldItalic":n.push(i.jsx("strong",{style:{fontStyle:"italic"},children:u.match[1]},o++));break;case"bold":n.push(i.jsx("strong",{children:u.match[1]},o++));break;case"italic":n.push(i.jsx("em",{children:u.match[1]},o++));break;case"code":n.push(i.jsx("code",{style:{background:t.editorBg,border:`1px solid ${t.cellBorder}`,borderRadius:4,padding:"1px 5px",fontSize:"0.9em",fontFamily:t.fontMono,color:t.accent},children:u.match[1]},o++));break;case"link":n.push(i.jsx("a",{href:u.match[2],target:"_blank",rel:"noopener noreferrer",style:{color:t.accent,textDecoration:"underline"},children:u.match[1]},o++));break}r=r.slice(T+u.match[0].length)}return i.jsx(i.Fragment,{children:n})}function Qy({value:e,onChange:t,onRun:n,themeMode:r}){const o=oe[r],[s,a]=f.useState(!1),l=f.useRef(null);f.useEffect(()=>{if(s&&l.current){l.current.focus();const u=l.current;u.style.height="auto",u.style.height=`${Math.max(u.scrollHeight,80)}px`}},[s]);const c=()=>{a(!1)},E=u=>{if(u.key==="Escape"&&a(!1),u.key==="Enter"&&u.shiftKey&&(u.preventDefault(),a(!1),n==null||n()),u.key==="Tab"){u.preventDefault();const T=u.currentTarget,S=T.selectionStart,h=T.selectionEnd,A=e.slice(0,S)+" "+e.slice(h);t(A),requestAnimationFrame(()=>{T.selectionStart=T.selectionEnd=S+2})}},d=u=>{t(u.target.value);const T=u.target;T.style.height="auto",T.style.height=`${Math.max(T.scrollHeight,80)}px`};return s?i.jsx("textarea",{ref:l,value:e,onChange:d,onBlur:c,onKeyDown:E,placeholder:"Write markdown here...",spellCheck:!1,style:{display:"block",width:"100%",minHeight:80,padding:"12px 16px",background:o.editorBg,color:o.textPrimary,border:"none",outline:"none",resize:"none",fontFamily:o.fontMono,fontSize:13,lineHeight:"20px",borderRadius:0,caretColor:o.accent}}):e.trim()?i.jsx("div",{onDoubleClick:()=>a(!0),title:"Double-click to edit",style:{padding:"12px 16px",cursor:"text",minHeight:48},children:qy(e,o)}):i.jsx("div",{onDoubleClick:()=>a(!0),style:{padding:"12px 16px",color:o.textMuted,fontFamily:o.font,fontSize:13,fontStyle:"italic",cursor:"text",minHeight:48,display:"flex",alignItems:"center"},children:"Double-click to add markdown..."})}function Zy({cell:e,themeMode:t,onApplyParam:n}){const{dispatch:r}=Te(),o=oe[t],[s,a]=f.useState(!1),l=e.paramConfig??{paramType:"text",label:"Parameter",defaultValue:"",options:[]},c=e.paramValue??l.defaultValue,E=S=>{r({type:"UPDATE_CELL",id:e.id,updates:{paramConfig:{...l,...S}}})},d=S=>{r({type:"SET_PARAM_VALUE",id:e.id,value:S})},u=(l.options??[]).map(S=>S.trim()).filter(Boolean),T=e.name?`{{${e.name}}}`:null;return i.jsxs("div",{style:{background:o.cellBg,border:`1px solid ${o.cellBorder}`,borderLeft:`3px solid ${o.warning}`,borderRadius:8,overflow:"hidden"},children:[s&&i.jsxs("div",{style:{background:o.tableHeaderBg,borderBottom:`1px solid ${o.cellBorder}`,padding:"12px 14px",display:"flex",flexDirection:"column",gap:10},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:2},children:[i.jsx("span",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.06em",color:o.warning,fontFamily:o.fontMono,textTransform:"uppercase"},children:"Configure Parameter"}),i.jsx("button",{onClick:()=>a(!1),title:"Done",style:{background:o.warning,border:"none",borderRadius:5,cursor:"pointer",color:"#000",fontSize:11,fontWeight:700,fontFamily:o.font,padding:"3px 10px",display:"flex",alignItems:"center",gap:4},children:"✓ Done"})]}),i.jsxs("div",{style:{display:"flex",gap:10,flexWrap:"wrap"},children:[i.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[i.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Variable name"}),i.jsx("input",{value:e.name??"",onChange:S=>r({type:"UPDATE_CELL",id:e.id,updates:{name:S.target.value||void 0}}),placeholder:"e.g. start_date",style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:4,color:o.textPrimary,fontSize:12,fontFamily:o.fontMono,padding:"4px 7px",outline:"none"}})]}),i.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[i.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Display label"}),i.jsx("input",{value:l.label,onChange:S=>E({label:S.target.value}),placeholder:"e.g. Start Date",style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:4,color:o.textPrimary,fontSize:12,fontFamily:o.font,padding:"4px 7px",outline:"none"}})]}),i.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 100px"},children:[i.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Type"}),i.jsxs("select",{value:l.paramType,onChange:S=>E({paramType:S.target.value}),style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:4,color:o.textPrimary,fontSize:12,fontFamily:o.font,padding:"4px 7px",outline:"none"},children:[i.jsx("option",{value:"text",children:"Text"}),i.jsx("option",{value:"number",children:"Number"}),i.jsx("option",{value:"date",children:"Date"}),i.jsx("option",{value:"select",children:"Select"})]})]}),i.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[i.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Default value"}),i.jsx("input",{type:l.paramType==="number"?"number":l.paramType==="date"?"date":"text",value:l.defaultValue,onChange:S=>E({defaultValue:S.target.value}),style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:4,color:o.textPrimary,fontSize:12,fontFamily:o.font,padding:"4px 7px",outline:"none"}})]})]}),l.paramType==="select"&&i.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3},children:[i.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Options (one per line)"}),i.jsx("textarea",{value:(l.options??[]).join(`
|
|
527
|
-
`),onChange:S=>E({options:S.target.value.split(`
|
|
528
|
-
`)}),rows:4,placeholder:`Option A
|
|
529
|
-
Option B
|
|
530
|
-
Option C`,style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:4,color:o.textPrimary,fontSize:12,fontFamily:o.fontMono,padding:"5px 7px",outline:"none",resize:"vertical"}})]})]}),i.jsxs("div",{style:{padding:"12px 14px",display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[i.jsx("button",{onClick:()=>a(S=>!S),title:s?"Close config":"Configure parameter",style:{background:s?`${o.warning}18`:"transparent",border:`1px solid ${s?o.warning:o.cellBorder}`,borderRadius:5,cursor:"pointer",color:s?o.warning:o.textMuted,width:26,height:26,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,transition:"all 0.15s"},children:s?i.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"})}):i.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"})})}),i.jsx("span",{style:{fontSize:13,fontWeight:500,fontFamily:o.font,color:o.textSecondary,flexShrink:0},children:l.label}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[l.paramType==="select"?i.jsx("select",{value:c,onChange:S=>d(S.target.value),style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:5,color:o.textPrimary,fontSize:13,fontFamily:o.font,padding:"5px 10px",outline:"none",minWidth:160},children:u.length===0?i.jsx("option",{value:"",children:"— no options configured —"}):u.map(S=>i.jsx("option",{value:S,children:S},S))}):i.jsx("input",{type:l.paramType,value:c,onChange:S=>d(S.target.value),style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:5,color:o.textPrimary,fontSize:13,fontFamily:l.paramType==="number"?o.fontMono:o.font,padding:"5px 10px",outline:"none",minWidth:160}}),T&&i.jsx("span",{style:{fontSize:10,fontFamily:o.fontMono,color:o.warning,opacity:.8},children:T})]}),c&&i.jsx("span",{style:{fontSize:12,fontFamily:o.fontMono,color:o.textPrimary,background:`${o.warning}18`,border:`1px solid ${o.warning}40`,borderRadius:4,padding:"2px 8px",flexShrink:0},children:c}),e.name&&n&&i.jsx("button",{onClick:()=>n(e.name),title:`Re-run cells that use {{${e.name}}}`,style:{background:o.warning,border:"none",borderRadius:5,cursor:"pointer",color:"#000",fontSize:11,fontWeight:600,fontFamily:o.font,padding:"4px 12px",flexShrink:0,transition:"opacity 0.15s"},children:"Apply"})]})]})}function e0({cell:e,themeMode:t,title:n,subtitle:r,color:o,badge:s}){const a=oe[t];return i.jsx(ER,{typeLabel:n,typeColor:o,idleBorder:a.cellBorder,background:a.cellBg,headerBackground:`${a.tableHeaderBg}80`,title:e.name?i.jsx("span",{style:{fontSize:12,fontFamily:a.fontMono,color:a.textSecondary},children:e.name}):void 0,actions:s?i.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:s}):void 0,children:i.jsx("div",{style:{padding:"12px 14px",fontSize:12,color:a.textSecondary,lineHeight:1.5,fontFamily:a.font},children:r})})}function t0(e){return e.type==="param"?"param":e.type.toUpperCase()}function n0({cells:e,index:t,content:n,themeMode:r,onInsertHandle:o}){const s=oe[r],[a,l]=f.useState(!1),c=f.useRef(null),E=f.useMemo(()=>e.slice(0,t).filter(T=>T.name&&T.name.trim().length>0),[e,t]),d=f.useMemo(()=>wx(n),[n]);f.useEffect(()=>{if(!a)return;const T=S=>{var h;(h=c.current)!=null&&h.contains(S.target)||l(!1)};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[a]);const u=d.length===0?"df":d.length===1?`df: ${d[0]}`:`df: ${d[0]} +${d.length-1}`;return i.jsxs("div",{ref:c,style:{position:"relative",flexShrink:0},children:[i.jsxs("button",{onClick:()=>l(T=>!T),title:"Insert an upstream dataframe handle ({{name}})",style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:10,fontFamily:s.fontMono,fontWeight:600,letterSpacing:"0.04em",color:d.length>0?s.accent:s.textMuted,background:d.length>0?`${s.accent}14`:"transparent",border:`1px solid ${d.length>0?`${s.accent}55`:s.btnBorder}`,borderRadius:4,padding:"1px 6px",cursor:"pointer",textTransform:"lowercase",transition:"border-color 0.15s, color 0.15s"},children:[u,i.jsx("span",{style:{fontSize:8,opacity:.7},children:"▾"})]}),a&&i.jsxs("div",{style:{position:"absolute",top:"calc(100% + 4px)",left:0,zIndex:20,minWidth:220,maxWidth:280,background:s.cellBg,border:`1px solid ${s.cellBorder}`,borderRadius:6,boxShadow:"0 6px 16px rgba(0,0,0,0.25)",padding:4,display:"flex",flexDirection:"column",gap:2},children:[i.jsx("div",{style:{fontSize:9,fontFamily:s.font,fontWeight:700,letterSpacing:"0.1em",color:s.textMuted,textTransform:"uppercase",padding:"4px 8px 2px"},children:"Upstream dataframes"}),E.length===0&&i.jsx("div",{style:{fontSize:11,fontFamily:s.font,color:s.textMuted,padding:"6px 8px 8px",lineHeight:1.4},children:"No named upstream cells yet. Name a cell (click its header) to expose it here."}),E.map(T=>{const S=T.name?d.includes(T.name):!1;return i.jsxs("button",{onClick:()=>{T.name&&o(T.name),l(!1)},style:{display:"flex",alignItems:"center",gap:8,padding:"5px 8px",background:S?`${s.accent}14`:"transparent",border:"none",borderRadius:4,cursor:"pointer",textAlign:"left",color:s.textPrimary,fontFamily:s.fontMono,fontSize:11},onMouseEnter:h=>{S||(h.currentTarget.style.background=s.tableRowHover)},onMouseLeave:h=>{S||(h.currentTarget.style.background="transparent")},children:[i.jsx("span",{style:{fontSize:9,fontFamily:s.fontMono,fontWeight:700,color:s.textMuted,minWidth:36},children:t0(T)}),i.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:T.name}),S&&i.jsx("span",{style:{fontSize:9,color:s.accent,fontWeight:700,letterSpacing:"0.08em"},children:"IN USE"})]},T.id)})]})]})}const r0=/date|time|_at$|_on$|timestamp/i;function o0(e){return typeof e=="number"||typeof e=="string"&&e!==""&&!isNaN(Number(e))}function Zc(e,t){if(r0.test(e))return"date";const n=t.slice(0,40).map(o=>o[e]).filter(o=>o!=null);return n.length===0?"string":n.every(o=>typeof o=="boolean")?"bool":n.every(o=>typeof o=="object")?"json":n.filter(o0).length/n.length>.8?"numeric":"string"}function jR(e){return e==="numeric"?"measure":e==="date"?"temporal":"dimension"}const s0=[25,50,100,500];function Vl(e){return typeof e=="number"?!0:typeof e=="string"?!isNaN(Number(e))&&e.trim()!=="":!1}function i0(e){switch(e){case"numeric":return{icon:"#",color:"#79c0ff"};case"date":return{icon:"📅",color:"#e3b341"};case"bool":return{icon:"T/F",color:"#a371f7"};case"json":return{icon:"{}",color:"#ff7b72"};case"string":default:return{icon:"A",color:"#56d364"}}}function YR(e){return e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}function a0(e,t){return e==null?1:t==null?-1:Vl(e)&&Vl(t)?Number(e)-Number(t):String(e).localeCompare(String(t))}function l0(e,t){const n=a=>a.includes(",")||a.includes('"')||a.includes(`
|
|
531
|
-
`)?`"${a.replace(/"/g,'""')}"`:a,r=e.columns.map(n).join(","),o=e.rows.map(a=>e.columns.map(l=>n(YR(a[l]))).join(",")),s=[r,...o].join(`
|
|
532
|
-
`);WR(s,"export.csv","text/csv")}function c0(e,t){const n=JSON.stringify(e.rows,null,2);WR(n,"export.json","application/json")}function WR(e,t,n){const r=new Blob([e],{type:n}),o=URL.createObjectURL(r),s=document.createElement("a");s.href=o,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(o)}function E0({dir:e,color:t}){return e?i.jsx("svg",{width:"8",height:"10",viewBox:"0 0 8 10",fill:t,style:{marginLeft:3,flexShrink:0},children:e==="asc"?i.jsx("path",{d:"M4 0L7 4H1L4 0Z"}):i.jsx("path",{d:"M4 10L1 6H7L4 10Z"})}):i.jsxs("svg",{width:"8",height:"10",viewBox:"0 0 8 10",fill:t,opacity:.3,style:{marginLeft:3,flexShrink:0},children:[i.jsx("path",{d:"M4 0L7 3.5H1L4 0Z"}),i.jsx("path",{d:"M4 10L1 6.5H7L4 10Z"})]})}function mo({result:e,themeMode:t}){const n=oe[t],[r,o]=f.useState(null),[s,a]=f.useState(null),[l,c]=f.useState(null),[E,d]=f.useState(""),[u,T]=f.useState(50),[S,h]=f.useState(0),A=f.useCallback(C=>{s===C?l==="asc"?c("desc"):l==="desc"?(a(null),c(null)):c("asc"):(a(C),c("asc")),h(0)},[s,l]),R=f.useMemo(()=>{if(!E.trim())return e.rows;const C=E.toLowerCase();return e.rows.filter(g=>e.columns.some(y=>{const _=g[y];return _==null?!1:String(_).toLowerCase().includes(C)}))},[e.rows,e.columns,E]),p=f.useMemo(()=>{if(!s||!l)return R;const C=[...R];return C.sort((g,y)=>{const _=a0(g[s],y[s]);return l==="desc"?-_:_}),C},[R,s,l]),N=f.useMemo(()=>{const C=new Map;for(const g of e.columns)C.set(g,Zc(g,e.rows));return C},[e.columns,e.rows]),I=Math.max(1,Math.ceil(p.length/u)),O=Math.min(S,I-1),m=p.slice(O*u,(O+1)*u);return e.columns.length===0?i.jsx("div",{style:{padding:"12px 16px",color:n.textMuted,fontSize:12,fontFamily:n.font,fontStyle:"italic"},children:"Query executed successfully. No columns to display."}):i.jsxs("div",{children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 8px",borderBottom:`1px solid ${n.tableBorder}`,background:`${n.tableHeaderBg}60`,flexWrap:"wrap"},children:[i.jsxs("div",{style:{position:"relative",flex:"0 1 200px",minWidth:120},children:[i.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:n.textMuted,style:{position:"absolute",left:6,top:6},children:i.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"})}),i.jsx("input",{value:E,onChange:C=>{d(C.target.value),h(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"}}),E&&i.jsx("button",{onClick:()=>d(""),style:{position:"absolute",right:4,top:3,background:"none",border:"none",color:n.textMuted,cursor:"pointer",fontSize:12,padding:"0 2px"},children:"×"})]}),i.jsxs("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font},children:[E?`${p.length} of ${e.rows.length}`:`${e.rows.length}`," rows"]}),i.jsx("div",{style:{flex:1}}),i.jsx(wd,{label:"CSV",onClick:()=>l0(e),t:n}),i.jsx(wd,{label:"JSON",onClick:()=>c0(e),t:n}),i.jsx("select",{value:u,onChange:C=>{T(Number(C.target.value)),h(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:s0.map(C=>i.jsxs("option",{value:C,children:[C," / page"]},C))}),I>1&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[i.jsx(Wn,{disabled:O===0,onClick:()=>h(0),t:n,children:"«"}),i.jsx(Wn,{disabled:O===0,onClick:()=>h(O-1),t:n,children:"‹"}),i.jsxs("span",{style:{fontSize:10,color:n.textSecondary,fontFamily:n.font,padding:"0 4px"},children:[O+1,"/",I]}),i.jsx(Wn,{disabled:O>=I-1,onClick:()=>h(O+1),t:n,children:"›"}),i.jsx(Wn,{disabled:O>=I-1,onClick:()=>h(I-1),t:n,children:"»"})]})]}),i.jsx("div",{style:{maxHeight:400,overflow:"auto",position:"relative"},children:i.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",tableLayout:"auto",fontSize:12,fontFamily:n.fontMono},children:[i.jsx("thead",{children:i.jsx("tr",{children:e.columns.map(C=>i.jsx("th",{onClick:()=>A(C),style:{background:n.tableHeaderBg,color:n.textSecondary,fontWeight:600,fontSize:11,textAlign:"left",padding:"6px 12px",borderBottom:`1px solid ${n.tableBorder}`,borderRight:`1px solid ${n.tableBorder}`,minWidth:80,maxWidth:300,whiteSpace:"nowrap",position:"sticky",top:0,zIndex:1,fontFamily:n.font,letterSpacing:"0.03em",overflow:"hidden",textOverflow:"ellipsis",cursor:"pointer",userSelect:"none",transition:"background 0.1s"},children:i.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6},children:[(()=>{const g=i0(N.get(C)??"string");return i.jsx("span",{title:N.get(C)??"string",style:{fontSize:9,fontFamily:n.fontMono,fontWeight:700,color:g.color,background:`${g.color}15`,border:`1px solid ${g.color}40`,borderRadius:3,padding:"0 4px",minWidth:14,textAlign:"center",lineHeight:"14px",flexShrink:0},children:g.icon})})(),i.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:C}),i.jsx(E0,{dir:s===C?l:null,color:s===C?n.accent:n.textMuted})]})},C))})}),i.jsx("tbody",{children:m.map((C,g)=>i.jsx("tr",{onMouseEnter:()=>o(g),onMouseLeave:()=>o(null),style:{background:r===g?n.tableRowHover:"transparent",transition:"background 0.1s"},children:e.columns.map(y=>{const _=C[y],P=_==null,D=Vl(_);return i.jsx("td",{style:{padding:"5px 12px",borderBottom:`1px solid ${n.tableBorder}`,borderRight:`1px solid ${n.tableBorder}`,color:P?n.textMuted:n.textPrimary,fontStyle:P?"italic":"normal",textAlign:D?"right":"left",whiteSpace:"nowrap",maxWidth:300,overflow:"hidden",textOverflow:"ellipsis"},children:P?"—":YR(_)},y)})},g))})]})}),i.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:[I>1&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[i.jsx(Wn,{disabled:O===0,onClick:()=>h(O-1),t:n,children:"‹"}),d0(I,O).map((C,g)=>C==="…"?i.jsx("span",{style:{color:n.textMuted,fontSize:10,padding:"0 2px"},children:"…"},`gap-${g}`):i.jsx("button",{onClick:()=>h(C-1),style:{background:C-1===O?`${n.accent}20`:"transparent",border:"none",color:C-1===O?n.accent:n.textSecondary,fontSize:10,fontFamily:n.font,fontWeight:C-1===O?700:400,padding:"1px 6px",borderRadius:3,cursor:"pointer",minWidth:20},children:C},C)),i.jsx(Wn,{disabled:O>=I-1,onClick:()=>h(O+1),t:n,children:"›"})]}),i.jsx("div",{style:{flex:1}}),i.jsx(Es,{label:"View",t:n}),i.jsx(Es,{label:"Format",t:n}),i.jsx(Es,{label:"Columns",t:n}),i.jsx(Es,{label:"Totals",t:n}),i.jsxs("span",{style:{fontSize:10,color:n.textSecondary,fontFamily:n.font,marginLeft:6,whiteSpace:"nowrap"},children:[p.length.toLocaleString()," ",p.length===1?"row":"rows",E&&e.rows.length!==p.length&&` of ${e.rows.length.toLocaleString()}`]})]})]})}function d0(e,t){if(e<=7)return Array.from({length:e},(o,s)=>s+1);const n=t+1,r=[1];n>3&&r.push("…");for(let o=Math.max(2,n-1);o<=Math.min(e-1,n+1);o++)r.push(o);return n<e-2&&r.push("…"),r.push(e),r}function Es({label:e,t}){const[n,r]=f.useState(!1);return i.jsx("button",{onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),title:`${e} (coming in v0.11)`,style:{background:n?t.btnHover:"transparent",border:`1px solid ${n?t.btnBorder:"transparent"}`,borderRadius:3,color:n?t.textSecondary:t.textMuted,fontSize:10,fontFamily:t.font,fontWeight:600,padding:"2px 8px",cursor:"pointer",transition:"all 0.15s"},children:e})}function wd({label:e,onClick:t,t:n}){const[r,o]=f.useState(!1);return i.jsxs("button",{onClick:t,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!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:[i.jsxs("svg",{width:"9",height:"9",viewBox:"0 0 16 16",fill:"currentColor",children:[i.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"}),i.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 Wn({disabled:e,onClick:t,children:n,t:r}){return i.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 Gi=[{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"}],u0=/date|time|at|day|month|year/i,VR=/^(label|name|category|status|type|group)$/i,$R=/^(value|count|total|revenue|amount|sum|avg|price|quantity|sales)$/i;function en(e){return typeof e=="number"?!0:typeof e=="string"?e.trim()!==""&&!isNaN(Number(e)):!1}function T0(e){return typeof e=="string"||typeof e=="number"}const S0=new Set(["bar","line","area","pie","donut","scatter","heatmap","funnel","waterfall","histogram","gauge","stacked-bar","grouped-bar","kpi","table"]);function to(e,t){if(t!=null&&t.chart){const n=t.chart.toLowerCase().replace(/_/g,"-");if(S0.has(n))return n}return f0(e)}function f0(e){const{columns:t,rows:n}=e;if(t.length<2||n.length===0)return"table";const r=t[0],o=t[1],s=n.slice(0,5),a=s.every(u=>en(u[o])),l=s.every(u=>T0(u[r]));if(u0.test(r)&&a&&l)return"line";const c=t.find(u=>VR.test(u)),E=t.find(u=>$R.test(u));return c&&E&&s.every(T=>en(T[E]))?"bar":s.every(u=>en(u[r]))&&a&&t.length>=2?"scatter":t.length===2&&l&&a?"bar":"table"}const XR={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"]},Ue=XR.default;function be(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 R0(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 Hi(e,t){const n=(t!=null&&t.x&&e.columns.includes(t.x)?t.x:void 0)??e.columns.find(o=>VR.test(o))??e.columns[0],r=(t!=null&&t.y&&e.columns.includes(t.y)?t.y:void 0)??e.columns.find(o=>$R.test(o))??e.columns[1];return{labelCol:n,valueCol:r}}const Ln=20;function eE({result:e,themeMode:t,chartConfig:n}){const r=oe[t],[o,s]=f.useState(null),{labelCol:a,valueCol:l}=Hi(e,n),c=(n==null?void 0:n.maxItems)??Ln,E=e.rows.slice(0,c).map(p=>({label:String(p[a]??""),value:Number(p[l]??0)})),d=e.rows.length>c,u=Math.max(...E.map(p=>p.value),1),T=28,S=120,h=6,A=12,R=E.length*(T+h)+A*2;return i.jsxs("div",{style:{padding:"8px 0"},children:[i.jsx("svg",{width:"100%",height:R,viewBox:`0 0 600 ${R}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:E.map((p,N)=>{const I=A+N*(T+h),O=600-S-84,m=Math.max(p.value/u*O,2),C=o===N;return i.jsxs("g",{onMouseEnter:()=>s(N),onMouseLeave:()=>s(null),style:{cursor:"default"},children:[i.jsx("text",{x:S-8,y:I+T/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:p.label.length>16?p.label.slice(0,15)+"…":p.label}),i.jsx("rect",{x:S,y:I,width:m,height:T,rx:3,fill:C?r.accentHover:r.accent,style:{transition:"fill 0.15s"}}),i.jsx("text",{x:S+m+6,y:I+T/2+4,textAnchor:"start",fontSize:11,fontFamily:r.fontMono,fill:r.textMuted,children:be(p.value)})]},N)})}),d&&i.jsxs("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,fontStyle:"italic",padding:"4px 12px"},children:["Showing ",Ln," of ",e.rows.length," rows"]})]})}function A0({result:e,themeMode:t,chartConfig:n}){const r=oe[t],[o,s]=f.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(p=>p!==a&&l.some(N=>en(N[p])));if(c.length===0)return i.jsx(eE,{result:e,themeMode:t,chartConfig:n});const E=e.rows.slice(0,Ln).map(p=>String(p[a]??"")),d=Math.max(...e.rows.slice(0,Ln).flatMap(p=>c.map(N=>Math.abs(Number(p[N]??0)))),1),u=24,T=u/c.length,S=120,h=12,A=8,R=E.length*(u+A)+h*2;return i.jsxs("div",{style:{padding:"8px 0"},children:[i.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:c.map((p,N)=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[i.jsx("div",{style:{width:10,height:10,borderRadius:2,background:Ue[N%Ue.length]}}),i.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:p})]},p))}),i.jsx("svg",{width:"100%",height:R,viewBox:`0 0 600 ${R}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:E.map((p,N)=>{const I=h+N*(u+A),O=e.rows[N];return i.jsxs("g",{children:[i.jsx("text",{x:S-8,y:I+u/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:p.length>16?p.slice(0,15)+"…":p}),c.map((m,C)=>{const g=Number(O[m]??0),y=600-S-60,_=Math.max(Math.abs(g)/d*y,1),P=I+C*T,D=`${N}-${C}`;return i.jsxs("g",{onMouseEnter:()=>s(D),onMouseLeave:()=>s(null),children:[i.jsx("rect",{x:S,y:P,width:_,height:T-1,rx:2,fill:Ue[C%Ue.length],opacity:o===D?1:.85,style:{transition:"opacity 0.15s"}}),o===D&&i.jsx("text",{x:S+_+4,y:P+T/2+3,fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:be(g)})]},C)})]},N)})})]})}function p0({result:e,themeMode:t,chartConfig:n}){const r=oe[t],[o,s]=f.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(p=>p!==a&&l.some(N=>en(N[p])));if(c.length===0)return i.jsx(eE,{result:e,themeMode:t,chartConfig:n});const E=e.rows.slice(0,Ln),d=E.map(p=>String(p[a]??"")),u=Math.max(...E.map(p=>c.reduce((N,I)=>N+Math.abs(Number(p[I]??0)),0)),1),T=28,S=120,h=12,A=6,R=d.length*(T+A)+h*2;return i.jsxs("div",{style:{padding:"8px 0"},children:[i.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:c.map((p,N)=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[i.jsx("div",{style:{width:10,height:10,borderRadius:2,background:Ue[N%Ue.length]}}),i.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:p})]},p))}),i.jsx("svg",{width:"100%",height:R,viewBox:`0 0 600 ${R}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:d.map((p,N)=>{const I=h+N*(T+A),O=E[N],m=600-S-60;let C=S;return i.jsxs("g",{children:[i.jsx("text",{x:S-8,y:I+T/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:p.length>16?p.slice(0,15)+"…":p}),c.map((g,y)=>{const _=Math.abs(Number(O[g]??0)),P=Math.max(_/u*m,0),D=C;C+=P;const b=`${N}-${y}`;return i.jsxs("g",{onMouseEnter:()=>s(b),onMouseLeave:()=>s(null),children:[i.jsx("rect",{x:D,y:I,width:P,height:T,rx:y===0?3:0,fill:Ue[y%Ue.length],opacity:o===b?1:.85,style:{transition:"opacity 0.15s"}}),o===b&&P>30&&i.jsx("text",{x:D+P/2,y:I+T/2+4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:"#fff",fontWeight:600,children:be(_)})]},y)})]},N)})})]})}function Bd({result:e,themeMode:t,showArea:n}){const r=oe[t],[o,s]=f.useState(null),a=e.columns[0],l=e.columns[1],c=e.rows.map(x=>({label:String(x[a]??""),value:Number(x[l]??0)}));if(c.length<2)return null;const E=560,d=200,u=52,T=16,S=16,h=36,A=E-u-T,R=d-S-h,p=Math.min(...c.map(x=>x.value)),I=Math.max(...c.map(x=>x.value))-p||1,O=A/(c.length-1),m=x=>u+x*O,C=x=>S+R-(x-p)/I*R,g=c.map((x,w)=>({x:m(w),y:C(x.value)})),y=g.reduce((x,w,M)=>{if(M===0)return`M ${w.x},${w.y}`;const B=g[M-1],v=B.x+(w.x-B.x)/2;return`${x} C ${v},${B.y} ${v},${w.y} ${w.x},${w.y}`},""),_=`${y} L ${g[g.length-1].x},${S+R} L ${u},${S+R} Z`,P=5,D=Array.from({length:P+1},(x,w)=>{const M=p+I*w/P;return{val:M,y:C(M)}}),b=Math.ceil(c.length/8),F=c.filter((x,w)=>w%b===0||w===c.length-1);return i.jsx("div",{style:{position:"relative",padding:"8px 0"},children:i.jsxs("svg",{width:"100%",height:d,viewBox:`0 0 ${E} ${d}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},onMouseLeave:()=>s(null),children:[D.map((x,w)=>i.jsxs("g",{children:[i.jsx("line",{x1:u,y1:x.y,x2:u+A,y2:x.y,stroke:r.tableBorder,strokeWidth:.5}),i.jsx("text",{x:u-6,y:x.y+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:be(x.val)})]},w)),i.jsx("path",{d:_,fill:r.accent,opacity:n?.3:.15}),i.jsx("path",{d:y,fill:"none",stroke:r.accent,strokeWidth:2,strokeLinejoin:"round"}),g.map((x,w)=>i.jsx("circle",{cx:x.x,cy:x.y,r:3,fill:r.accent,style:{cursor:"crosshair"},onMouseEnter:()=>s({x:x.x,y:x.y,label:c[w].label,value:c[w].value})},w)),F.map((x,w)=>{const M=c.indexOf(x);return i.jsx("text",{x:m(M),y:S+R+16,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:R0(x.label)},w)}),i.jsx("line",{x1:u,y1:S,x2:u,y2:S+R,stroke:r.tableBorder,strokeWidth:1}),i.jsx("line",{x1:u,y1:S+R,x2:u+A,y2:S+R,stroke:r.tableBorder,strokeWidth:1}),o&&i.jsxs("g",{children:[i.jsx("rect",{x:o.x+8,y:o.y-20,width:90,height:32,rx:4,fill:r.cellBg,stroke:r.cellBorder,strokeWidth:1}),i.jsx("text",{x:o.x+13,y:o.y-8,fontSize:10,fontFamily:r.font,fill:r.textSecondary,children:o.label.length>10?o.label.slice(0,10)+"…":o.label}),i.jsx("text",{x:o.x+13,y:o.y+6,fontSize:11,fontFamily:r.fontMono,fill:r.textPrimary,fontWeight:600,children:be(o.value)})]})]})})}function h0({result:e,themeMode:t,chartConfig:n}){const r=oe[t],[o,s]=f.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,E=e.rows.slice(0,200).map(D=>({x:Number(D[a]??0),y:Number(D[l]??0),color:c?String(D[c]??""):void 0})),d=560,u=300,T=52,S=16,h=16,A=36,R=d-T-S,p=u-h-A,N=Math.min(...E.map(D=>D.x)),I=Math.max(...E.map(D=>D.x)),O=Math.min(...E.map(D=>D.y)),m=Math.max(...E.map(D=>D.y)),C=I-N||1,g=m-O||1,y=D=>T+(D-N)/C*R,_=D=>h+p-(D-O)/g*p,P=c?[...new Set(E.map(D=>D.color))]:[];return i.jsxs("div",{style:{padding:"8px 0"},children:[c&&P.length>0&&i.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:P.slice(0,12).map((D,b)=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[i.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:Ue[b%Ue.length]}}),i.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:D})]},D))}),i.jsxs("svg",{width:"100%",height:u,viewBox:`0 0 ${d} ${u}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:6},(D,b)=>{const F=O+g*b/5,x=_(F);return i.jsxs("g",{children:[i.jsx("line",{x1:T,y1:x,x2:T+R,y2:x,stroke:r.tableBorder,strokeWidth:.5}),i.jsx("text",{x:T-6,y:x+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:be(F)})]},b)}),Array.from({length:6},(D,b)=>{const F=N+C*b/5,x=y(F);return i.jsx("text",{x,y:h+p+16,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:be(F)},b)}),i.jsx("line",{x1:T,y1:h,x2:T,y2:h+p,stroke:r.tableBorder,strokeWidth:1}),i.jsx("line",{x1:T,y1:h+p,x2:T+R,y2:h+p,stroke:r.tableBorder,strokeWidth:1}),i.jsx("text",{x:T+R/2,y:u-2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:a}),i.jsx("text",{x:10,y:h+p/2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,transform:`rotate(-90, 10, ${h+p/2})`,children:l}),E.map((D,b)=>{const F=c?P.indexOf(D.color):0;return i.jsx("circle",{cx:y(D.x),cy:_(D.y),r:o===b?5:3.5,fill:Ue[F%Ue.length],opacity:o===b?1:.7,style:{cursor:"crosshair",transition:"r 0.1s, opacity 0.1s"},onMouseEnter:()=>s(b),onMouseLeave:()=>s(null)},b)}),o!==null&&i.jsxs("g",{children:[i.jsx("rect",{x:y(E[o].x)+8,y:_(E[o].y)-24,width:100,height:28,rx:4,fill:r.cellBg,stroke:r.cellBorder,strokeWidth:1}),i.jsxs("text",{x:y(E[o].x)+13,y:_(E[o].y)-8,fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:["(",be(E[o].x),", ",be(E[o].y),")"]})]})]})]})}const I0=12;function Fd({result:e,themeMode:t,chartConfig:n,isDonut:r}){const o=oe[t],[s,a]=f.useState(null),{labelCol:l,valueCol:c}=Hi(e,n),E=e.rows.slice(0,I0).map(N=>({label:String(N[l]??""),value:Math.abs(Number(N[c]??0))})),d=E.reduce((N,I)=>N+I.value,0)||1,u=90,T=90,S=70,h=r?40:0,A=[];let R=-Math.PI/2;E.forEach((N,I)=>{const O=N.value/d*2*Math.PI,m=R,C=R+O,g=u+S*Math.cos(m),y=T+S*Math.sin(m),_=u+S*Math.cos(C),P=T+S*Math.sin(C),D=O>Math.PI?1:0;let b;if(h>0){const F=u+h*Math.cos(m),x=T+h*Math.sin(m),w=u+h*Math.cos(C),M=T+h*Math.sin(C);b=`M ${g} ${y} A ${S} ${S} 0 ${D} 1 ${_} ${P} L ${w} ${M} A ${h} ${h} 0 ${D} 0 ${F} ${x} Z`}else b=`M ${u} ${T} L ${g} ${y} A ${S} ${S} 0 ${D} 1 ${_} ${P} Z`;A.push({path:b,color:Ue[I%Ue.length],label:N.label,value:N.value,pct:N.value/d*100}),R=C});const p=s!==null?A[s]:null;return i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:16,padding:"8px 12px",flexWrap:"wrap"},children:[i.jsxs("svg",{width:180,height:180,style:{flexShrink:0},onMouseLeave:()=>a(null),children:[A.map((N,I)=>i.jsx("path",{d:N.path,fill:N.color,opacity:s===null||s===I?1:.55,style:{cursor:"pointer",transition:"opacity 0.15s"},onMouseEnter:()=>a(I)},I)),r&&i.jsxs(i.Fragment,{children:[i.jsx("text",{x:u,y:T-5,textAnchor:"middle",fontSize:11,fontFamily:o.fontMono,fill:o.textSecondary,children:be(p?p.value:d)}),i.jsx("text",{x:u,y:T+9,textAnchor:"middle",fontSize:9,fontFamily:o.font,fill:o.textMuted,children:p?`${p.pct.toFixed(1)}%`:"total"})]})]}),i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4,maxHeight:180,overflowY:"auto",flex:1},children:A.map((N,I)=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,cursor:"default",opacity:s===null||s===I?1:.5},onMouseEnter:()=>a(I),onMouseLeave:()=>a(null),children:[i.jsx("div",{style:{width:10,height:10,borderRadius:2,background:N.color,flexShrink:0}}),i.jsx("span",{style:{fontSize:11,fontFamily:o.font,color:o.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:N.label}),i.jsxs("span",{style:{fontSize:11,fontFamily:o.fontMono,color:o.textMuted,marginLeft:"auto",flexShrink:0},children:[N.pct.toFixed(1),"%"]})]},I))})]})}function N0({result:e,themeMode:t}){const n=oe[t],[r,o]=f.useState(null),s=e.columns[0],a=e.columns.slice(1),l=e.rows.slice(0,30),c=l.flatMap(R=>a.map(p=>Number(R[p]??0))),E=Math.min(...c),u=Math.max(...c)-E||1,T=Math.min(50,480/a.length),S=24,h=100;function A(R){const p=(R-E)/u,N=Math.round(56+p*192),I=Math.round(139+p*-58),O=Math.round(253+p*-180);return`rgb(${N},${I},${O})`}return i.jsx("div",{style:{padding:"8px 0",overflowX:"auto"},children:i.jsxs("svg",{width:h+a.length*T+20,height:l.length*S+S+16,style:{display:"block",overflow:"visible"},children:[a.map((R,p)=>i.jsx("text",{x:h+p*T+T/2,y:14,textAnchor:"middle",fontSize:9,fontFamily:n.font,fill:n.textMuted,transform:`rotate(-30, ${h+p*T+T/2}, 14)`,children:R.length>8?R.slice(0,7)+"…":R},p)),l.map((R,p)=>{const N=String(R[s]??""),I=S+p*S;return i.jsxs("g",{children:[i.jsx("text",{x:h-6,y:I+S/2+4,textAnchor:"end",fontSize:10,fontFamily:n.font,fill:n.textSecondary,children:N.length>14?N.slice(0,13)+"…":N}),a.map((O,m)=>{const C=Number(R[O]??0),g=(r==null?void 0:r.r)===p&&(r==null?void 0:r.c)===m;return i.jsxs("g",{onMouseEnter:()=>o({r:p,c:m}),onMouseLeave:()=>o(null),children:[i.jsx("rect",{x:h+m*T,y:I,width:T-1,height:S-1,rx:2,fill:A(C),opacity:g?1:.85,stroke:g?n.accent:"none",strokeWidth:g?1.5:0}),g&&i.jsx("text",{x:h+m*T+T/2,y:I+S/2+4,textAnchor:"middle",fontSize:10,fontFamily:n.fontMono,fill:"#fff",fontWeight:600,children:be(C)})]},m)})]},p)})]})})}function O0({result:e,themeMode:t,chartConfig:n}){const r=oe[t],[o,s]=f.useState(null),a=(n!=null&&n.x&&e.columns.includes(n.x)?n.x:void 0)??e.columns.find(y=>e.rows.slice(0,5).some(_=>en(_[y])))??e.columns[0],l=e.rows.map(y=>Number(y[a]??0)).filter(y=>!isNaN(y));if(l.length===0)return null;const c=Math.min(20,Math.max(5,Math.ceil(Math.sqrt(l.length)))),E=Math.min(...l),T=(Math.max(...l)-E||1)/c,S=Array.from({length:c},(y,_)=>({low:E+_*T,high:E+(_+1)*T,count:0}));l.forEach(y=>{const _=Math.min(Math.floor((y-E)/T),c-1);S[_].count++});const h=Math.max(...S.map(y=>y.count),1),A=560,R=200,p=52,N=16,I=16,O=36,m=A-p-N,C=R-I-O,g=m/c;return i.jsx("div",{style:{padding:"8px 0"},children:i.jsxs("svg",{width:"100%",height:R,viewBox:`0 0 ${A} ${R}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:5},(y,_)=>{const P=h*(_+1)/5,D=I+C-P/h*C;return i.jsxs("g",{children:[i.jsx("line",{x1:p,y1:D,x2:p+m,y2:D,stroke:r.tableBorder,strokeWidth:.5}),i.jsx("text",{x:p-6,y:D+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Math.round(P)})]},_)}),S.map((y,_)=>{const P=y.count/h*C,D=p+_*g,b=I+C-P,F=o===_;return i.jsxs("g",{onMouseEnter:()=>s(_),onMouseLeave:()=>s(null),children:[i.jsx("rect",{x:D+1,y:b,width:g-2,height:P,rx:1,fill:F?r.accentHover:r.accent,opacity:F?1:.85,style:{transition:"fill 0.1s"}}),F&&i.jsx("text",{x:D+g/2,y:b-4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:y.count})]},_)}),S.filter((y,_)=>_%Math.ceil(c/6)===0).map((y,_)=>{const P=S.indexOf(y);return i.jsx("text",{x:p+P*g+g/2,y:I+C+16,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:be(y.low)},_)}),i.jsx("line",{x1:p,y1:I,x2:p,y2:I+C,stroke:r.tableBorder,strokeWidth:1}),i.jsx("line",{x1:p,y1:I+C,x2:p+m,y2:I+C,stroke:r.tableBorder,strokeWidth:1}),i.jsx("text",{x:p+m/2,y:R-2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:a})]})})}function m0({result:e,themeMode:t,chartConfig:n}){const r=oe[t],[o,s]=f.useState(null),{labelCol:a,valueCol:l}=Hi(e,n),c=e.rows.slice(0,10).map(R=>({label:String(R[a]??""),value:Math.abs(Number(R[l]??0))}));if(c.length===0)return null;const E=c[0].value||1,d=400,u=36,T=4,S=16,h=c.length*(u+T)+S*2,A=d/2;return i.jsx("div",{style:{padding:"8px 0",display:"flex",justifyContent:"center"},children:i.jsx("svg",{width:d,height:h,style:{display:"block"},children:c.map((R,p)=>{const N=S+p*(u+T),I=R.value/E,O=Math.max(I*(d-80),40),m=o===p,C=p<c.length-1?c[p+1].value/E:I*.8,g=Math.max(C*(d-80),40),y=A-O/2,_=A+O/2,P=A+g/2,D=A-g/2,b=`M ${y} ${N} L ${_} ${N} L ${P} ${N+u} L ${D} ${N+u} Z`;return i.jsxs("g",{onMouseEnter:()=>s(p),onMouseLeave:()=>s(null),style:{cursor:"default"},children:[i.jsx("path",{d:b,fill:Ue[p%Ue.length],opacity:m?1:.85,style:{transition:"opacity 0.15s"}}),i.jsx("text",{x:A,y:N+u/2+1,textAnchor:"middle",fontSize:11,fontFamily:r.font,fill:"#fff",fontWeight:500,children:R.label}),i.jsxs("text",{x:A,y:N+u/2+13,textAnchor:"middle",fontSize:9,fontFamily:r.fontMono,fill:"rgba(255,255,255,0.7)",children:[be(R.value)," (",(I*100).toFixed(0),"%)"]})]},p)})})})}function C0({result:e,themeMode:t,chartConfig:n}){const r=oe[t],[o,s]=f.useState(null),{labelCol:a,valueCol:l}=Hi(e,n),c=e.rows.slice(0,15).map(_=>({label:String(_[a]??""),value:Number(_[l]??0)}));if(c.length===0)return null;let E=0;const d=c.map(_=>{const P=E;return E+=_.value,{..._,start:P,end:E}}),u=d.flatMap(_=>[_.start,_.end]),T=Math.min(0,...u),h=Math.max(0,...u)-T||1,A=560,R=240,p=52,N=16,I=16,O=44,m=A-p-N,C=R-I-O,g=m/d.length,y=_=>I+C-(_-T)/h*C;return i.jsx("div",{style:{padding:"8px 0"},children:i.jsxs("svg",{width:"100%",height:R,viewBox:`0 0 ${A} ${R}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:6},(_,P)=>{const D=T+h*P/5,b=y(D);return i.jsxs("g",{children:[i.jsx("line",{x1:p,y1:b,x2:p+m,y2:b,stroke:r.tableBorder,strokeWidth:.5}),i.jsx("text",{x:p-6,y:b+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:be(D)})]},P)}),i.jsx("line",{x1:p,y1:y(0),x2:p+m,y2:y(0),stroke:r.textMuted,strokeWidth:1,strokeDasharray:"3,3"}),d.map((_,P)=>{const D=p+P*g,b=y(Math.max(_.start,_.end)),x=y(Math.min(_.start,_.end))-b,w=_.value>=0,M=o===P;return i.jsxs("g",{onMouseEnter:()=>s(P),onMouseLeave:()=>s(null),children:[P<d.length-1&&i.jsx("line",{x1:D+g-2,y1:y(_.end),x2:D+g+2,y2:y(_.end),stroke:r.textMuted,strokeWidth:1,strokeDasharray:"2,2"}),i.jsx("rect",{x:D+4,y:b,width:g-8,height:Math.max(x,1),rx:2,fill:w?r.success:r.error,opacity:M?1:.8,style:{transition:"opacity 0.1s"}}),M&&i.jsxs("text",{x:D+g/2,y:b-4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:[_.value>=0?"+":"",be(_.value)]})]},P)}),d.map((_,P)=>i.jsx("text",{x:p+P*g+g/2,y:R-6,textAnchor:"middle",fontSize:9,fontFamily:r.font,fill:r.textMuted,transform:`rotate(-20, ${p+P*g+g/2}, ${R-6})`,children:_.label.length>8?_.label.slice(0,7)+"…":_.label},P)),i.jsx("line",{x1:p,y1:I,x2:p,y2:I+C,stroke:r.tableBorder,strokeWidth:1}),i.jsx("line",{x1:p,y1:I+C,x2:p+m,y2:I+C,stroke:r.tableBorder,strokeWidth:1})]})})}function g0({result:e,themeMode:t,chartConfig:n}){const r=oe[t],o=e.rows[0];if(!o)return null;const s=(n!=null&&n.y&&e.columns.includes(n.y)?n.y:void 0)??e.columns.find(y=>en(o[y]))??e.columns[0],a=Number(o[s]??0),l=(n==null?void 0:n.title)??s,c=a>100?a*1.2:100,E=Math.min(Math.max(a/c,0),1),d=120,u=110,T=80,S=Math.PI,h=0,A=S-(S-h)*E,R=d+T*Math.cos(S),p=u+T*Math.sin(S),N=d+T*Math.cos(A),I=u+T*Math.sin(A),O=E>.5?1:0,m=d+T*Math.cos(h),C=u+T*Math.sin(h),g=E<.33?r.error:E<.66?r.warning:r.success;return i.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",padding:"16px 24px"},children:i.jsxs("svg",{width:240,height:140,style:{display:"block",overflow:"visible"},children:[i.jsx("path",{d:`M ${R} ${p} A ${T} ${T} 0 1 1 ${m} ${C}`,fill:"none",stroke:r.tableBorder,strokeWidth:12,strokeLinecap:"round"}),E>0&&i.jsx("path",{d:`M ${R} ${p} A ${T} ${T} 0 ${O} 1 ${N} ${I}`,fill:"none",stroke:g,strokeWidth:12,strokeLinecap:"round"}),i.jsx("text",{x:d,y:u-4,textAnchor:"middle",fontSize:28,fontFamily:r.fontMono,fill:g,fontWeight:700,children:be(a)}),i.jsx("text",{x:d,y:u+16,textAnchor:"middle",fontSize:11,fontFamily:r.font,fill:r.textMuted,children:l})]})})}function KR({result:e,themeMode:t,chartConfig:n}){const r=oe[t],o=e.rows[0];if(!o)return null;const s=n!=null&&n.y&&e.columns.includes(n.y)?n.y:e.columns.find(d=>en(o[d]))??e.columns[0],a=o[s],l=Number(a),c=isNaN(l)?String(a):l.toLocaleString(void 0,{maximumFractionDigits:2}),E=(n==null?void 0:n.title)??(n!=null&&n.x&&o[n.x]?String(o[n.x]):s);return i.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"32px 24px",gap:8},children:[i.jsx("span",{style:{fontSize:40,fontWeight:700,fontFamily:r.fontMono,color:r.accent,lineHeight:1.1},children:c}),i.jsx("span",{style:{fontSize:13,fontFamily:r.font,color:r.textMuted,textTransform:"uppercase",letterSpacing:"0.08em",fontWeight:500},children:E})]})}function L0({config:e,columns:t,onChange:n,onClose:r,t:o}){const s={background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:4,color:o.textPrimary,fontSize:11,fontFamily:o.font,padding:"4px 8px",outline:"none",width:"100%",boxSizing:"border-box"};return i.jsxs("div",{style:{position:"absolute",top:4,right:4,zIndex:100,background:o.cellBg,border:`1px solid ${o.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:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[i.jsx("span",{style:{fontSize:11,fontWeight:600,color:o.textPrimary,fontFamily:o.font},children:"Chart Settings"}),i.jsx("button",{onClick:r,style:{background:"none",border:"none",color:o.textMuted,cursor:"pointer",fontSize:14},children:"×"})]}),i.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Title",i.jsx("input",{value:e.title??"",onChange:a=>n({title:a.target.value||void 0}),placeholder:"Chart title",style:{...s,marginTop:2}})]}),i.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["X-axis label",i.jsx("input",{value:e.xLabel??"",onChange:a=>n({xLabel:a.target.value||void 0}),placeholder:"Auto",style:{...s,marginTop:2}})]}),i.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Y-axis label",i.jsx("input",{value:e.yLabel??"",onChange:a=>n({yLabel:a.target.value||void 0}),placeholder:"Auto",style:{...s,marginTop:2}})]}),i.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Legend",i.jsxs("select",{value:e.legendPosition??"top",onChange:a=>n({legendPosition:a.target.value}),style:{...s,marginTop:2},children:[i.jsx("option",{value:"top",children:"Top"}),i.jsx("option",{value:"bottom",children:"Bottom"}),i.jsx("option",{value:"left",children:"Left"}),i.jsx("option",{value:"right",children:"Right"}),i.jsx("option",{value:"none",children:"Hidden"})]})]}),i.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Color palette",i.jsx("select",{value:e.colorPalette??"default",onChange:a=>n({colorPalette:a.target.value}),style:{...s,marginTop:2},children:Object.keys(XR).map(a=>i.jsx("option",{value:a,children:a.charAt(0).toUpperCase()+a.slice(1)},a))})]}),i.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Max items",i.jsx("input",{type:"number",value:e.maxItems??Ln,min:5,max:200,onChange:a=>n({maxItems:parseInt(a.target.value)||Ln}),style:{...s,marginTop:2}})]})]})}function _0({result:e,themeMode:t,chartConfig:n,onConfigChange:r}){const o=oe[t],s=to(e,n),[a,l]=f.useState(!1);return s==="kpi"?i.jsx(KR,{result:e,themeMode:t,chartConfig:n}):i.jsxs("div",{style:{position:"relative"},children:[(n==null?void 0:n.title)&&i.jsx("div",{style:{padding:"8px 12px 0",fontSize:13,fontWeight:600,color:o.textPrimary,fontFamily:o.font,textAlign:"center"},children:n.title}),r&&i.jsx("button",{onClick:()=>l(!a),title:"Chart settings",style:{position:"absolute",top:4,right:4,zIndex:50,background:a?`${o.accent}18`:"transparent",border:`1px solid ${a?o.accent:"transparent"}`,borderRadius:4,color:a?o.accent:o.textMuted,cursor:"pointer",fontSize:14,padding:"2px 6px",lineHeight:1},children:"⚙"}),a&&r&&i.jsx(L0,{config:n??{},columns:e.columns,onChange:c=>r(c),onClose:()=>l(!1),t:o}),ki(s,e,t,n)]})}function ki(e,t,n,r){const o=r!=null&&r.x&&t.columns.includes(r.x)?r.x:void 0,s=r!=null&&r.y&&t.columns.includes(r.y)?r.y:void 0,a=o||s?x0(t,o,s):t;switch(e){case"line":return i.jsx(Bd,{result:a,themeMode:n});case"area":return i.jsx(Bd,{result:a,themeMode:n,showArea:!0});case"bar":return i.jsx(eE,{result:a,themeMode:n,chartConfig:r});case"grouped-bar":return i.jsx(A0,{result:a,themeMode:n,chartConfig:r});case"stacked-bar":return i.jsx(p0,{result:a,themeMode:n,chartConfig:r});case"scatter":return i.jsx(h0,{result:t,themeMode:n,chartConfig:r});case"pie":return i.jsx(Fd,{result:t,themeMode:n,chartConfig:r,isDonut:!1});case"donut":return i.jsx(Fd,{result:t,themeMode:n,chartConfig:r,isDonut:!0});case"heatmap":return i.jsx(N0,{result:t,themeMode:n});case"histogram":return i.jsx(O0,{result:t,themeMode:n,chartConfig:r});case"funnel":return i.jsx(m0,{result:t,themeMode:n,chartConfig:r});case"waterfall":return i.jsx(C0,{result:t,themeMode:n,chartConfig:r});case"gauge":return i.jsx(g0,{result:t,themeMode:n,chartConfig:r});case"kpi":return i.jsx(KR,{result:t,themeMode:n,chartConfig:r});default:return i.jsx(mo,{result:t,themeMode:n})}}function x0(e,t,n){const r=e.columns,o=[];t&&r.includes(t)&&o.push(t),n&&r.includes(n)&&o.push(n);for(const s of r)o.includes(s)||o.push(s);return o.join(",")===r.join(",")?e:{...e,columns:o,rows:e.rows.map(s=>{const a={};for(const l of o)a[l]=s[l];return a})}}function ji(e){var c,E;if(!e)return{metrics:[],dimensions:[],columns:[],fields:[],hasSemanticBinding:!1};const t=new Set(((c=e.semanticRefs)==null?void 0:c.metrics)??[]),n=new Set(((E=e.semanticRefs)==null?void 0:E.dimensions)??[]),r=t.size>0||n.size>0,o=[],s=[],a=[],l=[];for(const d of e.columns)t.has(d)?(o.push(d),l.push({name:d,kind:"metric"})):n.has(d)&&(s.push(d),l.push({name:d,kind:"dimension"}));for(const d of e.columns)t.has(d)||n.has(d)||(a.push(d),l.push({name:d,kind:"column",chartRole:jR(Zc(d,e.rows))}));return{metrics:o,dimensions:s,columns:a,fields:l,hasSemanticBinding:r}}function no(e){return e==="metric"?"#":e==="dimension"?"∴":"A"}function ro(e,t){return e==="metric"?t:e==="dimension"?"#e3b341":"#56d364"}function Gd(e){return e==="metric"?"metric":e==="dimension"?"dimension":"column"}function zR({theme:e,value:t,fields:n,allowKinds:r,placeholder:o="Select field",minWidth:s=180,onChange:a}){const[l,c]=f.useState(!1),[E,d]=f.useState(""),u=f.useRef(null),T=f.useRef(null);f.useEffect(()=>{if(!l)return;const R=p=>{var N;(N=u.current)!=null&&N.contains(p.target)||c(!1)};return document.addEventListener("mousedown",R),()=>document.removeEventListener("mousedown",R)},[l]),f.useEffect(()=>{if(l){const R=setTimeout(()=>{var p;return(p=T.current)==null?void 0:p.focus()},20);return()=>clearTimeout(R)}d("")},[l]);const S=f.useMemo(()=>n.find(R=>R.name===t),[n,t]),h=f.useMemo(()=>{if(!E)return n;const R=E.toLowerCase();return n.filter(p=>p.name.toLowerCase().includes(R))},[n,E]),A=R=>r?r.includes(R):!0;return i.jsxs("div",{ref:u,style:{position:"relative",minWidth:s},children:[i.jsxs("button",{onClick:()=>c(R=>!R),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:S?e.textPrimary:e.textMuted,fontFamily:e.fontMono,fontSize:11,textAlign:"left"},children:[S?i.jsxs(i.Fragment,{children:[i.jsx("span",{style:{color:ro(S.kind,e.accent),fontWeight:700,width:12},children:no(S.kind)}),i.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.name})]}):i.jsx("span",{style:{flex:1},children:o}),i.jsx("span",{style:{color:e.textMuted,fontSize:9},children:"▾"})]}),l&&i.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(s,200)},children:[i.jsx("input",{ref:T,value:E,onChange:R=>d(R.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&&i.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"}),h.length===0&&i.jsx("div",{style:{padding:"6px 8px",fontSize:11,color:e.textMuted,fontFamily:e.font},children:"No matches"}),h.map(R=>{const p=A(R.kind);return i.jsxs("button",{onClick:()=>{p&&(a(R.name),c(!1))},disabled:!p,title:p?R.name:`${Gd(R.kind)} — not selectable here`,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 6px",background:"transparent",border:"none",borderRadius:3,cursor:p?"pointer":"not-allowed",textAlign:"left",color:p?e.textPrimary:e.textMuted,fontFamily:e.fontMono,fontSize:11,opacity:p?1:.55},onMouseEnter:N=>{p&&(N.currentTarget.style.background=e.tableRowHover)},onMouseLeave:N=>{N.currentTarget.style.background="transparent"},children:[i.jsx("span",{style:{color:ro(R.kind,e.accent),fontWeight:700,width:12,textAlign:"center"},children:no(R.kind)}),i.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:R.name}),i.jsx("span",{style:{fontSize:9,color:e.textMuted,fontFamily:e.font,textTransform:"uppercase",letterSpacing:"0.06em"},children:Gd(R.kind)})]},R.name)})]})]})}function Yi({theme:e}){return i.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 ",i.jsx("code",{children:"@metric(...)"})," or ",i.jsx("code",{children:"@dim(...)"})," upstream to populate typed pickers."]})}function Co({theme:e,accentColor:t,cellLabel:n,cellName:r,description:o,upstreamOptions:s,onPick:a}){return i.jsxs("div",{style:{background:e.cellBg,border:`1px solid ${e.cellBorder}`,borderLeft:`3px solid ${t}`,borderRadius:6,padding:"18px 20px",fontFamily:e.font},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[i.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&&i.jsx("span",{style:{fontSize:12,fontFamily:e.fontMono,color:e.textSecondary},children:r})]}),i.jsx("div",{style:{fontSize:12,color:e.textSecondary,marginBottom:8,lineHeight:1.5},children:o}),s.length===0?i.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:[i.jsx("div",{style:{fontWeight:600,color:e.textSecondary,marginBottom:4},children:"No dataframe available yet"}),i.jsxs("div",{children:["1. Add a ",i.jsx("span",{style:{fontFamily:e.fontMono,color:e.textSecondary},children:"SQL"})," or"," ",i.jsx("span",{style:{fontFamily:e.fontMono,color:e.textSecondary},children:"Block"})," cell above this one.",i.jsx("br",{}),"2. Run it ",i.jsx("span",{style:{fontFamily:e.fontMono},children:"(⌘↵)"})," and give the cell a name.",i.jsx("br",{}),"3. Come back here — named upstream cells show up as chips you can pick."]}),i.jsxs("div",{style:{marginTop:8,fontSize:10,color:e.textMuted,fontStyle:"italic"},children:["Tip: use ",i.jsx("span",{style:{fontFamily:e.fontMono},children:"@metric(...)"})," and"," ",i.jsx("span",{style:{fontFamily:e.fontMono},children:"@dim(...)"})," in the upstream SQL and metrics / dimensions appear with typed icons in the pickers here."]})]}):i.jsxs(i.Fragment,{children:[i.jsx("div",{style:{fontSize:10,color:e.textMuted,marginBottom:6,letterSpacing:"0.06em",textTransform:"uppercase",fontWeight:700},children:"Pick an upstream dataframe"}),i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:s.map(l=>i.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 $l(e){return e==="measure"?"#":e==="temporal"?"📅":"A"}function Xl(e,t){return e==="measure"?t.accent:e==="temporal"?t.warning:t.success}const y0=[{key:"x",label:"X-axis"},{key:"y",label:"Y-axis"},{key:"color",label:"Color"},{key:"facet",label:"Faceting"}],D0={chart:"bar"},tE="application/x-dql-chart-column";function JR(e,t){e.effectAllowed="move",e.setData(tE,JSON.stringify(t)),e.setData("text/plain",t.column)}function M0(e){const t=e.getData(tE);if(!t)return null;try{return JSON.parse(t)}catch{return null}}function P0({cell:e,cells:t,index:n,themeMode:r,onUpdate:o}){const s=oe[r],a=e.chartConfig??D0,l=a.chart??"bar",c=f.useMemo(()=>{const R=e.upstream;if(R)return t.find(p=>p.name===R)},[e.upstream,t]),E=f.useMemo(()=>t.slice(0,n).filter(R=>R.name&&R.result),[t,n]),d=c==null?void 0:c.result,u=f.useMemo(()=>ji(d),[d]),T=f.useMemo(()=>{if(!d)return new Map;const R=new Map,p=new Set(u.metrics),N=new Set(u.dimensions);for(const I of d.columns)p.has(I)?R.set(I,"measure"):N.has(I)?R.set(I,"dimension"):R.set(I,jR(Zc(I,d.rows)));return R},[d,u]),S=f.useMemo(()=>d?d.columns.filter(R=>T.get(R)==="measure"):[],[d,T]),h=f.useMemo(()=>d?d.columns.filter(R=>T.get(R)!=="measure"):[],[d,T]),A=R=>{o({chartConfig:{...a,...R}})};return!e.upstream||!d?i.jsx(Co,{theme:s,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:E,onPick:R=>o({upstream:R})}):i.jsxs("div",{style:{display:"flex",flexDirection:"column",background:s.cellBg,borderTop:`1px solid ${s.cellBorder}`,borderRight:`1px solid ${s.cellBorder}`,borderBottom:`1px solid ${s.cellBorder}`,borderLeft:"3px solid #a371f7",borderRadius:6,overflow:"hidden",fontFamily:s.font},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${s.cellBorder}`,background:`${s.tableHeaderBg}60`},children:[i.jsx("span",{style:{fontSize:10,fontFamily:s.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#a371f7",background:"#a371f718",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Chart"}),e.name&&i.jsx("span",{style:{fontSize:12,fontFamily:s.fontMono,color:s.textSecondary},children:e.name}),i.jsxs("span",{style:{fontSize:11,color:s.textMuted,fontFamily:s.fontMono},children:["· df: ",e.upstream]}),i.jsx("button",{onClick:()=>o({upstream:void 0}),title:"Change upstream dataframe",style:{fontSize:10,background:"transparent",border:`1px solid ${s.btnBorder}`,borderRadius:3,color:s.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:s.fontMono},children:"change"}),i.jsx("div",{style:{flex:1}}),i.jsx("select",{value:l,onChange:R=>A({chart:R.target.value}),style:{fontSize:11,fontFamily:s.font,background:s.editorBg,color:s.textSecondary,border:`1px solid ${s.cellBorder}`,borderRadius:3,padding:"2px 6px",outline:"none"},children:Gi.map(R=>i.jsx("option",{value:R.value,children:R.label},R.value))})]}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"200px 240px 1fr",minHeight:320},children:[i.jsxs("div",{style:{borderRight:`1px solid ${s.cellBorder}`,padding:10,display:"flex",flexDirection:"column",gap:12,overflow:"auto"},children:[!u.hasSemanticBinding&&i.jsx(Yi,{theme:s}),i.jsx(Hd,{label:"Measures",columns:S,kinds:T,theme:s,onPick:R=>A({y:R}),pickHint:"Y-axis"}),i.jsx(Hd,{label:"Dimensions",columns:h,kinds:T,theme:s,onPick:R=>A({x:R}),pickHint:"X-axis"})]}),i.jsxs("div",{style:{borderRight:`1px solid ${s.cellBorder}`,padding:10,display:"flex",flexDirection:"column",gap:8},children:[i.jsxs("div",{style:{display:"flex",gap:4,borderBottom:`1px solid ${s.cellBorder}`,paddingBottom:4},children:[i.jsx(kd,{label:"Data",active:!0,theme:s}),i.jsx(kd,{label:"Style",theme:s})]}),y0.map(R=>i.jsx(b0,{slotKey:R.key,label:R.label,value:a[R.key],columns:d.columns,kinds:T,theme:s,onAssign:(p,N)=>{const I={[R.key]:p};N&&N!==R.key&&(I[N]=void 0),A(I)},onClear:()=>A({[R.key]:void 0})},R.key))]}),i.jsx("div",{style:{padding:10,minWidth:0,overflow:"hidden"},children:ki(l,d,r,a)})]})]})}function Hd({label:e,columns:t,kinds:n,theme:r,onPick:o,pickHint:s}){return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[i.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&&i.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 i.jsxs("button",{onClick:()=>o(a),draggable:!0,onDragStart:c=>JR(c.dataTransfer,{column:a}),title:`Drag to an axis slot, or click to set as ${s}`,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:[i.jsx("span",{style:{fontSize:9,fontFamily:r.fontMono,fontWeight:700,color:Xl(l,r),width:14,textAlign:"center"},children:$l(l)}),i.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a})]},a)})]})}function kd({label:e,active:t,theme:n}){return i.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 b0({slotKey:e,label:t,value:n,columns:r,kinds:o,theme:s,onAssign:a,onClear:l}){const[c,E]=f.useState(!1),[d,u]=f.useState(!1),T=f.useRef(null);f.useEffect(()=>{if(!c)return;const N=I=>{var O;(O=T.current)!=null&&O.contains(I.target)||E(!1)};return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[c]);const S=N=>{N.dataTransfer.types.includes(tE)&&(N.preventDefault(),N.dataTransfer.dropEffect="move",d||u(!0))},h=()=>u(!1),A=N=>{u(!1);const I=M0(N.dataTransfer);I&&(N.preventDefault(),a(I.column,I.fromSlot),E(!1))},R=d?s.accent:n?`${s.accent}77`:s.cellBorder,p=d?`${s.accent}22`:n?`${s.accent}10`:s.editorBg;return i.jsxs("div",{ref:T,style:{position:"relative"},children:[i.jsx("div",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.1em",color:s.textMuted,textTransform:"uppercase",fontFamily:s.font,marginBottom:3},children:t}),i.jsx("button",{onClick:()=>E(N=>!N),onDragOver:S,onDragEnter:S,onDragLeave:h,onDrop:A,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"5px 8px",background:p,border:`1px dashed ${R}`,borderRadius:4,cursor:"pointer",color:n?s.textPrimary:s.textMuted,fontFamily:s.fontMono,fontSize:11,textAlign:"left",transition:"background 0.1s, border-color 0.1s"},children:n?i.jsxs(i.Fragment,{children:[i.jsxs("span",{draggable:!0,onDragStart:N=>{N.stopPropagation(),JR(N.dataTransfer,{column:n,fromSlot:e})},style:{display:"inline-flex",alignItems:"center",gap:6,flex:1,cursor:"grab",minWidth:0},children:[i.jsx("span",{style:{color:Xl(o.get(n)??"dimension",s),fontWeight:700,width:14},children:$l(o.get(n)??"dimension")}),i.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})]}),i.jsx("span",{onClick:N=>{N.stopPropagation(),l(),E(!1)},title:"Clear",style:{color:s.textMuted,fontSize:10,padding:"0 4px"},children:"✕"})]}):i.jsx("span",{children:d?"drop to set":"+ drop column"})}),c&&i.jsx("div",{style:{position:"absolute",top:"calc(100% + 2px)",left:0,right:0,zIndex:10,background:s.cellBg,border:`1px solid ${s.cellBorder}`,borderRadius:6,boxShadow:"0 6px 16px rgba(0,0,0,0.25)",padding:4,maxHeight:220,overflow:"auto"},children:r.map(N=>i.jsxs("button",{onClick:()=>{a(N),E(!1)},style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 6px",background:"transparent",border:"none",borderRadius:3,cursor:"pointer",textAlign:"left",color:s.textPrimary,fontFamily:s.fontMono,fontSize:11},onMouseEnter:I=>{I.currentTarget.style.background=s.tableRowHover},onMouseLeave:I=>{I.currentTarget.style.background="transparent"},children:[i.jsx("span",{style:{color:Xl(o.get(N)??"dimension",s),fontWeight:700,width:14},children:$l(o.get(N)??"dimension")}),i.jsx("span",{children:N})]},N))})]})}const Ps=[{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 Kl(e){return`${e}_${Math.random().toString(36).slice(2,10)}`}function v0(){return{mode:"keep",groups:[{id:Kl("g"),combinator:"and",rules:[]}]}}function U0(e){const t=Ps.find(n=>n.value===e.operation);return t?e.column?t.needsValue?`${e.column} ${t.label} ${e.value||"…"}`:`${e.column} ${t.label}`:"…":""}function w0({cell:e,cells:t,index:n,themeMode:r,onUpdate:o}){const s=oe[r],a=f.useMemo(v0,[e.id]),l=e.filterConfig??a,c=f.useMemo(()=>{const m=e.upstream??l.upstream;if(m)return t.find(C=>C.name===m)},[e.upstream,l.upstream,t]),E=f.useMemo(()=>t.slice(0,n).filter(m=>m.name&&m.result),[t,n]),d=c==null?void 0:c.result,u=(d==null?void 0:d.columns)??[],T=f.useMemo(()=>ji(d),[d]),S=m=>{o({filterConfig:m})},h=(m,C)=>{S({...l,groups:l.groups.map(g=>g.id===m?{...g,...C}:g)})},A=(m,C,g)=>{S({...l,groups:l.groups.map(y=>y.id===m?{...y,rules:y.rules.map(_=>_.id===C?{..._,...g}:_)}:y)})},R=m=>{S({...l,groups:l.groups.map(C=>C.id===m?{...C,rules:[...C.rules,{id:Kl("r"),column:u[0]??"",operation:"eq",value:""}]}:C)})},p=(m,C)=>{S({...l,groups:l.groups.map(g=>g.id===m?{...g,rules:g.rules.filter(y=>y.id!==C)}:g)})},N=()=>{S({...l,groups:[...l.groups,{id:Kl("g"),combinator:"and",rules:[]}]})},I=m=>{S({...l,groups:l.groups.filter(C=>C.id!==m)})};if(!c||!d)return i.jsx(Co,{theme:s,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:E,onPick:m=>o({upstream:m})});const O={background:s.editorBg,border:`1px solid ${s.cellBorder}`,borderRadius:3,color:s.textPrimary,fontSize:11,fontFamily:s.fontMono,padding:"3px 6px",outline:"none"};return i.jsxs("div",{style:{background:s.cellBg,border:`1px solid ${s.cellBorder}`,borderLeft:"3px solid #ff7b72",borderRadius:6,fontFamily:s.font,overflow:"hidden"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${s.cellBorder}`,background:`${s.tableHeaderBg}60`},children:[i.jsx("span",{style:{fontSize:10,fontFamily:s.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#ff7b72",background:"#ff7b7218",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Filter"}),e.name&&i.jsx("span",{style:{fontSize:12,fontFamily:s.fontMono,color:s.textSecondary},children:e.name}),i.jsxs("span",{style:{fontSize:11,color:s.textMuted,fontFamily:s.fontMono},children:["· df: ",c.name]}),i.jsx("button",{onClick:()=>o({upstream:void 0}),style:{fontSize:10,background:"transparent",border:`1px solid ${s.btnBorder}`,borderRadius:3,color:s.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:s.fontMono},children:"change"}),i.jsx("div",{style:{flex:1}}),i.jsx("div",{style:{display:"inline-flex",border:`1px solid ${s.cellBorder}`,borderRadius:3,overflow:"hidden"},children:["keep","drop"].map(m=>i.jsx("button",{onClick:()=>S({...l,mode:m}),style:{fontSize:10,fontFamily:s.font,fontWeight:600,letterSpacing:"0.04em",padding:"3px 10px",background:l.mode===m?`${s.accent}20`:"transparent",color:l.mode===m?s.accent:s.textMuted,border:"none",cursor:"pointer",textTransform:"uppercase"},children:m==="keep"?"Keep rows":"Drop rows"},m))})]}),i.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:10},children:[!T.hasSemanticBinding&&i.jsx(Yi,{theme:s}),l.groups.map((m,C)=>i.jsxs("div",{style:{border:`1px solid ${s.cellBorder}`,borderRadius:6,padding:10,background:`${s.tableHeaderBg}30`,display:"flex",flexDirection:"column",gap:8},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsxs("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.1em",color:s.textMuted,textTransform:"uppercase",fontFamily:s.font},children:["Group ",C+1]}),i.jsx("div",{style:{display:"inline-flex",border:`1px solid ${s.cellBorder}`,borderRadius:3,overflow:"hidden"},children:["and","or"].map(g=>i.jsx("button",{onClick:()=>h(m.id,{combinator:g}),style:{fontSize:10,fontFamily:s.fontMono,padding:"2px 8px",background:m.combinator===g?`${s.accent}20`:"transparent",color:m.combinator===g?s.accent:s.textMuted,border:"none",cursor:"pointer",textTransform:"uppercase",fontWeight:700},children:g},g))}),i.jsx("div",{style:{flex:1}}),l.groups.length>1&&i.jsx("button",{onClick:()=>I(m.id),style:{fontSize:10,background:"transparent",border:`1px solid ${s.btnBorder}`,borderRadius:3,color:s.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:s.font},children:"Remove group"})]}),m.rules.length===0&&i.jsx("div",{style:{fontSize:11,color:s.textMuted,fontFamily:s.font,padding:"4px 2px"},children:"No rules yet — add one below."}),m.rules.map(g=>{const y=Ps.find(_=>_.value===g.operation)??Ps[0];return i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsx(zR,{theme:s,value:g.column||void 0,fields:T.fields,placeholder:"Select field",minWidth:180,onChange:_=>A(m.id,g.id,{column:_??""})}),i.jsx("select",{value:g.operation,onChange:_=>A(m.id,g.id,{operation:_.target.value}),style:{...O,minWidth:120},children:Ps.map(_=>i.jsx("option",{value:_.value,children:_.label},_.value))}),y.needsValue&&i.jsx("input",{value:g.value,onChange:_=>A(m.id,g.id,{value:_.target.value}),placeholder:"Value",style:{...O,flex:1,minWidth:100}}),i.jsx("button",{onClick:()=>p(m.id,g.id),title:"Remove rule",style:{background:"transparent",border:`1px solid ${s.btnBorder}`,borderRadius:3,color:s.textMuted,fontSize:10,padding:"2px 6px",cursor:"pointer"},children:"✕"})]},g.id)}),i.jsx("div",{children:i.jsx("button",{onClick:()=>R(m.id),style:{fontSize:10,fontFamily:s.font,color:s.accent,background:"transparent",border:`1px dashed ${s.accent}55`,borderRadius:3,padding:"3px 10px",cursor:"pointer",letterSpacing:"0.04em"},children:"+ Add filter"})})]},m.id)),i.jsx("div",{children:i.jsx("button",{onClick:N,style:{fontSize:10,fontFamily:s.font,color:s.textMuted,background:"transparent",border:`1px dashed ${s.btnBorder}`,borderRadius:3,padding:"3px 10px",cursor:"pointer",letterSpacing:"0.04em"},children:"+ Add filter group"})})]}),i.jsxs("div",{style:{padding:"6px 12px",borderTop:`1px solid ${s.cellBorder}`,background:`${s.tableHeaderBg}40`,fontSize:10,fontFamily:s.fontMono,color:s.textMuted,letterSpacing:"0.04em",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},children:[l.mode==="keep"?"KEEP WHERE ":"DROP WHERE ",l.groups.map(m=>m.rules.map(U0).join(` ${m.combinator.toUpperCase()} `)).filter(Boolean).map(m=>`(${m})`).join(" AND ")||"—"]})]})}function jd(e){return typeof e=="number"?e:typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e))?Number(e):null}function zl(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 jd(r)}const n=e.map(jd).filter(r=>r!==null);if(n.length===0)return null;switch(t){case"sum":return n.reduce((r,o)=>r+o,0);case"avg":return n.reduce((r,o)=>r+o,0)/n.length;case"min":return n.reduce((r,o)=>o<r?o:r,n[0]);case"max":return n.reduce((r,o)=>o>r?o:r,n[0])}}const B0=[{value:"sum",label:"Sum"},{value:"avg",label:"Average"},{value:"count",label:"Count"},{value:"min",label:"Min"},{value:"max",label:"Max"},{value:"last",label:"Last"}],F0=[{value:"number",label:"Number"},{value:"currency",label:"Currency"},{value:"percent",label:"Percent"},{value:"duration",label:"Duration"}],G0={aggregation:"count",format:"number"};function H0(e,t,n){return n==="count"?zl(e.rows,"count"):!t||!e.columns.includes(t)?null:zl(e.rows.map(r=>r[t]),n)}function k0(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 j0({cell:e,cells:t,index:n,themeMode:r,onUpdate:o}){const s=oe[r],a=e.singleValueConfig??G0,l=a.aggregation??"count",c=a.format??"number",E=f.useMemo(()=>{const p=e.upstream??a.upstream;if(p)return t.find(N=>N.name===p)},[e.upstream,a.upstream,t]),d=f.useMemo(()=>t.slice(0,n).filter(p=>p.name&&p.result),[t,n]),u=E==null?void 0:E.result,T=f.useMemo(()=>ji(u),[u]),S=f.useMemo(()=>u?H0(u,a.metric,l):null,[u,a.metric,l]),h=p=>{o({singleValueConfig:{...a,...p}})};if(!E||!u)return i.jsx(Co,{theme:s,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:d,onPick:p=>o({upstream:p})});const A=k0(S,c),R={background:s.editorBg,border:`1px solid ${s.cellBorder}`,borderRadius:3,color:s.textPrimary,fontSize:11,fontFamily:s.fontMono,padding:"3px 6px",outline:"none"};return i.jsxs("div",{style:{background:s.cellBg,border:`1px solid ${s.cellBorder}`,borderLeft:"3px solid #a371f7",borderRadius:6,fontFamily:s.font,overflow:"hidden"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${s.cellBorder}`,background:`${s.tableHeaderBg}60`},children:[i.jsx("span",{style:{fontSize:10,fontFamily:s.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#a371f7",background:"#a371f718",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Single value"}),e.name&&i.jsx("span",{style:{fontSize:12,fontFamily:s.fontMono,color:s.textSecondary},children:e.name}),i.jsxs("span",{style:{fontSize:11,color:s.textMuted,fontFamily:s.fontMono},children:["· df: ",E.name]}),i.jsx("button",{onClick:()=>o({upstream:void 0}),style:{fontSize:10,background:"transparent",border:`1px solid ${s.btnBorder}`,borderRadius:3,color:s.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:s.fontMono},children:"change"})]}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"280px 1fr"},children:[i.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:8,borderRight:`1px solid ${s.cellBorder}`},children:[i.jsx(ds,{label:"Aggregation",theme:s,children:i.jsx("select",{value:l,onChange:p=>h({aggregation:p.target.value}),style:{...R,width:"100%"},children:B0.map(p=>i.jsx("option",{value:p.value,children:p.label},p.value))})}),l!=="count"&&i.jsxs(ds,{label:"Metric field",theme:s,children:[i.jsx(zR,{theme:s,value:a.metric,fields:T.fields,placeholder:"Select metric or column",minWidth:240,onChange:p=>h({metric:p})}),!T.hasSemanticBinding&&i.jsx(Yi,{theme:s})]}),i.jsx(ds,{label:"Format",theme:s,children:i.jsx("select",{value:c,onChange:p=>h({format:p.target.value}),style:{...R,width:"100%"},children:F0.map(p=>i.jsx("option",{value:p.value,children:p.label},p.value))})}),i.jsx(ds,{label:"Label",theme:s,children:i.jsx("input",{value:a.label??"",onChange:p=>h({label:p.target.value||void 0}),placeholder:"e.g. Total revenue",style:{...R,width:"100%"}})})]}),i.jsxs("div",{style:{padding:"24px 20px",display:"flex",flexDirection:"column",justifyContent:"center",gap:6},children:[i.jsx("div",{style:{fontSize:11,fontFamily:s.font,color:s.textMuted,letterSpacing:"0.06em",textTransform:"uppercase",fontWeight:600},children:a.label??`${l.toUpperCase()}${a.metric?` · ${a.metric}`:""}`}),i.jsx("div",{style:{fontSize:42,fontWeight:700,fontFamily:s.font,color:s.textPrimary,lineHeight:1.1,letterSpacing:"-0.02em"},children:A}),i.jsxs("div",{style:{fontSize:10,color:s.textMuted,fontFamily:s.fontMono},children:["from ",u.rows.length.toLocaleString()," rows"]})]})]})]})}function ds({label:e,theme:t,children:n}){return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[i.jsx("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.1em",color:t.textMuted,textTransform:"uppercase",fontFamily:t.font},children:e}),n]})}const Y0=["sum","avg","count","min","max","count_distinct"],W0={rows:[],columns:[],values:[]};function Yd(e,t){return t.map(n=>String(e[n]??"")).join("|")}function Fa(e,t){return e.metrics.includes(t)?"metric":e.dimensions.includes(t)?"dimension":"column"}function Wd(e,t){const n=e.fields.filter(o=>o.kind===t),r=e.fields.filter(o=>o.kind!==t);return[...n,...r].map(o=>({name:o.name,kind:o.kind}))}function V0({cell:e,cells:t,index:n,themeMode:r,onUpdate:o}){const s=oe[r],a=e.pivotConfig??W0,l={upstream:a.upstream,rows:a.rows??[],columns:a.columns??[],values:a.values??[]},c=f.useMemo(()=>{const R=e.upstream??l.upstream;if(R)return t.find(p=>p.name===R)},[e.upstream,l.upstream,t]),E=f.useMemo(()=>t.slice(0,n).filter(R=>R.name&&R.result),[t,n]),d=c==null?void 0:c.result;d==null||d.columns;const u=f.useMemo(()=>ji(d),[d]),T=f.useMemo(()=>Wd(u,"dimension"),[u]),S=f.useMemo(()=>Wd(u,"metric"),[u]),h=R=>o({pivotConfig:R}),A=f.useMemo(()=>{if(!d||l.rows.length===0&&l.columns.length===0||l.values.length===0)return null;const R=new Set,p=new Map;for(const m of d.rows){const C=Yd(m,l.rows),g=Yd(m,l.columns);R.add(g);let y=p.get(C);if(!y){const P={};for(const D of l.rows)P[D]=m[D];y={row:P,groups:new Map},p.set(C,y)}const _=y.groups.get(g)??[];_.push(m),y.groups.set(g,_)}const N=[...R].sort(),I=N.map(m=>m===""?"value":m),O=[];for(const[,m]of p){const C=m,g=N.map(y=>{const _=C.groups.get(y)??[],P={};for(const D of l.values){const b=_.map(F=>F[D.column]);P[`${D.aggregation}(${D.column})`]=zl(b,D.aggregation)}return P});O.push({rowDims:C.row,values:g})}return{columnKeys:N,columnHeaders:I,body:O}},[l,d]);return!c||!d?i.jsx(Co,{theme:s,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:E,onPick:R=>o({upstream:R})}):i.jsxs("div",{style:{background:s.cellBg,border:`1px solid ${s.cellBorder}`,borderLeft:"3px solid #a371f7",borderRadius:6,fontFamily:s.font,overflow:"hidden"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${s.cellBorder}`,background:`${s.tableHeaderBg}60`},children:[i.jsx("span",{style:{fontSize:10,fontFamily:s.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#a371f7",background:"#a371f718",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Pivot"}),e.name&&i.jsx("span",{style:{fontSize:12,fontFamily:s.fontMono,color:s.textSecondary},children:e.name}),i.jsxs("span",{style:{fontSize:11,color:s.textMuted,fontFamily:s.fontMono},children:["· df: ",c.name]}),i.jsx("button",{onClick:()=>o({upstream:void 0}),style:{fontSize:10,background:"transparent",border:`1px solid ${s.btnBorder}`,borderRadius:3,color:s.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:s.fontMono},children:"change"})]}),!u.hasSemanticBinding&&i.jsx("div",{style:{padding:"8px 12px 0"},children:i.jsx(Yi,{theme:s})}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",padding:12,gap:10,borderBottom:`1px solid ${s.cellBorder}`},children:[i.jsx(Vd,{label:"Rows",selected:l.rows,availableFields:T.filter(R=>!l.rows.includes(R.name)),kindFor:R=>Fa(u,R),theme:s,onAdd:R=>h({...l,rows:[...l.rows,R]}),onRemove:R=>h({...l,rows:l.rows.filter(p=>p!==R)})}),i.jsx(Vd,{label:"Columns",selected:l.columns,availableFields:T.filter(R=>!l.columns.includes(R.name)),kindFor:R=>Fa(u,R),theme:s,onAdd:R=>h({...l,columns:[...l.columns,R]}),onRemove:R=>h({...l,columns:l.columns.filter(p=>p!==R)})}),i.jsx($0,{values:l.values,availableFields:S,kindFor:R=>Fa(u,R),theme:s,onAdd:R=>h({...l,values:[...l.values,{column:R,aggregation:"sum"}]}),onUpdate:(R,p)=>h({...l,values:l.values.map((N,I)=>I===R?{...N,...p}:N)}),onRemove:R=>h({...l,values:l.values.filter((p,N)=>N!==R)})})]}),i.jsx("div",{style:{padding:12,overflowX:"auto"},children:!A||A.body.length===0?i.jsx("div",{style:{fontSize:11,color:s.textMuted,fontFamily:s.font},children:"Pick at least one row/column dimension and one value to see a preview."}):i.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontFamily:s.fontMono,fontSize:11},children:[i.jsx("thead",{children:i.jsxs("tr",{children:[l.rows.map(R=>i.jsx("th",{style:{textAlign:"left",padding:"4px 8px",borderBottom:`1px solid ${s.cellBorder}`,color:s.textSecondary,fontWeight:600},children:R},R)),A.columnHeaders.map((R,p)=>i.jsx("th",{style:{textAlign:"right",padding:"4px 8px",borderBottom:`1px solid ${s.cellBorder}`,color:s.textSecondary,fontWeight:600},children:R},p))]})}),i.jsx("tbody",{children:A.body.slice(0,50).map((R,p)=>i.jsxs("tr",{children:[l.rows.map(N=>i.jsx("td",{style:{padding:"3px 8px",color:s.textPrimary,borderBottom:`1px solid ${s.cellBorder}30`},children:String(R.rowDims[N]??"")},N)),R.values.map((N,I)=>i.jsx("td",{style:{padding:"3px 8px",color:s.textPrimary,textAlign:"right",borderBottom:`1px solid ${s.cellBorder}30`},children:Object.values(N).map((O,m)=>i.jsx("div",{children:O===null?"—":typeof O=="number"?O.toLocaleString(void 0,{maximumFractionDigits:2}):String(O)},m))},I))]},p))})]})})]})}function Vd({label:e,selected:t,availableFields:n,kindFor:r,theme:o,onAdd:s,onRemove:a}){return i.jsx(qR,{label:e,theme:o,availableFields:n,onAdd:s,children:t.length===0?i.jsx("span",{style:{fontSize:11,color:o.textMuted,fontFamily:o.font},children:"+ add field"}):t.map(l=>{const c=r(l);return i.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 6px",background:`${o.accent}14`,border:`1px solid ${o.accent}55`,borderRadius:3,fontSize:11,fontFamily:o.fontMono,color:o.textPrimary,margin:2},children:[i.jsx("span",{style:{color:ro(c,o.accent),fontWeight:700},children:no(c)}),l,i.jsx("span",{onClick:()=>a(l),style:{cursor:"pointer",color:o.textMuted,fontSize:10},title:"Remove",children:"✕"})]},l)})})}function $0({values:e,availableFields:t,kindFor:n,theme:r,onAdd:o,onUpdate:s,onRemove:a}){return i.jsx(qR,{label:"Values",theme:r,availableFields:t,onAdd:o,children:e.length===0?i.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font},children:"+ add value"}):e.map((l,c)=>{const E=n(l.column);return i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,margin:2},children:[i.jsx("select",{value:l.aggregation,onChange:d=>s(c,{aggregation:d.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:Y0.map(d=>i.jsx("option",{value:d,children:d},d))}),i.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:[i.jsx("span",{style:{color:ro(E,r.accent),fontWeight:700},children:no(E)}),l.column,i.jsx("span",{onClick:()=>a(c),style:{cursor:"pointer",color:r.textMuted,fontSize:10},children:"✕"})]})]},c)})})}function qR({label:e,theme:t,availableFields:n,onAdd:r,children:o}){const[s,a]=f.useState(!1),l=f.useRef(null);return f.useEffect(()=>{if(!s)return;const c=E=>{var d;(d=l.current)!=null&&d.contains(E.target)||a(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[s]),i.jsxs("div",{ref:l,style:{position:"relative",display:"flex",flexDirection:"column",gap:4},children:[i.jsx("div",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.1em",color:t.textMuted,textTransform:"uppercase",fontFamily:t.font},children:e}),i.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:o}),s&&n.length>0&&i.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=>i.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:E=>{E.currentTarget.style.background=t.tableRowHover},onMouseLeave:E=>{E.currentTarget.style.background="transparent"},children:[i.jsx("span",{style:{color:ro(c.kind,t.accent),fontWeight:700,width:12},children:no(c.kind)}),i.jsx("span",{children:c.name})]},c.name))})]})}const us="#79c0ff";function X0({cell:e,cells:t,index:n,themeMode:r,onUpdate:o}){const s=oe[r],a=e.tableConfig??{},l=f.useMemo(()=>{const T=e.upstream??a.upstream;if(T)return t.find(S=>S.name===T)},[e.upstream,a.upstream,t]),c=f.useMemo(()=>t.slice(0,n).filter(T=>T.name&&T.result),[t,n]),E=l==null?void 0:l.result,d=a.visibleColumns,u=f.useMemo(()=>{if(!E)return;if(!d||d.length===0)return E;const T=new Set(E.columns),S=d.filter(h=>T.has(h));return S.length===0?E:{...E,columns:S}},[E,d]);return!l||!u?i.jsx(Co,{theme:s,accentColor:us,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:T=>o({upstream:T})}):i.jsxs("div",{style:{display:"flex",flexDirection:"column",background:s.cellBg,border:`1px solid ${s.cellBorder}`,borderLeft:`3px solid ${us}`,borderRadius:6,overflow:"hidden",fontFamily:s.font},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${s.cellBorder}`,background:`${s.tableHeaderBg}60`},children:[i.jsx("span",{style:{fontSize:10,fontFamily:s.fontMono,fontWeight:700,letterSpacing:"0.08em",color:us,background:`${us}18`,padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Table"}),e.name&&i.jsx("span",{style:{fontSize:12,fontFamily:s.fontMono,color:s.textSecondary},children:e.name}),i.jsxs("span",{style:{fontSize:11,color:s.textMuted,fontFamily:s.fontMono},children:["· df: ",e.upstream??a.upstream]}),i.jsx("button",{onClick:()=>o({upstream:void 0}),title:"Change upstream dataframe",style:{fontSize:10,background:"transparent",border:`1px solid ${s.btnBorder}`,borderRadius:3,color:s.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:s.fontMono},children:"change"}),i.jsx("div",{style:{flex:1}}),i.jsxs("span",{style:{fontSize:11,color:s.textMuted,fontFamily:s.fontMono},children:[u.rows.length.toLocaleString()," rows · ",u.columns.length," cols"]})]}),i.jsx(mo,{result:u,themeMode:r})]})}async function K0(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(),o=new TextDecoder;let s="";try{for(;;){const{value:a,done:l}=await r.read();if(l)break;s+=o.decode(a,{stream:!0});let c;for(;(c=s.indexOf(`
|
|
533
|
-
|
|
534
|
-
`))!==-1;){const E=s.slice(0,c);s=s.slice(c+2);const d=E.split(`
|
|
535
|
-
`).find(u=>u.startsWith("data: "));if(d)try{t(JSON.parse(d.slice(6)))}catch{}}}}finally{r.releaseLock()}}function Ts(){return i.jsx("span",{style:{color:"#ff7b72",marginLeft:2},children:"*"})}function Ga(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function z0(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 QR({cell:e,onClose:t,onSaved:n,initialContent:r,initialName:o,initialDescription:s,initialTags:a}){const{state:l,dispatch:c}=Te(),E=oe[l.themeMode],d=f.useRef(null),[u,T]=f.useState(o||e.name||"new_block"),[S,h]=f.useState(""),[A,R]=f.useState(""),[p,N]=f.useState(s??l.notebookMetadata.description??""),[I,O]=f.useState((a??l.notebookMetadata.categories??[]).join(", ")),[m,C]=f.useState(r??e.content),[g,y]=f.useState(""),[_,P]=f.useState(""),[D,b]=f.useState([]),[F,x]=f.useState(!1),[w,M]=f.useState(null),B=f.useMemo(()=>z0(m),[m]),v=f.useMemo(()=>I.split(",").map($=>$.trim()).filter(Boolean),[I]),L=[{id:"has-name",label:"Block has name",severity:"error",passed:!!u.trim()},{id:"has-description",label:"Block has description",severity:"error",passed:!!p.trim()},{id:"has-owner",label:"Block has owner",severity:"error",passed:!!A.trim()},{id:"has-domain",label:"Block has domain",severity:"error",passed:!!S.trim()},{id:"has-tags",label:"Has at least one tag",severity:"warning",passed:v.length>0},{id:"has-llm-context",label:"Has LLM context (for agents)",severity:"warning",passed:!!g.trim()}],U=L.some($=>$.severity==="error"&&!$.passed);f.useEffect(()=>{var $;($=d.current)==null||$.focus()},[]),f.useEffect(()=>{const $=z=>{z.key==="Escape"&&t()};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[t]);const G=l.semanticLayer.domains,k=`${S.trim()?`blocks/${Ga(S)}/`:"blocks/"}${Ga(u)||"new-block"}.dql`,J=async()=>{var $;if(U){M("Fix the required governance fields before saving.");return}if(!m.trim()){M("Block content is required.");return}x(!0),M(null);try{const z=_.split(`
|
|
536
|
-
`).map(ne=>ne.trim()).filter(Boolean),q=D.map(ne=>({question:ne.question.trim(),sql:ne.sql.trim()||void 0})).filter(ne=>ne.question),X=await Z.saveAsBlock({cellId:e.id,notebookPath:(($=l.activeFile)==null?void 0:$.path)??null,name:u.trim(),domain:S.trim()||void 0,owner:A.trim()||void 0,content:m,description:p.trim()||void 0,tags:v,metricRefs:B,llmContext:g.trim()||void 0,examples:q.length>0?q:void 0,invariants:z.length>0?z:void 0}),Q={name:`${Ga(u)||"new-block"}.dql`,path:X.path,type:"block",folder:"blocks"};l.files.some(ne=>ne.path===X.path)||c({type:"FILE_ADDED",file:Q});const ae=await Z.openBlockStudio(X.path);c({type:"OPEN_BLOCK_STUDIO",file:Q,payload:ae}),n==null||n({...X,name:u.trim()}),t()}catch(z){M(z instanceof Error?z.message:String(z))}finally{x(!1)}},K={width:"100%",background:E.inputBg,border:`1px solid ${w?E.error:E.inputBorder}`,borderRadius:6,color:E.textPrimary,fontSize:13,fontFamily:E.font,padding:"8px 12px",outline:"none",boxSizing:"border-box"};return i.jsx("div",{onClick:$=>{$.target===$.currentTarget&&t()},style:{position:"fixed",inset:0,background:E.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1100,backdropFilter:"blur(4px)"},children:i.jsxs("div",{style:{width:760,maxWidth:"calc(100vw - 48px)",maxHeight:"calc(100vh - 48px)",overflow:"auto",background:E.modalBg,border:`1px solid ${E.cellBorder}`,borderRadius:12,boxShadow:"0 20px 60px rgba(0,0,0,0.5)"},children:[i.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[i.jsx("h2",{style:{margin:0,fontSize:16,fontWeight:600,color:E.textPrimary,fontFamily:E.font},children:"Save as Block"}),i.jsx("button",{onClick:t,style:{background:"transparent",border:"none",color:E.textMuted,cursor:"pointer",fontSize:18},children:"×"})]}),i.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:16},children:[i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsxs("label",{style:{fontSize:12,color:E.textSecondary,fontFamily:E.font},children:["Block Name ",i.jsx(Ts,{})]}),i.jsx("input",{ref:d,value:u,onChange:$=>T($.target.value),style:K})]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsxs("label",{style:{fontSize:12,color:E.textSecondary,fontFamily:E.font},children:["Domain ",i.jsx(Ts,{})]}),i.jsx("input",{value:S,onChange:$=>h($.target.value),list:"semantic-domain-options",style:K,placeholder:"finance"}),i.jsx("datalist",{id:"semantic-domain-options",children:G.map($=>i.jsx("option",{value:$},$))})]})]}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsxs("label",{style:{fontSize:12,color:E.textSecondary,fontFamily:E.font},children:["Owner ",i.jsx(Ts,{})]}),i.jsx("input",{value:A,onChange:$=>R($.target.value),style:K,placeholder:"data-platform@company.com"})]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,color:E.textSecondary,fontFamily:E.font},children:"Tags"}),i.jsx("input",{value:I,onChange:$=>O($.target.value),style:K,placeholder:"revenue, dashboard"})]})]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsxs("label",{style:{fontSize:12,color:E.textSecondary,fontFamily:E.font},children:["Description ",i.jsx(Ts,{})]}),i.jsx("input",{value:p,onChange:$=>N($.target.value),style:K})]}),i.jsxs("details",{style:{border:`1px solid ${E.cellBorder}`,borderRadius:6,padding:"8px 12px"},children:[i.jsx("summary",{style:{fontSize:12,fontWeight:600,color:E.textSecondary,fontFamily:E.font,cursor:"pointer"},children:"Agent-facing metadata (optional — helps AI tools ground answers on this block)"}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10,paddingTop:10},children:[i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,color:E.textSecondary,fontFamily:E.font},children:"How should an AI describe this block?"}),i.jsx("textarea",{value:g,onChange:$=>y($.target.value),rows:3,placeholder:'One paragraph. E.g. "Monthly revenue recognized from closed-won deals, grouped by billing month. Excludes refunds."',style:{...K,fontFamily:E.font,lineHeight:1.5,resize:"vertical"}})]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,color:E.textSecondary,fontFamily:E.font},children:"Invariants (one per line)"}),i.jsx("textarea",{value:_,onChange:$=>P($.target.value),rows:2,placeholder:`Revenue is never negative
|
|
537
|
-
Each row is a unique month`,style:{...K,fontFamily:E.fontMono,lineHeight:1.5,resize:"vertical"}})]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,color:E.textSecondary,fontFamily:E.font},children:"Example questions (grounding for chat cells)"}),D.map(($,z)=>i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr auto",gap:6},children:[i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsx("input",{value:$.question,onChange:q=>{const X=[...D];X[z]={...X[z],question:q.target.value},b(X)},placeholder:"What was revenue last month?",style:K}),i.jsx("input",{value:$.sql,onChange:q=>{const X=[...D];X[z]={...X[z],sql:q.target.value},b(X)},placeholder:"Optional SQL snippet",style:{...K,fontFamily:E.fontMono,fontSize:12}})]}),i.jsx("button",{type:"button",onClick:()=>b(D.filter((q,X)=>X!==z)),style:{background:"transparent",border:`1px solid ${E.cellBorder}`,borderRadius:6,color:E.textMuted,cursor:"pointer",fontSize:12,padding:"0 10px"},children:"×"})]},z)),i.jsx("button",{type:"button",onClick:()=>b([...D,{question:"",sql:""}]),style:{alignSelf:"flex-start",background:E.btnBg,border:`1px solid ${E.btnBorder}`,borderRadius:6,color:E.textSecondary,cursor:"pointer",fontSize:12,fontFamily:E.font,padding:"4px 10px"},children:"+ Add example"})]})]})]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,padding:"10px 12px",background:E.pillBg,borderRadius:6,border:`1px solid ${E.cellBorder}`},children:[i.jsx("div",{style:{fontSize:11,fontWeight:700,color:E.textSecondary,fontFamily:E.font,letterSpacing:"0.06em",textTransform:"uppercase"},children:"Governance checks"}),i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:L.map($=>{const z=$.passed?"#3fb950":$.severity==="error"?"#ff7b72":"#e3b341",q=$.passed?"✓":$.severity==="error"?"✕":"!";return i.jsxs("span",{title:$.passed?`${$.label} — passed`:`${$.label} — ${$.severity}`,style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,fontFamily:E.font,color:z,background:`${z}18`,border:`1px solid ${z}55`,borderRadius:999,padding:"2px 10px"},children:[i.jsx("span",{style:{fontWeight:700},children:q}),$.label]},$.id)})})]}),i.jsx("div",{style:{fontSize:12,color:E.textMuted,fontFamily:E.fontMono,padding:"8px 12px",background:E.pillBg,borderRadius:6},children:k}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,color:E.textSecondary,fontFamily:E.font},children:"Content Preview"}),i.jsx("textarea",{value:m,onChange:$=>C($.target.value),style:{...K,minHeight:220,resize:"vertical",fontFamily:E.fontMono,lineHeight:1.5}})]}),B.length>0&&i.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,padding:"10px 12px",background:E.pillBg,borderRadius:6},children:[i.jsx("span",{style:{fontSize:11,color:E.textMuted,fontFamily:E.font},children:"Detected semantic refs:"}),B.map($=>i.jsx("span",{style:{fontSize:11,color:E.accent,fontFamily:E.fontMono,background:`${E.accent}18`,borderRadius:999,padding:"2px 8px"},children:$},$))]}),w&&i.jsx("div",{style:{fontSize:12,color:E.error,fontFamily:E.font},children:w})]}),i.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${E.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[i.jsx("button",{onClick:t,style:{background:E.btnBg,border:`1px solid ${E.btnBorder}`,borderRadius:6,color:E.textSecondary,cursor:"pointer",fontSize:13,fontFamily:E.font,padding:"7px 16px"},children:"Cancel"}),i.jsx("button",{onClick:J,disabled:F||U,title:U?"Fix governance errors to enable Save":void 0,style:{background:E.accent,border:`1px solid ${E.accent}`,borderRadius:6,color:"#fff",cursor:F||U?"not-allowed":"pointer",fontSize:13,fontFamily:E.font,padding:"7px 20px",opacity:F||U?.5:1},children:F?"Saving...":"Save Block"})]})]})})}const $d=[{id:"claude-agent-sdk",label:"Claude Agent SDK",hint:"Uses ANTHROPIC_API_KEY / ~/.dql/credentials"},{id:"claude-code",label:"Claude Code",hint:"Spawns `claude -p` — uses your Claude Code auth"}];function Xd(){return`m_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function J0(e,t,n){if(n){const r=e.find(o=>o.name===n);if(r!=null&&r.content)return r.content}for(let r=t-1;r>=0;r--){const o=e[r];if((o.type==="sql"||o.type==="dql")&&o.content)return o.content}}function q0({cell:e,cells:t,index:n,themeMode:r,onUpdate:o}){const{dispatch:s}=Te(),a=oe[r],l=e.chatConfig??{provider:"claude-agent-sdk",history:[]},[c,E]=f.useState(""),[d,u]=f.useState(!1),[T,S]=f.useState(""),[h,A]=f.useState([]),[R,p]=f.useState(null),[N,I]=f.useState(!1),O=f.useRef(null),m=P=>{o({chatConfig:{...l,...P}})},C=async()=>{const P=c.trim();if(!P||d)return;const D={id:Xd(),role:"user",content:P},b={id:Xd(),role:"assistant",content:"",events:[]},F=[...l.history,D,b];m({history:F}),E(""),S(""),A([]),p(null),u(!0);const x=new AbortController;O.current=x;let w="";const M=[];let B;try{await K0({provider:l.provider,messages:[...l.history,D].map(v=>({role:v.role,content:v.content})),upstream:{cellId:e.id,sql:J0(t,n,l.upstream)},signal:x.signal},v=>{M.push(v),A([...M]),v.kind==="text"?(w+=v.text,S(w)):v.kind==="error"?p(v.message):v.kind==="proposal"&&(B={...v.proposal,certified:v.governance.certified,errors:v.governance.errors,warnings:v.governance.warnings})})}catch(v){p(v instanceof Error?v.message:String(v))}finally{const v=F.map(L=>L.id===b.id?{...L,content:w,events:M.map(U=>({kind:U.kind,payload:U}))}:L);o({chatConfig:{...l,history:v,lastProposal:B??l.lastProposal}}),u(!1),S(""),A([]),O.current=null}},g=()=>{var P;(P=O.current)==null||P.abort()},y=()=>{m({history:[],lastProposal:void 0})},_=l.lastProposal;return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10,padding:"14px 16px",background:a.cellBg,fontFamily:a.font},children:[i.jsx(Q0,{cell:e,provider:l.provider,onProviderChange:P=>m({provider:P}),onClear:l.history.length>0?y:void 0,t:a}),l.history.length===0&&!d&&i.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."}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[l.history.map(P=>i.jsx(Z0,{msg:P,t:a},P.id)),d&&i.jsx(eD,{streamingText:T,events:h,t:a})]}),R&&i.jsx("div",{style:{fontSize:12,color:"#ff7b72",padding:"6px 10px",background:"#ff7b7218",borderRadius:4},children:R}),_&&i.jsx(nD,{proposal:_,t:a,onOpen:()=>I(!0),onDismiss:()=>m({lastProposal:void 0})}),i.jsx(tD,{value:c,onChange:E,onSend:C,onStop:g,running:d,t:a}),N&&_&&i.jsx(QR,{cell:e,initialContent:_.sql,initialName:_.name,initialDescription:_.description,initialTags:_.tags,onClose:()=>I(!1),onSaved:({path:P,name:D})=>{I(!1),m({lastProposal:void 0}),s({type:"FILE_ADDED",file:{name:D,path:P,type:"block",folder:"blocks"}})}})]})}function Q0({cell:e,provider:t,onProviderChange:n,onClear:r,t:o}){var s;return i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{style:{fontSize:10,fontFamily:o.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#f0883e",textTransform:"uppercase",padding:"2px 6px",borderRadius:3,background:"#f0883e18"},children:"Chat"}),e.name&&i.jsx("span",{style:{fontSize:12,fontFamily:o.fontMono,color:o.textSecondary},children:e.name}),i.jsx("select",{value:t,onChange:a=>n(a.target.value),title:(s=$d.find(a=>a.id===t))==null?void 0:s.hint,style:{marginLeft:"auto",fontSize:11,fontFamily:o.fontMono,padding:"3px 6px",background:o.cellBg,color:o.textSecondary,border:`1px solid ${o.cellBorder}`,borderRadius:4},children:$d.map(a=>i.jsx("option",{value:a.id,children:a.label},a.id))}),r&&i.jsx("button",{onClick:r,style:{fontSize:11,padding:"3px 8px",background:"transparent",color:o.textSecondary,border:`1px solid ${o.cellBorder}`,borderRadius:4,cursor:"pointer"},children:"Clear"})]})}function Z0({msg:e,t}){const n=e.role==="user",r=(e.events??[]).map(o=>o.payload);return i.jsxs("div",{style:{padding:"8px 12px",borderRadius:6,background:n?`${t.accent}14`:t.cellBg,border:`1px solid ${n?`${t.accent}40`:t.cellBorder}`,fontSize:13,lineHeight:1.5,color:t.textPrimary,whiteSpace:"pre-wrap"},children:[i.jsx("div",{style:{fontSize:10,fontFamily:t.fontMono,color:t.textMuted,marginBottom:4,textTransform:"uppercase",letterSpacing:"0.08em"},children:n?"You":"Assistant"}),e.content||(r.length>0?i.jsx("em",{style:{color:t.textSecondary},children:"(tool calls only)"}):null),r.filter(o=>o.kind==="tool_call").map(o=>i.jsx(ZR,{turn:o,t},`tc-${o.id}`))]})}function eD({streamingText:e,events:t,t:n}){return i.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:[i.jsxs("div",{style:{fontSize:10,fontFamily:n.fontMono,color:n.textMuted,marginBottom:4,textTransform:"uppercase",letterSpacing:"0.08em"},children:["Assistant ",i.jsx("span",{style:{color:n.accent},children:"●"})]}),e||i.jsx("em",{style:{color:n.textSecondary},children:"Thinking…"}),t.filter(r=>r.kind==="tool_call").map(r=>i.jsx(ZR,{turn:r,t:n},`live-${r.id}`))]})}function ZR({turn:e,t}){return e.kind!=="tool_call"?null:i.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 tD({value:e,onChange:t,onSend:n,onStop:r,running:o,t:s}){return i.jsxs("div",{style:{display:"flex",gap:6,alignItems:"flex-end"},children:[i.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:s.font,background:s.cellBg,color:s.textPrimary,border:`1px solid ${s.cellBorder}`,borderRadius:6}}),o?i.jsx("button",{onClick:r,style:{padding:"8px 14px",fontSize:12,background:"#ff7b7218",color:"#ff7b72",border:"1px solid #ff7b72",borderRadius:6,cursor:"pointer"},children:"Stop"}):i.jsx("button",{onClick:n,disabled:!e.trim(),style:{padding:"8px 14px",fontSize:12,background:e.trim()?`${s.accent}28`:"transparent",color:e.trim()?s.accent:s.textMuted,border:`1px solid ${e.trim()?s.accent:s.cellBorder}`,borderRadius:6,cursor:e.trim()?"pointer":"not-allowed"},children:"Send"})]})}function nD({proposal:e,t,onOpen:n,onDismiss:r}){const o=[{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 i.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:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{style:{fontSize:10,fontFamily:t.fontMono,fontWeight:700,letterSpacing:"0.08em",color:e.certified?"#3fb950":"#f0883e",textTransform:"uppercase"},children:"Block Proposal"}),i.jsx("span",{style:{fontSize:13,fontFamily:t.fontMono,color:t.textPrimary},children:e.name}),e.domain&&i.jsxs("span",{style:{fontSize:11,color:t.textSecondary},children:["· ",e.domain]}),i.jsx("button",{onClick:r,style:{marginLeft:"auto",fontSize:11,padding:"2px 6px",background:"transparent",color:t.textMuted,border:"none",cursor:"pointer"},children:"✕"})]}),i.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:o.map(s=>i.jsxs("span",{style:{fontSize:10,fontFamily:t.fontMono,padding:"2px 6px",borderRadius:3,background:s.passed?"#3fb95020":"#ff7b7220",color:s.passed?"#3fb950":"#ff7b72",border:`1px solid ${s.passed?"#3fb95040":"#ff7b7240"}`},children:[s.passed?"✓":"✕"," ",s.label]},s.id))}),e.description&&i.jsx("div",{style:{fontSize:12,color:t.textSecondary},children:e.description}),i.jsx("div",{children:i.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 rD=[{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
|
|
538
|
-
category,
|
|
539
|
-
COUNT(*) AS count,
|
|
540
|
-
SUM(amount) AS total
|
|
541
|
-
FROM read_csv_auto('data/filename.csv')
|
|
542
|
-
GROUP BY category
|
|
543
|
-
ORDER BY total DESC`},{id:"filter-date",label:"Filter by date range",description:"Filter rows between two dates",category:"SQL",code:`SELECT *
|
|
544
|
-
FROM read_csv_auto('data/filename.csv')
|
|
545
|
-
WHERE date_column >= '2024-01-01'
|
|
546
|
-
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
|
|
547
|
-
*,
|
|
548
|
-
ROW_NUMBER() OVER (PARTITION BY category ORDER BY amount DESC) AS rank
|
|
549
|
-
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 (
|
|
550
|
-
SELECT *
|
|
551
|
-
FROM read_csv_auto('data/filename.csv')
|
|
552
|
-
WHERE amount > 0
|
|
553
|
-
)
|
|
554
|
-
SELECT
|
|
555
|
-
category,
|
|
556
|
-
SUM(amount) AS total
|
|
557
|
-
FROM base
|
|
558
|
-
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
|
|
559
|
-
FROM read_csv_auto('data/table_a.csv') AS a
|
|
560
|
-
JOIN read_csv_auto('data/table_b.csv') AS b
|
|
561
|
-
ON a.id = b.id`},{id:"pivot",label:"Pivot / unpivot",description:"Pivot a column into multiple columns",category:"SQL",code:`SELECT *
|
|
562
|
-
FROM (
|
|
563
|
-
SELECT category, quarter, amount
|
|
564
|
-
FROM read_csv_auto('data/filename.csv')
|
|
565
|
-
) 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" {
|
|
566
|
-
domain = "analytics"
|
|
567
|
-
type = "custom"
|
|
568
|
-
description = "Describe what this block does"
|
|
569
|
-
owner = "data-team"
|
|
570
|
-
tags = ["analytics"]
|
|
571
|
-
|
|
572
|
-
query = """
|
|
573
|
-
SELECT *
|
|
574
|
-
FROM read_csv_auto('data/filename.csv')
|
|
575
|
-
LIMIT 100
|
|
576
|
-
"""
|
|
577
|
-
|
|
578
|
-
visualization {
|
|
579
|
-
chart = "table"
|
|
580
|
-
}
|
|
581
|
-
}`},{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" {
|
|
582
|
-
domain = "revenue"
|
|
583
|
-
type = "custom"
|
|
584
|
-
description = "Revenue grouped by segment"
|
|
585
|
-
owner = "data-team"
|
|
586
|
-
tags = ["revenue"]
|
|
587
|
-
|
|
588
|
-
params {
|
|
589
|
-
period = "current_quarter"
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
query = """
|
|
593
|
-
SELECT
|
|
594
|
-
segment_tier AS segment,
|
|
595
|
-
SUM(amount) AS revenue
|
|
596
|
-
FROM read_csv_auto('data/revenue.csv')
|
|
597
|
-
WHERE fiscal_period = \${period}
|
|
598
|
-
GROUP BY segment_tier
|
|
599
|
-
ORDER BY revenue DESC
|
|
600
|
-
"""
|
|
601
|
-
|
|
602
|
-
visualization {
|
|
603
|
-
chart = "bar"
|
|
604
|
-
x = segment
|
|
605
|
-
y = revenue
|
|
606
|
-
}
|
|
607
|
-
|
|
608
|
-
tests {
|
|
609
|
-
assert row_count > 0
|
|
610
|
-
}
|
|
611
|
-
}`},{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)
|
|
612
|
-
FROM fct_revenue
|
|
613
|
-
GROUP BY @dim(segment)
|
|
614
|
-
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" {
|
|
615
|
-
domain = "revenue"
|
|
616
|
-
type = "semantic"
|
|
617
|
-
owner = "data-team"
|
|
618
|
-
description = "Annual Recurring Revenue by subscription plan tier"
|
|
619
|
-
tags = ["arr", "revenue", "saas"]
|
|
620
|
-
|
|
621
|
-
metric = "arr"
|
|
622
|
-
dimensions = ["plan_tier"]
|
|
623
|
-
|
|
624
|
-
visualization {
|
|
625
|
-
chart = "bar"
|
|
626
|
-
x = plan_tier
|
|
627
|
-
y = arr
|
|
628
|
-
}
|
|
629
|
-
|
|
630
|
-
tests {
|
|
631
|
-
assert row_count > 0
|
|
632
|
-
}
|
|
633
|
-
}`},{id:"revenue-by-segment",label:"Revenue by segment",description:"Aggregate revenue totals, deal count, and average deal size per segment",category:"Analysis",code:`SELECT
|
|
634
|
-
segment_tier,
|
|
635
|
-
SUM(amount) AS total_revenue,
|
|
636
|
-
COUNT(*) AS deals,
|
|
637
|
-
ROUND(AVG(amount), 0) AS avg_deal
|
|
638
|
-
FROM read_csv_auto('data/revenue.csv')
|
|
639
|
-
GROUP BY segment_tier
|
|
640
|
-
ORDER BY total_revenue DESC`},{id:"quarterly-trend",label:"Quarterly trend",description:"Revenue totals grouped by fiscal year and quarter",category:"Analysis",code:`SELECT
|
|
641
|
-
fiscal_year || ' ' || fiscal_quarter AS period,
|
|
642
|
-
SUM(amount) AS revenue
|
|
643
|
-
FROM read_csv_auto('data/revenue.csv')
|
|
644
|
-
GROUP BY fiscal_year, fiscal_quarter
|
|
645
|
-
ORDER BY fiscal_year, fiscal_quarter`}];function oD({onInsert:e,themeMode:t,cellType:n}){const r=oe[t],[o,s]=f.useState(!1),[a,l]=f.useState(null),c=f.useRef(null),E=rD.filter(T=>n==="dql"?T.category==="DQL":T.category==="SQL"||T.category==="Analysis"),d=Array.from(new Set(E.map(T=>T.category)));f.useEffect(()=>{if(!o)return;function T(S){c.current&&!c.current.contains(S.target)&&s(!1)}return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[o]);function u(T){e(T),s(!1)}return i.jsxs("div",{ref:c,style:{position:"relative",display:"inline-block"},children:[i.jsxs("button",{title:"Insert template snippet",onClick:()=>s(T=>!T),style:{height:22,padding:"0 8px",fontSize:10,fontFamily:r.font,fontWeight:600,letterSpacing:"0.04em",color:o?r.accent:r.textMuted,background:o?`${r.accent}15`:"transparent",border:`1px solid ${o?r.accent+"50":r.btnBorder}`,borderRadius:4,cursor:"pointer",display:"flex",alignItems:"center",gap:4,transition:"all 0.15s",whiteSpace:"nowrap"},children:[i.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"]}),o&&i.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:d.map(T=>i.jsxs("div",{children:[i.jsx("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:700,fontFamily:r.font,letterSpacing:"0.08em",textTransform:"uppercase",color:r.textMuted},children:T}),E.filter(S=>S.category===T).map(S=>i.jsxs("button",{onMouseEnter:()=>l(S.id),onMouseLeave:()=>l(null),onClick:()=>u(S.code),style:{width:"100%",padding:"7px 12px",textAlign:"left",background:a===S.id?r.sidebarItemHover:"transparent",border:"none",cursor:"pointer",display:"flex",flexDirection:"column",gap:2,transition:"background 0.1s"},children:[i.jsx("span",{style:{fontSize:12,fontWeight:600,fontFamily:r.font,color:r.textPrimary,lineHeight:1.4},children:S.label}),i.jsx("span",{style:{fontSize:11,fontFamily:r.font,color:r.textMuted,lineHeight:1.4},children:S.description})]},S.id))]},T))})]})}function sD(e,t){var o,s,a,l;const n=e.upstream??((o=e.singleValueConfig)==null?void 0:o.upstream)??((s=e.filterConfig)==null?void 0:s.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 iD(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}`),`
|
|
646
|
-
visualization {
|
|
647
|
-
${t.join(`
|
|
648
|
-
`)}
|
|
649
|
-
}`}function aD(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,'\\"')}"`),`
|
|
650
|
-
visualization {
|
|
651
|
-
${t.join(`
|
|
652
|
-
`)}
|
|
653
|
-
}`}function lD(e,t){return` query = """
|
|
654
|
-
${e.replace(/^/gm," ")}
|
|
655
|
-
"""${t}`}function cD(e,t){var a,l,c,E;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=sD(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="",o,s;switch(e.type){case"chart":r=iD(e.chartConfig),o=e.name??(n.name?`${n.name}_chart`:"chart_block"),s=((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=aD(e.singleValueConfig),o=e.name??((c=e.singleValueConfig)!=null&&c.label?e.singleValueConfig.label:`${n.name??"metric"}_kpi`),s=(E=e.singleValueConfig)==null?void 0:E.label;break;case"filter":case"pivot":case"table":o=e.name??(n.name?`${n.name}_${e.type}`:`${e.type}_block`);break}return{content:lD(n.sql,r),suggestedName:o,suggestedDescription:s,derivedFromUpstream:!0}}function ED(e){let t=e;try{const E=JSON.parse(e);E&&typeof E.error=="string"&&(t=E.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 o=t.match(/LINE\s+(\d+):/i)??t.match(/\bline\s+(\d+)\b/i);o&&(r=parseInt(o[1],10));let s;const a=t.match(/at or near "([^"]+)"/i);a?s=a[1]:/at end of input/i.test(t)&&(s="end of input");let l;n==="Syntax Error"?s==='"""'||t.includes('"""')?l="Triple-quoted strings are DQL block syntax. Use a DQL cell for block syntax, or plain SQL in a SQL cell.":s==="end of input"||/at end of input/i.test(t)?l="Query is incomplete — check for unclosed parentheses, missing keywords, or a dangling comma.":(s===")"||s==="(")&&(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:s,hint:l}}function dD(e,t){const n=e.length,r=t.length,o=Array.from({length:n+1},(s,a)=>Array.from({length:r+1},(l,c)=>a===0?c:c===0?a:0));for(let s=1;s<=n;s++)for(let a=1;a<=r;a++)o[s][a]=e[s-1]===t[a-1]?o[s-1][a-1]:1+Math.min(o[s-1][a],o[s][a-1],o[s-1][a-1]);return o[n][r]}function Kd(e,t){const n=e.toLowerCase();let r=null,o=4;for(const s of t){const a=dD(n,s.toLowerCase());a<o&&(o=a,r=s)}return r}function uD({message:e,themeMode:t,onFix:n,schemaTables:r}){const o=oe[t],s=ED(e);let a=null;if(r&&r.length>0&&s.type==="Reference Error"){const c=/column.*not found|Referenced column/i.test(s.message),E=/table.*not found|Table.*does not exist/i.test(s.message);if(c&&s.near){const d=r.flatMap(T=>T.columns.map(S=>S.name)),u=Kd(s.near,d);u&&(a=`Did you mean column "${u}"?`)}else if(E&&s.near){const d=Kd(s.near,r.map(u=>u.name));d&&(a=`Did you mean table "${d}"?`)}}const l=n&&(s.type==="Syntax Error"||s.near===")"||s.near==="("||s.near==="end of input");return i.jsxs("div",{style:{padding:"12px 14px",background:`${o.error}10`,borderLeft:`3px solid ${o.error}`,display:"flex",flexDirection:"column",gap:8},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[i.jsx("div",{style:{flexShrink:0,color:o.error,display:"flex",alignItems:"center"},children:i.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"})})}),i.jsx("span",{style:{fontSize:10,fontWeight:700,fontFamily:o.fontMono,letterSpacing:"0.06em",textTransform:"uppercase",color:o.error,background:`${o.error}18`,border:`1px solid ${o.error}40`,borderRadius:4,padding:"1px 7px",flexShrink:0},children:s.type}),s.line!==void 0&&i.jsxs("span",{style:{fontSize:10,fontWeight:600,fontFamily:o.fontMono,color:o.textSecondary,background:`${o.textMuted}18`,border:`1px solid ${o.textMuted}30`,borderRadius:4,padding:"1px 7px",flexShrink:0},children:["Line ",s.line]}),s.near&&i.jsxs("span",{style:{fontSize:11,fontFamily:o.fontMono,color:o.textSecondary,flexShrink:0},children:["near ",i.jsxs("span",{style:{color:o.error},children:["“",s.near,"”"]})]})]}),i.jsx("pre",{style:{margin:0,fontFamily:o.fontMono,fontSize:12,color:o.error,lineHeight:1.6,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:s.message}),a&&i.jsxs("div",{style:{fontSize:12,fontFamily:o.font,color:o.textSecondary,display:"flex",alignItems:"center",gap:6},children:[i.jsx("span",{style:{color:o.accent},children:"→"}),a]}),s.hint&&i.jsxs("div",{style:{marginTop:2,padding:"8px 12px",background:`${o.warning}12`,border:`1px solid ${o.warning}40`,borderRadius:6,display:"flex",alignItems:"flex-start",gap:8},children:[i.jsx("span",{style:{flexShrink:0,fontSize:13,lineHeight:1.5},children:"💡"}),i.jsx("span",{style:{fontSize:12,fontFamily:o.font,color:o.warning,lineHeight:1.6},children:s.hint})]}),l&&i.jsxs("button",{onClick:n,style:{alignSelf:"flex-start",marginTop:2,padding:"5px 12px",background:`${o.accent}15`,border:`1px solid ${o.accent}50`,borderRadius:6,color:o.accent,fontSize:12,fontFamily:o.font,fontWeight:500,cursor:"pointer",display:"flex",alignItems:"center",gap:6,transition:"all 0.15s"},onMouseEnter:c=>{c.currentTarget.style.background=`${o.accent}25`},onMouseLeave:c=>{c.currentTarget.style.background=`${o.accent}15`},children:[i.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:i.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 Jl({path:e,onNodeClick:t,focalNodeId:n,t:r}){return e.nodes.length===0?null:i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,alignItems:"center"},children:e.nodes.map((o,s)=>i.jsxs(ge.Fragment,{children:[i.jsx(TD,{node:o,isFocal:o.id===n,onClick:t?()=>t(o.id):void 0,t:r}),s<e.nodes.length-1&&i.jsx("span",{style:{color:r.textMuted,fontSize:10,lineHeight:1},children:"→"})]},o.id))})}function zd({title:e,paths:t,onNodeClick:n,focalNodeId:r,maxVisible:o=4,t:s}){const[a,l]=ge.useState(!1),c=a?t:t.slice(0,o),E=t.length>o;return t.length===0?null:i.jsxs("div",{style:{border:`1px solid ${s.cellBorder}`,borderRadius:10,overflow:"hidden",background:s.inputBg},children:[i.jsxs("div",{style:{padding:"8px 12px",borderBottom:`1px solid ${s.cellBorder}`,fontSize:11,fontWeight:700,color:s.textMuted,fontFamily:s.font,textTransform:"uppercase",letterSpacing:"0.04em",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[i.jsx("span",{children:e}),i.jsxs("span",{style:{fontWeight:400,fontSize:10},children:[t.length," path",t.length!==1?"s":""]})]}),i.jsxs("div",{style:{display:"grid",gap:8,padding:10},children:[c.map((d,u)=>i.jsx(Jl,{path:d,onNodeClick:n,focalNodeId:r,t:s},`path-${u}`)),E&&!a&&i.jsxs("button",{onClick:()=>l(!0),style:{background:"none",border:"none",color:s.accent,cursor:"pointer",fontSize:11,fontFamily:s.font,padding:"2px 0",textAlign:"left"},children:["Show ",t.length-o," more path",t.length-o!==1?"s":"","..."]})]})]})}function TD({node:e,isFocal:t,onClick:n,t:r}){const o=we[e.type]??"#8b949e",s=Wc[e.type]??e.type.slice(0,3).toUpperCase();return i.jsxs("button",{onClick:n,disabled:!n,style:{display:"inline-flex",alignItems:"center",gap:4,background:t?`${o}18`:r.pillBg??`${r.cellBg}`,border:`1px solid ${t?o: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:[i.jsx("span",{style:{fontSize:8,fontWeight:700,color:"#0d1117",background:o,borderRadius:3,padding:"1px 3px",flexShrink:0},children:s}),i.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]})}function SD({layerSummary:e,t}){const n=["source","transform","answer","consumption"];if(Object.values(e).reduce((a,l)=>a+l,0)===0)return null;const o={source:"#79c0ff",transform:"#ff7b72",answer:"#56d364",consumption:"#d2a8ff"},s={source:"Sources",transform:"Transform",answer:"Answer",consumption:"Consumption"};return i.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:i.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3},children:[i.jsx("span",{style:{width:8,height:8,borderRadius:2,background:o[a],display:"inline-block"}}),s[a],": ",l]},a)})})}function xe(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=xe(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var fD={value:()=>{}};function Wi(){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 bs(n)}function bs(e){this._=e}function RD(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",o=n.indexOf(".");if(o>=0&&(r=n.slice(o+1),n=n.slice(0,o)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}bs.prototype=Wi.prototype={constructor:bs,on:function(e,t){var n=this._,r=RD(e+"",n),o,s=-1,a=r.length;if(arguments.length<2){for(;++s<a;)if((o=(e=r[s]).type)&&(o=AD(n[o],e.name)))return o;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++s<a;)if(o=(e=r[s]).type)n[o]=Jd(n[o],e.name,t);else if(t==null)for(o in n)n[o]=Jd(n[o],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new bs(e)},call:function(e,t){if((o=arguments.length-2)>0)for(var n=new Array(o),r=0,o,s;r<o;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(s=this._[e],r=0,o=s.length;r<o;++r)s[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],o=0,s=r.length;o<s;++o)r[o].value.apply(t,n)}};function AD(e,t){for(var n=0,r=e.length,o;n<r;++n)if((o=e[n]).name===t)return o.value}function Jd(e,t,n){for(var r=0,o=e.length;r<o;++r)if(e[r].name===t){e[r]=fD,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var ql="http://www.w3.org/1999/xhtml";const qd={svg:"http://www.w3.org/2000/svg",xhtml:ql,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Vi(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),qd.hasOwnProperty(t)?{space:qd[t],local:e}:e}function pD(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===ql&&t.documentElement.namespaceURI===ql?t.createElement(e):t.createElementNS(n,e)}}function hD(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function eA(e){var t=Vi(e);return(t.local?hD:pD)(t)}function ID(){}function nE(e){return e==null?ID:function(){return this.querySelector(e)}}function ND(e){typeof e!="function"&&(e=nE(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var s=t[o],a=s.length,l=r[o]=new Array(a),c,E,d=0;d<a;++d)(c=s[d])&&(E=e.call(c,c.__data__,d,s))&&("__data__"in c&&(E.__data__=c.__data__),l[d]=E);return new Je(r,this._parents)}function OD(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function mD(){return[]}function tA(e){return e==null?mD:function(){return this.querySelectorAll(e)}}function CD(e){return function(){return OD(e.apply(this,arguments))}}function gD(e){typeof e=="function"?e=CD(e):e=tA(e);for(var t=this._groups,n=t.length,r=[],o=[],s=0;s<n;++s)for(var a=t[s],l=a.length,c,E=0;E<l;++E)(c=a[E])&&(r.push(e.call(c,c.__data__,E,a)),o.push(c));return new Je(r,o)}function nA(e){return function(){return this.matches(e)}}function rA(e){return function(t){return t.matches(e)}}var LD=Array.prototype.find;function _D(e){return function(){return LD.call(this.children,e)}}function xD(){return this.firstElementChild}function yD(e){return this.select(e==null?xD:_D(typeof e=="function"?e:rA(e)))}var DD=Array.prototype.filter;function MD(){return Array.from(this.children)}function PD(e){return function(){return DD.call(this.children,e)}}function bD(e){return this.selectAll(e==null?MD:PD(typeof e=="function"?e:rA(e)))}function vD(e){typeof e!="function"&&(e=nA(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var s=t[o],a=s.length,l=r[o]=[],c,E=0;E<a;++E)(c=s[E])&&e.call(c,c.__data__,E,s)&&l.push(c);return new Je(r,this._parents)}function oA(e){return new Array(e.length)}function UD(){return new Je(this._enter||this._groups.map(oA),this._parents)}function oi(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}oi.prototype={constructor:oi,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 wD(e){return function(){return e}}function BD(e,t,n,r,o,s){for(var a=0,l,c=t.length,E=s.length;a<E;++a)(l=t[a])?(l.__data__=s[a],r[a]=l):n[a]=new oi(e,s[a]);for(;a<c;++a)(l=t[a])&&(o[a]=l)}function FD(e,t,n,r,o,s,a){var l,c,E=new Map,d=t.length,u=s.length,T=new Array(d),S;for(l=0;l<d;++l)(c=t[l])&&(T[l]=S=a.call(c,c.__data__,l,t)+"",E.has(S)?o[l]=c:E.set(S,c));for(l=0;l<u;++l)S=a.call(e,s[l],l,s)+"",(c=E.get(S))?(r[l]=c,c.__data__=s[l],E.delete(S)):n[l]=new oi(e,s[l]);for(l=0;l<d;++l)(c=t[l])&&E.get(T[l])===c&&(o[l]=c)}function GD(e){return e.__data__}function HD(e,t){if(!arguments.length)return Array.from(this,GD);var n=t?FD:BD,r=this._parents,o=this._groups;typeof e!="function"&&(e=wD(e));for(var s=o.length,a=new Array(s),l=new Array(s),c=new Array(s),E=0;E<s;++E){var d=r[E],u=o[E],T=u.length,S=kD(e.call(d,d&&d.__data__,E,r)),h=S.length,A=l[E]=new Array(h),R=a[E]=new Array(h),p=c[E]=new Array(T);n(d,u,A,R,p,S,t);for(var N=0,I=0,O,m;N<h;++N)if(O=A[N]){for(N>=I&&(I=N+1);!(m=R[I])&&++I<h;);O._next=m||null}}return a=new Je(a,r),a._enter=l,a._exit=c,a}function kD(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function jD(){return new Je(this._exit||this._groups.map(oA),this._parents)}function YD(e,t,n){var r=this.enter(),o=this,s=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(o=t(o),o&&(o=o.selection())),n==null?s.remove():n(s),r&&o?r.merge(o).order():o}function WD(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,o=n.length,s=r.length,a=Math.min(o,s),l=new Array(o),c=0;c<a;++c)for(var E=n[c],d=r[c],u=E.length,T=l[c]=new Array(u),S,h=0;h<u;++h)(S=E[h]||d[h])&&(T[h]=S);for(;c<o;++c)l[c]=n[c];return new Je(l,this._parents)}function VD(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],o=r.length-1,s=r[o],a;--o>=0;)(a=r[o])&&(s&&a.compareDocumentPosition(s)^4&&s.parentNode.insertBefore(a,s),s=a);return this}function $D(e){e||(e=XD);function t(u,T){return u&&T?e(u.__data__,T.__data__):!u-!T}for(var n=this._groups,r=n.length,o=new Array(r),s=0;s<r;++s){for(var a=n[s],l=a.length,c=o[s]=new Array(l),E,d=0;d<l;++d)(E=a[d])&&(c[d]=E);c.sort(t)}return new Je(o,this._parents).order()}function XD(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function KD(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function zD(){return Array.from(this)}function JD(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],o=0,s=r.length;o<s;++o){var a=r[o];if(a)return a}return null}function qD(){let e=0;for(const t of this)++e;return e}function QD(){return!this.node()}function ZD(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var o=t[n],s=0,a=o.length,l;s<a;++s)(l=o[s])&&e.call(l,l.__data__,s,o);return this}function eM(e){return function(){this.removeAttribute(e)}}function tM(e){return function(){this.removeAttributeNS(e.space,e.local)}}function nM(e,t){return function(){this.setAttribute(e,t)}}function rM(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function oM(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function sM(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 iM(e,t){var n=Vi(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?tM:eM:typeof t=="function"?n.local?sM:oM:n.local?rM:nM)(n,t))}function sA(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function aM(e){return function(){this.style.removeProperty(e)}}function lM(e,t,n){return function(){this.style.setProperty(e,t,n)}}function cM(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function EM(e,t,n){return arguments.length>1?this.each((t==null?aM:typeof t=="function"?cM:lM)(e,t,n??"")):cr(this.node(),e)}function cr(e,t){return e.style.getPropertyValue(t)||sA(e).getComputedStyle(e,null).getPropertyValue(t)}function dM(e){return function(){delete this[e]}}function uM(e,t){return function(){this[e]=t}}function TM(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function SM(e,t){return arguments.length>1?this.each((t==null?dM:typeof t=="function"?TM:uM)(e,t)):this.node()[e]}function iA(e){return e.trim().split(/^|\s+/)}function rE(e){return e.classList||new aA(e)}function aA(e){this._node=e,this._names=iA(e.getAttribute("class")||"")}aA.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 lA(e,t){for(var n=rE(e),r=-1,o=t.length;++r<o;)n.add(t[r])}function cA(e,t){for(var n=rE(e),r=-1,o=t.length;++r<o;)n.remove(t[r])}function fM(e){return function(){lA(this,e)}}function RM(e){return function(){cA(this,e)}}function AM(e,t){return function(){(t.apply(this,arguments)?lA:cA)(this,e)}}function pM(e,t){var n=iA(e+"");if(arguments.length<2){for(var r=rE(this.node()),o=-1,s=n.length;++o<s;)if(!r.contains(n[o]))return!1;return!0}return this.each((typeof t=="function"?AM:t?fM:RM)(n,t))}function hM(){this.textContent=""}function IM(e){return function(){this.textContent=e}}function NM(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function OM(e){return arguments.length?this.each(e==null?hM:(typeof e=="function"?NM:IM)(e)):this.node().textContent}function mM(){this.innerHTML=""}function CM(e){return function(){this.innerHTML=e}}function gM(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function LM(e){return arguments.length?this.each(e==null?mM:(typeof e=="function"?gM:CM)(e)):this.node().innerHTML}function _M(){this.nextSibling&&this.parentNode.appendChild(this)}function xM(){return this.each(_M)}function yM(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function DM(){return this.each(yM)}function MM(e){var t=typeof e=="function"?e:eA(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function PM(){return null}function bM(e,t){var n=typeof e=="function"?e:eA(e),r=t==null?PM:typeof t=="function"?t:nE(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function vM(){var e=this.parentNode;e&&e.removeChild(this)}function UM(){return this.each(vM)}function wM(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function BM(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function FM(e){return this.select(e?BM:wM)}function GM(e){return arguments.length?this.property("__data__",e):this.node().__data__}function HM(e){return function(t){e.call(this,t,this.__data__)}}function kM(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,o=t.length,s;n<o;++n)s=t[n],(!e.type||s.type===e.type)&&s.name===e.name?this.removeEventListener(s.type,s.listener,s.options):t[++r]=s;++r?t.length=r:delete this.__on}}}function YM(e,t,n){return function(){var r=this.__on,o,s=HM(t);if(r){for(var a=0,l=r.length;a<l;++a)if((o=r[a]).type===e.type&&o.name===e.name){this.removeEventListener(o.type,o.listener,o.options),this.addEventListener(o.type,o.listener=s,o.options=n),o.value=t;return}}this.addEventListener(e.type,s,n),o={type:e.type,name:e.name,value:t,listener:s,options:n},r?r.push(o):this.__on=[o]}}function WM(e,t,n){var r=kM(e+""),o,s=r.length,a;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,E=l.length,d;c<E;++c)for(o=0,d=l[c];o<s;++o)if((a=r[o]).type===d.type&&a.name===d.name)return d.value}return}for(l=t?YM:jM,o=0;o<s;++o)this.each(l(r[o],t,n));return this}function EA(e,t,n){var r=sA(e),o=r.CustomEvent;typeof o=="function"?o=new o(t,n):(o=r.document.createEvent("Event"),n?(o.initEvent(t,n.bubbles,n.cancelable),o.detail=n.detail):o.initEvent(t,!1,!1)),e.dispatchEvent(o)}function VM(e,t){return function(){return EA(this,e,t)}}function $M(e,t){return function(){return EA(this,e,t.apply(this,arguments))}}function XM(e,t){return this.each((typeof t=="function"?$M:VM)(e,t))}function*KM(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],o=0,s=r.length,a;o<s;++o)(a=r[o])&&(yield a)}var dA=[null];function Je(e,t){this._groups=e,this._parents=t}function go(){return new Je([[document.documentElement]],dA)}function zM(){return this}Je.prototype=go.prototype={constructor:Je,select:ND,selectAll:gD,selectChild:yD,selectChildren:bD,filter:vD,data:HD,enter:UD,exit:jD,join:YD,merge:WD,selection:zM,order:VD,sort:$D,call:KD,nodes:zD,node:JD,size:qD,empty:QD,each:ZD,attr:iM,style:EM,property:SM,classed:pM,text:OM,html:LM,raise:xM,lower:DM,append:MM,insert:bM,remove:UM,clone:FM,datum:GM,on:WM,dispatch:XM,[Symbol.iterator]:KM};function Ke(e){return typeof e=="string"?new Je([[document.querySelector(e)]],[document.documentElement]):new Je([[e]],dA)}function JM(e){let t;for(;t=e.sourceEvent;)e=t;return e}function ot(e,t){if(e=JM(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 o=t.getBoundingClientRect();return[e.clientX-o.left-t.clientLeft,e.clientY-o.top-t.clientTop]}}return[e.pageX,e.pageY]}const qM={passive:!1},oo={capture:!0,passive:!1};function Ha(e){e.stopImmediatePropagation()}function nr(e){e.preventDefault(),e.stopImmediatePropagation()}function uA(e){var t=e.document.documentElement,n=Ke(e).on("dragstart.drag",nr,oo);"onselectstart"in t?n.on("selectstart.drag",nr,oo):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function TA(e,t){var n=e.document.documentElement,r=Ke(e).on("dragstart.drag",null);t&&(r.on("click.drag",nr,oo),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 Ss=e=>()=>e;function Ql(e,{sourceEvent:t,subject:n,target:r,identifier:o,active:s,x:a,y:l,dx:c,dy:E,dispatch:d}){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:o,enumerable:!0,configurable:!0},active:{value:s,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:E,enumerable:!0,configurable:!0},_:{value:d}})}Ql.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function QM(e){return!e.ctrlKey&&!e.button}function ZM(){return this.parentNode}function eP(e,t){return t??{x:e.x,y:e.y}}function tP(){return navigator.maxTouchPoints||"ontouchstart"in this}function SA(){var e=QM,t=ZM,n=eP,r=tP,o={},s=Wi("start","drag","end"),a=0,l,c,E,d,u=0;function T(O){O.on("mousedown.drag",S).filter(r).on("touchstart.drag",R).on("touchmove.drag",p,qM).on("touchend.drag touchcancel.drag",N).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function S(O,m){if(!(d||!e.call(this,O,m))){var C=I(this,t.call(this,O,m),O,m,"mouse");C&&(Ke(O.view).on("mousemove.drag",h,oo).on("mouseup.drag",A,oo),uA(O.view),Ha(O),E=!1,l=O.clientX,c=O.clientY,C("start",O))}}function h(O){if(nr(O),!E){var m=O.clientX-l,C=O.clientY-c;E=m*m+C*C>u}o.mouse("drag",O)}function A(O){Ke(O.view).on("mousemove.drag mouseup.drag",null),TA(O.view,E),nr(O),o.mouse("end",O)}function R(O,m){if(e.call(this,O,m)){var C=O.changedTouches,g=t.call(this,O,m),y=C.length,_,P;for(_=0;_<y;++_)(P=I(this,g,O,m,C[_].identifier,C[_]))&&(Ha(O),P("start",O,C[_]))}}function p(O){var m=O.changedTouches,C=m.length,g,y;for(g=0;g<C;++g)(y=o[m[g].identifier])&&(nr(O),y("drag",O,m[g]))}function N(O){var m=O.changedTouches,C=m.length,g,y;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),g=0;g<C;++g)(y=o[m[g].identifier])&&(Ha(O),y("end",O,m[g]))}function I(O,m,C,g,y,_){var P=s.copy(),D=ot(_||C,m),b,F,x;if((x=n.call(O,new Ql("beforestart",{sourceEvent:C,target:T,identifier:y,active:a,x:D[0],y:D[1],dx:0,dy:0,dispatch:P}),g))!=null)return b=x.x-D[0]||0,F=x.y-D[1]||0,function w(M,B,v){var L=D,U;switch(M){case"start":o[y]=w,U=a++;break;case"end":delete o[y],--a;case"drag":D=ot(v||B,m),U=a;break}P.call(M,O,new Ql(M,{sourceEvent:B,subject:x,target:T,identifier:y,active:U,x:D[0]+b,y:D[1]+F,dx:D[0]-L[0],dy:D[1]-L[1],dispatch:P}),g)}}return T.filter=function(O){return arguments.length?(e=typeof O=="function"?O:Ss(!!O),T):e},T.container=function(O){return arguments.length?(t=typeof O=="function"?O:Ss(O),T):t},T.subject=function(O){return arguments.length?(n=typeof O=="function"?O:Ss(O),T):n},T.touchable=function(O){return arguments.length?(r=typeof O=="function"?O:Ss(!!O),T):r},T.on=function(){var O=s.on.apply(s,arguments);return O===s?T:O},T.clickDistance=function(O){return arguments.length?(u=(O=+O)*O,T):Math.sqrt(u)},T}function oE(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function fA(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function Lo(){}var so=.7,si=1/so,rr="\\s*([+-]?\\d+)\\s*",io="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Ot="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",nP=/^#([0-9a-f]{3,8})$/,rP=new RegExp(`^rgb\\(${rr},${rr},${rr}\\)$`),oP=new RegExp(`^rgb\\(${Ot},${Ot},${Ot}\\)$`),sP=new RegExp(`^rgba\\(${rr},${rr},${rr},${io}\\)$`),iP=new RegExp(`^rgba\\(${Ot},${Ot},${Ot},${io}\\)$`),aP=new RegExp(`^hsl\\(${io},${Ot},${Ot}\\)$`),lP=new RegExp(`^hsla\\(${io},${Ot},${Ot},${io}\\)$`),Qd={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};oE(Lo,_n,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Zd,formatHex:Zd,formatHex8:cP,formatHsl:EP,formatRgb:eu,toString:eu});function Zd(){return this.rgb().formatHex()}function cP(){return this.rgb().formatHex8()}function EP(){return RA(this).formatHsl()}function eu(){return this.rgb().formatRgb()}function _n(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=nP.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?tu(t):n===3?new He(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?fs(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?fs(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=rP.exec(e))?new He(t[1],t[2],t[3],1):(t=oP.exec(e))?new He(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=sP.exec(e))?fs(t[1],t[2],t[3],t[4]):(t=iP.exec(e))?fs(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=aP.exec(e))?ou(t[1],t[2]/100,t[3]/100,1):(t=lP.exec(e))?ou(t[1],t[2]/100,t[3]/100,t[4]):Qd.hasOwnProperty(e)?tu(Qd[e]):e==="transparent"?new He(NaN,NaN,NaN,0):null}function tu(e){return new He(e>>16&255,e>>8&255,e&255,1)}function fs(e,t,n,r){return r<=0&&(e=t=n=NaN),new He(e,t,n,r)}function dP(e){return e instanceof Lo||(e=_n(e)),e?(e=e.rgb(),new He(e.r,e.g,e.b,e.opacity)):new He}function Zl(e,t,n,r){return arguments.length===1?dP(e):new He(e,t,n,r??1)}function He(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}oE(He,Zl,fA(Lo,{brighter(e){return e=e==null?si:Math.pow(si,e),new He(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?so:Math.pow(so,e),new He(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new He(On(this.r),On(this.g),On(this.b),ii(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:nu,formatHex:nu,formatHex8:uP,formatRgb:ru,toString:ru}));function nu(){return`#${Nn(this.r)}${Nn(this.g)}${Nn(this.b)}`}function uP(){return`#${Nn(this.r)}${Nn(this.g)}${Nn(this.b)}${Nn((isNaN(this.opacity)?1:this.opacity)*255)}`}function ru(){const e=ii(this.opacity);return`${e===1?"rgb(":"rgba("}${On(this.r)}, ${On(this.g)}, ${On(this.b)}${e===1?")":`, ${e})`}`}function ii(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function On(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Nn(e){return e=On(e),(e<16?"0":"")+e.toString(16)}function ou(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new st(e,t,n,r)}function RA(e){if(e instanceof st)return new st(e.h,e.s,e.l,e.opacity);if(e instanceof Lo||(e=_n(e)),!e)return new st;if(e instanceof st)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,o=Math.min(t,n,r),s=Math.max(t,n,r),a=NaN,l=s-o,c=(s+o)/2;return l?(t===s?a=(n-r)/l+(n<r)*6:n===s?a=(r-t)/l+2:a=(t-n)/l+4,l/=c<.5?s+o:2-s-o,a*=60):l=c>0&&c<1?0:a,new st(a,l,c,e.opacity)}function TP(e,t,n,r){return arguments.length===1?RA(e):new st(e,t,n,r??1)}function st(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}oE(st,TP,fA(Lo,{brighter(e){return e=e==null?si:Math.pow(si,e),new st(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?so:Math.pow(so,e),new st(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,o=2*n-r;return new He(ka(e>=240?e-240:e+120,o,r),ka(e,o,r),ka(e<120?e+240:e-120,o,r),this.opacity)},clamp(){return new st(su(this.h),Rs(this.s),Rs(this.l),ii(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=ii(this.opacity);return`${e===1?"hsl(":"hsla("}${su(this.h)}, ${Rs(this.s)*100}%, ${Rs(this.l)*100}%${e===1?")":`, ${e})`}`}}));function su(e){return e=(e||0)%360,e<0?e+360:e}function Rs(e){return Math.max(0,Math.min(1,e||0))}function ka(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 sE=e=>()=>e;function SP(e,t){return function(n){return e+n*t}}function fP(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 RP(e){return(e=+e)==1?AA:function(t,n){return n-t?fP(t,n,e):sE(isNaN(t)?n:t)}}function AA(e,t){var n=t-e;return n?SP(e,n):sE(isNaN(e)?t:e)}const ai=(function e(t){var n=RP(t);function r(o,s){var a=n((o=Zl(o)).r,(s=Zl(s)).r),l=n(o.g,s.g),c=n(o.b,s.b),E=AA(o.opacity,s.opacity);return function(d){return o.r=a(d),o.g=l(d),o.b=c(d),o.opacity=E(d),o+""}}return r.gamma=e,r})(1);function AP(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),o;return function(s){for(o=0;o<n;++o)r[o]=e[o]*(1-s)+t[o]*s;return r}}function pP(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function hP(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,o=new Array(r),s=new Array(n),a;for(a=0;a<r;++a)o[a]=Wr(e[a],t[a]);for(;a<n;++a)s[a]=t[a];return function(l){for(a=0;a<r;++a)s[a]=o[a](l);return s}}function IP(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function Rt(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function NP(e,t){var n={},r={},o;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(o in t)o in e?n[o]=Wr(e[o],t[o]):r[o]=t[o];return function(s){for(o in n)r[o]=n[o](s);return r}}var ec=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,ja=new RegExp(ec.source,"g");function OP(e){return function(){return e}}function mP(e){return function(t){return e(t)+""}}function pA(e,t){var n=ec.lastIndex=ja.lastIndex=0,r,o,s,a=-1,l=[],c=[];for(e=e+"",t=t+"";(r=ec.exec(e))&&(o=ja.exec(t));)(s=o.index)>n&&(s=t.slice(n,s),l[a]?l[a]+=s:l[++a]=s),(r=r[0])===(o=o[0])?l[a]?l[a]+=o:l[++a]=o:(l[++a]=null,c.push({i:a,x:Rt(r,o)})),n=ja.lastIndex;return n<t.length&&(s=t.slice(n),l[a]?l[a]+=s:l[++a]=s),l.length<2?c[0]?mP(c[0].x):OP(t):(t=c.length,function(E){for(var d=0,u;d<t;++d)l[(u=c[d]).i]=u.x(E);return l.join("")})}function Wr(e,t){var n=typeof t,r;return t==null||n==="boolean"?sE(t):(n==="number"?Rt:n==="string"?(r=_n(t))?(t=r,ai):pA:t instanceof _n?ai:t instanceof Date?IP:pP(t)?AP:Array.isArray(t)?hP:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?NP:Rt)(e,t)}var iu=180/Math.PI,tc={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function hA(e,t,n,r,o,s){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:o,translateY:s,rotate:Math.atan2(t,e)*iu,skewX:Math.atan(c)*iu,scaleX:a,scaleY:l}}var As;function CP(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?tc:hA(t.a,t.b,t.c,t.d,t.e,t.f)}function gP(e){return e==null||(As||(As=document.createElementNS("http://www.w3.org/2000/svg","g")),As.setAttribute("transform",e),!(e=As.transform.baseVal.consolidate()))?tc:(e=e.matrix,hA(e.a,e.b,e.c,e.d,e.e,e.f))}function IA(e,t,n,r){function o(E){return E.length?E.pop()+" ":""}function s(E,d,u,T,S,h){if(E!==u||d!==T){var A=S.push("translate(",null,t,null,n);h.push({i:A-4,x:Rt(E,u)},{i:A-2,x:Rt(d,T)})}else(u||T)&&S.push("translate("+u+t+T+n)}function a(E,d,u,T){E!==d?(E-d>180?d+=360:d-E>180&&(E+=360),T.push({i:u.push(o(u)+"rotate(",null,r)-2,x:Rt(E,d)})):d&&u.push(o(u)+"rotate("+d+r)}function l(E,d,u,T){E!==d?T.push({i:u.push(o(u)+"skewX(",null,r)-2,x:Rt(E,d)}):d&&u.push(o(u)+"skewX("+d+r)}function c(E,d,u,T,S,h){if(E!==u||d!==T){var A=S.push(o(S)+"scale(",null,",",null,")");h.push({i:A-4,x:Rt(E,u)},{i:A-2,x:Rt(d,T)})}else(u!==1||T!==1)&&S.push(o(S)+"scale("+u+","+T+")")}return function(E,d){var u=[],T=[];return E=e(E),d=e(d),s(E.translateX,E.translateY,d.translateX,d.translateY,u,T),a(E.rotate,d.rotate,u,T),l(E.skewX,d.skewX,u,T),c(E.scaleX,E.scaleY,d.scaleX,d.scaleY,u,T),E=d=null,function(S){for(var h=-1,A=T.length,R;++h<A;)u[(R=T[h]).i]=R.x(S);return u.join("")}}}var LP=IA(CP,"px, ","px)","deg)"),_P=IA(gP,", ",")",")"),xP=1e-12;function au(e){return((e=Math.exp(e))+1/e)/2}function yP(e){return((e=Math.exp(e))-1/e)/2}function DP(e){return((e=Math.exp(2*e))-1)/(e+1)}const vs=(function e(t,n,r){function o(s,a){var l=s[0],c=s[1],E=s[2],d=a[0],u=a[1],T=a[2],S=d-l,h=u-c,A=S*S+h*h,R,p;if(A<xP)p=Math.log(T/E)/t,R=function(g){return[l+g*S,c+g*h,E*Math.exp(t*g*p)]};else{var N=Math.sqrt(A),I=(T*T-E*E+r*A)/(2*E*n*N),O=(T*T-E*E-r*A)/(2*T*n*N),m=Math.log(Math.sqrt(I*I+1)-I),C=Math.log(Math.sqrt(O*O+1)-O);p=(C-m)/t,R=function(g){var y=g*p,_=au(m),P=E/(n*N)*(_*DP(t*y+m)-yP(m));return[l+P*S,c+P*h,E*_/au(t*y+m)]}}return R.duration=p*1e3*t/Math.SQRT2,R}return o.rho=function(s){var a=Math.max(.001,+s),l=a*a,c=l*l;return e(a,l,c)},o})(Math.SQRT2,2,4);var Er=0,Gr=0,Ur=0,NA=1e3,li,Hr,ci=0,xn=0,$i=0,ao=typeof performance=="object"&&performance.now?performance:Date,OA=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function iE(){return xn||(OA(MP),xn=ao.now()+$i)}function MP(){xn=0}function Ei(){this._call=this._time=this._next=null}Ei.prototype=mA.prototype={constructor:Ei,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?iE():+n)+(t==null?0:+t),!this._next&&Hr!==this&&(Hr?Hr._next=this:li=this,Hr=this),this._call=e,this._time=n,nc()},stop:function(){this._call&&(this._call=null,this._time=1/0,nc())}};function mA(e,t,n){var r=new Ei;return r.restart(e,t,n),r}function PP(){iE(),++Er;for(var e=li,t;e;)(t=xn-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Er}function lu(){xn=(ci=ao.now())+$i,Er=Gr=0;try{PP()}finally{Er=0,vP(),xn=0}}function bP(){var e=ao.now(),t=e-ci;t>NA&&($i-=t,ci=e)}function vP(){for(var e,t=li,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:li=n);Hr=e,nc(r)}function nc(e){if(!Er){Gr&&(Gr=clearTimeout(Gr));var t=e-xn;t>24?(e<1/0&&(Gr=setTimeout(lu,e-ao.now()-$i)),Ur&&(Ur=clearInterval(Ur))):(Ur||(ci=ao.now(),Ur=setInterval(bP,NA)),Er=1,OA(lu))}}function cu(e,t,n){var r=new Ei;return t=t==null?0:+t,r.restart(o=>{r.stop(),e(o+t)},t,n),r}var UP=Wi("start","end","cancel","interrupt"),wP=[],CA=0,Eu=1,rc=2,Us=3,du=4,oc=5,ws=6;function Xi(e,t,n,r,o,s){var a=e.__transition;if(!a)e.__transition={};else if(n in a)return;BP(e,n,{name:t,index:r,group:o,on:UP,tween:wP,time:s.time,delay:s.delay,duration:s.duration,ease:s.ease,timer:null,state:CA})}function aE(e,t){var n=Tt(e,t);if(n.state>CA)throw new Error("too late; already scheduled");return n}function gt(e,t){var n=Tt(e,t);if(n.state>Us)throw new Error("too late; already running");return n}function Tt(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function BP(e,t,n){var r=e.__transition,o;r[t]=n,n.timer=mA(s,0,n.time);function s(E){n.state=Eu,n.timer.restart(a,n.delay,n.time),n.delay<=E&&a(E-n.delay)}function a(E){var d,u,T,S;if(n.state!==Eu)return c();for(d in r)if(S=r[d],S.name===n.name){if(S.state===Us)return cu(a);S.state===du?(S.state=ws,S.timer.stop(),S.on.call("interrupt",e,e.__data__,S.index,S.group),delete r[d]):+d<t&&(S.state=ws,S.timer.stop(),S.on.call("cancel",e,e.__data__,S.index,S.group),delete r[d])}if(cu(function(){n.state===Us&&(n.state=du,n.timer.restart(l,n.delay,n.time),l(E))}),n.state=rc,n.on.call("start",e,e.__data__,n.index,n.group),n.state===rc){for(n.state=Us,o=new Array(T=n.tween.length),d=0,u=-1;d<T;++d)(S=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(o[++u]=S);o.length=u+1}}function l(E){for(var d=E<n.duration?n.ease.call(null,E/n.duration):(n.timer.restart(c),n.state=oc,1),u=-1,T=o.length;++u<T;)o[u].call(e,d);n.state===oc&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=ws,n.timer.stop(),delete r[t];for(var E in r)return;delete e.__transition}}function Bs(e,t){var n=e.__transition,r,o,s=!0,a;if(n){t=t==null?null:t+"";for(a in n){if((r=n[a]).name!==t){s=!1;continue}o=r.state>rc&&r.state<oc,r.state=ws,r.timer.stop(),r.on.call(o?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[a]}s&&delete e.__transition}}function FP(e){return this.each(function(){Bs(this,e)})}function GP(e,t){var n,r;return function(){var o=gt(this,e),s=o.tween;if(s!==n){r=n=s;for(var a=0,l=r.length;a<l;++a)if(r[a].name===t){r=r.slice(),r.splice(a,1);break}}o.tween=r}}function HP(e,t,n){var r,o;if(typeof n!="function")throw new Error;return function(){var s=gt(this,e),a=s.tween;if(a!==r){o=(r=a).slice();for(var l={name:t,value:n},c=0,E=o.length;c<E;++c)if(o[c].name===t){o[c]=l;break}c===E&&o.push(l)}s.tween=o}}function kP(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Tt(this.node(),n).tween,o=0,s=r.length,a;o<s;++o)if((a=r[o]).name===e)return a.value;return null}return this.each((t==null?GP:HP)(n,e,t))}function lE(e,t,n){var r=e._id;return e.each(function(){var o=gt(this,r);(o.value||(o.value={}))[t]=n.apply(this,arguments)}),function(o){return Tt(o,r).value[t]}}function gA(e,t){var n;return(typeof t=="number"?Rt:t instanceof _n?ai:(n=_n(t))?(t=n,ai):pA)(e,t)}function jP(e){return function(){this.removeAttribute(e)}}function YP(e){return function(){this.removeAttributeNS(e.space,e.local)}}function WP(e,t,n){var r,o=n+"",s;return function(){var a=this.getAttribute(e);return a===o?null:a===r?s:s=t(r=a,n)}}function VP(e,t,n){var r,o=n+"",s;return function(){var a=this.getAttributeNS(e.space,e.local);return a===o?null:a===r?s:s=t(r=a,n)}}function $P(e,t,n){var r,o,s;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===o?s:(o=c,s=t(r=a,l)))}}function XP(e,t,n){var r,o,s;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===o?s:(o=c,s=t(r=a,l)))}}function KP(e,t){var n=Vi(e),r=n==="transform"?_P:gA;return this.attrTween(e,typeof t=="function"?(n.local?XP:$P)(n,r,lE(this,"attr."+e,t)):t==null?(n.local?YP:jP)(n):(n.local?VP:WP)(n,r,t))}function zP(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function JP(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function qP(e,t){var n,r;function o(){var s=t.apply(this,arguments);return s!==r&&(n=(r=s)&&JP(e,s)),n}return o._value=t,o}function QP(e,t){var n,r;function o(){var s=t.apply(this,arguments);return s!==r&&(n=(r=s)&&zP(e,s)),n}return o._value=t,o}function ZP(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=Vi(e);return this.tween(n,(r.local?qP:QP)(r,t))}function eb(e,t){return function(){aE(this,e).delay=+t.apply(this,arguments)}}function tb(e,t){return t=+t,function(){aE(this,e).delay=t}}function nb(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?eb:tb)(t,e)):Tt(this.node(),t).delay}function rb(e,t){return function(){gt(this,e).duration=+t.apply(this,arguments)}}function ob(e,t){return t=+t,function(){gt(this,e).duration=t}}function sb(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?rb:ob)(t,e)):Tt(this.node(),t).duration}function ib(e,t){if(typeof t!="function")throw new Error;return function(){gt(this,e).ease=t}}function ab(e){var t=this._id;return arguments.length?this.each(ib(t,e)):Tt(this.node(),t).ease}function lb(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;gt(this,e).ease=n}}function cb(e){if(typeof e!="function")throw new Error;return this.each(lb(this._id,e))}function Eb(e){typeof e!="function"&&(e=nA(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var s=t[o],a=s.length,l=r[o]=[],c,E=0;E<a;++E)(c=s[E])&&e.call(c,c.__data__,E,s)&&l.push(c);return new Ft(r,this._parents,this._name,this._id)}function db(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,o=n.length,s=Math.min(r,o),a=new Array(r),l=0;l<s;++l)for(var c=t[l],E=n[l],d=c.length,u=a[l]=new Array(d),T,S=0;S<d;++S)(T=c[S]||E[S])&&(u[S]=T);for(;l<r;++l)a[l]=t[l];return new Ft(a,this._parents,this._name,this._id)}function ub(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 Tb(e,t,n){var r,o,s=ub(t)?aE:gt;return function(){var a=s(this,e),l=a.on;l!==r&&(o=(r=l).copy()).on(t,n),a.on=o}}function Sb(e,t){var n=this._id;return arguments.length<2?Tt(this.node(),n).on.on(e):this.each(Tb(n,e,t))}function fb(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function Rb(){return this.on("end.remove",fb(this._id))}function Ab(e){var t=this._name,n=this._id;typeof e!="function"&&(e=nE(e));for(var r=this._groups,o=r.length,s=new Array(o),a=0;a<o;++a)for(var l=r[a],c=l.length,E=s[a]=new Array(c),d,u,T=0;T<c;++T)(d=l[T])&&(u=e.call(d,d.__data__,T,l))&&("__data__"in d&&(u.__data__=d.__data__),E[T]=u,Xi(E[T],t,n,T,E,Tt(d,n)));return new Ft(s,this._parents,t,n)}function pb(e){var t=this._name,n=this._id;typeof e!="function"&&(e=tA(e));for(var r=this._groups,o=r.length,s=[],a=[],l=0;l<o;++l)for(var c=r[l],E=c.length,d,u=0;u<E;++u)if(d=c[u]){for(var T=e.call(d,d.__data__,u,c),S,h=Tt(d,n),A=0,R=T.length;A<R;++A)(S=T[A])&&Xi(S,t,n,A,T,h);s.push(T),a.push(d)}return new Ft(s,a,t,n)}var hb=go.prototype.constructor;function Ib(){return new hb(this._groups,this._parents)}function Nb(e,t){var n,r,o;return function(){var s=cr(this,e),a=(this.style.removeProperty(e),cr(this,e));return s===a?null:s===n&&a===r?o:o=t(n=s,r=a)}}function LA(e){return function(){this.style.removeProperty(e)}}function Ob(e,t,n){var r,o=n+"",s;return function(){var a=cr(this,e);return a===o?null:a===r?s:s=t(r=a,n)}}function mb(e,t,n){var r,o,s;return function(){var a=cr(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),cr(this,e))),a===c?null:a===r&&c===o?s:(o=c,s=t(r=a,l))}}function Cb(e,t){var n,r,o,s="style."+t,a="end."+s,l;return function(){var c=gt(this,e),E=c.on,d=c.value[s]==null?l||(l=LA(t)):void 0;(E!==n||o!==d)&&(r=(n=E).copy()).on(a,o=d),c.on=r}}function gb(e,t,n){var r=(e+="")=="transform"?LP:gA;return t==null?this.styleTween(e,Nb(e,r)).on("end.style."+e,LA(e)):typeof t=="function"?this.styleTween(e,mb(e,r,lE(this,"style."+e,t))).each(Cb(this._id,e)):this.styleTween(e,Ob(e,r,t),n).on("end.style."+e,null)}function Lb(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function _b(e,t,n){var r,o;function s(){var a=t.apply(this,arguments);return a!==o&&(r=(o=a)&&Lb(e,a,n)),r}return s._value=t,s}function xb(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,_b(e,t,n??""))}function yb(e){return function(){this.textContent=e}}function Db(e){return function(){var t=e(this);this.textContent=t??""}}function Mb(e){return this.tween("text",typeof e=="function"?Db(lE(this,"text",e)):yb(e==null?"":e+""))}function Pb(e){return function(t){this.textContent=e.call(this,t)}}function bb(e){var t,n;function r(){var o=e.apply(this,arguments);return o!==n&&(t=(n=o)&&Pb(o)),t}return r._value=e,r}function vb(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,bb(e))}function Ub(){for(var e=this._name,t=this._id,n=_A(),r=this._groups,o=r.length,s=0;s<o;++s)for(var a=r[s],l=a.length,c,E=0;E<l;++E)if(c=a[E]){var d=Tt(c,t);Xi(c,e,n,E,a,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new Ft(r,this._parents,e,n)}function wb(){var e,t,n=this,r=n._id,o=n.size();return new Promise(function(s,a){var l={value:a},c={value:function(){--o===0&&s()}};n.each(function(){var E=gt(this,r),d=E.on;d!==e&&(t=(e=d).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),E.on=t}),o===0&&s()})}var Bb=0;function Ft(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function _A(){return++Bb}var yt=go.prototype;Ft.prototype={constructor:Ft,select:Ab,selectAll:pb,selectChild:yt.selectChild,selectChildren:yt.selectChildren,filter:Eb,merge:db,selection:Ib,transition:Ub,call:yt.call,nodes:yt.nodes,node:yt.node,size:yt.size,empty:yt.empty,each:yt.each,on:Sb,attr:KP,attrTween:ZP,style:gb,styleTween:xb,text:Mb,textTween:vb,remove:Rb,tween:kP,delay:nb,duration:sb,ease:ab,easeVarying:cb,end:wb,[Symbol.iterator]:yt[Symbol.iterator]};function Fb(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var Gb={time:null,delay:0,duration:250,ease:Fb};function Hb(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 kb(e){var t,n;e instanceof Ft?(t=e._id,e=e._name):(t=_A(),(n=Gb).time=iE(),e=e==null?null:e+"");for(var r=this._groups,o=r.length,s=0;s<o;++s)for(var a=r[s],l=a.length,c,E=0;E<l;++E)(c=a[E])&&Xi(c,e,t,E,a,n||Hb(c,t));return new Ft(r,this._parents,e,t)}go.prototype.interrupt=FP;go.prototype.transition=kb;const ps=e=>()=>e;function jb(e,{sourceEvent:t,target:n,transform:r,dispatch:o}){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:o}})}function Pt(e,t,n){this.k=e,this.x=t,this.y=n}Pt.prototype={constructor:Pt,scale:function(e){return e===1?this:new Pt(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Pt(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 Ki=new Pt(1,0,0);xA.prototype=Pt.prototype;function xA(e){for(;!e.__zoom;)if(!(e=e.parentNode))return Ki;return e.__zoom}function Ya(e){e.stopImmediatePropagation()}function wr(e){e.preventDefault(),e.stopImmediatePropagation()}function Yb(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function Wb(){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 uu(){return this.__zoom||Ki}function Vb(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function $b(){return navigator.maxTouchPoints||"ontouchstart"in this}function Xb(e,t,n){var r=e.invertX(t[0][0])-n[0][0],o=e.invertX(t[1][0])-n[1][0],s=e.invertY(t[0][1])-n[0][1],a=e.invertY(t[1][1])-n[1][1];return e.translate(o>r?(r+o)/2:Math.min(0,r)||Math.max(0,o),a>s?(s+a)/2:Math.min(0,s)||Math.max(0,a))}function yA(){var e=Yb,t=Wb,n=Xb,r=Vb,o=$b,s=[0,1/0],a=[[-1/0,-1/0],[1/0,1/0]],l=250,c=vs,E=Wi("start","zoom","end"),d,u,T,S=500,h=150,A=0,R=10;function p(x){x.property("__zoom",uu).on("wheel.zoom",y,{passive:!1}).on("mousedown.zoom",_).on("dblclick.zoom",P).filter(o).on("touchstart.zoom",D).on("touchmove.zoom",b).on("touchend.zoom touchcancel.zoom",F).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}p.transform=function(x,w,M,B){var v=x.selection?x.selection():x;v.property("__zoom",uu),x!==v?m(x,w,M,B):v.interrupt().each(function(){C(this,arguments).event(B).start().zoom(null,typeof w=="function"?w.apply(this,arguments):w).end()})},p.scaleBy=function(x,w,M,B){p.scaleTo(x,function(){var v=this.__zoom.k,L=typeof w=="function"?w.apply(this,arguments):w;return v*L},M,B)},p.scaleTo=function(x,w,M,B){p.transform(x,function(){var v=t.apply(this,arguments),L=this.__zoom,U=M==null?O(v):typeof M=="function"?M.apply(this,arguments):M,G=L.invert(U),k=typeof w=="function"?w.apply(this,arguments):w;return n(I(N(L,k),U,G),v,a)},M,B)},p.translateBy=function(x,w,M,B){p.transform(x,function(){return n(this.__zoom.translate(typeof w=="function"?w.apply(this,arguments):w,typeof M=="function"?M.apply(this,arguments):M),t.apply(this,arguments),a)},null,B)},p.translateTo=function(x,w,M,B,v){p.transform(x,function(){var L=t.apply(this,arguments),U=this.__zoom,G=B==null?O(L):typeof B=="function"?B.apply(this,arguments):B;return n(Ki.translate(G[0],G[1]).scale(U.k).translate(typeof w=="function"?-w.apply(this,arguments):-w,typeof M=="function"?-M.apply(this,arguments):-M),L,a)},B,v)};function N(x,w){return w=Math.max(s[0],Math.min(s[1],w)),w===x.k?x:new Pt(w,x.x,x.y)}function I(x,w,M){var B=w[0]-M[0]*x.k,v=w[1]-M[1]*x.k;return B===x.x&&v===x.y?x:new Pt(x.k,B,v)}function O(x){return[(+x[0][0]+ +x[1][0])/2,(+x[0][1]+ +x[1][1])/2]}function m(x,w,M,B){x.on("start.zoom",function(){C(this,arguments).event(B).start()}).on("interrupt.zoom end.zoom",function(){C(this,arguments).event(B).end()}).tween("zoom",function(){var v=this,L=arguments,U=C(v,L).event(B),G=t.apply(v,L),k=M==null?O(G):typeof M=="function"?M.apply(v,L):M,J=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),K=v.__zoom,$=typeof w=="function"?w.apply(v,L):w,z=c(K.invert(k).concat(J/K.k),$.invert(k).concat(J/$.k));return function(q){if(q===1)q=$;else{var X=z(q),Q=J/X[2];q=new Pt(Q,k[0]-X[0]*Q,k[1]-X[1]*Q)}U.zoom(null,q)}})}function C(x,w,M){return!M&&x.__zooming||new g(x,w)}function g(x,w){this.that=x,this.args=w,this.active=0,this.sourceEvent=null,this.extent=t.apply(x,w),this.taps=0}g.prototype={event:function(x){return x&&(this.sourceEvent=x),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(x,w){return this.mouse&&x!=="mouse"&&(this.mouse[1]=w.invert(this.mouse[0])),this.touch0&&x!=="touch"&&(this.touch0[1]=w.invert(this.touch0[0])),this.touch1&&x!=="touch"&&(this.touch1[1]=w.invert(this.touch1[0])),this.that.__zoom=w,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(x){var w=Ke(this.that).datum();E.call(x,this.that,new jb(x,{sourceEvent:this.sourceEvent,target:p,transform:this.that.__zoom,dispatch:E}),w)}};function y(x,...w){if(!e.apply(this,arguments))return;var M=C(this,w).event(x),B=this.__zoom,v=Math.max(s[0],Math.min(s[1],B.k*Math.pow(2,r.apply(this,arguments)))),L=ot(x);if(M.wheel)(M.mouse[0][0]!==L[0]||M.mouse[0][1]!==L[1])&&(M.mouse[1]=B.invert(M.mouse[0]=L)),clearTimeout(M.wheel);else{if(B.k===v)return;M.mouse=[L,B.invert(L)],Bs(this),M.start()}wr(x),M.wheel=setTimeout(U,h),M.zoom("mouse",n(I(N(B,v),M.mouse[0],M.mouse[1]),M.extent,a));function U(){M.wheel=null,M.end()}}function _(x,...w){if(T||!e.apply(this,arguments))return;var M=x.currentTarget,B=C(this,w,!0).event(x),v=Ke(x.view).on("mousemove.zoom",k,!0).on("mouseup.zoom",J,!0),L=ot(x,M),U=x.clientX,G=x.clientY;uA(x.view),Ya(x),B.mouse=[L,this.__zoom.invert(L)],Bs(this),B.start();function k(K){if(wr(K),!B.moved){var $=K.clientX-U,z=K.clientY-G;B.moved=$*$+z*z>A}B.event(K).zoom("mouse",n(I(B.that.__zoom,B.mouse[0]=ot(K,M),B.mouse[1]),B.extent,a))}function J(K){v.on("mousemove.zoom mouseup.zoom",null),TA(K.view,B.moved),wr(K),B.event(K).end()}}function P(x,...w){if(e.apply(this,arguments)){var M=this.__zoom,B=ot(x.changedTouches?x.changedTouches[0]:x,this),v=M.invert(B),L=M.k*(x.shiftKey?.5:2),U=n(I(N(M,L),B,v),t.apply(this,w),a);wr(x),l>0?Ke(this).transition().duration(l).call(m,U,B,x):Ke(this).call(p.transform,U,B,x)}}function D(x,...w){if(e.apply(this,arguments)){var M=x.touches,B=M.length,v=C(this,w,x.changedTouches.length===B).event(x),L,U,G,k;for(Ya(x),U=0;U<B;++U)G=M[U],k=ot(G,this),k=[k,this.__zoom.invert(k),G.identifier],v.touch0?!v.touch1&&v.touch0[2]!==k[2]&&(v.touch1=k,v.taps=0):(v.touch0=k,L=!0,v.taps=1+!!d);d&&(d=clearTimeout(d)),L&&(v.taps<2&&(u=k[0],d=setTimeout(function(){d=null},S)),Bs(this),v.start())}}function b(x,...w){if(this.__zooming){var M=C(this,w).event(x),B=x.changedTouches,v=B.length,L,U,G,k;for(wr(x),L=0;L<v;++L)U=B[L],G=ot(U,this),M.touch0&&M.touch0[2]===U.identifier?M.touch0[0]=G:M.touch1&&M.touch1[2]===U.identifier&&(M.touch1[0]=G);if(U=M.that.__zoom,M.touch1){var J=M.touch0[0],K=M.touch0[1],$=M.touch1[0],z=M.touch1[1],q=(q=$[0]-J[0])*q+(q=$[1]-J[1])*q,X=(X=z[0]-K[0])*X+(X=z[1]-K[1])*X;U=N(U,Math.sqrt(q/X)),G=[(J[0]+$[0])/2,(J[1]+$[1])/2],k=[(K[0]+z[0])/2,(K[1]+z[1])/2]}else if(M.touch0)G=M.touch0[0],k=M.touch0[1];else return;M.zoom("touch",n(I(U,G,k),M.extent,a))}}function F(x,...w){if(this.__zooming){var M=C(this,w).event(x),B=x.changedTouches,v=B.length,L,U;for(Ya(x),T&&clearTimeout(T),T=setTimeout(function(){T=null},S),L=0;L<v;++L)U=B[L],M.touch0&&M.touch0[2]===U.identifier?delete M.touch0:M.touch1&&M.touch1[2]===U.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&&(U=ot(U,this),Math.hypot(u[0]-U[0],u[1]-U[1])<R)){var G=Ke(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return p.wheelDelta=function(x){return arguments.length?(r=typeof x=="function"?x:ps(+x),p):r},p.filter=function(x){return arguments.length?(e=typeof x=="function"?x:ps(!!x),p):e},p.touchable=function(x){return arguments.length?(o=typeof x=="function"?x:ps(!!x),p):o},p.extent=function(x){return arguments.length?(t=typeof x=="function"?x:ps([[+x[0][0],+x[0][1]],[+x[1][0],+x[1][1]]]),p):t},p.scaleExtent=function(x){return arguments.length?(s[0]=+x[0],s[1]=+x[1],p):[s[0],s[1]]},p.translateExtent=function(x){return arguments.length?(a[0][0]=+x[0][0],a[1][0]=+x[1][0],a[0][1]=+x[0][1],a[1][1]=+x[1][1],p):[[a[0][0],a[0][1]],[a[1][0],a[1][1]]]},p.constrain=function(x){return arguments.length?(n=x,p):n},p.duration=function(x){return arguments.length?(l=+x,p):l},p.interpolate=function(x){return arguments.length?(c=x,p):c},p.on=function(){var x=E.on.apply(E,arguments);return x===E?p:x},p.clickDistance=function(x){return arguments.length?(A=(x=+x)*x,p):Math.sqrt(A)},p.tapDistance=function(x){return arguments.length?(R=+x,p):R},p}const mt={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."},lo=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],DA=["Enter"," ","Escape"],MA={"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 dr;(function(e){e.Strict="strict",e.Loose="loose"})(dr||(dr={}));var mn;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(mn||(mn={}));var co;(function(e){e.Partial="partial",e.Full="full"})(co||(co={}));const PA={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var qt;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(qt||(qt={}));var ur;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(ur||(ur={}));var te;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(te||(te={}));const Tu={[te.Left]:te.Right,[te.Right]:te.Left,[te.Top]:te.Bottom,[te.Bottom]:te.Top};function bA(e){return e===null?null:e?"valid":"invalid"}const vA=e=>"id"in e&&"source"in e&&"target"in e,Kb=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),cE=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),_o=(e,t=[0,0])=>{const{width:n,height:r}=Ht(e),o=e.origin??t,s=n*o[0],a=r*o[1];return{x:e.position.x-s,y:e.position.y-a}},zb=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,o)=>{const s=typeof o=="string";let a=!t.nodeLookup&&!s?o:void 0;t.nodeLookup&&(a=s?t.nodeLookup.get(o):cE(o)?o:t.nodeLookup.get(o.id));const l=a?di(a,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return zi(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return Ji(n)},xo=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(o=>{(t.filter===void 0||t.filter(o))&&(n=zi(n,di(o)),r=!0)}),r?Ji(n):{x:0,y:0,width:0,height:0}},EE=(e,t,[n,r,o]=[0,0,1],s=!1,a=!1)=>{const l={...Do(t,[n,r,o]),width:t.width/o,height:t.height/o},c=[];for(const E of e.values()){const{measured:d,selectable:u=!0,hidden:T=!1}=E;if(a&&!u||T)continue;const S=d.width??E.width??E.initialWidth??null,h=d.height??E.height??E.initialHeight??null,A=Eo(l,Sr(E)),R=(S??0)*(h??0),p=s&&A>0;(!E.internals.handleBounds||p||A>=R||E.dragging)&&c.push(E)}return c},Jb=(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 qb(e,t){const n=new Map,r=t!=null&&t.nodes?new Set(t.nodes.map(o=>o.id)):null;return e.forEach(o=>{o.measured.width&&o.measured.height&&((t==null?void 0:t.includeHiddenNodes)||!o.hidden)&&(!r||r.has(o.id))&&n.set(o.id,o)}),n}async function Qb({nodes:e,width:t,height:n,panZoom:r,minZoom:o,maxZoom:s},a){if(e.size===0)return Promise.resolve(!0);const l=qb(e,a),c=xo(l),E=dE(c,t,n,(a==null?void 0:a.minZoom)??o,(a==null?void 0:a.maxZoom)??s,(a==null?void 0:a.padding)??.1);return await r.setViewport(E,{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 UA({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:o,onError:s}){const a=n.get(e),l=a.parentId?n.get(a.parentId):void 0,{x:c,y:E}=l?l.internals.positionAbsolute:{x:0,y:0},d=a.origin??r;let u=a.extent||o;if(a.extent==="parent"&&!a.expandParent)if(!l)s==null||s("005",mt.error005());else{const S=l.measured.width,h=l.measured.height;S&&h&&(u=[[c,E],[c+S,E+h]])}else l&&fr(a.extent)&&(u=[[a.extent[0][0]+c,a.extent[0][1]+E],[a.extent[1][0]+c,a.extent[1][1]+E]]);const T=fr(u)?yn(t,u,a.measured):t;return(a.measured.width===void 0||a.measured.height===void 0)&&(s==null||s("015",mt.error015())),{position:{x:T.x-c+(a.measured.width??0)*d[0],y:T.y-E+(a.measured.height??0)*d[1]},positionAbsolute:T}}async function Zb({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:o}){const s=new Set(e.map(T=>T.id)),a=[];for(const T of n){if(T.deletable===!1)continue;const S=s.has(T.id),h=!S&&T.parentId&&a.find(A=>A.id===T.parentId);(S||h)&&a.push(T)}const l=new Set(t.map(T=>T.id)),c=r.filter(T=>T.deletable!==!1),d=Jb(a,c);for(const T of c)l.has(T.id)&&!d.find(h=>h.id===T.id)&&d.push(T);if(!o)return{edges:d,nodes:a};const u=await o({nodes:a,edges:d});return typeof u=="boolean"?u?{edges:d,nodes:a}:{edges:[],nodes:[]}:u}const Tr=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),yn=(e={x:0,y:0},t,n)=>({x:Tr(e.x,t[0][0],t[1][0]-((n==null?void 0:n.width)??0)),y:Tr(e.y,t[0][1],t[1][1]-((n==null?void 0:n.height)??0))});function wA(e,t,n){const{width:r,height:o}=Ht(n),{x:s,y:a}=n.internals.positionAbsolute;return yn(e,[[s,a],[s+r,a+o]],t)}const Su=(e,t,n)=>e<t?Tr(Math.abs(e-t),1,t)/t:e>n?-Tr(Math.abs(e-n),1,t)/t:0,BA=(e,t,n=15,r=40)=>{const o=Su(e.x,r,t.width-r)*n,s=Su(e.y,r,t.height-r)*n;return[o,s]},zi=(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)}),sc=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),Ji=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),Sr=(e,t=[0,0])=>{var o,s;const{x:n,y:r}=cE(e)?e.internals.positionAbsolute:_o(e,t);return{x:n,y:r,width:((o=e.measured)==null?void 0:o.width)??e.width??e.initialWidth??0,height:((s=e.measured)==null?void 0:s.height)??e.height??e.initialHeight??0}},di=(e,t=[0,0])=>{var o,s;const{x:n,y:r}=cE(e)?e.internals.positionAbsolute:_o(e,t);return{x:n,y:r,x2:n+(((o=e.measured)==null?void 0:o.width)??e.width??e.initialWidth??0),y2:r+(((s=e.measured)==null?void 0:s.height)??e.height??e.initialHeight??0)}},FA=(e,t)=>Ji(zi(sc(e),sc(t))),Eo=(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)},fu=e=>it(e.width)&&it(e.height)&&it(e.x)&&it(e.y),it=e=>!isNaN(e)&&isFinite(e),e1=(e,t)=>{},yo=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),Do=({x:e,y:t},[n,r,o],s=!1,a=[1,1])=>{const l={x:(e-n)/o,y:(t-r)/o};return s?yo(l,a):l},ui=({x:e,y:t},[n,r,o])=>({x:e*o+n,y:t*o+r});function Vn(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 t1(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=Vn(e,n),o=Vn(e,t);return{top:r,right:o,bottom:r,left:o,x:o*2,y:r*2}}if(typeof e=="object"){const r=Vn(e.top??e.y??0,n),o=Vn(e.bottom??e.y??0,n),s=Vn(e.left??e.x??0,t),a=Vn(e.right??e.x??0,t);return{top:r,right:a,bottom:o,left:s,x:s+a,y:r+o}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function n1(e,t,n,r,o,s){const{x:a,y:l}=ui(e,[t,n,r]),{x:c,y:E}=ui({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=o-c,u=s-E;return{left:Math.floor(a),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(u)}}const dE=(e,t,n,r,o,s)=>{const a=t1(s,t,n),l=(t-a.x)/e.width,c=(n-a.y)/e.height,E=Math.min(l,c),d=Tr(E,r,o),u=e.x+e.width/2,T=e.y+e.height/2,S=t/2-u*d,h=n/2-T*d,A=n1(e,S,h,d,t,n),R={left:Math.min(A.left-a.left,0),top:Math.min(A.top-a.top,0),right:Math.min(A.right-a.right,0),bottom:Math.min(A.bottom-a.bottom,0)};return{x:S-R.left+R.right,y:h-R.top+R.bottom,zoom:d}},uo=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0};function fr(e){return e!=null&&e!=="parent"}function Ht(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 GA(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 HA(e,t={width:0,height:0},n,r,o){const s={...e},a=r.get(n);if(a){const l=a.origin||o;s.x+=a.internals.positionAbsolute.x-(t.width??0)*l[0],s.y+=a.internals.positionAbsolute.y-(t.height??0)*l[1]}return s}function Ru(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function r1(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}function o1(e){return{...MA,...e||{}}}function Vr(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:o}){const{x:s,y:a}=at(e),l=Do({x:s-((o==null?void 0:o.left)??0),y:a-((o==null?void 0:o.top)??0)},r),{x:c,y:E}=n?yo(l,t):l;return{xSnapped:c,ySnapped:E,...l}}const uE=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)},s1=["INPUT","SELECT","TEXTAREA"];function jA(e){var r,o;const t=((o=(r=e.composedPath)==null?void 0:r.call(e))==null?void 0:o[0])||e.target;return(t==null?void 0:t.nodeType)!==1?!1:s1.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const YA=e=>"clientX"in e,at=(e,t)=>{var s,a;const n=YA(e),r=n?e.clientX:(s=e.touches)==null?void 0:s[0].clientX,o=n?e.clientY:(a=e.touches)==null?void 0:a[0].clientY;return{x:r-((t==null?void 0:t.left)??0),y:o-((t==null?void 0:t.top)??0)}},Au=(e,t,n,r,o)=>{const s=t.querySelectorAll(`.${e}`);return!s||!s.length?null:Array.from(s).map(a=>{const l=a.getBoundingClientRect();return{id:a.getAttribute("data-handleid"),type:e,nodeId:o,position:a.getAttribute("data-handlepos"),x:(l.left-n.left)/r,y:(l.top-n.top)/r,...uE(a)}})};function WA({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:o,sourceControlY:s,targetControlX:a,targetControlY:l}){const c=e*.125+o*.375+a*.375+n*.125,E=t*.125+s*.375+l*.375+r*.125,d=Math.abs(c-e),u=Math.abs(E-t);return[c,E,d,u]}function hs(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function pu({pos:e,x1:t,y1:n,x2:r,y2:o,c:s}){switch(e){case te.Left:return[t-hs(t-r,s),n];case te.Right:return[t+hs(r-t,s),n];case te.Top:return[t,n-hs(n-o,s)];case te.Bottom:return[t,n+hs(o-n,s)]}}function VA({sourceX:e,sourceY:t,sourcePosition:n=te.Bottom,targetX:r,targetY:o,targetPosition:s=te.Top,curvature:a=.25}){const[l,c]=pu({pos:n,x1:e,y1:t,x2:r,y2:o,c:a}),[E,d]=pu({pos:s,x1:r,y1:o,x2:e,y2:t,c:a}),[u,T,S,h]=WA({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:l,sourceControlY:c,targetControlX:E,targetControlY:d});return[`M${e},${t} C${l},${c} ${E},${d} ${r},${o}`,u,T,S,h]}function $A({sourceX:e,sourceY:t,targetX:n,targetY:r}){const o=Math.abs(n-e)/2,s=n<e?n+o:n-o,a=Math.abs(r-t)/2,l=r<t?r+a:r-a;return[s,l,o,a]}function i1({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:o=!1,zIndexMode:s="basic"}){if(s==="manual")return r;const a=o&&n?r+1e3:r,l=Math.max(e.parentId||o&&e.selected?e.internals.z:0,t.parentId||o&&t.selected?t.internals.z:0);return a+l}function a1({sourceNode:e,targetNode:t,width:n,height:r,transform:o}){const s=zi(di(e),di(t));s.x===s.x2&&(s.x2+=1),s.y===s.y2&&(s.y2+=1);const a={x:-o[0]/o[2],y:-o[1]/o[2],width:n/o[2],height:r/o[2]};return Eo(a,Ji(s))>0}const l1=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,c1=(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)),E1=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||l1;let o;return vA(e)?o={...e}:o={...e,id:r(e)},c1(o,t)?t:(o.sourceHandle===null&&delete o.sourceHandle,o.targetHandle===null&&delete o.targetHandle,t.concat(o))};function XA({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[o,s,a,l]=$A({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,o,s,a,l]}const hu={[te.Left]:{x:-1,y:0},[te.Right]:{x:1,y:0},[te.Top]:{x:0,y:-1},[te.Bottom]:{x:0,y:1}},d1=({source:e,sourcePosition:t=te.Bottom,target:n})=>t===te.Left||t===te.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},Iu=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function u1({source:e,sourcePosition:t=te.Bottom,target:n,targetPosition:r=te.Top,center:o,offset:s,stepPosition:a}){const l=hu[t],c=hu[r],E={x:e.x+l.x*s,y:e.y+l.y*s},d={x:n.x+c.x*s,y:n.y+c.y*s},u=d1({source:E,sourcePosition:t,target:d}),T=u.x!==0?"x":"y",S=u[T];let h=[],A,R;const p={x:0,y:0},N={x:0,y:0},[,,I,O]=$A({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[T]*c[T]===-1){T==="x"?(A=o.x??E.x+(d.x-E.x)*a,R=o.y??(E.y+d.y)/2):(A=o.x??(E.x+d.x)/2,R=o.y??E.y+(d.y-E.y)*a);const C=[{x:A,y:E.y},{x:A,y:d.y}],g=[{x:E.x,y:R},{x:d.x,y:R}];l[T]===S?h=T==="x"?C:g:h=T==="x"?g:C}else{const C=[{x:E.x,y:d.y}],g=[{x:d.x,y:E.y}];if(T==="x"?h=l.x===S?g:C:h=l.y===S?C:g,t===r){const b=Math.abs(e[T]-n[T]);if(b<=s){const F=Math.min(s-1,s-b);l[T]===S?p[T]=(E[T]>e[T]?-1:1)*F:N[T]=(d[T]>n[T]?-1:1)*F}}if(t!==r){const b=T==="x"?"y":"x",F=l[T]===c[b],x=E[b]>d[b],w=E[b]<d[b];(l[T]===1&&(!F&&x||F&&w)||l[T]!==1&&(!F&&w||F&&x))&&(h=T==="x"?C:g)}const y={x:E.x+p.x,y:E.y+p.y},_={x:d.x+N.x,y:d.y+N.y},P=Math.max(Math.abs(y.x-h[0].x),Math.abs(_.x-h[0].x)),D=Math.max(Math.abs(y.y-h[0].y),Math.abs(_.y-h[0].y));P>=D?(A=(y.x+_.x)/2,R=h[0].y):(A=h[0].x,R=(y.y+_.y)/2)}return[[e,{x:E.x+p.x,y:E.y+p.y},...h,{x:d.x+N.x,y:d.y+N.y},n],A,R,I,O]}function T1(e,t,n,r){const o=Math.min(Iu(e,t)/2,Iu(t,n)/2,r),{x:s,y:a}=t;if(e.x===s&&s===n.x||e.y===a&&a===n.y)return`L${s} ${a}`;if(e.y===a){const E=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${s+o*E},${a}Q ${s},${a} ${s},${a+o*d}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${s},${a+o*c}Q ${s},${a} ${s+o*l},${a}`}function ic({sourceX:e,sourceY:t,sourcePosition:n=te.Bottom,targetX:r,targetY:o,targetPosition:s=te.Top,borderRadius:a=5,centerX:l,centerY:c,offset:E=20,stepPosition:d=.5}){const[u,T,S,h,A]=u1({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:o},targetPosition:s,center:{x:l,y:c},offset:E,stepPosition:d});return[u.reduce((p,N,I)=>{let O="";return I>0&&I<u.length-1?O=T1(u[I-1],N,u[I+1],a):O=`${I===0?"M":"L"}${N.x} ${N.y}`,p+=O,p},""),T,S,h,A]}function Nu(e){var t;return e&&!!(e.internals.handleBounds||(t=e.handles)!=null&&t.length)&&!!(e.measured.width||e.width||e.initialWidth)}function S1(e){var u;const{sourceNode:t,targetNode:n}=e;if(!Nu(t)||!Nu(n))return null;const r=t.internals.handleBounds||Ou(t.handles),o=n.internals.handleBounds||Ou(n.handles),s=mu((r==null?void 0:r.source)??[],e.sourceHandle),a=mu(e.connectionMode===dr.Strict?(o==null?void 0:o.target)??[]:((o==null?void 0:o.target)??[]).concat((o==null?void 0:o.source)??[]),e.targetHandle);if(!s||!a)return(u=e.onError)==null||u.call(e,"008",mt.error008(s?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=(s==null?void 0:s.position)||te.Bottom,c=(a==null?void 0:a.position)||te.Top,E=Dn(t,s,l),d=Dn(n,a,c);return{sourceX:E.x,sourceY:E.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function Ou(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 Dn(e,t,n=te.Left,r=!1){const o=((t==null?void 0:t.x)??0)+e.internals.positionAbsolute.x,s=((t==null?void 0:t.y)??0)+e.internals.positionAbsolute.y,{width:a,height:l}=t??Ht(e);if(r)return{x:o+a/2,y:s+l/2};switch((t==null?void 0:t.position)??n){case te.Top:return{x:o+a/2,y:s};case te.Right:return{x:o+a,y:s+l/2};case te.Bottom:return{x:o+a/2,y:s+l};case te.Left:return{x:o,y:s+l/2}}}function mu(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function ac(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function f1(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:o}){const s=new Set;return e.reduce((a,l)=>([l.markerStart||r,l.markerEnd||o].forEach(c=>{if(c&&typeof c=="object"){const E=ac(c,t);s.has(E)||(a.push({id:E,color:c.color||n,...c}),s.add(E))}}),a),[]).sort((a,l)=>a.id.localeCompare(l.id))}const KA=1e3,R1=10,TE={nodeOrigin:[0,0],nodeExtent:lo,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},A1={...TE,checkEquality:!0};function SE(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function p1(e,t,n){const r=SE(TE,n);for(const o of e.values())if(o.parentId)RE(o,e,t,r);else{const s=_o(o,r.nodeOrigin),a=fr(o.extent)?o.extent:r.nodeExtent,l=yn(s,a,Ht(o));o.internals.positionAbsolute=l}}function h1(e,t){if(!e.handles)return e.measured?t==null?void 0:t.internals.handleBounds:void 0;const n=[],r=[];for(const o of e.handles){const s={id:o.id,width:o.width??1,height:o.height??1,nodeId:e.id,x:o.x,y:o.y,position:o.position,type:o.type};o.type==="source"?n.push(s):o.type==="target"&&r.push(s)}return{source:n,target:r}}function fE(e){return e==="manual"}function lc(e,t,n,r={}){var E,d;const o=SE(A1,r),s={i:0},a=new Map(t),l=o!=null&&o.elevateNodesOnSelect&&!fE(o.zIndexMode)?KA:0;let c=e.length>0;t.clear(),n.clear();for(const u of e){let T=a.get(u.id);if(o.checkEquality&&u===(T==null?void 0:T.internals.userNode))t.set(u.id,T);else{const S=_o(u,o.nodeOrigin),h=fr(u.extent)?u.extent:o.nodeExtent,A=yn(S,h,Ht(u));T={...o.defaults,...u,measured:{width:(E=u.measured)==null?void 0:E.width,height:(d=u.measured)==null?void 0:d.height},internals:{positionAbsolute:A,handleBounds:h1(u,T),z:zA(u,l,o.zIndexMode),userNode:u}},t.set(u.id,T)}(T.measured===void 0||T.measured.width===void 0||T.measured.height===void 0)&&!T.hidden&&(c=!1),u.parentId&&RE(T,t,n,r,s)}return c}function I1(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 RE(e,t,n,r,o){const{elevateNodesOnSelect:s,nodeOrigin:a,nodeExtent:l,zIndexMode:c}=SE(TE,r),E=e.parentId,d=t.get(E);if(!d){console.warn(`Parent node ${E} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}I1(e,n),o&&!d.parentId&&d.internals.rootParentIndex===void 0&&c==="auto"&&(d.internals.rootParentIndex=++o.i,d.internals.z=d.internals.z+o.i*R1),o&&d.internals.rootParentIndex!==void 0&&(o.i=d.internals.rootParentIndex);const u=s&&!fE(c)?KA:0,{x:T,y:S,z:h}=N1(e,d,a,l,u,c),{positionAbsolute:A}=e.internals,R=T!==A.x||S!==A.y;(R||h!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:R?{x:T,y:S}:A,z:h}})}function zA(e,t,n){const r=it(e.zIndex)?e.zIndex:0;return fE(n)?r:r+(e.selected?t:0)}function N1(e,t,n,r,o,s){const{x:a,y:l}=t.internals.positionAbsolute,c=Ht(e),E=_o(e,n),d=fr(e.extent)?yn(E,e.extent,c):E;let u=yn({x:a+d.x,y:l+d.y},r,c);e.extent==="parent"&&(u=wA(u,c,t));const T=zA(e,o,s),S=t.internals.z??0;return{x:u.x,y:u.y,z:S>=T?S+1:T}}function AE(e,t,n,r=[0,0]){var a;const o=[],s=new Map;for(const l of e){const c=t.get(l.parentId);if(!c)continue;const E=((a=s.get(l.parentId))==null?void 0:a.expandedRect)??Sr(c),d=FA(E,l.rect);s.set(l.parentId,{expandedRect:d,parent:c})}return s.size>0&&s.forEach(({expandedRect:l,parent:c},E)=>{var I;const d=c.internals.positionAbsolute,u=Ht(c),T=c.origin??r,S=l.x<d.x?Math.round(Math.abs(d.x-l.x)):0,h=l.y<d.y?Math.round(Math.abs(d.y-l.y)):0,A=Math.max(u.width,Math.round(l.width)),R=Math.max(u.height,Math.round(l.height)),p=(A-u.width)*T[0],N=(R-u.height)*T[1];(S>0||h>0||p||N)&&(o.push({id:E,type:"position",position:{x:c.position.x-S+p,y:c.position.y-h+N}}),(I=n.get(E))==null||I.forEach(O=>{e.some(m=>m.id===O.id)||o.push({id:O.id,type:"position",position:{x:O.position.x+S,y:O.position.y+h}})})),(u.width<l.width||u.height<l.height||S||h)&&o.push({id:E,type:"dimensions",setAttributes:!0,dimensions:{width:A+(S?T[0]*S-p:0),height:R+(h?T[1]*h-N:0)}})}),o}function O1(e,t,n,r,o,s,a){const l=r==null?void 0:r.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const E=[],d=window.getComputedStyle(l),{m22:u}=new window.DOMMatrixReadOnly(d.transform),T=[];for(const S of e.values()){const h=t.get(S.id);if(!h)continue;if(h.hidden){t.set(h.id,{...h,internals:{...h.internals,handleBounds:void 0}}),c=!0;continue}const A=uE(S.nodeElement),R=h.measured.width!==A.width||h.measured.height!==A.height;if(!!(A.width&&A.height&&(R||!h.internals.handleBounds||S.force))){const N=S.nodeElement.getBoundingClientRect(),I=fr(h.extent)?h.extent:s;let{positionAbsolute:O}=h.internals;h.parentId&&h.extent==="parent"?O=wA(O,A,t.get(h.parentId)):I&&(O=yn(O,I,A));const m={...h,measured:A,internals:{...h.internals,positionAbsolute:O,handleBounds:{source:Au("source",S.nodeElement,N,u,h.id),target:Au("target",S.nodeElement,N,u,h.id)}}};t.set(h.id,m),h.parentId&&RE(m,t,n,{nodeOrigin:o,zIndexMode:a}),c=!0,R&&(E.push({id:h.id,type:"dimensions",dimensions:A}),h.expandParent&&h.parentId&&T.push({id:h.id,parentId:h.parentId,rect:Sr(m,o)}))}}if(T.length>0){const S=AE(T,t,n,o);E.push(...S)}return{changes:E,updatedInternals:c}}async function m1({delta:e,panZoom:t,transform:n,translateExtent:r,width:o,height:s}){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],[o,s]],r),l=!!a&&(a.x!==n[0]||a.y!==n[1]||a.k!==n[2]);return Promise.resolve(l)}function Cu(e,t,n,r,o,s){let a=o;const l=r.get(a)||new Map;r.set(a,l.set(n,t)),a=`${o}-${e}`;const c=r.get(a)||new Map;if(r.set(a,c.set(n,t)),s){a=`${o}-${e}-${s}`;const E=r.get(a)||new Map;r.set(a,E.set(n,t))}}function JA(e,t,n){e.clear(),t.clear();for(const r of n){const{source:o,target:s,sourceHandle:a=null,targetHandle:l=null}=r,c={edgeId:r.id,source:o,target:s,sourceHandle:a,targetHandle:l},E=`${o}-${a}--${s}-${l}`,d=`${s}-${l}--${o}-${a}`;Cu("source",c,d,e,o,a),Cu("target",c,E,e,s,l),t.set(r.id,r)}}function qA(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:qA(n,t):!1}function gu(e,t,n){var o;let r=e;do{if((o=r==null?void 0:r.matches)!=null&&o.call(r,t))return!0;if(r===n)return!1;r=r==null?void 0:r.parentElement}while(r);return!1}function C1(e,t,n,r){const o=new Map;for(const[s,a]of e)if((a.selected||a.id===r)&&(!a.parentId||!qA(a,e))&&(a.draggable||t&&typeof a.draggable>"u")){const l=e.get(s);l&&o.set(s,{id:s,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 o}function Wa({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){var a,l,c;const o=[];for(const[E,d]of t){const u=(a=n.get(E))==null?void 0:a.internals.userNode;u&&o.push({...u,position:d.position,dragging:r})}if(!e)return[o[0],o];const s=(l=n.get(e))==null?void 0:l.internals.userNode;return[s?{...s,position:((c=t.get(e))==null?void 0:c.position)||s.position,dragging:r}:o[0],o]}function g1({dragItems:e,snapGrid:t,x:n,y:r}){const o=e.values().next().value;if(!o)return null;const s={x:n-o.distance.x,y:r-o.distance.y},a=yo(s,t);return{x:a.x-s.x,y:a.y-s.y}}function L1({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:o}){let s={x:null,y:null},a=0,l=new Map,c=!1,E={x:0,y:0},d=null,u=!1,T=null,S=!1,h=!1,A=null;function R({noDragClassName:N,handleSelector:I,domNode:O,isSelectable:m,nodeId:C,nodeClickDistance:g=0}){T=Ke(O);function y({x:b,y:F}){const{nodeLookup:x,nodeExtent:w,snapGrid:M,snapToGrid:B,nodeOrigin:v,onNodeDrag:L,onSelectionDrag:U,onError:G,updateNodePositions:k}=t();s={x:b,y:F};let J=!1;const K=l.size>1,$=K&&w?sc(xo(l)):null,z=K&&B?g1({dragItems:l,snapGrid:M,x:b,y:F}):null;for(const[q,X]of l){if(!x.has(q))continue;let Q={x:b-X.distance.x,y:F-X.distance.y};B&&(Q=z?{x:Math.round(Q.x+z.x),y:Math.round(Q.y+z.y)}:yo(Q,M));let ae=null;if(K&&w&&!X.extent&&$){const{positionAbsolute:Y}=X.internals,se=Y.x-$.x+w[0][0],de=Y.x+X.measured.width-$.x2+w[1][0],ue=Y.y-$.y+w[0][1],me=Y.y+X.measured.height-$.y2+w[1][1];ae=[[se,ue],[de,me]]}const{position:ne,positionAbsolute:re}=UA({nodeId:q,nextPosition:Q,nodeLookup:x,nodeExtent:ae||w,nodeOrigin:v,onError:G});J=J||X.position.x!==ne.x||X.position.y!==ne.y,X.position=ne,X.internals.positionAbsolute=re}if(h=h||J,!!J&&(k(l,!0),A&&(r||L||!C&&U))){const[q,X]=Wa({nodeId:C,dragItems:l,nodeLookup:x});r==null||r(A,l,q,X),L==null||L(A,q,X),C||U==null||U(A,X)}}async function _(){if(!d)return;const{transform:b,panBy:F,autoPanSpeed:x,autoPanOnNodeDrag:w}=t();if(!w){c=!1,cancelAnimationFrame(a);return}const[M,B]=BA(E,d,x);(M!==0||B!==0)&&(s.x=(s.x??0)-M/b[2],s.y=(s.y??0)-B/b[2],await F({x:M,y:B})&&y(s)),a=requestAnimationFrame(_)}function P(b){var K;const{nodeLookup:F,multiSelectionActive:x,nodesDraggable:w,transform:M,snapGrid:B,snapToGrid:v,selectNodesOnDrag:L,onNodeDragStart:U,onSelectionDragStart:G,unselectNodesAndEdges:k}=t();u=!0,(!L||!m)&&!x&&C&&((K=F.get(C))!=null&&K.selected||k()),m&&L&&C&&(e==null||e(C));const J=Vr(b.sourceEvent,{transform:M,snapGrid:B,snapToGrid:v,containerBounds:d});if(s=J,l=C1(F,w,J,C),l.size>0&&(n||U||!C&&G)){const[$,z]=Wa({nodeId:C,dragItems:l,nodeLookup:F});n==null||n(b.sourceEvent,l,$,z),U==null||U(b.sourceEvent,$,z),C||G==null||G(b.sourceEvent,z)}}const D=SA().clickDistance(g).on("start",b=>{const{domNode:F,nodeDragThreshold:x,transform:w,snapGrid:M,snapToGrid:B}=t();d=(F==null?void 0:F.getBoundingClientRect())||null,S=!1,h=!1,A=b.sourceEvent,x===0&&P(b),s=Vr(b.sourceEvent,{transform:w,snapGrid:M,snapToGrid:B,containerBounds:d}),E=at(b.sourceEvent,d)}).on("drag",b=>{const{autoPanOnNodeDrag:F,transform:x,snapGrid:w,snapToGrid:M,nodeDragThreshold:B,nodeLookup:v}=t(),L=Vr(b.sourceEvent,{transform:x,snapGrid:w,snapToGrid:M,containerBounds:d});if(A=b.sourceEvent,(b.sourceEvent.type==="touchmove"&&b.sourceEvent.touches.length>1||C&&!v.has(C))&&(S=!0),!S){if(!c&&F&&u&&(c=!0,_()),!u){const U=at(b.sourceEvent,d),G=U.x-E.x,k=U.y-E.y;Math.sqrt(G*G+k*k)>B&&P(b)}(s.x!==L.xSnapped||s.y!==L.ySnapped)&&l&&u&&(E=at(b.sourceEvent,d),y(L))}}).on("end",b=>{if(!(!u||S)&&(c=!1,u=!1,cancelAnimationFrame(a),l.size>0)){const{nodeLookup:F,updateNodePositions:x,onNodeDragStop:w,onSelectionDragStop:M}=t();if(h&&(x(l,!1),h=!1),o||w||!C&&M){const[B,v]=Wa({nodeId:C,dragItems:l,nodeLookup:F,dragging:!1});o==null||o(b.sourceEvent,l,B,v),w==null||w(b.sourceEvent,B,v),C||M==null||M(b.sourceEvent,v)}}}).filter(b=>{const F=b.target;return!b.button&&(!N||!gu(F,`.${N}`,O))&&(!I||gu(F,I,O))});T.call(D)}function p(){T==null||T.on(".drag",null)}return{update:R,destroy:p}}function _1(e,t,n){const r=[],o={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const s of t.values())Eo(o,Sr(s))>0&&r.push(s);return r}const x1=250;function y1(e,t,n,r){var l,c;let o=[],s=1/0;const a=_1(e,n,t+x1);for(const E of a){const d=[...((l=E.internals.handleBounds)==null?void 0:l.source)??[],...((c=E.internals.handleBounds)==null?void 0:c.target)??[]];for(const u of d){if(r.nodeId===u.nodeId&&r.type===u.type&&r.id===u.id)continue;const{x:T,y:S}=Dn(E,u,u.position,!0),h=Math.sqrt(Math.pow(T-e.x,2)+Math.pow(S-e.y,2));h>t||(h<s?(o=[{...u,x:T,y:S}],s=h):h===s&&o.push({...u,x:T,y:S}))}}if(!o.length)return null;if(o.length>1){const E=r.type==="source"?"target":"source";return o.find(d=>d.type===E)??o[0]}return o[0]}function QA(e,t,n,r,o,s=!1){var E,d,u;const a=r.get(e);if(!a)return null;const l=o==="strict"?(E=a.internals.handleBounds)==null?void 0:E[t]:[...((d=a.internals.handleBounds)==null?void 0:d.source)??[],...((u=a.internals.handleBounds)==null?void 0:u.target)??[]],c=(n?l==null?void 0:l.find(T=>T.id===n):l==null?void 0:l[0])??null;return c&&s?{...c,...Dn(a,c,c.position,!0)}:c}function ZA(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function D1(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const ep=()=>!0;function M1(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:o,edgeUpdaterType:s,isTarget:a,domNode:l,nodeLookup:c,lib:E,autoPanOnConnect:d,flowId:u,panBy:T,cancelConnection:S,onConnectStart:h,onConnect:A,onConnectEnd:R,isValidConnection:p=ep,onReconnectEnd:N,updateConnection:I,getTransform:O,getFromHandle:m,autoPanSpeed:C,dragThreshold:g=1,handleDomNode:y}){const _=kA(e.target);let P=0,D;const{x:b,y:F}=at(e),x=ZA(s,y),w=l==null?void 0:l.getBoundingClientRect();let M=!1;if(!w||!x)return;const B=QA(o,x,r,c,t);if(!B)return;let v=at(e,w),L=!1,U=null,G=!1,k=null;function J(){if(!d||!w)return;const[ne,re]=BA(v,w,C);T({x:ne,y:re}),P=requestAnimationFrame(J)}const K={...B,nodeId:o,type:x,position:B.position},$=c.get(o);let q={inProgress:!0,isValid:null,from:Dn($,K,te.Left,!0),fromHandle:K,fromPosition:K.position,fromNode:$,to:v,toHandle:null,toPosition:Tu[K.position],toNode:null,pointer:v};function X(){M=!0,I(q),h==null||h(e,{nodeId:o,handleId:r,handleType:x})}g===0&&X();function Q(ne){if(!M){const{x:me,y:je}=at(ne),ve=me-b,St=je-F;if(!(ve*ve+St*St>g*g))return;X()}if(!m()||!K){ae(ne);return}const re=O();v=at(ne,w),D=y1(Do(v,re,!1,[1,1]),n,c,K),L||(J(),L=!0);const Y=tp(ne,{handle:D,connectionMode:t,fromNodeId:o,fromHandleId:r,fromType:a?"target":"source",isValidConnection:p,doc:_,lib:E,flowId:u,nodeLookup:c});k=Y.handleDomNode,U=Y.connection,G=D1(!!D,Y.isValid);const se=c.get(o),de=se?Dn(se,K,te.Left,!0):q.from,ue={...q,from:de,isValid:G,to:Y.toHandle&&G?ui({x:Y.toHandle.x,y:Y.toHandle.y},re):v,toHandle:Y.toHandle,toPosition:G&&Y.toHandle?Y.toHandle.position:Tu[K.position],toNode:Y.toHandle?c.get(Y.toHandle.nodeId):null,pointer:v};I(ue),q=ue}function ae(ne){if(!("touches"in ne&&ne.touches.length>0)){if(M){(D||k)&&U&&G&&(A==null||A(U));const{inProgress:re,...Y}=q,se={...Y,toPosition:q.toHandle?q.toPosition:null};R==null||R(ne,se),s&&(N==null||N(ne,se))}S(),cancelAnimationFrame(P),L=!1,G=!1,U=null,k=null,_.removeEventListener("mousemove",Q),_.removeEventListener("mouseup",ae),_.removeEventListener("touchmove",Q),_.removeEventListener("touchend",ae)}}_.addEventListener("mousemove",Q),_.addEventListener("mouseup",ae),_.addEventListener("touchmove",Q),_.addEventListener("touchend",ae)}function tp(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:o,fromType:s,doc:a,lib:l,flowId:c,isValidConnection:E=ep,nodeLookup:d}){const u=s==="target",T=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:S,y:h}=at(e),A=a.elementFromPoint(S,h),R=A!=null&&A.classList.contains(`${l}-flow__handle`)?A:T,p={handleDomNode:R,isValid:!1,connection:null,toHandle:null};if(R){const N=ZA(void 0,R),I=R.getAttribute("data-nodeid"),O=R.getAttribute("data-handleid"),m=R.classList.contains("connectable"),C=R.classList.contains("connectableend");if(!I||!N)return p;const g={source:u?I:r,sourceHandle:u?O:o,target:u?r:I,targetHandle:u?o:O};p.connection=g;const _=m&&C&&(n===dr.Strict?u&&N==="source"||!u&&N==="target":I!==r||O!==o);p.isValid=_&&E(g),p.toHandle=QA(I,N,O,d,n,!0)}return p}const cc={onPointerDown:M1,isValid:tp};function P1({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const o=Ke(e);function s({translateExtent:l,width:c,height:E,zoomStep:d=1,pannable:u=!0,zoomable:T=!0,inversePan:S=!1}){const h=I=>{if(I.sourceEvent.type!=="wheel"||!t)return;const O=n(),m=I.sourceEvent.ctrlKey&&uo()?10:1,C=-I.sourceEvent.deltaY*(I.sourceEvent.deltaMode===1?.05:I.sourceEvent.deltaMode?1:.002)*d,g=O[2]*Math.pow(2,C*m);t.scaleTo(g)};let A=[0,0];const R=I=>{(I.sourceEvent.type==="mousedown"||I.sourceEvent.type==="touchstart")&&(A=[I.sourceEvent.clientX??I.sourceEvent.touches[0].clientX,I.sourceEvent.clientY??I.sourceEvent.touches[0].clientY])},p=I=>{const O=n();if(I.sourceEvent.type!=="mousemove"&&I.sourceEvent.type!=="touchmove"||!t)return;const m=[I.sourceEvent.clientX??I.sourceEvent.touches[0].clientX,I.sourceEvent.clientY??I.sourceEvent.touches[0].clientY],C=[m[0]-A[0],m[1]-A[1]];A=m;const g=r()*Math.max(O[2],Math.log(O[2]))*(S?-1:1),y={x:O[0]-C[0]*g,y:O[1]-C[1]*g},_=[[0,0],[c,E]];t.setViewportConstrained({x:y.x,y:y.y,zoom:O[2]},_,l)},N=yA().on("start",R).on("zoom",u?p:null).on("zoom.wheel",T?h:null);o.call(N,{})}function a(){o.on("zoom",null)}return{update:s,destroy:a,pointer:ot}}const qi=e=>({x:e.x,y:e.y,zoom:e.k}),Va=({x:e,y:t,zoom:n})=>Ki.translate(e,t).scale(n),qn=(e,t)=>e.target.closest(`.${t}`),np=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),b1=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,$a=(e,t=0,n=b1,r=()=>{})=>{const o=typeof t=="number"&&t>0;return o||r(),o?e.transition().duration(t).ease(n).on("end",r):e},rp=e=>{const t=e.ctrlKey&&uo()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function v1({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:o,panOnScrollSpeed:s,zoomOnPinch:a,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:E}){return d=>{if(qn(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const u=n.property("__zoom").k||1;if(d.ctrlKey&&a){const R=ot(d),p=rp(d),N=u*Math.pow(2,p);r.scaleTo(n,N,R,d);return}const T=d.deltaMode===1?20:1;let S=o===mn.Vertical?0:d.deltaX*T,h=o===mn.Horizontal?0:d.deltaY*T;!uo()&&d.shiftKey&&o!==mn.Vertical&&(S=d.deltaY*T,h=0),r.translateBy(n,-(S/u)*s,-(h/u)*s,{internal:!0});const A=qi(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c==null||c(d,A),e.panScrollTimeout=setTimeout(()=>{E==null||E(d,A),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l==null||l(d,A))}}function U1({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,o){const s=r.type==="wheel",a=!t&&s&&!r.ctrlKey,l=qn(r,e);if(r.ctrlKey&&s&&l&&r.preventDefault(),a||l)return null;r.preventDefault(),n.call(this,r,o)}}function w1({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{var s,a,l;if((s=r.sourceEvent)!=null&&s.internal)return;const o=qi(r.transform);e.mouseButton=((a=r.sourceEvent)==null?void 0:a.button)||0,e.isZoomingOrPanning=!0,e.prevViewport=o,((l=r.sourceEvent)==null?void 0:l.type)==="mousedown"&&t(!0),n&&(n==null||n(r.sourceEvent,o))}}function B1({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:o}){return s=>{var a,l;e.usedRightMouseButton=!!(n&&np(t,e.mouseButton??0)),(a=s.sourceEvent)!=null&&a.sync||r([s.transform.x,s.transform.y,s.transform.k]),o&&!((l=s.sourceEvent)!=null&&l.internal)&&(o==null||o(s.sourceEvent,qi(s.transform)))}}function F1({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:o,onPaneContextMenu:s}){return a=>{var l;if(!((l=a.sourceEvent)!=null&&l.internal)&&(e.isZoomingOrPanning=!1,s&&np(t,e.mouseButton??0)&&!e.usedRightMouseButton&&a.sourceEvent&&s(a.sourceEvent),e.usedRightMouseButton=!1,r(!1),o)){const c=qi(a.transform);e.prevViewport=c,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{o==null||o(a.sourceEvent,c)},n?150:0)}}}function G1({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:o,zoomOnDoubleClick:s,userSelectionActive:a,noWheelClassName:l,noPanClassName:c,lib:E,connectionInProgress:d}){return u=>{var R;const T=e||t,S=n&&u.ctrlKey,h=u.type==="wheel";if(u.button===1&&u.type==="mousedown"&&(qn(u,`${E}-flow__node`)||qn(u,`${E}-flow__edge`)))return!0;if(!r&&!T&&!o&&!s&&!n||a||d&&!h||qn(u,l)&&h||qn(u,c)&&(!h||o&&h&&!e)||!n&&u.ctrlKey&&h)return!1;if(!n&&u.type==="touchstart"&&((R=u.touches)==null?void 0:R.length)>1)return u.preventDefault(),!1;if(!T&&!o&&!S&&h||!r&&(u.type==="mousedown"||u.type==="touchstart")||Array.isArray(r)&&!r.includes(u.button)&&u.type==="mousedown")return!1;const A=Array.isArray(r)&&r.includes(u.button)||!u.button||u.button<=1;return(!u.ctrlKey||h)&&A}}function H1({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:o,onPanZoom:s,onPanZoomStart:a,onPanZoomEnd:l,onDraggingChange:c}){const E={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},d=e.getBoundingClientRect(),u=yA().scaleExtent([t,n]).translateExtent(r),T=Ke(e).call(u);N({x:o.x,y:o.y,zoom:Tr(o.zoom,t,n)},[[0,0],[d.width,d.height]],r);const S=T.on("wheel.zoom"),h=T.on("dblclick.zoom");u.wheelDelta(rp);function A(D,b){return T?new Promise(F=>{u==null||u.interpolate((b==null?void 0:b.interpolate)==="linear"?Wr:vs).transform($a(T,b==null?void 0:b.duration,b==null?void 0:b.ease,()=>F(!0)),D)}):Promise.resolve(!1)}function R({noWheelClassName:D,noPanClassName:b,onPaneContextMenu:F,userSelectionActive:x,panOnScroll:w,panOnDrag:M,panOnScrollMode:B,panOnScrollSpeed:v,preventScrolling:L,zoomOnPinch:U,zoomOnScroll:G,zoomOnDoubleClick:k,zoomActivationKeyPressed:J,lib:K,onTransformChange:$,connectionInProgress:z,paneClickDistance:q,selectionOnDrag:X}){x&&!E.isZoomingOrPanning&&p();const Q=w&&!J&&!x;u.clickDistance(X?1/0:!it(q)||q<0?0:q);const ae=Q?v1({zoomPanValues:E,noWheelClassName:D,d3Selection:T,d3Zoom:u,panOnScrollMode:B,panOnScrollSpeed:v,zoomOnPinch:U,onPanZoomStart:a,onPanZoom:s,onPanZoomEnd:l}):U1({noWheelClassName:D,preventScrolling:L,d3ZoomHandler:S});if(T.on("wheel.zoom",ae,{passive:!1}),!x){const re=w1({zoomPanValues:E,onDraggingChange:c,onPanZoomStart:a});u.on("start",re);const Y=B1({zoomPanValues:E,panOnDrag:M,onPaneContextMenu:!!F,onPanZoom:s,onTransformChange:$});u.on("zoom",Y);const se=F1({zoomPanValues:E,panOnDrag:M,panOnScroll:w,onPaneContextMenu:F,onPanZoomEnd:l,onDraggingChange:c});u.on("end",se)}const ne=G1({zoomActivationKeyPressed:J,panOnDrag:M,zoomOnScroll:G,panOnScroll:w,zoomOnDoubleClick:k,zoomOnPinch:U,userSelectionActive:x,noPanClassName:b,noWheelClassName:D,lib:K,connectionInProgress:z});u.filter(ne),k?T.on("dblclick.zoom",h):T.on("dblclick.zoom",null)}function p(){u.on("zoom",null)}async function N(D,b,F){const x=Va(D),w=u==null?void 0:u.constrain()(x,b,F);return w&&await A(w),new Promise(M=>M(w))}async function I(D,b){const F=Va(D);return await A(F,b),new Promise(x=>x(F))}function O(D){if(T){const b=Va(D),F=T.property("__zoom");(F.k!==D.zoom||F.x!==D.x||F.y!==D.y)&&(u==null||u.transform(T,b,null,{sync:!0}))}}function m(){const D=T?xA(T.node()):{x:0,y:0,k:1};return{x:D.x,y:D.y,zoom:D.k}}function C(D,b){return T?new Promise(F=>{u==null||u.interpolate((b==null?void 0:b.interpolate)==="linear"?Wr:vs).scaleTo($a(T,b==null?void 0:b.duration,b==null?void 0:b.ease,()=>F(!0)),D)}):Promise.resolve(!1)}function g(D,b){return T?new Promise(F=>{u==null||u.interpolate((b==null?void 0:b.interpolate)==="linear"?Wr:vs).scaleBy($a(T,b==null?void 0:b.duration,b==null?void 0:b.ease,()=>F(!0)),D)}):Promise.resolve(!1)}function y(D){u==null||u.scaleExtent(D)}function _(D){u==null||u.translateExtent(D)}function P(D){const b=!it(D)||D<0?0:D;u==null||u.clickDistance(b)}return{update:R,destroy:p,setViewport:I,setViewportConstrained:N,getViewport:m,scaleTo:C,scaleBy:g,setScaleExtent:y,setTranslateExtent:_,syncViewport:O,setClickDistance:P}}var Rr;(function(e){e.Line="line",e.Handle="handle"})(Rr||(Rr={}));function k1({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:o,affectsY:s}){const a=e-t,l=n-r,c=[a>0?1:a<0?-1:0,l>0?1:l<0?-1:0];return a&&o&&(c[0]=c[0]*-1),l&&s&&(c[1]=c[1]*-1),c}function Lu(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),r=e.includes("left"),o=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:r,affectsY:o}}function Xt(e,t){return Math.max(0,t-e)}function Kt(e,t){return Math.max(0,e-t)}function Is(e,t,n){return Math.max(0,t-e,e-n)}function _u(e,t){return e?!t:t}function j1(e,t,n,r,o,s,a,l){let{affectsX:c,affectsY:E}=t;const{isHorizontal:d,isVertical:u}=t,T=d&&u,{xSnapped:S,ySnapped:h}=n,{minWidth:A,maxWidth:R,minHeight:p,maxHeight:N}=r,{x:I,y:O,width:m,height:C,aspectRatio:g}=e;let y=Math.floor(d?S-e.pointerX:0),_=Math.floor(u?h-e.pointerY:0);const P=m+(c?-y:y),D=C+(E?-_:_),b=-s[0]*m,F=-s[1]*C;let x=Is(P,A,R),w=Is(D,p,N);if(a){let v=0,L=0;c&&y<0?v=Xt(I+y+b,a[0][0]):!c&&y>0&&(v=Kt(I+P+b,a[1][0])),E&&_<0?L=Xt(O+_+F,a[0][1]):!E&&_>0&&(L=Kt(O+D+F,a[1][1])),x=Math.max(x,v),w=Math.max(w,L)}if(l){let v=0,L=0;c&&y>0?v=Kt(I+y,l[0][0]):!c&&y<0&&(v=Xt(I+P,l[1][0])),E&&_>0?L=Kt(O+_,l[0][1]):!E&&_<0&&(L=Xt(O+D,l[1][1])),x=Math.max(x,v),w=Math.max(w,L)}if(o){if(d){const v=Is(P/g,p,N)*g;if(x=Math.max(x,v),a){let L=0;!c&&!E||c&&!E&&T?L=Kt(O+F+P/g,a[1][1])*g:L=Xt(O+F+(c?y:-y)/g,a[0][1])*g,x=Math.max(x,L)}if(l){let L=0;!c&&!E||c&&!E&&T?L=Xt(O+P/g,l[1][1])*g:L=Kt(O+(c?y:-y)/g,l[0][1])*g,x=Math.max(x,L)}}if(u){const v=Is(D*g,A,R)/g;if(w=Math.max(w,v),a){let L=0;!c&&!E||E&&!c&&T?L=Kt(I+D*g+b,a[1][0])/g:L=Xt(I+(E?_:-_)*g+b,a[0][0])/g,w=Math.max(w,L)}if(l){let L=0;!c&&!E||E&&!c&&T?L=Xt(I+D*g,l[1][0])/g:L=Kt(I+(E?_:-_)*g,l[0][0])/g,w=Math.max(w,L)}}}_=_+(_<0?w:-w),y=y+(y<0?x:-x),o&&(T?P>D*g?_=(_u(c,E)?-y:y)/g:y=(_u(c,E)?-_:_)*g:d?(_=y/g,E=c):(y=_*g,c=E));const M=c?I+y:I,B=E?O+_:O;return{width:m+(c?-y:y),height:C+(E?-_:_),x:s[0]*y*(c?-1:1)+M,y:s[1]*_*(E?-1:1)+B}}const op={width:0,height:0,x:0,y:0},Y1={...op,pointerX:0,pointerY:0,aspectRatio:1};function W1(e){return[[0,0],[e.measured.width,e.measured.height]]}function V1(e,t,n){const r=t.position.x+e.position.x,o=t.position.y+e.position.y,s=e.measured.width??0,a=e.measured.height??0,l=n[0]*s,c=n[1]*a;return[[r-l,o-c],[r+s-l,o+a-c]]}function $1({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:o}){const s=Ke(e);let a={controlDirection:Lu("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:E,boundaries:d,keepAspectRatio:u,resizeDirection:T,onResizeStart:S,onResize:h,onResizeEnd:A,shouldResize:R}){let p={...op},N={...Y1};a={boundaries:d,resizeDirection:T,keepAspectRatio:u,controlDirection:Lu(E)};let I,O=null,m=[],C,g,y,_=!1;const P=SA().on("start",D=>{const{nodeLookup:b,transform:F,snapGrid:x,snapToGrid:w,nodeOrigin:M,paneDomNode:B}=n();if(I=b.get(t),!I)return;O=(B==null?void 0:B.getBoundingClientRect())??null;const{xSnapped:v,ySnapped:L}=Vr(D.sourceEvent,{transform:F,snapGrid:x,snapToGrid:w,containerBounds:O});p={width:I.measured.width??0,height:I.measured.height??0,x:I.position.x??0,y:I.position.y??0},N={...p,pointerX:v,pointerY:L,aspectRatio:p.width/p.height},C=void 0,I.parentId&&(I.extent==="parent"||I.expandParent)&&(C=b.get(I.parentId),g=C&&I.extent==="parent"?W1(C):void 0),m=[],y=void 0;for(const[U,G]of b)if(G.parentId===t&&(m.push({id:U,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const k=V1(G,I,G.origin??M);y?y=[[Math.min(k[0][0],y[0][0]),Math.min(k[0][1],y[0][1])],[Math.max(k[1][0],y[1][0]),Math.max(k[1][1],y[1][1])]]:y=k}S==null||S(D,{...p})}).on("drag",D=>{const{transform:b,snapGrid:F,snapToGrid:x,nodeOrigin:w}=n(),M=Vr(D.sourceEvent,{transform:b,snapGrid:F,snapToGrid:x,containerBounds:O}),B=[];if(!I)return;const{x:v,y:L,width:U,height:G}=p,k={},J=I.origin??w,{width:K,height:$,x:z,y:q}=j1(N,a.controlDirection,M,a.boundaries,a.keepAspectRatio,J,g,y),X=K!==U,Q=$!==G,ae=z!==v&&X,ne=q!==L&&Q;if(!ae&&!ne&&!X&&!Q)return;if((ae||ne||J[0]===1||J[1]===1)&&(k.x=ae?z:p.x,k.y=ne?q:p.y,p.x=k.x,p.y=k.y,m.length>0)){const de=z-v,ue=q-L;for(const me of m)me.position={x:me.position.x-de+J[0]*(K-U),y:me.position.y-ue+J[1]*($-G)},B.push(me)}if((X||Q)&&(k.width=X&&(!a.resizeDirection||a.resizeDirection==="horizontal")?K:p.width,k.height=Q&&(!a.resizeDirection||a.resizeDirection==="vertical")?$:p.height,p.width=k.width,p.height=k.height),C&&I.expandParent){const de=J[0]*(k.width??0);k.x&&k.x<de&&(p.x=de,N.x=N.x-(k.x-de));const ue=J[1]*(k.height??0);k.y&&k.y<ue&&(p.y=ue,N.y=N.y-(k.y-ue))}const re=k1({width:p.width,prevWidth:U,height:p.height,prevHeight:G,affectsX:a.controlDirection.affectsX,affectsY:a.controlDirection.affectsY}),Y={...p,direction:re};(R==null?void 0:R(D,Y))!==!1&&(_=!0,h==null||h(D,Y),r(k,B))}).on("end",D=>{_&&(A==null||A(D,{...p}),o==null||o({...p}),_=!1)});s.call(P)}function c(){s.on(".drag",null)}return{update:l,destroy:c}}var Xa={exports:{}},Ka={},za={exports:{}},Ja={};/**
|
|
656
|
-
* @license React
|
|
657
|
-
* use-sync-external-store-shim.production.js
|
|
658
|
-
*
|
|
659
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
660
|
-
*
|
|
661
|
-
* This source code is licensed under the MIT license found in the
|
|
662
|
-
* LICENSE file in the root directory of this source tree.
|
|
663
|
-
*/var xu;function X1(){if(xu)return Ja;xu=1;var e=hi();function t(u,T){return u===T&&(u!==0||1/u===1/T)||u!==u&&T!==T}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,s=e.useLayoutEffect,a=e.useDebugValue;function l(u,T){var S=T(),h=r({inst:{value:S,getSnapshot:T}}),A=h[0].inst,R=h[1];return s(function(){A.value=S,A.getSnapshot=T,c(A)&&R({inst:A})},[u,S,T]),o(function(){return c(A)&&R({inst:A}),u(function(){c(A)&&R({inst:A})})},[u]),a(S),S}function c(u){var T=u.getSnapshot;u=u.value;try{var S=T();return!n(u,S)}catch{return!0}}function E(u,T){return T()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?E:l;return Ja.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:d,Ja}var yu;function K1(){return yu||(yu=1,za.exports=X1()),za.exports}/**
|
|
664
|
-
* @license React
|
|
665
|
-
* use-sync-external-store-shim/with-selector.production.js
|
|
666
|
-
*
|
|
667
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
668
|
-
*
|
|
669
|
-
* This source code is licensed under the MIT license found in the
|
|
670
|
-
* LICENSE file in the root directory of this source tree.
|
|
671
|
-
*/var Du;function z1(){if(Du)return Ka;Du=1;var e=hi(),t=K1();function n(E,d){return E===d&&(E!==0||1/E===1/d)||E!==E&&d!==d}var r=typeof Object.is=="function"?Object.is:n,o=t.useSyncExternalStore,s=e.useRef,a=e.useEffect,l=e.useMemo,c=e.useDebugValue;return Ka.useSyncExternalStoreWithSelector=function(E,d,u,T,S){var h=s(null);if(h.current===null){var A={hasValue:!1,value:null};h.current=A}else A=h.current;h=l(function(){function p(C){if(!N){if(N=!0,I=C,C=T(C),S!==void 0&&A.hasValue){var g=A.value;if(S(g,C))return O=g}return O=C}if(g=O,r(I,C))return g;var y=T(C);return S!==void 0&&S(g,y)?(I=C,g):(I=C,O=y)}var N=!1,I,O,m=u===void 0?null:u;return[function(){return p(d())},m===null?void 0:function(){return p(m())}]},[d,u,T,S]);var R=o(E,h[0],h[1]);return a(function(){A.hasValue=!0,A.value=R},[R]),c(R),R},Ka}var Mu;function J1(){return Mu||(Mu=1,Xa.exports=z1()),Xa.exports}var q1=J1();const Q1=Ii(q1),Z1={},Pu=e=>{let t;const n=new Set,r=(d,u)=>{const T=typeof d=="function"?d(t):d;if(!Object.is(T,t)){const S=t;t=u??(typeof T!="object"||T===null)?T:Object.assign({},t,T),n.forEach(h=>h(t,S))}},o=()=>t,c={setState:r,getState:o,getInitialState:()=>E,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(Z1?"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()}},E=t=e(r,o,c);return c},ev=e=>e?Pu(e):Pu,{useDebugValue:tv}=ge,{useSyncExternalStoreWithSelector:nv}=Q1,rv=e=>e;function sp(e,t=rv,n){const r=nv(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return tv(r),r}const bu=(e,t)=>{const n=ev(e),r=(o,s=t)=>sp(n,o,s);return Object.assign(r,n),r},ov=(e,t)=>e?bu(e,t):bu;function Ie(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,o]of e)if(!Object.is(o,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 Qi=f.createContext(null),sv=Qi.Provider,ip=mt.error001();function Re(e,t){const n=f.useContext(Qi);if(n===null)throw new Error(ip);return sp(n,e,t)}function Oe(){const e=f.useContext(Qi);if(e===null)throw new Error(ip);return f.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const vu={display:"none"},iv={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},ap="react-flow__node-desc",lp="react-flow__edge-desc",av="react-flow__aria-live",lv=e=>e.ariaLiveMessage,cv=e=>e.ariaLabelConfig;function Ev({rfId:e}){const t=Re(lv);return i.jsx("div",{id:`${av}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:iv,children:t})}function dv({rfId:e,disableKeyboardA11y:t}){const n=Re(cv);return i.jsxs(i.Fragment,{children:[i.jsx("div",{id:`${ap}-${e}`,style:vu,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),i.jsx("div",{id:`${lp}-${e}`,style:vu,children:n["edge.a11yDescription.default"]}),!t&&i.jsx(Ev,{rfId:e})]})}const Ar=f.forwardRef(({position:e="top-left",children:t,className:n,style:r,...o},s)=>{const a=`${e}`.split("-");return i.jsx("div",{className:xe(["react-flow__panel",n,...a]),style:r,ref:s,...o,children:t})});Ar.displayName="Panel";function uv({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:i.jsx(Ar,{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:i.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const Tv=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}},Ns=e=>e.id;function Sv(e,t){return Ie(e.selectedNodes.map(Ns),t.selectedNodes.map(Ns))&&Ie(e.selectedEdges.map(Ns),t.selectedEdges.map(Ns))}function fv({onSelectionChange:e}){const t=Oe(),{selectedNodes:n,selectedEdges:r}=Re(Tv,Sv);return f.useEffect(()=>{const o={nodes:n,edges:r};e==null||e(o),t.getState().onSelectionChangeHandlers.forEach(s=>s(o))},[n,r,e]),null}const Rv=e=>!!e.onSelectionChangeHandlers;function Av({onSelectionChange:e}){const t=Re(Rv);return e||t?i.jsx(fv,{onSelectionChange:e}):null}const cp=[0,0],pv={x:0,y:0,zoom:1},hv=["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"],Uu=[...hv,"rfId"],Iv=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}),wu={translateExtent:lo,nodeOrigin:cp,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function Nv(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:o,setTranslateExtent:s,setNodeExtent:a,reset:l,setDefaultNodesAndEdges:c}=Re(Iv,Ie),E=Oe();f.useEffect(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=wu,l()}),[]);const d=f.useRef(wu);return f.useEffect(()=>{for(const u of Uu){const T=e[u],S=d.current[u];T!==S&&(typeof e[u]>"u"||(u==="nodes"?t(T):u==="edges"?n(T):u==="minZoom"?r(T):u==="maxZoom"?o(T):u==="translateExtent"?s(T):u==="nodeExtent"?a(T):u==="ariaLabelConfig"?E.setState({ariaLabelConfig:o1(T)}):u==="fitView"?E.setState({fitViewQueued:T}):u==="fitViewOptions"?E.setState({fitViewOptions:T}):E.setState({[u]:T})))}d.current=e},Uu.map(u=>e[u])),null}function Bu(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function Ov(e){var r;const[t,n]=f.useState(e==="system"?null:e);return f.useEffect(()=>{if(e!=="system"){n(e);return}const o=Bu(),s=()=>n(o!=null&&o.matches?"dark":"light");return s(),o==null||o.addEventListener("change",s),()=>{o==null||o.removeEventListener("change",s)}},[e]),t!==null?t:(r=Bu())!=null&&r.matches?"dark":"light"}const Fu=typeof document<"u"?document:null;function To(e=null,t={target:Fu,actInsideInputWithModifier:!0}){const[n,r]=f.useState(!1),o=f.useRef(!1),s=f.useRef(new Set([])),[a,l]=f.useMemo(()=>{if(e!==null){const E=(Array.isArray(e)?e:[e]).filter(u=>typeof u=="string").map(u=>u.replace("+",`
|
|
672
|
-
`).replace(`
|
|
673
|
-
|
|
674
|
-
`,`
|
|
675
|
-
+`).split(`
|
|
676
|
-
`)),d=E.reduce((u,T)=>u.concat(...T),[]);return[E,d]}return[[],[]]},[e]);return f.useEffect(()=>{const c=(t==null?void 0:t.target)??Fu,E=(t==null?void 0:t.actInsideInputWithModifier)??!0;if(e!==null){const d=S=>{var R,p;if(o.current=S.ctrlKey||S.metaKey||S.shiftKey||S.altKey,(!o.current||o.current&&!E)&&jA(S))return!1;const A=Hu(S.code,l);if(s.current.add(S[A]),Gu(a,s.current,!1)){const N=((p=(R=S.composedPath)==null?void 0:R.call(S))==null?void 0:p[0])||S.target,I=(N==null?void 0:N.nodeName)==="BUTTON"||(N==null?void 0:N.nodeName)==="A";t.preventDefault!==!1&&(o.current||!I)&&S.preventDefault(),r(!0)}},u=S=>{const h=Hu(S.code,l);Gu(a,s.current,!0)?(r(!1),s.current.clear()):s.current.delete(S[h]),S.key==="Meta"&&s.current.clear(),o.current=!1},T=()=>{s.current.clear(),r(!1)};return c==null||c.addEventListener("keydown",d),c==null||c.addEventListener("keyup",u),window.addEventListener("blur",T),window.addEventListener("contextmenu",T),()=>{c==null||c.removeEventListener("keydown",d),c==null||c.removeEventListener("keyup",u),window.removeEventListener("blur",T),window.removeEventListener("contextmenu",T)}}},[e,r]),n}function Gu(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(o=>t.has(o)))}function Hu(e,t){return t.includes(e)?"code":"key"}const mv=()=>{const e=Oe();return f.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,o,s],panZoom:a}=e.getState();return a?(await a.setViewport({x:t.x??r,y:t.y??o,zoom:t.zoom??s},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:o,minZoom:s,maxZoom:a,panZoom:l}=e.getState(),c=dE(t,r,o,s,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:o,snapToGrid:s,domNode:a}=e.getState();if(!a)return t;const{x:l,y:c}=a.getBoundingClientRect(),E={x:t.x-l,y:t.y-c},d=n.snapGrid??o,u=n.snapToGrid??s;return Do(E,r,u,d)},flowToScreenPosition:t=>{const{transform:n,domNode:r}=e.getState();if(!r)return t;const{x:o,y:s}=r.getBoundingClientRect(),a=ui(t,n);return{x:a.x+o,y:a.y+s}}}),[])};function Ep(e,t){const n=[],r=new Map,o=[];for(const s of e)if(s.type==="add"){o.push(s);continue}else if(s.type==="remove"||s.type==="replace")r.set(s.id,[s]);else{const a=r.get(s.id);a?a.push(s):r.set(s.id,[s])}for(const s of t){const a=r.get(s.id);if(!a){n.push(s);continue}if(a[0].type==="remove")continue;if(a[0].type==="replace"){n.push({...a[0].item});continue}const l={...s};for(const c of a)Cv(c,l);n.push(l)}return o.length&&o.forEach(s=>{s.index!==void 0?n.splice(s.index,0,{...s.item}):n.push({...s.item})}),n}function Cv(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 dp(e,t){return Ep(e,t)}function up(e,t){return Ep(e,t)}function hn(e,t){return{id:e,type:"select",selected:t}}function Qn(e,t=new Set,n=!1){const r=[];for(const[o,s]of e){const a=t.has(o);!(s.selected===void 0&&!a)&&s.selected!==a&&(n&&(s.selected=a),r.push(hn(s.id,a)))}return r}function ku({items:e=[],lookup:t}){var o;const n=[],r=new Map(e.map(s=>[s.id,s]));for(const[s,a]of e.entries()){const l=t.get(a.id),c=((o=l==null?void 0:l.internals)==null?void 0:o.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:s})}for(const[s]of t)r.get(s)===void 0&&n.push({id:s,type:"remove"});return n}function ju(e){return{id:e.id,type:"remove"}}const Yu=e=>Kb(e),gv=e=>vA(e);function Tp(e){return f.forwardRef(e)}const Lv=typeof window<"u"?f.useLayoutEffect:f.useEffect;function Wu(e){const[t,n]=f.useState(BigInt(0)),[r]=f.useState(()=>_v(()=>n(o=>o+BigInt(1))));return Lv(()=>{const o=r.get();o.length&&(e(o),r.reset())},[t]),r}function _v(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}const Sp=f.createContext(null);function xv({children:e}){const t=Oe(),n=f.useCallback(l=>{const{nodes:c=[],setNodes:E,hasDefaultNodes:d,onNodesChange:u,nodeLookup:T,fitViewQueued:S,onNodesChangeMiddlewareMap:h}=t.getState();let A=c;for(const p of l)A=typeof p=="function"?p(A):p;let R=ku({items:A,lookup:T});for(const p of h.values())R=p(R);d&&E(A),R.length>0?u==null||u(R):S&&window.requestAnimationFrame(()=>{const{fitViewQueued:p,nodes:N,setNodes:I}=t.getState();p&&I(N)})},[]),r=Wu(n),o=f.useCallback(l=>{const{edges:c=[],setEdges:E,hasDefaultEdges:d,onEdgesChange:u,edgeLookup:T}=t.getState();let S=c;for(const h of l)S=typeof h=="function"?h(S):h;d?E(S):u&&u(ku({items:S,lookup:T}))},[]),s=Wu(o),a=f.useMemo(()=>({nodeQueue:r,edgeQueue:s}),[]);return i.jsx(Sp.Provider,{value:a,children:e})}function yv(){const e=f.useContext(Sp);if(!e)throw new Error("useBatchContext must be used within a BatchProvider");return e}const Dv=e=>!!e.panZoom;function pE(){const e=mv(),t=Oe(),n=yv(),r=Re(Dv),o=f.useMemo(()=>{const s=u=>t.getState().nodeLookup.get(u),a=u=>{n.nodeQueue.push(u)},l=u=>{n.edgeQueue.push(u)},c=u=>{var p,N;const{nodeLookup:T,nodeOrigin:S}=t.getState(),h=Yu(u)?u:T.get(u.id),A=h.parentId?HA(h.position,h.measured,h.parentId,T,S):h.position,R={...h,position:A,width:((p=h.measured)==null?void 0:p.width)??h.width,height:((N=h.measured)==null?void 0:N.height)??h.height};return Sr(R)},E=(u,T,S={replace:!1})=>{a(h=>h.map(A=>{if(A.id===u){const R=typeof T=="function"?T(A):T;return S.replace&&Yu(R)?R:{...A,...R}}return A}))},d=(u,T,S={replace:!1})=>{l(h=>h.map(A=>{if(A.id===u){const R=typeof T=="function"?T(A):T;return S.replace&&gv(R)?R:{...A,...R}}return A}))};return{getNodes:()=>t.getState().nodes.map(u=>({...u})),getNode:u=>{var T;return(T=s(u))==null?void 0:T.internals.userNode},getInternalNode:s,getEdges:()=>{const{edges:u=[]}=t.getState();return u.map(T=>({...T}))},getEdge:u=>t.getState().edgeLookup.get(u),setNodes:a,setEdges:l,addNodes:u=>{const T=Array.isArray(u)?u:[u];n.nodeQueue.push(S=>[...S,...T])},addEdges:u=>{const T=Array.isArray(u)?u:[u];n.edgeQueue.push(S=>[...S,...T])},toObject:()=>{const{nodes:u=[],edges:T=[],transform:S}=t.getState(),[h,A,R]=S;return{nodes:u.map(p=>({...p})),edges:T.map(p=>({...p})),viewport:{x:h,y:A,zoom:R}}},deleteElements:async({nodes:u=[],edges:T=[]})=>{const{nodes:S,edges:h,onNodesDelete:A,onEdgesDelete:R,triggerNodeChanges:p,triggerEdgeChanges:N,onDelete:I,onBeforeDelete:O}=t.getState(),{nodes:m,edges:C}=await Zb({nodesToRemove:u,edgesToRemove:T,nodes:S,edges:h,onBeforeDelete:O}),g=C.length>0,y=m.length>0;if(g){const _=C.map(ju);R==null||R(C),N(_)}if(y){const _=m.map(ju);A==null||A(m),p(_)}return(y||g)&&(I==null||I({nodes:m,edges:C})),{deletedNodes:m,deletedEdges:C}},getIntersectingNodes:(u,T=!0,S)=>{const h=fu(u),A=h?u:c(u),R=S!==void 0;return A?(S||t.getState().nodes).filter(p=>{const N=t.getState().nodeLookup.get(p.id);if(N&&!h&&(p.id===u.id||!N.internals.positionAbsolute))return!1;const I=Sr(R?p:N),O=Eo(I,A);return T&&O>0||O>=I.width*I.height||O>=A.width*A.height}):[]},isNodeIntersecting:(u,T,S=!0)=>{const A=fu(u)?u:c(u);if(!A)return!1;const R=Eo(A,T);return S&&R>0||R>=T.width*T.height||R>=A.width*A.height},updateNode:E,updateNodeData:(u,T,S={replace:!1})=>{E(u,h=>{const A=typeof T=="function"?T(h):T;return S.replace?{...h,data:A}:{...h,data:{...h.data,...A}}},S)},updateEdge:d,updateEdgeData:(u,T,S={replace:!1})=>{d(u,h=>{const A=typeof T=="function"?T(h):T;return S.replace?{...h,data:A}:{...h,data:{...h.data,...A}}},S)},getNodesBounds:u=>{const{nodeLookup:T,nodeOrigin:S}=t.getState();return zb(u,{nodeLookup:T,nodeOrigin:S})},getHandleConnections:({type:u,id:T,nodeId:S})=>{var h;return Array.from(((h=t.getState().connectionLookup.get(`${S}-${u}${T?`-${T}`:""}`))==null?void 0:h.values())??[])},getNodeConnections:({type:u,handleId:T,nodeId:S})=>{var h;return Array.from(((h=t.getState().connectionLookup.get(`${S}${u?T?`-${u}-${T}`:`-${u}`:""}`))==null?void 0:h.values())??[])},fitView:async u=>{const T=t.getState().fitViewResolver??r1();return t.setState({fitViewQueued:!0,fitViewOptions:u,fitViewResolver:T}),n.nodeQueue.push(S=>[...S]),T.promise}}},[]);return f.useMemo(()=>({...o,...e,viewportInitialized:r}),[r])}const Vu=e=>e.selected,Mv=typeof window<"u"?window:void 0;function Pv({deleteKeyCode:e,multiSelectionKeyCode:t}){const n=Oe(),{deleteElements:r}=pE(),o=To(e,{actInsideInputWithModifier:!1}),s=To(t,{target:Mv});f.useEffect(()=>{if(o){const{edges:a,nodes:l}=n.getState();r({nodes:l.filter(Vu),edges:a.filter(Vu)}),n.setState({nodesSelectionActive:!1})}},[o]),f.useEffect(()=>{n.setState({multiSelectionActive:s})},[s])}function bv(e){const t=Oe();f.useEffect(()=>{const n=()=>{var o,s,a,l;if(!e.current||!(((s=(o=e.current).checkVisibility)==null?void 0:s.call(o))??!0))return!1;const r=uE(e.current);(r.height===0||r.width===0)&&((l=(a=t.getState()).onError)==null||l.call(a,"004",mt.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 Zi={position:"absolute",width:"100%",height:"100%",top:0,left:0},vv=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function Uv({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:r=!1,panOnScrollSpeed:o=.5,panOnScrollMode:s=mn.Free,zoomOnDoubleClick:a=!0,panOnDrag:l=!0,defaultViewport:c,translateExtent:E,minZoom:d,maxZoom:u,zoomActivationKeyCode:T,preventScrolling:S=!0,children:h,noWheelClassName:A,noPanClassName:R,onViewportChange:p,isControlledViewport:N,paneClickDistance:I,selectionOnDrag:O}){const m=Oe(),C=f.useRef(null),{userSelectionActive:g,lib:y,connectionInProgress:_}=Re(vv,Ie),P=To(T),D=f.useRef();bv(C);const b=f.useCallback(F=>{p==null||p({x:F[0],y:F[1],zoom:F[2]}),N||m.setState({transform:F})},[p,N]);return f.useEffect(()=>{if(C.current){D.current=H1({domNode:C.current,minZoom:d,maxZoom:u,translateExtent:E,viewport:c,onDraggingChange:M=>m.setState(B=>B.paneDragging===M?B:{paneDragging:M}),onPanZoomStart:(M,B)=>{const{onViewportChangeStart:v,onMoveStart:L}=m.getState();L==null||L(M,B),v==null||v(B)},onPanZoom:(M,B)=>{const{onViewportChange:v,onMove:L}=m.getState();L==null||L(M,B),v==null||v(B)},onPanZoomEnd:(M,B)=>{const{onViewportChangeEnd:v,onMoveEnd:L}=m.getState();L==null||L(M,B),v==null||v(B)}});const{x:F,y:x,zoom:w}=D.current.getViewport();return m.setState({panZoom:D.current,transform:[F,x,w],domNode:C.current.closest(".react-flow")}),()=>{var M;(M=D.current)==null||M.destroy()}}},[]),f.useEffect(()=>{var F;(F=D.current)==null||F.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:r,panOnScrollSpeed:o,panOnScrollMode:s,zoomOnDoubleClick:a,panOnDrag:l,zoomActivationKeyPressed:P,preventScrolling:S,noPanClassName:R,userSelectionActive:g,noWheelClassName:A,lib:y,onTransformChange:b,connectionInProgress:_,selectionOnDrag:O,paneClickDistance:I})},[e,t,n,r,o,s,a,l,P,S,R,g,A,y,b,_,O,I]),i.jsx("div",{className:"react-flow__renderer",ref:C,style:Zi,children:h})}const wv=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function Bv(){const{userSelectionActive:e,userSelectionRect:t}=Re(wv,Ie);return e&&t?i.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 qa=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},Fv=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,connectionInProgress:e.connection.inProgress,dragging:e.paneDragging});function Gv({isSelecting:e,selectionKeyPressed:t,selectionMode:n=co.Full,panOnDrag:r,paneClickDistance:o,selectionOnDrag:s,onSelectionStart:a,onSelectionEnd:l,onPaneClick:c,onPaneContextMenu:E,onPaneScroll:d,onPaneMouseEnter:u,onPaneMouseMove:T,onPaneMouseLeave:S,children:h}){const A=Oe(),{userSelectionActive:R,elementsSelectable:p,dragging:N,connectionInProgress:I}=Re(Fv,Ie),O=p&&(e||R),m=f.useRef(null),C=f.useRef(),g=f.useRef(new Set),y=f.useRef(new Set),_=f.useRef(!1),P=v=>{if(_.current||I){_.current=!1;return}c==null||c(v),A.getState().resetSelectedElements(),A.setState({nodesSelectionActive:!1})},D=v=>{if(Array.isArray(r)&&(r!=null&&r.includes(2))){v.preventDefault();return}E==null||E(v)},b=d?v=>d(v):void 0,F=v=>{_.current&&(v.stopPropagation(),_.current=!1)},x=v=>{var $,z;const{domNode:L}=A.getState();if(C.current=L==null?void 0:L.getBoundingClientRect(),!C.current)return;const U=v.target===m.current;if(!U&&!!v.target.closest(".nokey")||!e||!(s&&U||t)||v.button!==0||!v.isPrimary)return;(z=($=v.target)==null?void 0:$.setPointerCapture)==null||z.call($,v.pointerId),_.current=!1;const{x:J,y:K}=at(v.nativeEvent,C.current);A.setState({userSelectionRect:{width:0,height:0,startX:J,startY:K,x:J,y:K}}),U||(v.stopPropagation(),v.preventDefault())},w=v=>{const{userSelectionRect:L,transform:U,nodeLookup:G,edgeLookup:k,connectionLookup:J,triggerNodeChanges:K,triggerEdgeChanges:$,defaultEdgeOptions:z,resetSelectedElements:q}=A.getState();if(!C.current||!L)return;const{x:X,y:Q}=at(v.nativeEvent,C.current),{startX:ae,startY:ne}=L;if(!_.current){const ue=t?0:o;if(Math.hypot(X-ae,Q-ne)<=ue)return;q(),a==null||a(v)}_.current=!0;const re={startX:ae,startY:ne,x:X<ae?X:ae,y:Q<ne?Q:ne,width:Math.abs(X-ae),height:Math.abs(Q-ne)},Y=g.current,se=y.current;g.current=new Set(EE(G,re,U,n===co.Partial,!0).map(ue=>ue.id)),y.current=new Set;const de=(z==null?void 0:z.selectable)??!0;for(const ue of g.current){const me=J.get(ue);if(me)for(const{edgeId:je}of me.values()){const ve=k.get(je);ve&&(ve.selectable??de)&&y.current.add(je)}}if(!Ru(Y,g.current)){const ue=Qn(G,g.current,!0);K(ue)}if(!Ru(se,y.current)){const ue=Qn(k,y.current);$(ue)}A.setState({userSelectionRect:re,userSelectionActive:!0,nodesSelectionActive:!1})},M=v=>{var L,U;v.button===0&&((U=(L=v.target)==null?void 0:L.releasePointerCapture)==null||U.call(L,v.pointerId),!R&&v.target===m.current&&A.getState().userSelectionRect&&(P==null||P(v)),A.setState({userSelectionActive:!1,userSelectionRect:null}),_.current&&(l==null||l(v),A.setState({nodesSelectionActive:g.current.size>0})))},B=r===!0||Array.isArray(r)&&r.includes(0);return i.jsxs("div",{className:xe(["react-flow__pane",{draggable:B,dragging:N,selection:e}]),onClick:O?void 0:qa(P,m),onContextMenu:qa(D,m),onWheel:qa(b,m),onPointerEnter:O?void 0:u,onPointerMove:O?w:T,onPointerUp:O?M:void 0,onPointerDownCapture:O?x:void 0,onClickCapture:O?F:void 0,onPointerLeave:S,ref:m,style:Zi,children:[h,i.jsx(Bv,{})]})}function Ec({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:o,unselectNodesAndEdges:s,multiSelectionActive:a,nodeLookup:l,onError:c}=t.getState(),E=l.get(e);if(!E){c==null||c("012",mt.error012(e));return}t.setState({nodesSelectionActive:!1}),E.selected?(n||E.selected&&a)&&(s({nodes:[E],edges:[]}),requestAnimationFrame(()=>{var d;return(d=r==null?void 0:r.current)==null?void 0:d.blur()})):o([e])}function fp({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:o,isSelectable:s,nodeClickDistance:a}){const l=Oe(),[c,E]=f.useState(!1),d=f.useRef();return f.useEffect(()=>{d.current=L1({getStoreItems:()=>l.getState(),onNodeMouseDown:u=>{Ec({id:u,store:l,nodeRef:e})},onDragStart:()=>{E(!0)},onDragStop:()=>{E(!1)}})},[]),f.useEffect(()=>{if(!(t||!e.current||!d.current))return d.current.update({noDragClassName:n,handleSelector:r,domNode:e.current,isSelectable:s,nodeId:o,nodeClickDistance:a}),()=>{var u;(u=d.current)==null||u.destroy()}},[n,r,t,s,e,o,a]),c}const Hv=e=>t=>t.selected&&(t.draggable||e&&typeof t.draggable>"u");function Rp(){const e=Oe();return f.useCallback(n=>{const{nodeExtent:r,snapToGrid:o,snapGrid:s,nodesDraggable:a,onError:l,updateNodePositions:c,nodeLookup:E,nodeOrigin:d}=e.getState(),u=new Map,T=Hv(a),S=o?s[0]:5,h=o?s[1]:5,A=n.direction.x*S*n.factor,R=n.direction.y*h*n.factor;for(const[,p]of E){if(!T(p))continue;let N={x:p.internals.positionAbsolute.x+A,y:p.internals.positionAbsolute.y+R};o&&(N=yo(N,s));const{position:I,positionAbsolute:O}=UA({nodeId:p.id,nextPosition:N,nodeLookup:E,nodeExtent:r,nodeOrigin:d,onError:l});p.position=I,p.internals.positionAbsolute=O,u.set(p.id,p)}c(u)},[])}const hE=f.createContext(null),kv=hE.Provider;hE.Consumer;const Ap=()=>f.useContext(hE),jv=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),Yv=(e,t,n)=>r=>{const{connectionClickStartHandle:o,connectionMode:s,connection:a}=r,{fromHandle:l,toHandle:c,isValid:E}=a,d=(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:d,clickConnecting:(o==null?void 0:o.nodeId)===e&&(o==null?void 0:o.id)===t&&(o==null?void 0:o.type)===n,isPossibleEndHandle:s===dr.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:!!o,valid:d&&E}};function Wv({type:e="source",position:t=te.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:o=!0,isConnectableEnd:s=!0,id:a,onConnect:l,children:c,className:E,onMouseDown:d,onTouchStart:u,...T},S){var w,M;const h=a||null,A=e==="target",R=Oe(),p=Ap(),{connectOnClick:N,noPanClassName:I,rfId:O}=Re(jv,Ie),{connectingFrom:m,connectingTo:C,clickConnecting:g,isPossibleEndHandle:y,connectionInProcess:_,clickConnectionInProcess:P,valid:D}=Re(Yv(p,h,e),Ie);p||(M=(w=R.getState()).onError)==null||M.call(w,"010",mt.error010());const b=B=>{const{defaultEdgeOptions:v,onConnect:L,hasDefaultEdges:U}=R.getState(),G={...v,...B};if(U){const{edges:k,setEdges:J}=R.getState();J(E1(G,k))}L==null||L(G),l==null||l(G)},F=B=>{if(!p)return;const v=YA(B.nativeEvent);if(o&&(v&&B.button===0||!v)){const L=R.getState();cc.onPointerDown(B.nativeEvent,{handleDomNode:B.currentTarget,autoPanOnConnect:L.autoPanOnConnect,connectionMode:L.connectionMode,connectionRadius:L.connectionRadius,domNode:L.domNode,nodeLookup:L.nodeLookup,lib:L.lib,isTarget:A,handleId:h,nodeId:p,flowId:L.rfId,panBy:L.panBy,cancelConnection:L.cancelConnection,onConnectStart:L.onConnectStart,onConnectEnd:(...U)=>{var G,k;return(k=(G=R.getState()).onConnectEnd)==null?void 0:k.call(G,...U)},updateConnection:L.updateConnection,onConnect:b,isValidConnection:n||((...U)=>{var G,k;return((k=(G=R.getState()).isValidConnection)==null?void 0:k.call(G,...U))??!0}),getTransform:()=>R.getState().transform,getFromHandle:()=>R.getState().connection.fromHandle,autoPanSpeed:L.autoPanSpeed,dragThreshold:L.connectionDragThreshold})}v?d==null||d(B):u==null||u(B)},x=B=>{const{onClickConnectStart:v,onClickConnectEnd:L,connectionClickStartHandle:U,connectionMode:G,isValidConnection:k,lib:J,rfId:K,nodeLookup:$,connection:z}=R.getState();if(!p||!U&&!o)return;if(!U){v==null||v(B.nativeEvent,{nodeId:p,handleId:h,handleType:e}),R.setState({connectionClickStartHandle:{nodeId:p,type:e,id:h}});return}const q=kA(B.target),X=n||k,{connection:Q,isValid:ae}=cc.isValid(B.nativeEvent,{handle:{nodeId:p,id:h,type:e},connectionMode:G,fromNodeId:U.nodeId,fromHandleId:U.id||null,fromType:U.type,isValidConnection:X,flowId:K,doc:q,lib:J,nodeLookup:$});ae&&Q&&b(Q);const ne=structuredClone(z);delete ne.inProgress,ne.toPosition=ne.toHandle?ne.toHandle.position:null,L==null||L(B,ne),R.setState({connectionClickStartHandle:null})};return i.jsx("div",{"data-handleid":h,"data-nodeid":p,"data-handlepos":t,"data-id":`${O}-${p}-${h}-${e}`,className:xe(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",I,E,{source:!A,target:A,connectable:r,connectablestart:o,connectableend:s,clickconnecting:g,connectingfrom:m,connectingto:C,valid:D,connectionindicator:r&&(!_||y)&&(_||P?s:o)}]),onMouseDown:F,onTouchStart:F,onClick:N?x:void 0,ref:S,...T,children:c})}const an=f.memo(Tp(Wv));function Vv({data:e,isConnectable:t,sourcePosition:n=te.Bottom}){return i.jsxs(i.Fragment,{children:[e==null?void 0:e.label,i.jsx(an,{type:"source",position:n,isConnectable:t})]})}function $v({data:e,isConnectable:t,targetPosition:n=te.Top,sourcePosition:r=te.Bottom}){return i.jsxs(i.Fragment,{children:[i.jsx(an,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,i.jsx(an,{type:"source",position:r,isConnectable:t})]})}function Xv(){return null}function Kv({data:e,isConnectable:t,targetPosition:n=te.Top}){return i.jsxs(i.Fragment,{children:[i.jsx(an,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label]})}const Ti={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},$u={input:Vv,default:$v,output:Kv,group:Xv};function zv(e){var t,n,r,o;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??((o=e.style)==null?void 0:o.height)}}const Jv=e=>{const{width:t,height:n,x:r,y:o}=xo(e.nodeLookup,{filter:s=>!!s.selected});return{width:it(t)?t:null,height:it(n)?n:null,userSelectionActive:e.userSelectionActive,transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]}) translate(${r}px,${o}px)`}};function qv({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=Oe(),{width:o,height:s,transformString:a,userSelectionActive:l}=Re(Jv,Ie),c=Rp(),E=f.useRef(null);f.useEffect(()=>{var S;n||(S=E.current)==null||S.focus({preventScroll:!0})},[n]);const d=!l&&o!==null&&s!==null;if(fp({nodeRef:E,disabled:!d}),!d)return null;const u=e?S=>{const h=r.getState().nodes.filter(A=>A.selected);e(S,h)}:void 0,T=S=>{Object.prototype.hasOwnProperty.call(Ti,S.key)&&(S.preventDefault(),c({direction:Ti[S.key],factor:S.shiftKey?4:1}))};return i.jsx("div",{className:xe(["react-flow__nodesselection","react-flow__container",t]),style:{transform:a},children:i.jsx("div",{ref:E,className:"react-flow__nodesselection-rect",onContextMenu:u,tabIndex:n?void 0:-1,onKeyDown:n?void 0:T,style:{width:o,height:s}})})}const Xu=typeof window<"u"?window:void 0,Qv=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function pp({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:s,onPaneScroll:a,paneClickDistance:l,deleteKeyCode:c,selectionKeyCode:E,selectionOnDrag:d,selectionMode:u,onSelectionStart:T,onSelectionEnd:S,multiSelectionKeyCode:h,panActivationKeyCode:A,zoomActivationKeyCode:R,elementsSelectable:p,zoomOnScroll:N,zoomOnPinch:I,panOnScroll:O,panOnScrollSpeed:m,panOnScrollMode:C,zoomOnDoubleClick:g,panOnDrag:y,defaultViewport:_,translateExtent:P,minZoom:D,maxZoom:b,preventScrolling:F,onSelectionContextMenu:x,noWheelClassName:w,noPanClassName:M,disableKeyboardA11y:B,onViewportChange:v,isControlledViewport:L}){const{nodesSelectionActive:U,userSelectionActive:G}=Re(Qv,Ie),k=To(E,{target:Xu}),J=To(A,{target:Xu}),K=J||y,$=J||O,z=d&&K!==!0,q=k||G||z;return Pv({deleteKeyCode:c,multiSelectionKeyCode:h}),i.jsx(Uv,{onPaneContextMenu:s,elementsSelectable:p,zoomOnScroll:N,zoomOnPinch:I,panOnScroll:$,panOnScrollSpeed:m,panOnScrollMode:C,zoomOnDoubleClick:g,panOnDrag:!k&&K,defaultViewport:_,translateExtent:P,minZoom:D,maxZoom:b,zoomActivationKeyCode:R,preventScrolling:F,noWheelClassName:w,noPanClassName:M,onViewportChange:v,isControlledViewport:L,paneClickDistance:l,selectionOnDrag:z,children:i.jsxs(Gv,{onSelectionStart:T,onSelectionEnd:S,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:s,onPaneScroll:a,panOnDrag:K,isSelecting:!!q,selectionMode:u,selectionKeyPressed:k,paneClickDistance:l,selectionOnDrag:z,children:[e,U&&i.jsx(qv,{onSelectionContextMenu:x,noPanClassName:M,disableKeyboardA11y:B})]})})}pp.displayName="FlowRenderer";const Zv=f.memo(pp),eU=e=>t=>e?EE(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 tU(e){return Re(f.useCallback(eU(e),[e]),Ie)}const nU=e=>e.updateNodeInternals;function rU(){const e=Re(nU),[t]=f.useState(()=>typeof ResizeObserver>"u"?null:new ResizeObserver(n=>{const r=new Map;n.forEach(o=>{const s=o.target.getAttribute("data-id");r.set(s,{id:s,nodeElement:o.target,force:!0})}),e(r)}));return f.useEffect(()=>()=>{t==null||t.disconnect()},[t]),t}function oU({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){const o=Oe(),s=f.useRef(null),a=f.useRef(null),l=f.useRef(e.sourcePosition),c=f.useRef(e.targetPosition),E=f.useRef(t),d=n&&!!e.internals.handleBounds;return f.useEffect(()=>{s.current&&!e.hidden&&(!d||a.current!==s.current)&&(a.current&&(r==null||r.unobserve(a.current)),r==null||r.observe(s.current),a.current=s.current)},[d,e.hidden]),f.useEffect(()=>()=>{a.current&&(r==null||r.unobserve(a.current),a.current=null)},[]),f.useEffect(()=>{if(s.current){const u=E.current!==t,T=l.current!==e.sourcePosition,S=c.current!==e.targetPosition;(u||T||S)&&(E.current=t,l.current=e.sourcePosition,c.current=e.targetPosition,o.getState().updateNodeInternals(new Map([[e.id,{id:e.id,nodeElement:s.current,force:!0}]])))}},[e.id,t,e.sourcePosition,e.targetPosition]),s}function sU({id:e,onClick:t,onMouseEnter:n,onMouseMove:r,onMouseLeave:o,onContextMenu:s,onDoubleClick:a,nodesDraggable:l,elementsSelectable:c,nodesConnectable:E,nodesFocusable:d,resizeObserver:u,noDragClassName:T,noPanClassName:S,disableKeyboardA11y:h,rfId:A,nodeTypes:R,nodeClickDistance:p,onError:N}){const{node:I,internals:O,isParent:m}=Re(X=>{const Q=X.nodeLookup.get(e),ae=X.parentLookup.has(e);return{node:Q,internals:Q.internals,isParent:ae}},Ie);let C=I.type||"default",g=(R==null?void 0:R[C])||$u[C];g===void 0&&(N==null||N("003",mt.error003(C)),C="default",g=(R==null?void 0:R.default)||$u.default);const y=!!(I.draggable||l&&typeof I.draggable>"u"),_=!!(I.selectable||c&&typeof I.selectable>"u"),P=!!(I.connectable||E&&typeof I.connectable>"u"),D=!!(I.focusable||d&&typeof I.focusable>"u"),b=Oe(),F=GA(I),x=oU({node:I,nodeType:C,hasDimensions:F,resizeObserver:u}),w=fp({nodeRef:x,disabled:I.hidden||!y,noDragClassName:T,handleSelector:I.dragHandle,nodeId:e,isSelectable:_,nodeClickDistance:p}),M=Rp();if(I.hidden)return null;const B=Ht(I),v=zv(I),L=_||y||t||n||r||o,U=n?X=>n(X,{...O.userNode}):void 0,G=r?X=>r(X,{...O.userNode}):void 0,k=o?X=>o(X,{...O.userNode}):void 0,J=s?X=>s(X,{...O.userNode}):void 0,K=a?X=>a(X,{...O.userNode}):void 0,$=X=>{const{selectNodesOnDrag:Q,nodeDragThreshold:ae}=b.getState();_&&(!Q||!y||ae>0)&&Ec({id:e,store:b,nodeRef:x}),t&&t(X,{...O.userNode})},z=X=>{if(!(jA(X.nativeEvent)||h)){if(DA.includes(X.key)&&_){const Q=X.key==="Escape";Ec({id:e,store:b,unselect:Q,nodeRef:x})}else if(y&&I.selected&&Object.prototype.hasOwnProperty.call(Ti,X.key)){X.preventDefault();const{ariaLabelConfig:Q}=b.getState();b.setState({ariaLiveMessage:Q["node.a11yDescription.ariaLiveMessage"]({direction:X.key.replace("Arrow","").toLowerCase(),x:~~O.positionAbsolute.x,y:~~O.positionAbsolute.y})}),M({direction:Ti[X.key],factor:X.shiftKey?4:1})}}},q=()=>{var se;if(h||!((se=x.current)!=null&&se.matches(":focus-visible")))return;const{transform:X,width:Q,height:ae,autoPanOnNodeFocus:ne,setCenter:re}=b.getState();if(!ne)return;EE(new Map([[e,I]]),{x:0,y:0,width:Q,height:ae},X,!0).length>0||re(I.position.x+B.width/2,I.position.y+B.height/2,{zoom:X[2]})};return i.jsx("div",{className:xe(["react-flow__node",`react-flow__node-${C}`,{[S]:y},I.className,{selected:I.selected,selectable:_,parent:m,draggable:y,dragging:w}]),ref:x,style:{zIndex:O.z,transform:`translate(${O.positionAbsolute.x}px,${O.positionAbsolute.y}px)`,pointerEvents:L?"all":"none",visibility:F?"visible":"hidden",...I.style,...v},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:U,onMouseMove:G,onMouseLeave:k,onContextMenu:J,onClick:$,onDoubleClick:K,onKeyDown:D?z:void 0,tabIndex:D?0:void 0,onFocus:D?q:void 0,role:I.ariaRole??(D?"group":void 0),"aria-roledescription":"node","aria-describedby":h?void 0:`${ap}-${A}`,"aria-label":I.ariaLabel,...I.domAttributes,children:i.jsx(kv,{value:e,children:i.jsx(g,{id:e,data:I.data,type:C,positionAbsoluteX:O.positionAbsolute.x,positionAbsoluteY:O.positionAbsolute.y,selected:I.selected??!1,selectable:_,draggable:y,deletable:I.deletable??!0,isConnectable:P,sourcePosition:I.sourcePosition,targetPosition:I.targetPosition,dragging:w,dragHandle:I.dragHandle,zIndex:O.z,parentId:I.parentId,...B})})})}var iU=f.memo(sU);const aU=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function hp(e){const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:o,onError:s}=Re(aU,Ie),a=tU(e.onlyRenderVisibleElements),l=rU();return i.jsx("div",{className:"react-flow__nodes",style:Zi,children:a.map(c=>i.jsx(iU,{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:o,nodeClickDistance:e.nodeClickDistance,onError:s},c))})}hp.displayName="NodeRenderer";const lU=f.memo(hp);function cU(e){return Re(f.useCallback(n=>{if(!e)return n.edges.map(o=>o.id);const r=[];if(n.width&&n.height)for(const o of n.edges){const s=n.nodeLookup.get(o.source),a=n.nodeLookup.get(o.target);s&&a&&a1({sourceNode:s,targetNode:a,width:n.width,height:n.height,transform:n.transform})&&r.push(o.id)}return r},[e]),Ie)}const EU=({color:e="none",strokeWidth:t=1})=>{const n={strokeWidth:t,...e&&{stroke:e}};return i.jsx("polyline",{className:"arrow",style:n,strokeLinecap:"round",fill:"none",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4"})},dU=({color:e="none",strokeWidth:t=1})=>{const n={strokeWidth:t,...e&&{stroke:e,fill:e}};return i.jsx("polyline",{className:"arrowclosed",style:n,strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"})},Ku={[ur.Arrow]:EU,[ur.ArrowClosed]:dU};function uU(e){const t=Oe();return f.useMemo(()=>{var o,s;return Object.prototype.hasOwnProperty.call(Ku,e)?Ku[e]:((s=(o=t.getState()).onError)==null||s.call(o,"009",mt.error009(e)),null)},[e])}const TU=({id:e,type:t,color:n,width:r=12.5,height:o=12.5,markerUnits:s="strokeWidth",strokeWidth:a,orient:l="auto-start-reverse"})=>{const c=uU(t);return c?i.jsx("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${r}`,markerHeight:`${o}`,viewBox:"-10 -10 20 20",markerUnits:s,orient:l,refX:"0",refY:"0",children:i.jsx(c,{color:n,strokeWidth:a})}):null},Ip=({defaultColor:e,rfId:t})=>{const n=Re(s=>s.edges),r=Re(s=>s.defaultEdgeOptions),o=f.useMemo(()=>f1(n,{id:t,defaultColor:e,defaultMarkerStart:r==null?void 0:r.markerStart,defaultMarkerEnd:r==null?void 0:r.markerEnd}),[n,r,t,e]);return o.length?i.jsx("svg",{className:"react-flow__marker","aria-hidden":"true",children:i.jsx("defs",{children:o.map(s=>i.jsx(TU,{id:s.id,type:s.type,color:s.color,width:s.width,height:s.height,markerUnits:s.markerUnits,strokeWidth:s.strokeWidth,orient:s.orient},s.id))})}):null};Ip.displayName="MarkerDefinitions";var SU=f.memo(Ip);function Np({x:e,y:t,label:n,labelStyle:r,labelShowBg:o=!0,labelBgStyle:s,labelBgPadding:a=[2,4],labelBgBorderRadius:l=2,children:c,className:E,...d}){const[u,T]=f.useState({x:1,y:0,width:0,height:0}),S=xe(["react-flow__edge-textwrapper",E]),h=f.useRef(null);return f.useEffect(()=>{if(h.current){const A=h.current.getBBox();T({x:A.x,y:A.y,width:A.width,height:A.height})}},[n]),n?i.jsxs("g",{transform:`translate(${e-u.width/2} ${t-u.height/2})`,className:S,visibility:u.width?"visible":"hidden",...d,children:[o&&i.jsx("rect",{width:u.width+2*a[0],x:-a[0],y:-a[1],height:u.height+2*a[1],className:"react-flow__edge-textbg",style:s,rx:l,ry:l}),i.jsx("text",{className:"react-flow__edge-text",y:u.height/2,dy:"0.3em",ref:h,style:r,children:n}),c]}):null}Np.displayName="EdgeText";const fU=f.memo(Np);function ea({path:e,labelX:t,labelY:n,label:r,labelStyle:o,labelShowBg:s,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c,interactionWidth:E=20,...d}){return i.jsxs(i.Fragment,{children:[i.jsx("path",{...d,d:e,fill:"none",className:xe(["react-flow__edge-path",d.className])}),E?i.jsx("path",{d:e,fill:"none",strokeOpacity:0,strokeWidth:E,className:"react-flow__edge-interaction"}):null,r&&it(t)&&it(n)?i.jsx(fU,{x:t,y:n,label:r,labelStyle:o,labelShowBg:s,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c}):null]})}function zu({pos:e,x1:t,y1:n,x2:r,y2:o}){return e===te.Left||e===te.Right?[.5*(t+r),n]:[t,.5*(n+o)]}function Op({sourceX:e,sourceY:t,sourcePosition:n=te.Bottom,targetX:r,targetY:o,targetPosition:s=te.Top}){const[a,l]=zu({pos:n,x1:e,y1:t,x2:r,y2:o}),[c,E]=zu({pos:s,x1:r,y1:o,x2:e,y2:t}),[d,u,T,S]=WA({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:a,sourceControlY:l,targetControlX:c,targetControlY:E});return[`M${e},${t} C${a},${l} ${c},${E} ${r},${o}`,d,u,T,S]}function mp(e){return f.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,sourcePosition:a,targetPosition:l,label:c,labelStyle:E,labelShowBg:d,labelBgStyle:u,labelBgPadding:T,labelBgBorderRadius:S,style:h,markerEnd:A,markerStart:R,interactionWidth:p})=>{const[N,I,O]=Op({sourceX:n,sourceY:r,sourcePosition:a,targetX:o,targetY:s,targetPosition:l}),m=e.isInternal?void 0:t;return i.jsx(ea,{id:m,path:N,labelX:I,labelY:O,label:c,labelStyle:E,labelShowBg:d,labelBgStyle:u,labelBgPadding:T,labelBgBorderRadius:S,style:h,markerEnd:A,markerStart:R,interactionWidth:p})})}const RU=mp({isInternal:!1}),Cp=mp({isInternal:!0});RU.displayName="SimpleBezierEdge";Cp.displayName="SimpleBezierEdgeInternal";function gp(e){return f.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:E,labelBgPadding:d,labelBgBorderRadius:u,style:T,sourcePosition:S=te.Bottom,targetPosition:h=te.Top,markerEnd:A,markerStart:R,pathOptions:p,interactionWidth:N})=>{const[I,O,m]=ic({sourceX:n,sourceY:r,sourcePosition:S,targetX:o,targetY:s,targetPosition:h,borderRadius:p==null?void 0:p.borderRadius,offset:p==null?void 0:p.offset,stepPosition:p==null?void 0:p.stepPosition}),C=e.isInternal?void 0:t;return i.jsx(ea,{id:C,path:I,labelX:O,labelY:m,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:E,labelBgPadding:d,labelBgBorderRadius:u,style:T,markerEnd:A,markerStart:R,interactionWidth:N})})}const Lp=gp({isInternal:!1}),_p=gp({isInternal:!0});Lp.displayName="SmoothStepEdge";_p.displayName="SmoothStepEdgeInternal";function xp(e){return f.memo(({id:t,...n})=>{var o;const r=e.isInternal?void 0:t;return i.jsx(Lp,{...n,id:r,pathOptions:f.useMemo(()=>{var s;return{borderRadius:0,offset:(s=n.pathOptions)==null?void 0:s.offset}},[(o=n.pathOptions)==null?void 0:o.offset])})})}const AU=xp({isInternal:!1}),yp=xp({isInternal:!0});AU.displayName="StepEdge";yp.displayName="StepEdgeInternal";function Dp(e){return f.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:E,labelBgPadding:d,labelBgBorderRadius:u,style:T,markerEnd:S,markerStart:h,interactionWidth:A})=>{const[R,p,N]=XA({sourceX:n,sourceY:r,targetX:o,targetY:s}),I=e.isInternal?void 0:t;return i.jsx(ea,{id:I,path:R,labelX:p,labelY:N,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:E,labelBgPadding:d,labelBgBorderRadius:u,style:T,markerEnd:S,markerStart:h,interactionWidth:A})})}const pU=Dp({isInternal:!1}),Mp=Dp({isInternal:!0});pU.displayName="StraightEdge";Mp.displayName="StraightEdgeInternal";function Pp(e){return f.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,sourcePosition:a=te.Bottom,targetPosition:l=te.Top,label:c,labelStyle:E,labelShowBg:d,labelBgStyle:u,labelBgPadding:T,labelBgBorderRadius:S,style:h,markerEnd:A,markerStart:R,pathOptions:p,interactionWidth:N})=>{const[I,O,m]=VA({sourceX:n,sourceY:r,sourcePosition:a,targetX:o,targetY:s,targetPosition:l,curvature:p==null?void 0:p.curvature}),C=e.isInternal?void 0:t;return i.jsx(ea,{id:C,path:I,labelX:O,labelY:m,label:c,labelStyle:E,labelShowBg:d,labelBgStyle:u,labelBgPadding:T,labelBgBorderRadius:S,style:h,markerEnd:A,markerStart:R,interactionWidth:N})})}const hU=Pp({isInternal:!1}),bp=Pp({isInternal:!0});hU.displayName="BezierEdge";bp.displayName="BezierEdgeInternal";const Ju={default:bp,straight:Mp,step:yp,smoothstep:_p,simplebezier:Cp},qu={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},IU=(e,t,n)=>n===te.Left?e-t:n===te.Right?e+t:e,NU=(e,t,n)=>n===te.Top?e-t:n===te.Bottom?e+t:e,Qu="react-flow__edgeupdater";function Zu({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:o,onMouseEnter:s,onMouseOut:a,type:l}){return i.jsx("circle",{onMouseDown:o,onMouseEnter:s,onMouseOut:a,className:xe([Qu,`${Qu}-${l}`]),cx:IU(t,r,e),cy:NU(n,r,e),r,stroke:"transparent",fill:"transparent"})}function OU({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:r,sourceY:o,targetX:s,targetY:a,sourcePosition:l,targetPosition:c,onReconnect:E,onReconnectStart:d,onReconnectEnd:u,setReconnecting:T,setUpdateHover:S}){const h=Oe(),A=(O,m)=>{if(O.button!==0)return;const{autoPanOnConnect:C,domNode:g,connectionMode:y,connectionRadius:_,lib:P,onConnectStart:D,cancelConnection:b,nodeLookup:F,rfId:x,panBy:w,updateConnection:M}=h.getState(),B=m.type==="target",v=(G,k)=>{T(!1),u==null||u(G,n,m.type,k)},L=G=>E==null?void 0:E(n,G),U=(G,k)=>{T(!0),d==null||d(O,n,m.type),D==null||D(G,k)};cc.onPointerDown(O.nativeEvent,{autoPanOnConnect:C,connectionMode:y,connectionRadius:_,domNode:g,handleId:m.id,nodeId:m.nodeId,nodeLookup:F,isTarget:B,edgeUpdaterType:m.type,lib:P,flowId:x,cancelConnection:b,panBy:w,isValidConnection:(...G)=>{var k,J;return((J=(k=h.getState()).isValidConnection)==null?void 0:J.call(k,...G))??!0},onConnect:L,onConnectStart:U,onConnectEnd:(...G)=>{var k,J;return(J=(k=h.getState()).onConnectEnd)==null?void 0:J.call(k,...G)},onReconnectEnd:v,updateConnection:M,getTransform:()=>h.getState().transform,getFromHandle:()=>h.getState().connection.fromHandle,dragThreshold:h.getState().connectionDragThreshold,handleDomNode:O.currentTarget})},R=O=>A(O,{nodeId:n.target,id:n.targetHandle??null,type:"target"}),p=O=>A(O,{nodeId:n.source,id:n.sourceHandle??null,type:"source"}),N=()=>S(!0),I=()=>S(!1);return i.jsxs(i.Fragment,{children:[(e===!0||e==="source")&&i.jsx(Zu,{position:l,centerX:r,centerY:o,radius:t,onMouseDown:R,onMouseEnter:N,onMouseOut:I,type:"source"}),(e===!0||e==="target")&&i.jsx(Zu,{position:c,centerX:s,centerY:a,radius:t,onMouseDown:p,onMouseEnter:N,onMouseOut:I,type:"target"})]})}function mU({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:r,onClick:o,onDoubleClick:s,onContextMenu:a,onMouseEnter:l,onMouseMove:c,onMouseLeave:E,reconnectRadius:d,onReconnect:u,onReconnectStart:T,onReconnectEnd:S,rfId:h,edgeTypes:A,noPanClassName:R,onError:p,disableKeyboardA11y:N}){let I=Re(re=>re.edgeLookup.get(e));const O=Re(re=>re.defaultEdgeOptions);I=O?{...O,...I}:I;let m=I.type||"default",C=(A==null?void 0:A[m])||Ju[m];C===void 0&&(p==null||p("011",mt.error011(m)),m="default",C=(A==null?void 0:A.default)||Ju.default);const g=!!(I.focusable||t&&typeof I.focusable>"u"),y=typeof u<"u"&&(I.reconnectable||n&&typeof I.reconnectable>"u"),_=!!(I.selectable||r&&typeof I.selectable>"u"),P=f.useRef(null),[D,b]=f.useState(!1),[F,x]=f.useState(!1),w=Oe(),{zIndex:M,sourceX:B,sourceY:v,targetX:L,targetY:U,sourcePosition:G,targetPosition:k}=Re(f.useCallback(re=>{const Y=re.nodeLookup.get(I.source),se=re.nodeLookup.get(I.target);if(!Y||!se)return{zIndex:I.zIndex,...qu};const de=S1({id:e,sourceNode:Y,targetNode:se,sourceHandle:I.sourceHandle||null,targetHandle:I.targetHandle||null,connectionMode:re.connectionMode,onError:p});return{zIndex:i1({selected:I.selected,zIndex:I.zIndex,sourceNode:Y,targetNode:se,elevateOnSelect:re.elevateEdgesOnSelect,zIndexMode:re.zIndexMode}),...de||qu}},[I.source,I.target,I.sourceHandle,I.targetHandle,I.selected,I.zIndex]),Ie),J=f.useMemo(()=>I.markerStart?`url('#${ac(I.markerStart,h)}')`:void 0,[I.markerStart,h]),K=f.useMemo(()=>I.markerEnd?`url('#${ac(I.markerEnd,h)}')`:void 0,[I.markerEnd,h]);if(I.hidden||B===null||v===null||L===null||U===null)return null;const $=re=>{var ue;const{addSelectedEdges:Y,unselectNodesAndEdges:se,multiSelectionActive:de}=w.getState();_&&(w.setState({nodesSelectionActive:!1}),I.selected&&de?(se({nodes:[],edges:[I]}),(ue=P.current)==null||ue.blur()):Y([e])),o&&o(re,I)},z=s?re=>{s(re,{...I})}:void 0,q=a?re=>{a(re,{...I})}:void 0,X=l?re=>{l(re,{...I})}:void 0,Q=c?re=>{c(re,{...I})}:void 0,ae=E?re=>{E(re,{...I})}:void 0,ne=re=>{var Y;if(!N&&DA.includes(re.key)&&_){const{unselectNodesAndEdges:se,addSelectedEdges:de}=w.getState();re.key==="Escape"?((Y=P.current)==null||Y.blur(),se({edges:[I]})):de([e])}};return i.jsx("svg",{style:{zIndex:M},children:i.jsxs("g",{className:xe(["react-flow__edge",`react-flow__edge-${m}`,I.className,R,{selected:I.selected,animated:I.animated,inactive:!_&&!o,updating:D,selectable:_}]),onClick:$,onDoubleClick:z,onContextMenu:q,onMouseEnter:X,onMouseMove:Q,onMouseLeave:ae,onKeyDown:g?ne:void 0,tabIndex:g?0:void 0,role:I.ariaRole??(g?"group":"img"),"aria-roledescription":"edge","data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":I.ariaLabel===null?void 0:I.ariaLabel||`Edge from ${I.source} to ${I.target}`,"aria-describedby":g?`${lp}-${h}`:void 0,ref:P,...I.domAttributes,children:[!F&&i.jsx(C,{id:e,source:I.source,target:I.target,type:I.type,selected:I.selected,animated:I.animated,selectable:_,deletable:I.deletable??!0,label:I.label,labelStyle:I.labelStyle,labelShowBg:I.labelShowBg,labelBgStyle:I.labelBgStyle,labelBgPadding:I.labelBgPadding,labelBgBorderRadius:I.labelBgBorderRadius,sourceX:B,sourceY:v,targetX:L,targetY:U,sourcePosition:G,targetPosition:k,data:I.data,style:I.style,sourceHandleId:I.sourceHandle,targetHandleId:I.targetHandle,markerStart:J,markerEnd:K,pathOptions:"pathOptions"in I?I.pathOptions:void 0,interactionWidth:I.interactionWidth}),y&&i.jsx(OU,{edge:I,isReconnectable:y,reconnectRadius:d,onReconnect:u,onReconnectStart:T,onReconnectEnd:S,sourceX:B,sourceY:v,targetX:L,targetY:U,sourcePosition:G,targetPosition:k,setUpdateHover:b,setReconnecting:x})]})})}var CU=f.memo(mU);const gU=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function vp({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:r,noPanClassName:o,onReconnect:s,onEdgeContextMenu:a,onEdgeMouseEnter:l,onEdgeMouseMove:c,onEdgeMouseLeave:E,onEdgeClick:d,reconnectRadius:u,onEdgeDoubleClick:T,onReconnectStart:S,onReconnectEnd:h,disableKeyboardA11y:A}){const{edgesFocusable:R,edgesReconnectable:p,elementsSelectable:N,onError:I}=Re(gU,Ie),O=cU(t);return i.jsxs("div",{className:"react-flow__edges",children:[i.jsx(SU,{defaultColor:e,rfId:n}),O.map(m=>i.jsx(CU,{id:m,edgesFocusable:R,edgesReconnectable:p,elementsSelectable:N,noPanClassName:o,onReconnect:s,onContextMenu:a,onMouseEnter:l,onMouseMove:c,onMouseLeave:E,onClick:d,reconnectRadius:u,onDoubleClick:T,onReconnectStart:S,onReconnectEnd:h,rfId:n,onError:I,edgeTypes:r,disableKeyboardA11y:A},m))]})}vp.displayName="EdgeRenderer";const LU=f.memo(vp),_U=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function xU({children:e}){const t=Re(_U);return i.jsx("div",{className:"react-flow__viewport xyflow__viewport react-flow__container",style:{transform:t},children:e})}function yU(e){const t=pE(),n=f.useRef(!1);f.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const DU=e=>{var t;return(t=e.panZoom)==null?void 0:t.syncViewport};function MU(e){const t=Re(DU),n=Oe();return f.useEffect(()=>{e&&(t==null||t(e),n.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function PU(e){return e.connection.inProgress?{...e.connection,to:Do(e.connection.to,e.transform)}:{...e.connection}}function bU(e){return PU}function vU(e){const t=bU();return Re(t,Ie)}const UU=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function wU({containerStyle:e,style:t,type:n,component:r}){const{nodesConnectable:o,width:s,height:a,isValid:l,inProgress:c}=Re(UU,Ie);return!(s&&o&&c)?null:i.jsx("svg",{style:e,width:s,height:a,className:"react-flow__connectionline react-flow__container",children:i.jsx("g",{className:xe(["react-flow__connection",bA(l)]),children:i.jsx(Up,{style:t,type:n,CustomComponent:r,isValid:l})})})}const Up=({style:e,type:t=qt.Bezier,CustomComponent:n,isValid:r})=>{const{inProgress:o,from:s,fromNode:a,fromHandle:l,fromPosition:c,to:E,toNode:d,toHandle:u,toPosition:T,pointer:S}=vU();if(!o)return;if(n)return i.jsx(n,{connectionLineType:t,connectionLineStyle:e,fromNode:a,fromHandle:l,fromX:s.x,fromY:s.y,toX:E.x,toY:E.y,fromPosition:c,toPosition:T,connectionStatus:bA(r),toNode:d,toHandle:u,pointer:S});let h="";const A={sourceX:s.x,sourceY:s.y,sourcePosition:c,targetX:E.x,targetY:E.y,targetPosition:T};switch(t){case qt.Bezier:[h]=VA(A);break;case qt.SimpleBezier:[h]=Op(A);break;case qt.Step:[h]=ic({...A,borderRadius:0});break;case qt.SmoothStep:[h]=ic(A);break;default:[h]=XA(A)}return i.jsx("path",{d:h,fill:"none",className:"react-flow__connection-path",style:e})};Up.displayName="ConnectionLine";const BU={};function eT(e=BU){f.useRef(e),Oe(),f.useEffect(()=>{},[e])}function FU(){Oe(),f.useRef(!1),f.useEffect(()=>{},[])}function wp({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:r,onEdgeClick:o,onNodeDoubleClick:s,onEdgeDoubleClick:a,onNodeMouseEnter:l,onNodeMouseMove:c,onNodeMouseLeave:E,onNodeContextMenu:d,onSelectionContextMenu:u,onSelectionStart:T,onSelectionEnd:S,connectionLineType:h,connectionLineStyle:A,connectionLineComponent:R,connectionLineContainerStyle:p,selectionKeyCode:N,selectionOnDrag:I,selectionMode:O,multiSelectionKeyCode:m,panActivationKeyCode:C,zoomActivationKeyCode:g,deleteKeyCode:y,onlyRenderVisibleElements:_,elementsSelectable:P,defaultViewport:D,translateExtent:b,minZoom:F,maxZoom:x,preventScrolling:w,defaultMarkerColor:M,zoomOnScroll:B,zoomOnPinch:v,panOnScroll:L,panOnScrollSpeed:U,panOnScrollMode:G,zoomOnDoubleClick:k,panOnDrag:J,onPaneClick:K,onPaneMouseEnter:$,onPaneMouseMove:z,onPaneMouseLeave:q,onPaneScroll:X,onPaneContextMenu:Q,paneClickDistance:ae,nodeClickDistance:ne,onEdgeContextMenu:re,onEdgeMouseEnter:Y,onEdgeMouseMove:se,onEdgeMouseLeave:de,reconnectRadius:ue,onReconnect:me,onReconnectStart:je,onReconnectEnd:ve,noDragClassName:St,noWheelClassName:Tn,noPanClassName:kt,disableKeyboardA11y:Bn,nodeExtent:Po,rfId:jt,viewport:Lt,onViewportChange:Yt}){return eT(e),eT(t),FU(),yU(n),MU(Lt),i.jsx(Zv,{onPaneClick:K,onPaneMouseEnter:$,onPaneMouseMove:z,onPaneMouseLeave:q,onPaneContextMenu:Q,onPaneScroll:X,paneClickDistance:ae,deleteKeyCode:y,selectionKeyCode:N,selectionOnDrag:I,selectionMode:O,onSelectionStart:T,onSelectionEnd:S,multiSelectionKeyCode:m,panActivationKeyCode:C,zoomActivationKeyCode:g,elementsSelectable:P,zoomOnScroll:B,zoomOnPinch:v,zoomOnDoubleClick:k,panOnScroll:L,panOnScrollSpeed:U,panOnScrollMode:G,panOnDrag:J,defaultViewport:D,translateExtent:b,minZoom:F,maxZoom:x,onSelectionContextMenu:u,preventScrolling:w,noDragClassName:St,noWheelClassName:Tn,noPanClassName:kt,disableKeyboardA11y:Bn,onViewportChange:Yt,isControlledViewport:!!Lt,children:i.jsxs(xU,{children:[i.jsx(LU,{edgeTypes:t,onEdgeClick:o,onEdgeDoubleClick:a,onReconnect:me,onReconnectStart:je,onReconnectEnd:ve,onlyRenderVisibleElements:_,onEdgeContextMenu:re,onEdgeMouseEnter:Y,onEdgeMouseMove:se,onEdgeMouseLeave:de,reconnectRadius:ue,defaultMarkerColor:M,noPanClassName:kt,disableKeyboardA11y:Bn,rfId:jt}),i.jsx(wU,{style:A,type:h,component:R,containerStyle:p}),i.jsx("div",{className:"react-flow__edgelabel-renderer"}),i.jsx(lU,{nodeTypes:e,onNodeClick:r,onNodeDoubleClick:s,onNodeMouseEnter:l,onNodeMouseMove:c,onNodeMouseLeave:E,onNodeContextMenu:d,nodeClickDistance:ne,onlyRenderVisibleElements:_,noPanClassName:kt,noDragClassName:St,disableKeyboardA11y:Bn,nodeExtent:Po,rfId:jt}),i.jsx("div",{className:"react-flow__viewport-portal"})]})})}wp.displayName="GraphView";const GU=f.memo(wp),tT=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:s,fitView:a,fitViewOptions:l,minZoom:c=.5,maxZoom:E=2,nodeOrigin:d,nodeExtent:u,zIndexMode:T="basic"}={})=>{const S=new Map,h=new Map,A=new Map,R=new Map,p=r??t??[],N=n??e??[],I=d??[0,0],O=u??lo;JA(A,R,p);const m=lc(N,S,h,{nodeOrigin:I,nodeExtent:O,zIndexMode:T});let C=[0,0,1];if(a&&o&&s){const g=xo(S,{filter:D=>!!((D.width||D.initialWidth)&&(D.height||D.initialHeight))}),{x:y,y:_,zoom:P}=dE(g,o,s,c,E,(l==null?void 0:l.padding)??.1);C=[y,_,P]}return{rfId:"1",width:o??0,height:s??0,transform:C,nodes:N,nodesInitialized:m,nodeLookup:S,parentLookup:h,edges:p,edgeLookup:R,connectionLookup:A,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:n!==void 0,hasDefaultEdges:r!==void 0,panZoom:null,minZoom:c,maxZoom:E,translateExtent:lo,nodeExtent:O,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:dr.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:I,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:{...PA},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:e1,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:"react",debug:!1,ariaLabelConfig:MA,zIndexMode:T,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}},HU=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:s,fitView:a,fitViewOptions:l,minZoom:c,maxZoom:E,nodeOrigin:d,nodeExtent:u,zIndexMode:T})=>ov((S,h)=>{async function A(){const{nodeLookup:R,panZoom:p,fitViewOptions:N,fitViewResolver:I,width:O,height:m,minZoom:C,maxZoom:g}=h();p&&(await Qb({nodes:R,width:O,height:m,panZoom:p,minZoom:C,maxZoom:g},N),I==null||I.resolve(!0),S({fitViewResolver:null}))}return{...tT({nodes:e,edges:t,width:o,height:s,fitView:a,fitViewOptions:l,minZoom:c,maxZoom:E,nodeOrigin:d,nodeExtent:u,defaultNodes:n,defaultEdges:r,zIndexMode:T}),setNodes:R=>{const{nodeLookup:p,parentLookup:N,nodeOrigin:I,elevateNodesOnSelect:O,fitViewQueued:m,zIndexMode:C}=h(),g=lc(R,p,N,{nodeOrigin:I,nodeExtent:u,elevateNodesOnSelect:O,checkEquality:!0,zIndexMode:C});m&&g?(A(),S({nodes:R,nodesInitialized:g,fitViewQueued:!1,fitViewOptions:void 0})):S({nodes:R,nodesInitialized:g})},setEdges:R=>{const{connectionLookup:p,edgeLookup:N}=h();JA(p,N,R),S({edges:R})},setDefaultNodesAndEdges:(R,p)=>{if(R){const{setNodes:N}=h();N(R),S({hasDefaultNodes:!0})}if(p){const{setEdges:N}=h();N(p),S({hasDefaultEdges:!0})}},updateNodeInternals:R=>{const{triggerNodeChanges:p,nodeLookup:N,parentLookup:I,domNode:O,nodeOrigin:m,nodeExtent:C,debug:g,fitViewQueued:y,zIndexMode:_}=h(),{changes:P,updatedInternals:D}=O1(R,N,I,O,m,C,_);D&&(p1(N,I,{nodeOrigin:m,nodeExtent:C,zIndexMode:_}),y?(A(),S({fitViewQueued:!1,fitViewOptions:void 0})):S({}),(P==null?void 0:P.length)>0&&(g&&console.log("React Flow: trigger node changes",P),p==null||p(P)))},updateNodePositions:(R,p=!1)=>{const N=[];let I=[];const{nodeLookup:O,triggerNodeChanges:m,connection:C,updateConnection:g,onNodesChangeMiddlewareMap:y}=h();for(const[_,P]of R){const D=O.get(_),b=!!(D!=null&&D.expandParent&&(D!=null&&D.parentId)&&(P!=null&&P.position)),F={id:_,type:"position",position:b?{x:Math.max(0,P.position.x),y:Math.max(0,P.position.y)}:P.position,dragging:p};if(D&&C.inProgress&&C.fromNode.id===D.id){const x=Dn(D,C.fromHandle,te.Left,!0);g({...C,from:x})}b&&D.parentId&&N.push({id:_,parentId:D.parentId,rect:{...P.internals.positionAbsolute,width:P.measured.width??0,height:P.measured.height??0}}),I.push(F)}if(N.length>0){const{parentLookup:_,nodeOrigin:P}=h(),D=AE(N,O,_,P);I.push(...D)}for(const _ of y.values())I=_(I);m(I)},triggerNodeChanges:R=>{const{onNodesChange:p,setNodes:N,nodes:I,hasDefaultNodes:O,debug:m}=h();if(R!=null&&R.length){if(O){const C=dp(R,I);N(C)}m&&console.log("React Flow: trigger node changes",R),p==null||p(R)}},triggerEdgeChanges:R=>{const{onEdgesChange:p,setEdges:N,edges:I,hasDefaultEdges:O,debug:m}=h();if(R!=null&&R.length){if(O){const C=up(R,I);N(C)}m&&console.log("React Flow: trigger edge changes",R),p==null||p(R)}},addSelectedNodes:R=>{const{multiSelectionActive:p,edgeLookup:N,nodeLookup:I,triggerNodeChanges:O,triggerEdgeChanges:m}=h();if(p){const C=R.map(g=>hn(g,!0));O(C);return}O(Qn(I,new Set([...R]),!0)),m(Qn(N))},addSelectedEdges:R=>{const{multiSelectionActive:p,edgeLookup:N,nodeLookup:I,triggerNodeChanges:O,triggerEdgeChanges:m}=h();if(p){const C=R.map(g=>hn(g,!0));m(C);return}m(Qn(N,new Set([...R]))),O(Qn(I,new Set,!0))},unselectNodesAndEdges:({nodes:R,edges:p}={})=>{const{edges:N,nodes:I,nodeLookup:O,triggerNodeChanges:m,triggerEdgeChanges:C}=h(),g=R||I,y=p||N,_=[];for(const D of g){if(!D.selected)continue;const b=O.get(D.id);b&&(b.selected=!1),_.push(hn(D.id,!1))}const P=[];for(const D of y)D.selected&&P.push(hn(D.id,!1));m(_),C(P)},setMinZoom:R=>{const{panZoom:p,maxZoom:N}=h();p==null||p.setScaleExtent([R,N]),S({minZoom:R})},setMaxZoom:R=>{const{panZoom:p,minZoom:N}=h();p==null||p.setScaleExtent([N,R]),S({maxZoom:R})},setTranslateExtent:R=>{var p;(p=h().panZoom)==null||p.setTranslateExtent(R),S({translateExtent:R})},resetSelectedElements:()=>{const{edges:R,nodes:p,triggerNodeChanges:N,triggerEdgeChanges:I,elementsSelectable:O}=h();if(!O)return;const m=p.reduce((g,y)=>y.selected?[...g,hn(y.id,!1)]:g,[]),C=R.reduce((g,y)=>y.selected?[...g,hn(y.id,!1)]:g,[]);N(m),I(C)},setNodeExtent:R=>{const{nodes:p,nodeLookup:N,parentLookup:I,nodeOrigin:O,elevateNodesOnSelect:m,nodeExtent:C,zIndexMode:g}=h();R[0][0]===C[0][0]&&R[0][1]===C[0][1]&&R[1][0]===C[1][0]&&R[1][1]===C[1][1]||(lc(p,N,I,{nodeOrigin:O,nodeExtent:R,elevateNodesOnSelect:m,checkEquality:!1,zIndexMode:g}),S({nodeExtent:R}))},panBy:R=>{const{transform:p,width:N,height:I,panZoom:O,translateExtent:m}=h();return m1({delta:R,panZoom:O,transform:p,translateExtent:m,width:N,height:I})},setCenter:async(R,p,N)=>{const{width:I,height:O,maxZoom:m,panZoom:C}=h();if(!C)return Promise.resolve(!1);const g=typeof(N==null?void 0:N.zoom)<"u"?N.zoom:m;return await C.setViewport({x:I/2-R*g,y:O/2-p*g,zoom:g},{duration:N==null?void 0:N.duration,ease:N==null?void 0:N.ease,interpolate:N==null?void 0:N.interpolate}),Promise.resolve(!0)},cancelConnection:()=>{S({connection:{...PA}})},updateConnection:R=>{S({connection:R})},reset:()=>S({...tT()})}},Object.is);function kU({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:r,initialWidth:o,initialHeight:s,initialMinZoom:a,initialMaxZoom:l,initialFitViewOptions:c,fitView:E,nodeOrigin:d,nodeExtent:u,zIndexMode:T,children:S}){const[h]=f.useState(()=>HU({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:s,fitView:E,minZoom:a,maxZoom:l,fitViewOptions:c,nodeOrigin:d,nodeExtent:u,zIndexMode:T}));return i.jsx(sv,{value:h,children:i.jsx(xv,{children:S})})}function jU({children:e,nodes:t,edges:n,defaultNodes:r,defaultEdges:o,width:s,height:a,fitView:l,fitViewOptions:c,minZoom:E,maxZoom:d,nodeOrigin:u,nodeExtent:T,zIndexMode:S}){return f.useContext(Qi)?i.jsx(i.Fragment,{children:e}):i.jsx(kU,{initialNodes:t,initialEdges:n,defaultNodes:r,defaultEdges:o,initialWidth:s,initialHeight:a,fitView:l,initialFitViewOptions:c,initialMinZoom:E,initialMaxZoom:d,nodeOrigin:u,nodeExtent:T,zIndexMode:S,children:e})}const YU={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0};function WU({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:o,nodeTypes:s,edgeTypes:a,onNodeClick:l,onEdgeClick:c,onInit:E,onMove:d,onMoveStart:u,onMoveEnd:T,onConnect:S,onConnectStart:h,onConnectEnd:A,onClickConnectStart:R,onClickConnectEnd:p,onNodeMouseEnter:N,onNodeMouseMove:I,onNodeMouseLeave:O,onNodeContextMenu:m,onNodeDoubleClick:C,onNodeDragStart:g,onNodeDrag:y,onNodeDragStop:_,onNodesDelete:P,onEdgesDelete:D,onDelete:b,onSelectionChange:F,onSelectionDragStart:x,onSelectionDrag:w,onSelectionDragStop:M,onSelectionContextMenu:B,onSelectionStart:v,onSelectionEnd:L,onBeforeDelete:U,connectionMode:G,connectionLineType:k=qt.Bezier,connectionLineStyle:J,connectionLineComponent:K,connectionLineContainerStyle:$,deleteKeyCode:z="Backspace",selectionKeyCode:q="Shift",selectionOnDrag:X=!1,selectionMode:Q=co.Full,panActivationKeyCode:ae="Space",multiSelectionKeyCode:ne=uo()?"Meta":"Control",zoomActivationKeyCode:re=uo()?"Meta":"Control",snapToGrid:Y,snapGrid:se,onlyRenderVisibleElements:de=!1,selectNodesOnDrag:ue,nodesDraggable:me,autoPanOnNodeFocus:je,nodesConnectable:ve,nodesFocusable:St,nodeOrigin:Tn=cp,edgesFocusable:kt,edgesReconnectable:Bn,elementsSelectable:Po=!0,defaultViewport:jt=pv,minZoom:Lt=.5,maxZoom:Yt=2,translateExtent:bo=lo,preventScrolling:vo=!0,nodeExtent:gr,defaultMarkerColor:Uo="#b1b1b7",zoomOnScroll:oa=!0,zoomOnPinch:Wt=!0,panOnScroll:wo=!1,panOnScrollSpeed:Vt=.5,panOnScrollMode:Bo=mn.Free,zoomOnDoubleClick:Fn=!0,panOnDrag:Lr=!0,onPaneClick:nt,onPaneMouseEnter:sa,onPaneMouseMove:ia,onPaneMouseLeave:aa,onPaneScroll:Gn,onPaneContextMenu:Sn,paneClickDistance:la=1,nodeClickDistance:ca=0,children:_r,onReconnect:Ea,onReconnectStart:Fo,onReconnectEnd:Hn,onEdgeContextMenu:$t,onEdgeDoubleClick:Ye,onEdgeMouseEnter:Go,onEdgeMouseMove:Ho,onEdgeMouseLeave:ko,reconnectRadius:da=10,onNodesChange:ua,onEdgesChange:jo,noDragClassName:Ta="nodrag",noWheelClassName:Sa="nowheel",noPanClassName:Yo="nopan",fitView:Wo,fitViewOptions:xr,connectOnClick:Vo,attributionPosition:$o,proOptions:Xo,defaultEdgeOptions:Ko,elevateNodesOnSelect:zo=!0,elevateEdgesOnSelect:Jo=!1,disableKeyboardA11y:yr=!1,autoPanOnConnect:j,autoPanOnNodeDrag:Ee,autoPanSpeed:Ce,connectionRadius:_e,isValidConnection:fn,onError:Dr,style:Mr,id:LE,nodeDragThreshold:Gh,connectionDragThreshold:Hh,viewport:kh,onViewportChange:jh,width:Yh,height:Wh,colorMode:Vh="light",debug:$h,onScroll:qo,ariaLabelConfig:Xh,zIndexMode:_E="basic",...Kh},zh){const fa=LE||"1",Jh=Ov(Vh),qh=f.useCallback(xE=>{xE.currentTarget.scrollTo({top:0,left:0,behavior:"instant"}),qo==null||qo(xE)},[qo]);return i.jsx("div",{"data-testid":"rf__wrapper",...Kh,onScroll:qh,style:{...Mr,...YU},ref:zh,className:xe(["react-flow",o,Jh]),id:LE,role:"application",children:i.jsxs(jU,{nodes:e,edges:t,width:Yh,height:Wh,fitView:Wo,fitViewOptions:xr,minZoom:Lt,maxZoom:Yt,nodeOrigin:Tn,nodeExtent:gr,zIndexMode:_E,children:[i.jsx(GU,{onInit:E,onNodeClick:l,onEdgeClick:c,onNodeMouseEnter:N,onNodeMouseMove:I,onNodeMouseLeave:O,onNodeContextMenu:m,onNodeDoubleClick:C,nodeTypes:s,edgeTypes:a,connectionLineType:k,connectionLineStyle:J,connectionLineComponent:K,connectionLineContainerStyle:$,selectionKeyCode:q,selectionOnDrag:X,selectionMode:Q,deleteKeyCode:z,multiSelectionKeyCode:ne,panActivationKeyCode:ae,zoomActivationKeyCode:re,onlyRenderVisibleElements:de,defaultViewport:jt,translateExtent:bo,minZoom:Lt,maxZoom:Yt,preventScrolling:vo,zoomOnScroll:oa,zoomOnPinch:Wt,zoomOnDoubleClick:Fn,panOnScroll:wo,panOnScrollSpeed:Vt,panOnScrollMode:Bo,panOnDrag:Lr,onPaneClick:nt,onPaneMouseEnter:sa,onPaneMouseMove:ia,onPaneMouseLeave:aa,onPaneScroll:Gn,onPaneContextMenu:Sn,paneClickDistance:la,nodeClickDistance:ca,onSelectionContextMenu:B,onSelectionStart:v,onSelectionEnd:L,onReconnect:Ea,onReconnectStart:Fo,onReconnectEnd:Hn,onEdgeContextMenu:$t,onEdgeDoubleClick:Ye,onEdgeMouseEnter:Go,onEdgeMouseMove:Ho,onEdgeMouseLeave:ko,reconnectRadius:da,defaultMarkerColor:Uo,noDragClassName:Ta,noWheelClassName:Sa,noPanClassName:Yo,rfId:fa,disableKeyboardA11y:yr,nodeExtent:gr,viewport:kh,onViewportChange:jh}),i.jsx(Nv,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:S,onConnectStart:h,onConnectEnd:A,onClickConnectStart:R,onClickConnectEnd:p,nodesDraggable:me,autoPanOnNodeFocus:je,nodesConnectable:ve,nodesFocusable:St,edgesFocusable:kt,edgesReconnectable:Bn,elementsSelectable:Po,elevateNodesOnSelect:zo,elevateEdgesOnSelect:Jo,minZoom:Lt,maxZoom:Yt,nodeExtent:gr,onNodesChange:ua,onEdgesChange:jo,snapToGrid:Y,snapGrid:se,connectionMode:G,translateExtent:bo,connectOnClick:Vo,defaultEdgeOptions:Ko,fitView:Wo,fitViewOptions:xr,onNodesDelete:P,onEdgesDelete:D,onDelete:b,onNodeDragStart:g,onNodeDrag:y,onNodeDragStop:_,onSelectionDrag:w,onSelectionDragStart:x,onSelectionDragStop:M,onMove:d,onMoveStart:u,onMoveEnd:T,noPanClassName:Yo,nodeOrigin:Tn,rfId:fa,autoPanOnConnect:j,autoPanOnNodeDrag:Ee,autoPanSpeed:Ce,onError:Dr,connectionRadius:_e,isValidConnection:fn,selectNodesOnDrag:ue,nodeDragThreshold:Gh,connectionDragThreshold:Hh,onBeforeDelete:U,debug:$h,ariaLabelConfig:Xh,zIndexMode:_E}),i.jsx(Av,{onSelectionChange:F}),_r,i.jsx(uv,{proOptions:Xo,position:$o}),i.jsx(dv,{rfId:fa,disableKeyboardA11y:yr})]})})}var Bp=Tp(WU);function Fp(e){const[t,n]=f.useState(e),r=f.useCallback(o=>n(s=>dp(o,s)),[]);return[t,n,r]}function Gp(e){const[t,n]=f.useState(e),r=f.useCallback(o=>n(s=>up(o,s)),[]);return[t,n,r]}function VU({dimensions:e,lineWidth:t,variant:n,className:r}){return i.jsx("path",{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:xe(["react-flow__background-pattern",n,r])})}function $U({radius:e,className:t}){return i.jsx("circle",{cx:e,cy:e,r:e,className:xe(["react-flow__background-pattern","dots",t])})}var tn;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(tn||(tn={}));const XU={[tn.Dots]:1,[tn.Lines]:1,[tn.Cross]:6},KU=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function Hp({id:e,variant:t=tn.Dots,gap:n=20,size:r,lineWidth:o=1,offset:s=0,color:a,bgColor:l,style:c,className:E,patternClassName:d}){const u=f.useRef(null),{transform:T,patternId:S}=Re(KU,Ie),h=r||XU[t],A=t===tn.Dots,R=t===tn.Cross,p=Array.isArray(n)?n:[n,n],N=[p[0]*T[2]||1,p[1]*T[2]||1],I=h*T[2],O=Array.isArray(s)?s:[s,s],m=R?[I,I]:N,C=[O[0]*T[2]||1+m[0]/2,O[1]*T[2]||1+m[1]/2],g=`${S}${e||""}`;return i.jsxs("svg",{className:xe(["react-flow__background",E]),style:{...c,...Zi,"--xy-background-color-props":l,"--xy-background-pattern-color-props":a},ref:u,"data-testid":"rf__background",children:[i.jsx("pattern",{id:g,x:T[0]%N[0],y:T[1]%N[1],width:N[0],height:N[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${C[0]},-${C[1]})`,children:A?i.jsx($U,{radius:I/2,className:d}):i.jsx(VU,{dimensions:m,lineWidth:o,variant:t,className:d})}),i.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${g})`})]})}Hp.displayName="Background";const kp=f.memo(Hp);function zU(){return i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",children:i.jsx("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"})})}function JU(){return i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5",children:i.jsx("path",{d:"M0 0h32v4.2H0z"})})}function qU(){return i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30",children:i.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 QU(){return i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:i.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 ZU(){return i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:i.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 Os({children:e,className:t,...n}){return i.jsx("button",{type:"button",className:xe(["react-flow__controls-button",t]),...n,children:e})}const ew=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function jp({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:o,onZoomIn:s,onZoomOut:a,onFitView:l,onInteractiveChange:c,className:E,children:d,position:u="bottom-left",orientation:T="vertical","aria-label":S}){const h=Oe(),{isInteractive:A,minZoomReached:R,maxZoomReached:p,ariaLabelConfig:N}=Re(ew,Ie),{zoomIn:I,zoomOut:O,fitView:m}=pE(),C=()=>{I(),s==null||s()},g=()=>{O(),a==null||a()},y=()=>{m(o),l==null||l()},_=()=>{h.setState({nodesDraggable:!A,nodesConnectable:!A,elementsSelectable:!A}),c==null||c(!A)},P=T==="horizontal"?"horizontal":"vertical";return i.jsxs(Ar,{className:xe(["react-flow__controls",P,E]),position:u,style:e,"data-testid":"rf__controls","aria-label":S??N["controls.ariaLabel"],children:[t&&i.jsxs(i.Fragment,{children:[i.jsx(Os,{onClick:C,className:"react-flow__controls-zoomin",title:N["controls.zoomIn.ariaLabel"],"aria-label":N["controls.zoomIn.ariaLabel"],disabled:p,children:i.jsx(zU,{})}),i.jsx(Os,{onClick:g,className:"react-flow__controls-zoomout",title:N["controls.zoomOut.ariaLabel"],"aria-label":N["controls.zoomOut.ariaLabel"],disabled:R,children:i.jsx(JU,{})})]}),n&&i.jsx(Os,{className:"react-flow__controls-fitview",onClick:y,title:N["controls.fitView.ariaLabel"],"aria-label":N["controls.fitView.ariaLabel"],children:i.jsx(qU,{})}),r&&i.jsx(Os,{className:"react-flow__controls-interactive",onClick:_,title:N["controls.interactive.ariaLabel"],"aria-label":N["controls.interactive.ariaLabel"],children:A?i.jsx(ZU,{}):i.jsx(QU,{})}),d]})}jp.displayName="Controls";const tw=f.memo(jp);function nw({id:e,x:t,y:n,width:r,height:o,style:s,color:a,strokeColor:l,strokeWidth:c,className:E,borderRadius:d,shapeRendering:u,selected:T,onClick:S}){const{background:h,backgroundColor:A}=s||{},R=a||h||A;return i.jsx("rect",{className:xe(["react-flow__minimap-node",{selected:T},E]),x:t,y:n,rx:d,ry:d,width:r,height:o,style:{fill:R,stroke:l,strokeWidth:c},shapeRendering:u,onClick:S?p=>S(p,e):void 0})}const rw=f.memo(nw),ow=e=>e.nodes.map(t=>t.id),Qa=e=>e instanceof Function?e:()=>e;function sw({nodeStrokeColor:e,nodeColor:t,nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:o,nodeComponent:s=rw,onClick:a}){const l=Re(ow,Ie),c=Qa(t),E=Qa(e),d=Qa(n),u=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return i.jsx(i.Fragment,{children:l.map(T=>i.jsx(aw,{id:T,nodeColorFunc:c,nodeStrokeColorFunc:E,nodeClassNameFunc:d,nodeBorderRadius:r,nodeStrokeWidth:o,NodeComponent:s,onClick:a,shapeRendering:u},T))})}function iw({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:r,nodeBorderRadius:o,nodeStrokeWidth:s,shapeRendering:a,NodeComponent:l,onClick:c}){const{node:E,x:d,y:u,width:T,height:S}=Re(h=>{const A=h.nodeLookup.get(e);if(!A)return{node:void 0,x:0,y:0,width:0,height:0};const R=A.internals.userNode,{x:p,y:N}=A.internals.positionAbsolute,{width:I,height:O}=Ht(R);return{node:R,x:p,y:N,width:I,height:O}},Ie);return!E||E.hidden||!GA(E)?null:i.jsx(l,{x:d,y:u,width:T,height:S,style:E.style,selected:!!E.selected,className:r(E),color:t(E),borderRadius:o,strokeColor:n(E),strokeWidth:s,shapeRendering:a,onClick:c,id:E.id})}const aw=f.memo(iw);var lw=f.memo(sw);const cw=200,Ew=150,dw=e=>!e.hidden,uw=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?FA(xo(e.nodeLookup,{filter:dw}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}},Tw="react-flow__minimap-desc";function Yp({style:e,className:t,nodeStrokeColor:n,nodeColor:r,nodeClassName:o="",nodeBorderRadius:s=5,nodeStrokeWidth:a,nodeComponent:l,bgColor:c,maskColor:E,maskStrokeColor:d,maskStrokeWidth:u,position:T="bottom-right",onClick:S,onNodeClick:h,pannable:A=!1,zoomable:R=!1,ariaLabel:p,inversePan:N,zoomStep:I=1,offsetScale:O=5}){const m=Oe(),C=f.useRef(null),{boundingRect:g,viewBB:y,rfId:_,panZoom:P,translateExtent:D,flowWidth:b,flowHeight:F,ariaLabelConfig:x}=Re(uw,Ie),w=(e==null?void 0:e.width)??cw,M=(e==null?void 0:e.height)??Ew,B=g.width/w,v=g.height/M,L=Math.max(B,v),U=L*w,G=L*M,k=O*L,J=g.x-(U-g.width)/2-k,K=g.y-(G-g.height)/2-k,$=U+k*2,z=G+k*2,q=`${Tw}-${_}`,X=f.useRef(0),Q=f.useRef();X.current=L,f.useEffect(()=>{if(C.current&&P)return Q.current=P1({domNode:C.current,panZoom:P,getTransform:()=>m.getState().transform,getViewScale:()=>X.current}),()=>{var Y;(Y=Q.current)==null||Y.destroy()}},[P]),f.useEffect(()=>{var Y;(Y=Q.current)==null||Y.update({translateExtent:D,width:b,height:F,inversePan:N,pannable:A,zoomStep:I,zoomable:R})},[A,R,N,I,D,b,F]);const ae=S?Y=>{var ue;const[se,de]=((ue=Q.current)==null?void 0:ue.pointer(Y))||[0,0];S(Y,{x:se,y:de})}:void 0,ne=h?f.useCallback((Y,se)=>{const de=m.getState().nodeLookup.get(se).internals.userNode;h(Y,de)},[]):void 0,re=p??x["minimap.ariaLabel"];return i.jsx(Ar,{position:T,style:{...e,"--xy-minimap-background-color-props":typeof c=="string"?c:void 0,"--xy-minimap-mask-background-color-props":typeof E=="string"?E:void 0,"--xy-minimap-mask-stroke-color-props":typeof d=="string"?d:void 0,"--xy-minimap-mask-stroke-width-props":typeof u=="number"?u*L: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:xe(["react-flow__minimap",t]),"data-testid":"rf__minimap",children:i.jsxs("svg",{width:w,height:M,viewBox:`${J} ${K} ${$} ${z}`,className:"react-flow__minimap-svg",role:"img","aria-labelledby":q,ref:C,onClick:ae,children:[re&&i.jsx("title",{id:q,children:re}),i.jsx(lw,{onClick:ne,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:s,nodeClassName:o,nodeStrokeWidth:a,nodeComponent:l}),i.jsx("path",{className:"react-flow__minimap-mask",d:`M${J-k},${K-k}h${$+k*2}v${z+k*2}h${-$-k*2}z
|
|
677
|
-
M${y.x},${y.y}h${y.width}v${y.height}h${-y.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}Yp.displayName="MiniMap";const Sw=f.memo(Yp),fw=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,Rw={[Rr.Line]:"right",[Rr.Handle]:"bottom-right"};function Aw({nodeId:e,position:t,variant:n=Rr.Handle,className:r,style:o=void 0,children:s,color:a,minWidth:l=10,minHeight:c=10,maxWidth:E=Number.MAX_VALUE,maxHeight:d=Number.MAX_VALUE,keepAspectRatio:u=!1,resizeDirection:T,autoScale:S=!0,shouldResize:h,onResizeStart:A,onResize:R,onResizeEnd:p}){const N=Ap(),I=typeof e=="string"?e:N,O=Oe(),m=f.useRef(null),C=n===Rr.Handle,g=Re(f.useCallback(fw(C&&S),[C,S]),Ie),y=f.useRef(null),_=t??Rw[n];f.useEffect(()=>{if(!(!m.current||!I))return y.current||(y.current=$1({domNode:m.current,nodeId:I,getStoreItems:()=>{const{nodeLookup:D,transform:b,snapGrid:F,snapToGrid:x,nodeOrigin:w,domNode:M}=O.getState();return{nodeLookup:D,transform:b,snapGrid:F,snapToGrid:x,nodeOrigin:w,paneDomNode:M}},onChange:(D,b)=>{const{triggerNodeChanges:F,nodeLookup:x,parentLookup:w,nodeOrigin:M}=O.getState(),B=[],v={x:D.x,y:D.y},L=x.get(I);if(L&&L.expandParent&&L.parentId){const U=L.origin??M,G=D.width??L.measured.width??0,k=D.height??L.measured.height??0,J={id:L.id,parentId:L.parentId,rect:{width:G,height:k,...HA({x:D.x??L.position.x,y:D.y??L.position.y},{width:G,height:k},L.parentId,x,U)}},K=AE([J],x,w,M);B.push(...K),v.x=D.x?Math.max(U[0]*G,D.x):void 0,v.y=D.y?Math.max(U[1]*k,D.y):void 0}if(v.x!==void 0&&v.y!==void 0){const U={id:I,type:"position",position:{...v}};B.push(U)}if(D.width!==void 0&&D.height!==void 0){const G={id:I,type:"dimensions",resizing:!0,setAttributes:T?T==="horizontal"?"width":"height":!0,dimensions:{width:D.width,height:D.height}};B.push(G)}for(const U of b){const G={...U,type:"position"};B.push(G)}F(B)},onEnd:({width:D,height:b})=>{const F={id:I,type:"dimensions",resizing:!1,dimensions:{width:D,height:b}};O.getState().triggerNodeChanges([F])}})),y.current.update({controlPosition:_,boundaries:{minWidth:l,minHeight:c,maxWidth:E,maxHeight:d},keepAspectRatio:u,resizeDirection:T,onResizeStart:A,onResize:R,onResizeEnd:p,shouldResize:h}),()=>{var D;(D=y.current)==null||D.destroy()}},[_,l,c,E,d,u,A,R,p,h]);const P=_.split("-");return i.jsx("div",{className:xe(["react-flow__resize-control","nodrag",...P,n,r]),ref:m,style:{...o,scale:g,...a&&{[C?"backgroundColor":"borderColor"]:a}},children:s})}f.memo(Aw);var Wp=Object.defineProperty,pw=(e,t,n)=>t in e?Wp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,hw=(e,t)=>{for(var n in t)Wp(e,n,{get:t[n],enumerable:!0})},Iw=(e,t,n)=>pw(e,t+"",n),Vp={};hw(Vp,{Graph:()=>tt,alg:()=>IE,json:()=>Xp,version:()=>mw});var Nw=Object.defineProperty,$p=(e,t)=>{for(var n in t)Nw(e,n,{get:t[n],enumerable:!0})},tt=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(([o,s])=>{e(o)&&t.setNode(o,s)}),Object.values(this._edgeObjs).forEach(o=>{t.hasNode(o.v)&&t.hasNode(o.w)&&t.setEdge(o,this.edge(o))});let n={},r=o=>{let s=this.parent(o);return!s||t.hasNode(s)?(n[o]=s??void 0,s??void 0):s in n?n[s]:r(s)};return this._isCompound&&t.nodes().forEach(o=>t.setParent(o,r(o))),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 o,s,a,l,c=!1;typeof e=="object"&&e!==null&&"v"in e?(o=e.v,s=e.w,a=e.name,arguments.length===2&&(l=t,c=!0)):(o=e,s=t,a=r,arguments.length>2&&(l=n,c=!0)),o=""+o,s=""+s,a!==void 0&&(a=""+a);let E=kr(this._isDirected,o,s,a);if(E in this._edgeLabels)return c&&(this._edgeLabels[E]=l),this;if(a!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(o),this.setNode(s),this._edgeLabels[E]=c?l:this._defaultEdgeLabelFn(o,s,a);let d=Ow(this._isDirected,o,s,a);return o=d.v,s=d.w,Object.freeze(d),this._edgeObjs[E]=d,nT(this._preds[s],o),nT(this._sucs[o],s),this._in[s][E]=d,this._out[o][E]=d,this._edgeCount++,this}edge(e,t,n){let r=arguments.length===1?Za(this._isDirected,e):kr(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?Za(this._isDirected,e):kr(this._isDirected,e,t,n))in this._edgeLabels}removeEdge(e,t,n){let r=arguments.length===1?Za(this._isDirected,e):kr(this._isDirected,e,t,n),o=this._edgeObjs[r];if(o){let s=o.v,a=o.w;delete this._edgeLabels[r],delete this._edgeObjs[r],rT(this._preds[a],s),rT(this._sucs[s],a),delete this._in[a][r],delete this._out[s][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(o=>o.v===t&&o.w===n||o.v===n&&o.w===t):r}};function nT(e,t){e[t]?e[t]++:e[t]=1}function rT(e,t){e[t]!==void 0&&!--e[t]&&delete e[t]}function kr(e,t,n,r){let o=""+t,s=""+n;if(!e&&o>s){let a=o;o=s,s=a}return o+""+s+""+(r===void 0?"\0":r)}function Ow(e,t,n,r){let o=""+t,s=""+n;if(!e&&o>s){let l=o;o=s,s=l}let a={v:o,w:s};return r&&(a.name=r),a}function Za(e,t){return kr(e,t.v,t.w,t.name)}var mw="4.0.1",Xp={};$p(Xp,{read:()=>_w,write:()=>Cw});function Cw(e){let t={options:{directed:e.isDirected(),multigraph:e.isMultigraph(),compound:e.isCompound()},nodes:gw(e),edges:Lw(e)},n=e.graph();return n!==void 0&&(t.value=structuredClone(n)),t}function gw(e){return e.nodes().map(t=>{let n=e.node(t),r=e.parent(t),o={v:t};return n!==void 0&&(o.value=n),r!==void 0&&(o.parent=r),o})}function Lw(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 _w(e){let t=new tt(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 IE={};$p(IE,{CycleException:()=>fi,bellmanFord:()=>Kp,components:()=>Dw,dijkstra:()=>Si,dijkstraAll:()=>bw,findCycles:()=>vw,floydWarshall:()=>ww,isAcyclic:()=>Fw,postorder:()=>Hw,preorder:()=>kw,prim:()=>jw,shortestPaths:()=>Yw,tarjan:()=>Jp,topsort:()=>qp});var xw=()=>1;function Kp(e,t,n,r){return yw(e,String(t),n||xw,r||function(o){return e.outEdges(o)})}function yw(e,t,n,r){let o={},s,a=0,l=e.nodes(),c=function(u){let T=n(u);o[u.v].distance+T<o[u.w].distance&&(o[u.w]={distance:o[u.v].distance+T,predecessor:u.v},s=!0)},E=function(){l.forEach(function(u){r(u).forEach(function(T){let S=T.v===u?T.v:T.w,h=S===T.v?T.w:T.v;c({v:S,w:h})})})};l.forEach(function(u){let T=u===t?0:Number.POSITIVE_INFINITY;o[u]={distance:T,predecessor:""}});let d=l.length;for(let u=1;u<d&&(s=!1,a++,E(),!!s);u++);if(a===d-1&&(s=!1,E(),s))throw new Error("The graph contains a negative weight cycle");return o}function Dw(e){let t={},n=[],r;function o(s){s in t||(t[s]=!0,r.push(s),e.successors(s).forEach(o),e.predecessors(s).forEach(o))}return e.nodes().forEach(function(s){r=[],o(s),r.length&&n.push(r)}),n}var zp=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 o=this._arr,s=o.length;return n[r]=s,o.push({key:r,priority:t}),this._decrease(s),!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,o=e;n<t.length&&(o=t[n].priority<t[o].priority?n:o,r<t.length&&(o=t[r].priority<t[o].priority?r:o),o!==e&&(this._swap(e,o),this._heapify(o)))}_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,o=n[e],s=n[t];n[e]=s,n[t]=o,r[s.key]=e,r[o.key]=t}},Mw=()=>1;function Si(e,t,n,r){let o=function(s){return e.outEdges(s)};return Pw(e,String(t),n||Mw,r||o)}function Pw(e,t,n,r){let o={},s=new zp,a,l,c=function(E){let d=E.v!==a?E.v:E.w,u=o[d],T=n(E),S=l.distance+T;if(T<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+E+" Weight: "+T);S<u.distance&&(u.distance=S,u.predecessor=a,s.decrease(d,S))};for(e.nodes().forEach(function(E){let d=E===t?0:Number.POSITIVE_INFINITY;o[E]={distance:d,predecessor:""},s.add(E,d)});s.size()>0&&(a=s.removeMin(),l=o[a],l.distance!==Number.POSITIVE_INFINITY);)r(a).forEach(c);return o}function bw(e,t,n){return e.nodes().reduce(function(r,o){return r[o]=Si(e,o,t,n),r},{})}function Jp(e){let t=0,n=[],r={},o=[];function s(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)):(s(c),l.lowlink=Math.min(l.lowlink,r[c].lowlink))}),l.lowlink===l.index){let c=[],E;do E=n.pop(),r[E].onStack=!1,c.push(E);while(a!==E);o.push(c)}}return e.nodes().forEach(function(a){a in r||s(a)}),o}function vw(e){return Jp(e).filter(function(t){return t.length>1||t.length===1&&e.hasEdge(t[0],t[0])})}var Uw=()=>1;function ww(e,t,n){return Bw(e,t||Uw,n||function(r){return e.outEdges(r)})}function Bw(e,t,n){let r={},o=e.nodes();return o.forEach(function(s){r[s]={},r[s][s]={distance:0,predecessor:""},o.forEach(function(a){s!==a&&(r[s][a]={distance:Number.POSITIVE_INFINITY,predecessor:""})}),n(s).forEach(function(a){let l=a.v===s?a.w:a.v,c=t(a);r[s][l]={distance:c,predecessor:s}})}),o.forEach(function(s){let a=r[s];o.forEach(function(l){let c=r[l];o.forEach(function(E){let d=c[s],u=a[E],T=c[E],S=d.distance+u.distance;S<T.distance&&(T.distance=S,T.predecessor=u.predecessor)})})}),r}var fi=class extends Error{constructor(...e){super(...e)}};function qp(e){let t={},n={},r=[];function o(s){if(s in n)throw new fi;s in t||(n[s]=!0,t[s]=!0,e.predecessors(s).forEach(o),delete n[s],r.push(s))}if(e.sinks().forEach(o),Object.keys(t).length!==e.nodeCount())throw new fi;return r}function Fw(e){try{qp(e)}catch(t){if(t instanceof fi)return!1;throw t}return!0}function Gw(e,t,n,r,o){Array.isArray(t)||(t=[t]);let s=(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);o=Qp(e,l,n==="post",a,s,r,o)}),o}function Qp(e,t,n,r,o,s,a){return t in r||(r[t]=!0,n||(a=s(a,t)),o(t).forEach(function(l){a=Qp(e,l,n,r,o,s,a)}),n&&(a=s(a,t))),a}function Zp(e,t,n){return Gw(e,t,n,function(r,o){return r.push(o),r},[])}function Hw(e,t){return Zp(e,t,"post")}function kw(e,t){return Zp(e,t,"pre")}function jw(e,t){let n=new tt,r={},o=new zp,s;function a(c){let E=c.v===s?c.w:c.v,d=o.priority(E);if(d!==void 0){let u=t(c);u<d&&(r[E]=s,o.decrease(E,u))}}if(e.nodeCount()===0)return n;e.nodes().forEach(function(c){o.add(c,Number.POSITIVE_INFINITY),n.setNode(c)}),o.decrease(e.nodes()[0],0);let l=!1;for(;o.size()>0;){if(s=o.removeMin(),s in r)n.setEdge(s,r[s]);else{if(l)throw new Error("Input graph is not connected: "+e);l=!0}e.nodeEdges(s).forEach(a)}return n}function Yw(e,t,n,r){return Ww(e,t,n,r??(o=>{let s=e.outEdges(o);return s??[]}))}function Ww(e,t,n,r){if(n===void 0)return Si(e,t,n,r);let o=!1,s=e.nodes();for(let a=0;a<s.length;a++){let l=r(s[a]);for(let c=0;c<l.length;c++){let E=l[c],d=E.v===s[a]?E.v:E.w,u=d===E.v?E.w:E.v;n({v:d,w:u})<0&&(o=!0)}if(o)return Kp(e,t,n,r)}return Si(e,t,n,r)}function mr(e,t,n,r){let o=r;for(;e.hasNode(o);)o=NE(r);return n.dummy=t,e.setNode(o,n),o}function Vw(e){let t=new tt().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},o=e.edge(n);t.setEdge(n.v,n.w,{weight:r.weight+o.weight,minlen:Math.max(r.minlen,o.minlen)})}),t}function eh(e){let t=new tt({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 oT(e,t){let n=e.x,r=e.y,o=t.x-n,s=t.y-r,a=e.width/2,l=e.height/2;if(!o&&!s)throw new Error("Not possible to find intersection inside of the rectangle");let c,E;return Math.abs(s)*a>Math.abs(o)*l?(s<0&&(l=-l),c=l*o/s,E=l):(o<0&&(a=-a),c=a,E=a*s/o),{x:n+c,y:r+E}}function Mo(e){let t=So(nh(e)+1).map(()=>[]);return e.nodes().forEach(n=>{let r=e.node(n),o=r.rank;o!==void 0&&(t[o]||(t[o]=[]),t[o][r.order]=n)}),t}function $w(e){let t=e.nodes().map(r=>{let o=e.node(r).rank;return o===void 0?Number.MAX_VALUE:o}),n=It(Math.min,t);e.nodes().forEach(r=>{let o=e.node(r);Object.hasOwn(o,"rank")&&(o.rank-=n)})}function Xw(e){let t=e.nodes().map(a=>e.node(a).rank).filter(a=>a!==void 0),n=It(Math.min,t),r=[];e.nodes().forEach(a=>{let l=e.node(a).rank-n;r[l]||(r[l]=[]),r[l].push(a)});let o=0,s=e.graph().nodeRankFactor;Array.from(r).forEach((a,l)=>{a===void 0&&l%s!==0?--o:a!==void 0&&o&&a.forEach(c=>e.node(c).rank+=o)})}function sT(e,t,n,r){let o={width:0,height:0};return arguments.length>=4&&(o.rank=n,o.order=r),mr(e,"border",o,t)}function Kw(e,t=th){let n=[];for(let r=0;r<e.length;r+=t){let o=e.slice(r,r+t);n.push(o)}return n}var th=65535;function It(e,t){if(t.length>th){let n=Kw(t);return e(...n.map(r=>e(...r)))}else return e(...t)}function nh(e){let t=e.nodes().map(n=>{let r=e.node(n).rank;return r===void 0?Number.MIN_VALUE:r});return It(Math.max,t)}function zw(e,t){let n={lhs:[],rhs:[]};return e.forEach(r=>{t(r)?n.lhs.push(r):n.rhs.push(r)}),n}function rh(e,t){let n=Date.now();try{return t()}finally{console.log(e+" time: "+(Date.now()-n)+"ms")}}function oh(e,t){return t()}var Jw=0;function NE(e){let t=++Jw;return e+(""+t)}function So(e,t,n=1){t==null&&(t=e,e=0);let r=s=>s<t;n<0&&(r=s=>t<s);let o=[];for(let s=e;r(s);s+=n)o.push(s);return o}function Ri(e,t){let n={};for(let r of t)e[r]!==void 0&&(n[r]=e[r]);return n}function ta(e,t){let n;return typeof t=="string"?n=r=>r[t]:n=t,Object.entries(e).reduce((r,[o,s])=>(r[o]=n(s,o),r),{})}function qw(e,t){return e.reduce((n,r,o)=>(n[r]=t[o],n),{})}var na="\0",Qw="3.0.0",Zw=class{constructor(){Iw(this,"_sentinel");let e={};e._next=e._prev=e,this._sentinel=e}dequeue(){let e=this._sentinel,t=e._prev;if(t!==e)return iT(t),t}enqueue(e){let t=this._sentinel;e._prev&&e._next&&iT(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,eB)),n=n._prev;return"["+e.join(", ")+"]"}};function iT(e){e._prev._next=e._next,e._next._prev=e._prev,delete e._next,delete e._prev}function eB(e,t){if(e!=="_next"&&e!=="_prev")return t}var tB=Zw,nB=()=>1;function rB(e,t){if(e.nodeCount()<=1)return[];let n=sB(e,t||nB);return oB(n.graph,n.buckets,n.zeroIdx).flatMap(r=>e.outEdges(r.v,r.w)||[])}function oB(e,t,n){var r;let o=[],s=t[t.length-1],a=t[0],l;for(;e.nodeCount();){for(;l=a.dequeue();)el(e,t,n,l);for(;l=s.dequeue();)el(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){o=o.concat(el(e,t,n,l,!0)||[]);break}}}return o}function el(e,t,n,r,o){let s=[],a=o?s:void 0;return(e.inEdges(r.v)||[]).forEach(l=>{let c=e.edge(l),E=e.node(l.v);o&&s.push({v:l.v,w:l.w}),E.out-=c,dc(t,n,E)}),(e.outEdges(r.v)||[]).forEach(l=>{let c=e.edge(l),E=l.w,d=e.node(E);d.in-=c,dc(t,n,d)}),e.removeNode(r.v),a}function sB(e,t){let n=new tt,r=0,o=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,E=t(l),d=c+E;n.setEdge(l.v,l.w,d);let u=n.node(l.v),T=n.node(l.w);o=Math.max(o,u.out+=E),r=Math.max(r,T.in+=E)});let s=iB(o+r+3).map(()=>new tB),a=r+1;return n.nodes().forEach(l=>{dc(s,a,n.node(l))}),{graph:n,buckets:s,zeroIdx:a}}function dc(e,t,n){var r,o,s;n.out?n.in?(s=e[n.out-n.in+t])==null||s.enqueue(n):(o=e[e.length-1])==null||o.enqueue(n):(r=e[0])==null||r.enqueue(n)}function iB(e){let t=[];for(let n=0;n<e;n++)t.push(n);return t}function aB(e){(e.graph().acyclicer==="greedy"?rB(e,t(e)):lB(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,NE("rev"))});function t(n){return r=>n.edge(r).weight}}function lB(e){let t=[],n={},r={};function o(s){Object.hasOwn(r,s)||(r[s]=!0,n[s]=!0,e.outEdges(s).forEach(a=>{Object.hasOwn(n,a.w)?t.push(a):o(a.w)}),delete n[s])}return e.nodes().forEach(o),t}function cB(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 EB(e){e.graph().dummyChains=[],e.edges().forEach(t=>dB(e,t))}function dB(e,t){let n=t.v,r=e.node(n).rank,o=t.w,s=e.node(o).rank,a=t.name,l=e.edge(t),c=l.labelRank;if(s===r+1)return;e.removeEdge(t);let E,d,u;for(u=0,++r;r<s;++u,++r)l.points=[],d={width:0,height:0,edgeLabel:l,edgeObj:t,rank:r},E=mr(e,"edge",d,"_d"),r===c&&(d.width=l.width,d.height=l.height,d.dummy="edge-label",d.labelpos=l.labelpos),e.setEdge(n,E,{weight:l.weight},a),u===0&&e.graph().dummyChains.push(E),n=E;e.setEdge(n,o,{weight:l.weight},a)}function uB(e){e.graph().dummyChains.forEach(t=>{let n=e.node(t),r=n.edgeLabel,o;for(e.setEdge(n.edgeObj,r);n.dummy;)o=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=o,n=e.node(t)})}function OE(e){let t={};function n(r){let o=e.node(r);if(Object.hasOwn(t,r))return o.rank;t[r]=!0;let s=e.outEdges(r),a=s?s.map(c=>c==null?Number.POSITIVE_INFINITY:n(c.w)-e.edge(c).minlen):[],l=It(Math.min,a);return l===Number.POSITIVE_INFINITY&&(l=0),o.rank=l}e.sources().forEach(n)}function pr(e,t){return e.node(t.w).rank-e.node(t.v).rank-e.edge(t).minlen}var sh=TB;function TB(e){let t=new tt({directed:!1}),n=e.nodes();if(n.length===0)throw new Error("Graph must have at least one node");let r=n[0],o=e.nodeCount();t.setNode(r,{});let s,a;for(;SB(t,e)<o&&(s=fB(t,e),!!s);)a=t.hasNode(s.v)?pr(e,s):-pr(e,s),RB(t,e,a);return t}function SB(e,t){function n(r){let o=t.nodeEdges(r);o&&o.forEach(s=>{let a=s.v,l=r===a?s.w:a;!e.hasNode(l)&&!pr(t,s)&&(e.setNode(l,{}),e.setEdge(r,l,{}),n(l))})}return e.nodes().forEach(n),e.nodeCount()}function fB(e,t){return t.edges().reduce((n,r)=>{let o=Number.POSITIVE_INFINITY;return e.hasNode(r.v)!==e.hasNode(r.w)&&(o=pr(t,r)),o<n[0]?[o,r]:n},[Number.POSITIVE_INFINITY,null])[1]}function RB(e,t,n){e.nodes().forEach(r=>t.node(r).rank+=n)}var{preorder:AB,postorder:pB}=IE,hB=Un;Un.initLowLimValues=CE;Un.initCutValues=mE;Un.calcCutValue=ih;Un.leaveEdge=lh;Un.enterEdge=ch;Un.exchangeEdges=Eh;function Un(e){e=Vw(e),OE(e);let t=sh(e);CE(t),mE(t,e);let n,r;for(;n=lh(t);)r=ch(t,e,n),Eh(t,e,n,r)}function mE(e,t){let n=pB(e,e.nodes());n=n.slice(0,n.length-1),n.forEach(r=>IB(e,t,r))}function IB(e,t,n){let r=e.node(n).parent,o=e.edge(n,r);o.cutvalue=ih(e,t,n)}function ih(e,t,n){let r=e.node(n).parent,o=!0,s=t.edge(n,r),a=0;s||(o=!1,s=t.edge(r,n)),a=s.weight;let l=t.nodeEdges(n);return l&&l.forEach(c=>{let E=c.v===n,d=E?c.w:c.v;if(d!==r){let u=E===o,T=t.edge(c).weight;if(a+=u?T:-T,OB(e,n,d)){let S=e.edge(n,d).cutvalue;a+=u?-S:S}}}),a}function CE(e,t){arguments.length<2&&(t=e.nodes()[0]),ah(e,{},1,t)}function ah(e,t,n,r,o){let s=n,a=e.node(r);t[r]=!0;let l=e.neighbors(r);return l&&l.forEach(c=>{Object.hasOwn(t,c)||(n=ah(e,t,n,c,r))}),a.low=s,a.lim=n++,o?a.parent=o:delete a.parent,n}function lh(e){return e.edges().find(t=>e.edge(t).cutvalue<0)}function ch(e,t,n){let r=n.v,o=n.w;t.hasEdge(r,o)||(r=n.w,o=n.v);let s=e.node(r),a=e.node(o),l=s,c=!1;return s.lim>a.lim&&(l=a,c=!0),t.edges().filter(E=>c===aT(e,e.node(E.v),l)&&c!==aT(e,e.node(E.w),l)).reduce((E,d)=>pr(t,d)<pr(t,E)?d:E)}function Eh(e,t,n,r){let o=n.v,s=n.w;e.removeEdge(o,s),e.setEdge(r.v,r.w,{}),CE(e),mE(e,t),NB(e,t)}function NB(e,t){let n=e.nodes().find(o=>!e.node(o).parent);if(!n)return;let r=AB(e,[n]);r=r.slice(1),r.forEach(o=>{let s=e.node(o).parent,a=t.edge(o,s),l=!1;a||(a=t.edge(s,o),l=!0),t.node(o).rank=t.node(s).rank+(l?a.minlen:-a.minlen)})}function OB(e,t,n){return e.hasEdge(t,n)}function aT(e,t,n){return n.low<=t.lim&&t.lim<=n.lim}var mB=CB;function CB(e){let t=e.graph().ranker;if(typeof t=="function")return t(e);switch(t){case"network-simplex":lT(e);break;case"tight-tree":LB(e);break;case"longest-path":gB(e);break;case"none":break;default:lT(e)}}var gB=OE;function LB(e){OE(e),sh(e)}function lT(e){hB(e)}var _B=xB;function xB(e){let t=DB(e);e.graph().dummyChains.forEach(n=>{let r=e.node(n),o=r.edgeObj,s=yB(e,t,o.v,o.w),a=s.path,l=s.lca,c=0,E=a[c],d=!0;for(;n!==o.w;){if(r=e.node(n),d){for(;(E=a[c])!==l&&e.node(E).maxRank<r.rank;)c++;E===l&&(d=!1)}if(!d){for(;c<a.length-1&&e.node(a[c+1]).minRank<=r.rank;)c++;E=a[c]}E!==void 0&&e.setParent(n,E),n=e.successors(n)[0]}})}function yB(e,t,n,r){let o=[],s=[],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),o.push(c);while(c&&(t[c].low>a||l>t[c].lim));let E=c,d=r;for(;(d=e.parent(d))!==E;)s.push(d);return{path:o.concat(s.reverse()),lca:E}}function DB(e){let t={},n=0;function r(o){let s=n;e.children(o).forEach(r),t[o]={low:s,lim:n++}}return e.children(na).forEach(r),t}function MB(e){let t=mr(e,"root",{},"_root"),n=PB(e),r=Object.values(n),o=It(Math.max,r)-1,s=2*o+1;e.graph().nestingRoot=t,e.edges().forEach(l=>e.edge(l).minlen*=s);let a=bB(e)+1;e.children(na).forEach(l=>dh(e,t,s,a,o,n,l)),e.graph().nodeRankFactor=s}function dh(e,t,n,r,o,s,a){var l;let c=e.children(a);if(!c.length){a!==t&&e.setEdge(t,a,{weight:0,minlen:n});return}let E=sT(e,"_bt"),d=sT(e,"_bb"),u=e.node(a);e.setParent(E,a),u.borderTop=E,e.setParent(d,a),u.borderBottom=d,c.forEach(T=>{var S;dh(e,t,n,r,o,s,T);let h=e.node(T),A=h.borderTop?h.borderTop:T,R=h.borderBottom?h.borderBottom:T,p=h.borderTop?r:2*r,N=A!==R?1:o-((S=s[a])!=null?S:0)+1;e.setEdge(E,A,{weight:p,minlen:N,nestingEdge:!0}),e.setEdge(R,d,{weight:p,minlen:N,nestingEdge:!0})}),e.parent(a)||e.setEdge(t,E,{weight:0,minlen:o+((l=s[a])!=null?l:0)})}function PB(e){let t={};function n(r,o){let s=e.children(r);s&&s.length&&s.forEach(a=>n(a,o+1)),t[r]=o}return e.children(na).forEach(r=>n(r,1)),t}function bB(e){return e.edges().reduce((t,n)=>t+e.edge(n).weight,0)}function vB(e){let t=e.graph();e.removeNode(t.nestingRoot),delete t.nestingRoot,e.edges().forEach(n=>{e.edge(n).nestingEdge&&e.removeEdge(n)})}var UB=wB;function wB(e){function t(n){let r=e.children(n),o=e.node(n);if(r.length&&r.forEach(t),Object.hasOwn(o,"minRank")){o.borderLeft=[],o.borderRight=[];for(let s=o.minRank,a=o.maxRank+1;s<a;++s)cT(e,"borderLeft","_bl",n,o,s),cT(e,"borderRight","_br",n,o,s)}}e.children(na).forEach(t)}function cT(e,t,n,r,o,s){let a={width:0,height:0,rank:s,borderType:t},l=o[t][s-1],c=mr(e,"border",a,n);o[t][s]=c,e.setParent(c,r),l&&e.setEdge(l,c,{weight:1})}function BB(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="lr"||n==="rl")&&uh(e)}function FB(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="bt"||n==="rl")&&GB(e),(n==="lr"||n==="rl")&&(HB(e),uh(e))}function uh(e){e.nodes().forEach(t=>ET(e.node(t))),e.edges().forEach(t=>ET(e.edge(t)))}function ET(e){let t=e.width;e.width=e.height,e.height=t}function GB(e){e.nodes().forEach(t=>tl(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(tl),Object.hasOwn(r,"y")&&tl(r)})}function tl(e){e.y=-e.y}function HB(e){e.nodes().forEach(t=>nl(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(nl),Object.hasOwn(r,"x")&&nl(r)})}function nl(e){let t=e.x;e.x=e.y,e.y=t}function kB(e){let t={},n=e.nodes().filter(l=>!e.children(l).length),r=n.map(l=>e.node(l).rank),o=It(Math.max,r),s=So(o+1).map(()=>[]);function a(l){if(t[l])return;t[l]=!0;let c=e.node(l);s[c.rank].push(l);let E=e.successors(l);E&&E.forEach(a)}return n.sort((l,c)=>e.node(l).rank-e.node(c).rank).forEach(a),s}function jB(e,t){let n=0;for(let r=1;r<t.length;++r)n+=YB(e,t[r-1],t[r]);return n}function YB(e,t,n){let r=qw(n,n.map((E,d)=>d)),o=t.flatMap(E=>{let d=e.outEdges(E);return d?d.map(u=>({pos:r[u.w],weight:e.edge(u).weight})).sort((u,T)=>u.pos-T.pos):[]}),s=1;for(;s<n.length;)s<<=1;let a=2*s-1;s-=1;let l=new Array(a).fill(0),c=0;return o.forEach(E=>{let d=E.pos+s;l[d]+=E.weight;let u=0;for(;d>0;)d%2&&(u+=l[d+1]),d=d-1>>1,l[d]+=E.weight;c+=E.weight*u}),c}function WB(e,t=[]){return t.map(n=>{let r=e.inEdges(n);if(!r||!r.length)return{v:n};{let o=r.reduce((s,a)=>{let l=e.edge(a),c=e.node(a.v);return{sum:s.sum+l.weight*c.order,weight:s.weight+l.weight}},{sum:0,weight:0});return{v:n,barycenter:o.sum/o.weight,weight:o.weight}}})}function VB(e,t){let n={};e.forEach((o,s)=>{let a={indegree:0,in:[],out:[],vs:[o.v],i:s};o.barycenter!==void 0&&(a.barycenter=o.barycenter,a.weight=o.weight),n[o.v]=a}),t.edges().forEach(o=>{let s=n[o.v],a=n[o.w];s!==void 0&&a!==void 0&&(a.indegree++,s.out.push(a))});let r=Object.values(n).filter(o=>!o.indegree);return $B(r)}function $B(e){let t=[];function n(o){return s=>{s.merged||(s.barycenter===void 0||o.barycenter===void 0||s.barycenter>=o.barycenter)&&XB(o,s)}}function r(o){return s=>{s.in.push(o),--s.indegree===0&&e.push(s)}}for(;e.length;){let o=e.pop();t.push(o),o.in.reverse().forEach(n(o)),o.out.forEach(r(o))}return t.filter(o=>!o.merged).map(o=>Ri(o,["vs","i","barycenter","weight"]))}function XB(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 KB(e,t){let n=zw(e,d=>Object.hasOwn(d,"barycenter")),r=n.lhs,o=n.rhs.sort((d,u)=>u.i-d.i),s=[],a=0,l=0,c=0;r.sort(zB(!!t)),c=dT(s,o,c),r.forEach(d=>{c+=d.vs.length,s.push(d.vs),a+=d.barycenter*d.weight,l+=d.weight,c=dT(s,o,c)});let E={vs:s.flat(1)};return l&&(E.barycenter=a/l,E.weight=l),E}function dT(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 zB(e){return(t,n)=>t.barycenter<n.barycenter?-1:t.barycenter>n.barycenter?1:e?n.i-t.i:t.i-n.i}function Th(e,t,n,r){let o=e.children(t),s=e.node(t),a=s?s.borderLeft:void 0,l=s?s.borderRight:void 0,c={};a&&(o=o.filter(T=>T!==a&&T!==l));let E=WB(e,o);E.forEach(T=>{if(e.children(T.v).length){let S=Th(e,T.v,n,r);c[T.v]=S,Object.hasOwn(S,"barycenter")&&qB(T,S)}});let d=VB(E,n);JB(d,c);let u=KB(d,r);if(a&&l){u.vs=[a,u.vs,l].flat(1);let T=e.predecessors(a);if(T&&T.length){let S=e.node(T[0]),h=e.predecessors(l),A=e.node(h[0]);Object.hasOwn(u,"barycenter")||(u.barycenter=0,u.weight=0),u.barycenter=(u.barycenter*u.weight+S.order+A.order)/(u.weight+2),u.weight+=2}}return u}function JB(e,t){e.forEach(n=>{n.vs=n.vs.flatMap(r=>t[r]?t[r].vs:r)})}function qB(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 QB(e,t,n,r){r||(r=e.nodes());let o=ZB(e),s=new tt({compound:!0}).setGraph({root:o}).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){s.setNode(a),s.setParent(a,c||o);let E=e[n](a);E&&E.forEach(d=>{let u=d.v===a?d.w:d.v,T=s.edge(u,a),S=T!==void 0?T.weight:0;s.setEdge(u,a,{weight:e.edge(d).weight+S})}),Object.hasOwn(l,"minRank")&&s.setNode(a,{borderLeft:l.borderLeft[t],borderRight:l.borderRight[t]})}}),s}function ZB(e){let t;for(;e.hasNode(t=NE("_root")););return t}function eF(e,t,n){let r={},o;n.forEach(s=>{let a=e.parent(s),l,c;for(;a;){if(l=e.parent(a),l?(c=r[l],r[l]=a):(c=o,o=a),c&&c!==a){t.setEdge(c,a);return}a=l}})}function Sh(e,t={}){if(typeof t.customOrder=="function"){t.customOrder(e,Sh);return}let n=nh(e),r=uT(e,So(1,n+1),"inEdges"),o=uT(e,So(n-1,-1,-1),"outEdges"),s=kB(e);if(TT(e,s),t.disableOptimalOrderHeuristic)return;let a=Number.POSITIVE_INFINITY,l,c=t.constraints||[];for(let E=0,d=0;d<4;++E,++d){tF(E%2?r:o,E%4>=2,c),s=Mo(e);let u=jB(e,s);u<a?(d=0,l=Object.assign({},s),a=u):u===a&&(l=structuredClone(s))}TT(e,l)}function uT(e,t,n){let r=new Map,o=(s,a)=>{r.has(s)||r.set(s,[]),r.get(s).push(a)};for(let s of e.nodes()){let a=e.node(s);if(typeof a.rank=="number"&&o(a.rank,s),typeof a.minRank=="number"&&typeof a.maxRank=="number")for(let l=a.minRank;l<=a.maxRank;l++)l!==a.rank&&o(l,s)}return t.map(function(s){return QB(e,s,n,r.get(s)||[])})}function tF(e,t,n){let r=new tt;e.forEach(function(o){n.forEach(l=>r.setEdge(l.left,l.right));let s=o.graph().root,a=Th(o,s,r,t);a.vs.forEach((l,c)=>o.node(l).order=c),eF(o,r,a.vs)})}function TT(e,t){Object.values(t).forEach(n=>n.forEach((r,o)=>e.node(r).order=o))}function nF(e,t){let n={};function r(o,s){let a=0,l=0,c=o.length,E=s[s.length-1];return s.forEach((d,u)=>{let T=oF(e,d),S=T?e.node(T).order:c;(T||d===E)&&(s.slice(l,u+1).forEach(h=>{let A=e.predecessors(h);A&&A.forEach(R=>{let p=e.node(R),N=p.order;(N<a||S<N)&&!(p.dummy&&e.node(h).dummy)&&fh(n,R,h)})}),l=u+1,a=S)}),s}return t.length&&t.reduce(r),n}function rF(e,t){let n={};function r(s,a,l,c,E){So(a,l).forEach(d=>{let u=s[d];if(u!==void 0&&e.node(u).dummy){let T=e.predecessors(u);T&&T.forEach(S=>{if(S===void 0)return;let h=e.node(S);h.dummy&&(h.order<c||h.order>E)&&fh(n,S,u)})}})}function o(s,a){let l=-1,c=-1,E=0;return a.forEach((d,u)=>{if(e.node(d).dummy==="border"){let T=e.predecessors(d);if(T&&T.length){let S=T[0];if(S===void 0)return;c=e.node(S).order,r(a,E,u,l,c),E=u,l=c}}r(a,E,a.length,c,s.length)}),a}return t.length&&t.reduce(o),n}function oF(e,t){if(e.node(t).dummy){let n=e.predecessors(t);if(n)return n.find(r=>e.node(r).dummy)}}function fh(e,t,n){if(t>n){let o=t;t=n,n=o}let r=e[t];r||(e[t]=r={}),r[n]=!0}function sF(e,t,n){if(t>n){let o=t;t=n,n=o}let r=e[t];return r!==void 0&&Object.hasOwn(r,n)}function iF(e,t,n,r){let o={},s={},a={};return t.forEach(l=>{l.forEach((c,E)=>{o[c]=c,s[c]=c,a[c]=E})}),t.forEach(l=>{let c=-1;l.forEach(E=>{let d=r(E);if(d&&d.length){let u=d.sort((S,h)=>{let A=a[S],R=a[h];return(A!==void 0?A:0)-(R!==void 0?R:0)}),T=(u.length-1)/2;for(let S=Math.floor(T),h=Math.ceil(T);S<=h;++S){let A=u[S];if(A===void 0)continue;let R=a[A];if(R!==void 0&&s[E]===E&&c<R&&!sF(n,E,A)){let p=o[A];p!==void 0&&(s[A]=E,s[E]=o[E]=p,c=R)}}}})}),{root:o,align:s}}function aF(e,t,n,r,o=!1){let s={},a=lF(e,t,n,o),l=o?"borderLeft":"borderRight";function c(S,h){let A=a.nodes().slice(),R={},p=A.pop();for(;p;){if(R[p])S(p);else{R[p]=!0,A.push(p);for(let N of h(p))A.push(N)}p=A.pop()}}function E(S){let h=a.inEdges(S);h?s[S]=h.reduce((A,R)=>{var p;let N=(p=s[R.v])!=null?p:0,I=a.edge(R);return Math.max(A,N+(I!==void 0?I:0))},0):s[S]=0}function d(S){let h=a.outEdges(S),A=Number.POSITIVE_INFINITY;h&&(A=h.reduce((p,N)=>{let I=s[N.w],O=a.edge(N);return Math.min(p,(I!==void 0?I:0)-(O!==void 0?O:0))},Number.POSITIVE_INFINITY));let R=e.node(S);A!==Number.POSITIVE_INFINITY&&R.borderType!==l&&(s[S]=Math.max(s[S]!==void 0?s[S]:0,A))}function u(S){return a.predecessors(S)||[]}function T(S){return a.successors(S)||[]}return c(E,u),c(d,T),Object.keys(r).forEach(S=>{var h;let A=n[S];A!==void 0&&(s[S]=(h=s[A])!=null?h:0)}),s}function lF(e,t,n,r){let o=new tt,s=e.graph(),a=TF(s.nodesep,s.edgesep,r);return t.forEach(l=>{let c;l.forEach(E=>{let d=n[E];if(d!==void 0){if(o.setNode(d),c!==void 0){let u=n[c];if(u!==void 0){let T=o.edge(u,d);o.setEdge(u,d,Math.max(a(e,E,c),T||0))}}c=E}})}),o}function cF(e,t){return Object.values(t).reduce((n,r)=>{let o=Number.NEGATIVE_INFINITY,s=Number.POSITIVE_INFINITY;Object.entries(r).forEach(([l,c])=>{let E=SF(e,l)/2;o=Math.max(c+E,o),s=Math.min(c-E,s)});let a=o-s;return a<n[0]&&(n=[a,r]),n},[Number.POSITIVE_INFINITY,null])[1]}function EF(e,t){let n=Object.values(t),r=It(Math.min,n),o=It(Math.max,n);["u","d"].forEach(s=>{["l","r"].forEach(a=>{let l=s+a,c=e[l];if(!c||c===t)return;let E=Object.values(c),d=r-It(Math.min,E);a!=="l"&&(d=o-It(Math.max,E)),d&&(e[l]=ta(c,u=>u+d))})})}function dF(e,t=void 0){let n=e.ul;return n?ta(n,(r,o)=>{var s,a;if(t){let c=t.toLowerCase(),E=e[c];if(E&&E[o]!==void 0)return E[o]}let l=Object.values(e).map(c=>{let E=c[o];return E!==void 0?E:0}).sort((c,E)=>c-E);return(((s=l[1])!=null?s:0)+((a=l[2])!=null?a:0))/2}):{}}function uF(e){let t=Mo(e),n=Object.assign(nF(e,t),rF(e,t)),r={},o;["u","d"].forEach(a=>{o=a==="u"?t:Object.values(t).reverse(),["l","r"].forEach(l=>{l==="r"&&(o=o.map(d=>Object.values(d).reverse()));let c=iF(e,o,n,d=>(a==="u"?e.predecessors(d):e.successors(d))||[]),E=aF(e,o,c.root,c.align,l==="r");l==="r"&&(E=ta(E,d=>-d)),r[a+l]=E})});let s=cF(e,r);return EF(r,s),dF(r,e.graph().align)}function TF(e,t,n){return(r,o,s)=>{let a=r.node(o),l=r.node(s),c=0,E;if(c+=a.width/2,Object.hasOwn(a,"labelpos"))switch(a.labelpos.toLowerCase()){case"l":E=-a.width/2;break;case"r":E=a.width/2;break}if(E&&(c+=n?E:-E),E=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":E=l.width/2;break;case"r":E=-l.width/2;break}return E&&(c+=n?E:-E),c}}function SF(e,t){return e.node(t).width}function fF(e){e=eh(e),RF(e),Object.entries(uF(e)).forEach(([t,n])=>e.node(t).x=n)}function RF(e){let t=Mo(e),n=e.graph(),r=n.ranksep,o=n.rankalign,s=0;t.forEach(a=>{let l=a.reduce((c,E)=>{var d;let u=(d=e.node(E).height)!=null?d:0;return c>u?c:u},0);a.forEach(c=>{let E=e.node(c);o==="top"?E.y=s+E.height/2:o==="bottom"?E.y=s+l-E.height/2:E.y=s+l/2}),s+=l+r})}function AF(e,t={}){let n=t.debugTiming?rh:oh;return n("layout",()=>{let r=n(" buildLayoutGraph",()=>_F(e));return n(" runLayout",()=>pF(r,n,t)),n(" updateInputGraph",()=>hF(e,r)),r})}function pF(e,t,n){t(" makeSpaceForEdgeLabels",()=>xF(e)),t(" removeSelfEdges",()=>BF(e)),t(" acyclic",()=>aB(e)),t(" nestingGraph.run",()=>MB(e)),t(" rank",()=>mB(eh(e))),t(" injectEdgeLabelProxies",()=>yF(e)),t(" removeEmptyRanks",()=>Xw(e)),t(" nestingGraph.cleanup",()=>vB(e)),t(" normalizeRanks",()=>$w(e)),t(" assignRankMinMax",()=>DF(e)),t(" removeEdgeLabelProxies",()=>MF(e)),t(" normalize.run",()=>EB(e)),t(" parentDummyChains",()=>_B(e)),t(" addBorderSegments",()=>UB(e)),t(" order",()=>Sh(e,n)),t(" insertSelfEdges",()=>FF(e)),t(" adjustCoordinateSystem",()=>BB(e)),t(" position",()=>fF(e)),t(" positionSelfEdges",()=>GF(e)),t(" removeBorderNodes",()=>wF(e)),t(" normalize.undo",()=>uB(e)),t(" fixupEdgeLabelCoords",()=>vF(e)),t(" undoCoordinateSystem",()=>FB(e)),t(" translateGraph",()=>PF(e)),t(" assignNodeIntersects",()=>bF(e)),t(" reversePoints",()=>UF(e)),t(" acyclic.undo",()=>cB(e))}function hF(e,t){e.nodes().forEach(n=>{let r=e.node(n),o=t.node(n);r&&(r.x=o.x,r.y=o.y,r.order=o.order,r.rank=o.rank,t.children(n).length&&(r.width=o.width,r.height=o.height))}),e.edges().forEach(n=>{let r=e.edge(n),o=t.edge(n);r.points=o.points,Object.hasOwn(o,"x")&&(r.x=o.x,r.y=o.y)}),e.graph().width=t.graph().width,e.graph().height=t.graph().height}var IF=["nodesep","edgesep","ranksep","marginx","marginy"],NF={ranksep:50,edgesep:20,nodesep:50,rankdir:"TB",rankalign:"center"},OF=["acyclicer","ranker","rankdir","align","rankalign"],mF=["width","height","rank"],ST={width:0,height:0},CF=["minlen","weight","width","height","labeloffset"],gF={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},LF=["labelpos"];function _F(e){let t=new tt({multigraph:!0,compound:!0}),n=ol(e.graph());return t.setGraph(Object.assign({},NF,rl(n,IF),Ri(n,OF))),e.nodes().forEach(r=>{let o=ol(e.node(r)),s=rl(o,mF);Object.keys(ST).forEach(l=>{s[l]===void 0&&(s[l]=ST[l])}),t.setNode(r,s);let a=e.parent(r);a!==void 0&&t.setParent(r,a)}),e.edges().forEach(r=>{let o=ol(e.edge(r));t.setEdge(r,Object.assign({},gF,rl(o,CF),Ri(o,LF)))}),t}function xF(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 yF(e){e.edges().forEach(t=>{let n=e.edge(t);if(n.width&&n.height){let r=e.node(t.v),o={rank:(e.node(t.w).rank-r.rank)/2+r.rank,e:t};mr(e,"edge-proxy",o,"_ep")}})}function DF(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 MF(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 PF(e){let t=Number.POSITIVE_INFINITY,n=0,r=Number.POSITIVE_INFINITY,o=0,s=e.graph(),a=s.marginx||0,l=s.marginy||0;function c(E){let d=E.x,u=E.y,T=E.width,S=E.height;t=Math.min(t,d-T/2),n=Math.max(n,d+T/2),r=Math.min(r,u-S/2),o=Math.max(o,u+S/2)}e.nodes().forEach(E=>c(e.node(E))),e.edges().forEach(E=>{let d=e.edge(E);Object.hasOwn(d,"x")&&c(d)}),t-=a,r-=l,e.nodes().forEach(E=>{let d=e.node(E);d.x-=t,d.y-=r}),e.edges().forEach(E=>{let d=e.edge(E);d.points.forEach(u=>{u.x-=t,u.y-=r}),Object.hasOwn(d,"x")&&(d.x-=t),Object.hasOwn(d,"y")&&(d.y-=r)}),s.width=n-t+a,s.height=o-r+l}function bF(e){e.edges().forEach(t=>{let n=e.edge(t),r=e.node(t.v),o=e.node(t.w),s,a;n.points?(s=n.points[0],a=n.points[n.points.length-1]):(n.points=[],s=o,a=r),n.points.unshift(oT(r,s)),n.points.push(oT(o,a))})}function vF(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 UF(e){e.edges().forEach(t=>{let n=e.edge(t);n.reversed&&n.points.reverse()})}function wF(e){e.nodes().forEach(t=>{if(e.children(t).length){let n=e.node(t),r=e.node(n.borderTop),o=e.node(n.borderBottom),s=e.node(n.borderLeft[n.borderLeft.length-1]),a=e.node(n.borderRight[n.borderRight.length-1]);n.width=Math.abs(a.x-s.x),n.height=Math.abs(o.y-r.y),n.x=s.x+n.width/2,n.y=r.y+n.height/2}}),e.nodes().forEach(t=>{e.node(t).dummy==="border"&&e.removeNode(t)})}function BF(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 FF(e){Mo(e).forEach(t=>{let n=0;t.forEach((r,o)=>{let s=e.node(r);s.order=o+n,(s.selfEdges||[]).forEach(a=>{mr(e,"selfedge",{width:a.label.width,height:a.label.height,rank:s.rank,order:o+ ++n,e:a.e,label:a.label},"_se")}),delete s.selfEdges})})}function GF(e){e.nodes().forEach(t=>{let n=e.node(t);if(n.dummy==="selfedge"){let r=n,o=e.node(r.e.v),s=o.x+o.width/2,a=o.y,l=n.x-s,c=o.height/2;e.setEdge(r.e,r.label),e.removeNode(t),r.label.points=[{x:s+2*l/3,y:a-c},{x:s+5*l/6,y:a-c},{x:s+l,y:a},{x:s+5*l/6,y:a+c},{x:s+2*l/3,y:a+c}],r.label.x=n.x,r.label.y=n.y}})}function rl(e,t){return ta(Ri(e,t),Number)}function ol(e){let t={};return e&&Object.entries(e).forEach(([n,r])=>{typeof n=="string"&&(n=n.toLowerCase()),t[n]=r}),t}function HF(e){let t=Mo(e),n=new tt({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,o)=>{let s="layer"+o;n.setNode(s,{rank:"same"}),r.reduce((a,l)=>(n.setEdge(a,l,{style:"invis"}),l))}),n}var kF={graphlib:Vp,version:Qw,layout:AF,debug:HF,util:{time:rh,notime:oh}},Ai=kF;/*! For license information please see dagre.esm.js.LEGAL.txt */function jF(e,t,n={}){var o;if(e.length===0)return e;const r=new Ai.graphlib.Graph().setDefaultEdgeLabel(()=>({}));r.setGraph({rankdir:"LR",ranksep:60,nodesep:30,marginx:20,marginy:20});for(const s of e){const a={width:170,height:52};if(n.mode==="layered"&&((o=s.data)!=null&&o.layer)){const l=qs.indexOf(s.data.layer);l>=0&&(a.rank=l)}r.setNode(s.id,a)}for(const s of t)r.setEdge(s.source,s.target);return Ai.layout(r),e.map(s=>{const a=r.node(s.id);return{...s,position:{x:a.x-85,y:a.y-26}}})}function YF({data:e,selected:t}){const n=e.nodeType,r=e.isFocal,o=we[n]??"#8b949e",s=Wc[n]??n.toUpperCase();return i.jsxs("div",{style:{minWidth:140,maxWidth:190,background:"#161b22",border:`2px solid ${r||t?"#58a6ff":o}`,borderRadius:8,padding:"6px 8px",boxShadow:r?"0 0 0 2px rgba(88, 166, 255, 0.25)":"none"},children:[i.jsx(an,{type:"target",position:te.Left,style:{width:6,height:6,background:o,border:"none"}}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginBottom:2},children:[i.jsx("span",{style:{fontSize:8,fontWeight:700,letterSpacing:"0.04em",color:"#0d1117",background:o,borderRadius:3,padding:"1px 4px"},children:s}),e.domain&&i.jsx("span",{style:{color:"#8b949e",fontSize:9},children:e.domain})]}),i.jsx("div",{style:{color:"#e6edf3",fontSize:10,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.label,children:e.label}),i.jsx(an,{type:"source",position:te.Right,style:{width:6,height:6,background:o,border:"none"}})]})}const WF={miniDagNode:YF};function Rh({nodes:e,edges:t,focalNodeId:n,height:r=250,onNodeClick:o,interactive:s=!0,layoutMode:a="flow"}){const[l,c,E]=Fp([]),[d,u,T]=Gp([]);return f.useEffect(()=>{const S=e.map(A=>({id:A.id,type:"miniDagNode",position:{x:0,y:0},data:{label:A.name,nodeType:A.type,domain:A.domain,layer:Vc(A),isFocal:A.id===n}})),h=t.map((A,R)=>({id:`mini-edge-${R}-${A.source}-${A.target}`,source:A.source,target:A.target,style:{stroke:Yr[A.type]??"#8b949e",strokeWidth:1.4},markerEnd:{type:ur.ArrowClosed,color:Yr[A.type]??"#8b949e",width:10,height:10}}));c(jF(S,h,{mode:a})),u(h)},[e,t,n,a,c,u]),e.length===0?i.jsx("div",{style:{height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#8b949e",fontSize:11},children:"No lineage nodes to display"}):i.jsx("div",{style:{height:r,width:"100%",borderRadius:8,overflow:"hidden",border:"1px solid #30363d"},children:i.jsx(Bp,{nodes:l,edges:d,onNodesChange:s?E:void 0,onEdgesChange:s?T:void 0,onNodeClick:o?(S,h)=>o(h.id):void 0,nodeTypes:WF,fitView:!0,fitViewOptions:{padding:.15},proOptions:{hideAttribution:!0},nodesDraggable:s,nodesConnectable:!1,zoomOnScroll:s,panOnDrag:s,style:{background:"#0d1117"},children:i.jsx(kp,{color:"#21262d",gap:20,size:1})})})}function VF(e){const t=e.match(/^\s*block\s+"([^"]+)"/i);return t?t[1]:null}function $F(e){const t=[],n=/\b(?:FROM|JOIN)\s+([a-zA-Z_][\w.]*)/gi;for(const o of e.matchAll(n)){const s=o[1].toLowerCase();["select","where","group","order","having","limit","union","lateral"].includes(s)||t.push(s)}const r=/\bref\s*\(\s*"([^"]+)"\s*\)/gi;for(const o of e.matchAll(r))t.push(o[1]);return[...new Set(t)]}function XF(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 KF({cellContent:e,cellType:t,cellName:n,themeMode:r,t:o,onFocusNode:s}){const[a,l]=f.useState(!1),[c,E]=f.useState(!1),[d,u]=f.useState([]),[T,S]=f.useState([]),[h,A]=f.useState(),[R,p]=f.useState([]),[N,I]=f.useState({metrics:[],dimensions:[]}),[O,m]=f.useState(null),[C,g]=f.useState(null),_=(t==="dql"?VF(e):null)||n,P=f.useCallback(async()=>{if(!(!_&&t!=="sql")){E(!0),g(null);try{const b=$F(e);if(p(b),I(XF(e)),_){const F=`block:${_}`;A(F);const[x,w]=await Promise.all([Z.queryLineage({focus:F}),Z.fetchLineagePaths(F)]);x!=null&&x.graph&&(u(x.graph.nodes??[]),S(x.graph.edges??[])),w&&m(w)}else{A(void 0);const x=((await Z.fetchLineage()).nodes??[]).filter(w=>b.some(M=>w.name===M||w.id===`table:${M}`));u(x),S([])}}catch{g("Failed to load lineage")}finally{E(!1)}}},[_,e,t]);f.useEffect(()=>{a&&P()},[a,P]);const D=R.length>0||N.metrics.length>0||N.dimensions.length>0;return e.trim()?i.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`},children:[i.jsxs("button",{onClick:()=>l(b=>!b),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 12px",background:a?`${o.tableHeaderBg}60`:"transparent",border:"none",cursor:"pointer",color:o.textMuted,fontSize:10,fontFamily:o.font,transition:"background 0.15s"},children:[i.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",style:{flexShrink:0},children:[i.jsx("circle",{cx:"4",cy:"4",r:"2"}),i.jsx("circle",{cx:"12",cy:"8",r:"2"}),i.jsx("circle",{cx:"4",cy:"12",r:"2"}),i.jsx("line",{x1:"6",y1:"4",x2:"10",y2:"8"}),i.jsx("line",{x1:"6",y1:"12",x2:"10",y2:"8"})]}),i.jsx("span",{children:"Lineage"}),i.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:i.jsx("path",{d:"M1 3l4 4 4-4",stroke:"currentColor",fill:"none",strokeWidth:"1.5"})}),a&&_&&s&&i.jsx("span",{onClick:b=>{b.stopPropagation(),s(`block:${_}`)},style:{marginLeft:"auto",fontSize:9,color:o.accent,cursor:"pointer",textDecoration:"underline"},children:"View in DAG"})]}),a&&i.jsx("div",{style:{fontSize:11},children:c?i.jsx("div",{style:{color:o.textMuted,padding:"8px 12px"},children:"Loading lineage..."}):C?i.jsx("div",{style:{color:o.error,padding:"8px 12px"},children:C}):i.jsxs(i.Fragment,{children:[d.length>0&&h&&i.jsx("div",{style:{borderBottom:`1px solid ${o.cellBorder}`},children:i.jsx(Rh,{nodes:d,edges:T,focalNodeId:h,height:200,onNodeClick:s,interactive:!0,layoutMode:"flow"})}),i.jsxs("div",{style:{padding:"6px 12px 8px"},children:[O&&(O.upstreamPaths.length>0||O.downstreamPaths.length>0)&&i.jsxs("div",{style:{marginBottom:8},children:[i.jsx("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:4},children:"Complete Paths"}),i.jsxs("div",{style:{display:"grid",gap:6},children:[O.upstreamPaths.slice(0,3).map((b,F)=>i.jsx(Jl,{path:b,onNodeClick:s,focalNodeId:h,t:o},`up-${F}`)),O.downstreamPaths.slice(0,2).map((b,F)=>i.jsx(Jl,{path:b,onNodeClick:s,focalNodeId:h,t:o},`down-${F}`))]})]}),R.length>0&&i.jsxs("div",{style:{marginBottom:6},children:[i.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Reads From (",R.length,")"]}),R.map(b=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[i.jsx("span",{style:{color:we.source_table,fontSize:9,fontWeight:700,width:26},children:"TBL"}),i.jsx("span",{children:b})]},b))]}),N.metrics.length>0&&i.jsxs("div",{style:{marginBottom:6},children:[i.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Metrics (",N.metrics.length,")"]}),N.metrics.map(b=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[i.jsx("span",{style:{color:we.metric,fontSize:9,fontWeight:700,width:26},children:"MET"}),i.jsx("span",{children:b})]},b))]}),N.dimensions.length>0&&i.jsxs("div",{style:{marginBottom:6},children:[i.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Dimensions (",N.dimensions.length,")"]}),N.dimensions.map(b=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[i.jsx("span",{style:{color:we.dimension,fontSize:9,fontWeight:700,width:26},children:"DIM"}),i.jsx("span",{children:b})]},b))]}),!D&&d.length===0&&!O&&i.jsx("div",{style:{color:o.textMuted,padding:"2px 0"},children:"No lineage dependencies detected for this cell."})]})]})})]}):null}const H=e=>e.flatMap(zF),zF=e=>Fs(qF(e)).map(JF),JF=e=>e.replace(/ +/g," ").trim(),qF=e=>({type:"mandatory_block",items:gE(e,0)[0]}),gE=(e,t,n)=>{const r=[];for(;e[t];){const[o,s]=QF(e,t);if(r.push(o),t=s,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]},QF=(e,t)=>{const n=[];for(;;){const[r,o]=ZF(e,t);if(r)n.push(r),t=o;else break}return n.length===1?[n[0],t]:[{type:"concatenation",items:n},t]},ZF=(e,t)=>{if(e[t]==="{")return eG(e,t+1);if(e[t]==="[")return tG(e,t+1);{let n="";for(;e[t]&&/[A-Za-z0-9_ ]/.test(e[t]);)n+=e[t],t++;return[n,t]}},eG=(e,t)=>{const[n,r]=gE(e,t,"}");return[{type:"mandatory_block",items:n},r]},tG=(e,t)=>{const[n,r]=gE(e,t,"]");return[{type:"optional_block",items:n},r]},Fs=e=>{if(typeof e=="string")return[e];if(e.type==="concatenation")return e.items.map(Fs).reduce(nG,[""]);if(e.type==="mandatory_block")return e.items.flatMap(Fs);if(e.type==="optional_block")return["",...e.items.flatMap(Fs)];throw new Error(`Unknown node type: ${e}`)},nG=(e,t)=>{const n=[];for(const r of e)for(const o of t)n.push(r+o);return n};var V;(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"})(V=V||(V={}));const Ah=e=>({type:V.EOF,raw:"«EOF»",text:"«EOF»",start:e}),ln=Ah(1/0),$n=e=>t=>t.type===e.type&&t.text===e.text,cn={ARRAY:$n({text:"ARRAY",type:V.RESERVED_DATA_TYPE}),BY:$n({text:"BY",type:V.RESERVED_KEYWORD}),SET:$n({text:"SET",type:V.RESERVED_CLAUSE}),STRUCT:$n({text:"STRUCT",type:V.RESERVED_DATA_TYPE}),WINDOW:$n({text:"WINDOW",type:V.RESERVED_CLAUSE}),VALUES:$n({text:"VALUES",type:V.RESERVED_CLAUSE})},ph=e=>e===V.RESERVED_DATA_TYPE||e===V.RESERVED_KEYWORD||e===V.RESERVED_FUNCTION_NAME||e===V.RESERVED_KEYWORD_PHRASE||e===V.RESERVED_DATA_TYPE_PHRASE||e===V.RESERVED_CLAUSE||e===V.RESERVED_SELECT||e===V.RESERVED_SET_OPERATION||e===V.RESERVED_JOIN||e===V.ARRAY_KEYWORD||e===V.CASE||e===V.END||e===V.WHEN||e===V.ELSE||e===V.THEN||e===V.LIMIT||e===V.BETWEEN||e===V.AND||e===V.OR||e===V.XOR,rG=e=>e===V.AND||e===V.OR||e===V.XOR,oG=["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"],sG=["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"],iG=["ARRAY","BOOL","BYTES","DATE","DATETIME","GEOGRAPHY","INTERVAL","INT64","INT","SMALLINT","INTEGER","BIGINT","TINYINT","BYTEINT","NUMERIC","DECIMAL","BIGNUMERIC","BIGDECIMAL","FLOAT64","STRING","STRUCT","TIME","TIMEZONE"],aG=H(["SELECT [ALL | DISTINCT] [AS STRUCT | AS VALUE]"]),lG=H(["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"]),fT=H(["CREATE [OR REPLACE] [TEMP|TEMPORARY|SNAPSHOT|EXTERNAL] TABLE [IF NOT EXISTS]"]),sl=H(["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"]),cG=H(["UNION {ALL | DISTINCT}","EXCEPT DISTINCT","INTERSECT DISTINCT"]),EG=H(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN"]),dG=H(["TABLESAMPLE SYSTEM","ANY TYPE","ALL COLUMNS","NOT DETERMINISTIC","{ROWS | RANGE} BETWEEN","IS [NOT] DISTINCT FROM"]),uG=H([]),TG={name:"bigquery",tokenizerOptions:{reservedSelect:aG,reservedClauses:[...lG,...sl,...fT],reservedSetOperations:cG,reservedJoins:EG,reservedKeywordPhrases:dG,reservedDataTypePhrases:uG,reservedKeywords:sG,reservedDataTypes:iG,reservedFunctionNames:oG,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:SG},formatOptions:{onelineClauses:[...fT,...sl],tabularOnelineClauses:sl}};function SG(e){return fG(RG(e))}function fG(e){let t=ln;return e.map(n=>n.text==="OFFSET"&&t.text==="["?(t=n,Object.assign(Object.assign({},n),{type:V.RESERVED_FUNCTION_NAME})):(t=n,n))}function RG(e){var t;const n=[];for(let r=0;r<e.length;r++){const o=e[r];if((cn.ARRAY(o)||cn.STRUCT(o))&&((t=e[r+1])===null||t===void 0?void 0:t.text)==="<"){const s=AG(e,r+1),a=e.slice(r,s+1);n.push({type:V.IDENTIFIER,raw:a.map(RT("raw")).join(""),text:a.map(RT("text")).join(""),start:o.start}),r=s}else n.push(o)}return n}const RT=e=>t=>t.type===V.IDENTIFIER||t.type===V.COMMA?t[e]+" ":t[e];function AG(e,t){let n=0;for(let r=t;r<e.length;r++){const o=e[r];if(o.text==="<"?n++:o.text===">"?n--:o.text===">>"&&(n-=2),n===0)return r}return e.length-1}const pG=["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"],hG=["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"],IG=["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"],NG=H(["SELECT [DISTINCT]","MODIFY QUERY SELECT [DISTINCT]"]),OG=H(["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]"]),AT=H(["CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS]"]),il=H(["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"]),mG=H(["UNION [ALL | DISTINCT]","PARALLEL WITH"]),CG=H(["[GLOBAL] [INNER|LEFT|RIGHT|FULL|CROSS] [OUTER|SEMI|ANTI|ANY|ALL|ASOF] JOIN","[LEFT] ARRAY JOIN"]),gG=H(["{ROWS | RANGE} BETWEEN","ALTER MATERIALIZE STATISTICS"]),LG={name:"clickhouse",tokenizerOptions:{reservedSelect:NG,reservedClauses:[...OG,...AT,...il],reservedSetOperations:mG,reservedJoins:CG,reservedKeywordPhrases:gG,reservedKeywords:hG,reservedDataTypes:IG,reservedFunctionNames:pG,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:_G},formatOptions:{onelineClauses:[...AT,...il],tabularOnelineClauses:il}};function _G(e){return e.map((t,n)=>{const r=e[n+1]||ln,o=e[n-1]||ln;return t.type===V.RESERVED_SELECT&&(r.type===V.COMMA||o.type===V.RESERVED_CLAUSE||o.type===V.COMMA)?Object.assign(Object.assign({},t),{type:V.RESERVED_KEYWORD}):cn.SET(t)&&r.type===V.OPEN_PAREN?Object.assign(Object.assign({},t),{type:V.RESERVED_FUNCTION_NAME}):t})}const xG=["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"],yG=["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"],DG=["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"],MG=H(["SELECT [ALL | DISTINCT]"]),PG=H(["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"]),pT=H(["CREATE [GLOBAL TEMPORARY | EXTERNAL] TABLE [IF NOT EXISTS]"]),al=H(["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"]),bG=H(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),vG=H(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN"]),UG=H(["ON DELETE","ON UPDATE","SET NULL","{ROWS | RANGE} BETWEEN"]),wG=H([]),BG={name:"db2",tokenizerOptions:{reservedSelect:MG,reservedClauses:[...PG,...pT,...al],reservedSetOperations:bG,reservedJoins:vG,reservedKeywordPhrases:UG,reservedDataTypePhrases:wG,reservedKeywords:yG,reservedDataTypes:DG,reservedFunctionNames:xG,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:[...pT,...al],tabularOnelineClauses:al}},FG=["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"],GG=["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"],HG=["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"],kG=H(["SELECT [ALL | DISTINCT]"]),jG=H(["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"]),hT=H(["CREATE [OR REPLACE] TABLE"]),ll=H(["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}"]),YG=H(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),WG=H(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","[LEFT | RIGHT] EXCEPTION JOIN","{INNER | CROSS} JOIN"]),VG=H(["ON DELETE","ON UPDATE","SET NULL","{ROWS | RANGE} BETWEEN"]),$G=H([]),XG={name:"db2i",tokenizerOptions:{reservedSelect:kG,reservedClauses:[...jG,...hT,...ll],reservedSetOperations:YG,reservedJoins:WG,reservedKeywordPhrases:VG,reservedDataTypePhrases:$G,reservedKeywords:GG,reservedDataTypes:HG,reservedFunctionNames:FG,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:[...hT,...ll],tabularOnelineClauses:ll}},KG=["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"],zG=["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"],JG=["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"],qG=H(["SELECT [ALL | DISTINCT]"]),QG=H(["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"]),IT=H(["CREATE [OR REPLACE] [TEMPORARY | TEMP] TABLE [IF NOT EXISTS]"]),cl=H(["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]"]),ZG=H(["UNION [ALL | BY NAME]","EXCEPT [ALL]","INTERSECT [ALL]"]),eH=H(["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"]),tH=H(["{ROWS | RANGE | GROUPS} BETWEEN","SIMILAR TO","IS [NOT] DISTINCT FROM"]),nH=H(["TIMESTAMP WITH TIME ZONE"]),rH={name:"duckdb",tokenizerOptions:{reservedSelect:qG,reservedClauses:[...QG,...IT,...cl],reservedSetOperations:ZG,reservedJoins:eH,reservedKeywordPhrases:tH,reservedDataTypePhrases:nH,supportsXor:!0,reservedKeywords:zG,reservedDataTypes:JG,reservedFunctionNames:KG,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:[...IT,...cl],tabularOnelineClauses:cl}},oH=["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"],sH=["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"],iH=["ARRAY","BIGINT","BINARY","BOOLEAN","CHAR","DATE","DECIMAL","DOUBLE","FLOAT","INT","INTEGER","INTERVAL","MAP","NUMERIC","PRECISION","SMALLINT","STRUCT","TIMESTAMP","VARCHAR"],aH=H(["SELECT [ALL | DISTINCT]"]),lH=H(["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"]),NT=H(["CREATE [TEMPORARY] [EXTERNAL] TABLE [IF NOT EXISTS]"]),El=H(["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"]),cH=H(["UNION [ALL | DISTINCT]"]),EH=H(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","LEFT SEMI JOIN"]),dH=H(["{ROWS | RANGE} BETWEEN"]),uH=H([]),TH={name:"hive",tokenizerOptions:{reservedSelect:aH,reservedClauses:[...lH,...NT,...El],reservedSetOperations:cH,reservedJoins:EH,reservedKeywordPhrases:dH,reservedDataTypePhrases:uH,reservedKeywords:sH,reservedDataTypes:iH,reservedFunctionNames:oH,extraParens:["[]"],stringTypes:['""-bs',"''-bs"],identTypes:["``"],variableTypes:[{quote:"{}",prefixes:["$"],requirePrefix:!0}],operators:["%","~","^","|","&","<=>","==","!","||"]},formatOptions:{onelineClauses:[...NT,...El],tabularOnelineClauses:El}};function ra(e){return e.map((t,n)=>{const r=e[n+1]||ln;if(cn.SET(t)&&r.text==="(")return Object.assign(Object.assign({},t),{type:V.RESERVED_FUNCTION_NAME});const o=e[n-1]||ln;return cn.VALUES(t)&&o.text==="="?Object.assign(Object.assign({},t),{type:V.RESERVED_FUNCTION_NAME}):t})}const SH=["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"],fH=["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"],RH=["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"],AH=H(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),pH=H(["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"]),OT=H(["CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS]"]),dl=H(["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"]),hH=H(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]","MINUS [ALL | DISTINCT]"]),IH=H(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),NH=H(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),OH=H([]),mH={name:"mariadb",tokenizerOptions:{reservedSelect:AH,reservedClauses:[...pH,...OT,...dl],reservedSetOperations:hH,reservedJoins:IH,reservedKeywordPhrases:NH,reservedDataTypePhrases:OH,supportsXor:!0,reservedKeywords:SH,reservedDataTypes:fH,reservedFunctionNames:RH,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:ra},formatOptions:{onelineClauses:[...OT,...dl],tabularOnelineClauses:dl}},CH=["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"],gH=["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"],LH=["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"],_H=H(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),xH=H(["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"]),mT=H(["CREATE [TEMPORARY] TABLE [IF NOT EXISTS]"]),ul=H(["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"]),yH=H(["UNION [ALL | DISTINCT]"]),DH=H(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),MH=H(["ON {UPDATE | DELETE} [SET NULL]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),PH=H([]),bH={name:"mysql",tokenizerOptions:{reservedSelect:_H,reservedClauses:[...xH,...mT,...ul],reservedSetOperations:yH,reservedJoins:DH,reservedKeywordPhrases:MH,reservedDataTypePhrases:PH,supportsXor:!0,reservedKeywords:CH,reservedDataTypes:gH,reservedFunctionNames:LH,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:ra},formatOptions:{onelineClauses:[...mT,...ul],tabularOnelineClauses:ul}},vH=["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"],UH=["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"],wH=["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"],BH=H(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),FH=H(["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"]),CT=H(["CREATE [TEMPORARY] TABLE [IF NOT EXISTS]"]),Tl=H(["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"]),GH=H(["UNION [ALL | DISTINCT]"]),HH=H(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),kH=H(["ON {UPDATE | DELETE} [SET NULL]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),jH=H([]),YH={name:"tidb",tokenizerOptions:{reservedSelect:BH,reservedClauses:[...FH,...CT,...Tl],reservedSetOperations:GH,reservedJoins:HH,reservedKeywordPhrases:kH,reservedDataTypePhrases:jH,supportsXor:!0,reservedKeywords:vH,reservedDataTypes:UH,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:ra},formatOptions:{onelineClauses:[...CT,...Tl],tabularOnelineClauses:Tl}},WH=["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"],VH=["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"],$H=[],XH=H(["SELECT [ALL | DISTINCT]"]),KH=H(["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"]),gT=H(["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"]),zH=H(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),JH=H(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","INNER JOIN"]),qH=H(["{ROWS | RANGE | GROUPS} BETWEEN"]),QH=H([]),ZH={name:"n1ql",tokenizerOptions:{reservedSelect:XH,reservedClauses:[...KH,...gT],reservedSetOperations:zH,reservedJoins:JH,reservedKeywordPhrases:qH,reservedDataTypePhrases:QH,supportsXor:!0,reservedKeywords:VH,reservedDataTypes:$H,reservedFunctionNames:WH,stringTypes:['""-bs',"''-bs"],identTypes:["``"],extraParens:["[]","{}"],paramTypes:{positional:!0,numbered:["$"],named:["$"]},lineCommentTypes:["#","--"],operators:["%","==",":","||"]},formatOptions:{onelineClauses:gT}},e2=["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"],t2=["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"],n2=["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"],r2=H(["SELECT [ALL | DISTINCT | UNIQUE]"]),o2=H(["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"]),LT=H(["CREATE [GLOBAL TEMPORARY | PRIVATE TEMPORARY | SHARDED | DUPLICATED | IMMUTABLE BLOCKCHAIN | BLOCKCHAIN | IMMUTABLE] TABLE"]),Sl=H(["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"]),s2=H(["UNION [ALL]","MINUS","INTERSECT"]),i2=H(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN","{CROSS | OUTER} APPLY"]),a2=H(["ON {UPDATE | DELETE} [SET NULL]","ON COMMIT","{ROWS | RANGE} BETWEEN"]),l2=H([]),c2={name:"plsql",tokenizerOptions:{reservedSelect:r2,reservedClauses:[...o2,...LT,...Sl],reservedSetOperations:s2,reservedJoins:i2,reservedKeywordPhrases:a2,reservedDataTypePhrases:l2,supportsXor:!0,reservedKeywords:e2,reservedDataTypes:t2,reservedFunctionNames:n2,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:E2},formatOptions:{alwaysDenseOperators:["@"],onelineClauses:[...LT,...Sl],tabularOnelineClauses:Sl}};function E2(e){let t=ln;return e.map(n=>cn.SET(n)&&cn.BY(t)?Object.assign(Object.assign({},n),{type:V.RESERVED_KEYWORD}):(ph(n.type)&&(t=n),n))}const d2=["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"],u2=["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"],T2=["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"],S2=H(["SELECT [ALL | DISTINCT]"]),f2=H(["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"]),_T=H(["CREATE [GLOBAL | LOCAL] [TEMPORARY | TEMP | UNLOGGED] TABLE [IF NOT EXISTS]"]),fl=H(["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"]),R2=H(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),A2=H(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),p2=H(["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"]),h2=H(["[TIMESTAMP | TIME] {WITH | WITHOUT} TIME ZONE"]),I2={name:"postgresql",tokenizerOptions:{reservedSelect:S2,reservedClauses:[...f2,..._T,...fl],reservedSetOperations:R2,reservedJoins:A2,reservedKeywordPhrases:p2,reservedDataTypePhrases:h2,reservedKeywords:u2,reservedDataTypes:T2,reservedFunctionNames:d2,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:[..._T,...fl],tabularOnelineClauses:fl}},N2=["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"],O2=["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"],m2=["ARRAY","BIGINT","BPCHAR","CHAR","CHARACTER VARYING","CHARACTER","DECIMAL","INT","INT2","INT4","INT8","INTEGER","NCHAR","NUMERIC","NVARCHAR","SMALLINT","TEXT","VARBYTE","VARCHAR"],C2=H(["SELECT [ALL | DISTINCT]"]),g2=H(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","QUALIFY","PARTITION BY","ORDER BY","LIMIT","OFFSET","INSERT INTO","VALUES","SET"]),xT=H(["CREATE [TEMPORARY | TEMP | LOCAL TEMPORARY | LOCAL TEMP] TABLE [IF NOT EXISTS]"]),Rl=H(["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"]),L2=H(["UNION [ALL]","EXCEPT","INTERSECT","MINUS"]),_2=H(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),x2=H(["NULL AS","DATA CATALOG","HIVE METASTORE","{ROWS | RANGE} BETWEEN"]),y2=H([]),D2={name:"redshift",tokenizerOptions:{reservedSelect:C2,reservedClauses:[...g2,...xT,...Rl],reservedSetOperations:L2,reservedJoins:_2,reservedKeywordPhrases:x2,reservedDataTypePhrases:y2,reservedKeywords:O2,reservedDataTypes:m2,reservedFunctionNames:N2,extraParens:["[]"],stringTypes:["''-qq"],identTypes:['""-qq'],identChars:{first:"#"},paramTypes:{numbered:["$"]},operators:["^","%","@","|/","||/","&","|","~","<<",">>","||","::"]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...xT,...Rl],tabularOnelineClauses:Rl}},M2=["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"],P2=["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"],b2=["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"],v2=H(["SELECT [ALL | DISTINCT]"]),U2=H(["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"]),yT=H(["CREATE [EXTERNAL] TABLE [IF NOT EXISTS]"]),Al=H(["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"]),w2=H(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),B2=H(["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"]),F2=H(["ON DELETE","ON UPDATE","CURRENT ROW","{ROWS | RANGE} BETWEEN"]),G2=H([]),H2={name:"spark",tokenizerOptions:{reservedSelect:v2,reservedClauses:[...U2,...yT,...Al],reservedSetOperations:w2,reservedJoins:B2,reservedKeywordPhrases:F2,reservedDataTypePhrases:G2,supportsXor:!0,reservedKeywords:M2,reservedDataTypes:P2,reservedFunctionNames:b2,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:k2},formatOptions:{onelineClauses:[...yT,...Al],tabularOnelineClauses:Al}};function k2(e){return e.map((t,n)=>{const r=e[n-1]||ln,o=e[n+1]||ln;return cn.WINDOW(t)&&o.type===V.OPEN_PAREN?Object.assign(Object.assign({},t),{type:V.RESERVED_FUNCTION_NAME}):t.text==="ITEMS"&&t.type===V.RESERVED_KEYWORD&&!(r.text==="COLLECTION"&&o.text==="TERMINATED")?Object.assign(Object.assign({},t),{type:V.IDENTIFIER,text:t.raw}):t})}const j2=["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"],Y2=["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"],W2=["ANY","ARRAY","BLOB","CHARACTER","DECIMAL","INT","INTEGER","NATIVE CHARACTER","NCHAR","NUMERIC","NVARCHAR","REAL","TEXT","VARCHAR","VARYING CHARACTER"],V2=H(["SELECT [ALL | DISTINCT]"]),$2=H(["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"]),DT=H(["CREATE [TEMPORARY | TEMP] TABLE [IF NOT EXISTS]"]),pl=H(["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"]),X2=H(["UNION [ALL]","EXCEPT","INTERSECT"]),K2=H(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),z2=H(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE | GROUPS} BETWEEN","DO UPDATE"]),J2=H([]),q2={name:"sqlite",tokenizerOptions:{reservedSelect:V2,reservedClauses:[...$2,...DT,...pl],reservedSetOperations:X2,reservedJoins:K2,reservedKeywordPhrases:z2,reservedDataTypePhrases:J2,reservedKeywords:Y2,reservedDataTypes:W2,reservedFunctionNames:j2,stringTypes:["''-qq",{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq',"``","[]"],paramTypes:{positional:!0,numbered:["?"],named:[":","@","$"]},operators:["%","~","&","|","<<",">>","==","->","->>","||"]},formatOptions:{onelineClauses:[...DT,...pl],tabularOnelineClauses:pl}},Q2=["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"],Z2=["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"],ek=["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"],tk=H(["SELECT [ALL | DISTINCT]"]),nk=H(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY [ALL | DISTINCT]","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","FETCH {FIRST | NEXT}","INSERT INTO","VALUES","SET"]),MT=H(["CREATE [GLOBAL TEMPORARY | LOCAL TEMPORARY] TABLE"]),hl=H(["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"]),rk=H(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),ok=H(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),sk=H(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE} BETWEEN"]),ik=H([]),ak={name:"sql",tokenizerOptions:{reservedSelect:tk,reservedClauses:[...nk,...MT,...hl],reservedSetOperations:rk,reservedJoins:ok,reservedKeywordPhrases:sk,reservedDataTypePhrases:ik,reservedKeywords:Z2,reservedDataTypes:ek,reservedFunctionNames:Q2,stringTypes:[{quote:"''-qq-bs",prefixes:["N","U&"]},{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq',"``"],paramTypes:{positional:!0},operators:["||"]},formatOptions:{onelineClauses:[...MT,...hl],tabularOnelineClauses:hl}},lk=["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"],ck=["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"],Ek=["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"],dk=H(["SELECT [ALL | DISTINCT]"]),uk=H(["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"]),PT=H(["CREATE TABLE [IF NOT EXISTS]"]),Il=H(["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"]),Tk=H(["UNION [ALL | DISTINCT] [CORRESPONDING]","EXCEPT [ALL | DISTINCT] [CORRESPONDING]","INTERSECT [ALL | DISTINCT] [CORRESPONDING]"]),Sk=H(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),fk=H(["{ROWS | RANGE | GROUPS} BETWEEN","IS [NOT] DISTINCT FROM"]),Rk=H([]),Ak={name:"trino",tokenizerOptions:{reservedSelect:dk,reservedClauses:[...uk,...PT,...Il],reservedSetOperations:Tk,reservedJoins:Sk,reservedKeywordPhrases:fk,reservedDataTypePhrases:Rk,reservedKeywords:ck,reservedDataTypes:Ek,reservedFunctionNames:lk,extraParens:["[]","{}"],stringTypes:[{quote:"''-qq",prefixes:["U&"]},{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq'],paramTypes:{positional:!0},operators:["%","->","=>",":","||","|","^","$"]},formatOptions:{onelineClauses:[...PT,...Il],tabularOnelineClauses:Il}},pk=["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"],hk=["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"],Ik=["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"],Nk=H(["SELECT [ALL | DISTINCT]"]),Ok=H(["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"]),bT=H(["CREATE TABLE"]),Nl=H(["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"]),mk=H(["UNION [ALL]","EXCEPT","INTERSECT"]),Ck=H(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","{CROSS | OUTER} APPLY"]),gk=H(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE} BETWEEN"]),Lk=H([]),_k={name:"transactsql",tokenizerOptions:{reservedSelect:Nk,reservedClauses:[...Ok,...bT,...Nl],reservedSetOperations:mk,reservedJoins:Ck,reservedKeywordPhrases:gk,reservedDataTypePhrases:Lk,reservedKeywords:hk,reservedDataTypes:Ik,reservedFunctionNames:pk,nestedBlockComments:!0,stringTypes:[{quote:"''-qq",prefixes:["N"]},"{}"],identTypes:['""-qq',"[]"],identChars:{first:"#@",rest:"#@$"},paramTypes:{named:["@"],quoted:["@"]},operators:["%","&","|","^","~","!<","!>","+=","-=","*=","/=","%=","|=","&=","^=","::",":"],propertyAccessOperators:[".."]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...bT,...Nl],tabularOnelineClauses:Nl}},xk=["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"],yk=["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"],Dk=["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"],Mk=H(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),Pk=H(["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"]),vT=H(["CREATE [ROWSTORE] [REFERENCE | TEMPORARY | GLOBAL TEMPORARY] TABLE [IF NOT EXISTS]"]),Ol=H(["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"]),bk=H(["UNION [ALL | DISTINCT]","EXCEPT","INTERSECT","MINUS"]),vk=H(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),Uk=H(["ON DELETE","ON UPDATE","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),wk=H([]),Bk={name:"singlestoredb",tokenizerOptions:{reservedSelect:Mk,reservedClauses:[...Pk,...vT,...Ol],reservedSetOperations:bk,reservedJoins:vk,reservedKeywordPhrases:Uk,reservedDataTypePhrases:wk,reservedKeywords:xk,reservedDataTypes:yk,reservedFunctionNames:Dk,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:ra},formatOptions:{alwaysDenseOperators:["::","::$","::%"],onelineClauses:[...vT,...Ol],tabularOnelineClauses:Ol}},Fk=["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"],Gk=["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"],Hk=["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"],kk=H(["SELECT [ALL | DISTINCT]"]),jk=H(["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"]),UT=H(["CREATE [OR REPLACE] [VOLATILE] TABLE [IF NOT EXISTS]","CREATE [OR REPLACE] [LOCAL | GLOBAL] {TEMP|TEMPORARY} TABLE [IF NOT EXISTS]"]),ml=H(["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"]),Yk=H(["UNION [ALL]","MINUS","EXCEPT","INTERSECT"]),Wk=H(["[INNER] JOIN","[NATURAL] {LEFT | RIGHT | FULL} [OUTER] JOIN","{CROSS | NATURAL} JOIN"]),Vk=H(["{ROWS | RANGE} BETWEEN","ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]"]),$k=H([]),Xk={name:"snowflake",tokenizerOptions:{reservedSelect:kk,reservedClauses:[...jk,...UT,...ml],reservedSetOperations:Yk,reservedJoins:Wk,reservedKeywordPhrases:Vk,reservedDataTypePhrases:$k,reservedKeywords:Gk,reservedDataTypes:Hk,reservedFunctionNames:Fk,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:[...UT,...ml],tabularOnelineClauses:ml}},Kk=Object.freeze(Object.defineProperty({__proto__:null,bigquery:TG,clickhouse:LG,db2:BG,db2i:XG,duckdb:rH,hive:TH,mariadb:mH,mysql:bH,n1ql:ZH,plsql:c2,postgresql:I2,redshift:D2,singlestoredb:Bk,snowflake:Xk,spark:H2,sql:ak,sqlite:q2,tidb:YH,transactsql:_k,trino:Ak},Symbol.toStringTag,{value:"Module"})),$r=e=>e[e.length-1],hh=e=>e.sort((t,n)=>n.length-t.length||t.localeCompare(n)),Gs=e=>e.replace(/\s+/gu," "),Cl=e=>/\n/.test(e),lt=e=>e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),wT=/\s+/uy,wn=e=>new RegExp(`(?:${e})`,"uy"),zk=e=>e.split("").map(t=>/ /gu.test(t)?"\\s+":`[${t.toUpperCase()}${t.toLowerCase()}]`).join(""),Jk=e=>e+"(?:-"+e+")*",qk=({prefixes:e,requirePrefix:t})=>`(?:${e.map(zk).join("|")}${t?"":"|"})`,Qk=e=>new RegExp(`(?:${e.map(lt).join("|")}).*?(?=\r
|
|
678
|
-
|\r|
|
|
679
|
-
|$)`,"uy"),BT=(e,t=[])=>{const n=e==="open"?0:1,r=["()",...t].map(o=>o[n]);return wn(r.map(lt).join("|"))},FT=e=>wn(`${hh(e).map(lt).join("|")}`),Zk=({rest:e,dashes:t})=>e||t?`(?![${e||""}${t?"-":""}])`:"",Dt=(e,t={})=>{if(e.length===0)return/^\b$/u;const n=Zk(t),r=hh(e).map(lt).join("|").replace(/ /gu,"\\s+");return new RegExp(`(?:${r})${n}\\b`,"iuy")},gl=(e,t)=>{if(!e.length)return;const n=e.map(lt).join("|");return wn(`(?:${n})(?:${t})`)},ej=()=>{const e={"<":">","[":"]","(":")","{":"}"},t="{left}(?:(?!{right}').)*?{right}",n=Object.entries(e).map(([a,l])=>t.replace(/{left}/g,lt(a)).replace(/{right}/g,lt(l))),r=lt(Object.keys(e).join(""));return`[Qq]'(?:${String.raw`(?<tag>[^\s${r}])(?:(?!\k<tag>').)*?\k<tag>`}|${n.join("|")})'`},GT={"``":"(?:`[^`]*`)+","[]":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''":ej()},Ih=e=>typeof e=="string"?GT[e]:"regex"in e?e.regex:qk(e)+GT[e.quote],tj=e=>wn(e.map(t=>"regex"in t?t.regex:Ih(t)).join("|")),Nh=e=>e.map(Ih).join("|"),HT=e=>wn(Nh(e)),nj=(e={})=>wn(Oh(e)),Oh=({first:e,rest:t,dashes:n,allowFirstCharNumber:r}={})=>{const o="\\p{Alphabetic}\\p{Mark}_",s="\\p{Decimal_Number}",a=lt(e??""),l=lt(t??""),c=r?`[${o}${s}${a}][${o}${s}${l}]*`:`[${o}${a}][${o}${s}${l}]*`;return n?Jk(c):c};function mh(e,t){const n=e.slice(0,t).split(/\n/);return{line:n.length,col:n[n.length-1].length+1}}class rj{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 o=this.getWhitespace();if(this.index<this.input.length){if(r=this.getNextToken(),!r)throw this.createParseError();n.push(Object.assign(Object.assign({},r),{precedingWhitespace:o}))}}return n}createParseError(){const t=this.input.slice(this.index,this.index+10),{line:n,col:r}=mh(this.input,this.index);return new Error(`Parse error: Unexpected "${t}" at line ${n} column ${r}.
|
|
680
|
-
${this.dialectInfo()}`)}dialectInfo(){return this.dialectName==="sql"?`This likely happens because you're using the default "sql" dialect.
|
|
681
|
-
If possible, please select a more specific dialect (like sqlite, postgresql, etc).`:`SQL dialect used: "${this.dialectName}".`}getWhitespace(){wT.lastIndex=this.index;const t=wT.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],o={type:t.type,raw:r,text:t.text?t.text(r):r,start:this.index};return t.key&&(o.key=t.key(r)),this.index+=r.length,o}}}const kT=/\/\*/uy,oj=/[\s\S]/uy,sj=/\*\//uy;class ij{constructor(){this.lastIndex=0}exec(t){let n="",r,o=0;if(r=this.matchSection(kT,t))n+=r,o++;else return null;for(;o>0;)if(r=this.matchSection(kT,t))n+=r,o++;else if(r=this.matchSection(sj,t))n+=r,o--;else if(r=this.matchSection(oj,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 aj{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],o=new rj(r,this.dialectName).tokenize(t);return this.cfg.postProcess?this.cfg.postProcess(o):o}buildRulesBeforeParams(t){var n,r,o;return this.validRules([{type:V.DISABLE_COMMENT,regex:/(\/\* *sql-formatter-disable *\*\/[\s\S]*?(?:\/\* *sql-formatter-enable *\*\/|$))/uy},{type:V.BLOCK_COMMENT,regex:t.nestedBlockComments?new ij:/(\/\*[^]*?\*\/)/uy},{type:V.LINE_COMMENT,regex:Qk((n=t.lineCommentTypes)!==null&&n!==void 0?n:["--"])},{type:V.QUOTED_IDENTIFIER,regex:HT(t.identTypes)},{type:V.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:V.RESERVED_KEYWORD_PHRASE,regex:Dt((r=t.reservedKeywordPhrases)!==null&&r!==void 0?r:[],t.identChars),text:ye},{type:V.RESERVED_DATA_TYPE_PHRASE,regex:Dt((o=t.reservedDataTypePhrases)!==null&&o!==void 0?o:[],t.identChars),text:ye},{type:V.CASE,regex:/CASE\b/iuy,text:ye},{type:V.END,regex:/END\b/iuy,text:ye},{type:V.BETWEEN,regex:/BETWEEN\b/iuy,text:ye},{type:V.LIMIT,regex:t.reservedClauses.includes("LIMIT")?/LIMIT\b/iuy:void 0,text:ye},{type:V.RESERVED_CLAUSE,regex:Dt(t.reservedClauses,t.identChars),text:ye},{type:V.RESERVED_SELECT,regex:Dt(t.reservedSelect,t.identChars),text:ye},{type:V.RESERVED_SET_OPERATION,regex:Dt(t.reservedSetOperations,t.identChars),text:ye},{type:V.WHEN,regex:/WHEN\b/iuy,text:ye},{type:V.ELSE,regex:/ELSE\b/iuy,text:ye},{type:V.THEN,regex:/THEN\b/iuy,text:ye},{type:V.RESERVED_JOIN,regex:Dt(t.reservedJoins,t.identChars),text:ye},{type:V.AND,regex:/AND\b/iuy,text:ye},{type:V.OR,regex:/OR\b/iuy,text:ye},{type:V.XOR,regex:t.supportsXor?/XOR\b/iuy:void 0,text:ye},...t.operatorKeyword?[{type:V.OPERATOR,regex:/OPERATOR *\([^)]+\)/iuy}]:[],{type:V.RESERVED_FUNCTION_NAME,regex:Dt(t.reservedFunctionNames,t.identChars),text:ye},{type:V.RESERVED_DATA_TYPE,regex:Dt(t.reservedDataTypes,t.identChars),text:ye},{type:V.RESERVED_KEYWORD,regex:Dt(t.reservedKeywords,t.identChars),text:ye}])}buildRulesAfterParams(t){var n,r;return this.validRules([{type:V.VARIABLE,regex:t.variableTypes?tj(t.variableTypes):void 0},{type:V.STRING,regex:HT(t.stringTypes)},{type:V.IDENTIFIER,regex:nj(t.identChars)},{type:V.DELIMITER,regex:/[;]/uy},{type:V.COMMA,regex:/[,]/y},{type:V.OPEN_PAREN,regex:BT("open",t.extraParens)},{type:V.CLOSE_PAREN,regex:BT("close",t.extraParens)},{type:V.OPERATOR,regex:FT(["+","-","/",">","<","=","<>","<=",">=","!=",...(n=t.operators)!==null&&n!==void 0?n:[]])},{type:V.ASTERISK,regex:/[*]/uy},{type:V.PROPERTY_ACCESS_OPERATOR,regex:FT([".",...(r=t.propertyAccessOperators)!==null&&r!==void 0?r:[]])}])}buildParamRules(t,n){var r,o,s,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)||((o=t.paramTypes)===null||o===void 0?void 0:o.quoted)||[],numbered:(n==null?void 0:n.numbered)||((s=t.paramTypes)===null||s===void 0?void 0:s.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:V.NAMED_PARAMETER,regex:gl(c.named,Oh(t.paramChars||t.identChars)),key:E=>E.slice(1)},{type:V.QUOTED_PARAMETER,regex:gl(c.quoted,Nh(t.identTypes)),key:E=>(({tokenKey:d,quoteChar:u})=>d.replace(new RegExp(lt("\\"+u),"gu"),u))({tokenKey:E.slice(2,-1),quoteChar:E.slice(-1)})},{type:V.NUMBERED_PARAMETER,regex:gl(c.numbered,"[0-9]+"),key:E=>E.slice(1)},{type:V.POSITIONAL_PARAMETER,regex:c.positional?/[?]/y:void 0},...c.custom.map(E=>{var d;return{type:V.CUSTOM_PARAMETER,regex:wn(E.regex),key:(d=E.key)!==null&&d!==void 0?d:(u=>u)}})])}validRules(t){return t.filter(n=>!!n.regex)}}const ye=e=>Gs(e.toUpperCase()),jT=new Map,lj=e=>{let t=jT.get(e);return t||(t=cj(e),jT.set(e,t)),t},cj=e=>({tokenizer:new aj(e.tokenizerOptions,e.name),formatOptions:Ej(e.formatOptions)}),Ej=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 dj(e){return e.indentStyle==="tabularLeft"||e.indentStyle==="tabularRight"?" ".repeat(10):e.useTabs?" ":" ".repeat(e.tabWidth)}function Xn(e){return e.indentStyle==="tabularLeft"||e.indentStyle==="tabularRight"}class uj{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 Hs={exports:{}},Tj=Hs.exports,YT;function Sj(){return YT||(YT=1,(function(e){(function(t,n){e.exports?e.exports=n():t.nearley=n()})(Tj,function(){function t(E,d,u){return this.id=++t.highestId,this.name=E,this.symbols=d,this.postprocess=u,this}t.highestId=0,t.prototype.toString=function(E){var d=typeof E>"u"?this.symbols.map(c).join(" "):this.symbols.slice(0,E).map(c).join(" ")+" ● "+this.symbols.slice(E).map(c).join(" ");return this.name+" → "+d};function n(E,d,u,T){this.rule=E,this.dot=d,this.reference=u,this.data=[],this.wantedBy=T,this.isComplete=this.dot===E.symbols.length}n.prototype.toString=function(){return"{"+this.rule.toString(this.dot)+"}, from: "+(this.reference||0)},n.prototype.nextState=function(E){var d=new n(this.rule,this.dot+1,this.reference,this.wantedBy);return d.left=this,d.right=E,d.isComplete&&(d.data=d.build(),d.right=void 0),d},n.prototype.build=function(){var E=[],d=this;do E.push(d.right.data),d=d.left;while(d.left);return E.reverse(),E},n.prototype.finish=function(){this.rule.postprocess&&(this.data=this.rule.postprocess(this.data,this.reference,a.fail))};function r(E,d){this.grammar=E,this.index=d,this.states=[],this.wants={},this.scannable=[],this.completed={}}r.prototype.process=function(E){for(var d=this.states,u=this.wants,T=this.completed,S=0;S<d.length;S++){var h=d[S];if(h.isComplete){if(h.finish(),h.data!==a.fail){for(var A=h.wantedBy,R=A.length;R--;){var p=A[R];this.complete(p,h)}if(h.reference===this.index){var N=h.rule.name;(this.completed[N]=this.completed[N]||[]).push(h)}}}else{var N=h.rule.symbols[h.dot];if(typeof N!="string"){this.scannable.push(h);continue}if(u[N]){if(u[N].push(h),T.hasOwnProperty(N))for(var I=T[N],R=0;R<I.length;R++){var O=I[R];this.complete(h,O)}}else u[N]=[h],this.predict(N)}}},r.prototype.predict=function(E){for(var d=this.grammar.byName[E]||[],u=0;u<d.length;u++){var T=d[u],S=this.wants[E],h=new n(T,0,this.index,S);this.states.push(h)}},r.prototype.complete=function(E,d){var u=E.nextState(d);this.states.push(u)};function o(E,d){this.rules=E,this.start=d||this.rules[0].name;var u=this.byName={};this.rules.forEach(function(T){u.hasOwnProperty(T.name)||(u[T.name]=[]),u[T.name].push(T)})}o.fromCompiled=function(T,d){var u=T.Lexer;T.ParserStart&&(d=T.ParserStart,T=T.ParserRules);var T=T.map(function(h){return new t(h.name,h.symbols,h.postprocess)}),S=new o(T,d);return S.lexer=u,S};function s(){this.reset("")}s.prototype.reset=function(E,d){this.buffer=E,this.index=0,this.line=d?d.line:1,this.lastLineBreak=d?-d.col:0},s.prototype.next=function(){if(this.index<this.buffer.length){var E=this.buffer[this.index++];return E===`
|
|
682
|
-
`&&(this.line+=1,this.lastLineBreak=this.index),{value:E}}},s.prototype.save=function(){return{line:this.line,col:this.index-this.lastLineBreak}},s.prototype.formatError=function(E,d){var u=this.buffer;if(typeof u=="string"){var T=u.split(`
|
|
683
|
-
`).slice(Math.max(0,this.line-5),this.line),S=u.indexOf(`
|
|
684
|
-
`,this.index);S===-1&&(S=u.length);var h=this.index-this.lastLineBreak,A=String(this.line).length;return d+=" at line "+this.line+" col "+h+`:
|
|
685
|
-
|
|
686
|
-
`,d+=T.map(function(p,N){return R(this.line-T.length+N+1,A)+" "+p},this).join(`
|
|
687
|
-
`),d+=`
|
|
688
|
-
`+R("",A+h)+`^
|
|
689
|
-
`,d}else return d+" at index "+(this.index-1);function R(p,N){var I=String(p);return Array(N-I.length+1).join(" ")+I}};function a(E,d,u){if(E instanceof o)var T=E,u=d;else var T=o.fromCompiled(E,d);this.grammar=T,this.options={keepHistory:!1,lexer:T.lexer||new s};for(var S in u||{})this.options[S]=u[S];this.lexer=this.options.lexer,this.lexerState=void 0;var h=new r(T,0);this.table=[h],h.wants[T.start]=[],h.predict(T.start),h.process(),this.current=0}a.fail={},a.prototype.feed=function(E){var d=this.lexer;d.reset(E,this.lexerState);for(var u;;){try{if(u=d.next(),!u)break}catch(g){var A=new r(this.grammar,this.current+1);this.table.push(A);var T=new Error(this.reportLexerError(g));throw T.offset=this.current,T.token=g.token,T}var S=this.table[this.current];this.options.keepHistory||delete this.table[this.current-1];var h=this.current+1,A=new r(this.grammar,h);this.table.push(A);for(var R=u.text!==void 0?u.text:u.value,p=d.constructor===s?u.value:u,N=S.scannable,I=N.length;I--;){var O=N[I],m=O.rule.symbols[O.dot];if(m.test?m.test(p):m.type?m.type===u.type:m.literal===R){var C=O.nextState({data:p,token:u,isToken:!0,reference:h-1});A.states.push(C)}}if(A.process(),A.states.length===0){var T=new Error(this.reportError(u));throw T.offset=this.current,T.token=u,T}this.options.keepHistory&&(S.lexerState=d.save()),this.current++}return S&&(this.lexerState=d.save()),this.results=this.finish(),this},a.prototype.reportLexerError=function(E){var d,u,T=E.token;return T?(d="input "+JSON.stringify(T.text[0])+" (lexer error)",u=this.lexer.formatError(T,"Syntax error")):(d="input (lexer error)",u=E.message),this.reportErrorCommon(u,d)},a.prototype.reportError=function(E){var d=(E.type?E.type+" token: ":"")+JSON.stringify(E.value!==void 0?E.value:E),u=this.lexer.formatError(E,"Syntax error");return this.reportErrorCommon(u,d)},a.prototype.reportErrorCommon=function(E,d){var u=[];u.push(E);var T=this.table.length-2,S=this.table[T],h=S.states.filter(function(R){var p=R.rule.symbols[R.dot];return p&&typeof p!="string"});if(h.length===0)u.push("Unexpected "+d+`. I did not expect any more input. Here is the state of my parse table:
|
|
690
|
-
`),this.displayStateStack(S.states,u);else{u.push("Unexpected "+d+`. Instead, I was expecting to see one of the following:
|
|
691
|
-
`);var A=h.map(function(R){return this.buildFirstStateStack(R,[])||[R]},this);A.forEach(function(R){var p=R[0],N=p.rule.symbols[p.dot],I=this.getSymbolDisplay(N);u.push("A "+I+" based on:"),this.displayStateStack(R,u)},this)}return u.push(""),u.join(`
|
|
692
|
-
`)},a.prototype.displayStateStack=function(E,d){for(var u,T=0,S=0;S<E.length;S++){var h=E[S],A=h.rule.toString(h.dot);A===u?T++:(T>0&&d.push(" ^ "+T+" more lines identical to this"),T=0,d.push(" "+A)),u=A}},a.prototype.getSymbolDisplay=function(E){return l(E)},a.prototype.buildFirstStateStack=function(E,d){if(d.indexOf(E)!==-1)return null;if(E.wantedBy.length===0)return[E];var u=E.wantedBy[0],T=[E].concat(d),S=this.buildFirstStateStack(u,T);return S===null?null:[E].concat(S)},a.prototype.save=function(){var E=this.table[this.current];return E.lexerState=this.lexerState,E},a.prototype.restore=function(E){var d=E.index;this.current=d,this.table[d]=E,this.table.splice(d+1),this.lexerState=E.lexerState,this.results=this.finish()},a.prototype.rewind=function(E){if(!this.options.keepHistory)throw new Error("set option `keepHistory` to enable rewinding");this.restore(this.table[E])},a.prototype.finish=function(){var E=[],d=this.grammar.start,u=this.table[this.table.length-1];return u.states.forEach(function(T){T.rule.name===d&&T.dot===T.rule.symbols.length&&T.reference===0&&T.data!==a.fail&&E.push(T)}),E.map(function(T){return T.data})};function l(E){var d=typeof E;if(d==="string")return E;if(d==="object"){if(E.literal)return JSON.stringify(E.literal);if(E instanceof RegExp)return"character matching "+E;if(E.type)return E.type+" token";if(E.test)return"token matching "+String(E.test);throw new Error("Unknown symbol type: "+E)}}function c(E){var d=typeof E;if(d==="string")return E;if(d==="object"){if(E.literal)return JSON.stringify(E.literal);if(E instanceof RegExp)return E.toString();if(E.type)return"%"+E.type;if(E.test)return"<"+String(E.test)+">";throw new Error("Unknown symbol type: "+E)}}return{Parser:a,Grammar:o,Rule:t}})})(Hs)),Hs.exports}var fj=Sj();const Rj=Ii(fj);function Aj(e){return e.map(pj).map(hj).map(Ij).map(Nj).map(Oj)}const pj=(e,t,n)=>{if(ph(e.type)){const r=mj(n,t);if(r&&r.type===V.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:V.IDENTIFIER,text:e.raw});const o=Cr(n,t);if(o&&o.type===V.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:V.IDENTIFIER,text:e.raw})}return e},hj=(e,t,n)=>{if(e.type===V.RESERVED_FUNCTION_NAME){const r=Cr(n,t);if(!r||!Ch(r))return Object.assign(Object.assign({},e),{type:V.IDENTIFIER,text:e.raw})}return e},Ij=(e,t,n)=>{if(e.type===V.RESERVED_DATA_TYPE){const r=Cr(n,t);if(r&&Ch(r))return Object.assign(Object.assign({},e),{type:V.RESERVED_PARAMETERIZED_DATA_TYPE})}return e},Nj=(e,t,n)=>{if(e.type===V.IDENTIFIER){const r=Cr(n,t);if(r&&gh(r))return Object.assign(Object.assign({},e),{type:V.ARRAY_IDENTIFIER})}return e},Oj=(e,t,n)=>{if(e.type===V.RESERVED_DATA_TYPE){const r=Cr(n,t);if(r&&gh(r))return Object.assign(Object.assign({},e),{type:V.ARRAY_KEYWORD})}return e},mj=(e,t)=>Cr(e,t,-1),Cr=(e,t,n=1)=>{let r=1;for(;e[t+r*n]&&Cj(e[t+r*n]);)r++;return e[t+r*n]},Ch=e=>e.type===V.OPEN_PAREN&&e.text==="(",gh=e=>e.type===V.OPEN_PAREN&&e.text==="[",Cj=e=>e.type===V.BLOCK_COMMENT||e.type===V.LINE_COMMENT;class Lh{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}=mh(this.input,t.start);return`Parse error at token: ${t.text} at line ${n} column ${r}`}has(t){return t in V}}var ee;(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"})(ee=ee||(ee={}));function Ll(e){return e[0]}const le=new Lh(e=>[]),pn=([[e]])=>e,De=e=>({type:ee.keyword,tokenType:e.type,text:e.text,raw:e.raw}),WT=e=>({type:ee.data_type,text:e.text,raw:e.raw}),Me=(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),gj=(e,{leading:t,trailing:n})=>{if(t!=null&&t.length){const[r,...o]=e;e=[Me(r,{leading:t}),...o]}if(n!=null&&n.length){const r=e.slice(0,-1),o=e[e.length-1];e=[...r,Me(o,{trailing:n})]}return e},Lj={Lexer:le,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:[le.has("DELIMITER")?{type:"DELIMITER"}:DELIMITER]},{name:"statement$subexpression$1",symbols:[le.has("EOF")?{type:"EOF"}:EOF]},{name:"statement",symbols:["expressions_or_clauses","statement$subexpression$1"],postprocess:([e,[t]])=>({type:ee.statement,children:e,hasSemicolon:t.type===V.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:pn},{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:[le.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:Ll},{name:"limit_clause$ebnf$1",symbols:[],postprocess:()=>null},{name:"limit_clause",symbols:[le.has("LIMIT")?{type:"LIMIT"}:LIMIT,"_","expression_chain_","limit_clause$ebnf$1"],postprocess:([e,t,n,r])=>{if(r){const[o,s]=r;return{type:ee.limit_clause,limitKw:Me(De(e),{trailing:t}),offset:n,count:s}}else return{type:ee.limit_clause,limitKw:Me(De(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:[le.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT,"select_clause$subexpression$1"],postprocess:([e,[t,n]])=>({type:ee.clause,nameKw:De(e),children:[t,...n]})},{name:"select_clause",symbols:[le.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT],postprocess:([e])=>({type:ee.clause,nameKw:De(e),children:[]})},{name:"all_columns_asterisk",symbols:[le.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK],postprocess:()=>({type:ee.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:[le.has("RESERVED_CLAUSE")?{type:"RESERVED_CLAUSE"}:RESERVED_CLAUSE,"other_clause$ebnf$1"],postprocess:([e,t])=>({type:ee.clause,nameKw:De(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:[le.has("RESERVED_SET_OPERATION")?{type:"RESERVED_SET_OPERATION"}:RESERVED_SET_OPERATION,"set_operation$ebnf$1"],postprocess:([e,t])=>({type:ee.set_operation,nameKw:De(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:Ll},{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])=>Me(e,{trailing:t})},{name:"_expression_with_comments",symbols:["_","expression"],postprocess:([e,t])=>Me(t,{leading:e})},{name:"_andless_expression_with_comments",symbols:["_","andless_expression"],postprocess:([e,t])=>Me(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:pn},{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:pn},{name:"expression$subexpression$1",symbols:["andless_expression"]},{name:"expression$subexpression$1",symbols:["logic_operator"]},{name:"expression",symbols:["expression$subexpression$1"],postprocess:pn},{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:pn},{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:pn},{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:pn},{name:"array_subscript",symbols:[le.has("ARRAY_IDENTIFIER")?{type:"ARRAY_IDENTIFIER"}:ARRAY_IDENTIFIER,"_","square_brackets"],postprocess:([e,t,n])=>({type:ee.array_subscript,array:Me({type:ee.identifier,quoted:!1,text:e.text},{trailing:t}),parenthesis:n})},{name:"array_subscript",symbols:[le.has("ARRAY_KEYWORD")?{type:"ARRAY_KEYWORD"}:ARRAY_KEYWORD,"_","square_brackets"],postprocess:([e,t,n])=>({type:ee.array_subscript,array:Me(De(e),{trailing:t}),parenthesis:n})},{name:"function_call",symbols:[le.has("RESERVED_FUNCTION_NAME")?{type:"RESERVED_FUNCTION_NAME"}:RESERVED_FUNCTION_NAME,"_","parenthesis"],postprocess:([e,t,n])=>({type:ee.function_call,nameKw:Me(De(e),{trailing:t}),parenthesis:n})},{name:"parenthesis",symbols:[{literal:"("},"expressions_or_clauses",{literal:")"}],postprocess:([e,t,n])=>({type:ee.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:ee.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:ee.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","_",le.has("PROPERTY_ACCESS_OPERATOR")?{type:"PROPERTY_ACCESS_OPERATOR"}:PROPERTY_ACCESS_OPERATOR,"_","property_access$subexpression$1"],postprocess:([e,t,n,r,[o]])=>({type:ee.property_access,object:Me(e,{trailing:t}),operator:n.text,property:Me(o,{leading:r})})},{name:"between_predicate",symbols:[le.has("BETWEEN")?{type:"BETWEEN"}:BETWEEN,"_","andless_expression_chain","_",le.has("AND")?{type:"AND"}:AND,"_","andless_expression"],postprocess:([e,t,n,r,o,s,a])=>({type:ee.between_predicate,betweenKw:De(e),expr1:gj(n,{leading:t,trailing:r}),andKw:De(o),expr2:[Me(a,{leading:s})]})},{name:"case_expression$ebnf$1",symbols:["expression_chain_"],postprocess:Ll},{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:[le.has("CASE")?{type:"CASE"}:CASE,"_","case_expression$ebnf$1","case_expression$ebnf$2",le.has("END")?{type:"END"}:END],postprocess:([e,t,n,r,o])=>({type:ee.case_expression,caseKw:Me(De(e),{trailing:t}),endKw:De(o),expr:n||[],clauses:r})},{name:"case_clause",symbols:[le.has("WHEN")?{type:"WHEN"}:WHEN,"_","expression_chain_",le.has("THEN")?{type:"THEN"}:THEN,"_","expression_chain_"],postprocess:([e,t,n,r,o,s])=>({type:ee.case_when,whenKw:Me(De(e),{trailing:t}),thenKw:Me(De(r),{trailing:o}),condition:n,result:s})},{name:"case_clause",symbols:[le.has("ELSE")?{type:"ELSE"}:ELSE,"_","expression_chain_"],postprocess:([e,t,n])=>({type:ee.case_else,elseKw:Me(De(e),{trailing:t}),result:n})},{name:"comma$subexpression$1",symbols:[le.has("COMMA")?{type:"COMMA"}:COMMA]},{name:"comma",symbols:["comma$subexpression$1"],postprocess:([[e]])=>({type:ee.comma})},{name:"asterisk$subexpression$1",symbols:[le.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK]},{name:"asterisk",symbols:["asterisk$subexpression$1"],postprocess:([[e]])=>({type:ee.operator,text:e.text})},{name:"operator$subexpression$1",symbols:[le.has("OPERATOR")?{type:"OPERATOR"}:OPERATOR]},{name:"operator",symbols:["operator$subexpression$1"],postprocess:([[e]])=>({type:ee.operator,text:e.text})},{name:"identifier$subexpression$1",symbols:[le.has("IDENTIFIER")?{type:"IDENTIFIER"}:IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[le.has("QUOTED_IDENTIFIER")?{type:"QUOTED_IDENTIFIER"}:QUOTED_IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[le.has("VARIABLE")?{type:"VARIABLE"}:VARIABLE]},{name:"identifier",symbols:["identifier$subexpression$1"],postprocess:([[e]])=>({type:ee.identifier,quoted:e.type!=="IDENTIFIER",text:e.text})},{name:"parameter$subexpression$1",symbols:[le.has("NAMED_PARAMETER")?{type:"NAMED_PARAMETER"}:NAMED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[le.has("QUOTED_PARAMETER")?{type:"QUOTED_PARAMETER"}:QUOTED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[le.has("NUMBERED_PARAMETER")?{type:"NUMBERED_PARAMETER"}:NUMBERED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[le.has("POSITIONAL_PARAMETER")?{type:"POSITIONAL_PARAMETER"}:POSITIONAL_PARAMETER]},{name:"parameter$subexpression$1",symbols:[le.has("CUSTOM_PARAMETER")?{type:"CUSTOM_PARAMETER"}:CUSTOM_PARAMETER]},{name:"parameter",symbols:["parameter$subexpression$1"],postprocess:([[e]])=>({type:ee.parameter,key:e.key,text:e.text})},{name:"literal$subexpression$1",symbols:[le.has("NUMBER")?{type:"NUMBER"}:NUMBER]},{name:"literal$subexpression$1",symbols:[le.has("STRING")?{type:"STRING"}:STRING]},{name:"literal",symbols:["literal$subexpression$1"],postprocess:([[e]])=>({type:ee.literal,text:e.text})},{name:"keyword$subexpression$1",symbols:[le.has("RESERVED_KEYWORD")?{type:"RESERVED_KEYWORD"}:RESERVED_KEYWORD]},{name:"keyword$subexpression$1",symbols:[le.has("RESERVED_KEYWORD_PHRASE")?{type:"RESERVED_KEYWORD_PHRASE"}:RESERVED_KEYWORD_PHRASE]},{name:"keyword$subexpression$1",symbols:[le.has("RESERVED_JOIN")?{type:"RESERVED_JOIN"}:RESERVED_JOIN]},{name:"keyword",symbols:["keyword$subexpression$1"],postprocess:([[e]])=>De(e)},{name:"data_type$subexpression$1",symbols:[le.has("RESERVED_DATA_TYPE")?{type:"RESERVED_DATA_TYPE"}:RESERVED_DATA_TYPE]},{name:"data_type$subexpression$1",symbols:[le.has("RESERVED_DATA_TYPE_PHRASE")?{type:"RESERVED_DATA_TYPE_PHRASE"}:RESERVED_DATA_TYPE_PHRASE]},{name:"data_type",symbols:["data_type$subexpression$1"],postprocess:([[e]])=>WT(e)},{name:"data_type",symbols:[le.has("RESERVED_PARAMETERIZED_DATA_TYPE")?{type:"RESERVED_PARAMETERIZED_DATA_TYPE"}:RESERVED_PARAMETERIZED_DATA_TYPE,"_","parenthesis"],postprocess:([e,t,n])=>({type:ee.parameterized_data_type,dataType:Me(WT(e),{trailing:t}),parenthesis:n})},{name:"logic_operator$subexpression$1",symbols:[le.has("AND")?{type:"AND"}:AND]},{name:"logic_operator$subexpression$1",symbols:[le.has("OR")?{type:"OR"}:OR]},{name:"logic_operator$subexpression$1",symbols:[le.has("XOR")?{type:"XOR"}:XOR]},{name:"logic_operator",symbols:["logic_operator$subexpression$1"],postprocess:([[e]])=>De(e)},{name:"other_keyword$subexpression$1",symbols:[le.has("WHEN")?{type:"WHEN"}:WHEN]},{name:"other_keyword$subexpression$1",symbols:[le.has("THEN")?{type:"THEN"}:THEN]},{name:"other_keyword$subexpression$1",symbols:[le.has("ELSE")?{type:"ELSE"}:ELSE]},{name:"other_keyword$subexpression$1",symbols:[le.has("END")?{type:"END"}:END]},{name:"other_keyword",symbols:["other_keyword$subexpression$1"],postprocess:([[e]])=>De(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:[le.has("LINE_COMMENT")?{type:"LINE_COMMENT"}:LINE_COMMENT],postprocess:([e])=>({type:ee.line_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[le.has("BLOCK_COMMENT")?{type:"BLOCK_COMMENT"}:BLOCK_COMMENT],postprocess:([e])=>({type:ee.block_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[le.has("DISABLE_COMMENT")?{type:"DISABLE_COMMENT"}:DISABLE_COMMENT],postprocess:([e])=>({type:ee.disable_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})}],ParserStart:"main"},{Parser:_j,Grammar:xj}=Rj;function yj(e){let t={};const n=new Lh(o=>[...Aj(e.tokenize(o,t)),Ah(o.length)]),r=new _j(xj.fromCompiled(Lj),{lexer:n});return{parse:(o,s)=>{t=s;const{results:a}=r.feed(o);if(a.length===1)return a[0];throw a.length===0?new Error("Parse error: Invalid SQL"):new Error(`Parse error: Ambiguous grammar
|
|
693
|
-
${JSON.stringify(a,void 0,2)}`)}}}var W;(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"})(W=W||(W={}));class _h{constructor(t){this.indentation=t,this.items=[]}add(...t){for(const n of t)switch(n){case W.SPACE:this.items.push(W.SPACE);break;case W.NO_SPACE:this.trimHorizontalWhitespace();break;case W.NO_NEWLINE:this.trimWhitespace();break;case W.NEWLINE:this.trimHorizontalWhitespace(),this.addNewline(W.NEWLINE);break;case W.MANDATORY_NEWLINE:this.trimHorizontalWhitespace(),this.addNewline(W.MANDATORY_NEWLINE);break;case W.INDENT:this.addIndentation();break;case W.SINGLE_INDENT:this.items.push(W.SINGLE_INDENT);break;default:this.items.push(n)}}trimHorizontalWhitespace(){for(;Dj($r(this.items));)this.items.pop()}trimWhitespace(){for(;Mj($r(this.items));)this.items.pop()}addNewline(t){if(this.items.length>0)switch($r(this.items)){case W.NEWLINE:this.items.pop(),this.items.push(t);break;case W.MANDATORY_NEWLINE:break;default:this.items.push(t);break}}addIndentation(){for(let t=0;t<this.indentation.getLevel();t++)this.items.push(W.SINGLE_INDENT)}toString(){return this.items.map(t=>this.itemToString(t)).join("")}getLayoutItems(){return this.items}itemToString(t){switch(t){case W.SPACE:return" ";case W.NEWLINE:case W.MANDATORY_NEWLINE:return`
|
|
694
|
-
`;case W.SINGLE_INDENT:return this.indentation.getSingleIndent();default:return t}}}const Dj=e=>e===W.SPACE||e===W.SINGLE_INDENT,Mj=e=>e===W.SPACE||e===W.SINGLE_INDENT||e===W.NEWLINE;function VT(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 $T(e){return rG(e)||e===V.RESERVED_CLAUSE||e===V.RESERVED_SELECT||e===V.RESERVED_SET_OPERATION||e===V.RESERVED_JOIN||e===V.LIMIT}const _l="top-level",Pj="block-level";class xh{constructor(t){this.indent=t,this.indentTypes=[]}getSingleIndent(){return this.indent}getLevel(){return this.indentTypes.length}increaseTopLevel(){this.indentTypes.push(_l)}increaseBlockLevel(){this.indentTypes.push(Pj)}decreaseTopLevel(){this.indentTypes.length>0&&$r(this.indentTypes)===_l&&this.indentTypes.pop()}decreaseBlockLevel(){for(;this.indentTypes.length>0&&this.indentTypes.pop()===_l;);}}class bj extends _h{constructor(t){super(new xh("")),this.expressionWidth=t,this.length=0,this.trailingSpace=!1}add(...t){if(t.forEach(n=>this.addToLength(n)),this.length>this.expressionWidth)throw new uc;super.add(...t)}addToLength(t){if(typeof t=="string")this.length+=t.length,this.trailingSpace=!1;else{if(t===W.MANDATORY_NEWLINE||t===W.NEWLINE)throw new uc;t===W.INDENT||t===W.SINGLE_INDENT||t===W.SPACE?this.trailingSpace||(this.length++,this.trailingSpace=!0):(t===W.NO_NEWLINE||t===W.NO_SPACE)&&this.trailingSpace&&(this.trailingSpace=!1,this.length--)}}}class uc extends Error{}class pi{constructor({cfg:t,dialectCfg:n,params:r,layout:o,inline:s=!1}){this.inline=!1,this.nodes=[],this.index=-1,this.cfg=t,this.dialectCfg=n,this.inline=s,this.params=r,this.layout=o}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 ee.function_call:return this.formatFunctionCall(t);case ee.parameterized_data_type:return this.formatParameterizedDataType(t);case ee.array_subscript:return this.formatArraySubscript(t);case ee.property_access:return this.formatPropertyAccess(t);case ee.parenthesis:return this.formatParenthesis(t);case ee.between_predicate:return this.formatBetweenPredicate(t);case ee.case_expression:return this.formatCaseExpression(t);case ee.case_when:return this.formatCaseWhen(t);case ee.case_else:return this.formatCaseElse(t);case ee.clause:return this.formatClause(t);case ee.set_operation:return this.formatSetOperation(t);case ee.limit_clause:return this.formatLimitClause(t);case ee.all_columns_asterisk:return this.formatAllColumnsAsterisk(t);case ee.literal:return this.formatLiteral(t);case ee.identifier:return this.formatIdentifier(t);case ee.parameter:return this.formatParameter(t);case ee.operator:return this.formatOperator(t);case ee.comma:return this.formatComma(t);case ee.line_comment:return this.formatLineComment(t);case ee.block_comment:return this.formatBlockComment(t);case ee.disable_comment:return this.formatBlockComment(t);case ee.data_type:return this.formatDataType(t);case ee.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 ee.data_type:n=this.showDataType(t.array);break;case ee.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(W.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(W.NO_SPACE,t.closeParen,W.SPACE)):(this.layout.add(t.openParen,W.NEWLINE),Xn(this.cfg)?(this.layout.add(W.INDENT),this.layout=this.formatSubExpression(t.children)):(this.layout.indentation.increaseBlockLevel(),this.layout.add(W.INDENT),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseBlockLevel()),this.layout.add(W.NEWLINE,W.INDENT,t.closeParen,W.SPACE))}formatBetweenPredicate(t){this.layout.add(this.showKw(t.betweenKw),W.SPACE),this.layout=this.formatSubExpression(t.expr1),this.layout.add(W.NO_SPACE,W.SPACE,this.showNonTabularKw(t.andKw),W.SPACE),this.layout=this.formatSubExpression(t.expr2),this.layout.add(W.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(W.NEWLINE,W.INDENT),this.formatNode(t.endKw)}formatCaseWhen(t){this.layout.add(W.NEWLINE,W.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(W.NEWLINE,W.INDENT),this.formatNode(t.elseKw),this.layout=this.formatSubExpression(t.result)}formatClause(t){this.isOnelineClause(t)?this.formatClauseInOnelineStyle(t):Xn(this.cfg)?this.formatClauseInTabularStyle(t):this.formatClauseInIndentedStyle(t)}isOnelineClause(t){return Xn(this.cfg)?this.dialectCfg.tabularOnelineClauses[t.nameKw.text]:this.dialectCfg.onelineClauses[t.nameKw.text]}formatClauseInIndentedStyle(t){this.layout.add(W.NEWLINE,W.INDENT,this.showKw(t.nameKw),W.NEWLINE),this.layout.indentation.increaseTopLevel(),this.layout.add(W.INDENT),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseTopLevel()}formatClauseInOnelineStyle(t){this.layout.add(W.NEWLINE,W.INDENT,this.showKw(t.nameKw),W.SPACE),this.layout=this.formatSubExpression(t.children)}formatClauseInTabularStyle(t){this.layout.add(W.NEWLINE,W.INDENT,this.showKw(t.nameKw),W.SPACE),this.layout.indentation.increaseTopLevel(),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseTopLevel()}formatSetOperation(t){this.layout.add(W.NEWLINE,W.INDENT,this.showKw(t.nameKw),W.NEWLINE),this.layout.add(W.INDENT),this.layout=this.formatSubExpression(t.children)}formatLimitClause(t){this.withComments(t.limitKw,()=>{this.layout.add(W.NEWLINE,W.INDENT,this.showKw(t.limitKw))}),this.layout.indentation.increaseTopLevel(),Xn(this.cfg)?this.layout.add(W.SPACE):this.layout.add(W.NEWLINE,W.INDENT),t.offset?(this.layout=this.formatSubExpression(t.offset),this.layout.add(W.NO_SPACE,",",W.SPACE),this.layout=this.formatSubExpression(t.count)):this.layout=this.formatSubExpression(t.count),this.layout.indentation.decreaseTopLevel()}formatAllColumnsAsterisk(t){this.layout.add("*",W.SPACE)}formatLiteral(t){this.layout.add(t.text,W.SPACE)}formatIdentifier(t){this.layout.add(this.showIdentifier(t),W.SPACE)}formatParameter(t){this.layout.add(this.params.get(t),W.SPACE)}formatOperator({text:t}){this.cfg.denseOperators||this.dialectCfg.alwaysDenseOperators.includes(t)?this.layout.add(W.NO_SPACE,t):t===":"?this.layout.add(W.NO_SPACE,t,W.SPACE):this.layout.add(t,W.SPACE)}formatComma(t){this.inline?this.layout.add(W.NO_SPACE,",",W.SPACE):this.layout.add(W.NO_SPACE,",",W.NEWLINE,W.INDENT)}withComments(t,n){this.formatComments(t.leadingComments),n(),this.formatComments(t.trailingComments)}formatComments(t){t&&t.forEach(n=>{n.type===ee.line_comment?this.formatLineComment(n):this.formatBlockComment(n)})}formatLineComment(t){Cl(t.precedingWhitespace||"")?this.layout.add(W.NEWLINE,W.INDENT,t.text,W.MANDATORY_NEWLINE,W.INDENT):this.layout.getLayoutItems().length>0?this.layout.add(W.NO_NEWLINE,W.SPACE,t.text,W.MANDATORY_NEWLINE,W.INDENT):this.layout.add(t.text,W.MANDATORY_NEWLINE,W.INDENT)}formatBlockComment(t){t.type===ee.block_comment&&this.isMultilineBlockComment(t)?(this.splitBlockComment(t.text).forEach(n=>{this.layout.add(W.NEWLINE,W.INDENT,n)}),this.layout.add(W.NEWLINE,W.INDENT)):this.layout.add(t.text,W.SPACE)}isMultilineBlockComment(t){return Cl(t.text)||Cl(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($r(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 pi({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 pi({cfg:this.cfg,dialectCfg:this.dialectCfg,params:this.params,layout:new bj(this.cfg.expressionWidth),inline:!0}).format(t)}catch(r){if(r instanceof uc){this.params.setPositionalParameterIndex(n);return}else throw r}}formatKeywordNode(t){switch(t.tokenType){case V.RESERVED_JOIN:return this.formatJoin(t);case V.AND:case V.OR:case V.XOR:return this.formatLogicalOperator(t);default:return this.formatKeyword(t)}}formatJoin(t){Xn(this.cfg)?(this.layout.indentation.decreaseTopLevel(),this.layout.add(W.NEWLINE,W.INDENT,this.showKw(t),W.SPACE),this.layout.indentation.increaseTopLevel()):this.layout.add(W.NEWLINE,W.INDENT,this.showKw(t),W.SPACE)}formatKeyword(t){this.layout.add(this.showKw(t),W.SPACE)}formatLogicalOperator(t){this.cfg.logicalOperatorNewline==="before"?Xn(this.cfg)?(this.layout.indentation.decreaseTopLevel(),this.layout.add(W.NEWLINE,W.INDENT,this.showKw(t),W.SPACE),this.layout.indentation.increaseTopLevel()):this.layout.add(W.NEWLINE,W.INDENT,this.showKw(t),W.SPACE):this.layout.add(this.showKw(t),W.NEWLINE,W.INDENT)}formatDataType(t){this.layout.add(this.showDataType(t),W.SPACE)}showKw(t){return $T(t.tokenType)?VT(this.showNonTabularKw(t),this.cfg.indentStyle):this.showNonTabularKw(t)}showNonTabularKw(t){switch(this.cfg.keywordCase){case"preserve":return Gs(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}showFunctionKw(t){return $T(t.tokenType)?VT(this.showNonTabularFunctionKw(t),this.cfg.indentStyle):this.showNonTabularFunctionKw(t)}showNonTabularFunctionKw(t){switch(this.cfg.functionCase){case"preserve":return Gs(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 Gs(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}}class vj{constructor(t,n){this.dialect=t,this.cfg=n,this.params=new uj(this.cfg.params)}format(t){const n=this.parse(t);return this.formatAst(n).trimEnd()}parse(t){return yj(this.dialect.tokenizer).parse(t,this.cfg.paramTypes||{})}formatAst(t){return t.map(n=>this.formatStatement(n)).join(`
|
|
695
|
-
`.repeat(this.cfg.linesBetweenQueries+1))}formatStatement(t){const n=new pi({cfg:this.cfg,dialectCfg:this.dialect.formatOptions,params:this.params,layout:new _h(new xh(dj(this.cfg)))}).format(t.children);return t.hasSemicolon&&(this.cfg.newlineBeforeSemicolon?n.add(W.NEWLINE,";"):n.add(W.NO_NEWLINE,";")),n.toString()}}class ks extends Error{}function Uj(e){const t=["multilineLists","newlineBeforeOpenParen","newlineBeforeCloseParen","aliasAs","commaPosition","tabulateAlias"];for(const n of t)if(n in e)throw new ks(`${n} config is no more supported.`);if(e.expressionWidth<=0)throw new ks(`expressionWidth config must be positive number. Received ${e.expressionWidth} instead.`);if(e.params&&!wj(e.params)&&console.warn('WARNING: All "params" option values should be strings.'),e.paramTypes&&!Bj(e.paramTypes))throw new ks("Empty regex given in custom paramTypes. That would result in matching infinite amount of parameters.");return e}function wj(e){return(e instanceof Array?e:Object.values(e)).every(n=>typeof n=="string")}function Bj(e){return e.custom&&Array.isArray(e.custom)?e.custom.every(t=>t.regex!==""):!0}var Fj=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 o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n};const yh={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"},Gj=Object.keys(yh),Hj={tabWidth:2,useTabs:!1,keywordCase:"preserve",identifierCase:"preserve",dataTypeCase:"preserve",functionCase:"preserve",indentStyle:"standard",logicalOperatorNewline:"before",expressionWidth:50,linesBetweenQueries:1,denseOperators:!1,newlineBeforeSemicolon:!1},kj=(e,t={})=>{if(typeof t.language=="string"&&!Gj.includes(t.language))throw new ks(`Unsupported SQL dialect: ${t.language}`);const n=yh[t.language||"sql"];return jj(e,Object.assign(Object.assign({},t),{dialect:Kk[n]}))},jj=(e,t)=>{var{dialect:n}=t,r=Fj(t,["dialect"]);if(typeof e!="string")throw new Error("Invalid query argument. Expected string, instead got "+typeof e);const o=Uj(Object.assign(Object.assign({},Hj),r));return new vj(lj(n),o).format(e)};function zt({cell:e,t,onRun:n,onMoveUp:r,onMoveDown:o,onDelete:s,children:a}){const[l,c]=f.useState(!1),E=Mh(e,t),d=js[e.type]??t.accent,u=e.name?i.jsx("span",{style:{color:t.textSecondary,fontSize:12,fontFamily:t.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:200},children:e.name}):void 0,T=l?i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[n&&i.jsx(At,{title:"Run cell (Shift+Enter)",onClick:n,t,accent:!0,children:i.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:i.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})})}),i.jsx(At,{title:"Move up",onClick:r,t,children:i.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"})})}),i.jsx(At,{title:"Move down",onClick:o,t,children:i.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"})})}),i.jsx(At,{title:"Delete cell",onClick:s,t,danger:!0,children:i.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:i.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 i.jsx(ER,{typeLabel:Dh[e.type]??e.type.toUpperCase(),typeColor:d,accent:E,idleBorder:t.cellBorder,background:t.cellBg,headerBackground:`${t.tableHeaderBg}80`,active:l||e.status!=="idle",title:u,actions:T,gutter:i.jsx(Ph,{cell:e,t}),onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:a})}const Dh={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"},js={sql:"#388bfd",markdown:"#56d364",dql:"#e3b341",param:"#e3b341",chart:"#a371f7",pivot:"#a371f7",single_value:"#a371f7",filter:"#ff7b72",table:"#79c0ff",map:"#7ce38b",writeback:"#d2a8ff",python:"#3572a5",chat:"#f0883e"},Yj={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 Mh(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 Ph({cell:e,t}){var s;let n="",r=t.textMuted,o="";if(e.status==="running")n="[*]",r=t.cellBorderRunning;else if(e.status==="error")n="[!]",r=t.error;else if(e.executionCount!==void 0){if(n=`[${e.executionCount}]`,r=t.textMuted,((s=e.result)==null?void 0:s.executionTime)!==void 0){const a=e.result.executionTime;o=a<1e3?`${a}ms`:`${(a/1e3).toFixed(1)}s`}}else n="[ ]",r=t.textMuted;return i.jsxs("div",{style:{width:40,display:"flex",flexDirection:"column",alignItems:"center",paddingTop:12,flexShrink:0,gap:2},children:[i.jsx("span",{style:{fontFamily:t.fontMono,fontSize:11,color:r,lineHeight:1.4,userSelect:"none",transition:"color 0.2s"},children:e.status==="running"?i.jsxs("span",{style:{display:"inline-block",animation:"spin 0.8s linear infinite"},children:[i.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:i.jsx("circle",{cx:"6",cy:"6",r:"4.5",stroke:r,strokeWidth:"1.5",strokeDasharray:"14 7"})}),i.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}):n}),o&&i.jsx("span",{style:{fontFamily:t.fontMono,fontSize:8,color:t.textMuted,lineHeight:1,userSelect:"none"},children:o})]})}function Wj(e){if(!/^\s*block\s+"/i.test(e.trim()))return null;const t=o=>{var s;return((s=e.match(new RegExp(`\\b${o}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:s[1])??""},n=e.match(/\btags\s*=\s*\[([^\]]*)\]/i),r=n?(n[1].match(/"([^"]*)"/g)??[]).map(o=>o.slice(1,-1)):[];return{domain:t("domain"),owner:t("owner"),description:t("description"),blockType:t("type")||"custom",tags:r}}function xl(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 Vj(e,t){const n=t.map(o=>`"${o}"`).join(", "),r=/(\btags\s*=\s*)\[[^\]]*\]/i;return r.test(e)?e.replace(r,`$1[${n}]`):e}function $j({binding:e,t,onRevert:n,onUnbind:r}){const o=e.state==="forked",s=o?t.warning:t.success,a=o?"FORKED":"BOUND",l=o?"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 i.jsxs("div",{title:l,style:{display:"flex",alignItems:"center",gap:8,padding:"4px 10px",borderBottom:`1px solid ${t.cellBorder}`,background:`${s}10`,fontFamily:t.fontMono,fontSize:11},children:[i.jsx("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.08em",color:s,background:`${s}24`,border:`1px solid ${s}55`,borderRadius:3,padding:"1px 5px"},children:a}),i.jsx("span",{style:{color:t.textSecondary},children:e.path}),e.version&&i.jsxs("span",{style:{color:t.textMuted},children:["· v",e.version]}),!o&&i.jsx("span",{title:"Bound cells track the block file — edits fork locally",style:{color:t.textMuted},children:"🔒"}),i.jsx("div",{style:{flex:1}}),o&&i.jsx("button",{onClick:n,title:"Discard local edits and restore the block file body",style:XT(t,s),children:"Revert"}),i.jsx("button",{onClick:r,title:"Detach this cell from the block file",style:XT(t,t.btnBorder),children:"Unbind"})]})}function XT(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 Xj({content:e,onChange:t,t:n}){const r=Wj(e);if(!r)return null;const o={background:n.editorBg,border:`1px solid ${n.cellBorder}`,borderRadius:3,color:n.textSecondary,fontSize:11,fontFamily:n.fontMono,padding:"2px 6px",outline:"none"},s={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 i.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 12px",padding:"5px 10px",borderBottom:`1px solid ${n.cellBorder}`,background:`${n.tableHeaderBg}40`},children:[i.jsxs("div",{style:a,children:[i.jsx("span",{style:s,children:"domain"}),i.jsx("input",{style:{...o,width:80},value:r.domain,placeholder:"e.g. finance",onChange:l=>t(xl(e,"domain",l.target.value))})]}),i.jsxs("div",{style:a,children:[i.jsx("span",{style:s,children:"owner"}),i.jsx("input",{style:{...o,width:90},value:r.owner,placeholder:"e.g. data-team",onChange:l=>t(xl(e,"owner",l.target.value))})]}),i.jsxs("div",{style:a,children:[i.jsx("span",{style:s,children:"tags"}),i.jsx("input",{style:{...o,width:110},value:r.tags.join(", "),placeholder:"revenue, kpi",onChange:l=>{const c=l.target.value.split(",").map(E=>E.trim()).filter(Boolean);t(Vj(e,c))}})]}),i.jsxs("div",{style:{...a,flex:1},children:[i.jsx("span",{style:s,children:"description"}),i.jsx("input",{style:{...o,flex:1,minWidth:120},value:r.description,placeholder:"What this block measures",onChange:l=>t(xl(e,"description",l.target.value))})]})]})}const Kj=new Set(["sql","dql","param","writeback","python","chat"]);function zj({cell:e,index:t}){var re;const{state:n,dispatch:r}=Te(),o=oe[n.themeMode],{executeCell:s,executeDependents:a,cancelCell:l}=Fi(),[c,E]=f.useState(!1),[d,u]=f.useState(!1),[T,S]=f.useState(e.name??""),[h,A]=f.useState(!0),[R,p]=f.useState("table"),[N,I]=f.useState(null),[O,m]=f.useState(!1),[C,g]=f.useState(!1),[y,_]=f.useState(!1),P=f.useMemo(()=>y?cD(e,n.cells):null,[y,e,n.cells]),D=e.type==="sql"||e.type==="dql"||e.type==="chart"||e.type==="pivot"||e.type==="single_value"||e.type==="filter"||e.type==="table",b=Mh(e,o),F=e.type!=="markdown"&&e.type!=="param",x=f.useRef(null),w=f.useRef(e.content),[M,B]=f.useState(!1),v=f.useMemo(()=>n.schemaTables.length>0?Object.fromEntries(n.schemaTables.map(Y=>[Y.name,Y.columns.map(se=>se.name)])):void 0,[n.schemaTables]);f.useEffect(()=>{if(e.status==="success"&&e.result){const Y=to(e.result,e.chartConfig);I(Y!=="table"?Y:null),p(Y!=="table"?"chart":"table")}},[e.status,e.result,e.chartConfig]);const L=f.useCallback(()=>{F&&s(e.id)},[e.id,s,F]),U=f.useCallback(Y=>{const se={content:Y},de=e.blockBinding;if((de==null?void 0:de.originalContent)!==void 0){const me=Y.trim()!==de.originalContent.trim()?"forked":"bound";me!==de.state&&(se.blockBinding={...de,state:me})}r({type:"UPDATE_CELL",id:e.id,updates:se}),B(Y!==w.current)},[e.id,e.blockBinding,r]),G=f.useCallback(()=>{var se;const Y=w.current;r({type:"UPDATE_CELL",id:e.id,updates:{content:Y}}),(se=x.current)==null||se.resetTo(Y),B(!1)},[e.id,r]),k=f.useCallback(()=>{if(e.content.trim())try{const Y=kj(e.content,{language:"sql",tabWidth:2,keywordCase:"upper",linesBetweenQueries:1});r({type:"UPDATE_CELL",id:e.id,updates:{content:Y}})}catch{}},[e.content,e.id,r]),J=f.useCallback(()=>{k(),setTimeout(()=>s(e.id),80)},[k,s,e.id]),K=f.useCallback(Y=>r({type:"UPDATE_CELL",id:e.id,updates:Y}),[r,e.id]),$=()=>{r({type:"DELETE_CELL",id:e.id})},z=()=>{r({type:"MOVE_CELL",id:e.id,direction:"up"})},q=()=>{r({type:"MOVE_CELL",id:e.id,direction:"down"})},X={cell:e,t:o,onMoveUp:z,onMoveDown:q,onDelete:$};if(n.appMode==="app"&&Kj.has(e.type))return i.jsxs("div",{style:{marginTop:8,marginBottom:8,padding:"6px 10px",borderRadius:6,border:`1px dashed ${o.cellBorder}`,background:o.cellBg,color:o.textMuted,fontSize:11,fontFamily:o.font,display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{style:{opacity:.7},children:"◎"}),i.jsxs("span",{children:[e.type.toUpperCase()," cell hidden in App view",e.name?` · ${e.name}`:""]})]});if(e.type==="param")return i.jsx(zt,{...X,onRun:()=>a(e.id),children:i.jsx(Zy,{cell:e,themeMode:n.themeMode,onApplyParam:a})});if(e.type==="pivot")return i.jsx(zt,{...X,children:i.jsx(V0,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:K})});if(e.type==="single_value")return i.jsx(zt,{...X,children:i.jsx(j0,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:K})});if(e.type==="filter")return i.jsx(zt,{...X,children:i.jsx(w0,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:K})});if(e.type==="chart")return i.jsx(zt,{...X,children:i.jsx(P0,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:K})});if(e.type==="table")return i.jsx(zt,{...X,children:i.jsx(X0,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:K})});if(e.type==="chat")return i.jsx(zt,{...X,children:i.jsx(q0,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:K})});const Q=Yj[e.type];if(Q)return i.jsx(zt,{...X,children:i.jsx(e0,{cell:e,themeMode:n.themeMode,title:Q.title,subtitle:Q.subtitle,color:Q.color,badge:Q.badge})});const ae=()=>{u(!1),r({type:"UPDATE_CELL",id:e.id,updates:{name:T.trim()||void 0}})},ne=(e.result||e.error)&&e.type!=="markdown";return e.result&&to(e.result,e.chartConfig),i.jsxs("div",{onMouseEnter:()=>E(!0),onMouseLeave:()=>E(!1),style:{display:"flex",gap:0,marginBottom:2},children:[y&&P&&i.jsx(QR,{cell:e,initialContent:P.derivedFromUpstream?P.content:void 0,initialName:P.suggestedName,initialDescription:P.suggestedDescription,onClose:()=>_(!1),onSaved:({path:Y,name:se})=>{r({type:"FILE_ADDED",file:{name:se,path:Y,type:"block",folder:"blocks"}})}}),i.jsx(Ph,{cell:e,t:o}),i.jsxs("div",{style:{flex:1,minWidth:0,borderRadius:8,border:`1px solid ${c||e.status!=="idle"?b:o.cellBorder}`,borderLeft:`2px solid ${b}`,background:o.cellBg,overflow:"hidden",transition:"border-color 0.2s"},children:[i.jsxs("div",{style:{height:32,display:"flex",alignItems:"center",padding:"0 8px 0 10px",gap:8,borderBottom:`1px solid ${o.cellBorder}`,background:`${o.tableHeaderBg}80`},children:[i.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:10,fontWeight:700,fontFamily:o.fontMono,letterSpacing:"0.08em",color:js[e.type]??o.accent,background:`${js[e.type]??o.accent}18`,border:`1px solid ${js[e.type]??o.accent}40`,borderRadius:4,padding:"1px 6px",flexShrink:0,textTransform:"uppercase"},children:Dh[e.type]}),c&&(e.type==="sql"||e.type==="dql")&&i.jsx(oD,{themeMode:n.themeMode,cellType:e.type,onInsert:Y=>U(Y)}),c&&(e.type==="sql"||e.type==="dql")&&i.jsx("button",{title:"Format SQL (clean up whitespace & keywords)",onClick:k,style:{background:"transparent",border:`1px solid ${o.btnBorder}`,borderRadius:4,color:o.textMuted,fontSize:10,fontFamily:o.font,fontWeight:600,letterSpacing:"0.04em",padding:"1px 7px",cursor:"pointer",transition:"color 0.15s, border-color 0.15s"},onMouseEnter:Y=>{Y.currentTarget.style.color=o.textSecondary,Y.currentTarget.style.borderColor=o.accent},onMouseLeave:Y=>{Y.currentTarget.style.color=o.textMuted,Y.currentTarget.style.borderColor=o.btnBorder},children:"Format"}),M&&(e.type==="sql"||e.type==="dql")&&i.jsx("button",{title:"Reset to last saved version (discard changes)",onClick:G,style:{background:"transparent",border:`1px solid ${o.btnBorder}`,borderRadius:4,color:o.error,fontSize:10,fontFamily:o.font,fontWeight:600,letterSpacing:"0.04em",padding:"1px 7px",cursor:"pointer",transition:"color 0.15s, border-color 0.15s"},onMouseEnter:Y=>{Y.currentTarget.style.borderColor=o.error},onMouseLeave:Y=>{Y.currentTarget.style.borderColor=o.btnBorder},children:"↺ Reset"}),c&&D&&i.jsx("button",{title:"Save this cell as a reusable block",onClick:()=>_(!0),style:{background:"transparent",border:`1px solid ${o.btnBorder}`,borderRadius:4,color:o.textMuted,fontSize:10,fontFamily:o.font,fontWeight:600,letterSpacing:"0.04em",padding:"1px 7px",cursor:"pointer",transition:"color 0.15s, border-color 0.15s"},onMouseEnter:Y=>{Y.currentTarget.style.color=o.textSecondary,Y.currentTarget.style.borderColor=o.accent},onMouseLeave:Y=>{Y.currentTarget.style.color=o.textMuted,Y.currentTarget.style.borderColor=o.btnBorder},children:"Save as Block"}),(e.type==="sql"||e.type==="dql")&&i.jsx(n0,{cells:n.cells,index:t,content:e.content,themeMode:n.themeMode,onInsertHandle:Y=>{const se=`{{${Y}}}`,de=e.content??"";if(de.includes(se))return;const ue=de.trim().length===0?`SELECT * FROM ${se}`:`${de.replace(/\s*$/,"")} ${se}`;U(ue)}}),d?i.jsx("input",{autoFocus:!0,value:T,onChange:Y=>S(Y.target.value),onBlur:ae,onKeyDown:Y=>{Y.key==="Enter"&&ae(),Y.key==="Escape"&&u(!1)},style:{background:"transparent",border:`1px solid ${o.cellBorderActive}`,borderRadius:4,color:o.textSecondary,fontSize:12,fontFamily:o.fontMono,padding:"1px 6px",outline:"none",width:140}}):e.name&&i.jsx("span",{onClick:()=>{S(e.name??""),u(!0)},title:"Click to rename",style:{color:o.textSecondary,fontSize:12,fontFamily:o.fontMono,cursor:"text",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:200},children:e.name}),i.jsx("div",{style:{flex:1}}),c&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[!e.name&&!d&&i.jsx(At,{title:"Name this cell",onClick:()=>{S(""),u(!0)},t:o,children:i.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"})})}),F&&e.status==="running"?i.jsx(At,{title:"Cancel execution",onClick:()=>l(e.id),t:o,danger:!0,children:i.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:i.jsx("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1"})})}):F?i.jsx(At,{title:"Run cell (Shift+Enter)",onClick:L,t:o,accent:!0,children:i.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:i.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})})}):null,i.jsx(At,{title:"Move up",onClick:z,t:o,children:i.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"})})}),i.jsx(At,{title:"Move down",onClick:q,t:o,children:i.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"})})}),i.jsx(At,{title:"Delete cell",onClick:$,t:o,danger:!0,children:i.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"&&i.jsx(Xj,{content:e.content,onChange:U,t:o}),e.blockBinding&&i.jsx($j,{binding:e.blockBinding,t:o,onRevert:async()=>{var se;const Y=e.blockBinding;if(Y)try{const de=await Z.openBlockStudio(Y.path),ue=$c(de.source)??de.source;r({type:"UPDATE_CELL",id:e.id,updates:{content:ue,blockBinding:{...Y,state:"bound",originalContent:ue}}}),(se=x.current)==null||se.resetTo(ue)}catch(de){console.error("Failed to revert bound cell",de)}},onUnbind:()=>{r({type:"UPDATE_CELL",id:e.id,updates:{blockBinding:void 0}})}}),e.type==="markdown"?i.jsx(Qy,{value:e.content,onChange:U,themeMode:n.themeMode}):i.jsx(Qc,{value:e.content,onChange:U,onRun:L,themeMode:n.themeMode,schema:v,errorMessage:e.status==="error"?e.error:void 0,editorRef:x}),ne&&i.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`},children:[i.jsxs("div",{style:{height:28,display:"flex",alignItems:"center",padding:"0 12px",gap:10,borderBottom:e.result&&h?`1px solid ${o.cellBorder}`:"none",background:`${o.tableHeaderBg}60`},children:[e.result&&i.jsxs("span",{style:{fontSize:11,fontFamily:o.font,color:o.textMuted},children:[(e.result.rowCount??e.result.rows.length).toLocaleString()," rows",e.result.executionTime!==void 0&&i.jsxs(i.Fragment,{children:[" · ",e.result.executionTime<1e3?`${e.result.executionTime}ms`:`${(e.result.executionTime/1e3).toFixed(2)}s`]})]}),e.fromSnapshot&&e.result&&i.jsx("span",{title:"Result loaded from the last saved run; re-run to refresh.",style:{fontSize:10,fontFamily:o.font,color:o.textMuted,border:`1px solid ${o.btnBorder}`,borderRadius:3,padding:"0 6px",lineHeight:"16px"},children:"cached"}),e.error&&i.jsx("span",{style:{fontSize:11,fontFamily:o.font,color:o.error},children:"Error"}),i.jsx("div",{style:{flex:1}}),e.result&&h&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:3,position:"relative"},children:[i.jsx("button",{onClick:()=>{p("table"),m(!1)},style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${R==="table"?o.accent:o.btnBorder}`,background:R==="table"?`${o.accent}20`:"transparent",color:R==="table"?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s"},children:"Table"}),i.jsxs("div",{style:{position:"relative"},children:[i.jsxs("button",{onClick:()=>{R==="chart"&&O?m(!1):(p("chart"),m(Y=>!Y))},style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${R==="chart"?o.accent:o.btnBorder}`,background:R==="chart"?`${o.accent}20`:"transparent",color:R==="chart"?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s",display:"flex",alignItems:"center",gap:3},children:[N?((re=Gi.find(Y=>Y.value===N))==null?void 0:re.label)??"Chart":"Chart",i.jsx("svg",{width:"6",height:"6",viewBox:"0 0 8 8",fill:"currentColor",children:i.jsx("path",{d:"M1 2.5l3 3 3-3",stroke:"currentColor",fill:"none",strokeWidth:"1.2",strokeLinecap:"round"})})]}),O&&i.jsx(Jj,{selected:N,onSelect:Y=>{I(Y),p("chart"),m(!1)},onClose:()=>m(!1),t:o})]}),R==="chart"&&i.jsx("button",{onClick:()=>g(Y=>!Y),title:"Chart configuration",style:{padding:"1px 5px",fontSize:11,borderRadius:3,cursor:"pointer",border:`1px solid ${C?o.accent:o.btnBorder}`,background:C?`${o.accent}20`:"transparent",color:C?o.accent:o.textMuted,transition:"all 0.15s",display:"flex",alignItems:"center"},children:i.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"})})})]}),i.jsxs("button",{onClick:()=>A(Y=>!Y),style:{background:"transparent",border:"none",cursor:"pointer",color:o.textMuted,fontSize:11,fontFamily:o.font,padding:"2px 4px",display:"flex",alignItems:"center",gap:4},children:[i.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:h?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.15s"},children:i.jsx("path",{d:"M1 3l4 4 4-4",stroke:"currentColor",fill:"none",strokeWidth:"1.5"})}),h?"Hide":"Show"]})]}),h&&i.jsxs(i.Fragment,{children:[e.error&&i.jsx(uD,{message:e.error,themeMode:n.themeMode,onFix:F?J:void 0,schemaTables:n.schemaTables}),e.result&&!e.error&&(R==="chart"&&N?i.jsxs(i.Fragment,{children:[ki(N,e.result,n.themeMode,e.chartConfig),C&&i.jsx(qj,{columns:e.result.columns,chartConfig:e.chartConfig,onChange:Y=>r({type:"UPDATE_CELL",id:e.id,updates:{chartConfig:{...e.chartConfig,...Y}}}),t:o})]}):i.jsx(mo,{result:e.result,themeMode:n.themeMode}))]})]}),F&&i.jsx(KF,{cellContent:e.content,cellType:e.type,cellName:e.name,themeMode:n.themeMode,t:o,onFocusNode:Y=>{r({type:"SET_LINEAGE_FOCUS",nodeId:Y}),n.lineageFullscreen||r({type:"TOGGLE_LINEAGE_FULLSCREEN"})}})]})]})}function At({title:e,onClick:t,children:n,t:r,accent:o,danger:s}){const[a,l]=f.useState(!1);return i.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?s?`${r.error}18`:o?`${r.accent}18`:r.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:a?s?r.error:o?r.accent:r.textSecondary:r.textMuted,transition:"all 0.15s",padding:0},children:n})}function Jj({selected:e,onSelect:t,onClose:n,t:r}){const[o,s]=f.useState(null);return ge.useEffect(()=>{const a=l=>{setTimeout(()=>n(),0)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[n]),i.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:Gi.map(({value:a,label:l})=>i.jsx("button",{onClick:()=>t(a),onMouseEnter:()=>s(a),onMouseLeave:()=>s(null),style:{background:e===a?`${r.accent}20`:o===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 qj({columns:e,chartConfig:t,onChange:n,t:r}){const o={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},s={fontSize:9,fontWeight:700,color:r.textMuted,fontFamily:r.font,letterSpacing:"0.05em",textTransform:"uppercase",minWidth:40,flexShrink:0};return i.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px 16px",padding:"8px 12px",borderTop:`1px solid ${r.cellBorder}`,background:`${r.tableHeaderBg}40`},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsx("span",{style:s,children:"X axis"}),i.jsxs("select",{style:o,value:(t==null?void 0:t.x)??"",onChange:a=>n({x:a.target.value||void 0}),children:[i.jsx("option",{value:"",children:"Auto"}),e.map(a=>i.jsx("option",{value:a,children:a},a))]})]}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsx("span",{style:s,children:"Y axis"}),i.jsxs("select",{style:o,value:(t==null?void 0:t.y)??"",onChange:a=>n({y:a.target.value||void 0}),children:[i.jsx("option",{value:"",children:"Auto"}),e.map(a=>i.jsx("option",{value:a,children:a},a))]})]}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsx("span",{style:s,children:"Color"}),i.jsxs("select",{style:o,value:(t==null?void 0:t.color)??"",onChange:a=>n({color:a.target.value||void 0}),children:[i.jsx("option",{value:"",children:"None"}),e.map(a=>i.jsx("option",{value:a,children:a},a))]})]}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:150},children:[i.jsx("span",{style:s,children:"Title"}),i.jsx("input",{style:{...o,fontFamily:r.font},value:(t==null?void 0:t.title)??"",placeholder:"Chart title",onChange:a=>n({title:a.target.value||void 0})})]})]})}const Qj={draft:"#8b949e",review:"#d29922",certified:"#3fb950",deprecated:"#f85149",pending_recertification:"#db6d28"};function Zj({themeMode:e,onPick:t,autoFocus:n=!0,compact:r=!0}){const o=oe[e],[s,a]=f.useState([]),[l,c]=f.useState(!0),[E,d]=f.useState(""),[u,T]=f.useState(""),[S,h]=f.useState(""),A=f.useRef(null);f.useEffect(()=>{let O=!1;return c(!0),Z.getBlockLibrary().then(m=>{O||a(m.blocks)}).finally(()=>{O||c(!1)}),()=>{O=!0}},[]),f.useEffect(()=>{if(n){const O=setTimeout(()=>{var m;return(m=A.current)==null?void 0:m.focus()},30);return()=>clearTimeout(O)}},[n]);const R=f.useMemo(()=>[...new Set(s.map(O=>O.domain))].sort(),[s]),p=f.useMemo(()=>[...new Set(s.map(O=>O.status))].sort(),[s]),N=f.useMemo(()=>s.filter(O=>{if(E){const m=E.toLowerCase();if(!O.name.toLowerCase().includes(m)&&!O.description.toLowerCase().includes(m))return!1}return!(u&&O.domain!==u||S&&O.status!==S)}),[s,E,u,S]),I={background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:4,color:o.textPrimary,fontSize:11,fontFamily:o.font,padding:"4px 6px",outline:"none"};return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:r?340:void 0},children:[i.jsxs("div",{style:{display:"flex",gap:4,alignItems:"center"},children:[i.jsx("input",{ref:A,value:E,onChange:O=>d(O.target.value),placeholder:"Search blocks...",style:{...I,flex:1,padding:"6px 8px"}}),i.jsxs("select",{value:u,onChange:O=>T(O.target.value),style:I,children:[i.jsx("option",{value:"",children:"All domains"}),R.map(O=>i.jsx("option",{value:O,children:O},O))]}),i.jsxs("select",{value:S,onChange:O=>h(O.target.value),style:I,children:[i.jsx("option",{value:"",children:"Any"}),p.map(O=>i.jsx("option",{value:O,children:O},O))]})]}),i.jsx("div",{style:{maxHeight:r?220:420,overflowY:"auto",display:"flex",flexDirection:"column",border:`1px solid ${o.cellBorder}`,borderRadius:4},children:l?i.jsx(KT,{t:o,children:"Loading blocks..."}):N.length===0?i.jsx(KT,{t:o,children:s.length===0?"No blocks yet. Save a cell as a block to get started.":"No blocks match your filters."}):N.map(O=>i.jsx(eY,{block:O,onClick:()=>t(O),t:o,compact:r},O.path))})]})}function KT({children:e,t}){return i.jsx("div",{style:{padding:16,textAlign:"center",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:e})}function eY({block:e,onClick:t,t:n,compact:r}){const[o,s]=f.useState(!1),a=Qj[e.status]??n.textMuted;return i.jsxs("button",{onClick:t,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),style:{background:o?`${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:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:3},children:[i.jsx("span",{style:{fontSize:12,fontWeight:600,color:n.textPrimary},children:e.name}),i.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&&i.jsx("div",{style:{fontSize:11,color:n.textMuted,lineHeight:1.3,marginBottom:3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.description}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:10,color:n.textMuted},children:[i.jsx("span",{style:{background:n.pillBg,padding:"1px 6px",borderRadius:4},children:e.domain||"no domain"}),e.owner&&i.jsxs("span",{children:["by ",e.owner]})]})]})}const tY=[{type:"block",label:"Block",Icon:pR,color:"#3fb950",group:"library"},{type:"chat",label:"Chat",Icon:L_,color:"#f0883e",group:"compute"},{type:"sql",label:"SQL",Icon:I_,color:"#388bfd",group:"compute"},{type:"markdown",label:"Text",Icon:wL,color:"#56d364",group:"compute"},{type:"chart",label:"Chart",Icon:N_,color:"#a371f7",group:"viz"},{type:"pivot",label:"Pivot",Icon:O_,color:"#a371f7",group:"viz"},{type:"single_value",label:"Single value",Icon:m_,color:"#a371f7",group:"viz"},{type:"table",label:"Table",Icon:r_,color:"#79c0ff",group:"viz"},{type:"param",label:"Inputs",Icon:C_,color:"#e3b341",group:"io"},{type:"filter",label:"Filter",Icon:g_,color:"#ff7b72",group:"transform"}];function yl({afterId:e}){const{state:t,dispatch:n}=Te(),r=oe[t.themeMode],[o,s]=f.useState(!1),[a,l]=f.useState(!1),[c,E]=f.useState(!1),[d,u]=f.useState(!1),T=f.useRef(null);f.useEffect(()=>{if(!a)return;function R(p){T.current&&!T.current.contains(p.target)&&(l(!1),E(!1))}return document.addEventListener("mousedown",R),()=>document.removeEventListener("mousedown",R)},[a]);const S=()=>{l(!1),E(!1)},h=R=>{const p=$e(R);n({type:"ADD_CELL",cell:p,afterId:e}),R==="sql"&&n({type:"SET_SIDEBAR_PANEL",panel:"schema"}),S()},A=async R=>{let p;try{p=await Z.openBlockStudio(R.path)}catch(O){console.error("Failed to bind block cell",O),window.alert(`Couldn't load block ${R.path}. Check the console for details.`),S();return}const N=$c(p.source)??p.source,I=$e("sql",N);I.name=R.name,I.blockBinding={path:R.path,state:"bound",originalContent:N},n({type:"ADD_CELL",cell:I,afterId:e}),S()};return i.jsxs("div",{ref:T,onDragOver:R=>{R.dataTransfer.types.includes(ri)&&(R.preventDefault(),u(!0))},onDragLeave:()=>u(!1),onDrop:R=>{const p=HR(R.dataTransfer.getData(ri));if(!p)return;R.preventDefault(),u(!1);const N=$e("sql",p.reference);n({type:"ADD_CELL",cell:N,afterId:e}),Z.trackUsage(p.name),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:p.name}}))},onMouseEnter:()=>s(!0),onMouseLeave:()=>{s(!1),u(!1)},style:{position:"relative",height:28,display:"flex",alignItems:"center",justifyContent:"center",cursor:"default"},children:[(o||a||d)&&i.jsxs("button",{onClick:()=>l(R=>!R),style:{position:"relative",zIndex:2,height:22,padding:"0 10px",borderRadius:11,border:`1px solid ${d?r.accent:r.cellBorderActive}`,background:d?`${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:[i.jsx("span",{style:{fontSize:14,lineHeight:1,marginTop:-1},children:"+"}),"Add cell"]}),a&&i.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:[i.jsx("div",{style:{display:"flex",gap:6,flexWrap:"nowrap",alignItems:"center",justifyContent:"space-between"},children:tY.map(R=>i.jsx(nY,{entry:R,active:R.type==="block"&&c,onClick:()=>{if(R.type==="block"){E(p=>!p);return}h(R.type)},t:r},R.type))}),c&&i.jsx("div",{style:{padding:"6px 2px 2px",borderTop:`1px solid ${r.cellBorder}`},children:i.jsx(Zj,{themeMode:t.themeMode,onPick:R=>void A(R)})})]})]})}function nY({entry:e,onClick:t,t:n,active:r=!1}){const[o,s]=f.useState(!1),a=r||o,l=e.Icon;return i.jsxs("button",{onClick:t,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!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:[i.jsx("span",{style:{color:e.color,display:"flex",alignItems:"center",justifyContent:"center"},children:i.jsx(l,{size:18,strokeWidth:1.75})}),i.jsx("span",{style:{letterSpacing:"0.02em"},children:e.label})]})}function rY({registerCellRef:e}){const{state:t,dispatch:n}=Te(),{executeCell:r}=Fi(),o=oe[t.themeMode],[s,a]=f.useState(null),l=f.useRef(0),[c,E]=f.useState(null),[d,u]=f.useState(null);f.useCallback(R=>{a(R)},[]),f.useEffect(()=>{s&&t.inspectorOpen&&n({type:"SET_INSPECTOR_CONTEXT",context:{kind:"cell",cellId:s}})},[s,t.inspectorOpen,n]),f.useEffect(()=>{function R(p){var m;if(!s)return;const N=p.target;if(N.tagName==="TEXTAREA"||N.tagName==="INPUT"||N.isContentEditable||N.closest(".cm-editor")){a(null);return}const I=t.cells,O=I.findIndex(C=>C.id===s);if(O!==-1)switch(p.key){case"a":{p.preventDefault();const C=$e("sql");if(O===0)n({type:"ADD_CELL",cell:C,afterId:I[0].id}),n({type:"MOVE_CELL",id:C.id,direction:"up"});else{const g=I[O-1].id;n({type:"ADD_CELL",cell:C,afterId:g})}a(C.id);break}case"b":{p.preventDefault();const C=$e("sql");n({type:"ADD_CELL",cell:C,afterId:s}),a(C.id);break}case"d":{p.preventDefault();const C=Date.now();if(C-l.current<=500){if(n({type:"DELETE_CELL",id:s}),I.length>1){const g=O>0?O-1:1;a(((m=I[g])==null?void 0:m.id)??null)}else a(null);l.current=0}else l.current=C;break}case"Enter":{if(p.shiftKey){p.preventDefault();const C=I[O];C&&C.type!=="markdown"&&r(C.id)}break}}}return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[s,t.cells,n,r]),f.useEffect(()=>{function R(p){p.target.closest("[data-cell-id]")||a(null)}return document.addEventListener("mousedown",R),()=>document.removeEventListener("mousedown",R)},[]);const T=f.useCallback((R,p)=>{E(p),R.dataTransfer.effectAllowed="move",R.dataTransfer.setData("text/plain",String(p));const N=R.currentTarget;setTimeout(()=>{N.style.opacity="0.4"},0)},[]),S=f.useCallback(R=>{R.currentTarget.style.opacity="1",E(null),u(null)},[]),h=f.useCallback((R,p)=>{R.preventDefault(),R.dataTransfer.dropEffect="move",u(p)},[]),A=f.useCallback((R,p)=>{R.preventDefault(),c!==null&&c!==p&&n({type:"REORDER_CELL",fromIndex:c,toIndex:p}),E(null),u(null)},[c,n]);return t.cells.length===0?i.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[t.appMode==="studio"&&i.jsx(yl,{}),i.jsx(oY,{t:o})]}):i.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[t.appMode==="studio"&&i.jsx(yl,{afterId:void 0}),t.cells.map((R,p)=>i.jsxs(ge.Fragment,{children:[i.jsxs("div",{ref:N=>e(R.id,N),"data-cell-id":R.id,draggable:t.appMode==="studio",onDragStart:t.appMode==="studio"?N=>T(N,p):void 0,onDragEnd:t.appMode==="studio"?S:void 0,onDragOver:t.appMode==="studio"?N=>h(N,p):void 0,onDrop:t.appMode==="studio"?N=>A(N,p):void 0,onClick:N=>{const I=N.target;!I.closest(".cm-editor")&&!I.closest("textarea")&&!I.closest("input")&&a(R.id)},style:{outline:s===R.id?`2px solid ${o.accent}40`:"none",outlineOffset:2,borderRadius:10,transition:"outline 0.1s, transform 0.15s",position:"relative",...d===p&&c!==null&&c!==p?{borderTop:`2px solid ${o.accent}`}:{}},children:[i.jsx("div",{style:{position:"absolute",left:-20,top:8,width:16,height:24,display:"flex",alignItems:"center",justifyContent:"center",cursor:"grab",color:o.textMuted,opacity:0,transition:"opacity 0.15s",zIndex:5},className:"drag-handle",children:i.jsxs("svg",{width:"8",height:"14",viewBox:"0 0 8 14",fill:"currentColor",children:[i.jsx("circle",{cx:"2",cy:"2",r:"1.2"}),i.jsx("circle",{cx:"6",cy:"2",r:"1.2"}),i.jsx("circle",{cx:"2",cy:"7",r:"1.2"}),i.jsx("circle",{cx:"6",cy:"7",r:"1.2"}),i.jsx("circle",{cx:"2",cy:"12",r:"1.2"}),i.jsx("circle",{cx:"6",cy:"12",r:"1.2"})]})}),i.jsx(zj,{cell:R,index:p})]}),t.appMode==="studio"&&i.jsx(yl,{afterId:R.id})]},R.id)),i.jsx("style",{children:`
|
|
696
|
-
[data-cell-id]:hover .drag-handle { opacity: 0.5 !important; }
|
|
697
|
-
[data-cell-id]:hover .drag-handle:hover { opacity: 1 !important; }
|
|
698
|
-
`})]})}function oY({t:e}){return i.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"48px 0",gap:12,color:e.textMuted},children:[i.jsx("svg",{width:"40",height:"40",viewBox:"0 0 16 16",fill:"currentColor",style:{opacity:.3},children:i.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"})}),i.jsx("span",{style:{fontSize:13,fontFamily:e.font},children:"Empty notebook. Click + to add your first cell."})]})}function sY(){const{state:e}=Te(),t=oe[e.themeMode],n=e.cells.filter(r=>r.type==="markdown"||r.result&&r.status!=="running"||r.error);return i.jsx("div",{style:{flex:1,overflow:"auto",background:t.appBg,padding:"32px 24px 48px"},children:i.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",display:"flex",flexDirection:"column",gap:24},children:[i.jsxs("div",{style:{textAlign:"center",marginBottom:8},children:[i.jsx("h1",{style:{fontSize:28,fontWeight:700,color:t.textPrimary,fontFamily:t.font,letterSpacing:"-0.3px",margin:0},children:e.notebookTitle||"Untitled"}),i.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?i.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=>i.jsx(iY,{cell:r},r.id))]})})}function iY({cell:e}){const{state:t}=Te(),n=oe[t.themeMode];if(e.type==="markdown")return i.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:lY(e.content,n)}});if(e.error)return i.jsxs("div",{style:{background:n.cellBg,borderRadius:10,border:`1px solid ${n.error}40`,padding:"16px 24px"},children:[e.name&&i.jsx(aY,{name:e.name,t:n}),i.jsx("div",{style:{color:n.error,fontSize:12,fontFamily:n.fontMono,whiteSpace:"pre-wrap"},children:e.error})]});if(!e.result)return null;const r=to(e.result,e.chartConfig),o=r!=="table";return i.jsxs("div",{style:{background:n.cellBg,borderRadius:10,border:`1px solid ${n.cellBorder}`,overflow:"hidden"},children:[i.jsxs("div",{style:{padding:"10px 20px",borderBottom:`1px solid ${n.cellBorder}`,display:"flex",alignItems:"center",gap:8},children:[e.name?i.jsx("span",{style:{fontSize:13,fontWeight:600,color:n.textPrimary,fontFamily:n.font,flex:1},children:e.name}):i.jsx("span",{style:{flex:1}}),i.jsxs("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.fontMono},children:[e.result.rowCount??e.result.rows.length," rows",e.result.executionTime!=null&&i.jsxs(i.Fragment,{children:[" · ",e.result.executionTime<1e3?`${e.result.executionTime}ms`:`${(e.result.executionTime/1e3).toFixed(1)}s`]})]})]}),i.jsx("div",{style:{padding:o?"16px 20px":0},children:o?ki(r,e.result,t.themeMode,e.chartConfig):i.jsx(mo,{result:e.result,themeMode:t.themeMode})})]})}function aY({name:e,t}){return i.jsx("div",{style:{fontSize:13,fontWeight:600,color:t.textPrimary,fontFamily:t.font,marginBottom:8},children:e})}function lY(e,t){const n=r=>r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");return e.split(`
|
|
699
|
-
`).map(r=>{const o=r.trim(),s=o.match(/^(#{1,6})\s+(.+)$/);if(s){const l=s[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(s[2])}</div>`}if(/^[-*_]{3,}$/.test(o))return`<hr style="border:none;border-top:1px solid ${t.cellBorder};margin:8px 0"/>`;if(!o)return'<div style="height:6px"></div>';let a=n(o);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 bh=[{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 cY(e){return e?bh.find(t=>t.value===e)??{value:e,label:e,dot:"#888"}:null}function EY(){const{state:e,dispatch:t}=Te(),n=oe[e.themeMode],[r,o]=f.useState(null),s=f.useRef(null);if(f.useEffect(()=>{if(!r)return;const S=A=>{s.current&&!s.current.contains(A.target)&&o(null)},h=A=>{A.key==="Escape"&&o(null)};return document.addEventListener("mousedown",S),document.addEventListener("keydown",h),()=>{document.removeEventListener("mousedown",S),document.removeEventListener("keydown",h)}},[r]),!e.activeFile)return null;const a=e.activeFile.name.replace(/\.dqlnb$/,""),l=e.notebookMetadata,c=S=>{t({type:"UPDATE_NOTEBOOK_METADATA",updates:S})},E=cY(l.status),d=(l.categories??[]).length>0,u=!!l.description,T=!!l.projectFilter;return i.jsxs("div",{ref:s,style:{maxWidth:1080,margin:"0 auto",padding:"32px 48px 8px",display:"flex",flexDirection:"column",gap:12},children:[i.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,alignItems:"center",position:"relative"},children:[i.jsx(ms,{t:n,active:r==="status",filled:!!E,icon:i.jsx("span",{style:{color:(E==null?void 0:E.dot)??n.textMuted,fontSize:12},children:"●"}),label:(E==null?void 0:E.label)??"Add status",onClick:()=>o(r==="status"?null:"status"),children:r==="status"&&i.jsxs(Cs,{t:n,children:[bh.map(S=>i.jsxs("button",{onClick:()=>{c({status:S.value}),o(null)},style:qT(n,l.status===S.value),children:[i.jsx("span",{style:{color:S.dot,fontSize:12},children:"●"}),i.jsx("span",{children:S.label})]},S.value)),l.status&&i.jsx("button",{onClick:()=>{c({status:void 0}),o(null)},style:{...qT(n,!1),color:n.textMuted},children:i.jsx("span",{children:"Clear"})})]})}),i.jsx(ms,{t:n,active:r==="categories",filled:d,icon:i.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10},children:"#"}),label:d?(l.categories??[]).slice(0,3).join(", ")+((l.categories??[]).length>3?"…":""):"Add categories",onClick:()=>o(r==="categories"?null:"categories"),children:r==="categories"&&i.jsx(Cs,{t:n,width:260,children:i.jsx(uY,{t:n,value:l.categories??[],onChange:S=>c({categories:S.length?S:void 0})})})}),i.jsx(ms,{t:n,active:r==="description",filled:u,icon:i.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10},children:"✎"}),label:u?zT(l.description,48):"Add description",onClick:()=>o(r==="description"?null:"description"),children:r==="description"&&i.jsx(Cs,{t:n,width:320,children:i.jsx(JT,{multiline:!0,initial:l.description??"",onCommit:S=>c({description:S||void 0}),placeholder:"What does this notebook answer?",style:dY(n)})})}),i.jsx(ms,{t:n,active:r==="projectFilter",filled:T,icon:i.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10},children:"⌕"}),label:T?zT(l.projectFilter,32):"Add project filter",onClick:()=>o(r==="projectFilter"?null:"projectFilter"),children:r==="projectFilter"&&i.jsx(Cs,{t:n,width:280,children:i.jsx(JT,{initial:l.projectFilter??"",onCommit:S=>c({projectFilter:S||void 0}),placeholder:"e.g. team:analytics",style:vh(n)})})})]}),i.jsx("div",{style:{fontSize:22,fontWeight:600,color:n.textPrimary,fontFamily:n.font,letterSpacing:"-0.01em"},children:a})]})}function zT(e,t){return e.length>t?`${e.slice(0,t-1)}…`:e}function JT({initial:e,onCommit:t,multiline:n,placeholder:r,style:o}){const[s,a]=f.useState(e),l=f.useRef(s);l.current=s;const c=()=>{const E=l.current.trim();E!==e.trim()&&t(E)};return f.useEffect(()=>()=>c(),[]),n?i.jsx("textarea",{autoFocus:!0,value:s,onChange:E=>a(E.target.value),onBlur:c,placeholder:r,rows:4,style:o}):i.jsx("input",{autoFocus:!0,value:s,onChange:E=>a(E.target.value),onBlur:c,onKeyDown:E=>{E.key==="Enter"&&(E.preventDefault(),E.target.blur())},placeholder:r,style:o})}function ms({t:e,active:t,filled:n,icon:r,label:o,onClick:s,children:a}){return i.jsxs("div",{style:{position:"relative"},children:[i.jsxs("button",{className:"dql-meta-pill",onClick:s,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,i.jsx("span",{children:o})]}),a]})}function Cs({t:e,width:t=200,children:n}){return i.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 qT(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 dY(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 vh(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 uY({t:e,value:t,onChange:n}){const[r,o]=f.useState(""),s=()=>{const a=r.trim();if(a){if(t.includes(a)){o("");return}n([...t,a]),o("")}};return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.length>0&&i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:t.map(a=>i.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,i.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))}),i.jsx("input",{autoFocus:!0,value:r,onChange:a=>o(a.target.value),onKeyDown:a=>{a.key==="Enter"||a.key===","?(a.preventDefault(),s()):a.key==="Backspace"&&!r&&t.length>0&&n(t.slice(0,-1))},placeholder:"Add category, press Enter",style:vh(e)})]})}function TY({onOpenFile:e,registerCellRef:t}){const{state:n}=Te(),r=oe[n.themeMode];return n.activeFile?n.dashboardMode?i.jsx(sY,{}):i.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",background:r.appBg},children:[i.jsx(SY,{t:r}),i.jsxs("div",{style:{flex:1,overflow:"auto",padding:"0 0 40px"},children:[i.jsx(EY,{}),i.jsx(rY,{registerCellRef:t})]})]}):i.jsx(Ey,{onOpenFile:e})}function SY({t:e}){const{state:t}=Te(),n=t.cells.length;return i.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:[i.jsx(fY,{t:e}),i.jsx("div",{style:{flex:1}}),i.jsxs("span",{style:{fontSize:11,color:e.textMuted,fontFamily:e.font,display:"flex",alignItems:"center",gap:12},children:[i.jsxs("span",{children:[n," ",n===1?"cell":"cells"]}),t.notebookDirty&&i.jsx("span",{style:{color:e.warning},children:"● unsaved"})]})]})}function fY({t:e}){const{state:t}=Te();if(!t.activeFile)return null;const n=t.activeFile.path.split("/").filter(Boolean);return i.jsx("div",{style:{display:"flex",alignItems:"center",gap:4,fontSize:12,fontFamily:e.fontMono,color:e.textMuted,overflow:"hidden"},children:n.map((r,o)=>i.jsxs(ge.Fragment,{children:[o>0&&i.jsx("span",{style:{color:e.textMuted,opacity:.5},children:"/"}),i.jsx("span",{style:{color:o===n.length-1?e.textSecondary:e.textMuted,fontWeight:o===n.length-1?500:400,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:o===n.length-1?200:100},children:r})]},o))})}const QT={blank:"Blank",revenue:"Revenue Analysis",pipeline:"Pipeline Health"},RY={blank:"Start with an empty notebook.",revenue:"Pre-built queries for revenue metrics and trends.",pipeline:"Templates for data pipeline health monitoring."};function ZT(e){return e.toLowerCase().replace(/[^a-z0-9\-_\s]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,64)}function AY(e){return e.trim()?/^[a-zA-Z0-9\-_ ]+$/.test(e)?null:"Only letters, numbers, hyphens, underscores, and spaces allowed.":"Name is required."}function pY(e){switch(e){case"revenue":return[$e("markdown",`# Revenue Analysis
|
|
700
|
-
|
|
701
|
-
This notebook analyzes revenue metrics and trends over time.`),{...$e("sql",`SELECT
|
|
702
|
-
DATE_TRUNC('month', order_date) AS month,
|
|
703
|
-
SUM(amount) AS revenue
|
|
704
|
-
FROM orders
|
|
705
|
-
GROUP BY 1
|
|
706
|
-
ORDER BY 1`),name:"monthly_revenue"},{...$e("sql",`SELECT
|
|
707
|
-
product_category,
|
|
708
|
-
SUM(amount) AS total_revenue,
|
|
709
|
-
COUNT(*) AS orders
|
|
710
|
-
FROM orders
|
|
711
|
-
GROUP BY 1
|
|
712
|
-
ORDER BY 2 DESC`),name:"revenue_by_category"}];case"pipeline":return[$e("markdown",`# Pipeline Health
|
|
713
|
-
|
|
714
|
-
Monitor data pipeline performance, SLA compliance, and error rates.`),{...$e("sql",`SELECT
|
|
715
|
-
pipeline_name,
|
|
716
|
-
COUNT(*) AS runs,
|
|
717
|
-
AVG(duration_seconds) AS avg_duration,
|
|
718
|
-
SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failures
|
|
719
|
-
FROM pipeline_runs
|
|
720
|
-
GROUP BY 1
|
|
721
|
-
ORDER BY 4 DESC`),name:"pipeline_summary"},{...$e("sql",`SELECT
|
|
722
|
-
*
|
|
723
|
-
FROM pipeline_runs
|
|
724
|
-
WHERE status = 'failed'
|
|
725
|
-
AND run_date >= CURRENT_DATE - INTERVAL '7 days'
|
|
726
|
-
ORDER BY run_date DESC`),name:"recent_failures"}];default:return[$e("sql")]}}function hY({onFileOpened:e}){const{state:t,dispatch:n}=Te(),r=oe[t.themeMode],[o,s]=f.useState(""),[a,l]=f.useState("blank"),[c,E]=f.useState(null),[d,u]=f.useState(!1),T=f.useRef(null);f.useEffect(()=>{var A;(A=T.current)==null||A.focus()},[]),f.useEffect(()=>{const A=R=>{R.key==="Escape"&&n({type:"CLOSE_NEW_NOTEBOOK_MODAL"})};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[n]);const S=async()=>{const A=AY(o);if(A){E(A);return}u(!0),E(null);const R=ZT(o),p=pY(a);try{const N=await Z.createNotebook(R,a),I={name:`${R}.dqlnb`,path:N.path,type:"notebook",folder:"notebooks",isNew:!0};n({type:"FILE_ADDED",file:I}),n({type:"OPEN_FILE",file:I,cells:p,title:o.trim()}),n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),e(I)}catch{const N=`notebooks/${R}.dqlnb`,I={name:`${R}.dqlnb`,path:N,type:"notebook",folder:"notebooks",isNew:!0};n({type:"FILE_ADDED",file:I}),n({type:"OPEN_FILE",file:I,cells:p,title:o.trim()}),n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),e(I)}finally{u(!1)}},h=A=>{A.target===A.currentTarget&&n({type:"CLOSE_NEW_NOTEBOOK_MODAL"})};return i.jsx("div",{onClick:h,style:{position:"fixed",inset:0,background:r.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(4px)"},children:i.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:[i.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[i.jsx("h2",{style:{fontSize:16,fontWeight:600,color:r.textPrimary,fontFamily:r.font,margin:0},children:"New Notebook"}),i.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:"×"})]}),i.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:20},children:[i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Name"}),i.jsx("input",{ref:T,value:o,onChange:A=>{s(A.target.value),E(null)},onKeyDown:A=>{A.key==="Enter"&&S()},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&&i.jsx("span",{style:{fontSize:11,color:r.error,fontFamily:r.font},children:c}),o&&!c&&i.jsxs("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.fontMono},children:["File: ",ZT(o),".dqlnb"]})]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Template"}),i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:Object.keys(QT).map(A=>i.jsx(IY,{value:A,selected:a===A,onSelect:()=>l(A),label:QT[A],description:RY[A],t:r},A))})]})]}),i.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${r.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[i.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"}),i.jsx("button",{onClick:S,disabled:d||!o.trim(),style:{background:r.accent,border:`1px solid ${r.accent}`,borderRadius:6,color:"#ffffff",cursor:d||!o.trim()?"not-allowed":"pointer",fontSize:13,fontFamily:r.font,fontWeight:500,padding:"7px 20px",opacity:d||!o.trim()?.6:1,display:"flex",alignItems:"center",gap:6},children:d?"Creating…":"Create Notebook"})]})]})})}function IY({value:e,selected:t,onSelect:n,label:r,description:o,t:s}){const[a,l]=f.useState(!1);return i.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?s.cellBorderActive:a?s.textMuted:s.inputBorder}`,background:t?`${s.cellBorderActive}10`:a?s.sidebarItemHover:"transparent",cursor:"pointer",transition:"all 0.15s"},children:[i.jsx("div",{style:{width:16,height:16,borderRadius:8,border:`2px solid ${t?s.accent:s.textMuted}`,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:1,transition:"border-color 0.15s"},children:t&&i.jsx("div",{style:{width:8,height:8,borderRadius:4,background:s.accent}})}),i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:13,fontWeight:500,color:s.textPrimary,fontFamily:s.font,marginBottom:2},children:r}),i.jsx("div",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font},children:o})]})]})}function eS(e){return e.toLowerCase().replace(/[^a-z0-9\-_\s]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,64)}function NY(e){return e.trim()?/^[a-zA-Z0-9\-_ ]+$/.test(e)?null:"Only letters, numbers, hyphens, underscores, and spaces allowed.":"Name is required."}function OY({onFileOpened:e}){const{state:t,dispatch:n}=Te(),r=oe[t.themeMode],[o,s]=f.useState(""),[a,l]=f.useState(null),[c,E]=f.useState(!1),d=f.useRef(null);f.useEffect(()=>{var S;(S=d.current)==null||S.focus()},[]),f.useEffect(()=>{const S=h=>{h.key==="Escape"&&n({type:"CLOSE_NEW_BLOCK_MODAL"})};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[n]);const u=async()=>{var A;const S=NY(o);if(S){l(S);return}E(!0),l(null);const h=eS(o);try{const R=await Z.createBlock(o.trim()),p={name:`${h}.dql`,path:R.path,type:"block",folder:"blocks",isNew:!0};n({type:"FILE_ADDED",file:p}),n({type:"CLOSE_NEW_BLOCK_MODAL"}),e(p)}catch(R){(A=R.message)!=null&&A.includes("already exists")?l("A block with this name already exists."):l(R.message??"Failed to create block.")}finally{E(!1)}},T=S=>{S.target===S.currentTarget&&n({type:"CLOSE_NEW_BLOCK_MODAL"})};return i.jsx("div",{onClick:T,style:{position:"fixed",inset:0,background:r.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(4px)"},children:i.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:[i.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[i.jsx("h2",{style:{fontSize:16,fontWeight:600,color:r.textPrimary,fontFamily:r.font,margin:0},children:"New Block"}),i.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:"×"})]}),i.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:16},children:[i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Block Name"}),i.jsx("input",{ref:d,value:o,onChange:S=>{s(S.target.value),l(null)},onKeyDown:S=>{S.key==="Enter"&&u()},placeholder:"revenue-summary",style:{background:r.inputBg,border:`1px solid ${a?r.error:r.inputBorder}`,borderRadius:6,color:r.textPrimary,fontSize:13,fontFamily:r.font,padding:"8px 12px",outline:"none",transition:"border-color 0.15s"}}),a&&i.jsx("span",{style:{fontSize:11,color:r.error,fontFamily:r.font},children:a}),o&&!a&&i.jsxs("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.fontMono},children:["blocks/",eS(o),".dql"]})]}),i.jsxs("div",{style:{fontSize:12,color:r.textMuted,fontFamily:r.font,lineHeight:1.5,padding:"8px 12px",background:r.pillBg,borderRadius:6},children:["Blocks are reusable SQL queries stored in the ",i.jsx("code",{style:{fontFamily:r.fontMono,fontSize:11},children:"blocks/"})," folder. They can be referenced from notebooks and other blocks."]})]}),i.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${r.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[i.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"}),i.jsx("button",{onClick:u,disabled:c||!o.trim(),style:{background:r.accent,border:`1px solid ${r.accent}`,borderRadius:6,color:"#ffffff",cursor:c||!o.trim()?"not-allowed":"pointer",fontSize:13,fontFamily:r.font,fontWeight:500,padding:"7px 20px",opacity:c||!o.trim()?.6:1,display:"flex",alignItems:"center",gap:6},children:c?"Creating...":"Create Block"})]})]})})}function mY({item:e,favorite:t,onInsert:n,onPreview:r,onCopySql:o,onToggleFavorite:s,t:a}){if(!e)return null;const l=e.kind==="metric"||e.kind==="dimension",c=!!e.sql,E=e.source?`${e.source.provider} · ${e.source.objectType}`:null;return i.jsxs("div",{style:{borderTop:`1px solid ${a.headerBorder}`,padding:"12px 10px",display:"flex",flexDirection:"column",gap:10,background:`${a.cellBg}cc`},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsxs("div",{style:{flex:1,minWidth:0},children:[i.jsx("div",{style:{fontSize:12,fontWeight:600,color:a.textPrimary,fontFamily:a.font},children:e.label||e.name}),i.jsxs("div",{style:{fontSize:10,color:a.textMuted,fontFamily:a.fontMono},children:[e.kind," · ",e.name]})]}),i.jsx("button",{onClick:s,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&&i.jsx("div",{style:{fontSize:12,color:a.textSecondary,fontFamily:a.font,lineHeight:1.5},children:e.description}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,fontSize:11,fontFamily:a.fontMono,color:a.textMuted},children:[i.jsxs("div",{children:["domain: ",e.domain||"uncategorized"]}),i.jsxs("div",{children:["owner: ",e.owner??"unassigned"]}),e.table?i.jsxs("div",{children:["table: ",e.table]}):i.jsx("div",{}),e.cube?i.jsxs("div",{children:["cube: ",e.cube]}):i.jsx("div",{}),e.type?i.jsxs("div",{children:["type: ",e.type]}):i.jsx("div",{}),E?i.jsxs("div",{children:["source: ",E]}):i.jsx("div",{})]}),e.tags.length>0&&i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:e.tags.map(d=>i.jsx("span",{style:{fontSize:10,color:a.textMuted,background:a.pillBg,borderRadius:999,padding:"2px 8px",fontFamily:a.font},children:d},d))}),e.sql&&i.jsxs("div",{style:{position:"relative"},children:[i.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}),i.jsx("button",{onClick:o,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&&i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsx("div",{style:{fontSize:11,fontWeight:600,color:a.textSecondary,fontFamily:a.font},children:"Joins"}),e.joins.map(d=>i.jsxs("div",{style:{fontSize:10,color:a.textMuted,fontFamily:a.fontMono},children:[d.left," ",d.type," ",d.right]},d.name))]}),e.levels&&e.levels.length>0&&i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsx("div",{style:{fontSize:11,fontWeight:600,color:a.textSecondary,fontFamily:a.font},children:"Levels"}),e.levels.map(d=>i.jsxs("div",{style:{fontSize:10,color:a.textMuted,fontFamily:a.fontMono},children:[d.order,". ",d.label," → ",d.dimension]},d.name))]}),i.jsxs("div",{style:{display:"flex",gap:8},children:[i.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"}),i.jsx("button",{onClick:o,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"}),i.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 CY({query:e,provider:t,cube:n,owner:r,domain:o,tag:s,type:a,providers:l,cubes:c,owners:E,domains:d,tags:u,onQueryChange:T,onProviderChange:S,onCubeChange:h,onOwnerChange:A,onDomainChange:R,onTagChange:p,onTypeChange:N,t:I}){const O={width:"100%",background:I.inputBg,border:`1px solid ${I.inputBorder}`,borderRadius:6,color:I.textPrimary,fontSize:12,fontFamily:I.font,padding:"7px 10px",outline:"none",boxSizing:"border-box"};return i.jsxs("div",{style:{padding:"10px",display:"flex",flexDirection:"column",gap:8,borderBottom:`1px solid ${I.headerBorder}`},children:[i.jsx("input",{value:e,onChange:m=>T(m.target.value),placeholder:"Search labels, cubes, owners, tags...",style:O}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:6},children:[i.jsxs("select",{value:t,onChange:m=>S(m.target.value),style:O,children:[i.jsx("option",{value:"",children:"All providers"}),l.map(m=>i.jsx("option",{value:m,children:m},m))]}),i.jsxs("select",{value:o,onChange:m=>R(m.target.value),style:O,children:[i.jsx("option",{value:"",children:"All domains"}),d.map(m=>i.jsx("option",{value:m,children:m},m))]}),i.jsxs("select",{value:n,onChange:m=>h(m.target.value),style:O,children:[i.jsx("option",{value:"",children:"All cubes"}),c.map(m=>i.jsx("option",{value:m,children:m},m))]}),i.jsxs("select",{value:r,onChange:m=>A(m.target.value),style:O,children:[i.jsx("option",{value:"",children:"All owners"}),E.map(m=>i.jsx("option",{value:m,children:m},m))]}),i.jsxs("select",{value:s,onChange:m=>p(m.target.value),style:O,children:[i.jsx("option",{value:"",children:"All tags"}),u.map(m=>i.jsx("option",{value:m,children:m},m))]}),i.jsxs("select",{value:a,onChange:m=>N(m.target.value),style:O,children:[i.jsx("option",{value:"",children:"All types"}),i.jsx("option",{value:"cube",children:"Cubes"}),i.jsx("option",{value:"metric",children:"Metrics"}),i.jsx("option",{value:"dimension",children:"Dimensions"}),i.jsx("option",{value:"hierarchy",children:"Hierarchies"}),i.jsx("option",{value:"segment",children:"Segments"}),i.jsx("option",{value:"pre_aggregation",children:"Pre-aggregations"})]})]})]})}function Tc({label:e,depth:t=0,badge:n,badgeColor:r,count:o,expanded:s,favorite:a,selected:l,onClick:c,onDoubleClick:E,onToggle:d,onFavoriteToggle:u,onDragStart:T,title:S,muted:h,t:A}){const[R,p]=f.useState(!1);return i.jsxs("button",{draggable:!!T,onDragStart:T,onClick:c,onDoubleClick:E,onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),title:S,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:`5px 8px 5px ${10+t*14}px`,background:l?`${A.accent}18`:R?A.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:h?A.textMuted:A.textPrimary,fontSize:12,fontFamily:A.font,textAlign:"left"},children:[d?i.jsx("span",{onClick:N=>{N.stopPropagation(),d()},style:{display:"inline-flex",transform:s?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.15s",color:A.textMuted},children:i.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:i.jsx("path",{d:"M3 2l4 3-4 3V2Z"})})}):i.jsx("span",{style:{width:10,flexShrink:0}}),i.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e}),n&&i.jsx("span",{style:{fontSize:9,fontFamily:A.fontMono,color:r??A.accent,background:`${r??A.accent}18`,borderRadius:4,padding:"1px 4px",flexShrink:0},children:n}),typeof o=="number"&&i.jsx("span",{style:{fontSize:10,color:A.textMuted,background:A.pillBg,borderRadius:999,padding:"1px 6px",flexShrink:0},children:o}),typeof a=="boolean"&&i.jsx("span",{onClick:N=>{N.stopPropagation(),u==null||u()},style:{color:a?"#e3b341":A.textMuted,display:"inline-flex",flexShrink:0},children:i.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:i.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 gs=31,tS=10;function gY(){var xr,Vo,$o,Xo,Ko,zo,Jo,yr;const{state:e,dispatch:t}=Te(),n=oe[e.themeMode],[r,o]=f.useState("semantic"),[s,a]=f.useState("validate"),[l,c]=f.useState(""),[E,d]=f.useState(""),[u,T]=f.useState(""),[S,h]=f.useState(""),[A,R]=f.useState(""),[p,N]=f.useState(""),[I,O]=f.useState(""),[m,C]=f.useState({}),[g,y]=f.useState(null),[_,P]=f.useState(null),[D,b]=f.useState([]),[F,x]=f.useState({}),[w,M]=f.useState(""),[B,v]=f.useState(new Set),[L,U]=f.useState(!1),[G,k]=f.useState(!1),[J,K]=f.useState(null),[$,z]=f.useState(null),[q,X]=f.useState([]),[Q,ae]=f.useState(!1),[ne,re]=f.useState(null),[Y,se]=f.useState(!1),[de,ue]=f.useState(!1),[me,je]=f.useState(null),[ve,St]=f.useState(null),[Tn,kt]=f.useState(null),[Bn,Po]=f.useState(!1),[jt,Lt]=f.useState(0),[Yt,bo]=f.useState(400),[vo,gr]=f.useState(360),[Uo,oa]=f.useState(420),[Wt,wo]=f.useState(!1),[Vt,Bo]=f.useState(!1),Fn=f.useRef(null);f.useEffect(()=>{t({type:"SET_BLOCK_STUDIO_CATALOG_LOADING",loading:!0}),z(null),Z.getBlockStudioCatalog().then(j=>{t({type:"SET_BLOCK_STUDIO_CATALOG",catalog:j}),b(j.databaseTree)}).catch(()=>{z("Failed to load schema. Check your connection and try refreshing.")}).finally(()=>t({type:"SET_BLOCK_STUDIO_CATALOG_LOADING",loading:!1}))},[t]),f.useEffect(()=>{if(!g||g.startsWith("provider:")||g.startsWith("domain:")||g.startsWith("group:")){P(null);return}Z.getSemanticObject(g).then(P).catch(()=>P(null))},[g]),f.useEffect(()=>{const j=window.setTimeout(()=>{e.blockStudioDraft.trim()&&Z.validateBlockStudio(e.blockStudioDraft,e.activeBlockPath).then(Ee=>t({type:"SET_BLOCK_STUDIO_VALIDATION",validation:Ee})).catch(()=>{})},250);return()=>window.clearTimeout(j)},[e.blockStudioDraft,e.activeBlockPath,t]);const Lr=((xr=e.blockStudioCatalog)==null?void 0:xr.semanticTree)??null,nt=f.useMemo(()=>HY(Lr)?Lr:kY(e.semanticLayer),[Lr,e.semanticLayer]),sa=f.useMemo(()=>Dl(nt,"provider"),[nt]),ia=f.useMemo(()=>Dl(nt,"cube"),[nt]),aa=f.useMemo(()=>Dl(nt,"owner"),[nt]),Gn=f.useMemo(()=>nt?Uh(nt,{query:l,provider:E,domain:u,cube:S,owner:A,tag:p,type:I}):null,[nt,l,E,u,S,A,p,I]),Sn=f.useMemo(()=>wh((Gn==null?void 0:Gn.children)??[],m),[Gn,m]),la=f.useMemo(()=>FY(D,w),[D,w]),ca=f.useMemo(()=>GY(D),[D]),_r={metrics:e.semanticLayer.metrics.length,dimensions:e.semanticLayer.dimensions.length,hierarchies:e.semanticLayer.hierarchies.length},Ea=Sn.length*gs,Fo=f.useMemo(()=>{const j=Math.max(0,Math.floor(jt/gs)-tS),Ee=Math.min(Sn.length,Math.ceil((jt+Yt)/gs)+tS);return{offsetTop:j*gs,rows:Sn.slice(j,Ee)}},[Sn,jt,Yt]);f.useEffect(()=>{const j=Fn.current;if(!j)return;const Ee=()=>bo(j.clientHeight||400);if(Ee(),typeof ResizeObserver>"u")return window.addEventListener("resize",Ee),()=>window.removeEventListener("resize",Ee);const Ce=new ResizeObserver(()=>Ee());return Ce.observe(j),()=>Ce.disconnect()},[]),f.useEffect(()=>{Lt(0),Fn.current&&(Fn.current.scrollTop=0)},[l,E,u,S,A,p,I]);const Hn=f.useMemo(()=>{var Ee;const j=Od(e.blockStudioDraft);return e.blockStudioMetadata?{...j,name:(j==null?void 0:j.name)||e.blockStudioMetadata.name,domain:(j==null?void 0:j.domain)||e.blockStudioMetadata.domain,description:(j==null?void 0:j.description)||e.blockStudioMetadata.description,owner:(j==null?void 0:j.owner)||e.blockStudioMetadata.owner,tags:(Ee=j==null?void 0:j.tags)!=null&&Ee.length?j.tags:e.blockStudioMetadata.tags,blockType:(j==null?void 0:j.blockType)||"custom"}:j},[e.blockStudioDraft,e.blockStudioMetadata]),$t=(Hn==null?void 0:Hn.name)??((Vo=e.blockStudioMetadata)==null?void 0:Vo.name)??null;f.useEffect(()=>{if(!$t)return;const j=`block:${$t}`;t({type:"SET_LINEAGE_FOCUS",nodeId:j}),ue(!0),Promise.all([Z.fetchLineageNode(j),Z.queryLineage({focus:j}),Z.fetchLineagePaths(j)]).then(([Ee,Ce,_e])=>{je(Ee),St(Ce.graph??null),kt(_e)}).catch(()=>{je(null),St(null),kt(null)}).finally(()=>ue(!1))},[$t,t]);const Ye=j=>{t({type:"SET_BLOCK_STUDIO_DRAFT",draft:j})},Go=async()=>{var j,Ee,Ce;U(!0);try{const _e=await Z.runBlockStudio(e.blockStudioDraft,e.activeBlockPath);t({type:"SET_BLOCK_STUDIO_PREVIEW",preview:_e}),a("results")}catch(_e){t({type:"SET_BLOCK_STUDIO_VALIDATION",validation:{valid:!1,chartConfig:(j=e.blockStudioValidation)==null?void 0:j.chartConfig,executableSql:((Ee=e.blockStudioValidation)==null?void 0:Ee.executableSql)??null,semanticRefs:((Ce=e.blockStudioValidation)==null?void 0:Ce.semanticRefs)??{metrics:[],dimensions:[],segments:[]},diagnostics:[{severity:"error",code:"block_run_failed",message:_e instanceof Error?_e.message:String(_e)}]}}),a("validate")}finally{U(!1)}},Ho=async()=>{if(!e.blockStudioMetadata){t({type:"OPEN_NEW_BLOCK_MODAL"});return}k(!0),K(null);try{const j=await Z.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:`${j.metadata.name}.dql`,path:j.path,type:"block",folder:"blocks"},payload:j}),e.files.some(Ce=>Ce.path===j.path)||t({type:"FILE_ADDED",file:{name:`${j.metadata.name}.dql`,path:j.path,type:"block",folder:"blocks"}}),a("save")}catch(j){const Ee=(j==null?void 0:j.message)??"Save failed";K(Ee.includes("409")||Ee.includes("BLOCK_EXISTS")?"A block with this name already exists. Rename and try again.":Ee),setTimeout(()=>K(null),5e3)}finally{k(!1)}},ko=j=>{var Ee;if(j.kind==="metric"||j.kind==="dimension"){const Ce=Wx(j.kind==="metric"?"metric":"dimension",j.name);(((Ee=Od(e.blockStudioDraft))==null?void 0:Ee.blockType)??"custom")==="semantic"?Ye(Vx(e.blockStudioDraft,{kind:j.kind==="metric"?"metric":"dimension",name:j.name})):ky(Ce)||Ye($x(e.blockStudioDraft,Ce)),t({type:"ADD_SEMANTIC_RECENT",name:j.name});return}if(j.kind==="segment"&&j.sql){Ye(_s(e.blockStudioDraft,`/* segment:${j.name} */ (${j.sql})`));return}j.kind==="pre_aggregation"&&Ye(_s(e.blockStudioDraft,`/* pre_aggregation:${j.name} */`))},da=j=>{Ye(_s(e.blockStudioDraft,j))},ua=async j=>{if(!(!j.path||j.kind!=="table"||j.children&&j.children.length>0)){v(Ee=>new Set(Ee).add(j.id));try{const Ee=await Z.describeTable(j.path);b(Ce=>Bh(Ce,j.id,{...j,children:Ee.map(_e=>({id:`db-column:${j.path}:${_e.name}`,label:_e.name,kind:"column",path:j.path,type:_e.type}))}))}finally{v(Ee=>{const Ce=new Set(Ee);return Ce.delete(j.id),Ce})}}},jo=f.useCallback(async()=>{try{const j=await Z.getBlockStudioCatalog();j!=null&&j.databaseTree&&b(j.databaseTree),t({type:"SET_BLOCK_STUDIO_CATALOG",catalog:j})}catch{}},[t]),Ta=(($o=e.blockStudioValidation)==null?void 0:$o.chartConfig)??((Xo=e.blockStudioPreview)==null?void 0:Xo.chartConfig)??{chart:"table"},Sa=e.blockStudioPreview?to(e.blockStudioPreview.result,e.blockStudioPreview.chartConfig):"table",Yo=j=>{j.preventDefault();const Ee=j.clientX,Ce=vo,_e=Dr=>{const Mr=Math.min(520,Math.max(280,Ce+Dr.clientX-Ee));gr(Mr)},fn=()=>{window.removeEventListener("mousemove",_e),window.removeEventListener("mouseup",fn)};window.addEventListener("mousemove",_e),window.addEventListener("mouseup",fn)},Wo=j=>{j.preventDefault();const Ee=j.clientY,Ce=Uo,_e=Dr=>{const Mr=Math.min(520,Math.max(180,Ce-(Dr.clientY-Ee)));oa(Mr)},fn=()=>{window.removeEventListener("mousemove",_e),window.removeEventListener("mouseup",fn)};window.addEventListener("mousemove",_e),window.addEventListener("mouseup",fn)};return i.jsxs("div",{style:{flex:1,position:"relative",display:"grid",gridTemplateColumns:Wt?"0 0 minmax(0, 1fr)":`${vo}px 6px minmax(0, 1fr)`,gridTemplateRows:Vt?"minmax(0, 1fr) 0 0":`minmax(0, 1fr) 6px ${Uo}px`,overflow:"hidden",background:n.appBg},children:[i.jsxs("div",{style:{borderRight:Wt?"none":`1px solid ${n.headerBorder}`,display:Wt?"none":"flex",flexDirection:"column",overflow:"hidden",background:n.sidebarBg,minWidth:0},children:[i.jsxs("div",{style:{padding:14,display:"grid",gap:12,borderBottom:`1px solid ${n.headerBorder}`},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:12,fontWeight:700,color:n.textPrimary,fontFamily:n.font},children:"Block Studio"}),i.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:"Build DQL with semantic models and live database structure in one workspace."})]}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.semanticLayer.provider&&i.jsx("span",{style:{fontSize:10,fontWeight:700,color:n.accent,background:`${n.accent}18`,borderRadius:999,padding:"5px 9px",textTransform:"uppercase",letterSpacing:"0.04em"},children:e.semanticLayer.provider}),i.jsx("button",{onClick:()=>wo(!0),style:{background:n.btnBg,border:`1px solid ${n.btnBorder}`,borderRadius:6,color:n.textSecondary,cursor:"pointer",fontSize:12,fontFamily:n.font,padding:"4px 8px"},title:"Collapse explorer",children:"‹"})]})]}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:8},children:[i.jsx(or,{label:"Metrics",value:_r.metrics,t:n}),i.jsx(or,{label:"Dimensions",value:_r.dimensions,t:n}),i.jsx(or,{label:"Hierarchies",value:_r.hierarchies,t:n})]})]}),i.jsxs("div",{style:{display:"flex",padding:"10px 12px",gap:8,borderBottom:`1px solid ${n.headerBorder}`},children:[i.jsx(ft,{active:r==="semantic",onClick:()=>o("semantic"),label:"Semantic Layer"}),i.jsx(ft,{active:r==="database",onClick:()=>o("database"),label:"Database"})]}),r==="semantic"?i.jsxs(i.Fragment,{children:[i.jsx("div",{style:{padding:12,borderBottom:`1px solid ${n.headerBorder}`,background:`${n.cellBg}66`},children:i.jsx(CY,{query:l,provider:E,cube:S,owner:A,domain:u,tag:p,type:I,providers:sa,cubes:ia,owners:aa,domains:e.semanticLayer.domains,tags:e.semanticLayer.tags,onQueryChange:c,onProviderChange:d,onCubeChange:h,onOwnerChange:R,onDomainChange:T,onTagChange:N,onTypeChange:O,t:n})}),i.jsx("div",{ref:Fn,onScroll:j=>Lt(j.currentTarget.scrollTop),style:{flex:1,overflowY:"auto",borderBottom:`1px solid ${n.headerBorder}`,background:n.cellBg},children:$?i.jsxs("div",{style:{padding:16,display:"grid",gap:8,textAlign:"center"},children:[i.jsx("div",{style:{fontSize:12,color:"#f85149",fontFamily:n.font},children:$}),i.jsx("button",{onClick:()=>{z(null),jo()},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?i.jsx(vt,{message:"Loading semantic catalog…"}):Sn.length===0?i.jsx(vt,{message:"No semantic objects match the current filters."}):i.jsx("div",{style:{height:Ea,position:"relative"},children:i.jsx("div",{style:{position:"absolute",top:Fo.offsetTop,left:0,right:0},children:Fo.rows.map(j=>i.jsx(UY,{row:j,selectedId:g,setSelectedId:y,expanded:m,setExpanded:C,onInsert:ko,favorites:new Set(e.semanticLayer.favorites),dispatch:t,t:n},j.node.id))})})}),i.jsx(mY,{item:_,favorite:!!(_&&e.semanticLayer.favorites.includes(_.name)),onInsert:()=>_&&ko(_),onPreview:()=>{_!=null&&_.sql&&Ye(_s(e.blockStudioDraft,_.sql))},onCopySql:()=>{_!=null&&_.sql&&navigator.clipboard.writeText(_.sql)},onToggleFavorite:()=>{!_||_.kind!=="metric"&&_.kind!=="dimension"||Z.toggleFavorite(_.name).then(j=>t({type:"SET_SEMANTIC_FAVORITES",favorites:j}))},t:n})]}):i.jsx(vY,{tree:la,totalTree:D,expanded:F,setExpanded:x,onEnsureColumns:ua,onInsert:da,query:w,onQueryChange:M,stats:ca,connectionName:((Ko=e.blockStudioCatalog)==null?void 0:Ko.connection.current)??"default",loadingNodes:B,onRefresh:jo,t:n})]}),i.jsx("div",{onMouseDown:Wt?void 0:Yo,style:{display:Wt?"none":"block",cursor:"col-resize",background:n.headerBorder}}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0,overflow:"hidden",gridColumn:"3",gridRow:"1"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"12px 14px",borderBottom:`1px solid ${n.headerBorder}`,background:n.cellBg},children:[Wt&&i.jsx("button",{onClick:()=>wo(!1),style:{background:n.btnBg,border:`1px solid ${n.btnBorder}`,borderRadius:6,color:n.textSecondary,cursor:"pointer",fontSize:12,fontFamily:n.font,padding:"6px 10px"},title:"Open explorer",children:"Explorer"}),i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:12,fontWeight:700,color:n.textPrimary,fontFamily:n.font},children:"DQL Source"}),i.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:"Use templates, insert semantic refs, run, validate, and save from one editor."})]}),i.jsx("div",{style:{flex:1}}),i.jsx(Ls,{label:"Semantic Skeleton",onClick:()=>{var j;return Ye(wY(((j=e.blockStudioMetadata)==null?void 0:j.name)??"New Block"))}}),i.jsx(Ls,{label:"Custom Skeleton",onClick:()=>{var j;return Ye(BY(((j=e.blockStudioMetadata)==null?void 0:j.name)??"New Block"))}}),i.jsx(Ls,{label:"Run",onClick:()=>void Go(),busy:L}),i.jsx(Ls,{label:"Save",onClick:()=>void Ho(),busy:G}),J&&i.jsx("span",{style:{fontSize:11,color:"#f85149",fontFamily:n.font,padding:"4px 8px",background:"#f8514918",borderRadius:6},children:J})]}),i.jsx("div",{style:{flex:1,overflow:"hidden"},children:i.jsx(Qc,{value:e.blockStudioDraft,onChange:Ye,onRun:()=>void Go(),themeMode:e.themeMode,autoFocus:!0,errorMessage:(Jo=(zo=e.blockStudioValidation)==null?void 0:zo.diagnostics.find(j=>j.severity==="error"))==null?void 0:Jo.message})})]}),i.jsx("div",{onMouseDown:Vt?void 0:Wo,style:{gridColumn:"1 / -1",gridRow:"2",display:Vt?"none":"block",cursor:"row-resize",background:n.headerBorder}}),i.jsxs("div",{style:{gridColumn:"1 / -1",gridRow:"3",borderTop:Vt?"none":`1px solid ${n.headerBorder}`,display:Vt?"none":"flex",flexDirection:"column",overflow:"hidden",background:n.cellBg},children:[i.jsxs("div",{style:{padding:"12px 14px",display:"grid",gap:10,borderBottom:`1px solid ${n.headerBorder}`},children:[i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:12,fontWeight:700,color:n.textPrimary,fontFamily:n.font},children:"Preview & Governance"}),i.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:"Validate references, inspect results, tune visualization, and save companion metadata."})]}),i.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[i.jsx(ft,{active:s==="results",onClick:()=>a("results"),label:"Results"}),i.jsx(ft,{active:s==="visualization",onClick:()=>a("visualization"),label:"Visualization"}),i.jsx(ft,{active:s==="lineage",onClick:()=>a("lineage"),label:"Lineage"}),i.jsx(ft,{active:s==="validate",onClick:()=>a("validate"),label:"Validate"}),i.jsx(ft,{active:s==="tests",onClick:()=>a("tests"),label:"Tests"}),i.jsx(ft,{active:s==="history",onClick:()=>{a("history"),!Q&&e.activeBlockPath&&Z.getBlockHistory(e.activeBlockPath).then(j=>{X(j.entries),ae(!0)})},label:"History"}),i.jsx(ft,{active:s==="save",onClick:()=>a("save"),label:"Save"}),i.jsx("div",{style:{flex:1}}),i.jsx("button",{onClick:()=>Bo(!0),style:{background:n.btnBg,border:`1px solid ${n.btnBorder}`,borderRadius:6,color:n.textSecondary,cursor:"pointer",fontSize:12,fontFamily:n.font,padding:"6px 10px"},children:"Hide Pane"})]})]}),i.jsxs("div",{style:{flex:1,overflow:"auto"},children:[s==="results"&&(e.blockStudioPreview?i.jsxs("div",{style:{display:"grid",gap:12,padding:12},children:[i.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.fontMono},children:e.blockStudioPreview.sql}),Sa==="table"?i.jsx(mo,{result:e.blockStudioPreview.result,themeMode:e.themeMode}):i.jsx(_0,{result:e.blockStudioPreview.result,chartConfig:e.blockStudioPreview.chartConfig,themeMode:e.themeMode})]}):i.jsx(vt,{message:"Run the block to preview results and visualization."})),s==="visualization"&&i.jsx(_Y,{chartConfig:Ta,onChange:j=>Ye(Yx(e.blockStudioDraft,j)),t:n}),s==="lineage"&&i.jsx(xY,{blockName:$t,loading:de,detail:me,graph:ve,paths:Tn,onSelectNode:j=>{t({type:"SET_LINEAGE_FOCUS",nodeId:j}),e.lineageFullscreen||t({type:"TOGGLE_LINEAGE_FULLSCREEN"})},onOpenFull:()=>{$t&&(t({type:"SET_LINEAGE_FOCUS",nodeId:`block:${$t}`}),e.lineageFullscreen||t({type:"TOGGLE_LINEAGE_FULLSCREEN"}))},t:n}),s==="tests"&&i.jsx(PY,{source:e.blockStudioDraft,blockPath:e.activeBlockPath,testResults:ne,running:Y,onRunTests:async()=>{if(e.activeBlockPath){se(!0);try{const j=await Z.runBlockTests(e.blockStudioDraft,e.activeBlockPath);re(j.assertions??[])}catch{re([])}finally{se(!1)}}},t:n}),s==="validate"&&i.jsx(LY,{diagnostics:((yr=e.blockStudioValidation)==null?void 0:yr.diagnostics)??[],t:n}),s==="history"&&i.jsx(bY,{entries:q,t:n}),s==="save"&&i.jsxs("div",{style:{display:"grid",gap:12},children:[e.activeBlockPath&&e.blockStudioMetadata&&i.jsx("div",{style:{padding:"12px 12px 0"},children:i.jsx(MY,{currentStatus:e.blockStudioMetadata.reviewStatus??"draft",blockPath:e.activeBlockPath,onStatusChanged:j=>{e.blockStudioMetadata&&t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,reviewStatus:j}})},t:n})}),i.jsx(yY,{metadata:e.blockStudioMetadata,draftMetadata:Hn,onChange:j=>{if(!e.blockStudioMetadata)return;t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,...j}});let Ee=e.blockStudioDraft;typeof j.name=="string"&&(Ee=yR(Ee,j.name)),typeof j.domain=="string"&&(Ee=Ua(Ee,"domain",j.domain)),typeof j.owner=="string"&&(Ee=Ua(Ee,"owner",j.owner)),typeof j.description=="string"&&(Ee=Ua(Ee,"description",j.description)),j.tags&&(Ee=jx(Ee,j.tags)),Ye(Ee)},onSave:()=>void Ho(),saving:G,t:n})]})]})]}),Vt&&i.jsx("div",{style:{position:"absolute",right:16,bottom:16},children:i.jsx("button",{onClick:()=>Bo(!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"})})]})}function ft({active:e,onClick:t,label:n,busy:r}){const{state:o}=Te(),s=oe[o.themeMode];return i.jsx("button",{onClick:t,style:{background:e?`${s.accent}18`:s.btnBg,border:`1px solid ${e?s.accent:s.btnBorder}`,borderRadius:6,color:e?s.accent:s.textSecondary,cursor:"pointer",fontSize:11,fontFamily:s.font,padding:"6px 10px",opacity:r?.7:1},children:r?`${n}…`:n})}function Ls(e){return i.jsx(ft,{active:!1,...e})}function or({label:e,value:t,t:n}){return i.jsxs("div",{style:{background:n.cellBg,border:`1px solid ${n.headerBorder}`,borderRadius:10,padding:"10px 12px"},children:[i.jsx("div",{style:{fontSize:10,fontWeight:700,color:n.textMuted,fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.05em"},children:e}),i.jsx("div",{style:{fontSize:20,fontWeight:700,color:n.textPrimary,fontFamily:n.font,marginTop:4},children:t})]})}function LY({diagnostics:e,t}){return e.length===0?i.jsx(vt,{message:"No validation messages."}):i.jsx("div",{style:{display:"grid",gap:8,padding:12},children:e.map((n,r)=>i.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:[i.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}),i.jsx("div",{style:{fontSize:12,color:t.textPrimary,marginTop:4},children:n.message})]},`${n.code??n.message}-${r}`))})}function _Y({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 i.jsxs("div",{style:{display:"grid",gap:10,padding:12},children:[i.jsxs("select",{value:e.chart??"table",onChange:o=>t({...e,chart:o.target.value}),style:r,children:[i.jsx("option",{value:"table",children:"Table"}),Gi.map(o=>i.jsx("option",{value:o.value,children:o.label},o.value))]}),i.jsx("input",{value:e.x??"",onChange:o=>t({...e,x:o.target.value}),placeholder:"x binding",style:r}),i.jsx("input",{value:e.y??"",onChange:o=>t({...e,y:o.target.value}),placeholder:"y binding",style:r}),i.jsx("input",{value:e.color??"",onChange:o=>t({...e,color:o.target.value}),placeholder:"color binding",style:r}),i.jsx("input",{value:e.title??"",onChange:o=>t({...e,title:o.target.value}),placeholder:"title",style:r})]})}function xY({blockName:e,loading:t,detail:n,graph:r,paths:o,onSelectNode:s,onOpenFull:a,t:l}){const[c,E]=f.useState(!1);if(!e)return i.jsx(vt,{message:"Lineage will appear once the block has a name."});if(t)return i.jsx(vt,{message:"Loading block lineage…"});if(!(n!=null&&n.node))return i.jsxs("div",{style:{padding:12,display:"grid",gap:12},children:[i.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."}),i.jsx("div",{children:i.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 d=`block:${e}`;return i.jsxs("div",{style:{padding:12,display:"grid",gap:12,overflowY:"auto"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:12,fontWeight:700,color:l.textPrimary,fontFamily:l.font},children:n.node.name}),i.jsx("div",{style:{fontSize:11,color:l.textMuted,fontFamily:l.font},children:n.node.domain?`Domain: ${n.node.domain}`:"Block lineage focus"})]}),i.jsx("div",{style:{flex:1}}),i.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"})]}),(o==null?void 0:o.layerSummary)&&i.jsx(SD,{layerSummary:o.layerSummary,t:l}),r&&r.nodes.length>0&&i.jsx(Rh,{nodes:r.nodes,edges:r.edges,focalNodeId:d,height:360,onNodeClick:s,layoutMode:"flow"}),o&&(o.upstreamPaths.length>0||o.downstreamPaths.length>0)&&i.jsxs("div",{style:{display:"grid",gap:10},children:[o.upstreamPaths.length>0&&i.jsx(zd,{title:"Source to Block",paths:o.upstreamPaths,onNodeClick:s,focalNodeId:d,t:l}),o.downstreamPaths.length>0&&i.jsx(zd,{title:"Block to Consumption",paths:o.downstreamPaths,onNodeClick:s,focalNodeId:d,t:l})]}),i.jsxs("button",{onClick:()=>E(u=>!u),style:{background:"none",border:`1px solid ${l.cellBorder}`,borderRadius:6,padding:"6px 10px",color:l.textMuted,cursor:"pointer",fontSize:11,fontFamily:l.font,textAlign:"left"},children:[c?"▾":"▸"," Upstream / Downstream Details"]}),c&&i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, minmax(0, 1fr))",gap:12},children:[i.jsx(nS,{title:"Upstream",entries:n.incoming,emptyMessage:"No upstream dependencies yet.",onSelectNode:s,t:l}),i.jsx(nS,{title:"Downstream",entries:n.outgoing,emptyMessage:"No downstream dependencies yet.",onSelectNode:s,t:l})]})]})}function nS({title:e,entries:t,emptyMessage:n,onSelectNode:r,t:o}){const s=t.filter(a=>a.node);return i.jsxs("div",{style:{border:`1px solid ${o.cellBorder}`,borderRadius:10,overflow:"hidden",background:o.inputBg},children:[i.jsxs("div",{style:{padding:"10px 12px",borderBottom:`1px solid ${o.cellBorder}`,fontSize:11,fontWeight:700,color:o.textMuted,fontFamily:o.font,textTransform:"uppercase",letterSpacing:"0.04em"},children:[e," (",s.length,")"]}),s.length===0?i.jsx("div",{style:{padding:12,fontSize:12,color:o.textMuted,fontFamily:o.font},children:n}):i.jsx("div",{style:{display:"grid"},children:s.map(a=>i.jsxs("button",{onClick:()=>r(a.node.id),style:{background:"transparent",border:"none",borderTop:`1px solid ${o.cellBorder}`,padding:"10px 12px",textAlign:"left",cursor:"pointer"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{style:{fontSize:10,fontWeight:700,color:o.accent,fontFamily:o.font,textTransform:"uppercase"},children:a.node.type.replace("_"," ")}),i.jsx("span",{style:{fontSize:12,color:o.textPrimary,fontFamily:o.font,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.node.name})]}),i.jsxs("div",{style:{marginTop:3,fontSize:11,color:o.textMuted,fontFamily:o.font},children:["via ",a.edge.type,a.node.domain?` · ${a.node.domain}`:""]})]},`${a.node.id}-${a.edge.type}`))})]})}function yY({metadata:e,draftMetadata:t,onChange:n,onSave:r,saving:o,t:s}){const a={width:"100%",background:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:6,color:s.textPrimary,fontSize:12,fontFamily:s.font,padding:"8px 10px",outline:"none"},l={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 i.jsxs("div",{style:{display:"grid",gap:10,padding:12},children:[i.jsx("input",{value:l.name,onChange:c=>n({name:c.target.value}),placeholder:"Block name",style:a}),i.jsx("input",{value:l.domain,onChange:c=>n({domain:c.target.value}),placeholder:"Domain",style:a}),i.jsx("input",{value:l.owner,onChange:c=>n({owner:c.target.value}),placeholder:"Owner",style:a}),i.jsx("input",{value:l.description,onChange:c=>n({description:c.target.value}),placeholder:"Description",style:a}),i.jsx("input",{value:l.tags.join(", "),onChange:c=>n({tags:c.target.value.split(",").map(E=>E.trim()).filter(Boolean)}),placeholder:"Tags",style:a}),i.jsx("button",{onClick:r,style:{background:s.accent,border:`1px solid ${s.accent}`,borderRadius:6,color:"#fff",cursor:"pointer",fontSize:12,fontFamily:s.font,padding:"8px 12px"},children:o?"Saving…":"Save Block"})]})}function vt({message:e}){const{state:t}=Te(),n=oe[t.themeMode];return i.jsx("div",{style:{padding:16,fontSize:12,color:n.textMuted},children:e})}const rS={draft:"#8b949e",review:"#d29922",certified:"#3fb950",deprecated:"#f85149"},DY={draft:["review"],review:["certified","draft"],certified:["deprecated"],deprecated:["draft"]};function MY({currentStatus:e,blockPath:t,onStatusChanged:n,t:r}){const[o,s]=f.useState(!1),a=DY[e]??[],l=async c=>{if(t){s(!0);try{const E=await Z.updateBlockStatus(t,c);E.ok&&E.status&&n(E.status)}finally{s(!1)}}};return i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 12px",background:r.pillBg,borderRadius:8},children:[i.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font},children:"Status:"}),i.jsx("span",{style:{fontSize:11,fontWeight:600,color:rS[e]??r.textMuted,background:`${rS[e]??r.textMuted}18`,padding:"2px 8px",borderRadius:4,textTransform:"uppercase",letterSpacing:"0.04em",fontFamily:r.font},children:e}),i.jsx("span",{style:{flex:1}}),a.map(c=>i.jsx("button",{onClick:()=>void l(c),disabled:o,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:o?"not-allowed":"pointer",fontSize:10,fontWeight:600,fontFamily:r.font,padding:"3px 10px",textTransform:"capitalize",opacity:o?.5:1},children:o?"...":c==="certified"?"Certify":c==="deprecated"?"Deprecate":`Move to ${c}`},c))]})}function PY({source:e,blockPath:t,testResults:n,running:r,onRunTests:o,t:s}){const l=[...e.matchAll(/assert\s+(\w+)\s*(>=?|<=?|==|!=|IN)\s*(\S+)/g)].map(c=>({field:c[1],operator:c[2],expected:c[3]}));return i.jsxs("div",{style:{padding:12,display:"grid",gap:10},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{style:{fontSize:12,fontWeight:600,color:s.textPrimary,fontFamily:s.font},children:"Test Assertions"}),i.jsx("span",{style:{flex:1}}),i.jsx("button",{onClick:o,disabled:r||!t,style:{background:s.accent,border:"none",borderRadius:6,color:"#fff",cursor:r||!t?"not-allowed":"pointer",fontSize:11,fontWeight:600,fontFamily:s.font,padding:"5px 14px",opacity:r||!t?.5:1},children:r?"Running...":"Run Tests"})]}),l.length===0&&i.jsxs("div",{style:{fontSize:12,color:s.textMuted,fontFamily:s.font,lineHeight:1.5},children:["No test assertions found. Add assertions in your block:",i.jsx("pre",{style:{margin:"8px 0 0",padding:"8px 10px",background:s.editorBg,border:`1px solid ${s.cellBorder}`,borderRadius:6,fontSize:10,fontFamily:s.fontMono,color:s.textSecondary},children:`tests {
|
|
727
|
-
assert row_count > 0
|
|
728
|
-
assert max_value <= 1000000
|
|
729
|
-
}`})]}),l.map((c,E)=>{const d=n==null?void 0:n[E],u=d==null?void 0:d.passed;return i.jsxs("div",{style:{padding:"8px 12px",borderRadius:8,border:`1px solid ${d?u?"#3fb95040":"#f8514940":s.cellBorder}`,background:d?u?"#3fb95008":"#f8514908":"transparent",display:"flex",alignItems:"center",gap:8},children:[d&&i.jsx("span",{style:{fontSize:14,color:u?"#3fb950":"#f85149",fontWeight:700},children:u?"✓":"✗"}),i.jsxs("div",{style:{flex:1},children:[i.jsxs("div",{style:{fontSize:12,color:s.textPrimary,fontFamily:s.fontMono},children:[c.field," ",c.operator," ",c.expected]}),d&&!u&&d.actual&&i.jsxs("div",{style:{fontSize:11,color:"#f85149",fontFamily:s.font,marginTop:2},children:["Actual: ",d.actual]})]})]},E)}),n&&n.length>0&&i.jsxs("div",{style:{padding:"8px 12px",background:s.pillBg,borderRadius:8,fontSize:12,fontFamily:s.font,color:s.textSecondary},children:[n.filter(c=>c.passed).length,"/",n.length," passed"]})]})}function bY({entries:e,t}){return e.length===0?i.jsx(vt,{message:"No version history available. Commit changes to build history."}):i.jsxs("div",{style:{padding:12,display:"grid",gap:8},children:[i.jsx("div",{style:{fontSize:12,fontWeight:600,color:t.textPrimary,fontFamily:t.font},children:"Version History"}),e.map(n=>i.jsxs("div",{style:{padding:"8px 12px",border:`1px solid ${t.cellBorder}`,borderRadius:8,background:t.inputBg},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:[i.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)}),i.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.font},children:new Date(n.date).toLocaleDateString()}),i.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.font,marginLeft:"auto"},children:n.author})]}),i.jsx("div",{style:{fontSize:12,color:t.textPrimary,fontFamily:t.font},children:n.message})]},n.hash))]})}function vY({tree:e,totalTree:t,expanded:n,setExpanded:r,onEnsureColumns:o,onInsert:s,query:a,onQueryChange:l,stats:c,connectionName:E,loadingNodes:d,onRefresh:u,t:T}){const S={width:"100%",background:T.inputBg,border:`1px solid ${T.inputBorder}`,borderRadius:8,color:T.textPrimary,fontSize:12,fontFamily:T.font,padding:"8px 10px",outline:"none",boxSizing:"border-box"},h=(A,R=0)=>{var g,y,_;const p=A.kind!=="column",N=n[A.id]??R<1,I=d.has(A.id),O=A.kind==="schema"?(g=A.children)==null?void 0:g.length:A.kind==="table"?(y=A.children)==null?void 0:y.length:void 0,m=A.kind==="column"?A.type:A.kind,C=A.kind==="column"&&A.type?kl(A.type,T.accent):void 0;return i.jsxs("div",{children:[i.jsx(Tc,{label:I?`${A.label} …`:A.label,depth:R,count:O,expanded:p?N:void 0,onToggle:p?()=>{r(P=>({...P,[A.id]:!N})),N||o(A)}:void 0,badge:m,badgeColor:C,onClick:()=>{if(A.kind==="table"&&A.path&&s(A.path),A.kind==="column"){const P=A.path?A.path.split(".").pop():"";s(P?`${P}.${A.label}`:A.label)}},onDoubleClick:()=>{A.kind==="table"&&A.path&&s(`SELECT *
|
|
730
|
-
FROM ${A.path}
|
|
731
|
-
LIMIT 100`)},t:T}),p&&N&&((_=A.children)==null?void 0:_.map(P=>h(P,R+1)))]},A.id)};return i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:{padding:12,display:"grid",gap:12,borderBottom:`1px solid ${T.headerBorder}`,background:`${T.cellBg}66`},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:12,fontWeight:700,color:T.textPrimary,fontFamily:T.font},children:"Database Browser"}),i.jsx("div",{style:{fontSize:11,color:T.textMuted,fontFamily:T.font},children:"Browse the active connection, inspect schemas and columns, then insert tables or starter queries into the block."})]}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsx("button",{onClick:u,title:"Refresh schema",style:{background:"none",border:"none",cursor:"pointer",padding:4,borderRadius:6,color:T.textMuted,fontSize:14,lineHeight:1},children:"↻"}),i.jsx("span",{style:{fontSize:10,fontWeight:700,color:T.accent,background:`${T.accent}18`,borderRadius:999,padding:"5px 9px",textTransform:"uppercase",letterSpacing:"0.04em"},children:E})]})]}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:8},children:[i.jsx(or,{label:"Schemas",value:c.schemas,t:T}),i.jsx(or,{label:"Tables",value:c.tables,t:T}),i.jsx(or,{label:"Columns",value:c.columns,t:T})]}),i.jsx("input",{value:a,onChange:A=>l(A.target.value),placeholder:"Search schemas, tables, columns...",style:S})]}),i.jsx("div",{style:{flex:1,overflowY:"auto",padding:e.length>0?"6px 0 0":0},children:t.length===0?i.jsx(vt,{message:"No schemas were found for the active connection yet."}):e.length===0?i.jsx(vt,{message:"No database objects match the current search."}):e.map(A=>h(A))})]})}function UY({row:e,selectedId:t,setSelectedId:n,expanded:r,setExpanded:o,onInsert:s,favorites:a,dispatch:l,t:c}){var h;const{node:E,depth:d,hasChildren:u,isExpanded:T}=e,S=E.id.split(":").slice(1).join(":");return u?i.jsx(Tc,{label:E.label,depth:d,count:(h=E.children)==null?void 0:h.length,expanded:T,onToggle:()=>o(A=>({...A,[E.id]:!T})),onClick:()=>n(E.id),selected:t===E.id,t:c}):i.jsx(Tc,{label:E.label,depth:d,badge:E.kind,selected:t===E.id,onClick:()=>n(E.id),onDoubleClick:()=>{Z.getSemanticObject(E.id).then(s).catch(()=>{})},onFavoriteToggle:E.kind==="metric"||E.kind==="dimension"?()=>void Z.toggleFavorite(S).then(A=>l({type:"SET_SEMANTIC_FAVORITES",favorites:A})):void 0,favorite:E.kind==="metric"||E.kind==="dimension"?a.has(S):void 0,t:c})}function _s(e,t){const n=e.match(/query\s*=\s*"""([\s\S]*?)"""/i);return n?e.replace(n[0],`query = """${n[1].trimEnd()}
|
|
732
|
-
${t}
|
|
733
|
-
"""`):/^\s*block\s+"/i.test(e.trim())?e.replace(/\n\}\s*$/,`
|
|
734
|
-
|
|
735
|
-
query = """
|
|
736
|
-
${t}
|
|
737
|
-
"""
|
|
738
|
-
}
|
|
739
|
-
`):`${e.trimEnd()}
|
|
740
|
-
${t}
|
|
741
|
-
`}function wY(e){return`block "${e}" {
|
|
742
|
-
domain = "uncategorized"
|
|
743
|
-
type = "semantic"
|
|
744
|
-
description = ""
|
|
745
|
-
owner = ""
|
|
746
|
-
tags = []
|
|
747
|
-
metric = "total_revenue"
|
|
748
|
-
|
|
749
|
-
visualization {
|
|
750
|
-
chart = "table"
|
|
751
|
-
}
|
|
752
|
-
}
|
|
753
|
-
`}function BY(e){return`block "${e}" {
|
|
754
|
-
domain = "uncategorized"
|
|
755
|
-
type = "custom"
|
|
756
|
-
description = ""
|
|
757
|
-
owner = ""
|
|
758
|
-
tags = []
|
|
759
|
-
|
|
760
|
-
query = """
|
|
761
|
-
SELECT 1 AS value
|
|
762
|
-
"""
|
|
763
|
-
|
|
764
|
-
visualization {
|
|
765
|
-
chart = "table"
|
|
766
|
-
}
|
|
767
|
-
}
|
|
768
|
-
`}function Dl(e,t){if(!e)return[];const n=new Set,r=o=>{var a;const s=(a=o.meta)==null?void 0:a[t];typeof s=="string"&&s.trim()&&n.add(s.trim());for(const l of o.children??[])r(l)};return r(e),Array.from(n).sort((o,s)=>o.localeCompare(s))}function Uh(e,t){var T,S,h,A,R;const n=t.query.trim().toLowerCase(),r=Object.values(e.meta??{}).filter(p=>p!=null).map(p=>String(p).toLowerCase()),o=!n||e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)||r.some(p=>p.includes(n)),s=!t.type||e.kind===t.type||e.kind==="provider"||e.kind==="domain"||e.kind==="group",a=!t.domain||e.kind==="provider"||e.kind==="group"||((T=e.meta)==null?void 0:T.domain)===t.domain||e.kind==="domain"&&e.label===t.domain,l=!t.provider||((S=e.meta)==null?void 0:S.provider)===t.provider||e.id===`provider:${t.provider}`,c=!t.cube||((h=e.meta)==null?void 0:h.cube)===t.cube,E=!t.owner||((A=e.meta)==null?void 0:A.owner)===t.owner,d=!t.tag||String(((R=e.meta)==null?void 0:R.tags)??"").split(",").filter(Boolean).includes(t.tag),u=(e.children??[]).map(p=>Uh(p,t)).filter(p=>!!p);return u.length>0?{...e,children:u,count:e.kind==="provider"||e.kind==="domain"||e.kind==="group"?u.length:e.count}:o&&s&&a&&l&&c&&E&&d?{...e,children:[]}:null}function wh(e,t,n=0){const r=[];for(const o of e){const s=!!(o.children&&o.children.length>0),a=t[o.id]??n<3;r.push({node:o,depth:n,hasChildren:s,isExpanded:a}),s&&a&&r.push(...wh(o.children??[],t,n+1))}return r}function Bh(e,t,n){return e.map(r=>r.id===t?n:r.children?{...r,children:Bh(r.children,t,n)}:r)}function FY(e,t){const n=t.trim().toLowerCase();if(!n)return e;const r=o=>{const s=[o.label,o.path,o.type].filter(l=>!!l).some(l=>l.toLowerCase().includes(n)),a=(o.children??[]).map(l=>r(l)).filter(l=>!!l);return s||a.length>0?{...o,children:a}:null};return e.map(o=>r(o)).filter(o=>!!o)}function GY(e){let t=0,n=0,r=0;const o=s=>{s.kind==="schema"&&(t+=1),s.kind==="table"&&(n+=1),s.kind==="column"&&(r+=1);for(const a of s.children??[])o(a)};for(const s of e)o(s);return{schemas:t,tables:n,columns:r}}function HY(e){return!!(e&&e.children&&e.children.length>0)}function kY(e){if(e.metrics.length===0&&e.dimensions.length===0&&e.hierarchies.length===0)return null;const t=e.provider??"dql",n=new Map,r=(s,a)=>{const l=n.get(s)??[];l.push(a),n.set(s,l)};for(const s of e.metrics){const a=s.domain||"uncategorized";r(a,{id:`metric:${s.name}`,label:s.label||s.name,kind:"metric",meta:{provider:t,domain:a,cube:s.table,owner:s.owner??"",tags:s.tags.join(",")}})}for(const s of e.dimensions){const a=s.domain||"uncategorized";r(a,{id:`dimension:${s.name}`,label:s.label||s.name,kind:"dimension",meta:{provider:t,domain:a,cube:s.table,owner:s.owner??"",tags:s.tags.join(",")}})}for(const s of e.hierarchies){const a=s.domain||"uncategorized";r(a,{id:`hierarchy:${s.name}`,label:s.label||s.name,kind:"hierarchy",meta:{provider:t,domain:a}})}const o=Array.from(n.entries()).sort((s,a)=>s[0].localeCompare(a[0])).map(([s,a])=>{const l=a.filter(u=>u.kind==="metric"),c=a.filter(u=>u.kind==="dimension"),E=a.filter(u=>u.kind==="hierarchy"),d=[];return l.length>0&&d.push({id:`group:${s}:metrics`,label:"Metrics",kind:"group",count:l.length,meta:{provider:t,domain:s},children:l.sort((u,T)=>u.label.localeCompare(T.label))}),c.length>0&&d.push({id:`group:${s}:dimensions`,label:"Dimensions",kind:"group",count:c.length,meta:{provider:t,domain:s},children:c.sort((u,T)=>u.label.localeCompare(T.label))}),E.length>0&&d.push({id:`group:${s}:hierarchies`,label:"Hierarchies",kind:"group",count:E.length,meta:{provider:t,domain:s},children:E.sort((u,T)=>u.label.localeCompare(T.label))}),{id:`domain:${t}:${s}`,label:s,kind:"domain",count:d.length,meta:{provider:t,domain:s},children:d}});return{id:"root:semantic",label:"Semantic Layer",kind:"group",children:[{id:`provider:${t}`,label:t.toUpperCase(),kind:"provider",count:o.length,meta:{provider:t},children:o}]}}const Fh={source_table:"TABLE",dbt_model:"DBT",dbt_source:"SOURCE",block:"BLOCK",metric:"METRIC",dimension:"DIM",domain:"DOMAIN",chart:"CHART",dashboard:"NOTEBOOK"};function jY(e,t,n="flow",r="LR"){var a;const o=new Ai.graphlib.Graph().setDefaultEdgeLabel(()=>({})),s=r==="LR";o.setGraph({rankdir:r,ranksep:n==="layered"?120:s?80:60,nodesep:s?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 E=qs.indexOf(l.data.layer);E>=0&&(c.rank=E)}o.setNode(l.id,c)}for(const l of t)o.setEdge(l.source,l.target);return Ai.layout(o),e.map(l=>{const c=o.node(l.id);return{...l,position:{x:c.x-95,y:c.y-29},data:{...l.data,direction:r}}})}function YY({data:e,selected:t}){const n=e.nodeType,r=we[n]??"var(--color-text-tertiary)",o=Fh[n]??n.toUpperCase(),s=e.direction??"LR",a=s==="LR"?te.Left:te.Top,l=s==="LR"?te.Right:te.Bottom;return i.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:[i.jsx(an,{type:"target",position:a,style:{width:7,height:7,background:r,border:"none"}}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[i.jsx("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.04em",color:"var(--color-bg-primary)",background:r,borderRadius:4,padding:"2px 6px"},children:o}),e.domain&&i.jsx("span",{style:{color:"var(--color-text-tertiary)",fontSize:10},children:e.domain})]}),i.jsx("div",{style:{color:"var(--color-text-primary)",fontSize:11,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.label,children:e.label}),i.jsx("div",{style:{color:"var(--color-text-tertiary)",fontSize:10,marginTop:3},children:Bi[n]??n}),i.jsx(an,{type:"source",position:l,style:{width:7,height:7,background:r,border:"none"}})]})}const WY={dagNode:YY};function Kn({label:e,active:t,color:n,onClick:r}){return i.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 VY(){const{state:e,dispatch:t}=Te(),n=oe[e.themeMode],[r,o]=f.useState(!0),[s,a]=f.useState({nodes:[],edges:[]}),[l,c]=f.useState({nodes:[],edges:[]}),[E,d]=f.useState(null),[u,T]=f.useState(null),[S,h]=f.useState(""),[A,R]=f.useState([]),[p,N]=f.useState({source_table:!0,dbt_model:!0,dbt_source:!0,block:!0,dashboard:!0,domain:!0}),[I,O]=f.useState("flow"),[m,C]=f.useState("LR"),[g,y,_]=Fp([]),[P,D,b]=Gp([]),F=f.useCallback(async()=>{o(!0);const L=await Z.fetchLineage(),U={nodes:L.nodes??[],edges:L.edges??[]};a(U),c(U),o(!1)},[]);f.useEffect(()=>{F()},[F]),f.useEffect(()=>{let L=!1;if(S.trim().length<2){R([]);return}return Z.searchLineage(S.trim()).then(U=>{L||R(U.matches??[])}),()=>{L=!0}},[S]);const x=f.useMemo(()=>{const L=new Set(l.nodes.filter(U=>p[U.type]??!1).map(U=>U.id));return{nodes:l.nodes.filter(U=>L.has(U.id)),edges:l.edges.filter(U=>L.has(U.source)&&L.has(U.target))}},[l,p]);f.useEffect(()=>{const L=x.nodes.map(G=>({id:G.id,type:"dagNode",position:{x:0,y:0},data:{label:G.name,nodeType:G.type,domain:G.domain,layer:Vc(G)}})),U=x.edges.map((G,k)=>({id:`edge-${k}-${G.source}-${G.target}-${G.type}`,source:G.source,target:G.target,style:{stroke:Yr[G.type]??"var(--color-text-tertiary)",strokeWidth:1.6},markerEnd:{type:ur.ArrowClosed,color:Yr[G.type]??"var(--color-text-tertiary)",width:12,height:12}}));y(jY(L,U,I,m)),D(U)},[x,I,m,D,y]);const w=f.useCallback(async L=>{const U=await Z.queryLineage({focus:L});c(U.graph??{nodes:[],edges:[]}),d(U.focalNode??null),T(U.focalNode??null),t({type:"SET_LINEAGE_FOCUS",nodeId:L}),h(""),R([])},[t]);f.useEffect(()=>{e.lineageFocusNodeId&&w(e.lineageFocusNodeId)},[w,e.lineageFocusNodeId]);const M=f.useCallback(()=>{c(s),d(null),T(null),t({type:"SET_LINEAGE_FOCUS",nodeId:null})},[t,s]),B=f.useCallback(async(L,U)=>{await w(U.id)},[w]),v=f.useMemo(()=>{if(!u)return null;const L=l.edges.filter(G=>G.target===u.id).length,U=l.edges.filter(G=>G.source===u.id).length;return{incoming:L,outgoing:U}},[l.edges,u]);return r?i.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"Loading lineage graph..."}):s.nodes.length===0?i.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"No lineage graph available yet."}):i.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",background:"var(--color-bg-primary)"},children:[i.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`,background:n.sidebarBg},children:[i.jsxs("div",{style:{display:"flex",gap:6,marginBottom:8,flexWrap:"wrap",alignItems:"center"},children:[i.jsxs("div",{style:{display:"flex",borderRadius:6,border:`1px solid ${n.headerBorder}`,overflow:"hidden"},children:[i.jsx("button",{onClick:()=>O("flow"),style:{padding:"4px 8px",fontSize:10,fontWeight:700,border:"none",cursor:"pointer",background:I==="flow"?"var(--color-bg-tertiary)":"transparent",color:I==="flow"?"var(--color-text-primary)":"var(--color-text-tertiary)"},children:"Flow"}),i.jsx("button",{onClick:()=>O("layered"),style:{padding:"4px 8px",fontSize:10,fontWeight:700,border:"none",borderLeft:`1px solid ${n.headerBorder}`,cursor:"pointer",background:I==="layered"?"var(--color-bg-tertiary)":"transparent",color:I==="layered"?"var(--color-text-primary)":"var(--color-text-tertiary)"},children:"Layered"})]}),i.jsxs("div",{style:{display:"flex",borderRadius:6,border:`1px solid ${n.headerBorder}`,overflow:"hidden",marginRight:4},children:[i.jsxs("button",{title:"Horizontal layout (left → right)",onClick:()=>C("LR"),style:{padding:"4px 8px",fontSize:10,fontWeight:700,border:"none",cursor:"pointer",background:m==="LR"?"var(--color-bg-tertiary)":"transparent",color:m==="LR"?"var(--color-text-primary)":"var(--color-text-tertiary)",display:"flex",alignItems:"center",gap:3},children:[i.jsxs("svg",{width:"14",height:"10",viewBox:"0 0 14 10",fill:"none",children:[i.jsx("rect",{x:"0",y:"2",width:"4",height:"6",rx:"1",fill:"currentColor",opacity:"0.7"}),i.jsx("line",{x1:"4",y1:"5",x2:"10",y2:"5",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M9 3l2 2-2 2",stroke:"currentColor",strokeWidth:"1.2",fill:"none"}),i.jsx("rect",{x:"10",y:"2",width:"4",height:"6",rx:"1",fill:"currentColor"})]}),"LR"]}),i.jsxs("button",{title:"Vertical layout (top → bottom)",onClick:()=>C("TB"),style:{padding:"4px 8px",fontSize:10,fontWeight:700,border:"none",borderLeft:`1px solid ${n.headerBorder}`,cursor:"pointer",background:m==="TB"?"var(--color-bg-tertiary)":"transparent",color:m==="TB"?"var(--color-text-primary)":"var(--color-text-tertiary)",display:"flex",alignItems:"center",gap:3},children:[i.jsxs("svg",{width:"10",height:"14",viewBox:"0 0 10 14",fill:"none",children:[i.jsx("rect",{x:"2",y:"0",width:"6",height:"4",rx:"1",fill:"currentColor",opacity:"0.7"}),i.jsx("line",{x1:"5",y1:"4",x2:"5",y2:"10",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M3 9l2 2 2-2",stroke:"currentColor",strokeWidth:"1.2",fill:"none"}),i.jsx("rect",{x:"2",y:"10",width:"6",height:"4",rx:"1",fill:"currentColor"})]}),"TB"]})]}),i.jsx(Kn,{label:"Tables",active:p.source_table,color:we.source_table,onClick:()=>N(L=>({...L,source_table:!L.source_table}))}),i.jsx(Kn,{label:"dbt Models",active:p.dbt_model,color:we.dbt_model,onClick:()=>N(L=>({...L,dbt_model:!L.dbt_model}))}),i.jsx(Kn,{label:"dbt Sources",active:p.dbt_source,color:we.dbt_source,onClick:()=>N(L=>({...L,dbt_source:!L.dbt_source}))}),i.jsx(Kn,{label:"DQL Blocks",active:p.block,color:we.block,onClick:()=>N(L=>({...L,block:!L.block}))}),i.jsx(Kn,{label:"Notebooks",active:p.dashboard,color:we.dashboard,onClick:()=>N(L=>({...L,dashboard:!L.dashboard}))}),i.jsx(Kn,{label:"Domains",active:p.domain,color:we.domain,onClick:()=>N(L=>({...L,domain:!L.domain}))})]}),i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsx("input",{value:S,onChange:L=>h(L.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"}}),E&&i.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"})]}),i.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."}),A.length>0&&i.jsx("div",{style:{marginTop:8,border:`1px solid ${n.headerBorder}`,borderRadius:8,overflow:"hidden"},children:A.slice(0,8).map(L=>i.jsxs("button",{onClick:()=>void w(L.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:[i.jsx("span",{style:{color:we[L.node.type]??"var(--color-text-tertiary)",fontSize:10,fontWeight:700,marginRight:8},children:Fh[L.node.type]??L.node.type.toUpperCase()}),L.node.name]},L.node.id))})]}),i.jsx("div",{style:{flex:1,position:"relative"},children:i.jsxs(Bp,{nodes:g,edges:P,onNodesChange:_,onEdgesChange:b,onNodeClick:B,nodeTypes:WY,fitView:!0,fitViewOptions:{padding:.18},proOptions:{hideAttribution:!0},style:{background:"var(--color-bg-primary)"},children:[i.jsx(kp,{color:"var(--color-border-secondary)",gap:24,size:1}),i.jsx(tw,{showInteractive:!1}),i.jsx(Sw,{nodeColor:L=>{var U;return we[((U=L.data)==null?void 0:U.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)"}}),i.jsx(Ar,{position:"top-left",children:i.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:[i.jsx("div",{style:{fontWeight:700,marginBottom:4},children:E?E.name:"Full Lineage View"}),i.jsxs("div",{style:{color:"var(--color-text-tertiary)",fontSize:11},children:[l.nodes.length," node(s), ",l.edges.length," edge(s)"]}),i.jsx("div",{style:{color:"var(--color-text-tertiary)",fontSize:11,marginTop:6,lineHeight:1.5},children:E?`Focused on ${Bi[E.type]??E.type}. Upstream shows provenance from tables/dbt; downstream shows DQL and notebook consumption.`:"Full project lineage across source tables, dbt, DQL blocks, and notebooks."}),u&&v&&i.jsxs("div",{style:{marginTop:8,color:"var(--color-text-tertiary)",fontSize:11},children:[v.incoming," upstream, ",v.outgoing," downstream"]})]})}),i.jsx(Ar,{position:"bottom-left",children:i.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(Yr).map(([L,U])=>i.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[i.jsx("span",{style:{width:10,height:2,background:U,display:"inline-block"}}),ax[L]??L]},L))})})]})})]})}function $Y(){const{state:e,dispatch:t}=Te(),{executeAll:n}=Fi();f.useEffect(()=>{const r=o=>{const s=o.metaKey||o.ctrlKey;if(s&&o.key==="b"&&!o.shiftKey){o.preventDefault(),t({type:"TOGGLE_SIDEBAR"});return}if(s&&o.shiftKey&&o.key==="Enter"){o.preventDefault(),e.activeFile&&n();return}if(s&&o.key==="j"&&!o.shiftKey){o.preventDefault(),t({type:"TOGGLE_DEV_PANEL"});return}if(s&&o.key==="d"&&!o.shiftKey){o.preventDefault(),e.activeFile&&t({type:"TOGGLE_DASHBOARD_MODE"});return}if(o.key==="Escape"){if(e.dashboardMode){t({type:"TOGGLE_DASHBOARD_MODE"});return}if(e.newNotebookModalOpen){t({type:"CLOSE_NEW_NOTEBOOK_MODAL"});return}if(e.newBlockModalOpen){t({type:"CLOSE_NEW_BLOCK_MODAL"});return}}};return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[t,n,e.activeFile,e.newNotebookModalOpen,e.newBlockModalOpen,e.dashboardMode])}const XY=600;function KY(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 oS(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 zY(){var o;const{state:e}=Te(),t=f.useRef(null),n=f.useRef(""),r=f.useRef(null);f.useEffect(()=>{var l;const s=((l=e.activeFile)==null?void 0:l.path)??null;if(!s)return;if(s!==r.current){r.current=s,n.current=oS(e.cells);return}const a=oS(e.cells);return a!==n.current&&(n.current=a,t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{const c=KY(s,e.cells);Z.saveRunSnapshot(s,c).catch(()=>{})},XY)),()=>{t.current&&(clearTimeout(t.current),t.current=null)}},[e.cells,(o=e.activeFile)==null?void 0:o.path])}function JY(){const{state:e,dispatch:t}=Te(),n=oe[e.themeMode],r=f.useRef({}),[o,s]=f.useState(!1);$Y(),zY(),f.useEffect(()=>{const c=E=>{(E.metaKey||E.ctrlKey)&&E.key.toLowerCase()==="k"&&!E.shiftKey&&(E.preventDefault(),s(d=>!d)),(E.metaKey||E.ctrlKey)&&E.shiftKey&&E.key.toLowerCase()==="i"&&(E.preventDefault(),t({type:"TOGGLE_INSPECTOR"}))};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[t]);const a=f.useCallback(async c=>{try{if(c.type==="block"){const A=await Z.openBlockStudio(c.path);t({type:"OPEN_BLOCK_STUDIO",file:c,payload:A});return}const{content:E}=await Z.readNotebook(c.path),{title:d,cells:u,metadata:T}=Ux(c.path,E),S=c.path.endsWith(".dqlnb")?await Z.fetchRunSnapshot(c.path):null;let h=u;if(S!=null&&S.found&&S.snapshot){const A=new Map(S.snapshot.cells.map(R=>[R.cellId,R]));h=u.map(R=>{const p=A.get(R.id);return p?{...R,status:p.status??R.status,result:p.result??R.result,error:p.error??R.error,executionCount:p.executionCount??R.executionCount,fromSnapshot:p.result!=null}:R})}t({type:"OPEN_FILE",file:c,cells:h,title:d,metadata:T}),e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"})}catch(E){if(console.error("Failed to open file:",E),c.type==="block")try{const{content:d}=await Z.readNotebook(c.path);t({type:"OPEN_BLOCK_STUDIO",file:c,payload:{path:c.path,source:d,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(d){console.error("Failed to open block fallback:",d)}else t({type:"OPEN_FILE",file:c,cells:[$e("sql")],title:c.name})}},[t,e.sidebarPanel]);f.useCallback(c=>{const E=r.current[c];E&&E.scrollIntoView({behavior:"smooth",block:"start"})},[]);const l=f.useCallback((c,E)=>{E?r.current[c]=E:delete r.current[c]},[]);return i.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100vh",width:"100vw",background:n.appBg,fontFamily:n.font,color:n.textPrimary,overflow:"hidden"},children:[i.jsx(ry,{}),i.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[e.appMode==="studio"&&i.jsx(y_,{}),e.appMode==="studio"&&e.sidebarOpen&&i.jsx(yx,{onOpenFile:a}),i.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:e.lineageFullscreen?i.jsx(VY,{}):e.mainView==="connection"?i.jsx(sS,{title:"Connections",description:"Manage database connections, edit driver settings, and test connectivity in a full-page workspace.",children:i.jsx(mR,{})}):e.mainView==="reference"?i.jsx(sS,{title:"Quick Reference",description:"Browse the complete DQL guide, semantic workflows, and authoring patterns in a documentation-style view.",children:i.jsx(CR,{themeMode:e.themeMode})}):i.jsx(i.Fragment,{children:e.mainView==="block_studio"?i.jsx(gY,{}):i.jsxs(i.Fragment,{children:[i.jsx(TY,{onOpenFile:a,registerCellRef:l}),e.appMode==="studio"&&i.jsx(ly,{})]})})}),e.appMode==="studio"&&e.inspectorOpen&&!e.lineageFullscreen&&!e.dashboardMode&&i.jsx(d_,{})]}),e.newNotebookModalOpen&&i.jsx(hY,{onFileOpened:a}),e.newBlockModalOpen&&i.jsx(OY,{onFileOpened:a}),i.jsx(E_,{open:o,onClose:()=>s(!1)})]})}function sS({title:e,description:t,children:n}){return i.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",minWidth:0,overflow:"hidden"},children:[i.jsxs("div",{style:{padding:"18px 24px 12px",borderBottom:"1px solid rgba(127, 127, 127, 0.16)"},children:[i.jsx("div",{style:{fontSize:22,fontWeight:700},children:e}),i.jsx("div",{style:{fontSize:13,opacity:.72,marginTop:6,maxWidth:760,lineHeight:1.5},children:t})]}),i.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto"},children:n})]})}function qY(){const{state:e,dispatch:t}=Te(),n=f.useRef(null),r=f.useRef(null);f.useEffect(()=>{var o;n.current=((o=e.activeFile)==null?void 0:o.path)??null},[e.activeFile]),f.useEffect(()=>{if(typeof EventSource>"u")return;const o=()=>{const s=new EventSource(`${window.location.origin}/api/watch`);r.current=s,s.addEventListener("change",a=>{try{const l=JSON.parse(a.data);(l.type==="file-added"||l.type==="file-deleted")&&Z.listNotebooks().then(c=>{t({type:"SET_FILES",files:c})}),l.type==="file-changed"&&Z.listNotebooks().then(c=>{t({type:"SET_FILES",files:c})}),l.type==="semantic-reload"&&(t({type:"SET_SEMANTIC_LOADING",loading:!0}),Z.getSemanticLayer().then(c=>{t({type:"SET_SEMANTIC_LAYER",layer:c})}))}catch{}}),s.addEventListener("error",()=>{s.close(),setTimeout(o,5e3)})};return o(),()=>{var s;(s=r.current)==null||s.close(),r.current=null}},[t])}function QY(){const{state:e,dispatch:t}=Te(),n=oe[e.themeMode];return f.useEffect(()=>{const r="dql-global-styles";let o=document.getElementById(r);o||(o=document.createElement("style"),o.id=r,document.head.appendChild(o)),o.textContent=`
|
|
769
|
-
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
770
|
-
body {
|
|
771
|
-
font-family: var(--font-ui, ${n.font});
|
|
772
|
-
overflow: hidden;
|
|
773
|
-
background: var(--color-bg-primary);
|
|
774
|
-
color: var(--color-text-primary);
|
|
775
|
-
}
|
|
776
|
-
::-webkit-scrollbar { width: 6px; height: 6px; }
|
|
777
|
-
::-webkit-scrollbar-track { background: transparent; }
|
|
778
|
-
::-webkit-scrollbar-thumb {
|
|
779
|
-
background: var(--color-border-secondary);
|
|
780
|
-
border-radius: 3px;
|
|
781
|
-
}
|
|
782
|
-
::-webkit-scrollbar-thumb:hover {
|
|
783
|
-
background: var(--color-text-tertiary);
|
|
784
|
-
}
|
|
785
|
-
::selection {
|
|
786
|
-
background: color-mix(in srgb, var(--color-accent-blue) 25%, transparent);
|
|
787
|
-
color: var(--color-text-primary);
|
|
788
|
-
}
|
|
789
|
-
.dql-meta-pill:hover {
|
|
790
|
-
background: var(--dql-pill-hover-bg) !important;
|
|
791
|
-
border-color: var(--dql-pill-hover-border) !important;
|
|
792
|
-
}
|
|
793
|
-
`},[n]),f.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]),f.useEffect(()=>{t({type:"SET_FILES_LOADING",loading:!0}),Z.listNotebooks().then(r=>{t({type:"SET_FILES",files:r}),t({type:"SET_FILES_LOADING",loading:!1})})},[t]),f.useEffect(()=>{t({type:"SET_SCHEMA_LOADING",loading:!0}),Z.getSchema().then(r=>{t({type:"SET_SCHEMA",tables:r}),t({type:"SET_SCHEMA_LOADING",loading:!1})})},[t]),qY(),i.jsx(GI,{theme:e.themeMode,applyGlobal:!0,children:i.jsx(JO,{delayDuration:200,skipDelayDuration:400,children:i.jsx(JY,{})})})}function ZY(){return i.jsx(EL,{children:i.jsx(QY,{})})}wI.createRoot(document.getElementById("root")).render(i.jsx(ZY,{}));
|