@duckcodeailabs/dql-cli 0.8.8 → 0.8.10

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.
@@ -0,0 +1,564 @@
1
+ import{r as ho,a as FE,g as hi}from"./react-CRB3T2We.js";import{S as Co,g as GE,E as Ze,s as uS,a as Me,b as wE,c as RS,P as AS,d as IS,e as NS,F as OS,f as fS,h as HE,V as pS,D as vt,R as hS,i as CS,C as _t,j as YE,k as Ve,r as LS,l as _S,m as mS,t as gS,n as xS,o as yS,p as DS,q as MS,u as PS,v as bS,w as hr,x as US,y as vS,z as BS,A as FS,B as GS,G as wS,H as HS,I as YS,J as kS,K as VS,L as WS}from"./codemirror-CCrEt63p.js";(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 Qo={exports:{}},_n={};/**
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 ia;function jS(){if(ia)return _n;ia=1;var e=ho(),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,E,c){var d,T={},S=null,u=null;c!==void 0&&(S=""+c),E.key!==void 0&&(S=""+E.key),E.ref!==void 0&&(u=E.ref);for(d in E)r.call(E,d)&&!s.hasOwnProperty(d)&&(T[d]=E[d]);if(l&&l.defaultProps)for(d in E=l.defaultProps,E)T[d]===void 0&&(T[d]=E[d]);return{$$typeof:t,type:l,key:S,ref:u,props:T,_owner:o.current}}return _n.Fragment=n,_n.jsx=a,_n.jsxs=a,_n}var aa;function $S(){return aa||(aa=1,Qo.exports=jS()),Qo.exports}var i=$S(),Cr={},la;function XS(){if(la)return Cr;la=1;var e=FE();return Cr.createRoot=e.createRoot,Cr.hydrateRoot=e.hydrateRoot,Cr}var KS=XS(),f=ho();const En=hi(f),zS={mainView:"notebook",themeMode:"dark",sidebarPanel:"files",sidebarOpen:!0,files:[],filesLoading:!1,activeFile:null,cells:[],notebookTitle:"",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,dashboardMode:!1,activeBlockPath:null,blockStudioDraft:"",blockStudioDirty:!1,blockStudioPreview:null,blockStudioValidation:null,blockStudioMetadata:null,blockStudioCatalog:null,blockStudioCatalogLoading:!1};function JS(e,t){var n;switch(t.type){case"SET_MAIN_VIEW":return{...e,mainView:t.view,lineageFullscreen:!1};case"SET_THEME":return{...e,themeMode:t.mode};case"SET_SIDEBAR_PANEL":return{...e,sidebarPanel:t.panel,sidebarOpen:t.panel!==null&&t.panel!=="connection"&&t.panel!=="reference",lineageFullscreen:!1,mainView:t.panel==="connection"?"connection":t.panel==="reference"?"reference":((n=e.activeFile)==null?void 0:n.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,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};case"OPEN_BLOCK_STUDIO":return{...e,activeFile:t.file,cells:[],notebookTitle:t.payload.metadata.name,notebookDirty:!1,mainView:"block_studio",sidebarPanel:e.sidebarPanel==="semantic"?"files":e.sidebarPanel,dashboardMode:!1,activeBlockPath:t.payload.path,blockStudioDraft:t.payload.source,blockStudioDirty:!1,blockStudioPreview:null,blockStudioValidation:t.payload.validation,blockStudioMetadata:t.payload.metadata,lineageFullscreen:!1};case"SET_CELLS":return{...e,cells:t.cells,notebookDirty:!0};case"ADD_CELL":{if(!t.afterId)return{...e,cells:[...e.cells,t.cell],notebookDirty:!0};const r=e.cells.findIndex(s=>s.id===t.afterId);if(r===-1)return{...e,cells:[...e.cells,t.cell],notebookDirty:!0};const o=[...e.cells];return o.splice(r+1,0,t.cell),{...e,cells:o,notebookDirty:!0}}case"UPDATE_CELL":{const r=e.cells.map(s=>s.id===t.id?{...s,...t.updates}:s),o=t.updates.executionCount!==void 0?e.executionCounter+1:e.executionCounter;return{...e,cells:r,notebookDirty:!0,executionCounter:o}}case"DELETE_CELL":return{...e,cells:e.cells.filter(r=>r.id!==t.id),notebookDirty:!0};case"MOVE_CELL":{const r=e.cells.findIndex(s=>s.id===t.id);if(r===-1)return e;const o=[...e.cells];return t.direction==="up"&&r>0?[o[r-1],o[r]]=[o[r],o[r-1]]:t.direction==="down"&&r<o.length-1&&([o[r],o[r+1]]=[o[r+1],o[r]]),{...e,cells:o,notebookDirty:!0}}case"REORDER_CELL":{const{fromIndex:r,toIndex:o}=t;if(r===o||r<0||o<0||r>=e.cells.length||o>=e.cells.length)return e;const s=[...e.cells],[a]=s.splice(r,1);return s.splice(o,0,a),{...e,cells:s,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(r=>r.name===t.tableName?{...r,expanded:!r.expanded}:r)};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(r=>r.name===t.tableName?{...r,columns:t.columns}:r)};case"SET_PARAM_VALUE":return{...e,cells:e.cells.map(r=>r.id===t.id?{...r,paramValue:t.value}:r),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 r=[t.name,...e.semanticLayer.recentlyUsed.filter(o=>o!==t.name)].slice(0,12);return{...e,semanticLayer:{...e.semanticLayer,recentlyUsed:r}}}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"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};default:return e}}const kE=f.createContext(null);function qS({children:e}){const[t,n]=f.useReducer(JS,zS);return i.jsx(kE.Provider,{value:{state:t,dispatch:n},children:e})}function Se(){const e=f.useContext(kE);if(!e)throw new Error("useNotebook must be used within NotebookProvider");return e}function Rt(){return`cell_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function xe(e,t=""){const n={id:Rt(),type:e,content:t,status:"idle"};return e==="param"&&(n.content="",n.paramConfig={paramType:"text",label:"Parameter",defaultValue:"",options:[]}),n}const QS={appBg:"#0d1117",sidebarBg:"#161b22",activityBarBg:"#0d1117",headerBg:"#161b22",headerBorder:"#21262d",cellBg:"#161b22",cellBorder:"#30363d",cellBorderActive:"#388bfd",cellBorderRunning:"#56d364",textPrimary:"#e6edf3",textSecondary:"#8b949e",textMuted:"#484f58",editorBg:"#0d1117",editorBorder:"#30363d",tableBorder:"#30363d",tableHeaderBg:"#1c2128",tableRowHover:"#21262d",accent:"#388bfd",accentHover:"#58a6ff",success:"#56d364",error:"#f85149",warning:"#e3b341",btnBg:"#21262d",btnBorder:"#30363d",btnHover:"#30363d",sidebarItemHover:"#21262d",sidebarItemActive:"#1f2d3d",scrollbarThumb:"#30363d",modalBg:"#161b22",modalOverlay:"rgba(0,0,0,0.7)",inputBg:"#0d1117",inputBorder:"#30363d",pillBg:"#21262d",font:"Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontMono:"'JetBrains Mono', 'Fira Code', Consolas, monospace",fontSerif:"Georgia, 'Times New Roman', serif"},ZS={appBg:"#ffffff",sidebarBg:"#f6f8fa",activityBarBg:"#eff1f3",headerBg:"#ffffff",headerBorder:"#d0d7de",cellBg:"#ffffff",cellBorder:"#d0d7de",cellBorderActive:"#0969da",cellBorderRunning:"#1f883d",textPrimary:"#1f2328",textSecondary:"#57606a",textMuted:"#8c959f",editorBg:"#f6f8fa",editorBorder:"#d0d7de",tableBorder:"#d0d7de",tableHeaderBg:"#f6f8fa",tableRowHover:"#f6f8fa",accent:"#0969da",accentHover:"#0550ae",success:"#1f883d",error:"#cf222e",warning:"#9a6700",btnBg:"#f6f8fa",btnBorder:"#d0d7de",btnHover:"#eaeef2",sidebarItemHover:"#eaeef2",sidebarItemActive:"#dbeafe",scrollbarThumb:"#d0d7de",modalBg:"#ffffff",modalOverlay:"rgba(0,0,0,0.4)",inputBg:"#ffffff",inputBorder:"#d0d7de",pillBg:"#eaeef2",font:"Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontMono:"'JetBrains Mono', 'Fira Code', Consolas, monospace",fontSerif:"Georgia, 'Times New Roman', serif"},le={dark:QS,light:ZS};function ct({title:e,active:t,onClick:n,children:r,t:o}){const[s,a]=f.useState(!1);return i.jsx("button",{title:e,onClick:n,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{width:32,height:32,display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",borderLeft:t?`2px solid ${o.accent}`:"2px solid transparent",cursor:"pointer",color:t?o.textPrimary:s?o.textSecondary:o.textMuted,transition:"color 0.15s, border-color 0.15s",padding:0,flexShrink:0},children:r})}function eu(){return i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:i.jsx("path",{d:"M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"})})}function tu(){return i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:i.jsx("path",{d:"M8 0C3.58 0 0 1.567 0 3.5v9C0 14.433 3.58 16 8 16s8-1.567 8-3.5v-9C16 1.567 12.42 0 8 0ZM1.5 7.784V5.716C3.05 6.51 5.404 7 8 7s4.95-.49 6.5-1.284v2.068C12.95 8.578 10.596 9 8 9s-4.95-.422-6.5-1.216ZM8 1.5c3.17 0 5.854 1.116 6.357 2.5H1.643C2.146 2.616 4.83 1.5 8 1.5Zm0 13c-3.17 0-5.854-1.116-6.357-2.5h12.714C13.854 13.384 11.17 14.5 8 14.5Zm6.5-3.284C12.95 11.01 10.596 11.5 8 11.5s-4.95-.49-6.5-1.284V8.216C3.05 9.01 5.404 9.5 8 9.5s4.95-.49 6.5-1.284v2.5Z"})})}function nu(){return i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:i.jsx("path",{d:"M8 1.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13ZM0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8Zm6.5-2a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0Zm-2 4.5a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0Zm5 0a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0Z"})})}function ru(){return i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:i.jsx("path",{d:"M4 2a2 2 0 1 1 0 4 2 2 0 0 1 0-4Zm8 4a2 2 0 1 1 0 4 2 2 0 0 1 0-4Zm-8 4a2 2 0 1 1 0 4 2 2 0 0 1 0-4ZM6 4h4l2 4-2 4H6",stroke:"currentColor",strokeWidth:"1.2",fill:"none"})})}function ou(){return i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:i.jsx("path",{d:"M1 2.75C1 1.784 1.784 1 2.75 1h2.5C6.216 1 7 1.784 7 2.75v2.5C7 6.216 6.216 7 5.25 7h-2.5C1.784 7 1 6.216 1 5.25Zm1.75-.25a.25.25 0 0 0-.25.25v2.5c0 .138.112.25.25.25h2.5A.25.25 0 0 0 6 5.25v-2.5A.25.25 0 0 0 5.25 2.5ZM9 2.75C9 1.784 9.784 1 10.75 1h2.5C14.216 1 15 1.784 15 2.75v2.5C15 6.216 14.216 7 13.25 7h-2.5C9.784 7 9 6.216 9 5.25Zm1.75-.25a.25.25 0 0 0-.25.25v2.5c0 .138.112.25.25.25h2.5a.25.25 0 0 0 .25-.25v-2.5a.25.25 0 0 0-.25-.25ZM1 10.75C1 9.784 1.784 9 2.75 9h2.5C6.216 9 7 9.784 7 10.75v2.5C7 14.216 6.216 15 5.25 15h-2.5C1.784 15 1 14.216 1 13.25Zm1.75-.25a.25.25 0 0 0-.25.25v2.5c0 .138.112.25.25.25h2.5a.25.25 0 0 0 .25-.25v-2.5a.25.25 0 0 0-.25-.25ZM13 9.75a.75.75 0 0 1 .75.75v1.75H15.5a.75.75 0 0 1 0 1.5h-1.75V15.5a.75.75 0 0 1-1.5 0v-1.75H10.5a.75.75 0 0 1 0-1.5h1.75V10.5A.75.75 0 0 1 13 9.75Z"})})}function su(){return i.jsx("svg",{width:"16",height:"16",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.06 0l-.622-.621A2.25 2.25 0 0 0 5.258 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.5v9h3.757a3.75 3.75 0 0 1 1.994.574ZM8.755 4.75l-.004 7.322a3.752 3.752 0 0 1 1.992-.572H14.5v-9h-3.495a2.25 2.25 0 0 0-2.25 2.25Z"})})}function iu(){return i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:i.jsx("path",{d:"M0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8Zm8-6.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13ZM6.92 6.085h.001a.749.749 0 1 1-1.342-.67C6.03 4.26 6.88 3.75 8 3.75c1.463 0 2.5 1.008 2.5 2.25 0 1.133-.67 1.8-1.4 2.25-.487.3-.6.47-.6.75V9.5a.75.75 0 0 1-1.5 0v-.5c0-.833.585-1.33 1.1-1.65.387-.24.9-.597.9-1.35 0-.65-.53-1.25-1.5-1.25-.74 0-1.163.353-1.58.835ZM8 12a1 1 0 1 1 0-2 1 1 0 0 1 0 2Z"})})}function au(){return i.jsx("svg",{width:"16",height:"16",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.103-.303c-.066-.019-.176-.011-.299.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.103.303c.066.019.176.011.299-.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-.147a6.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"})})}function lu(){const{state:e,dispatch:t}=Se(),n=le[e.themeMode],r=e.mainView!=="block_studio";function o(s){if(s==="connection"||s==="reference"){t({type:"SET_SIDEBAR_PANEL",panel:s});return}e.sidebarPanel===s&&e.sidebarOpen?t({type:"TOGGLE_SIDEBAR"}):t({type:"SET_SIDEBAR_PANEL",panel:s})}return i.jsxs("div",{style:{width:32,flexShrink:0,background:n.activityBarBg,borderRight:`1px solid ${n.headerBorder}`,display:"flex",flexDirection:"column",alignItems:"center",paddingTop:8,paddingBottom:8,gap:2,userSelect:"none"},children:[i.jsx(ct,{title:"Files",active:e.sidebarPanel==="files"&&e.sidebarOpen,onClick:()=>o("files"),t:n,children:i.jsx(eu,{})}),i.jsx(ct,{title:"Schema",active:e.sidebarPanel==="schema"&&e.sidebarOpen,onClick:()=>o("schema"),t:n,children:i.jsx(tu,{})}),r&&i.jsx(ct,{title:"Semantic Layer",active:e.sidebarPanel==="semantic"&&e.sidebarOpen,onClick:()=>o("semantic"),t:n,children:i.jsx(nu,{})}),i.jsx(ct,{title:"Block Library",active:e.sidebarPanel==="block_library"&&e.sidebarOpen,onClick:()=>o("block_library"),t:n,children:i.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",children:[i.jsx("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",stroke:"currentColor",strokeWidth:"1.3"}),i.jsx("rect",{x:"10",y:"2",width:"6",height:"6",rx:"1",stroke:"currentColor",strokeWidth:"1.3"}),i.jsx("rect",{x:"2",y:"10",width:"6",height:"6",rx:"1",stroke:"currentColor",strokeWidth:"1.3"}),i.jsx("rect",{x:"10",y:"10",width:"6",height:"6",rx:"1",stroke:"currentColor",strokeWidth:"1.3"})]})}),i.jsx(ct,{title:"Lineage",active:e.sidebarPanel==="lineage"&&e.sidebarOpen,onClick:()=>o("lineage"),t:n,children:i.jsx(ru,{})}),i.jsx(ct,{title:"Connection",active:e.mainView==="connection",onClick:()=>o("connection"),t:n,children:i.jsx(ou,{})}),i.jsx(ct,{title:"Reference",active:e.mainView==="reference",onClick:()=>o("reference"),t:n,children:i.jsx(su,{})}),i.jsx("div",{style:{flex:1}}),i.jsx(ct,{title:"Help & Reference",active:e.mainView==="reference",onClick:()=>o("reference"),t:n,children:i.jsx(iu,{})}),i.jsx(ct,{title:"Settings",active:!1,onClick:()=>{},t:n,children:i.jsx(au,{})})]})}const Zo={notebooks:"Notebooks",workbooks:"Workbooks",blocks:"Blocks",dashboards:"Dashboards"};function Eu({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"workbook":return i.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:i.jsx("path",{d:"M2 1.75C2 .784 2.784 0 3.75 0h8.5C13.216 0 14 .784 14 1.75v12.5A1.75 1.75 0 0 1 12.25 16h-8.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25Zm2 3.5a.75.75 0 0 1 .75-.75h3a.75.75 0 0 1 0 1.5h-3a.75.75 0 0 1-.75-.75ZM6.5 7.25a.75.75 0 0 0 0 1.5h3a.75.75 0 0 0 0-1.5Zm-.75 3.5a.75.75 0 0 1 .75-.75h3a.75.75 0 0 1 0 1.5h-3a.75.75 0 0 1-.75-.75Z"})});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 cu({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 Tu(e){return e.name.replace(/\.(dqlnb|dql)$/,"")}function du({onOpenFile:e}){const{state:t,dispatch:n}=Se(),r=le[t.themeMode],[o,s]=f.useState({notebooks:!0,workbooks:!0,blocks:!1,dashboards:!1}),[a,l]=f.useState(!1),E={notebooks:[],workbooks:[],blocks:[],dashboards:[]};for(const d of t.files){const T=d.folder.toLowerCase();T in E&&E[T].push(d)}const c=d=>{s(T=>({...T,[d]:!T[d]}))};return i.jsxs("div",{style:{flex:1,overflow:"auto",padding:"8px 0",display:"flex",flexDirection:"column",gap:0},children:[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"]})}),t.filesLoading&&i.jsx("div",{style:{padding:"8px 14px",color:r.textMuted,fontSize:12,fontFamily:r.font},children:"Loading files…"}),Object.keys(Zo).map(d=>{const T=E[d],S=o[d],u=d==="notebooks"?()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}):d==="blocks"?()=>n({type:"OPEN_NEW_BLOCK_MODAL"}):void 0;return i.jsxs("div",{children:[i.jsx(Su,{label:Zo[d],count:T.length,expanded:S,onToggle:()=>c(d),onAdd:u,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 ",Zo[d].toLowerCase()]}):T.map(R=>{var I;return i.jsx(uu,{file:R,active:((I=t.activeFile)==null?void 0:I.path)===R.path,onClick:()=>e(R),t:r},R.path)})})]},d)})]})}function Su({label:e,count:t,expanded:n,onToggle:r,onAdd:o,t:s}){const[a,l]=f.useState(!1),[E,c]=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(cu,{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:()=>c(!0),onMouseLeave:()=>c(!1),title:`New ${e.slice(0,-1)}`,style:{background:E?s.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:E?s.accent:s.textMuted,fontSize:14,lineHeight:1,padding:"2px 8px",marginRight:4,flexShrink:0,transition:"color 0.1s"},children:"+"})]})}function uu({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(Eu,{type:e.type})}),i.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:Tu(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 Ru=window.location.origin;async function ce(e,t){const n=await fetch(`${Ru}${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 te={async listNotebooks(){try{return await ce("/api/notebooks")}catch{return[]}},async readNotebook(e){return ce(`/api/notebook-content?path=${encodeURIComponent(e)}`)},async createNotebook(e,t){return ce("/api/notebooks",{method:"POST",body:JSON.stringify({name:e,template:t})})},async createBlock(e){return ce("/api/blocks",{method:"POST",body:JSON.stringify({name:e})})},async getBlockLibrary(){try{return await ce("/api/blocks/library")}catch{return{blocks:[]}}},async updateBlockStatus(e,t){return ce("/api/blocks/status",{method:"POST",body:JSON.stringify({path:e,newStatus:t})})},async getBlockHistory(e){try{return await ce(`/api/blocks/history?path=${encodeURIComponent(e)}`)}catch{return{entries:[]}}},async runBlockTests(e,t){return ce("/api/blocks/run-tests",{method:"POST",body:JSON.stringify({source:e,path:t})})},async getBlockStudioCatalog(){return ce("/api/block-studio/catalog")},async openBlockStudio(e){return ce(`/api/block-studio/open?path=${encodeURIComponent(e)}`)},async validateBlockStudio(e,t){return ce("/api/block-studio/validate",{method:"POST",body:JSON.stringify({source:e,path:t})})},async runBlockStudio(e,t){return ce("/api/block-studio/run",{method:"POST",body:JSON.stringify({source:e,path:t})})},async saveBlockStudio(e){return ce("/api/block-studio/save",{method:"POST",body:JSON.stringify(e)})},async saveAsBlock(e){return ce("/api/blocks/save-from-cell",{method:"POST",body:JSON.stringify(e)})},async getBlockTemplates(){try{return(await ce("/api/blocks/templates")).templates}catch{return[]}},async listBlocks(e){try{return(await ce("/api/notebooks")).filter(n=>n.type==="block"&&(!e||n.path.startsWith(`blocks/${e}/`)))}catch{return[]}},async saveNotebook(e,t){return ce("/api/notebook-content",{method:"PUT",body:JSON.stringify({path:e,content:t})})},async executeQuery(e,t){var o;const n=await ce("/api/query",{method:"POST",body:JSON.stringify({sql:e}),signal:t});return{columns:Array.isArray(n==null?void 0:n.columns)?n.columns.map(s=>typeof s=="string"?s:typeof(s==null?void 0:s.name)=="string"?s.name:String(s)):[],rows:Array.isArray(n==null?void 0:n.rows)?n.rows:[],rowCount:(n==null?void 0:n.rowCount)??((o=n==null?void 0:n.rows)==null?void 0:o.length)??0,executionTime:(n==null?void 0:n.executionTime)??(n==null?void 0:n.executionTimeMs)??0}},async getSchema(){try{return await ce("/api/schema")}catch{return[]}},async getConnections(){try{return await ce("/api/connections")}catch{return{default:"unknown",connections:{}}}},async saveConnections(e){return ce("/api/connections",{method:"PUT",body:JSON.stringify({connections:e})})},async testConnection(){try{return await ce("/api/test-connection",{method:"POST",body:JSON.stringify({})})}catch(e){return{ok:!1,message:e.message??"Connection failed"}}},async getSemanticLayer(){try{return await ce("/api/semantic-layer")}catch{return{available:!1,provider:null,metrics:[],dimensions:[],hierarchies:[],domains:[],tags:[],favorites:[],recentlyUsed:[],lastSyncTime:null}}},async getSemanticTree(){return(await ce("/api/semantic-layer/tree")).tree},async getSemanticObject(e){return ce(`/api/semantic-layer/object/${encodeURIComponent(e)}`)},async importSemanticLayer(e){return ce("/api/semantic-layer/import",{method:"POST",body:JSON.stringify(e)})},async syncSemanticLayer(){return ce("/api/semantic-layer/sync",{method:"POST",body:JSON.stringify({})})},async previewSemanticImport(e){return ce("/api/semantic-layer/import-preview",{method:"POST",body:JSON.stringify(e)})},async previewSyncDiff(){return ce("/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 ce(`/api/semantic-layer/search?${t.toString()}`)}catch{return{metrics:[],dimensions:[],hierarchies:[]}}},async getFavorites(){try{return(await ce("/api/user-prefs/favorites")).favorites}catch{return[]}},async toggleFavorite(e){return(await ce("/api/user-prefs/favorites",{method:"POST",body:JSON.stringify({name:e})})).favorites},async getRecentlyUsed(){try{return(await ce("/api/user-prefs/recent")).recentlyUsed}catch{return[]}},async trackUsage(e){try{return(await ce("/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 ce(`/api/semantic-layer/compatible-dims?${t.toString()}`)).dimensions}catch{return[]}},async composeQuery(e,t,n){try{return await ce("/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 ce("/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 ce("/api/semantic-builder/save",{method:"POST",body:JSON.stringify(e)})},async createMetric(e){try{return await ce("/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 ce(`/api/describe-table?${o.toString()}`)}catch{return[]}},async fetchLineage(){try{return await ce("/api/lineage")}catch{return{nodes:[],edges:[]}}},async fetchBlockLineage(e){try{return await ce(`/api/lineage/block/${encodeURIComponent(e)}`)}catch{return null}},async fetchImpactAnalysis(e){try{return await ce(`/api/lineage/impact/${encodeURIComponent(e)}`)}catch{return null}}},Au={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 ei(e,t){const n=e.toLowerCase().split("(")[0].trim();return Au[n]??t}function Iu({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 Nu(){const{state:e,dispatch:t}=Se(),n=le[e.themeMode],[r,o]=f.useState(!1),[s,a]=f.useState(""),l=async()=>{t({type:"SET_SCHEMA_LOADING",loading:!0});try{const S=await te.getSchema();t({type:"SET_SCHEMA",tables:S})}catch(S){console.error("Schema refresh failed:",S)}finally{t({type:"SET_SCHEMA_LOADING",loading:!1})}},E=f.useMemo(()=>{const S=s.trim().toLowerCase();return S?e.schemaTables.filter(u=>{const R=[u.name,u.path,u.objectType].filter(N=>!!N).some(N=>N.toLowerCase().includes(S)),I=u.columns.some(N=>N.name.toLowerCase().includes(S)||N.type.toLowerCase().includes(S));return R||I}):e.schemaTables},[s,e.schemaTables]),c=f.useMemo(()=>{const S=new Map;for(const u of E){const[R,...I]=u.name.split("."),N=I.length>0?R:u.source==="file"?"files":"default",A=S.get(N)??[];A.push(u),S.set(N,A)}return Array.from(S.entries()).sort((u,R)=>u[0].localeCompare(R[0]))},[E]),d={schemas:c.length,tables:e.schemaTables.length,columns:e.schemaTables.reduce((S,u)=>S+u.columns.length,0)},T={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"};return i.jsxs("div",{style:{flex:1,overflow:"auto",display:"flex",flexDirection:"column"},children:[i.jsxs("div",{style:{padding:"10px",display:"grid",gap:10,borderBottom:`1px solid ${n.headerBorder}`},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:12,fontWeight:700,color:n.textPrimary,fontFamily:n.font},children:"Database Catalog"}),i.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:"Browse schemas, tables, views, and loaded columns from the active connection."})]}),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"]})]}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:8},children:[i.jsx(es,{label:"Schemas",value:d.schemas,t:n}),i.jsx(es,{label:"Tables",value:d.tables,t:n}),i.jsx(es,{label:"Columns",value:d.columns,t:n})]}),i.jsx("input",{value:s,onChange:S=>a(S.target.value),placeholder:"Search schemas, tables, columns...",style:T})]}),e.schemaLoading?i.jsx(Iu,{t:n}):e.schemaTables.length===0?i.jsxs("div",{style:{padding:"24px 14px",color:n.textMuted,fontSize:12,fontFamily:n.font,textAlign:"center",fontStyle:"italic"},children:["No tables found.",i.jsx("br",{}),"Connect a data source to explore schema."]}):E.length===0?i.jsx("div",{style:{padding:"24px 14px",color:n.textMuted,fontSize:12,fontFamily:n.font,textAlign:"center",fontStyle:"italic"},children:"No database objects match the current search."}):i.jsx("div",{style:{overflow:"auto",flex:1},children:c.map(([S,u])=>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:[S," · ",u.length]}),u.map(R=>i.jsx(Ou,{table:R,t:n},R.name))]},S))})]})}function es({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 Ou({table:e,t}){var E;const{dispatch:n}=Se(),[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 c=await te.describeTable(e.path);c.length>0&&n({type:"SET_TABLE_COLUMNS",tableName:e.name,columns:c})}catch(c){console.error("describeTable failed:",c)}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"}),((E=e.governance)==null?void 0:E.status)&&i.jsx(hu,{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(c=>i.jsx(fu,{col:c,t},c.name))]})]})}function fu({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:ei(e.type,t.accent),background:`${ei(e.type,t.accent)}18`,borderRadius:4,padding:"1px 5px",flexShrink:0},children:e.type.toLowerCase()})]})}const pu={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 hu({status:e,t}){const n=pu[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 ti={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"},ts={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"},Cu={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"]},Lu=[{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 VE(){const{state:e}=Se(),t=le[e.themeMode],[n,r]=f.useState(null),[o,s]=f.useState(!1),[a,l]=f.useState(null),[E,c]=f.useState(null),[d,T]=f.useState(!1),[S,u]=f.useState(!1),[R,I]=f.useState(null),[N,A]=f.useState(""),[p,O]=f.useState("duckdb"),[h,C]=f.useState({});f.useEffect(()=>{te.getConnections().then(D=>{r(D),Object.keys(D.connections).length>0&&te.testConnection().then(l)})},[]);const _=async()=>{s(!0),l(null);const D=await te.testConnection();l(D),s(!1)},m=(D,B)=>{c(D),T(!1),A(D),O((B==null?void 0:B.driver)??"duckdb");const v={};Object.entries(B??{}).forEach(([U,Y])=>{U!=="driver"&&U!=="type"&&(v[U]=String(Y??""))}),C(v)},M=()=>{T(!0),c(null),A(""),O("duckdb"),C({})},y=()=>{c(null),T(!1)},b=async()=>{if(!n)return;u(!0),I(null);const D=N.trim()||(E??"default"),B={driver:p};Object.entries(h).forEach(([U,Y])=>{Y.trim()&&(U==="port"&&!isNaN(Number(Y))?B[U]=Number(Y):B[U]=Y)});const v={...n.connections};E&&E!==D&&delete v[E],v[D]=B;try{await te.saveConnections(v);const U=await te.getConnections();r(U),I("Saved"),setTimeout(()=>I(null),2e3),c(null),T(!1);try{s(!0);const Y=await te.testConnection();l(Y)}catch{}finally{s(!1)}}catch(U){I(`Error: ${U.message}`)}finally{u(!1)}},g=async D=>{if(!n)return;const B={...n.connections};delete B[D],u(!0);try{await te.saveConnections(B);const v=await te.getConnections();r(v),c(null)}finally{u(!1)}},x={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},L=(n==null?void 0:n.connections)??{},P=(n==null?void 0:n.default)??"";return i.jsxs("div",{style:{flex:1,overflow:"auto",padding:"12px 12px 20px"},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:x,children:"Connections"}),n===null?i.jsx("div",{style:{fontSize:12,color:t.textMuted,fontFamily:t.font},children:"Loading…"}):Object.entries(L).map(([D,B])=>{const v=(B==null?void 0:B.driver)??(B==null?void 0:B.type)??"unknown",U=D===P||Object.keys(L).length===1,Y=ts[v]??t.accent;return E===D?i.jsx(Ea,{t,editName:N,setEditName:A,editDriver:p,setEditDriver:O,editFields:h,setEditFields:C,onSave:b,onCancel:y,onDelete:()=>g(D),saving:S,isNew:!1},D):i.jsxs("div",{style:{...F,borderLeft:U?`3px solid ${Y}`:`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:Y,background:`${Y}18`,border:`1px solid ${Y}40`,borderRadius:4,padding:"1px 6px",letterSpacing:"0.05em",textTransform:"uppercase"},children:ti[v]??v}),i.jsx("span",{style:{fontSize:11,fontFamily:t.fontMono,color:t.textSecondary,fontWeight:500},children:D}),U&&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:()=>m(D,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(([W])=>W!=="driver"&&W!=="type").map(([W,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:W}),i.jsx("span",{style:{fontSize:11,color:t.textSecondary,fontFamily:t.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:W.toLowerCase().includes("password")||W.toLowerCase().includes("token")?"••••••••":String(k)})]},W))})]},D)}),!d&&!E&&Object.keys(L).length===0&&i.jsxs(i.Fragment,{children:[i.jsx("div",{style:{...x,marginTop:8},children:"Quick Connect"}),i.jsx("div",{style:{display:"grid",gap:6,marginBottom:12},children:Lu.map(D=>i.jsxs("button",{onClick:async()=>{u(!0);try{const B={...L,[D.name]:D.config};await te.saveConnections(B);const v=await te.getConnections();r(v),s(!0);const U=await te.testConnection();l(U),s(!1)}finally{u(!1)}},disabled:S,style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:7,cursor:S?"not-allowed":"pointer",textAlign:"left",transition:"border-color 0.15s"},children:[i.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:ts[D.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:D.label}),i.jsx("div",{style:{fontSize:10,color:t.textMuted,fontFamily:t.font},children:D.description})]})]},D.name))})]}),d?i.jsx(Ea,{t,editName:N,setEditName:A,editDriver:p,setEditDriver:O,editFields:h,setEditFields:C,onSave:b,onCancel:y,saving:S,isNew:!0}):i.jsxs("button",{onClick:M,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"]}),R&&i.jsx("div",{style:{fontSize:11,fontFamily:t.font,padding:"4px 10px",borderRadius:4,marginBottom:8,color:R.startsWith("Error")?t.error:t.success,background:R.startsWith("Error")?`${t.error}12`:`${t.success}12`},children:R}),i.jsx("button",{onClick:_,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:{...x,marginTop:4},children:"Supported Drivers"}),i.jsx("div",{style:{...F,display:"flex",flexDirection:"column",gap:4},children:Object.entries(ti).map(([D,B])=>i.jsxs("div",{style:{display:"flex",gap:8,alignItems:"baseline"},children:[i.jsx("code",{style:{fontSize:10,fontFamily:t.fontMono,color:ts[D]??t.textMuted,minWidth:80,flexShrink:0},children:D}),i.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.font},children:B})]},D))})]})}function Ea({t:e,editName:t,setEditName:n,editDriver:r,setEditDriver:o,editFields:s,setEditFields:a,onSave:l,onCancel:E,onDelete:c,saving:d,isNew:T}){const S=Cu[r]??[],u={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%"},R={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:T?"New Connection":"Edit Connection"}),i.jsxs("div",{style:{marginBottom:6},children:[i.jsx("div",{style:R,children:"Name"}),i.jsx("input",{style:u,value:t,onChange:I=>n(I.target.value),placeholder:"e.g. production"})]}),i.jsxs("div",{style:{marginBottom:6},children:[i.jsx("div",{style:R,children:"Driver"}),i.jsx("select",{style:{...u,fontFamily:e.font},value:r,onChange:I=>{o(I.target.value),a({})},children:Object.entries(ti).map(([I,N])=>i.jsx("option",{value:I,children:N},I))})]}),S.map(I=>i.jsxs("div",{style:{marginBottom:6},children:[i.jsx("div",{style:R,children:I}),i.jsx("input",{style:u,type:I.toLowerCase().includes("password")||I.toLowerCase().includes("token")?"password":"text",value:s[I]??"",placeholder:I==="port"?"5432":I==="filepath"?":memory:":"",onChange:N=>a({...s,[I]:N.target.value})})]},I)),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:E,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"}),c&&!T&&i.jsx("button",{onClick:c,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 Tt({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(E=>!E),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 _u({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 ge({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(_u,{code:e,t})]})}function ca({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 mu=`block "Revenue by Channel" {
10
+ domain = "revenue"
11
+ type = "custom"
12
+ description = "Revenue grouped by sales channel"
13
+ owner = "data-team"
14
+ tags = ["revenue"]
15
+
16
+ params {
17
+ period = "current_quarter"
18
+ }
19
+
20
+ query = """
21
+ SELECT channel,
22
+ SUM(order_total) AS revenue
23
+ FROM read_csv_auto('data/orders.csv')
24
+ WHERE fiscal_period = \${period}
25
+ GROUP BY channel
26
+ ORDER BY revenue DESC
27
+ """
28
+
29
+ visualization {
30
+ chart = "bar"
31
+ x = channel
32
+ y = revenue
33
+ }
34
+
35
+ tests {
36
+ assert row_count > 0
37
+ }
38
+ }`,gu=`# semantic-layer/metrics/total_revenue.yaml
39
+ name: total_revenue
40
+ label: Total Revenue
41
+ description: Sum of all recognized revenue.
42
+ domain: finance
43
+ sql: SUM(amount)
44
+ type: sum # sum|count|count_distinct|avg|min|max|custom
45
+ table: fct_revenue
46
+ tags:
47
+ - revenue
48
+ - kpi`,xu=`# semantic-layer/dimensions/segment.yaml
49
+ name: segment
50
+ label: Customer Segment
51
+ description: Customer segment tier.
52
+ sql: segment_tier
53
+ type: string # string|number|date|boolean
54
+ table: fct_revenue`,yu=`# semantic-layer/hierarchies/time.yaml
55
+ name: fiscal_time
56
+ label: Fiscal Time
57
+ description: Drill from year to quarter.
58
+ domain: finance
59
+ levels:
60
+ - name: fiscal_year
61
+ dimension: fiscal_year
62
+ order: 1
63
+ - name: fiscal_quarter
64
+ dimension: fiscal_quarter
65
+ order: 2
66
+ defaultRollup: sum`,Du=`# semantic-layer/cubes/revenue_cube.yaml
67
+ name: revenue
68
+ label: Revenue Cube
69
+ table: fct_revenue
70
+ domain: finance
71
+
72
+ measures:
73
+ - name: total_revenue
74
+ sql: SUM(amount)
75
+ type: sum
76
+ - name: deal_count
77
+ sql: COUNT(*)
78
+ type: count
79
+
80
+ dimensions:
81
+ - name: segment_tier
82
+ sql: segment_tier
83
+ type: string
84
+
85
+ time_dimensions:
86
+ - name: recognized_at
87
+ sql: recognized_at
88
+ primary_time: true
89
+ granularities: [day, month, quarter, year]
90
+
91
+ joins:
92
+ - name: customers
93
+ type: left
94
+ sql: "\${left}.customer_id = \${right}.id"`,Mu=`{
95
+ "semanticLayer": {
96
+ "provider": "dql"
97
+ }
98
+ }`,Pu=`{
99
+ "semanticLayer": {
100
+ "provider": "dbt",
101
+ "projectPath": "/path/to/your/dbt-project"
102
+ }
103
+ }`,bu=`{
104
+ "semanticLayer": {
105
+ "provider": "cubejs",
106
+ "projectPath": "/path/to/your/cube-project"
107
+ }
108
+ }`,Uu=`{
109
+ "defaultConnection": {
110
+ "driver": "file",
111
+ "filepath": ":memory:"
112
+ }
113
+ }`,vu=`{
114
+ "defaultConnection": {
115
+ "driver": "snowflake",
116
+ "account": "acme.snowflakecomputing.com",
117
+ "username": "your_user",
118
+ "password": "\${SNOWFLAKE_PASSWORD}",
119
+ "database": "ANALYTICS",
120
+ "schema": "PUBLIC",
121
+ "warehouse": "COMPUTE_WH",
122
+ "role": "ANALYST"
123
+ }
124
+ }`,Bu=`{
125
+ "defaultConnection": {
126
+ "driver": "bigquery",
127
+ "project": "your-gcp-project-id",
128
+ "dataset": "analytics",
129
+ "keyFilename": "./service-account.json"
130
+ }
131
+ }`,Fu=`{
132
+ "defaultConnection": {
133
+ "driver": "postgres",
134
+ "host": "localhost",
135
+ "port": 5432,
136
+ "database": "analytics",
137
+ "username": "your_user",
138
+ "password": "\${POSTGRES_PASSWORD}"
139
+ }
140
+ }`,Gu=`-- Primary workflow: use Compose Query in the Semantic Layer panel
141
+ -- 1. Pick metrics + dimensions (+ optional time dimension)
142
+ -- 2. Click "Compose SQL"
143
+ -- 3. Click "+ Insert as Cell" → edit and run
144
+
145
+ -- Advanced: reference metrics inline in any SQL cell
146
+ -- DQL resolves @metric() and @dim() at query time
147
+ SELECT
148
+ @dim(segment_tier),
149
+ @metric(total_revenue)
150
+ FROM fct_revenue
151
+ GROUP BY @dim(segment_tier)
152
+ ORDER BY @metric(total_revenue) DESC`,wu=`{
153
+ "semanticLayer": {
154
+ "provider": "snowflake",
155
+ "projectPath": "MY_DATABASE"
156
+ }
157
+ }`;function WE({themeMode:e}){const t=le[e];return i.jsxs("div",{style:{flex:1,overflowY:"auto",fontFamily:t.font},children:[i.jsx(Tt,{title:"SQL Essentials",defaultOpen:!0,t,children:i.jsx(ge,{t,code:`-- Basic select
158
+ SELECT col1, col2
159
+ FROM table_name
160
+ WHERE condition
161
+ ORDER BY col1 DESC
162
+ LIMIT 100
163
+
164
+ -- GROUP BY
165
+ SELECT col, COUNT(*), SUM(val)
166
+ FROM table_name
167
+ GROUP BY col
168
+
169
+ -- JOIN
170
+ SELECT a.*, b.col
171
+ FROM table_a AS a
172
+ JOIN table_b AS b ON a.id = b.id
173
+
174
+ -- CTE (WITH)
175
+ WITH cte AS (
176
+ SELECT * FROM table_name WHERE val > 0
177
+ )
178
+ SELECT * FROM cte
179
+
180
+ -- Window function
181
+ SELECT *,
182
+ ROW_NUMBER() OVER (
183
+ PARTITION BY group_col
184
+ ORDER BY val DESC
185
+ ) AS rank
186
+ FROM table_name`})}),i.jsx(Tt,{title:"DuckDB Functions",defaultOpen:!1,t,children:i.jsx(ca,{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(Tt,{title:"DQL Block Structure",defaultOpen:!0,t,children:[i.jsx(ge,{t,code:mu}),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(Tt,{title:"DQL Chart Types",defaultOpen:!1,t,children:[i.jsx(ca,{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(Tt,{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(ge,{t,code:Gu})]}),i.jsxs(Tt,{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(ge,{t,code:`my-project/
187
+ ├── dql.config.json
188
+ └── semantic-layer/
189
+ ├── metrics/ ← one YAML per metric
190
+ ├── dimensions/ ← one YAML per dimension
191
+ ├── hierarchies/ ← optional drill paths
192
+ └── 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(ge,{t,code:gu}),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(ge,{t,code:xu}),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(ge,{t,code:yu}),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(ge,{t,code:Du})]}),i.jsxs(Tt,{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(ge,{t,code:Mu}),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(ge,{t,code:Pu}),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(ge,{t,code:bu}),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(ge,{t,code:wu}),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(Tt,{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(ge,{t,code:Uu}),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(ge,{t,code:vu}),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(ge,{t,code:Bu}),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(ge,{t,code:Fu}),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(Tt,{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(ge,{t,code:`-- Param cell named "start_date" holds '2024-01-01'
193
+ SELECT *
194
+ FROM read_csv_auto('data/sales.csv')
195
+ WHERE date >= {{start_date}}
196
+
197
+ -- SQL cell named "base_query" used as CTE
198
+ SELECT segment, SUM(revenue) AS total
199
+ FROM {{base_query}}
200
+ GROUP BY segment`})]})]})}const Hu=3e4,to="application/dql-semantic-ref";let Lr=[],Ta=0,Gn=null;function Yu(e){te.trackUsage(e),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:e}}))}async function da(){if(Date.now()<Ta&&Lr.length>0)return Lr;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 Lr=Array.isArray(t.completions)?t.completions:[],Ta=Date.now()+Hu,Lr}function ku(e,t){return e==="metric"?`@metric(${t})`:`@dim(${t})`}function jE(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 Vu(e){Gn=e}function Wu(e){Gn===e&&(Gn=null)}function ni(e){return Gn?(jE(Gn,e),!0):!1}function ju(e,t,n){const r=n?e.posAtCoords(n)??e.state.selection.main.from:e.state.selection.main.from;jE(e,t,r)}function Sa(e,t,n){return{label:e.name,detail:e.type==="metric"?"@metric":"@dim",type:e.type==="metric"?"function":"variable",info:`${e.label}${e.description?`
201
+ ${e.description}`:""}${e.sql?`
202
+ ${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}}),Yu(e.name)}}}function $u(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 Xu=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(),E=n-o[1].length,c=(await da()).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(T=>T.toLowerCase().includes(l))).slice(0,50);return{from:E,options:c.map(d=>Sa(d,E,n)),validFor:/^[\w-]*$/}}const s=/@dim\(([^)]*)$/i.exec(r);if(s){const l=s[1].trim().toLowerCase(),E=n-s[1].length,c=(await da()).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(T=>T.toLowerCase().includes(l))).slice(0,50);return{from:E,options:c.map(d=>Sa(d,E,n)),validFor:/^[\w-]*$/}}const a=/@([md][a-z_]*)?$/i.exec(r);return a?$u(n-a[0].length):(e.explicit,null)};function Ku(e,t){return JSON.stringify({type:e,name:t,reference:ku(e,t)})}function $E(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 XE({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",E=!!e.sql,c=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",{}),c?i.jsxs("div",{children:["source: ",c]}):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:!E,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 KE({query:e,provider:t,cube:n,owner:r,domain:o,tag:s,type:a,providers:l,cubes:E,owners:c,domains:d,tags:T,onQueryChange:S,onProviderChange:u,onCubeChange:R,onOwnerChange:I,onDomainChange:N,onTagChange:A,onTypeChange:p,t:O}){const h={width:"100%",background:O.inputBg,border:`1px solid ${O.inputBorder}`,borderRadius:6,color:O.textPrimary,fontSize:12,fontFamily:O.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 ${O.headerBorder}`},children:[i.jsx("input",{value:e,onChange:C=>S(C.target.value),placeholder:"Search labels, cubes, owners, tags...",style:h}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:6},children:[i.jsxs("select",{value:t,onChange:C=>u(C.target.value),style:h,children:[i.jsx("option",{value:"",children:"All providers"}),l.map(C=>i.jsx("option",{value:C,children:C},C))]}),i.jsxs("select",{value:o,onChange:C=>N(C.target.value),style:h,children:[i.jsx("option",{value:"",children:"All domains"}),d.map(C=>i.jsx("option",{value:C,children:C},C))]}),i.jsxs("select",{value:n,onChange:C=>R(C.target.value),style:h,children:[i.jsx("option",{value:"",children:"All cubes"}),E.map(C=>i.jsx("option",{value:C,children:C},C))]}),i.jsxs("select",{value:r,onChange:C=>I(C.target.value),style:h,children:[i.jsx("option",{value:"",children:"All owners"}),c.map(C=>i.jsx("option",{value:C,children:C},C))]}),i.jsxs("select",{value:s,onChange:C=>A(C.target.value),style:h,children:[i.jsx("option",{value:"",children:"All tags"}),T.map(C=>i.jsx("option",{value:C,children:C},C))]}),i.jsxs("select",{value:a,onChange:C=>p(C.target.value),style:h,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 wn({label:e,depth:t=0,badge:n,badgeColor:r,count:o,expanded:s,favorite:a,selected:l,onClick:E,onDoubleClick:c,onToggle:d,onFavoriteToggle:T,onDragStart:S,title:u,muted:R,t:I}){const[N,A]=f.useState(!1);return i.jsxs("button",{draggable:!!S,onDragStart:S,onClick:E,onDoubleClick:c,onMouseEnter:()=>A(!0),onMouseLeave:()=>A(!1),title:u,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:`5px 8px 5px ${10+t*14}px`,background:l?`${I.accent}18`:N?I.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:R?I.textMuted:I.textPrimary,fontSize:12,fontFamily:I.font,textAlign:"left"},children:[d?i.jsx("span",{onClick:p=>{p.stopPropagation(),d()},style:{display:"inline-flex",transform:s?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.15s",color:I.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:I.fontMono,color:r??I.accent,background:`${r??I.accent}18`,borderRadius:4,padding:"1px 4px",flexShrink:0},children:n}),typeof o=="number"&&i.jsx("span",{style:{fontSize:10,color:I.textMuted,background:I.pillBg,borderRadius:999,padding:"1px 6px",flexShrink:0},children:o}),typeof a=="boolean"&&i.jsx("span",{onClick:p=>{p.stopPropagation(),T==null||T()},style:{color:a?"#e3b341":I.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 zu=[{id:"dbt",label:"dbt",description:"Import semantic models, metrics, and dimensions from a dbt project (v1.6+).",icon:"dbt",color:"#ff694a"},{id:"cubejs",label:"Cube.js",description:"Import cubes, measures, dimensions, joins, and pre-aggregations from Cube.js.",icon:"cube",color:"#7a77ff"},{id:"snowflake",label:"Snowflake",description:"Introspect Snowflake semantic views and import metrics and dimensions.",icon:"snow",color:"#29b5e8"}];function Ju({detectedProvider:e,onClose:t,onImported:n}){const{state:r}=Se(),o=le[r.themeMode],[s,a]=f.useState("provider"),[l,E]=f.useState(null),[c,d]=f.useState(""),[T,S]=f.useState(""),[u,R]=f.useState(""),[I,N]=f.useState(""),[A,p]=f.useState(""),[O,h]=f.useState("local"),[C,_]=f.useState([]),[m,M]=f.useState(null),[y,b]=f.useState(!1),[g,x]=f.useState(null),[F,L]=f.useState(null),[P,D]=f.useState(null),[B,v]=f.useState(null),[U,Y]=f.useState(null);f.useEffect(()=>{te.getConnections().then(H=>{H!=null&&H.connections&&_(Object.keys(H.connections))}).catch(()=>{})},[]);const W=()=>l?l==="snowflake"?{provider:l,connection:A||void 0}:O==="repo"?{provider:l,repoUrl:T,branch:u||void 0,subPath:I||void 0}:{provider:l,projectPath:c||void 0}:null,k=async()=>{const H=W();if(H){b(!0),x(null),L(null);try{const J=await te.previewSemanticImport(H);M(J),a("preview")}catch(J){let V={};try{V=JSON.parse(J.message)}catch{V={error:J.message}}x(V.error??J.message??"Preview failed"),L(V.hint??null)}finally{b(!1)}}},w=async()=>{const H=W();if(H){a("importing"),v(null),Y(null);try{const J=await te.importSemanticLayer(H);D(J),a("done")}catch(J){let V={};try{V=JSON.parse(J.message)}catch{V={error:J.message}}v(V.error??J.message??"Import failed"),Y(V.hint??null),a("preview")}}},z=()=>{n(),t()},q=H=>{H.target===H.currentTarget&&t()};f.useEffect(()=>{const H=J=>{J.key==="Escape"&&t()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[t]);const Z={background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:6,color:o.textPrimary,fontSize:13,fontFamily:o.font,padding:"8px 12px",outline:"none",width:"100%",boxSizing:"border-box"},K={fontSize:12,fontWeight:500,color:o.textSecondary,fontFamily:o.font,marginBottom:4,display:"block"};return i.jsx("div",{onClick:q,style:{position:"fixed",inset:0,background:o.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(4px)"},children:i.jsxs("div",{style:{background:o.modalBg,border:`1px solid ${o.cellBorder}`,borderRadius:12,width:560,maxWidth:"calc(100vw - 48px)",maxHeight:"calc(100vh - 80px)",display:"flex",flexDirection:"column",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:o.textPrimary,fontFamily:o.font,margin:0},children:s==="done"?"Import Complete":"Set Up Semantic Layer"}),i.jsx("button",{onClick:t,style:{background:"transparent",border:"none",cursor:"pointer",color:o.textMuted,fontSize:18,lineHeight:1,padding:"2px 4px",borderRadius:4},children:"×"})]}),s!=="done"&&i.jsx("div",{style:{padding:"12px 24px 0",display:"flex",gap:4},children:["provider","configure","preview","importing"].map((H,J)=>i.jsx("div",{style:{flex:1,height:3,borderRadius:2,background:["provider","configure","preview","importing"].indexOf(s)>=J?o.accent:o.cellBorder,transition:"background 0.2s"}},H))}),i.jsxs("div",{style:{padding:"20px 24px 24px",flex:1,overflowY:"auto"},children:[s==="provider"&&i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[i.jsx("div",{style:{fontSize:13,color:o.textSecondary,fontFamily:o.font,lineHeight:1.5},children:"Choose where to import your semantic definitions from."}),zu.map(H=>{const J=e===H.id,V=l===H.id;return i.jsxs("button",{onClick:()=>E(H.id),style:{background:V?`${H.color}11`:o.inputBg,border:`2px solid ${V?H.color:o.cellBorder}`,borderRadius:10,padding:"14px 16px",cursor:"pointer",textAlign:"left",display:"flex",flexDirection:"column",gap:4,transition:"border-color 0.15s, background 0.15s"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{style:{display:"inline-block",width:10,height:10,borderRadius:"50%",background:H.color,flexShrink:0}}),i.jsx("span",{style:{fontSize:14,fontWeight:600,color:o.textPrimary,fontFamily:o.font},children:H.label}),J&&i.jsx("span",{style:{fontSize:10,fontWeight:600,color:H.color,fontFamily:o.font,background:`${H.color}18`,padding:"2px 8px",borderRadius:8,marginLeft:4},children:"Detected"})]}),i.jsx("span",{style:{fontSize:12,color:o.textMuted,fontFamily:o.font,lineHeight:1.4},children:H.description})]},H.id)})]}),s==="configure"&&l&&i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[i.jsx("div",{style:{fontSize:13,color:o.textSecondary,fontFamily:o.font,lineHeight:1.5},children:l==="snowflake"?"Select the Snowflake connection to introspect semantic views.":`Configure the source for your ${l==="dbt"?"dbt":"Cube.js"} project.`}),l==="snowflake"?i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:K,children:"Connection"}),i.jsxs("select",{value:A,onChange:H=>p(H.target.value),style:Z,children:[i.jsx("option",{value:"",children:"Select a connection..."}),C.map(H=>i.jsx("option",{value:H,children:H},H))]}),C.length===0&&i.jsx("span",{style:{fontSize:11,color:o.warning??"#f0ad4e",fontFamily:o.font},children:"No connections configured. Set up a Snowflake connection first."})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsx("button",{onClick:()=>h("local"),style:{background:O==="local"?o.accent:"transparent",color:O==="local"?"#fff":o.textSecondary,border:`1px solid ${O==="local"?o.accent:o.cellBorder}`,borderRadius:6,padding:"5px 14px",cursor:"pointer",fontSize:12,fontFamily:o.font,fontWeight:500},children:"Local Path"}),i.jsx("button",{onClick:()=>h("repo"),style:{background:O==="repo"?o.accent:"transparent",color:O==="repo"?"#fff":o.textSecondary,border:`1px solid ${O==="repo"?o.accent:o.cellBorder}`,borderRadius:6,padding:"5px 14px",cursor:"pointer",fontSize:12,fontFamily:o.font,fontWeight:500},children:"Git Repository"})]}),O==="local"?i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:K,children:"Project Path"}),i.jsx("input",{value:c,onChange:H=>d(H.target.value),placeholder:l==="dbt"?"../my-dbt-project":"../my-cube-project",style:Z}),i.jsx("span",{style:{fontSize:11,color:o.textMuted,fontFamily:o.font},children:l==="dbt"?"Path to the directory containing dbt_project.yml":"Path to the directory containing model/ or schema/"})]}):i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:K,children:"Repository URL"}),i.jsx("input",{value:T,onChange:H=>S(H.target.value),placeholder:"https://github.com/org/repo",style:Z})]}),i.jsxs("div",{style:{display:"flex",gap:12},children:[i.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:K,children:"Branch"}),i.jsx("input",{value:u,onChange:H=>R(H.target.value),placeholder:"main",style:Z})]}),i.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:K,children:"Sub-path"}),i.jsx("input",{value:I,onChange:H=>N(H.target.value),placeholder:"optional/sub/dir",style:Z})]})]})]})]}),g&&i.jsxs("div",{style:{background:`${o.error}12`,border:`1px solid ${o.error}40`,borderRadius:8,padding:"10px 14px"},children:[i.jsx("div",{style:{fontSize:12,color:o.error,fontFamily:o.font,fontWeight:600,marginBottom:4},children:"Validation Failed"}),i.jsx("div",{style:{fontSize:12,color:o.textSecondary,fontFamily:o.font,lineHeight:1.4},children:g}),F&&i.jsx("div",{style:{fontSize:11,color:o.textMuted,fontFamily:o.font,marginTop:6,fontStyle:"italic"},children:F})]})]}),s==="preview"&&m&&i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[i.jsx("div",{style:{fontSize:13,color:o.textSecondary,fontFamily:o.font,lineHeight:1.5},children:"Review what will be imported into your project."}),i.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:10},children:Object.entries(m.counts).filter(([,H])=>H>0).map(([H,J])=>i.jsxs("div",{style:{background:o.inputBg,borderRadius:8,padding:"12px 14px",border:`1px solid ${o.cellBorder}`,textAlign:"center"},children:[i.jsx("div",{style:{fontSize:22,fontWeight:700,color:o.accent,fontFamily:o.font},children:J}),i.jsxs("div",{style:{fontSize:11,color:o.textMuted,fontFamily:o.font,textTransform:"capitalize"},children:[H.replace("_","-"),"s"]})]},H))}),m.domains.length>0&&i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:12,fontWeight:600,color:o.textSecondary,fontFamily:o.font,marginBottom:6},children:"Domains"}),i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:m.domains.map(H=>i.jsx("span",{style:{fontSize:11,fontFamily:o.font,background:o.pillBg,padding:"3px 10px",borderRadius:8,color:o.textSecondary},children:H},H))})]}),m.warnings.length>0&&i.jsxs("div",{style:{background:`${o.warning??"#f0ad4e"}12`,border:`1px solid ${o.warning??"#f0ad4e"}40`,borderRadius:8,padding:"10px 14px"},children:[i.jsx("div",{style:{fontSize:12,fontWeight:600,color:o.warning??"#f0ad4e",fontFamily:o.font,marginBottom:4},children:"Warnings"}),m.warnings.map((H,J)=>i.jsx("div",{style:{fontSize:12,color:o.textSecondary,fontFamily:o.font,lineHeight:1.4},children:H},J))]}),B&&i.jsxs("div",{style:{background:`${o.error}12`,border:`1px solid ${o.error}40`,borderRadius:8,padding:"10px 14px"},children:[i.jsx("div",{style:{fontSize:12,color:o.error,fontFamily:o.font,fontWeight:600,marginBottom:4},children:"Import Failed"}),i.jsx("div",{style:{fontSize:12,color:o.textSecondary,fontFamily:o.font,lineHeight:1.4},children:B}),U&&i.jsx("div",{style:{fontSize:11,color:o.textMuted,fontFamily:o.font,marginTop:6,fontStyle:"italic"},children:U})]})]}),s==="importing"&&i.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:16,padding:"32px 0"},children:[i.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`3px solid ${o.cellBorder}`,borderTopColor:o.accent,animation:"spin 0.8s linear infinite"}}),i.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"}),i.jsxs("div",{style:{fontSize:14,color:o.textSecondary,fontFamily:o.font},children:["Importing ",l," semantic layer..."]}),i.jsx("div",{style:{fontSize:12,color:o.textMuted,fontFamily:o.font},children:"Parsing models, writing YAML files, refreshing state"})]}),s==="done"&&P&&i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 0"},children:[i.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:36,height:36,borderRadius:"50%",background:`${o.success??"#28a745"}20`,color:o.success??"#28a745",fontSize:20,fontWeight:700},children:"✓"}),i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:14,fontWeight:600,color:o.textPrimary,fontFamily:o.font},children:"Semantic layer imported successfully"}),i.jsx("div",{style:{fontSize:12,color:o.textMuted,fontFamily:o.font},children:Object.entries(P.counts).filter(([,H])=>H>0).map(([H,J])=>`${J} ${H.replace("_","-")}${J!==1?"s":""}`).join(", ")})]})]}),P.manifest.warnings.length>0&&i.jsx("div",{style:{background:`${o.warning??"#f0ad4e"}12`,border:`1px solid ${o.warning??"#f0ad4e"}40`,borderRadius:8,padding:"10px 14px"},children:P.manifest.warnings.map((H,J)=>i.jsx("div",{style:{fontSize:12,color:o.textSecondary,fontFamily:o.font},children:H},J))}),i.jsx("div",{style:{background:o.inputBg,borderRadius:8,padding:"12px 14px",border:`1px solid ${o.cellBorder}`,fontSize:12,color:o.textMuted,fontFamily:o.font,lineHeight:1.5},children:"Your semantic definitions are now available in the Semantic Layer browser. Use the Guided Builder or drag metrics into your editor to start creating blocks."})]})]}),i.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${o.cellBorder}`,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[i.jsx("div",{children:s!=="provider"&&s!=="importing"&&s!=="done"&&i.jsx("button",{onClick:()=>{s==="configure"?a("provider"):s==="preview"&&a("configure")},style:{background:"transparent",border:`1px solid ${o.cellBorder}`,borderRadius:6,color:o.textSecondary,cursor:"pointer",fontSize:13,fontFamily:o.font,fontWeight:500,padding:"7px 16px"},children:"Back"})}),i.jsxs("div",{style:{display:"flex",gap:10},children:[s!=="importing"&&i.jsx("button",{onClick:t,style:{background:o.btnBg,border:`1px solid ${o.btnBorder}`,borderRadius:6,color:o.textSecondary,cursor:"pointer",fontSize:13,fontFamily:o.font,fontWeight:500,padding:"7px 16px"},children:"Cancel"}),s==="provider"&&i.jsx("button",{onClick:()=>l&&a("configure"),disabled:!l,style:{background:o.accent,border:`1px solid ${o.accent}`,borderRadius:6,color:"#fff",cursor:l?"pointer":"not-allowed",fontSize:13,fontFamily:o.font,fontWeight:500,padding:"7px 20px",opacity:l?1:.5},children:"Next"}),s==="configure"&&i.jsx("button",{onClick:k,disabled:y,style:{background:o.accent,border:`1px solid ${o.accent}`,borderRadius:6,color:"#fff",cursor:y?"not-allowed":"pointer",fontSize:13,fontFamily:o.font,fontWeight:500,padding:"7px 20px",opacity:y?.6:1,display:"flex",alignItems:"center",gap:6},children:y?"Validating...":"Validate & Preview"}),s==="preview"&&i.jsx("button",{onClick:w,style:{background:o.accent,border:`1px solid ${o.accent}`,borderRadius:6,color:"#fff",cursor:"pointer",fontSize:13,fontFamily:o.font,fontWeight:500,padding:"7px 20px"},children:"Import"}),s==="done"&&i.jsx("button",{onClick:z,style:{background:o.accent,border:`1px solid ${o.accent}`,borderRadius:6,color:"#fff",cursor:"pointer",fontSize:13,fontFamily:o.font,fontWeight:500,padding:"7px 20px"},children:"Open Semantic Browser"})]})]})]})})}const qu=[25,50,100,500];function ri(e){return typeof e=="number"?!0:typeof e=="string"?!isNaN(Number(e))&&e.trim()!=="":!1}function zE(e){return e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}function Qu(e,t){return e==null?1:t==null?-1:ri(e)&&ri(t)?Number(e)-Number(t):String(e).localeCompare(String(t))}function Zu(e,t){const n=a=>a.includes(",")||a.includes('"')||a.includes(`
203
+ `)?`"${a.replace(/"/g,'""')}"`:a,r=e.columns.map(n).join(","),o=e.rows.map(a=>e.columns.map(l=>n(zE(a[l]))).join(",")),s=[r,...o].join(`
204
+ `);JE(s,"export.csv","text/csv")}function eR(e,t){const n=JSON.stringify(e.rows,null,2);JE(n,"export.json","application/json")}function JE(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 tR({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 Lo({result:e,themeMode:t}){const n=le[t],[r,o]=f.useState(null),[s,a]=f.useState(null),[l,E]=f.useState(null),[c,d]=f.useState(""),[T,S]=f.useState(50),[u,R]=f.useState(0),I=f.useCallback(C=>{s===C?l==="asc"?E("desc"):l==="desc"?(a(null),E(null)):E("asc"):(a(C),E("asc")),R(0)},[s,l]),N=f.useMemo(()=>{if(!c.trim())return e.rows;const C=c.toLowerCase();return e.rows.filter(_=>e.columns.some(m=>{const M=_[m];return M==null?!1:String(M).toLowerCase().includes(C)}))},[e.rows,e.columns,c]),A=f.useMemo(()=>{if(!s||!l)return N;const C=[...N];return C.sort((_,m)=>{const M=Qu(_[s],m[s]);return l==="desc"?-M:M}),C},[N,s,l]),p=Math.max(1,Math.ceil(A.length/T)),O=Math.min(u,p-1),h=A.slice(O*T,(O+1)*T);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:c,onChange:C=>{d(C.target.value),R(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"}}),c&&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:[c?`${A.length} of ${e.rows.length}`:`${e.rows.length}`," rows"]}),i.jsx("div",{style:{flex:1}}),i.jsx(ua,{label:"CSV",onClick:()=>Zu(e),t:n}),i.jsx(ua,{label:"JSON",onClick:()=>eR(e),t:n}),i.jsx("select",{value:T,onChange:C=>{S(Number(C.target.value)),R(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:qu.map(C=>i.jsxs("option",{value:C,children:[C," / page"]},C))}),p>1&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[i.jsx(_r,{disabled:O===0,onClick:()=>R(0),t:n,children:"«"}),i.jsx(_r,{disabled:O===0,onClick:()=>R(O-1),t:n,children:"‹"}),i.jsxs("span",{style:{fontSize:10,color:n.textSecondary,fontFamily:n.font,padding:"0 4px"},children:[O+1,"/",p]}),i.jsx(_r,{disabled:O>=p-1,onClick:()=>R(O+1),t:n,children:"›"}),i.jsx(_r,{disabled:O>=p-1,onClick:()=>R(p-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:()=>I(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"},children:[C,i.jsx(tR,{dir:s===C?l:null,color:s===C?n.accent:n.textMuted})]})},C))})}),i.jsx("tbody",{children:h.map((C,_)=>i.jsx("tr",{onMouseEnter:()=>o(_),onMouseLeave:()=>o(null),style:{background:r===_?n.tableRowHover:"transparent",transition:"background 0.1s"},children:e.columns.map(m=>{const M=C[m],y=M==null,b=ri(M);return i.jsx("td",{style:{padding:"5px 12px",borderBottom:`1px solid ${n.tableBorder}`,borderRight:`1px solid ${n.tableBorder}`,color:y?n.textMuted:n.textPrimary,fontStyle:y?"italic":"normal",textAlign:b?"right":"left",whiteSpace:"nowrap",maxWidth:300,overflow:"hidden",textOverflow:"ellipsis"},children:y?"—":zE(M)},m)})},_))})]})}),(c||A.length>T)&&i.jsxs("div",{style:{padding:"4px 12px",color:n.textMuted,fontSize:10,fontFamily:n.font,borderTop:`1px solid ${n.tableBorder}`,background:`${n.tableHeaderBg}60`,display:"flex",justifyContent:"space-between"},children:[i.jsxs("span",{children:["Showing ",O*T+1,"–",Math.min((O+1)*T,A.length)," of ",A.length,c&&` (filtered from ${e.rows.length})`]}),s&&i.jsxs("span",{children:["Sorted by ",s," ",l]})]})]})}function ua({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 _r({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 Ci=[{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"}],nR=/date|time|at|day|month|year/i,qE=/^(label|name|category|status|type|group)$/i,QE=/^(value|count|total|revenue|amount|sum|avg|price|quantity|sales)$/i;function mt(e){return typeof e=="number"?!0:typeof e=="string"?e.trim()!==""&&!isNaN(Number(e)):!1}function rR(e){return typeof e=="string"||typeof e=="number"}const oR=new Set(["bar","line","area","pie","donut","scatter","heatmap","funnel","waterfall","histogram","gauge","stacked-bar","grouped-bar","kpi","table"]);function Hn(e,t){if(t!=null&&t.chart){const n=t.chart.toLowerCase().replace(/_/g,"-");if(oR.has(n))return n}return ZE(e)}function ZE(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(T=>mt(T[o])),l=s.every(T=>rR(T[r]));if(nR.test(r)&&a&&l)return"line";const E=t.find(T=>qE.test(T)),c=t.find(T=>QE.test(T));return E&&c&&s.every(S=>mt(S[c]))?"bar":s.every(T=>mt(T[r]))&&a&&t.length>=2?"scatter":t.length===2&&l&&a?"bar":"table"}const ec={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"]},Pe=ec.default;function ye(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 sR(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 _o(e,t){const n=(t!=null&&t.x&&e.columns.includes(t.x)?t.x:void 0)??e.columns.find(o=>qE.test(o))??e.columns[0],r=(t!=null&&t.y&&e.columns.includes(t.y)?t.y:void 0)??e.columns.find(o=>QE.test(o))??e.columns[1];return{labelCol:n,valueCol:r}}const Ht=20;function Li({result:e,themeMode:t,chartConfig:n}){const r=le[t],[o,s]=f.useState(null),{labelCol:a,valueCol:l}=_o(e,n),E=(n==null?void 0:n.maxItems)??Ht,c=e.rows.slice(0,E).map(A=>({label:String(A[a]??""),value:Number(A[l]??0)})),d=e.rows.length>E,T=Math.max(...c.map(A=>A.value),1),S=28,u=120,R=6,I=12,N=c.length*(S+R)+I*2;return i.jsxs("div",{style:{padding:"8px 0"},children:[i.jsx("svg",{width:"100%",height:N,viewBox:`0 0 600 ${N}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:c.map((A,p)=>{const O=I+p*(S+R),h=600-u-84,C=Math.max(A.value/T*h,2),_=o===p;return i.jsxs("g",{onMouseEnter:()=>s(p),onMouseLeave:()=>s(null),style:{cursor:"default"},children:[i.jsx("text",{x:u-8,y:O+S/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:A.label.length>16?A.label.slice(0,15)+"…":A.label}),i.jsx("rect",{x:u,y:O,width:C,height:S,rx:3,fill:_?r.accentHover:r.accent,style:{transition:"fill 0.15s"}}),i.jsx("text",{x:u+C+6,y:O+S/2+4,textAnchor:"start",fontSize:11,fontFamily:r.fontMono,fill:r.textMuted,children:ye(A.value)})]},p)})}),d&&i.jsxs("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,fontStyle:"italic",padding:"4px 12px"},children:["Showing ",Ht," of ",e.rows.length," rows"]})]})}function iR({result:e,themeMode:t,chartConfig:n}){const r=le[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),E=e.columns.filter(A=>A!==a&&l.some(p=>mt(p[A])));if(E.length===0)return i.jsx(Li,{result:e,themeMode:t,chartConfig:n});const c=e.rows.slice(0,Ht).map(A=>String(A[a]??"")),d=Math.max(...e.rows.slice(0,Ht).flatMap(A=>E.map(p=>Math.abs(Number(A[p]??0)))),1),T=24,S=T/E.length,u=120,R=12,I=8,N=c.length*(T+I)+R*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:E.map((A,p)=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[i.jsx("div",{style:{width:10,height:10,borderRadius:2,background:Pe[p%Pe.length]}}),i.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:A})]},A))}),i.jsx("svg",{width:"100%",height:N,viewBox:`0 0 600 ${N}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:c.map((A,p)=>{const O=R+p*(T+I),h=e.rows[p];return i.jsxs("g",{children:[i.jsx("text",{x:u-8,y:O+T/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:A.length>16?A.slice(0,15)+"…":A}),E.map((C,_)=>{const m=Number(h[C]??0),M=600-u-60,y=Math.max(Math.abs(m)/d*M,1),b=O+_*S,g=`${p}-${_}`;return i.jsxs("g",{onMouseEnter:()=>s(g),onMouseLeave:()=>s(null),children:[i.jsx("rect",{x:u,y:b,width:y,height:S-1,rx:2,fill:Pe[_%Pe.length],opacity:o===g?1:.85,style:{transition:"opacity 0.15s"}}),o===g&&i.jsx("text",{x:u+y+4,y:b+S/2+3,fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:ye(m)})]},_)})]},p)})})]})}function aR({result:e,themeMode:t,chartConfig:n}){const r=le[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),E=e.columns.filter(A=>A!==a&&l.some(p=>mt(p[A])));if(E.length===0)return i.jsx(Li,{result:e,themeMode:t,chartConfig:n});const c=e.rows.slice(0,Ht),d=c.map(A=>String(A[a]??"")),T=Math.max(...c.map(A=>E.reduce((p,O)=>p+Math.abs(Number(A[O]??0)),0)),1),S=28,u=120,R=12,I=6,N=d.length*(S+I)+R*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:E.map((A,p)=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[i.jsx("div",{style:{width:10,height:10,borderRadius:2,background:Pe[p%Pe.length]}}),i.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:A})]},A))}),i.jsx("svg",{width:"100%",height:N,viewBox:`0 0 600 ${N}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:d.map((A,p)=>{const O=R+p*(S+I),h=c[p],C=600-u-60;let _=u;return i.jsxs("g",{children:[i.jsx("text",{x:u-8,y:O+S/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:A.length>16?A.slice(0,15)+"…":A}),E.map((m,M)=>{const y=Math.abs(Number(h[m]??0)),b=Math.max(y/T*C,0),g=_;_+=b;const x=`${p}-${M}`;return i.jsxs("g",{onMouseEnter:()=>s(x),onMouseLeave:()=>s(null),children:[i.jsx("rect",{x:g,y:O,width:b,height:S,rx:M===0?3:0,fill:Pe[M%Pe.length],opacity:o===x?1:.85,style:{transition:"opacity 0.15s"}}),o===x&&b>30&&i.jsx("text",{x:g+b/2,y:O+S/2+4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:"#fff",fontWeight:600,children:ye(y)})]},M)})]},p)})})]})}function Ra({result:e,themeMode:t,showArea:n}){const r=le[t],[o,s]=f.useState(null),a=e.columns[0],l=e.columns[1],E=e.rows.map(L=>({label:String(L[a]??""),value:Number(L[l]??0)}));if(E.length<2)return null;const c=560,d=200,T=52,S=16,u=16,R=36,I=c-T-S,N=d-u-R,A=Math.min(...E.map(L=>L.value)),O=Math.max(...E.map(L=>L.value))-A||1,h=I/(E.length-1),C=L=>T+L*h,_=L=>u+N-(L-A)/O*N,m=E.map((L,P)=>({x:C(P),y:_(L.value)})),M=m.reduce((L,P,D)=>{if(D===0)return`M ${P.x},${P.y}`;const B=m[D-1],v=B.x+(P.x-B.x)/2;return`${L} C ${v},${B.y} ${v},${P.y} ${P.x},${P.y}`},""),y=`${M} L ${m[m.length-1].x},${u+N} L ${T},${u+N} Z`,b=5,g=Array.from({length:b+1},(L,P)=>{const D=A+O*P/b;return{val:D,y:_(D)}}),x=Math.ceil(E.length/8),F=E.filter((L,P)=>P%x===0||P===E.length-1);return i.jsx("div",{style:{position:"relative",padding:"8px 0"},children:i.jsxs("svg",{width:"100%",height:d,viewBox:`0 0 ${c} ${d}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},onMouseLeave:()=>s(null),children:[g.map((L,P)=>i.jsxs("g",{children:[i.jsx("line",{x1:T,y1:L.y,x2:T+I,y2:L.y,stroke:r.tableBorder,strokeWidth:.5}),i.jsx("text",{x:T-6,y:L.y+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:ye(L.val)})]},P)),i.jsx("path",{d:y,fill:r.accent,opacity:n?.3:.15}),i.jsx("path",{d:M,fill:"none",stroke:r.accent,strokeWidth:2,strokeLinejoin:"round"}),m.map((L,P)=>i.jsx("circle",{cx:L.x,cy:L.y,r:3,fill:r.accent,style:{cursor:"crosshair"},onMouseEnter:()=>s({x:L.x,y:L.y,label:E[P].label,value:E[P].value})},P)),F.map((L,P)=>{const D=E.indexOf(L);return i.jsx("text",{x:C(D),y:u+N+16,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:sR(L.label)},P)}),i.jsx("line",{x1:T,y1:u,x2:T,y2:u+N,stroke:r.tableBorder,strokeWidth:1}),i.jsx("line",{x1:T,y1:u+N,x2:T+I,y2:u+N,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:ye(o.value)})]})]})})}function lR({result:e,themeMode:t,chartConfig:n}){const r=le[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],E=n!=null&&n.color&&e.columns.includes(n.color)?n.color:void 0,c=e.rows.slice(0,200).map(g=>({x:Number(g[a]??0),y:Number(g[l]??0),color:E?String(g[E]??""):void 0})),d=560,T=300,S=52,u=16,R=16,I=36,N=d-S-u,A=T-R-I,p=Math.min(...c.map(g=>g.x)),O=Math.max(...c.map(g=>g.x)),h=Math.min(...c.map(g=>g.y)),C=Math.max(...c.map(g=>g.y)),_=O-p||1,m=C-h||1,M=g=>S+(g-p)/_*N,y=g=>R+A-(g-h)/m*A,b=E?[...new Set(c.map(g=>g.color))]:[];return i.jsxs("div",{style:{padding:"8px 0"},children:[E&&b.length>0&&i.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:b.slice(0,12).map((g,x)=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[i.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:Pe[x%Pe.length]}}),i.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:g})]},g))}),i.jsxs("svg",{width:"100%",height:T,viewBox:`0 0 ${d} ${T}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:6},(g,x)=>{const F=h+m*x/5,L=y(F);return i.jsxs("g",{children:[i.jsx("line",{x1:S,y1:L,x2:S+N,y2:L,stroke:r.tableBorder,strokeWidth:.5}),i.jsx("text",{x:S-6,y:L+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:ye(F)})]},x)}),Array.from({length:6},(g,x)=>{const F=p+_*x/5,L=M(F);return i.jsx("text",{x:L,y:R+A+16,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:ye(F)},x)}),i.jsx("line",{x1:S,y1:R,x2:S,y2:R+A,stroke:r.tableBorder,strokeWidth:1}),i.jsx("line",{x1:S,y1:R+A,x2:S+N,y2:R+A,stroke:r.tableBorder,strokeWidth:1}),i.jsx("text",{x:S+N/2,y:T-2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:a}),i.jsx("text",{x:10,y:R+A/2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,transform:`rotate(-90, 10, ${R+A/2})`,children:l}),c.map((g,x)=>{const F=E?b.indexOf(g.color):0;return i.jsx("circle",{cx:M(g.x),cy:y(g.y),r:o===x?5:3.5,fill:Pe[F%Pe.length],opacity:o===x?1:.7,style:{cursor:"crosshair",transition:"r 0.1s, opacity 0.1s"},onMouseEnter:()=>s(x),onMouseLeave:()=>s(null)},x)}),o!==null&&i.jsxs("g",{children:[i.jsx("rect",{x:M(c[o].x)+8,y:y(c[o].y)-24,width:100,height:28,rx:4,fill:r.cellBg,stroke:r.cellBorder,strokeWidth:1}),i.jsxs("text",{x:M(c[o].x)+13,y:y(c[o].y)-8,fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:["(",ye(c[o].x),", ",ye(c[o].y),")"]})]})]})]})}const ER=12;function Aa({result:e,themeMode:t,chartConfig:n,isDonut:r}){const o=le[t],[s,a]=f.useState(null),{labelCol:l,valueCol:E}=_o(e,n),c=e.rows.slice(0,ER).map(p=>({label:String(p[l]??""),value:Math.abs(Number(p[E]??0))})),d=c.reduce((p,O)=>p+O.value,0)||1,T=90,S=90,u=70,R=r?40:0,I=[];let N=-Math.PI/2;c.forEach((p,O)=>{const h=p.value/d*2*Math.PI,C=N,_=N+h,m=T+u*Math.cos(C),M=S+u*Math.sin(C),y=T+u*Math.cos(_),b=S+u*Math.sin(_),g=h>Math.PI?1:0;let x;if(R>0){const F=T+R*Math.cos(C),L=S+R*Math.sin(C),P=T+R*Math.cos(_),D=S+R*Math.sin(_);x=`M ${m} ${M} A ${u} ${u} 0 ${g} 1 ${y} ${b} L ${P} ${D} A ${R} ${R} 0 ${g} 0 ${F} ${L} Z`}else x=`M ${T} ${S} L ${m} ${M} A ${u} ${u} 0 ${g} 1 ${y} ${b} Z`;I.push({path:x,color:Pe[O%Pe.length],label:p.label,value:p.value,pct:p.value/d*100}),N=_});const A=s!==null?I[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:[I.map((p,O)=>i.jsx("path",{d:p.path,fill:p.color,opacity:s===null||s===O?1:.55,style:{cursor:"pointer",transition:"opacity 0.15s"},onMouseEnter:()=>a(O)},O)),r&&i.jsxs(i.Fragment,{children:[i.jsx("text",{x:T,y:S-5,textAnchor:"middle",fontSize:11,fontFamily:o.fontMono,fill:o.textSecondary,children:ye(A?A.value:d)}),i.jsx("text",{x:T,y:S+9,textAnchor:"middle",fontSize:9,fontFamily:o.font,fill:o.textMuted,children:A?`${A.pct.toFixed(1)}%`:"total"})]})]}),i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4,maxHeight:180,overflowY:"auto",flex:1},children:I.map((p,O)=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,cursor:"default",opacity:s===null||s===O?1:.5},onMouseEnter:()=>a(O),onMouseLeave:()=>a(null),children:[i.jsx("div",{style:{width:10,height:10,borderRadius:2,background:p.color,flexShrink:0}}),i.jsx("span",{style:{fontSize:11,fontFamily:o.font,color:o.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:p.label}),i.jsxs("span",{style:{fontSize:11,fontFamily:o.fontMono,color:o.textMuted,marginLeft:"auto",flexShrink:0},children:[p.pct.toFixed(1),"%"]})]},O))})]})}function cR({result:e,themeMode:t}){const n=le[t],[r,o]=f.useState(null),s=e.columns[0],a=e.columns.slice(1),l=e.rows.slice(0,30),E=l.flatMap(N=>a.map(A=>Number(N[A]??0))),c=Math.min(...E),T=Math.max(...E)-c||1,S=Math.min(50,480/a.length),u=24,R=100;function I(N){const A=(N-c)/T,p=Math.round(56+A*192),O=Math.round(139+A*-58),h=Math.round(253+A*-180);return`rgb(${p},${O},${h})`}return i.jsx("div",{style:{padding:"8px 0",overflowX:"auto"},children:i.jsxs("svg",{width:R+a.length*S+20,height:l.length*u+u+16,style:{display:"block",overflow:"visible"},children:[a.map((N,A)=>i.jsx("text",{x:R+A*S+S/2,y:14,textAnchor:"middle",fontSize:9,fontFamily:n.font,fill:n.textMuted,transform:`rotate(-30, ${R+A*S+S/2}, 14)`,children:N.length>8?N.slice(0,7)+"…":N},A)),l.map((N,A)=>{const p=String(N[s]??""),O=u+A*u;return i.jsxs("g",{children:[i.jsx("text",{x:R-6,y:O+u/2+4,textAnchor:"end",fontSize:10,fontFamily:n.font,fill:n.textSecondary,children:p.length>14?p.slice(0,13)+"…":p}),a.map((h,C)=>{const _=Number(N[h]??0),m=(r==null?void 0:r.r)===A&&(r==null?void 0:r.c)===C;return i.jsxs("g",{onMouseEnter:()=>o({r:A,c:C}),onMouseLeave:()=>o(null),children:[i.jsx("rect",{x:R+C*S,y:O,width:S-1,height:u-1,rx:2,fill:I(_),opacity:m?1:.85,stroke:m?n.accent:"none",strokeWidth:m?1.5:0}),m&&i.jsx("text",{x:R+C*S+S/2,y:O+u/2+4,textAnchor:"middle",fontSize:10,fontFamily:n.fontMono,fill:"#fff",fontWeight:600,children:ye(_)})]},C)})]},A)})]})})}function TR({result:e,themeMode:t,chartConfig:n}){const r=le[t],[o,s]=f.useState(null),a=(n!=null&&n.x&&e.columns.includes(n.x)?n.x:void 0)??e.columns.find(M=>e.rows.slice(0,5).some(y=>mt(y[M])))??e.columns[0],l=e.rows.map(M=>Number(M[a]??0)).filter(M=>!isNaN(M));if(l.length===0)return null;const E=Math.min(20,Math.max(5,Math.ceil(Math.sqrt(l.length)))),c=Math.min(...l),S=(Math.max(...l)-c||1)/E,u=Array.from({length:E},(M,y)=>({low:c+y*S,high:c+(y+1)*S,count:0}));l.forEach(M=>{const y=Math.min(Math.floor((M-c)/S),E-1);u[y].count++});const R=Math.max(...u.map(M=>M.count),1),I=560,N=200,A=52,p=16,O=16,h=36,C=I-A-p,_=N-O-h,m=C/E;return i.jsx("div",{style:{padding:"8px 0"},children:i.jsxs("svg",{width:"100%",height:N,viewBox:`0 0 ${I} ${N}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:5},(M,y)=>{const b=R*(y+1)/5,g=O+_-b/R*_;return i.jsxs("g",{children:[i.jsx("line",{x1:A,y1:g,x2:A+C,y2:g,stroke:r.tableBorder,strokeWidth:.5}),i.jsx("text",{x:A-6,y:g+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Math.round(b)})]},y)}),u.map((M,y)=>{const b=M.count/R*_,g=A+y*m,x=O+_-b,F=o===y;return i.jsxs("g",{onMouseEnter:()=>s(y),onMouseLeave:()=>s(null),children:[i.jsx("rect",{x:g+1,y:x,width:m-2,height:b,rx:1,fill:F?r.accentHover:r.accent,opacity:F?1:.85,style:{transition:"fill 0.1s"}}),F&&i.jsx("text",{x:g+m/2,y:x-4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:M.count})]},y)}),u.filter((M,y)=>y%Math.ceil(E/6)===0).map((M,y)=>{const b=u.indexOf(M);return i.jsx("text",{x:A+b*m+m/2,y:O+_+16,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:ye(M.low)},y)}),i.jsx("line",{x1:A,y1:O,x2:A,y2:O+_,stroke:r.tableBorder,strokeWidth:1}),i.jsx("line",{x1:A,y1:O+_,x2:A+C,y2:O+_,stroke:r.tableBorder,strokeWidth:1}),i.jsx("text",{x:A+C/2,y:N-2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:a})]})})}function dR({result:e,themeMode:t,chartConfig:n}){const r=le[t],[o,s]=f.useState(null),{labelCol:a,valueCol:l}=_o(e,n),E=e.rows.slice(0,10).map(N=>({label:String(N[a]??""),value:Math.abs(Number(N[l]??0))}));if(E.length===0)return null;const c=E[0].value||1,d=400,T=36,S=4,u=16,R=E.length*(T+S)+u*2,I=d/2;return i.jsx("div",{style:{padding:"8px 0",display:"flex",justifyContent:"center"},children:i.jsx("svg",{width:d,height:R,style:{display:"block"},children:E.map((N,A)=>{const p=u+A*(T+S),O=N.value/c,h=Math.max(O*(d-80),40),C=o===A,_=A<E.length-1?E[A+1].value/c:O*.8,m=Math.max(_*(d-80),40),M=I-h/2,y=I+h/2,b=I+m/2,g=I-m/2,x=`M ${M} ${p} L ${y} ${p} L ${b} ${p+T} L ${g} ${p+T} Z`;return i.jsxs("g",{onMouseEnter:()=>s(A),onMouseLeave:()=>s(null),style:{cursor:"default"},children:[i.jsx("path",{d:x,fill:Pe[A%Pe.length],opacity:C?1:.85,style:{transition:"opacity 0.15s"}}),i.jsx("text",{x:I,y:p+T/2+1,textAnchor:"middle",fontSize:11,fontFamily:r.font,fill:"#fff",fontWeight:500,children:N.label}),i.jsxs("text",{x:I,y:p+T/2+13,textAnchor:"middle",fontSize:9,fontFamily:r.fontMono,fill:"rgba(255,255,255,0.7)",children:[ye(N.value)," (",(O*100).toFixed(0),"%)"]})]},A)})})})}function SR({result:e,themeMode:t,chartConfig:n}){const r=le[t],[o,s]=f.useState(null),{labelCol:a,valueCol:l}=_o(e,n),E=e.rows.slice(0,15).map(y=>({label:String(y[a]??""),value:Number(y[l]??0)}));if(E.length===0)return null;let c=0;const d=E.map(y=>{const b=c;return c+=y.value,{...y,start:b,end:c}}),T=d.flatMap(y=>[y.start,y.end]),S=Math.min(0,...T),R=Math.max(0,...T)-S||1,I=560,N=240,A=52,p=16,O=16,h=44,C=I-A-p,_=N-O-h,m=C/d.length,M=y=>O+_-(y-S)/R*_;return i.jsx("div",{style:{padding:"8px 0"},children:i.jsxs("svg",{width:"100%",height:N,viewBox:`0 0 ${I} ${N}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:6},(y,b)=>{const g=S+R*b/5,x=M(g);return i.jsxs("g",{children:[i.jsx("line",{x1:A,y1:x,x2:A+C,y2:x,stroke:r.tableBorder,strokeWidth:.5}),i.jsx("text",{x:A-6,y:x+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:ye(g)})]},b)}),i.jsx("line",{x1:A,y1:M(0),x2:A+C,y2:M(0),stroke:r.textMuted,strokeWidth:1,strokeDasharray:"3,3"}),d.map((y,b)=>{const g=A+b*m,x=M(Math.max(y.start,y.end)),L=M(Math.min(y.start,y.end))-x,P=y.value>=0,D=o===b;return i.jsxs("g",{onMouseEnter:()=>s(b),onMouseLeave:()=>s(null),children:[b<d.length-1&&i.jsx("line",{x1:g+m-2,y1:M(y.end),x2:g+m+2,y2:M(y.end),stroke:r.textMuted,strokeWidth:1,strokeDasharray:"2,2"}),i.jsx("rect",{x:g+4,y:x,width:m-8,height:Math.max(L,1),rx:2,fill:P?r.success:r.error,opacity:D?1:.8,style:{transition:"opacity 0.1s"}}),D&&i.jsxs("text",{x:g+m/2,y:x-4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:[y.value>=0?"+":"",ye(y.value)]})]},b)}),d.map((y,b)=>i.jsx("text",{x:A+b*m+m/2,y:N-6,textAnchor:"middle",fontSize:9,fontFamily:r.font,fill:r.textMuted,transform:`rotate(-20, ${A+b*m+m/2}, ${N-6})`,children:y.label.length>8?y.label.slice(0,7)+"…":y.label},b)),i.jsx("line",{x1:A,y1:O,x2:A,y2:O+_,stroke:r.tableBorder,strokeWidth:1}),i.jsx("line",{x1:A,y1:O+_,x2:A+C,y2:O+_,stroke:r.tableBorder,strokeWidth:1})]})})}function uR({result:e,themeMode:t,chartConfig:n}){const r=le[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(M=>mt(o[M]))??e.columns[0],a=Number(o[s]??0),l=(n==null?void 0:n.title)??s,E=a>100?a*1.2:100,c=Math.min(Math.max(a/E,0),1),d=120,T=110,S=80,u=Math.PI,R=0,I=u-(u-R)*c,N=d+S*Math.cos(u),A=T+S*Math.sin(u),p=d+S*Math.cos(I),O=T+S*Math.sin(I),h=c>.5?1:0,C=d+S*Math.cos(R),_=T+S*Math.sin(R),m=c<.33?r.error:c<.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 ${N} ${A} A ${S} ${S} 0 1 1 ${C} ${_}`,fill:"none",stroke:r.tableBorder,strokeWidth:12,strokeLinecap:"round"}),c>0&&i.jsx("path",{d:`M ${N} ${A} A ${S} ${S} 0 ${h} 1 ${p} ${O}`,fill:"none",stroke:m,strokeWidth:12,strokeLinecap:"round"}),i.jsx("text",{x:d,y:T-4,textAnchor:"middle",fontSize:28,fontFamily:r.fontMono,fill:m,fontWeight:700,children:ye(a)}),i.jsx("text",{x:d,y:T+16,textAnchor:"middle",fontSize:11,fontFamily:r.font,fill:r.textMuted,children:l})]})})}function tc({result:e,themeMode:t,chartConfig:n}){const r=le[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=>mt(o[d]))??e.columns[0],a=o[s],l=Number(a),E=isNaN(l)?String(a):l.toLocaleString(void 0,{maximumFractionDigits:2}),c=(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:E}),i.jsx("span",{style:{fontSize:13,fontFamily:r.font,color:r.textMuted,textTransform:"uppercase",letterSpacing:"0.08em",fontWeight:500},children:c})]})}function RR({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(ec).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??Ht,min:5,max:200,onChange:a=>n({maxItems:parseInt(a.target.value)||Ht}),style:{...s,marginTop:2}})]})]})}function AR({result:e,themeMode:t,chartConfig:n,onConfigChange:r}){const o=le[t],s=Hn(e,n),[a,l]=f.useState(!1);return s==="kpi"?i.jsx(tc,{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(RR,{config:n??{},columns:e.columns,onChange:E=>r(E),onClose:()=>l(!1),t:o}),_i(s,e,t,n)]})}function _i(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?IR(t,o,s):t;switch(e){case"line":return i.jsx(Ra,{result:a,themeMode:n});case"area":return i.jsx(Ra,{result:a,themeMode:n,showArea:!0});case"bar":return i.jsx(Li,{result:a,themeMode:n,chartConfig:r});case"grouped-bar":return i.jsx(iR,{result:a,themeMode:n,chartConfig:r});case"stacked-bar":return i.jsx(aR,{result:a,themeMode:n,chartConfig:r});case"scatter":return i.jsx(lR,{result:t,themeMode:n,chartConfig:r});case"pie":return i.jsx(Aa,{result:t,themeMode:n,chartConfig:r,isDonut:!1});case"donut":return i.jsx(Aa,{result:t,themeMode:n,chartConfig:r,isDonut:!0});case"heatmap":return i.jsx(cR,{result:t,themeMode:n});case"histogram":return i.jsx(TR,{result:t,themeMode:n,chartConfig:r});case"funnel":return i.jsx(dR,{result:t,themeMode:n,chartConfig:r});case"waterfall":return i.jsx(SR,{result:t,themeMode:n,chartConfig:r});case"gauge":return i.jsx(uR,{result:t,themeMode:n,chartConfig:r});case"kpi":return i.jsx(tc,{result:t,themeMode:n,chartConfig:r});default:return i.jsx(Lo,{result:t,themeMode:n})}}function IR(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 kr({label:e,count:t,t:n}){return i.jsxs("div",{style:{padding:"8px 10px 4px",fontSize:10,fontWeight:700,color:n.textMuted,fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.05em"},children:[e,typeof t=="number"?` · ${t}`:""]})}const NR=[{id:"dbt",label:"dbt",color:"#ff694a",desc:"Import semantic models, metrics, and dimensions"},{id:"cubejs",label:"Cube.js",color:"#7a77ff",desc:"Import cubes, measures, joins, and pre-aggregations"},{id:"snowflake",label:"Snowflake",color:"#29b5e8",desc:"Introspect semantic views for metrics and dimensions"}];function fR({t:e,provider:t,errors:n,onOpenWizard:r,onRefresh:o}){return i.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"14px",fontFamily:e.font},children:[i.jsx("div",{style:{fontSize:13,fontWeight:600,color:e.textPrimary,marginBottom:4},children:"Connect your Semantic Layer"}),i.jsx("div",{style:{fontSize:12,color:e.textMuted,lineHeight:1.5,marginBottom:14},children:"Import metrics and dimensions from your existing data stack to build certified DQL blocks."}),i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:14},children:NR.map(s=>{const a=t===s.id;return i.jsxs("button",{onClick:r,style:{background:e.inputBg,border:`1px solid ${a?s.color:e.cellBorder}`,borderRadius:8,padding:"10px 12px",cursor:"pointer",textAlign:"left",display:"flex",alignItems:"center",gap:10,transition:"border-color 0.15s"},children:[i.jsx("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:s.color,flexShrink:0}}),i.jsxs("div",{style:{flex:1},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsx("span",{style:{fontSize:12,fontWeight:600,color:e.textPrimary,fontFamily:e.font},children:s.label}),a&&i.jsx("span",{style:{fontSize:9,fontWeight:600,color:s.color,fontFamily:e.font,background:`${s.color}18`,padding:"1px 6px",borderRadius:6},children:"Detected"})]}),i.jsx("span",{style:{fontSize:11,color:e.textMuted,fontFamily:e.font},children:s.desc})]})]},s.id)})}),n&&n.length>0&&i.jsx("div",{style:{background:`${e.error}12`,border:`1px solid ${e.error}40`,borderRadius:8,padding:"8px 12px",marginBottom:12},children:n.map((s,a)=>i.jsx("div",{style:{fontSize:11,color:e.error,fontFamily:e.font,lineHeight:1.4},children:s},a))}),i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsx("button",{onClick:r,style:{background:e.accent,border:"none",borderRadius:6,color:"#fff",cursor:"pointer",fontSize:12,fontFamily:e.font,fontWeight:500,padding:"7px 16px"},children:"Setup Wizard"}),i.jsx("button",{onClick:o,style:{background:"transparent",border:`1px solid ${e.cellBorder}`,borderRadius:6,color:e.textSecondary,cursor:"pointer",fontSize:12,fontFamily:e.font,padding:"7px 14px"},children:"Refresh"})]})]})}function pR({t:e,semanticLayer:t,onClose:n,onSaved:r}){const[o,s]=f.useState(1),[a,l]=f.useState("new_semantic_block"),[E,c]=f.useState(""),[d,T]=f.useState(""),[S,u]=f.useState(""),[R,I]=f.useState(""),[N,A]=f.useState("table"),[p,O]=f.useState("semantic"),[h,C]=f.useState([]),[_,m]=f.useState([]),[M,y]=f.useState(""),[b,g]=f.useState("month"),[x,F]=f.useState(null),[L,P]=f.useState(null),[D,B]=f.useState(!1),[v,U]=f.useState(!1),[Y,W]=f.useState(!1),[k,w]=f.useState(t.dimensions);f.useEffect(()=>{let V=!1;if(h.length===0){w(t.dimensions);return}return U(!0),te.getCompatibleDimensions(h).then(ee=>{V||w(ee)}).finally(()=>{V||U(!1)}),()=>{V=!0}},[h,t.dimensions]);const z=k.filter(V=>V.type==="date"),q=k.filter(V=>V.type!=="date"),Z=(V,ee,ne)=>{ne(oe=>oe.includes(V)?oe.filter(Te=>Te!==V):[...oe,V])},K={width:"100%",background:e.inputBg,border:`1px solid ${e.inputBorder}`,borderRadius:6,color:e.textPrimary,fontSize:12,fontFamily:e.font,padding:"7px 10px",outline:"none",boxSizing:"border-box"},H=async()=>{if(h.length===0){P("Select at least one metric.");return}B(!0),P(null);const V=await te.previewSemanticBuilder({metrics:h,dimensions:_,timeDimension:M?{name:M,granularity:b}:void 0});if(B(!1),"error"in V){P(V.error);return}if(F(V),V.result&&V.result.columns&&V.result.rows){const ee=ZE(V.result);ee!=="table"&&A(ee)}s(3)},J=async()=>{if(!a.trim()){P("Block name is required.");return}W(!0),P(null);try{const V=await te.saveSemanticBuilder({name:a.trim(),domain:E.trim()||void 0,description:d.trim()||void 0,owner:S.trim()||void 0,tags:R.split(",").map(ee=>ee.trim()).filter(Boolean),metrics:h,dimensions:_,timeDimension:M?{name:M,granularity:b}:void 0,chart:N,blockType:p});r(V),n()}catch(V){P(V instanceof Error?V.message:String(V))}finally{W(!1)}};return i.jsxs("div",{style:{position:"absolute",inset:0,zIndex:200,background:`${e.sidebarBg}f4`,display:"flex",flexDirection:"column"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",borderBottom:`1px solid ${e.headerBorder}`},children:[i.jsx("div",{style:{fontSize:12,fontWeight:600,color:e.textPrimary,fontFamily:e.font},children:"Guided Block Builder"}),i.jsx("button",{onClick:n,style:{background:"transparent",border:"none",color:e.textMuted,cursor:"pointer",fontSize:16},children:"×"})]}),i.jsx("div",{style:{display:"flex",gap:8,padding:"8px 12px",borderBottom:`1px solid ${e.headerBorder}`},children:[1,2,3,4].map(V=>i.jsxs("div",{style:{flex:1,textAlign:"center",padding:"6px 0",borderRadius:6,background:o===V?`${e.accent}18`:e.pillBg,color:o===V?e.accent:e.textMuted,fontSize:10,fontFamily:e.font,fontWeight:600},children:["Step ",V]},V))}),i.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"12px",display:"grid",gap:12},children:[o===1&&i.jsxs(i.Fragment,{children:[i.jsx(kr,{label:"Choose Metrics",count:h.length,t:e}),i.jsx("div",{style:{display:"grid",gap:4,maxHeight:220,overflowY:"auto"},children:t.metrics.map(V=>i.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:e.textPrimary,fontFamily:e.font},children:[i.jsx("input",{type:"checkbox",checked:h.includes(V.name),onChange:()=>Z(V.name,h,C)}),i.jsx("span",{style:{flex:1},children:V.label||V.name}),i.jsx("span",{style:{color:e.textMuted,fontFamily:e.fontMono},children:V.domain||"uncategorized"})]},V.name))})]}),o===2&&i.jsxs(i.Fragment,{children:[i.jsx(kr,{label:"Dimensions",count:_.length,t:e}),v&&i.jsx("div",{style:{fontSize:11,color:e.textMuted,fontFamily:e.font},children:"Resolving compatible dimensions…"}),i.jsx("div",{style:{display:"grid",gap:4,maxHeight:180,overflowY:"auto"},children:q.map(V=>i.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:e.textPrimary,fontFamily:e.font},children:[i.jsx("input",{type:"checkbox",checked:_.includes(V.name),onChange:()=>Z(V.name,_,m)}),i.jsx("span",{style:{flex:1},children:V.label||V.name}),i.jsx("span",{style:{color:e.textMuted,fontFamily:e.fontMono},children:V.table})]},V.name))}),i.jsxs("div",{style:{display:"grid",gap:8},children:[i.jsx("div",{style:{fontSize:11,color:e.textSecondary,fontFamily:e.font},children:"Time grain"}),i.jsxs("select",{value:M,onChange:V=>y(V.target.value),style:K,children:[i.jsx("option",{value:"",children:"No time dimension"}),z.map(V=>i.jsx("option",{value:V.name,children:V.label||V.name},V.name))]}),M&&i.jsxs("select",{value:b,onChange:V=>g(V.target.value),style:K,children:[i.jsx("option",{value:"day",children:"day"}),i.jsx("option",{value:"week",children:"week"}),i.jsx("option",{value:"month",children:"month"}),i.jsx("option",{value:"quarter",children:"quarter"}),i.jsx("option",{value:"year",children:"year"})]})]})]}),o===3&&i.jsxs(i.Fragment,{children:[i.jsx(kr,{label:"Preview SQL",t:e}),x&&i.jsxs(i.Fragment,{children:[i.jsx("pre",{style:{margin:0,padding:"10px",background:e.editorBg,border:`1px solid ${e.cellBorder}`,borderRadius:6,fontSize:10,color:e.textSecondary,fontFamily:e.fontMono,whiteSpace:"pre-wrap"},children:x.sql}),i.jsxs("div",{style:{fontSize:11,color:e.textMuted,fontFamily:e.font},children:[x.tables.length," table(s) · ",x.result.rowCount??x.result.rows.length," row(s)"]})]})]}),o===4&&i.jsx(i.Fragment,{children:i.jsxs("div",{style:{display:"grid",gap:8},children:[i.jsx("input",{value:a,onChange:V=>l(V.target.value),style:K,placeholder:"Block name"}),i.jsx("input",{value:E,onChange:V=>c(V.target.value),style:K,placeholder:"Domain"}),i.jsx("input",{value:d,onChange:V=>T(V.target.value),style:K,placeholder:"Description"}),i.jsx("input",{value:S,onChange:V=>u(V.target.value),style:K,placeholder:"Owner"}),i.jsx("input",{value:R,onChange:V=>I(V.target.value),style:K,placeholder:"Tags (comma separated)"}),i.jsxs("div",{children:[i.jsxs("select",{value:N,onChange:V=>A(V.target.value),style:K,children:[i.jsx("option",{value:"table",children:"table"}),i.jsx("option",{value:"bar",children:"bar"}),i.jsx("option",{value:"line",children:"line"}),i.jsx("option",{value:"scatter",children:"scatter"}),i.jsx("option",{value:"pie",children:"pie"}),i.jsx("option",{value:"area",children:"area"}),i.jsx("option",{value:"kpi",children:"kpi"}),i.jsx("option",{value:"heatmap",children:"heatmap"}),i.jsx("option",{value:"funnel",children:"funnel"}),i.jsx("option",{value:"gauge",children:"gauge"})]}),(x==null?void 0:x.result)&&N!=="table"&&i.jsx("div",{style:{fontSize:10,color:e.accent,fontFamily:e.font,marginTop:2},children:"Suggested based on result shape"})]}),i.jsxs("select",{value:p,onChange:V=>O(V.target.value),style:K,children:[i.jsx("option",{value:"semantic",children:"semantic block"}),i.jsx("option",{value:"custom",children:"custom block"})]})]})}),L&&i.jsx("div",{style:{color:e.error,fontSize:11,fontFamily:e.font},children:L})]}),i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"10px 12px",borderTop:`1px solid ${e.headerBorder}`},children:[i.jsx("button",{onClick:()=>s(V=>Math.max(1,V-1)),disabled:o===1,style:{background:e.btnBg,border:`1px solid ${e.btnBorder}`,borderRadius:6,color:e.textSecondary,cursor:"pointer",fontSize:11,fontFamily:e.font,padding:"6px 12px"},children:"Back"}),i.jsxs("div",{style:{display:"flex",gap:8},children:[o<2&&i.jsx("button",{onClick:()=>s(2),style:{background:e.accent,border:"none",borderRadius:6,color:"#fff",cursor:"pointer",fontSize:11,fontFamily:e.font,padding:"6px 12px"},children:"Next"}),o===2&&i.jsx("button",{onClick:()=>void H(),disabled:D,style:{background:e.accent,border:"none",borderRadius:6,color:"#fff",cursor:"pointer",fontSize:11,fontFamily:e.font,padding:"6px 12px"},children:D?"Previewing…":"Preview"}),o===3&&i.jsx("button",{onClick:()=>s(4),style:{background:e.accent,border:"none",borderRadius:6,color:"#fff",cursor:"pointer",fontSize:11,fontFamily:e.font,padding:"6px 12px"},children:"Continue"}),o===4&&i.jsx("button",{onClick:()=>void J(),disabled:Y,style:{background:e.accent,border:"none",borderRadius:6,color:"#fff",cursor:"pointer",fontSize:11,fontFamily:e.font,padding:"6px 12px"},children:Y?"Saving…":"Save Block"})]})]})]})}const mr=31,Ia=10;function nc(e,t){var S,u,R,I,N,A;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"||((S=e.meta)==null?void 0:S.domain)===t.domain||e.kind==="domain"&&e.label===t.domain,l=!t.provider||((u=e.meta)==null?void 0:u.provider)===t.provider||e.kind==="provider"&&e.id===`provider:${t.provider}`,E=!t.cube||((R=e.meta)==null?void 0:R.cube)===t.cube||e.kind==="cube"&&(((I=e.meta)==null?void 0:I.cube)===t.cube||e.label===t.cube),c=!t.owner||((N=e.meta)==null?void 0:N.owner)===t.owner,d=!t.tag||String(((A=e.meta)==null?void 0:A.tags)??"").split(",").filter(Boolean).includes(t.tag),T=(e.children??[]).map(p=>nc(p,t)).filter(p=>!!p);return T.length>0?{...e,children:T,count:e.kind==="provider"||e.kind==="domain"||e.kind==="group"?T.length:e.count}:o&&s&&a&&l&&E&&c&&d?{...e,children:[]}:null}function rc(e){return!e.children||e.children.length===0?e.kind==="group"||e.kind==="provider"||e.kind==="domain"?0:1:e.children.reduce((t,n)=>t+rc(n),0)}function ns(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 oc(e,t,n=0){const r=[];for(const o of e){const s=!!(o.children&&o.children.length>0),a=t[o.id]??n<2;r.push({node:o,depth:n,hasChildren:s,isExpanded:a}),s&&a&&r.push(...oc(o.children??[],t,n+1))}return r}function hR(){const{state:e,dispatch:t}=Se(),n=le[e.themeMode],r=e.semanticLayer,[o,s]=f.useState(null),[a,l]=f.useState(null),[E,c]=f.useState(null),[d,T]=f.useState(!1),[S,u]=f.useState(""),[R,I]=f.useState(""),[N,A]=f.useState(""),[p,O]=f.useState(""),[h,C]=f.useState(""),[_,m]=f.useState(""),[M,y]=f.useState(""),[b,g]=f.useState({}),[x,F]=f.useState(!1),[L,P]=f.useState(!1),[D,B]=f.useState(!1),[v,U]=f.useState(new Set),[Y,W]=f.useState(new Set),[k,w]=f.useState(!1),[z,q]=f.useState(0),[Z,K]=f.useState(400),H=f.useRef(null),J=async()=>{t({type:"SET_SEMANTIC_LOADING",loading:!0});try{const[Q,Ee]=await Promise.all([te.getSemanticLayer(),te.getSemanticTree().catch(()=>null)]);t({type:"SET_SEMANTIC_LAYER",layer:Q}),s(Ee)}finally{t({type:"SET_SEMANTIC_LOADING",loading:!1})}};f.useEffect(()=>{(r.metrics.length===0&&r.dimensions.length===0&&!r.loading||!o)&&J()},[]),f.useEffect(()=>{if(!a){c(null);return}if(a.startsWith("provider:")||a.startsWith("domain:")||a.startsWith("group:")){c(null);return}te.getSemanticObject(a).then(c).catch(()=>c(null))},[a]);const V=f.useMemo(()=>o?nc(o,{query:S,provider:R,domain:N,cube:p,owner:h,tag:_,type:M}):null,[o,S,R,N,p,h,_,M]),ee=f.useMemo(()=>new Set(r.favorites),[r.favorites]),ne=f.useMemo(()=>new Map(r.metrics.map(Q=>[Q.name,Q])),[r.metrics]),oe=f.useMemo(()=>new Map(r.dimensions.map(Q=>[Q.name,Q])),[r.dimensions]),Te=f.useMemo(()=>ns(o,"provider"),[o]),Ie=f.useMemo(()=>ns(o,"cube"),[o]),de=f.useMemo(()=>ns(o,"owner"),[o]),Ne=f.useMemo(()=>oc((V==null?void 0:V.children)??[],b),[V,b]),Fe=Ne.length*mr,be=f.useMemo(()=>{const Q=Math.max(0,Math.floor(z/mr)-Ia),Ee=Math.min(Ne.length,Math.ceil((z+Z)/mr)+Ia);return{startIndex:Q,endIndex:Ee,offsetTop:Q*mr,rows:Ne.slice(Q,Ee)}},[Ne,z,Z]);f.useEffect(()=>{const Q=H.current;if(!Q)return;const Ee=()=>K(Q.clientHeight||400);if(Ee(),typeof ResizeObserver>"u")return window.addEventListener("resize",Ee),()=>window.removeEventListener("resize",Ee);const Re=new ResizeObserver(()=>Ee());return Re.observe(Q),()=>Re.disconnect()},[V]),f.useEffect(()=>{q(0),H.current&&(H.current.scrollTop=0)},[S,R,N,p,h,_,M]);const je=async Q=>{const Ee=Q.kind==="metric"?`@metric(${Q.name})`:`@dim(${Q.name})`;ni(Ee)||t({type:"ADD_CELL",cell:xe("sql",Ee)}),t({type:"ADD_SEMANTIC_RECENT",name:Q.name})},tt=(Q,Ee)=>{const Re=Q.kind==="metric"||Q.kind==="dimension"?Q.kind:null,Ae=Q.id.split(":").slice(1).join(":"),ft=Re==="metric"?v.has(Ae):Re==="dimension"?Y.has(Ae):!1;return i.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[D&&Re&&i.jsx("input",{type:"checkbox",checked:ft,onChange:()=>Ot(Re,Ae),style:{marginLeft:Ee*12+6,marginRight:-Ee*12-2,accentColor:n.accent,cursor:"pointer"}}),i.jsx(wn,{label:Q.label,depth:D&&Re?0:Ee,badge:Q.kind==="metric"||Q.kind==="dimension"||Q.kind==="segment"||Q.kind==="pre_aggregation"?Q.kind:void 0,selected:a===Q.id,onClick:()=>{D&&Re?Ot(Re,Ae):l(Q.id)},onDoubleClick:()=>{if(Q.kind==="metric"||Q.kind==="dimension"){const De=Q.kind==="metric"?ne.get(Q.id.slice(7)):oe.get(Q.id.slice(10));if(De){const pt=Q.kind==="metric"?`@metric(${De.name})`:`@dim(${De.name})`;ni(pt)||t({type:"ADD_CELL",cell:xe("sql",pt)})}}},onFavoriteToggle:Re?()=>void te.toggleFavorite(Ae).then(De=>t({type:"SET_SEMANTIC_FAVORITES",favorites:De})):void 0,favorite:Re?ee.has(Ae):void 0,onDragStart:Re?De=>{De.dataTransfer.effectAllowed="copy",De.dataTransfer.setData("text/plain",Ae),De.dataTransfer.setData("application/dql-semantic-ref",Ku(Re,Ae))}:void 0,t:n})]},Q.id)},Et=Q=>{var De;const{node:Ee,depth:Re,hasChildren:Ae,isExpanded:ft}=Q;return Ae?i.jsx("div",{children:i.jsx(wn,{label:Ee.label,depth:Re,count:(De=Ee.children)==null?void 0:De.length,expanded:ft,onToggle:()=>g(pt=>({...pt,[Ee.id]:!ft})),onClick:()=>l(Ee.id),selected:a===Ee.id,t:n})},Ee.id):tt(Ee,Re)},nt=async()=>{F(!0);try{await te.syncSemanticLayer(),await J()}finally{F(!1)}},Ot=(Q,Ee)=>{Q==="metric"?U(Re=>{const Ae=new Set(Re);return Ae.has(Ee)?Ae.delete(Ee):Ae.add(Ee),Ae}):W(Re=>{const Ae=new Set(Re);return Ae.has(Ee)?Ae.delete(Ee):Ae.add(Ee),Ae})},Ge=async()=>{if(v.size!==0){w(!0);try{const Q=await te.composeQuery(Array.from(v),Array.from(Y));if("error"in Q)return;t({type:"ADD_CELL",cell:xe("sql",Q.sql)}),B(!1),U(new Set),W(new Set)}finally{w(!1)}}},$e=()=>{var Q;if(((Q=e.activeFile)==null?void 0:Q.type)==="block"){te.openBlockStudio(e.activeFile.path).then(Ee=>{t({type:"OPEN_BLOCK_STUDIO",file:e.activeFile,payload:Ee})});return}t({type:"OPEN_NEW_BLOCK_MODAL"})};if(!r.available&&!r.loading)return i.jsxs(i.Fragment,{children:[i.jsx(fR,{t:n,provider:r.provider,errors:e.semanticLayer.errors,onOpenWizard:()=>P(!0),onRefresh:()=>void J()}),L&&i.jsx(Ju,{detectedProvider:r.provider,onClose:()=>P(!1),onImported:()=>void J()})]});const Ue=V?rc(V):0;return i.jsxs("div",{style:{flex:1,overflow:"hidden",display:"flex",flexDirection:"column",position:"relative"},children:[d&&i.jsx(pR,{t:n,semanticLayer:r,onClose:()=>T(!1),onSaved:Q=>{const Ee={name:Q.path.split("/").pop()??Q.path,path:Q.path,type:"block",folder:"blocks"};e.files.some(Re=>Re.path===Q.path)||t({type:"FILE_ADDED",file:Ee}),te.openBlockStudio(Q.path).then(Re=>{t({type:"OPEN_BLOCK_STUDIO",file:Ee,payload:Re})})}}),i.jsxs("div",{style:{padding:"8px 10px",display:"flex",alignItems:"center",gap:6,borderBottom:`1px solid ${n.headerBorder}`},children:[r.provider&&i.jsx("span",{style:{fontSize:9,fontWeight:600,color:n.accent,background:`${n.accent}18`,borderRadius:4,padding:"1px 5px",textTransform:"uppercase",letterSpacing:"0.04em"},children:r.provider}),i.jsxs("span",{style:{flex:1,fontSize:11,color:n.textMuted,fontFamily:n.font},children:[r.metrics.length," metrics · ",r.dimensions.length," dimensions",r.lastSyncTime?` · synced ${new Date(r.lastSyncTime).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`:""]}),i.jsx("button",{onClick:$e,style:{background:n.accent,border:"none",borderRadius:4,color:"#fff",cursor:"pointer",fontSize:10,fontWeight:600,fontFamily:n.font,padding:"2px 8px"},children:"Open Studio"}),i.jsx("button",{onClick:()=>T(!0),style:{background:"transparent",border:`1px solid ${n.cellBorder}`,borderRadius:4,color:n.textSecondary,cursor:"pointer",fontSize:10,fontFamily:n.font,padding:"2px 8px"},children:"Quick Build"}),i.jsx("button",{onClick:()=>{B(Q=>!Q),D&&(U(new Set),W(new Set))},style:{background:D?`${n.accent}20`:"transparent",border:`1px solid ${D?n.accent:n.cellBorder}`,borderRadius:4,color:D?n.accent:n.textSecondary,cursor:"pointer",fontSize:10,fontFamily:n.font,padding:"2px 8px"},children:D?"Cancel":"Select"}),i.jsx("button",{onClick:()=>void nt(),style:{background:"transparent",border:`1px solid ${n.cellBorder}`,borderRadius:4,color:n.textSecondary,cursor:"pointer",fontSize:10,fontFamily:n.font,padding:"2px 6px"},children:x?"Syncing…":"Sync"}),i.jsx("button",{onClick:()=>void J(),style:{background:"transparent",border:`1px solid ${n.cellBorder}`,borderRadius:4,color:n.textSecondary,cursor:"pointer",fontSize:10,fontFamily:n.font,padding:"2px 6px"},children:r.loading?"Loading…":"Refresh"})]}),i.jsxs("div",{style:{padding:"10px",borderBottom:`1px solid ${n.headerBorder}`,background:`${n.accent}0d`,display:"grid",gap:6},children:[i.jsx("div",{style:{fontSize:11,fontWeight:600,color:n.textPrimary,fontFamily:n.font},children:"Build blocks in Block Studio"}),i.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font,lineHeight:1.5},children:"Use the full-screen studio to author DQL with semantic metrics, database schemas, validation, results, and visualization in one workspace."})]}),i.jsx(KE,{query:S,provider:R,cube:p,owner:h,domain:N,tag:_,type:M,providers:Te,cubes:Ie,owners:de,domains:r.domains,tags:r.tags,onQueryChange:u,onProviderChange:I,onCubeChange:O,onOwnerChange:C,onDomainChange:A,onTagChange:m,onTypeChange:y,t:n}),i.jsx(kr,{label:"Semantic Tree",count:Ue,t:n}),i.jsx("div",{ref:H,onScroll:Q=>q(Q.currentTarget.scrollTop),style:{flex:1,overflowY:"auto"},children:i.jsx("div",{style:{height:Fe,position:"relative"},children:i.jsx("div",{style:{position:"absolute",top:be.offsetTop,left:0,right:0},children:be.rows.map(Q=>Et(Q))})})}),i.jsx(XE,{item:E,favorite:!!(E&&ee.has(E.name)),onInsert:()=>E&&(E.kind==="metric"||E.kind==="dimension")&&void je(E),onPreview:()=>{if(!(E!=null&&E.sql))return;const Q=E.kind==="cube"&&E.table?`SELECT * FROM ${E.table} LIMIT 25`:E.sql;t({type:"ADD_CELL",cell:xe("sql",Q)})},onCopySql:()=>{E!=null&&E.sql&&navigator.clipboard.writeText(E.sql)},onToggleFavorite:()=>{E&&(E.kind==="metric"||E.kind==="dimension")&&te.toggleFavorite(E.name).then(Q=>t({type:"SET_SEMANTIC_FAVORITES",favorites:Q}))},t:n}),D&&(v.size>0||Y.size>0)&&i.jsxs("div",{style:{padding:"8px 12px",borderTop:`1px solid ${n.headerBorder}`,background:n.cellBg,display:"flex",alignItems:"center",gap:8},children:[i.jsxs("span",{style:{flex:1,fontSize:11,color:n.textMuted,fontFamily:n.font},children:[v.size," metric",v.size!==1?"s":"",Y.size>0?`, ${Y.size} dim${Y.size!==1?"s":""}`:""]}),i.jsx("button",{onClick:()=>void Ge(),disabled:k||v.size===0,style:{background:n.accent,border:"none",borderRadius:6,color:"#fff",cursor:k?"not-allowed":"pointer",fontSize:11,fontWeight:600,fontFamily:n.font,padding:"6px 14px",opacity:k||v.size===0?.5:1},children:k?"Composing...":"Compose Query"})]})]})}const sc={source_table:"#8b949e",block:"#56d364",metric:"#388bfd",dimension:"#e3b341",domain:"#d2a8ff",chart:"#f778ba"},CR={certified:{label:"CERTIFIED",color:"#56d364"},draft:{label:"DRAFT",color:"#8b949e"},review:{label:"REVIEW",color:"#e3b341"},deprecated:{label:"DEPRECATED",color:"#f85149"},pending_recertification:{label:"PENDING",color:"#d29922"}};function ic({type:e}){const t=sc[e]??"#8b949e";return i.jsx("span",{style:{color:t,fontSize:10,fontWeight:600,textTransform:"uppercase",marginRight:4},children:e==="source_table"?"TBL":e==="block"?"BLK":e==="metric"?"MET":e==="dimension"?"DIM":e==="chart"?"CHT":e.slice(0,3).toUpperCase()})}function LR({status:e}){if(!e)return null;const t=CR[e];return t?i.jsx("span",{style:{fontSize:9,fontWeight:600,color:t.color,border:`1px solid ${t.color}`,borderRadius:3,padding:"0 3px",marginLeft:4},children:t.label}):null}function gr({label:e,count:t,expanded:n,onToggle:r,t:o}){const[s,a]=f.useState(!1);return i.jsxs("button",{onClick:r,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{width:"100%",display:"flex",alignItems:"center",gap:4,padding:"6px 8px",background:s?o.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:o.textPrimary,fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.5px",textAlign:"left"},children:[i.jsx("span",{style:{fontSize:10},children:n?"▼":"▶"}),i.jsx("span",{style:{flex:1},children:e}),i.jsx("span",{style:{color:o.textMuted,fontWeight:400},children:t})]})}function mn({node:e,t,onClick:n}){const[r,o]=f.useState(!1);return i.jsxs("div",{onClick:n,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),style:{padding:"3px 8px 3px 20px",cursor:n?"pointer":"default",background:r?t.sidebarItemHover:"transparent",display:"flex",alignItems:"center",gap:2,fontSize:12,color:t.textPrimary},children:[i.jsx(ic,{type:e.type}),i.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),i.jsx(LR,{status:e.status})]})}function _R(){const{state:e,dispatch:t}=Se(),n=le[e.themeMode],[r,o]=f.useState(!0),[s,a]=f.useState([]),[l,E]=f.useState([]),[c,d]=f.useState(null),[T,S]=f.useState(null),[u,R]=f.useState(!0),[I,N]=f.useState(!0),[A,p]=f.useState(!0),[O,h]=f.useState(!0),C=f.useCallback(async()=>{o(!0);const x=await te.fetchLineage();a(x.nodes),E(x.edges),o(!1)},[]);f.useEffect(()=>{C()},[C]);const _=f.useCallback(async x=>{if(c===x){d(null),S(null);return}d(x);const F=await te.fetchBlockLineage(x);F&&S({ancestors:F.ancestors,descendants:F.descendants})},[c]),m=s.filter(x=>x.type==="block"),M=s.filter(x=>x.type==="metric"),y=s.filter(x=>x.type==="source_table"),b=[...new Set(s.map(x=>x.domain).filter(Boolean))],g=l.filter(x=>x.type==="crosses_domain");return r?i.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"Loading lineage..."}):s.length===0?i.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"No lineage data found. Add blocks and semantic layer definitions to see the lineage graph."}):i.jsxs("div",{style:{overflow:"auto",flex:1,fontSize:12},children:[i.jsxs("div",{style:{padding:"6px 8px",borderBottom:`1px solid ${n.headerBorder}`},children:[i.jsxs("button",{onClick:()=>t({type:"TOGGLE_LINEAGE_FULLSCREEN"}),style:{width:"100%",padding:"6px 10px",marginBottom:6,background:e.lineageFullscreen?"#388bfd":"transparent",border:`1px solid ${e.lineageFullscreen?"#388bfd":"#30363d"}`,borderRadius:5,color:e.lineageFullscreen?"#fff":n.textPrimary,fontSize:11,fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:6,transition:"all 0.15s"},children:[i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("circle",{cx:"6",cy:"6",r:"3"}),i.jsx("circle",{cx:"18",cy:"6",r:"3"}),i.jsx("circle",{cx:"18",cy:"18",r:"3"}),i.jsx("line",{x1:"8.6",y1:"7.4",x2:"15.4",y2:"16.6"}),i.jsx("line",{x1:"9",y1:"6",x2:"15",y2:"6"})]}),e.lineageFullscreen?"Close Graph View":"Open Graph View"]}),i.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",fontSize:11,color:n.textMuted},children:[i.jsxs("span",{children:[m.length," blocks"]}),i.jsxs("span",{children:[M.length," metrics"]}),i.jsxs("span",{children:[y.length," tables"]}),g.length>0&&i.jsxs("span",{style:{color:"#d2a8ff"},children:[g.length," cross-domain"]})]})]}),c&&T&&i.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`},children:[i.jsxs("div",{style:{fontWeight:600,color:n.textPrimary,marginBottom:4,display:"flex",alignItems:"center",gap:4},children:[i.jsx(ic,{type:"block"}),c,i.jsx("button",{onClick:()=>{d(null),S(null)},style:{marginLeft:"auto",background:"transparent",border:"none",color:n.textMuted,cursor:"pointer",fontSize:14},children:"×"})]}),T.ancestors.length>0&&i.jsxs("div",{style:{marginTop:4},children:[i.jsxs("div",{style:{color:n.textMuted,fontSize:10,fontWeight:600,textTransform:"uppercase",marginBottom:2},children:["Upstream (",T.ancestors.length,")"]}),T.ancestors.map(x=>i.jsx(mn,{node:x,t:n},x.id))]}),T.descendants.length>0&&i.jsxs("div",{style:{marginTop:4},children:[i.jsxs("div",{style:{color:n.textMuted,fontSize:10,fontWeight:600,textTransform:"uppercase",marginBottom:2},children:["Downstream (",T.descendants.length,")"]}),T.descendants.map(x=>i.jsx(mn,{node:x,t:n},x.id))]})]}),i.jsx(gr,{label:"Blocks",count:m.length,expanded:u,onToggle:()=>R(!u),t:n}),u&&m.map(x=>i.jsx(mn,{node:x,t:n,onClick:()=>_(x.name)},x.id)),i.jsx(gr,{label:"Metrics",count:M.length,expanded:I,onToggle:()=>N(!I),t:n}),I&&M.map(x=>i.jsx(mn,{node:x,t:n},x.id)),i.jsx(gr,{label:"Source Tables",count:y.length,expanded:A,onToggle:()=>p(!A),t:n}),A&&y.map(x=>i.jsx(mn,{node:x,t:n},x.id)),i.jsx(gr,{label:"Domains",count:b.length,expanded:O,onToggle:()=>h(!O),t:n}),O&&b.map(x=>{const F=m.filter(D=>D.domain===x),L=F.filter(D=>D.status==="certified").length,P=F.length>0?Math.round(L/F.length*100):0;return i.jsxs("div",{style:{padding:"3px 8px 3px 20px",fontSize:12,color:n.textPrimary,display:"flex",gap:4,alignItems:"center"},children:[i.jsx("span",{style:{color:sc.domain,fontSize:10,fontWeight:600},children:"DOM"}),i.jsx("span",{style:{flex:1},children:x}),i.jsxs("span",{style:{color:n.textMuted,fontSize:10},children:[L,"/",F.length," (",P,"%)"]})]},x)}),g.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("div",{style:{padding:"6px 8px",fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.5px",color:n.textPrimary},children:"Cross-Domain Flows"}),g.map((x,F)=>i.jsxs("div",{style:{padding:"2px 8px 2px 20px",fontSize:11,color:n.textMuted},children:[x.sourceDomain," → ",x.targetDomain]},F))]})]})}const Na={draft:"#8b949e",review:"#d29922",certified:"#3fb950",deprecated:"#f85149",pending_recertification:"#db6d28"};function mR(){const{state:e,dispatch:t}=Se(),n=le[e.themeMode],[r,o]=f.useState([]),[s,a]=f.useState(!0),[l,E]=f.useState(""),[c,d]=f.useState(""),[T,S]=f.useState("");f.useEffect(()=>{a(!0),te.getBlockLibrary().then(p=>o(p.blocks)).finally(()=>a(!1))},[]);const u=[...new Set(r.map(p=>p.domain))].sort(),R=[...new Set(r.map(p=>p.status))].sort(),I=r.filter(p=>!(l&&!p.name.toLowerCase().includes(l.toLowerCase())&&!p.description.toLowerCase().includes(l.toLowerCase())||c&&p.domain!==c||T&&p.status!==T)),N=p=>{const O={name:p.path.split("/").pop()??p.name,path:p.path,type:"block",folder:"blocks"};e.files.some(h=>h.path===p.path)||t({type:"FILE_ADDED",file:O}),te.openBlockStudio(p.path).then(h=>{t({type:"OPEN_BLOCK_STUDIO",file:O,payload:h})})},A={background:n.inputBg,border:`1px solid ${n.inputBorder}`,borderRadius:4,color:n.textPrimary,fontSize:11,fontFamily:n.font,padding:"4px 6px",outline:"none"};return i.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[i.jsxs("div",{style:{padding:"10px 12px",borderBottom:`1px solid ${n.headerBorder}`,display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{style:{fontSize:12,fontWeight:600,color:n.textPrimary,fontFamily:n.font},children:"Blocks"}),i.jsx("span",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:I.length}),i.jsx("span",{style:{flex:1}}),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:()=>{a(!0),te.getBlockLibrary().then(p=>o(p.blocks)).finally(()=>a(!1))},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"})]}),i.jsxs("div",{style:{padding:"8px 12px",borderBottom:`1px solid ${n.headerBorder}`,display:"flex",gap:6,flexWrap:"wrap"},children:[i.jsx("input",{value:l,onChange:p=>E(p.target.value),placeholder:"Search blocks...",style:{...A,flex:1,minWidth:100}}),i.jsxs("select",{value:c,onChange:p=>d(p.target.value),style:A,children:[i.jsx("option",{value:"",children:"All domains"}),u.map(p=>i.jsx("option",{value:p,children:p},p))]}),i.jsxs("select",{value:T,onChange:p=>S(p.target.value),style:A,children:[i.jsx("option",{value:"",children:"All statuses"}),R.map(p=>i.jsx("option",{value:p,children:p},p))]})]}),i.jsx("div",{style:{flex:1,overflowY:"auto"},children:s?i.jsx("div",{style:{padding:20,textAlign:"center",fontSize:12,color:n.textMuted,fontFamily:n.font},children:"Loading blocks..."}):I.length===0?i.jsx("div",{style:{padding:20,textAlign:"center",fontSize:12,color:n.textMuted,fontFamily:n.font},children:r.length===0?"No blocks found. Create your first block to get started.":"No blocks match your filters."}):I.map(p=>i.jsxs("button",{onClick:()=>N(p),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:O=>{O.currentTarget.style.background=`${n.accent}0a`},onMouseLeave:O=>{O.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:p.name}),i.jsx("span",{style:{fontSize:9,fontWeight:600,color:Na[p.status]??n.textMuted,background:`${Na[p.status]??n.textMuted}18`,padding:"1px 6px",borderRadius:4,textTransform:"uppercase",letterSpacing:"0.04em",fontFamily:n.font},children:p.status})]}),p.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:p.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:p.domain}),p.owner&&i.jsxs("span",{children:["by ",p.owner]}),i.jsx("span",{style:{marginLeft:"auto"},children:new Date(p.lastModified).toLocaleDateString()})]})]},p.path))})]})}const gR={files:"Explorer",schema:"Schema",block_library:"Block Library",semantic:"Semantic Layer",lineage:"Lineage",connection:"Connection",reference:"Quick Reference"};function xR({onOpenFile:e}){const{state:t,dispatch:n}=Se(),r=le[t.themeMode],[o,s]=f.useState(!1),a=t.mainView==="block_studio"&&t.sidebarPanel==="semantic"?"files":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:gR[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(du,{onOpenFile:e}),a==="schema"&&i.jsx(Nu,{}),a==="block_library"&&i.jsx(mR,{}),a==="semantic"&&i.jsx(hR,{}),a==="lineage"&&i.jsx(_R,{}),a==="connection"&&i.jsx(VE,{}),a==="reference"&&i.jsx(WE,{themeMode:t.themeMode})]})]})}function yR(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:Rt(),type:"markdown",content:`# ${a}`,status:"idle"}),l&&r.push({id:Rt(),type:"dql",name:a.toLowerCase().replace(/\s+/g,"_"),content:l,status:"idle"})}return r.length===0&&r.push({id:Rt(),type:"dql",content:e.trim(),status:"idle"}),{title:n,cells:r}}catch{return{title:"Untitled Workbook",cells:[{id:Rt(),type:"dql",content:e.trim(),status:"idle"}]}}}function DR(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(s=>({id:s.id||Rt(),type:s.type||"sql",content:s.content??s.source??"",name:s.name||s.title,status:"idle",...s.paramConfig?{paramConfig:s.paramConfig}:{},...s.paramValue!==void 0?{paramValue:s.paramValue}:{},...s.chartConfig?{chartConfig:s.chartConfig}:{}}));return{title:r,cells:o}}catch{return{title:"Untitled",cells:[{id:Rt(),type:"sql",content:e,status:"idle"}]}}}function MR(e,t,n){const r={version:1,title:e,metadata:{...n,modifiedAt:new Date().toISOString(),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}:{}}))};return JSON.stringify(r,null,2)}function PR(e,t){return e.endsWith(".dql")?yR(t):DR(t)}function bR(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(E=>{const c=a[E];return c==null?"NULL":typeof c=="number"?String(c):typeof c=="boolean"?c?"TRUE":"FALSE":`'${String(c).replace(/'/g,"''")}'`}).join(", ")})`).join(`,
205
+ `),s=n.map(a=>`"${a.replace(/"/g,'""')}"`).join(", ");return`${e} AS (
206
+ SELECT * FROM (VALUES
207
+ ${o}
208
+ ) AS _t(${s})
209
+ )`}function UR(e,t){if(t==="number"){const n=Number(e);return isNaN(n)?`'${e.replace(/'/g,"''")}'`:String(n)}return`'${e.replace(/'/g,"''")}'`}function vR(){const{state:e}=Se();return{substituteVariables:f.useCallback(n=>{var d;const r=/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g,o=[...n.matchAll(r)];if(o.length===0)return{sql:n,substituted:[]};const s=[],a=[];let l=n;const E=new Map,c=new Map;for(const T of e.cells){const S=(d=T.name)==null?void 0:d.trim();S&&(T.type==="param"?E.set(S,T):T.status==="success"&&T.result&&c.set(S,T.result))}for(const T of o){const S=T[1];if(E.has(S)){const u=E.get(S),R=u.paramConfig,I=u.paramValue??(R==null?void 0:R.defaultValue)??"",N=(R==null?void 0:R.paramType)??"text",A=UR(I,N);l=l.replace(T[0],A),s.push(S)}else c.has(S)&&(a.push(bR(S,c.get(S))),l=l.replace(T[0],`"${S}"`),s.push(S))}if(a.length===0&&s.length===0)return{sql:n,substituted:[]};if(a.length>0){const T=l.trimStart();/^WITH\s+/i.test(T)?l=l.replace(/^(\s*WITH\s+)/i,`$1${a.join(`,
210
+ `)},
211
+ `):l=`WITH ${a.join(`,
212
+ `)}
213
+ ${l}`}return{sql:l,substituted:s}},[e.cells])}}function BR(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 FR(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=GR(s),s.trim()||null}return null}function GR(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 Oa(e){const t=jt(e);return t?{name:t.name,domain:t.domain,owner:t.owner,description:t.description,blockType:t.blockType,tags:t.tags}:null}function rs(e,t,n){const r=jt(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}"`):mi(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),On(o)}function ac(e,t){const n=jt(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 On({...n,name:t})}function wR(e,t){const n=jt(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}]`):mi(e,` tags = [${r}]`)}return On({...n,tags:t})}function HR(e,t){const n=jt(e),r=WR(t);return n?On({...n,visualization:r}):/visualization\s*\{[\s\S]*?\n\s*\}/i.test(e)?e.replace(/visualization\s*\{[\s\S]*?\n\s*\}/i,r):mi(e,` ${r.replace(/\n/g,`
214
+ `)}`,!0)}function YR(e,t){return e==="metric"?`@metric(${t})`:`@dim(${t})`}function kR(e,t){const n=jt(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 On(r)}function VR(e,t){const n=jt(e);if(!n||n.blockType!=="custom")return`${e.trimEnd()}
215
+ ${t}
216
+ `;const r=n.query.trimEnd(),o=r?`${r}
217
+ ${t}`:t;return On({...n,query:o})}function jt(e){var s,a;if(!/^\s*block\s+"/i.test(e.trim()))return null;const t=l=>{var E;return((E=e.match(new RegExp(`\\b${l}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:E[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:fa(e,"metrics"),dimensions:fa(e,"dimensions"),timeDimension:t("time_dimension"),granularity:t("granularity"),query:((a=o==null?void 0:o[1])==null?void 0:a.trim())??"",visualization:pa(e,"visualization"),tests:pa(e,"tests")}}function fa(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 pa(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 On(e){const t=[`block "${Xe(e.name||"New Block")}" {`,` domain = "${Xe(e.domain||"uncategorized")}"`,` type = "${e.blockType}"`,` description = "${Xe(e.description)}"`,` owner = "${Xe(e.owner)}"`,` tags = [${e.tags.map(n=>`"${Xe(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 = "${Xe(n[0])}"`):n.length>1&&t.push(` metrics = [${n.map(r=>`"${Xe(r)}"`).join(", ")}]`),e.dimensions.length>0&&t.push(` dimensions = [${Array.from(new Set(e.dimensions)).map(r=>`"${Xe(r)}"`).join(", ")}]`),e.timeDimension&&t.push(` time_dimension = "${Xe(e.timeDimension)}"`),e.granularity&&t.push(` granularity = "${Xe(e.granularity)}"`)}return e.blockType==="custom"&&(t.push(""),t.push(' query = """'),t.push(...jR(e.query.trim(),4)),t.push(' """')),e.visualization&&(t.push(""),t.push(...ha(e.visualization,2))),e.tests&&(t.push(""),t.push(...ha(e.tests,2))),t.push("}"),t.join(`
218
+ `)+`
219
+ `}function WR(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 = "${Xe(e.title)}"`),t.push("}"),t.join(`
220
+ `)}function jR(e,t){const n=" ".repeat(t);return(e?e.split(`
221
+ `):[""]).map(o=>`${n}${o}`)}function ha(e,t){const n=" ".repeat(t);return e.split(`
222
+ `).map(r=>`${n}${r.trimEnd()}`)}function Xe(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function mi(e,t,n=!1){const r=e.trimEnd();if(!/^\s*block\s+"/i.test(r))return`${r}
223
+ ${t}
224
+ `;const o=n?`
225
+
226
+ ${t}
227
+ `:`
228
+ ${t}`;return r.replace(/\n\}\s*$/,`${o}
229
+ }`)}const gn=new Map;function $R(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?FR(t):null}function mo(){const{state:e,dispatch:t}=Se(),{substituteVariables:n}=vR(),r=f.useCallback(async l=>{const E=e.cells.find(R=>R.id===l);if(!E)return;const c=$R(E);if(!c)return;if(E.type==="dql"){const R=BR(E.content);R&&JSON.stringify(R)!==JSON.stringify(E.chartConfig)&&t({type:"UPDATE_CELL",id:l,updates:{chartConfig:R}})}const{sql:d}=n(c),T=Date.now(),S=gn.get(l);S&&S.abort();const u=new AbortController;gn.set(l,u),t({type:"UPDATE_CELL",id:l,updates:{status:"running",error:void 0,result:void 0}});try{const R=await te.executeQuery(d,u.signal),I=Date.now()-T,N=(E.executionCount??0)+1;t({type:"UPDATE_CELL",id:l,updates:{status:"success",result:{...R,executionTime:R.executionTime??I,rowCount:R.rowCount??R.rows.length},executionCount:N}}),t({type:"APPEND_QUERY_LOG",entry:{id:Rt(),cellName:E.name??E.id,rows:R.rowCount??R.rows.length,time:R.executionTime??I,ts:new Date}}),setTimeout(()=>{t({type:"UPDATE_CELL",id:l,updates:{status:"idle"}})},2e3)}catch(R){if(u.signal.aborted){t({type:"UPDATE_CELL",id:l,updates:{status:"idle",error:void 0}});return}const I=Date.now()-T,N=R instanceof Error?R.message:String(R);t({type:"UPDATE_CELL",id:l,updates:{status:"error",error:N,executionCount:(E.executionCount??0)+1}}),t({type:"APPEND_QUERY_LOG",entry:{id:Rt(),cellName:E.name??E.id,rows:0,time:I,ts:new Date,error:N}})}finally{gn.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 E=`{{${l}}}`;for(const c of e.cells)c.type==="markdown"||c.type==="param"||c.content.includes(E)&&await r(c.id)},[e.cells,r]),a=f.useCallback(l=>{const E=gn.get(l);E&&(E.abort(),gn.delete(l)),t({type:"UPDATE_CELL",id:l,updates:{status:"idle"}})},[t]);return{executeCell:r,executeAll:o,executeDependents:s,cancelCell:a}}function ve(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function XR(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 KR(e){const t=e.split(`
230
+ `),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(ve(a));continue}if(a.startsWith("### ")){o&&(n.push("</ul>"),o=!1),n.push(`<h3>${ve(a.slice(4))}</h3>`);continue}if(a.startsWith("## ")){o&&(n.push("</ul>"),o=!1),n.push(`<h2>${ve(a.slice(3))}</h2>`);continue}if(a.startsWith("# ")){o&&(n.push("</ul>"),o=!1),n.push(`<h1>${ve(a.slice(2))}</h1>`);continue}if(a.startsWith("> ")){o&&(n.push("</ul>"),o=!1),n.push(`<blockquote><p>${ve(a.slice(2))}</p></blockquote>`);continue}if(a.startsWith("- ")||a.startsWith("* ")){o||(n.push("<ul>"),o=!0),n.push(`<li>${Ca(a.slice(2))}</li>`);continue}if(o&&(n.push("</ul>"),o=!1),a.trim()===""){n.push("<br>");continue}n.push(`<p>${Ca(a)}</p>`)}return o&&n.push("</ul>"),r&&n.push("</code></pre>"),n.join(`
231
+ `)}function Ca(e){return ve(e).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/`(.+?)`/g,"<code>$1</code>")}function zR(e){const{columns:t,rows:n}=e,r=n.slice(0,200),o=n.length>200,s=t.map(l=>`<th>${ve(l)}</th>`).join(""),a=r.map(l=>`<tr>${t.map(c=>{const d=l[c],T=typeof d=="number",S=d==null?"—":String(d);return`<td${T?' class="num"':""}>${ve(S)}</td>`}).join("")}</tr>`).join("");return`
232
+ <div class="table-wrap">
233
+ <table>
234
+ <thead><tr>${s}</tr></thead>
235
+ <tbody>${a}</tbody>
236
+ </table>
237
+ ${o?`<p class="truncated">Showing first 200 of ${n.length.toLocaleString()} rows</p>`:""}
238
+ </div>`}function JR(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 qR(e){const t=JR(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,E=n.length*(o+s)+40,c=n.map((d,T)=>{const S=T*(o+s)+20,u=Math.max(d.value/r*l,2);return`
239
+ <text x="${a-6}" y="${S+o/2+4}" text-anchor="end" font-size="11" fill="#8b949e">${ve(d.label.slice(0,20))}</text>
240
+ <rect x="${a}" y="${S}" width="${u}" height="${o}" rx="3" fill="#388bfd" />
241
+ <text x="${a+u+5}" y="${S+o/2+4}" font-size="11" fill="#e6edf3">${XR(d.value)}</text>`}).join("");return`<svg xmlns="http://www.w3.org/2000/svg" width="${a+l+80}" height="${E}" style="max-width:100%">${c}</svg>`}function QR(e,t){const n=t.map(r=>{if(r.type==="markdown")return`<section class="cell md-cell">${KR(r.content)}</section>`;const o=r.name?`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span><span class="cell-name">${ve(r.name)}</span></div>`:`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span></div>`,s=`<pre class="cell-code"><code>${ve(r.content)}</code></pre>`;let a="";if(r.result&&r.result.rows.length>0){const l=qR(r.result),E=zR(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?"":E}</div>`}else r.error&&(a=`<div class="cell-error">⚠ ${ve(r.error)}</div>`);return`<section class="cell sql-cell">${o}${s}${a}</section>`}).join(`
242
+ `);return`<!DOCTYPE html>
243
+ <html lang="en">
244
+ <head>
245
+ <meta charset="UTF-8">
246
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
247
+ <title>${ve(e)}</title>
248
+ <style>
249
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
250
+ body {
251
+ font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
252
+ background: #0d1117; color: #e6edf3;
253
+ line-height: 1.6; padding: 0;
254
+ }
255
+ .page-header {
256
+ background: #161b22; border-bottom: 1px solid #21262d;
257
+ padding: 16px 32px; display: flex; align-items: center; gap: 12px;
258
+ }
259
+ .logo {
260
+ width: 28px; height: 28px; border-radius: 6px;
261
+ background: linear-gradient(135deg, #388bfd, #1f6feb);
262
+ display: flex; align-items: center; justify-content: center;
263
+ font-size: 10px; font-weight: 700; color: #fff;
264
+ font-family: monospace; letter-spacing: -0.5px; flex-shrink: 0;
265
+ }
266
+ .page-title { font-size: 18px; font-weight: 600; color: #e6edf3; }
267
+ .page-meta { font-size: 12px; color: #8b949e; margin-left: auto; }
268
+ .content { max-width: 900px; margin: 0 auto; padding: 32px 24px; display: flex; flex-direction: column; gap: 24px; }
269
+ .cell { border-radius: 8px; overflow: hidden; }
270
+ .md-cell { padding: 4px 0; }
271
+ .md-cell h1 { font-size: 26px; font-weight: 700; color: #e6edf3; margin: 0 0 12px; }
272
+ .md-cell h2 { font-size: 20px; font-weight: 600; color: #e6edf3; margin: 20px 0 10px; }
273
+ .md-cell h3 { font-size: 16px; font-weight: 600; color: #e6edf3; margin: 16px 0 8px; }
274
+ .md-cell p { color: #c9d1d9; margin-bottom: 8px; }
275
+ .md-cell ul { padding-left: 20px; color: #c9d1d9; margin-bottom: 8px; }
276
+ .md-cell code { background: #21262d; padding: 2px 6px; border-radius: 4px; font-family: monospace; font-size: 13px; }
277
+ .md-cell pre { background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 14px; overflow-x: auto; margin-bottom: 8px; }
278
+ .md-cell pre code { background: none; padding: 0; }
279
+ .md-cell blockquote { border-left: 3px solid #388bfd; padding-left: 14px; color: #8b949e; }
280
+ .sql-cell { background: #161b22; border: 1px solid #30363d; }
281
+ .cell-header { display: flex; align-items: center; gap: 8px; padding: 8px 14px; border-bottom: 1px solid #21262d; background: #1c2128; }
282
+ .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; }
283
+ .cell-name { font-size: 12px; color: #388bfd; font-family: monospace; }
284
+ .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; }
285
+ .cell-output { padding: 14px; }
286
+ .output-meta { font-size: 11px; color: #8b949e; margin-bottom: 10px; }
287
+ .table-wrap { overflow-x: auto; }
288
+ table { width: 100%; border-collapse: collapse; font-size: 12px; }
289
+ th { background: #1c2128; color: #8b949e; font-weight: 600; text-align: left; padding: 7px 12px; border-bottom: 1px solid #30363d; white-space: nowrap; }
290
+ td { padding: 6px 12px; border-bottom: 1px solid #21262d; color: #e6edf3; }
291
+ td.num { text-align: right; font-family: monospace; }
292
+ tr:last-child td { border-bottom: none; }
293
+ .truncated { font-size: 11px; color: #8b949e; margin-top: 8px; }
294
+ .cell-error { padding: 12px 14px; background: #3d1a1a; border-top: 1px solid #f85149; color: #f85149; font-size: 13px; }
295
+ .exported-by { text-align: center; color: #484f58; font-size: 11px; padding: 40px 0 24px; }
296
+ </style>
297
+ </head>
298
+ <body>
299
+ <div class="page-header">
300
+ <div class="logo">DQL</div>
301
+ <span class="page-title">${ve(e)}</span>
302
+ <span class="page-meta">Exported ${new Date().toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}</span>
303
+ </div>
304
+ <div class="content">
305
+ ${n}
306
+ </div>
307
+ <p class="exported-by">Built with DQL Notebook</p>
308
+ </body>
309
+ </html>`}function ZR(e,t){const n=QR(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 eA(e,t){var s,a;const n=[];n.push(`workbook "${e}" {`);let r=0,o=0;for(const l of t)if(l.type!=="param"){if(l.type==="markdown"){o++;const E=`Markdown ${o}`;n.push(""),n.push(` page "${E}" {`);const c=l.content.split(`
310
+ `);for(const d of c)n.push(` // ${d}`);n.push(" }")}else if(l.type==="sql"){r++;const E=((s=l.name)==null?void 0:s.trim())||`Query ${r}`;n.push(""),n.push(` page "${E}" {`);const d=l.content.trim().split(`
311
+ `).map(T=>` ${T}`).join(`
312
+ `);n.push(" chart.table("),n.push(d+","),n.push(` title = "${E}"`),n.push(" )"),n.push(" }")}else if(l.type==="dql"){r++;const E=((a=l.name)==null?void 0:a.trim())||`Query ${r}`;n.push(""),n.push(` page "${E}" {`);const c=l.content.trim().split(`
313
+ `);for(const d of c)n.push(` ${d}`);n.push(" }")}}return n.push("}"),n.join(`
314
+ `)}function tA(e,t){const n=eA(e,t),r=new Blob([n],{type:"text/plain;charset=utf-8"}),o=URL.createObjectURL(r),s=document.createElement("a"),a=e.replace(/[^a-zA-Z0-9_-]/g,"_")+".dql";s.href=o,s.download=a,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(o)}function nA({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 rA(){const{state:e,dispatch:t}=Se(),n=le[e.themeMode],{executeAll:r}=mo(),[o,s]=f.useState(!1),[a,l]=f.useState(""),[E,c]=f.useState(!1),[d,T]=f.useState(!1),[S,u]=f.useState(!1),[R,I]=f.useState(!1),[N,A]=f.useState(!1),[p,O]=f.useState(!1),h=f.useRef(null),C=f.useRef(null),_=e.mainView==="block_studio"?e.blockStudioDirty:e.notebookDirty,m=e.mainView==="notebook",M=e.mainView==="connection"?"Connections":e.mainView==="reference"?"Quick Reference":e.notebookTitle||"Untitled";f.useEffect(()=>{o&&C.current&&(C.current.focus(),C.current.select())},[o]),f.useEffect(()=>{if(!p)return;function L(P){h.current&&!h.current.contains(P.target)&&O(!1)}return document.addEventListener("mousedown",L),()=>document.removeEventListener("mousedown",L)},[p]);const y=()=>{l(e.notebookTitle),s(!0)},b=()=>{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:ac(e.blockStudioDraft,a.trim())})):t({type:"SET_NOTEBOOK_DIRTY",dirty:!0}))},g=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 P=await te.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:`${P.metadata.name}.dql`,path:P.path,type:"block",folder:"blocks"},payload:P}),e.files.some(D=>D.path===P.path)||t({type:"FILE_ADDED",file:{name:`${P.metadata.name}.dql`,path:P.path,type:"block",folder:"blocks"}})}else{const P=e.activeFile.type==="block"?((L=e.cells[0])==null?void 0:L.content)??"":MR(e.notebookTitle,e.cells);await te.saveNotebook(e.activeFile.path,P),t({type:"SET_NOTEBOOK_DIRTY",dirty:!1})}c(!0),setTimeout(()=>c(!1),2e3)}catch(P){console.error("Save failed:",P)}finally{t({type:"SET_SAVING",saving:!1})}}},[e.activeFile,e.activeBlockPath,e.blockStudioDraft,e.blockStudioMetadata,e.files,e.mainView,e.notebookTitle,e.cells,t]);f.useEffect(()=>{const L=P=>{(P.metaKey||P.ctrlKey)&&P.key==="s"&&(P.preventDefault(),g())};return document.addEventListener("keydown",L),()=>document.removeEventListener("keydown",L)},[g]),f.useEffect(()=>{if(!e.autoSave||!_||!e.activeFile)return;const L=setTimeout(()=>{g()},2e3);return()=>clearTimeout(L)},[e.autoSave,_,e.activeFile,e.cells,e.blockStudioDraft,g]);const x=()=>{t({type:"SET_THEME",mode:e.themeMode==="dark"?"light":"dark"})},F={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(nA,{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:C,value:a,onChange:L=>l(L.target.value),onBlur:b,onKeyDown:L=>{L.key==="Enter"&&b(),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:y,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:[M,_&&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:M})]}),i.jsx("div",{style:{flex:1}}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsxs("button",{onClick:m?r:void 0,disabled:!e.activeFile||!m,onMouseEnter:()=>T(!0),onMouseLeave:()=>T(!1),style:{...F,background:(d&&e.activeFile,n.accent),color:"#ffffff",border:`1px solid ${n.accent}`,opacity:!e.activeFile||!m?.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}}),i.jsx("button",{onClick:x,onMouseEnter:()=>I(!0),onMouseLeave:()=>I(!1),title:e.themeMode==="dark"?"Switch to light mode":"Switch to dark mode",style:{...F,background:R?n.btnHover:n.btnBg,color:n.textSecondary,padding:"0 8px",fontSize:14},children:e.themeMode==="dark"?"☀":"☾"}),i.jsx("button",{onClick:g,disabled:!e.activeFile||e.savingFile,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),title:"Save (Cmd+S)",style:{...F,background:S&&e.activeFile?n.btnHover:n.btnBg,color:E?n.success:n.textSecondary,opacity:e.activeFile?1:.4},children:e.savingFile?i.jsxs(i.Fragment,{children:[i.jsx(oA,{}),"Saving…"]}):E?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:{...F,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:{...F,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:h,style:{position:"relative"},children:[i.jsxs("button",{onClick:()=>{e.activeFile&&O(L=>!L)},disabled:!e.activeFile,onMouseEnter:()=>A(!0),onMouseLeave:()=>A(!1),title:"Export options",style:{...F,background:(N||p)&&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"})})]}),p&&i.jsxs("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(La,{label:"Export HTML",description:"Standalone dashboard",t:n,onClick:()=>{ZR(e.notebookTitle||"dashboard",e.cells),O(!1)}}),i.jsx(La,{label:"Export .dql",description:"DQL workbook file",t:n,onClick:()=>{tA(e.notebookTitle||"notebook",e.cells),O(!1)}})]})]})]})]})}function La({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 oA(){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 sA(e){return e.toTimeString().slice(0,8)}function iA(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}function aA(){const{state:e,dispatch:t}=Se(),n=le[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(lA,{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",border:"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(_a,{t:n,message:"No queries executed yet."}):[...e.queryLog].reverse().map(l=>i.jsx(ma,{entry:l,t:n},l.id))),e.devPanelTab==="errors"&&(s.length===0?i.jsx(_a,{t:n,message:"No errors."}):[...s].reverse().map(l=>i.jsx(ma,{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",border:`1px solid ${n.headerBorder}`,borderBottom:e.devPanelOpen?`1px solid ${n.sidebarBg}`:void 0,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 lA({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",border:"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 _a({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 ma({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:sA(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:iA(e.time)})]})]})}function EA({onOpenFile:e}){const{state:t,dispatch:n}=Se(),r=le[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(ga,{title:"New Notebook",description:"Start a fresh analysis with an empty notebook.",icon:i.jsx(dA,{}),accent:r.accent,onClick:()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}),t:r}),i.jsx(cA,{recentFiles:o,onOpenFile:e,t:r}),i.jsx(ga,{title:"New Block",description:"Create a reusable SQL block file.",icon:i.jsx(uA,{}),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 ga({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 cA({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(SA,{})}),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(TA,{file:s,onClick:()=>t(s),t:n},s.path))})]})]})}function TA({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 dA(){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 SA(){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 uA(){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 xa=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class Yn{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(xa(l)):xa,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 IS(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=CS(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=NS(t);let o=this.normalize(n);if(o.length)for(let s=0,a=r;;s++){let l=o.charCodeAt(s),E=this.match(l,a,this.bufferPos+this.bufferStart);if(s==o.length-1){if(E)return this.value=E,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"&&(Yn.prototype[Symbol.iterator]=function(){return this});const lc={from:-1,to:-1,match:/.*/.exec("")},gi="gm"+(/x/.unicode==null?"":"u");class Ec{constructor(t,n,r,o=0,s=t.length){if(this.text=t,this.to=s,this.curLine="",this.done=!1,this.value=lc,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new cc(t,n,r,o,s);this.re=new RegExp(n,gi+(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=no(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=no(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 os=new WeakMap;class on{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let o=os.get(t);if(!o||o.from>=r||o.to<=n){let l=new on(n,t.sliceString(n,r));return os.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)),os.set(t,new on(a,s)),new on(n,s.slice(n-a,r-a))}}class cc{constructor(t,n,r,o,s){this.text=t,this.to=s,this.done=!1,this.value=lc,this.matchPos=no(t,o),this.re=new RegExp(n,gi+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.flat=on.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=no(this.text,o+(r==o?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=on.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(Ec.prototype[Symbol.iterator]=cc.prototype[Symbol.iterator]=function(){return this});function RA(e){try{return new RegExp(e,gi),!0}catch{return!1}}function no(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 AA=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:o}=uS(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),[,E,c,d,T]=a,S=d?+d.slice(1):0,u=c?+c:l.number;if(c&&T){let N=u/100;E&&(N=N*(E=="-"?-1:1)+l.number/t.doc.lines),u=Math.round(t.doc.lines*N)}else c&&E&&(u=u*(E=="-"?-1:1)+l.number);let R=t.doc.line(Math.max(1,Math.min(t.doc.lines,u))),I=Ze.cursor(R.from+Math.max(0,Math.min(S,R.length)));e.dispatch({effects:[r,Me.scrollIntoView(I.from,{y:"center"})],selection:I})}),!0},IA=({state:e,dispatch:t})=>{let{selection:n}=e,r=Ze.create(n.ranges.map(o=>e.wordAt(o.head)||Ze.cursor(o.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function NA(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 Yn(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(a)return null;l=new Yn(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),a=!0}else{if(a&&r.some(E=>E.from==l.value.from))continue;if(s){let E=e.wordAt(l.value.from);if(!E||E.from!=l.value.from||E.to!=l.value.to)continue}return l.value}}const OA=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(s=>s.from===s.to))return IA({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=NA(e,r);return o?(t(e.update({selection:e.selection.addRange(Ze.range(o.from,o.to),!1),effects:Me.scrollIntoView(o.to)})),!0):!1},$t=OS.define({combine(e){return fS(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new UA(t),scrollToMatch:t=>Me.scrollIntoView(t)})}});function fA(e){return e?[$t.of(e),si]:si}class Tc{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||RA(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"?`
315
+ `: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 mA(this):new CA(this)}getCursor(t,n=0,r){let o=t.doc?t:HE.create({doc:t});return r==null&&(r=o.doc.length),this.regexp?tn(this,o,n,r):en(this,o,n,r)}}class dc{constructor(t){this.spec=t}}function pA(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 en(e,t,n,r){let o;return e.wholeWord&&(o=hA(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(o=pA(e.test,t,o)),new Yn(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:s=>s.toLowerCase(),o)}function hA(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(ro(o,n-s))!=_t.Word||t(oo(o,n-s))!=_t.Word)&&(t(oo(o,r-s))!=_t.Word||t(ro(o,r-s))!=_t.Word))}class CA extends dc{constructor(t){super(t)}nextMatch(t,n,r){let o=en(this.spec,t,r,t.doc.length).nextOverlapping();if(o.done){let s=Math.min(t.doc.length,n+this.spec.unquoted.length);o=en(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=en(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=en(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=en(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 LA(e,t,n){return(r,o,s)=>(!n||n(r,o,s))&&e(s[0],t,r,o)}function tn(e,t,n,r){let o;return e.wholeWord&&(o=_A(t.charCategorizer(t.selection.main.head))),e.test&&(o=LA(e.test,t,o)),new Ec(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:o},n,r)}function ro(e,t){return e.slice(YE(e,t,!1),t)}function oo(e,t){return e.slice(t,YE(e,t))}function _A(e){return(t,n,r)=>!r[0].length||(e(ro(r.input,r.index))!=_t.Word||e(oo(r.input,r.index))!=_t.Word)&&(e(oo(r.input,r.index+r[0].length))!=_t.Word||e(ro(r.input,r.index+r[0].length))!=_t.Word)}class mA extends dc{nextMatch(t,n,r){let o=tn(this.spec,t,r,t.doc.length).next();return o.done&&(o=tn(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=tn(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=tn(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=tn(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 kn=Co.define(),xi=Co.define(),gt=wE.define({create(e){return new ss(oi(e).create(),null)},update(e,t){for(let n of t.effects)n.is(kn)?e=new ss(n.value.create(),e.panel):n.is(xi)&&(e=new ss(e.query,n.value?yi:null));return e},provide:e=>RS.from(e,t=>t.panel)});class ss{constructor(t,n){this.query=t,this.panel=n}}const gA=vt.mark({class:"cm-searchMatch"}),xA=vt.mark({class:"cm-searchMatch cm-searchMatch-selected"}),yA=pS.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(gt))}update(e){let t=e.state.field(gt);(t!=e.startState.field(gt)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return vt.none;let{view:n}=this,r=new hS;for(let o=0,s=n.visibleRanges,a=s.length;o<a;o++){let{from:l,to:E}=s[o];for(;o<a-1&&E>s[o+1].from-500;)E=s[++o].to;e.highlight(n.state,l,E,(c,d)=>{let T=n.state.selection.ranges.some(S=>S.from==c&&S.to==d);r.add(c,d,T?xA:gA)})}return r.finish()}},{decorations:e=>e.decorations});function er(e){return t=>{let n=t.state.field(gt,!1);return n&&n.query.spec.valid?e(t,n):Rc(t)}}const so=er((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let o=Ze.single(r.from,r.to),s=e.state.facet($t);return e.dispatch({selection:o,effects:[Di(e,r),s.scrollToMatch(o.main,e)],userEvent:"select.search"}),uc(e),!0}),io=er((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,o=t.prevMatch(n,r,r);if(!o)return!1;let s=Ze.single(o.from,o.to),a=e.state.facet($t);return e.dispatch({selection:s,effects:[Di(e,o),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),uc(e),!0}),DA=er((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:Ze.create(n.map(r=>Ze.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),MA=({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 Yn(e.doc,e.sliceDoc(r,o));!l.next().done;){if(s.length>1e3)return!1;l.value.from==r&&(a=s.length),s.push(Ze.range(l.value.from,l.value.to))}return t(e.update({selection:Ze.create(s,a),userEvent:"select.search.matches"})),!0},ya=er((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=[],E,c,d=[];a.from==r&&a.to==o&&(c=n.toText(t.getReplacement(a)),l.push({from:a.from,to:a.to,insert:c}),a=t.nextMatch(n,a.from,a.to),d.push(Me.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+".")));let T=e.state.changes(l);return a&&(E=Ze.single(a.from,a.to).map(T),d.push(Di(e,a)),d.push(n.facet($t).scrollToMatch(E.main,e))),e.dispatch({changes:T,selection:E,effects:d,userEvent:"input.replace"}),!0}),PA=er((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:Me.announce.of(r),userEvent:"input.replace.all"}),!0});function yi(e){return e.state.facet($t).createPanel(e)}function oi(e,t){var n,r,o,s,a;let l=e.selection.main,E=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!E)return t;let c=e.facet($t);return new Tc({search:((n=t==null?void 0:t.literal)!==null&&n!==void 0?n:c.literal)?E:E.replace(/\n/g,"\\n"),caseSensitive:(r=t==null?void 0:t.caseSensitive)!==null&&r!==void 0?r:c.caseSensitive,literal:(o=t==null?void 0:t.literal)!==null&&o!==void 0?o:c.literal,regexp:(s=t==null?void 0:t.regexp)!==null&&s!==void 0?s:c.regexp,wholeWord:(a=t==null?void 0:t.wholeWord)!==null&&a!==void 0?a:c.wholeWord})}function Sc(e){let t=GE(e,yi);return t&&t.dom.querySelector("[main-field]")}function uc(e){let t=Sc(e);t&&t==e.root.activeElement&&t.select()}const Rc=e=>{let t=e.state.field(gt,!1);if(t&&t.panel){let n=Sc(e);if(n&&n!=e.root.activeElement){let r=oi(e.state,t.query.spec);r.valid&&e.dispatch({effects:kn.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[xi.of(!0),t?kn.of(oi(e.state,t.query.spec)):Co.appendConfig.of(si)]});return!0},Ac=e=>{let t=e.state.field(gt,!1);if(!t||!t.panel)return!1;let n=GE(e,yi);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:xi.of(!1)}),!0},bA=[{key:"Mod-f",run:Rc,scope:"editor search-panel"},{key:"F3",run:so,shift:io,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:so,shift:io,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:Ac,scope:"editor search-panel"},{key:"Mod-Shift-l",run:MA},{key:"Mod-Alt-g",run:AA},{key:"Mod-d",run:OA,preventDefault:!0}];class UA{constructor(t){this.view=t;let n=this.query=t.state.field(gt).query.spec;this.commit=this.commit.bind(this),this.searchField=Ve("input",{value:n.search,placeholder:He(t,"Find"),"aria-label":He(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=Ve("input",{value:n.replace,placeholder:He(t,"Replace"),"aria-label":He(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=Ve("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=Ve("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=Ve("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(o,s,a){return Ve("button",{class:"cm-button",name:o,onclick:s,type:"button"},a)}this.dom=Ve("div",{onkeydown:o=>this.keydown(o),class:"cm-search"},[this.searchField,r("next",()=>so(t),[He(t,"next")]),r("prev",()=>io(t),[He(t,"previous")]),r("select",()=>DA(t),[He(t,"all")]),Ve("label",null,[this.caseField,He(t,"match case")]),Ve("label",null,[this.reField,He(t,"regexp")]),Ve("label",null,[this.wordField,He(t,"by word")]),...t.state.readOnly?[]:[Ve("br"),this.replaceField,r("replace",()=>ya(t),[He(t,"replace")]),r("replaceAll",()=>PA(t),[He(t,"replace all")])],Ve("button",{name:"close",onclick:()=>Ac(t),"aria-label":He(t,"close"),type:"button"},["×"])])}commit(){let t=new Tc({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:kn.of(t)}))}keydown(t){LS(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?io:so)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),ya(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(kn)&&!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($t).top}}function He(e,t){return e.state.phrase(t)}const xr=30,yr=/[\s\.,:;?!]/;function Di(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-xr),a=Math.min(o,n+xr),l=e.state.sliceDoc(s,a);if(s!=r.from){for(let E=0;E<xr;E++)if(!yr.test(l[E+1])&&yr.test(l[E])){l=l.slice(E);break}}if(a!=o){for(let E=l.length-1;E>l.length-xr;E--)if(!yr.test(l[E-1])&&yr.test(l[E])){l=l.slice(0,E);break}}return Me.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const vA=Me.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"}}),si=[gt,AS.low(yA),vA];function BA(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 Vr=Co.define(),FA=wE.define({create(){return vt.none},update(e,t){for(const n of t.effects)if(n.is(Vr)){if(!n.value)return vt.none;const{from:r,to:o,message:s}=n.value;return vt.set([vt.mark({class:"cm-sql-error",attributes:{title:s}}).range(r,o)])}return e},provide:e=>Me.decorations.from(e)}),GA=Me.baseTheme({".cm-sql-error":{textDecoration:"underline wavy #f85149",textUnderlineOffset:"3px",background:"rgba(248, 81, 73, 0.08)"}}),wA=Me.theme({"&":{background:"#f6f8fa",color:"#1f2328"},".cm-content":{caretColor:"#1f2328"},".cm-cursor":{borderLeftColor:"#1f2328"},".cm-selectionBackground":{background:"#b3d4fc"},"&.cm-focused .cm-selectionBackground":{background:"#b3d4fc"},".cm-gutters":{background:"#f0f2f5",color:"#8c959f",border:"none",borderRight:"1px solid #d0d7de"},".cm-activeLineGutter":{background:"#e8f0fe"},".cm-activeLine":{background:"#eaf0fb"},".cm-matchingBracket":{background:"#c8e6c9",outline:"1px solid #66bb6a"},".cm-foldPlaceholder":{background:"#eaeef2",border:"1px solid #d0d7de",color:"#57606a",borderRadius:3,padding:"0 4px"},".cm-tooltip":{background:"#ffffff",border:"1px solid #d0d7de",borderRadius:6,boxShadow:"0 4px 12px rgba(0,0,0,0.12)"},".cm-tooltip.cm-tooltip-autocomplete":{"& > ul > li":{padding:"3px 8px"},"& > ul > li[aria-selected]":{background:"#dbeafe",color:"#0550ae"}},".cm-searchMatch":{background:"#fff3b0",outline:"1px solid #f5c518"},".cm-searchMatch.cm-searchMatch-selected":{background:"#f5c518"},".cm-panels":{background:"#f0f2f5",borderTop:"1px solid #d0d7de"},".cm-panel":{padding:"6px 8px"},".cm-panel input":{background:"#fff",border:"1px solid #d0d7de",borderRadius:4,padding:"2px 6px",fontSize:12},".cm-panel button":{background:"#f6f8fa",border:"1px solid #d0d7de",borderRadius:4,padding:"2px 8px",cursor:"pointer",fontSize:12,marginLeft:4}},{dark:!1}),HA=Me.theme({".cm-panels":{background:"#161b22",borderTop:"1px solid #30363d"},".cm-panel input":{background:"#0d1117",border:"1px solid #30363d",color:"#e6edf3",borderRadius:4,padding:"2px 6px",fontSize:12},".cm-panel button":{background:"#21262d",border:"1px solid #30363d",color:"#e6edf3",borderRadius:4,padding:"2px 8px",cursor:"pointer",fontSize:12,marginLeft:4},".cm-tooltip":{background:"#1c2128",border:"1px solid #30363d",borderRadius:6,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"},".cm-tooltip.cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{background:"#1f3858",color:"#58a6ff"}},".cm-matchingBracket":{background:"#1f3858",outline:"1px solid #388bfd"},".cm-searchMatch":{background:"#3d3000",outline:"1px solid #e3b341"},".cm-searchMatch.cm-searchMatch-selected":{background:"#6a4e00"}},{dark:!0});function Mi({value:e,onChange:t,onRun:n,themeMode:r,autoFocus:o,schema:s,errorMessage:a}){const l=le[r],E=f.useRef(null),c=f.useRef(null),[d,T]=f.useState(!1),S=f.useRef(n),u=f.useRef(t),R=f.useRef(new _S);return S.current=n,u.current=t,f.useEffect(()=>{if(!E.current)return;const I=mS.of([{key:"Shift-Enter",run:()=>(S.current(),!0)},{key:"Ctrl-Enter",mac:"Cmd-Enter",run:()=>(S.current(),!0)},{key:"Ctrl-/",mac:"Cmd-/",run:gS},xS,...yS,...DS,...MS,...bA,...PS,...bS]),N=Me.updateListener.of(m=>{m.docChanged&&u.current(m.state.doc.toString())}),A=Me.domEventHandlers({focus:(m,M)=>{Vu(M)},blur:(m,M)=>{Wu(M)}}),p=Me.theme({"&":{background:l.editorBg,fontFamily:l.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?hr({schema:s,upperCaseKeywords:!1}):hr({upperCaseKeywords:!1}),h=[I,N,A,p,R.current.of(O),vS({closeOnBlur:!1,override:[Xu]}),BS(),FS(),GS(),wS(),HS(),YS(),kS(),Me.lineWrapping,fA({top:!0}),FA,GA,...r==="dark"?[US,HA]:[wA,VS(WS)]],C=HE.create({doc:e,extensions:h}),_=new Me({state:C,parent:E.current});return c.current=_,o&&_.focus(),()=>{_.destroy(),c.current=null}},[r]),f.useEffect(()=>{const I=c.current;if(!I)return;const N=s?hr({schema:s,upperCaseKeywords:!1}):hr({upperCaseKeywords:!1});I.dispatch({effects:R.current.reconfigure(N)})},[s]),f.useEffect(()=>{const I=c.current;if(!I)return;const N=I.state.doc.toString();N!==e&&I.dispatch({changes:{from:0,to:N.length,insert:e}})},[e]),f.useEffect(()=>{const I=c.current;if(!I)return;if(!a){I.dispatch({effects:Vr.of(null)});return}const N=BA(a),A=I.state.doc;if(N&&N.line>=1&&N.line<=A.lines){const p=A.line(N.line),O=p.from+Math.max(0,N.col-1),h=Math.max(O+1,p.to);I.dispatch({effects:Vr.of({from:Math.min(O,A.length),to:Math.min(h,A.length),message:a})})}else if(A.lines>=1){const p=A.line(1);I.dispatch({effects:Vr.of({from:p.from,to:Math.max(p.from+1,p.to),message:a})})}},[a]),i.jsx("div",{onDragOver:I=>{I.dataTransfer.types.includes(to)&&(I.preventDefault(),T(!0))},onDragLeave:()=>T(!1),onDrop:I=>{const N=c.current;if(!N)return;const A=$E(I.dataTransfer.getData(to));A&&(I.preventDefault(),T(!1),ju(N,A.reference,{x:I.clientX,y:I.clientY}),te.trackUsage(A.name),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:A.name}})))},style:{background:l.editorBg,minHeight:80,border:d?`1px solid ${l.accent}`:"1px solid transparent",borderRadius:6,transition:"border-color 0.15s"},children:i.jsx("div",{ref:E,style:{minHeight:80}})})}Mi.displayName="SQLCellEditor";function YA(e,t){const n=e.split(`
316
+ `),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,E=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:xn(E,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:xn(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(`
317
+ `)},o)),o++;continue}if(/^[-*+]\s/.test(s)){const l=[];for(;o<n.length&&/^[-*+]\s/.test(n[o]);)l.push(n[o].replace(/^[-*+]\s/,"")),o++;r.push(i.jsx("ul",{style:{paddingLeft:20,marginBottom:8,color:t.textSecondary},children:l.map((E,c)=>i.jsx("li",{style:{fontSize:14,fontFamily:t.font,lineHeight:1.6,marginBottom:2},children:xn(E,t)},c))},o));continue}if(/^\d+\.\s/.test(s)){const l=[];for(;o<n.length&&/^\d+\.\s/.test(n[o]);)l.push(n[o].replace(/^\d+\.\s/,"")),o++;r.push(i.jsx("ol",{style:{paddingLeft:20,marginBottom:8,color:t.textSecondary},children:l.map((E,c)=>i.jsx("li",{style:{fontSize:14,fontFamily:t.font,lineHeight:1.6,marginBottom:2},children:xn(E,t)},c))},o));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:xn(s,t)},o)),o++}return r}function xn(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(/\*(.+?)\*/),E=r.match(/`(.+?)`/),c=r.match(/\[(.+?)\]\((.+?)\)/),d=[s?{match:s,type:"boldItalic"}:null,a?{match:a,type:"bold"}:null,l?{match:l,type:"italic"}:null,E?{match:E,type:"code"}:null,c?{match:c,type:"link"}:null].filter(Boolean);if(d.length===0){n.push(i.jsx(En.Fragment,{children:r},o++));break}const T=d.reduce((u,R)=>(u.match.index??0)<(R.match.index??0)?u:R),S=T.match.index??0;switch(S>0&&n.push(i.jsx(En.Fragment,{children:r.slice(0,S)},o++)),T.type){case"boldItalic":n.push(i.jsx("strong",{style:{fontStyle:"italic"},children:T.match[1]},o++));break;case"bold":n.push(i.jsx("strong",{children:T.match[1]},o++));break;case"italic":n.push(i.jsx("em",{children:T.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:T.match[1]},o++));break;case"link":n.push(i.jsx("a",{href:T.match[2],target:"_blank",rel:"noopener noreferrer",style:{color:t.accent,textDecoration:"underline"},children:T.match[1]},o++));break}r=r.slice(S+T.match[0].length)}return i.jsx(i.Fragment,{children:n})}function kA({value:e,onChange:t,onRun:n,themeMode:r}){const o=le[r],[s,a]=f.useState(!1),l=f.useRef(null);f.useEffect(()=>{if(s&&l.current){l.current.focus();const T=l.current;T.style.height="auto",T.style.height=`${Math.max(T.scrollHeight,80)}px`}},[s]);const E=()=>{a(!1)},c=T=>{if(T.key==="Escape"&&a(!1),T.key==="Enter"&&T.shiftKey&&(T.preventDefault(),a(!1),n==null||n()),T.key==="Tab"){T.preventDefault();const S=T.currentTarget,u=S.selectionStart,R=S.selectionEnd,I=e.slice(0,u)+" "+e.slice(R);t(I),requestAnimationFrame(()=>{S.selectionStart=S.selectionEnd=u+2})}},d=T=>{t(T.target.value);const S=T.target;S.style.height="auto",S.style.height=`${Math.max(S.scrollHeight,80)}px`};return s?i.jsx("textarea",{ref:l,value:e,onChange:d,onBlur:E,onKeyDown:c,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:YA(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 VA({cell:e,themeMode:t,onApplyParam:n}){const{dispatch:r}=Se(),o=le[t],[s,a]=f.useState(!1),l=e.paramConfig??{paramType:"text",label:"Parameter",defaultValue:"",options:[]},E=e.paramValue??l.defaultValue,c=u=>{r({type:"UPDATE_CELL",id:e.id,updates:{paramConfig:{...l,...u}}})},d=u=>{r({type:"SET_PARAM_VALUE",id:e.id,value:u})},T=(l.options??[]).map(u=>u.trim()).filter(Boolean),S=e.name?`{{${e.name}}}`:null;return i.jsxs("div",{style:{background:o.cellBg,border:`1px solid ${o.cellBorder}`,borderLeft:"3px solid #e3b341",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:"#e3b341",fontFamily:o.fontMono,textTransform:"uppercase"},children:"Configure Parameter"}),i.jsx("button",{onClick:()=>a(!1),title:"Done",style:{background:"#e3b341",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:u=>r({type:"UPDATE_CELL",id:e.id,updates:{name:u.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:u=>c({label:u.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:u=>c({paramType:u.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:u=>c({defaultValue:u.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(`
318
+ `),onChange:u=>c({options:u.target.value.split(`
319
+ `)}),rows:4,placeholder:`Option A
320
+ Option B
321
+ 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(u=>!u),title:s?"Close config":"Configure parameter",style:{background:s?"#e3b34118":"transparent",border:`1px solid ${s?"#e3b341":o.cellBorder}`,borderRadius:5,cursor:"pointer",color:s?"#e3b341":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:E,onChange:u=>d(u.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:T.length===0?i.jsx("option",{value:"",children:"— no options configured —"}):T.map(u=>i.jsx("option",{value:u,children:u},u))}):i.jsx("input",{type:l.paramType,value:E,onChange:u=>d(u.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}}),S&&i.jsx("span",{style:{fontSize:10,fontFamily:o.fontMono,color:"#e3b341",opacity:.8},children:S})]}),E&&i.jsx("span",{style:{fontSize:12,fontFamily:o.fontMono,color:o.textPrimary,background:"#e3b34118",border:"1px solid #e3b34140",borderRadius:4,padding:"2px 8px",flexShrink:0},children:E}),e.name&&n&&i.jsx("button",{onClick:()=>n(e.name),title:`Re-run cells that use {{${e.name}}}`,style:{background:"#e3b341",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"})]})]})}const WA=[{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
322
+ category,
323
+ COUNT(*) AS count,
324
+ SUM(amount) AS total
325
+ FROM read_csv_auto('data/filename.csv')
326
+ GROUP BY category
327
+ ORDER BY total DESC`},{id:"filter-date",label:"Filter by date range",description:"Filter rows between two dates",category:"SQL",code:`SELECT *
328
+ FROM read_csv_auto('data/filename.csv')
329
+ WHERE date_column >= '2024-01-01'
330
+ 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
331
+ *,
332
+ ROW_NUMBER() OVER (PARTITION BY category ORDER BY amount DESC) AS rank
333
+ 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 (
334
+ SELECT *
335
+ FROM read_csv_auto('data/filename.csv')
336
+ WHERE amount > 0
337
+ )
338
+ SELECT
339
+ category,
340
+ SUM(amount) AS total
341
+ FROM base
342
+ 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
343
+ FROM read_csv_auto('data/table_a.csv') AS a
344
+ JOIN read_csv_auto('data/table_b.csv') AS b
345
+ ON a.id = b.id`},{id:"pivot",label:"Pivot / unpivot",description:"Pivot a column into multiple columns",category:"SQL",code:`SELECT *
346
+ FROM (
347
+ SELECT category, quarter, amount
348
+ FROM read_csv_auto('data/filename.csv')
349
+ ) 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" {
350
+ domain = "analytics"
351
+ type = "custom"
352
+ description = "Describe what this block does"
353
+ owner = "data-team"
354
+ tags = ["analytics"]
355
+
356
+ query = """
357
+ SELECT *
358
+ FROM read_csv_auto('data/filename.csv')
359
+ LIMIT 100
360
+ """
361
+
362
+ visualization {
363
+ chart = "table"
364
+ }
365
+ }`},{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" {
366
+ domain = "revenue"
367
+ type = "custom"
368
+ description = "Revenue grouped by segment"
369
+ owner = "data-team"
370
+ tags = ["revenue"]
371
+
372
+ params {
373
+ period = "current_quarter"
374
+ }
375
+
376
+ query = """
377
+ SELECT
378
+ segment_tier AS segment,
379
+ SUM(amount) AS revenue
380
+ FROM read_csv_auto('data/revenue.csv')
381
+ WHERE fiscal_period = \${period}
382
+ GROUP BY segment_tier
383
+ ORDER BY revenue DESC
384
+ """
385
+
386
+ visualization {
387
+ chart = "bar"
388
+ x = segment
389
+ y = revenue
390
+ }
391
+
392
+ tests {
393
+ assert row_count > 0
394
+ }
395
+ }`},{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)
396
+ FROM fct_revenue
397
+ GROUP BY @dim(segment)
398
+ 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" {
399
+ domain = "revenue"
400
+ type = "semantic"
401
+ owner = "data-team"
402
+ description = "Annual Recurring Revenue by subscription plan tier"
403
+ tags = ["arr", "revenue", "saas"]
404
+
405
+ metric = "arr"
406
+ dimensions = ["plan_tier"]
407
+
408
+ visualization {
409
+ chart = "bar"
410
+ x = plan_tier
411
+ y = arr
412
+ }
413
+
414
+ tests {
415
+ assert row_count > 0
416
+ }
417
+ }`},{id:"revenue-by-segment",label:"Revenue by segment",description:"Aggregate revenue totals, deal count, and average deal size per segment",category:"Analysis",code:`SELECT
418
+ segment_tier,
419
+ SUM(amount) AS total_revenue,
420
+ COUNT(*) AS deals,
421
+ ROUND(AVG(amount), 0) AS avg_deal
422
+ FROM read_csv_auto('data/revenue.csv')
423
+ GROUP BY segment_tier
424
+ ORDER BY total_revenue DESC`},{id:"quarterly-trend",label:"Quarterly trend",description:"Revenue totals grouped by fiscal year and quarter",category:"Analysis",code:`SELECT
425
+ fiscal_year || ' ' || fiscal_quarter AS period,
426
+ SUM(amount) AS revenue
427
+ FROM read_csv_auto('data/revenue.csv')
428
+ GROUP BY fiscal_year, fiscal_quarter
429
+ ORDER BY fiscal_year, fiscal_quarter`}];function jA({onInsert:e,themeMode:t,cellType:n}){const r=le[t],[o,s]=f.useState(!1),[a,l]=f.useState(null),E=f.useRef(null),c=WA.filter(S=>n==="dql"?S.category==="DQL":S.category==="SQL"||S.category==="Analysis"),d=Array.from(new Set(c.map(S=>S.category)));f.useEffect(()=>{if(!o)return;function S(u){E.current&&!E.current.contains(u.target)&&s(!1)}return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[o]);function T(S){e(S),s(!1)}return i.jsxs("div",{ref:E,style:{position:"relative",display:"inline-block"},children:[i.jsxs("button",{title:"Insert template snippet",onClick:()=>s(S=>!S),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(S=>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:S}),c.filter(u=>u.category===S).map(u=>i.jsxs("button",{onMouseEnter:()=>l(u.id),onMouseLeave:()=>l(null),onClick:()=>T(u.code),style:{width:"100%",padding:"7px 12px",textAlign:"left",background:a===u.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:u.label}),i.jsx("span",{style:{fontSize:11,fontFamily:r.font,color:r.textMuted,lineHeight:1.4},children:u.description})]},u.id))]},S))})]})}function is(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function $A(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 XA({cell:e,onClose:t,onSaved:n}){const{state:r,dispatch:o}=Se(),s=le[r.themeMode],a=f.useRef(null),[l,E]=f.useState(e.name||"new_block"),[c,d]=f.useState(""),[T,S]=f.useState(""),[u,R]=f.useState(""),[I,N]=f.useState(e.content),[A,p]=f.useState(!1),[O,h]=f.useState(null),C=f.useMemo(()=>$A(I),[I]);f.useEffect(()=>{var b;(b=a.current)==null||b.focus()},[]),f.useEffect(()=>{const b=g=>{g.key==="Escape"&&t()};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[t]);const _=r.semanticLayer.domains,m=`${c.trim()?`blocks/${is(c)}/`:"blocks/"}${is(l)||"new-block"}.dql`,M=async()=>{var b;if(!l.trim()){h("Block name is required.");return}if(!I.trim()){h("Block content is required.");return}p(!0),h(null);try{const g=await te.saveAsBlock({cellId:e.id,notebookPath:((b=r.activeFile)==null?void 0:b.path)??null,name:l.trim(),domain:c.trim()||void 0,content:I,description:T.trim()||void 0,tags:u.split(",").map(L=>L.trim()).filter(Boolean),metricRefs:C}),x={name:`${is(l)||"new-block"}.dql`,path:g.path,type:"block",folder:"blocks"};r.files.some(L=>L.path===g.path)||o({type:"FILE_ADDED",file:x});const F=await te.openBlockStudio(g.path);o({type:"OPEN_BLOCK_STUDIO",file:x,payload:F}),n==null||n({...g,name:l.trim()}),t()}catch(g){h(g instanceof Error?g.message:String(g))}finally{p(!1)}},y={width:"100%",background:s.inputBg,border:`1px solid ${O?s.error:s.inputBorder}`,borderRadius:6,color:s.textPrimary,fontSize:13,fontFamily:s.font,padding:"8px 12px",outline:"none",boxSizing:"border-box"};return i.jsx("div",{onClick:b=>{b.target===b.currentTarget&&t()},style:{position:"fixed",inset:0,background:s.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:s.modalBg,border:`1px solid ${s.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:s.textPrimary,fontFamily:s.font},children:"Save as Block"}),i.jsx("button",{onClick:t,style:{background:"transparent",border:"none",color:s.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.jsx("label",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font},children:"Block Name"}),i.jsx("input",{ref:a,value:l,onChange:b=>E(b.target.value),style:y})]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font},children:"Domain"}),i.jsx("input",{value:c,onChange:b=>d(b.target.value),list:"semantic-domain-options",style:y,placeholder:"finance"}),i.jsx("datalist",{id:"semantic-domain-options",children:_.map(b=>i.jsx("option",{value:b},b))})]})]}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font},children:"Description"}),i.jsx("input",{value:T,onChange:b=>S(b.target.value),style:y})]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font},children:"Tags"}),i.jsx("input",{value:u,onChange:b=>R(b.target.value),style:y,placeholder:"revenue, dashboard"})]})]}),i.jsx("div",{style:{fontSize:12,color:s.textMuted,fontFamily:s.fontMono,padding:"8px 12px",background:s.pillBg,borderRadius:6},children:m}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font},children:"Content Preview"}),i.jsx("textarea",{value:I,onChange:b=>N(b.target.value),style:{...y,minHeight:220,resize:"vertical",fontFamily:s.fontMono,lineHeight:1.5}})]}),C.length>0&&i.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,padding:"10px 12px",background:s.pillBg,borderRadius:6},children:[i.jsx("span",{style:{fontSize:11,color:s.textMuted,fontFamily:s.font},children:"Detected semantic refs:"}),C.map(b=>i.jsx("span",{style:{fontSize:11,color:s.accent,fontFamily:s.fontMono,background:`${s.accent}18`,borderRadius:999,padding:"2px 8px"},children:b},b))]}),O&&i.jsx("div",{style:{fontSize:12,color:s.error,fontFamily:s.font},children:O})]}),i.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${s.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[i.jsx("button",{onClick:t,style:{background:s.btnBg,border:`1px solid ${s.btnBorder}`,borderRadius:6,color:s.textSecondary,cursor:"pointer",fontSize:13,fontFamily:s.font,padding:"7px 16px"},children:"Cancel"}),i.jsx("button",{onClick:M,disabled:A,style:{background:s.accent,border:`1px solid ${s.accent}`,borderRadius:6,color:"#fff",cursor:A?"not-allowed":"pointer",fontSize:13,fontFamily:s.font,padding:"7px 20px",opacity:A?.6:1},children:A?"Saving...":"Save Block"})]})]})})}function KA(e){let t=e;try{const c=JSON.parse(e);c&&typeof c.error=="string"&&(t=c.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 E=t.replace(/^(Parser Error|Binder Error|Conversion Error|Invalid Input Error|IO Error|Constraint Error):\s*/i,"").trim();return{type:n,message:E,line:r,near:s,hint:l}}function zA(e,t){const n=e.length,r=t.length,o=Array.from({length:n+1},(s,a)=>Array.from({length:r+1},(l,E)=>a===0?E:E===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 Da(e,t){const n=e.toLowerCase();let r=null,o=4;for(const s of t){const a=zA(n,s.toLowerCase());a<o&&(o=a,r=s)}return r}function JA({message:e,themeMode:t,onFix:n,schemaTables:r}){const o=le[t],s=KA(e);let a=null;if(r&&r.length>0&&s.type==="Reference Error"){const E=/column.*not found|Referenced column/i.test(s.message),c=/table.*not found|Table.*does not exist/i.test(s.message);if(E&&s.near){const d=r.flatMap(S=>S.columns.map(u=>u.name)),T=Da(s.near,d);T&&(a=`Did you mean column "${T}"?`)}else if(c&&s.near){const d=Da(s.near,r.map(T=>T.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:E=>{E.currentTarget.style.background=`${o.accent}25`},onMouseLeave:E=>{E.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"]})]})}const Wr={source_table:"#8b949e",block:"#56d364",metric:"#388bfd",dimension:"#e3b341",domain:"#d2a8ff",chart:"#f778ba"},qA={source_table:"TBL",block:"BLK",metric:"MET",dimension:"DIM",chart:"CHT",domain:"DOM"},QA={certified:"#56d364",draft:"#8b949e",review:"#e3b341",deprecated:"#f85149"};function ZA(e){const t=e.match(/^\s*block\s+"([^"]+)"/i);return t?t[1]:null}function eI(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 tI(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 Ma({node:e,t}){const n=Wr[e.type]??"#8b949e",r=qA[e.type]??e.type.slice(0,3).toUpperCase(),o=e.status?QA[e.status]:void 0;return i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"2px 0",fontSize:11,color:t.textPrimary},children:[i.jsx("span",{style:{color:n,fontSize:9,fontWeight:700,width:26,flexShrink:0},children:r}),i.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:e.name}),e.domain&&i.jsx("span",{style:{fontSize:9,color:t.textMuted},children:e.domain}),o&&i.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:o,flexShrink:0}})]})}function nI({cellContent:e,cellType:t,cellName:n,themeMode:r,t:o}){const[s,a]=f.useState(!1),[l,E]=f.useState(!1),[c,d]=f.useState([]),[T,S]=f.useState([]),[u,R]=f.useState([]),[I,N]=f.useState({metrics:[],dimensions:[]}),[A,p]=f.useState(null),h=(t==="dql"?ZA(e):null)||n,C=f.useCallback(async()=>{if(!(!h&&t!=="sql")){E(!0),p(null);try{const m=eI(e);if(R(m),N(tI(e)),h){const M=await te.fetchBlockLineage(h);M&&(d(M.ancestors??[]),S(M.descendants??[]))}else{const y=(await te.fetchLineage()).nodes.filter(b=>m.some(g=>b.name===g||b.id===`table:${g}`||b.id===`block:${g}`));d(y),S([])}}catch{p("Failed to load lineage")}finally{E(!1)}}},[h,e,t]);f.useEffect(()=>{s&&C()},[s,C]);const _=u.length>0||I.metrics.length>0||I.dimensions.length>0;return e.trim()?i.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`},children:[i.jsxs("button",{onClick:()=>a(m=>!m),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 12px",background:s?`${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:s?"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"})})]}),s&&i.jsx("div",{style:{padding:"6px 12px 8px",fontSize:11},children:l?i.jsx("div",{style:{color:o.textMuted,padding:"4px 0"},children:"Loading lineage..."}):A?i.jsx("div",{style:{color:o.error,padding:"4px 0"},children:A}):i.jsxs(i.Fragment,{children:[u.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 (",u.length,")"]}),u.map(m=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[i.jsx("span",{style:{color:Wr.source_table,fontSize:9,fontWeight:700,width:26},children:"TBL"}),i.jsx("span",{children:m})]},m))]}),I.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 (",I.metrics.length,")"]}),I.metrics.map(m=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[i.jsx("span",{style:{color:Wr.metric,fontSize:9,fontWeight:700,width:26},children:"MET"}),i.jsx("span",{children:m})]},m))]}),I.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 (",I.dimensions.length,")"]}),I.dimensions.map(m=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[i.jsx("span",{style:{color:Wr.dimension,fontSize:9,fontWeight:700,width:26},children:"DIM"}),i.jsx("span",{children:m})]},m))]}),c.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:["Upstream (",c.length,")"]}),c.map(m=>i.jsx(Ma,{node:m,t:o},m.id))]}),T.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:["Downstream (",T.length,")"]}),T.map(m=>i.jsx(Ma,{node:m,t:o},m.id))]}),!_&&c.length===0&&T.length===0&&i.jsx("div",{style:{color:o.textMuted,padding:"2px 0"},children:"No lineage dependencies detected for this cell."})]})})]}):null}const G=e=>e.flatMap(rI),rI=e=>jr(sI(e)).map(oI),oI=e=>e.replace(/ +/g," ").trim(),sI=e=>({type:"mandatory_block",items:Pi(e,0)[0]}),Pi=(e,t,n)=>{const r=[];for(;e[t];){const[o,s]=iI(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]},iI=(e,t)=>{const n=[];for(;;){const[r,o]=aI(e,t);if(r)n.push(r),t=o;else break}return n.length===1?[n[0],t]:[{type:"concatenation",items:n},t]},aI=(e,t)=>{if(e[t]==="{")return lI(e,t+1);if(e[t]==="[")return EI(e,t+1);{let n="";for(;e[t]&&/[A-Za-z0-9_ ]/.test(e[t]);)n+=e[t],t++;return[n,t]}},lI=(e,t)=>{const[n,r]=Pi(e,t,"}");return[{type:"mandatory_block",items:n},r]},EI=(e,t)=>{const[n,r]=Pi(e,t,"]");return[{type:"optional_block",items:n},r]},jr=e=>{if(typeof e=="string")return[e];if(e.type==="concatenation")return e.items.map(jr).reduce(cI,[""]);if(e.type==="mandatory_block")return e.items.flatMap(jr);if(e.type==="optional_block")return["",...e.items.flatMap(jr)];throw new Error(`Unknown node type: ${e}`)},cI=(e,t)=>{const n=[];for(const r of e)for(const o of t)n.push(r+o);return n};var X;(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"})(X=X||(X={}));const Ic=e=>({type:X.EOF,raw:"«EOF»",text:"«EOF»",start:e}),yt=Ic(1/0),Jt=e=>t=>t.type===e.type&&t.text===e.text,Dt={ARRAY:Jt({text:"ARRAY",type:X.RESERVED_DATA_TYPE}),BY:Jt({text:"BY",type:X.RESERVED_KEYWORD}),SET:Jt({text:"SET",type:X.RESERVED_CLAUSE}),STRUCT:Jt({text:"STRUCT",type:X.RESERVED_DATA_TYPE}),WINDOW:Jt({text:"WINDOW",type:X.RESERVED_CLAUSE}),VALUES:Jt({text:"VALUES",type:X.RESERVED_CLAUSE})},Nc=e=>e===X.RESERVED_DATA_TYPE||e===X.RESERVED_KEYWORD||e===X.RESERVED_FUNCTION_NAME||e===X.RESERVED_KEYWORD_PHRASE||e===X.RESERVED_DATA_TYPE_PHRASE||e===X.RESERVED_CLAUSE||e===X.RESERVED_SELECT||e===X.RESERVED_SET_OPERATION||e===X.RESERVED_JOIN||e===X.ARRAY_KEYWORD||e===X.CASE||e===X.END||e===X.WHEN||e===X.ELSE||e===X.THEN||e===X.LIMIT||e===X.BETWEEN||e===X.AND||e===X.OR||e===X.XOR,TI=e=>e===X.AND||e===X.OR||e===X.XOR,dI=["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"],SI=["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"],uI=["ARRAY","BOOL","BYTES","DATE","DATETIME","GEOGRAPHY","INTERVAL","INT64","INT","SMALLINT","INTEGER","BIGINT","TINYINT","BYTEINT","NUMERIC","DECIMAL","BIGNUMERIC","BIGDECIMAL","FLOAT64","STRING","STRUCT","TIME","TIMEZONE"],RI=G(["SELECT [ALL | DISTINCT] [AS STRUCT | AS VALUE]"]),AI=G(["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"]),Pa=G(["CREATE [OR REPLACE] [TEMP|TEMPORARY|SNAPSHOT|EXTERNAL] TABLE [IF NOT EXISTS]"]),as=G(["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"]),II=G(["UNION {ALL | DISTINCT}","EXCEPT DISTINCT","INTERSECT DISTINCT"]),NI=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN"]),OI=G(["TABLESAMPLE SYSTEM","ANY TYPE","ALL COLUMNS","NOT DETERMINISTIC","{ROWS | RANGE} BETWEEN","IS [NOT] DISTINCT FROM"]),fI=G([]),pI={name:"bigquery",tokenizerOptions:{reservedSelect:RI,reservedClauses:[...AI,...as,...Pa],reservedSetOperations:II,reservedJoins:NI,reservedKeywordPhrases:OI,reservedDataTypePhrases:fI,reservedKeywords:SI,reservedDataTypes:uI,reservedFunctionNames:dI,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:hI},formatOptions:{onelineClauses:[...Pa,...as],tabularOnelineClauses:as}};function hI(e){return CI(LI(e))}function CI(e){let t=yt;return e.map(n=>n.text==="OFFSET"&&t.text==="["?(t=n,Object.assign(Object.assign({},n),{type:X.RESERVED_FUNCTION_NAME})):(t=n,n))}function LI(e){var t;const n=[];for(let r=0;r<e.length;r++){const o=e[r];if((Dt.ARRAY(o)||Dt.STRUCT(o))&&((t=e[r+1])===null||t===void 0?void 0:t.text)==="<"){const s=_I(e,r+1),a=e.slice(r,s+1);n.push({type:X.IDENTIFIER,raw:a.map(ba("raw")).join(""),text:a.map(ba("text")).join(""),start:o.start}),r=s}else n.push(o)}return n}const ba=e=>t=>t.type===X.IDENTIFIER||t.type===X.COMMA?t[e]+" ":t[e];function _I(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 mI=["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"],gI=["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"],xI=["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"],yI=G(["SELECT [DISTINCT]","MODIFY QUERY SELECT [DISTINCT]"]),DI=G(["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]"]),Ua=G(["CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS]"]),ls=G(["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"]),MI=G(["UNION [ALL | DISTINCT]","PARALLEL WITH"]),PI=G(["[GLOBAL] [INNER|LEFT|RIGHT|FULL|CROSS] [OUTER|SEMI|ANTI|ANY|ALL|ASOF] JOIN","[LEFT] ARRAY JOIN"]),bI=G(["{ROWS | RANGE} BETWEEN","ALTER MATERIALIZE STATISTICS"]),UI={name:"clickhouse",tokenizerOptions:{reservedSelect:yI,reservedClauses:[...DI,...Ua,...ls],reservedSetOperations:MI,reservedJoins:PI,reservedKeywordPhrases:bI,reservedKeywords:gI,reservedDataTypes:xI,reservedFunctionNames:mI,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:vI},formatOptions:{onelineClauses:[...Ua,...ls],tabularOnelineClauses:ls}};function vI(e){return e.map((t,n)=>{const r=e[n+1]||yt,o=e[n-1]||yt;return t.type===X.RESERVED_SELECT&&(r.type===X.COMMA||o.type===X.RESERVED_CLAUSE||o.type===X.COMMA)?Object.assign(Object.assign({},t),{type:X.RESERVED_KEYWORD}):Dt.SET(t)&&r.type===X.OPEN_PAREN?Object.assign(Object.assign({},t),{type:X.RESERVED_FUNCTION_NAME}):t})}const BI=["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"],FI=["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"],GI=["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"],wI=G(["SELECT [ALL | DISTINCT]"]),HI=G(["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"]),va=G(["CREATE [GLOBAL TEMPORARY | EXTERNAL] TABLE [IF NOT EXISTS]"]),Es=G(["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"]),YI=G(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),kI=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN"]),VI=G(["ON DELETE","ON UPDATE","SET NULL","{ROWS | RANGE} BETWEEN"]),WI=G([]),jI={name:"db2",tokenizerOptions:{reservedSelect:wI,reservedClauses:[...HI,...va,...Es],reservedSetOperations:YI,reservedJoins:kI,reservedKeywordPhrases:VI,reservedDataTypePhrases:WI,reservedKeywords:FI,reservedDataTypes:GI,reservedFunctionNames:BI,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:[...va,...Es],tabularOnelineClauses:Es}},$I=["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"],XI=["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"],KI=["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"],zI=G(["SELECT [ALL | DISTINCT]"]),JI=G(["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"]),Ba=G(["CREATE [OR REPLACE] TABLE"]),cs=G(["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}"]),qI=G(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),QI=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","[LEFT | RIGHT] EXCEPTION JOIN","{INNER | CROSS} JOIN"]),ZI=G(["ON DELETE","ON UPDATE","SET NULL","{ROWS | RANGE} BETWEEN"]),eN=G([]),tN={name:"db2i",tokenizerOptions:{reservedSelect:zI,reservedClauses:[...JI,...Ba,...cs],reservedSetOperations:qI,reservedJoins:QI,reservedKeywordPhrases:ZI,reservedDataTypePhrases:eN,reservedKeywords:XI,reservedDataTypes:KI,reservedFunctionNames:$I,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:[...Ba,...cs],tabularOnelineClauses:cs}},nN=["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"],rN=["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"],oN=["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"],sN=G(["SELECT [ALL | DISTINCT]"]),iN=G(["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"]),Fa=G(["CREATE [OR REPLACE] [TEMPORARY | TEMP] TABLE [IF NOT EXISTS]"]),Ts=G(["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]"]),aN=G(["UNION [ALL | BY NAME]","EXCEPT [ALL]","INTERSECT [ALL]"]),lN=G(["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"]),EN=G(["{ROWS | RANGE | GROUPS} BETWEEN","SIMILAR TO","IS [NOT] DISTINCT FROM"]),cN=G(["TIMESTAMP WITH TIME ZONE"]),TN={name:"duckdb",tokenizerOptions:{reservedSelect:sN,reservedClauses:[...iN,...Fa,...Ts],reservedSetOperations:aN,reservedJoins:lN,reservedKeywordPhrases:EN,reservedDataTypePhrases:cN,supportsXor:!0,reservedKeywords:rN,reservedDataTypes:oN,reservedFunctionNames:nN,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:[...Fa,...Ts],tabularOnelineClauses:Ts}},dN=["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"],SN=["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"],uN=["ARRAY","BIGINT","BINARY","BOOLEAN","CHAR","DATE","DECIMAL","DOUBLE","FLOAT","INT","INTEGER","INTERVAL","MAP","NUMERIC","PRECISION","SMALLINT","STRUCT","TIMESTAMP","VARCHAR"],RN=G(["SELECT [ALL | DISTINCT]"]),AN=G(["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"]),Ga=G(["CREATE [TEMPORARY] [EXTERNAL] TABLE [IF NOT EXISTS]"]),ds=G(["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"]),IN=G(["UNION [ALL | DISTINCT]"]),NN=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","LEFT SEMI JOIN"]),ON=G(["{ROWS | RANGE} BETWEEN"]),fN=G([]),pN={name:"hive",tokenizerOptions:{reservedSelect:RN,reservedClauses:[...AN,...Ga,...ds],reservedSetOperations:IN,reservedJoins:NN,reservedKeywordPhrases:ON,reservedDataTypePhrases:fN,reservedKeywords:SN,reservedDataTypes:uN,reservedFunctionNames:dN,extraParens:["[]"],stringTypes:['""-bs',"''-bs"],identTypes:["``"],variableTypes:[{quote:"{}",prefixes:["$"],requirePrefix:!0}],operators:["%","~","^","|","&","<=>","==","!","||"]},formatOptions:{onelineClauses:[...Ga,...ds],tabularOnelineClauses:ds}};function go(e){return e.map((t,n)=>{const r=e[n+1]||yt;if(Dt.SET(t)&&r.text==="(")return Object.assign(Object.assign({},t),{type:X.RESERVED_FUNCTION_NAME});const o=e[n-1]||yt;return Dt.VALUES(t)&&o.text==="="?Object.assign(Object.assign({},t),{type:X.RESERVED_FUNCTION_NAME}):t})}const hN=["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"],CN=["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"],LN=["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"],_N=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),mN=G(["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"]),wa=G(["CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS]"]),Ss=G(["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"]),gN=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]","MINUS [ALL | DISTINCT]"]),xN=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),yN=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),DN=G([]),MN={name:"mariadb",tokenizerOptions:{reservedSelect:_N,reservedClauses:[...mN,...wa,...Ss],reservedSetOperations:gN,reservedJoins:xN,reservedKeywordPhrases:yN,reservedDataTypePhrases:DN,supportsXor:!0,reservedKeywords:hN,reservedDataTypes:CN,reservedFunctionNames:LN,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:go},formatOptions:{onelineClauses:[...wa,...Ss],tabularOnelineClauses:Ss}},PN=["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"],bN=["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"],UN=["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"],vN=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),BN=G(["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"]),Ha=G(["CREATE [TEMPORARY] TABLE [IF NOT EXISTS]"]),us=G(["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"]),FN=G(["UNION [ALL | DISTINCT]"]),GN=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),wN=G(["ON {UPDATE | DELETE} [SET NULL]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),HN=G([]),YN={name:"mysql",tokenizerOptions:{reservedSelect:vN,reservedClauses:[...BN,...Ha,...us],reservedSetOperations:FN,reservedJoins:GN,reservedKeywordPhrases:wN,reservedDataTypePhrases:HN,supportsXor:!0,reservedKeywords:PN,reservedDataTypes:bN,reservedFunctionNames:UN,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:go},formatOptions:{onelineClauses:[...Ha,...us],tabularOnelineClauses:us}},kN=["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"],VN=["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"],WN=["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"],jN=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),$N=G(["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"]),Ya=G(["CREATE [TEMPORARY] TABLE [IF NOT EXISTS]"]),Rs=G(["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"]),XN=G(["UNION [ALL | DISTINCT]"]),KN=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),zN=G(["ON {UPDATE | DELETE} [SET NULL]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),JN=G([]),qN={name:"tidb",tokenizerOptions:{reservedSelect:jN,reservedClauses:[...$N,...Ya,...Rs],reservedSetOperations:XN,reservedJoins:KN,reservedKeywordPhrases:zN,reservedDataTypePhrases:JN,supportsXor:!0,reservedKeywords:kN,reservedDataTypes:VN,reservedFunctionNames:WN,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:go},formatOptions:{onelineClauses:[...Ya,...Rs],tabularOnelineClauses:Rs}},QN=["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"],ZN=["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"],eO=[],tO=G(["SELECT [ALL | DISTINCT]"]),nO=G(["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"]),ka=G(["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"]),rO=G(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),oO=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","INNER JOIN"]),sO=G(["{ROWS | RANGE | GROUPS} BETWEEN"]),iO=G([]),aO={name:"n1ql",tokenizerOptions:{reservedSelect:tO,reservedClauses:[...nO,...ka],reservedSetOperations:rO,reservedJoins:oO,reservedKeywordPhrases:sO,reservedDataTypePhrases:iO,supportsXor:!0,reservedKeywords:ZN,reservedDataTypes:eO,reservedFunctionNames:QN,stringTypes:['""-bs',"''-bs"],identTypes:["``"],extraParens:["[]","{}"],paramTypes:{positional:!0,numbered:["$"],named:["$"]},lineCommentTypes:["#","--"],operators:["%","==",":","||"]},formatOptions:{onelineClauses:ka}},lO=["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"],EO=["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"],cO=["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"],TO=G(["SELECT [ALL | DISTINCT | UNIQUE]"]),dO=G(["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"]),Va=G(["CREATE [GLOBAL TEMPORARY | PRIVATE TEMPORARY | SHARDED | DUPLICATED | IMMUTABLE BLOCKCHAIN | BLOCKCHAIN | IMMUTABLE] TABLE"]),As=G(["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"]),SO=G(["UNION [ALL]","MINUS","INTERSECT"]),uO=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN","{CROSS | OUTER} APPLY"]),RO=G(["ON {UPDATE | DELETE} [SET NULL]","ON COMMIT","{ROWS | RANGE} BETWEEN"]),AO=G([]),IO={name:"plsql",tokenizerOptions:{reservedSelect:TO,reservedClauses:[...dO,...Va,...As],reservedSetOperations:SO,reservedJoins:uO,reservedKeywordPhrases:RO,reservedDataTypePhrases:AO,supportsXor:!0,reservedKeywords:lO,reservedDataTypes:EO,reservedFunctionNames:cO,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:NO},formatOptions:{alwaysDenseOperators:["@"],onelineClauses:[...Va,...As],tabularOnelineClauses:As}};function NO(e){let t=yt;return e.map(n=>Dt.SET(n)&&Dt.BY(t)?Object.assign(Object.assign({},n),{type:X.RESERVED_KEYWORD}):(Nc(n.type)&&(t=n),n))}const OO=["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"],fO=["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"],pO=["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"],hO=G(["SELECT [ALL | DISTINCT]"]),CO=G(["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"]),Wa=G(["CREATE [GLOBAL | LOCAL] [TEMPORARY | TEMP | UNLOGGED] TABLE [IF NOT EXISTS]"]),Is=G(["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"]),LO=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),_O=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),mO=G(["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"]),gO=G(["[TIMESTAMP | TIME] {WITH | WITHOUT} TIME ZONE"]),xO={name:"postgresql",tokenizerOptions:{reservedSelect:hO,reservedClauses:[...CO,...Wa,...Is],reservedSetOperations:LO,reservedJoins:_O,reservedKeywordPhrases:mO,reservedDataTypePhrases:gO,reservedKeywords:fO,reservedDataTypes:pO,reservedFunctionNames:OO,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:[...Wa,...Is],tabularOnelineClauses:Is}},yO=["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"],DO=["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"],MO=["ARRAY","BIGINT","BPCHAR","CHAR","CHARACTER VARYING","CHARACTER","DECIMAL","INT","INT2","INT4","INT8","INTEGER","NCHAR","NUMERIC","NVARCHAR","SMALLINT","TEXT","VARBYTE","VARCHAR"],PO=G(["SELECT [ALL | DISTINCT]"]),bO=G(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","QUALIFY","PARTITION BY","ORDER BY","LIMIT","OFFSET","INSERT INTO","VALUES","SET"]),ja=G(["CREATE [TEMPORARY | TEMP | LOCAL TEMPORARY | LOCAL TEMP] TABLE [IF NOT EXISTS]"]),Ns=G(["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"]),UO=G(["UNION [ALL]","EXCEPT","INTERSECT","MINUS"]),vO=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),BO=G(["NULL AS","DATA CATALOG","HIVE METASTORE","{ROWS | RANGE} BETWEEN"]),FO=G([]),GO={name:"redshift",tokenizerOptions:{reservedSelect:PO,reservedClauses:[...bO,...ja,...Ns],reservedSetOperations:UO,reservedJoins:vO,reservedKeywordPhrases:BO,reservedDataTypePhrases:FO,reservedKeywords:DO,reservedDataTypes:MO,reservedFunctionNames:yO,extraParens:["[]"],stringTypes:["''-qq"],identTypes:['""-qq'],identChars:{first:"#"},paramTypes:{numbered:["$"]},operators:["^","%","@","|/","||/","&","|","~","<<",">>","||","::"]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...ja,...Ns],tabularOnelineClauses:Ns}},wO=["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"],HO=["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"],YO=["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"],kO=G(["SELECT [ALL | DISTINCT]"]),VO=G(["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"]),$a=G(["CREATE [EXTERNAL] TABLE [IF NOT EXISTS]"]),Os=G(["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"]),WO=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),jO=G(["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"]),$O=G(["ON DELETE","ON UPDATE","CURRENT ROW","{ROWS | RANGE} BETWEEN"]),XO=G([]),KO={name:"spark",tokenizerOptions:{reservedSelect:kO,reservedClauses:[...VO,...$a,...Os],reservedSetOperations:WO,reservedJoins:jO,reservedKeywordPhrases:$O,reservedDataTypePhrases:XO,supportsXor:!0,reservedKeywords:wO,reservedDataTypes:HO,reservedFunctionNames:YO,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:zO},formatOptions:{onelineClauses:[...$a,...Os],tabularOnelineClauses:Os}};function zO(e){return e.map((t,n)=>{const r=e[n-1]||yt,o=e[n+1]||yt;return Dt.WINDOW(t)&&o.type===X.OPEN_PAREN?Object.assign(Object.assign({},t),{type:X.RESERVED_FUNCTION_NAME}):t.text==="ITEMS"&&t.type===X.RESERVED_KEYWORD&&!(r.text==="COLLECTION"&&o.text==="TERMINATED")?Object.assign(Object.assign({},t),{type:X.IDENTIFIER,text:t.raw}):t})}const JO=["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"],qO=["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"],QO=["ANY","ARRAY","BLOB","CHARACTER","DECIMAL","INT","INTEGER","NATIVE CHARACTER","NCHAR","NUMERIC","NVARCHAR","REAL","TEXT","VARCHAR","VARYING CHARACTER"],ZO=G(["SELECT [ALL | DISTINCT]"]),ef=G(["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"]),Xa=G(["CREATE [TEMPORARY | TEMP] TABLE [IF NOT EXISTS]"]),fs=G(["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"]),tf=G(["UNION [ALL]","EXCEPT","INTERSECT"]),nf=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),rf=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE | GROUPS} BETWEEN","DO UPDATE"]),of=G([]),sf={name:"sqlite",tokenizerOptions:{reservedSelect:ZO,reservedClauses:[...ef,...Xa,...fs],reservedSetOperations:tf,reservedJoins:nf,reservedKeywordPhrases:rf,reservedDataTypePhrases:of,reservedKeywords:qO,reservedDataTypes:QO,reservedFunctionNames:JO,stringTypes:["''-qq",{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq',"``","[]"],paramTypes:{positional:!0,numbered:["?"],named:[":","@","$"]},operators:["%","~","&","|","<<",">>","==","->","->>","||"]},formatOptions:{onelineClauses:[...Xa,...fs],tabularOnelineClauses:fs}},af=["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"],lf=["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"],Ef=["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"],cf=G(["SELECT [ALL | DISTINCT]"]),Tf=G(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY [ALL | DISTINCT]","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","FETCH {FIRST | NEXT}","INSERT INTO","VALUES","SET"]),Ka=G(["CREATE [GLOBAL TEMPORARY | LOCAL TEMPORARY] TABLE"]),ps=G(["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"]),df=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),Sf=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),uf=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE} BETWEEN"]),Rf=G([]),Af={name:"sql",tokenizerOptions:{reservedSelect:cf,reservedClauses:[...Tf,...Ka,...ps],reservedSetOperations:df,reservedJoins:Sf,reservedKeywordPhrases:uf,reservedDataTypePhrases:Rf,reservedKeywords:lf,reservedDataTypes:Ef,reservedFunctionNames:af,stringTypes:[{quote:"''-qq-bs",prefixes:["N","U&"]},{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq',"``"],paramTypes:{positional:!0},operators:["||"]},formatOptions:{onelineClauses:[...Ka,...ps],tabularOnelineClauses:ps}},If=["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"],Nf=["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"],Of=["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"],ff=G(["SELECT [ALL | DISTINCT]"]),pf=G(["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"]),za=G(["CREATE TABLE [IF NOT EXISTS]"]),hs=G(["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"]),hf=G(["UNION [ALL | DISTINCT] [CORRESPONDING]","EXCEPT [ALL | DISTINCT] [CORRESPONDING]","INTERSECT [ALL | DISTINCT] [CORRESPONDING]"]),Cf=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),Lf=G(["{ROWS | RANGE | GROUPS} BETWEEN","IS [NOT] DISTINCT FROM"]),_f=G([]),mf={name:"trino",tokenizerOptions:{reservedSelect:ff,reservedClauses:[...pf,...za,...hs],reservedSetOperations:hf,reservedJoins:Cf,reservedKeywordPhrases:Lf,reservedDataTypePhrases:_f,reservedKeywords:Nf,reservedDataTypes:Of,reservedFunctionNames:If,extraParens:["[]","{}"],stringTypes:[{quote:"''-qq",prefixes:["U&"]},{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq'],paramTypes:{positional:!0},operators:["%","->","=>",":","||","|","^","$"]},formatOptions:{onelineClauses:[...za,...hs],tabularOnelineClauses:hs}},gf=["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"],xf=["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"],yf=["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"],Df=G(["SELECT [ALL | DISTINCT]"]),Mf=G(["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"]),Ja=G(["CREATE TABLE"]),Cs=G(["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"]),Pf=G(["UNION [ALL]","EXCEPT","INTERSECT"]),bf=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","{CROSS | OUTER} APPLY"]),Uf=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE} BETWEEN"]),vf=G([]),Bf={name:"transactsql",tokenizerOptions:{reservedSelect:Df,reservedClauses:[...Mf,...Ja,...Cs],reservedSetOperations:Pf,reservedJoins:bf,reservedKeywordPhrases:Uf,reservedDataTypePhrases:vf,reservedKeywords:xf,reservedDataTypes:yf,reservedFunctionNames:gf,nestedBlockComments:!0,stringTypes:[{quote:"''-qq",prefixes:["N"]},"{}"],identTypes:['""-qq',"[]"],identChars:{first:"#@",rest:"#@$"},paramTypes:{named:["@"],quoted:["@"]},operators:["%","&","|","^","~","!<","!>","+=","-=","*=","/=","%=","|=","&=","^=","::",":"],propertyAccessOperators:[".."]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...Ja,...Cs],tabularOnelineClauses:Cs}},Ff=["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"],Gf=["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"],wf=["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"],Hf=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),Yf=G(["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"]),qa=G(["CREATE [ROWSTORE] [REFERENCE | TEMPORARY | GLOBAL TEMPORARY] TABLE [IF NOT EXISTS]"]),Ls=G(["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"]),kf=G(["UNION [ALL | DISTINCT]","EXCEPT","INTERSECT","MINUS"]),Vf=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),Wf=G(["ON DELETE","ON UPDATE","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),jf=G([]),$f={name:"singlestoredb",tokenizerOptions:{reservedSelect:Hf,reservedClauses:[...Yf,...qa,...Ls],reservedSetOperations:kf,reservedJoins:Vf,reservedKeywordPhrases:Wf,reservedDataTypePhrases:jf,reservedKeywords:Ff,reservedDataTypes:Gf,reservedFunctionNames:wf,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:go},formatOptions:{alwaysDenseOperators:["::","::$","::%"],onelineClauses:[...qa,...Ls],tabularOnelineClauses:Ls}},Xf=["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"],Kf=["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"],zf=["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"],Jf=G(["SELECT [ALL | DISTINCT]"]),qf=G(["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"]),Qa=G(["CREATE [OR REPLACE] [VOLATILE] TABLE [IF NOT EXISTS]","CREATE [OR REPLACE] [LOCAL | GLOBAL] {TEMP|TEMPORARY} TABLE [IF NOT EXISTS]"]),_s=G(["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"]),Qf=G(["UNION [ALL]","MINUS","EXCEPT","INTERSECT"]),Zf=G(["[INNER] JOIN","[NATURAL] {LEFT | RIGHT | FULL} [OUTER] JOIN","{CROSS | NATURAL} JOIN"]),ep=G(["{ROWS | RANGE} BETWEEN","ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]"]),tp=G([]),np={name:"snowflake",tokenizerOptions:{reservedSelect:Jf,reservedClauses:[...qf,...Qa,..._s],reservedSetOperations:Qf,reservedJoins:Zf,reservedKeywordPhrases:ep,reservedDataTypePhrases:tp,reservedKeywords:Kf,reservedDataTypes:zf,reservedFunctionNames:Xf,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:[...Qa,..._s],tabularOnelineClauses:_s}},rp=Object.freeze(Object.defineProperty({__proto__:null,bigquery:pI,clickhouse:UI,db2:jI,db2i:tN,duckdb:TN,hive:pN,mariadb:MN,mysql:YN,n1ql:aO,plsql:IO,postgresql:xO,redshift:GO,singlestoredb:$f,snowflake:np,spark:KO,sql:Af,sqlite:sf,tidb:qN,transactsql:Bf,trino:mf},Symbol.toStringTag,{value:"Module"})),vn=e=>e[e.length-1],Oc=e=>e.sort((t,n)=>n.length-t.length||t.localeCompare(n)),$r=e=>e.replace(/\s+/gu," "),ms=e=>/\n/.test(e),Qe=e=>e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),Za=/\s+/uy,Xt=e=>new RegExp(`(?:${e})`,"uy"),op=e=>e.split("").map(t=>/ /gu.test(t)?"\\s+":`[${t.toUpperCase()}${t.toLowerCase()}]`).join(""),sp=e=>e+"(?:-"+e+")*",ip=({prefixes:e,requirePrefix:t})=>`(?:${e.map(op).join("|")}${t?"":"|"})`,ap=e=>new RegExp(`(?:${e.map(Qe).join("|")}).*?(?=\r
430
+ |\r|
431
+ |$)`,"uy"),el=(e,t=[])=>{const n=e==="open"?0:1,r=["()",...t].map(o=>o[n]);return Xt(r.map(Qe).join("|"))},tl=e=>Xt(`${Oc(e).map(Qe).join("|")}`),lp=({rest:e,dashes:t})=>e||t?`(?![${e||""}${t?"-":""}])`:"",dt=(e,t={})=>{if(e.length===0)return/^\b$/u;const n=lp(t),r=Oc(e).map(Qe).join("|").replace(/ /gu,"\\s+");return new RegExp(`(?:${r})${n}\\b`,"iuy")},gs=(e,t)=>{if(!e.length)return;const n=e.map(Qe).join("|");return Xt(`(?:${n})(?:${t})`)},Ep=()=>{const e={"<":">","[":"]","(":")","{":"}"},t="{left}(?:(?!{right}').)*?{right}",n=Object.entries(e).map(([a,l])=>t.replace(/{left}/g,Qe(a)).replace(/{right}/g,Qe(l))),r=Qe(Object.keys(e).join(""));return`[Qq]'(?:${String.raw`(?<tag>[^\s${r}])(?:(?!\k<tag>').)*?\k<tag>`}|${n.join("|")})'`},nl={"``":"(?:`[^`]*`)+","[]":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''":Ep()},fc=e=>typeof e=="string"?nl[e]:"regex"in e?e.regex:ip(e)+nl[e.quote],cp=e=>Xt(e.map(t=>"regex"in t?t.regex:fc(t)).join("|")),pc=e=>e.map(fc).join("|"),rl=e=>Xt(pc(e)),Tp=(e={})=>Xt(hc(e)),hc=({first:e,rest:t,dashes:n,allowFirstCharNumber:r}={})=>{const o="\\p{Alphabetic}\\p{Mark}_",s="\\p{Decimal_Number}",a=Qe(e??""),l=Qe(t??""),E=r?`[${o}${s}${a}][${o}${s}${l}]*`:`[${o}${a}][${o}${s}${l}]*`;return n?sp(E):E};function Cc(e,t){const n=e.slice(0,t).split(/\n/);return{line:n.length,col:n[n.length-1].length+1}}class dp{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}=Cc(this.input,this.index);return new Error(`Parse error: Unexpected "${t}" at line ${n} column ${r}.
432
+ ${this.dialectInfo()}`)}dialectInfo(){return this.dialectName==="sql"?`This likely happens because you're using the default "sql" dialect.
433
+ If possible, please select a more specific dialect (like sqlite, postgresql, etc).`:`SQL dialect used: "${this.dialectName}".`}getWhitespace(){Za.lastIndex=this.index;const t=Za.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 ol=/\/\*/uy,Sp=/[\s\S]/uy,up=/\*\//uy;class Rp{constructor(){this.lastIndex=0}exec(t){let n="",r,o=0;if(r=this.matchSection(ol,t))n+=r,o++;else return null;for(;o>0;)if(r=this.matchSection(ol,t))n+=r,o++;else if(r=this.matchSection(up,t))n+=r,o--;else if(r=this.matchSection(Sp,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 Ap{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 dp(r,this.dialectName).tokenize(t);return this.cfg.postProcess?this.cfg.postProcess(o):o}buildRulesBeforeParams(t){var n,r,o;return this.validRules([{type:X.DISABLE_COMMENT,regex:/(\/\* *sql-formatter-disable *\*\/[\s\S]*?(?:\/\* *sql-formatter-enable *\*\/|$))/uy},{type:X.BLOCK_COMMENT,regex:t.nestedBlockComments?new Rp:/(\/\*[^]*?\*\/)/uy},{type:X.LINE_COMMENT,regex:ap((n=t.lineCommentTypes)!==null&&n!==void 0?n:["--"])},{type:X.QUOTED_IDENTIFIER,regex:rl(t.identTypes)},{type:X.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:X.RESERVED_KEYWORD_PHRASE,regex:dt((r=t.reservedKeywordPhrases)!==null&&r!==void 0?r:[],t.identChars),text:Ce},{type:X.RESERVED_DATA_TYPE_PHRASE,regex:dt((o=t.reservedDataTypePhrases)!==null&&o!==void 0?o:[],t.identChars),text:Ce},{type:X.CASE,regex:/CASE\b/iuy,text:Ce},{type:X.END,regex:/END\b/iuy,text:Ce},{type:X.BETWEEN,regex:/BETWEEN\b/iuy,text:Ce},{type:X.LIMIT,regex:t.reservedClauses.includes("LIMIT")?/LIMIT\b/iuy:void 0,text:Ce},{type:X.RESERVED_CLAUSE,regex:dt(t.reservedClauses,t.identChars),text:Ce},{type:X.RESERVED_SELECT,regex:dt(t.reservedSelect,t.identChars),text:Ce},{type:X.RESERVED_SET_OPERATION,regex:dt(t.reservedSetOperations,t.identChars),text:Ce},{type:X.WHEN,regex:/WHEN\b/iuy,text:Ce},{type:X.ELSE,regex:/ELSE\b/iuy,text:Ce},{type:X.THEN,regex:/THEN\b/iuy,text:Ce},{type:X.RESERVED_JOIN,regex:dt(t.reservedJoins,t.identChars),text:Ce},{type:X.AND,regex:/AND\b/iuy,text:Ce},{type:X.OR,regex:/OR\b/iuy,text:Ce},{type:X.XOR,regex:t.supportsXor?/XOR\b/iuy:void 0,text:Ce},...t.operatorKeyword?[{type:X.OPERATOR,regex:/OPERATOR *\([^)]+\)/iuy}]:[],{type:X.RESERVED_FUNCTION_NAME,regex:dt(t.reservedFunctionNames,t.identChars),text:Ce},{type:X.RESERVED_DATA_TYPE,regex:dt(t.reservedDataTypes,t.identChars),text:Ce},{type:X.RESERVED_KEYWORD,regex:dt(t.reservedKeywords,t.identChars),text:Ce}])}buildRulesAfterParams(t){var n,r;return this.validRules([{type:X.VARIABLE,regex:t.variableTypes?cp(t.variableTypes):void 0},{type:X.STRING,regex:rl(t.stringTypes)},{type:X.IDENTIFIER,regex:Tp(t.identChars)},{type:X.DELIMITER,regex:/[;]/uy},{type:X.COMMA,regex:/[,]/y},{type:X.OPEN_PAREN,regex:el("open",t.extraParens)},{type:X.CLOSE_PAREN,regex:el("close",t.extraParens)},{type:X.OPERATOR,regex:tl(["+","-","/",">","<","=","<>","<=",">=","!=",...(n=t.operators)!==null&&n!==void 0?n:[]])},{type:X.ASTERISK,regex:/[*]/uy},{type:X.PROPERTY_ACCESS_OPERATOR,regex:tl([".",...(r=t.propertyAccessOperators)!==null&&r!==void 0?r:[]])}])}buildParamRules(t,n){var r,o,s,a,l;const E={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:X.NAMED_PARAMETER,regex:gs(E.named,hc(t.paramChars||t.identChars)),key:c=>c.slice(1)},{type:X.QUOTED_PARAMETER,regex:gs(E.quoted,pc(t.identTypes)),key:c=>(({tokenKey:d,quoteChar:T})=>d.replace(new RegExp(Qe("\\"+T),"gu"),T))({tokenKey:c.slice(2,-1),quoteChar:c.slice(-1)})},{type:X.NUMBERED_PARAMETER,regex:gs(E.numbered,"[0-9]+"),key:c=>c.slice(1)},{type:X.POSITIONAL_PARAMETER,regex:E.positional?/[?]/y:void 0},...E.custom.map(c=>{var d;return{type:X.CUSTOM_PARAMETER,regex:Xt(c.regex),key:(d=c.key)!==null&&d!==void 0?d:(T=>T)}})])}validRules(t){return t.filter(n=>!!n.regex)}}const Ce=e=>$r(e.toUpperCase()),sl=new Map,Ip=e=>{let t=sl.get(e);return t||(t=Np(e),sl.set(e,t)),t},Np=e=>({tokenizer:new Ap(e.tokenizerOptions,e.name),formatOptions:Op(e.formatOptions)}),Op=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 fp(e){return e.indentStyle==="tabularLeft"||e.indentStyle==="tabularRight"?" ".repeat(10):e.useTabs?" ":" ".repeat(e.tabWidth)}function qt(e){return e.indentStyle==="tabularLeft"||e.indentStyle==="tabularRight"}class pp{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 Xr={exports:{}},hp=Xr.exports,il;function Cp(){return il||(il=1,(function(e){(function(t,n){e.exports?e.exports=n():t.nearley=n()})(hp,function(){function t(c,d,T){return this.id=++t.highestId,this.name=c,this.symbols=d,this.postprocess=T,this}t.highestId=0,t.prototype.toString=function(c){var d=typeof c>"u"?this.symbols.map(E).join(" "):this.symbols.slice(0,c).map(E).join(" ")+" ● "+this.symbols.slice(c).map(E).join(" ");return this.name+" → "+d};function n(c,d,T,S){this.rule=c,this.dot=d,this.reference=T,this.data=[],this.wantedBy=S,this.isComplete=this.dot===c.symbols.length}n.prototype.toString=function(){return"{"+this.rule.toString(this.dot)+"}, from: "+(this.reference||0)},n.prototype.nextState=function(c){var d=new n(this.rule,this.dot+1,this.reference,this.wantedBy);return d.left=this,d.right=c,d.isComplete&&(d.data=d.build(),d.right=void 0),d},n.prototype.build=function(){var c=[],d=this;do c.push(d.right.data),d=d.left;while(d.left);return c.reverse(),c},n.prototype.finish=function(){this.rule.postprocess&&(this.data=this.rule.postprocess(this.data,this.reference,a.fail))};function r(c,d){this.grammar=c,this.index=d,this.states=[],this.wants={},this.scannable=[],this.completed={}}r.prototype.process=function(c){for(var d=this.states,T=this.wants,S=this.completed,u=0;u<d.length;u++){var R=d[u];if(R.isComplete){if(R.finish(),R.data!==a.fail){for(var I=R.wantedBy,N=I.length;N--;){var A=I[N];this.complete(A,R)}if(R.reference===this.index){var p=R.rule.name;(this.completed[p]=this.completed[p]||[]).push(R)}}}else{var p=R.rule.symbols[R.dot];if(typeof p!="string"){this.scannable.push(R);continue}if(T[p]){if(T[p].push(R),S.hasOwnProperty(p))for(var O=S[p],N=0;N<O.length;N++){var h=O[N];this.complete(R,h)}}else T[p]=[R],this.predict(p)}}},r.prototype.predict=function(c){for(var d=this.grammar.byName[c]||[],T=0;T<d.length;T++){var S=d[T],u=this.wants[c],R=new n(S,0,this.index,u);this.states.push(R)}},r.prototype.complete=function(c,d){var T=c.nextState(d);this.states.push(T)};function o(c,d){this.rules=c,this.start=d||this.rules[0].name;var T=this.byName={};this.rules.forEach(function(S){T.hasOwnProperty(S.name)||(T[S.name]=[]),T[S.name].push(S)})}o.fromCompiled=function(S,d){var T=S.Lexer;S.ParserStart&&(d=S.ParserStart,S=S.ParserRules);var S=S.map(function(R){return new t(R.name,R.symbols,R.postprocess)}),u=new o(S,d);return u.lexer=T,u};function s(){this.reset("")}s.prototype.reset=function(c,d){this.buffer=c,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 c=this.buffer[this.index++];return c===`
434
+ `&&(this.line+=1,this.lastLineBreak=this.index),{value:c}}},s.prototype.save=function(){return{line:this.line,col:this.index-this.lastLineBreak}},s.prototype.formatError=function(c,d){var T=this.buffer;if(typeof T=="string"){var S=T.split(`
435
+ `).slice(Math.max(0,this.line-5),this.line),u=T.indexOf(`
436
+ `,this.index);u===-1&&(u=T.length);var R=this.index-this.lastLineBreak,I=String(this.line).length;return d+=" at line "+this.line+" col "+R+`:
437
+
438
+ `,d+=S.map(function(A,p){return N(this.line-S.length+p+1,I)+" "+A},this).join(`
439
+ `),d+=`
440
+ `+N("",I+R)+`^
441
+ `,d}else return d+" at index "+(this.index-1);function N(A,p){var O=String(A);return Array(p-O.length+1).join(" ")+O}};function a(c,d,T){if(c instanceof o)var S=c,T=d;else var S=o.fromCompiled(c,d);this.grammar=S,this.options={keepHistory:!1,lexer:S.lexer||new s};for(var u in T||{})this.options[u]=T[u];this.lexer=this.options.lexer,this.lexerState=void 0;var R=new r(S,0);this.table=[R],R.wants[S.start]=[],R.predict(S.start),R.process(),this.current=0}a.fail={},a.prototype.feed=function(c){var d=this.lexer;d.reset(c,this.lexerState);for(var T;;){try{if(T=d.next(),!T)break}catch(m){var I=new r(this.grammar,this.current+1);this.table.push(I);var S=new Error(this.reportLexerError(m));throw S.offset=this.current,S.token=m.token,S}var u=this.table[this.current];this.options.keepHistory||delete this.table[this.current-1];var R=this.current+1,I=new r(this.grammar,R);this.table.push(I);for(var N=T.text!==void 0?T.text:T.value,A=d.constructor===s?T.value:T,p=u.scannable,O=p.length;O--;){var h=p[O],C=h.rule.symbols[h.dot];if(C.test?C.test(A):C.type?C.type===T.type:C.literal===N){var _=h.nextState({data:A,token:T,isToken:!0,reference:R-1});I.states.push(_)}}if(I.process(),I.states.length===0){var S=new Error(this.reportError(T));throw S.offset=this.current,S.token=T,S}this.options.keepHistory&&(u.lexerState=d.save()),this.current++}return u&&(this.lexerState=d.save()),this.results=this.finish(),this},a.prototype.reportLexerError=function(c){var d,T,S=c.token;return S?(d="input "+JSON.stringify(S.text[0])+" (lexer error)",T=this.lexer.formatError(S,"Syntax error")):(d="input (lexer error)",T=c.message),this.reportErrorCommon(T,d)},a.prototype.reportError=function(c){var d=(c.type?c.type+" token: ":"")+JSON.stringify(c.value!==void 0?c.value:c),T=this.lexer.formatError(c,"Syntax error");return this.reportErrorCommon(T,d)},a.prototype.reportErrorCommon=function(c,d){var T=[];T.push(c);var S=this.table.length-2,u=this.table[S],R=u.states.filter(function(N){var A=N.rule.symbols[N.dot];return A&&typeof A!="string"});if(R.length===0)T.push("Unexpected "+d+`. I did not expect any more input. Here is the state of my parse table:
442
+ `),this.displayStateStack(u.states,T);else{T.push("Unexpected "+d+`. Instead, I was expecting to see one of the following:
443
+ `);var I=R.map(function(N){return this.buildFirstStateStack(N,[])||[N]},this);I.forEach(function(N){var A=N[0],p=A.rule.symbols[A.dot],O=this.getSymbolDisplay(p);T.push("A "+O+" based on:"),this.displayStateStack(N,T)},this)}return T.push(""),T.join(`
444
+ `)},a.prototype.displayStateStack=function(c,d){for(var T,S=0,u=0;u<c.length;u++){var R=c[u],I=R.rule.toString(R.dot);I===T?S++:(S>0&&d.push(" ^ "+S+" more lines identical to this"),S=0,d.push(" "+I)),T=I}},a.prototype.getSymbolDisplay=function(c){return l(c)},a.prototype.buildFirstStateStack=function(c,d){if(d.indexOf(c)!==-1)return null;if(c.wantedBy.length===0)return[c];var T=c.wantedBy[0],S=[c].concat(d),u=this.buildFirstStateStack(T,S);return u===null?null:[c].concat(u)},a.prototype.save=function(){var c=this.table[this.current];return c.lexerState=this.lexerState,c},a.prototype.restore=function(c){var d=c.index;this.current=d,this.table[d]=c,this.table.splice(d+1),this.lexerState=c.lexerState,this.results=this.finish()},a.prototype.rewind=function(c){if(!this.options.keepHistory)throw new Error("set option `keepHistory` to enable rewinding");this.restore(this.table[c])},a.prototype.finish=function(){var c=[],d=this.grammar.start,T=this.table[this.table.length-1];return T.states.forEach(function(S){S.rule.name===d&&S.dot===S.rule.symbols.length&&S.reference===0&&S.data!==a.fail&&c.push(S)}),c.map(function(S){return S.data})};function l(c){var d=typeof c;if(d==="string")return c;if(d==="object"){if(c.literal)return JSON.stringify(c.literal);if(c instanceof RegExp)return"character matching "+c;if(c.type)return c.type+" token";if(c.test)return"token matching "+String(c.test);throw new Error("Unknown symbol type: "+c)}}function E(c){var d=typeof c;if(d==="string")return c;if(d==="object"){if(c.literal)return JSON.stringify(c.literal);if(c instanceof RegExp)return c.toString();if(c.type)return"%"+c.type;if(c.test)return"<"+String(c.test)+">";throw new Error("Unknown symbol type: "+c)}}return{Parser:a,Grammar:o,Rule:t}})})(Xr)),Xr.exports}var Lp=Cp();const _p=hi(Lp);function mp(e){return e.map(gp).map(xp).map(yp).map(Dp).map(Mp)}const gp=(e,t,n)=>{if(Nc(e.type)){const r=Pp(n,t);if(r&&r.type===X.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:X.IDENTIFIER,text:e.raw});const o=fn(n,t);if(o&&o.type===X.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:X.IDENTIFIER,text:e.raw})}return e},xp=(e,t,n)=>{if(e.type===X.RESERVED_FUNCTION_NAME){const r=fn(n,t);if(!r||!Lc(r))return Object.assign(Object.assign({},e),{type:X.IDENTIFIER,text:e.raw})}return e},yp=(e,t,n)=>{if(e.type===X.RESERVED_DATA_TYPE){const r=fn(n,t);if(r&&Lc(r))return Object.assign(Object.assign({},e),{type:X.RESERVED_PARAMETERIZED_DATA_TYPE})}return e},Dp=(e,t,n)=>{if(e.type===X.IDENTIFIER){const r=fn(n,t);if(r&&_c(r))return Object.assign(Object.assign({},e),{type:X.ARRAY_IDENTIFIER})}return e},Mp=(e,t,n)=>{if(e.type===X.RESERVED_DATA_TYPE){const r=fn(n,t);if(r&&_c(r))return Object.assign(Object.assign({},e),{type:X.ARRAY_KEYWORD})}return e},Pp=(e,t)=>fn(e,t,-1),fn=(e,t,n=1)=>{let r=1;for(;e[t+r*n]&&bp(e[t+r*n]);)r++;return e[t+r*n]},Lc=e=>e.type===X.OPEN_PAREN&&e.text==="(",_c=e=>e.type===X.OPEN_PAREN&&e.text==="[",bp=e=>e.type===X.BLOCK_COMMENT||e.type===X.LINE_COMMENT;class mc{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}=Cc(this.input,t.start);return`Parse error at token: ${t.text} at line ${n} column ${r}`}has(t){return t in X}}var re;(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"})(re=re||(re={}));function xs(e){return e[0]}const ie=new mc(e=>[]),bt=([[e]])=>e,_e=e=>({type:re.keyword,tokenType:e.type,text:e.text,raw:e.raw}),al=e=>({type:re.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),Up=(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},vp={Lexer:ie,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:[ie.has("DELIMITER")?{type:"DELIMITER"}:DELIMITER]},{name:"statement$subexpression$1",symbols:[ie.has("EOF")?{type:"EOF"}:EOF]},{name:"statement",symbols:["expressions_or_clauses","statement$subexpression$1"],postprocess:([e,[t]])=>({type:re.statement,children:e,hasSemicolon:t.type===X.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:bt},{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:[ie.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:xs},{name:"limit_clause$ebnf$1",symbols:[],postprocess:()=>null},{name:"limit_clause",symbols:[ie.has("LIMIT")?{type:"LIMIT"}:LIMIT,"_","expression_chain_","limit_clause$ebnf$1"],postprocess:([e,t,n,r])=>{if(r){const[o,s]=r;return{type:re.limit_clause,limitKw:me(_e(e),{trailing:t}),offset:n,count:s}}else return{type:re.limit_clause,limitKw:me(_e(e),{trailing:t}),count:n}}},{name:"select_clause$subexpression$1$ebnf$1",symbols:[]},{name:"select_clause$subexpression$1$ebnf$1",symbols:["select_clause$subexpression$1$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"select_clause$subexpression$1",symbols:["all_columns_asterisk","select_clause$subexpression$1$ebnf$1"]},{name:"select_clause$subexpression$1$ebnf$2",symbols:[]},{name:"select_clause$subexpression$1$ebnf$2",symbols:["select_clause$subexpression$1$ebnf$2","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"select_clause$subexpression$1",symbols:["asteriskless_free_form_sql","select_clause$subexpression$1$ebnf$2"]},{name:"select_clause",symbols:[ie.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT,"select_clause$subexpression$1"],postprocess:([e,[t,n]])=>({type:re.clause,nameKw:_e(e),children:[t,...n]})},{name:"select_clause",symbols:[ie.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT],postprocess:([e])=>({type:re.clause,nameKw:_e(e),children:[]})},{name:"all_columns_asterisk",symbols:[ie.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK],postprocess:()=>({type:re.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:[ie.has("RESERVED_CLAUSE")?{type:"RESERVED_CLAUSE"}:RESERVED_CLAUSE,"other_clause$ebnf$1"],postprocess:([e,t])=>({type:re.clause,nameKw:_e(e),children:t})},{name:"set_operation$ebnf$1",symbols:[]},{name:"set_operation$ebnf$1",symbols:["set_operation$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"set_operation",symbols:[ie.has("RESERVED_SET_OPERATION")?{type:"RESERVED_SET_OPERATION"}:RESERVED_SET_OPERATION,"set_operation$ebnf$1"],postprocess:([e,t])=>({type:re.set_operation,nameKw:_e(e),children:t})},{name:"expression_chain_$ebnf$1",symbols:["expression_with_comments_"]},{name:"expression_chain_$ebnf$1",symbols:["expression_chain_$ebnf$1","expression_with_comments_"],postprocess:e=>e[0].concat([e[1]])},{name:"expression_chain_",symbols:["expression_chain_$ebnf$1"],postprocess:xs},{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:bt},{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:bt},{name:"expression$subexpression$1",symbols:["andless_expression"]},{name:"expression$subexpression$1",symbols:["logic_operator"]},{name:"expression",symbols:["expression$subexpression$1"],postprocess:bt},{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:bt},{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:bt},{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:bt},{name:"array_subscript",symbols:[ie.has("ARRAY_IDENTIFIER")?{type:"ARRAY_IDENTIFIER"}:ARRAY_IDENTIFIER,"_","square_brackets"],postprocess:([e,t,n])=>({type:re.array_subscript,array:me({type:re.identifier,quoted:!1,text:e.text},{trailing:t}),parenthesis:n})},{name:"array_subscript",symbols:[ie.has("ARRAY_KEYWORD")?{type:"ARRAY_KEYWORD"}:ARRAY_KEYWORD,"_","square_brackets"],postprocess:([e,t,n])=>({type:re.array_subscript,array:me(_e(e),{trailing:t}),parenthesis:n})},{name:"function_call",symbols:[ie.has("RESERVED_FUNCTION_NAME")?{type:"RESERVED_FUNCTION_NAME"}:RESERVED_FUNCTION_NAME,"_","parenthesis"],postprocess:([e,t,n])=>({type:re.function_call,nameKw:me(_e(e),{trailing:t}),parenthesis:n})},{name:"parenthesis",symbols:[{literal:"("},"expressions_or_clauses",{literal:")"}],postprocess:([e,t,n])=>({type:re.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:re.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:re.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","_",ie.has("PROPERTY_ACCESS_OPERATOR")?{type:"PROPERTY_ACCESS_OPERATOR"}:PROPERTY_ACCESS_OPERATOR,"_","property_access$subexpression$1"],postprocess:([e,t,n,r,[o]])=>({type:re.property_access,object:me(e,{trailing:t}),operator:n.text,property:me(o,{leading:r})})},{name:"between_predicate",symbols:[ie.has("BETWEEN")?{type:"BETWEEN"}:BETWEEN,"_","andless_expression_chain","_",ie.has("AND")?{type:"AND"}:AND,"_","andless_expression"],postprocess:([e,t,n,r,o,s,a])=>({type:re.between_predicate,betweenKw:_e(e),expr1:Up(n,{leading:t,trailing:r}),andKw:_e(o),expr2:[me(a,{leading:s})]})},{name:"case_expression$ebnf$1",symbols:["expression_chain_"],postprocess:xs},{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:[ie.has("CASE")?{type:"CASE"}:CASE,"_","case_expression$ebnf$1","case_expression$ebnf$2",ie.has("END")?{type:"END"}:END],postprocess:([e,t,n,r,o])=>({type:re.case_expression,caseKw:me(_e(e),{trailing:t}),endKw:_e(o),expr:n||[],clauses:r})},{name:"case_clause",symbols:[ie.has("WHEN")?{type:"WHEN"}:WHEN,"_","expression_chain_",ie.has("THEN")?{type:"THEN"}:THEN,"_","expression_chain_"],postprocess:([e,t,n,r,o,s])=>({type:re.case_when,whenKw:me(_e(e),{trailing:t}),thenKw:me(_e(r),{trailing:o}),condition:n,result:s})},{name:"case_clause",symbols:[ie.has("ELSE")?{type:"ELSE"}:ELSE,"_","expression_chain_"],postprocess:([e,t,n])=>({type:re.case_else,elseKw:me(_e(e),{trailing:t}),result:n})},{name:"comma$subexpression$1",symbols:[ie.has("COMMA")?{type:"COMMA"}:COMMA]},{name:"comma",symbols:["comma$subexpression$1"],postprocess:([[e]])=>({type:re.comma})},{name:"asterisk$subexpression$1",symbols:[ie.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK]},{name:"asterisk",symbols:["asterisk$subexpression$1"],postprocess:([[e]])=>({type:re.operator,text:e.text})},{name:"operator$subexpression$1",symbols:[ie.has("OPERATOR")?{type:"OPERATOR"}:OPERATOR]},{name:"operator",symbols:["operator$subexpression$1"],postprocess:([[e]])=>({type:re.operator,text:e.text})},{name:"identifier$subexpression$1",symbols:[ie.has("IDENTIFIER")?{type:"IDENTIFIER"}:IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[ie.has("QUOTED_IDENTIFIER")?{type:"QUOTED_IDENTIFIER"}:QUOTED_IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[ie.has("VARIABLE")?{type:"VARIABLE"}:VARIABLE]},{name:"identifier",symbols:["identifier$subexpression$1"],postprocess:([[e]])=>({type:re.identifier,quoted:e.type!=="IDENTIFIER",text:e.text})},{name:"parameter$subexpression$1",symbols:[ie.has("NAMED_PARAMETER")?{type:"NAMED_PARAMETER"}:NAMED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[ie.has("QUOTED_PARAMETER")?{type:"QUOTED_PARAMETER"}:QUOTED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[ie.has("NUMBERED_PARAMETER")?{type:"NUMBERED_PARAMETER"}:NUMBERED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[ie.has("POSITIONAL_PARAMETER")?{type:"POSITIONAL_PARAMETER"}:POSITIONAL_PARAMETER]},{name:"parameter$subexpression$1",symbols:[ie.has("CUSTOM_PARAMETER")?{type:"CUSTOM_PARAMETER"}:CUSTOM_PARAMETER]},{name:"parameter",symbols:["parameter$subexpression$1"],postprocess:([[e]])=>({type:re.parameter,key:e.key,text:e.text})},{name:"literal$subexpression$1",symbols:[ie.has("NUMBER")?{type:"NUMBER"}:NUMBER]},{name:"literal$subexpression$1",symbols:[ie.has("STRING")?{type:"STRING"}:STRING]},{name:"literal",symbols:["literal$subexpression$1"],postprocess:([[e]])=>({type:re.literal,text:e.text})},{name:"keyword$subexpression$1",symbols:[ie.has("RESERVED_KEYWORD")?{type:"RESERVED_KEYWORD"}:RESERVED_KEYWORD]},{name:"keyword$subexpression$1",symbols:[ie.has("RESERVED_KEYWORD_PHRASE")?{type:"RESERVED_KEYWORD_PHRASE"}:RESERVED_KEYWORD_PHRASE]},{name:"keyword$subexpression$1",symbols:[ie.has("RESERVED_JOIN")?{type:"RESERVED_JOIN"}:RESERVED_JOIN]},{name:"keyword",symbols:["keyword$subexpression$1"],postprocess:([[e]])=>_e(e)},{name:"data_type$subexpression$1",symbols:[ie.has("RESERVED_DATA_TYPE")?{type:"RESERVED_DATA_TYPE"}:RESERVED_DATA_TYPE]},{name:"data_type$subexpression$1",symbols:[ie.has("RESERVED_DATA_TYPE_PHRASE")?{type:"RESERVED_DATA_TYPE_PHRASE"}:RESERVED_DATA_TYPE_PHRASE]},{name:"data_type",symbols:["data_type$subexpression$1"],postprocess:([[e]])=>al(e)},{name:"data_type",symbols:[ie.has("RESERVED_PARAMETERIZED_DATA_TYPE")?{type:"RESERVED_PARAMETERIZED_DATA_TYPE"}:RESERVED_PARAMETERIZED_DATA_TYPE,"_","parenthesis"],postprocess:([e,t,n])=>({type:re.parameterized_data_type,dataType:me(al(e),{trailing:t}),parenthesis:n})},{name:"logic_operator$subexpression$1",symbols:[ie.has("AND")?{type:"AND"}:AND]},{name:"logic_operator$subexpression$1",symbols:[ie.has("OR")?{type:"OR"}:OR]},{name:"logic_operator$subexpression$1",symbols:[ie.has("XOR")?{type:"XOR"}:XOR]},{name:"logic_operator",symbols:["logic_operator$subexpression$1"],postprocess:([[e]])=>_e(e)},{name:"other_keyword$subexpression$1",symbols:[ie.has("WHEN")?{type:"WHEN"}:WHEN]},{name:"other_keyword$subexpression$1",symbols:[ie.has("THEN")?{type:"THEN"}:THEN]},{name:"other_keyword$subexpression$1",symbols:[ie.has("ELSE")?{type:"ELSE"}:ELSE]},{name:"other_keyword$subexpression$1",symbols:[ie.has("END")?{type:"END"}:END]},{name:"other_keyword",symbols:["other_keyword$subexpression$1"],postprocess:([[e]])=>_e(e)},{name:"_$ebnf$1",symbols:[]},{name:"_$ebnf$1",symbols:["_$ebnf$1","comment"],postprocess:e=>e[0].concat([e[1]])},{name:"_",symbols:["_$ebnf$1"],postprocess:([e])=>e},{name:"comment",symbols:[ie.has("LINE_COMMENT")?{type:"LINE_COMMENT"}:LINE_COMMENT],postprocess:([e])=>({type:re.line_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[ie.has("BLOCK_COMMENT")?{type:"BLOCK_COMMENT"}:BLOCK_COMMENT],postprocess:([e])=>({type:re.block_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[ie.has("DISABLE_COMMENT")?{type:"DISABLE_COMMENT"}:DISABLE_COMMENT],postprocess:([e])=>({type:re.disable_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})}],ParserStart:"main"},{Parser:Bp,Grammar:Fp}=_p;function Gp(e){let t={};const n=new mc(o=>[...mp(e.tokenize(o,t)),Ic(o.length)]),r=new Bp(Fp.fromCompiled(vp),{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
445
+ ${JSON.stringify(a,void 0,2)}`)}}}var $;(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"})($=$||($={}));class gc{constructor(t){this.indentation=t,this.items=[]}add(...t){for(const n of t)switch(n){case $.SPACE:this.items.push($.SPACE);break;case $.NO_SPACE:this.trimHorizontalWhitespace();break;case $.NO_NEWLINE:this.trimWhitespace();break;case $.NEWLINE:this.trimHorizontalWhitespace(),this.addNewline($.NEWLINE);break;case $.MANDATORY_NEWLINE:this.trimHorizontalWhitespace(),this.addNewline($.MANDATORY_NEWLINE);break;case $.INDENT:this.addIndentation();break;case $.SINGLE_INDENT:this.items.push($.SINGLE_INDENT);break;default:this.items.push(n)}}trimHorizontalWhitespace(){for(;wp(vn(this.items));)this.items.pop()}trimWhitespace(){for(;Hp(vn(this.items));)this.items.pop()}addNewline(t){if(this.items.length>0)switch(vn(this.items)){case $.NEWLINE:this.items.pop(),this.items.push(t);break;case $.MANDATORY_NEWLINE:break;default:this.items.push(t);break}}addIndentation(){for(let t=0;t<this.indentation.getLevel();t++)this.items.push($.SINGLE_INDENT)}toString(){return this.items.map(t=>this.itemToString(t)).join("")}getLayoutItems(){return this.items}itemToString(t){switch(t){case $.SPACE:return" ";case $.NEWLINE:case $.MANDATORY_NEWLINE:return`
446
+ `;case $.SINGLE_INDENT:return this.indentation.getSingleIndent();default:return t}}}const wp=e=>e===$.SPACE||e===$.SINGLE_INDENT,Hp=e=>e===$.SPACE||e===$.SINGLE_INDENT||e===$.NEWLINE;function ll(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 El(e){return TI(e)||e===X.RESERVED_CLAUSE||e===X.RESERVED_SELECT||e===X.RESERVED_SET_OPERATION||e===X.RESERVED_JOIN||e===X.LIMIT}const ys="top-level",Yp="block-level";class xc{constructor(t){this.indent=t,this.indentTypes=[]}getSingleIndent(){return this.indent}getLevel(){return this.indentTypes.length}increaseTopLevel(){this.indentTypes.push(ys)}increaseBlockLevel(){this.indentTypes.push(Yp)}decreaseTopLevel(){this.indentTypes.length>0&&vn(this.indentTypes)===ys&&this.indentTypes.pop()}decreaseBlockLevel(){for(;this.indentTypes.length>0&&this.indentTypes.pop()===ys;);}}class kp extends gc{constructor(t){super(new xc("")),this.expressionWidth=t,this.length=0,this.trailingSpace=!1}add(...t){if(t.forEach(n=>this.addToLength(n)),this.length>this.expressionWidth)throw new ii;super.add(...t)}addToLength(t){if(typeof t=="string")this.length+=t.length,this.trailingSpace=!1;else{if(t===$.MANDATORY_NEWLINE||t===$.NEWLINE)throw new ii;t===$.INDENT||t===$.SINGLE_INDENT||t===$.SPACE?this.trailingSpace||(this.length++,this.trailingSpace=!0):(t===$.NO_NEWLINE||t===$.NO_SPACE)&&this.trailingSpace&&(this.trailingSpace=!1,this.length--)}}}class ii extends Error{}class ao{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 re.function_call:return this.formatFunctionCall(t);case re.parameterized_data_type:return this.formatParameterizedDataType(t);case re.array_subscript:return this.formatArraySubscript(t);case re.property_access:return this.formatPropertyAccess(t);case re.parenthesis:return this.formatParenthesis(t);case re.between_predicate:return this.formatBetweenPredicate(t);case re.case_expression:return this.formatCaseExpression(t);case re.case_when:return this.formatCaseWhen(t);case re.case_else:return this.formatCaseElse(t);case re.clause:return this.formatClause(t);case re.set_operation:return this.formatSetOperation(t);case re.limit_clause:return this.formatLimitClause(t);case re.all_columns_asterisk:return this.formatAllColumnsAsterisk(t);case re.literal:return this.formatLiteral(t);case re.identifier:return this.formatIdentifier(t);case re.parameter:return this.formatParameter(t);case re.operator:return this.formatOperator(t);case re.comma:return this.formatComma(t);case re.line_comment:return this.formatLineComment(t);case re.block_comment:return this.formatBlockComment(t);case re.disable_comment:return this.formatBlockComment(t);case re.data_type:return this.formatDataType(t);case re.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 re.data_type:n=this.showDataType(t.array);break;case re.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($.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($.NO_SPACE,t.closeParen,$.SPACE)):(this.layout.add(t.openParen,$.NEWLINE),qt(this.cfg)?(this.layout.add($.INDENT),this.layout=this.formatSubExpression(t.children)):(this.layout.indentation.increaseBlockLevel(),this.layout.add($.INDENT),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseBlockLevel()),this.layout.add($.NEWLINE,$.INDENT,t.closeParen,$.SPACE))}formatBetweenPredicate(t){this.layout.add(this.showKw(t.betweenKw),$.SPACE),this.layout=this.formatSubExpression(t.expr1),this.layout.add($.NO_SPACE,$.SPACE,this.showNonTabularKw(t.andKw),$.SPACE),this.layout=this.formatSubExpression(t.expr2),this.layout.add($.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($.NEWLINE,$.INDENT),this.formatNode(t.endKw)}formatCaseWhen(t){this.layout.add($.NEWLINE,$.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($.NEWLINE,$.INDENT),this.formatNode(t.elseKw),this.layout=this.formatSubExpression(t.result)}formatClause(t){this.isOnelineClause(t)?this.formatClauseInOnelineStyle(t):qt(this.cfg)?this.formatClauseInTabularStyle(t):this.formatClauseInIndentedStyle(t)}isOnelineClause(t){return qt(this.cfg)?this.dialectCfg.tabularOnelineClauses[t.nameKw.text]:this.dialectCfg.onelineClauses[t.nameKw.text]}formatClauseInIndentedStyle(t){this.layout.add($.NEWLINE,$.INDENT,this.showKw(t.nameKw),$.NEWLINE),this.layout.indentation.increaseTopLevel(),this.layout.add($.INDENT),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseTopLevel()}formatClauseInOnelineStyle(t){this.layout.add($.NEWLINE,$.INDENT,this.showKw(t.nameKw),$.SPACE),this.layout=this.formatSubExpression(t.children)}formatClauseInTabularStyle(t){this.layout.add($.NEWLINE,$.INDENT,this.showKw(t.nameKw),$.SPACE),this.layout.indentation.increaseTopLevel(),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseTopLevel()}formatSetOperation(t){this.layout.add($.NEWLINE,$.INDENT,this.showKw(t.nameKw),$.NEWLINE),this.layout.add($.INDENT),this.layout=this.formatSubExpression(t.children)}formatLimitClause(t){this.withComments(t.limitKw,()=>{this.layout.add($.NEWLINE,$.INDENT,this.showKw(t.limitKw))}),this.layout.indentation.increaseTopLevel(),qt(this.cfg)?this.layout.add($.SPACE):this.layout.add($.NEWLINE,$.INDENT),t.offset?(this.layout=this.formatSubExpression(t.offset),this.layout.add($.NO_SPACE,",",$.SPACE),this.layout=this.formatSubExpression(t.count)):this.layout=this.formatSubExpression(t.count),this.layout.indentation.decreaseTopLevel()}formatAllColumnsAsterisk(t){this.layout.add("*",$.SPACE)}formatLiteral(t){this.layout.add(t.text,$.SPACE)}formatIdentifier(t){this.layout.add(this.showIdentifier(t),$.SPACE)}formatParameter(t){this.layout.add(this.params.get(t),$.SPACE)}formatOperator({text:t}){this.cfg.denseOperators||this.dialectCfg.alwaysDenseOperators.includes(t)?this.layout.add($.NO_SPACE,t):t===":"?this.layout.add($.NO_SPACE,t,$.SPACE):this.layout.add(t,$.SPACE)}formatComma(t){this.inline?this.layout.add($.NO_SPACE,",",$.SPACE):this.layout.add($.NO_SPACE,",",$.NEWLINE,$.INDENT)}withComments(t,n){this.formatComments(t.leadingComments),n(),this.formatComments(t.trailingComments)}formatComments(t){t&&t.forEach(n=>{n.type===re.line_comment?this.formatLineComment(n):this.formatBlockComment(n)})}formatLineComment(t){ms(t.precedingWhitespace||"")?this.layout.add($.NEWLINE,$.INDENT,t.text,$.MANDATORY_NEWLINE,$.INDENT):this.layout.getLayoutItems().length>0?this.layout.add($.NO_NEWLINE,$.SPACE,t.text,$.MANDATORY_NEWLINE,$.INDENT):this.layout.add(t.text,$.MANDATORY_NEWLINE,$.INDENT)}formatBlockComment(t){t.type===re.block_comment&&this.isMultilineBlockComment(t)?(this.splitBlockComment(t.text).forEach(n=>{this.layout.add($.NEWLINE,$.INDENT,n)}),this.layout.add($.NEWLINE,$.INDENT)):this.layout.add(t.text,$.SPACE)}isMultilineBlockComment(t){return ms(t.text)||ms(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(vn(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 ao({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 ao({cfg:this.cfg,dialectCfg:this.dialectCfg,params:this.params,layout:new kp(this.cfg.expressionWidth),inline:!0}).format(t)}catch(r){if(r instanceof ii){this.params.setPositionalParameterIndex(n);return}else throw r}}formatKeywordNode(t){switch(t.tokenType){case X.RESERVED_JOIN:return this.formatJoin(t);case X.AND:case X.OR:case X.XOR:return this.formatLogicalOperator(t);default:return this.formatKeyword(t)}}formatJoin(t){qt(this.cfg)?(this.layout.indentation.decreaseTopLevel(),this.layout.add($.NEWLINE,$.INDENT,this.showKw(t),$.SPACE),this.layout.indentation.increaseTopLevel()):this.layout.add($.NEWLINE,$.INDENT,this.showKw(t),$.SPACE)}formatKeyword(t){this.layout.add(this.showKw(t),$.SPACE)}formatLogicalOperator(t){this.cfg.logicalOperatorNewline==="before"?qt(this.cfg)?(this.layout.indentation.decreaseTopLevel(),this.layout.add($.NEWLINE,$.INDENT,this.showKw(t),$.SPACE),this.layout.indentation.increaseTopLevel()):this.layout.add($.NEWLINE,$.INDENT,this.showKw(t),$.SPACE):this.layout.add(this.showKw(t),$.NEWLINE,$.INDENT)}formatDataType(t){this.layout.add(this.showDataType(t),$.SPACE)}showKw(t){return El(t.tokenType)?ll(this.showNonTabularKw(t),this.cfg.indentStyle):this.showNonTabularKw(t)}showNonTabularKw(t){switch(this.cfg.keywordCase){case"preserve":return $r(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}showFunctionKw(t){return El(t.tokenType)?ll(this.showNonTabularFunctionKw(t),this.cfg.indentStyle):this.showNonTabularFunctionKw(t)}showNonTabularFunctionKw(t){switch(this.cfg.functionCase){case"preserve":return $r(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 $r(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}}class Vp{constructor(t,n){this.dialect=t,this.cfg=n,this.params=new pp(this.cfg.params)}format(t){const n=this.parse(t);return this.formatAst(n).trimEnd()}parse(t){return Gp(this.dialect.tokenizer).parse(t,this.cfg.paramTypes||{})}formatAst(t){return t.map(n=>this.formatStatement(n)).join(`
447
+ `.repeat(this.cfg.linesBetweenQueries+1))}formatStatement(t){const n=new ao({cfg:this.cfg,dialectCfg:this.dialect.formatOptions,params:this.params,layout:new gc(new xc(fp(this.cfg)))}).format(t.children);return t.hasSemicolon&&(this.cfg.newlineBeforeSemicolon?n.add($.NEWLINE,";"):n.add($.NO_NEWLINE,";")),n.toString()}}class Kr extends Error{}function Wp(e){const t=["multilineLists","newlineBeforeOpenParen","newlineBeforeCloseParen","aliasAs","commaPosition","tabulateAlias"];for(const n of t)if(n in e)throw new Kr(`${n} config is no more supported.`);if(e.expressionWidth<=0)throw new Kr(`expressionWidth config must be positive number. Received ${e.expressionWidth} instead.`);if(e.params&&!jp(e.params)&&console.warn('WARNING: All "params" option values should be strings.'),e.paramTypes&&!$p(e.paramTypes))throw new Kr("Empty regex given in custom paramTypes. That would result in matching infinite amount of parameters.");return e}function jp(e){return(e instanceof Array?e:Object.values(e)).every(n=>typeof n=="string")}function $p(e){return e.custom&&Array.isArray(e.custom)?e.custom.every(t=>t.regex!==""):!0}var Xp=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 yc={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"},Kp=Object.keys(yc),zp={tabWidth:2,useTabs:!1,keywordCase:"preserve",identifierCase:"preserve",dataTypeCase:"preserve",functionCase:"preserve",indentStyle:"standard",logicalOperatorNewline:"before",expressionWidth:50,linesBetweenQueries:1,denseOperators:!1,newlineBeforeSemicolon:!1},Jp=(e,t={})=>{if(typeof t.language=="string"&&!Kp.includes(t.language))throw new Kr(`Unsupported SQL dialect: ${t.language}`);const n=yc[t.language||"sql"];return qp(e,Object.assign(Object.assign({},t),{dialect:rp[n]}))},qp=(e,t)=>{var{dialect:n}=t,r=Xp(t,["dialect"]);if(typeof e!="string")throw new Error("Invalid query argument. Expected string, instead got "+typeof e);const o=Wp(Object.assign(Object.assign({},zp),r));return new Vp(Ip(n),o).format(e)},Qp={sql:"SQL",markdown:"MD",dql:"DQL",param:"PARAM"},Ds={sql:"#388bfd",markdown:"#56d364",dql:"#e3b341",param:"#e3b341"};function Zp(e,t){switch(e.status){case"running":return t.cellBorderRunning;case"success":return t.success;case"error":return t.error;default:return t.cellBorder}}function eh({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 th(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 Ms(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 nh(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 rh({content:e,onChange:t,t:n}){const r=th(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(Ms(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(Ms(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 E=l.target.value.split(",").map(c=>c.trim()).filter(Boolean);t(nh(e,E))}})]}),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(Ms(e,"description",l.target.value))})]})]})}function oh({cell:e,index:t}){var k;const{state:n,dispatch:r}=Se(),o=le[n.themeMode],{executeCell:s,executeDependents:a,cancelCell:l}=mo(),[E,c]=f.useState(!1),[d,T]=f.useState(!1),[S,u]=f.useState(e.name??""),[R,I]=f.useState(!0),[N,A]=f.useState("table"),[p,O]=f.useState(null),[h,C]=f.useState(!1),[_,m]=f.useState(!1),[M,y]=f.useState(!1),b=Zp(e,o),g=e.type!=="markdown"&&e.type!=="param",x=f.useMemo(()=>n.schemaTables.length>0?Object.fromEntries(n.schemaTables.map(w=>[w.name,w.columns.map(z=>z.name)])):void 0,[n.schemaTables]);if(e.type==="param")return i.jsxs("div",{onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{display:"flex",gap:0,marginBottom:2},children:[i.jsx("div",{style:{width:40,flexShrink:0}}),i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(VA,{cell:e,themeMode:n.themeMode,onApplyParam:a})})]});f.useEffect(()=>{if(e.status==="success"&&e.result){const w=Hn(e.result,e.chartConfig);O(w!=="table"?w:null),A(w!=="table"?"chart":"table")}},[e.status,e.result,e.chartConfig]);const F=f.useCallback(()=>{g&&s(e.id)},[e.id,s,g]),L=f.useCallback(w=>{r({type:"UPDATE_CELL",id:e.id,updates:{content:w}})},[e.id,r]),P=f.useCallback(()=>{if(e.content.trim())try{const w=Jp(e.content,{language:"sql",tabWidth:2,keywordCase:"upper",linesBetweenQueries:1});r({type:"UPDATE_CELL",id:e.id,updates:{content:w}})}catch{}},[e.content,e.id,r]),D=f.useCallback(()=>{P(),setTimeout(()=>s(e.id),80)},[P,s,e.id]),B=()=>{r({type:"DELETE_CELL",id:e.id})},v=()=>{r({type:"MOVE_CELL",id:e.id,direction:"up"})},U=()=>{r({type:"MOVE_CELL",id:e.id,direction:"down"})},Y=()=>{T(!1),r({type:"UPDATE_CELL",id:e.id,updates:{name:S.trim()||void 0}})},W=(e.result||e.error)&&e.type!=="markdown";return e.result&&Hn(e.result,e.chartConfig),i.jsxs("div",{onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{display:"flex",gap:0,marginBottom:2},children:[M&&i.jsx(XA,{cell:e,onClose:()=>y(!1),onSaved:({path:w,name:z})=>{r({type:"FILE_ADDED",file:{name:z,path:w,type:"block",folder:"blocks"}})}}),i.jsx(eh,{cell:e,t:o}),i.jsxs("div",{style:{flex:1,minWidth:0,borderRadius:8,border:`1px solid ${E||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:Ds[e.type]??o.accent,background:`${Ds[e.type]??o.accent}18`,border:`1px solid ${Ds[e.type]??o.accent}40`,borderRadius:4,padding:"1px 6px",flexShrink:0,textTransform:"uppercase"},children:Qp[e.type]}),E&&(e.type==="sql"||e.type==="dql")&&i.jsx(jA,{themeMode:n.themeMode,cellType:e.type,onInsert:w=>L(w)}),E&&(e.type==="sql"||e.type==="dql")&&i.jsx("button",{title:"Format SQL (clean up whitespace & keywords)",onClick:P,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:w=>{w.currentTarget.style.color=o.textSecondary,w.currentTarget.style.borderColor=o.accent},onMouseLeave:w=>{w.currentTarget.style.color=o.textMuted,w.currentTarget.style.borderColor=o.btnBorder},children:"Format"}),E&&(e.type==="sql"||e.type==="dql")&&i.jsx("button",{title:"Save this cell as a reusable block",onClick:()=>y(!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:w=>{w.currentTarget.style.color=o.textSecondary,w.currentTarget.style.borderColor=o.accent},onMouseLeave:w=>{w.currentTarget.style.color=o.textMuted,w.currentTarget.style.borderColor=o.btnBorder},children:"Save as Block"}),d?i.jsx("input",{autoFocus:!0,value:S,onChange:w=>u(w.target.value),onBlur:Y,onKeyDown:w=>{w.key==="Enter"&&Y(),w.key==="Escape"&&T(!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:()=>{u(e.name??""),T(!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}}),E&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[!e.name&&!d&&i.jsx(Qt,{title:"Name this cell",onClick:()=>{u(""),T(!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"})})}),g&&e.status==="running"?i.jsx(Qt,{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"})})}):g?i.jsx(Qt,{title:"Run cell (Shift+Enter)",onClick:F,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(Qt,{title:"Move up",onClick:v,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(Qt,{title:"Move down",onClick:U,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(Qt,{title:"Delete cell",onClick:B,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(rh,{content:e.content,onChange:L,t:o}),e.type==="markdown"?i.jsx(kA,{value:e.content,onChange:L,themeMode:n.themeMode}):i.jsx(Mi,{value:e.content,onChange:L,onRun:F,themeMode:n.themeMode,schema:x,errorMessage:e.status==="error"?e.error:void 0}),W&&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&&R?`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.error&&i.jsx("span",{style:{fontSize:11,fontFamily:o.font,color:o.error},children:"Error"}),i.jsx("div",{style:{flex:1}}),e.result&&R&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:3,position:"relative"},children:[i.jsx("button",{onClick:()=>{A("table"),C(!1)},style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${N==="table"?o.accent:o.btnBorder}`,background:N==="table"?`${o.accent}20`:"transparent",color:N==="table"?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s"},children:"Table"}),i.jsxs("div",{style:{position:"relative"},children:[i.jsxs("button",{onClick:()=>{N==="chart"&&h?C(!1):(A("chart"),C(w=>!w))},style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${N==="chart"?o.accent:o.btnBorder}`,background:N==="chart"?`${o.accent}20`:"transparent",color:N==="chart"?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s",display:"flex",alignItems:"center",gap:3},children:[p?((k=Ci.find(w=>w.value===p))==null?void 0:k.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"})})]}),h&&i.jsx(sh,{selected:p,onSelect:w=>{O(w),A("chart"),C(!1)},onClose:()=>C(!1),t:o})]}),N==="chart"&&i.jsx("button",{onClick:()=>m(w=>!w),title:"Chart configuration",style:{padding:"1px 5px",fontSize:11,borderRadius:3,cursor:"pointer",border:`1px solid ${_?o.accent:o.btnBorder}`,background:_?`${o.accent}20`:"transparent",color:_?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:()=>I(w=>!w),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:R?"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"})}),R?"Hide":"Show"]})]}),R&&i.jsxs(i.Fragment,{children:[e.error&&i.jsx(JA,{message:e.error,themeMode:n.themeMode,onFix:g?D:void 0,schemaTables:n.schemaTables}),e.result&&!e.error&&(N==="chart"&&p?i.jsxs(i.Fragment,{children:[_i(p,e.result,n.themeMode,e.chartConfig),_&&i.jsx(ih,{columns:e.result.columns,chartConfig:e.chartConfig,onChange:w=>r({type:"UPDATE_CELL",id:e.id,updates:{chartConfig:{...e.chartConfig,...w}}}),t:o})]}):i.jsx(Lo,{result:e.result,themeMode:n.themeMode}))]})]}),g&&i.jsx(nI,{cellContent:e.content,cellType:e.type,cellName:e.name,themeMode:n.themeMode,t:o})]})]})}function Qt({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 sh({selected:e,onSelect:t,onClose:n,t:r}){const[o,s]=f.useState(null);return En.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:Ci.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 ih({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 ah=[{type:"sql",label:"SQL",color:"#388bfd"},{type:"markdown",label:"Markdown",color:"#56d364"},{type:"dql",label:"DQL",color:"#e3b341"},{type:"param",label:"Param",color:"#e3b341"}];function Ps({afterId:e}){const{state:t,dispatch:n}=Se(),r=le[t.themeMode],[o,s]=f.useState(!1),[a,l]=f.useState(!1),[E,c]=f.useState(!1),[d,T]=f.useState(""),[S,u]=f.useState(!1),R=f.useRef(null),I=f.useRef(null);f.useEffect(()=>{if(!a)return;function h(C){R.current&&!R.current.contains(C.target)&&l(!1)}return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[a]);const N=h=>{const C=xe(h);n({type:"ADD_CELL",cell:C,afterId:e}),l(!1),c(!1)},A=t.files.filter(h=>h.type==="block"),p=d?A.filter(h=>h.name.toLowerCase().includes(d.toLowerCase())):A,O=h=>{const C=xe("sql",`-- Block: ${h.path}
448
+ @include('${h.path}')`);n({type:"ADD_CELL",cell:C,afterId:e}),l(!1),c(!1),T("")};return i.jsxs("div",{ref:R,onDragOver:h=>{h.dataTransfer.types.includes(to)&&(h.preventDefault(),u(!0))},onDragLeave:()=>u(!1),onDrop:h=>{const C=$E(h.dataTransfer.getData(to));if(!C)return;h.preventDefault(),u(!1);const _=xe("sql",C.reference);n({type:"ADD_CELL",cell:_,afterId:e}),te.trackUsage(C.name),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:C.name}}))},onMouseEnter:()=>s(!0),onMouseLeave:()=>{s(!1),u(!1)},style:{position:"relative",height:28,display:"flex",alignItems:"center",justifyContent:"center",cursor:"default"},children:[i.jsx("div",{style:{position:"absolute",left:0,right:0,height:1,background:S?r.accent:o||a?r.cellBorderActive:"transparent",transition:"background 0.15s"}}),(o||a||S)&&i.jsxs("button",{onClick:()=>l(h=>!h),style:{position:"relative",zIndex:2,height:22,padding:"0 10px",borderRadius:11,border:`1px solid ${S?r.accent:r.cellBorderActive}`,background:S?`${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:8,boxShadow:"0 8px 24px rgba(0,0,0,0.3)",padding:4,display:"flex",flexDirection:"column",gap:4},children:[i.jsxs("div",{style:{display:"flex",gap:4},children:[ah.map(({type:h,label:C,color:_})=>i.jsx(cl,{label:C,color:_,onClick:()=>N(h),t:r},h)),i.jsx(cl,{label:"Block",color:"#d2a8ff",onClick:()=>{c(h=>!h),setTimeout(()=>{var h;return(h=I.current)==null?void 0:h.focus()},50)},t:r})]}),E&&i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"4px 2px"},children:[i.jsx("input",{ref:I,value:d,onChange:h=>T(h.target.value),placeholder:"Search blocks...",style:{background:r.inputBg,border:`1px solid ${r.inputBorder}`,borderRadius:4,color:r.textPrimary,fontSize:11,fontFamily:r.font,padding:"4px 8px",outline:"none"}}),i.jsx("div",{style:{maxHeight:160,overflow:"auto",display:"flex",flexDirection:"column",gap:2},children:p.length===0?i.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,padding:"4px 8px",fontStyle:"italic"},children:A.length===0?"No blocks yet":"No matches"}):p.map(h=>i.jsx(lh,{file:h,onClick:()=>O(h),t:r},h.path))})]})]})]})}function cl({label:e,color: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:o?`${t}18`:"transparent",border:`1px solid ${o?t:r.cellBorder}`,borderRadius:6,cursor:"pointer",color:o?t:r.textSecondary,fontSize:11,fontFamily:r.fontMono,fontWeight:600,padding:"4px 10px",letterSpacing:"0.04em",transition:"all 0.15s",whiteSpace:"nowrap"},children:e})}function lh({file: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.sidebarItemHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:n.textPrimary,fontSize:11,fontFamily:n.font,padding:"4px 8px",textAlign:"left",display:"flex",flexDirection:"column",gap:1,transition:"background 0.1s"},children:[i.jsx("span",{style:{fontWeight:500},children:e.name.replace(/\.dql$/,"")}),i.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.fontMono},children:e.path})]})}function Eh({registerCellRef:e}){const{state:t,dispatch:n}=Se(),{executeCell:r}=mo(),o=le[t.themeMode],[s,a]=f.useState(null),l=f.useRef(0),[E,c]=f.useState(null),[d,T]=f.useState(null);f.useCallback(N=>{a(N)},[]),f.useEffect(()=>{function N(A){var C;if(!s)return;const p=A.target;if(p.tagName==="TEXTAREA"||p.tagName==="INPUT"||p.isContentEditable||p.closest(".cm-editor")){a(null);return}const O=t.cells,h=O.findIndex(_=>_.id===s);if(h!==-1)switch(A.key){case"a":{A.preventDefault();const _=xe("sql");if(h===0)n({type:"ADD_CELL",cell:_,afterId:O[0].id}),n({type:"MOVE_CELL",id:_.id,direction:"up"});else{const m=O[h-1].id;n({type:"ADD_CELL",cell:_,afterId:m})}a(_.id);break}case"b":{A.preventDefault();const _=xe("sql");n({type:"ADD_CELL",cell:_,afterId:s}),a(_.id);break}case"d":{A.preventDefault();const _=Date.now();if(_-l.current<=500){if(n({type:"DELETE_CELL",id:s}),O.length>1){const m=h>0?h-1:1;a(((C=O[m])==null?void 0:C.id)??null)}else a(null);l.current=0}else l.current=_;break}case"Enter":{if(A.shiftKey){A.preventDefault();const _=O[h];_&&_.type!=="markdown"&&r(_.id)}break}}}return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[s,t.cells,n,r]),f.useEffect(()=>{function N(A){A.target.closest("[data-cell-id]")||a(null)}return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[]);const S=f.useCallback((N,A)=>{c(A),N.dataTransfer.effectAllowed="move",N.dataTransfer.setData("text/plain",String(A));const p=N.currentTarget;setTimeout(()=>{p.style.opacity="0.4"},0)},[]),u=f.useCallback(N=>{N.currentTarget.style.opacity="1",c(null),T(null)},[]),R=f.useCallback((N,A)=>{N.preventDefault(),N.dataTransfer.dropEffect="move",T(A)},[]),I=f.useCallback((N,A)=>{N.preventDefault(),E!==null&&E!==A&&n({type:"REORDER_CELL",fromIndex:E,toIndex:A}),c(null),T(null)},[E,n]);return t.cells.length===0?i.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[i.jsx(Ps,{}),i.jsx(ch,{t:o})]}):i.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[i.jsx(Ps,{afterId:void 0}),t.cells.map((N,A)=>i.jsxs(En.Fragment,{children:[i.jsxs("div",{ref:p=>e(N.id,p),"data-cell-id":N.id,draggable:!0,onDragStart:p=>S(p,A),onDragEnd:u,onDragOver:p=>R(p,A),onDrop:p=>I(p,A),onClick:p=>{const O=p.target;!O.closest(".cm-editor")&&!O.closest("textarea")&&!O.closest("input")&&a(N.id)},style:{outline:s===N.id?`2px solid ${o.accent}40`:"none",outlineOffset:2,borderRadius:10,transition:"outline 0.1s, transform 0.15s",position:"relative",...d===A&&E!==null&&E!==A?{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(oh,{cell:N,index:A})]}),i.jsx(Ps,{afterId:N.id})]},N.id)),i.jsx("style",{children:`
449
+ [data-cell-id]:hover .drag-handle { opacity: 0.5 !important; }
450
+ [data-cell-id]:hover .drag-handle:hover { opacity: 1 !important; }
451
+ `})]})}function ch({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 Th(){const{state:e}=Se(),t=le[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(dh,{cell:r},r.id))]})})}function dh({cell:e}){const{state:t}=Se(),n=le[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:uh(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(Sh,{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=Hn(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?_i(r,e.result,t.themeMode,e.chartConfig):i.jsx(Lo,{result:e.result,themeMode:t.themeMode})})]})}function Sh({name:e,t}){return i.jsx("div",{style:{fontSize:13,fontWeight:600,color:t.textPrimary,fontFamily:t.font,marginBottom:8},children:e})}function uh(e,t){const n=r=>r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return e.split(`
452
+ `).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("")}function Rh({onOpenFile:e,registerCellRef:t}){const{state:n}=Se(),r=le[n.themeMode];return n.activeFile?n.dashboardMode?i.jsx(Th,{}):i.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",background:r.appBg},children:[i.jsx(Ah,{t:r}),i.jsx("div",{style:{flex:1,overflow:"auto",padding:"24px 0 40px"},children:i.jsx(Eh,{registerCellRef:t})})]}):i.jsx(EA,{onOpenFile:e})}function Ah({t:e}){const{state:t}=Se(),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(Ih,{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 Ih({t:e}){const{state:t}=Se();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(En.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 Tl={blank:"Blank",revenue:"Revenue Analysis",pipeline:"Pipeline Health"},Nh={blank:"Start with an empty notebook.",revenue:"Pre-built queries for revenue metrics and trends.",pipeline:"Templates for data pipeline health monitoring."};function dl(e){return e.toLowerCase().replace(/[^a-z0-9\-_\s]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,64)}function Oh(e){return e.trim()?/^[a-zA-Z0-9\-_ ]+$/.test(e)?null:"Only letters, numbers, hyphens, underscores, and spaces allowed.":"Name is required."}function fh(e){switch(e){case"revenue":return[xe("markdown",`# Revenue Analysis
453
+
454
+ This notebook analyzes revenue metrics and trends over time.`),{...xe("sql",`SELECT
455
+ DATE_TRUNC('month', order_date) AS month,
456
+ SUM(amount) AS revenue
457
+ FROM orders
458
+ GROUP BY 1
459
+ ORDER BY 1`),name:"monthly_revenue"},{...xe("sql",`SELECT
460
+ product_category,
461
+ SUM(amount) AS total_revenue,
462
+ COUNT(*) AS orders
463
+ FROM orders
464
+ GROUP BY 1
465
+ ORDER BY 2 DESC`),name:"revenue_by_category"}];case"pipeline":return[xe("markdown",`# Pipeline Health
466
+
467
+ Monitor data pipeline performance, SLA compliance, and error rates.`),{...xe("sql",`SELECT
468
+ pipeline_name,
469
+ COUNT(*) AS runs,
470
+ AVG(duration_seconds) AS avg_duration,
471
+ SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failures
472
+ FROM pipeline_runs
473
+ GROUP BY 1
474
+ ORDER BY 4 DESC`),name:"pipeline_summary"},{...xe("sql",`SELECT
475
+ *
476
+ FROM pipeline_runs
477
+ WHERE status = 'failed'
478
+ AND run_date >= CURRENT_DATE - INTERVAL '7 days'
479
+ ORDER BY run_date DESC`),name:"recent_failures"}];default:return[xe("sql")]}}function ph({onFileOpened:e}){const{state:t,dispatch:n}=Se(),r=le[t.themeMode],[o,s]=f.useState(""),[a,l]=f.useState("blank"),[E,c]=f.useState(null),[d,T]=f.useState(!1),S=f.useRef(null);f.useEffect(()=>{var I;(I=S.current)==null||I.focus()},[]),f.useEffect(()=>{const I=N=>{N.key==="Escape"&&n({type:"CLOSE_NEW_NOTEBOOK_MODAL"})};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[n]);const u=async()=>{const I=Oh(o);if(I){c(I);return}T(!0),c(null);const N=dl(o),A=fh(a);try{const p=await te.createNotebook(N,a),O={name:`${N}.dqlnb`,path:p.path,type:"notebook",folder:"notebooks",isNew:!0};n({type:"FILE_ADDED",file:O}),n({type:"OPEN_FILE",file:O,cells:A,title:o.trim()}),n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),e(O)}catch{const p=`notebooks/${N}.dqlnb`,O={name:`${N}.dqlnb`,path:p,type:"notebook",folder:"notebooks",isNew:!0};n({type:"FILE_ADDED",file:O}),n({type:"OPEN_FILE",file:O,cells:A,title:o.trim()}),n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),e(O)}finally{T(!1)}},R=I=>{I.target===I.currentTarget&&n({type:"CLOSE_NEW_NOTEBOOK_MODAL"})};return i.jsx("div",{onClick:R,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:S,value:o,onChange:I=>{s(I.target.value),c(null)},onKeyDown:I=>{I.key==="Enter"&&u()},placeholder:"my-analysis",style:{background:r.inputBg,border:`1px solid ${E?r.error:r.inputBorder}`,borderRadius:6,color:r.textPrimary,fontSize:13,fontFamily:r.font,padding:"8px 12px",outline:"none",transition:"border-color 0.15s"}}),E&&i.jsx("span",{style:{fontSize:11,color:r.error,fontFamily:r.font},children:E}),o&&!E&&i.jsxs("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.fontMono},children:["File: ",dl(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(Tl).map(I=>i.jsx(hh,{value:I,selected:a===I,onSelect:()=>l(I),label:Tl[I],description:Nh[I],t:r},I))})]})]}),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:u,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 hh({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 Sl(e){return e.toLowerCase().replace(/[^a-z0-9\-_\s]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,64)}function Ch(e){return e.trim()?/^[a-zA-Z0-9\-_ ]+$/.test(e)?null:"Only letters, numbers, hyphens, underscores, and spaces allowed.":"Name is required."}function Lh({onFileOpened:e}){const{state:t,dispatch:n}=Se(),r=le[t.themeMode],[o,s]=f.useState(""),[a,l]=f.useState(null),[E,c]=f.useState(!1),d=f.useRef(null);f.useEffect(()=>{var u;(u=d.current)==null||u.focus()},[]),f.useEffect(()=>{const u=R=>{R.key==="Escape"&&n({type:"CLOSE_NEW_BLOCK_MODAL"})};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[n]);const T=async()=>{var I;const u=Ch(o);if(u){l(u);return}c(!0),l(null);const R=Sl(o);try{const N=await te.createBlock(o.trim()),A={name:`${R}.dql`,path:N.path,type:"block",folder:"blocks",isNew:!0};n({type:"FILE_ADDED",file:A}),n({type:"CLOSE_NEW_BLOCK_MODAL"}),e(A)}catch(N){(I=N.message)!=null&&I.includes("already exists")?l("A block with this name already exists."):l(N.message??"Failed to create block.")}finally{c(!1)}},S=u=>{u.target===u.currentTarget&&n({type:"CLOSE_NEW_BLOCK_MODAL"})};return i.jsx("div",{onClick:S,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:u=>{s(u.target.value),l(null)},onKeyDown:u=>{u.key==="Enter"&&T()},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/",Sl(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:T,disabled:E||!o.trim(),style:{background:r.accent,border:`1px solid ${r.accent}`,borderRadius:6,color:"#ffffff",cursor:E||!o.trim()?"not-allowed":"pointer",fontSize:13,fontFamily:r.font,fontWeight:500,padding:"7px 20px",opacity:E||!o.trim()?.6:1,display:"flex",alignItems:"center",gap:6},children:E?"Creating...":"Create Block"})]})]})})}const Dr=31,ul=10;function _h(){var ur,Rr,Ar,Ir,Nr,Or,fr;const{state:e,dispatch:t}=Se(),n=le[e.themeMode],[r,o]=f.useState("semantic"),[s,a]=f.useState("validate"),[l,E]=f.useState(""),[c,d]=f.useState(""),[T,S]=f.useState(""),[u,R]=f.useState(""),[I,N]=f.useState(""),[A,p]=f.useState(""),[O,h]=f.useState(""),[C,_]=f.useState({}),[m,M]=f.useState(null),[y,b]=f.useState(null),[g,x]=f.useState([]),[F,L]=f.useState({}),[P,D]=f.useState(""),[B,v]=f.useState(new Set),[U,Y]=f.useState(!1),[W,k]=f.useState(!1),[w,z]=f.useState(null),[q,Z]=f.useState(null),[K,H]=f.useState([]),[J,V]=f.useState(!1),[ee,ne]=f.useState(null),[oe,Te]=f.useState(!1),[Ie,de]=f.useState(!1),[Ne,Fe]=f.useState(0),[be,je]=f.useState(400),[tt,Et]=f.useState(360),[nt,Ot]=f.useState(280),[Ge,$e]=f.useState(!1),[Ue,Q]=f.useState(!1),Ee=f.useRef(null);f.useEffect(()=>{t({type:"SET_BLOCK_STUDIO_CATALOG_LOADING",loading:!0}),Z(null),te.getBlockStudioCatalog().then(j=>{t({type:"SET_BLOCK_STUDIO_CATALOG",catalog:j}),x(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(!m||m.startsWith("provider:")||m.startsWith("domain:")||m.startsWith("group:")){b(null);return}te.getSemanticObject(m).then(b).catch(()=>b(null))},[m]),f.useEffect(()=>{const j=window.setTimeout(()=>{e.blockStudioDraft.trim()&&te.validateBlockStudio(e.blockStudioDraft,e.activeBlockPath).then(ae=>t({type:"SET_BLOCK_STUDIO_VALIDATION",validation:ae})).catch(()=>{})},250);return()=>window.clearTimeout(j)},[e.blockStudioDraft,e.activeBlockPath,t]);const Re=((ur=e.blockStudioCatalog)==null?void 0:ur.semanticTree)??null,Ae=f.useMemo(()=>wh(Re)?Re:Hh(e.semanticLayer),[Re,e.semanticLayer]),ft=f.useMemo(()=>bs(Ae,"provider"),[Ae]),De=f.useMemo(()=>bs(Ae,"cube"),[Ae]),pt=f.useMemo(()=>bs(Ae,"owner"),[Ae]),zt=f.useMemo(()=>Ae?Dc(Ae,{query:l,provider:c,domain:T,cube:u,owner:I,tag:A,type:O}):null,[Ae,l,c,T,u,I,A,O]),Mt=f.useMemo(()=>Mc((zt==null?void 0:zt.children)??[],C),[zt,C]),Yo=f.useMemo(()=>Fh(g,P),[g,P]),ko=f.useMemo(()=>Gh(g),[g]),hn={metrics:e.semanticLayer.metrics.length,dimensions:e.semanticLayer.dimensions.length,hierarchies:e.semanticLayer.hierarchies.length},Vo=Mt.length*Dr,Er=f.useMemo(()=>{const j=Math.max(0,Math.floor(Ne/Dr)-ul),ae=Math.min(Mt.length,Math.ceil((Ne+be)/Dr)+ul);return{offsetTop:j*Dr,rows:Mt.slice(j,ae)}},[Mt,Ne,be]);f.useEffect(()=>{const j=Ee.current;if(!j)return;const ae=()=>je(j.clientHeight||400);if(ae(),typeof ResizeObserver>"u")return window.addEventListener("resize",ae),()=>window.removeEventListener("resize",ae);const pe=new ResizeObserver(()=>ae());return pe.observe(j),()=>pe.disconnect()},[]),f.useEffect(()=>{Fe(0),Ee.current&&(Ee.current.scrollTop=0)},[l,c,T,u,I,A,O]);const Wo=f.useMemo(()=>{var ae;const j=Oa(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:(ae=j==null?void 0:j.tags)!=null&&ae.length?j.tags:e.blockStudioMetadata.tags,blockType:(j==null?void 0:j.blockType)||"custom"}:j},[e.blockStudioDraft,e.blockStudioMetadata]),we=j=>{t({type:"SET_BLOCK_STUDIO_DRAFT",draft:j})},cr=async()=>{var j,ae,pe;Y(!0);try{const Le=await te.runBlockStudio(e.blockStudioDraft,e.activeBlockPath);t({type:"SET_BLOCK_STUDIO_PREVIEW",preview:Le}),a("results")}catch(Le){t({type:"SET_BLOCK_STUDIO_VALIDATION",validation:{valid:!1,chartConfig:(j=e.blockStudioValidation)==null?void 0:j.chartConfig,executableSql:((ae=e.blockStudioValidation)==null?void 0:ae.executableSql)??null,semanticRefs:((pe=e.blockStudioValidation)==null?void 0:pe.semanticRefs)??{metrics:[],dimensions:[],segments:[]},diagnostics:[{severity:"error",code:"block_run_failed",message:Le instanceof Error?Le.message:String(Le)}]}}),a("validate")}finally{Y(!1)}},Tr=async()=>{if(!e.blockStudioMetadata){t({type:"OPEN_NEW_BLOCK_MODAL"});return}k(!0),z(null);try{const j=await te.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(pe=>pe.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 ae=(j==null?void 0:j.message)??"Save failed";z(ae.includes("409")||ae.includes("BLOCK_EXISTS")?"A block with this name already exists. Rename and try again.":ae),setTimeout(()=>z(null),5e3)}finally{k(!1)}},dr=j=>{var ae;if(j.kind==="metric"||j.kind==="dimension"){const pe=YR(j.kind==="metric"?"metric":"dimension",j.name);(((ae=Oa(e.blockStudioDraft))==null?void 0:ae.blockType)??"custom")==="semantic"?we(kR(e.blockStudioDraft,{kind:j.kind==="metric"?"metric":"dimension",name:j.name})):ni(pe)||we(VR(e.blockStudioDraft,pe)),t({type:"ADD_SEMANTIC_RECENT",name:j.name});return}if(j.kind==="segment"&&j.sql){we(Pr(e.blockStudioDraft,`/* segment:${j.name} */ (${j.sql})`));return}j.kind==="pre_aggregation"&&we(Pr(e.blockStudioDraft,`/* pre_aggregation:${j.name} */`))},jo=j=>{we(Pr(e.blockStudioDraft,j))},$o=async j=>{if(!(!j.path||j.kind!=="table"||j.children&&j.children.length>0)){v(ae=>new Set(ae).add(j.id));try{const ae=await te.describeTable(j.path);x(pe=>Pc(pe,j.id,{...j,children:ae.map(Le=>({id:`db-column:${j.path}:${Le.name}`,label:Le.name,kind:"column",path:j.path,type:Le.type}))}))}finally{v(ae=>{const pe=new Set(ae);return pe.delete(j.id),pe})}}},Sr=f.useCallback(async()=>{try{const j=await te.getBlockStudioCatalog();j!=null&&j.databaseTree&&x(j.databaseTree),t({type:"SET_BLOCK_STUDIO_CATALOG",catalog:j})}catch{}},[t]),Xo=((Rr=e.blockStudioValidation)==null?void 0:Rr.chartConfig)??((Ar=e.blockStudioPreview)==null?void 0:Ar.chartConfig)??{chart:"table"},Ko=e.blockStudioPreview?Hn(e.blockStudioPreview.result,e.blockStudioPreview.chartConfig):"table",zo=j=>{j.preventDefault();const ae=j.clientX,pe=tt,Le=Cn=>{const Ln=Math.min(520,Math.max(280,pe+Cn.clientX-ae));Et(Ln)},Pt=()=>{window.removeEventListener("mousemove",Le),window.removeEventListener("mouseup",Pt)};window.addEventListener("mousemove",Le),window.addEventListener("mouseup",Pt)},Jo=j=>{j.preventDefault();const ae=j.clientY,pe=nt,Le=Cn=>{const Ln=Math.min(520,Math.max(180,pe-(Cn.clientY-ae)));Ot(Ln)},Pt=()=>{window.removeEventListener("mousemove",Le),window.removeEventListener("mouseup",Pt)};window.addEventListener("mousemove",Le),window.addEventListener("mouseup",Pt)};return i.jsxs("div",{style:{flex:1,position:"relative",display:"grid",gridTemplateColumns:Ge?"0 0 minmax(0, 1fr)":`${tt}px 6px minmax(0, 1fr)`,gridTemplateRows:Ue?"minmax(0, 1fr) 0 0":`minmax(0, 1fr) 6px ${nt}px`,overflow:"hidden",background:n.appBg},children:[i.jsxs("div",{style:{borderRight:Ge?"none":`1px solid ${n.headerBorder}`,display:Ge?"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:()=>$e(!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(sn,{label:"Metrics",value:hn.metrics,t:n}),i.jsx(sn,{label:"Dimensions",value:hn.dimensions,t:n}),i.jsx(sn,{label:"Hierarchies",value:hn.hierarchies,t:n})]})]}),i.jsxs("div",{style:{display:"flex",padding:"10px 12px",gap:8,borderBottom:`1px solid ${n.headerBorder}`},children:[i.jsx(ut,{active:r==="semantic",onClick:()=>o("semantic"),label:"Semantic Layer"}),i.jsx(ut,{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(KE,{query:l,provider:c,cube:u,owner:I,domain:T,tag:A,type:O,providers:ft,cubes:De,owners:pt,domains:e.semanticLayer.domains,tags:e.semanticLayer.tags,onQueryChange:E,onProviderChange:d,onCubeChange:R,onOwnerChange:N,onDomainChange:S,onTagChange:p,onTypeChange:h,t:n})}),i.jsx("div",{ref:Ee,onScroll:j=>Fe(j.currentTarget.scrollTop),style:{flex:1,overflowY:"auto",borderBottom:`1px solid ${n.headerBorder}`,background:n.cellBg},children:q?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:q}),i.jsx("button",{onClick:()=>{Z(null),Sr()},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(Ft,{message:"Loading semantic catalog…"}):Mt.length===0?i.jsx(Ft,{message:"No semantic objects match the current filters."}):i.jsx("div",{style:{height:Vo,position:"relative"},children:i.jsx("div",{style:{position:"absolute",top:Er.offsetTop,left:0,right:0},children:Er.rows.map(j=>i.jsx(Uh,{row:j,selectedId:m,setSelectedId:M,expanded:C,setExpanded:_,onInsert:dr,favorites:new Set(e.semanticLayer.favorites),dispatch:t,t:n},j.node.id))})})}),i.jsx(XE,{item:y,favorite:!!(y&&e.semanticLayer.favorites.includes(y.name)),onInsert:()=>y&&dr(y),onPreview:()=>{y!=null&&y.sql&&we(Pr(e.blockStudioDraft,y.sql))},onCopySql:()=>{y!=null&&y.sql&&navigator.clipboard.writeText(y.sql)},onToggleFavorite:()=>{!y||y.kind!=="metric"&&y.kind!=="dimension"||te.toggleFavorite(y.name).then(j=>t({type:"SET_SEMANTIC_FAVORITES",favorites:j}))},t:n})]}):i.jsx(bh,{tree:Yo,totalTree:g,expanded:F,setExpanded:L,onEnsureColumns:$o,onInsert:jo,query:P,onQueryChange:D,stats:ko,connectionName:((Ir=e.blockStudioCatalog)==null?void 0:Ir.connection.current)??"default",loadingNodes:B,onRefresh:Sr,t:n})]}),i.jsx("div",{onMouseDown:Ge?void 0:zo,style:{display:Ge?"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:[Ge&&i.jsx("button",{onClick:()=>$e(!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(Mr,{label:"Semantic Skeleton",onClick:()=>{var j;return we(vh(((j=e.blockStudioMetadata)==null?void 0:j.name)??"New Block"))}}),i.jsx(Mr,{label:"Custom Skeleton",onClick:()=>{var j;return we(Bh(((j=e.blockStudioMetadata)==null?void 0:j.name)??"New Block"))}}),i.jsx(Mr,{label:"Run",onClick:()=>void cr(),busy:U}),i.jsx(Mr,{label:"Save",onClick:()=>void Tr(),busy:W}),w&&i.jsx("span",{style:{fontSize:11,color:"#f85149",fontFamily:n.font,padding:"4px 8px",background:"#f8514918",borderRadius:6},children:w})]}),i.jsx("div",{style:{flex:1,overflow:"hidden"},children:i.jsx(Mi,{value:e.blockStudioDraft,onChange:we,onRun:()=>void cr(),themeMode:e.themeMode,autoFocus:!0,errorMessage:(Or=(Nr=e.blockStudioValidation)==null?void 0:Nr.diagnostics.find(j=>j.severity==="error"))==null?void 0:Or.message})})]}),i.jsx("div",{onMouseDown:Ue?void 0:Jo,style:{gridColumn:"1 / -1",gridRow:"2",display:Ue?"none":"block",cursor:"row-resize",background:n.headerBorder}}),i.jsxs("div",{style:{gridColumn:"1 / -1",gridRow:"3",borderTop:Ue?"none":`1px solid ${n.headerBorder}`,display:Ue?"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(ut,{active:s==="results",onClick:()=>a("results"),label:"Results"}),i.jsx(ut,{active:s==="visualization",onClick:()=>a("visualization"),label:"Visualization"}),i.jsx(ut,{active:s==="validate",onClick:()=>a("validate"),label:"Validate"}),i.jsx(ut,{active:s==="tests",onClick:()=>a("tests"),label:"Tests"}),i.jsx(ut,{active:s==="history",onClick:()=>{a("history"),!J&&e.activeBlockPath&&te.getBlockHistory(e.activeBlockPath).then(j=>{H(j.entries),V(!0)})},label:"History"}),i.jsx(ut,{active:s==="save",onClick:()=>a("save"),label:"Save"}),i.jsx("div",{style:{flex:1}}),i.jsx("button",{onClick:()=>Q(!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}),Ko==="table"?i.jsx(Lo,{result:e.blockStudioPreview.result,themeMode:e.themeMode}):i.jsx(AR,{result:e.blockStudioPreview.result,chartConfig:e.blockStudioPreview.chartConfig,themeMode:e.themeMode})]}):i.jsx(Ft,{message:"Run the block to preview results and visualization."})),s==="visualization"&&i.jsx(gh,{chartConfig:Xo,onChange:j=>we(HR(e.blockStudioDraft,j)),t:n}),s==="tests"&&i.jsx(Mh,{source:e.blockStudioDraft,blockPath:e.activeBlockPath,testResults:ee,running:oe,onRunTests:async()=>{if(e.activeBlockPath){Te(!0);try{const j=await te.runBlockTests(e.blockStudioDraft,e.activeBlockPath);ne(j.assertions??[])}catch{ne([])}finally{Te(!1)}}},t:n}),s==="validate"&&i.jsx(mh,{diagnostics:((fr=e.blockStudioValidation)==null?void 0:fr.diagnostics)??[],t:n}),s==="history"&&i.jsx(Ph,{entries:K,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(Dh,{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(xh,{metadata:e.blockStudioMetadata,draftMetadata:Wo,onChange:j=>{if(!e.blockStudioMetadata)return;t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,...j}});let ae=e.blockStudioDraft;typeof j.name=="string"&&(ae=ac(ae,j.name)),typeof j.domain=="string"&&(ae=rs(ae,"domain",j.domain)),typeof j.owner=="string"&&(ae=rs(ae,"owner",j.owner)),typeof j.description=="string"&&(ae=rs(ae,"description",j.description)),j.tags&&(ae=wR(ae,j.tags)),we(ae)},onSave:()=>void Tr(),saving:W,t:n})]})]})]}),Ue&&i.jsx("div",{style:{position:"absolute",right:16,bottom:16},children:i.jsx("button",{onClick:()=>Q(!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 ut({active:e,onClick:t,label:n,busy:r}){const{state:o}=Se(),s=le[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 Mr(e){return i.jsx(ut,{active:!1,...e})}function sn({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 mh({diagnostics:e,t}){return e.length===0?i.jsx(Ft,{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 gh({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"}),Ci.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 xh({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:E=>n({name:E.target.value}),placeholder:"Block name",style:a}),i.jsx("input",{value:l.domain,onChange:E=>n({domain:E.target.value}),placeholder:"Domain",style:a}),i.jsx("input",{value:l.owner,onChange:E=>n({owner:E.target.value}),placeholder:"Owner",style:a}),i.jsx("input",{value:l.description,onChange:E=>n({description:E.target.value}),placeholder:"Description",style:a}),i.jsx("input",{value:l.tags.join(", "),onChange:E=>n({tags:E.target.value.split(",").map(c=>c.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 Ft({message:e}){const{state:t}=Se(),n=le[t.themeMode];return i.jsx("div",{style:{padding:16,fontSize:12,color:n.textMuted},children:e})}const Rl={draft:"#8b949e",review:"#d29922",certified:"#3fb950",deprecated:"#f85149"},yh={draft:["review"],review:["certified","draft"],certified:["deprecated"],deprecated:["draft"]};function Dh({currentStatus:e,blockPath:t,onStatusChanged:n,t:r}){const[o,s]=f.useState(!1),a=yh[e]??[],l=async E=>{if(t){s(!0);try{const c=await te.updateBlockStatus(t,E);c.ok&&c.status&&n(c.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:Rl[e]??r.textMuted,background:`${Rl[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(E=>i.jsx("button",{onClick:()=>void l(E),disabled:o,style:{background:E==="certified"?"#3fb950":E==="deprecated"?"#f85149":r.btnBg,border:`1px solid ${E==="certified"?"#3fb950":E==="deprecated"?"#f85149":r.btnBorder}`,borderRadius:4,color:E==="certified"||E==="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?"...":E==="certified"?"Certify":E==="deprecated"?"Deprecate":`Move to ${E}`},E))]})}function Mh({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(E=>({field:E[1],operator:E[2],expected:E[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 {
480
+ assert row_count > 0
481
+ assert max_value <= 1000000
482
+ }`})]}),l.map((E,c)=>{const d=n==null?void 0:n[c],T=d==null?void 0:d.passed;return i.jsxs("div",{style:{padding:"8px 12px",borderRadius:8,border:`1px solid ${d?T?"#3fb95040":"#f8514940":s.cellBorder}`,background:d?T?"#3fb95008":"#f8514908":"transparent",display:"flex",alignItems:"center",gap:8},children:[d&&i.jsx("span",{style:{fontSize:14,color:T?"#3fb950":"#f85149",fontWeight:700},children:T?"✓":"✗"}),i.jsxs("div",{style:{flex:1},children:[i.jsxs("div",{style:{fontSize:12,color:s.textPrimary,fontFamily:s.fontMono},children:[E.field," ",E.operator," ",E.expected]}),d&&!T&&d.actual&&i.jsxs("div",{style:{fontSize:11,color:"#f85149",fontFamily:s.font,marginTop:2},children:["Actual: ",d.actual]})]})]},c)}),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(E=>E.passed).length,"/",n.length," passed"]})]})}function Ph({entries:e,t}){return e.length===0?i.jsx(Ft,{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 bh({tree:e,totalTree:t,expanded:n,setExpanded:r,onEnsureColumns:o,onInsert:s,query:a,onQueryChange:l,stats:E,connectionName:c,loadingNodes:d,onRefresh:T,t:S}){const u={width:"100%",background:S.inputBg,border:`1px solid ${S.inputBorder}`,borderRadius:8,color:S.textPrimary,fontSize:12,fontFamily:S.font,padding:"8px 10px",outline:"none",boxSizing:"border-box"},R=(I,N=0)=>{var m,M,y;const A=I.kind!=="column",p=n[I.id]??N<1,O=d.has(I.id),h=I.kind==="schema"?(m=I.children)==null?void 0:m.length:I.kind==="table"?(M=I.children)==null?void 0:M.length:void 0,C=I.kind==="column"?I.type:I.kind,_=I.kind==="column"&&I.type?ei(I.type,S.accent):void 0;return i.jsxs("div",{children:[i.jsx(wn,{label:O?`${I.label} …`:I.label,depth:N,count:h,expanded:A?p:void 0,onToggle:A?()=>{r(b=>({...b,[I.id]:!p})),p||o(I)}:void 0,badge:C,badgeColor:_,onClick:()=>{if(I.kind==="table"&&I.path&&s(I.path),I.kind==="column"){const b=I.path?I.path.split(".").pop():"";s(b?`${b}.${I.label}`:I.label)}},onDoubleClick:()=>{I.kind==="table"&&I.path&&s(`SELECT *
483
+ FROM ${I.path}
484
+ LIMIT 100`)},t:S}),A&&p&&((y=I.children)==null?void 0:y.map(b=>R(b,N+1)))]},I.id)};return i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:{padding:12,display:"grid",gap:12,borderBottom:`1px solid ${S.headerBorder}`,background:`${S.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:S.textPrimary,fontFamily:S.font},children:"Database Browser"}),i.jsx("div",{style:{fontSize:11,color:S.textMuted,fontFamily:S.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:T,title:"Refresh schema",style:{background:"none",border:"none",cursor:"pointer",padding:4,borderRadius:6,color:S.textMuted,fontSize:14,lineHeight:1},children:"↻"}),i.jsx("span",{style:{fontSize:10,fontWeight:700,color:S.accent,background:`${S.accent}18`,borderRadius:999,padding:"5px 9px",textTransform:"uppercase",letterSpacing:"0.04em"},children:c})]})]}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:8},children:[i.jsx(sn,{label:"Schemas",value:E.schemas,t:S}),i.jsx(sn,{label:"Tables",value:E.tables,t:S}),i.jsx(sn,{label:"Columns",value:E.columns,t:S})]}),i.jsx("input",{value:a,onChange:I=>l(I.target.value),placeholder:"Search schemas, tables, columns...",style:u})]}),i.jsx("div",{style:{flex:1,overflowY:"auto",padding:e.length>0?"6px 0 0":0},children:t.length===0?i.jsx(Ft,{message:"No schemas were found for the active connection yet."}):e.length===0?i.jsx(Ft,{message:"No database objects match the current search."}):e.map(I=>R(I))})]})}function Uh({row:e,selectedId:t,setSelectedId:n,expanded:r,setExpanded:o,onInsert:s,favorites:a,dispatch:l,t:E}){var R;const{node:c,depth:d,hasChildren:T,isExpanded:S}=e,u=c.id.split(":").slice(1).join(":");return T?i.jsx(wn,{label:c.label,depth:d,count:(R=c.children)==null?void 0:R.length,expanded:S,onToggle:()=>o(I=>({...I,[c.id]:!S})),onClick:()=>n(c.id),selected:t===c.id,t:E}):i.jsx(wn,{label:c.label,depth:d,badge:c.kind,selected:t===c.id,onClick:()=>n(c.id),onDoubleClick:()=>{te.getSemanticObject(c.id).then(s).catch(()=>{})},onFavoriteToggle:c.kind==="metric"||c.kind==="dimension"?()=>void te.toggleFavorite(u).then(I=>l({type:"SET_SEMANTIC_FAVORITES",favorites:I})):void 0,favorite:c.kind==="metric"||c.kind==="dimension"?a.has(u):void 0,t:E})}function Pr(e,t){const n=e.match(/query\s*=\s*"""([\s\S]*?)"""/i);return n?e.replace(n[0],`query = """${n[1].trimEnd()}
485
+ ${t}
486
+ """`):/^\s*block\s+"/i.test(e.trim())?e.replace(/\n\}\s*$/,`
487
+
488
+ query = """
489
+ ${t}
490
+ """
491
+ }
492
+ `):`${e.trimEnd()}
493
+ ${t}
494
+ `}function vh(e){return`block "${e}" {
495
+ domain = "uncategorized"
496
+ type = "semantic"
497
+ description = ""
498
+ owner = ""
499
+ tags = []
500
+ metric = "total_revenue"
501
+
502
+ visualization {
503
+ chart = "table"
504
+ }
505
+ }
506
+ `}function Bh(e){return`block "${e}" {
507
+ domain = "uncategorized"
508
+ type = "custom"
509
+ description = ""
510
+ owner = ""
511
+ tags = []
512
+
513
+ query = """
514
+ SELECT 1 AS value
515
+ """
516
+
517
+ visualization {
518
+ chart = "table"
519
+ }
520
+ }
521
+ `}function bs(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 Dc(e,t){var S,u,R,I,N;const n=t.query.trim().toLowerCase(),r=Object.values(e.meta??{}).filter(A=>A!=null).map(A=>String(A).toLowerCase()),o=!n||e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)||r.some(A=>A.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"||((S=e.meta)==null?void 0:S.domain)===t.domain||e.kind==="domain"&&e.label===t.domain,l=!t.provider||((u=e.meta)==null?void 0:u.provider)===t.provider||e.id===`provider:${t.provider}`,E=!t.cube||((R=e.meta)==null?void 0:R.cube)===t.cube,c=!t.owner||((I=e.meta)==null?void 0:I.owner)===t.owner,d=!t.tag||String(((N=e.meta)==null?void 0:N.tags)??"").split(",").filter(Boolean).includes(t.tag),T=(e.children??[]).map(A=>Dc(A,t)).filter(A=>!!A);return T.length>0?{...e,children:T,count:e.kind==="provider"||e.kind==="domain"||e.kind==="group"?T.length:e.count}:o&&s&&a&&l&&E&&c&&d?{...e,children:[]}:null}function Mc(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(...Mc(o.children??[],t,n+1))}return r}function Pc(e,t,n){return e.map(r=>r.id===t?n:r.children?{...r,children:Pc(r.children,t,n)}:r)}function Fh(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 Gh(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 wh(e){return!!(e&&e.children&&e.children.length>0)}function Hh(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(T=>T.kind==="metric"),E=a.filter(T=>T.kind==="dimension"),c=a.filter(T=>T.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((T,S)=>T.label.localeCompare(S.label))}),E.length>0&&d.push({id:`group:${s}:dimensions`,label:"Dimensions",kind:"group",count:E.length,meta:{provider:t,domain:s},children:E.sort((T,S)=>T.label.localeCompare(S.label))}),c.length>0&&d.push({id:`group:${s}:hierarchies`,label:"Hierarchies",kind:"group",count:c.length,meta:{provider:t,domain:s},children:c.sort((T,S)=>T.label.localeCompare(S.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}]}}function he(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=he(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var Yh={value:()=>{}};function xo(){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 zr(n)}function zr(e){this._=e}function kh(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}})}zr.prototype=xo.prototype={constructor:zr,on:function(e,t){var n=this._,r=kh(e+"",n),o,s=-1,a=r.length;if(arguments.length<2){for(;++s<a;)if((o=(e=r[s]).type)&&(o=Vh(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]=Al(n[o],e.name,t);else if(t==null)for(o in n)n[o]=Al(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 zr(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 Vh(e,t){for(var n=0,r=e.length,o;n<r;++n)if((o=e[n]).name===t)return o.value}function Al(e,t,n){for(var r=0,o=e.length;r<o;++r)if(e[r].name===t){e[r]=Yh,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var ai="http://www.w3.org/1999/xhtml";const Il={svg:"http://www.w3.org/2000/svg",xhtml:ai,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function yo(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),Il.hasOwnProperty(t)?{space:Il[t],local:e}:e}function Wh(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===ai&&t.documentElement.namespaceURI===ai?t.createElement(e):t.createElementNS(n,e)}}function jh(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function bc(e){var t=yo(e);return(t.local?jh:Wh)(t)}function $h(){}function bi(e){return e==null?$h:function(){return this.querySelector(e)}}function Xh(e){typeof e!="function"&&(e=bi(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),E,c,d=0;d<a;++d)(E=s[d])&&(c=e.call(E,E.__data__,d,s))&&("__data__"in E&&(c.__data__=E.__data__),l[d]=c);return new ke(r,this._parents)}function Kh(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function zh(){return[]}function Uc(e){return e==null?zh:function(){return this.querySelectorAll(e)}}function Jh(e){return function(){return Kh(e.apply(this,arguments))}}function qh(e){typeof e=="function"?e=Jh(e):e=Uc(e);for(var t=this._groups,n=t.length,r=[],o=[],s=0;s<n;++s)for(var a=t[s],l=a.length,E,c=0;c<l;++c)(E=a[c])&&(r.push(e.call(E,E.__data__,c,a)),o.push(E));return new ke(r,o)}function vc(e){return function(){return this.matches(e)}}function Bc(e){return function(t){return t.matches(e)}}var Qh=Array.prototype.find;function Zh(e){return function(){return Qh.call(this.children,e)}}function eC(){return this.firstElementChild}function tC(e){return this.select(e==null?eC:Zh(typeof e=="function"?e:Bc(e)))}var nC=Array.prototype.filter;function rC(){return Array.from(this.children)}function oC(e){return function(){return nC.call(this.children,e)}}function sC(e){return this.selectAll(e==null?rC:oC(typeof e=="function"?e:Bc(e)))}function iC(e){typeof e!="function"&&(e=vc(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]=[],E,c=0;c<a;++c)(E=s[c])&&e.call(E,E.__data__,c,s)&&l.push(E);return new ke(r,this._parents)}function Fc(e){return new Array(e.length)}function aC(){return new ke(this._enter||this._groups.map(Fc),this._parents)}function lo(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}lo.prototype={constructor:lo,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 lC(e){return function(){return e}}function EC(e,t,n,r,o,s){for(var a=0,l,E=t.length,c=s.length;a<c;++a)(l=t[a])?(l.__data__=s[a],r[a]=l):n[a]=new lo(e,s[a]);for(;a<E;++a)(l=t[a])&&(o[a]=l)}function cC(e,t,n,r,o,s,a){var l,E,c=new Map,d=t.length,T=s.length,S=new Array(d),u;for(l=0;l<d;++l)(E=t[l])&&(S[l]=u=a.call(E,E.__data__,l,t)+"",c.has(u)?o[l]=E:c.set(u,E));for(l=0;l<T;++l)u=a.call(e,s[l],l,s)+"",(E=c.get(u))?(r[l]=E,E.__data__=s[l],c.delete(u)):n[l]=new lo(e,s[l]);for(l=0;l<d;++l)(E=t[l])&&c.get(S[l])===E&&(o[l]=E)}function TC(e){return e.__data__}function dC(e,t){if(!arguments.length)return Array.from(this,TC);var n=t?cC:EC,r=this._parents,o=this._groups;typeof e!="function"&&(e=lC(e));for(var s=o.length,a=new Array(s),l=new Array(s),E=new Array(s),c=0;c<s;++c){var d=r[c],T=o[c],S=T.length,u=SC(e.call(d,d&&d.__data__,c,r)),R=u.length,I=l[c]=new Array(R),N=a[c]=new Array(R),A=E[c]=new Array(S);n(d,T,I,N,A,u,t);for(var p=0,O=0,h,C;p<R;++p)if(h=I[p]){for(p>=O&&(O=p+1);!(C=N[O])&&++O<R;);h._next=C||null}}return a=new ke(a,r),a._enter=l,a._exit=E,a}function SC(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function uC(){return new ke(this._exit||this._groups.map(Fc),this._parents)}function RC(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 AC(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),E=0;E<a;++E)for(var c=n[E],d=r[E],T=c.length,S=l[E]=new Array(T),u,R=0;R<T;++R)(u=c[R]||d[R])&&(S[R]=u);for(;E<o;++E)l[E]=n[E];return new ke(l,this._parents)}function IC(){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 NC(e){e||(e=OC);function t(T,S){return T&&S?e(T.__data__,S.__data__):!T-!S}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,E=o[s]=new Array(l),c,d=0;d<l;++d)(c=a[d])&&(E[d]=c);E.sort(t)}return new ke(o,this._parents).order()}function OC(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function fC(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function pC(){return Array.from(this)}function hC(){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 CC(){let e=0;for(const t of this)++e;return e}function LC(){return!this.node()}function _C(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 mC(e){return function(){this.removeAttribute(e)}}function gC(e){return function(){this.removeAttributeNS(e.space,e.local)}}function xC(e,t){return function(){this.setAttribute(e,t)}}function yC(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function DC(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function MC(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 PC(e,t){var n=yo(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?gC:mC:typeof t=="function"?n.local?MC:DC:n.local?yC:xC)(n,t))}function Gc(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function bC(e){return function(){this.style.removeProperty(e)}}function UC(e,t,n){return function(){this.style.setProperty(e,t,n)}}function vC(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function BC(e,t,n){return arguments.length>1?this.each((t==null?bC:typeof t=="function"?vC:UC)(e,t,n??"")):cn(this.node(),e)}function cn(e,t){return e.style.getPropertyValue(t)||Gc(e).getComputedStyle(e,null).getPropertyValue(t)}function FC(e){return function(){delete this[e]}}function GC(e,t){return function(){this[e]=t}}function wC(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function HC(e,t){return arguments.length>1?this.each((t==null?FC:typeof t=="function"?wC:GC)(e,t)):this.node()[e]}function wc(e){return e.trim().split(/^|\s+/)}function Ui(e){return e.classList||new Hc(e)}function Hc(e){this._node=e,this._names=wc(e.getAttribute("class")||"")}Hc.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 Yc(e,t){for(var n=Ui(e),r=-1,o=t.length;++r<o;)n.add(t[r])}function kc(e,t){for(var n=Ui(e),r=-1,o=t.length;++r<o;)n.remove(t[r])}function YC(e){return function(){Yc(this,e)}}function kC(e){return function(){kc(this,e)}}function VC(e,t){return function(){(t.apply(this,arguments)?Yc:kc)(this,e)}}function WC(e,t){var n=wc(e+"");if(arguments.length<2){for(var r=Ui(this.node()),o=-1,s=n.length;++o<s;)if(!r.contains(n[o]))return!1;return!0}return this.each((typeof t=="function"?VC:t?YC:kC)(n,t))}function jC(){this.textContent=""}function $C(e){return function(){this.textContent=e}}function XC(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function KC(e){return arguments.length?this.each(e==null?jC:(typeof e=="function"?XC:$C)(e)):this.node().textContent}function zC(){this.innerHTML=""}function JC(e){return function(){this.innerHTML=e}}function qC(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function QC(e){return arguments.length?this.each(e==null?zC:(typeof e=="function"?qC:JC)(e)):this.node().innerHTML}function ZC(){this.nextSibling&&this.parentNode.appendChild(this)}function eL(){return this.each(ZC)}function tL(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function nL(){return this.each(tL)}function rL(e){var t=typeof e=="function"?e:bc(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function oL(){return null}function sL(e,t){var n=typeof e=="function"?e:bc(e),r=t==null?oL:typeof t=="function"?t:bi(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function iL(){var e=this.parentNode;e&&e.removeChild(this)}function aL(){return this.each(iL)}function lL(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function EL(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function cL(e){return this.select(e?EL:lL)}function TL(e){return arguments.length?this.property("__data__",e):this.node().__data__}function dL(e){return function(t){e.call(this,t,this.__data__)}}function SL(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 uL(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 RL(e,t,n){return function(){var r=this.__on,o,s=dL(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 AL(e,t,n){var r=SL(e+""),o,s=r.length,a;if(arguments.length<2){var l=this.node().__on;if(l){for(var E=0,c=l.length,d;E<c;++E)for(o=0,d=l[E];o<s;++o)if((a=r[o]).type===d.type&&a.name===d.name)return d.value}return}for(l=t?RL:uL,o=0;o<s;++o)this.each(l(r[o],t,n));return this}function Vc(e,t,n){var r=Gc(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 IL(e,t){return function(){return Vc(this,e,t)}}function NL(e,t){return function(){return Vc(this,e,t.apply(this,arguments))}}function OL(e,t){return this.each((typeof t=="function"?NL:IL)(e,t))}function*fL(){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 Wc=[null];function ke(e,t){this._groups=e,this._parents=t}function tr(){return new ke([[document.documentElement]],Wc)}function pL(){return this}ke.prototype=tr.prototype={constructor:ke,select:Xh,selectAll:qh,selectChild:tC,selectChildren:sC,filter:iC,data:dC,enter:aC,exit:uC,join:RC,merge:AC,selection:pL,order:IC,sort:NC,call:fC,nodes:pC,node:hC,size:CC,empty:LC,each:_C,attr:PC,style:BC,property:HC,classed:WC,text:KC,html:QC,raise:eL,lower:nL,append:rL,insert:sL,remove:aL,clone:cL,datum:TL,on:AL,dispatch:OL,[Symbol.iterator]:fL};function Ye(e){return typeof e=="string"?new ke([[document.querySelector(e)]],[document.documentElement]):new ke([[e]],Wc)}function hL(e){let t;for(;t=e.sourceEvent;)e=t;return e}function Ke(e,t){if(e=hL(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 CL={passive:!1},Vn={capture:!0,passive:!1};function Us(e){e.stopImmediatePropagation()}function an(e){e.preventDefault(),e.stopImmediatePropagation()}function jc(e){var t=e.document.documentElement,n=Ye(e).on("dragstart.drag",an,Vn);"onselectstart"in t?n.on("selectstart.drag",an,Vn):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function $c(e,t){var n=e.document.documentElement,r=Ye(e).on("dragstart.drag",null);t&&(r.on("click.drag",an,Vn),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 br=e=>()=>e;function li(e,{sourceEvent:t,subject:n,target:r,identifier:o,active:s,x:a,y:l,dx:E,dy:c,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:E,enumerable:!0,configurable:!0},dy:{value:c,enumerable:!0,configurable:!0},_:{value:d}})}li.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function LL(e){return!e.ctrlKey&&!e.button}function _L(){return this.parentNode}function mL(e,t){return t??{x:e.x,y:e.y}}function gL(){return navigator.maxTouchPoints||"ontouchstart"in this}function Xc(){var e=LL,t=_L,n=mL,r=gL,o={},s=xo("start","drag","end"),a=0,l,E,c,d,T=0;function S(h){h.on("mousedown.drag",u).filter(r).on("touchstart.drag",N).on("touchmove.drag",A,CL).on("touchend.drag touchcancel.drag",p).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function u(h,C){if(!(d||!e.call(this,h,C))){var _=O(this,t.call(this,h,C),h,C,"mouse");_&&(Ye(h.view).on("mousemove.drag",R,Vn).on("mouseup.drag",I,Vn),jc(h.view),Us(h),c=!1,l=h.clientX,E=h.clientY,_("start",h))}}function R(h){if(an(h),!c){var C=h.clientX-l,_=h.clientY-E;c=C*C+_*_>T}o.mouse("drag",h)}function I(h){Ye(h.view).on("mousemove.drag mouseup.drag",null),$c(h.view,c),an(h),o.mouse("end",h)}function N(h,C){if(e.call(this,h,C)){var _=h.changedTouches,m=t.call(this,h,C),M=_.length,y,b;for(y=0;y<M;++y)(b=O(this,m,h,C,_[y].identifier,_[y]))&&(Us(h),b("start",h,_[y]))}}function A(h){var C=h.changedTouches,_=C.length,m,M;for(m=0;m<_;++m)(M=o[C[m].identifier])&&(an(h),M("drag",h,C[m]))}function p(h){var C=h.changedTouches,_=C.length,m,M;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),m=0;m<_;++m)(M=o[C[m].identifier])&&(Us(h),M("end",h,C[m]))}function O(h,C,_,m,M,y){var b=s.copy(),g=Ke(y||_,C),x,F,L;if((L=n.call(h,new li("beforestart",{sourceEvent:_,target:S,identifier:M,active:a,x:g[0],y:g[1],dx:0,dy:0,dispatch:b}),m))!=null)return x=L.x-g[0]||0,F=L.y-g[1]||0,function P(D,B,v){var U=g,Y;switch(D){case"start":o[M]=P,Y=a++;break;case"end":delete o[M],--a;case"drag":g=Ke(v||B,C),Y=a;break}b.call(D,h,new li(D,{sourceEvent:B,subject:L,target:S,identifier:M,active:Y,x:g[0]+x,y:g[1]+F,dx:g[0]-U[0],dy:g[1]-U[1],dispatch:b}),m)}}return S.filter=function(h){return arguments.length?(e=typeof h=="function"?h:br(!!h),S):e},S.container=function(h){return arguments.length?(t=typeof h=="function"?h:br(h),S):t},S.subject=function(h){return arguments.length?(n=typeof h=="function"?h:br(h),S):n},S.touchable=function(h){return arguments.length?(r=typeof h=="function"?h:br(!!h),S):r},S.on=function(){var h=s.on.apply(s,arguments);return h===s?S:h},S.clickDistance=function(h){return arguments.length?(T=(h=+h)*h,S):Math.sqrt(T)},S}function vi(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function Kc(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function nr(){}var Wn=.7,Eo=1/Wn,ln="\\s*([+-]?\\d+)\\s*",jn="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",it="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",xL=/^#([0-9a-f]{3,8})$/,yL=new RegExp(`^rgb\\(${ln},${ln},${ln}\\)$`),DL=new RegExp(`^rgb\\(${it},${it},${it}\\)$`),ML=new RegExp(`^rgba\\(${ln},${ln},${ln},${jn}\\)$`),PL=new RegExp(`^rgba\\(${it},${it},${it},${jn}\\)$`),bL=new RegExp(`^hsl\\(${jn},${it},${it}\\)$`),UL=new RegExp(`^hsla\\(${jn},${it},${it},${jn}\\)$`),Nl={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};vi(nr,Yt,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Ol,formatHex:Ol,formatHex8:vL,formatHsl:BL,formatRgb:fl,toString:fl});function Ol(){return this.rgb().formatHex()}function vL(){return this.rgb().formatHex8()}function BL(){return zc(this).formatHsl()}function fl(){return this.rgb().formatRgb()}function Yt(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=xL.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?pl(t):n===3?new Be(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?Ur(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?Ur(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=yL.exec(e))?new Be(t[1],t[2],t[3],1):(t=DL.exec(e))?new Be(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=ML.exec(e))?Ur(t[1],t[2],t[3],t[4]):(t=PL.exec(e))?Ur(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=bL.exec(e))?Ll(t[1],t[2]/100,t[3]/100,1):(t=UL.exec(e))?Ll(t[1],t[2]/100,t[3]/100,t[4]):Nl.hasOwnProperty(e)?pl(Nl[e]):e==="transparent"?new Be(NaN,NaN,NaN,0):null}function pl(e){return new Be(e>>16&255,e>>8&255,e&255,1)}function Ur(e,t,n,r){return r<=0&&(e=t=n=NaN),new Be(e,t,n,r)}function FL(e){return e instanceof nr||(e=Yt(e)),e?(e=e.rgb(),new Be(e.r,e.g,e.b,e.opacity)):new Be}function Ei(e,t,n,r){return arguments.length===1?FL(e):new Be(e,t,n,r??1)}function Be(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}vi(Be,Ei,Kc(nr,{brighter(e){return e=e==null?Eo:Math.pow(Eo,e),new Be(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Wn:Math.pow(Wn,e),new Be(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Be(Gt(this.r),Gt(this.g),Gt(this.b),co(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:hl,formatHex:hl,formatHex8:GL,formatRgb:Cl,toString:Cl}));function hl(){return`#${Bt(this.r)}${Bt(this.g)}${Bt(this.b)}`}function GL(){return`#${Bt(this.r)}${Bt(this.g)}${Bt(this.b)}${Bt((isNaN(this.opacity)?1:this.opacity)*255)}`}function Cl(){const e=co(this.opacity);return`${e===1?"rgb(":"rgba("}${Gt(this.r)}, ${Gt(this.g)}, ${Gt(this.b)}${e===1?")":`, ${e})`}`}function co(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Gt(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Bt(e){return e=Gt(e),(e<16?"0":"")+e.toString(16)}function Ll(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new ze(e,t,n,r)}function zc(e){if(e instanceof ze)return new ze(e.h,e.s,e.l,e.opacity);if(e instanceof nr||(e=Yt(e)),!e)return new ze;if(e instanceof ze)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,E=(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/=E<.5?s+o:2-s-o,a*=60):l=E>0&&E<1?0:a,new ze(a,l,E,e.opacity)}function wL(e,t,n,r){return arguments.length===1?zc(e):new ze(e,t,n,r??1)}function ze(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}vi(ze,wL,Kc(nr,{brighter(e){return e=e==null?Eo:Math.pow(Eo,e),new ze(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Wn:Math.pow(Wn,e),new ze(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 Be(vs(e>=240?e-240:e+120,o,r),vs(e,o,r),vs(e<120?e+240:e-120,o,r),this.opacity)},clamp(){return new ze(_l(this.h),vr(this.s),vr(this.l),co(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=co(this.opacity);return`${e===1?"hsl(":"hsla("}${_l(this.h)}, ${vr(this.s)*100}%, ${vr(this.l)*100}%${e===1?")":`, ${e})`}`}}));function _l(e){return e=(e||0)%360,e<0?e+360:e}function vr(e){return Math.max(0,Math.min(1,e||0))}function vs(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 Bi=e=>()=>e;function HL(e,t){return function(n){return e+n*t}}function YL(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 kL(e){return(e=+e)==1?Jc:function(t,n){return n-t?YL(t,n,e):Bi(isNaN(t)?n:t)}}function Jc(e,t){var n=t-e;return n?HL(e,n):Bi(isNaN(e)?t:e)}const To=(function e(t){var n=kL(t);function r(o,s){var a=n((o=Ei(o)).r,(s=Ei(s)).r),l=n(o.g,s.g),E=n(o.b,s.b),c=Jc(o.opacity,s.opacity);return function(d){return o.r=a(d),o.g=l(d),o.b=E(d),o.opacity=c(d),o+""}}return r.gamma=e,r})(1);function VL(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 WL(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function jL(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]=Bn(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 $L(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function ot(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function XL(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]=Bn(e[o],t[o]):r[o]=t[o];return function(s){for(o in n)r[o]=n[o](s);return r}}var ci=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Bs=new RegExp(ci.source,"g");function KL(e){return function(){return e}}function zL(e){return function(t){return e(t)+""}}function qc(e,t){var n=ci.lastIndex=Bs.lastIndex=0,r,o,s,a=-1,l=[],E=[];for(e=e+"",t=t+"";(r=ci.exec(e))&&(o=Bs.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,E.push({i:a,x:ot(r,o)})),n=Bs.lastIndex;return n<t.length&&(s=t.slice(n),l[a]?l[a]+=s:l[++a]=s),l.length<2?E[0]?zL(E[0].x):KL(t):(t=E.length,function(c){for(var d=0,T;d<t;++d)l[(T=E[d]).i]=T.x(c);return l.join("")})}function Bn(e,t){var n=typeof t,r;return t==null||n==="boolean"?Bi(t):(n==="number"?ot:n==="string"?(r=Yt(t))?(t=r,To):qc:t instanceof Yt?To:t instanceof Date?$L:WL(t)?VL:Array.isArray(t)?jL:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?XL:ot)(e,t)}var ml=180/Math.PI,Ti={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Qc(e,t,n,r,o,s){var a,l,E;return(a=Math.sqrt(e*e+t*t))&&(e/=a,t/=a),(E=e*n+t*r)&&(n-=e*E,r-=t*E),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,E/=l),e*r<t*n&&(e=-e,t=-t,E=-E,a=-a),{translateX:o,translateY:s,rotate:Math.atan2(t,e)*ml,skewX:Math.atan(E)*ml,scaleX:a,scaleY:l}}var Br;function JL(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Ti:Qc(t.a,t.b,t.c,t.d,t.e,t.f)}function qL(e){return e==null||(Br||(Br=document.createElementNS("http://www.w3.org/2000/svg","g")),Br.setAttribute("transform",e),!(e=Br.transform.baseVal.consolidate()))?Ti:(e=e.matrix,Qc(e.a,e.b,e.c,e.d,e.e,e.f))}function Zc(e,t,n,r){function o(c){return c.length?c.pop()+" ":""}function s(c,d,T,S,u,R){if(c!==T||d!==S){var I=u.push("translate(",null,t,null,n);R.push({i:I-4,x:ot(c,T)},{i:I-2,x:ot(d,S)})}else(T||S)&&u.push("translate("+T+t+S+n)}function a(c,d,T,S){c!==d?(c-d>180?d+=360:d-c>180&&(c+=360),S.push({i:T.push(o(T)+"rotate(",null,r)-2,x:ot(c,d)})):d&&T.push(o(T)+"rotate("+d+r)}function l(c,d,T,S){c!==d?S.push({i:T.push(o(T)+"skewX(",null,r)-2,x:ot(c,d)}):d&&T.push(o(T)+"skewX("+d+r)}function E(c,d,T,S,u,R){if(c!==T||d!==S){var I=u.push(o(u)+"scale(",null,",",null,")");R.push({i:I-4,x:ot(c,T)},{i:I-2,x:ot(d,S)})}else(T!==1||S!==1)&&u.push(o(u)+"scale("+T+","+S+")")}return function(c,d){var T=[],S=[];return c=e(c),d=e(d),s(c.translateX,c.translateY,d.translateX,d.translateY,T,S),a(c.rotate,d.rotate,T,S),l(c.skewX,d.skewX,T,S),E(c.scaleX,c.scaleY,d.scaleX,d.scaleY,T,S),c=d=null,function(u){for(var R=-1,I=S.length,N;++R<I;)T[(N=S[R]).i]=N.x(u);return T.join("")}}}var QL=Zc(JL,"px, ","px)","deg)"),ZL=Zc(qL,", ",")",")"),e_=1e-12;function gl(e){return((e=Math.exp(e))+1/e)/2}function t_(e){return((e=Math.exp(e))-1/e)/2}function n_(e){return((e=Math.exp(2*e))-1)/(e+1)}const Jr=(function e(t,n,r){function o(s,a){var l=s[0],E=s[1],c=s[2],d=a[0],T=a[1],S=a[2],u=d-l,R=T-E,I=u*u+R*R,N,A;if(I<e_)A=Math.log(S/c)/t,N=function(m){return[l+m*u,E+m*R,c*Math.exp(t*m*A)]};else{var p=Math.sqrt(I),O=(S*S-c*c+r*I)/(2*c*n*p),h=(S*S-c*c-r*I)/(2*S*n*p),C=Math.log(Math.sqrt(O*O+1)-O),_=Math.log(Math.sqrt(h*h+1)-h);A=(_-C)/t,N=function(m){var M=m*A,y=gl(C),b=c/(n*p)*(y*n_(t*M+C)-t_(C));return[l+b*u,E+b*R,c*y/gl(t*M+C)]}}return N.duration=A*1e3*t/Math.SQRT2,N}return o.rho=function(s){var a=Math.max(.001,+s),l=a*a,E=l*l;return e(a,l,E)},o})(Math.SQRT2,2,4);var Tn=0,Pn=0,yn=0,eT=1e3,So,bn,uo=0,kt=0,Do=0,$n=typeof performance=="object"&&performance.now?performance:Date,tT=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Fi(){return kt||(tT(r_),kt=$n.now()+Do)}function r_(){kt=0}function Ro(){this._call=this._time=this._next=null}Ro.prototype=nT.prototype={constructor:Ro,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?Fi():+n)+(t==null?0:+t),!this._next&&bn!==this&&(bn?bn._next=this:So=this,bn=this),this._call=e,this._time=n,di()},stop:function(){this._call&&(this._call=null,this._time=1/0,di())}};function nT(e,t,n){var r=new Ro;return r.restart(e,t,n),r}function o_(){Fi(),++Tn;for(var e=So,t;e;)(t=kt-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Tn}function xl(){kt=(uo=$n.now())+Do,Tn=Pn=0;try{o_()}finally{Tn=0,i_(),kt=0}}function s_(){var e=$n.now(),t=e-uo;t>eT&&(Do-=t,uo=e)}function i_(){for(var e,t=So,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:So=n);bn=e,di(r)}function di(e){if(!Tn){Pn&&(Pn=clearTimeout(Pn));var t=e-kt;t>24?(e<1/0&&(Pn=setTimeout(xl,e-$n.now()-Do)),yn&&(yn=clearInterval(yn))):(yn||(uo=$n.now(),yn=setInterval(s_,eT)),Tn=1,tT(xl))}}function yl(e,t,n){var r=new Ro;return t=t==null?0:+t,r.restart(o=>{r.stop(),e(o+t)},t,n),r}var a_=xo("start","end","cancel","interrupt"),l_=[],rT=0,Dl=1,Si=2,qr=3,Ml=4,ui=5,Qr=6;function Mo(e,t,n,r,o,s){var a=e.__transition;if(!a)e.__transition={};else if(n in a)return;E_(e,n,{name:t,index:r,group:o,on:a_,tween:l_,time:s.time,delay:s.delay,duration:s.duration,ease:s.ease,timer:null,state:rT})}function Gi(e,t){var n=et(e,t);if(n.state>rT)throw new Error("too late; already scheduled");return n}function lt(e,t){var n=et(e,t);if(n.state>qr)throw new Error("too late; already running");return n}function et(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function E_(e,t,n){var r=e.__transition,o;r[t]=n,n.timer=nT(s,0,n.time);function s(c){n.state=Dl,n.timer.restart(a,n.delay,n.time),n.delay<=c&&a(c-n.delay)}function a(c){var d,T,S,u;if(n.state!==Dl)return E();for(d in r)if(u=r[d],u.name===n.name){if(u.state===qr)return yl(a);u.state===Ml?(u.state=Qr,u.timer.stop(),u.on.call("interrupt",e,e.__data__,u.index,u.group),delete r[d]):+d<t&&(u.state=Qr,u.timer.stop(),u.on.call("cancel",e,e.__data__,u.index,u.group),delete r[d])}if(yl(function(){n.state===qr&&(n.state=Ml,n.timer.restart(l,n.delay,n.time),l(c))}),n.state=Si,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Si){for(n.state=qr,o=new Array(S=n.tween.length),d=0,T=-1;d<S;++d)(u=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(o[++T]=u);o.length=T+1}}function l(c){for(var d=c<n.duration?n.ease.call(null,c/n.duration):(n.timer.restart(E),n.state=ui,1),T=-1,S=o.length;++T<S;)o[T].call(e,d);n.state===ui&&(n.on.call("end",e,e.__data__,n.index,n.group),E())}function E(){n.state=Qr,n.timer.stop(),delete r[t];for(var c in r)return;delete e.__transition}}function Zr(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>Si&&r.state<ui,r.state=Qr,r.timer.stop(),r.on.call(o?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[a]}s&&delete e.__transition}}function c_(e){return this.each(function(){Zr(this,e)})}function T_(e,t){var n,r;return function(){var o=lt(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 d_(e,t,n){var r,o;if(typeof n!="function")throw new Error;return function(){var s=lt(this,e),a=s.tween;if(a!==r){o=(r=a).slice();for(var l={name:t,value:n},E=0,c=o.length;E<c;++E)if(o[E].name===t){o[E]=l;break}E===c&&o.push(l)}s.tween=o}}function S_(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=et(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?T_:d_)(n,e,t))}function wi(e,t,n){var r=e._id;return e.each(function(){var o=lt(this,r);(o.value||(o.value={}))[t]=n.apply(this,arguments)}),function(o){return et(o,r).value[t]}}function oT(e,t){var n;return(typeof t=="number"?ot:t instanceof Yt?To:(n=Yt(t))?(t=n,To):qc)(e,t)}function u_(e){return function(){this.removeAttribute(e)}}function R_(e){return function(){this.removeAttributeNS(e.space,e.local)}}function A_(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 I_(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 N_(e,t,n){var r,o,s;return function(){var a,l=n(this),E;return l==null?void this.removeAttribute(e):(a=this.getAttribute(e),E=l+"",a===E?null:a===r&&E===o?s:(o=E,s=t(r=a,l)))}}function O_(e,t,n){var r,o,s;return function(){var a,l=n(this),E;return l==null?void this.removeAttributeNS(e.space,e.local):(a=this.getAttributeNS(e.space,e.local),E=l+"",a===E?null:a===r&&E===o?s:(o=E,s=t(r=a,l)))}}function f_(e,t){var n=yo(e),r=n==="transform"?ZL:oT;return this.attrTween(e,typeof t=="function"?(n.local?O_:N_)(n,r,wi(this,"attr."+e,t)):t==null?(n.local?R_:u_)(n):(n.local?I_:A_)(n,r,t))}function p_(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function h_(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function C_(e,t){var n,r;function o(){var s=t.apply(this,arguments);return s!==r&&(n=(r=s)&&h_(e,s)),n}return o._value=t,o}function L_(e,t){var n,r;function o(){var s=t.apply(this,arguments);return s!==r&&(n=(r=s)&&p_(e,s)),n}return o._value=t,o}function __(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=yo(e);return this.tween(n,(r.local?C_:L_)(r,t))}function m_(e,t){return function(){Gi(this,e).delay=+t.apply(this,arguments)}}function g_(e,t){return t=+t,function(){Gi(this,e).delay=t}}function x_(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?m_:g_)(t,e)):et(this.node(),t).delay}function y_(e,t){return function(){lt(this,e).duration=+t.apply(this,arguments)}}function D_(e,t){return t=+t,function(){lt(this,e).duration=t}}function M_(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?y_:D_)(t,e)):et(this.node(),t).duration}function P_(e,t){if(typeof t!="function")throw new Error;return function(){lt(this,e).ease=t}}function b_(e){var t=this._id;return arguments.length?this.each(P_(t,e)):et(this.node(),t).ease}function U_(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;lt(this,e).ease=n}}function v_(e){if(typeof e!="function")throw new Error;return this.each(U_(this._id,e))}function B_(e){typeof e!="function"&&(e=vc(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]=[],E,c=0;c<a;++c)(E=s[c])&&e.call(E,E.__data__,c,s)&&l.push(E);return new It(r,this._parents,this._name,this._id)}function F_(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 E=t[l],c=n[l],d=E.length,T=a[l]=new Array(d),S,u=0;u<d;++u)(S=E[u]||c[u])&&(T[u]=S);for(;l<r;++l)a[l]=t[l];return new It(a,this._parents,this._name,this._id)}function G_(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 w_(e,t,n){var r,o,s=G_(t)?Gi:lt;return function(){var a=s(this,e),l=a.on;l!==r&&(o=(r=l).copy()).on(t,n),a.on=o}}function H_(e,t){var n=this._id;return arguments.length<2?et(this.node(),n).on.on(e):this.each(w_(n,e,t))}function Y_(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function k_(){return this.on("end.remove",Y_(this._id))}function V_(e){var t=this._name,n=this._id;typeof e!="function"&&(e=bi(e));for(var r=this._groups,o=r.length,s=new Array(o),a=0;a<o;++a)for(var l=r[a],E=l.length,c=s[a]=new Array(E),d,T,S=0;S<E;++S)(d=l[S])&&(T=e.call(d,d.__data__,S,l))&&("__data__"in d&&(T.__data__=d.__data__),c[S]=T,Mo(c[S],t,n,S,c,et(d,n)));return new It(s,this._parents,t,n)}function W_(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Uc(e));for(var r=this._groups,o=r.length,s=[],a=[],l=0;l<o;++l)for(var E=r[l],c=E.length,d,T=0;T<c;++T)if(d=E[T]){for(var S=e.call(d,d.__data__,T,E),u,R=et(d,n),I=0,N=S.length;I<N;++I)(u=S[I])&&Mo(u,t,n,I,S,R);s.push(S),a.push(d)}return new It(s,a,t,n)}var j_=tr.prototype.constructor;function $_(){return new j_(this._groups,this._parents)}function X_(e,t){var n,r,o;return function(){var s=cn(this,e),a=(this.style.removeProperty(e),cn(this,e));return s===a?null:s===n&&a===r?o:o=t(n=s,r=a)}}function sT(e){return function(){this.style.removeProperty(e)}}function K_(e,t,n){var r,o=n+"",s;return function(){var a=cn(this,e);return a===o?null:a===r?s:s=t(r=a,n)}}function z_(e,t,n){var r,o,s;return function(){var a=cn(this,e),l=n(this),E=l+"";return l==null&&(E=l=(this.style.removeProperty(e),cn(this,e))),a===E?null:a===r&&E===o?s:(o=E,s=t(r=a,l))}}function J_(e,t){var n,r,o,s="style."+t,a="end."+s,l;return function(){var E=lt(this,e),c=E.on,d=E.value[s]==null?l||(l=sT(t)):void 0;(c!==n||o!==d)&&(r=(n=c).copy()).on(a,o=d),E.on=r}}function q_(e,t,n){var r=(e+="")=="transform"?QL:oT;return t==null?this.styleTween(e,X_(e,r)).on("end.style."+e,sT(e)):typeof t=="function"?this.styleTween(e,z_(e,r,wi(this,"style."+e,t))).each(J_(this._id,e)):this.styleTween(e,K_(e,r,t),n).on("end.style."+e,null)}function Q_(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function Z_(e,t,n){var r,o;function s(){var a=t.apply(this,arguments);return a!==o&&(r=(o=a)&&Q_(e,a,n)),r}return s._value=t,s}function em(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,Z_(e,t,n??""))}function tm(e){return function(){this.textContent=e}}function nm(e){return function(){var t=e(this);this.textContent=t??""}}function rm(e){return this.tween("text",typeof e=="function"?nm(wi(this,"text",e)):tm(e==null?"":e+""))}function om(e){return function(t){this.textContent=e.call(this,t)}}function sm(e){var t,n;function r(){var o=e.apply(this,arguments);return o!==n&&(t=(n=o)&&om(o)),t}return r._value=e,r}function im(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,sm(e))}function am(){for(var e=this._name,t=this._id,n=iT(),r=this._groups,o=r.length,s=0;s<o;++s)for(var a=r[s],l=a.length,E,c=0;c<l;++c)if(E=a[c]){var d=et(E,t);Mo(E,e,n,c,a,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new It(r,this._parents,e,n)}function lm(){var e,t,n=this,r=n._id,o=n.size();return new Promise(function(s,a){var l={value:a},E={value:function(){--o===0&&s()}};n.each(function(){var c=lt(this,r),d=c.on;d!==e&&(t=(e=d).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(E)),c.on=t}),o===0&&s()})}var Em=0;function It(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function iT(){return++Em}var St=tr.prototype;It.prototype={constructor:It,select:V_,selectAll:W_,selectChild:St.selectChild,selectChildren:St.selectChildren,filter:B_,merge:F_,selection:$_,transition:am,call:St.call,nodes:St.nodes,node:St.node,size:St.size,empty:St.empty,each:St.each,on:H_,attr:f_,attrTween:__,style:q_,styleTween:em,text:rm,textTween:im,remove:k_,tween:S_,delay:x_,duration:M_,ease:b_,easeVarying:v_,end:lm,[Symbol.iterator]:St[Symbol.iterator]};function cm(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var Tm={time:null,delay:0,duration:250,ease:cm};function dm(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 Sm(e){var t,n;e instanceof It?(t=e._id,e=e._name):(t=iT(),(n=Tm).time=Fi(),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,E,c=0;c<l;++c)(E=a[c])&&Mo(E,e,t,c,a,n||dm(E,t));return new It(r,this._parents,e,t)}tr.prototype.interrupt=c_;tr.prototype.transition=Sm;const Fr=e=>()=>e;function um(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 At(e,t,n){this.k=e,this.x=t,this.y=n}At.prototype={constructor:At,scale:function(e){return e===1?this:new At(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new At(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 Po=new At(1,0,0);aT.prototype=At.prototype;function aT(e){for(;!e.__zoom;)if(!(e=e.parentNode))return Po;return e.__zoom}function Fs(e){e.stopImmediatePropagation()}function Dn(e){e.preventDefault(),e.stopImmediatePropagation()}function Rm(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function Am(){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 Pl(){return this.__zoom||Po}function Im(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function Nm(){return navigator.maxTouchPoints||"ontouchstart"in this}function Om(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 lT(){var e=Rm,t=Am,n=Om,r=Im,o=Nm,s=[0,1/0],a=[[-1/0,-1/0],[1/0,1/0]],l=250,E=Jr,c=xo("start","zoom","end"),d,T,S,u=500,R=150,I=0,N=10;function A(L){L.property("__zoom",Pl).on("wheel.zoom",M,{passive:!1}).on("mousedown.zoom",y).on("dblclick.zoom",b).filter(o).on("touchstart.zoom",g).on("touchmove.zoom",x).on("touchend.zoom touchcancel.zoom",F).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}A.transform=function(L,P,D,B){var v=L.selection?L.selection():L;v.property("__zoom",Pl),L!==v?C(L,P,D,B):v.interrupt().each(function(){_(this,arguments).event(B).start().zoom(null,typeof P=="function"?P.apply(this,arguments):P).end()})},A.scaleBy=function(L,P,D,B){A.scaleTo(L,function(){var v=this.__zoom.k,U=typeof P=="function"?P.apply(this,arguments):P;return v*U},D,B)},A.scaleTo=function(L,P,D,B){A.transform(L,function(){var v=t.apply(this,arguments),U=this.__zoom,Y=D==null?h(v):typeof D=="function"?D.apply(this,arguments):D,W=U.invert(Y),k=typeof P=="function"?P.apply(this,arguments):P;return n(O(p(U,k),Y,W),v,a)},D,B)},A.translateBy=function(L,P,D,B){A.transform(L,function(){return n(this.__zoom.translate(typeof P=="function"?P.apply(this,arguments):P,typeof D=="function"?D.apply(this,arguments):D),t.apply(this,arguments),a)},null,B)},A.translateTo=function(L,P,D,B,v){A.transform(L,function(){var U=t.apply(this,arguments),Y=this.__zoom,W=B==null?h(U):typeof B=="function"?B.apply(this,arguments):B;return n(Po.translate(W[0],W[1]).scale(Y.k).translate(typeof P=="function"?-P.apply(this,arguments):-P,typeof D=="function"?-D.apply(this,arguments):-D),U,a)},B,v)};function p(L,P){return P=Math.max(s[0],Math.min(s[1],P)),P===L.k?L:new At(P,L.x,L.y)}function O(L,P,D){var B=P[0]-D[0]*L.k,v=P[1]-D[1]*L.k;return B===L.x&&v===L.y?L:new At(L.k,B,v)}function h(L){return[(+L[0][0]+ +L[1][0])/2,(+L[0][1]+ +L[1][1])/2]}function C(L,P,D,B){L.on("start.zoom",function(){_(this,arguments).event(B).start()}).on("interrupt.zoom end.zoom",function(){_(this,arguments).event(B).end()}).tween("zoom",function(){var v=this,U=arguments,Y=_(v,U).event(B),W=t.apply(v,U),k=D==null?h(W):typeof D=="function"?D.apply(v,U):D,w=Math.max(W[1][0]-W[0][0],W[1][1]-W[0][1]),z=v.__zoom,q=typeof P=="function"?P.apply(v,U):P,Z=E(z.invert(k).concat(w/z.k),q.invert(k).concat(w/q.k));return function(K){if(K===1)K=q;else{var H=Z(K),J=w/H[2];K=new At(J,k[0]-H[0]*J,k[1]-H[1]*J)}Y.zoom(null,K)}})}function _(L,P,D){return!D&&L.__zooming||new m(L,P)}function m(L,P){this.that=L,this.args=P,this.active=0,this.sourceEvent=null,this.extent=t.apply(L,P),this.taps=0}m.prototype={event:function(L){return L&&(this.sourceEvent=L),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(L,P){return this.mouse&&L!=="mouse"&&(this.mouse[1]=P.invert(this.mouse[0])),this.touch0&&L!=="touch"&&(this.touch0[1]=P.invert(this.touch0[0])),this.touch1&&L!=="touch"&&(this.touch1[1]=P.invert(this.touch1[0])),this.that.__zoom=P,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(L){var P=Ye(this.that).datum();c.call(L,this.that,new um(L,{sourceEvent:this.sourceEvent,target:A,transform:this.that.__zoom,dispatch:c}),P)}};function M(L,...P){if(!e.apply(this,arguments))return;var D=_(this,P).event(L),B=this.__zoom,v=Math.max(s[0],Math.min(s[1],B.k*Math.pow(2,r.apply(this,arguments)))),U=Ke(L);if(D.wheel)(D.mouse[0][0]!==U[0]||D.mouse[0][1]!==U[1])&&(D.mouse[1]=B.invert(D.mouse[0]=U)),clearTimeout(D.wheel);else{if(B.k===v)return;D.mouse=[U,B.invert(U)],Zr(this),D.start()}Dn(L),D.wheel=setTimeout(Y,R),D.zoom("mouse",n(O(p(B,v),D.mouse[0],D.mouse[1]),D.extent,a));function Y(){D.wheel=null,D.end()}}function y(L,...P){if(S||!e.apply(this,arguments))return;var D=L.currentTarget,B=_(this,P,!0).event(L),v=Ye(L.view).on("mousemove.zoom",k,!0).on("mouseup.zoom",w,!0),U=Ke(L,D),Y=L.clientX,W=L.clientY;jc(L.view),Fs(L),B.mouse=[U,this.__zoom.invert(U)],Zr(this),B.start();function k(z){if(Dn(z),!B.moved){var q=z.clientX-Y,Z=z.clientY-W;B.moved=q*q+Z*Z>I}B.event(z).zoom("mouse",n(O(B.that.__zoom,B.mouse[0]=Ke(z,D),B.mouse[1]),B.extent,a))}function w(z){v.on("mousemove.zoom mouseup.zoom",null),$c(z.view,B.moved),Dn(z),B.event(z).end()}}function b(L,...P){if(e.apply(this,arguments)){var D=this.__zoom,B=Ke(L.changedTouches?L.changedTouches[0]:L,this),v=D.invert(B),U=D.k*(L.shiftKey?.5:2),Y=n(O(p(D,U),B,v),t.apply(this,P),a);Dn(L),l>0?Ye(this).transition().duration(l).call(C,Y,B,L):Ye(this).call(A.transform,Y,B,L)}}function g(L,...P){if(e.apply(this,arguments)){var D=L.touches,B=D.length,v=_(this,P,L.changedTouches.length===B).event(L),U,Y,W,k;for(Fs(L),Y=0;Y<B;++Y)W=D[Y],k=Ke(W,this),k=[k,this.__zoom.invert(k),W.identifier],v.touch0?!v.touch1&&v.touch0[2]!==k[2]&&(v.touch1=k,v.taps=0):(v.touch0=k,U=!0,v.taps=1+!!d);d&&(d=clearTimeout(d)),U&&(v.taps<2&&(T=k[0],d=setTimeout(function(){d=null},u)),Zr(this),v.start())}}function x(L,...P){if(this.__zooming){var D=_(this,P).event(L),B=L.changedTouches,v=B.length,U,Y,W,k;for(Dn(L),U=0;U<v;++U)Y=B[U],W=Ke(Y,this),D.touch0&&D.touch0[2]===Y.identifier?D.touch0[0]=W:D.touch1&&D.touch1[2]===Y.identifier&&(D.touch1[0]=W);if(Y=D.that.__zoom,D.touch1){var w=D.touch0[0],z=D.touch0[1],q=D.touch1[0],Z=D.touch1[1],K=(K=q[0]-w[0])*K+(K=q[1]-w[1])*K,H=(H=Z[0]-z[0])*H+(H=Z[1]-z[1])*H;Y=p(Y,Math.sqrt(K/H)),W=[(w[0]+q[0])/2,(w[1]+q[1])/2],k=[(z[0]+Z[0])/2,(z[1]+Z[1])/2]}else if(D.touch0)W=D.touch0[0],k=D.touch0[1];else return;D.zoom("touch",n(O(Y,W,k),D.extent,a))}}function F(L,...P){if(this.__zooming){var D=_(this,P).event(L),B=L.changedTouches,v=B.length,U,Y;for(Fs(L),S&&clearTimeout(S),S=setTimeout(function(){S=null},u),U=0;U<v;++U)Y=B[U],D.touch0&&D.touch0[2]===Y.identifier?delete D.touch0:D.touch1&&D.touch1[2]===Y.identifier&&delete D.touch1;if(D.touch1&&!D.touch0&&(D.touch0=D.touch1,delete D.touch1),D.touch0)D.touch0[1]=this.__zoom.invert(D.touch0[0]);else if(D.end(),D.taps===2&&(Y=Ke(Y,this),Math.hypot(T[0]-Y[0],T[1]-Y[1])<N)){var W=Ye(this).on("dblclick.zoom");W&&W.apply(this,arguments)}}}return A.wheelDelta=function(L){return arguments.length?(r=typeof L=="function"?L:Fr(+L),A):r},A.filter=function(L){return arguments.length?(e=typeof L=="function"?L:Fr(!!L),A):e},A.touchable=function(L){return arguments.length?(o=typeof L=="function"?L:Fr(!!L),A):o},A.extent=function(L){return arguments.length?(t=typeof L=="function"?L:Fr([[+L[0][0],+L[0][1]],[+L[1][0],+L[1][1]]]),A):t},A.scaleExtent=function(L){return arguments.length?(s[0]=+L[0],s[1]=+L[1],A):[s[0],s[1]]},A.translateExtent=function(L){return arguments.length?(a[0][0]=+L[0][0],a[1][0]=+L[1][0],a[0][1]=+L[0][1],a[1][1]=+L[1][1],A):[[a[0][0],a[0][1]],[a[1][0],a[1][1]]]},A.constrain=function(L){return arguments.length?(n=L,A):n},A.duration=function(L){return arguments.length?(l=+L,A):l},A.interpolate=function(L){return arguments.length?(E=L,A):E},A.on=function(){var L=c.on.apply(c,arguments);return L===c?A:L},A.clickDistance=function(L){return arguments.length?(I=(L=+L)*L,A):Math.sqrt(I)},A.tapDistance=function(L){return arguments.length?(N=+L,A):N},A}const at={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."},Xn=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],ET=["Enter"," ","Escape"],cT={"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 dn;(function(e){e.Strict="strict",e.Loose="loose"})(dn||(dn={}));var wt;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(wt||(wt={}));var Kn;(function(e){e.Partial="partial",e.Full="full"})(Kn||(Kn={}));const TT={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var Lt;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(Lt||(Lt={}));var zn;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(zn||(zn={}));var se;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(se||(se={}));const bl={[se.Left]:se.Right,[se.Right]:se.Left,[se.Top]:se.Bottom,[se.Bottom]:se.Top};function dT(e){return e===null?null:e?"valid":"invalid"}const ST=e=>"id"in e&&"source"in e&&"target"in e,fm=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),Hi=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),rr=(e,t=[0,0])=>{const{width:n,height:r}=Nt(e),o=e.origin??t,s=n*o[0],a=r*o[1];return{x:e.position.x-s,y:e.position.y-a}},pm=(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):Hi(o)?o:t.nodeLookup.get(o.id));const l=a?Ao(a,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return bo(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return Uo(n)},or=(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=bo(n,Ao(o)),r=!0)}),r?Uo(n):{x:0,y:0,width:0,height:0}},Yi=(e,t,[n,r,o]=[0,0,1],s=!1,a=!1)=>{const l={...ir(t,[n,r,o]),width:t.width/o,height:t.height/o},E=[];for(const c of e.values()){const{measured:d,selectable:T=!0,hidden:S=!1}=c;if(a&&!T||S)continue;const u=d.width??c.width??c.initialWidth??null,R=d.height??c.height??c.initialHeight??null,I=Jn(l,un(c)),N=(u??0)*(R??0),A=s&&I>0;(!c.internals.handleBounds||A||I>=N||c.dragging)&&E.push(c)}return E},hm=(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 Cm(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 Lm({nodes:e,width:t,height:n,panZoom:r,minZoom:o,maxZoom:s},a){if(e.size===0)return Promise.resolve(!0);const l=Cm(e,a),E=or(l),c=ki(E,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(c,{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 uT({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:E,y:c}=l?l.internals.positionAbsolute:{x:0,y:0},d=a.origin??r;let T=a.extent||o;if(a.extent==="parent"&&!a.expandParent)if(!l)s==null||s("005",at.error005());else{const u=l.measured.width,R=l.measured.height;u&&R&&(T=[[E,c],[E+u,c+R]])}else l&&Rn(a.extent)&&(T=[[a.extent[0][0]+E,a.extent[0][1]+c],[a.extent[1][0]+E,a.extent[1][1]+c]]);const S=Rn(T)?Vt(t,T,a.measured):t;return(a.measured.width===void 0||a.measured.height===void 0)&&(s==null||s("015",at.error015())),{position:{x:S.x-E+(a.measured.width??0)*d[0],y:S.y-c+(a.measured.height??0)*d[1]},positionAbsolute:S}}async function _m({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:o}){const s=new Set(e.map(S=>S.id)),a=[];for(const S of n){if(S.deletable===!1)continue;const u=s.has(S.id),R=!u&&S.parentId&&a.find(I=>I.id===S.parentId);(u||R)&&a.push(S)}const l=new Set(t.map(S=>S.id)),E=r.filter(S=>S.deletable!==!1),d=hm(a,E);for(const S of E)l.has(S.id)&&!d.find(R=>R.id===S.id)&&d.push(S);if(!o)return{edges:d,nodes:a};const T=await o({nodes:a,edges:d});return typeof T=="boolean"?T?{edges:d,nodes:a}:{edges:[],nodes:[]}:T}const Sn=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Vt=(e={x:0,y:0},t,n)=>({x:Sn(e.x,t[0][0],t[1][0]-((n==null?void 0:n.width)??0)),y:Sn(e.y,t[0][1],t[1][1]-((n==null?void 0:n.height)??0))});function RT(e,t,n){const{width:r,height:o}=Nt(n),{x:s,y:a}=n.internals.positionAbsolute;return Vt(e,[[s,a],[s+r,a+o]],t)}const Ul=(e,t,n)=>e<t?Sn(Math.abs(e-t),1,t)/t:e>n?-Sn(Math.abs(e-n),1,t)/t:0,AT=(e,t,n=15,r=40)=>{const o=Ul(e.x,r,t.width-r)*n,s=Ul(e.y,r,t.height-r)*n;return[o,s]},bo=(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)}),Ri=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),Uo=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),un=(e,t=[0,0])=>{var o,s;const{x:n,y:r}=Hi(e)?e.internals.positionAbsolute:rr(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}},Ao=(e,t=[0,0])=>{var o,s;const{x:n,y:r}=Hi(e)?e.internals.positionAbsolute:rr(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)}},IT=(e,t)=>Uo(bo(Ri(e),Ri(t))),Jn=(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)},vl=e=>Je(e.width)&&Je(e.height)&&Je(e.x)&&Je(e.y),Je=e=>!isNaN(e)&&isFinite(e),mm=(e,t)=>{},sr=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),ir=({x:e,y:t},[n,r,o],s=!1,a=[1,1])=>{const l={x:(e-n)/o,y:(t-r)/o};return s?sr(l,a):l},Io=({x:e,y:t},[n,r,o])=>({x:e*o+n,y:t*o+r});function Zt(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 gm(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=Zt(e,n),o=Zt(e,t);return{top:r,right:o,bottom:r,left:o,x:o*2,y:r*2}}if(typeof e=="object"){const r=Zt(e.top??e.y??0,n),o=Zt(e.bottom??e.y??0,n),s=Zt(e.left??e.x??0,t),a=Zt(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 xm(e,t,n,r,o,s){const{x:a,y:l}=Io(e,[t,n,r]),{x:E,y:c}=Io({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=o-E,T=s-c;return{left:Math.floor(a),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(T)}}const ki=(e,t,n,r,o,s)=>{const a=gm(s,t,n),l=(t-a.x)/e.width,E=(n-a.y)/e.height,c=Math.min(l,E),d=Sn(c,r,o),T=e.x+e.width/2,S=e.y+e.height/2,u=t/2-T*d,R=n/2-S*d,I=xm(e,u,R,d,t,n),N={left:Math.min(I.left-a.left,0),top:Math.min(I.top-a.top,0),right:Math.min(I.right-a.right,0),bottom:Math.min(I.bottom-a.bottom,0)};return{x:u-N.left+N.right,y:R-N.top+N.bottom,zoom:d}},qn=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0};function Rn(e){return e!=null&&e!=="parent"}function Nt(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 NT(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 OT(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 Bl(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function ym(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}function Dm(e){return{...cT,...e||{}}}function Fn(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:o}){const{x:s,y:a}=qe(e),l=ir({x:s-((o==null?void 0:o.left)??0),y:a-((o==null?void 0:o.top)??0)},r),{x:E,y:c}=n?sr(l,t):l;return{xSnapped:E,ySnapped:c,...l}}const Vi=e=>({width:e.offsetWidth,height:e.offsetHeight}),fT=e=>{var t;return((t=e==null?void 0:e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},Mm=["INPUT","SELECT","TEXTAREA"];function pT(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:Mm.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const hT=e=>"clientX"in e,qe=(e,t)=>{var s,a;const n=hT(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)}},Fl=(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,...Vi(a)}})};function CT({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:o,sourceControlY:s,targetControlX:a,targetControlY:l}){const E=e*.125+o*.375+a*.375+n*.125,c=t*.125+s*.375+l*.375+r*.125,d=Math.abs(E-e),T=Math.abs(c-t);return[E,c,d,T]}function Gr(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Gl({pos:e,x1:t,y1:n,x2:r,y2:o,c:s}){switch(e){case se.Left:return[t-Gr(t-r,s),n];case se.Right:return[t+Gr(r-t,s),n];case se.Top:return[t,n-Gr(n-o,s)];case se.Bottom:return[t,n+Gr(o-n,s)]}}function LT({sourceX:e,sourceY:t,sourcePosition:n=se.Bottom,targetX:r,targetY:o,targetPosition:s=se.Top,curvature:a=.25}){const[l,E]=Gl({pos:n,x1:e,y1:t,x2:r,y2:o,c:a}),[c,d]=Gl({pos:s,x1:r,y1:o,x2:e,y2:t,c:a}),[T,S,u,R]=CT({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:l,sourceControlY:E,targetControlX:c,targetControlY:d});return[`M${e},${t} C${l},${E} ${c},${d} ${r},${o}`,T,S,u,R]}function _T({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 Pm({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 bm({sourceNode:e,targetNode:t,width:n,height:r,transform:o}){const s=bo(Ao(e),Ao(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 Jn(a,Uo(s))>0}const Um=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,vm=(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)),Bm=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||Um;let o;return ST(e)?o={...e}:o={...e,id:r(e)},vm(o,t)?t:(o.sourceHandle===null&&delete o.sourceHandle,o.targetHandle===null&&delete o.targetHandle,t.concat(o))};function mT({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[o,s,a,l]=_T({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,o,s,a,l]}const wl={[se.Left]:{x:-1,y:0},[se.Right]:{x:1,y:0},[se.Top]:{x:0,y:-1},[se.Bottom]:{x:0,y:1}},Fm=({source:e,sourcePosition:t=se.Bottom,target:n})=>t===se.Left||t===se.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},Hl=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function Gm({source:e,sourcePosition:t=se.Bottom,target:n,targetPosition:r=se.Top,center:o,offset:s,stepPosition:a}){const l=wl[t],E=wl[r],c={x:e.x+l.x*s,y:e.y+l.y*s},d={x:n.x+E.x*s,y:n.y+E.y*s},T=Fm({source:c,sourcePosition:t,target:d}),S=T.x!==0?"x":"y",u=T[S];let R=[],I,N;const A={x:0,y:0},p={x:0,y:0},[,,O,h]=_T({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[S]*E[S]===-1){S==="x"?(I=o.x??c.x+(d.x-c.x)*a,N=o.y??(c.y+d.y)/2):(I=o.x??(c.x+d.x)/2,N=o.y??c.y+(d.y-c.y)*a);const _=[{x:I,y:c.y},{x:I,y:d.y}],m=[{x:c.x,y:N},{x:d.x,y:N}];l[S]===u?R=S==="x"?_:m:R=S==="x"?m:_}else{const _=[{x:c.x,y:d.y}],m=[{x:d.x,y:c.y}];if(S==="x"?R=l.x===u?m:_:R=l.y===u?_:m,t===r){const x=Math.abs(e[S]-n[S]);if(x<=s){const F=Math.min(s-1,s-x);l[S]===u?A[S]=(c[S]>e[S]?-1:1)*F:p[S]=(d[S]>n[S]?-1:1)*F}}if(t!==r){const x=S==="x"?"y":"x",F=l[S]===E[x],L=c[x]>d[x],P=c[x]<d[x];(l[S]===1&&(!F&&L||F&&P)||l[S]!==1&&(!F&&P||F&&L))&&(R=S==="x"?_:m)}const M={x:c.x+A.x,y:c.y+A.y},y={x:d.x+p.x,y:d.y+p.y},b=Math.max(Math.abs(M.x-R[0].x),Math.abs(y.x-R[0].x)),g=Math.max(Math.abs(M.y-R[0].y),Math.abs(y.y-R[0].y));b>=g?(I=(M.x+y.x)/2,N=R[0].y):(I=R[0].x,N=(M.y+y.y)/2)}return[[e,{x:c.x+A.x,y:c.y+A.y},...R,{x:d.x+p.x,y:d.y+p.y},n],I,N,O,h]}function wm(e,t,n,r){const o=Math.min(Hl(e,t)/2,Hl(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 c=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${s+o*c},${a}Q ${s},${a} ${s},${a+o*d}`}const l=e.x<n.x?1:-1,E=e.y<n.y?-1:1;return`L ${s},${a+o*E}Q ${s},${a} ${s+o*l},${a}`}function Ai({sourceX:e,sourceY:t,sourcePosition:n=se.Bottom,targetX:r,targetY:o,targetPosition:s=se.Top,borderRadius:a=5,centerX:l,centerY:E,offset:c=20,stepPosition:d=.5}){const[T,S,u,R,I]=Gm({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:o},targetPosition:s,center:{x:l,y:E},offset:c,stepPosition:d});return[T.reduce((A,p,O)=>{let h="";return O>0&&O<T.length-1?h=wm(T[O-1],p,T[O+1],a):h=`${O===0?"M":"L"}${p.x} ${p.y}`,A+=h,A},""),S,u,R,I]}function Yl(e){var t;return e&&!!(e.internals.handleBounds||(t=e.handles)!=null&&t.length)&&!!(e.measured.width||e.width||e.initialWidth)}function Hm(e){var T;const{sourceNode:t,targetNode:n}=e;if(!Yl(t)||!Yl(n))return null;const r=t.internals.handleBounds||kl(t.handles),o=n.internals.handleBounds||kl(n.handles),s=Vl((r==null?void 0:r.source)??[],e.sourceHandle),a=Vl(e.connectionMode===dn.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(T=e.onError)==null||T.call(e,"008",at.error008(s?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=(s==null?void 0:s.position)||se.Bottom,E=(a==null?void 0:a.position)||se.Top,c=Wt(t,s,l),d=Wt(n,a,E);return{sourceX:c.x,sourceY:c.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:E}}function kl(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 Wt(e,t,n=se.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??Nt(e);if(r)return{x:o+a/2,y:s+l/2};switch((t==null?void 0:t.position)??n){case se.Top:return{x:o+a/2,y:s};case se.Right:return{x:o+a,y:s+l/2};case se.Bottom:return{x:o+a/2,y:s+l};case se.Left:return{x:o,y:s+l/2}}}function Vl(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Ii(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function Ym(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(E=>{if(E&&typeof E=="object"){const c=Ii(E,t);s.has(c)||(a.push({id:c,color:E.color||n,...E}),s.add(c))}}),a),[]).sort((a,l)=>a.id.localeCompare(l.id))}const gT=1e3,km=10,Wi={nodeOrigin:[0,0],nodeExtent:Xn,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},Vm={...Wi,checkEquality:!0};function ji(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function Wm(e,t,n){const r=ji(Wi,n);for(const o of e.values())if(o.parentId)Xi(o,e,t,r);else{const s=rr(o,r.nodeOrigin),a=Rn(o.extent)?o.extent:r.nodeExtent,l=Vt(s,a,Nt(o));o.internals.positionAbsolute=l}}function jm(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 $i(e){return e==="manual"}function Ni(e,t,n,r={}){var c,d;const o=ji(Vm,r),s={i:0},a=new Map(t),l=o!=null&&o.elevateNodesOnSelect&&!$i(o.zIndexMode)?gT:0;let E=e.length>0;t.clear(),n.clear();for(const T of e){let S=a.get(T.id);if(o.checkEquality&&T===(S==null?void 0:S.internals.userNode))t.set(T.id,S);else{const u=rr(T,o.nodeOrigin),R=Rn(T.extent)?T.extent:o.nodeExtent,I=Vt(u,R,Nt(T));S={...o.defaults,...T,measured:{width:(c=T.measured)==null?void 0:c.width,height:(d=T.measured)==null?void 0:d.height},internals:{positionAbsolute:I,handleBounds:jm(T,S),z:xT(T,l,o.zIndexMode),userNode:T}},t.set(T.id,S)}(S.measured===void 0||S.measured.width===void 0||S.measured.height===void 0)&&!S.hidden&&(E=!1),T.parentId&&Xi(S,t,n,r,s)}return E}function $m(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 Xi(e,t,n,r,o){const{elevateNodesOnSelect:s,nodeOrigin:a,nodeExtent:l,zIndexMode:E}=ji(Wi,r),c=e.parentId,d=t.get(c);if(!d){console.warn(`Parent node ${c} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}$m(e,n),o&&!d.parentId&&d.internals.rootParentIndex===void 0&&E==="auto"&&(d.internals.rootParentIndex=++o.i,d.internals.z=d.internals.z+o.i*km),o&&d.internals.rootParentIndex!==void 0&&(o.i=d.internals.rootParentIndex);const T=s&&!$i(E)?gT:0,{x:S,y:u,z:R}=Xm(e,d,a,l,T,E),{positionAbsolute:I}=e.internals,N=S!==I.x||u!==I.y;(N||R!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:N?{x:S,y:u}:I,z:R}})}function xT(e,t,n){const r=Je(e.zIndex)?e.zIndex:0;return $i(n)?r:r+(e.selected?t:0)}function Xm(e,t,n,r,o,s){const{x:a,y:l}=t.internals.positionAbsolute,E=Nt(e),c=rr(e,n),d=Rn(e.extent)?Vt(c,e.extent,E):c;let T=Vt({x:a+d.x,y:l+d.y},r,E);e.extent==="parent"&&(T=RT(T,E,t));const S=xT(e,o,s),u=t.internals.z??0;return{x:T.x,y:T.y,z:u>=S?u+1:S}}function Ki(e,t,n,r=[0,0]){var a;const o=[],s=new Map;for(const l of e){const E=t.get(l.parentId);if(!E)continue;const c=((a=s.get(l.parentId))==null?void 0:a.expandedRect)??un(E),d=IT(c,l.rect);s.set(l.parentId,{expandedRect:d,parent:E})}return s.size>0&&s.forEach(({expandedRect:l,parent:E},c)=>{var O;const d=E.internals.positionAbsolute,T=Nt(E),S=E.origin??r,u=l.x<d.x?Math.round(Math.abs(d.x-l.x)):0,R=l.y<d.y?Math.round(Math.abs(d.y-l.y)):0,I=Math.max(T.width,Math.round(l.width)),N=Math.max(T.height,Math.round(l.height)),A=(I-T.width)*S[0],p=(N-T.height)*S[1];(u>0||R>0||A||p)&&(o.push({id:c,type:"position",position:{x:E.position.x-u+A,y:E.position.y-R+p}}),(O=n.get(c))==null||O.forEach(h=>{e.some(C=>C.id===h.id)||o.push({id:h.id,type:"position",position:{x:h.position.x+u,y:h.position.y+R}})})),(T.width<l.width||T.height<l.height||u||R)&&o.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:I+(u?S[0]*u-A:0),height:N+(R?S[1]*R-p:0)}})}),o}function Km(e,t,n,r,o,s,a){const l=r==null?void 0:r.querySelector(".xyflow__viewport");let E=!1;if(!l)return{changes:[],updatedInternals:E};const c=[],d=window.getComputedStyle(l),{m22:T}=new window.DOMMatrixReadOnly(d.transform),S=[];for(const u of e.values()){const R=t.get(u.id);if(!R)continue;if(R.hidden){t.set(R.id,{...R,internals:{...R.internals,handleBounds:void 0}}),E=!0;continue}const I=Vi(u.nodeElement),N=R.measured.width!==I.width||R.measured.height!==I.height;if(!!(I.width&&I.height&&(N||!R.internals.handleBounds||u.force))){const p=u.nodeElement.getBoundingClientRect(),O=Rn(R.extent)?R.extent:s;let{positionAbsolute:h}=R.internals;R.parentId&&R.extent==="parent"?h=RT(h,I,t.get(R.parentId)):O&&(h=Vt(h,O,I));const C={...R,measured:I,internals:{...R.internals,positionAbsolute:h,handleBounds:{source:Fl("source",u.nodeElement,p,T,R.id),target:Fl("target",u.nodeElement,p,T,R.id)}}};t.set(R.id,C),R.parentId&&Xi(C,t,n,{nodeOrigin:o,zIndexMode:a}),E=!0,N&&(c.push({id:R.id,type:"dimensions",dimensions:I}),R.expandParent&&R.parentId&&S.push({id:R.id,parentId:R.parentId,rect:un(C,o)}))}}if(S.length>0){const u=Ki(S,t,n,o);c.push(...u)}return{changes:c,updatedInternals:E}}async function zm({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 Wl(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 E=r.get(a)||new Map;if(r.set(a,E.set(n,t)),s){a=`${o}-${e}-${s}`;const c=r.get(a)||new Map;r.set(a,c.set(n,t))}}function yT(e,t,n){e.clear(),t.clear();for(const r of n){const{source:o,target:s,sourceHandle:a=null,targetHandle:l=null}=r,E={edgeId:r.id,source:o,target:s,sourceHandle:a,targetHandle:l},c=`${o}-${a}--${s}-${l}`,d=`${s}-${l}--${o}-${a}`;Wl("source",E,d,e,o,a),Wl("target",E,c,e,s,l),t.set(r.id,r)}}function DT(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:DT(n,t):!1}function jl(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 Jm(e,t,n,r){const o=new Map;for(const[s,a]of e)if((a.selected||a.id===r)&&(!a.parentId||!DT(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 Gs({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){var a,l,E;const o=[];for(const[c,d]of t){const T=(a=n.get(c))==null?void 0:a.internals.userNode;T&&o.push({...T,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:((E=t.get(e))==null?void 0:E.position)||s.position,dragging:r}:o[0],o]}function qm({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=sr(s,t);return{x:a.x-s.x,y:a.y-s.y}}function Qm({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:o}){let s={x:null,y:null},a=0,l=new Map,E=!1,c={x:0,y:0},d=null,T=!1,S=null,u=!1,R=!1,I=null;function N({noDragClassName:p,handleSelector:O,domNode:h,isSelectable:C,nodeId:_,nodeClickDistance:m=0}){S=Ye(h);function M({x,y:F}){const{nodeLookup:L,nodeExtent:P,snapGrid:D,snapToGrid:B,nodeOrigin:v,onNodeDrag:U,onSelectionDrag:Y,onError:W,updateNodePositions:k}=t();s={x,y:F};let w=!1;const z=l.size>1,q=z&&P?Ri(or(l)):null,Z=z&&B?qm({dragItems:l,snapGrid:D,x,y:F}):null;for(const[K,H]of l){if(!L.has(K))continue;let J={x:x-H.distance.x,y:F-H.distance.y};B&&(J=Z?{x:Math.round(J.x+Z.x),y:Math.round(J.y+Z.y)}:sr(J,D));let V=null;if(z&&P&&!H.extent&&q){const{positionAbsolute:oe}=H.internals,Te=oe.x-q.x+P[0][0],Ie=oe.x+H.measured.width-q.x2+P[1][0],de=oe.y-q.y+P[0][1],Ne=oe.y+H.measured.height-q.y2+P[1][1];V=[[Te,de],[Ie,Ne]]}const{position:ee,positionAbsolute:ne}=uT({nodeId:K,nextPosition:J,nodeLookup:L,nodeExtent:V||P,nodeOrigin:v,onError:W});w=w||H.position.x!==ee.x||H.position.y!==ee.y,H.position=ee,H.internals.positionAbsolute=ne}if(R=R||w,!!w&&(k(l,!0),I&&(r||U||!_&&Y))){const[K,H]=Gs({nodeId:_,dragItems:l,nodeLookup:L});r==null||r(I,l,K,H),U==null||U(I,K,H),_||Y==null||Y(I,H)}}async function y(){if(!d)return;const{transform:x,panBy:F,autoPanSpeed:L,autoPanOnNodeDrag:P}=t();if(!P){E=!1,cancelAnimationFrame(a);return}const[D,B]=AT(c,d,L);(D!==0||B!==0)&&(s.x=(s.x??0)-D/x[2],s.y=(s.y??0)-B/x[2],await F({x:D,y:B})&&M(s)),a=requestAnimationFrame(y)}function b(x){var z;const{nodeLookup:F,multiSelectionActive:L,nodesDraggable:P,transform:D,snapGrid:B,snapToGrid:v,selectNodesOnDrag:U,onNodeDragStart:Y,onSelectionDragStart:W,unselectNodesAndEdges:k}=t();T=!0,(!U||!C)&&!L&&_&&((z=F.get(_))!=null&&z.selected||k()),C&&U&&_&&(e==null||e(_));const w=Fn(x.sourceEvent,{transform:D,snapGrid:B,snapToGrid:v,containerBounds:d});if(s=w,l=Jm(F,P,w,_),l.size>0&&(n||Y||!_&&W)){const[q,Z]=Gs({nodeId:_,dragItems:l,nodeLookup:F});n==null||n(x.sourceEvent,l,q,Z),Y==null||Y(x.sourceEvent,q,Z),_||W==null||W(x.sourceEvent,Z)}}const g=Xc().clickDistance(m).on("start",x=>{const{domNode:F,nodeDragThreshold:L,transform:P,snapGrid:D,snapToGrid:B}=t();d=(F==null?void 0:F.getBoundingClientRect())||null,u=!1,R=!1,I=x.sourceEvent,L===0&&b(x),s=Fn(x.sourceEvent,{transform:P,snapGrid:D,snapToGrid:B,containerBounds:d}),c=qe(x.sourceEvent,d)}).on("drag",x=>{const{autoPanOnNodeDrag:F,transform:L,snapGrid:P,snapToGrid:D,nodeDragThreshold:B,nodeLookup:v}=t(),U=Fn(x.sourceEvent,{transform:L,snapGrid:P,snapToGrid:D,containerBounds:d});if(I=x.sourceEvent,(x.sourceEvent.type==="touchmove"&&x.sourceEvent.touches.length>1||_&&!v.has(_))&&(u=!0),!u){if(!E&&F&&T&&(E=!0,y()),!T){const Y=qe(x.sourceEvent,d),W=Y.x-c.x,k=Y.y-c.y;Math.sqrt(W*W+k*k)>B&&b(x)}(s.x!==U.xSnapped||s.y!==U.ySnapped)&&l&&T&&(c=qe(x.sourceEvent,d),M(U))}}).on("end",x=>{if(!(!T||u)&&(E=!1,T=!1,cancelAnimationFrame(a),l.size>0)){const{nodeLookup:F,updateNodePositions:L,onNodeDragStop:P,onSelectionDragStop:D}=t();if(R&&(L(l,!1),R=!1),o||P||!_&&D){const[B,v]=Gs({nodeId:_,dragItems:l,nodeLookup:F,dragging:!1});o==null||o(x.sourceEvent,l,B,v),P==null||P(x.sourceEvent,B,v),_||D==null||D(x.sourceEvent,v)}}}).filter(x=>{const F=x.target;return!x.button&&(!p||!jl(F,`.${p}`,h))&&(!O||jl(F,O,h))});S.call(g)}function A(){S==null||S.on(".drag",null)}return{update:N,destroy:A}}function Zm(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())Jn(o,un(s))>0&&r.push(s);return r}const eg=250;function tg(e,t,n,r){var l,E;let o=[],s=1/0;const a=Zm(e,n,t+eg);for(const c of a){const d=[...((l=c.internals.handleBounds)==null?void 0:l.source)??[],...((E=c.internals.handleBounds)==null?void 0:E.target)??[]];for(const T of d){if(r.nodeId===T.nodeId&&r.type===T.type&&r.id===T.id)continue;const{x:S,y:u}=Wt(c,T,T.position,!0),R=Math.sqrt(Math.pow(S-e.x,2)+Math.pow(u-e.y,2));R>t||(R<s?(o=[{...T,x:S,y:u}],s=R):R===s&&o.push({...T,x:S,y:u}))}}if(!o.length)return null;if(o.length>1){const c=r.type==="source"?"target":"source";return o.find(d=>d.type===c)??o[0]}return o[0]}function MT(e,t,n,r,o,s=!1){var c,d,T;const a=r.get(e);if(!a)return null;const l=o==="strict"?(c=a.internals.handleBounds)==null?void 0:c[t]:[...((d=a.internals.handleBounds)==null?void 0:d.source)??[],...((T=a.internals.handleBounds)==null?void 0:T.target)??[]],E=(n?l==null?void 0:l.find(S=>S.id===n):l==null?void 0:l[0])??null;return E&&s?{...E,...Wt(a,E,E.position,!0)}:E}function PT(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function ng(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const bT=()=>!0;function rg(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:o,edgeUpdaterType:s,isTarget:a,domNode:l,nodeLookup:E,lib:c,autoPanOnConnect:d,flowId:T,panBy:S,cancelConnection:u,onConnectStart:R,onConnect:I,onConnectEnd:N,isValidConnection:A=bT,onReconnectEnd:p,updateConnection:O,getTransform:h,getFromHandle:C,autoPanSpeed:_,dragThreshold:m=1,handleDomNode:M}){const y=fT(e.target);let b=0,g;const{x,y:F}=qe(e),L=PT(s,M),P=l==null?void 0:l.getBoundingClientRect();let D=!1;if(!P||!L)return;const B=MT(o,L,r,E,t);if(!B)return;let v=qe(e,P),U=!1,Y=null,W=!1,k=null;function w(){if(!d||!P)return;const[ee,ne]=AT(v,P,_);S({x:ee,y:ne}),b=requestAnimationFrame(w)}const z={...B,nodeId:o,type:L,position:B.position},q=E.get(o);let K={inProgress:!0,isValid:null,from:Wt(q,z,se.Left,!0),fromHandle:z,fromPosition:z.position,fromNode:q,to:v,toHandle:null,toPosition:bl[z.position],toNode:null,pointer:v};function H(){D=!0,O(K),R==null||R(e,{nodeId:o,handleId:r,handleType:L})}m===0&&H();function J(ee){if(!D){const{x:Ne,y:Fe}=qe(ee),be=Ne-x,je=Fe-F;if(!(be*be+je*je>m*m))return;H()}if(!C()||!z){V(ee);return}const ne=h();v=qe(ee,P),g=tg(ir(v,ne,!1,[1,1]),n,E,z),U||(w(),U=!0);const oe=UT(ee,{handle:g,connectionMode:t,fromNodeId:o,fromHandleId:r,fromType:a?"target":"source",isValidConnection:A,doc:y,lib:c,flowId:T,nodeLookup:E});k=oe.handleDomNode,Y=oe.connection,W=ng(!!g,oe.isValid);const Te=E.get(o),Ie=Te?Wt(Te,z,se.Left,!0):K.from,de={...K,from:Ie,isValid:W,to:oe.toHandle&&W?Io({x:oe.toHandle.x,y:oe.toHandle.y},ne):v,toHandle:oe.toHandle,toPosition:W&&oe.toHandle?oe.toHandle.position:bl[z.position],toNode:oe.toHandle?E.get(oe.toHandle.nodeId):null,pointer:v};O(de),K=de}function V(ee){if(!("touches"in ee&&ee.touches.length>0)){if(D){(g||k)&&Y&&W&&(I==null||I(Y));const{inProgress:ne,...oe}=K,Te={...oe,toPosition:K.toHandle?K.toPosition:null};N==null||N(ee,Te),s&&(p==null||p(ee,Te))}u(),cancelAnimationFrame(b),U=!1,W=!1,Y=null,k=null,y.removeEventListener("mousemove",J),y.removeEventListener("mouseup",V),y.removeEventListener("touchmove",J),y.removeEventListener("touchend",V)}}y.addEventListener("mousemove",J),y.addEventListener("mouseup",V),y.addEventListener("touchmove",J),y.addEventListener("touchend",V)}function UT(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:o,fromType:s,doc:a,lib:l,flowId:E,isValidConnection:c=bT,nodeLookup:d}){const T=s==="target",S=t?a.querySelector(`.${l}-flow__handle[data-id="${E}-${t==null?void 0:t.nodeId}-${t==null?void 0:t.id}-${t==null?void 0:t.type}"]`):null,{x:u,y:R}=qe(e),I=a.elementFromPoint(u,R),N=I!=null&&I.classList.contains(`${l}-flow__handle`)?I:S,A={handleDomNode:N,isValid:!1,connection:null,toHandle:null};if(N){const p=PT(void 0,N),O=N.getAttribute("data-nodeid"),h=N.getAttribute("data-handleid"),C=N.classList.contains("connectable"),_=N.classList.contains("connectableend");if(!O||!p)return A;const m={source:T?O:r,sourceHandle:T?h:o,target:T?r:O,targetHandle:T?o:h};A.connection=m;const y=C&&_&&(n===dn.Strict?T&&p==="source"||!T&&p==="target":O!==r||h!==o);A.isValid=y&&c(m),A.toHandle=MT(O,p,h,d,n,!0)}return A}const Oi={onPointerDown:rg,isValid:UT};function og({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const o=Ye(e);function s({translateExtent:l,width:E,height:c,zoomStep:d=1,pannable:T=!0,zoomable:S=!0,inversePan:u=!1}){const R=O=>{if(O.sourceEvent.type!=="wheel"||!t)return;const h=n(),C=O.sourceEvent.ctrlKey&&qn()?10:1,_=-O.sourceEvent.deltaY*(O.sourceEvent.deltaMode===1?.05:O.sourceEvent.deltaMode?1:.002)*d,m=h[2]*Math.pow(2,_*C);t.scaleTo(m)};let I=[0,0];const N=O=>{(O.sourceEvent.type==="mousedown"||O.sourceEvent.type==="touchstart")&&(I=[O.sourceEvent.clientX??O.sourceEvent.touches[0].clientX,O.sourceEvent.clientY??O.sourceEvent.touches[0].clientY])},A=O=>{const h=n();if(O.sourceEvent.type!=="mousemove"&&O.sourceEvent.type!=="touchmove"||!t)return;const C=[O.sourceEvent.clientX??O.sourceEvent.touches[0].clientX,O.sourceEvent.clientY??O.sourceEvent.touches[0].clientY],_=[C[0]-I[0],C[1]-I[1]];I=C;const m=r()*Math.max(h[2],Math.log(h[2]))*(u?-1:1),M={x:h[0]-_[0]*m,y:h[1]-_[1]*m},y=[[0,0],[E,c]];t.setViewportConstrained({x:M.x,y:M.y,zoom:h[2]},y,l)},p=lT().on("start",N).on("zoom",T?A:null).on("zoom.wheel",S?R:null);o.call(p,{})}function a(){o.on("zoom",null)}return{update:s,destroy:a,pointer:Ke}}const vo=e=>({x:e.x,y:e.y,zoom:e.k}),ws=({x:e,y:t,zoom:n})=>Po.translate(e,t).scale(n),nn=(e,t)=>e.target.closest(`.${t}`),vT=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),sg=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,Hs=(e,t=0,n=sg,r=()=>{})=>{const o=typeof t=="number"&&t>0;return o||r(),o?e.transition().duration(t).ease(n).on("end",r):e},BT=e=>{const t=e.ctrlKey&&qn()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function ig({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:o,panOnScrollSpeed:s,zoomOnPinch:a,onPanZoomStart:l,onPanZoom:E,onPanZoomEnd:c}){return d=>{if(nn(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const T=n.property("__zoom").k||1;if(d.ctrlKey&&a){const N=Ke(d),A=BT(d),p=T*Math.pow(2,A);r.scaleTo(n,p,N,d);return}const S=d.deltaMode===1?20:1;let u=o===wt.Vertical?0:d.deltaX*S,R=o===wt.Horizontal?0:d.deltaY*S;!qn()&&d.shiftKey&&o!==wt.Vertical&&(u=d.deltaY*S,R=0),r.translateBy(n,-(u/T)*s,-(R/T)*s,{internal:!0});const I=vo(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(E==null||E(d,I),e.panScrollTimeout=setTimeout(()=>{c==null||c(d,I),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l==null||l(d,I))}}function ag({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,o){const s=r.type==="wheel",a=!t&&s&&!r.ctrlKey,l=nn(r,e);if(r.ctrlKey&&s&&l&&r.preventDefault(),a||l)return null;r.preventDefault(),n.call(this,r,o)}}function lg({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{var s,a,l;if((s=r.sourceEvent)!=null&&s.internal)return;const o=vo(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 Eg({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:o}){return s=>{var a,l;e.usedRightMouseButton=!!(n&&vT(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,vo(s.transform)))}}function cg({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&&vT(t,e.mouseButton??0)&&!e.usedRightMouseButton&&a.sourceEvent&&s(a.sourceEvent),e.usedRightMouseButton=!1,r(!1),o)){const E=vo(a.transform);e.prevViewport=E,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{o==null||o(a.sourceEvent,E)},n?150:0)}}}function Tg({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:o,zoomOnDoubleClick:s,userSelectionActive:a,noWheelClassName:l,noPanClassName:E,lib:c,connectionInProgress:d}){return T=>{var N;const S=e||t,u=n&&T.ctrlKey,R=T.type==="wheel";if(T.button===1&&T.type==="mousedown"&&(nn(T,`${c}-flow__node`)||nn(T,`${c}-flow__edge`)))return!0;if(!r&&!S&&!o&&!s&&!n||a||d&&!R||nn(T,l)&&R||nn(T,E)&&(!R||o&&R&&!e)||!n&&T.ctrlKey&&R)return!1;if(!n&&T.type==="touchstart"&&((N=T.touches)==null?void 0:N.length)>1)return T.preventDefault(),!1;if(!S&&!o&&!u&&R||!r&&(T.type==="mousedown"||T.type==="touchstart")||Array.isArray(r)&&!r.includes(T.button)&&T.type==="mousedown")return!1;const I=Array.isArray(r)&&r.includes(T.button)||!T.button||T.button<=1;return(!T.ctrlKey||R)&&I}}function dg({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:o,onPanZoom:s,onPanZoomStart:a,onPanZoomEnd:l,onDraggingChange:E}){const c={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},d=e.getBoundingClientRect(),T=lT().scaleExtent([t,n]).translateExtent(r),S=Ye(e).call(T);p({x:o.x,y:o.y,zoom:Sn(o.zoom,t,n)},[[0,0],[d.width,d.height]],r);const u=S.on("wheel.zoom"),R=S.on("dblclick.zoom");T.wheelDelta(BT);function I(g,x){return S?new Promise(F=>{T==null||T.interpolate((x==null?void 0:x.interpolate)==="linear"?Bn:Jr).transform(Hs(S,x==null?void 0:x.duration,x==null?void 0:x.ease,()=>F(!0)),g)}):Promise.resolve(!1)}function N({noWheelClassName:g,noPanClassName:x,onPaneContextMenu:F,userSelectionActive:L,panOnScroll:P,panOnDrag:D,panOnScrollMode:B,panOnScrollSpeed:v,preventScrolling:U,zoomOnPinch:Y,zoomOnScroll:W,zoomOnDoubleClick:k,zoomActivationKeyPressed:w,lib:z,onTransformChange:q,connectionInProgress:Z,paneClickDistance:K,selectionOnDrag:H}){L&&!c.isZoomingOrPanning&&A();const J=P&&!w&&!L;T.clickDistance(H?1/0:!Je(K)||K<0?0:K);const V=J?ig({zoomPanValues:c,noWheelClassName:g,d3Selection:S,d3Zoom:T,panOnScrollMode:B,panOnScrollSpeed:v,zoomOnPinch:Y,onPanZoomStart:a,onPanZoom:s,onPanZoomEnd:l}):ag({noWheelClassName:g,preventScrolling:U,d3ZoomHandler:u});if(S.on("wheel.zoom",V,{passive:!1}),!L){const ne=lg({zoomPanValues:c,onDraggingChange:E,onPanZoomStart:a});T.on("start",ne);const oe=Eg({zoomPanValues:c,panOnDrag:D,onPaneContextMenu:!!F,onPanZoom:s,onTransformChange:q});T.on("zoom",oe);const Te=cg({zoomPanValues:c,panOnDrag:D,panOnScroll:P,onPaneContextMenu:F,onPanZoomEnd:l,onDraggingChange:E});T.on("end",Te)}const ee=Tg({zoomActivationKeyPressed:w,panOnDrag:D,zoomOnScroll:W,panOnScroll:P,zoomOnDoubleClick:k,zoomOnPinch:Y,userSelectionActive:L,noPanClassName:x,noWheelClassName:g,lib:z,connectionInProgress:Z});T.filter(ee),k?S.on("dblclick.zoom",R):S.on("dblclick.zoom",null)}function A(){T.on("zoom",null)}async function p(g,x,F){const L=ws(g),P=T==null?void 0:T.constrain()(L,x,F);return P&&await I(P),new Promise(D=>D(P))}async function O(g,x){const F=ws(g);return await I(F,x),new Promise(L=>L(F))}function h(g){if(S){const x=ws(g),F=S.property("__zoom");(F.k!==g.zoom||F.x!==g.x||F.y!==g.y)&&(T==null||T.transform(S,x,null,{sync:!0}))}}function C(){const g=S?aT(S.node()):{x:0,y:0,k:1};return{x:g.x,y:g.y,zoom:g.k}}function _(g,x){return S?new Promise(F=>{T==null||T.interpolate((x==null?void 0:x.interpolate)==="linear"?Bn:Jr).scaleTo(Hs(S,x==null?void 0:x.duration,x==null?void 0:x.ease,()=>F(!0)),g)}):Promise.resolve(!1)}function m(g,x){return S?new Promise(F=>{T==null||T.interpolate((x==null?void 0:x.interpolate)==="linear"?Bn:Jr).scaleBy(Hs(S,x==null?void 0:x.duration,x==null?void 0:x.ease,()=>F(!0)),g)}):Promise.resolve(!1)}function M(g){T==null||T.scaleExtent(g)}function y(g){T==null||T.translateExtent(g)}function b(g){const x=!Je(g)||g<0?0:g;T==null||T.clickDistance(x)}return{update:N,destroy:A,setViewport:O,setViewportConstrained:p,getViewport:C,scaleTo:_,scaleBy:m,setScaleExtent:M,setTranslateExtent:y,syncViewport:h,setClickDistance:b}}var An;(function(e){e.Line="line",e.Handle="handle"})(An||(An={}));function Sg({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:o,affectsY:s}){const a=e-t,l=n-r,E=[a>0?1:a<0?-1:0,l>0?1:l<0?-1:0];return a&&o&&(E[0]=E[0]*-1),l&&s&&(E[1]=E[1]*-1),E}function $l(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 ht(e,t){return Math.max(0,t-e)}function Ct(e,t){return Math.max(0,e-t)}function wr(e,t,n){return Math.max(0,t-e,e-n)}function Xl(e,t){return e?!t:t}function ug(e,t,n,r,o,s,a,l){let{affectsX:E,affectsY:c}=t;const{isHorizontal:d,isVertical:T}=t,S=d&&T,{xSnapped:u,ySnapped:R}=n,{minWidth:I,maxWidth:N,minHeight:A,maxHeight:p}=r,{x:O,y:h,width:C,height:_,aspectRatio:m}=e;let M=Math.floor(d?u-e.pointerX:0),y=Math.floor(T?R-e.pointerY:0);const b=C+(E?-M:M),g=_+(c?-y:y),x=-s[0]*C,F=-s[1]*_;let L=wr(b,I,N),P=wr(g,A,p);if(a){let v=0,U=0;E&&M<0?v=ht(O+M+x,a[0][0]):!E&&M>0&&(v=Ct(O+b+x,a[1][0])),c&&y<0?U=ht(h+y+F,a[0][1]):!c&&y>0&&(U=Ct(h+g+F,a[1][1])),L=Math.max(L,v),P=Math.max(P,U)}if(l){let v=0,U=0;E&&M>0?v=Ct(O+M,l[0][0]):!E&&M<0&&(v=ht(O+b,l[1][0])),c&&y>0?U=Ct(h+y,l[0][1]):!c&&y<0&&(U=ht(h+g,l[1][1])),L=Math.max(L,v),P=Math.max(P,U)}if(o){if(d){const v=wr(b/m,A,p)*m;if(L=Math.max(L,v),a){let U=0;!E&&!c||E&&!c&&S?U=Ct(h+F+b/m,a[1][1])*m:U=ht(h+F+(E?M:-M)/m,a[0][1])*m,L=Math.max(L,U)}if(l){let U=0;!E&&!c||E&&!c&&S?U=ht(h+b/m,l[1][1])*m:U=Ct(h+(E?M:-M)/m,l[0][1])*m,L=Math.max(L,U)}}if(T){const v=wr(g*m,I,N)/m;if(P=Math.max(P,v),a){let U=0;!E&&!c||c&&!E&&S?U=Ct(O+g*m+x,a[1][0])/m:U=ht(O+(c?y:-y)*m+x,a[0][0])/m,P=Math.max(P,U)}if(l){let U=0;!E&&!c||c&&!E&&S?U=ht(O+g*m,l[1][0])/m:U=Ct(O+(c?y:-y)*m,l[0][0])/m,P=Math.max(P,U)}}}y=y+(y<0?P:-P),M=M+(M<0?L:-L),o&&(S?b>g*m?y=(Xl(E,c)?-M:M)/m:M=(Xl(E,c)?-y:y)*m:d?(y=M/m,c=E):(M=y*m,E=c));const D=E?O+M:O,B=c?h+y:h;return{width:C+(E?-M:M),height:_+(c?-y:y),x:s[0]*M*(E?-1:1)+D,y:s[1]*y*(c?-1:1)+B}}const FT={width:0,height:0,x:0,y:0},Rg={...FT,pointerX:0,pointerY:0,aspectRatio:1};function Ag(e){return[[0,0],[e.measured.width,e.measured.height]]}function Ig(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,E=n[1]*a;return[[r-l,o-E],[r+s-l,o+a-E]]}function Ng({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:o}){const s=Ye(e);let a={controlDirection:$l("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:c,boundaries:d,keepAspectRatio:T,resizeDirection:S,onResizeStart:u,onResize:R,onResizeEnd:I,shouldResize:N}){let A={...FT},p={...Rg};a={boundaries:d,resizeDirection:S,keepAspectRatio:T,controlDirection:$l(c)};let O,h=null,C=[],_,m,M,y=!1;const b=Xc().on("start",g=>{const{nodeLookup:x,transform:F,snapGrid:L,snapToGrid:P,nodeOrigin:D,paneDomNode:B}=n();if(O=x.get(t),!O)return;h=(B==null?void 0:B.getBoundingClientRect())??null;const{xSnapped:v,ySnapped:U}=Fn(g.sourceEvent,{transform:F,snapGrid:L,snapToGrid:P,containerBounds:h});A={width:O.measured.width??0,height:O.measured.height??0,x:O.position.x??0,y:O.position.y??0},p={...A,pointerX:v,pointerY:U,aspectRatio:A.width/A.height},_=void 0,O.parentId&&(O.extent==="parent"||O.expandParent)&&(_=x.get(O.parentId),m=_&&O.extent==="parent"?Ag(_):void 0),C=[],M=void 0;for(const[Y,W]of x)if(W.parentId===t&&(C.push({id:Y,position:{...W.position},extent:W.extent}),W.extent==="parent"||W.expandParent)){const k=Ig(W,O,W.origin??D);M?M=[[Math.min(k[0][0],M[0][0]),Math.min(k[0][1],M[0][1])],[Math.max(k[1][0],M[1][0]),Math.max(k[1][1],M[1][1])]]:M=k}u==null||u(g,{...A})}).on("drag",g=>{const{transform:x,snapGrid:F,snapToGrid:L,nodeOrigin:P}=n(),D=Fn(g.sourceEvent,{transform:x,snapGrid:F,snapToGrid:L,containerBounds:h}),B=[];if(!O)return;const{x:v,y:U,width:Y,height:W}=A,k={},w=O.origin??P,{width:z,height:q,x:Z,y:K}=ug(p,a.controlDirection,D,a.boundaries,a.keepAspectRatio,w,m,M),H=z!==Y,J=q!==W,V=Z!==v&&H,ee=K!==U&&J;if(!V&&!ee&&!H&&!J)return;if((V||ee||w[0]===1||w[1]===1)&&(k.x=V?Z:A.x,k.y=ee?K:A.y,A.x=k.x,A.y=k.y,C.length>0)){const Ie=Z-v,de=K-U;for(const Ne of C)Ne.position={x:Ne.position.x-Ie+w[0]*(z-Y),y:Ne.position.y-de+w[1]*(q-W)},B.push(Ne)}if((H||J)&&(k.width=H&&(!a.resizeDirection||a.resizeDirection==="horizontal")?z:A.width,k.height=J&&(!a.resizeDirection||a.resizeDirection==="vertical")?q:A.height,A.width=k.width,A.height=k.height),_&&O.expandParent){const Ie=w[0]*(k.width??0);k.x&&k.x<Ie&&(A.x=Ie,p.x=p.x-(k.x-Ie));const de=w[1]*(k.height??0);k.y&&k.y<de&&(A.y=de,p.y=p.y-(k.y-de))}const ne=Sg({width:A.width,prevWidth:Y,height:A.height,prevHeight:W,affectsX:a.controlDirection.affectsX,affectsY:a.controlDirection.affectsY}),oe={...A,direction:ne};(N==null?void 0:N(g,oe))!==!1&&(y=!0,R==null||R(g,oe),r(k,B))}).on("end",g=>{y&&(I==null||I(g,{...A}),o==null||o({...A}),y=!1)});s.call(b)}function E(){s.on(".drag",null)}return{update:l,destroy:E}}var Ys={exports:{}},ks={},Vs={exports:{}},Ws={};/**
522
+ * @license React
523
+ * use-sync-external-store-shim.production.js
524
+ *
525
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
526
+ *
527
+ * This source code is licensed under the MIT license found in the
528
+ * LICENSE file in the root directory of this source tree.
529
+ */var Kl;function Og(){if(Kl)return Ws;Kl=1;var e=ho();function t(T,S){return T===S&&(T!==0||1/T===1/S)||T!==T&&S!==S}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,s=e.useLayoutEffect,a=e.useDebugValue;function l(T,S){var u=S(),R=r({inst:{value:u,getSnapshot:S}}),I=R[0].inst,N=R[1];return s(function(){I.value=u,I.getSnapshot=S,E(I)&&N({inst:I})},[T,u,S]),o(function(){return E(I)&&N({inst:I}),T(function(){E(I)&&N({inst:I})})},[T]),a(u),u}function E(T){var S=T.getSnapshot;T=T.value;try{var u=S();return!n(T,u)}catch{return!0}}function c(T,S){return S()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?c:l;return Ws.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:d,Ws}var zl;function fg(){return zl||(zl=1,Vs.exports=Og()),Vs.exports}/**
530
+ * @license React
531
+ * use-sync-external-store-shim/with-selector.production.js
532
+ *
533
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
534
+ *
535
+ * This source code is licensed under the MIT license found in the
536
+ * LICENSE file in the root directory of this source tree.
537
+ */var Jl;function pg(){if(Jl)return ks;Jl=1;var e=ho(),t=fg();function n(c,d){return c===d&&(c!==0||1/c===1/d)||c!==c&&d!==d}var r=typeof Object.is=="function"?Object.is:n,o=t.useSyncExternalStore,s=e.useRef,a=e.useEffect,l=e.useMemo,E=e.useDebugValue;return ks.useSyncExternalStoreWithSelector=function(c,d,T,S,u){var R=s(null);if(R.current===null){var I={hasValue:!1,value:null};R.current=I}else I=R.current;R=l(function(){function A(_){if(!p){if(p=!0,O=_,_=S(_),u!==void 0&&I.hasValue){var m=I.value;if(u(m,_))return h=m}return h=_}if(m=h,r(O,_))return m;var M=S(_);return u!==void 0&&u(m,M)?(O=_,m):(O=_,h=M)}var p=!1,O,h,C=T===void 0?null:T;return[function(){return A(d())},C===null?void 0:function(){return A(C())}]},[d,T,S,u]);var N=o(c,R[0],R[1]);return a(function(){I.hasValue=!0,I.value=N},[N]),E(N),N},ks}var ql;function hg(){return ql||(ql=1,Ys.exports=pg()),Ys.exports}var Cg=hg();const Lg=hi(Cg),_g={},Ql=e=>{let t;const n=new Set,r=(d,T)=>{const S=typeof d=="function"?d(t):d;if(!Object.is(S,t)){const u=t;t=T??(typeof S!="object"||S===null)?S:Object.assign({},t,S),n.forEach(R=>R(t,u))}},o=()=>t,E={setState:r,getState:o,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(_g?"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()}},c=t=e(r,o,E);return E},mg=e=>e?Ql(e):Ql,{useDebugValue:gg}=En,{useSyncExternalStoreWithSelector:xg}=Lg,yg=e=>e;function GT(e,t=yg,n){const r=xg(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return gg(r),r}const Zl=(e,t)=>{const n=mg(e),r=(o,s=t)=>GT(n,o,s);return Object.assign(r,n),r},Dg=(e,t)=>e?Zl(e,t):Zl;function Oe(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}FE();const Bo=f.createContext(null),Mg=Bo.Provider,wT=at.error001();function ue(e,t){const n=f.useContext(Bo);if(n===null)throw new Error(wT);return GT(n,e,t)}function fe(){const e=f.useContext(Bo);if(e===null)throw new Error(wT);return f.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const eE={display:"none"},Pg={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},HT="react-flow__node-desc",YT="react-flow__edge-desc",bg="react-flow__aria-live",Ug=e=>e.ariaLiveMessage,vg=e=>e.ariaLabelConfig;function Bg({rfId:e}){const t=ue(Ug);return i.jsx("div",{id:`${bg}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:Pg,children:t})}function Fg({rfId:e,disableKeyboardA11y:t}){const n=ue(vg);return i.jsxs(i.Fragment,{children:[i.jsx("div",{id:`${HT}-${e}`,style:eE,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),i.jsx("div",{id:`${YT}-${e}`,style:eE,children:n["edge.a11yDescription.default"]}),!t&&i.jsx(Bg,{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:he(["react-flow__panel",n,...a]),style:r,ref:s,...o,children:t})});ar.displayName="Panel";function Gg({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 wg=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}},Hr=e=>e.id;function Hg(e,t){return Oe(e.selectedNodes.map(Hr),t.selectedNodes.map(Hr))&&Oe(e.selectedEdges.map(Hr),t.selectedEdges.map(Hr))}function Yg({onSelectionChange:e}){const t=fe(),{selectedNodes:n,selectedEdges:r}=ue(wg,Hg);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 kg=e=>!!e.onSelectionChangeHandlers;function Vg({onSelectionChange:e}){const t=ue(kg);return e||t?i.jsx(Yg,{onSelectionChange:e}):null}const kT=[0,0],Wg={x:0,y:0,zoom:1},jg=["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"],tE=[...jg,"rfId"],$g=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}),nE={translateExtent:Xn,nodeOrigin:kT,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function Xg(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:o,setTranslateExtent:s,setNodeExtent:a,reset:l,setDefaultNodesAndEdges:E}=ue($g,Oe),c=fe();f.useEffect(()=>(E(e.defaultNodes,e.defaultEdges),()=>{d.current=nE,l()}),[]);const d=f.useRef(nE);return f.useEffect(()=>{for(const T of tE){const S=e[T],u=d.current[T];S!==u&&(typeof e[T]>"u"||(T==="nodes"?t(S):T==="edges"?n(S):T==="minZoom"?r(S):T==="maxZoom"?o(S):T==="translateExtent"?s(S):T==="nodeExtent"?a(S):T==="ariaLabelConfig"?c.setState({ariaLabelConfig:Dm(S)}):T==="fitView"?c.setState({fitViewQueued:S}):T==="fitViewOptions"?c.setState({fitViewOptions:S}):c.setState({[T]:S})))}d.current=e},tE.map(T=>e[T])),null}function rE(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function Kg(e){var r;const[t,n]=f.useState(e==="system"?null:e);return f.useEffect(()=>{if(e!=="system"){n(e);return}const o=rE(),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=rE())!=null&&r.matches?"dark":"light"}const oE=typeof document<"u"?document:null;function Qn(e=null,t={target:oE,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 c=(Array.isArray(e)?e:[e]).filter(T=>typeof T=="string").map(T=>T.replace("+",`
538
+ `).replace(`
539
+
540
+ `,`
541
+ +`).split(`
542
+ `)),d=c.reduce((T,S)=>T.concat(...S),[]);return[c,d]}return[[],[]]},[e]);return f.useEffect(()=>{const E=(t==null?void 0:t.target)??oE,c=(t==null?void 0:t.actInsideInputWithModifier)??!0;if(e!==null){const d=u=>{var N,A;if(o.current=u.ctrlKey||u.metaKey||u.shiftKey||u.altKey,(!o.current||o.current&&!c)&&pT(u))return!1;const I=iE(u.code,l);if(s.current.add(u[I]),sE(a,s.current,!1)){const p=((A=(N=u.composedPath)==null?void 0:N.call(u))==null?void 0:A[0])||u.target,O=(p==null?void 0:p.nodeName)==="BUTTON"||(p==null?void 0:p.nodeName)==="A";t.preventDefault!==!1&&(o.current||!O)&&u.preventDefault(),r(!0)}},T=u=>{const R=iE(u.code,l);sE(a,s.current,!0)?(r(!1),s.current.clear()):s.current.delete(u[R]),u.key==="Meta"&&s.current.clear(),o.current=!1},S=()=>{s.current.clear(),r(!1)};return E==null||E.addEventListener("keydown",d),E==null||E.addEventListener("keyup",T),window.addEventListener("blur",S),window.addEventListener("contextmenu",S),()=>{E==null||E.removeEventListener("keydown",d),E==null||E.removeEventListener("keyup",T),window.removeEventListener("blur",S),window.removeEventListener("contextmenu",S)}}},[e,r]),n}function sE(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(o=>t.has(o)))}function iE(e,t){return t.includes(e)?"code":"key"}const zg=()=>{const e=fe();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(),E=ki(t,r,o,s,a,(n==null?void 0:n.padding)??.1);return l?(await l.setViewport(E,{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:E}=a.getBoundingClientRect(),c={x:t.x-l,y:t.y-E},d=n.snapGrid??o,T=n.snapToGrid??s;return ir(c,r,T,d)},flowToScreenPosition:t=>{const{transform:n,domNode:r}=e.getState();if(!r)return t;const{x:o,y:s}=r.getBoundingClientRect(),a=Io(t,n);return{x:a.x+o,y:a.y+s}}}),[])};function VT(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 E of a)Jg(E,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 Jg(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 WT(e,t){return VT(e,t)}function jT(e,t){return VT(e,t)}function Ut(e,t){return{id:e,type:"select",selected:t}}function rn(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(Ut(s.id,a)))}return r}function aE({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),E=((o=l==null?void 0:l.internals)==null?void 0:o.userNode)??l;E!==void 0&&E!==a&&n.push({id:a.id,item:a,type:"replace"}),E===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 lE(e){return{id:e.id,type:"remove"}}const EE=e=>fm(e),qg=e=>ST(e);function $T(e){return f.forwardRef(e)}const Qg=typeof window<"u"?f.useLayoutEffect:f.useEffect;function cE(e){const[t,n]=f.useState(BigInt(0)),[r]=f.useState(()=>Zg(()=>n(o=>o+BigInt(1))));return Qg(()=>{const o=r.get();o.length&&(e(o),r.reset())},[t]),r}function Zg(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}const XT=f.createContext(null);function ex({children:e}){const t=fe(),n=f.useCallback(l=>{const{nodes:E=[],setNodes:c,hasDefaultNodes:d,onNodesChange:T,nodeLookup:S,fitViewQueued:u,onNodesChangeMiddlewareMap:R}=t.getState();let I=E;for(const A of l)I=typeof A=="function"?A(I):A;let N=aE({items:I,lookup:S});for(const A of R.values())N=A(N);d&&c(I),N.length>0?T==null||T(N):u&&window.requestAnimationFrame(()=>{const{fitViewQueued:A,nodes:p,setNodes:O}=t.getState();A&&O(p)})},[]),r=cE(n),o=f.useCallback(l=>{const{edges:E=[],setEdges:c,hasDefaultEdges:d,onEdgesChange:T,edgeLookup:S}=t.getState();let u=E;for(const R of l)u=typeof R=="function"?R(u):R;d?c(u):T&&T(aE({items:u,lookup:S}))},[]),s=cE(o),a=f.useMemo(()=>({nodeQueue:r,edgeQueue:s}),[]);return i.jsx(XT.Provider,{value:a,children:e})}function tx(){const e=f.useContext(XT);if(!e)throw new Error("useBatchContext must be used within a BatchProvider");return e}const nx=e=>!!e.panZoom;function zi(){const e=zg(),t=fe(),n=tx(),r=ue(nx),o=f.useMemo(()=>{const s=T=>t.getState().nodeLookup.get(T),a=T=>{n.nodeQueue.push(T)},l=T=>{n.edgeQueue.push(T)},E=T=>{var A,p;const{nodeLookup:S,nodeOrigin:u}=t.getState(),R=EE(T)?T:S.get(T.id),I=R.parentId?OT(R.position,R.measured,R.parentId,S,u):R.position,N={...R,position:I,width:((A=R.measured)==null?void 0:A.width)??R.width,height:((p=R.measured)==null?void 0:p.height)??R.height};return un(N)},c=(T,S,u={replace:!1})=>{a(R=>R.map(I=>{if(I.id===T){const N=typeof S=="function"?S(I):S;return u.replace&&EE(N)?N:{...I,...N}}return I}))},d=(T,S,u={replace:!1})=>{l(R=>R.map(I=>{if(I.id===T){const N=typeof S=="function"?S(I):S;return u.replace&&qg(N)?N:{...I,...N}}return I}))};return{getNodes:()=>t.getState().nodes.map(T=>({...T})),getNode:T=>{var S;return(S=s(T))==null?void 0:S.internals.userNode},getInternalNode:s,getEdges:()=>{const{edges:T=[]}=t.getState();return T.map(S=>({...S}))},getEdge:T=>t.getState().edgeLookup.get(T),setNodes:a,setEdges:l,addNodes:T=>{const S=Array.isArray(T)?T:[T];n.nodeQueue.push(u=>[...u,...S])},addEdges:T=>{const S=Array.isArray(T)?T:[T];n.edgeQueue.push(u=>[...u,...S])},toObject:()=>{const{nodes:T=[],edges:S=[],transform:u}=t.getState(),[R,I,N]=u;return{nodes:T.map(A=>({...A})),edges:S.map(A=>({...A})),viewport:{x:R,y:I,zoom:N}}},deleteElements:async({nodes:T=[],edges:S=[]})=>{const{nodes:u,edges:R,onNodesDelete:I,onEdgesDelete:N,triggerNodeChanges:A,triggerEdgeChanges:p,onDelete:O,onBeforeDelete:h}=t.getState(),{nodes:C,edges:_}=await _m({nodesToRemove:T,edgesToRemove:S,nodes:u,edges:R,onBeforeDelete:h}),m=_.length>0,M=C.length>0;if(m){const y=_.map(lE);N==null||N(_),p(y)}if(M){const y=C.map(lE);I==null||I(C),A(y)}return(M||m)&&(O==null||O({nodes:C,edges:_})),{deletedNodes:C,deletedEdges:_}},getIntersectingNodes:(T,S=!0,u)=>{const R=vl(T),I=R?T:E(T),N=u!==void 0;return I?(u||t.getState().nodes).filter(A=>{const p=t.getState().nodeLookup.get(A.id);if(p&&!R&&(A.id===T.id||!p.internals.positionAbsolute))return!1;const O=un(N?A:p),h=Jn(O,I);return S&&h>0||h>=O.width*O.height||h>=I.width*I.height}):[]},isNodeIntersecting:(T,S,u=!0)=>{const I=vl(T)?T:E(T);if(!I)return!1;const N=Jn(I,S);return u&&N>0||N>=S.width*S.height||N>=I.width*I.height},updateNode:c,updateNodeData:(T,S,u={replace:!1})=>{c(T,R=>{const I=typeof S=="function"?S(R):S;return u.replace?{...R,data:I}:{...R,data:{...R.data,...I}}},u)},updateEdge:d,updateEdgeData:(T,S,u={replace:!1})=>{d(T,R=>{const I=typeof S=="function"?S(R):S;return u.replace?{...R,data:I}:{...R,data:{...R.data,...I}}},u)},getNodesBounds:T=>{const{nodeLookup:S,nodeOrigin:u}=t.getState();return pm(T,{nodeLookup:S,nodeOrigin:u})},getHandleConnections:({type:T,id:S,nodeId:u})=>{var R;return Array.from(((R=t.getState().connectionLookup.get(`${u}-${T}${S?`-${S}`:""}`))==null?void 0:R.values())??[])},getNodeConnections:({type:T,handleId:S,nodeId:u})=>{var R;return Array.from(((R=t.getState().connectionLookup.get(`${u}${T?S?`-${T}-${S}`:`-${T}`:""}`))==null?void 0:R.values())??[])},fitView:async T=>{const S=t.getState().fitViewResolver??ym();return t.setState({fitViewQueued:!0,fitViewOptions:T,fitViewResolver:S}),n.nodeQueue.push(u=>[...u]),S.promise}}},[]);return f.useMemo(()=>({...o,...e,viewportInitialized:r}),[r])}const TE=e=>e.selected,rx=typeof window<"u"?window:void 0;function ox({deleteKeyCode:e,multiSelectionKeyCode:t}){const n=fe(),{deleteElements:r}=zi(),o=Qn(e,{actInsideInputWithModifier:!1}),s=Qn(t,{target:rx});f.useEffect(()=>{if(o){const{edges:a,nodes:l}=n.getState();r({nodes:l.filter(TE),edges:a.filter(TE)}),n.setState({nodesSelectionActive:!1})}},[o]),f.useEffect(()=>{n.setState({multiSelectionActive:s})},[s])}function sx(e){const t=fe();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=Vi(e.current);(r.height===0||r.width===0)&&((l=(a=t.getState()).onError)==null||l.call(a,"004",at.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 Fo={position:"absolute",width:"100%",height:"100%",top:0,left:0},ix=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function ax({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:r=!1,panOnScrollSpeed:o=.5,panOnScrollMode:s=wt.Free,zoomOnDoubleClick:a=!0,panOnDrag:l=!0,defaultViewport:E,translateExtent:c,minZoom:d,maxZoom:T,zoomActivationKeyCode:S,preventScrolling:u=!0,children:R,noWheelClassName:I,noPanClassName:N,onViewportChange:A,isControlledViewport:p,paneClickDistance:O,selectionOnDrag:h}){const C=fe(),_=f.useRef(null),{userSelectionActive:m,lib:M,connectionInProgress:y}=ue(ix,Oe),b=Qn(S),g=f.useRef();sx(_);const x=f.useCallback(F=>{A==null||A({x:F[0],y:F[1],zoom:F[2]}),p||C.setState({transform:F})},[A,p]);return f.useEffect(()=>{if(_.current){g.current=dg({domNode:_.current,minZoom:d,maxZoom:T,translateExtent:c,viewport:E,onDraggingChange:D=>C.setState(B=>B.paneDragging===D?B:{paneDragging:D}),onPanZoomStart:(D,B)=>{const{onViewportChangeStart:v,onMoveStart:U}=C.getState();U==null||U(D,B),v==null||v(B)},onPanZoom:(D,B)=>{const{onViewportChange:v,onMove:U}=C.getState();U==null||U(D,B),v==null||v(B)},onPanZoomEnd:(D,B)=>{const{onViewportChangeEnd:v,onMoveEnd:U}=C.getState();U==null||U(D,B),v==null||v(B)}});const{x:F,y:L,zoom:P}=g.current.getViewport();return C.setState({panZoom:g.current,transform:[F,L,P],domNode:_.current.closest(".react-flow")}),()=>{var D;(D=g.current)==null||D.destroy()}}},[]),f.useEffect(()=>{var F;(F=g.current)==null||F.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:r,panOnScrollSpeed:o,panOnScrollMode:s,zoomOnDoubleClick:a,panOnDrag:l,zoomActivationKeyPressed:b,preventScrolling:u,noPanClassName:N,userSelectionActive:m,noWheelClassName:I,lib:M,onTransformChange:x,connectionInProgress:y,selectionOnDrag:h,paneClickDistance:O})},[e,t,n,r,o,s,a,l,b,u,N,m,I,M,x,y,h,O]),i.jsx("div",{className:"react-flow__renderer",ref:_,style:Fo,children:R})}const lx=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function Ex(){const{userSelectionActive:e,userSelectionRect:t}=ue(lx,Oe);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 js=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},cx=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,connectionInProgress:e.connection.inProgress,dragging:e.paneDragging});function Tx({isSelecting:e,selectionKeyPressed:t,selectionMode:n=Kn.Full,panOnDrag:r,paneClickDistance:o,selectionOnDrag:s,onSelectionStart:a,onSelectionEnd:l,onPaneClick:E,onPaneContextMenu:c,onPaneScroll:d,onPaneMouseEnter:T,onPaneMouseMove:S,onPaneMouseLeave:u,children:R}){const I=fe(),{userSelectionActive:N,elementsSelectable:A,dragging:p,connectionInProgress:O}=ue(cx,Oe),h=A&&(e||N),C=f.useRef(null),_=f.useRef(),m=f.useRef(new Set),M=f.useRef(new Set),y=f.useRef(!1),b=v=>{if(y.current||O){y.current=!1;return}E==null||E(v),I.getState().resetSelectedElements(),I.setState({nodesSelectionActive:!1})},g=v=>{if(Array.isArray(r)&&(r!=null&&r.includes(2))){v.preventDefault();return}c==null||c(v)},x=d?v=>d(v):void 0,F=v=>{y.current&&(v.stopPropagation(),y.current=!1)},L=v=>{var q,Z;const{domNode:U}=I.getState();if(_.current=U==null?void 0:U.getBoundingClientRect(),!_.current)return;const Y=v.target===C.current;if(!Y&&!!v.target.closest(".nokey")||!e||!(s&&Y||t)||v.button!==0||!v.isPrimary)return;(Z=(q=v.target)==null?void 0:q.setPointerCapture)==null||Z.call(q,v.pointerId),y.current=!1;const{x:w,y:z}=qe(v.nativeEvent,_.current);I.setState({userSelectionRect:{width:0,height:0,startX:w,startY:z,x:w,y:z}}),Y||(v.stopPropagation(),v.preventDefault())},P=v=>{const{userSelectionRect:U,transform:Y,nodeLookup:W,edgeLookup:k,connectionLookup:w,triggerNodeChanges:z,triggerEdgeChanges:q,defaultEdgeOptions:Z,resetSelectedElements:K}=I.getState();if(!_.current||!U)return;const{x:H,y:J}=qe(v.nativeEvent,_.current),{startX:V,startY:ee}=U;if(!y.current){const de=t?0:o;if(Math.hypot(H-V,J-ee)<=de)return;K(),a==null||a(v)}y.current=!0;const ne={startX:V,startY:ee,x:H<V?H:V,y:J<ee?J:ee,width:Math.abs(H-V),height:Math.abs(J-ee)},oe=m.current,Te=M.current;m.current=new Set(Yi(W,ne,Y,n===Kn.Partial,!0).map(de=>de.id)),M.current=new Set;const Ie=(Z==null?void 0:Z.selectable)??!0;for(const de of m.current){const Ne=w.get(de);if(Ne)for(const{edgeId:Fe}of Ne.values()){const be=k.get(Fe);be&&(be.selectable??Ie)&&M.current.add(Fe)}}if(!Bl(oe,m.current)){const de=rn(W,m.current,!0);z(de)}if(!Bl(Te,M.current)){const de=rn(k,M.current);q(de)}I.setState({userSelectionRect:ne,userSelectionActive:!0,nodesSelectionActive:!1})},D=v=>{var U,Y;v.button===0&&((Y=(U=v.target)==null?void 0:U.releasePointerCapture)==null||Y.call(U,v.pointerId),!N&&v.target===C.current&&I.getState().userSelectionRect&&(b==null||b(v)),I.setState({userSelectionActive:!1,userSelectionRect:null}),y.current&&(l==null||l(v),I.setState({nodesSelectionActive:m.current.size>0})))},B=r===!0||Array.isArray(r)&&r.includes(0);return i.jsxs("div",{className:he(["react-flow__pane",{draggable:B,dragging:p,selection:e}]),onClick:h?void 0:js(b,C),onContextMenu:js(g,C),onWheel:js(x,C),onPointerEnter:h?void 0:T,onPointerMove:h?P:S,onPointerUp:h?D:void 0,onPointerDownCapture:h?L:void 0,onClickCapture:h?F:void 0,onPointerLeave:u,ref:C,style:Fo,children:[R,i.jsx(Ex,{})]})}function fi({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:o,unselectNodesAndEdges:s,multiSelectionActive:a,nodeLookup:l,onError:E}=t.getState(),c=l.get(e);if(!c){E==null||E("012",at.error012(e));return}t.setState({nodesSelectionActive:!1}),c.selected?(n||c.selected&&a)&&(s({nodes:[c],edges:[]}),requestAnimationFrame(()=>{var d;return(d=r==null?void 0:r.current)==null?void 0:d.blur()})):o([e])}function KT({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:o,isSelectable:s,nodeClickDistance:a}){const l=fe(),[E,c]=f.useState(!1),d=f.useRef();return f.useEffect(()=>{d.current=Qm({getStoreItems:()=>l.getState(),onNodeMouseDown:T=>{fi({id:T,store:l,nodeRef:e})},onDragStart:()=>{c(!0)},onDragStop:()=>{c(!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 T;(T=d.current)==null||T.destroy()}},[n,r,t,s,e,o,a]),E}const dx=e=>t=>t.selected&&(t.draggable||e&&typeof t.draggable>"u");function zT(){const e=fe();return f.useCallback(n=>{const{nodeExtent:r,snapToGrid:o,snapGrid:s,nodesDraggable:a,onError:l,updateNodePositions:E,nodeLookup:c,nodeOrigin:d}=e.getState(),T=new Map,S=dx(a),u=o?s[0]:5,R=o?s[1]:5,I=n.direction.x*u*n.factor,N=n.direction.y*R*n.factor;for(const[,A]of c){if(!S(A))continue;let p={x:A.internals.positionAbsolute.x+I,y:A.internals.positionAbsolute.y+N};o&&(p=sr(p,s));const{position:O,positionAbsolute:h}=uT({nodeId:A.id,nextPosition:p,nodeLookup:c,nodeExtent:r,nodeOrigin:d,onError:l});A.position=O,A.internals.positionAbsolute=h,T.set(A.id,A)}E(T)},[])}const Ji=f.createContext(null),Sx=Ji.Provider;Ji.Consumer;const JT=()=>f.useContext(Ji),ux=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),Rx=(e,t,n)=>r=>{const{connectionClickStartHandle:o,connectionMode:s,connection:a}=r,{fromHandle:l,toHandle:E,isValid:c}=a,d=(E==null?void 0:E.nodeId)===e&&(E==null?void 0:E.id)===t&&(E==null?void 0:E.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===dn.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&&c}};function Ax({type:e="source",position:t=se.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:o=!0,isConnectableEnd:s=!0,id:a,onConnect:l,children:E,className:c,onMouseDown:d,onTouchStart:T,...S},u){var P,D;const R=a||null,I=e==="target",N=fe(),A=JT(),{connectOnClick:p,noPanClassName:O,rfId:h}=ue(ux,Oe),{connectingFrom:C,connectingTo:_,clickConnecting:m,isPossibleEndHandle:M,connectionInProcess:y,clickConnectionInProcess:b,valid:g}=ue(Rx(A,R,e),Oe);A||(D=(P=N.getState()).onError)==null||D.call(P,"010",at.error010());const x=B=>{const{defaultEdgeOptions:v,onConnect:U,hasDefaultEdges:Y}=N.getState(),W={...v,...B};if(Y){const{edges:k,setEdges:w}=N.getState();w(Bm(W,k))}U==null||U(W),l==null||l(W)},F=B=>{if(!A)return;const v=hT(B.nativeEvent);if(o&&(v&&B.button===0||!v)){const U=N.getState();Oi.onPointerDown(B.nativeEvent,{handleDomNode:B.currentTarget,autoPanOnConnect:U.autoPanOnConnect,connectionMode:U.connectionMode,connectionRadius:U.connectionRadius,domNode:U.domNode,nodeLookup:U.nodeLookup,lib:U.lib,isTarget:I,handleId:R,nodeId:A,flowId:U.rfId,panBy:U.panBy,cancelConnection:U.cancelConnection,onConnectStart:U.onConnectStart,onConnectEnd:(...Y)=>{var W,k;return(k=(W=N.getState()).onConnectEnd)==null?void 0:k.call(W,...Y)},updateConnection:U.updateConnection,onConnect:x,isValidConnection:n||((...Y)=>{var W,k;return((k=(W=N.getState()).isValidConnection)==null?void 0:k.call(W,...Y))??!0}),getTransform:()=>N.getState().transform,getFromHandle:()=>N.getState().connection.fromHandle,autoPanSpeed:U.autoPanSpeed,dragThreshold:U.connectionDragThreshold})}v?d==null||d(B):T==null||T(B)},L=B=>{const{onClickConnectStart:v,onClickConnectEnd:U,connectionClickStartHandle:Y,connectionMode:W,isValidConnection:k,lib:w,rfId:z,nodeLookup:q,connection:Z}=N.getState();if(!A||!Y&&!o)return;if(!Y){v==null||v(B.nativeEvent,{nodeId:A,handleId:R,handleType:e}),N.setState({connectionClickStartHandle:{nodeId:A,type:e,id:R}});return}const K=fT(B.target),H=n||k,{connection:J,isValid:V}=Oi.isValid(B.nativeEvent,{handle:{nodeId:A,id:R,type:e},connectionMode:W,fromNodeId:Y.nodeId,fromHandleId:Y.id||null,fromType:Y.type,isValidConnection:H,flowId:z,doc:K,lib:w,nodeLookup:q});V&&J&&x(J);const ee=structuredClone(Z);delete ee.inProgress,ee.toPosition=ee.toHandle?ee.toHandle.position:null,U==null||U(B,ee),N.setState({connectionClickStartHandle:null})};return i.jsx("div",{"data-handleid":R,"data-nodeid":A,"data-handlepos":t,"data-id":`${h}-${A}-${R}-${e}`,className:he(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",O,c,{source:!I,target:I,connectable:r,connectablestart:o,connectableend:s,clickconnecting:m,connectingfrom:C,connectingto:_,valid:g,connectionindicator:r&&(!y||M)&&(y||b?s:o)}]),onMouseDown:F,onTouchStart:F,onClick:p?L:void 0,ref:u,...S,children:E})}const In=f.memo($T(Ax));function Ix({data:e,isConnectable:t,sourcePosition:n=se.Bottom}){return i.jsxs(i.Fragment,{children:[e==null?void 0:e.label,i.jsx(In,{type:"source",position:n,isConnectable:t})]})}function Nx({data:e,isConnectable:t,targetPosition:n=se.Top,sourcePosition:r=se.Bottom}){return i.jsxs(i.Fragment,{children:[i.jsx(In,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,i.jsx(In,{type:"source",position:r,isConnectable:t})]})}function Ox(){return null}function fx({data:e,isConnectable:t,targetPosition:n=se.Top}){return i.jsxs(i.Fragment,{children:[i.jsx(In,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label]})}const No={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},dE={input:Ix,default:Nx,output:fx,group:Ox};function px(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 hx=e=>{const{width:t,height:n,x:r,y:o}=or(e.nodeLookup,{filter:s=>!!s.selected});return{width:Je(t)?t:null,height:Je(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 Cx({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=fe(),{width:o,height:s,transformString:a,userSelectionActive:l}=ue(hx,Oe),E=zT(),c=f.useRef(null);f.useEffect(()=>{var u;n||(u=c.current)==null||u.focus({preventScroll:!0})},[n]);const d=!l&&o!==null&&s!==null;if(KT({nodeRef:c,disabled:!d}),!d)return null;const T=e?u=>{const R=r.getState().nodes.filter(I=>I.selected);e(u,R)}:void 0,S=u=>{Object.prototype.hasOwnProperty.call(No,u.key)&&(u.preventDefault(),E({direction:No[u.key],factor:u.shiftKey?4:1}))};return i.jsx("div",{className:he(["react-flow__nodesselection","react-flow__container",t]),style:{transform:a},children:i.jsx("div",{ref:c,className:"react-flow__nodesselection-rect",onContextMenu:T,tabIndex:n?void 0:-1,onKeyDown:n?void 0:S,style:{width:o,height:s}})})}const SE=typeof window<"u"?window:void 0,Lx=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function qT({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:s,onPaneScroll:a,paneClickDistance:l,deleteKeyCode:E,selectionKeyCode:c,selectionOnDrag:d,selectionMode:T,onSelectionStart:S,onSelectionEnd:u,multiSelectionKeyCode:R,panActivationKeyCode:I,zoomActivationKeyCode:N,elementsSelectable:A,zoomOnScroll:p,zoomOnPinch:O,panOnScroll:h,panOnScrollSpeed:C,panOnScrollMode:_,zoomOnDoubleClick:m,panOnDrag:M,defaultViewport:y,translateExtent:b,minZoom:g,maxZoom:x,preventScrolling:F,onSelectionContextMenu:L,noWheelClassName:P,noPanClassName:D,disableKeyboardA11y:B,onViewportChange:v,isControlledViewport:U}){const{nodesSelectionActive:Y,userSelectionActive:W}=ue(Lx,Oe),k=Qn(c,{target:SE}),w=Qn(I,{target:SE}),z=w||M,q=w||h,Z=d&&z!==!0,K=k||W||Z;return ox({deleteKeyCode:E,multiSelectionKeyCode:R}),i.jsx(ax,{onPaneContextMenu:s,elementsSelectable:A,zoomOnScroll:p,zoomOnPinch:O,panOnScroll:q,panOnScrollSpeed:C,panOnScrollMode:_,zoomOnDoubleClick:m,panOnDrag:!k&&z,defaultViewport:y,translateExtent:b,minZoom:g,maxZoom:x,zoomActivationKeyCode:N,preventScrolling:F,noWheelClassName:P,noPanClassName:D,onViewportChange:v,isControlledViewport:U,paneClickDistance:l,selectionOnDrag:Z,children:i.jsxs(Tx,{onSelectionStart:S,onSelectionEnd:u,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:s,onPaneScroll:a,panOnDrag:z,isSelecting:!!K,selectionMode:T,selectionKeyPressed:k,paneClickDistance:l,selectionOnDrag:Z,children:[e,Y&&i.jsx(Cx,{onSelectionContextMenu:L,noPanClassName:D,disableKeyboardA11y:B})]})})}qT.displayName="FlowRenderer";const _x=f.memo(qT),mx=e=>t=>e?Yi(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 gx(e){return ue(f.useCallback(mx(e),[e]),Oe)}const xx=e=>e.updateNodeInternals;function yx(){const e=ue(xx),[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 Dx({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){const o=fe(),s=f.useRef(null),a=f.useRef(null),l=f.useRef(e.sourcePosition),E=f.useRef(e.targetPosition),c=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 T=c.current!==t,S=l.current!==e.sourcePosition,u=E.current!==e.targetPosition;(T||S||u)&&(c.current=t,l.current=e.sourcePosition,E.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 Mx({id:e,onClick:t,onMouseEnter:n,onMouseMove:r,onMouseLeave:o,onContextMenu:s,onDoubleClick:a,nodesDraggable:l,elementsSelectable:E,nodesConnectable:c,nodesFocusable:d,resizeObserver:T,noDragClassName:S,noPanClassName:u,disableKeyboardA11y:R,rfId:I,nodeTypes:N,nodeClickDistance:A,onError:p}){const{node:O,internals:h,isParent:C}=ue(H=>{const J=H.nodeLookup.get(e),V=H.parentLookup.has(e);return{node:J,internals:J.internals,isParent:V}},Oe);let _=O.type||"default",m=(N==null?void 0:N[_])||dE[_];m===void 0&&(p==null||p("003",at.error003(_)),_="default",m=(N==null?void 0:N.default)||dE.default);const M=!!(O.draggable||l&&typeof O.draggable>"u"),y=!!(O.selectable||E&&typeof O.selectable>"u"),b=!!(O.connectable||c&&typeof O.connectable>"u"),g=!!(O.focusable||d&&typeof O.focusable>"u"),x=fe(),F=NT(O),L=Dx({node:O,nodeType:_,hasDimensions:F,resizeObserver:T}),P=KT({nodeRef:L,disabled:O.hidden||!M,noDragClassName:S,handleSelector:O.dragHandle,nodeId:e,isSelectable:y,nodeClickDistance:A}),D=zT();if(O.hidden)return null;const B=Nt(O),v=px(O),U=y||M||t||n||r||o,Y=n?H=>n(H,{...h.userNode}):void 0,W=r?H=>r(H,{...h.userNode}):void 0,k=o?H=>o(H,{...h.userNode}):void 0,w=s?H=>s(H,{...h.userNode}):void 0,z=a?H=>a(H,{...h.userNode}):void 0,q=H=>{const{selectNodesOnDrag:J,nodeDragThreshold:V}=x.getState();y&&(!J||!M||V>0)&&fi({id:e,store:x,nodeRef:L}),t&&t(H,{...h.userNode})},Z=H=>{if(!(pT(H.nativeEvent)||R)){if(ET.includes(H.key)&&y){const J=H.key==="Escape";fi({id:e,store:x,unselect:J,nodeRef:L})}else if(M&&O.selected&&Object.prototype.hasOwnProperty.call(No,H.key)){H.preventDefault();const{ariaLabelConfig:J}=x.getState();x.setState({ariaLiveMessage:J["node.a11yDescription.ariaLiveMessage"]({direction:H.key.replace("Arrow","").toLowerCase(),x:~~h.positionAbsolute.x,y:~~h.positionAbsolute.y})}),D({direction:No[H.key],factor:H.shiftKey?4:1})}}},K=()=>{var Te;if(R||!((Te=L.current)!=null&&Te.matches(":focus-visible")))return;const{transform:H,width:J,height:V,autoPanOnNodeFocus:ee,setCenter:ne}=x.getState();if(!ee)return;Yi(new Map([[e,O]]),{x:0,y:0,width:J,height:V},H,!0).length>0||ne(O.position.x+B.width/2,O.position.y+B.height/2,{zoom:H[2]})};return i.jsx("div",{className:he(["react-flow__node",`react-flow__node-${_}`,{[u]:M},O.className,{selected:O.selected,selectable:y,parent:C,draggable:M,dragging:P}]),ref:L,style:{zIndex:h.z,transform:`translate(${h.positionAbsolute.x}px,${h.positionAbsolute.y}px)`,pointerEvents:U?"all":"none",visibility:F?"visible":"hidden",...O.style,...v},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:Y,onMouseMove:W,onMouseLeave:k,onContextMenu:w,onClick:q,onDoubleClick:z,onKeyDown:g?Z:void 0,tabIndex:g?0:void 0,onFocus:g?K:void 0,role:O.ariaRole??(g?"group":void 0),"aria-roledescription":"node","aria-describedby":R?void 0:`${HT}-${I}`,"aria-label":O.ariaLabel,...O.domAttributes,children:i.jsx(Sx,{value:e,children:i.jsx(m,{id:e,data:O.data,type:_,positionAbsoluteX:h.positionAbsolute.x,positionAbsoluteY:h.positionAbsolute.y,selected:O.selected??!1,selectable:y,draggable:M,deletable:O.deletable??!0,isConnectable:b,sourcePosition:O.sourcePosition,targetPosition:O.targetPosition,dragging:P,dragHandle:O.dragHandle,zIndex:h.z,parentId:O.parentId,...B})})})}var Px=f.memo(Mx);const bx=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function QT(e){const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:o,onError:s}=ue(bx,Oe),a=gx(e.onlyRenderVisibleElements),l=yx();return i.jsx("div",{className:"react-flow__nodes",style:Fo,children:a.map(E=>i.jsx(Px,{id:E,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},E))})}QT.displayName="NodeRenderer";const Ux=f.memo(QT);function vx(e){return ue(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&&bm({sourceNode:s,targetNode:a,width:n.width,height:n.height,transform:n.transform})&&r.push(o.id)}return r},[e]),Oe)}const Bx=({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"})},Fx=({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"})},uE={[zn.Arrow]:Bx,[zn.ArrowClosed]:Fx};function Gx(e){const t=fe();return f.useMemo(()=>{var o,s;return Object.prototype.hasOwnProperty.call(uE,e)?uE[e]:((s=(o=t.getState()).onError)==null||s.call(o,"009",at.error009(e)),null)},[e])}const wx=({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 E=Gx(t);return E?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(E,{color:n,strokeWidth:a})}):null},ZT=({defaultColor:e,rfId:t})=>{const n=ue(s=>s.edges),r=ue(s=>s.defaultEdgeOptions),o=f.useMemo(()=>Ym(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(wx,{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};ZT.displayName="MarkerDefinitions";var Hx=f.memo(ZT);function ed({x:e,y:t,label:n,labelStyle:r,labelShowBg:o=!0,labelBgStyle:s,labelBgPadding:a=[2,4],labelBgBorderRadius:l=2,children:E,className:c,...d}){const[T,S]=f.useState({x:1,y:0,width:0,height:0}),u=he(["react-flow__edge-textwrapper",c]),R=f.useRef(null);return f.useEffect(()=>{if(R.current){const I=R.current.getBBox();S({x:I.x,y:I.y,width:I.width,height:I.height})}},[n]),n?i.jsxs("g",{transform:`translate(${e-T.width/2} ${t-T.height/2})`,className:u,visibility:T.width?"visible":"hidden",...d,children:[o&&i.jsx("rect",{width:T.width+2*a[0],x:-a[0],y:-a[1],height:T.height+2*a[1],className:"react-flow__edge-textbg",style:s,rx:l,ry:l}),i.jsx("text",{className:"react-flow__edge-text",y:T.height/2,dy:"0.3em",ref:R,style:r,children:n}),E]}):null}ed.displayName="EdgeText";const Yx=f.memo(ed);function Go({path:e,labelX:t,labelY:n,label:r,labelStyle:o,labelShowBg:s,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:E,interactionWidth:c=20,...d}){return i.jsxs(i.Fragment,{children:[i.jsx("path",{...d,d:e,fill:"none",className:he(["react-flow__edge-path",d.className])}),c?i.jsx("path",{d:e,fill:"none",strokeOpacity:0,strokeWidth:c,className:"react-flow__edge-interaction"}):null,r&&Je(t)&&Je(n)?i.jsx(Yx,{x:t,y:n,label:r,labelStyle:o,labelShowBg:s,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:E}):null]})}function RE({pos:e,x1:t,y1:n,x2:r,y2:o}){return e===se.Left||e===se.Right?[.5*(t+r),n]:[t,.5*(n+o)]}function td({sourceX:e,sourceY:t,sourcePosition:n=se.Bottom,targetX:r,targetY:o,targetPosition:s=se.Top}){const[a,l]=RE({pos:n,x1:e,y1:t,x2:r,y2:o}),[E,c]=RE({pos:s,x1:r,y1:o,x2:e,y2:t}),[d,T,S,u]=CT({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:a,sourceControlY:l,targetControlX:E,targetControlY:c});return[`M${e},${t} C${a},${l} ${E},${c} ${r},${o}`,d,T,S,u]}function nd(e){return f.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,sourcePosition:a,targetPosition:l,label:E,labelStyle:c,labelShowBg:d,labelBgStyle:T,labelBgPadding:S,labelBgBorderRadius:u,style:R,markerEnd:I,markerStart:N,interactionWidth:A})=>{const[p,O,h]=td({sourceX:n,sourceY:r,sourcePosition:a,targetX:o,targetY:s,targetPosition:l}),C=e.isInternal?void 0:t;return i.jsx(Go,{id:C,path:p,labelX:O,labelY:h,label:E,labelStyle:c,labelShowBg:d,labelBgStyle:T,labelBgPadding:S,labelBgBorderRadius:u,style:R,markerEnd:I,markerStart:N,interactionWidth:A})})}const kx=nd({isInternal:!1}),rd=nd({isInternal:!0});kx.displayName="SimpleBezierEdge";rd.displayName="SimpleBezierEdgeInternal";function od(e){return f.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,label:a,labelStyle:l,labelShowBg:E,labelBgStyle:c,labelBgPadding:d,labelBgBorderRadius:T,style:S,sourcePosition:u=se.Bottom,targetPosition:R=se.Top,markerEnd:I,markerStart:N,pathOptions:A,interactionWidth:p})=>{const[O,h,C]=Ai({sourceX:n,sourceY:r,sourcePosition:u,targetX:o,targetY:s,targetPosition:R,borderRadius:A==null?void 0:A.borderRadius,offset:A==null?void 0:A.offset,stepPosition:A==null?void 0:A.stepPosition}),_=e.isInternal?void 0:t;return i.jsx(Go,{id:_,path:O,labelX:h,labelY:C,label:a,labelStyle:l,labelShowBg:E,labelBgStyle:c,labelBgPadding:d,labelBgBorderRadius:T,style:S,markerEnd:I,markerStart:N,interactionWidth:p})})}const sd=od({isInternal:!1}),id=od({isInternal:!0});sd.displayName="SmoothStepEdge";id.displayName="SmoothStepEdgeInternal";function ad(e){return f.memo(({id:t,...n})=>{var o;const r=e.isInternal?void 0:t;return i.jsx(sd,{...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 Vx=ad({isInternal:!1}),ld=ad({isInternal:!0});Vx.displayName="StepEdge";ld.displayName="StepEdgeInternal";function Ed(e){return f.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,label:a,labelStyle:l,labelShowBg:E,labelBgStyle:c,labelBgPadding:d,labelBgBorderRadius:T,style:S,markerEnd:u,markerStart:R,interactionWidth:I})=>{const[N,A,p]=mT({sourceX:n,sourceY:r,targetX:o,targetY:s}),O=e.isInternal?void 0:t;return i.jsx(Go,{id:O,path:N,labelX:A,labelY:p,label:a,labelStyle:l,labelShowBg:E,labelBgStyle:c,labelBgPadding:d,labelBgBorderRadius:T,style:S,markerEnd:u,markerStart:R,interactionWidth:I})})}const Wx=Ed({isInternal:!1}),cd=Ed({isInternal:!0});Wx.displayName="StraightEdge";cd.displayName="StraightEdgeInternal";function Td(e){return f.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,sourcePosition:a=se.Bottom,targetPosition:l=se.Top,label:E,labelStyle:c,labelShowBg:d,labelBgStyle:T,labelBgPadding:S,labelBgBorderRadius:u,style:R,markerEnd:I,markerStart:N,pathOptions:A,interactionWidth:p})=>{const[O,h,C]=LT({sourceX:n,sourceY:r,sourcePosition:a,targetX:o,targetY:s,targetPosition:l,curvature:A==null?void 0:A.curvature}),_=e.isInternal?void 0:t;return i.jsx(Go,{id:_,path:O,labelX:h,labelY:C,label:E,labelStyle:c,labelShowBg:d,labelBgStyle:T,labelBgPadding:S,labelBgBorderRadius:u,style:R,markerEnd:I,markerStart:N,interactionWidth:p})})}const jx=Td({isInternal:!1}),dd=Td({isInternal:!0});jx.displayName="BezierEdge";dd.displayName="BezierEdgeInternal";const AE={default:dd,straight:cd,step:ld,smoothstep:id,simplebezier:rd},IE={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},$x=(e,t,n)=>n===se.Left?e-t:n===se.Right?e+t:e,Xx=(e,t,n)=>n===se.Top?e-t:n===se.Bottom?e+t:e,NE="react-flow__edgeupdater";function OE({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:he([NE,`${NE}-${l}`]),cx:$x(t,r,e),cy:Xx(n,r,e),r,stroke:"transparent",fill:"transparent"})}function Kx({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:r,sourceY:o,targetX:s,targetY:a,sourcePosition:l,targetPosition:E,onReconnect:c,onReconnectStart:d,onReconnectEnd:T,setReconnecting:S,setUpdateHover:u}){const R=fe(),I=(h,C)=>{if(h.button!==0)return;const{autoPanOnConnect:_,domNode:m,connectionMode:M,connectionRadius:y,lib:b,onConnectStart:g,cancelConnection:x,nodeLookup:F,rfId:L,panBy:P,updateConnection:D}=R.getState(),B=C.type==="target",v=(W,k)=>{S(!1),T==null||T(W,n,C.type,k)},U=W=>c==null?void 0:c(n,W),Y=(W,k)=>{S(!0),d==null||d(h,n,C.type),g==null||g(W,k)};Oi.onPointerDown(h.nativeEvent,{autoPanOnConnect:_,connectionMode:M,connectionRadius:y,domNode:m,handleId:C.id,nodeId:C.nodeId,nodeLookup:F,isTarget:B,edgeUpdaterType:C.type,lib:b,flowId:L,cancelConnection:x,panBy:P,isValidConnection:(...W)=>{var k,w;return((w=(k=R.getState()).isValidConnection)==null?void 0:w.call(k,...W))??!0},onConnect:U,onConnectStart:Y,onConnectEnd:(...W)=>{var k,w;return(w=(k=R.getState()).onConnectEnd)==null?void 0:w.call(k,...W)},onReconnectEnd:v,updateConnection:D,getTransform:()=>R.getState().transform,getFromHandle:()=>R.getState().connection.fromHandle,dragThreshold:R.getState().connectionDragThreshold,handleDomNode:h.currentTarget})},N=h=>I(h,{nodeId:n.target,id:n.targetHandle??null,type:"target"}),A=h=>I(h,{nodeId:n.source,id:n.sourceHandle??null,type:"source"}),p=()=>u(!0),O=()=>u(!1);return i.jsxs(i.Fragment,{children:[(e===!0||e==="source")&&i.jsx(OE,{position:l,centerX:r,centerY:o,radius:t,onMouseDown:N,onMouseEnter:p,onMouseOut:O,type:"source"}),(e===!0||e==="target")&&i.jsx(OE,{position:E,centerX:s,centerY:a,radius:t,onMouseDown:A,onMouseEnter:p,onMouseOut:O,type:"target"})]})}function zx({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:r,onClick:o,onDoubleClick:s,onContextMenu:a,onMouseEnter:l,onMouseMove:E,onMouseLeave:c,reconnectRadius:d,onReconnect:T,onReconnectStart:S,onReconnectEnd:u,rfId:R,edgeTypes:I,noPanClassName:N,onError:A,disableKeyboardA11y:p}){let O=ue(ne=>ne.edgeLookup.get(e));const h=ue(ne=>ne.defaultEdgeOptions);O=h?{...h,...O}:O;let C=O.type||"default",_=(I==null?void 0:I[C])||AE[C];_===void 0&&(A==null||A("011",at.error011(C)),C="default",_=(I==null?void 0:I.default)||AE.default);const m=!!(O.focusable||t&&typeof O.focusable>"u"),M=typeof T<"u"&&(O.reconnectable||n&&typeof O.reconnectable>"u"),y=!!(O.selectable||r&&typeof O.selectable>"u"),b=f.useRef(null),[g,x]=f.useState(!1),[F,L]=f.useState(!1),P=fe(),{zIndex:D,sourceX:B,sourceY:v,targetX:U,targetY:Y,sourcePosition:W,targetPosition:k}=ue(f.useCallback(ne=>{const oe=ne.nodeLookup.get(O.source),Te=ne.nodeLookup.get(O.target);if(!oe||!Te)return{zIndex:O.zIndex,...IE};const Ie=Hm({id:e,sourceNode:oe,targetNode:Te,sourceHandle:O.sourceHandle||null,targetHandle:O.targetHandle||null,connectionMode:ne.connectionMode,onError:A});return{zIndex:Pm({selected:O.selected,zIndex:O.zIndex,sourceNode:oe,targetNode:Te,elevateOnSelect:ne.elevateEdgesOnSelect,zIndexMode:ne.zIndexMode}),...Ie||IE}},[O.source,O.target,O.sourceHandle,O.targetHandle,O.selected,O.zIndex]),Oe),w=f.useMemo(()=>O.markerStart?`url('#${Ii(O.markerStart,R)}')`:void 0,[O.markerStart,R]),z=f.useMemo(()=>O.markerEnd?`url('#${Ii(O.markerEnd,R)}')`:void 0,[O.markerEnd,R]);if(O.hidden||B===null||v===null||U===null||Y===null)return null;const q=ne=>{var de;const{addSelectedEdges:oe,unselectNodesAndEdges:Te,multiSelectionActive:Ie}=P.getState();y&&(P.setState({nodesSelectionActive:!1}),O.selected&&Ie?(Te({nodes:[],edges:[O]}),(de=b.current)==null||de.blur()):oe([e])),o&&o(ne,O)},Z=s?ne=>{s(ne,{...O})}:void 0,K=a?ne=>{a(ne,{...O})}:void 0,H=l?ne=>{l(ne,{...O})}:void 0,J=E?ne=>{E(ne,{...O})}:void 0,V=c?ne=>{c(ne,{...O})}:void 0,ee=ne=>{var oe;if(!p&&ET.includes(ne.key)&&y){const{unselectNodesAndEdges:Te,addSelectedEdges:Ie}=P.getState();ne.key==="Escape"?((oe=b.current)==null||oe.blur(),Te({edges:[O]})):Ie([e])}};return i.jsx("svg",{style:{zIndex:D},children:i.jsxs("g",{className:he(["react-flow__edge",`react-flow__edge-${C}`,O.className,N,{selected:O.selected,animated:O.animated,inactive:!y&&!o,updating:g,selectable:y}]),onClick:q,onDoubleClick:Z,onContextMenu:K,onMouseEnter:H,onMouseMove:J,onMouseLeave:V,onKeyDown:m?ee:void 0,tabIndex:m?0:void 0,role:O.ariaRole??(m?"group":"img"),"aria-roledescription":"edge","data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":O.ariaLabel===null?void 0:O.ariaLabel||`Edge from ${O.source} to ${O.target}`,"aria-describedby":m?`${YT}-${R}`:void 0,ref:b,...O.domAttributes,children:[!F&&i.jsx(_,{id:e,source:O.source,target:O.target,type:O.type,selected:O.selected,animated:O.animated,selectable:y,deletable:O.deletable??!0,label:O.label,labelStyle:O.labelStyle,labelShowBg:O.labelShowBg,labelBgStyle:O.labelBgStyle,labelBgPadding:O.labelBgPadding,labelBgBorderRadius:O.labelBgBorderRadius,sourceX:B,sourceY:v,targetX:U,targetY:Y,sourcePosition:W,targetPosition:k,data:O.data,style:O.style,sourceHandleId:O.sourceHandle,targetHandleId:O.targetHandle,markerStart:w,markerEnd:z,pathOptions:"pathOptions"in O?O.pathOptions:void 0,interactionWidth:O.interactionWidth}),M&&i.jsx(Kx,{edge:O,isReconnectable:M,reconnectRadius:d,onReconnect:T,onReconnectStart:S,onReconnectEnd:u,sourceX:B,sourceY:v,targetX:U,targetY:Y,sourcePosition:W,targetPosition:k,setUpdateHover:x,setReconnecting:L})]})})}var Jx=f.memo(zx);const qx=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function Sd({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:r,noPanClassName:o,onReconnect:s,onEdgeContextMenu:a,onEdgeMouseEnter:l,onEdgeMouseMove:E,onEdgeMouseLeave:c,onEdgeClick:d,reconnectRadius:T,onEdgeDoubleClick:S,onReconnectStart:u,onReconnectEnd:R,disableKeyboardA11y:I}){const{edgesFocusable:N,edgesReconnectable:A,elementsSelectable:p,onError:O}=ue(qx,Oe),h=vx(t);return i.jsxs("div",{className:"react-flow__edges",children:[i.jsx(Hx,{defaultColor:e,rfId:n}),h.map(C=>i.jsx(Jx,{id:C,edgesFocusable:N,edgesReconnectable:A,elementsSelectable:p,noPanClassName:o,onReconnect:s,onContextMenu:a,onMouseEnter:l,onMouseMove:E,onMouseLeave:c,onClick:d,reconnectRadius:T,onDoubleClick:S,onReconnectStart:u,onReconnectEnd:R,rfId:n,onError:O,edgeTypes:r,disableKeyboardA11y:I},C))]})}Sd.displayName="EdgeRenderer";const Qx=f.memo(Sd),Zx=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function ey({children:e}){const t=ue(Zx);return i.jsx("div",{className:"react-flow__viewport xyflow__viewport react-flow__container",style:{transform:t},children:e})}function ty(e){const t=zi(),n=f.useRef(!1);f.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const ny=e=>{var t;return(t=e.panZoom)==null?void 0:t.syncViewport};function ry(e){const t=ue(ny),n=fe();return f.useEffect(()=>{e&&(t==null||t(e),n.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function oy(e){return e.connection.inProgress?{...e.connection,to:ir(e.connection.to,e.transform)}:{...e.connection}}function sy(e){return oy}function iy(e){const t=sy();return ue(t,Oe)}const ay=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function ly({containerStyle:e,style:t,type:n,component:r}){const{nodesConnectable:o,width:s,height:a,isValid:l,inProgress:E}=ue(ay,Oe);return!(s&&o&&E)?null:i.jsx("svg",{style:e,width:s,height:a,className:"react-flow__connectionline react-flow__container",children:i.jsx("g",{className:he(["react-flow__connection",dT(l)]),children:i.jsx(ud,{style:t,type:n,CustomComponent:r,isValid:l})})})}const ud=({style:e,type:t=Lt.Bezier,CustomComponent:n,isValid:r})=>{const{inProgress:o,from:s,fromNode:a,fromHandle:l,fromPosition:E,to:c,toNode:d,toHandle:T,toPosition:S,pointer:u}=iy();if(!o)return;if(n)return i.jsx(n,{connectionLineType:t,connectionLineStyle:e,fromNode:a,fromHandle:l,fromX:s.x,fromY:s.y,toX:c.x,toY:c.y,fromPosition:E,toPosition:S,connectionStatus:dT(r),toNode:d,toHandle:T,pointer:u});let R="";const I={sourceX:s.x,sourceY:s.y,sourcePosition:E,targetX:c.x,targetY:c.y,targetPosition:S};switch(t){case Lt.Bezier:[R]=LT(I);break;case Lt.SimpleBezier:[R]=td(I);break;case Lt.Step:[R]=Ai({...I,borderRadius:0});break;case Lt.SmoothStep:[R]=Ai(I);break;default:[R]=mT(I)}return i.jsx("path",{d:R,fill:"none",className:"react-flow__connection-path",style:e})};ud.displayName="ConnectionLine";const Ey={};function fE(e=Ey){f.useRef(e),fe(),f.useEffect(()=>{},[e])}function cy(){fe(),f.useRef(!1),f.useEffect(()=>{},[])}function Rd({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:r,onEdgeClick:o,onNodeDoubleClick:s,onEdgeDoubleClick:a,onNodeMouseEnter:l,onNodeMouseMove:E,onNodeMouseLeave:c,onNodeContextMenu:d,onSelectionContextMenu:T,onSelectionStart:S,onSelectionEnd:u,connectionLineType:R,connectionLineStyle:I,connectionLineComponent:N,connectionLineContainerStyle:A,selectionKeyCode:p,selectionOnDrag:O,selectionMode:h,multiSelectionKeyCode:C,panActivationKeyCode:_,zoomActivationKeyCode:m,deleteKeyCode:M,onlyRenderVisibleElements:y,elementsSelectable:b,defaultViewport:g,translateExtent:x,minZoom:F,maxZoom:L,preventScrolling:P,defaultMarkerColor:D,zoomOnScroll:B,zoomOnPinch:v,panOnScroll:U,panOnScrollSpeed:Y,panOnScrollMode:W,zoomOnDoubleClick:k,panOnDrag:w,onPaneClick:z,onPaneMouseEnter:q,onPaneMouseMove:Z,onPaneMouseLeave:K,onPaneScroll:H,onPaneContextMenu:J,paneClickDistance:V,nodeClickDistance:ee,onEdgeContextMenu:ne,onEdgeMouseEnter:oe,onEdgeMouseMove:Te,onEdgeMouseLeave:Ie,reconnectRadius:de,onReconnect:Ne,onReconnectStart:Fe,onReconnectEnd:be,noDragClassName:je,noWheelClassName:tt,noPanClassName:Et,disableKeyboardA11y:nt,nodeExtent:Ot,rfId:Ge,viewport:$e,onViewportChange:Ue}){return fE(e),fE(t),cy(),ty(n),ry($e),i.jsx(_x,{onPaneClick:z,onPaneMouseEnter:q,onPaneMouseMove:Z,onPaneMouseLeave:K,onPaneContextMenu:J,onPaneScroll:H,paneClickDistance:V,deleteKeyCode:M,selectionKeyCode:p,selectionOnDrag:O,selectionMode:h,onSelectionStart:S,onSelectionEnd:u,multiSelectionKeyCode:C,panActivationKeyCode:_,zoomActivationKeyCode:m,elementsSelectable:b,zoomOnScroll:B,zoomOnPinch:v,zoomOnDoubleClick:k,panOnScroll:U,panOnScrollSpeed:Y,panOnScrollMode:W,panOnDrag:w,defaultViewport:g,translateExtent:x,minZoom:F,maxZoom:L,onSelectionContextMenu:T,preventScrolling:P,noDragClassName:je,noWheelClassName:tt,noPanClassName:Et,disableKeyboardA11y:nt,onViewportChange:Ue,isControlledViewport:!!$e,children:i.jsxs(ey,{children:[i.jsx(Qx,{edgeTypes:t,onEdgeClick:o,onEdgeDoubleClick:a,onReconnect:Ne,onReconnectStart:Fe,onReconnectEnd:be,onlyRenderVisibleElements:y,onEdgeContextMenu:ne,onEdgeMouseEnter:oe,onEdgeMouseMove:Te,onEdgeMouseLeave:Ie,reconnectRadius:de,defaultMarkerColor:D,noPanClassName:Et,disableKeyboardA11y:nt,rfId:Ge}),i.jsx(ly,{style:I,type:R,component:N,containerStyle:A}),i.jsx("div",{className:"react-flow__edgelabel-renderer"}),i.jsx(Ux,{nodeTypes:e,onNodeClick:r,onNodeDoubleClick:s,onNodeMouseEnter:l,onNodeMouseMove:E,onNodeMouseLeave:c,onNodeContextMenu:d,nodeClickDistance:ee,onlyRenderVisibleElements:y,noPanClassName:Et,noDragClassName:je,disableKeyboardA11y:nt,nodeExtent:Ot,rfId:Ge}),i.jsx("div",{className:"react-flow__viewport-portal"})]})})}Rd.displayName="GraphView";const Ty=f.memo(Rd),pE=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:s,fitView:a,fitViewOptions:l,minZoom:E=.5,maxZoom:c=2,nodeOrigin:d,nodeExtent:T,zIndexMode:S="basic"}={})=>{const u=new Map,R=new Map,I=new Map,N=new Map,A=r??t??[],p=n??e??[],O=d??[0,0],h=T??Xn;yT(I,N,A);const C=Ni(p,u,R,{nodeOrigin:O,nodeExtent:h,zIndexMode:S});let _=[0,0,1];if(a&&o&&s){const m=or(u,{filter:g=>!!((g.width||g.initialWidth)&&(g.height||g.initialHeight))}),{x:M,y,zoom:b}=ki(m,o,s,E,c,(l==null?void 0:l.padding)??.1);_=[M,y,b]}return{rfId:"1",width:o??0,height:s??0,transform:_,nodes:p,nodesInitialized:C,nodeLookup:u,parentLookup:R,edges:A,edgeLookup:N,connectionLookup:I,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:n!==void 0,hasDefaultEdges:r!==void 0,panZoom:null,minZoom:E,maxZoom:c,translateExtent:Xn,nodeExtent:h,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:dn.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:O,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:{...TT},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:mm,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:"react",debug:!1,ariaLabelConfig:cT,zIndexMode:S,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}},dy=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:s,fitView:a,fitViewOptions:l,minZoom:E,maxZoom:c,nodeOrigin:d,nodeExtent:T,zIndexMode:S})=>Dg((u,R)=>{async function I(){const{nodeLookup:N,panZoom:A,fitViewOptions:p,fitViewResolver:O,width:h,height:C,minZoom:_,maxZoom:m}=R();A&&(await Lm({nodes:N,width:h,height:C,panZoom:A,minZoom:_,maxZoom:m},p),O==null||O.resolve(!0),u({fitViewResolver:null}))}return{...pE({nodes:e,edges:t,width:o,height:s,fitView:a,fitViewOptions:l,minZoom:E,maxZoom:c,nodeOrigin:d,nodeExtent:T,defaultNodes:n,defaultEdges:r,zIndexMode:S}),setNodes:N=>{const{nodeLookup:A,parentLookup:p,nodeOrigin:O,elevateNodesOnSelect:h,fitViewQueued:C,zIndexMode:_}=R(),m=Ni(N,A,p,{nodeOrigin:O,nodeExtent:T,elevateNodesOnSelect:h,checkEquality:!0,zIndexMode:_});C&&m?(I(),u({nodes:N,nodesInitialized:m,fitViewQueued:!1,fitViewOptions:void 0})):u({nodes:N,nodesInitialized:m})},setEdges:N=>{const{connectionLookup:A,edgeLookup:p}=R();yT(A,p,N),u({edges:N})},setDefaultNodesAndEdges:(N,A)=>{if(N){const{setNodes:p}=R();p(N),u({hasDefaultNodes:!0})}if(A){const{setEdges:p}=R();p(A),u({hasDefaultEdges:!0})}},updateNodeInternals:N=>{const{triggerNodeChanges:A,nodeLookup:p,parentLookup:O,domNode:h,nodeOrigin:C,nodeExtent:_,debug:m,fitViewQueued:M,zIndexMode:y}=R(),{changes:b,updatedInternals:g}=Km(N,p,O,h,C,_,y);g&&(Wm(p,O,{nodeOrigin:C,nodeExtent:_,zIndexMode:y}),M?(I(),u({fitViewQueued:!1,fitViewOptions:void 0})):u({}),(b==null?void 0:b.length)>0&&(m&&console.log("React Flow: trigger node changes",b),A==null||A(b)))},updateNodePositions:(N,A=!1)=>{const p=[];let O=[];const{nodeLookup:h,triggerNodeChanges:C,connection:_,updateConnection:m,onNodesChangeMiddlewareMap:M}=R();for(const[y,b]of N){const g=h.get(y),x=!!(g!=null&&g.expandParent&&(g!=null&&g.parentId)&&(b!=null&&b.position)),F={id:y,type:"position",position:x?{x:Math.max(0,b.position.x),y:Math.max(0,b.position.y)}:b.position,dragging:A};if(g&&_.inProgress&&_.fromNode.id===g.id){const L=Wt(g,_.fromHandle,se.Left,!0);m({..._,from:L})}x&&g.parentId&&p.push({id:y,parentId:g.parentId,rect:{...b.internals.positionAbsolute,width:b.measured.width??0,height:b.measured.height??0}}),O.push(F)}if(p.length>0){const{parentLookup:y,nodeOrigin:b}=R(),g=Ki(p,h,y,b);O.push(...g)}for(const y of M.values())O=y(O);C(O)},triggerNodeChanges:N=>{const{onNodesChange:A,setNodes:p,nodes:O,hasDefaultNodes:h,debug:C}=R();if(N!=null&&N.length){if(h){const _=WT(N,O);p(_)}C&&console.log("React Flow: trigger node changes",N),A==null||A(N)}},triggerEdgeChanges:N=>{const{onEdgesChange:A,setEdges:p,edges:O,hasDefaultEdges:h,debug:C}=R();if(N!=null&&N.length){if(h){const _=jT(N,O);p(_)}C&&console.log("React Flow: trigger edge changes",N),A==null||A(N)}},addSelectedNodes:N=>{const{multiSelectionActive:A,edgeLookup:p,nodeLookup:O,triggerNodeChanges:h,triggerEdgeChanges:C}=R();if(A){const _=N.map(m=>Ut(m,!0));h(_);return}h(rn(O,new Set([...N]),!0)),C(rn(p))},addSelectedEdges:N=>{const{multiSelectionActive:A,edgeLookup:p,nodeLookup:O,triggerNodeChanges:h,triggerEdgeChanges:C}=R();if(A){const _=N.map(m=>Ut(m,!0));C(_);return}C(rn(p,new Set([...N]))),h(rn(O,new Set,!0))},unselectNodesAndEdges:({nodes:N,edges:A}={})=>{const{edges:p,nodes:O,nodeLookup:h,triggerNodeChanges:C,triggerEdgeChanges:_}=R(),m=N||O,M=A||p,y=[];for(const g of m){if(!g.selected)continue;const x=h.get(g.id);x&&(x.selected=!1),y.push(Ut(g.id,!1))}const b=[];for(const g of M)g.selected&&b.push(Ut(g.id,!1));C(y),_(b)},setMinZoom:N=>{const{panZoom:A,maxZoom:p}=R();A==null||A.setScaleExtent([N,p]),u({minZoom:N})},setMaxZoom:N=>{const{panZoom:A,minZoom:p}=R();A==null||A.setScaleExtent([p,N]),u({maxZoom:N})},setTranslateExtent:N=>{var A;(A=R().panZoom)==null||A.setTranslateExtent(N),u({translateExtent:N})},resetSelectedElements:()=>{const{edges:N,nodes:A,triggerNodeChanges:p,triggerEdgeChanges:O,elementsSelectable:h}=R();if(!h)return;const C=A.reduce((m,M)=>M.selected?[...m,Ut(M.id,!1)]:m,[]),_=N.reduce((m,M)=>M.selected?[...m,Ut(M.id,!1)]:m,[]);p(C),O(_)},setNodeExtent:N=>{const{nodes:A,nodeLookup:p,parentLookup:O,nodeOrigin:h,elevateNodesOnSelect:C,nodeExtent:_,zIndexMode:m}=R();N[0][0]===_[0][0]&&N[0][1]===_[0][1]&&N[1][0]===_[1][0]&&N[1][1]===_[1][1]||(Ni(A,p,O,{nodeOrigin:h,nodeExtent:N,elevateNodesOnSelect:C,checkEquality:!1,zIndexMode:m}),u({nodeExtent:N}))},panBy:N=>{const{transform:A,width:p,height:O,panZoom:h,translateExtent:C}=R();return zm({delta:N,panZoom:h,transform:A,translateExtent:C,width:p,height:O})},setCenter:async(N,A,p)=>{const{width:O,height:h,maxZoom:C,panZoom:_}=R();if(!_)return Promise.resolve(!1);const m=typeof(p==null?void 0:p.zoom)<"u"?p.zoom:C;return await _.setViewport({x:O/2-N*m,y:h/2-A*m,zoom:m},{duration:p==null?void 0:p.duration,ease:p==null?void 0:p.ease,interpolate:p==null?void 0:p.interpolate}),Promise.resolve(!0)},cancelConnection:()=>{u({connection:{...TT}})},updateConnection:N=>{u({connection:N})},reset:()=>u({...pE()})}},Object.is);function Sy({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:r,initialWidth:o,initialHeight:s,initialMinZoom:a,initialMaxZoom:l,initialFitViewOptions:E,fitView:c,nodeOrigin:d,nodeExtent:T,zIndexMode:S,children:u}){const[R]=f.useState(()=>dy({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:s,fitView:c,minZoom:a,maxZoom:l,fitViewOptions:E,nodeOrigin:d,nodeExtent:T,zIndexMode:S}));return i.jsx(Mg,{value:R,children:i.jsx(ex,{children:u})})}function uy({children:e,nodes:t,edges:n,defaultNodes:r,defaultEdges:o,width:s,height:a,fitView:l,fitViewOptions:E,minZoom:c,maxZoom:d,nodeOrigin:T,nodeExtent:S,zIndexMode:u}){return f.useContext(Bo)?i.jsx(i.Fragment,{children:e}):i.jsx(Sy,{initialNodes:t,initialEdges:n,defaultNodes:r,defaultEdges:o,initialWidth:s,initialHeight:a,fitView:l,initialFitViewOptions:E,initialMinZoom:c,initialMaxZoom:d,nodeOrigin:T,nodeExtent:S,zIndexMode:u,children:e})}const Ry={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0};function Ay({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:o,nodeTypes:s,edgeTypes:a,onNodeClick:l,onEdgeClick:E,onInit:c,onMove:d,onMoveStart:T,onMoveEnd:S,onConnect:u,onConnectStart:R,onConnectEnd:I,onClickConnectStart:N,onClickConnectEnd:A,onNodeMouseEnter:p,onNodeMouseMove:O,onNodeMouseLeave:h,onNodeContextMenu:C,onNodeDoubleClick:_,onNodeDragStart:m,onNodeDrag:M,onNodeDragStop:y,onNodesDelete:b,onEdgesDelete:g,onDelete:x,onSelectionChange:F,onSelectionDragStart:L,onSelectionDrag:P,onSelectionDragStop:D,onSelectionContextMenu:B,onSelectionStart:v,onSelectionEnd:U,onBeforeDelete:Y,connectionMode:W,connectionLineType:k=Lt.Bezier,connectionLineStyle:w,connectionLineComponent:z,connectionLineContainerStyle:q,deleteKeyCode:Z="Backspace",selectionKeyCode:K="Shift",selectionOnDrag:H=!1,selectionMode:J=Kn.Full,panActivationKeyCode:V="Space",multiSelectionKeyCode:ee=qn()?"Meta":"Control",zoomActivationKeyCode:ne=qn()?"Meta":"Control",snapToGrid:oe,snapGrid:Te,onlyRenderVisibleElements:Ie=!1,selectNodesOnDrag:de,nodesDraggable:Ne,autoPanOnNodeFocus:Fe,nodesConnectable:be,nodesFocusable:je,nodeOrigin:tt=kT,edgesFocusable:Et,edgesReconnectable:nt,elementsSelectable:Ot=!0,defaultViewport:Ge=Wg,minZoom:$e=.5,maxZoom:Ue=2,translateExtent:Q=Xn,preventScrolling:Ee=!0,nodeExtent:Re,defaultMarkerColor:Ae="#b1b1b7",zoomOnScroll:ft=!0,zoomOnPinch:De=!0,panOnScroll:pt=!1,panOnScrollSpeed:zt=.5,panOnScrollMode:Mt=wt.Free,zoomOnDoubleClick:Yo=!0,panOnDrag:ko=!0,onPaneClick:hn,onPaneMouseEnter:Vo,onPaneMouseMove:Er,onPaneMouseLeave:Wo,onPaneScroll:we,onPaneContextMenu:cr,paneClickDistance:Tr=1,nodeClickDistance:dr=0,children:jo,onReconnect:$o,onReconnectStart:Sr,onReconnectEnd:Xo,onEdgeContextMenu:Ko,onEdgeDoubleClick:zo,onEdgeMouseEnter:Jo,onEdgeMouseMove:ur,onEdgeMouseLeave:Rr,reconnectRadius:Ar=10,onNodesChange:Ir,onEdgesChange:Nr,noDragClassName:Or="nodrag",noWheelClassName:fr="nowheel",noPanClassName:j="nopan",fitView:ae,fitViewOptions:pe,connectOnClick:Le,attributionPosition:Pt,proOptions:Cn,defaultEdgeOptions:Ln,elevateNodesOnSelect:$d=!0,elevateEdgesOnSelect:Xd=!1,disableKeyboardA11y:na=!1,autoPanOnConnect:Kd,autoPanOnNodeDrag:zd,autoPanSpeed:Jd,connectionRadius:qd,isValidConnection:Qd,onError:Zd,style:eS,id:ra,nodeDragThreshold:tS,connectionDragThreshold:nS,viewport:rS,onViewportChange:oS,width:sS,height:iS,colorMode:aS="light",debug:lS,onScroll:pr,ariaLabelConfig:ES,zIndexMode:oa="basic",...cS},TS){const qo=ra||"1",dS=Kg(aS),SS=f.useCallback(sa=>{sa.currentTarget.scrollTo({top:0,left:0,behavior:"instant"}),pr==null||pr(sa)},[pr]);return i.jsx("div",{"data-testid":"rf__wrapper",...cS,onScroll:SS,style:{...eS,...Ry},ref:TS,className:he(["react-flow",o,dS]),id:ra,role:"application",children:i.jsxs(uy,{nodes:e,edges:t,width:sS,height:iS,fitView:ae,fitViewOptions:pe,minZoom:$e,maxZoom:Ue,nodeOrigin:tt,nodeExtent:Re,zIndexMode:oa,children:[i.jsx(Ty,{onInit:c,onNodeClick:l,onEdgeClick:E,onNodeMouseEnter:p,onNodeMouseMove:O,onNodeMouseLeave:h,onNodeContextMenu:C,onNodeDoubleClick:_,nodeTypes:s,edgeTypes:a,connectionLineType:k,connectionLineStyle:w,connectionLineComponent:z,connectionLineContainerStyle:q,selectionKeyCode:K,selectionOnDrag:H,selectionMode:J,deleteKeyCode:Z,multiSelectionKeyCode:ee,panActivationKeyCode:V,zoomActivationKeyCode:ne,onlyRenderVisibleElements:Ie,defaultViewport:Ge,translateExtent:Q,minZoom:$e,maxZoom:Ue,preventScrolling:Ee,zoomOnScroll:ft,zoomOnPinch:De,zoomOnDoubleClick:Yo,panOnScroll:pt,panOnScrollSpeed:zt,panOnScrollMode:Mt,panOnDrag:ko,onPaneClick:hn,onPaneMouseEnter:Vo,onPaneMouseMove:Er,onPaneMouseLeave:Wo,onPaneScroll:we,onPaneContextMenu:cr,paneClickDistance:Tr,nodeClickDistance:dr,onSelectionContextMenu:B,onSelectionStart:v,onSelectionEnd:U,onReconnect:$o,onReconnectStart:Sr,onReconnectEnd:Xo,onEdgeContextMenu:Ko,onEdgeDoubleClick:zo,onEdgeMouseEnter:Jo,onEdgeMouseMove:ur,onEdgeMouseLeave:Rr,reconnectRadius:Ar,defaultMarkerColor:Ae,noDragClassName:Or,noWheelClassName:fr,noPanClassName:j,rfId:qo,disableKeyboardA11y:na,nodeExtent:Re,viewport:rS,onViewportChange:oS}),i.jsx(Xg,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:u,onConnectStart:R,onConnectEnd:I,onClickConnectStart:N,onClickConnectEnd:A,nodesDraggable:Ne,autoPanOnNodeFocus:Fe,nodesConnectable:be,nodesFocusable:je,edgesFocusable:Et,edgesReconnectable:nt,elementsSelectable:Ot,elevateNodesOnSelect:$d,elevateEdgesOnSelect:Xd,minZoom:$e,maxZoom:Ue,nodeExtent:Re,onNodesChange:Ir,onEdgesChange:Nr,snapToGrid:oe,snapGrid:Te,connectionMode:W,translateExtent:Q,connectOnClick:Le,defaultEdgeOptions:Ln,fitView:ae,fitViewOptions:pe,onNodesDelete:b,onEdgesDelete:g,onDelete:x,onNodeDragStart:m,onNodeDrag:M,onNodeDragStop:y,onSelectionDrag:P,onSelectionDragStart:L,onSelectionDragStop:D,onMove:d,onMoveStart:T,onMoveEnd:S,noPanClassName:j,nodeOrigin:tt,rfId:qo,autoPanOnConnect:Kd,autoPanOnNodeDrag:zd,autoPanSpeed:Jd,onError:Zd,connectionRadius:qd,isValidConnection:Qd,selectNodesOnDrag:de,nodeDragThreshold:tS,connectionDragThreshold:nS,onBeforeDelete:Y,debug:lS,ariaLabelConfig:ES,zIndexMode:oa}),i.jsx(Vg,{onSelectionChange:F}),jo,i.jsx(Gg,{proOptions:Cn,position:Pt}),i.jsx(Fg,{rfId:qo,disableKeyboardA11y:na})]})})}var Iy=$T(Ay);function Ny(e){const[t,n]=f.useState(e),r=f.useCallback(o=>n(s=>WT(o,s)),[]);return[t,n,r]}function Oy(e){const[t,n]=f.useState(e),r=f.useCallback(o=>n(s=>jT(o,s)),[]);return[t,n,r]}function fy({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:he(["react-flow__background-pattern",n,r])})}function py({radius:e,className:t}){return i.jsx("circle",{cx:e,cy:e,r:e,className:he(["react-flow__background-pattern","dots",t])})}var xt;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(xt||(xt={}));const hy={[xt.Dots]:1,[xt.Lines]:1,[xt.Cross]:6},Cy=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function Ad({id:e,variant:t=xt.Dots,gap:n=20,size:r,lineWidth:o=1,offset:s=0,color:a,bgColor:l,style:E,className:c,patternClassName:d}){const T=f.useRef(null),{transform:S,patternId:u}=ue(Cy,Oe),R=r||hy[t],I=t===xt.Dots,N=t===xt.Cross,A=Array.isArray(n)?n:[n,n],p=[A[0]*S[2]||1,A[1]*S[2]||1],O=R*S[2],h=Array.isArray(s)?s:[s,s],C=N?[O,O]:p,_=[h[0]*S[2]||1+C[0]/2,h[1]*S[2]||1+C[1]/2],m=`${u}${e||""}`;return i.jsxs("svg",{className:he(["react-flow__background",c]),style:{...E,...Fo,"--xy-background-color-props":l,"--xy-background-pattern-color-props":a},ref:T,"data-testid":"rf__background",children:[i.jsx("pattern",{id:m,x:S[0]%p[0],y:S[1]%p[1],width:p[0],height:p[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${_[0]},-${_[1]})`,children:I?i.jsx(py,{radius:O/2,className:d}):i.jsx(fy,{dimensions:C,lineWidth:o,variant:t,className:d})}),i.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${m})`})]})}Ad.displayName="Background";const Ly=f.memo(Ad);function _y(){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 my(){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 gy(){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 xy(){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 yy(){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 Yr({children:e,className:t,...n}){return i.jsx("button",{type:"button",className:he(["react-flow__controls-button",t]),...n,children:e})}const Dy=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function Id({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:o,onZoomIn:s,onZoomOut:a,onFitView:l,onInteractiveChange:E,className:c,children:d,position:T="bottom-left",orientation:S="vertical","aria-label":u}){const R=fe(),{isInteractive:I,minZoomReached:N,maxZoomReached:A,ariaLabelConfig:p}=ue(Dy,Oe),{zoomIn:O,zoomOut:h,fitView:C}=zi(),_=()=>{O(),s==null||s()},m=()=>{h(),a==null||a()},M=()=>{C(o),l==null||l()},y=()=>{R.setState({nodesDraggable:!I,nodesConnectable:!I,elementsSelectable:!I}),E==null||E(!I)},b=S==="horizontal"?"horizontal":"vertical";return i.jsxs(ar,{className:he(["react-flow__controls",b,c]),position:T,style:e,"data-testid":"rf__controls","aria-label":u??p["controls.ariaLabel"],children:[t&&i.jsxs(i.Fragment,{children:[i.jsx(Yr,{onClick:_,className:"react-flow__controls-zoomin",title:p["controls.zoomIn.ariaLabel"],"aria-label":p["controls.zoomIn.ariaLabel"],disabled:A,children:i.jsx(_y,{})}),i.jsx(Yr,{onClick:m,className:"react-flow__controls-zoomout",title:p["controls.zoomOut.ariaLabel"],"aria-label":p["controls.zoomOut.ariaLabel"],disabled:N,children:i.jsx(my,{})})]}),n&&i.jsx(Yr,{className:"react-flow__controls-fitview",onClick:M,title:p["controls.fitView.ariaLabel"],"aria-label":p["controls.fitView.ariaLabel"],children:i.jsx(gy,{})}),r&&i.jsx(Yr,{className:"react-flow__controls-interactive",onClick:y,title:p["controls.interactive.ariaLabel"],"aria-label":p["controls.interactive.ariaLabel"],children:I?i.jsx(yy,{}):i.jsx(xy,{})}),d]})}Id.displayName="Controls";const My=f.memo(Id);function Py({id:e,x:t,y:n,width:r,height:o,style:s,color:a,strokeColor:l,strokeWidth:E,className:c,borderRadius:d,shapeRendering:T,selected:S,onClick:u}){const{background:R,backgroundColor:I}=s||{},N=a||R||I;return i.jsx("rect",{className:he(["react-flow__minimap-node",{selected:S},c]),x:t,y:n,rx:d,ry:d,width:r,height:o,style:{fill:N,stroke:l,strokeWidth:E},shapeRendering:T,onClick:u?A=>u(A,e):void 0})}const by=f.memo(Py),Uy=e=>e.nodes.map(t=>t.id),$s=e=>e instanceof Function?e:()=>e;function vy({nodeStrokeColor:e,nodeColor:t,nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:o,nodeComponent:s=by,onClick:a}){const l=ue(Uy,Oe),E=$s(t),c=$s(e),d=$s(n),T=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return i.jsx(i.Fragment,{children:l.map(S=>i.jsx(Fy,{id:S,nodeColorFunc:E,nodeStrokeColorFunc:c,nodeClassNameFunc:d,nodeBorderRadius:r,nodeStrokeWidth:o,NodeComponent:s,onClick:a,shapeRendering:T},S))})}function By({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:r,nodeBorderRadius:o,nodeStrokeWidth:s,shapeRendering:a,NodeComponent:l,onClick:E}){const{node:c,x:d,y:T,width:S,height:u}=ue(R=>{const I=R.nodeLookup.get(e);if(!I)return{node:void 0,x:0,y:0,width:0,height:0};const N=I.internals.userNode,{x:A,y:p}=I.internals.positionAbsolute,{width:O,height:h}=Nt(N);return{node:N,x:A,y:p,width:O,height:h}},Oe);return!c||c.hidden||!NT(c)?null:i.jsx(l,{x:d,y:T,width:S,height:u,style:c.style,selected:!!c.selected,className:r(c),color:t(c),borderRadius:o,strokeColor:n(c),strokeWidth:s,shapeRendering:a,onClick:E,id:c.id})}const Fy=f.memo(By);var Gy=f.memo(vy);const wy=200,Hy=150,Yy=e=>!e.hidden,ky=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?IT(or(e.nodeLookup,{filter:Yy}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}},Vy="react-flow__minimap-desc";function Nd({style:e,className:t,nodeStrokeColor:n,nodeColor:r,nodeClassName:o="",nodeBorderRadius:s=5,nodeStrokeWidth:a,nodeComponent:l,bgColor:E,maskColor:c,maskStrokeColor:d,maskStrokeWidth:T,position:S="bottom-right",onClick:u,onNodeClick:R,pannable:I=!1,zoomable:N=!1,ariaLabel:A,inversePan:p,zoomStep:O=1,offsetScale:h=5}){const C=fe(),_=f.useRef(null),{boundingRect:m,viewBB:M,rfId:y,panZoom:b,translateExtent:g,flowWidth:x,flowHeight:F,ariaLabelConfig:L}=ue(ky,Oe),P=(e==null?void 0:e.width)??wy,D=(e==null?void 0:e.height)??Hy,B=m.width/P,v=m.height/D,U=Math.max(B,v),Y=U*P,W=U*D,k=h*U,w=m.x-(Y-m.width)/2-k,z=m.y-(W-m.height)/2-k,q=Y+k*2,Z=W+k*2,K=`${Vy}-${y}`,H=f.useRef(0),J=f.useRef();H.current=U,f.useEffect(()=>{if(_.current&&b)return J.current=og({domNode:_.current,panZoom:b,getTransform:()=>C.getState().transform,getViewScale:()=>H.current}),()=>{var oe;(oe=J.current)==null||oe.destroy()}},[b]),f.useEffect(()=>{var oe;(oe=J.current)==null||oe.update({translateExtent:g,width:x,height:F,inversePan:p,pannable:I,zoomStep:O,zoomable:N})},[I,N,p,O,g,x,F]);const V=u?oe=>{var de;const[Te,Ie]=((de=J.current)==null?void 0:de.pointer(oe))||[0,0];u(oe,{x:Te,y:Ie})}:void 0,ee=R?f.useCallback((oe,Te)=>{const Ie=C.getState().nodeLookup.get(Te).internals.userNode;R(oe,Ie)},[]):void 0,ne=A??L["minimap.ariaLabel"];return i.jsx(ar,{position:S,style:{...e,"--xy-minimap-background-color-props":typeof E=="string"?E:void 0,"--xy-minimap-mask-background-color-props":typeof c=="string"?c:void 0,"--xy-minimap-mask-stroke-color-props":typeof d=="string"?d:void 0,"--xy-minimap-mask-stroke-width-props":typeof T=="number"?T*U:void 0,"--xy-minimap-node-background-color-props":typeof r=="string"?r:void 0,"--xy-minimap-node-stroke-color-props":typeof n=="string"?n:void 0,"--xy-minimap-node-stroke-width-props":typeof a=="number"?a:void 0},className:he(["react-flow__minimap",t]),"data-testid":"rf__minimap",children:i.jsxs("svg",{width:P,height:D,viewBox:`${w} ${z} ${q} ${Z}`,className:"react-flow__minimap-svg",role:"img","aria-labelledby":K,ref:_,onClick:V,children:[ne&&i.jsx("title",{id:K,children:ne}),i.jsx(Gy,{onClick:ee,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:s,nodeClassName:o,nodeStrokeWidth:a,nodeComponent:l}),i.jsx("path",{className:"react-flow__minimap-mask",d:`M${w-k},${z-k}h${q+k*2}v${Z+k*2}h${-q-k*2}z
543
+ M${M.x},${M.y}h${M.width}v${M.height}h${-M.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}Nd.displayName="MiniMap";const Wy=f.memo(Nd),jy=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,$y={[An.Line]:"right",[An.Handle]:"bottom-right"};function Xy({nodeId:e,position:t,variant:n=An.Handle,className:r,style:o=void 0,children:s,color:a,minWidth:l=10,minHeight:E=10,maxWidth:c=Number.MAX_VALUE,maxHeight:d=Number.MAX_VALUE,keepAspectRatio:T=!1,resizeDirection:S,autoScale:u=!0,shouldResize:R,onResizeStart:I,onResize:N,onResizeEnd:A}){const p=JT(),O=typeof e=="string"?e:p,h=fe(),C=f.useRef(null),_=n===An.Handle,m=ue(f.useCallback(jy(_&&u),[_,u]),Oe),M=f.useRef(null),y=t??$y[n];f.useEffect(()=>{if(!(!C.current||!O))return M.current||(M.current=Ng({domNode:C.current,nodeId:O,getStoreItems:()=>{const{nodeLookup:g,transform:x,snapGrid:F,snapToGrid:L,nodeOrigin:P,domNode:D}=h.getState();return{nodeLookup:g,transform:x,snapGrid:F,snapToGrid:L,nodeOrigin:P,paneDomNode:D}},onChange:(g,x)=>{const{triggerNodeChanges:F,nodeLookup:L,parentLookup:P,nodeOrigin:D}=h.getState(),B=[],v={x:g.x,y:g.y},U=L.get(O);if(U&&U.expandParent&&U.parentId){const Y=U.origin??D,W=g.width??U.measured.width??0,k=g.height??U.measured.height??0,w={id:U.id,parentId:U.parentId,rect:{width:W,height:k,...OT({x:g.x??U.position.x,y:g.y??U.position.y},{width:W,height:k},U.parentId,L,Y)}},z=Ki([w],L,P,D);B.push(...z),v.x=g.x?Math.max(Y[0]*W,g.x):void 0,v.y=g.y?Math.max(Y[1]*k,g.y):void 0}if(v.x!==void 0&&v.y!==void 0){const Y={id:O,type:"position",position:{...v}};B.push(Y)}if(g.width!==void 0&&g.height!==void 0){const W={id:O,type:"dimensions",resizing:!0,setAttributes:S?S==="horizontal"?"width":"height":!0,dimensions:{width:g.width,height:g.height}};B.push(W)}for(const Y of x){const W={...Y,type:"position"};B.push(W)}F(B)},onEnd:({width:g,height:x})=>{const F={id:O,type:"dimensions",resizing:!1,dimensions:{width:g,height:x}};h.getState().triggerNodeChanges([F])}})),M.current.update({controlPosition:y,boundaries:{minWidth:l,minHeight:E,maxWidth:c,maxHeight:d},keepAspectRatio:T,resizeDirection:S,onResizeStart:I,onResize:N,onResizeEnd:A,shouldResize:R}),()=>{var g;(g=M.current)==null||g.destroy()}},[y,l,E,c,d,T,I,N,A,R]);const b=y.split("-");return i.jsx("div",{className:he(["react-flow__resize-control","nodrag",...b,n,r]),ref:C,style:{...o,scale:m,...a&&{[_?"backgroundColor":"borderColor"]:a}},children:s})}f.memo(Xy);var Od=Object.defineProperty,Ky=(e,t,n)=>t in e?Od(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,zy=(e,t)=>{for(var n in t)Od(e,n,{get:t[n],enumerable:!0})},Jy=(e,t,n)=>Ky(e,t+"",n),fd={};zy(fd,{Graph:()=>We,alg:()=>qi,json:()=>hd,version:()=>Zy});var qy=Object.defineProperty,pd=(e,t)=>{for(var n in t)qy(e,n,{get:t[n],enumerable:!0})},We=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,E=!1;typeof e=="object"&&e!==null&&"v"in e?(o=e.v,s=e.w,a=e.name,arguments.length===2&&(l=t,E=!0)):(o=e,s=t,a=r,arguments.length>2&&(l=n,E=!0)),o=""+o,s=""+s,a!==void 0&&(a=""+a);let c=Un(this._isDirected,o,s,a);if(c in this._edgeLabels)return E&&(this._edgeLabels[c]=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[c]=E?l:this._defaultEdgeLabelFn(o,s,a);let d=Qy(this._isDirected,o,s,a);return o=d.v,s=d.w,Object.freeze(d),this._edgeObjs[c]=d,hE(this._preds[s],o),hE(this._sucs[o],s),this._in[s][c]=d,this._out[o][c]=d,this._edgeCount++,this}edge(e,t,n){let r=arguments.length===1?Xs(this._isDirected,e):Un(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?Xs(this._isDirected,e):Un(this._isDirected,e,t,n))in this._edgeLabels}removeEdge(e,t,n){let r=arguments.length===1?Xs(this._isDirected,e):Un(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],CE(this._preds[a],s),CE(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 hE(e,t){e[t]?e[t]++:e[t]=1}function CE(e,t){e[t]!==void 0&&!--e[t]&&delete e[t]}function Un(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 Qy(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 Xs(e,t){return Un(e,t.v,t.w,t.name)}var Zy="4.0.1",hd={};pd(hd,{read:()=>rD,write:()=>eD});function eD(e){let t={options:{directed:e.isDirected(),multigraph:e.isMultigraph(),compound:e.isCompound()},nodes:tD(e),edges:nD(e)},n=e.graph();return n!==void 0&&(t.value=structuredClone(n)),t}function tD(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 nD(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 rD(e){let t=new We(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 qi={};pd(qi,{CycleException:()=>fo,bellmanFord:()=>Cd,components:()=>iD,dijkstra:()=>Oo,dijkstraAll:()=>ED,findCycles:()=>cD,floydWarshall:()=>dD,isAcyclic:()=>uD,postorder:()=>AD,preorder:()=>ID,prim:()=>ND,shortestPaths:()=>OD,tarjan:()=>_d,topsort:()=>md});var oD=()=>1;function Cd(e,t,n,r){return sD(e,String(t),n||oD,r||function(o){return e.outEdges(o)})}function sD(e,t,n,r){let o={},s,a=0,l=e.nodes(),E=function(T){let S=n(T);o[T.v].distance+S<o[T.w].distance&&(o[T.w]={distance:o[T.v].distance+S,predecessor:T.v},s=!0)},c=function(){l.forEach(function(T){r(T).forEach(function(S){let u=S.v===T?S.v:S.w,R=u===S.v?S.w:S.v;E({v:u,w:R})})})};l.forEach(function(T){let S=T===t?0:Number.POSITIVE_INFINITY;o[T]={distance:S,predecessor:""}});let d=l.length;for(let T=1;T<d&&(s=!1,a++,c(),!!s);T++);if(a===d-1&&(s=!1,c(),s))throw new Error("The graph contains a negative weight cycle");return o}function iD(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 Ld=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}},aD=()=>1;function Oo(e,t,n,r){let o=function(s){return e.outEdges(s)};return lD(e,String(t),n||aD,r||o)}function lD(e,t,n,r){let o={},s=new Ld,a,l,E=function(c){let d=c.v!==a?c.v:c.w,T=o[d],S=n(c),u=l.distance+S;if(S<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+c+" Weight: "+S);u<T.distance&&(T.distance=u,T.predecessor=a,s.decrease(d,u))};for(e.nodes().forEach(function(c){let d=c===t?0:Number.POSITIVE_INFINITY;o[c]={distance:d,predecessor:""},s.add(c,d)});s.size()>0&&(a=s.removeMin(),l=o[a],l.distance!==Number.POSITIVE_INFINITY);)r(a).forEach(E);return o}function ED(e,t,n){return e.nodes().reduce(function(r,o){return r[o]=Oo(e,o,t,n),r},{})}function _d(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(E){E in r?r[E].onStack&&(l.lowlink=Math.min(l.lowlink,r[E].index)):(s(E),l.lowlink=Math.min(l.lowlink,r[E].lowlink))}),l.lowlink===l.index){let E=[],c;do c=n.pop(),r[c].onStack=!1,E.push(c);while(a!==c);o.push(E)}}return e.nodes().forEach(function(a){a in r||s(a)}),o}function cD(e){return _d(e).filter(function(t){return t.length>1||t.length===1&&e.hasEdge(t[0],t[0])})}var TD=()=>1;function dD(e,t,n){return SD(e,t||TD,n||function(r){return e.outEdges(r)})}function SD(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,E=t(a);r[s][l]={distance:E,predecessor:s}})}),o.forEach(function(s){let a=r[s];o.forEach(function(l){let E=r[l];o.forEach(function(c){let d=E[s],T=a[c],S=E[c],u=d.distance+T.distance;u<S.distance&&(S.distance=u,S.predecessor=T.predecessor)})})}),r}var fo=class extends Error{constructor(...e){super(...e)}};function md(e){let t={},n={},r=[];function o(s){if(s in n)throw new fo;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 fo;return r}function uD(e){try{md(e)}catch(t){if(t instanceof fo)return!1;throw t}return!0}function RD(e,t,n,r,o){Array.isArray(t)||(t=[t]);let s=(l=>{var E;return(E=e.isDirected()?e.successors(l):e.neighbors(l))!=null?E:[]}),a={};return t.forEach(function(l){if(!e.hasNode(l))throw new Error("Graph does not have node: "+l);o=gd(e,l,n==="post",a,s,r,o)}),o}function gd(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=gd(e,l,n,r,o,s,a)}),n&&(a=s(a,t))),a}function xd(e,t,n){return RD(e,t,n,function(r,o){return r.push(o),r},[])}function AD(e,t){return xd(e,t,"post")}function ID(e,t){return xd(e,t,"pre")}function ND(e,t){let n=new We,r={},o=new Ld,s;function a(E){let c=E.v===s?E.w:E.v,d=o.priority(c);if(d!==void 0){let T=t(E);T<d&&(r[c]=s,o.decrease(c,T))}}if(e.nodeCount()===0)return n;e.nodes().forEach(function(E){o.add(E,Number.POSITIVE_INFINITY),n.setNode(E)}),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 OD(e,t,n,r){return fD(e,t,n,r??(o=>{let s=e.outEdges(o);return s??[]}))}function fD(e,t,n,r){if(n===void 0)return Oo(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 E=0;E<l.length;E++){let c=l[E],d=c.v===s[a]?c.v:c.w,T=d===c.v?c.w:c.v;n({v:d,w:T})<0&&(o=!0)}if(o)return Cd(e,t,n,r)}return Oo(e,t,n,r)}function pn(e,t,n,r){let o=r;for(;e.hasNode(o);)o=Qi(r);return n.dummy=t,e.setNode(o,n),o}function pD(e){let t=new We().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 yd(e){let t=new We({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 LE(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 E,c;return Math.abs(s)*a>Math.abs(o)*l?(s<0&&(l=-l),E=l*o/s,c=l):(o<0&&(a=-a),E=a,c=a*s/o),{x:n+E,y:r+c}}function lr(e){let t=Zn(Md(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 hD(e){let t=e.nodes().map(r=>{let o=e.node(r).rank;return o===void 0?Number.MAX_VALUE:o}),n=st(Math.min,t);e.nodes().forEach(r=>{let o=e.node(r);Object.hasOwn(o,"rank")&&(o.rank-=n)})}function CD(e){let t=e.nodes().map(a=>e.node(a).rank).filter(a=>a!==void 0),n=st(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(E=>e.node(E).rank+=o)})}function _E(e,t,n,r){let o={width:0,height:0};return arguments.length>=4&&(o.rank=n,o.order=r),pn(e,"border",o,t)}function LD(e,t=Dd){let n=[];for(let r=0;r<e.length;r+=t){let o=e.slice(r,r+t);n.push(o)}return n}var Dd=65535;function st(e,t){if(t.length>Dd){let n=LD(t);return e(...n.map(r=>e(...r)))}else return e(...t)}function Md(e){let t=e.nodes().map(n=>{let r=e.node(n).rank;return r===void 0?Number.MIN_VALUE:r});return st(Math.max,t)}function _D(e,t){let n={lhs:[],rhs:[]};return e.forEach(r=>{t(r)?n.lhs.push(r):n.rhs.push(r)}),n}function Pd(e,t){let n=Date.now();try{return t()}finally{console.log(e+" time: "+(Date.now()-n)+"ms")}}function bd(e,t){return t()}var mD=0;function Qi(e){let t=++mD;return e+(""+t)}function Zn(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 po(e,t){let n={};for(let r of t)e[r]!==void 0&&(n[r]=e[r]);return n}function wo(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 gD(e,t){return e.reduce((n,r,o)=>(n[r]=t[o],n),{})}var Ho="\0",xD="3.0.0",yD=class{constructor(){Jy(this,"_sentinel");let e={};e._next=e._prev=e,this._sentinel=e}dequeue(){let e=this._sentinel,t=e._prev;if(t!==e)return mE(t),t}enqueue(e){let t=this._sentinel;e._prev&&e._next&&mE(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,DD)),n=n._prev;return"["+e.join(", ")+"]"}};function mE(e){e._prev._next=e._next,e._next._prev=e._prev,delete e._next,delete e._prev}function DD(e,t){if(e!=="_next"&&e!=="_prev")return t}var MD=yD,PD=()=>1;function bD(e,t){if(e.nodeCount()<=1)return[];let n=vD(e,t||PD);return UD(n.graph,n.buckets,n.zeroIdx).flatMap(r=>e.outEdges(r.v,r.w)||[])}function UD(e,t,n){var r;let o=[],s=t[t.length-1],a=t[0],l;for(;e.nodeCount();){for(;l=a.dequeue();)Ks(e,t,n,l);for(;l=s.dequeue();)Ks(e,t,n,l);if(e.nodeCount()){for(let E=t.length-2;E>0;--E)if(l=(r=t[E])==null?void 0:r.dequeue(),l){o=o.concat(Ks(e,t,n,l,!0)||[]);break}}}return o}function Ks(e,t,n,r,o){let s=[],a=o?s:void 0;return(e.inEdges(r.v)||[]).forEach(l=>{let E=e.edge(l),c=e.node(l.v);o&&s.push({v:l.v,w:l.w}),c.out-=E,pi(t,n,c)}),(e.outEdges(r.v)||[]).forEach(l=>{let E=e.edge(l),c=l.w,d=e.node(c);d.in-=E,pi(t,n,d)}),e.removeNode(r.v),a}function vD(e,t){let n=new We,r=0,o=0;e.nodes().forEach(l=>{n.setNode(l,{v:l,in:0,out:0})}),e.edges().forEach(l=>{let E=n.edge(l.v,l.w)||0,c=t(l),d=E+c;n.setEdge(l.v,l.w,d);let T=n.node(l.v),S=n.node(l.w);o=Math.max(o,T.out+=c),r=Math.max(r,S.in+=c)});let s=BD(o+r+3).map(()=>new MD),a=r+1;return n.nodes().forEach(l=>{pi(s,a,n.node(l))}),{graph:n,buckets:s,zeroIdx:a}}function pi(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 BD(e){let t=[];for(let n=0;n<e;n++)t.push(n);return t}function FD(e){(e.graph().acyclicer==="greedy"?bD(e,t(e)):GD(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,Qi("rev"))});function t(n){return r=>n.edge(r).weight}}function GD(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 wD(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 HD(e){e.graph().dummyChains=[],e.edges().forEach(t=>YD(e,t))}function YD(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),E=l.labelRank;if(s===r+1)return;e.removeEdge(t);let c,d,T;for(T=0,++r;r<s;++T,++r)l.points=[],d={width:0,height:0,edgeLabel:l,edgeObj:t,rank:r},c=pn(e,"edge",d,"_d"),r===E&&(d.width=l.width,d.height=l.height,d.dummy="edge-label",d.labelpos=l.labelpos),e.setEdge(n,c,{weight:l.weight},a),T===0&&e.graph().dummyChains.push(c),n=c;e.setEdge(n,o,{weight:l.weight},a)}function kD(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 Zi(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(E=>E==null?Number.POSITIVE_INFINITY:n(E.w)-e.edge(E).minlen):[],l=st(Math.min,a);return l===Number.POSITIVE_INFINITY&&(l=0),o.rank=l}e.sources().forEach(n)}function Nn(e,t){return e.node(t.w).rank-e.node(t.v).rank-e.edge(t).minlen}var Ud=VD;function VD(e){let t=new We({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(;WD(t,e)<o&&(s=jD(t,e),!!s);)a=t.hasNode(s.v)?Nn(e,s):-Nn(e,s),$D(t,e,a);return t}function WD(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)&&!Nn(t,s)&&(e.setNode(l,{}),e.setEdge(r,l,{}),n(l))})}return e.nodes().forEach(n),e.nodeCount()}function jD(e,t){return t.edges().reduce((n,r)=>{let o=Number.POSITIVE_INFINITY;return e.hasNode(r.v)!==e.hasNode(r.w)&&(o=Nn(t,r)),o<n[0]?[o,r]:n},[Number.POSITIVE_INFINITY,null])[1]}function $D(e,t,n){e.nodes().forEach(r=>t.node(r).rank+=n)}var{preorder:XD,postorder:KD}=qi,zD=Kt;Kt.initLowLimValues=ta;Kt.initCutValues=ea;Kt.calcCutValue=vd;Kt.leaveEdge=Fd;Kt.enterEdge=Gd;Kt.exchangeEdges=wd;function Kt(e){e=pD(e),Zi(e);let t=Ud(e);ta(t),ea(t,e);let n,r;for(;n=Fd(t);)r=Gd(t,e,n),wd(t,e,n,r)}function ea(e,t){let n=KD(e,e.nodes());n=n.slice(0,n.length-1),n.forEach(r=>JD(e,t,r))}function JD(e,t,n){let r=e.node(n).parent,o=e.edge(n,r);o.cutvalue=vd(e,t,n)}function vd(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(E=>{let c=E.v===n,d=c?E.w:E.v;if(d!==r){let T=c===o,S=t.edge(E).weight;if(a+=T?S:-S,QD(e,n,d)){let u=e.edge(n,d).cutvalue;a+=T?-u:u}}}),a}function ta(e,t){arguments.length<2&&(t=e.nodes()[0]),Bd(e,{},1,t)}function Bd(e,t,n,r,o){let s=n,a=e.node(r);t[r]=!0;let l=e.neighbors(r);return l&&l.forEach(E=>{Object.hasOwn(t,E)||(n=Bd(e,t,n,E,r))}),a.low=s,a.lim=n++,o?a.parent=o:delete a.parent,n}function Fd(e){return e.edges().find(t=>e.edge(t).cutvalue<0)}function Gd(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,E=!1;return s.lim>a.lim&&(l=a,E=!0),t.edges().filter(c=>E===gE(e,e.node(c.v),l)&&E!==gE(e,e.node(c.w),l)).reduce((c,d)=>Nn(t,d)<Nn(t,c)?d:c)}function wd(e,t,n,r){let o=n.v,s=n.w;e.removeEdge(o,s),e.setEdge(r.v,r.w,{}),ta(e),ea(e,t),qD(e,t)}function qD(e,t){let n=e.nodes().find(o=>!e.node(o).parent);if(!n)return;let r=XD(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 QD(e,t,n){return e.hasEdge(t,n)}function gE(e,t,n){return n.low<=t.lim&&t.lim<=n.lim}var ZD=e0;function e0(e){let t=e.graph().ranker;if(typeof t=="function")return t(e);switch(t){case"network-simplex":xE(e);break;case"tight-tree":n0(e);break;case"longest-path":t0(e);break;case"none":break;default:xE(e)}}var t0=Zi;function n0(e){Zi(e),Ud(e)}function xE(e){zD(e)}var r0=o0;function o0(e){let t=i0(e);e.graph().dummyChains.forEach(n=>{let r=e.node(n),o=r.edgeObj,s=s0(e,t,o.v,o.w),a=s.path,l=s.lca,E=0,c=a[E],d=!0;for(;n!==o.w;){if(r=e.node(n),d){for(;(c=a[E])!==l&&e.node(c).maxRank<r.rank;)E++;c===l&&(d=!1)}if(!d){for(;E<a.length-1&&e.node(a[E+1]).minRank<=r.rank;)E++;c=a[E]}c!==void 0&&e.setParent(n,c),n=e.successors(n)[0]}})}function s0(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),E;E=n;do E=e.parent(E),o.push(E);while(E&&(t[E].low>a||l>t[E].lim));let c=E,d=r;for(;(d=e.parent(d))!==c;)s.push(d);return{path:o.concat(s.reverse()),lca:c}}function i0(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(Ho).forEach(r),t}function a0(e){let t=pn(e,"root",{},"_root"),n=l0(e),r=Object.values(n),o=st(Math.max,r)-1,s=2*o+1;e.graph().nestingRoot=t,e.edges().forEach(l=>e.edge(l).minlen*=s);let a=E0(e)+1;e.children(Ho).forEach(l=>Hd(e,t,s,a,o,n,l)),e.graph().nodeRankFactor=s}function Hd(e,t,n,r,o,s,a){var l;let E=e.children(a);if(!E.length){a!==t&&e.setEdge(t,a,{weight:0,minlen:n});return}let c=_E(e,"_bt"),d=_E(e,"_bb"),T=e.node(a);e.setParent(c,a),T.borderTop=c,e.setParent(d,a),T.borderBottom=d,E.forEach(S=>{var u;Hd(e,t,n,r,o,s,S);let R=e.node(S),I=R.borderTop?R.borderTop:S,N=R.borderBottom?R.borderBottom:S,A=R.borderTop?r:2*r,p=I!==N?1:o-((u=s[a])!=null?u:0)+1;e.setEdge(c,I,{weight:A,minlen:p,nestingEdge:!0}),e.setEdge(N,d,{weight:A,minlen:p,nestingEdge:!0})}),e.parent(a)||e.setEdge(t,c,{weight:0,minlen:o+((l=s[a])!=null?l:0)})}function l0(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(Ho).forEach(r=>n(r,1)),t}function E0(e){return e.edges().reduce((t,n)=>t+e.edge(n).weight,0)}function c0(e){let t=e.graph();e.removeNode(t.nestingRoot),delete t.nestingRoot,e.edges().forEach(n=>{e.edge(n).nestingEdge&&e.removeEdge(n)})}var T0=d0;function d0(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)yE(e,"borderLeft","_bl",n,o,s),yE(e,"borderRight","_br",n,o,s)}}e.children(Ho).forEach(t)}function yE(e,t,n,r,o,s){let a={width:0,height:0,rank:s,borderType:t},l=o[t][s-1],E=pn(e,"border",a,n);o[t][s]=E,e.setParent(E,r),l&&e.setEdge(l,E,{weight:1})}function S0(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="lr"||n==="rl")&&Yd(e)}function u0(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="bt"||n==="rl")&&R0(e),(n==="lr"||n==="rl")&&(A0(e),Yd(e))}function Yd(e){e.nodes().forEach(t=>DE(e.node(t))),e.edges().forEach(t=>DE(e.edge(t)))}function DE(e){let t=e.width;e.width=e.height,e.height=t}function R0(e){e.nodes().forEach(t=>zs(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(zs),Object.hasOwn(r,"y")&&zs(r)})}function zs(e){e.y=-e.y}function A0(e){e.nodes().forEach(t=>Js(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(Js),Object.hasOwn(r,"x")&&Js(r)})}function Js(e){let t=e.x;e.x=e.y,e.y=t}function I0(e){let t={},n=e.nodes().filter(l=>!e.children(l).length),r=n.map(l=>e.node(l).rank),o=st(Math.max,r),s=Zn(o+1).map(()=>[]);function a(l){if(t[l])return;t[l]=!0;let E=e.node(l);s[E.rank].push(l);let c=e.successors(l);c&&c.forEach(a)}return n.sort((l,E)=>e.node(l).rank-e.node(E).rank).forEach(a),s}function N0(e,t){let n=0;for(let r=1;r<t.length;++r)n+=O0(e,t[r-1],t[r]);return n}function O0(e,t,n){let r=gD(n,n.map((c,d)=>d)),o=t.flatMap(c=>{let d=e.outEdges(c);return d?d.map(T=>({pos:r[T.w],weight:e.edge(T).weight})).sort((T,S)=>T.pos-S.pos):[]}),s=1;for(;s<n.length;)s<<=1;let a=2*s-1;s-=1;let l=new Array(a).fill(0),E=0;return o.forEach(c=>{let d=c.pos+s;l[d]+=c.weight;let T=0;for(;d>0;)d%2&&(T+=l[d+1]),d=d-1>>1,l[d]+=c.weight;E+=c.weight*T}),E}function f0(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),E=e.node(a.v);return{sum:s.sum+l.weight*E.order,weight:s.weight+l.weight}},{sum:0,weight:0});return{v:n,barycenter:o.sum/o.weight,weight:o.weight}}})}function p0(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 h0(r)}function h0(e){let t=[];function n(o){return s=>{s.merged||(s.barycenter===void 0||o.barycenter===void 0||s.barycenter>=o.barycenter)&&C0(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=>po(o,["vs","i","barycenter","weight"]))}function C0(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 L0(e,t){let n=_D(e,d=>Object.hasOwn(d,"barycenter")),r=n.lhs,o=n.rhs.sort((d,T)=>T.i-d.i),s=[],a=0,l=0,E=0;r.sort(_0(!!t)),E=ME(s,o,E),r.forEach(d=>{E+=d.vs.length,s.push(d.vs),a+=d.barycenter*d.weight,l+=d.weight,E=ME(s,o,E)});let c={vs:s.flat(1)};return l&&(c.barycenter=a/l,c.weight=l),c}function ME(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 _0(e){return(t,n)=>t.barycenter<n.barycenter?-1:t.barycenter>n.barycenter?1:e?n.i-t.i:t.i-n.i}function kd(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,E={};a&&(o=o.filter(S=>S!==a&&S!==l));let c=f0(e,o);c.forEach(S=>{if(e.children(S.v).length){let u=kd(e,S.v,n,r);E[S.v]=u,Object.hasOwn(u,"barycenter")&&g0(S,u)}});let d=p0(c,n);m0(d,E);let T=L0(d,r);if(a&&l){T.vs=[a,T.vs,l].flat(1);let S=e.predecessors(a);if(S&&S.length){let u=e.node(S[0]),R=e.predecessors(l),I=e.node(R[0]);Object.hasOwn(T,"barycenter")||(T.barycenter=0,T.weight=0),T.barycenter=(T.barycenter*T.weight+u.order+I.order)/(T.weight+2),T.weight+=2}}return T}function m0(e,t){e.forEach(n=>{n.vs=n.vs.flatMap(r=>t[r]?t[r].vs:r)})}function g0(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 x0(e,t,n,r){r||(r=e.nodes());let o=y0(e),s=new We({compound:!0}).setGraph({root:o}).setDefaultNodeLabel(a=>e.node(a));return r.forEach(a=>{let l=e.node(a),E=e.parent(a);if(l.rank===t||l.minRank<=t&&t<=l.maxRank){s.setNode(a),s.setParent(a,E||o);let c=e[n](a);c&&c.forEach(d=>{let T=d.v===a?d.w:d.v,S=s.edge(T,a),u=S!==void 0?S.weight:0;s.setEdge(T,a,{weight:e.edge(d).weight+u})}),Object.hasOwn(l,"minRank")&&s.setNode(a,{borderLeft:l.borderLeft[t],borderRight:l.borderRight[t]})}}),s}function y0(e){let t;for(;e.hasNode(t=Qi("_root")););return t}function D0(e,t,n){let r={},o;n.forEach(s=>{let a=e.parent(s),l,E;for(;a;){if(l=e.parent(a),l?(E=r[l],r[l]=a):(E=o,o=a),E&&E!==a){t.setEdge(E,a);return}a=l}})}function Vd(e,t={}){if(typeof t.customOrder=="function"){t.customOrder(e,Vd);return}let n=Md(e),r=PE(e,Zn(1,n+1),"inEdges"),o=PE(e,Zn(n-1,-1,-1),"outEdges"),s=I0(e);if(bE(e,s),t.disableOptimalOrderHeuristic)return;let a=Number.POSITIVE_INFINITY,l,E=t.constraints||[];for(let c=0,d=0;d<4;++c,++d){M0(c%2?r:o,c%4>=2,E),s=lr(e);let T=N0(e,s);T<a?(d=0,l=Object.assign({},s),a=T):T===a&&(l=structuredClone(s))}bE(e,l)}function PE(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 x0(e,s,n,r.get(s)||[])})}function M0(e,t,n){let r=new We;e.forEach(function(o){n.forEach(l=>r.setEdge(l.left,l.right));let s=o.graph().root,a=kd(o,s,r,t);a.vs.forEach((l,E)=>o.node(l).order=E),D0(o,r,a.vs)})}function bE(e,t){Object.values(t).forEach(n=>n.forEach((r,o)=>e.node(r).order=o))}function P0(e,t){let n={};function r(o,s){let a=0,l=0,E=o.length,c=s[s.length-1];return s.forEach((d,T)=>{let S=U0(e,d),u=S?e.node(S).order:E;(S||d===c)&&(s.slice(l,T+1).forEach(R=>{let I=e.predecessors(R);I&&I.forEach(N=>{let A=e.node(N),p=A.order;(p<a||u<p)&&!(A.dummy&&e.node(R).dummy)&&Wd(n,N,R)})}),l=T+1,a=u)}),s}return t.length&&t.reduce(r),n}function b0(e,t){let n={};function r(s,a,l,E,c){Zn(a,l).forEach(d=>{let T=s[d];if(T!==void 0&&e.node(T).dummy){let S=e.predecessors(T);S&&S.forEach(u=>{if(u===void 0)return;let R=e.node(u);R.dummy&&(R.order<E||R.order>c)&&Wd(n,u,T)})}})}function o(s,a){let l=-1,E=-1,c=0;return a.forEach((d,T)=>{if(e.node(d).dummy==="border"){let S=e.predecessors(d);if(S&&S.length){let u=S[0];if(u===void 0)return;E=e.node(u).order,r(a,c,T,l,E),c=T,l=E}}r(a,c,a.length,E,s.length)}),a}return t.length&&t.reduce(o),n}function U0(e,t){if(e.node(t).dummy){let n=e.predecessors(t);if(n)return n.find(r=>e.node(r).dummy)}}function Wd(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 v0(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 B0(e,t,n,r){let o={},s={},a={};return t.forEach(l=>{l.forEach((E,c)=>{o[E]=E,s[E]=E,a[E]=c})}),t.forEach(l=>{let E=-1;l.forEach(c=>{let d=r(c);if(d&&d.length){let T=d.sort((u,R)=>{let I=a[u],N=a[R];return(I!==void 0?I:0)-(N!==void 0?N:0)}),S=(T.length-1)/2;for(let u=Math.floor(S),R=Math.ceil(S);u<=R;++u){let I=T[u];if(I===void 0)continue;let N=a[I];if(N!==void 0&&s[c]===c&&E<N&&!v0(n,c,I)){let A=o[I];A!==void 0&&(s[I]=c,s[c]=o[c]=A,E=N)}}}})}),{root:o,align:s}}function F0(e,t,n,r,o=!1){let s={},a=G0(e,t,n,o),l=o?"borderLeft":"borderRight";function E(u,R){let I=a.nodes().slice(),N={},A=I.pop();for(;A;){if(N[A])u(A);else{N[A]=!0,I.push(A);for(let p of R(A))I.push(p)}A=I.pop()}}function c(u){let R=a.inEdges(u);R?s[u]=R.reduce((I,N)=>{var A;let p=(A=s[N.v])!=null?A:0,O=a.edge(N);return Math.max(I,p+(O!==void 0?O:0))},0):s[u]=0}function d(u){let R=a.outEdges(u),I=Number.POSITIVE_INFINITY;R&&(I=R.reduce((A,p)=>{let O=s[p.w],h=a.edge(p);return Math.min(A,(O!==void 0?O:0)-(h!==void 0?h:0))},Number.POSITIVE_INFINITY));let N=e.node(u);I!==Number.POSITIVE_INFINITY&&N.borderType!==l&&(s[u]=Math.max(s[u]!==void 0?s[u]:0,I))}function T(u){return a.predecessors(u)||[]}function S(u){return a.successors(u)||[]}return E(c,T),E(d,S),Object.keys(r).forEach(u=>{var R;let I=n[u];I!==void 0&&(s[u]=(R=s[I])!=null?R:0)}),s}function G0(e,t,n,r){let o=new We,s=e.graph(),a=V0(s.nodesep,s.edgesep,r);return t.forEach(l=>{let E;l.forEach(c=>{let d=n[c];if(d!==void 0){if(o.setNode(d),E!==void 0){let T=n[E];if(T!==void 0){let S=o.edge(T,d);o.setEdge(T,d,Math.max(a(e,c,E),S||0))}}E=c}})}),o}function w0(e,t){return Object.values(t).reduce((n,r)=>{let o=Number.NEGATIVE_INFINITY,s=Number.POSITIVE_INFINITY;Object.entries(r).forEach(([l,E])=>{let c=W0(e,l)/2;o=Math.max(E+c,o),s=Math.min(E-c,s)});let a=o-s;return a<n[0]&&(n=[a,r]),n},[Number.POSITIVE_INFINITY,null])[1]}function H0(e,t){let n=Object.values(t),r=st(Math.min,n),o=st(Math.max,n);["u","d"].forEach(s=>{["l","r"].forEach(a=>{let l=s+a,E=e[l];if(!E||E===t)return;let c=Object.values(E),d=r-st(Math.min,c);a!=="l"&&(d=o-st(Math.max,c)),d&&(e[l]=wo(E,T=>T+d))})})}function Y0(e,t=void 0){let n=e.ul;return n?wo(n,(r,o)=>{var s,a;if(t){let E=t.toLowerCase(),c=e[E];if(c&&c[o]!==void 0)return c[o]}let l=Object.values(e).map(E=>{let c=E[o];return c!==void 0?c:0}).sort((E,c)=>E-c);return(((s=l[1])!=null?s:0)+((a=l[2])!=null?a:0))/2}):{}}function k0(e){let t=lr(e),n=Object.assign(P0(e,t),b0(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 E=B0(e,o,n,d=>(a==="u"?e.predecessors(d):e.successors(d))||[]),c=F0(e,o,E.root,E.align,l==="r");l==="r"&&(c=wo(c,d=>-d)),r[a+l]=c})});let s=w0(e,r);return H0(r,s),Y0(r,e.graph().align)}function V0(e,t,n){return(r,o,s)=>{let a=r.node(o),l=r.node(s),E=0,c;if(E+=a.width/2,Object.hasOwn(a,"labelpos"))switch(a.labelpos.toLowerCase()){case"l":c=-a.width/2;break;case"r":c=a.width/2;break}if(c&&(E+=n?c:-c),c=void 0,E+=(a.dummy?t:e)/2,E+=(l.dummy?t:e)/2,E+=l.width/2,Object.hasOwn(l,"labelpos"))switch(l.labelpos.toLowerCase()){case"l":c=l.width/2;break;case"r":c=-l.width/2;break}return c&&(E+=n?c:-c),E}}function W0(e,t){return e.node(t).width}function j0(e){e=yd(e),$0(e),Object.entries(k0(e)).forEach(([t,n])=>e.node(t).x=n)}function $0(e){let t=lr(e),n=e.graph(),r=n.ranksep,o=n.rankalign,s=0;t.forEach(a=>{let l=a.reduce((E,c)=>{var d;let T=(d=e.node(c).height)!=null?d:0;return E>T?E:T},0);a.forEach(E=>{let c=e.node(E);o==="top"?c.y=s+c.height/2:o==="bottom"?c.y=s+l-c.height/2:c.y=s+l/2}),s+=l+r})}function X0(e,t={}){let n=t.debugTiming?Pd:bd;return n("layout",()=>{let r=n(" buildLayoutGraph",()=>rM(e));return n(" runLayout",()=>K0(r,n,t)),n(" updateInputGraph",()=>z0(e,r)),r})}function K0(e,t,n){t(" makeSpaceForEdgeLabels",()=>oM(e)),t(" removeSelfEdges",()=>SM(e)),t(" acyclic",()=>FD(e)),t(" nestingGraph.run",()=>a0(e)),t(" rank",()=>ZD(yd(e))),t(" injectEdgeLabelProxies",()=>sM(e)),t(" removeEmptyRanks",()=>CD(e)),t(" nestingGraph.cleanup",()=>c0(e)),t(" normalizeRanks",()=>hD(e)),t(" assignRankMinMax",()=>iM(e)),t(" removeEdgeLabelProxies",()=>aM(e)),t(" normalize.run",()=>HD(e)),t(" parentDummyChains",()=>r0(e)),t(" addBorderSegments",()=>T0(e)),t(" order",()=>Vd(e,n)),t(" insertSelfEdges",()=>uM(e)),t(" adjustCoordinateSystem",()=>S0(e)),t(" position",()=>j0(e)),t(" positionSelfEdges",()=>RM(e)),t(" removeBorderNodes",()=>dM(e)),t(" normalize.undo",()=>kD(e)),t(" fixupEdgeLabelCoords",()=>cM(e)),t(" undoCoordinateSystem",()=>u0(e)),t(" translateGraph",()=>lM(e)),t(" assignNodeIntersects",()=>EM(e)),t(" reversePoints",()=>TM(e)),t(" acyclic.undo",()=>wD(e))}function z0(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 J0=["nodesep","edgesep","ranksep","marginx","marginy"],q0={ranksep:50,edgesep:20,nodesep:50,rankdir:"TB",rankalign:"center"},Q0=["acyclicer","ranker","rankdir","align","rankalign"],Z0=["width","height","rank"],UE={width:0,height:0},eM=["minlen","weight","width","height","labeloffset"],tM={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},nM=["labelpos"];function rM(e){let t=new We({multigraph:!0,compound:!0}),n=Qs(e.graph());return t.setGraph(Object.assign({},q0,qs(n,J0),po(n,Q0))),e.nodes().forEach(r=>{let o=Qs(e.node(r)),s=qs(o,Z0);Object.keys(UE).forEach(l=>{s[l]===void 0&&(s[l]=UE[l])}),t.setNode(r,s);let a=e.parent(r);a!==void 0&&t.setParent(r,a)}),e.edges().forEach(r=>{let o=Qs(e.edge(r));t.setEdge(r,Object.assign({},tM,qs(o,eM),po(o,nM)))}),t}function oM(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 sM(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};pn(e,"edge-proxy",o,"_ep")}})}function iM(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 aM(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 lM(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 E(c){let d=c.x,T=c.y,S=c.width,u=c.height;t=Math.min(t,d-S/2),n=Math.max(n,d+S/2),r=Math.min(r,T-u/2),o=Math.max(o,T+u/2)}e.nodes().forEach(c=>E(e.node(c))),e.edges().forEach(c=>{let d=e.edge(c);Object.hasOwn(d,"x")&&E(d)}),t-=a,r-=l,e.nodes().forEach(c=>{let d=e.node(c);d.x-=t,d.y-=r}),e.edges().forEach(c=>{let d=e.edge(c);d.points.forEach(T=>{T.x-=t,T.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 EM(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(LE(r,s)),n.points.push(LE(o,a))})}function cM(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 TM(e){e.edges().forEach(t=>{let n=e.edge(t);n.reversed&&n.points.reverse()})}function dM(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 SM(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 uM(e){lr(e).forEach(t=>{let n=0;t.forEach((r,o)=>{let s=e.node(r);s.order=o+n,(s.selfEdges||[]).forEach(a=>{pn(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 RM(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,E=o.height/2;e.setEdge(r.e,r.label),e.removeNode(t),r.label.points=[{x:s+2*l/3,y:a-E},{x:s+5*l/6,y:a-E},{x:s+l,y:a},{x:s+5*l/6,y:a+E},{x:s+2*l/3,y:a+E}],r.label.x=n.x,r.label.y=n.y}})}function qs(e,t){return wo(po(e,t),Number)}function Qs(e){let t={};return e&&Object.entries(e).forEach(([n,r])=>{typeof n=="string"&&(n=n.toLowerCase()),t[n]=r}),t}function AM(e){let t=lr(e),n=new We({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 IM={graphlib:fd,version:xD,layout:X0,debug:AM,util:{time:Pd,notime:bd}},vE=IM;/*! For license information please see dagre.esm.js.LEGAL.txt */const rt={source_table:"#8b949e",block:"#56d364",metric:"#388bfd",dimension:"#e3b341",domain:"#d2a8ff",chart:"#f778ba"},eo={source_table:"TABLE",block:"BLOCK",metric:"METRIC",dimension:"DIM",domain:"DOMAIN",chart:"CHART"},jd={certified:"#56d364",draft:"#8b949e",review:"#e3b341",deprecated:"#f85149",pending_recertification:"#d29922"},Zs={reads_from:"#8b949e",feeds_into:"#56d364",aggregates:"#388bfd",visualizes:"#f778ba",crosses_domain:"#d2a8ff"};function NM(e,t,n="LR"){const r=new vE.graphlib.Graph().setDefaultEdgeLabel(()=>({}));r.setGraph({rankdir:n,ranksep:80,nodesep:40,marginx:40,marginy:40});for(const s of e){const a=s.type==="domainGroup"?200:180,l=s.type==="domainGroup"?60:56;r.setNode(s.id,{width:a,height:l})}for(const s of t)r.setEdge(s.source,s.target);return vE.layout(r),{nodes:e.map(s=>{const a=r.node(s.id),l=s.type==="domainGroup"?200:180,E=s.type==="domainGroup"?60:56;return{...s,position:{x:a.x-l/2,y:a.y-E/2}}}),edges:t}}function OM({data:e,selected:t}){const n=e.nodeType,r=rt[n]??"#8b949e",o=eo[n]??n.slice(0,5).toUpperCase(),s=e.label,a=e.domain,l=e.status,E=l?jd[l]:void 0,c=e.highlighted,d=e.dimmed;return i.jsxs("div",{style:{background:"#161b22",border:`2px solid ${t?"#58a6ff":c?r:"#30363d"}`,borderRadius:8,padding:"6px 10px",minWidth:140,maxWidth:200,opacity:d?.3:1,transition:"opacity 0.2s, border-color 0.2s",cursor:"pointer"},children:[i.jsx(In,{type:"target",position:se.Left,style:{background:r,width:6,height:6,border:"none"}}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginBottom:3},children:[i.jsx("span",{style:{fontSize:9,fontWeight:700,color:"#0d1117",background:r,borderRadius:3,padding:"1px 5px",letterSpacing:"0.5px"},children:o}),a&&i.jsx("span",{style:{fontSize:9,color:"#8b949e"},children:a}),E&&i.jsx("span",{style:{marginLeft:"auto",width:7,height:7,borderRadius:"50%",background:E,flexShrink:0},title:l})]}),i.jsx("div",{style:{fontSize:11,fontWeight:600,color:"#e6edf3",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:s,children:s}),i.jsx(In,{type:"source",position:se.Right,style:{background:r,width:6,height:6,border:"none"}})]})}const fM={dagNode:OM};function Mn({label:e,color:t,active:n,count:r,onClick:o}){return i.jsxs("button",{onClick:o,style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:9,fontWeight:600,padding:"2px 6px",borderRadius:4,border:`1px solid ${n?t:"#30363d"}`,background:n?`${t}20`:"transparent",color:n?t:"#8b949e",cursor:"pointer",transition:"all 0.15s"},children:[i.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:n?t:"#484f58"}}),e,i.jsx("span",{style:{fontWeight:400,opacity:.7},children:r})]})}function pM(){const{state:e}=Se(),t=le[e.themeMode],[n,r]=f.useState(!0),[o,s]=f.useState([]),[a,l]=f.useState([]),[E,c,d]=Ny([]),[T,S,u]=Oy([]),[R,I]=f.useState(!0),[N,A]=f.useState(!0),[p,O]=f.useState(!0),[h,C]=f.useState(!0),[_,m]=f.useState(!0),[M,y]=f.useState(null),[b,g]=f.useState(new Set),[x,F]=f.useState(null),[L,P]=f.useState([]),[D,B]=f.useState([]),v=f.useCallback(async()=>{r(!0);const w=await te.fetchLineage();s(w.nodes??[]),l(w.edges??[]),r(!1)},[]);f.useEffect(()=>{v()},[v]);const U=f.useMemo(()=>{const w=new Set;return R&&w.add("source_table"),N&&w.add("block"),p&&w.add("metric"),h&&w.add("dimension"),_&&w.add("chart"),w.add("domain"),w},[R,N,p,h,_]);f.useEffect(()=>{const w=o.filter(K=>U.has(K.type)),z=new Set(w.map(K=>K.id)),q=w.map(K=>({id:K.id,type:"dagNode",position:{x:0,y:0},data:{label:K.name,nodeType:K.type,domain:K.domain,status:K.status,owner:K.owner,highlighted:b.has(K.id),dimmed:b.size>0&&!b.has(K.id)}})),Z=a.filter(K=>z.has(K.source)&&z.has(K.target)&&K.type!=="crosses_domain").map((K,H)=>({id:`e-${H}`,source:K.source,target:K.target,type:"default",animated:K.type==="feeds_into",style:{stroke:Zs[K.type]??"#30363d",strokeWidth:b.size>0?b.has(K.source)&&b.has(K.target)?2.5:.5:1.5,opacity:b.size>0?b.has(K.source)&&b.has(K.target)?1:.15:.7},markerEnd:{type:zn.ArrowClosed,width:12,height:12,color:Zs[K.type]??"#30363d"}}));if(q.length>0){const K=NM(q,Z,"LR");c(K.nodes),S(K.edges)}else c([]),S([])},[o,a,U,b,c,S]);const Y=f.useCallback(async(w,z)=>{if(M===z.id){y(null),g(new Set),F(null),P([]),B([]);return}y(z.id);const q=o.find(ee=>ee.id===z.id);F(q??null);const Z=new Set,K=new Set;function H(ee){for(const ne of a)ne.target===ee&&ne.type!=="crosses_domain"&&!Z.has(ne.source)&&(Z.add(ne.source),H(ne.source))}function J(ee){for(const ne of a)ne.source===ee&&ne.type!=="crosses_domain"&&!K.has(ne.target)&&(K.add(ne.target),J(ne.target))}H(z.id),J(z.id);const V=new Set([z.id,...Z,...K]);if(g(V),P(o.filter(ee=>Z.has(ee.id))),B(o.filter(ee=>K.has(ee.id))),(q==null?void 0:q.type)==="block"){const ee=await te.fetchBlockLineage(q.name);ee&&(P(ee.ancestors??[]),B(ee.descendants??[]))}},[M,o,a]),W=f.useCallback(()=>{y(null),g(new Set),F(null),P([]),B([])},[]),k=f.useMemo(()=>{const w={};for(const z of o)w[z.type]=(w[z.type]??0)+1;return w},[o]);return n?i.jsx("div",{style:{padding:16,color:t.textMuted,fontSize:12,height:"100%"},children:"Loading lineage graph..."}):o.length===0?i.jsxs("div",{style:{padding:16,color:t.textMuted,fontSize:12,height:"100%"},children:["No lineage data. Add DQL blocks or run ",i.jsx("code",{children:"dql compile"})," to generate lineage."]}):i.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",background:"#0d1117"},children:[i.jsxs("div",{style:{display:"flex",gap:4,padding:"6px 8px",flexWrap:"wrap",borderBottom:`1px solid ${t.headerBorder}`,background:t.sidebarBg,flexShrink:0},children:[i.jsx(Mn,{label:"Tables",color:rt.source_table,active:R,count:k.source_table??0,onClick:()=>I(!R)}),i.jsx(Mn,{label:"Blocks",color:rt.block,active:N,count:k.block??0,onClick:()=>A(!N)}),i.jsx(Mn,{label:"Metrics",color:rt.metric,active:p,count:k.metric??0,onClick:()=>O(!p)}),i.jsx(Mn,{label:"Dims",color:rt.dimension,active:h,count:k.dimension??0,onClick:()=>C(!h)}),i.jsx(Mn,{label:"Charts",color:rt.chart,active:_,count:k.chart??0,onClick:()=>m(!_)})]}),i.jsx("div",{style:{flex:1,position:"relative"},children:i.jsxs(Iy,{nodes:E,edges:T,onNodesChange:d,onEdgesChange:u,onNodeClick:Y,onPaneClick:W,nodeTypes:fM,fitView:!0,fitViewOptions:{padding:.2},minZoom:.1,maxZoom:2,proOptions:{hideAttribution:!0},style:{background:"#0d1117"},children:[i.jsx(Ly,{color:"#21262d",gap:24,size:1}),i.jsx(My,{showInteractive:!1,style:{button:{background:"#161b22",color:"#e6edf3",border:"1px solid #30363d"}}}),i.jsx(Wy,{nodeColor:w=>{var q;const z=(q=w.data)==null?void 0:q.nodeType;return rt[z]??"#8b949e"},maskColor:"rgba(0,0,0,0.6)",style:{background:"#0d1117",border:"1px solid #30363d"}}),i.jsx(ar,{position:"bottom-left",children:i.jsx("div",{style:{display:"flex",gap:10,background:"rgba(22,27,34,0.9)",padding:"4px 10px",borderRadius:6,border:"1px solid #30363d",fontSize:9,color:"#8b949e"},children:Object.entries(Zs).map(([w,z])=>i.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3},children:[i.jsx("span",{style:{width:12,height:2,background:z,borderRadius:1}}),w.replace(/_/g," ")]},w))})})]})}),x&&i.jsxs("div",{style:{flexShrink:0,maxHeight:180,overflow:"auto",borderTop:`1px solid ${t.headerBorder}`,background:t.sidebarBg,padding:8,fontSize:11},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginBottom:6},children:[i.jsx("span",{style:{fontSize:9,fontWeight:700,color:"#0d1117",background:rt[x.type]??"#8b949e",borderRadius:3,padding:"1px 5px"},children:eo[x.type]??x.type}),i.jsx("span",{style:{fontWeight:600,color:t.textPrimary,flex:1},children:x.name}),i.jsx("button",{onClick:()=>{y(null),g(new Set),F(null)},style:{background:"transparent",border:"none",color:t.textMuted,cursor:"pointer",fontSize:14},children:"×"})]}),x.domain&&i.jsxs("div",{style:{color:t.textMuted,marginBottom:2},children:["Domain: ",i.jsx("span",{style:{color:"#d2a8ff"},children:x.domain})]}),x.owner&&i.jsxs("div",{style:{color:t.textMuted,marginBottom:2},children:["Owner: ",i.jsx("span",{style:{color:t.textSecondary},children:x.owner})]}),x.status&&i.jsxs("div",{style:{color:t.textMuted,marginBottom:4},children:["Status: ",i.jsx("span",{style:{color:jd[x.status]??t.textSecondary},children:x.status})]}),L.length>0&&i.jsxs("div",{style:{marginTop:4},children:[i.jsxs("div",{style:{color:t.textMuted,fontSize:9,fontWeight:600,textTransform:"uppercase",marginBottom:2},children:["Upstream (",L.length,")"]}),L.slice(0,8).map(w=>{var z;return i.jsxs("div",{style:{padding:"1px 0",color:t.textSecondary,display:"flex",alignItems:"center",gap:3},children:[i.jsx("span",{style:{color:rt[w.type],fontSize:8,fontWeight:700},children:((z=eo[w.type])==null?void 0:z.slice(0,3))??"???"}),w.name]},w.id)}),L.length>8&&i.jsxs("div",{style:{color:t.textMuted,fontSize:10},children:["+",L.length-8," more"]})]}),D.length>0&&i.jsxs("div",{style:{marginTop:4},children:[i.jsxs("div",{style:{color:t.textMuted,fontSize:9,fontWeight:600,textTransform:"uppercase",marginBottom:2},children:["Downstream (",D.length,")"]}),D.slice(0,8).map(w=>{var z;return i.jsxs("div",{style:{padding:"1px 0",color:t.textSecondary,display:"flex",alignItems:"center",gap:3},children:[i.jsx("span",{style:{color:rt[w.type],fontSize:8,fontWeight:700},children:((z=eo[w.type])==null?void 0:z.slice(0,3))??"???"}),w.name]},w.id)}),D.length>8&&i.jsxs("div",{style:{color:t.textMuted,fontSize:10},children:["+",D.length-8," more"]})]})]})]})}function hM(){const{state:e,dispatch:t}=Se(),{executeAll:n}=mo();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])}function CM(){const{state:e,dispatch:t}=Se(),n=le[e.themeMode],r=f.useRef({});hM();const o=f.useCallback(async a=>{try{if(a.type==="block"){const d=await te.openBlockStudio(a.path);t({type:"OPEN_BLOCK_STUDIO",file:a,payload:d});return}const{content:l}=await te.readNotebook(a.path),{title:E,cells:c}=PR(a.path,l);t({type:"OPEN_FILE",file:a,cells:c,title:E}),e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"})}catch(l){if(console.error("Failed to open file:",l),a.type==="block")try{const{content:E}=await te.readNotebook(a.path);t({type:"OPEN_BLOCK_STUDIO",file:a,payload:{path:a.path,source:E,companionPath:null,metadata:{name:a.name.replace(/\.dql$/i,""),path:a.path,domain:a.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(E){console.error("Failed to open block fallback:",E)}else t({type:"OPEN_FILE",file:a,cells:[xe("sql")],title:a.name})}},[t,e.sidebarPanel]);f.useCallback(a=>{const l=r.current[a];l&&l.scrollIntoView({behavior:"smooth",block:"start"})},[]);const s=f.useCallback((a,l)=>{l?r.current[a]=l:delete r.current[a]},[]);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(rA,{}),i.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[i.jsx(lu,{}),e.sidebarOpen&&i.jsx(xR,{onOpenFile:o}),i.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:e.lineageFullscreen?i.jsx(pM,{}):e.mainView==="connection"?i.jsx(BE,{title:"Connections",description:"Manage database connections, edit driver settings, and test connectivity in a full-page workspace.",children:i.jsx(VE,{})}):e.mainView==="reference"?i.jsx(BE,{title:"Quick Reference",description:"Browse the complete DQL guide, semantic workflows, and authoring patterns in a documentation-style view.",children:i.jsx(WE,{themeMode:e.themeMode})}):i.jsx(i.Fragment,{children:e.mainView==="block_studio"?i.jsx(_h,{}):i.jsxs(i.Fragment,{children:[i.jsx(Rh,{onOpenFile:o,registerCellRef:s}),i.jsx(aA,{})]})})})]}),e.newNotebookModalOpen&&i.jsx(ph,{onFileOpened:o}),e.newBlockModalOpen&&i.jsx(Lh,{onFileOpened:o})]})}function BE({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 LM(){const{state:e,dispatch:t}=Se(),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")&&te.listNotebooks().then(E=>{t({type:"SET_FILES",files:E})}),l.type==="file-changed"&&te.listNotebooks().then(E=>{t({type:"SET_FILES",files:E})}),l.type==="semantic-reload"&&(t({type:"SET_SEMANTIC_LOADING",loading:!0}),te.getSemanticLayer().then(E=>{t({type:"SET_SEMANTIC_LAYER",layer:E})}))}catch{}}),s.addEventListener("error",()=>{s.close(),setTimeout(o,5e3)})};return o(),()=>{var s;(s=r.current)==null||s.close(),r.current=null}},[t])}function _M(){const{state:e,dispatch:t}=Se(),n=le[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=`
544
+ * { margin: 0; padding: 0; box-sizing: border-box; }
545
+ body {
546
+ font-family: ${n.font};
547
+ overflow: hidden;
548
+ background: ${n.appBg};
549
+ color: ${n.textPrimary};
550
+ }
551
+ ::-webkit-scrollbar { width: 6px; height: 6px; }
552
+ ::-webkit-scrollbar-track { background: transparent; }
553
+ ::-webkit-scrollbar-thumb {
554
+ background: ${n.scrollbarThumb};
555
+ border-radius: 3px;
556
+ }
557
+ ::-webkit-scrollbar-thumb:hover {
558
+ background: ${n.textMuted};
559
+ }
560
+ ::selection {
561
+ background: ${n.accent}40;
562
+ color: ${n.textPrimary};
563
+ }
564
+ `},[n]),f.useEffect(()=>{t({type:"SET_FILES_LOADING",loading:!0}),te.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}),te.getSchema().then(r=>{t({type:"SET_SCHEMA",tables:r}),t({type:"SET_SCHEMA_LOADING",loading:!1})})},[t]),LM(),i.jsx(CM,{})}function mM(){return i.jsx(qS,{children:i.jsx(_M,{})})}KS.createRoot(document.getElementById("root")).render(i.jsx(mM,{}));