@duckcodeailabs/dql-cli 0.8.4 → 0.8.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +13 -4
  2. package/dist/args.d.ts +1 -0
  3. package/dist/args.d.ts.map +1 -1
  4. package/dist/args.js +4 -0
  5. package/dist/args.js.map +1 -1
  6. package/dist/assets/dql-notebook/assets/index-CTmiMNUc.js +558 -0
  7. package/dist/assets/dql-notebook/index.html +1 -1
  8. package/dist/block-templates.d.ts +8 -0
  9. package/dist/block-templates.d.ts.map +1 -0
  10. package/dist/block-templates.js +60 -0
  11. package/dist/block-templates.js.map +1 -0
  12. package/dist/commands/build.test.js +1 -1
  13. package/dist/commands/build.test.js.map +1 -1
  14. package/dist/commands/doctor.d.ts.map +1 -1
  15. package/dist/commands/doctor.js +17 -1
  16. package/dist/commands/doctor.js.map +1 -1
  17. package/dist/commands/doctor.test.js +1 -1
  18. package/dist/commands/doctor.test.js.map +1 -1
  19. package/dist/commands/init.d.ts.map +1 -1
  20. package/dist/commands/init.js +73 -5
  21. package/dist/commands/init.js.map +1 -1
  22. package/dist/commands/init.test.js +82 -2
  23. package/dist/commands/init.test.js.map +1 -1
  24. package/dist/commands/new.test.js +7 -7
  25. package/dist/commands/new.test.js.map +1 -1
  26. package/dist/commands/notebook.d.ts.map +1 -1
  27. package/dist/commands/notebook.js +2 -2
  28. package/dist/commands/notebook.js.map +1 -1
  29. package/dist/commands/semantic.d.ts +2 -0
  30. package/dist/commands/semantic.d.ts.map +1 -1
  31. package/dist/commands/semantic.js +115 -1
  32. package/dist/commands/semantic.js.map +1 -1
  33. package/dist/index.js +18 -0
  34. package/dist/index.js.map +1 -1
  35. package/dist/local-runtime.d.ts +35 -0
  36. package/dist/local-runtime.d.ts.map +1 -1
  37. package/dist/local-runtime.js +1690 -45
  38. package/dist/local-runtime.js.map +1 -1
  39. package/dist/local-runtime.test.js +69 -1
  40. package/dist/local-runtime.test.js.map +1 -1
  41. package/dist/semantic-import.d.ts +127 -0
  42. package/dist/semantic-import.d.ts.map +1 -0
  43. package/dist/semantic-import.js +713 -0
  44. package/dist/semantic-import.js.map +1 -0
  45. package/dist/semantic-import.test.d.ts +2 -0
  46. package/dist/semantic-import.test.d.ts.map +1 -0
  47. package/dist/semantic-import.test.js +278 -0
  48. package/dist/semantic-import.test.js.map +1 -0
  49. package/package.json +8 -7
  50. package/dist/assets/dql-notebook/assets/index-DeyBtNqN.js +0 -533
@@ -1,533 +0,0 @@
1
- import{r as Cr,a as ca,g as ss}from"./react-CRB3T2We.js";import{S as is,g as Ra,E as be,s as iR,a as pe,b as ER,c as aR,P as lR,d as TR,e as cR,F as RR,f as AR,h as Aa,V as SR,D as Es,R as dR,i as IR,C as tt,j as Sa,k as De,r as uR,l as NR,m as fR,t as CR,n as LR,o as hR,p as _R,q as pR,u as mR,v as DR,w as yn,x as gR,y as PR,z as MR,A as yR,B as xR,G as UR,H as bR,I as GR,J as BR,K as vR,L as HR}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 i of s.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).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 Fr={exports:{}},Xt={};/**
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 $s;function FR(){if($s)return Xt;$s=1;var e=Cr(),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 i(a,T,l){var R,c={},A=null,S=null;l!==void 0&&(A=""+l),T.key!==void 0&&(A=""+T.key),T.ref!==void 0&&(S=T.ref);for(R in T)r.call(T,R)&&!s.hasOwnProperty(R)&&(c[R]=T[R]);if(a&&a.defaultProps)for(R in T=a.defaultProps,T)c[R]===void 0&&(c[R]=T[R]);return{$$typeof:t,type:a,key:A,ref:S,props:c,_owner:o.current}}return Xt.Fragment=n,Xt.jsx=i,Xt.jsxs=i,Xt}var Ks;function wR(){return Ks||(Ks=1,Fr.exports=FR()),Fr.exports}var E=wR(),xn={},Js;function YR(){if(Js)return xn;Js=1;var e=ca();return xn.createRoot=e.createRoot,xn.hydrateRoot=e.hydrateRoot,xn}var VR=YR(),C=Cr();const on=ss(C),WR={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:[],loading:!1},devPanelOpen:!1,devPanelTab:"logs",queryLog:[],newNotebookModalOpen:!1,newBlockModalOpen:!1,autoSave:!1,executionCounter:0,savingFile:!1,lineageFullscreen:!1};function kR(e,t){switch(t.type){case"SET_THEME":return{...e,themeMode:t.mode};case"SET_SIDEBAR_PANEL":return{...e,sidebarPanel:t.panel,sidebarOpen:t.panel!==null};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};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 n=e.cells.findIndex(o=>o.id===t.afterId);if(n===-1)return{...e,cells:[...e.cells,t.cell],notebookDirty:!0};const r=[...e.cells];return r.splice(n+1,0,t.cell),{...e,cells:r,notebookDirty:!0}}case"UPDATE_CELL":{const n=e.cells.map(o=>o.id===t.id?{...o,...t.updates}:o),r=t.updates.executionCount!==void 0?e.executionCounter+1:e.executionCounter;return{...e,cells:n,notebookDirty:!0,executionCounter:r}}case"DELETE_CELL":return{...e,cells:e.cells.filter(n=>n.id!==t.id),notebookDirty:!0};case"MOVE_CELL":{const n=e.cells.findIndex(o=>o.id===t.id);if(n===-1)return e;const r=[...e.cells];return t.direction==="up"&&n>0?[r[n-1],r[n]]=[r[n],r[n-1]]:t.direction==="down"&&n<r.length-1&&([r[n],r[n+1]]=[r[n+1],r[n]]),{...e,cells:r,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(n=>n.name===t.tableName?{...n,expanded:!n.expanded}:n)};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(n=>n.name===t.tableName?{...n,columns:t.columns}:n)};case"SET_PARAM_VALUE":return{...e,cells:e.cells.map(n=>n.id===t.id?{...n,paramValue:t.value}:n),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"TOGGLE_LINEAGE_FULLSCREEN":return{...e,lineageFullscreen:!e.lineageFullscreen};default:return e}}const da=C.createContext(null);function XR({children:e}){const[t,n]=C.useReducer(kR,WR);return E.jsx(da.Provider,{value:{state:t,dispatch:n},children:e})}function ae(){const e=C.useContext(da);if(!e)throw new Error("useNotebook must be used within NotebookProvider");return e}function $e(){return`cell_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function fe(e,t=""){const n={id:$e(),type:e,content:t,status:"idle"};return e==="param"&&(n.content="",n.paramConfig={paramType:"text",label:"Parameter",defaultValue:"",options:[]}),n}const jR={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"},$R={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"},ie={dark:jR,light:$R};function We({title:e,active:t,onClick:n,children:r,t:o}){const[s,i]=C.useState(!1);return E.jsx("button",{title:e,onClick:n,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!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 KR(){return E.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 JR(){return E.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 zR(){return E.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 qR(){return E.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 ZR(){return E.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M2 2h12a1 1 0 0 1 0 2H2a1 1 0 0 1 0-2Zm0 4h8a1 1 0 0 1 0 2H2a1 1 0 0 1 0-2Zm0 4h10a1 1 0 0 1 0 2H2a1 1 0 0 1 0-2Z"})})}function QR(){return E.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 eA(){return E.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 tA(){return E.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 nA(){return E.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 rA(){const{state:e,dispatch:t}=ae(),n=ie[e.themeMode];function r(o){e.sidebarPanel===o&&e.sidebarOpen?t({type:"TOGGLE_SIDEBAR"}):t({type:"SET_SIDEBAR_PANEL",panel:o})}return E.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:[E.jsx(We,{title:"Files",active:e.sidebarPanel==="files"&&e.sidebarOpen,onClick:()=>r("files"),t:n,children:E.jsx(KR,{})}),E.jsx(We,{title:"Schema",active:e.sidebarPanel==="schema"&&e.sidebarOpen,onClick:()=>r("schema"),t:n,children:E.jsx(JR,{})}),E.jsx(We,{title:"Semantic Layer",active:e.sidebarPanel==="semantic"&&e.sidebarOpen,onClick:()=>r("semantic"),t:n,children:E.jsx(zR,{})}),E.jsx(We,{title:"Lineage",active:e.sidebarPanel==="lineage"&&e.sidebarOpen,onClick:()=>r("lineage"),t:n,children:E.jsx(qR,{})}),E.jsx(We,{title:"Outline",active:e.sidebarPanel==="outline"&&e.sidebarOpen,onClick:()=>r("outline"),t:n,children:E.jsx(ZR,{})}),E.jsx(We,{title:"Connection",active:e.sidebarPanel==="connection"&&e.sidebarOpen,onClick:()=>r("connection"),t:n,children:E.jsx(QR,{})}),E.jsx(We,{title:"Reference",active:e.sidebarPanel==="reference"&&e.sidebarOpen,onClick:()=>r("reference"),t:n,children:E.jsx(eA,{})}),E.jsx("div",{style:{flex:1}}),E.jsx(We,{title:"Help & Reference",active:e.sidebarPanel==="reference"&&e.sidebarOpen,onClick:()=>r("reference"),t:n,children:E.jsx(tA,{})}),E.jsx(We,{title:"Settings",active:!1,onClick:()=>{},t:n,children:E.jsx(nA,{})})]})}const wr={notebooks:"Notebooks",workbooks:"Workbooks",blocks:"Blocks",dashboards:"Dashboards"};function oA({type:e}){switch(e){case"notebook":return E.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 E.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 E.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 E.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 sA({expanded:e}){return E.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:e?E.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"}):E.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 iA(e){return e.name.replace(/\.(dqlnb|dql)$/,"")}function EA({onOpenFile:e}){const{state:t,dispatch:n}=ae(),r=ie[t.themeMode],[o,s]=C.useState({notebooks:!0,workbooks:!0,blocks:!1,dashboards:!1}),[i,a]=C.useState(!1),T={notebooks:[],workbooks:[],blocks:[],dashboards:[]};for(const R of t.files){const c=R.folder.toLowerCase();c in T&&T[c].push(R)}const l=R=>{s(c=>({...c,[R]:!c[R]}))};return E.jsxs("div",{style:{flex:1,overflow:"auto",padding:"8px 0",display:"flex",flexDirection:"column",gap:0},children:[E.jsx("div",{style:{padding:"0 8px 8px"},children:E.jsxs("button",{onClick:()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{width:"100%",height:30,background:"transparent",border:`1px dashed ${i?r.accent:r.cellBorder}`,borderRadius:6,color:i?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:[E.jsx("span",{style:{fontSize:16,lineHeight:1},children:"+"}),"New Notebook"]})}),t.filesLoading&&E.jsx("div",{style:{padding:"8px 14px",color:r.textMuted,fontSize:12,fontFamily:r.font},children:"Loading files…"}),Object.keys(wr).map(R=>{const c=T[R],A=o[R],S=R==="notebooks"?()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}):R==="blocks"?()=>n({type:"OPEN_NEW_BLOCK_MODAL"}):void 0;return E.jsxs("div",{children:[E.jsx(aA,{label:wr[R],count:c.length,expanded:A,onToggle:()=>l(R),onAdd:S,t:r}),A&&E.jsx("div",{children:c.length===0?E.jsxs("div",{style:{padding:"4px 14px 4px 32px",fontSize:12,color:r.textMuted,fontFamily:r.font,fontStyle:"italic"},children:["No ",wr[R].toLowerCase()]}):c.map(d=>{var I;return E.jsx(lA,{file:d,active:((I=t.activeFile)==null?void 0:I.path)===d.path,onClick:()=>e(d),t:r},d.path)})})]},R)})]})}function aA({label:e,count:t,expanded:n,onToggle:r,onAdd:o,t:s}){const[i,a]=C.useState(!1),[T,l]=C.useState(!1);return E.jsxs("div",{onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{display:"flex",alignItems:"center",background:i?s.sidebarItemHover:"transparent",transition:"background 0.1s"},children:[E.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:[E.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:E.jsx("path",{d:"M3 2l4 3-4 3V2Z"})}),E.jsx(sA,{expanded:n}),E.jsx("span",{style:{flex:1},children:e}),t>0&&E.jsx("span",{style:{background:s.pillBg,color:s.textMuted,borderRadius:10,padding:"0 5px",fontSize:10,fontWeight:500},children:t})]}),o&&i&&E.jsx("button",{onClick:R=>{R.stopPropagation(),o()},onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),title:`New ${e.slice(0,-1)}`,style:{background:T?s.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:T?s.accent:s.textMuted,fontSize:14,lineHeight:1,padding:"2px 8px",marginRight:4,flexShrink:0,transition:"color 0.1s"},children:"+"})]})}function lA({file:e,active:t,onClick:n,t:r}){const[o,s]=C.useState(!1);return E.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:[E.jsx("span",{style:{flexShrink:0,color:t?r.accent:r.textMuted},children:E.jsx(oA,{type:e.type})}),E.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:iA(e)}),e.isNew&&E.jsx("span",{style:{fontSize:9,fontWeight:600,color:r.accent,background:r.sidebarItemActive,borderRadius:4,padding:"1px 4px",flexShrink:0},children:"NEW"})]})}const TA=window.location.origin;async function Oe(e,t){const n=await fetch(`${TA}${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 Re={async listNotebooks(){try{return await Oe("/api/notebooks")}catch{return[]}},async readNotebook(e){return Oe(`/api/notebook-content?path=${encodeURIComponent(e)}`)},async createNotebook(e,t){return Oe("/api/notebooks",{method:"POST",body:JSON.stringify({name:e,template:t})})},async createBlock(e){return Oe("/api/blocks",{method:"POST",body:JSON.stringify({name:e})})},async saveNotebook(e,t){return Oe("/api/notebook-content",{method:"PUT",body:JSON.stringify({path:e,content:t})})},async executeQuery(e){var r;const t=await Oe("/api/query",{method:"POST",body:JSON.stringify({sql:e})});return{columns:Array.isArray(t==null?void 0:t.columns)?t.columns.map(o=>typeof o=="string"?o:typeof(o==null?void 0:o.name)=="string"?o.name:String(o)):[],rows:Array.isArray(t==null?void 0:t.rows)?t.rows:[],rowCount:(t==null?void 0:t.rowCount)??((r=t==null?void 0:t.rows)==null?void 0:r.length)??0,executionTime:(t==null?void 0:t.executionTime)??(t==null?void 0:t.executionTimeMs)??0}},async getSchema(){try{return await Oe("/api/schema")}catch{return[]}},async getConnections(){try{return await Oe("/api/connections")}catch{return{default:"unknown",connections:{}}}},async testConnection(){try{return await Oe("/api/test-connection",{method:"POST",body:JSON.stringify({})})}catch(e){return{ok:!1,message:e.message??"Connection failed"}}},async getSemanticLayer(){try{return await Oe("/api/semantic-layer")}catch{return{available:!1,provider:null,metrics:[],dimensions:[],hierarchies:[]}}},async composeQuery(e,t,n){try{return await Oe("/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 createMetric(e){try{return await Oe("/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=/\.(csv|parquet|json)$/i.test(e)||e.startsWith("data/"),n=e.replace(/'/g,"''"),r=t?`DESCRIBE SELECT * FROM read_csv_auto('${n}') LIMIT 0`:`DESCRIBE "${n}"`;try{return(await Oe("/api/query",{method:"POST",body:JSON.stringify({sql:r})})).rows.map(s=>({name:String(s.column_name??s.Field??""),type:String(s.column_type??s.Type??"")}))}catch{return[]}},async fetchLineage(){try{return await Oe("/api/lineage")}catch{return{nodes:[],edges:[]}}},async fetchBlockLineage(e){try{return await Oe(`/api/lineage/block/${encodeURIComponent(e)}`)}catch{return null}},async fetchImpactAnalysis(e){try{return await Oe(`/api/lineage/impact/${encodeURIComponent(e)}`)}catch{return null}}},cA={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 zs(e,t){const n=e.toLowerCase().split("(")[0].trim();return cA[n]??t}function RA({t:e}){return E.jsxs("div",{style:{padding:"8px 12px",display:"flex",flexDirection:"column",gap:8},children:[[1,2,3].map(t=>E.jsx("div",{style:{height:28,borderRadius:4,background:e.pillBg,opacity:.6,animation:"pulse 1.5s ease-in-out infinite"}},t)),E.jsx("style",{children:"@keyframes pulse { 0%,100%{opacity:.6} 50%{opacity:.3} }"})]})}function AA(){const{state:e,dispatch:t}=ae(),n=ie[e.themeMode],[r,o]=C.useState(!1),s=async()=>{t({type:"SET_SCHEMA_LOADING",loading:!0});try{const i=await Re.getSchema();t({type:"SET_SCHEMA",tables:i})}catch(i){console.error("Schema refresh failed:",i)}finally{t({type:"SET_SCHEMA_LOADING",loading:!1})}};return E.jsxs("div",{style:{flex:1,overflow:"auto",display:"flex",flexDirection:"column"},children:[E.jsxs("div",{style:{padding:"8px 10px",display:"flex",alignItems:"center",gap:6,borderBottom:`1px solid ${n.headerBorder}`},children:[E.jsxs("span",{style:{flex:1,fontSize:11,color:n.textMuted,fontFamily:n.font},children:[e.schemaTables.length," tables"]}),E.jsxs("button",{onClick:s,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),title:"Refresh schema",style:{background:r?n.btnHover:"transparent",border:`1px solid ${r?n.btnBorder:"transparent"}`,borderRadius:4,cursor:"pointer",color:r?n.textSecondary:n.textMuted,fontSize:11,fontFamily:n.font,padding:"2px 6px",display:"flex",alignItems:"center",gap:4,transition:"all 0.15s"},children:[E.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:E.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"]})]}),e.schemaLoading?E.jsx(RA,{t:n}):e.schemaTables.length===0?E.jsxs("div",{style:{padding:"24px 14px",color:n.textMuted,fontSize:12,fontFamily:n.font,textAlign:"center",fontStyle:"italic"},children:["No tables found.",E.jsx("br",{}),"Connect a data source to explore schema."]}):E.jsx("div",{style:{overflow:"auto",flex:1},children:e.schemaTables.map(i=>E.jsx(SA,{table:i,t:n},i.name))})]})}function SA({table:e,t}){const{dispatch:n}=ae(),[r,o]=C.useState(!1),[s,i]=C.useState(!1),a=async()=>{if(n({type:"TOGGLE_SCHEMA_TABLE",tableName:e.name}),!e.expanded&&e.columns.length===0){i(!0);try{const T=await Re.describeTable(e.path);T.length>0&&n({type:"SET_TABLE_COLUMNS",tableName:e.name,columns:T})}catch(T){console.error("describeTable failed:",T)}finally{i(!1)}}};return E.jsxs("div",{children:[E.jsxs("button",{onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onClick:a,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:[E.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:E.jsx("path",{d:"M3 2l4 3-4 3V2Z"})}),e.source==="database"?E.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",style:{color:"#56d364",flexShrink:0},children:E.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"})}):E.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",style:{color:t.accent,flexShrink:0},children:E.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"})}),E.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),e.columns.length>0&&E.jsx("span",{style:{fontSize:10,color:t.textMuted,background:t.pillBg,borderRadius:8,padding:"1px 5px",flexShrink:0},children:e.columns.length})]}),e.expanded&&E.jsx("div",{style:{paddingLeft:26},children:s?E.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:"..."}):e.columns.length===0?E.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:"No columns"}):e.columns.map(T=>E.jsx(dA,{col:T,t},T.name))})]})}function dA({col:e,t}){const[n,r]=C.useState(!1);return E.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:[E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",style:{color:t.textMuted,flexShrink:0},children:E.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"})}),E.jsx("span",{style:{flex:1,fontSize:11,fontFamily:t.fontMono,color:t.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),E.jsx("span",{style:{fontSize:10,fontFamily:t.fontMono,color:zs(e.type,t.accent),background:`${zs(e.type,t.accent)}18`,borderRadius:4,padding:"1px 5px",flexShrink:0},children:e.type.toLowerCase()})]})}function IA(e){if(e.type==="markdown"){const t=e.content.match(/^#{1,6}\s+(.+)$/m);if(t)return t[1];const n=e.content.split(`
10
- `).find(r=>r.trim());return(n==null?void 0:n.trim())||null}return e.name?e.name:null}function Ia(e){if(e.type!=="markdown")return 0;const t=e.content.match(/^(#{1,6})\s/m);return t?t[1].length:0}function uA({cell:e,t}){if(e.type==="markdown")return E.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",style:{color:t.textMuted,flexShrink:0},children:[E.jsx("path",{d:"M14.85 3H7.39L6.74.translateX(.5.25C6.45.11 6.23 0 6 0H1.75A1.75 1.75 0 0 0 0 1.75v12.5C0 15.216.784 16 1.75 16h12.5A1.75 1.75 0 0 0 16 14.25V4.75A1.75 1.75 0 0 0 14.25 3ZM1.5 1.75a.25.25 0 0 1 .25-.25H6l.5 1.5H1.5Z"}),E.jsx("path",{d:"M2 2h12v12H2z",fill:"none",stroke:"currentColor",strokeWidth:"1.5"})]});const n=e.type==="sql"?t.accent:t.warning;return E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",style:{color:n,flexShrink:0},children:E.jsx("path",{d:"M0 5.75C0 4.784.784 4 1.75 4h12.5c.966 0 1.75.784 1.75 1.75v4.5A1.75 1.75 0 0 1 14.25 12H1.75A1.75 1.75 0 0 1 0 10.25Zm1.75-.25a.25.25 0 0 0-.25.25v4.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25v-4.5a.25.25 0 0 0-.25-.25Z"})})}function NA({onNavigate:e}){const{state:t}=ae(),n=ie[t.themeMode];if(!t.activeFile)return E.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:20,textAlign:"center"},children:E.jsxs("div",{children:[E.jsx("svg",{width:"32",height:"32",viewBox:"0 0 16 16",fill:"currentColor",style:{color:n.textMuted,marginBottom:8},children:E.jsx("path",{d:"M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25ZM1.75 1.5a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25ZM3.5 6.25a.75.75 0 0 1 .75-.75h7a.75.75 0 0 1 0 1.5h-7a.75.75 0 0 1-.75-.75Zm.75 2.25h4a.75.75 0 0 1 0 1.5h-4a.75.75 0 0 1 0-1.5Z"})}),E.jsx("div",{style:{fontSize:12,color:n.textMuted,fontFamily:n.font,lineHeight:1.5},children:"Open a notebook to see its outline."})]})});const r=t.cells.map(o=>({cell:o,label:IA(o)})).filter(o=>o.label!==null);return r.length===0?E.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:20,color:n.textMuted,fontSize:12,fontFamily:n.font,fontStyle:"italic",textAlign:"center"},children:["No named cells or headings yet.",E.jsx("br",{}),"Name your cells or add markdown headings."]}):E.jsx("div",{style:{flex:1,overflow:"auto",padding:"6px 0"},children:r.map(({cell:o,label:s})=>{const i=Ia(o),a=o.type==="markdown"?Math.max(0,(i-1)*12):0;return E.jsx(OA,{cell:o,label:s,indent:a,onClick:()=>e(o.id),t:n},o.id)})})}function OA({cell:e,label:t,indent:n,onClick:r,t:o}){const[s,i]=C.useState(!1);return E.jsxs("button",{onClick:r,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:`4px 10px 4px ${14+n}px`,background:s?o.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:s?o.textPrimary:o.textSecondary,fontSize:12,fontFamily:e.type==="markdown"?o.font:o.fontMono,textAlign:"left",transition:"background 0.1s, color 0.1s",overflow:"hidden"},children:[E.jsx(uA,{cell:e,t:o}),E.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,fontWeight:e.type==="markdown"&&Ia(e)===1?600:400},children:t})]})}const fA={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"},CA={duckdb:"#f4bc00",file:"#f4bc00",postgres:"#336791",bigquery:"#4285f4",snowflake:"#29b5e8",sqlite:"#003b57",mysql:"#00758f",mssql:"#cc2927",redshift:"#8c4fff",databricks:"#ff3621",clickhouse:"#ffcc00",athena:"#ff9900",trino:"#dd00a1",fabric:"#0078d4"};function LA(){const{state:e}=ae(),t=ie[e.themeMode],[n,r]=C.useState(null),[o,s]=C.useState(!1),[i,a]=C.useState(null);C.useEffect(()=>{Re.getConnections().then(r)},[]);const T=async()=>{s(!0),a(null);const S=await Re.testConnection();a(S),s(!1)},l={fontSize:10,fontWeight:600,letterSpacing:"0.07em",textTransform:"uppercase",color:t.textMuted,fontFamily:t.font,marginBottom:6},R={background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:7,padding:"10px 12px",marginBottom:10},c=(n==null?void 0:n.connections)??{},A=(n==null?void 0:n.default)??"";return E.jsxs("div",{style:{flex:1,overflow:"auto",padding:"12px 12px 20px"},children:[E.jsx("div",{style:l,children:"Active Connection"}),n===null?E.jsx("div",{style:{fontSize:12,color:t.textMuted,fontFamily:t.font},children:"Loading…"}):Object.entries(c).map(([S,d])=>{const I=(d==null?void 0:d.driver)??(d==null?void 0:d.type)??"unknown",O=S===A||Object.keys(c).length===1,u=CA[I]??t.accent;return E.jsxs("div",{style:{...R,borderLeft:O?`3px solid ${u}`:`1px solid ${t.cellBorder}`},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6},children:[E.jsx("span",{style:{fontSize:10,fontWeight:700,fontFamily:t.fontMono,color:u,background:`${u}18`,border:`1px solid ${u}40`,borderRadius:4,padding:"1px 6px",letterSpacing:"0.05em",textTransform:"uppercase"},children:fA[I]??I}),O&&E.jsx("span",{style:{fontSize:10,color:t.textMuted,fontFamily:t.font},children:"default"})]}),E.jsx("div",{style:{display:"flex",flexDirection:"column",gap:3},children:Object.entries(d??{}).filter(([f])=>f!=="driver"&&f!=="type").map(([f,N])=>E.jsxs("div",{style:{display:"flex",gap:6,alignItems:"baseline"},children:[E.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.fontMono,minWidth:70,flexShrink:0},children:f}),E.jsx("span",{style:{fontSize:11,color:t.textSecondary,fontFamily:t.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:f.toLowerCase().includes("password")?"••••••••":String(N)})]},f))})]},S)}),E.jsx("button",{onClick:T,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"}),i&&E.jsxs("div",{style:{fontSize:12,fontFamily:t.font,color:i.ok?t.success:t.error,background:i.ok?`${t.success}12`:`${t.error}12`,border:`1px solid ${i.ok?t.success:t.error}40`,borderRadius:6,padding:"7px 10px",marginBottom:12},children:[i.ok?"✓ ":"✗ ",i.message]}),E.jsx("div",{style:{...l,marginTop:4},children:"Change Connection"}),E.jsxs("div",{style:{...R,fontSize:12,fontFamily:t.font,color:t.textSecondary,lineHeight:1.6},children:["Edit ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql.config.json"})," in your project root to add or switch connections. Supported drivers:",E.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4,marginTop:8},children:[{driver:"duckdb / file",desc:"Local CSV, Parquet, DuckDB"},{driver:"postgres",desc:"PostgreSQL / Supabase / RDS"},{driver:"bigquery",desc:"Google BigQuery"},{driver:"snowflake",desc:"Snowflake"},{driver:"mysql",desc:"MySQL / MariaDB / PlanetScale"},{driver:"mssql",desc:"SQL Server / Azure SQL"},{driver:"redshift",desc:"Amazon Redshift"},{driver:"databricks",desc:"Databricks SQL"},{driver:"clickhouse",desc:"ClickHouse"},{driver:"athena",desc:"Amazon Athena"},{driver:"trino",desc:"Trino / Starburst"},{driver:"fabric",desc:"Microsoft Fabric"}].map(({driver:S,desc:d})=>E.jsxs("div",{style:{display:"flex",gap:8,alignItems:"baseline"},children:[E.jsx("code",{style:{fontSize:10,fontFamily:t.fontMono,color:t.textMuted,minWidth:80,flexShrink:0},children:S}),E.jsx("span",{style:{fontSize:11,color:t.textMuted},children:d})]},S))})]}),E.jsx("div",{style:{...l,marginTop:4},children:"Example Config"}),E.jsx("pre",{style:{background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:7,padding:"10px 12px",fontSize:11,fontFamily:t.fontMono,color:t.textSecondary,overflow:"auto",lineHeight:1.6,margin:0},children:`{
11
- "connections": {
12
- "default": {
13
- "driver": "duckdb",
14
- "path": ":memory:"
15
- },
16
- "prod": {
17
- "driver": "postgres",
18
- "host": "localhost",
19
- "port": 5432,
20
- "database": "analytics",
21
- "user": "analyst",
22
- "password": "..."
23
- }
24
- }
25
- }`})]})}function ke({title:e,defaultOpen:t=!1,children:n,t:r}){const[o,s]=C.useState(t),[i,a]=C.useState(!1);return E.jsxs("div",{style:{borderBottom:`1px solid ${r.headerBorder}`},children:[E.jsxs("button",{onClick:()=>s(T=>!T),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{width:"100%",padding:"7px 12px",display:"flex",alignItems:"center",gap:6,background:i?r.sidebarItemHover:"transparent",border:"none",cursor:"pointer",textAlign:"left",transition:"background 0.1s"},children:[E.jsx("span",{style:{fontSize:9,color:r.textMuted,display:"inline-block",transition:"transform 0.15s",transform:o?"rotate(90deg)":"rotate(0deg)",lineHeight:1},children:"▶"}),E.jsx("span",{style:{fontSize:11,fontWeight:600,fontFamily:r.font,color:r.textSecondary,letterSpacing:"0.04em"},children:e})]}),o&&E.jsx("div",{style:{padding:"4px 12px 10px"},children:n})]})}function hA({code:e,t}){const[n,r]=C.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 E.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 ue({code:e,t}){return E.jsxs("div",{style:{position:"relative",marginTop:6},children:[E.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}),E.jsx(hA,{code:e,t})]})}function qs({rows:e,t}){return E.jsx("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11,fontFamily:t.font,marginTop:6},children:E.jsx("tbody",{children:e.map(([n,r],o)=>E.jsxs("tr",{style:{borderBottom:`1px solid ${t.tableBorder}`},children:[E.jsx("td",{style:{padding:"5px 6px 5px 0",fontFamily:t.fontMono,fontSize:11,color:t.accent,whiteSpace:"nowrap",verticalAlign:"top",width:"45%"},children:n}),E.jsx("td",{style:{padding:"5px 0",color:t.textSecondary,verticalAlign:"top",lineHeight:1.5},children:r})]},o))})})}const _A=`block "Revenue by Channel" {
26
- domain = "revenue"
27
- type = "custom"
28
- description = "Revenue grouped by sales channel"
29
- owner = "data-team"
30
- tags = ["revenue"]
31
-
32
- params {
33
- period = "current_quarter"
34
- }
35
-
36
- query = """
37
- SELECT channel,
38
- SUM(order_total) AS revenue
39
- FROM read_csv_auto('data/orders.csv')
40
- WHERE fiscal_period = \${period}
41
- GROUP BY channel
42
- ORDER BY revenue DESC
43
- """
44
-
45
- visualization {
46
- chart = "bar"
47
- x = channel
48
- y = revenue
49
- }
50
-
51
- tests {
52
- assert row_count > 0
53
- }
54
- }`,pA=`# semantic-layer/metrics/total_revenue.yaml
55
- name: total_revenue
56
- label: Total Revenue
57
- description: Sum of all recognized revenue.
58
- domain: finance
59
- sql: SUM(amount)
60
- type: sum # sum|count|count_distinct|avg|min|max|custom
61
- table: fct_revenue
62
- tags:
63
- - revenue
64
- - kpi`,mA=`# semantic-layer/dimensions/segment.yaml
65
- name: segment
66
- label: Customer Segment
67
- description: Customer segment tier.
68
- sql: segment_tier
69
- type: string # string|number|date|boolean
70
- table: fct_revenue`,DA=`# semantic-layer/hierarchies/time.yaml
71
- name: fiscal_time
72
- label: Fiscal Time
73
- description: Drill from year to quarter.
74
- domain: finance
75
- levels:
76
- - name: fiscal_year
77
- dimension: fiscal_year
78
- order: 1
79
- - name: fiscal_quarter
80
- dimension: fiscal_quarter
81
- order: 2
82
- defaultRollup: sum`,gA=`# semantic-layer/cubes/revenue_cube.yaml
83
- name: revenue
84
- label: Revenue Cube
85
- table: fct_revenue
86
- domain: finance
87
-
88
- measures:
89
- - name: total_revenue
90
- sql: SUM(amount)
91
- type: sum
92
- - name: deal_count
93
- sql: COUNT(*)
94
- type: count
95
-
96
- dimensions:
97
- - name: segment_tier
98
- sql: segment_tier
99
- type: string
100
-
101
- time_dimensions:
102
- - name: recognized_at
103
- sql: recognized_at
104
- primary_time: true
105
- granularities: [day, month, quarter, year]
106
-
107
- joins:
108
- - name: customers
109
- type: left
110
- sql: "\${left}.customer_id = \${right}.id"`,PA=`{
111
- "semanticLayer": {
112
- "provider": "dql"
113
- }
114
- }`,MA=`{
115
- "semanticLayer": {
116
- "provider": "dbt",
117
- "projectPath": "/path/to/your/dbt-project"
118
- }
119
- }`,yA=`{
120
- "semanticLayer": {
121
- "provider": "cubejs",
122
- "projectPath": "/path/to/your/cube-project"
123
- }
124
- }`,xA=`{
125
- "defaultConnection": {
126
- "driver": "file",
127
- "filepath": ":memory:"
128
- }
129
- }`,UA=`{
130
- "defaultConnection": {
131
- "driver": "snowflake",
132
- "account": "acme.snowflakecomputing.com",
133
- "username": "your_user",
134
- "password": "\${SNOWFLAKE_PASSWORD}",
135
- "database": "ANALYTICS",
136
- "schema": "PUBLIC",
137
- "warehouse": "COMPUTE_WH",
138
- "role": "ANALYST"
139
- }
140
- }`,bA=`{
141
- "defaultConnection": {
142
- "driver": "bigquery",
143
- "project": "your-gcp-project-id",
144
- "dataset": "analytics",
145
- "keyFilename": "./service-account.json"
146
- }
147
- }`,GA=`{
148
- "defaultConnection": {
149
- "driver": "postgres",
150
- "host": "localhost",
151
- "port": 5432,
152
- "database": "analytics",
153
- "username": "your_user",
154
- "password": "\${POSTGRES_PASSWORD}"
155
- }
156
- }`,BA=`-- Primary workflow: use Compose Query in the Semantic Layer panel
157
- -- 1. Pick metrics + dimensions (+ optional time dimension)
158
- -- 2. Click "Compose SQL"
159
- -- 3. Click "+ Insert as Cell" → edit and run
160
-
161
- -- Advanced: reference metrics inline in any SQL cell
162
- -- DQL resolves @metric() and @dim() at query time
163
- SELECT
164
- @dim(segment_tier),
165
- @metric(total_revenue)
166
- FROM fct_revenue
167
- GROUP BY @dim(segment_tier)
168
- ORDER BY @metric(total_revenue) DESC`,vA=`{
169
- "semanticLayer": {
170
- "provider": "snowflake",
171
- "projectPath": "MY_DATABASE"
172
- }
173
- }`;function HA({themeMode:e}){const t=ie[e];return E.jsxs("div",{style:{flex:1,overflowY:"auto",fontFamily:t.font},children:[E.jsx(ke,{title:"SQL Essentials",defaultOpen:!0,t,children:E.jsx(ue,{t,code:`-- Basic select
174
- SELECT col1, col2
175
- FROM table_name
176
- WHERE condition
177
- ORDER BY col1 DESC
178
- LIMIT 100
179
-
180
- -- GROUP BY
181
- SELECT col, COUNT(*), SUM(val)
182
- FROM table_name
183
- GROUP BY col
184
-
185
- -- JOIN
186
- SELECT a.*, b.col
187
- FROM table_a AS a
188
- JOIN table_b AS b ON a.id = b.id
189
-
190
- -- CTE (WITH)
191
- WITH cte AS (
192
- SELECT * FROM table_name WHERE val > 0
193
- )
194
- SELECT * FROM cte
195
-
196
- -- Window function
197
- SELECT *,
198
- ROW_NUMBER() OVER (
199
- PARTITION BY group_col
200
- ORDER BY val DESC
201
- ) AS rank
202
- FROM table_name`})}),E.jsx(ke,{title:"DuckDB Functions",defaultOpen:!1,t,children:E.jsx(qs,{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"]]})}),E.jsxs(ke,{title:"DQL Block Structure",defaultOpen:!0,t,children:[E.jsx(ue,{t,code:_A}),E.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.6},children:["Run ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql certify <file> --connection duckdb"})," to execute ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"tests {}"})," assertions against live data. Use ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"--skip-tests"})," to check governance fields only."]})]}),E.jsxs(ke,{title:"DQL Chart Types",defaultOpen:!1,t,children:[E.jsx(qs,{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)"]]}),E.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.6},children:["Set chart type inside the"," ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:'visualization { chart = "pie"; x = label_col; y = value_col }'})," ","block."]})]}),E.jsxs(ke,{title:"Semantic Layer Usage",defaultOpen:!1,t,children:[E.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:6},children:["Primary workflow: open the ",E.jsx("strong",{children:"Semantic Layer"})," panel → Compose Query → pick metrics and dimensions → Compose SQL → + Insert as Cell. Advanced: use ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"@metric(name)"})," and ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"@dim(name)"})," refs directly in any SQL cell."]}),E.jsx(ue,{t,code:BA})]}),E.jsxs(ke,{title:"Semantic Layer",defaultOpen:!1,t,children:[E.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"," ",E.jsx("strong",{style:{color:t.textPrimary},children:"Semantic Layer"})," sidebar panel."]}),E.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"10px 0 4px",letterSpacing:"0.03em"},children:"Directory Structure"}),E.jsx(ue,{t,code:`my-project/
203
- ├── dql.config.json
204
- └── semantic-layer/
205
- ├── metrics/ ← one YAML per metric
206
- ├── dimensions/ ← one YAML per dimension
207
- ├── hierarchies/ ← optional drill paths
208
- └── cubes/ ← optional (groups all into one)`}),E.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:[E.jsx("strong",{style:{color:t.textPrimary},children:"Recommended:"})," For multi-table projects, use a ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"cubes/"})," file — it keeps metrics, dimensions, and joins together. Use standalone ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"metrics/"})," and ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dimensions/"})," files only for simple single-table projects."]}),E.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Metric YAML"}),E.jsx(ue,{t,code:pA}),E.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Dimension YAML"}),E.jsx(ue,{t,code:mA}),E.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Hierarchy YAML"}),E.jsx(ue,{t,code:DA}),E.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)"}),E.jsx(ue,{t,code:gA})]}),E.jsxs(ke,{title:"Semantic Layer Providers",defaultOpen:!1,t,children:[E.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Add to your ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql.config.json"})," to connect a semantic layer provider."]}),E.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/)"}),E.jsx(ue,{t,code:PA}),E.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)"}),E.jsx(ue,{t,code:MA}),E.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 ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dbt_project.yml"}),"). Reads ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"semantic_models"})," and"," ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"metrics"})," blocks (dbt 1.6+)."]}),E.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/)"}),E.jsx(ue,{t,code:yA}),E.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"," ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"cubes:"})," blocks from YAML schema files."]}),E.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)"}),E.jsx(ue,{t,code:vA}),E.jsxs("div",{style:{marginTop:4,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:["Introspects Snowflake semantic views via"," ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"SHOW SEMANTIC VIEWS"}),". Set ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"projectPath"})," to your database name to scope discovery. Requires a Snowflake connection in ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"defaultConnection"}),"."]})]}),E.jsxs(ke,{title:"Connection Setup",defaultOpen:!1,t,children:[E.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Configure ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"defaultConnection"})," in"," ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql.config.json"}),"."]}),E.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)"}),E.jsx(ue,{t,code:xA}),E.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Snowflake"}),E.jsx(ue,{t,code:UA}),E.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"BigQuery"}),E.jsx(ue,{t,code:bA}),E.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"PostgreSQL"}),E.jsx(ue,{t,code:GA}),E.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:["Use ",E.jsxs("code",{style:{fontFamily:t.fontMono,fontSize:10},children:["$","${ENV_VAR}"]})," syntax for secrets. Run ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dql doctor"})," to verify your connection."]})]}),E.jsxs(ke,{title:"Variable References",defaultOpen:!1,t,children:[E.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Use"," ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"{{cell_name}}"})," ","to reference other cells:",E.jsxs("ul",{style:{margin:"6px 0 0",paddingLeft:18},children:[E.jsxs("li",{children:[E.jsx("strong",{children:"Param cell"})," → substituted as a SQL literal value"]}),E.jsxs("li",{children:[E.jsx("strong",{children:"SQL cell"})," → injected as a CTE"]})]})]}),E.jsx(ue,{t,code:`-- Param cell named "start_date" holds '2024-01-01'
209
- SELECT *
210
- FROM read_csv_auto('data/sales.csv')
211
- WHERE date >= {{start_date}}
212
-
213
- -- SQL cell named "base_query" used as CTE
214
- SELECT segment, SUM(revenue) AS total
215
- FROM {{base_query}}
216
- GROUP BY segment`})]})]})}const ua={sum:"#56d364",count:"#388bfd",count_distinct:"#388bfd",avg:"#e3b341",min:"#f778ba",max:"#f778ba",custom:"#d2a8ff"};function FA(){return E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M8 1a7 7 0 1 0 0 14A7 7 0 0 0 8 1Zm0 1.5a5.5 5.5 0 1 1 0 11 5.5 5.5 0 0 1 0-11Zm0 2a.75.75 0 0 1 .75.75v2h2a.75.75 0 0 1 0 1.5h-2v2a.75.75 0 0 1-1.5 0v-2h-2a.75.75 0 0 1 0-1.5h2v-2A.75.75 0 0 1 8 4.5Z"})})}function wA(){return E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M1 2.75C1 1.784 1.784 1 2.75 1h10.5c.966 0 1.75.784 1.75 1.75v10.5A1.75 1.75 0 0 1 13.25 15H2.75A1.75 1.75 0 0 1 1 13.25Zm1.75-.25a.25.25 0 0 0-.25.25v10.5c0 .138.112.25.25.25h10.5a.25.25 0 0 0 .25-.25V2.75a.25.25 0 0 0-.25-.25ZM8 4a.75.75 0 0 1 .75.75v6.5a.75.75 0 0 1-1.5 0v-6.5A.75.75 0 0 1 8 4Zm-3 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 5 7Zm6-1a.75.75 0 0 1 .75.75v4.5a.75.75 0 0 1-1.5 0v-4.5A.75.75 0 0 1 11 6Z"})})}function YA(){return E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M8 1a1 1 0 0 1 1 1v2.586l2.293-2.293a1 1 0 0 1 1.414 1.414L10.414 6H13a1 1 0 1 1 0 2h-2.586l2.293 2.293a1 1 0 0 1-1.414 1.414L9 9.414V12a1 1 0 1 1-2 0V9.414l-2.293 2.293a1 1 0 0 1-1.414-1.414L5.586 8H3a1 1 0 0 1 0-2h2.586L3.293 3.707a1 1 0 0 1 1.414-1.414L7 4.586V2a1 1 0 0 1 1-1Z"})})}function Yr({label:e,count:t,expanded:n,onToggle:r,t:o}){const[s,i]=C.useState(!1);return E.jsxs("button",{onClick:r,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"3px 8px 3px 10px",background:s?o.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:o.textSecondary,fontSize:11,fontWeight:600,fontFamily:o.font,letterSpacing:"0.04em",textTransform:"uppercase",textAlign:"left",transition:"background 0.1s"},children:[E.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:E.jsx("path",{d:"M3 2l4 3-4 3V2Z"})}),E.jsx("span",{style:{flex:1},children:e}),t>0&&E.jsx("span",{style:{background:o.pillBg,color:o.textMuted,borderRadius:10,padding:"0 5px",fontSize:10,fontWeight:500},children:t})]})}function VA({metric:e,t}){const[n,r]=C.useState(!1),[o,s]=C.useState(!1),i=ua[e.type]??t.accent;return E.jsxs("div",{children:[E.jsxs("button",{onClick:()=>s(!o),onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 8px 4px 22px",background:n?t.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:t.textPrimary,fontSize:12,fontFamily:t.font,textAlign:"left",transition:"background 0.1s"},children:[E.jsx("span",{style:{color:i,flexShrink:0},children:E.jsx(FA,{})}),E.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.label||e.name}),E.jsx("span",{style:{fontSize:9,fontFamily:t.fontMono,color:i,background:`${i}18`,borderRadius:4,padding:"1px 4px",flexShrink:0},children:e.type})]}),o&&E.jsxs("div",{style:{padding:"2px 8px 6px 40px",fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:[e.description&&E.jsx("div",{children:e.description}),E.jsxs("div",{style:{fontFamily:t.fontMono,fontSize:10,color:t.textSecondary,marginTop:2},children:["table: ",e.table]}),e.domain&&E.jsxs("div",{style:{fontFamily:t.fontMono,fontSize:10,color:t.textSecondary},children:["domain: ",e.domain]}),e.tags.length>0&&E.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap",marginTop:3},children:e.tags.map(a=>E.jsx("span",{style:{fontSize:9,background:t.pillBg,color:t.textMuted,borderRadius:3,padding:"1px 4px"},children:a},a))})]})]})}function WA({dimension:e,t}){const[n,r]=C.useState(!1),o=e.type==="date"?"#e3b341":e.type==="number"?"#56d364":"#388bfd";return E.jsxs("div",{onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 8px 4px 22px",background:n?t.sidebarItemHover:"transparent",cursor:"default",transition:"background 0.1s"},children:[E.jsx("span",{style:{color:t.textMuted,flexShrink:0},children:E.jsx(wA,{})}),E.jsx("span",{style:{flex:1,fontSize:12,fontFamily:t.font,color:t.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.description,children:e.label||e.name}),E.jsx("span",{style:{fontSize:9,fontFamily:t.fontMono,color:o,background:`${o}18`,borderRadius:4,padding:"1px 4px",flexShrink:0},children:e.type})]})}function kA({hierarchy:e,t}){const[n,r]=C.useState(!1),[o,s]=C.useState(!1);return E.jsxs("div",{children:[E.jsxs("button",{onClick:()=>s(!o),onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 8px 4px 22px",background:n?t.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:t.textSecondary,fontSize:12,fontFamily:t.font,textAlign:"left",transition:"background 0.1s"},children:[E.jsx("span",{style:{color:"#d2a8ff",flexShrink:0},children:E.jsx(YA,{})}),E.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.label||e.name}),E.jsx("span",{style:{fontSize:10,color:t.textMuted,background:t.pillBg,borderRadius:8,padding:"1px 5px",flexShrink:0},children:e.levels.length})]}),o&&E.jsx("div",{style:{paddingLeft:40},children:e.levels.map((i,a)=>E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"2px 0",fontSize:11,fontFamily:t.fontMono,color:t.textMuted},children:[E.jsxs("span",{style:{color:t.textMuted,fontSize:9},children:[a+1,"."]}),i.label||i.name]},i.name))})]})}const XA=["day","week","month","quarter","year"];function jA({t:e,metrics:t,dimensions:n,onInsertCell:r}){const[o,s]=C.useState(!1),[i,a]=C.useState(new Set),[T,l]=C.useState(new Set),[R,c]=C.useState(""),[A,S]=C.useState("month"),[d,I]=C.useState(null),[O,u]=C.useState(null),[f,N]=C.useState(!1),[L,m]=C.useState(!1),p=n.filter(_=>_.type==="date"),D=_=>{a(U=>{const h=new Set(U);return h.has(_)?h.delete(_):h.add(_),h}),I(null)},M=_=>{l(U=>{const h=new Set(U);return h.has(_)?h.delete(_):h.add(_),h}),I(null)},B=async()=>{if(i.size!==0){N(!0),u(null);try{const _=R?{name:R,granularity:A}:void 0,U=await Re.composeQuery(Array.from(i),Array.from(T),_);"error"in U?u(U.error):I(U.sql)}catch(_){u(_.message??"Failed to compose")}finally{N(!1)}}},F=()=>{d&&(navigator.clipboard.writeText(d),m(!0),setTimeout(()=>m(!1),1500))},g=_=>({width:14,height:14,borderRadius:3,border:`1.5px solid ${_?e.accent:e.cellBorder}`,background:_?e.accent:"transparent",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,transition:"all 0.15s"});return E.jsxs("div",{style:{borderBottom:`1px solid ${e.headerBorder}`},children:[E.jsxs("button",{onClick:()=>s(!o),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"6px 10px",background:o?`${e.accent}10`:"transparent",border:"none",cursor:"pointer",color:e.accent,fontSize:11,fontWeight:600,fontFamily:e.font,textAlign:"left"},children:[E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:E.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"})}),"Compose Query",E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",style:{marginLeft:"auto",transform:o?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.15s"},children:E.jsx("path",{d:"M3 2l4 3-4 3V2Z"})})]}),o&&E.jsxs("div",{style:{padding:"6px 10px 10px",fontSize:11,fontFamily:e.font},children:[E.jsx("div",{style:{fontSize:10,fontWeight:600,color:e.textSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Select Metrics"}),E.jsx("div",{style:{maxHeight:120,overflowY:"auto",marginBottom:8},children:t.map(_=>E.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,padding:"2px 0",cursor:"pointer",color:e.textPrimary,fontSize:11},onClick:()=>D(_.name),children:[E.jsx("div",{style:g(i.has(_.name)),children:i.has(_.name)&&E.jsx("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"#fff",children:E.jsx("path",{d:"M8.5 2.5L4 7 1.5 4.5",stroke:"#fff",strokeWidth:"1.5",fill:"none"})})}),E.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:_.label||_.name}),E.jsx("span",{style:{fontSize:9,color:ua[_.type]??e.accent,marginLeft:"auto",flexShrink:0},children:_.type})]},_.name))}),E.jsx("div",{style:{fontSize:10,fontWeight:600,color:e.textSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Select Dimensions (optional)"}),E.jsx("div",{style:{maxHeight:120,overflowY:"auto",marginBottom:8},children:n.map(_=>E.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,padding:"2px 0",cursor:"pointer",color:e.textPrimary,fontSize:11},onClick:()=>M(_.name),children:[E.jsx("div",{style:g(T.has(_.name)),children:T.has(_.name)&&E.jsx("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"#fff",children:E.jsx("path",{d:"M8.5 2.5L4 7 1.5 4.5",stroke:"#fff",strokeWidth:"1.5",fill:"none"})})}),E.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:_.label||_.name})]},_.name))}),p.length>0&&E.jsxs("div",{style:{marginBottom:8},children:[E.jsx("div",{style:{fontSize:10,fontWeight:600,color:e.textSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Time Dimension (optional)"}),E.jsxs("select",{value:R,onChange:_=>{c(_.target.value),I(null)},style:{width:"100%",padding:"3px 6px",background:e.editorBg,border:`1px solid ${e.cellBorder}`,borderRadius:4,color:R?e.textPrimary:e.textMuted,fontSize:11,fontFamily:e.font,marginBottom:4,cursor:"pointer"},children:[E.jsx("option",{value:"",children:"None"}),p.map(_=>E.jsx("option",{value:_.name,children:_.label||_.name},_.name))]}),R&&E.jsx("div",{style:{display:"flex",gap:4},children:XA.map(_=>E.jsx("button",{onClick:()=>{S(_),I(null)},style:{flex:1,padding:"2px 0",background:A===_?e.accent:e.pillBg,border:"none",borderRadius:3,color:A===_?"#fff":e.textMuted,fontSize:9,fontWeight:600,fontFamily:e.font,cursor:"pointer",textTransform:"capitalize"},children:_},_))})]}),E.jsx("button",{onClick:B,disabled:i.size===0||f,style:{width:"100%",padding:"5px 12px",background:i.size===0?e.pillBg:e.accent,color:i.size===0?e.textMuted:"#fff",border:"none",borderRadius:5,cursor:i.size===0?"not-allowed":"pointer",fontSize:11,fontWeight:600,fontFamily:e.font,opacity:f?.7:1},children:f?"Composing...":`Compose SQL (${i.size} metric${i.size!==1?"s":""})`}),O&&E.jsx("div",{style:{marginTop:6,padding:"4px 8px",background:"#f8514922",border:"1px solid #f8514944",borderRadius:4,fontSize:10,color:"#f85149"},children:O}),d&&E.jsxs("div",{style:{marginTop:8},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4},children:[E.jsx("span",{style:{fontSize:10,fontWeight:600,color:e.textSecondary,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Generated SQL"}),E.jsxs("div",{style:{display:"flex",gap:4},children:[r&&E.jsx("button",{onClick:()=>d&&r(d),style:{background:e.accent,border:"none",borderRadius:3,color:"#fff",cursor:"pointer",fontSize:9,fontWeight:600,fontFamily:e.font,padding:"2px 8px"},children:"+ Insert as Cell"}),E.jsx("button",{onClick:F,style:{background:"transparent",border:`1px solid ${e.cellBorder}`,borderRadius:3,color:L?"#56d364":e.textMuted,cursor:"pointer",fontSize:9,fontFamily:e.font,padding:"1px 6px"},children:L?"Copied!":"Copy"})]})]}),E.jsx("pre",{style:{margin:0,padding:"6px 8px",background:e.editorBg,border:`1px solid ${e.cellBorder}`,borderRadius:4,fontFamily:e.fontMono,fontSize:10,color:e.textSecondary,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-all",maxHeight:200,overflowY:"auto"},children:d})]})]})]})}const $A=["sum","count","count_distinct","avg","min","max"];function KA({t:e,onClose:t,onCreated:n}){const[r,o]=C.useState(""),[s,i]=C.useState(""),[a,T]=C.useState(""),[l,R]=C.useState("sum"),[c,A]=C.useState(""),[S,d]=C.useState(""),[I,O]=C.useState(""),[u,f]=C.useState(!1),[N,L]=C.useState(null),m={width:"100%",padding:"4px 7px",background:e.editorBg,border:`1px solid ${e.cellBorder}`,borderRadius:4,color:e.textPrimary,fontSize:11,fontFamily:e.fontMono,outline:"none",boxSizing:"border-box"},p={fontSize:10,fontWeight:600,color:e.textSecondary,fontFamily:e.font,letterSpacing:"0.04em",textTransform:"uppercase",display:"block",marginBottom:3,marginTop:8},D=async()=>{if(!r.trim()||!a.trim()||!c.trim()){L("Name, SQL expression, and table are required.");return}f(!0),L(null);const M=await Re.createMetric({name:r.trim(),label:s.trim()||r.trim(),description:I.trim(),domain:S.trim()||"general",sql:a.trim(),type:l,table:c.trim()});f(!1),M.ok?(n(),t()):L(M.error??"Unknown error")};return E.jsxs("div",{style:{position:"absolute",inset:0,zIndex:100,background:`${e.sidebarBg}f0`,display:"flex",flexDirection:"column",padding:"12px 14px",overflowY:"auto"},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10},children:[E.jsx("span",{style:{fontSize:12,fontWeight:600,color:e.textPrimary,fontFamily:e.font},children:"New Metric"}),E.jsx("button",{onClick:t,style:{background:"transparent",border:"none",cursor:"pointer",color:e.textMuted,fontSize:16,fontFamily:e.font,padding:"0 2px"},children:"×"})]}),E.jsx("span",{style:p,children:"Name *"}),E.jsx("input",{style:m,value:r,onChange:M=>o(M.target.value),placeholder:"total_revenue"}),E.jsx("span",{style:p,children:"Label"}),E.jsx("input",{style:m,value:s,onChange:M=>i(M.target.value),placeholder:"Total Revenue"}),E.jsx("span",{style:p,children:"SQL Expression *"}),E.jsx("input",{style:m,value:a,onChange:M=>T(M.target.value),placeholder:"SUM(amount)"}),E.jsx("span",{style:p,children:"Aggregation Type *"}),E.jsx("select",{value:l,onChange:M=>R(M.target.value),style:{...m,cursor:"pointer"},children:$A.map(M=>E.jsx("option",{value:M,children:M},M))}),E.jsx("span",{style:p,children:"Table / Source *"}),E.jsx("input",{style:m,value:c,onChange:M=>A(M.target.value),placeholder:"fct_revenue or read_csv_auto('data/revenue.csv')"}),E.jsx("span",{style:p,children:"Domain"}),E.jsx("input",{style:m,value:S,onChange:M=>d(M.target.value),placeholder:"finance"}),E.jsx("span",{style:p,children:"Description"}),E.jsx("input",{style:m,value:I,onChange:M=>O(M.target.value),placeholder:"Sum of all recognized revenue"}),N&&E.jsx("div",{style:{marginTop:8,padding:"4px 8px",background:"#f8514922",border:"1px solid #f8514944",borderRadius:4,fontSize:10,color:"#f85149"},children:N}),E.jsxs("div",{style:{display:"flex",gap:6,marginTop:12},children:[E.jsx("button",{onClick:D,disabled:u,style:{flex:1,padding:"5px 0",background:e.accent,color:"#fff",border:"none",borderRadius:5,fontSize:11,fontWeight:600,fontFamily:e.font,cursor:u?"not-allowed":"pointer",opacity:u?.7:1},children:u?"Creating...":"Create Metric"}),E.jsx("button",{onClick:t,style:{padding:"5px 12px",background:"transparent",border:`1px solid ${e.cellBorder}`,borderRadius:5,fontSize:11,fontFamily:e.font,color:e.textMuted,cursor:"pointer"},children:"Cancel"})]}),E.jsxs("div",{style:{marginTop:10,fontSize:10,color:e.textMuted,fontFamily:e.font,lineHeight:1.5},children:["Creates ",E.jsxs("code",{style:{fontFamily:e.fontMono},children:["semantic-layer/metrics/","{name}",".yaml"]})," and reloads the panel automatically."]})]})}function JA(){const{state:e,dispatch:t}=ae(),n=ie[e.themeMode],[r,o]=C.useState(""),[s,i]=C.useState(!1),[a,T]=C.useState(!1),[l,R]=C.useState({metrics:!0,dimensions:!0,hierarchies:!1}),c=e.semanticLayer,A=async()=>{t({type:"SET_SEMANTIC_LOADING",loading:!0});try{const p=await Re.getSemanticLayer();t({type:"SET_SEMANTIC_LAYER",layer:p})}catch(p){console.error("Semantic layer refresh failed:",p)}finally{t({type:"SET_SEMANTIC_LOADING",loading:!1})}};C.useEffect(()=>{c.metrics.length===0&&!c.loading&&A()},[]);const S=r.toLowerCase(),d=C.useMemo(()=>S?c.metrics.filter(p=>p.name.toLowerCase().includes(S)||p.label.toLowerCase().includes(S)||p.description.toLowerCase().includes(S)||p.tags.some(D=>D.toLowerCase().includes(S))):c.metrics,[c.metrics,S]),I=C.useMemo(()=>S?c.dimensions.filter(p=>p.name.toLowerCase().includes(S)||p.label.toLowerCase().includes(S)||p.description.toLowerCase().includes(S)):c.dimensions,[c.dimensions,S]),O=C.useMemo(()=>S?c.hierarchies.filter(p=>p.name.toLowerCase().includes(S)||p.label.toLowerCase().includes(S)):c.hierarchies,[c.hierarchies,S]),u=p=>{R(D=>({...D,[p]:!D[p]}))},f={background:n.pillBg,padding:"1px 4px",borderRadius:3,fontSize:10,fontFamily:n.fontMono},N={fontSize:11,fontWeight:600,color:n.textPrimary,fontFamily:n.font,marginBottom:4},L={fontSize:11,color:n.textMuted,fontFamily:n.font,lineHeight:1.6,marginBottom:2},m={margin:"4px 0 0",padding:"6px 8px",background:n.editorBg,border:`1px solid ${n.cellBorder}`,borderRadius:4,fontFamily:n.fontMono,fontSize:10,color:n.textSecondary,lineHeight:1.5,whiteSpace:"pre",overflowX:"auto"};return!c.available&&!c.loading?E.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"12px 14px",fontFamily:n.font},children:[E.jsxs("div",{style:{textAlign:"center",marginBottom:14},children:[E.jsx("svg",{width:"28",height:"28",viewBox:"0 0 16 16",fill:n.accent,style:{opacity:.7},children:E.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"})}),E.jsx("div",{style:{fontSize:12,fontWeight:600,color:n.textPrimary,marginTop:6},children:"Set Up Semantic Layer"}),E.jsx("div",{style:{fontSize:11,color:n.textMuted,marginTop:2,lineHeight:1.5},children:"Choose a provider below, then click Retry."})]}),E.jsxs("div",{style:{marginBottom:12},children:[E.jsx("div",{style:N,children:"Step 1: Pick a provider"}),E.jsxs("div",{style:L,children:["Add ",E.jsx("code",{style:f,children:"semanticLayer"})," to your ",E.jsx("code",{style:f,children:"dql.config.json"}),":"]}),E.jsx("div",{style:{fontSize:10,fontWeight:600,color:n.accent,marginTop:8,letterSpacing:"0.03em"},children:"A) DQL Native — write YAML files directly"}),E.jsx("pre",{style:m,children:`"semanticLayer": {
217
- "provider": "dql"
218
- }`}),E.jsx("div",{style:{fontSize:10,fontWeight:600,color:n.accent,marginTop:8,letterSpacing:"0.03em"},children:"B) dbt — point to your dbt project"}),E.jsx("pre",{style:m,children:`"semanticLayer": {
219
- "provider": "dbt",
220
- "projectPath": "/path/to/dbt-project"
221
- }`}),E.jsx("div",{style:{fontSize:10,fontWeight:600,color:n.accent,marginTop:8,letterSpacing:"0.03em"},children:"C) Cube.js — point to your Cube project"}),E.jsx("pre",{style:m,children:`"semanticLayer": {
222
- "provider": "cubejs",
223
- "projectPath": "/path/to/cube-project"
224
- }`}),E.jsx("div",{style:{fontSize:10,fontWeight:600,color:n.accent,marginTop:8,letterSpacing:"0.03em"},children:"D) Snowflake — introspects Snowflake semantic views"}),E.jsx("pre",{style:m,children:`"semanticLayer": {
225
- "provider": "snowflake",
226
- "projectPath": "MY_DATABASE"
227
- }`}),E.jsxs("div",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font,marginTop:3,lineHeight:1.5},children:["Requires a Snowflake ",E.jsx("code",{style:{fontFamily:n.fontMono,fontSize:9},children:"defaultConnection"}),". DQL introspects semantic views automatically."]})]}),E.jsxs("div",{style:{marginBottom:12},children:[E.jsx("div",{style:N,children:"Step 2: Add definitions (DQL native only)"}),E.jsx("div",{style:L,children:"Create YAML files in your project:"}),E.jsx("pre",{style:m,children:`semantic-layer/
228
- metrics/total_revenue.yaml
229
- dimensions/segment.yaml
230
- hierarchies/time.yaml (optional)
231
- cubes/revenue_cube.yaml (optional)`}),E.jsx("div",{style:{...L,marginTop:6},children:"Minimal metric example:"}),E.jsx("pre",{style:m,children:`name: total_revenue
232
- label: Total Revenue
233
- sql: SUM(amount)
234
- type: sum
235
- table: fct_revenue`})]}),E.jsxs("div",{style:{marginBottom:14},children:[E.jsx("div",{style:N,children:"Step 3: Restart & refresh"}),E.jsxs("div",{style:L,children:["Restart ",E.jsx("code",{style:f,children:"dql notebook"}),", then click Retry below."]})]}),E.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"center"},children:[E.jsx("button",{onClick:A,style:{background:n.accent,border:"none",borderRadius:6,color:"#fff",cursor:"pointer",fontSize:11,fontWeight:600,fontFamily:n.font,padding:"6px 16px"},children:"Retry"}),E.jsx("button",{onClick:()=>t({type:"SET_SIDEBAR_PANEL",panel:"reference"}),style:{background:"transparent",border:`1px solid ${n.cellBorder}`,borderRadius:6,color:n.textSecondary,cursor:"pointer",fontSize:11,fontFamily:n.font,padding:"6px 12px"},children:"Full Reference"})]})]}):E.jsxs("div",{style:{flex:1,overflow:"auto",display:"flex",flexDirection:"column",position:"relative"},children:[a&&E.jsx(KA,{t:n,onClose:()=>T(!1),onCreated:()=>A()}),E.jsxs("div",{style:{padding:"8px 10px",display:"flex",alignItems:"center",gap:6,borderBottom:`1px solid ${n.headerBorder}`},children:[c.provider&&E.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:c.provider}),E.jsxs("span",{style:{flex:1,fontSize:11,color:n.textMuted,fontFamily:n.font},children:[c.metrics.length," metrics"]}),E.jsx("button",{onClick:()=>T(!0),title:"Create a new metric YAML file",style:{background:n.accent,border:"none",borderRadius:4,color:"#fff",cursor:"pointer",fontSize:10,fontWeight:600,fontFamily:n.font,padding:"2px 8px"},children:"+ New"}),E.jsx("button",{onClick:A,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),title:"Refresh semantic layer",style:{background:s?n.btnHover:"transparent",border:`1px solid ${s?n.btnBorder:"transparent"}`,borderRadius:4,cursor:"pointer",color:s?n.textSecondary:n.textMuted,fontSize:11,fontFamily:n.font,padding:"2px 6px",display:"flex",alignItems:"center",gap:4,transition:"all 0.15s"},children:E.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:E.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"})})})]}),E.jsx(jA,{t:n,metrics:c.metrics,dimensions:c.dimensions,onInsertCell:p=>{const D=fe("sql",p);t({type:"ADD_CELL",cell:D})}}),E.jsx("div",{style:{padding:"6px 8px",borderBottom:`1px solid ${n.headerBorder}`},children:E.jsx("input",{type:"text",placeholder:"Search metrics, dimensions...",value:r,onChange:p=>o(p.target.value),style:{width:"100%",padding:"4px 8px",background:n.cellBg,border:`1px solid ${n.cellBorder}`,borderRadius:4,color:n.textPrimary,fontSize:11,fontFamily:n.font,outline:"none"}})}),c.loading?E.jsxs("div",{style:{padding:"8px 12px",display:"flex",flexDirection:"column",gap:8},children:[[1,2,3].map(p=>E.jsx("div",{style:{height:28,borderRadius:4,background:n.pillBg,opacity:.6,animation:"pulse 1.5s ease-in-out infinite"}},p)),E.jsx("style",{children:"@keyframes pulse { 0%,100%{opacity:.6} 50%{opacity:.3} }"})]}):E.jsxs("div",{style:{overflow:"auto",flex:1},children:[E.jsx(Yr,{label:"Metrics",count:d.length,expanded:l.metrics,onToggle:()=>u("metrics"),t:n}),l.metrics&&E.jsx("div",{children:d.length===0?E.jsx("div",{style:{padding:"4px 14px 4px 32px",fontSize:12,color:n.textMuted,fontFamily:n.font,fontStyle:"italic"},children:S?"No matching metrics":"No metrics defined"}):d.map(p=>E.jsx(VA,{metric:p,t:n},p.name))}),E.jsx(Yr,{label:"Dimensions",count:I.length,expanded:l.dimensions,onToggle:()=>u("dimensions"),t:n}),l.dimensions&&E.jsx("div",{children:I.length===0?E.jsx("div",{style:{padding:"4px 14px 4px 32px",fontSize:12,color:n.textMuted,fontFamily:n.font,fontStyle:"italic"},children:S?"No matching dimensions":"No dimensions defined"}):I.map(p=>E.jsx(WA,{dimension:p,t:n},p.name))}),c.hierarchies.length>0&&E.jsxs(E.Fragment,{children:[E.jsx(Yr,{label:"Hierarchies",count:O.length,expanded:l.hierarchies,onToggle:()=>u("hierarchies"),t:n}),l.hierarchies&&E.jsx("div",{children:O.map(p=>E.jsx(kA,{hierarchy:p,t:n},p.name))})]})]})]})}const Na={source_table:"#8b949e",block:"#56d364",metric:"#388bfd",dimension:"#e3b341",domain:"#d2a8ff",chart:"#f778ba"},zA={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 Oa({type:e}){const t=Na[e]??"#8b949e";return E.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 qA({status:e}){if(!e)return null;const t=zA[e];return t?E.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 Un({label:e,count:t,expanded:n,onToggle:r,t:o}){const[s,i]=C.useState(!1);return E.jsxs("button",{onClick:r,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!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:[E.jsx("span",{style:{fontSize:10},children:n?"▼":"▶"}),E.jsx("span",{style:{flex:1},children:e}),E.jsx("span",{style:{color:o.textMuted,fontWeight:400},children:t})]})}function jt({node:e,t,onClick:n}){const[r,o]=C.useState(!1);return E.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:[E.jsx(Oa,{type:e.type}),E.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),E.jsx(qA,{status:e.status})]})}function ZA(){const{state:e,dispatch:t}=ae(),n=ie[e.themeMode],[r,o]=C.useState(!0),[s,i]=C.useState([]),[a,T]=C.useState([]),[l,R]=C.useState(null),[c,A]=C.useState(null),[S,d]=C.useState(!0),[I,O]=C.useState(!0),[u,f]=C.useState(!0),[N,L]=C.useState(!0),m=C.useCallback(async()=>{o(!0);const _=await Re.fetchLineage();i(_.nodes),T(_.edges),o(!1)},[]);C.useEffect(()=>{m()},[m]);const p=C.useCallback(async _=>{if(l===_){R(null),A(null);return}R(_);const U=await Re.fetchBlockLineage(_);U&&A({ancestors:U.ancestors,descendants:U.descendants})},[l]),D=s.filter(_=>_.type==="block"),M=s.filter(_=>_.type==="metric"),B=s.filter(_=>_.type==="source_table"),F=[...new Set(s.map(_=>_.domain).filter(Boolean))],g=a.filter(_=>_.type==="crosses_domain");return r?E.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"Loading lineage..."}):s.length===0?E.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."}):E.jsxs("div",{style:{overflow:"auto",flex:1,fontSize:12},children:[E.jsxs("div",{style:{padding:"6px 8px",borderBottom:`1px solid ${n.headerBorder}`},children:[E.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:[E.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[E.jsx("circle",{cx:"6",cy:"6",r:"3"}),E.jsx("circle",{cx:"18",cy:"6",r:"3"}),E.jsx("circle",{cx:"18",cy:"18",r:"3"}),E.jsx("line",{x1:"8.6",y1:"7.4",x2:"15.4",y2:"16.6"}),E.jsx("line",{x1:"9",y1:"6",x2:"15",y2:"6"})]}),e.lineageFullscreen?"Close Graph View":"Open Graph View"]}),E.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",fontSize:11,color:n.textMuted},children:[E.jsxs("span",{children:[D.length," blocks"]}),E.jsxs("span",{children:[M.length," metrics"]}),E.jsxs("span",{children:[B.length," tables"]}),g.length>0&&E.jsxs("span",{style:{color:"#d2a8ff"},children:[g.length," cross-domain"]})]})]}),l&&c&&E.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`},children:[E.jsxs("div",{style:{fontWeight:600,color:n.textPrimary,marginBottom:4,display:"flex",alignItems:"center",gap:4},children:[E.jsx(Oa,{type:"block"}),l,E.jsx("button",{onClick:()=>{R(null),A(null)},style:{marginLeft:"auto",background:"transparent",border:"none",color:n.textMuted,cursor:"pointer",fontSize:14},children:"×"})]}),c.ancestors.length>0&&E.jsxs("div",{style:{marginTop:4},children:[E.jsxs("div",{style:{color:n.textMuted,fontSize:10,fontWeight:600,textTransform:"uppercase",marginBottom:2},children:["Upstream (",c.ancestors.length,")"]}),c.ancestors.map(_=>E.jsx(jt,{node:_,t:n},_.id))]}),c.descendants.length>0&&E.jsxs("div",{style:{marginTop:4},children:[E.jsxs("div",{style:{color:n.textMuted,fontSize:10,fontWeight:600,textTransform:"uppercase",marginBottom:2},children:["Downstream (",c.descendants.length,")"]}),c.descendants.map(_=>E.jsx(jt,{node:_,t:n},_.id))]})]}),E.jsx(Un,{label:"Blocks",count:D.length,expanded:S,onToggle:()=>d(!S),t:n}),S&&D.map(_=>E.jsx(jt,{node:_,t:n,onClick:()=>p(_.name)},_.id)),E.jsx(Un,{label:"Metrics",count:M.length,expanded:I,onToggle:()=>O(!I),t:n}),I&&M.map(_=>E.jsx(jt,{node:_,t:n},_.id)),E.jsx(Un,{label:"Source Tables",count:B.length,expanded:u,onToggle:()=>f(!u),t:n}),u&&B.map(_=>E.jsx(jt,{node:_,t:n},_.id)),E.jsx(Un,{label:"Domains",count:F.length,expanded:N,onToggle:()=>L(!N),t:n}),N&&F.map(_=>{const U=D.filter(P=>P.domain===_),h=U.filter(P=>P.status==="certified").length,x=U.length>0?Math.round(h/U.length*100):0;return E.jsxs("div",{style:{padding:"3px 8px 3px 20px",fontSize:12,color:n.textPrimary,display:"flex",gap:4,alignItems:"center"},children:[E.jsx("span",{style:{color:Na.domain,fontSize:10,fontWeight:600},children:"DOM"}),E.jsx("span",{style:{flex:1},children:_}),E.jsxs("span",{style:{color:n.textMuted,fontSize:10},children:[h,"/",U.length," (",x,"%)"]})]},_)}),g.length>0&&E.jsxs(E.Fragment,{children:[E.jsx("div",{style:{padding:"6px 8px",fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.5px",color:n.textPrimary},children:"Cross-Domain Flows"}),g.map((_,U)=>E.jsxs("div",{style:{padding:"2px 8px 2px 20px",fontSize:11,color:n.textMuted},children:[_.sourceDomain," → ",_.targetDomain]},U))]})]})}const QA={files:"Explorer",schema:"Schema",semantic:"Semantic Layer",lineage:"Lineage",outline:"Outline",connection:"Connection",reference:"Quick Reference"};function eS({onOpenFile:e,onNavigateToCell:t}){const{state:n,dispatch:r}=ae(),o=ie[n.themeMode],[s,i]=C.useState(!1),a=n.sidebarPanel;return E.jsxs("div",{style:{width:240,flexShrink:0,background:o.sidebarBg,borderRight:`1px solid ${o.headerBorder}`,display:"flex",flexDirection:"column",overflow:"hidden"},children:[E.jsxs("div",{style:{height:36,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 10px 0 14px",borderBottom:`1px solid ${o.headerBorder}`},children:[E.jsx("span",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.06em",textTransform:"uppercase",color:o.textSecondary,fontFamily:o.font},children:QA[a??""]??""}),E.jsx("button",{title:"Collapse sidebar",onClick:()=>r({type:"TOGGLE_SIDEBAR"}),onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{background:"transparent",border:"none",cursor:"pointer",color:s?o.textPrimary:o.textMuted,padding:"2px 4px",borderRadius:4,fontSize:14,lineHeight:1,transition:"color 0.15s",display:"flex",alignItems:"center"},children:"‹"})]}),E.jsxs("div",{style:{flex:1,overflow:"hidden",display:"flex",flexDirection:"column"},children:[a==="files"&&E.jsx(EA,{onOpenFile:e}),a==="schema"&&E.jsx(AA,{}),a==="semantic"&&E.jsx(JA,{}),a==="lineage"&&E.jsx(ZA,{}),a==="outline"&&E.jsx(NA,{onNavigate:t}),a==="connection"&&E.jsx(LA,{}),a==="reference"&&E.jsx(HA,{themeMode:n.themeMode})]})]})}function tS(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 i=s[1],a=s[2].trim();r.push({id:$e(),type:"markdown",content:`# ${i}`,status:"idle"}),a&&r.push({id:$e(),type:"dql",name:i.toLowerCase().replace(/\s+/g,"_"),content:a,status:"idle"})}return r.length===0&&r.push({id:$e(),type:"dql",content:e.trim(),status:"idle"}),{title:n,cells:r}}catch{return{title:"Untitled Workbook",cells:[{id:$e(),type:"dql",content:e.trim(),status:"idle"}]}}}function nS(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||$e(),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:$e(),type:"sql",content:e,status:"idle"}]}}}function rS(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 oS(e,t){return e.endsWith(".dql")?tS(t):nS(t)}function sS(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(i=>`(${n.map(T=>{const l=i[T];return l==null?"NULL":typeof l=="number"?String(l):typeof l=="boolean"?l?"TRUE":"FALSE":`'${String(l).replace(/'/g,"''")}'`}).join(", ")})`).join(`,
236
- `),s=n.map(i=>`"${i.replace(/"/g,'""')}"`).join(", ");return`${e} AS (
237
- SELECT * FROM (VALUES
238
- ${o}
239
- ) AS _t(${s})
240
- )`}function iS(e,t){if(t==="number"){const n=Number(e);return isNaN(n)?`'${e.replace(/'/g,"''")}'`:String(n)}return`'${e.replace(/'/g,"''")}'`}function ES(){const{state:e}=ae();return{substituteVariables:C.useCallback(n=>{var R;const r=/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g,o=[...n.matchAll(r)];if(o.length===0)return{sql:n,substituted:[]};const s=[],i=[];let a=n;const T=new Map,l=new Map;for(const c of e.cells){const A=(R=c.name)==null?void 0:R.trim();A&&(c.type==="param"?T.set(A,c):c.status==="success"&&c.result&&l.set(A,c.result))}for(const c of o){const A=c[1];if(T.has(A)){const S=T.get(A),d=S.paramConfig,I=S.paramValue??(d==null?void 0:d.defaultValue)??"",O=(d==null?void 0:d.paramType)??"text",u=iS(I,O);a=a.replace(c[0],u),s.push(A)}else l.has(A)&&(i.push(sS(A,l.get(A))),a=a.replace(c[0],`"${A}"`),s.push(A))}if(i.length===0&&s.length===0)return{sql:n,substituted:[]};if(i.length>0){const c=a.trimStart();/^WITH\s+/i.test(c)?a=a.replace(/^(\s*WITH\s+)/i,`$1${i.join(`,
241
- `)},
242
- `):a=`WITH ${i.join(`,
243
- `)}
244
- ${a}`}return{sql:a,substituted:s}},[e.cells])}}function aS(e){const t=e.match(/visualization\s*\{([^}]+)\}/is);if(!t)return;const n=t[1],r=s=>{var i;return(i=n.match(new RegExp(`\\b${s}\\s*=\\s*["']?([\\w-]+)["']?`,"i")))==null?void 0:i[1]},o=r("chart");if(o)return{chart:o,x:r("x"),y:r("y"),color:r("color"),title:r("title")}}function lS(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?TS(t):null}function TS(e){const t=e.match(/query\s*=\s*"""([\s\S]*?)"""/i);if(t)return t[1].trim()||null;const n=e.match(/"""([\s\S]*?)"""/);if(n)return n[1].trim()||null;if(/^\s*(dashboard|workbook)\s+"/i.test(e))return null;const r=e.match(/\b(SELECT|WITH|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|SHOW|DESCRIBE|EXPLAIN)\b([\s\S]*)/i);if(r){let o=r[0];const s=o.search(/\b(visualization|tests|block)\s*\{/i);return s>0&&(o=o.slice(0,s)),o=cS(o),o.trim()||null}return null}function cS(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 as(){const{state:e,dispatch:t}=ae(),{substituteVariables:n}=ES(),r=C.useCallback(async i=>{const a=e.cells.find(c=>c.id===i);if(!a)return;const T=lS(a);if(!T)return;if(a.type==="dql"){const c=aS(a.content);c&&JSON.stringify(c)!==JSON.stringify(a.chartConfig)&&t({type:"UPDATE_CELL",id:i,updates:{chartConfig:c}})}const{sql:l}=n(T),R=Date.now();t({type:"UPDATE_CELL",id:i,updates:{status:"running",error:void 0,result:void 0}});try{const c=await Re.executeQuery(l),A=Date.now()-R,S=(a.executionCount??0)+1;t({type:"UPDATE_CELL",id:i,updates:{status:"success",result:{...c,executionTime:c.executionTime??A,rowCount:c.rowCount??c.rows.length},executionCount:S}}),t({type:"APPEND_QUERY_LOG",entry:{id:$e(),cellName:a.name??a.id,rows:c.rowCount??c.rows.length,time:c.executionTime??A,ts:new Date}}),setTimeout(()=>{t({type:"UPDATE_CELL",id:i,updates:{status:"idle"}})},2e3)}catch(c){const A=Date.now()-R,S=c instanceof Error?c.message:String(c);t({type:"UPDATE_CELL",id:i,updates:{status:"error",error:S,executionCount:(a.executionCount??0)+1}}),t({type:"APPEND_QUERY_LOG",entry:{id:$e(),cellName:a.name??a.id,rows:0,time:A,ts:new Date,error:S}})}},[e.cells,t]),o=C.useCallback(async()=>{for(const i of e.cells)i.type!=="markdown"&&await r(i.id)},[e.cells,r]),s=C.useCallback(async i=>{if(!i)return;const a=`{{${i}}}`;for(const T of e.cells)T.type==="markdown"||T.type==="param"||T.content.includes(a)&&await r(T.id)},[e.cells,r]);return{executeCell:r,executeAll:o,executeDependents:s}}function Ce(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function RS(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 AS(e){const t=e.split(`
245
- `),n=[];let r=!1,o=!1;for(const s of t){const i=s;if(i.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(Ce(i));continue}if(i.startsWith("### ")){o&&(n.push("</ul>"),o=!1),n.push(`<h3>${Ce(i.slice(4))}</h3>`);continue}if(i.startsWith("## ")){o&&(n.push("</ul>"),o=!1),n.push(`<h2>${Ce(i.slice(3))}</h2>`);continue}if(i.startsWith("# ")){o&&(n.push("</ul>"),o=!1),n.push(`<h1>${Ce(i.slice(2))}</h1>`);continue}if(i.startsWith("> ")){o&&(n.push("</ul>"),o=!1),n.push(`<blockquote><p>${Ce(i.slice(2))}</p></blockquote>`);continue}if(i.startsWith("- ")||i.startsWith("* ")){o||(n.push("<ul>"),o=!0),n.push(`<li>${Zs(i.slice(2))}</li>`);continue}if(o&&(n.push("</ul>"),o=!1),i.trim()===""){n.push("<br>");continue}n.push(`<p>${Zs(i)}</p>`)}return o&&n.push("</ul>"),r&&n.push("</code></pre>"),n.join(`
246
- `)}function Zs(e){return Ce(e).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/`(.+?)`/g,"<code>$1</code>")}function SS(e){const{columns:t,rows:n}=e,r=n.slice(0,200),o=n.length>200,s=t.map(a=>`<th>${Ce(a)}</th>`).join(""),i=r.map(a=>`<tr>${t.map(l=>{const R=a[l],c=typeof R=="number",A=R==null?"—":String(R);return`<td${c?' class="num"':""}>${Ce(A)}</td>`}).join("")}</tr>`).join("");return`
247
- <div class="table-wrap">
248
- <table>
249
- <thead><tr>${s}</tr></thead>
250
- <tbody>${i}</tbody>
251
- </table>
252
- ${o?`<p class="truncated">Showing first 200 of ${n.length.toLocaleString()} rows</p>`:""}
253
- </div>`}function dS(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 IS(e){const t=dS(e);if(!t)return null;const n=e.rows.slice(0,20).map(R=>({label:String(R[t.labelCol]??""),value:Number(R[t.valueCol]??0)})),r=Math.max(...n.map(R=>R.value),1),o=28,s=6,i=140,a=440,T=n.length*(o+s)+40,l=n.map((R,c)=>{const A=c*(o+s)+20,S=Math.max(R.value/r*a,2);return`
254
- <text x="${i-6}" y="${A+o/2+4}" text-anchor="end" font-size="11" fill="#8b949e">${Ce(R.label.slice(0,20))}</text>
255
- <rect x="${i}" y="${A}" width="${S}" height="${o}" rx="3" fill="#388bfd" />
256
- <text x="${i+S+5}" y="${A+o/2+4}" font-size="11" fill="#e6edf3">${RS(R.value)}</text>`}).join("");return`<svg xmlns="http://www.w3.org/2000/svg" width="${i+a+80}" height="${T}" style="max-width:100%">${l}</svg>`}function uS(e,t){const n=t.map(r=>{if(r.type==="markdown")return`<section class="cell md-cell">${AS(r.content)}</section>`;const o=r.name?`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span><span class="cell-name">${Ce(r.name)}</span></div>`:`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span></div>`,s=`<pre class="cell-code"><code>${Ce(r.content)}</code></pre>`;let i="";if(r.result&&r.result.rows.length>0){const a=IS(r.result),T=SS(r.result);i=`<div class="cell-output">${`<div class="output-meta">${r.result.rows.length.toLocaleString()} rows${r.result.executionTime?` · ${r.result.executionTime}ms`:""}</div>`}${a??""}${a?"":T}</div>`}else r.error&&(i=`<div class="cell-error">⚠ ${Ce(r.error)}</div>`);return`<section class="cell sql-cell">${o}${s}${i}</section>`}).join(`
257
- `);return`<!DOCTYPE html>
258
- <html lang="en">
259
- <head>
260
- <meta charset="UTF-8">
261
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
262
- <title>${Ce(e)}</title>
263
- <style>
264
- *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
265
- body {
266
- font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
267
- background: #0d1117; color: #e6edf3;
268
- line-height: 1.6; padding: 0;
269
- }
270
- .page-header {
271
- background: #161b22; border-bottom: 1px solid #21262d;
272
- padding: 16px 32px; display: flex; align-items: center; gap: 12px;
273
- }
274
- .logo {
275
- width: 28px; height: 28px; border-radius: 6px;
276
- background: linear-gradient(135deg, #388bfd, #1f6feb);
277
- display: flex; align-items: center; justify-content: center;
278
- font-size: 10px; font-weight: 700; color: #fff;
279
- font-family: monospace; letter-spacing: -0.5px; flex-shrink: 0;
280
- }
281
- .page-title { font-size: 18px; font-weight: 600; color: #e6edf3; }
282
- .page-meta { font-size: 12px; color: #8b949e; margin-left: auto; }
283
- .content { max-width: 900px; margin: 0 auto; padding: 32px 24px; display: flex; flex-direction: column; gap: 24px; }
284
- .cell { border-radius: 8px; overflow: hidden; }
285
- .md-cell { padding: 4px 0; }
286
- .md-cell h1 { font-size: 26px; font-weight: 700; color: #e6edf3; margin: 0 0 12px; }
287
- .md-cell h2 { font-size: 20px; font-weight: 600; color: #e6edf3; margin: 20px 0 10px; }
288
- .md-cell h3 { font-size: 16px; font-weight: 600; color: #e6edf3; margin: 16px 0 8px; }
289
- .md-cell p { color: #c9d1d9; margin-bottom: 8px; }
290
- .md-cell ul { padding-left: 20px; color: #c9d1d9; margin-bottom: 8px; }
291
- .md-cell code { background: #21262d; padding: 2px 6px; border-radius: 4px; font-family: monospace; font-size: 13px; }
292
- .md-cell pre { background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 14px; overflow-x: auto; margin-bottom: 8px; }
293
- .md-cell pre code { background: none; padding: 0; }
294
- .md-cell blockquote { border-left: 3px solid #388bfd; padding-left: 14px; color: #8b949e; }
295
- .sql-cell { background: #161b22; border: 1px solid #30363d; }
296
- .cell-header { display: flex; align-items: center; gap: 8px; padding: 8px 14px; border-bottom: 1px solid #21262d; background: #1c2128; }
297
- .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; }
298
- .cell-name { font-size: 12px; color: #388bfd; font-family: monospace; }
299
- .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; }
300
- .cell-output { padding: 14px; }
301
- .output-meta { font-size: 11px; color: #8b949e; margin-bottom: 10px; }
302
- .table-wrap { overflow-x: auto; }
303
- table { width: 100%; border-collapse: collapse; font-size: 12px; }
304
- th { background: #1c2128; color: #8b949e; font-weight: 600; text-align: left; padding: 7px 12px; border-bottom: 1px solid #30363d; white-space: nowrap; }
305
- td { padding: 6px 12px; border-bottom: 1px solid #21262d; color: #e6edf3; }
306
- td.num { text-align: right; font-family: monospace; }
307
- tr:last-child td { border-bottom: none; }
308
- .truncated { font-size: 11px; color: #8b949e; margin-top: 8px; }
309
- .cell-error { padding: 12px 14px; background: #3d1a1a; border-top: 1px solid #f85149; color: #f85149; font-size: 13px; }
310
- .exported-by { text-align: center; color: #484f58; font-size: 11px; padding: 40px 0 24px; }
311
- </style>
312
- </head>
313
- <body>
314
- <div class="page-header">
315
- <div class="logo">DQL</div>
316
- <span class="page-title">${Ce(e)}</span>
317
- <span class="page-meta">Exported ${new Date().toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}</span>
318
- </div>
319
- <div class="content">
320
- ${n}
321
- </div>
322
- <p class="exported-by">Built with DQL Notebook</p>
323
- </body>
324
- </html>`}function NS(e,t){const n=uS(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 OS(e,t){var s,i;const n=[];n.push(`workbook "${e}" {`);let r=0,o=0;for(const a of t)if(a.type!=="param"){if(a.type==="markdown"){o++;const T=`Markdown ${o}`;n.push(""),n.push(` page "${T}" {`);const l=a.content.split(`
325
- `);for(const R of l)n.push(` // ${R}`);n.push(" }")}else if(a.type==="sql"){r++;const T=((s=a.name)==null?void 0:s.trim())||`Query ${r}`;n.push(""),n.push(` page "${T}" {`);const R=a.content.trim().split(`
326
- `).map(c=>` ${c}`).join(`
327
- `);n.push(" chart.table("),n.push(R+","),n.push(` title = "${T}"`),n.push(" )"),n.push(" }")}else if(a.type==="dql"){r++;const T=((i=a.name)==null?void 0:i.trim())||`Query ${r}`;n.push(""),n.push(` page "${T}" {`);const l=a.content.trim().split(`
328
- `);for(const R of l)n.push(` ${R}`);n.push(" }")}}return n.push("}"),n.join(`
329
- `)}function fS(e,t){const n=OS(e,t),r=new Blob([n],{type:"text/plain;charset=utf-8"}),o=URL.createObjectURL(r),s=document.createElement("a"),i=e.replace(/[^a-zA-Z0-9_-]/g,"_")+".dql";s.href=o,s.download=i,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(o)}function CS({t:e}){return E.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:E.jsx("span",{style:{color:"#ffffff",fontSize:10,fontWeight:700,fontFamily:e.fontMono,letterSpacing:"-0.5px"},children:"DQL"})})}function LS(){const{state:e,dispatch:t}=ae(),n=ie[e.themeMode],{executeAll:r}=as(),[o,s]=C.useState(!1),[i,a]=C.useState(""),[T,l]=C.useState(!1),[R,c]=C.useState(!1),[A,S]=C.useState(!1),[d,I]=C.useState(!1),[O,u]=C.useState(!1),[f,N]=C.useState(!1),L=C.useRef(null),m=C.useRef(null);C.useEffect(()=>{o&&m.current&&(m.current.focus(),m.current.select())},[o]),C.useEffect(()=>{if(!f)return;function g(_){L.current&&!L.current.contains(_.target)&&N(!1)}return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[f]);const p=()=>{a(e.notebookTitle),s(!0)},D=()=>{s(!1),i.trim()&&i!==e.notebookTitle&&t({type:"SET_NOTEBOOK_DIRTY",dirty:!0})},M=C.useCallback(async()=>{var g;if(e.activeFile){t({type:"SET_SAVING",saving:!0});try{const _=e.activeFile.type==="block"?((g=e.cells[0])==null?void 0:g.content)??"":rS(e.notebookTitle,e.cells);await Re.saveNotebook(e.activeFile.path,_),t({type:"SET_NOTEBOOK_DIRTY",dirty:!1}),l(!0),setTimeout(()=>l(!1),2e3)}catch(_){console.error("Save failed:",_)}finally{t({type:"SET_SAVING",saving:!1})}}},[e.activeFile,e.notebookTitle,e.cells,t]);C.useEffect(()=>{const g=_=>{(_.metaKey||_.ctrlKey)&&_.key==="s"&&(_.preventDefault(),M())};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[M]),C.useEffect(()=>{if(!e.autoSave||!e.notebookDirty||!e.activeFile)return;const g=setTimeout(()=>{M()},2e3);return()=>clearTimeout(g)},[e.autoSave,e.notebookDirty,e.activeFile,e.cells,M]);const B=()=>{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 E.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:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[E.jsx(CS,{t:n}),E.jsx("div",{style:{width:1,height:20,background:n.headerBorder,flexShrink:0}}),e.activeFile&&E.jsx("span",{style:{fontSize:10,fontWeight:600,color:e.activeFile.type==="block"?"#e3b341":n.accent,background:`${e.activeFile.type==="block"?"#e3b341":n.accent}18`,borderRadius:4,padding:"2px 6px",fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.05em",flexShrink:0},children:e.activeFile.type}),e.activeFile?o?E.jsx("input",{ref:m,value:i,onChange:g=>a(g.target.value),onBlur:D,onKeyDown:g=>{g.key==="Enter"&&D(),g.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}}):E.jsxs("span",{onClick:p,title:"Click to rename",style:{color:n.textPrimary,fontSize:13,fontWeight:500,fontFamily:n.font,cursor:"text",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",padding:"2px 4px",borderRadius:4,border:"1px solid transparent"},children:[e.notebookTitle||"Untitled",e.notebookDirty&&E.jsx("span",{style:{color:n.textMuted,marginLeft:4},children:"●"})]}):E.jsx("span",{style:{color:n.textSecondary,fontSize:13,fontFamily:n.font,padding:"2px 4px"},children:"DQL Notebook"})]}),E.jsx("div",{style:{flex:1}}),E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[E.jsxs("button",{onClick:r,disabled:!e.activeFile,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{...F,background:(R&&e.activeFile,n.accent),color:"#ffffff",border:`1px solid ${n.accent}`,opacity:e.activeFile?R?.9:1:.4},children:[E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:E.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})}),"Run All"]}),E.jsx("div",{style:{width:1,height:20,background:n.headerBorder}}),E.jsx("button",{onClick:B,onMouseEnter:()=>I(!0),onMouseLeave:()=>I(!1),title:e.themeMode==="dark"?"Switch to light mode":"Switch to dark mode",style:{...F,background:d?n.btnHover:n.btnBg,color:n.textSecondary,padding:"0 8px",fontSize:14},children:e.themeMode==="dark"?"☀":"☾"}),E.jsx("button",{onClick:M,disabled:!e.activeFile||e.savingFile,onMouseEnter:()=>S(!0),onMouseLeave:()=>S(!1),title:"Save (Cmd+S)",style:{...F,background:A&&e.activeFile?n.btnHover:n.btnBg,color:T?n.success:n.textSecondary,opacity:e.activeFile?1:.4},children:e.savingFile?E.jsxs(E.Fragment,{children:[E.jsx(hS,{}),"Saving…"]}):T?E.jsx(E.Fragment,{children:"✓ Saved"}):E.jsx(E.Fragment,{children:"Save"})}),E.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"}),E.jsx("div",{style:{width:1,height:20,background:n.headerBorder}}),E.jsxs("div",{ref:L,style:{position:"relative"},children:[E.jsxs("button",{onClick:()=>{e.activeFile&&N(g=>!g)},disabled:!e.activeFile,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),title:"Export options",style:{...F,background:(O||f)&&e.activeFile?n.btnHover:n.btnBg,color:n.textSecondary,opacity:e.activeFile?1:.4},children:[E.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:[E.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"}),E.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",E.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"currentColor",style:{marginLeft:1},children:E.jsx("path",{d:"M1 2.5l3 3 3-3",stroke:"currentColor",fill:"none",strokeWidth:"1.2",strokeLinecap:"round"})})]}),f&&E.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:[E.jsx(Qs,{label:"Export HTML",description:"Standalone dashboard",t:n,onClick:()=>{NS(e.notebookTitle||"dashboard",e.cells),N(!1)}}),E.jsx(Qs,{label:"Export .dql",description:"DQL workbook file",t:n,onClick:()=>{fS(e.notebookTitle||"notebook",e.cells),N(!1)}})]})]})]})]})}function Qs({label:e,description:t,t:n,onClick:r}){const[o,s]=C.useState(!1);return E.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:[E.jsx("span",{style:{fontSize:12,fontWeight:500,color:n.textPrimary,fontFamily:n.font},children:e}),E.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font},children:t})]})}function hS(){return E.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",style:{animation:"spin 0.8s linear infinite"},children:[E.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"}),E.jsx("circle",{cx:"6",cy:"6",r:"4.5",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"14 7"})]})}function _S(e){return e.toTimeString().slice(0,8)}function pS(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}function mS(){const{state:e,dispatch:t}=ae(),n=ie[e.themeMode],[r,o]=C.useState(!1),s=e.queryLog.filter(a=>a.error),i=a=>t({type:"SET_DEV_PANEL_TAB",tab:a});return E.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&&E.jsxs(E.Fragment,{children:[E.jsxs("div",{style:{height:32,flexShrink:0,display:"flex",alignItems:"center",borderBottom:`1px solid ${n.headerBorder}`,padding:"0 8px",gap:2},children:[["logs","errors"].map(a=>E.jsx(DS,{label:a==="errors"?`Errors${s.length>0?` (${s.length})`:""}`:`Logs (${e.queryLog.length})`,active:e.devPanelTab===a,onClick:()=>i(a),t:n},a)),E.jsx("div",{style:{flex:1}}),E.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"})]}),E.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[e.devPanelTab==="logs"&&(e.queryLog.length===0?E.jsx(ei,{t:n,message:"No queries executed yet."}):[...e.queryLog].reverse().map(a=>E.jsx(ti,{entry:a,t:n},a.id))),e.devPanelTab==="errors"&&(s.length===0?E.jsx(ei,{t:n,message:"No errors."}):[...s].reverse().map(a=>E.jsx(ti,{entry:a,t:n},a.id)))]})]}),E.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:[E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:E.jsx("path",{d:e.devPanelOpen?"M1 7l4-4 4 4":"M1 3l4 4 4-4",strokeWidth:"1.5",stroke:"currentColor",fill:"none"})}),"Dev"]})]})}function DS({label:e,active:t,onClick:n,t:r}){const[o,s]=C.useState(!1);return E.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 ei({t:e,message:t}){return E.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:e.textMuted,fontSize:12,fontFamily:e.font,fontStyle:"italic"},children:t})}function ti({entry:e,t}){return E.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:[E.jsx("span",{style:{color:t.textMuted,flexShrink:0},children:_S(e.ts)}),E.jsx("span",{style:{flexShrink:0,color:t.textPrimary,maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.cellName}),e.error?E.jsx("span",{style:{color:t.error,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.error}):E.jsxs(E.Fragment,{children:[E.jsxs("span",{style:{color:t.textMuted},children:[e.rows.toLocaleString()," rows"]}),E.jsx("span",{style:{color:t.textMuted},children:pS(e.time)})]})]})}function gS({onOpenFile:e}){const{state:t,dispatch:n}=ae(),r=ie[t.themeMode],o=t.files.slice(0,3);return E.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",background:r.appBg,padding:40,overflow:"auto"},children:E.jsxs("div",{style:{maxWidth:720,width:"100%",display:"flex",flexDirection:"column",alignItems:"center",gap:48},children:[E.jsxs("div",{style:{textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[E.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:E.jsx("span",{style:{color:"#fff",fontSize:26,fontWeight:800,fontFamily:r.fontMono,letterSpacing:"-1px"},children:"DQL"})}),E.jsxs("div",{children:[E.jsx("h1",{style:{fontSize:32,fontWeight:700,color:r.textPrimary,fontFamily:r.font,marginBottom:8,letterSpacing:"-0.5px"},children:"DQL Notebook"}),E.jsx("p",{style:{fontSize:15,color:r.textSecondary,fontFamily:r.font,letterSpacing:"0.02em"},children:"Analytics as Code"})]})]}),E.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:16,width:"100%"},children:[E.jsx(ni,{title:"New Notebook",description:"Start a fresh analysis with an empty notebook.",icon:E.jsx(yS,{}),accent:r.accent,onClick:()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}),t:r}),E.jsx(PS,{recentFiles:o,onOpenFile:e,t:r}),E.jsx(ni,{title:"Browse Examples",description:"Explore sample notebooks and DQL workbooks.",icon:E.jsx(US,{}),accent:r.success,onClick:()=>{const s=t.files.find(i=>i.folder.toLowerCase()==="notebooks");s&&e(s)},t:r})]}),E.jsxs("div",{style:{width:"100%",borderRadius:10,border:`1px solid ${r.cellBorder}`,padding:"16px 20px",background:r.cellBg},children:[E.jsx("div",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.08em",textTransform:"uppercase",color:r.textMuted,fontFamily:r.font,marginBottom:12},children:"Quick Tips"}),E.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, 1fr)",gap:8},children:[["Shift + Enter","Run cell"],["Click +","Add a new cell"],["Double-click MD cell","Edit markdown"],["Header title","Click to rename notebook"]].map(([s,i])=>E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[E.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}),E.jsx("span",{style:{fontSize:12,color:r.textMuted,fontFamily:r.font},children:i})]},s))})]})]})})}function ni({title:e,description:t,icon:n,accent:r,onClick:o,t:s}){const[i,a]=C.useState(!1);return E.jsxs("button",{onClick:o,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{background:i?s.cellBg:"transparent",border:`1px solid ${i?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:i?`0 0 0 1px ${r}30, 0 4px 16px rgba(0,0,0,0.15)`:"none"},children:[E.jsx("div",{style:{width:36,height:36,borderRadius:8,background:`${r}18`,display:"flex",alignItems:"center",justifyContent:"center",color:r},children:n}),E.jsxs("div",{children:[E.jsx("div",{style:{fontSize:13,fontWeight:600,color:s.textPrimary,fontFamily:s.font,marginBottom:4},children:e}),E.jsx("div",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font,lineHeight:1.5},children:t})]})]})}function PS({recentFiles:e,onOpenFile:t,t:n}){const[r,o]=C.useState(!1);return E.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:[E.jsx("div",{style:{width:36,height:36,borderRadius:8,background:`${n.warning}18`,display:"flex",alignItems:"center",justifyContent:"center",color:n.warning},children:E.jsx(xS,{})}),E.jsxs("div",{children:[E.jsx("div",{style:{fontSize:13,fontWeight:600,color:n.textPrimary,fontFamily:n.font,marginBottom:8},children:"Open Recent"}),e.length===0?E.jsx("div",{style:{fontSize:12,color:n.textMuted,fontFamily:n.font,fontStyle:"italic"},children:"No recent files."}):E.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:e.map(s=>E.jsx(MS,{file:s,onClick:()=>t(s),t:n},s.path))})]})]})}function MS({file:e,onClick:t,t:n}){const[r,o]=C.useState(!1);return E.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 yS(){return E.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 xS(){return E.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 US(){return E.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:E.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.41 1.376a.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"})})}const ri=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class sn{constructor(t,n,r=0,o=t.length,s,i){this.test=i,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?a=>s(ri(a)):ri,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 TR(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=IR(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=cR(t);let o=this.normalize(n);if(o.length)for(let s=0,i=r;;s++){let a=o.charCodeAt(s),T=this.match(a,i,this.bufferPos+this.bufferStart);if(s==o.length-1){if(T)return this.value=T,this;break}i==r&&s<n.length&&n.charCodeAt(s)==a&&i++}}}match(t,n,r){let o=null;for(let s=0;s<this.matches.length;s+=2){let i=this.matches[s],a=!1;this.query.charCodeAt(i)==t&&(i==this.query.length-1?o={from:this.matches[s+1],to:r}:(this.matches[s]++,a=!0)),a||(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"&&(sn.prototype[Symbol.iterator]=function(){return this});const fa={from:-1,to:-1,match:/.*/.exec("")},ls="gm"+(/x/.unicode==null?"":"u");class Ca{constructor(t,n,r,o=0,s=t.length){if(this.text=t,this.to=s,this.curLine="",this.done=!1,this.value=fa,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new La(t,n,r,o,s);this.re=new RegExp(n,ls+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.iter=t.iter();let i=t.lineAt(o);this.curLineStart=i.from,this.matchPos=nr(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=nr(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 Vr=new WeakMap;class Dt{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let o=Vr.get(t);if(!o||o.from>=r||o.to<=n){let a=new Dt(n,t.sliceString(n,r));return Vr.set(t,a),a}if(o.from==n&&o.to==r)return o;let{text:s,from:i}=o;return i>n&&(s=t.sliceString(n,i)+s,i=n),o.to<r&&(s+=t.sliceString(o.to,r)),Vr.set(t,new Dt(i,s)),new Dt(n,s.slice(n-i,r-i))}}class La{constructor(t,n,r,o,s){this.text=t,this.to=s,this.done=!1,this.value=fa,this.matchPos=nr(t,o),this.re=new RegExp(n,ls+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.flat=Dt.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=nr(this.text,o+(r==o?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Dt.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(Ca.prototype[Symbol.iterator]=La.prototype[Symbol.iterator]=function(){return this});function bS(e){try{return new RegExp(e,ls),!0}catch{return!1}}function nr(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 GS=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:o}=iR(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 i=s&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(s.elements.line.value);if(!i){e.dispatch({effects:r});return}let a=t.doc.lineAt(t.selection.main.head),[,T,l,R,c]=i,A=R?+R.slice(1):0,S=l?+l:a.number;if(l&&c){let O=S/100;T&&(O=O*(T=="-"?-1:1)+a.number/t.doc.lines),S=Math.round(t.doc.lines*O)}else l&&T&&(S=S*(T=="-"?-1:1)+a.number);let d=t.doc.line(Math.max(1,Math.min(t.doc.lines,S))),I=be.cursor(d.from+Math.max(0,Math.min(A,d.length)));e.dispatch({effects:[r,pe.scrollIntoView(I.from,{y:"center"})],selection:I})}),!0},BS=({state:e,dispatch:t})=>{let{selection:n}=e,r=be.create(n.ranges.map(o=>e.wordAt(o.head)||be.cursor(o.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function vS(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 i=!1,a=new sn(e.doc,t,r[r.length-1].to);;)if(a.next(),a.done){if(i)return null;a=new sn(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),i=!0}else{if(i&&r.some(T=>T.from==a.value.from))continue;if(s){let T=e.wordAt(a.value.from);if(!T||T.from!=a.value.from||T.to!=a.value.to)continue}return a.value}}const HS=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(s=>s.from===s.to))return BS({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=vS(e,r);return o?(t(e.update({selection:e.selection.addRange(be.range(o.from,o.to),!1),effects:pe.scrollIntoView(o.to)})),!0):!1},It=RR.define({combine(e){return AR(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new QS(t),scrollToMatch:t=>pe.scrollIntoView(t)})}});function FS(e){return e?[It.of(e),wo]:wo}class ha{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||bS(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"?`
330
- `: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 XS(this):new VS(this)}getCursor(t,n=0,r){let o=t.doc?t:Aa.create({doc:t});return r==null&&(r=o.doc.length),this.regexp?_t(this,o,n,r):ht(this,o,n,r)}}class _a{constructor(t){this.spec=t}}function wS(e,t,n){return(r,o,s,i)=>{if(n&&!n(r,o,s,i))return!1;let a=r>=i&&o<=i+s.length?s.slice(r-i,o-i):t.doc.sliceString(r,o);return e(a,t,r,o)}}function ht(e,t,n,r){let o;return e.wholeWord&&(o=YS(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(o=wS(e.test,t,o)),new sn(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:s=>s.toLowerCase(),o)}function YS(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(rr(o,n-s))!=tt.Word||t(or(o,n-s))!=tt.Word)&&(t(or(o,r-s))!=tt.Word||t(rr(o,r-s))!=tt.Word))}class VS extends _a{constructor(t){super(t)}nextMatch(t,n,r){let o=ht(this.spec,t,r,t.doc.length).nextOverlapping();if(o.done){let s=Math.min(t.doc.length,n+this.spec.unquoted.length);o=ht(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),i=ht(this.spec,t,s,o),a=null;for(;!i.nextOverlapping().done;)a=i.value;if(a)return a;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=ht(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=ht(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 WS(e,t,n){return(r,o,s)=>(!n||n(r,o,s))&&e(s[0],t,r,o)}function _t(e,t,n,r){let o;return e.wholeWord&&(o=kS(t.charCategorizer(t.selection.main.head))),e.test&&(o=WS(e.test,t,o)),new Ca(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:o},n,r)}function rr(e,t){return e.slice(Sa(e,t,!1),t)}function or(e,t){return e.slice(t,Sa(e,t))}function kS(e){return(t,n,r)=>!r[0].length||(e(rr(r.input,r.index))!=tt.Word||e(or(r.input,r.index))!=tt.Word)&&(e(or(r.input,r.index+r[0].length))!=tt.Word||e(rr(r.input,r.index+r[0].length))!=tt.Word)}class XS extends _a{nextMatch(t,n,r){let o=_t(this.spec,t,r,t.doc.length).next();return o.done&&(o=_t(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),i=_t(this.spec,t,s,r),a=null;for(;!i.next().done;)a=i.value;if(a&&(s==n||a.from>s+10))return a;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=_t(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=_t(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 En=is.define(),Ts=is.define(),nt=ER.define({create(e){return new Wr(Fo(e).create(),null)},update(e,t){for(let n of t.effects)n.is(En)?e=new Wr(n.value.create(),e.panel):n.is(Ts)&&(e=new Wr(e.query,n.value?cs:null));return e},provide:e=>aR.from(e,t=>t.panel)});class Wr{constructor(t,n){this.query=t,this.panel=n}}const jS=Es.mark({class:"cm-searchMatch"}),$S=Es.mark({class:"cm-searchMatch cm-searchMatch-selected"}),KS=SR.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(nt))}update(e){let t=e.state.field(nt);(t!=e.startState.field(nt)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Es.none;let{view:n}=this,r=new dR;for(let o=0,s=n.visibleRanges,i=s.length;o<i;o++){let{from:a,to:T}=s[o];for(;o<i-1&&T>s[o+1].from-500;)T=s[++o].to;e.highlight(n.state,a,T,(l,R)=>{let c=n.state.selection.ranges.some(A=>A.from==l&&A.to==R);r.add(l,R,c?$S:jS)})}return r.finish()}},{decorations:e=>e.decorations});function fn(e){return t=>{let n=t.state.field(nt,!1);return n&&n.query.spec.valid?e(t,n):Da(t)}}const sr=fn((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let o=be.single(r.from,r.to),s=e.state.facet(It);return e.dispatch({selection:o,effects:[Rs(e,r),s.scrollToMatch(o.main,e)],userEvent:"select.search"}),ma(e),!0}),ir=fn((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,o=t.prevMatch(n,r,r);if(!o)return!1;let s=be.single(o.from,o.to),i=e.state.facet(It);return e.dispatch({selection:s,effects:[Rs(e,o),i.scrollToMatch(s.main,e)],userEvent:"select.search"}),ma(e),!0}),JS=fn((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:be.create(n.map(r=>be.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),zS=({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=[],i=0;for(let a=new sn(e.doc,e.sliceDoc(r,o));!a.next().done;){if(s.length>1e3)return!1;a.value.from==r&&(i=s.length),s.push(be.range(a.value.from,a.value.to))}return t(e.update({selection:be.create(s,i),userEvent:"select.search.matches"})),!0},oi=fn((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 i=s,a=[],T,l,R=[];i.from==r&&i.to==o&&(l=n.toText(t.getReplacement(i)),a.push({from:i.from,to:i.to,insert:l}),i=t.nextMatch(n,i.from,i.to),R.push(pe.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+".")));let c=e.state.changes(a);return i&&(T=be.single(i.from,i.to).map(c),R.push(Rs(e,i)),R.push(n.facet(It).scrollToMatch(T.main,e))),e.dispatch({changes:c,selection:T,effects:R,userEvent:"input.replace"}),!0}),qS=fn((e,{query:t})=>{if(e.state.readOnly)return!1;let n=t.matchAll(e.state,1e9).map(o=>{let{from:s,to:i}=o;return{from:s,to:i,insert:t.getReplacement(o)}});if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:pe.announce.of(r),userEvent:"input.replace.all"}),!0});function cs(e){return e.state.facet(It).createPanel(e)}function Fo(e,t){var n,r,o,s,i;let a=e.selection.main,T=a.empty||a.to>a.from+100?"":e.sliceDoc(a.from,a.to);if(t&&!T)return t;let l=e.facet(It);return new ha({search:((n=t==null?void 0:t.literal)!==null&&n!==void 0?n:l.literal)?T:T.replace(/\n/g,"\\n"),caseSensitive:(r=t==null?void 0:t.caseSensitive)!==null&&r!==void 0?r:l.caseSensitive,literal:(o=t==null?void 0:t.literal)!==null&&o!==void 0?o:l.literal,regexp:(s=t==null?void 0:t.regexp)!==null&&s!==void 0?s:l.regexp,wholeWord:(i=t==null?void 0:t.wholeWord)!==null&&i!==void 0?i:l.wholeWord})}function pa(e){let t=Ra(e,cs);return t&&t.dom.querySelector("[main-field]")}function ma(e){let t=pa(e);t&&t==e.root.activeElement&&t.select()}const Da=e=>{let t=e.state.field(nt,!1);if(t&&t.panel){let n=pa(e);if(n&&n!=e.root.activeElement){let r=Fo(e.state,t.query.spec);r.valid&&e.dispatch({effects:En.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[Ts.of(!0),t?En.of(Fo(e.state,t.query.spec)):is.appendConfig.of(wo)]});return!0},ga=e=>{let t=e.state.field(nt,!1);if(!t||!t.panel)return!1;let n=Ra(e,cs);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:Ts.of(!1)}),!0},ZS=[{key:"Mod-f",run:Da,scope:"editor search-panel"},{key:"F3",run:sr,shift:ir,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:sr,shift:ir,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:ga,scope:"editor search-panel"},{key:"Mod-Shift-l",run:zS},{key:"Mod-Alt-g",run:GS},{key:"Mod-d",run:HS,preventDefault:!0}];class QS{constructor(t){this.view=t;let n=this.query=t.state.field(nt).query.spec;this.commit=this.commit.bind(this),this.searchField=De("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=De("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=De("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=De("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=De("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(o,s,i){return De("button",{class:"cm-button",name:o,onclick:s,type:"button"},i)}this.dom=De("div",{onkeydown:o=>this.keydown(o),class:"cm-search"},[this.searchField,r("next",()=>sr(t),[he(t,"next")]),r("prev",()=>ir(t),[he(t,"previous")]),r("select",()=>JS(t),[he(t,"all")]),De("label",null,[this.caseField,he(t,"match case")]),De("label",null,[this.reField,he(t,"regexp")]),De("label",null,[this.wordField,he(t,"by word")]),...t.state.readOnly?[]:[De("br"),this.replaceField,r("replace",()=>oi(t),[he(t,"replace")]),r("replaceAll",()=>qS(t),[he(t,"replace all")])],De("button",{name:"close",onclick:()=>ga(t),"aria-label":he(t,"close"),type:"button"},["×"])])}commit(){let t=new ha({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:En.of(t)}))}keydown(t){uR(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?ir:sr)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),oi(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(En)&&!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(It).top}}function he(e,t){return e.state.phrase(t)}const bn=30,Gn=/[\s\.,:;?!]/;function Rs(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-bn),i=Math.min(o,n+bn),a=e.state.sliceDoc(s,i);if(s!=r.from){for(let T=0;T<bn;T++)if(!Gn.test(a[T+1])&&Gn.test(a[T])){a=a.slice(T);break}}if(i!=o){for(let T=a.length-1;T>a.length-bn;T--)if(!Gn.test(a[T-1])&&Gn.test(a[T])){a=a.slice(0,T);break}}return pe.announce.of(`${e.state.phrase("current match")}. ${a} ${e.state.phrase("on line")} ${r.number}.`)}const ed=pe.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"}}),wo=[nt,lR.low(KS),ed],td=pe.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}),nd=pe.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 Pa({value:e,onChange:t,onRun:n,themeMode:r,autoFocus:o,schema:s}){const i=ie[r],a=C.useRef(null),T=C.useRef(null),l=C.useRef(n),R=C.useRef(t),c=C.useRef(new NR);return l.current=n,R.current=t,C.useEffect(()=>{if(!a.current)return;const A=fR.of([{key:"Shift-Enter",run:()=>(l.current(),!0)},{key:"Ctrl-Enter",mac:"Cmd-Enter",run:()=>(l.current(),!0)},{key:"Ctrl-/",mac:"Cmd-/",run:CR},LR,...hR,..._R,...pR,...ZS,...mR,...DR]),S=pe.updateListener.of(N=>{N.docChanged&&R.current(N.state.doc.toString())}),d=pe.theme({"&":{background:i.editorBg,fontFamily:i.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"}}),I=s?yn({schema:s,upperCaseKeywords:!1}):yn({upperCaseKeywords:!1}),O=[A,S,d,c.current.of(I),PR({closeOnBlur:!1}),MR(),yR(),xR(),UR(),bR(),GR(),BR(),pe.lineWrapping,FS({top:!0}),...r==="dark"?[gR,nd]:[td,vR(HR)]],u=Aa.create({doc:e,extensions:O}),f=new pe({state:u,parent:a.current});return T.current=f,o&&f.focus(),()=>{f.destroy(),T.current=null}},[r]),C.useEffect(()=>{const A=T.current;if(!A)return;const S=s?yn({schema:s,upperCaseKeywords:!1}):yn({upperCaseKeywords:!1});A.dispatch({effects:c.current.reconfigure(S)})},[s]),C.useEffect(()=>{const A=T.current;if(!A)return;const S=A.state.doc.toString();S!==e&&A.dispatch({changes:{from:0,to:S.length,insert:e}})},[e]),E.jsx("div",{ref:a,style:{background:i.editorBg,minHeight:80}})}Pa.displayName="SQLCellEditor";function rd(e,t){const n=e.split(`
331
- `),r=[];let o=0;for(;o<n.length;){const s=n[o],i=s.match(/^(#{1,6})\s+(.+)$/);if(i){const a=i[1].length,T=i[2],R=[28,22,18,16,14,13][a-1];r.push(E.jsx("div",{style:{fontSize:R,fontWeight:a<=2?700:600,color:t.textPrimary,fontFamily:t.font,lineHeight:1.3,marginBottom:a===1?12:8,marginTop:o>0?a===1?16:10:0,borderBottom:a===1?`1px solid ${t.cellBorder}`:void 0,paddingBottom:a===1?8:void 0},children:$t(T,t)},o)),o++;continue}if(/^[-*_]{3,}$/.test(s.trim())){r.push(E.jsx("hr",{style:{border:"none",borderTop:`1px solid ${t.cellBorder}`,margin:"12px 0"}},o)),o++;continue}if(s.startsWith("> ")){r.push(E.jsx("div",{style:{borderLeft:`3px solid ${t.textMuted}`,paddingLeft:12,marginLeft:4,color:t.textSecondary,fontStyle:"italic",fontFamily:t.fontSerif,fontSize:14},children:$t(s.slice(2),t)},o)),o++;continue}if(s.startsWith("```")){const a=[];for(o++;o<n.length&&!n[o].startsWith("```");)a.push(n[o]),o++;r.push(E.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:a.join(`
332
- `)},o)),o++;continue}if(/^[-*+]\s/.test(s)){const a=[];for(;o<n.length&&/^[-*+]\s/.test(n[o]);)a.push(n[o].replace(/^[-*+]\s/,"")),o++;r.push(E.jsx("ul",{style:{paddingLeft:20,marginBottom:8,color:t.textSecondary},children:a.map((T,l)=>E.jsx("li",{style:{fontSize:14,fontFamily:t.font,lineHeight:1.6,marginBottom:2},children:$t(T,t)},l))},o));continue}if(/^\d+\.\s/.test(s)){const a=[];for(;o<n.length&&/^\d+\.\s/.test(n[o]);)a.push(n[o].replace(/^\d+\.\s/,"")),o++;r.push(E.jsx("ol",{style:{paddingLeft:20,marginBottom:8,color:t.textSecondary},children:a.map((T,l)=>E.jsx("li",{style:{fontSize:14,fontFamily:t.font,lineHeight:1.6,marginBottom:2},children:$t(T,t)},l))},o));continue}if(!s.trim()){r.push(E.jsx("div",{style:{height:8}},o)),o++;continue}r.push(E.jsx("p",{style:{fontSize:14,lineHeight:1.7,fontFamily:t.fontSerif,color:t.textSecondary,marginBottom:6},children:$t(s,t)},o)),o++}return r}function $t(e,t){const n=[];let r=e,o=0;for(;r.length>0;){const s=r.match(/\*{3}(.+?)\*{3}/),i=r.match(/\*{2}(.+?)\*{2}/),a=r.match(/\*(.+?)\*/),T=r.match(/`(.+?)`/),l=r.match(/\[(.+?)\]\((.+?)\)/),R=[s?{match:s,type:"boldItalic"}:null,i?{match:i,type:"bold"}:null,a?{match:a,type:"italic"}:null,T?{match:T,type:"code"}:null,l?{match:l,type:"link"}:null].filter(Boolean);if(R.length===0){n.push(E.jsx(on.Fragment,{children:r},o++));break}const c=R.reduce((S,d)=>(S.match.index??0)<(d.match.index??0)?S:d),A=c.match.index??0;switch(A>0&&n.push(E.jsx(on.Fragment,{children:r.slice(0,A)},o++)),c.type){case"boldItalic":n.push(E.jsx("strong",{style:{fontStyle:"italic"},children:c.match[1]},o++));break;case"bold":n.push(E.jsx("strong",{children:c.match[1]},o++));break;case"italic":n.push(E.jsx("em",{children:c.match[1]},o++));break;case"code":n.push(E.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:c.match[1]},o++));break;case"link":n.push(E.jsx("a",{href:c.match[2],target:"_blank",rel:"noopener noreferrer",style:{color:t.accent,textDecoration:"underline"},children:c.match[1]},o++));break}r=r.slice(A+c.match[0].length)}return E.jsx(E.Fragment,{children:n})}function od({value:e,onChange:t,onRun:n,themeMode:r}){const o=ie[r],[s,i]=C.useState(!1),a=C.useRef(null);C.useEffect(()=>{if(s&&a.current){a.current.focus();const c=a.current;c.style.height="auto",c.style.height=`${Math.max(c.scrollHeight,80)}px`}},[s]);const T=()=>{i(!1)},l=c=>{if(c.key==="Escape"&&i(!1),c.key==="Enter"&&c.shiftKey&&(c.preventDefault(),i(!1),n==null||n()),c.key==="Tab"){c.preventDefault();const A=c.currentTarget,S=A.selectionStart,d=A.selectionEnd,I=e.slice(0,S)+" "+e.slice(d);t(I),requestAnimationFrame(()=>{A.selectionStart=A.selectionEnd=S+2})}},R=c=>{t(c.target.value);const A=c.target;A.style.height="auto",A.style.height=`${Math.max(A.scrollHeight,80)}px`};return s?E.jsx("textarea",{ref:a,value:e,onChange:R,onBlur:T,onKeyDown:l,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()?E.jsx("div",{onDoubleClick:()=>i(!0),title:"Double-click to edit",style:{padding:"12px 16px",cursor:"text",minHeight:48},children:rd(e,o)}):E.jsx("div",{onDoubleClick:()=>i(!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 sd({cell:e,themeMode:t,onApplyParam:n}){const{dispatch:r}=ae(),o=ie[t],[s,i]=C.useState(!1),a=e.paramConfig??{paramType:"text",label:"Parameter",defaultValue:"",options:[]},T=e.paramValue??a.defaultValue,l=S=>{r({type:"UPDATE_CELL",id:e.id,updates:{paramConfig:{...a,...S}}})},R=S=>{r({type:"SET_PARAM_VALUE",id:e.id,value:S})},c=(a.options??[]).map(S=>S.trim()).filter(Boolean),A=e.name?`{{${e.name}}}`:null;return E.jsxs("div",{style:{background:o.cellBg,border:`1px solid ${o.cellBorder}`,borderLeft:"3px solid #e3b341",borderRadius:8,overflow:"hidden"},children:[s&&E.jsxs("div",{style:{background:o.tableHeaderBg,borderBottom:`1px solid ${o.cellBorder}`,padding:"12px 14px",display:"flex",flexDirection:"column",gap:10},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:2},children:[E.jsx("span",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.06em",color:"#e3b341",fontFamily:o.fontMono,textTransform:"uppercase"},children:"Configure Parameter"}),E.jsx("button",{onClick:()=>i(!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"})]}),E.jsxs("div",{style:{display:"flex",gap:10,flexWrap:"wrap"},children:[E.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[E.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Variable name"}),E.jsx("input",{value:e.name??"",onChange:S=>r({type:"UPDATE_CELL",id:e.id,updates:{name:S.target.value||void 0}}),placeholder:"e.g. start_date",style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:4,color:o.textPrimary,fontSize:12,fontFamily:o.fontMono,padding:"4px 7px",outline:"none"}})]}),E.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[E.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Display label"}),E.jsx("input",{value:a.label,onChange:S=>l({label:S.target.value}),placeholder:"e.g. Start Date",style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:4,color:o.textPrimary,fontSize:12,fontFamily:o.font,padding:"4px 7px",outline:"none"}})]}),E.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 100px"},children:[E.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Type"}),E.jsxs("select",{value:a.paramType,onChange:S=>l({paramType:S.target.value}),style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:4,color:o.textPrimary,fontSize:12,fontFamily:o.font,padding:"4px 7px",outline:"none"},children:[E.jsx("option",{value:"text",children:"Text"}),E.jsx("option",{value:"number",children:"Number"}),E.jsx("option",{value:"date",children:"Date"}),E.jsx("option",{value:"select",children:"Select"})]})]}),E.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[E.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Default value"}),E.jsx("input",{type:a.paramType==="number"?"number":a.paramType==="date"?"date":"text",value:a.defaultValue,onChange:S=>l({defaultValue:S.target.value}),style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:4,color:o.textPrimary,fontSize:12,fontFamily:o.font,padding:"4px 7px",outline:"none"}})]})]}),a.paramType==="select"&&E.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3},children:[E.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Options (one per line)"}),E.jsx("textarea",{value:(a.options??[]).join(`
333
- `),onChange:S=>l({options:S.target.value.split(`
334
- `)}),rows:4,placeholder:`Option A
335
- Option B
336
- 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"}})]})]}),E.jsxs("div",{style:{padding:"12px 14px",display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[E.jsx("button",{onClick:()=>i(S=>!S),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?E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.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"})}):E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.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"})})}),E.jsx("span",{style:{fontSize:13,fontWeight:500,fontFamily:o.font,color:o.textSecondary,flexShrink:0},children:a.label}),E.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[a.paramType==="select"?E.jsx("select",{value:T,onChange:S=>R(S.target.value),style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:5,color:o.textPrimary,fontSize:13,fontFamily:o.font,padding:"5px 10px",outline:"none",minWidth:160},children:c.length===0?E.jsx("option",{value:"",children:"— no options configured —"}):c.map(S=>E.jsx("option",{value:S,children:S},S))}):E.jsx("input",{type:a.paramType,value:T,onChange:S=>R(S.target.value),style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:5,color:o.textPrimary,fontSize:13,fontFamily:a.paramType==="number"?o.fontMono:o.font,padding:"5px 10px",outline:"none",minWidth:160}}),A&&E.jsx("span",{style:{fontSize:10,fontFamily:o.fontMono,color:"#e3b341",opacity:.8},children:A})]}),T&&E.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:T}),e.name&&n&&E.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 id=[{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
337
- category,
338
- COUNT(*) AS count,
339
- SUM(amount) AS total
340
- FROM read_csv_auto('data/filename.csv')
341
- GROUP BY category
342
- ORDER BY total DESC`},{id:"filter-date",label:"Filter by date range",description:"Filter rows between two dates",category:"SQL",code:`SELECT *
343
- FROM read_csv_auto('data/filename.csv')
344
- WHERE date_column >= '2024-01-01'
345
- 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
346
- *,
347
- ROW_NUMBER() OVER (PARTITION BY category ORDER BY amount DESC) AS rank
348
- 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 (
349
- SELECT *
350
- FROM read_csv_auto('data/filename.csv')
351
- WHERE amount > 0
352
- )
353
- SELECT
354
- category,
355
- SUM(amount) AS total
356
- FROM base
357
- 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
358
- FROM read_csv_auto('data/table_a.csv') AS a
359
- JOIN read_csv_auto('data/table_b.csv') AS b
360
- ON a.id = b.id`},{id:"pivot",label:"Pivot / unpivot",description:"Pivot a column into multiple columns",category:"SQL",code:`SELECT *
361
- FROM (
362
- SELECT category, quarter, amount
363
- FROM read_csv_auto('data/filename.csv')
364
- ) 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" {
365
- domain = "analytics"
366
- type = "custom"
367
- description = "Describe what this block does"
368
- owner = "data-team"
369
- tags = ["analytics"]
370
-
371
- query = """
372
- SELECT *
373
- FROM read_csv_auto('data/filename.csv')
374
- LIMIT 100
375
- """
376
-
377
- visualization {
378
- chart = "table"
379
- }
380
- }`},{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" {
381
- domain = "revenue"
382
- type = "custom"
383
- description = "Revenue grouped by segment"
384
- owner = "data-team"
385
- tags = ["revenue"]
386
-
387
- params {
388
- period = "current_quarter"
389
- }
390
-
391
- query = """
392
- SELECT
393
- segment_tier AS segment,
394
- SUM(amount) AS revenue
395
- FROM read_csv_auto('data/revenue.csv')
396
- WHERE fiscal_period = \${period}
397
- GROUP BY segment_tier
398
- ORDER BY revenue DESC
399
- """
400
-
401
- visualization {
402
- chart = "bar"
403
- x = segment
404
- y = revenue
405
- }
406
-
407
- tests {
408
- assert row_count > 0
409
- }
410
- }`},{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)
411
- FROM fct_revenue
412
- GROUP BY @dim(segment)
413
- 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" {
414
- domain = "revenue"
415
- type = "semantic"
416
- owner = "data-team"
417
- description = "Annual Recurring Revenue by subscription plan tier"
418
- tags = ["arr", "revenue", "saas"]
419
-
420
- metric = "arr"
421
- dimensions = ["plan_tier"]
422
-
423
- visualization {
424
- chart = "bar"
425
- x = plan_tier
426
- y = arr
427
- }
428
-
429
- tests {
430
- assert row_count > 0
431
- }
432
- }`},{id:"revenue-by-segment",label:"Revenue by segment",description:"Aggregate revenue totals, deal count, and average deal size per segment",category:"Analysis",code:`SELECT
433
- segment_tier,
434
- SUM(amount) AS total_revenue,
435
- COUNT(*) AS deals,
436
- ROUND(AVG(amount), 0) AS avg_deal
437
- FROM read_csv_auto('data/revenue.csv')
438
- GROUP BY segment_tier
439
- ORDER BY total_revenue DESC`},{id:"quarterly-trend",label:"Quarterly trend",description:"Revenue totals grouped by fiscal year and quarter",category:"Analysis",code:`SELECT
440
- fiscal_year || ' ' || fiscal_quarter AS period,
441
- SUM(amount) AS revenue
442
- FROM read_csv_auto('data/revenue.csv')
443
- GROUP BY fiscal_year, fiscal_quarter
444
- ORDER BY fiscal_year, fiscal_quarter`}];function Ed({onInsert:e,themeMode:t,cellType:n}){const r=ie[t],[o,s]=C.useState(!1),[i,a]=C.useState(null),T=C.useRef(null),l=id.filter(A=>n==="dql"?A.category==="DQL":A.category==="SQL"||A.category==="Analysis"),R=Array.from(new Set(l.map(A=>A.category)));C.useEffect(()=>{if(!o)return;function A(S){T.current&&!T.current.contains(S.target)&&s(!1)}return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[o]);function c(A){e(A),s(!1)}return E.jsxs("div",{ref:T,style:{position:"relative",display:"inline-block"},children:[E.jsxs("button",{title:"Insert template snippet",onClick:()=>s(A=>!A),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:[E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:E.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&&E.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:R.map(A=>E.jsxs("div",{children:[E.jsx("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:700,fontFamily:r.font,letterSpacing:"0.08em",textTransform:"uppercase",color:r.textMuted},children:A}),l.filter(S=>S.category===A).map(S=>E.jsxs("button",{onMouseEnter:()=>a(S.id),onMouseLeave:()=>a(null),onClick:()=>c(S.code),style:{width:"100%",padding:"7px 12px",textAlign:"left",background:i===S.id?r.sidebarItemHover:"transparent",border:"none",cursor:"pointer",display:"flex",flexDirection:"column",gap:2,transition:"background 0.1s"},children:[E.jsx("span",{style:{fontSize:12,fontWeight:600,fontFamily:r.font,color:r.textPrimary,lineHeight:1.4},children:S.label}),E.jsx("span",{style:{fontSize:11,fontFamily:r.font,color:r.textMuted,lineHeight:1.4},children:S.description})]},S.id))]},A))})]})}const kr=500;function ad(e){return typeof e=="number"?!0:typeof e=="string"?!isNaN(Number(e))&&e.trim()!=="":!1}function ld(e){return e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}function Ma({result:e,themeMode:t}){const n=ie[t],[r,o]=C.useState(null),s=e.rows.slice(0,kr),i=e.rows.length>kr;return e.columns.length===0?E.jsx("div",{style:{padding:"12px 16px",color:n.textMuted,fontSize:12,fontFamily:n.font,fontStyle:"italic"},children:"Query executed successfully. No columns to display."}):E.jsxs("div",{style:{maxHeight:400,overflow:"auto",position:"relative"},children:[E.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",tableLayout:"auto",fontSize:12,fontFamily:n.fontMono},children:[E.jsx("thead",{children:E.jsx("tr",{children:e.columns.map(a=>E.jsx("th",{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"},children:a},a))})}),E.jsx("tbody",{children:s.map((a,T)=>E.jsx("tr",{onMouseEnter:()=>o(T),onMouseLeave:()=>o(null),style:{background:r===T?n.tableRowHover:"transparent",transition:"background 0.1s"},children:e.columns.map(l=>{const R=a[l],c=R==null,A=ad(R);return E.jsx("td",{style:{padding:"5px 12px",borderBottom:`1px solid ${n.tableBorder}`,borderRight:`1px solid ${n.tableBorder}`,color:c?n.textMuted:n.textPrimary,fontStyle:c?"italic":"normal",textAlign:A?"right":"left",whiteSpace:"nowrap",maxWidth:300,overflow:"hidden",textOverflow:"ellipsis"},children:c?"—":ld(R)},l)})},T))})]}),i&&E.jsxs("div",{style:{padding:"8px 12px",color:n.textMuted,fontSize:11,fontFamily:n.font,borderTop:`1px solid ${n.tableBorder}`,background:n.tableHeaderBg,fontStyle:"italic"},children:["Showing ",kr.toLocaleString()," of ",e.rows.length.toLocaleString()," rows"]})]})}const Td=/date|time|at|day|month|year/i,As=/^(label|name|category)$/i,Ss=/^(value|count|total|revenue|amount)$/i;function Yo(e){return typeof e=="number"?!0:typeof e=="string"?e.trim()!==""&&!isNaN(Number(e)):!1}function cd(e){return typeof e=="string"||typeof e=="number"}function Vo(e,t){if(t!=null&&t.chart){const n=t.chart.toLowerCase();if(n==="bar"||n==="line"||n==="pie"||n==="kpi")return n;if(n==="table")return"table"}return Rd(e)}function Rd(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),i=s.every(R=>Yo(R[o])),a=s.every(R=>cd(R[r]));if(Td.test(r)&&i&&a)return"line";const T=t.find(R=>As.test(R)),l=t.find(R=>Ss.test(R));return T&&l&&s.every(c=>Yo(c[l]))||t.length===2&&a&&i?"bar":"table"}function an(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})}const Xr=20;function Ad({result:e,themeMode:t}){const n=ie[t],[r,o]=C.useState(null),s=e.columns.find(O=>As.test(O))??e.columns[0],i=e.columns.find(O=>Ss.test(O))??e.columns[1],a=e.rows.slice(0,Xr).map(O=>({label:String(O[s]??""),value:Number(O[i]??0)})),T=e.rows.length>Xr,l=Math.max(...a.map(O=>O.value),1),R=28,c=120,A=60,S=6,d=12,I=a.length*(R+S)+d*2;return E.jsxs("div",{style:{padding:"8px 0"},children:[E.jsx("svg",{width:"100%",height:I,style:{display:"block",overflow:"visible"},viewBox:`0 0 600 ${I}`,preserveAspectRatio:"xMidYMid meet",children:a.map((O,u)=>{const f=d+u*(R+S),N=600-c-A-24,L=Math.max(O.value/l*N,2),m=r===u;return E.jsxs("g",{onMouseEnter:()=>o(u),onMouseLeave:()=>o(null),style:{cursor:"default"},children:[E.jsx("text",{x:c-8,y:f+R/2+4,textAnchor:"end",fontSize:11,fontFamily:n.font,fill:n.textSecondary,children:O.label.length>16?O.label.slice(0,15)+"…":O.label}),E.jsx("rect",{x:c,y:f,width:L,height:R,rx:3,fill:m?n.accentHover:n.accent,style:{transition:"fill 0.15s"}}),E.jsx("text",{x:c+L+6,y:f+R/2+4,textAnchor:"start",fontSize:11,fontFamily:n.fontMono,fill:n.textMuted,children:an(O.value)})]},u)})}),T&&E.jsxs("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font,fontStyle:"italic",padding:"4px 12px"},children:["Showing ",Xr," of ",e.rows.length," rows"]})]})}function Sd(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 dd({result:e,themeMode:t}){const n=ie[t],[r,o]=C.useState(null),s=e.columns[0],i=e.columns[1],a=e.rows.map(U=>({label:String(U[s]??""),value:Number(U[i]??0)}));if(a.length<2)return null;const T=560,l=200,R=52,c=16,A=16,S=36,d=T-R-c,I=l-A-S,O=Math.min(...a.map(U=>U.value)),f=Math.max(...a.map(U=>U.value))-O||1,N=d/(a.length-1),L=U=>R+U*N,m=U=>A+I-(U-O)/f*I,p=a.map((U,h)=>({x:L(h),y:m(U.value)})),D=p.reduce((U,h,x)=>{if(x===0)return`M ${h.x},${h.y}`;const P=p[x-1],v=P.x+(h.x-P.x)/2,b=P.y,y=P.x+(h.x-P.x)/2,Y=h.y;return`${U} C ${v},${b} ${y},${Y} ${h.x},${h.y}`},""),M=`${D} L ${p[p.length-1].x},${A+I} L ${R},${A+I} Z`,B=5,F=Array.from({length:B+1},(U,h)=>{const x=O+f*h/B,P=m(x);return{val:x,y:P}}),g=Math.ceil(a.length/8),_=a.filter((U,h)=>h%g===0||h===a.length-1);return E.jsx("div",{style:{position:"relative",padding:"8px 0"},children:E.jsxs("svg",{width:"100%",height:l,viewBox:`0 0 ${T} ${l}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},onMouseLeave:()=>o(null),children:[F.map((U,h)=>E.jsxs("g",{children:[E.jsx("line",{x1:R,y1:U.y,x2:R+d,y2:U.y,stroke:n.tableBorder,strokeWidth:.5}),E.jsx("text",{x:R-6,y:U.y+4,textAnchor:"end",fontSize:10,fontFamily:n.fontMono,fill:n.textMuted,children:an(U.val)})]},h)),E.jsx("path",{d:M,fill:n.accent,opacity:.15}),E.jsx("path",{d:D,fill:"none",stroke:n.accent,strokeWidth:2,strokeLinejoin:"round"}),p.map((U,h)=>E.jsx("circle",{cx:U.x,cy:U.y,r:3,fill:n.accent,style:{cursor:"crosshair"},onMouseEnter:()=>o({x:U.x,y:U.y,label:a[h].label,value:a[h].value})},h)),_.map((U,h)=>{const x=a.indexOf(U);return E.jsx("text",{x:L(x),y:A+I+16,textAnchor:"middle",fontSize:10,fontFamily:n.font,fill:n.textMuted,children:Sd(U.label)},h)}),E.jsx("line",{x1:R,y1:A,x2:R,y2:A+I,stroke:n.tableBorder,strokeWidth:1}),E.jsx("line",{x1:R,y1:A+I,x2:R+d,y2:A+I,stroke:n.tableBorder,strokeWidth:1}),r&&E.jsxs("g",{children:[E.jsx("rect",{x:r.x+8,y:r.y-20,width:90,height:32,rx:4,fill:n.cellBg,stroke:n.cellBorder,strokeWidth:1}),E.jsx("text",{x:r.x+13,y:r.y-8,fontSize:10,fontFamily:n.font,fill:n.textSecondary,children:r.label.length>10?r.label.slice(0,10)+"…":r.label}),E.jsx("text",{x:r.x+13,y:r.y+6,fontSize:11,fontFamily:n.fontMono,fill:n.textPrimary,fontWeight:600,children:an(r.value)})]})]})})}const Id=12,si=["#388bfd","#56d364","#e3b341","#f78166","#a371f7","#39c5cf","#ffa657","#ff7b72","#89d185","#d2a8ff","#58a6ff","#3fb950"];function ud({result:e,themeMode:t,chartConfig:n}){const r=ie[t],[o,s]=C.useState(null),i=(n!=null&&n.x?e.columns.find(u=>u===n.x):void 0)??e.columns.find(u=>As.test(u))??e.columns[0],a=(n!=null&&n.y?e.columns.find(u=>u===n.y):void 0)??e.columns.find(u=>Ss.test(u))??e.columns[1],T=e.rows.slice(0,Id).map(u=>({label:String(u[i]??""),value:Math.abs(Number(u[a]??0))})),l=T.reduce((u,f)=>u+f.value,0)||1,R=90,c=90,A=70,S=40,d=[];let I=-Math.PI/2;T.forEach((u,f)=>{const N=u.value/l*2*Math.PI,L=I,m=I+N,p=R+A*Math.cos(L),D=c+A*Math.sin(L),M=R+A*Math.cos(m),B=c+A*Math.sin(m),F=R+S*Math.cos(L),g=c+S*Math.sin(L),_=R+S*Math.cos(m),U=c+S*Math.sin(m),h=N>Math.PI?1:0,x=[`M ${p} ${D}`,`A ${A} ${A} 0 ${h} 1 ${M} ${B}`,`L ${_} ${U}`,`A ${S} ${S} 0 ${h} 0 ${F} ${g}`,"Z"].join(" ");d.push({path:x,color:si[f%si.length],label:u.label,value:u.value,pct:u.value/l*100}),I=m});const O=o!==null?d[o]:null;return E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:16,padding:"8px 12px",flexWrap:"wrap"},children:[E.jsxs("svg",{width:180,height:180,style:{flexShrink:0},onMouseLeave:()=>s(null),children:[d.map((u,f)=>E.jsx("path",{d:u.path,fill:u.color,opacity:o===null||o===f?1:.55,style:{cursor:"pointer",transition:"opacity 0.15s"},onMouseEnter:()=>s(f)},f)),E.jsx("text",{x:R,y:c-5,textAnchor:"middle",fontSize:11,fontFamily:r.fontMono,fill:r.textSecondary,children:an(O?O.value:l)}),E.jsx("text",{x:R,y:c+9,textAnchor:"middle",fontSize:9,fontFamily:r.font,fill:r.textMuted,children:O?`${O.pct.toFixed(1)}%`:"total"})]}),E.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4,maxHeight:180,overflowY:"auto",flex:1},children:d.map((u,f)=>E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,cursor:"default",opacity:o===null||o===f?1:.5},onMouseEnter:()=>s(f),onMouseLeave:()=>s(null),children:[E.jsx("div",{style:{width:10,height:10,borderRadius:2,background:u.color,flexShrink:0}}),E.jsx("span",{style:{fontSize:11,fontFamily:r.font,color:r.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:u.label}),E.jsxs("span",{style:{fontSize:11,fontFamily:r.fontMono,color:r.textMuted,marginLeft:"auto",flexShrink:0},children:[u.pct.toFixed(1),"%"]})]},f))})]})}function Nd({result:e,themeMode:t,chartConfig:n}){const r=ie[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(R=>Yo(o[R]))??e.columns[0],i=o[s],a=Number(i),T=isNaN(a)?String(i):a.toLocaleString(void 0,{maximumFractionDigits:2}),l=(n==null?void 0:n.title)??(n!=null&&n.x&&o[n.x]?String(o[n.x]):s);return E.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"32px 24px",gap:8},children:[E.jsx("span",{style:{fontSize:40,fontWeight:700,fontFamily:r.fontMono,color:r.accent,lineHeight:1.1},children:T}),E.jsx("span",{style:{fontSize:13,fontFamily:r.font,color:r.textMuted,textTransform:"uppercase",letterSpacing:"0.08em",fontWeight:500},children:l})]})}function Od({result:e,themeMode:t,chartConfig:n}){const r=ie[t],o=Vo(e,n),s=o!=="table",[i,a]=C.useState(s?"chart":"table"),T=n!=null&&n.x&&e.columns.includes(n.x)?n.x:void 0,l=n!=null&&n.y&&e.columns.includes(n.y)?n.y:void 0,R=T||l?fd(e,T,l):e,c=[];n!=null&&n.x&&!e.columns.includes(n.x)&&c.push(`Column '${n.x}' not found in results — using auto-detection.`),n!=null&&n.y&&!e.columns.includes(n.y)&&c.push(`Column '${n.y}' not found in results — using auto-detection.`);const A=o==="line"?"Line":o==="pie"?"Pie":o==="kpi"?"KPI":"Bar";return o==="kpi"?E.jsxs("div",{children:[c.length>0&&E.jsx(ii,{warnings:c,t:r}),E.jsx(Nd,{result:e,themeMode:t,chartConfig:n})]}):E.jsxs("div",{children:[c.length>0&&E.jsx(ii,{warnings:c,t:r}),s&&E.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",padding:"4px 12px",gap:4,borderBottom:`1px solid ${r.cellBorder}`,background:`${r.tableHeaderBg}60`},children:[E.jsx("span",{style:{fontSize:10,color:r.textMuted,fontFamily:r.font,marginRight:4},children:"View:"}),["chart","table"].map(S=>E.jsx("button",{onClick:()=>a(S),style:{padding:"2px 8px",fontSize:10,fontFamily:r.font,borderRadius:4,border:`1px solid ${i===S?r.accent:r.btnBorder}`,background:i===S?`${r.accent}20`:"transparent",color:i===S?r.accent:r.textMuted,cursor:"pointer",transition:"all 0.15s",textTransform:"capitalize"},children:S==="chart"?A:"Table"},S))]}),i==="table"||!s?E.jsx(Ma,{result:e,themeMode:t}):o==="line"?E.jsx(dd,{result:R,themeMode:t}):o==="pie"?E.jsx(ud,{result:e,themeMode:t,chartConfig:n}):E.jsx(Ad,{result:R,themeMode:t})]})}function ii({warnings:e,t}){return E.jsx("div",{style:{padding:"4px 12px",background:"#e3b34115",borderBottom:"1px solid #e3b34130",display:"flex",flexDirection:"column",gap:2},children:e.map((n,r)=>E.jsx("span",{style:{fontSize:11,color:"#e3b341",fontFamily:t.font},children:n},r))})}function fd(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 i={};for(const a of o)i[a]=s[a];return i})}}function Cd(e){let t=e;try{const l=JSON.parse(e);l&&typeof l.error=="string"&&(t=l.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 i=t.match(/at or near "([^"]+)"/i);i?s=i[1]:/at end of input/i.test(t)&&(s="end of input");let a;n==="Syntax Error"?s==='"""'||t.includes('"""')?a="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)?a="Query is incomplete — check for unclosed parentheses, missing keywords, or a dangling comma.":(s===")"||s==="(")&&(a="Mismatched parentheses — check that every opening ( has a closing )."):n==="Reference Error"?/column.*not found|Referenced column/i.test(t)?a="Column not found — check the column name in the Schema panel (left sidebar).":/table.*not found|Table.*does not exist/i.test(t)&&(a="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)&&(a="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"?a="File could not be read — use read_csv_auto('./data/filename.csv'). Open the Schema panel to browse available data files.":n==="Type Error"&&(a="Type mismatch — you may be comparing or casting incompatible types (e.g. text vs number).");const T=t.replace(/^(Parser Error|Binder Error|Conversion Error|Invalid Input Error|IO Error|Constraint Error):\s*/i,"").trim();return{type:n,message:T,line:r,near:s,hint:a}}function Ld(e,t){const n=e.length,r=t.length,o=Array.from({length:n+1},(s,i)=>Array.from({length:r+1},(a,T)=>i===0?T:T===0?i:0));for(let s=1;s<=n;s++)for(let i=1;i<=r;i++)o[s][i]=e[s-1]===t[i-1]?o[s-1][i-1]:1+Math.min(o[s-1][i],o[s][i-1],o[s-1][i-1]);return o[n][r]}function Ei(e,t){const n=e.toLowerCase();let r=null,o=4;for(const s of t){const i=Ld(n,s.toLowerCase());i<o&&(o=i,r=s)}return r}function hd({message:e,themeMode:t,onFix:n,schemaTables:r}){const o=ie[t],s=Cd(e);let i=null;if(r&&r.length>0&&s.type==="Reference Error"){const T=/column.*not found|Referenced column/i.test(s.message),l=/table.*not found|Table.*does not exist/i.test(s.message);if(T&&s.near){const R=r.flatMap(A=>A.columns.map(S=>S.name)),c=Ei(s.near,R);c&&(i=`Did you mean column "${c}"?`)}else if(l&&s.near){const R=Ei(s.near,r.map(c=>c.name));R&&(i=`Did you mean table "${R}"?`)}}const a=n&&(s.type==="Syntax Error"||s.near===")"||s.near==="("||s.near==="end of input");return E.jsxs("div",{style:{padding:"12px 14px",background:`${o.error}10`,borderLeft:`3px solid ${o.error}`,display:"flex",flexDirection:"column",gap:8},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[E.jsx("div",{style:{flexShrink:0,color:o.error,display:"flex",alignItems:"center"},children:E.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:E.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"})})}),E.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&&E.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&&E.jsxs("span",{style:{fontSize:11,fontFamily:o.fontMono,color:o.textSecondary,flexShrink:0},children:["near ",E.jsxs("span",{style:{color:o.error},children:["“",s.near,"”"]})]})]}),E.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}),i&&E.jsxs("div",{style:{fontSize:12,fontFamily:o.font,color:o.textSecondary,display:"flex",alignItems:"center",gap:6},children:[E.jsx("span",{style:{color:o.accent},children:"→"}),i]}),s.hint&&E.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:[E.jsx("span",{style:{flexShrink:0,fontSize:13,lineHeight:1.5},children:"💡"}),E.jsx("span",{style:{fontSize:12,fontFamily:o.font,color:o.warning,lineHeight:1.6},children:s.hint})]}),a&&E.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:T=>{T.currentTarget.style.background=`${o.accent}25`},onMouseLeave:T=>{T.currentTarget.style.background=`${o.accent}15`},children:[E.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 Xn={source_table:"#8b949e",block:"#56d364",metric:"#388bfd",dimension:"#e3b341",domain:"#d2a8ff",chart:"#f778ba"},_d={source_table:"TBL",block:"BLK",metric:"MET",dimension:"DIM",chart:"CHT",domain:"DOM"},pd={certified:"#56d364",draft:"#8b949e",review:"#e3b341",deprecated:"#f85149"};function md(e){const t=e.match(/^\s*block\s+"([^"]+)"/i);return t?t[1]:null}function Dd(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 gd(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 ai({node:e,t}){const n=Xn[e.type]??"#8b949e",r=_d[e.type]??e.type.slice(0,3).toUpperCase(),o=e.status?pd[e.status]:void 0;return E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"2px 0",fontSize:11,color:t.textPrimary},children:[E.jsx("span",{style:{color:n,fontSize:9,fontWeight:700,width:26,flexShrink:0},children:r}),E.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:e.name}),e.domain&&E.jsx("span",{style:{fontSize:9,color:t.textMuted},children:e.domain}),o&&E.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:o,flexShrink:0}})]})}function Pd({cellContent:e,cellType:t,cellName:n,themeMode:r,t:o}){const[s,i]=C.useState(!1),[a,T]=C.useState(!1),[l,R]=C.useState([]),[c,A]=C.useState([]),[S,d]=C.useState([]),[I,O]=C.useState({metrics:[],dimensions:[]}),[u,f]=C.useState(null),L=(t==="dql"?md(e):null)||n,m=C.useCallback(async()=>{if(!(!L&&t!=="sql")){T(!0),f(null);try{const D=Dd(e);if(d(D),O(gd(e)),L){const M=await Re.fetchBlockLineage(L);M&&(R(M.ancestors??[]),A(M.descendants??[]))}else{const B=(await Re.fetchLineage()).nodes.filter(F=>D.some(g=>F.name===g||F.id===`table:${g}`||F.id===`block:${g}`));R(B),A([])}}catch{f("Failed to load lineage")}finally{T(!1)}}},[L,e,t]);C.useEffect(()=>{s&&m()},[s,m]);const p=S.length>0||I.metrics.length>0||I.dimensions.length>0;return e.trim()?E.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`},children:[E.jsxs("button",{onClick:()=>i(D=>!D),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:[E.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",style:{flexShrink:0},children:[E.jsx("circle",{cx:"4",cy:"4",r:"2"}),E.jsx("circle",{cx:"12",cy:"8",r:"2"}),E.jsx("circle",{cx:"4",cy:"12",r:"2"}),E.jsx("line",{x1:"6",y1:"4",x2:"10",y2:"8"}),E.jsx("line",{x1:"6",y1:"12",x2:"10",y2:"8"})]}),E.jsx("span",{children:"Lineage"}),E.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:E.jsx("path",{d:"M1 3l4 4 4-4",stroke:"currentColor",fill:"none",strokeWidth:"1.5"})})]}),s&&E.jsx("div",{style:{padding:"6px 12px 8px",fontSize:11},children:a?E.jsx("div",{style:{color:o.textMuted,padding:"4px 0"},children:"Loading lineage..."}):u?E.jsx("div",{style:{color:o.error,padding:"4px 0"},children:u}):E.jsxs(E.Fragment,{children:[S.length>0&&E.jsxs("div",{style:{marginBottom:6},children:[E.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Reads From (",S.length,")"]}),S.map(D=>E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[E.jsx("span",{style:{color:Xn.source_table,fontSize:9,fontWeight:700,width:26},children:"TBL"}),E.jsx("span",{children:D})]},D))]}),I.metrics.length>0&&E.jsxs("div",{style:{marginBottom:6},children:[E.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(D=>E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[E.jsx("span",{style:{color:Xn.metric,fontSize:9,fontWeight:700,width:26},children:"MET"}),E.jsx("span",{children:D})]},D))]}),I.dimensions.length>0&&E.jsxs("div",{style:{marginBottom:6},children:[E.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(D=>E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[E.jsx("span",{style:{color:Xn.dimension,fontSize:9,fontWeight:700,width:26},children:"DIM"}),E.jsx("span",{children:D})]},D))]}),l.length>0&&E.jsxs("div",{style:{marginBottom:6},children:[E.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Upstream (",l.length,")"]}),l.map(D=>E.jsx(ai,{node:D,t:o},D.id))]}),c.length>0&&E.jsxs("div",{style:{marginBottom:6},children:[E.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Downstream (",c.length,")"]}),c.map(D=>E.jsx(ai,{node:D,t:o},D.id))]}),!p&&l.length===0&&c.length===0&&E.jsx("div",{style:{color:o.textMuted,padding:"2px 0"},children:"No lineage dependencies detected for this cell."})]})})]}):null}const G=e=>e.flatMap(Md),Md=e=>jn(xd(e)).map(yd),yd=e=>e.replace(/ +/g," ").trim(),xd=e=>({type:"mandatory_block",items:ds(e,0)[0]}),ds=(e,t,n)=>{const r=[];for(;e[t];){const[o,s]=Ud(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]},Ud=(e,t)=>{const n=[];for(;;){const[r,o]=bd(e,t);if(r)n.push(r),t=o;else break}return n.length===1?[n[0],t]:[{type:"concatenation",items:n},t]},bd=(e,t)=>{if(e[t]==="{")return Gd(e,t+1);if(e[t]==="[")return Bd(e,t+1);{let n="";for(;e[t]&&/[A-Za-z0-9_ ]/.test(e[t]);)n+=e[t],t++;return[n,t]}},Gd=(e,t)=>{const[n,r]=ds(e,t,"}");return[{type:"mandatory_block",items:n},r]},Bd=(e,t)=>{const[n,r]=ds(e,t,"]");return[{type:"optional_block",items:n},r]},jn=e=>{if(typeof e=="string")return[e];if(e.type==="concatenation")return e.items.map(jn).reduce(vd,[""]);if(e.type==="mandatory_block")return e.items.flatMap(jn);if(e.type==="optional_block")return["",...e.items.flatMap(jn)];throw new Error(`Unknown node type: ${e}`)},vd=(e,t)=>{const n=[];for(const r of e)for(const o of t)n.push(r+o);return n};var w;(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"})(w=w||(w={}));const ya=e=>({type:w.EOF,raw:"«EOF»",text:"«EOF»",start:e}),ot=ya(1/0),ft=e=>t=>t.type===e.type&&t.text===e.text,st={ARRAY:ft({text:"ARRAY",type:w.RESERVED_DATA_TYPE}),BY:ft({text:"BY",type:w.RESERVED_KEYWORD}),SET:ft({text:"SET",type:w.RESERVED_CLAUSE}),STRUCT:ft({text:"STRUCT",type:w.RESERVED_DATA_TYPE}),WINDOW:ft({text:"WINDOW",type:w.RESERVED_CLAUSE}),VALUES:ft({text:"VALUES",type:w.RESERVED_CLAUSE})},xa=e=>e===w.RESERVED_DATA_TYPE||e===w.RESERVED_KEYWORD||e===w.RESERVED_FUNCTION_NAME||e===w.RESERVED_KEYWORD_PHRASE||e===w.RESERVED_DATA_TYPE_PHRASE||e===w.RESERVED_CLAUSE||e===w.RESERVED_SELECT||e===w.RESERVED_SET_OPERATION||e===w.RESERVED_JOIN||e===w.ARRAY_KEYWORD||e===w.CASE||e===w.END||e===w.WHEN||e===w.ELSE||e===w.THEN||e===w.LIMIT||e===w.BETWEEN||e===w.AND||e===w.OR||e===w.XOR,Hd=e=>e===w.AND||e===w.OR||e===w.XOR,Fd=["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"],wd=["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"],Yd=["ARRAY","BOOL","BYTES","DATE","DATETIME","GEOGRAPHY","INTERVAL","INT64","INT","SMALLINT","INTEGER","BIGINT","TINYINT","BYTEINT","NUMERIC","DECIMAL","BIGNUMERIC","BIGDECIMAL","FLOAT64","STRING","STRUCT","TIME","TIMEZONE"],Vd=G(["SELECT [ALL | DISTINCT] [AS STRUCT | AS VALUE]"]),Wd=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"]),li=G(["CREATE [OR REPLACE] [TEMP|TEMPORARY|SNAPSHOT|EXTERNAL] TABLE [IF NOT EXISTS]"]),jr=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"]),kd=G(["UNION {ALL | DISTINCT}","EXCEPT DISTINCT","INTERSECT DISTINCT"]),Xd=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN"]),jd=G(["TABLESAMPLE SYSTEM","ANY TYPE","ALL COLUMNS","NOT DETERMINISTIC","{ROWS | RANGE} BETWEEN","IS [NOT] DISTINCT FROM"]),$d=G([]),Kd={name:"bigquery",tokenizerOptions:{reservedSelect:Vd,reservedClauses:[...Wd,...jr,...li],reservedSetOperations:kd,reservedJoins:Xd,reservedKeywordPhrases:jd,reservedDataTypePhrases:$d,reservedKeywords:wd,reservedDataTypes:Yd,reservedFunctionNames:Fd,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:Jd},formatOptions:{onelineClauses:[...li,...jr],tabularOnelineClauses:jr}};function Jd(e){return zd(qd(e))}function zd(e){let t=ot;return e.map(n=>n.text==="OFFSET"&&t.text==="["?(t=n,Object.assign(Object.assign({},n),{type:w.RESERVED_FUNCTION_NAME})):(t=n,n))}function qd(e){var t;const n=[];for(let r=0;r<e.length;r++){const o=e[r];if((st.ARRAY(o)||st.STRUCT(o))&&((t=e[r+1])===null||t===void 0?void 0:t.text)==="<"){const s=Zd(e,r+1),i=e.slice(r,s+1);n.push({type:w.IDENTIFIER,raw:i.map(Ti("raw")).join(""),text:i.map(Ti("text")).join(""),start:o.start}),r=s}else n.push(o)}return n}const Ti=e=>t=>t.type===w.IDENTIFIER||t.type===w.COMMA?t[e]+" ":t[e];function Zd(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 Qd=["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"],eI=["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"],tI=["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"],nI=G(["SELECT [DISTINCT]","MODIFY QUERY SELECT [DISTINCT]"]),rI=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]"]),ci=G(["CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS]"]),$r=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"]),oI=G(["UNION [ALL | DISTINCT]","PARALLEL WITH"]),sI=G(["[GLOBAL] [INNER|LEFT|RIGHT|FULL|CROSS] [OUTER|SEMI|ANTI|ANY|ALL|ASOF] JOIN","[LEFT] ARRAY JOIN"]),iI=G(["{ROWS | RANGE} BETWEEN","ALTER MATERIALIZE STATISTICS"]),EI={name:"clickhouse",tokenizerOptions:{reservedSelect:nI,reservedClauses:[...rI,...ci,...$r],reservedSetOperations:oI,reservedJoins:sI,reservedKeywordPhrases:iI,reservedKeywords:eI,reservedDataTypes:tI,reservedFunctionNames:Qd,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:aI},formatOptions:{onelineClauses:[...ci,...$r],tabularOnelineClauses:$r}};function aI(e){return e.map((t,n)=>{const r=e[n+1]||ot,o=e[n-1]||ot;return t.type===w.RESERVED_SELECT&&(r.type===w.COMMA||o.type===w.RESERVED_CLAUSE||o.type===w.COMMA)?Object.assign(Object.assign({},t),{type:w.RESERVED_KEYWORD}):st.SET(t)&&r.type===w.OPEN_PAREN?Object.assign(Object.assign({},t),{type:w.RESERVED_FUNCTION_NAME}):t})}const lI=["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"],TI=["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"],cI=["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"],RI=G(["SELECT [ALL | DISTINCT]"]),AI=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"]),Ri=G(["CREATE [GLOBAL TEMPORARY | EXTERNAL] TABLE [IF NOT EXISTS]"]),Kr=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"]),SI=G(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),dI=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN"]),II=G(["ON DELETE","ON UPDATE","SET NULL","{ROWS | RANGE} BETWEEN"]),uI=G([]),NI={name:"db2",tokenizerOptions:{reservedSelect:RI,reservedClauses:[...AI,...Ri,...Kr],reservedSetOperations:SI,reservedJoins:dI,reservedKeywordPhrases:II,reservedDataTypePhrases:uI,reservedKeywords:TI,reservedDataTypes:cI,reservedFunctionNames:lI,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:[...Ri,...Kr],tabularOnelineClauses:Kr}},OI=["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"],fI=["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"],CI=["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"],LI=G(["SELECT [ALL | DISTINCT]"]),hI=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"]),Ai=G(["CREATE [OR REPLACE] TABLE"]),Jr=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}"]),_I=G(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),pI=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","[LEFT | RIGHT] EXCEPTION JOIN","{INNER | CROSS} JOIN"]),mI=G(["ON DELETE","ON UPDATE","SET NULL","{ROWS | RANGE} BETWEEN"]),DI=G([]),gI={name:"db2i",tokenizerOptions:{reservedSelect:LI,reservedClauses:[...hI,...Ai,...Jr],reservedSetOperations:_I,reservedJoins:pI,reservedKeywordPhrases:mI,reservedDataTypePhrases:DI,reservedKeywords:fI,reservedDataTypes:CI,reservedFunctionNames:OI,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:[...Ai,...Jr],tabularOnelineClauses:Jr}},PI=["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"],MI=["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"],yI=["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"],xI=G(["SELECT [ALL | DISTINCT]"]),UI=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"]),Si=G(["CREATE [OR REPLACE] [TEMPORARY | TEMP] TABLE [IF NOT EXISTS]"]),zr=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]"]),bI=G(["UNION [ALL | BY NAME]","EXCEPT [ALL]","INTERSECT [ALL]"]),GI=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"]),BI=G(["{ROWS | RANGE | GROUPS} BETWEEN","SIMILAR TO","IS [NOT] DISTINCT FROM"]),vI=G(["TIMESTAMP WITH TIME ZONE"]),HI={name:"duckdb",tokenizerOptions:{reservedSelect:xI,reservedClauses:[...UI,...Si,...zr],reservedSetOperations:bI,reservedJoins:GI,reservedKeywordPhrases:BI,reservedDataTypePhrases:vI,supportsXor:!0,reservedKeywords:MI,reservedDataTypes:yI,reservedFunctionNames:PI,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:[...Si,...zr],tabularOnelineClauses:zr}},FI=["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"],wI=["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"],YI=["ARRAY","BIGINT","BINARY","BOOLEAN","CHAR","DATE","DECIMAL","DOUBLE","FLOAT","INT","INTEGER","INTERVAL","MAP","NUMERIC","PRECISION","SMALLINT","STRUCT","TIMESTAMP","VARCHAR"],VI=G(["SELECT [ALL | DISTINCT]"]),WI=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"]),di=G(["CREATE [TEMPORARY] [EXTERNAL] TABLE [IF NOT EXISTS]"]),qr=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"]),kI=G(["UNION [ALL | DISTINCT]"]),XI=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","LEFT SEMI JOIN"]),jI=G(["{ROWS | RANGE} BETWEEN"]),$I=G([]),KI={name:"hive",tokenizerOptions:{reservedSelect:VI,reservedClauses:[...WI,...di,...qr],reservedSetOperations:kI,reservedJoins:XI,reservedKeywordPhrases:jI,reservedDataTypePhrases:$I,reservedKeywords:wI,reservedDataTypes:YI,reservedFunctionNames:FI,extraParens:["[]"],stringTypes:['""-bs',"''-bs"],identTypes:["``"],variableTypes:[{quote:"{}",prefixes:["$"],requirePrefix:!0}],operators:["%","~","^","|","&","<=>","==","!","||"]},formatOptions:{onelineClauses:[...di,...qr],tabularOnelineClauses:qr}};function Lr(e){return e.map((t,n)=>{const r=e[n+1]||ot;if(st.SET(t)&&r.text==="(")return Object.assign(Object.assign({},t),{type:w.RESERVED_FUNCTION_NAME});const o=e[n-1]||ot;return st.VALUES(t)&&o.text==="="?Object.assign(Object.assign({},t),{type:w.RESERVED_FUNCTION_NAME}):t})}const JI=["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"],zI=["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"],qI=["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"],ZI=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),QI=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"]),Ii=G(["CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS]"]),Zr=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"]),eu=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]","MINUS [ALL | DISTINCT]"]),tu=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),nu=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),ru=G([]),ou={name:"mariadb",tokenizerOptions:{reservedSelect:ZI,reservedClauses:[...QI,...Ii,...Zr],reservedSetOperations:eu,reservedJoins:tu,reservedKeywordPhrases:nu,reservedDataTypePhrases:ru,supportsXor:!0,reservedKeywords:JI,reservedDataTypes:zI,reservedFunctionNames:qI,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:Lr},formatOptions:{onelineClauses:[...Ii,...Zr],tabularOnelineClauses:Zr}},su=["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"],iu=["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"],Eu=["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"],au=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),lu=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"]),ui=G(["CREATE [TEMPORARY] TABLE [IF NOT EXISTS]"]),Qr=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"]),Tu=G(["UNION [ALL | DISTINCT]"]),cu=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),Ru=G(["ON {UPDATE | DELETE} [SET NULL]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),Au=G([]),Su={name:"mysql",tokenizerOptions:{reservedSelect:au,reservedClauses:[...lu,...ui,...Qr],reservedSetOperations:Tu,reservedJoins:cu,reservedKeywordPhrases:Ru,reservedDataTypePhrases:Au,supportsXor:!0,reservedKeywords:su,reservedDataTypes:iu,reservedFunctionNames:Eu,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:Lr},formatOptions:{onelineClauses:[...ui,...Qr],tabularOnelineClauses:Qr}},du=["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"],Iu=["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"],uu=["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"],Nu=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),Ou=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"]),Ni=G(["CREATE [TEMPORARY] TABLE [IF NOT EXISTS]"]),eo=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"]),fu=G(["UNION [ALL | DISTINCT]"]),Cu=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),Lu=G(["ON {UPDATE | DELETE} [SET NULL]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),hu=G([]),_u={name:"tidb",tokenizerOptions:{reservedSelect:Nu,reservedClauses:[...Ou,...Ni,...eo],reservedSetOperations:fu,reservedJoins:Cu,reservedKeywordPhrases:Lu,reservedDataTypePhrases:hu,supportsXor:!0,reservedKeywords:du,reservedDataTypes:Iu,reservedFunctionNames:uu,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:Lr},formatOptions:{onelineClauses:[...Ni,...eo],tabularOnelineClauses:eo}},pu=["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"],mu=["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"],Du=[],gu=G(["SELECT [ALL | DISTINCT]"]),Pu=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"]),Oi=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"]),Mu=G(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),yu=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","INNER JOIN"]),xu=G(["{ROWS | RANGE | GROUPS} BETWEEN"]),Uu=G([]),bu={name:"n1ql",tokenizerOptions:{reservedSelect:gu,reservedClauses:[...Pu,...Oi],reservedSetOperations:Mu,reservedJoins:yu,reservedKeywordPhrases:xu,reservedDataTypePhrases:Uu,supportsXor:!0,reservedKeywords:mu,reservedDataTypes:Du,reservedFunctionNames:pu,stringTypes:['""-bs',"''-bs"],identTypes:["``"],extraParens:["[]","{}"],paramTypes:{positional:!0,numbered:["$"],named:["$"]},lineCommentTypes:["#","--"],operators:["%","==",":","||"]},formatOptions:{onelineClauses:Oi}},Gu=["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"],Bu=["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"],vu=["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"],Hu=G(["SELECT [ALL | DISTINCT | UNIQUE]"]),Fu=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"]),fi=G(["CREATE [GLOBAL TEMPORARY | PRIVATE TEMPORARY | SHARDED | DUPLICATED | IMMUTABLE BLOCKCHAIN | BLOCKCHAIN | IMMUTABLE] TABLE"]),to=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"]),wu=G(["UNION [ALL]","MINUS","INTERSECT"]),Yu=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN","{CROSS | OUTER} APPLY"]),Vu=G(["ON {UPDATE | DELETE} [SET NULL]","ON COMMIT","{ROWS | RANGE} BETWEEN"]),Wu=G([]),ku={name:"plsql",tokenizerOptions:{reservedSelect:Hu,reservedClauses:[...Fu,...fi,...to],reservedSetOperations:wu,reservedJoins:Yu,reservedKeywordPhrases:Vu,reservedDataTypePhrases:Wu,supportsXor:!0,reservedKeywords:Gu,reservedDataTypes:Bu,reservedFunctionNames:vu,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:Xu},formatOptions:{alwaysDenseOperators:["@"],onelineClauses:[...fi,...to],tabularOnelineClauses:to}};function Xu(e){let t=ot;return e.map(n=>st.SET(n)&&st.BY(t)?Object.assign(Object.assign({},n),{type:w.RESERVED_KEYWORD}):(xa(n.type)&&(t=n),n))}const ju=["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"],$u=["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"],Ku=["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"],Ju=G(["SELECT [ALL | DISTINCT]"]),zu=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"]),Ci=G(["CREATE [GLOBAL | LOCAL] [TEMPORARY | TEMP | UNLOGGED] TABLE [IF NOT EXISTS]"]),no=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"]),qu=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),Zu=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),Qu=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"]),eN=G(["[TIMESTAMP | TIME] {WITH | WITHOUT} TIME ZONE"]),tN={name:"postgresql",tokenizerOptions:{reservedSelect:Ju,reservedClauses:[...zu,...Ci,...no],reservedSetOperations:qu,reservedJoins:Zu,reservedKeywordPhrases:Qu,reservedDataTypePhrases:eN,reservedKeywords:$u,reservedDataTypes:Ku,reservedFunctionNames:ju,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:[...Ci,...no],tabularOnelineClauses:no}},nN=["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"],rN=["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"],oN=["ARRAY","BIGINT","BPCHAR","CHAR","CHARACTER VARYING","CHARACTER","DECIMAL","INT","INT2","INT4","INT8","INTEGER","NCHAR","NUMERIC","NVARCHAR","SMALLINT","TEXT","VARBYTE","VARCHAR"],sN=G(["SELECT [ALL | DISTINCT]"]),iN=G(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","QUALIFY","PARTITION BY","ORDER BY","LIMIT","OFFSET","INSERT INTO","VALUES","SET"]),Li=G(["CREATE [TEMPORARY | TEMP | LOCAL TEMPORARY | LOCAL TEMP] TABLE [IF NOT EXISTS]"]),ro=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"]),EN=G(["UNION [ALL]","EXCEPT","INTERSECT","MINUS"]),aN=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),lN=G(["NULL AS","DATA CATALOG","HIVE METASTORE","{ROWS | RANGE} BETWEEN"]),TN=G([]),cN={name:"redshift",tokenizerOptions:{reservedSelect:sN,reservedClauses:[...iN,...Li,...ro],reservedSetOperations:EN,reservedJoins:aN,reservedKeywordPhrases:lN,reservedDataTypePhrases:TN,reservedKeywords:rN,reservedDataTypes:oN,reservedFunctionNames:nN,extraParens:["[]"],stringTypes:["''-qq"],identTypes:['""-qq'],identChars:{first:"#"},paramTypes:{numbered:["$"]},operators:["^","%","@","|/","||/","&","|","~","<<",">>","||","::"]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...Li,...ro],tabularOnelineClauses:ro}},RN=["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"],AN=["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"],SN=["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"],dN=G(["SELECT [ALL | DISTINCT]"]),IN=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"]),hi=G(["CREATE [EXTERNAL] TABLE [IF NOT EXISTS]"]),oo=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"]),uN=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),NN=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"]),ON=G(["ON DELETE","ON UPDATE","CURRENT ROW","{ROWS | RANGE} BETWEEN"]),fN=G([]),CN={name:"spark",tokenizerOptions:{reservedSelect:dN,reservedClauses:[...IN,...hi,...oo],reservedSetOperations:uN,reservedJoins:NN,reservedKeywordPhrases:ON,reservedDataTypePhrases:fN,supportsXor:!0,reservedKeywords:RN,reservedDataTypes:AN,reservedFunctionNames:SN,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:LN},formatOptions:{onelineClauses:[...hi,...oo],tabularOnelineClauses:oo}};function LN(e){return e.map((t,n)=>{const r=e[n-1]||ot,o=e[n+1]||ot;return st.WINDOW(t)&&o.type===w.OPEN_PAREN?Object.assign(Object.assign({},t),{type:w.RESERVED_FUNCTION_NAME}):t.text==="ITEMS"&&t.type===w.RESERVED_KEYWORD&&!(r.text==="COLLECTION"&&o.text==="TERMINATED")?Object.assign(Object.assign({},t),{type:w.IDENTIFIER,text:t.raw}):t})}const hN=["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"],_N=["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"],pN=["ANY","ARRAY","BLOB","CHARACTER","DECIMAL","INT","INTEGER","NATIVE CHARACTER","NCHAR","NUMERIC","NVARCHAR","REAL","TEXT","VARCHAR","VARYING CHARACTER"],mN=G(["SELECT [ALL | DISTINCT]"]),DN=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"]),_i=G(["CREATE [TEMPORARY | TEMP] TABLE [IF NOT EXISTS]"]),so=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"]),gN=G(["UNION [ALL]","EXCEPT","INTERSECT"]),PN=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),MN=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE | GROUPS} BETWEEN","DO UPDATE"]),yN=G([]),xN={name:"sqlite",tokenizerOptions:{reservedSelect:mN,reservedClauses:[...DN,..._i,...so],reservedSetOperations:gN,reservedJoins:PN,reservedKeywordPhrases:MN,reservedDataTypePhrases:yN,reservedKeywords:_N,reservedDataTypes:pN,reservedFunctionNames:hN,stringTypes:["''-qq",{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq',"``","[]"],paramTypes:{positional:!0,numbered:["?"],named:[":","@","$"]},operators:["%","~","&","|","<<",">>","==","->","->>","||"]},formatOptions:{onelineClauses:[..._i,...so],tabularOnelineClauses:so}},UN=["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"],bN=["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"],GN=["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"],BN=G(["SELECT [ALL | DISTINCT]"]),vN=G(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY [ALL | DISTINCT]","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","FETCH {FIRST | NEXT}","INSERT INTO","VALUES","SET"]),pi=G(["CREATE [GLOBAL TEMPORARY | LOCAL TEMPORARY] TABLE"]),io=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"]),HN=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),FN=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),wN=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE} BETWEEN"]),YN=G([]),VN={name:"sql",tokenizerOptions:{reservedSelect:BN,reservedClauses:[...vN,...pi,...io],reservedSetOperations:HN,reservedJoins:FN,reservedKeywordPhrases:wN,reservedDataTypePhrases:YN,reservedKeywords:bN,reservedDataTypes:GN,reservedFunctionNames:UN,stringTypes:[{quote:"''-qq-bs",prefixes:["N","U&"]},{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq',"``"],paramTypes:{positional:!0},operators:["||"]},formatOptions:{onelineClauses:[...pi,...io],tabularOnelineClauses:io}},WN=["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"],kN=["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"],XN=["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"],jN=G(["SELECT [ALL | DISTINCT]"]),$N=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"]),mi=G(["CREATE TABLE [IF NOT EXISTS]"]),Eo=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"]),KN=G(["UNION [ALL | DISTINCT] [CORRESPONDING]","EXCEPT [ALL | DISTINCT] [CORRESPONDING]","INTERSECT [ALL | DISTINCT] [CORRESPONDING]"]),JN=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),zN=G(["{ROWS | RANGE | GROUPS} BETWEEN","IS [NOT] DISTINCT FROM"]),qN=G([]),ZN={name:"trino",tokenizerOptions:{reservedSelect:jN,reservedClauses:[...$N,...mi,...Eo],reservedSetOperations:KN,reservedJoins:JN,reservedKeywordPhrases:zN,reservedDataTypePhrases:qN,reservedKeywords:kN,reservedDataTypes:XN,reservedFunctionNames:WN,extraParens:["[]","{}"],stringTypes:[{quote:"''-qq",prefixes:["U&"]},{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq'],paramTypes:{positional:!0},operators:["%","->","=>",":","||","|","^","$"]},formatOptions:{onelineClauses:[...mi,...Eo],tabularOnelineClauses:Eo}},QN=["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"],eO=["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"],tO=["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"],nO=G(["SELECT [ALL | DISTINCT]"]),rO=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"]),Di=G(["CREATE TABLE"]),ao=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"]),oO=G(["UNION [ALL]","EXCEPT","INTERSECT"]),sO=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","{CROSS | OUTER} APPLY"]),iO=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE} BETWEEN"]),EO=G([]),aO={name:"transactsql",tokenizerOptions:{reservedSelect:nO,reservedClauses:[...rO,...Di,...ao],reservedSetOperations:oO,reservedJoins:sO,reservedKeywordPhrases:iO,reservedDataTypePhrases:EO,reservedKeywords:eO,reservedDataTypes:tO,reservedFunctionNames:QN,nestedBlockComments:!0,stringTypes:[{quote:"''-qq",prefixes:["N"]},"{}"],identTypes:['""-qq',"[]"],identChars:{first:"#@",rest:"#@$"},paramTypes:{named:["@"],quoted:["@"]},operators:["%","&","|","^","~","!<","!>","+=","-=","*=","/=","%=","|=","&=","^=","::",":"],propertyAccessOperators:[".."]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...Di,...ao],tabularOnelineClauses:ao}},lO=["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"],TO=["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"],cO=["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"],RO=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),AO=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"]),gi=G(["CREATE [ROWSTORE] [REFERENCE | TEMPORARY | GLOBAL TEMPORARY] TABLE [IF NOT EXISTS]"]),lo=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"]),SO=G(["UNION [ALL | DISTINCT]","EXCEPT","INTERSECT","MINUS"]),dO=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),IO=G(["ON DELETE","ON UPDATE","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),uO=G([]),NO={name:"singlestoredb",tokenizerOptions:{reservedSelect:RO,reservedClauses:[...AO,...gi,...lo],reservedSetOperations:SO,reservedJoins:dO,reservedKeywordPhrases:IO,reservedDataTypePhrases:uO,reservedKeywords:lO,reservedDataTypes:TO,reservedFunctionNames:cO,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:Lr},formatOptions:{alwaysDenseOperators:["::","::$","::%"],onelineClauses:[...gi,...lo],tabularOnelineClauses:lo}},OO=["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"],fO=["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"],CO=["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"],LO=G(["SELECT [ALL | DISTINCT]"]),hO=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"]),Pi=G(["CREATE [OR REPLACE] [VOLATILE] TABLE [IF NOT EXISTS]","CREATE [OR REPLACE] [LOCAL | GLOBAL] {TEMP|TEMPORARY} TABLE [IF NOT EXISTS]"]),To=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"]),_O=G(["UNION [ALL]","MINUS","EXCEPT","INTERSECT"]),pO=G(["[INNER] JOIN","[NATURAL] {LEFT | RIGHT | FULL} [OUTER] JOIN","{CROSS | NATURAL} JOIN"]),mO=G(["{ROWS | RANGE} BETWEEN","ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]"]),DO=G([]),gO={name:"snowflake",tokenizerOptions:{reservedSelect:LO,reservedClauses:[...hO,...Pi,...To],reservedSetOperations:_O,reservedJoins:pO,reservedKeywordPhrases:mO,reservedDataTypePhrases:DO,reservedKeywords:fO,reservedDataTypes:CO,reservedFunctionNames:OO,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:[...Pi,...To],tabularOnelineClauses:To}},PO=Object.freeze(Object.defineProperty({__proto__:null,bigquery:Kd,clickhouse:EI,db2:NI,db2i:gI,duckdb:HI,hive:KI,mariadb:ou,mysql:Su,n1ql:bu,plsql:ku,postgresql:tN,redshift:cN,singlestoredb:NO,snowflake:gO,spark:CN,sql:VN,sqlite:xN,tidb:_u,transactsql:aO,trino:ZN},Symbol.toStringTag,{value:"Module"})),tn=e=>e[e.length-1],Ua=e=>e.sort((t,n)=>n.length-t.length||t.localeCompare(n)),$n=e=>e.replace(/\s+/gu," "),co=e=>/\n/.test(e),Ue=e=>e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),Mi=/\s+/uy,ut=e=>new RegExp(`(?:${e})`,"uy"),MO=e=>e.split("").map(t=>/ /gu.test(t)?"\\s+":`[${t.toUpperCase()}${t.toLowerCase()}]`).join(""),yO=e=>e+"(?:-"+e+")*",xO=({prefixes:e,requirePrefix:t})=>`(?:${e.map(MO).join("|")}${t?"":"|"})`,UO=e=>new RegExp(`(?:${e.map(Ue).join("|")}).*?(?=\r
445
- |\r|
446
- |$)`,"uy"),yi=(e,t=[])=>{const n=e==="open"?0:1,r=["()",...t].map(o=>o[n]);return ut(r.map(Ue).join("|"))},xi=e=>ut(`${Ua(e).map(Ue).join("|")}`),bO=({rest:e,dashes:t})=>e||t?`(?![${e||""}${t?"-":""}])`:"",Xe=(e,t={})=>{if(e.length===0)return/^\b$/u;const n=bO(t),r=Ua(e).map(Ue).join("|").replace(/ /gu,"\\s+");return new RegExp(`(?:${r})${n}\\b`,"iuy")},Ro=(e,t)=>{if(!e.length)return;const n=e.map(Ue).join("|");return ut(`(?:${n})(?:${t})`)},GO=()=>{const e={"<":">","[":"]","(":")","{":"}"},t="{left}(?:(?!{right}').)*?{right}",n=Object.entries(e).map(([i,a])=>t.replace(/{left}/g,Ue(i)).replace(/{right}/g,Ue(a))),r=Ue(Object.keys(e).join(""));return`[Qq]'(?:${String.raw`(?<tag>[^\s${r}])(?:(?!\k<tag>').)*?\k<tag>`}|${n.join("|")})'`},Ui={"``":"(?:`[^`]*`)+","[]":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''":GO()},ba=e=>typeof e=="string"?Ui[e]:"regex"in e?e.regex:xO(e)+Ui[e.quote],BO=e=>ut(e.map(t=>"regex"in t?t.regex:ba(t)).join("|")),Ga=e=>e.map(ba).join("|"),bi=e=>ut(Ga(e)),vO=(e={})=>ut(Ba(e)),Ba=({first:e,rest:t,dashes:n,allowFirstCharNumber:r}={})=>{const o="\\p{Alphabetic}\\p{Mark}_",s="\\p{Decimal_Number}",i=Ue(e??""),a=Ue(t??""),T=r?`[${o}${s}${i}][${o}${s}${a}]*`:`[${o}${i}][${o}${s}${a}]*`;return n?yO(T):T};function va(e,t){const n=e.slice(0,t).split(/\n/);return{line:n.length,col:n[n.length-1].length+1}}class HO{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}=va(this.input,this.index);return new Error(`Parse error: Unexpected "${t}" at line ${n} column ${r}.
447
- ${this.dialectInfo()}`)}dialectInfo(){return this.dialectName==="sql"?`This likely happens because you're using the default "sql" dialect.
448
- If possible, please select a more specific dialect (like sqlite, postgresql, etc).`:`SQL dialect used: "${this.dialectName}".`}getWhitespace(){Mi.lastIndex=this.index;const t=Mi.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 Gi=/\/\*/uy,FO=/[\s\S]/uy,wO=/\*\//uy;class YO{constructor(){this.lastIndex=0}exec(t){let n="",r,o=0;if(r=this.matchSection(Gi,t))n+=r,o++;else return null;for(;o>0;)if(r=this.matchSection(Gi,t))n+=r,o++;else if(r=this.matchSection(wO,t))n+=r,o--;else if(r=this.matchSection(FO,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 VO{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 HO(r,this.dialectName).tokenize(t);return this.cfg.postProcess?this.cfg.postProcess(o):o}buildRulesBeforeParams(t){var n,r,o;return this.validRules([{type:w.DISABLE_COMMENT,regex:/(\/\* *sql-formatter-disable *\*\/[\s\S]*?(?:\/\* *sql-formatter-enable *\*\/|$))/uy},{type:w.BLOCK_COMMENT,regex:t.nestedBlockComments?new YO:/(\/\*[^]*?\*\/)/uy},{type:w.LINE_COMMENT,regex:UO((n=t.lineCommentTypes)!==null&&n!==void 0?n:["--"])},{type:w.QUOTED_IDENTIFIER,regex:bi(t.identTypes)},{type:w.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:w.RESERVED_KEYWORD_PHRASE,regex:Xe((r=t.reservedKeywordPhrases)!==null&&r!==void 0?r:[],t.identChars),text:Se},{type:w.RESERVED_DATA_TYPE_PHRASE,regex:Xe((o=t.reservedDataTypePhrases)!==null&&o!==void 0?o:[],t.identChars),text:Se},{type:w.CASE,regex:/CASE\b/iuy,text:Se},{type:w.END,regex:/END\b/iuy,text:Se},{type:w.BETWEEN,regex:/BETWEEN\b/iuy,text:Se},{type:w.LIMIT,regex:t.reservedClauses.includes("LIMIT")?/LIMIT\b/iuy:void 0,text:Se},{type:w.RESERVED_CLAUSE,regex:Xe(t.reservedClauses,t.identChars),text:Se},{type:w.RESERVED_SELECT,regex:Xe(t.reservedSelect,t.identChars),text:Se},{type:w.RESERVED_SET_OPERATION,regex:Xe(t.reservedSetOperations,t.identChars),text:Se},{type:w.WHEN,regex:/WHEN\b/iuy,text:Se},{type:w.ELSE,regex:/ELSE\b/iuy,text:Se},{type:w.THEN,regex:/THEN\b/iuy,text:Se},{type:w.RESERVED_JOIN,regex:Xe(t.reservedJoins,t.identChars),text:Se},{type:w.AND,regex:/AND\b/iuy,text:Se},{type:w.OR,regex:/OR\b/iuy,text:Se},{type:w.XOR,regex:t.supportsXor?/XOR\b/iuy:void 0,text:Se},...t.operatorKeyword?[{type:w.OPERATOR,regex:/OPERATOR *\([^)]+\)/iuy}]:[],{type:w.RESERVED_FUNCTION_NAME,regex:Xe(t.reservedFunctionNames,t.identChars),text:Se},{type:w.RESERVED_DATA_TYPE,regex:Xe(t.reservedDataTypes,t.identChars),text:Se},{type:w.RESERVED_KEYWORD,regex:Xe(t.reservedKeywords,t.identChars),text:Se}])}buildRulesAfterParams(t){var n,r;return this.validRules([{type:w.VARIABLE,regex:t.variableTypes?BO(t.variableTypes):void 0},{type:w.STRING,regex:bi(t.stringTypes)},{type:w.IDENTIFIER,regex:vO(t.identChars)},{type:w.DELIMITER,regex:/[;]/uy},{type:w.COMMA,regex:/[,]/y},{type:w.OPEN_PAREN,regex:yi("open",t.extraParens)},{type:w.CLOSE_PAREN,regex:yi("close",t.extraParens)},{type:w.OPERATOR,regex:xi(["+","-","/",">","<","=","<>","<=",">=","!=",...(n=t.operators)!==null&&n!==void 0?n:[]])},{type:w.ASTERISK,regex:/[*]/uy},{type:w.PROPERTY_ACCESS_OPERATOR,regex:xi([".",...(r=t.propertyAccessOperators)!==null&&r!==void 0?r:[]])}])}buildParamRules(t,n){var r,o,s,i,a;const T={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:(i=t.paramTypes)===null||i===void 0?void 0:i.positional,custom:(n==null?void 0:n.custom)||((a=t.paramTypes)===null||a===void 0?void 0:a.custom)||[]};return this.validRules([{type:w.NAMED_PARAMETER,regex:Ro(T.named,Ba(t.paramChars||t.identChars)),key:l=>l.slice(1)},{type:w.QUOTED_PARAMETER,regex:Ro(T.quoted,Ga(t.identTypes)),key:l=>(({tokenKey:R,quoteChar:c})=>R.replace(new RegExp(Ue("\\"+c),"gu"),c))({tokenKey:l.slice(2,-1),quoteChar:l.slice(-1)})},{type:w.NUMBERED_PARAMETER,regex:Ro(T.numbered,"[0-9]+"),key:l=>l.slice(1)},{type:w.POSITIONAL_PARAMETER,regex:T.positional?/[?]/y:void 0},...T.custom.map(l=>{var R;return{type:w.CUSTOM_PARAMETER,regex:ut(l.regex),key:(R=l.key)!==null&&R!==void 0?R:(c=>c)}})])}validRules(t){return t.filter(n=>!!n.regex)}}const Se=e=>$n(e.toUpperCase()),Bi=new Map,WO=e=>{let t=Bi.get(e);return t||(t=kO(e),Bi.set(e,t)),t},kO=e=>({tokenizer:new VO(e.tokenizerOptions,e.name),formatOptions:XO(e.formatOptions)}),XO=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 jO(e){return e.indentStyle==="tabularLeft"||e.indentStyle==="tabularRight"?" ".repeat(10):e.useTabs?" ":" ".repeat(e.tabWidth)}function Ct(e){return e.indentStyle==="tabularLeft"||e.indentStyle==="tabularRight"}class $O{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 Kn={exports:{}},KO=Kn.exports,vi;function JO(){return vi||(vi=1,(function(e){(function(t,n){e.exports?e.exports=n():t.nearley=n()})(KO,function(){function t(l,R,c){return this.id=++t.highestId,this.name=l,this.symbols=R,this.postprocess=c,this}t.highestId=0,t.prototype.toString=function(l){var R=typeof l>"u"?this.symbols.map(T).join(" "):this.symbols.slice(0,l).map(T).join(" ")+" ● "+this.symbols.slice(l).map(T).join(" ");return this.name+" → "+R};function n(l,R,c,A){this.rule=l,this.dot=R,this.reference=c,this.data=[],this.wantedBy=A,this.isComplete=this.dot===l.symbols.length}n.prototype.toString=function(){return"{"+this.rule.toString(this.dot)+"}, from: "+(this.reference||0)},n.prototype.nextState=function(l){var R=new n(this.rule,this.dot+1,this.reference,this.wantedBy);return R.left=this,R.right=l,R.isComplete&&(R.data=R.build(),R.right=void 0),R},n.prototype.build=function(){var l=[],R=this;do l.push(R.right.data),R=R.left;while(R.left);return l.reverse(),l},n.prototype.finish=function(){this.rule.postprocess&&(this.data=this.rule.postprocess(this.data,this.reference,i.fail))};function r(l,R){this.grammar=l,this.index=R,this.states=[],this.wants={},this.scannable=[],this.completed={}}r.prototype.process=function(l){for(var R=this.states,c=this.wants,A=this.completed,S=0;S<R.length;S++){var d=R[S];if(d.isComplete){if(d.finish(),d.data!==i.fail){for(var I=d.wantedBy,O=I.length;O--;){var u=I[O];this.complete(u,d)}if(d.reference===this.index){var f=d.rule.name;(this.completed[f]=this.completed[f]||[]).push(d)}}}else{var f=d.rule.symbols[d.dot];if(typeof f!="string"){this.scannable.push(d);continue}if(c[f]){if(c[f].push(d),A.hasOwnProperty(f))for(var N=A[f],O=0;O<N.length;O++){var L=N[O];this.complete(d,L)}}else c[f]=[d],this.predict(f)}}},r.prototype.predict=function(l){for(var R=this.grammar.byName[l]||[],c=0;c<R.length;c++){var A=R[c],S=this.wants[l],d=new n(A,0,this.index,S);this.states.push(d)}},r.prototype.complete=function(l,R){var c=l.nextState(R);this.states.push(c)};function o(l,R){this.rules=l,this.start=R||this.rules[0].name;var c=this.byName={};this.rules.forEach(function(A){c.hasOwnProperty(A.name)||(c[A.name]=[]),c[A.name].push(A)})}o.fromCompiled=function(A,R){var c=A.Lexer;A.ParserStart&&(R=A.ParserStart,A=A.ParserRules);var A=A.map(function(d){return new t(d.name,d.symbols,d.postprocess)}),S=new o(A,R);return S.lexer=c,S};function s(){this.reset("")}s.prototype.reset=function(l,R){this.buffer=l,this.index=0,this.line=R?R.line:1,this.lastLineBreak=R?-R.col:0},s.prototype.next=function(){if(this.index<this.buffer.length){var l=this.buffer[this.index++];return l===`
449
- `&&(this.line+=1,this.lastLineBreak=this.index),{value:l}}},s.prototype.save=function(){return{line:this.line,col:this.index-this.lastLineBreak}},s.prototype.formatError=function(l,R){var c=this.buffer;if(typeof c=="string"){var A=c.split(`
450
- `).slice(Math.max(0,this.line-5),this.line),S=c.indexOf(`
451
- `,this.index);S===-1&&(S=c.length);var d=this.index-this.lastLineBreak,I=String(this.line).length;return R+=" at line "+this.line+" col "+d+`:
452
-
453
- `,R+=A.map(function(u,f){return O(this.line-A.length+f+1,I)+" "+u},this).join(`
454
- `),R+=`
455
- `+O("",I+d)+`^
456
- `,R}else return R+" at index "+(this.index-1);function O(u,f){var N=String(u);return Array(f-N.length+1).join(" ")+N}};function i(l,R,c){if(l instanceof o)var A=l,c=R;else var A=o.fromCompiled(l,R);this.grammar=A,this.options={keepHistory:!1,lexer:A.lexer||new s};for(var S in c||{})this.options[S]=c[S];this.lexer=this.options.lexer,this.lexerState=void 0;var d=new r(A,0);this.table=[d],d.wants[A.start]=[],d.predict(A.start),d.process(),this.current=0}i.fail={},i.prototype.feed=function(l){var R=this.lexer;R.reset(l,this.lexerState);for(var c;;){try{if(c=R.next(),!c)break}catch(D){var I=new r(this.grammar,this.current+1);this.table.push(I);var A=new Error(this.reportLexerError(D));throw A.offset=this.current,A.token=D.token,A}var S=this.table[this.current];this.options.keepHistory||delete this.table[this.current-1];var d=this.current+1,I=new r(this.grammar,d);this.table.push(I);for(var O=c.text!==void 0?c.text:c.value,u=R.constructor===s?c.value:c,f=S.scannable,N=f.length;N--;){var L=f[N],m=L.rule.symbols[L.dot];if(m.test?m.test(u):m.type?m.type===c.type:m.literal===O){var p=L.nextState({data:u,token:c,isToken:!0,reference:d-1});I.states.push(p)}}if(I.process(),I.states.length===0){var A=new Error(this.reportError(c));throw A.offset=this.current,A.token=c,A}this.options.keepHistory&&(S.lexerState=R.save()),this.current++}return S&&(this.lexerState=R.save()),this.results=this.finish(),this},i.prototype.reportLexerError=function(l){var R,c,A=l.token;return A?(R="input "+JSON.stringify(A.text[0])+" (lexer error)",c=this.lexer.formatError(A,"Syntax error")):(R="input (lexer error)",c=l.message),this.reportErrorCommon(c,R)},i.prototype.reportError=function(l){var R=(l.type?l.type+" token: ":"")+JSON.stringify(l.value!==void 0?l.value:l),c=this.lexer.formatError(l,"Syntax error");return this.reportErrorCommon(c,R)},i.prototype.reportErrorCommon=function(l,R){var c=[];c.push(l);var A=this.table.length-2,S=this.table[A],d=S.states.filter(function(O){var u=O.rule.symbols[O.dot];return u&&typeof u!="string"});if(d.length===0)c.push("Unexpected "+R+`. I did not expect any more input. Here is the state of my parse table:
457
- `),this.displayStateStack(S.states,c);else{c.push("Unexpected "+R+`. Instead, I was expecting to see one of the following:
458
- `);var I=d.map(function(O){return this.buildFirstStateStack(O,[])||[O]},this);I.forEach(function(O){var u=O[0],f=u.rule.symbols[u.dot],N=this.getSymbolDisplay(f);c.push("A "+N+" based on:"),this.displayStateStack(O,c)},this)}return c.push(""),c.join(`
459
- `)},i.prototype.displayStateStack=function(l,R){for(var c,A=0,S=0;S<l.length;S++){var d=l[S],I=d.rule.toString(d.dot);I===c?A++:(A>0&&R.push(" ^ "+A+" more lines identical to this"),A=0,R.push(" "+I)),c=I}},i.prototype.getSymbolDisplay=function(l){return a(l)},i.prototype.buildFirstStateStack=function(l,R){if(R.indexOf(l)!==-1)return null;if(l.wantedBy.length===0)return[l];var c=l.wantedBy[0],A=[l].concat(R),S=this.buildFirstStateStack(c,A);return S===null?null:[l].concat(S)},i.prototype.save=function(){var l=this.table[this.current];return l.lexerState=this.lexerState,l},i.prototype.restore=function(l){var R=l.index;this.current=R,this.table[R]=l,this.table.splice(R+1),this.lexerState=l.lexerState,this.results=this.finish()},i.prototype.rewind=function(l){if(!this.options.keepHistory)throw new Error("set option `keepHistory` to enable rewinding");this.restore(this.table[l])},i.prototype.finish=function(){var l=[],R=this.grammar.start,c=this.table[this.table.length-1];return c.states.forEach(function(A){A.rule.name===R&&A.dot===A.rule.symbols.length&&A.reference===0&&A.data!==i.fail&&l.push(A)}),l.map(function(A){return A.data})};function a(l){var R=typeof l;if(R==="string")return l;if(R==="object"){if(l.literal)return JSON.stringify(l.literal);if(l instanceof RegExp)return"character matching "+l;if(l.type)return l.type+" token";if(l.test)return"token matching "+String(l.test);throw new Error("Unknown symbol type: "+l)}}function T(l){var R=typeof l;if(R==="string")return l;if(R==="object"){if(l.literal)return JSON.stringify(l.literal);if(l instanceof RegExp)return l.toString();if(l.type)return"%"+l.type;if(l.test)return"<"+String(l.test)+">";throw new Error("Unknown symbol type: "+l)}}return{Parser:i,Grammar:o,Rule:t}})})(Kn)),Kn.exports}var zO=JO();const qO=ss(zO);function ZO(e){return e.map(QO).map(ef).map(tf).map(nf).map(rf)}const QO=(e,t,n)=>{if(xa(e.type)){const r=of(n,t);if(r&&r.type===w.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:w.IDENTIFIER,text:e.raw});const o=Ft(n,t);if(o&&o.type===w.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:w.IDENTIFIER,text:e.raw})}return e},ef=(e,t,n)=>{if(e.type===w.RESERVED_FUNCTION_NAME){const r=Ft(n,t);if(!r||!Ha(r))return Object.assign(Object.assign({},e),{type:w.IDENTIFIER,text:e.raw})}return e},tf=(e,t,n)=>{if(e.type===w.RESERVED_DATA_TYPE){const r=Ft(n,t);if(r&&Ha(r))return Object.assign(Object.assign({},e),{type:w.RESERVED_PARAMETERIZED_DATA_TYPE})}return e},nf=(e,t,n)=>{if(e.type===w.IDENTIFIER){const r=Ft(n,t);if(r&&Fa(r))return Object.assign(Object.assign({},e),{type:w.ARRAY_IDENTIFIER})}return e},rf=(e,t,n)=>{if(e.type===w.RESERVED_DATA_TYPE){const r=Ft(n,t);if(r&&Fa(r))return Object.assign(Object.assign({},e),{type:w.ARRAY_KEYWORD})}return e},of=(e,t)=>Ft(e,t,-1),Ft=(e,t,n=1)=>{let r=1;for(;e[t+r*n]&&sf(e[t+r*n]);)r++;return e[t+r*n]},Ha=e=>e.type===w.OPEN_PAREN&&e.text==="(",Fa=e=>e.type===w.OPEN_PAREN&&e.text==="[",sf=e=>e.type===w.BLOCK_COMMENT||e.type===w.LINE_COMMENT;class wa{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}=va(this.input,t.start);return`Parse error at token: ${t.text} at line ${n} column ${r}`}has(t){return t in w}}var J;(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"})(J=J||(J={}));function Ao(e){return e[0]}const ne=new wa(e=>[]),Et=([[e]])=>e,de=e=>({type:J.keyword,tokenType:e.type,text:e.text,raw:e.raw}),Hi=e=>({type:J.data_type,text:e.text,raw:e.raw}),Ie=(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),Ef=(e,{leading:t,trailing:n})=>{if(t!=null&&t.length){const[r,...o]=e;e=[Ie(r,{leading:t}),...o]}if(n!=null&&n.length){const r=e.slice(0,-1),o=e[e.length-1];e=[...r,Ie(o,{trailing:n})]}return e},af={Lexer:ne,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:[ne.has("DELIMITER")?{type:"DELIMITER"}:DELIMITER]},{name:"statement$subexpression$1",symbols:[ne.has("EOF")?{type:"EOF"}:EOF]},{name:"statement",symbols:["expressions_or_clauses","statement$subexpression$1"],postprocess:([e,[t]])=>({type:J.statement,children:e,hasSemicolon:t.type===w.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:Et},{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:[ne.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:Ao},{name:"limit_clause$ebnf$1",symbols:[],postprocess:()=>null},{name:"limit_clause",symbols:[ne.has("LIMIT")?{type:"LIMIT"}:LIMIT,"_","expression_chain_","limit_clause$ebnf$1"],postprocess:([e,t,n,r])=>{if(r){const[o,s]=r;return{type:J.limit_clause,limitKw:Ie(de(e),{trailing:t}),offset:n,count:s}}else return{type:J.limit_clause,limitKw:Ie(de(e),{trailing:t}),count:n}}},{name:"select_clause$subexpression$1$ebnf$1",symbols:[]},{name:"select_clause$subexpression$1$ebnf$1",symbols:["select_clause$subexpression$1$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"select_clause$subexpression$1",symbols:["all_columns_asterisk","select_clause$subexpression$1$ebnf$1"]},{name:"select_clause$subexpression$1$ebnf$2",symbols:[]},{name:"select_clause$subexpression$1$ebnf$2",symbols:["select_clause$subexpression$1$ebnf$2","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"select_clause$subexpression$1",symbols:["asteriskless_free_form_sql","select_clause$subexpression$1$ebnf$2"]},{name:"select_clause",symbols:[ne.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT,"select_clause$subexpression$1"],postprocess:([e,[t,n]])=>({type:J.clause,nameKw:de(e),children:[t,...n]})},{name:"select_clause",symbols:[ne.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT],postprocess:([e])=>({type:J.clause,nameKw:de(e),children:[]})},{name:"all_columns_asterisk",symbols:[ne.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK],postprocess:()=>({type:J.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:[ne.has("RESERVED_CLAUSE")?{type:"RESERVED_CLAUSE"}:RESERVED_CLAUSE,"other_clause$ebnf$1"],postprocess:([e,t])=>({type:J.clause,nameKw:de(e),children:t})},{name:"set_operation$ebnf$1",symbols:[]},{name:"set_operation$ebnf$1",symbols:["set_operation$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"set_operation",symbols:[ne.has("RESERVED_SET_OPERATION")?{type:"RESERVED_SET_OPERATION"}:RESERVED_SET_OPERATION,"set_operation$ebnf$1"],postprocess:([e,t])=>({type:J.set_operation,nameKw:de(e),children:t})},{name:"expression_chain_$ebnf$1",symbols:["expression_with_comments_"]},{name:"expression_chain_$ebnf$1",symbols:["expression_chain_$ebnf$1","expression_with_comments_"],postprocess:e=>e[0].concat([e[1]])},{name:"expression_chain_",symbols:["expression_chain_$ebnf$1"],postprocess:Ao},{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])=>Ie(e,{trailing:t})},{name:"_expression_with_comments",symbols:["_","expression"],postprocess:([e,t])=>Ie(t,{leading:e})},{name:"_andless_expression_with_comments",symbols:["_","andless_expression"],postprocess:([e,t])=>Ie(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:Et},{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:Et},{name:"expression$subexpression$1",symbols:["andless_expression"]},{name:"expression$subexpression$1",symbols:["logic_operator"]},{name:"expression",symbols:["expression$subexpression$1"],postprocess:Et},{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:Et},{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:Et},{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:Et},{name:"array_subscript",symbols:[ne.has("ARRAY_IDENTIFIER")?{type:"ARRAY_IDENTIFIER"}:ARRAY_IDENTIFIER,"_","square_brackets"],postprocess:([e,t,n])=>({type:J.array_subscript,array:Ie({type:J.identifier,quoted:!1,text:e.text},{trailing:t}),parenthesis:n})},{name:"array_subscript",symbols:[ne.has("ARRAY_KEYWORD")?{type:"ARRAY_KEYWORD"}:ARRAY_KEYWORD,"_","square_brackets"],postprocess:([e,t,n])=>({type:J.array_subscript,array:Ie(de(e),{trailing:t}),parenthesis:n})},{name:"function_call",symbols:[ne.has("RESERVED_FUNCTION_NAME")?{type:"RESERVED_FUNCTION_NAME"}:RESERVED_FUNCTION_NAME,"_","parenthesis"],postprocess:([e,t,n])=>({type:J.function_call,nameKw:Ie(de(e),{trailing:t}),parenthesis:n})},{name:"parenthesis",symbols:[{literal:"("},"expressions_or_clauses",{literal:")"}],postprocess:([e,t,n])=>({type:J.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:J.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:J.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","_",ne.has("PROPERTY_ACCESS_OPERATOR")?{type:"PROPERTY_ACCESS_OPERATOR"}:PROPERTY_ACCESS_OPERATOR,"_","property_access$subexpression$1"],postprocess:([e,t,n,r,[o]])=>({type:J.property_access,object:Ie(e,{trailing:t}),operator:n.text,property:Ie(o,{leading:r})})},{name:"between_predicate",symbols:[ne.has("BETWEEN")?{type:"BETWEEN"}:BETWEEN,"_","andless_expression_chain","_",ne.has("AND")?{type:"AND"}:AND,"_","andless_expression"],postprocess:([e,t,n,r,o,s,i])=>({type:J.between_predicate,betweenKw:de(e),expr1:Ef(n,{leading:t,trailing:r}),andKw:de(o),expr2:[Ie(i,{leading:s})]})},{name:"case_expression$ebnf$1",symbols:["expression_chain_"],postprocess:Ao},{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:[ne.has("CASE")?{type:"CASE"}:CASE,"_","case_expression$ebnf$1","case_expression$ebnf$2",ne.has("END")?{type:"END"}:END],postprocess:([e,t,n,r,o])=>({type:J.case_expression,caseKw:Ie(de(e),{trailing:t}),endKw:de(o),expr:n||[],clauses:r})},{name:"case_clause",symbols:[ne.has("WHEN")?{type:"WHEN"}:WHEN,"_","expression_chain_",ne.has("THEN")?{type:"THEN"}:THEN,"_","expression_chain_"],postprocess:([e,t,n,r,o,s])=>({type:J.case_when,whenKw:Ie(de(e),{trailing:t}),thenKw:Ie(de(r),{trailing:o}),condition:n,result:s})},{name:"case_clause",symbols:[ne.has("ELSE")?{type:"ELSE"}:ELSE,"_","expression_chain_"],postprocess:([e,t,n])=>({type:J.case_else,elseKw:Ie(de(e),{trailing:t}),result:n})},{name:"comma$subexpression$1",symbols:[ne.has("COMMA")?{type:"COMMA"}:COMMA]},{name:"comma",symbols:["comma$subexpression$1"],postprocess:([[e]])=>({type:J.comma})},{name:"asterisk$subexpression$1",symbols:[ne.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK]},{name:"asterisk",symbols:["asterisk$subexpression$1"],postprocess:([[e]])=>({type:J.operator,text:e.text})},{name:"operator$subexpression$1",symbols:[ne.has("OPERATOR")?{type:"OPERATOR"}:OPERATOR]},{name:"operator",symbols:["operator$subexpression$1"],postprocess:([[e]])=>({type:J.operator,text:e.text})},{name:"identifier$subexpression$1",symbols:[ne.has("IDENTIFIER")?{type:"IDENTIFIER"}:IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[ne.has("QUOTED_IDENTIFIER")?{type:"QUOTED_IDENTIFIER"}:QUOTED_IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[ne.has("VARIABLE")?{type:"VARIABLE"}:VARIABLE]},{name:"identifier",symbols:["identifier$subexpression$1"],postprocess:([[e]])=>({type:J.identifier,quoted:e.type!=="IDENTIFIER",text:e.text})},{name:"parameter$subexpression$1",symbols:[ne.has("NAMED_PARAMETER")?{type:"NAMED_PARAMETER"}:NAMED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[ne.has("QUOTED_PARAMETER")?{type:"QUOTED_PARAMETER"}:QUOTED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[ne.has("NUMBERED_PARAMETER")?{type:"NUMBERED_PARAMETER"}:NUMBERED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[ne.has("POSITIONAL_PARAMETER")?{type:"POSITIONAL_PARAMETER"}:POSITIONAL_PARAMETER]},{name:"parameter$subexpression$1",symbols:[ne.has("CUSTOM_PARAMETER")?{type:"CUSTOM_PARAMETER"}:CUSTOM_PARAMETER]},{name:"parameter",symbols:["parameter$subexpression$1"],postprocess:([[e]])=>({type:J.parameter,key:e.key,text:e.text})},{name:"literal$subexpression$1",symbols:[ne.has("NUMBER")?{type:"NUMBER"}:NUMBER]},{name:"literal$subexpression$1",symbols:[ne.has("STRING")?{type:"STRING"}:STRING]},{name:"literal",symbols:["literal$subexpression$1"],postprocess:([[e]])=>({type:J.literal,text:e.text})},{name:"keyword$subexpression$1",symbols:[ne.has("RESERVED_KEYWORD")?{type:"RESERVED_KEYWORD"}:RESERVED_KEYWORD]},{name:"keyword$subexpression$1",symbols:[ne.has("RESERVED_KEYWORD_PHRASE")?{type:"RESERVED_KEYWORD_PHRASE"}:RESERVED_KEYWORD_PHRASE]},{name:"keyword$subexpression$1",symbols:[ne.has("RESERVED_JOIN")?{type:"RESERVED_JOIN"}:RESERVED_JOIN]},{name:"keyword",symbols:["keyword$subexpression$1"],postprocess:([[e]])=>de(e)},{name:"data_type$subexpression$1",symbols:[ne.has("RESERVED_DATA_TYPE")?{type:"RESERVED_DATA_TYPE"}:RESERVED_DATA_TYPE]},{name:"data_type$subexpression$1",symbols:[ne.has("RESERVED_DATA_TYPE_PHRASE")?{type:"RESERVED_DATA_TYPE_PHRASE"}:RESERVED_DATA_TYPE_PHRASE]},{name:"data_type",symbols:["data_type$subexpression$1"],postprocess:([[e]])=>Hi(e)},{name:"data_type",symbols:[ne.has("RESERVED_PARAMETERIZED_DATA_TYPE")?{type:"RESERVED_PARAMETERIZED_DATA_TYPE"}:RESERVED_PARAMETERIZED_DATA_TYPE,"_","parenthesis"],postprocess:([e,t,n])=>({type:J.parameterized_data_type,dataType:Ie(Hi(e),{trailing:t}),parenthesis:n})},{name:"logic_operator$subexpression$1",symbols:[ne.has("AND")?{type:"AND"}:AND]},{name:"logic_operator$subexpression$1",symbols:[ne.has("OR")?{type:"OR"}:OR]},{name:"logic_operator$subexpression$1",symbols:[ne.has("XOR")?{type:"XOR"}:XOR]},{name:"logic_operator",symbols:["logic_operator$subexpression$1"],postprocess:([[e]])=>de(e)},{name:"other_keyword$subexpression$1",symbols:[ne.has("WHEN")?{type:"WHEN"}:WHEN]},{name:"other_keyword$subexpression$1",symbols:[ne.has("THEN")?{type:"THEN"}:THEN]},{name:"other_keyword$subexpression$1",symbols:[ne.has("ELSE")?{type:"ELSE"}:ELSE]},{name:"other_keyword$subexpression$1",symbols:[ne.has("END")?{type:"END"}:END]},{name:"other_keyword",symbols:["other_keyword$subexpression$1"],postprocess:([[e]])=>de(e)},{name:"_$ebnf$1",symbols:[]},{name:"_$ebnf$1",symbols:["_$ebnf$1","comment"],postprocess:e=>e[0].concat([e[1]])},{name:"_",symbols:["_$ebnf$1"],postprocess:([e])=>e},{name:"comment",symbols:[ne.has("LINE_COMMENT")?{type:"LINE_COMMENT"}:LINE_COMMENT],postprocess:([e])=>({type:J.line_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[ne.has("BLOCK_COMMENT")?{type:"BLOCK_COMMENT"}:BLOCK_COMMENT],postprocess:([e])=>({type:J.block_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[ne.has("DISABLE_COMMENT")?{type:"DISABLE_COMMENT"}:DISABLE_COMMENT],postprocess:([e])=>({type:J.disable_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})}],ParserStart:"main"},{Parser:lf,Grammar:Tf}=qO;function cf(e){let t={};const n=new wa(o=>[...ZO(e.tokenize(o,t)),ya(o.length)]),r=new lf(Tf.fromCompiled(af),{lexer:n});return{parse:(o,s)=>{t=s;const{results:i}=r.feed(o);if(i.length===1)return i[0];throw i.length===0?new Error("Parse error: Invalid SQL"):new Error(`Parse error: Ambiguous grammar
460
- ${JSON.stringify(i,void 0,2)}`)}}}var H;(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"})(H=H||(H={}));class Ya{constructor(t){this.indentation=t,this.items=[]}add(...t){for(const n of t)switch(n){case H.SPACE:this.items.push(H.SPACE);break;case H.NO_SPACE:this.trimHorizontalWhitespace();break;case H.NO_NEWLINE:this.trimWhitespace();break;case H.NEWLINE:this.trimHorizontalWhitespace(),this.addNewline(H.NEWLINE);break;case H.MANDATORY_NEWLINE:this.trimHorizontalWhitespace(),this.addNewline(H.MANDATORY_NEWLINE);break;case H.INDENT:this.addIndentation();break;case H.SINGLE_INDENT:this.items.push(H.SINGLE_INDENT);break;default:this.items.push(n)}}trimHorizontalWhitespace(){for(;Rf(tn(this.items));)this.items.pop()}trimWhitespace(){for(;Af(tn(this.items));)this.items.pop()}addNewline(t){if(this.items.length>0)switch(tn(this.items)){case H.NEWLINE:this.items.pop(),this.items.push(t);break;case H.MANDATORY_NEWLINE:break;default:this.items.push(t);break}}addIndentation(){for(let t=0;t<this.indentation.getLevel();t++)this.items.push(H.SINGLE_INDENT)}toString(){return this.items.map(t=>this.itemToString(t)).join("")}getLayoutItems(){return this.items}itemToString(t){switch(t){case H.SPACE:return" ";case H.NEWLINE:case H.MANDATORY_NEWLINE:return`
461
- `;case H.SINGLE_INDENT:return this.indentation.getSingleIndent();default:return t}}}const Rf=e=>e===H.SPACE||e===H.SINGLE_INDENT,Af=e=>e===H.SPACE||e===H.SINGLE_INDENT||e===H.NEWLINE;function Fi(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 wi(e){return Hd(e)||e===w.RESERVED_CLAUSE||e===w.RESERVED_SELECT||e===w.RESERVED_SET_OPERATION||e===w.RESERVED_JOIN||e===w.LIMIT}const So="top-level",Sf="block-level";class Va{constructor(t){this.indent=t,this.indentTypes=[]}getSingleIndent(){return this.indent}getLevel(){return this.indentTypes.length}increaseTopLevel(){this.indentTypes.push(So)}increaseBlockLevel(){this.indentTypes.push(Sf)}decreaseTopLevel(){this.indentTypes.length>0&&tn(this.indentTypes)===So&&this.indentTypes.pop()}decreaseBlockLevel(){for(;this.indentTypes.length>0&&this.indentTypes.pop()===So;);}}class df extends Ya{constructor(t){super(new Va("")),this.expressionWidth=t,this.length=0,this.trailingSpace=!1}add(...t){if(t.forEach(n=>this.addToLength(n)),this.length>this.expressionWidth)throw new Wo;super.add(...t)}addToLength(t){if(typeof t=="string")this.length+=t.length,this.trailingSpace=!1;else{if(t===H.MANDATORY_NEWLINE||t===H.NEWLINE)throw new Wo;t===H.INDENT||t===H.SINGLE_INDENT||t===H.SPACE?this.trailingSpace||(this.length++,this.trailingSpace=!0):(t===H.NO_NEWLINE||t===H.NO_SPACE)&&this.trailingSpace&&(this.trailingSpace=!1,this.length--)}}}class Wo extends Error{}class Er{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 J.function_call:return this.formatFunctionCall(t);case J.parameterized_data_type:return this.formatParameterizedDataType(t);case J.array_subscript:return this.formatArraySubscript(t);case J.property_access:return this.formatPropertyAccess(t);case J.parenthesis:return this.formatParenthesis(t);case J.between_predicate:return this.formatBetweenPredicate(t);case J.case_expression:return this.formatCaseExpression(t);case J.case_when:return this.formatCaseWhen(t);case J.case_else:return this.formatCaseElse(t);case J.clause:return this.formatClause(t);case J.set_operation:return this.formatSetOperation(t);case J.limit_clause:return this.formatLimitClause(t);case J.all_columns_asterisk:return this.formatAllColumnsAsterisk(t);case J.literal:return this.formatLiteral(t);case J.identifier:return this.formatIdentifier(t);case J.parameter:return this.formatParameter(t);case J.operator:return this.formatOperator(t);case J.comma:return this.formatComma(t);case J.line_comment:return this.formatLineComment(t);case J.block_comment:return this.formatBlockComment(t);case J.disable_comment:return this.formatBlockComment(t);case J.data_type:return this.formatDataType(t);case J.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 J.data_type:n=this.showDataType(t.array);break;case J.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(H.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(H.NO_SPACE,t.closeParen,H.SPACE)):(this.layout.add(t.openParen,H.NEWLINE),Ct(this.cfg)?(this.layout.add(H.INDENT),this.layout=this.formatSubExpression(t.children)):(this.layout.indentation.increaseBlockLevel(),this.layout.add(H.INDENT),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseBlockLevel()),this.layout.add(H.NEWLINE,H.INDENT,t.closeParen,H.SPACE))}formatBetweenPredicate(t){this.layout.add(this.showKw(t.betweenKw),H.SPACE),this.layout=this.formatSubExpression(t.expr1),this.layout.add(H.NO_SPACE,H.SPACE,this.showNonTabularKw(t.andKw),H.SPACE),this.layout=this.formatSubExpression(t.expr2),this.layout.add(H.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(H.NEWLINE,H.INDENT),this.formatNode(t.endKw)}formatCaseWhen(t){this.layout.add(H.NEWLINE,H.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(H.NEWLINE,H.INDENT),this.formatNode(t.elseKw),this.layout=this.formatSubExpression(t.result)}formatClause(t){this.isOnelineClause(t)?this.formatClauseInOnelineStyle(t):Ct(this.cfg)?this.formatClauseInTabularStyle(t):this.formatClauseInIndentedStyle(t)}isOnelineClause(t){return Ct(this.cfg)?this.dialectCfg.tabularOnelineClauses[t.nameKw.text]:this.dialectCfg.onelineClauses[t.nameKw.text]}formatClauseInIndentedStyle(t){this.layout.add(H.NEWLINE,H.INDENT,this.showKw(t.nameKw),H.NEWLINE),this.layout.indentation.increaseTopLevel(),this.layout.add(H.INDENT),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseTopLevel()}formatClauseInOnelineStyle(t){this.layout.add(H.NEWLINE,H.INDENT,this.showKw(t.nameKw),H.SPACE),this.layout=this.formatSubExpression(t.children)}formatClauseInTabularStyle(t){this.layout.add(H.NEWLINE,H.INDENT,this.showKw(t.nameKw),H.SPACE),this.layout.indentation.increaseTopLevel(),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseTopLevel()}formatSetOperation(t){this.layout.add(H.NEWLINE,H.INDENT,this.showKw(t.nameKw),H.NEWLINE),this.layout.add(H.INDENT),this.layout=this.formatSubExpression(t.children)}formatLimitClause(t){this.withComments(t.limitKw,()=>{this.layout.add(H.NEWLINE,H.INDENT,this.showKw(t.limitKw))}),this.layout.indentation.increaseTopLevel(),Ct(this.cfg)?this.layout.add(H.SPACE):this.layout.add(H.NEWLINE,H.INDENT),t.offset?(this.layout=this.formatSubExpression(t.offset),this.layout.add(H.NO_SPACE,",",H.SPACE),this.layout=this.formatSubExpression(t.count)):this.layout=this.formatSubExpression(t.count),this.layout.indentation.decreaseTopLevel()}formatAllColumnsAsterisk(t){this.layout.add("*",H.SPACE)}formatLiteral(t){this.layout.add(t.text,H.SPACE)}formatIdentifier(t){this.layout.add(this.showIdentifier(t),H.SPACE)}formatParameter(t){this.layout.add(this.params.get(t),H.SPACE)}formatOperator({text:t}){this.cfg.denseOperators||this.dialectCfg.alwaysDenseOperators.includes(t)?this.layout.add(H.NO_SPACE,t):t===":"?this.layout.add(H.NO_SPACE,t,H.SPACE):this.layout.add(t,H.SPACE)}formatComma(t){this.inline?this.layout.add(H.NO_SPACE,",",H.SPACE):this.layout.add(H.NO_SPACE,",",H.NEWLINE,H.INDENT)}withComments(t,n){this.formatComments(t.leadingComments),n(),this.formatComments(t.trailingComments)}formatComments(t){t&&t.forEach(n=>{n.type===J.line_comment?this.formatLineComment(n):this.formatBlockComment(n)})}formatLineComment(t){co(t.precedingWhitespace||"")?this.layout.add(H.NEWLINE,H.INDENT,t.text,H.MANDATORY_NEWLINE,H.INDENT):this.layout.getLayoutItems().length>0?this.layout.add(H.NO_NEWLINE,H.SPACE,t.text,H.MANDATORY_NEWLINE,H.INDENT):this.layout.add(t.text,H.MANDATORY_NEWLINE,H.INDENT)}formatBlockComment(t){t.type===J.block_comment&&this.isMultilineBlockComment(t)?(this.splitBlockComment(t.text).forEach(n=>{this.layout.add(H.NEWLINE,H.INDENT,n)}),this.layout.add(H.NEWLINE,H.INDENT)):this.layout.add(t.text,H.SPACE)}isMultilineBlockComment(t){return co(t.text)||co(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(tn(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 Er({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 Er({cfg:this.cfg,dialectCfg:this.dialectCfg,params:this.params,layout:new df(this.cfg.expressionWidth),inline:!0}).format(t)}catch(r){if(r instanceof Wo){this.params.setPositionalParameterIndex(n);return}else throw r}}formatKeywordNode(t){switch(t.tokenType){case w.RESERVED_JOIN:return this.formatJoin(t);case w.AND:case w.OR:case w.XOR:return this.formatLogicalOperator(t);default:return this.formatKeyword(t)}}formatJoin(t){Ct(this.cfg)?(this.layout.indentation.decreaseTopLevel(),this.layout.add(H.NEWLINE,H.INDENT,this.showKw(t),H.SPACE),this.layout.indentation.increaseTopLevel()):this.layout.add(H.NEWLINE,H.INDENT,this.showKw(t),H.SPACE)}formatKeyword(t){this.layout.add(this.showKw(t),H.SPACE)}formatLogicalOperator(t){this.cfg.logicalOperatorNewline==="before"?Ct(this.cfg)?(this.layout.indentation.decreaseTopLevel(),this.layout.add(H.NEWLINE,H.INDENT,this.showKw(t),H.SPACE),this.layout.indentation.increaseTopLevel()):this.layout.add(H.NEWLINE,H.INDENT,this.showKw(t),H.SPACE):this.layout.add(this.showKw(t),H.NEWLINE,H.INDENT)}formatDataType(t){this.layout.add(this.showDataType(t),H.SPACE)}showKw(t){return wi(t.tokenType)?Fi(this.showNonTabularKw(t),this.cfg.indentStyle):this.showNonTabularKw(t)}showNonTabularKw(t){switch(this.cfg.keywordCase){case"preserve":return $n(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}showFunctionKw(t){return wi(t.tokenType)?Fi(this.showNonTabularFunctionKw(t),this.cfg.indentStyle):this.showNonTabularFunctionKw(t)}showNonTabularFunctionKw(t){switch(this.cfg.functionCase){case"preserve":return $n(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 $n(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}}class If{constructor(t,n){this.dialect=t,this.cfg=n,this.params=new $O(this.cfg.params)}format(t){const n=this.parse(t);return this.formatAst(n).trimEnd()}parse(t){return cf(this.dialect.tokenizer).parse(t,this.cfg.paramTypes||{})}formatAst(t){return t.map(n=>this.formatStatement(n)).join(`
462
- `.repeat(this.cfg.linesBetweenQueries+1))}formatStatement(t){const n=new Er({cfg:this.cfg,dialectCfg:this.dialect.formatOptions,params:this.params,layout:new Ya(new Va(jO(this.cfg)))}).format(t.children);return t.hasSemicolon&&(this.cfg.newlineBeforeSemicolon?n.add(H.NEWLINE,";"):n.add(H.NO_NEWLINE,";")),n.toString()}}class Jn extends Error{}function uf(e){const t=["multilineLists","newlineBeforeOpenParen","newlineBeforeCloseParen","aliasAs","commaPosition","tabulateAlias"];for(const n of t)if(n in e)throw new Jn(`${n} config is no more supported.`);if(e.expressionWidth<=0)throw new Jn(`expressionWidth config must be positive number. Received ${e.expressionWidth} instead.`);if(e.params&&!Nf(e.params)&&console.warn('WARNING: All "params" option values should be strings.'),e.paramTypes&&!Of(e.paramTypes))throw new Jn("Empty regex given in custom paramTypes. That would result in matching infinite amount of parameters.");return e}function Nf(e){return(e instanceof Array?e:Object.values(e)).every(n=>typeof n=="string")}function Of(e){return e.custom&&Array.isArray(e.custom)?e.custom.every(t=>t.regex!==""):!0}var ff=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 Wa={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"},Cf=Object.keys(Wa),Lf={tabWidth:2,useTabs:!1,keywordCase:"preserve",identifierCase:"preserve",dataTypeCase:"preserve",functionCase:"preserve",indentStyle:"standard",logicalOperatorNewline:"before",expressionWidth:50,linesBetweenQueries:1,denseOperators:!1,newlineBeforeSemicolon:!1},hf=(e,t={})=>{if(typeof t.language=="string"&&!Cf.includes(t.language))throw new Jn(`Unsupported SQL dialect: ${t.language}`);const n=Wa[t.language||"sql"];return _f(e,Object.assign(Object.assign({},t),{dialect:PO[n]}))},_f=(e,t)=>{var{dialect:n}=t,r=ff(t,["dialect"]);if(typeof e!="string")throw new Error("Invalid query argument. Expected string, instead got "+typeof e);const o=uf(Object.assign(Object.assign({},Lf),r));return new If(WO(n),o).format(e)},pf={sql:"SQL",markdown:"MD",dql:"DQL",param:"PARAM"},Io={sql:"#388bfd",markdown:"#56d364",dql:"#e3b341",param:"#e3b341"};function mf(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 Df({cell:e,t}){let n="",r=t.textMuted;return e.status==="running"?(n="[*]",r=t.cellBorderRunning):e.status==="error"?(n="[!]",r=t.error):e.executionCount!==void 0?(n=`[${e.executionCount}]`,r=t.textMuted):(n="[ ]",r=t.textMuted),E.jsx("div",{style:{width:40,display:"flex",alignItems:"flex-start",justifyContent:"center",paddingTop:12,flexShrink:0},children:E.jsx("span",{style:{fontFamily:t.fontMono,fontSize:11,color:r,lineHeight:1.4,userSelect:"none",transition:"color 0.2s"},children:n})})}function gf(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 uo(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 Pf(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 Mf({content:e,onChange:t,t:n}){const r=gf(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},i={display:"flex",alignItems:"center",gap:4};return E.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 12px",padding:"5px 10px",borderBottom:`1px solid ${n.cellBorder}`,background:`${n.tableHeaderBg}40`},children:[E.jsxs("div",{style:i,children:[E.jsx("span",{style:s,children:"domain"}),E.jsx("input",{style:{...o,width:80},value:r.domain,placeholder:"e.g. finance",onChange:a=>t(uo(e,"domain",a.target.value))})]}),E.jsxs("div",{style:i,children:[E.jsx("span",{style:s,children:"owner"}),E.jsx("input",{style:{...o,width:90},value:r.owner,placeholder:"e.g. data-team",onChange:a=>t(uo(e,"owner",a.target.value))})]}),E.jsxs("div",{style:i,children:[E.jsx("span",{style:s,children:"tags"}),E.jsx("input",{style:{...o,width:110},value:r.tags.join(", "),placeholder:"revenue, kpi",onChange:a=>{const T=a.target.value.split(",").map(l=>l.trim()).filter(Boolean);t(Pf(e,T))}})]}),E.jsxs("div",{style:{...i,flex:1},children:[E.jsx("span",{style:s,children:"description"}),E.jsx("input",{style:{...o,flex:1,minWidth:120},value:r.description,placeholder:"What this block measures",onChange:a=>t(uo(e,"description",a.target.value))})]})]})}function yf({cell:e,index:t}){const{state:n,dispatch:r}=ae(),o=ie[n.themeMode],{executeCell:s,executeDependents:i}=as(),[a,T]=C.useState(!1),[l,R]=C.useState(!1),[c,A]=C.useState(e.name??""),[S,d]=C.useState(!0),[I,O]=C.useState("table"),u=mf(e,o),f=e.type!=="markdown"&&e.type!=="param",N=C.useMemo(()=>n.schemaTables.length>0?Object.fromEntries(n.schemaTables.map(h=>[h.name,h.columns.map(x=>x.name)])):void 0,[n.schemaTables]);if(e.type==="param")return E.jsxs("div",{onMouseEnter:()=>T(!0),onMouseLeave:()=>T(!1),style:{display:"flex",gap:0,marginBottom:2},children:[E.jsx("div",{style:{width:40,flexShrink:0}}),E.jsx("div",{style:{flex:1,minWidth:0},children:E.jsx(sd,{cell:e,themeMode:n.themeMode,onApplyParam:i})})]});C.useEffect(()=>{if(e.status==="success"&&e.result){const h=Vo(e.result,e.chartConfig);O(h!=="table"?"chart":"table")}},[e.status,e.result,e.chartConfig]);const L=C.useCallback(()=>{f&&s(e.id)},[e.id,s,f]),m=C.useCallback(h=>{r({type:"UPDATE_CELL",id:e.id,updates:{content:h}})},[e.id,r]),p=C.useCallback(()=>{if(e.content.trim())try{const h=hf(e.content,{language:"sql",tabWidth:2,keywordCase:"upper",linesBetweenQueries:1});r({type:"UPDATE_CELL",id:e.id,updates:{content:h}})}catch{}},[e.content,e.id,r]),D=C.useCallback(()=>{p(),setTimeout(()=>s(e.id),80)},[p,s,e.id]),M=()=>{r({type:"DELETE_CELL",id:e.id})},B=()=>{r({type:"MOVE_CELL",id:e.id,direction:"up"})},F=()=>{r({type:"MOVE_CELL",id:e.id,direction:"down"})},g=()=>{R(!1),r({type:"UPDATE_CELL",id:e.id,updates:{name:c.trim()||void 0}})},_=(e.result||e.error)&&e.type!=="markdown",U=e.result?Vo(e.result,e.chartConfig)!=="table":!1;return E.jsxs("div",{onMouseEnter:()=>T(!0),onMouseLeave:()=>T(!1),style:{display:"flex",gap:0,marginBottom:2},children:[E.jsx(Df,{cell:e,t:o}),E.jsxs("div",{style:{flex:1,minWidth:0,borderRadius:8,border:`1px solid ${a||e.status!=="idle"?u:o.cellBorder}`,borderLeft:`2px solid ${u}`,background:o.cellBg,overflow:"hidden",transition:"border-color 0.2s"},children:[E.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:[E.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:Io[e.type]??o.accent,background:`${Io[e.type]??o.accent}18`,border:`1px solid ${Io[e.type]??o.accent}40`,borderRadius:4,padding:"1px 6px",flexShrink:0,textTransform:"uppercase"},children:pf[e.type]}),a&&(e.type==="sql"||e.type==="dql")&&E.jsx(Ed,{themeMode:n.themeMode,cellType:e.type,onInsert:h=>m(h)}),a&&(e.type==="sql"||e.type==="dql")&&E.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:h=>{h.currentTarget.style.color=o.textSecondary,h.currentTarget.style.borderColor=o.accent},onMouseLeave:h=>{h.currentTarget.style.color=o.textMuted,h.currentTarget.style.borderColor=o.btnBorder},children:"Format"}),l?E.jsx("input",{autoFocus:!0,value:c,onChange:h=>A(h.target.value),onBlur:g,onKeyDown:h=>{h.key==="Enter"&&g(),h.key==="Escape"&&R(!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&&E.jsx("span",{onClick:()=>{A(e.name??""),R(!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}),E.jsx("div",{style:{flex:1}}),a&&E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[!e.name&&!l&&E.jsx(Kt,{title:"Name this cell",onClick:()=>{A(""),R(!0)},t:o,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M11.013 1.427a1.75 1.75 0 0 1 2.474 0l1.086 1.086a1.75 1.75 0 0 1 0 2.474l-8.61 8.61c-.21.21-.47.364-.756.445l-3.251.93a.75.75 0 0 1-.927-.928l.929-3.25c.081-.286.235-.547.445-.758l8.61-8.61Zm.176 4.823L9.75 4.81l-6.286 6.287a.253.253 0 0 0-.064.108l-.558 1.953 1.953-.558a.253.253 0 0 0 .108-.064Zm1.238-3.763a.25.25 0 0 0-.354 0L10.811 3.75l1.439 1.44 1.263-1.263a.25.25 0 0 0 0-.354Z"})})}),f&&E.jsx(Kt,{title:"Run cell (Shift+Enter)",onClick:L,t:o,accent:!0,children:E.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:E.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})})}),E.jsx(Kt,{title:"Move up",onClick:B,t:o,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.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"})})}),E.jsx(Kt,{title:"Move down",onClick:F,t:o,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.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"})})}),E.jsx(Kt,{title:"Delete cell",onClick:M,t:o,danger:!0,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.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"&&E.jsx(Mf,{content:e.content,onChange:m,t:o}),e.type==="markdown"?E.jsx(od,{value:e.content,onChange:m,themeMode:n.themeMode}):E.jsx(Pa,{value:e.content,onChange:m,onRun:L,themeMode:n.themeMode,schema:N}),_&&E.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`},children:[E.jsxs("div",{style:{height:28,display:"flex",alignItems:"center",padding:"0 12px",gap:10,borderBottom:e.result&&S?`1px solid ${o.cellBorder}`:"none",background:`${o.tableHeaderBg}60`},children:[e.result&&E.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&&E.jsxs(E.Fragment,{children:[" · ",e.result.executionTime<1e3?`${e.result.executionTime}ms`:`${(e.result.executionTime/1e3).toFixed(2)}s`]})]}),e.error&&E.jsx("span",{style:{fontSize:11,fontFamily:o.font,color:o.error},children:"Error"}),E.jsx("div",{style:{flex:1}}),e.result&&U&&S&&E.jsx("div",{style:{display:"flex",alignItems:"center",gap:3},children:["chart","table"].map(h=>E.jsx("button",{onClick:()=>O(h),style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${I===h?o.accent:o.btnBorder}`,background:I===h?`${o.accent}20`:"transparent",color:I===h?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s",textTransform:"capitalize"},children:h==="chart"?"Chart":"Table"},h))}),E.jsxs("button",{onClick:()=>d(h=>!h),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:[E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:S?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.15s"},children:E.jsx("path",{d:"M1 3l4 4 4-4",stroke:"currentColor",fill:"none",strokeWidth:"1.5"})}),S?"Hide":"Show"]})]}),S&&E.jsxs(E.Fragment,{children:[e.error&&E.jsx(hd,{message:e.error,themeMode:n.themeMode,onFix:f?D:void 0,schemaTables:n.schemaTables}),e.result&&!e.error&&(I==="chart"&&U?E.jsx(Od,{result:e.result,themeMode:n.themeMode,chartConfig:e.chartConfig}):E.jsx(Ma,{result:e.result,themeMode:n.themeMode}))]})]}),f&&E.jsx(Pd,{cellContent:e.content,cellType:e.type,cellName:e.name,themeMode:n.themeMode,t:o})]})]})}function Kt({title:e,onClick:t,children:n,t:r,accent:o,danger:s}){const[i,a]=C.useState(!1);return E.jsx("button",{title:e,onClick:t,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center",background:i?s?`${r.error}18`:o?`${r.accent}18`:r.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:i?s?r.error:o?r.accent:r.textSecondary:r.textMuted,transition:"all 0.15s",padding:0},children:n})}const xf=[{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 No({afterId:e}){const{state:t,dispatch:n}=ae(),r=ie[t.themeMode],[o,s]=C.useState(!1),[i,a]=C.useState(!1),[T,l]=C.useState(!1),[R,c]=C.useState(""),A=C.useRef(null),S=C.useRef(null);C.useEffect(()=>{if(!i)return;function f(N){A.current&&!A.current.contains(N.target)&&a(!1)}return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[i]);const d=f=>{const N=fe(f);n({type:"ADD_CELL",cell:N,afterId:e}),a(!1),l(!1)},I=t.files.filter(f=>f.type==="block"),O=R?I.filter(f=>f.name.toLowerCase().includes(R.toLowerCase())):I,u=f=>{const N=fe("sql",`-- Block: ${f.path}
463
- @include('${f.path}')`);n({type:"ADD_CELL",cell:N,afterId:e}),a(!1),l(!1),c("")};return E.jsxs("div",{ref:A,onMouseEnter:()=>s(!0),onMouseLeave:()=>{s(!1)},style:{position:"relative",height:28,display:"flex",alignItems:"center",justifyContent:"center",cursor:"default"},children:[E.jsx("div",{style:{position:"absolute",left:0,right:0,height:1,background:o||i?r.cellBorderActive:"transparent",transition:"background 0.15s"}}),(o||i)&&E.jsxs("button",{onClick:()=>a(f=>!f),style:{position:"relative",zIndex:2,height:22,padding:"0 10px",borderRadius:11,border:`1px solid ${r.cellBorderActive}`,background:`${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:[E.jsx("span",{style:{fontSize:14,lineHeight:1,marginTop:-1},children:"+"}),"Add cell"]}),i&&E.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:[E.jsxs("div",{style:{display:"flex",gap:4},children:[xf.map(({type:f,label:N,color:L})=>E.jsx(Yi,{label:N,color:L,onClick:()=>d(f),t:r},f)),E.jsx(Yi,{label:"Block",color:"#d2a8ff",onClick:()=>{l(f=>!f),setTimeout(()=>{var f;return(f=S.current)==null?void 0:f.focus()},50)},t:r})]}),T&&E.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"4px 2px"},children:[E.jsx("input",{ref:S,value:R,onChange:f=>c(f.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"}}),E.jsx("div",{style:{maxHeight:160,overflow:"auto",display:"flex",flexDirection:"column",gap:2},children:O.length===0?E.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,padding:"4px 8px",fontStyle:"italic"},children:I.length===0?"No blocks yet":"No matches"}):O.map(f=>E.jsx(Uf,{file:f,onClick:()=>u(f),t:r},f.path))})]})]})]})}function Yi({label:e,color:t,onClick:n,t:r}){const[o,s]=C.useState(!1);return E.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 Uf({file:e,onClick:t,t:n}){const[r,o]=C.useState(!1);return E.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:[E.jsx("span",{style:{fontWeight:500},children:e.name.replace(/\.dql$/,"")}),E.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.fontMono},children:e.path})]})}function bf({registerCellRef:e}){const{state:t,dispatch:n}=ae(),{executeCell:r}=as(),o=ie[t.themeMode],[s,i]=C.useState(null),a=C.useRef(0);return C.useCallback(T=>{i(T)},[]),C.useEffect(()=>{function T(l){var S;if(!s)return;const R=l.target;if(R.tagName==="TEXTAREA"||R.tagName==="INPUT"||R.isContentEditable||R.closest(".cm-editor")){i(null);return}const c=t.cells,A=c.findIndex(d=>d.id===s);if(A!==-1)switch(l.key){case"a":{l.preventDefault();const d=fe("sql");if(A===0)n({type:"ADD_CELL",cell:d,afterId:c[0].id}),n({type:"MOVE_CELL",id:d.id,direction:"up"});else{const I=c[A-1].id;n({type:"ADD_CELL",cell:d,afterId:I})}i(d.id);break}case"b":{l.preventDefault();const d=fe("sql");n({type:"ADD_CELL",cell:d,afterId:s}),i(d.id);break}case"d":{l.preventDefault();const d=Date.now();if(d-a.current<=500){if(n({type:"DELETE_CELL",id:s}),c.length>1){const I=A>0?A-1:1;i(((S=c[I])==null?void 0:S.id)??null)}else i(null);a.current=0}else a.current=d;break}case"Enter":{if(l.shiftKey){l.preventDefault();const d=c[A];d&&d.type!=="markdown"&&r(d.id)}break}}}return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[s,t.cells,n,r]),C.useEffect(()=>{function T(l){l.target.closest("[data-cell-id]")||i(null)}return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[]),t.cells.length===0?E.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[E.jsx(No,{}),E.jsx(Gf,{t:o})]}):E.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[E.jsx(No,{afterId:void 0}),t.cells.map((T,l)=>E.jsxs(on.Fragment,{children:[E.jsx("div",{ref:R=>e(T.id,R),"data-cell-id":T.id,onClick:R=>{const c=R.target;!c.closest(".cm-editor")&&!c.closest("textarea")&&!c.closest("input")&&i(T.id)},style:{outline:s===T.id?`2px solid ${o.accent}40`:"none",outlineOffset:2,borderRadius:10,transition:"outline 0.1s"},children:E.jsx(yf,{cell:T,index:l})}),E.jsx(No,{afterId:T.id})]},T.id))]})}function Gf({t:e}){return E.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"48px 0",gap:12,color:e.textMuted},children:[E.jsx("svg",{width:"40",height:"40",viewBox:"0 0 16 16",fill:"currentColor",style:{opacity:.3},children:E.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"})}),E.jsx("span",{style:{fontSize:13,fontFamily:e.font},children:"Empty notebook. Click + to add your first cell."})]})}function Bf({onOpenFile:e,registerCellRef:t}){const{state:n}=ae(),r=ie[n.themeMode];return n.activeFile?E.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",background:r.appBg},children:[E.jsx(vf,{t:r}),E.jsx("div",{style:{flex:1,overflow:"auto",padding:"24px 0 40px"},children:E.jsx(bf,{registerCellRef:t})})]}):E.jsx(gS,{onOpenFile:e})}function vf({t:e}){const{state:t}=ae(),n=t.cells.length;return E.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:[E.jsx(Hf,{t:e}),E.jsx("div",{style:{flex:1}}),E.jsxs("span",{style:{fontSize:11,color:e.textMuted,fontFamily:e.font,display:"flex",alignItems:"center",gap:12},children:[E.jsxs("span",{children:[n," ",n===1?"cell":"cells"]}),t.notebookDirty&&E.jsx("span",{style:{color:e.warning},children:"● unsaved"})]})]})}function Hf({t:e}){const{state:t}=ae();if(!t.activeFile)return null;const n=t.activeFile.path.split("/").filter(Boolean);return E.jsx("div",{style:{display:"flex",alignItems:"center",gap:4,fontSize:12,fontFamily:e.fontMono,color:e.textMuted,overflow:"hidden"},children:n.map((r,o)=>E.jsxs(on.Fragment,{children:[o>0&&E.jsx("span",{style:{color:e.textMuted,opacity:.5},children:"/"}),E.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 Vi={blank:"Blank",revenue:"Revenue Analysis",pipeline:"Pipeline Health"},Ff={blank:"Start with an empty notebook.",revenue:"Pre-built queries for revenue metrics and trends.",pipeline:"Templates for data pipeline health monitoring."};function Wi(e){return e.toLowerCase().replace(/[^a-z0-9\-_\s]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,64)}function wf(e){return e.trim()?/^[a-zA-Z0-9\-_ ]+$/.test(e)?null:"Only letters, numbers, hyphens, underscores, and spaces allowed.":"Name is required."}function Yf(e){switch(e){case"revenue":return[fe("markdown",`# Revenue Analysis
464
-
465
- This notebook analyzes revenue metrics and trends over time.`),{...fe("sql",`SELECT
466
- DATE_TRUNC('month', order_date) AS month,
467
- SUM(amount) AS revenue
468
- FROM orders
469
- GROUP BY 1
470
- ORDER BY 1`),name:"monthly_revenue"},{...fe("sql",`SELECT
471
- product_category,
472
- SUM(amount) AS total_revenue,
473
- COUNT(*) AS orders
474
- FROM orders
475
- GROUP BY 1
476
- ORDER BY 2 DESC`),name:"revenue_by_category"}];case"pipeline":return[fe("markdown",`# Pipeline Health
477
-
478
- Monitor data pipeline performance, SLA compliance, and error rates.`),{...fe("sql",`SELECT
479
- pipeline_name,
480
- COUNT(*) AS runs,
481
- AVG(duration_seconds) AS avg_duration,
482
- SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failures
483
- FROM pipeline_runs
484
- GROUP BY 1
485
- ORDER BY 4 DESC`),name:"pipeline_summary"},{...fe("sql",`SELECT
486
- *
487
- FROM pipeline_runs
488
- WHERE status = 'failed'
489
- AND run_date >= CURRENT_DATE - INTERVAL '7 days'
490
- ORDER BY run_date DESC`),name:"recent_failures"}];default:return[fe("sql")]}}function Vf({onFileOpened:e}){const{state:t,dispatch:n}=ae(),r=ie[t.themeMode],[o,s]=C.useState(""),[i,a]=C.useState("blank"),[T,l]=C.useState(null),[R,c]=C.useState(!1),A=C.useRef(null);C.useEffect(()=>{var I;(I=A.current)==null||I.focus()},[]),C.useEffect(()=>{const I=O=>{O.key==="Escape"&&n({type:"CLOSE_NEW_NOTEBOOK_MODAL"})};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[n]);const S=async()=>{const I=wf(o);if(I){l(I);return}c(!0),l(null);const O=Wi(o),u=Yf(i);try{const f=await Re.createNotebook(O,i),N={name:`${O}.dqlnb`,path:f.path,type:"notebook",folder:"notebooks",isNew:!0};n({type:"FILE_ADDED",file:N}),n({type:"OPEN_FILE",file:N,cells:u,title:o.trim()}),n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),e(N)}catch{const f=`notebooks/${O}.dqlnb`,N={name:`${O}.dqlnb`,path:f,type:"notebook",folder:"notebooks",isNew:!0};n({type:"FILE_ADDED",file:N}),n({type:"OPEN_FILE",file:N,cells:u,title:o.trim()}),n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),e(N)}finally{c(!1)}},d=I=>{I.target===I.currentTarget&&n({type:"CLOSE_NEW_NOTEBOOK_MODAL"})};return E.jsx("div",{onClick:d,style:{position:"fixed",inset:0,background:r.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(4px)"},children:E.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:[E.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[E.jsx("h2",{style:{fontSize:16,fontWeight:600,color:r.textPrimary,fontFamily:r.font,margin:0},children:"New Notebook"}),E.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:"×"})]}),E.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:20},children:[E.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[E.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Name"}),E.jsx("input",{ref:A,value:o,onChange:I=>{s(I.target.value),l(null)},onKeyDown:I=>{I.key==="Enter"&&S()},placeholder:"my-analysis",style:{background:r.inputBg,border:`1px solid ${T?r.error:r.inputBorder}`,borderRadius:6,color:r.textPrimary,fontSize:13,fontFamily:r.font,padding:"8px 12px",outline:"none",transition:"border-color 0.15s"}}),T&&E.jsx("span",{style:{fontSize:11,color:r.error,fontFamily:r.font},children:T}),o&&!T&&E.jsxs("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.fontMono},children:["File: ",Wi(o),".dqlnb"]})]}),E.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[E.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Template"}),E.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:Object.keys(Vi).map(I=>E.jsx(Wf,{value:I,selected:i===I,onSelect:()=>a(I),label:Vi[I],description:Ff[I],t:r},I))})]})]}),E.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${r.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[E.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"}),E.jsx("button",{onClick:S,disabled:R||!o.trim(),style:{background:r.accent,border:`1px solid ${r.accent}`,borderRadius:6,color:"#ffffff",cursor:R||!o.trim()?"not-allowed":"pointer",fontSize:13,fontFamily:r.font,fontWeight:500,padding:"7px 20px",opacity:R||!o.trim()?.6:1,display:"flex",alignItems:"center",gap:6},children:R?"Creating…":"Create Notebook"})]})]})})}function Wf({value:e,selected:t,onSelect:n,label:r,description:o,t:s}){const[i,a]=C.useState(!1);return E.jsxs("div",{onClick:n,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{display:"flex",alignItems:"flex-start",gap:10,padding:"10px 12px",borderRadius:8,border:`1px solid ${t?s.cellBorderActive:i?s.textMuted:s.inputBorder}`,background:t?`${s.cellBorderActive}10`:i?s.sidebarItemHover:"transparent",cursor:"pointer",transition:"all 0.15s"},children:[E.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&&E.jsx("div",{style:{width:8,height:8,borderRadius:4,background:s.accent}})}),E.jsxs("div",{children:[E.jsx("div",{style:{fontSize:13,fontWeight:500,color:s.textPrimary,fontFamily:s.font,marginBottom:2},children:r}),E.jsx("div",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font},children:o})]})]})}function ki(e){return e.toLowerCase().replace(/[^a-z0-9\-_\s]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,64)}function kf(e){return e.trim()?/^[a-zA-Z0-9\-_ ]+$/.test(e)?null:"Only letters, numbers, hyphens, underscores, and spaces allowed.":"Name is required."}function Xf({onFileOpened:e}){const{state:t,dispatch:n}=ae(),r=ie[t.themeMode],[o,s]=C.useState(""),[i,a]=C.useState(null),[T,l]=C.useState(!1),R=C.useRef(null);C.useEffect(()=>{var S;(S=R.current)==null||S.focus()},[]),C.useEffect(()=>{const S=d=>{d.key==="Escape"&&n({type:"CLOSE_NEW_BLOCK_MODAL"})};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[n]);const c=async()=>{var I;const S=kf(o);if(S){a(S);return}l(!0),a(null);const d=ki(o);try{const O=await Re.createBlock(o),u={name:`${d}.dql`,path:O.path,type:"block",folder:"blocks",isNew:!0};n({type:"FILE_ADDED",file:u}),n({type:"OPEN_FILE",file:u,cells:[fe("sql",O.content)],title:o.trim()}),n({type:"CLOSE_NEW_BLOCK_MODAL"}),e(u)}catch(O){(I=O.message)!=null&&I.includes("already exists")?a("A block with this name already exists."):a(O.message??"Failed to create block.")}finally{l(!1)}},A=S=>{S.target===S.currentTarget&&n({type:"CLOSE_NEW_BLOCK_MODAL"})};return E.jsx("div",{onClick:A,style:{position:"fixed",inset:0,background:r.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(4px)"},children:E.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:[E.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[E.jsx("h2",{style:{fontSize:16,fontWeight:600,color:r.textPrimary,fontFamily:r.font,margin:0},children:"New Block"}),E.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:"×"})]}),E.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:16},children:[E.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[E.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Block Name"}),E.jsx("input",{ref:R,value:o,onChange:S=>{s(S.target.value),a(null)},onKeyDown:S=>{S.key==="Enter"&&c()},placeholder:"revenue-summary",style:{background:r.inputBg,border:`1px solid ${i?r.error:r.inputBorder}`,borderRadius:6,color:r.textPrimary,fontSize:13,fontFamily:r.font,padding:"8px 12px",outline:"none",transition:"border-color 0.15s"}}),i&&E.jsx("span",{style:{fontSize:11,color:r.error,fontFamily:r.font},children:i}),o&&!i&&E.jsxs("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.fontMono},children:["blocks/",ki(o),".dql"]})]}),E.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 ",E.jsx("code",{style:{fontFamily:r.fontMono,fontSize:11},children:"blocks/"})," folder. They can be referenced from notebooks and other blocks."]})]}),E.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${r.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[E.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"}),E.jsx("button",{onClick:c,disabled:T||!o.trim(),style:{background:r.accent,border:`1px solid ${r.accent}`,borderRadius:6,color:"#ffffff",cursor:T||!o.trim()?"not-allowed":"pointer",fontSize:13,fontFamily:r.font,fontWeight:500,padding:"7px 20px",opacity:T||!o.trim()?.6:1,display:"flex",alignItems:"center",gap:6},children:T?"Creating...":"Create Block"})]})]})})}function Ae(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=Ae(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var jf={value:()=>{}};function hr(){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 zn(n)}function zn(e){this._=e}function $f(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}})}zn.prototype=hr.prototype={constructor:zn,on:function(e,t){var n=this._,r=$f(e+"",n),o,s=-1,i=r.length;if(arguments.length<2){for(;++s<i;)if((o=(e=r[s]).type)&&(o=Kf(n[o],e.name)))return o;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++s<i;)if(o=(e=r[s]).type)n[o]=Xi(n[o],e.name,t);else if(t==null)for(o in n)n[o]=Xi(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 zn(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 Kf(e,t){for(var n=0,r=e.length,o;n<r;++n)if((o=e[n]).name===t)return o.value}function Xi(e,t,n){for(var r=0,o=e.length;r<o;++r)if(e[r].name===t){e[r]=jf,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var ko="http://www.w3.org/1999/xhtml";const ji={svg:"http://www.w3.org/2000/svg",xhtml:ko,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function _r(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),ji.hasOwnProperty(t)?{space:ji[t],local:e}:e}function Jf(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===ko&&t.documentElement.namespaceURI===ko?t.createElement(e):t.createElementNS(n,e)}}function zf(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function ka(e){var t=_r(e);return(t.local?zf:Jf)(t)}function qf(){}function Is(e){return e==null?qf:function(){return this.querySelector(e)}}function Zf(e){typeof e!="function"&&(e=Is(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var s=t[o],i=s.length,a=r[o]=new Array(i),T,l,R=0;R<i;++R)(T=s[R])&&(l=e.call(T,T.__data__,R,s))&&("__data__"in T&&(l.__data__=T.__data__),a[R]=l);return new me(r,this._parents)}function Qf(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function eC(){return[]}function Xa(e){return e==null?eC:function(){return this.querySelectorAll(e)}}function tC(e){return function(){return Qf(e.apply(this,arguments))}}function nC(e){typeof e=="function"?e=tC(e):e=Xa(e);for(var t=this._groups,n=t.length,r=[],o=[],s=0;s<n;++s)for(var i=t[s],a=i.length,T,l=0;l<a;++l)(T=i[l])&&(r.push(e.call(T,T.__data__,l,i)),o.push(T));return new me(r,o)}function ja(e){return function(){return this.matches(e)}}function $a(e){return function(t){return t.matches(e)}}var rC=Array.prototype.find;function oC(e){return function(){return rC.call(this.children,e)}}function sC(){return this.firstElementChild}function iC(e){return this.select(e==null?sC:oC(typeof e=="function"?e:$a(e)))}var EC=Array.prototype.filter;function aC(){return Array.from(this.children)}function lC(e){return function(){return EC.call(this.children,e)}}function TC(e){return this.selectAll(e==null?aC:lC(typeof e=="function"?e:$a(e)))}function cC(e){typeof e!="function"&&(e=ja(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var s=t[o],i=s.length,a=r[o]=[],T,l=0;l<i;++l)(T=s[l])&&e.call(T,T.__data__,l,s)&&a.push(T);return new me(r,this._parents)}function Ka(e){return new Array(e.length)}function RC(){return new me(this._enter||this._groups.map(Ka),this._parents)}function ar(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}ar.prototype={constructor:ar,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 AC(e){return function(){return e}}function SC(e,t,n,r,o,s){for(var i=0,a,T=t.length,l=s.length;i<l;++i)(a=t[i])?(a.__data__=s[i],r[i]=a):n[i]=new ar(e,s[i]);for(;i<T;++i)(a=t[i])&&(o[i]=a)}function dC(e,t,n,r,o,s,i){var a,T,l=new Map,R=t.length,c=s.length,A=new Array(R),S;for(a=0;a<R;++a)(T=t[a])&&(A[a]=S=i.call(T,T.__data__,a,t)+"",l.has(S)?o[a]=T:l.set(S,T));for(a=0;a<c;++a)S=i.call(e,s[a],a,s)+"",(T=l.get(S))?(r[a]=T,T.__data__=s[a],l.delete(S)):n[a]=new ar(e,s[a]);for(a=0;a<R;++a)(T=t[a])&&l.get(A[a])===T&&(o[a]=T)}function IC(e){return e.__data__}function uC(e,t){if(!arguments.length)return Array.from(this,IC);var n=t?dC:SC,r=this._parents,o=this._groups;typeof e!="function"&&(e=AC(e));for(var s=o.length,i=new Array(s),a=new Array(s),T=new Array(s),l=0;l<s;++l){var R=r[l],c=o[l],A=c.length,S=NC(e.call(R,R&&R.__data__,l,r)),d=S.length,I=a[l]=new Array(d),O=i[l]=new Array(d),u=T[l]=new Array(A);n(R,c,I,O,u,S,t);for(var f=0,N=0,L,m;f<d;++f)if(L=I[f]){for(f>=N&&(N=f+1);!(m=O[N])&&++N<d;);L._next=m||null}}return i=new me(i,r),i._enter=a,i._exit=T,i}function NC(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function OC(){return new me(this._exit||this._groups.map(Ka),this._parents)}function fC(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 CC(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,o=n.length,s=r.length,i=Math.min(o,s),a=new Array(o),T=0;T<i;++T)for(var l=n[T],R=r[T],c=l.length,A=a[T]=new Array(c),S,d=0;d<c;++d)(S=l[d]||R[d])&&(A[d]=S);for(;T<o;++T)a[T]=n[T];return new me(a,this._parents)}function LC(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],o=r.length-1,s=r[o],i;--o>=0;)(i=r[o])&&(s&&i.compareDocumentPosition(s)^4&&s.parentNode.insertBefore(i,s),s=i);return this}function hC(e){e||(e=_C);function t(c,A){return c&&A?e(c.__data__,A.__data__):!c-!A}for(var n=this._groups,r=n.length,o=new Array(r),s=0;s<r;++s){for(var i=n[s],a=i.length,T=o[s]=new Array(a),l,R=0;R<a;++R)(l=i[R])&&(T[R]=l);T.sort(t)}return new me(o,this._parents).order()}function _C(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function pC(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function mC(){return Array.from(this)}function DC(){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 i=r[o];if(i)return i}return null}function gC(){let e=0;for(const t of this)++e;return e}function PC(){return!this.node()}function MC(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var o=t[n],s=0,i=o.length,a;s<i;++s)(a=o[s])&&e.call(a,a.__data__,s,o);return this}function yC(e){return function(){this.removeAttribute(e)}}function xC(e){return function(){this.removeAttributeNS(e.space,e.local)}}function UC(e,t){return function(){this.setAttribute(e,t)}}function bC(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function GC(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function BC(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 vC(e,t){var n=_r(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?xC:yC:typeof t=="function"?n.local?BC:GC:n.local?bC:UC)(n,t))}function Ja(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function HC(e){return function(){this.style.removeProperty(e)}}function FC(e,t,n){return function(){this.style.setProperty(e,t,n)}}function wC(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function YC(e,t,n){return arguments.length>1?this.each((t==null?HC:typeof t=="function"?wC:FC)(e,t,n??"")):Mt(this.node(),e)}function Mt(e,t){return e.style.getPropertyValue(t)||Ja(e).getComputedStyle(e,null).getPropertyValue(t)}function VC(e){return function(){delete this[e]}}function WC(e,t){return function(){this[e]=t}}function kC(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function XC(e,t){return arguments.length>1?this.each((t==null?VC:typeof t=="function"?kC:WC)(e,t)):this.node()[e]}function za(e){return e.trim().split(/^|\s+/)}function us(e){return e.classList||new qa(e)}function qa(e){this._node=e,this._names=za(e.getAttribute("class")||"")}qa.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 Za(e,t){for(var n=us(e),r=-1,o=t.length;++r<o;)n.add(t[r])}function Qa(e,t){for(var n=us(e),r=-1,o=t.length;++r<o;)n.remove(t[r])}function jC(e){return function(){Za(this,e)}}function $C(e){return function(){Qa(this,e)}}function KC(e,t){return function(){(t.apply(this,arguments)?Za:Qa)(this,e)}}function JC(e,t){var n=za(e+"");if(arguments.length<2){for(var r=us(this.node()),o=-1,s=n.length;++o<s;)if(!r.contains(n[o]))return!1;return!0}return this.each((typeof t=="function"?KC:t?jC:$C)(n,t))}function zC(){this.textContent=""}function qC(e){return function(){this.textContent=e}}function ZC(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function QC(e){return arguments.length?this.each(e==null?zC:(typeof e=="function"?ZC:qC)(e)):this.node().textContent}function eL(){this.innerHTML=""}function tL(e){return function(){this.innerHTML=e}}function nL(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function rL(e){return arguments.length?this.each(e==null?eL:(typeof e=="function"?nL:tL)(e)):this.node().innerHTML}function oL(){this.nextSibling&&this.parentNode.appendChild(this)}function sL(){return this.each(oL)}function iL(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function EL(){return this.each(iL)}function aL(e){var t=typeof e=="function"?e:ka(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function lL(){return null}function TL(e,t){var n=typeof e=="function"?e:ka(e),r=t==null?lL:typeof t=="function"?t:Is(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function cL(){var e=this.parentNode;e&&e.removeChild(this)}function RL(){return this.each(cL)}function AL(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function SL(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function dL(e){return this.select(e?SL:AL)}function IL(e){return arguments.length?this.property("__data__",e):this.node().__data__}function uL(e){return function(t){e.call(this,t,this.__data__)}}function NL(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 OL(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 fL(e,t,n){return function(){var r=this.__on,o,s=uL(t);if(r){for(var i=0,a=r.length;i<a;++i)if((o=r[i]).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 CL(e,t,n){var r=NL(e+""),o,s=r.length,i;if(arguments.length<2){var a=this.node().__on;if(a){for(var T=0,l=a.length,R;T<l;++T)for(o=0,R=a[T];o<s;++o)if((i=r[o]).type===R.type&&i.name===R.name)return R.value}return}for(a=t?fL:OL,o=0;o<s;++o)this.each(a(r[o],t,n));return this}function el(e,t,n){var r=Ja(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 LL(e,t){return function(){return el(this,e,t)}}function hL(e,t){return function(){return el(this,e,t.apply(this,arguments))}}function _L(e,t){return this.each((typeof t=="function"?hL:LL)(e,t))}function*pL(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],o=0,s=r.length,i;o<s;++o)(i=r[o])&&(yield i)}var tl=[null];function me(e,t){this._groups=e,this._parents=t}function Cn(){return new me([[document.documentElement]],tl)}function mL(){return this}me.prototype=Cn.prototype={constructor:me,select:Zf,selectAll:nC,selectChild:iC,selectChildren:TC,filter:cC,data:uC,enter:RC,exit:OC,join:fC,merge:CC,selection:mL,order:LC,sort:hC,call:pC,nodes:mC,node:DC,size:gC,empty:PC,each:MC,attr:vC,style:YC,property:XC,classed:JC,text:QC,html:rL,raise:sL,lower:EL,append:aL,insert:TL,remove:RL,clone:dL,datum:IL,on:CL,dispatch:_L,[Symbol.iterator]:pL};function _e(e){return typeof e=="string"?new me([[document.querySelector(e)]],[document.documentElement]):new me([[e]],tl)}function DL(e){let t;for(;t=e.sourceEvent;)e=t;return e}function Pe(e,t){if(e=DL(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 gL={passive:!1},ln={capture:!0,passive:!1};function Oo(e){e.stopImmediatePropagation()}function gt(e){e.preventDefault(),e.stopImmediatePropagation()}function nl(e){var t=e.document.documentElement,n=_e(e).on("dragstart.drag",gt,ln);"onselectstart"in t?n.on("selectstart.drag",gt,ln):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function rl(e,t){var n=e.document.documentElement,r=_e(e).on("dragstart.drag",null);t&&(r.on("click.drag",gt,ln),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 Bn=e=>()=>e;function Xo(e,{sourceEvent:t,subject:n,target:r,identifier:o,active:s,x:i,y:a,dx:T,dy:l,dispatch:R}){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:i,enumerable:!0,configurable:!0},y:{value:a,enumerable:!0,configurable:!0},dx:{value:T,enumerable:!0,configurable:!0},dy:{value:l,enumerable:!0,configurable:!0},_:{value:R}})}Xo.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function PL(e){return!e.ctrlKey&&!e.button}function ML(){return this.parentNode}function yL(e,t){return t??{x:e.x,y:e.y}}function xL(){return navigator.maxTouchPoints||"ontouchstart"in this}function ol(){var e=PL,t=ML,n=yL,r=xL,o={},s=hr("start","drag","end"),i=0,a,T,l,R,c=0;function A(L){L.on("mousedown.drag",S).filter(r).on("touchstart.drag",O).on("touchmove.drag",u,gL).on("touchend.drag touchcancel.drag",f).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function S(L,m){if(!(R||!e.call(this,L,m))){var p=N(this,t.call(this,L,m),L,m,"mouse");p&&(_e(L.view).on("mousemove.drag",d,ln).on("mouseup.drag",I,ln),nl(L.view),Oo(L),l=!1,a=L.clientX,T=L.clientY,p("start",L))}}function d(L){if(gt(L),!l){var m=L.clientX-a,p=L.clientY-T;l=m*m+p*p>c}o.mouse("drag",L)}function I(L){_e(L.view).on("mousemove.drag mouseup.drag",null),rl(L.view,l),gt(L),o.mouse("end",L)}function O(L,m){if(e.call(this,L,m)){var p=L.changedTouches,D=t.call(this,L,m),M=p.length,B,F;for(B=0;B<M;++B)(F=N(this,D,L,m,p[B].identifier,p[B]))&&(Oo(L),F("start",L,p[B]))}}function u(L){var m=L.changedTouches,p=m.length,D,M;for(D=0;D<p;++D)(M=o[m[D].identifier])&&(gt(L),M("drag",L,m[D]))}function f(L){var m=L.changedTouches,p=m.length,D,M;for(R&&clearTimeout(R),R=setTimeout(function(){R=null},500),D=0;D<p;++D)(M=o[m[D].identifier])&&(Oo(L),M("end",L,m[D]))}function N(L,m,p,D,M,B){var F=s.copy(),g=Pe(B||p,m),_,U,h;if((h=n.call(L,new Xo("beforestart",{sourceEvent:p,target:A,identifier:M,active:i,x:g[0],y:g[1],dx:0,dy:0,dispatch:F}),D))!=null)return _=h.x-g[0]||0,U=h.y-g[1]||0,function x(P,v,b){var y=g,Y;switch(P){case"start":o[M]=x,Y=i++;break;case"end":delete o[M],--i;case"drag":g=Pe(b||v,m),Y=i;break}F.call(P,L,new Xo(P,{sourceEvent:v,subject:h,target:A,identifier:M,active:Y,x:g[0]+_,y:g[1]+U,dx:g[0]-y[0],dy:g[1]-y[1],dispatch:F}),D)}}return A.filter=function(L){return arguments.length?(e=typeof L=="function"?L:Bn(!!L),A):e},A.container=function(L){return arguments.length?(t=typeof L=="function"?L:Bn(L),A):t},A.subject=function(L){return arguments.length?(n=typeof L=="function"?L:Bn(L),A):n},A.touchable=function(L){return arguments.length?(r=typeof L=="function"?L:Bn(!!L),A):r},A.on=function(){var L=s.on.apply(s,arguments);return L===s?A:L},A.clickDistance=function(L){return arguments.length?(c=(L=+L)*L,A):Math.sqrt(c)},A}function Ns(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function sl(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function Ln(){}var Tn=.7,lr=1/Tn,Pt="\\s*([+-]?\\d+)\\s*",cn="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Fe="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",UL=/^#([0-9a-f]{3,8})$/,bL=new RegExp(`^rgb\\(${Pt},${Pt},${Pt}\\)$`),GL=new RegExp(`^rgb\\(${Fe},${Fe},${Fe}\\)$`),BL=new RegExp(`^rgba\\(${Pt},${Pt},${Pt},${cn}\\)$`),vL=new RegExp(`^rgba\\(${Fe},${Fe},${Fe},${cn}\\)$`),HL=new RegExp(`^hsl\\(${cn},${Fe},${Fe}\\)$`),FL=new RegExp(`^hsla\\(${cn},${Fe},${Fe},${cn}\\)$`),$i={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};Ns(Ln,Rt,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Ki,formatHex:Ki,formatHex8:wL,formatHsl:YL,formatRgb:Ji,toString:Ji});function Ki(){return this.rgb().formatHex()}function wL(){return this.rgb().formatHex8()}function YL(){return il(this).formatHsl()}function Ji(){return this.rgb().formatRgb()}function Rt(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=UL.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?zi(t):n===3?new Le(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?vn(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?vn(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=bL.exec(e))?new Le(t[1],t[2],t[3],1):(t=GL.exec(e))?new Le(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=BL.exec(e))?vn(t[1],t[2],t[3],t[4]):(t=vL.exec(e))?vn(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=HL.exec(e))?Qi(t[1],t[2]/100,t[3]/100,1):(t=FL.exec(e))?Qi(t[1],t[2]/100,t[3]/100,t[4]):$i.hasOwnProperty(e)?zi($i[e]):e==="transparent"?new Le(NaN,NaN,NaN,0):null}function zi(e){return new Le(e>>16&255,e>>8&255,e&255,1)}function vn(e,t,n,r){return r<=0&&(e=t=n=NaN),new Le(e,t,n,r)}function VL(e){return e instanceof Ln||(e=Rt(e)),e?(e=e.rgb(),new Le(e.r,e.g,e.b,e.opacity)):new Le}function jo(e,t,n,r){return arguments.length===1?VL(e):new Le(e,t,n,r??1)}function Le(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Ns(Le,jo,sl(Ln,{brighter(e){return e=e==null?lr:Math.pow(lr,e),new Le(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Tn:Math.pow(Tn,e),new Le(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Le(Tt(this.r),Tt(this.g),Tt(this.b),Tr(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:qi,formatHex:qi,formatHex8:WL,formatRgb:Zi,toString:Zi}));function qi(){return`#${lt(this.r)}${lt(this.g)}${lt(this.b)}`}function WL(){return`#${lt(this.r)}${lt(this.g)}${lt(this.b)}${lt((isNaN(this.opacity)?1:this.opacity)*255)}`}function Zi(){const e=Tr(this.opacity);return`${e===1?"rgb(":"rgba("}${Tt(this.r)}, ${Tt(this.g)}, ${Tt(this.b)}${e===1?")":`, ${e})`}`}function Tr(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Tt(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function lt(e){return e=Tt(e),(e<16?"0":"")+e.toString(16)}function Qi(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Me(e,t,n,r)}function il(e){if(e instanceof Me)return new Me(e.h,e.s,e.l,e.opacity);if(e instanceof Ln||(e=Rt(e)),!e)return new Me;if(e instanceof Me)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),i=NaN,a=s-o,T=(s+o)/2;return a?(t===s?i=(n-r)/a+(n<r)*6:n===s?i=(r-t)/a+2:i=(t-n)/a+4,a/=T<.5?s+o:2-s-o,i*=60):a=T>0&&T<1?0:i,new Me(i,a,T,e.opacity)}function kL(e,t,n,r){return arguments.length===1?il(e):new Me(e,t,n,r??1)}function Me(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Ns(Me,kL,sl(Ln,{brighter(e){return e=e==null?lr:Math.pow(lr,e),new Me(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Tn:Math.pow(Tn,e),new Me(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 Le(fo(e>=240?e-240:e+120,o,r),fo(e,o,r),fo(e<120?e+240:e-120,o,r),this.opacity)},clamp(){return new Me(eE(this.h),Hn(this.s),Hn(this.l),Tr(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=Tr(this.opacity);return`${e===1?"hsl(":"hsla("}${eE(this.h)}, ${Hn(this.s)*100}%, ${Hn(this.l)*100}%${e===1?")":`, ${e})`}`}}));function eE(e){return e=(e||0)%360,e<0?e+360:e}function Hn(e){return Math.max(0,Math.min(1,e||0))}function fo(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 Os=e=>()=>e;function XL(e,t){return function(n){return e+n*t}}function jL(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 $L(e){return(e=+e)==1?El:function(t,n){return n-t?jL(t,n,e):Os(isNaN(t)?n:t)}}function El(e,t){var n=t-e;return n?XL(e,n):Os(isNaN(e)?t:e)}const cr=(function e(t){var n=$L(t);function r(o,s){var i=n((o=jo(o)).r,(s=jo(s)).r),a=n(o.g,s.g),T=n(o.b,s.b),l=El(o.opacity,s.opacity);return function(R){return o.r=i(R),o.g=a(R),o.b=T(R),o.opacity=l(R),o+""}}return r.gamma=e,r})(1);function KL(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 JL(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function zL(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,o=new Array(r),s=new Array(n),i;for(i=0;i<r;++i)o[i]=nn(e[i],t[i]);for(;i<n;++i)s[i]=t[i];return function(a){for(i=0;i<r;++i)s[i]=o[i](a);return s}}function qL(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function ve(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function ZL(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]=nn(e[o],t[o]):r[o]=t[o];return function(s){for(o in n)r[o]=n[o](s);return r}}var $o=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Co=new RegExp($o.source,"g");function QL(e){return function(){return e}}function eh(e){return function(t){return e(t)+""}}function al(e,t){var n=$o.lastIndex=Co.lastIndex=0,r,o,s,i=-1,a=[],T=[];for(e=e+"",t=t+"";(r=$o.exec(e))&&(o=Co.exec(t));)(s=o.index)>n&&(s=t.slice(n,s),a[i]?a[i]+=s:a[++i]=s),(r=r[0])===(o=o[0])?a[i]?a[i]+=o:a[++i]=o:(a[++i]=null,T.push({i,x:ve(r,o)})),n=Co.lastIndex;return n<t.length&&(s=t.slice(n),a[i]?a[i]+=s:a[++i]=s),a.length<2?T[0]?eh(T[0].x):QL(t):(t=T.length,function(l){for(var R=0,c;R<t;++R)a[(c=T[R]).i]=c.x(l);return a.join("")})}function nn(e,t){var n=typeof t,r;return t==null||n==="boolean"?Os(t):(n==="number"?ve:n==="string"?(r=Rt(t))?(t=r,cr):al:t instanceof Rt?cr:t instanceof Date?qL:JL(t)?KL:Array.isArray(t)?zL:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?ZL:ve)(e,t)}var tE=180/Math.PI,Ko={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function ll(e,t,n,r,o,s){var i,a,T;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(T=e*n+t*r)&&(n-=e*T,r-=t*T),(a=Math.sqrt(n*n+r*r))&&(n/=a,r/=a,T/=a),e*r<t*n&&(e=-e,t=-t,T=-T,i=-i),{translateX:o,translateY:s,rotate:Math.atan2(t,e)*tE,skewX:Math.atan(T)*tE,scaleX:i,scaleY:a}}var Fn;function th(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Ko:ll(t.a,t.b,t.c,t.d,t.e,t.f)}function nh(e){return e==null||(Fn||(Fn=document.createElementNS("http://www.w3.org/2000/svg","g")),Fn.setAttribute("transform",e),!(e=Fn.transform.baseVal.consolidate()))?Ko:(e=e.matrix,ll(e.a,e.b,e.c,e.d,e.e,e.f))}function Tl(e,t,n,r){function o(l){return l.length?l.pop()+" ":""}function s(l,R,c,A,S,d){if(l!==c||R!==A){var I=S.push("translate(",null,t,null,n);d.push({i:I-4,x:ve(l,c)},{i:I-2,x:ve(R,A)})}else(c||A)&&S.push("translate("+c+t+A+n)}function i(l,R,c,A){l!==R?(l-R>180?R+=360:R-l>180&&(l+=360),A.push({i:c.push(o(c)+"rotate(",null,r)-2,x:ve(l,R)})):R&&c.push(o(c)+"rotate("+R+r)}function a(l,R,c,A){l!==R?A.push({i:c.push(o(c)+"skewX(",null,r)-2,x:ve(l,R)}):R&&c.push(o(c)+"skewX("+R+r)}function T(l,R,c,A,S,d){if(l!==c||R!==A){var I=S.push(o(S)+"scale(",null,",",null,")");d.push({i:I-4,x:ve(l,c)},{i:I-2,x:ve(R,A)})}else(c!==1||A!==1)&&S.push(o(S)+"scale("+c+","+A+")")}return function(l,R){var c=[],A=[];return l=e(l),R=e(R),s(l.translateX,l.translateY,R.translateX,R.translateY,c,A),i(l.rotate,R.rotate,c,A),a(l.skewX,R.skewX,c,A),T(l.scaleX,l.scaleY,R.scaleX,R.scaleY,c,A),l=R=null,function(S){for(var d=-1,I=A.length,O;++d<I;)c[(O=A[d]).i]=O.x(S);return c.join("")}}}var rh=Tl(th,"px, ","px)","deg)"),oh=Tl(nh,", ",")",")"),sh=1e-12;function nE(e){return((e=Math.exp(e))+1/e)/2}function ih(e){return((e=Math.exp(e))-1/e)/2}function Eh(e){return((e=Math.exp(2*e))-1)/(e+1)}const qn=(function e(t,n,r){function o(s,i){var a=s[0],T=s[1],l=s[2],R=i[0],c=i[1],A=i[2],S=R-a,d=c-T,I=S*S+d*d,O,u;if(I<sh)u=Math.log(A/l)/t,O=function(D){return[a+D*S,T+D*d,l*Math.exp(t*D*u)]};else{var f=Math.sqrt(I),N=(A*A-l*l+r*I)/(2*l*n*f),L=(A*A-l*l-r*I)/(2*A*n*f),m=Math.log(Math.sqrt(N*N+1)-N),p=Math.log(Math.sqrt(L*L+1)-L);u=(p-m)/t,O=function(D){var M=D*u,B=nE(m),F=l/(n*f)*(B*Eh(t*M+m)-ih(m));return[a+F*S,T+F*d,l*B/nE(t*M+m)]}}return O.duration=u*1e3*t/Math.SQRT2,O}return o.rho=function(s){var i=Math.max(.001,+s),a=i*i,T=a*a;return e(i,a,T)},o})(Math.SQRT2,2,4);var yt=0,Zt=0,Jt=0,cl=1e3,Rr,Qt,Ar=0,At=0,pr=0,Rn=typeof performance=="object"&&performance.now?performance:Date,Rl=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function fs(){return At||(Rl(ah),At=Rn.now()+pr)}function ah(){At=0}function Sr(){this._call=this._time=this._next=null}Sr.prototype=Al.prototype={constructor:Sr,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?fs():+n)+(t==null?0:+t),!this._next&&Qt!==this&&(Qt?Qt._next=this:Rr=this,Qt=this),this._call=e,this._time=n,Jo()},stop:function(){this._call&&(this._call=null,this._time=1/0,Jo())}};function Al(e,t,n){var r=new Sr;return r.restart(e,t,n),r}function lh(){fs(),++yt;for(var e=Rr,t;e;)(t=At-e._time)>=0&&e._call.call(void 0,t),e=e._next;--yt}function rE(){At=(Ar=Rn.now())+pr,yt=Zt=0;try{lh()}finally{yt=0,ch(),At=0}}function Th(){var e=Rn.now(),t=e-Ar;t>cl&&(pr-=t,Ar=e)}function ch(){for(var e,t=Rr,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:Rr=n);Qt=e,Jo(r)}function Jo(e){if(!yt){Zt&&(Zt=clearTimeout(Zt));var t=e-At;t>24?(e<1/0&&(Zt=setTimeout(rE,e-Rn.now()-pr)),Jt&&(Jt=clearInterval(Jt))):(Jt||(Ar=Rn.now(),Jt=setInterval(Th,cl)),yt=1,Rl(rE))}}function oE(e,t,n){var r=new Sr;return t=t==null?0:+t,r.restart(o=>{r.stop(),e(o+t)},t,n),r}var Rh=hr("start","end","cancel","interrupt"),Ah=[],Sl=0,sE=1,zo=2,Zn=3,iE=4,qo=5,Qn=6;function mr(e,t,n,r,o,s){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;Sh(e,n,{name:t,index:r,group:o,on:Rh,tween:Ah,time:s.time,delay:s.delay,duration:s.duration,ease:s.ease,timer:null,state:Sl})}function Cs(e,t){var n=Ge(e,t);if(n.state>Sl)throw new Error("too late; already scheduled");return n}function Ye(e,t){var n=Ge(e,t);if(n.state>Zn)throw new Error("too late; already running");return n}function Ge(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function Sh(e,t,n){var r=e.__transition,o;r[t]=n,n.timer=Al(s,0,n.time);function s(l){n.state=sE,n.timer.restart(i,n.delay,n.time),n.delay<=l&&i(l-n.delay)}function i(l){var R,c,A,S;if(n.state!==sE)return T();for(R in r)if(S=r[R],S.name===n.name){if(S.state===Zn)return oE(i);S.state===iE?(S.state=Qn,S.timer.stop(),S.on.call("interrupt",e,e.__data__,S.index,S.group),delete r[R]):+R<t&&(S.state=Qn,S.timer.stop(),S.on.call("cancel",e,e.__data__,S.index,S.group),delete r[R])}if(oE(function(){n.state===Zn&&(n.state=iE,n.timer.restart(a,n.delay,n.time),a(l))}),n.state=zo,n.on.call("start",e,e.__data__,n.index,n.group),n.state===zo){for(n.state=Zn,o=new Array(A=n.tween.length),R=0,c=-1;R<A;++R)(S=n.tween[R].value.call(e,e.__data__,n.index,n.group))&&(o[++c]=S);o.length=c+1}}function a(l){for(var R=l<n.duration?n.ease.call(null,l/n.duration):(n.timer.restart(T),n.state=qo,1),c=-1,A=o.length;++c<A;)o[c].call(e,R);n.state===qo&&(n.on.call("end",e,e.__data__,n.index,n.group),T())}function T(){n.state=Qn,n.timer.stop(),delete r[t];for(var l in r)return;delete e.__transition}}function er(e,t){var n=e.__transition,r,o,s=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){s=!1;continue}o=r.state>zo&&r.state<qo,r.state=Qn,r.timer.stop(),r.on.call(o?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}s&&delete e.__transition}}function dh(e){return this.each(function(){er(this,e)})}function Ih(e,t){var n,r;return function(){var o=Ye(this,e),s=o.tween;if(s!==n){r=n=s;for(var i=0,a=r.length;i<a;++i)if(r[i].name===t){r=r.slice(),r.splice(i,1);break}}o.tween=r}}function uh(e,t,n){var r,o;if(typeof n!="function")throw new Error;return function(){var s=Ye(this,e),i=s.tween;if(i!==r){o=(r=i).slice();for(var a={name:t,value:n},T=0,l=o.length;T<l;++T)if(o[T].name===t){o[T]=a;break}T===l&&o.push(a)}s.tween=o}}function Nh(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Ge(this.node(),n).tween,o=0,s=r.length,i;o<s;++o)if((i=r[o]).name===e)return i.value;return null}return this.each((t==null?Ih:uh)(n,e,t))}function Ls(e,t,n){var r=e._id;return e.each(function(){var o=Ye(this,r);(o.value||(o.value={}))[t]=n.apply(this,arguments)}),function(o){return Ge(o,r).value[t]}}function dl(e,t){var n;return(typeof t=="number"?ve:t instanceof Rt?cr:(n=Rt(t))?(t=n,cr):al)(e,t)}function Oh(e){return function(){this.removeAttribute(e)}}function fh(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Ch(e,t,n){var r,o=n+"",s;return function(){var i=this.getAttribute(e);return i===o?null:i===r?s:s=t(r=i,n)}}function Lh(e,t,n){var r,o=n+"",s;return function(){var i=this.getAttributeNS(e.space,e.local);return i===o?null:i===r?s:s=t(r=i,n)}}function hh(e,t,n){var r,o,s;return function(){var i,a=n(this),T;return a==null?void this.removeAttribute(e):(i=this.getAttribute(e),T=a+"",i===T?null:i===r&&T===o?s:(o=T,s=t(r=i,a)))}}function _h(e,t,n){var r,o,s;return function(){var i,a=n(this),T;return a==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),T=a+"",i===T?null:i===r&&T===o?s:(o=T,s=t(r=i,a)))}}function ph(e,t){var n=_r(e),r=n==="transform"?oh:dl;return this.attrTween(e,typeof t=="function"?(n.local?_h:hh)(n,r,Ls(this,"attr."+e,t)):t==null?(n.local?fh:Oh)(n):(n.local?Lh:Ch)(n,r,t))}function mh(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function Dh(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function gh(e,t){var n,r;function o(){var s=t.apply(this,arguments);return s!==r&&(n=(r=s)&&Dh(e,s)),n}return o._value=t,o}function Ph(e,t){var n,r;function o(){var s=t.apply(this,arguments);return s!==r&&(n=(r=s)&&mh(e,s)),n}return o._value=t,o}function Mh(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=_r(e);return this.tween(n,(r.local?gh:Ph)(r,t))}function yh(e,t){return function(){Cs(this,e).delay=+t.apply(this,arguments)}}function xh(e,t){return t=+t,function(){Cs(this,e).delay=t}}function Uh(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?yh:xh)(t,e)):Ge(this.node(),t).delay}function bh(e,t){return function(){Ye(this,e).duration=+t.apply(this,arguments)}}function Gh(e,t){return t=+t,function(){Ye(this,e).duration=t}}function Bh(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?bh:Gh)(t,e)):Ge(this.node(),t).duration}function vh(e,t){if(typeof t!="function")throw new Error;return function(){Ye(this,e).ease=t}}function Hh(e){var t=this._id;return arguments.length?this.each(vh(t,e)):Ge(this.node(),t).ease}function Fh(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Ye(this,e).ease=n}}function wh(e){if(typeof e!="function")throw new Error;return this.each(Fh(this._id,e))}function Yh(e){typeof e!="function"&&(e=ja(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var s=t[o],i=s.length,a=r[o]=[],T,l=0;l<i;++l)(T=s[l])&&e.call(T,T.__data__,l,s)&&a.push(T);return new Je(r,this._parents,this._name,this._id)}function Vh(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),i=new Array(r),a=0;a<s;++a)for(var T=t[a],l=n[a],R=T.length,c=i[a]=new Array(R),A,S=0;S<R;++S)(A=T[S]||l[S])&&(c[S]=A);for(;a<r;++a)i[a]=t[a];return new Je(i,this._parents,this._name,this._id)}function Wh(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 kh(e,t,n){var r,o,s=Wh(t)?Cs:Ye;return function(){var i=s(this,e),a=i.on;a!==r&&(o=(r=a).copy()).on(t,n),i.on=o}}function Xh(e,t){var n=this._id;return arguments.length<2?Ge(this.node(),n).on.on(e):this.each(kh(n,e,t))}function jh(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function $h(){return this.on("end.remove",jh(this._id))}function Kh(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Is(e));for(var r=this._groups,o=r.length,s=new Array(o),i=0;i<o;++i)for(var a=r[i],T=a.length,l=s[i]=new Array(T),R,c,A=0;A<T;++A)(R=a[A])&&(c=e.call(R,R.__data__,A,a))&&("__data__"in R&&(c.__data__=R.__data__),l[A]=c,mr(l[A],t,n,A,l,Ge(R,n)));return new Je(s,this._parents,t,n)}function Jh(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Xa(e));for(var r=this._groups,o=r.length,s=[],i=[],a=0;a<o;++a)for(var T=r[a],l=T.length,R,c=0;c<l;++c)if(R=T[c]){for(var A=e.call(R,R.__data__,c,T),S,d=Ge(R,n),I=0,O=A.length;I<O;++I)(S=A[I])&&mr(S,t,n,I,A,d);s.push(A),i.push(R)}return new Je(s,i,t,n)}var zh=Cn.prototype.constructor;function qh(){return new zh(this._groups,this._parents)}function Zh(e,t){var n,r,o;return function(){var s=Mt(this,e),i=(this.style.removeProperty(e),Mt(this,e));return s===i?null:s===n&&i===r?o:o=t(n=s,r=i)}}function Il(e){return function(){this.style.removeProperty(e)}}function Qh(e,t,n){var r,o=n+"",s;return function(){var i=Mt(this,e);return i===o?null:i===r?s:s=t(r=i,n)}}function e_(e,t,n){var r,o,s;return function(){var i=Mt(this,e),a=n(this),T=a+"";return a==null&&(T=a=(this.style.removeProperty(e),Mt(this,e))),i===T?null:i===r&&T===o?s:(o=T,s=t(r=i,a))}}function t_(e,t){var n,r,o,s="style."+t,i="end."+s,a;return function(){var T=Ye(this,e),l=T.on,R=T.value[s]==null?a||(a=Il(t)):void 0;(l!==n||o!==R)&&(r=(n=l).copy()).on(i,o=R),T.on=r}}function n_(e,t,n){var r=(e+="")=="transform"?rh:dl;return t==null?this.styleTween(e,Zh(e,r)).on("end.style."+e,Il(e)):typeof t=="function"?this.styleTween(e,e_(e,r,Ls(this,"style."+e,t))).each(t_(this._id,e)):this.styleTween(e,Qh(e,r,t),n).on("end.style."+e,null)}function r_(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function o_(e,t,n){var r,o;function s(){var i=t.apply(this,arguments);return i!==o&&(r=(o=i)&&r_(e,i,n)),r}return s._value=t,s}function s_(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,o_(e,t,n??""))}function i_(e){return function(){this.textContent=e}}function E_(e){return function(){var t=e(this);this.textContent=t??""}}function a_(e){return this.tween("text",typeof e=="function"?E_(Ls(this,"text",e)):i_(e==null?"":e+""))}function l_(e){return function(t){this.textContent=e.call(this,t)}}function T_(e){var t,n;function r(){var o=e.apply(this,arguments);return o!==n&&(t=(n=o)&&l_(o)),t}return r._value=e,r}function c_(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,T_(e))}function R_(){for(var e=this._name,t=this._id,n=ul(),r=this._groups,o=r.length,s=0;s<o;++s)for(var i=r[s],a=i.length,T,l=0;l<a;++l)if(T=i[l]){var R=Ge(T,t);mr(T,e,n,l,i,{time:R.time+R.delay+R.duration,delay:0,duration:R.duration,ease:R.ease})}return new Je(r,this._parents,e,n)}function A_(){var e,t,n=this,r=n._id,o=n.size();return new Promise(function(s,i){var a={value:i},T={value:function(){--o===0&&s()}};n.each(function(){var l=Ye(this,r),R=l.on;R!==e&&(t=(e=R).copy(),t._.cancel.push(a),t._.interrupt.push(a),t._.end.push(T)),l.on=t}),o===0&&s()})}var S_=0;function Je(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function ul(){return++S_}var je=Cn.prototype;Je.prototype={constructor:Je,select:Kh,selectAll:Jh,selectChild:je.selectChild,selectChildren:je.selectChildren,filter:Yh,merge:Vh,selection:qh,transition:R_,call:je.call,nodes:je.nodes,node:je.node,size:je.size,empty:je.empty,each:je.each,on:Xh,attr:ph,attrTween:Mh,style:n_,styleTween:s_,text:a_,textTween:c_,remove:$h,tween:Nh,delay:Uh,duration:Bh,ease:Hh,easeVarying:wh,end:A_,[Symbol.iterator]:je[Symbol.iterator]};function d_(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var I_={time:null,delay:0,duration:250,ease:d_};function u_(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 N_(e){var t,n;e instanceof Je?(t=e._id,e=e._name):(t=ul(),(n=I_).time=fs(),e=e==null?null:e+"");for(var r=this._groups,o=r.length,s=0;s<o;++s)for(var i=r[s],a=i.length,T,l=0;l<a;++l)(T=i[l])&&mr(T,e,t,l,i,n||u_(T,t));return new Je(r,this._parents,e,t)}Cn.prototype.interrupt=dh;Cn.prototype.transition=N_;const wn=e=>()=>e;function O_(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 Ke(e,t,n){this.k=e,this.x=t,this.y=n}Ke.prototype={constructor:Ke,scale:function(e){return e===1?this:new Ke(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Ke(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 Dr=new Ke(1,0,0);Nl.prototype=Ke.prototype;function Nl(e){for(;!e.__zoom;)if(!(e=e.parentNode))return Dr;return e.__zoom}function Lo(e){e.stopImmediatePropagation()}function zt(e){e.preventDefault(),e.stopImmediatePropagation()}function f_(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function C_(){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 EE(){return this.__zoom||Dr}function L_(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function h_(){return navigator.maxTouchPoints||"ontouchstart"in this}function __(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],i=e.invertY(t[1][1])-n[1][1];return e.translate(o>r?(r+o)/2:Math.min(0,r)||Math.max(0,o),i>s?(s+i)/2:Math.min(0,s)||Math.max(0,i))}function Ol(){var e=f_,t=C_,n=__,r=L_,o=h_,s=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],a=250,T=qn,l=hr("start","zoom","end"),R,c,A,S=500,d=150,I=0,O=10;function u(h){h.property("__zoom",EE).on("wheel.zoom",M,{passive:!1}).on("mousedown.zoom",B).on("dblclick.zoom",F).filter(o).on("touchstart.zoom",g).on("touchmove.zoom",_).on("touchend.zoom touchcancel.zoom",U).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}u.transform=function(h,x,P,v){var b=h.selection?h.selection():h;b.property("__zoom",EE),h!==b?m(h,x,P,v):b.interrupt().each(function(){p(this,arguments).event(v).start().zoom(null,typeof x=="function"?x.apply(this,arguments):x).end()})},u.scaleBy=function(h,x,P,v){u.scaleTo(h,function(){var b=this.__zoom.k,y=typeof x=="function"?x.apply(this,arguments):x;return b*y},P,v)},u.scaleTo=function(h,x,P,v){u.transform(h,function(){var b=t.apply(this,arguments),y=this.__zoom,Y=P==null?L(b):typeof P=="function"?P.apply(this,arguments):P,W=y.invert(Y),V=typeof x=="function"?x.apply(this,arguments):x;return n(N(f(y,V),Y,W),b,i)},P,v)},u.translateBy=function(h,x,P,v){u.transform(h,function(){return n(this.__zoom.translate(typeof x=="function"?x.apply(this,arguments):x,typeof P=="function"?P.apply(this,arguments):P),t.apply(this,arguments),i)},null,v)},u.translateTo=function(h,x,P,v,b){u.transform(h,function(){var y=t.apply(this,arguments),Y=this.__zoom,W=v==null?L(y):typeof v=="function"?v.apply(this,arguments):v;return n(Dr.translate(W[0],W[1]).scale(Y.k).translate(typeof x=="function"?-x.apply(this,arguments):-x,typeof P=="function"?-P.apply(this,arguments):-P),y,i)},v,b)};function f(h,x){return x=Math.max(s[0],Math.min(s[1],x)),x===h.k?h:new Ke(x,h.x,h.y)}function N(h,x,P){var v=x[0]-P[0]*h.k,b=x[1]-P[1]*h.k;return v===h.x&&b===h.y?h:new Ke(h.k,v,b)}function L(h){return[(+h[0][0]+ +h[1][0])/2,(+h[0][1]+ +h[1][1])/2]}function m(h,x,P,v){h.on("start.zoom",function(){p(this,arguments).event(v).start()}).on("interrupt.zoom end.zoom",function(){p(this,arguments).event(v).end()}).tween("zoom",function(){var b=this,y=arguments,Y=p(b,y).event(v),W=t.apply(b,y),V=P==null?L(W):typeof P=="function"?P.apply(b,y):P,k=Math.max(W[1][0]-W[0][0],W[1][1]-W[0][1]),X=b.__zoom,K=typeof x=="function"?x.apply(b,y):x,Q=T(X.invert(V).concat(k/X.k),K.invert(V).concat(k/K.k));return function(j){if(j===1)j=K;else{var $=Q(j),ee=k/$[2];j=new Ke(ee,V[0]-$[0]*ee,V[1]-$[1]*ee)}Y.zoom(null,j)}})}function p(h,x,P){return!P&&h.__zooming||new D(h,x)}function D(h,x){this.that=h,this.args=x,this.active=0,this.sourceEvent=null,this.extent=t.apply(h,x),this.taps=0}D.prototype={event:function(h){return h&&(this.sourceEvent=h),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(h,x){return this.mouse&&h!=="mouse"&&(this.mouse[1]=x.invert(this.mouse[0])),this.touch0&&h!=="touch"&&(this.touch0[1]=x.invert(this.touch0[0])),this.touch1&&h!=="touch"&&(this.touch1[1]=x.invert(this.touch1[0])),this.that.__zoom=x,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(h){var x=_e(this.that).datum();l.call(h,this.that,new O_(h,{sourceEvent:this.sourceEvent,target:u,transform:this.that.__zoom,dispatch:l}),x)}};function M(h,...x){if(!e.apply(this,arguments))return;var P=p(this,x).event(h),v=this.__zoom,b=Math.max(s[0],Math.min(s[1],v.k*Math.pow(2,r.apply(this,arguments)))),y=Pe(h);if(P.wheel)(P.mouse[0][0]!==y[0]||P.mouse[0][1]!==y[1])&&(P.mouse[1]=v.invert(P.mouse[0]=y)),clearTimeout(P.wheel);else{if(v.k===b)return;P.mouse=[y,v.invert(y)],er(this),P.start()}zt(h),P.wheel=setTimeout(Y,d),P.zoom("mouse",n(N(f(v,b),P.mouse[0],P.mouse[1]),P.extent,i));function Y(){P.wheel=null,P.end()}}function B(h,...x){if(A||!e.apply(this,arguments))return;var P=h.currentTarget,v=p(this,x,!0).event(h),b=_e(h.view).on("mousemove.zoom",V,!0).on("mouseup.zoom",k,!0),y=Pe(h,P),Y=h.clientX,W=h.clientY;nl(h.view),Lo(h),v.mouse=[y,this.__zoom.invert(y)],er(this),v.start();function V(X){if(zt(X),!v.moved){var K=X.clientX-Y,Q=X.clientY-W;v.moved=K*K+Q*Q>I}v.event(X).zoom("mouse",n(N(v.that.__zoom,v.mouse[0]=Pe(X,P),v.mouse[1]),v.extent,i))}function k(X){b.on("mousemove.zoom mouseup.zoom",null),rl(X.view,v.moved),zt(X),v.event(X).end()}}function F(h,...x){if(e.apply(this,arguments)){var P=this.__zoom,v=Pe(h.changedTouches?h.changedTouches[0]:h,this),b=P.invert(v),y=P.k*(h.shiftKey?.5:2),Y=n(N(f(P,y),v,b),t.apply(this,x),i);zt(h),a>0?_e(this).transition().duration(a).call(m,Y,v,h):_e(this).call(u.transform,Y,v,h)}}function g(h,...x){if(e.apply(this,arguments)){var P=h.touches,v=P.length,b=p(this,x,h.changedTouches.length===v).event(h),y,Y,W,V;for(Lo(h),Y=0;Y<v;++Y)W=P[Y],V=Pe(W,this),V=[V,this.__zoom.invert(V),W.identifier],b.touch0?!b.touch1&&b.touch0[2]!==V[2]&&(b.touch1=V,b.taps=0):(b.touch0=V,y=!0,b.taps=1+!!R);R&&(R=clearTimeout(R)),y&&(b.taps<2&&(c=V[0],R=setTimeout(function(){R=null},S)),er(this),b.start())}}function _(h,...x){if(this.__zooming){var P=p(this,x).event(h),v=h.changedTouches,b=v.length,y,Y,W,V;for(zt(h),y=0;y<b;++y)Y=v[y],W=Pe(Y,this),P.touch0&&P.touch0[2]===Y.identifier?P.touch0[0]=W:P.touch1&&P.touch1[2]===Y.identifier&&(P.touch1[0]=W);if(Y=P.that.__zoom,P.touch1){var k=P.touch0[0],X=P.touch0[1],K=P.touch1[0],Q=P.touch1[1],j=(j=K[0]-k[0])*j+(j=K[1]-k[1])*j,$=($=Q[0]-X[0])*$+($=Q[1]-X[1])*$;Y=f(Y,Math.sqrt(j/$)),W=[(k[0]+K[0])/2,(k[1]+K[1])/2],V=[(X[0]+Q[0])/2,(X[1]+Q[1])/2]}else if(P.touch0)W=P.touch0[0],V=P.touch0[1];else return;P.zoom("touch",n(N(Y,W,V),P.extent,i))}}function U(h,...x){if(this.__zooming){var P=p(this,x).event(h),v=h.changedTouches,b=v.length,y,Y;for(Lo(h),A&&clearTimeout(A),A=setTimeout(function(){A=null},S),y=0;y<b;++y)Y=v[y],P.touch0&&P.touch0[2]===Y.identifier?delete P.touch0:P.touch1&&P.touch1[2]===Y.identifier&&delete P.touch1;if(P.touch1&&!P.touch0&&(P.touch0=P.touch1,delete P.touch1),P.touch0)P.touch0[1]=this.__zoom.invert(P.touch0[0]);else if(P.end(),P.taps===2&&(Y=Pe(Y,this),Math.hypot(c[0]-Y[0],c[1]-Y[1])<O)){var W=_e(this).on("dblclick.zoom");W&&W.apply(this,arguments)}}}return u.wheelDelta=function(h){return arguments.length?(r=typeof h=="function"?h:wn(+h),u):r},u.filter=function(h){return arguments.length?(e=typeof h=="function"?h:wn(!!h),u):e},u.touchable=function(h){return arguments.length?(o=typeof h=="function"?h:wn(!!h),u):o},u.extent=function(h){return arguments.length?(t=typeof h=="function"?h:wn([[+h[0][0],+h[0][1]],[+h[1][0],+h[1][1]]]),u):t},u.scaleExtent=function(h){return arguments.length?(s[0]=+h[0],s[1]=+h[1],u):[s[0],s[1]]},u.translateExtent=function(h){return arguments.length?(i[0][0]=+h[0][0],i[1][0]=+h[1][0],i[0][1]=+h[0][1],i[1][1]=+h[1][1],u):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},u.constrain=function(h){return arguments.length?(n=h,u):n},u.duration=function(h){return arguments.length?(a=+h,u):a},u.interpolate=function(h){return arguments.length?(T=h,u):T},u.on=function(){var h=l.on.apply(l,arguments);return h===l?u:h},u.clickDistance=function(h){return arguments.length?(I=(h=+h)*h,u):Math.sqrt(I)},u.tapDistance=function(h){return arguments.length?(O=+h,u):O},u}const we={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."},An=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],fl=["Enter"," ","Escape"],Cl={"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 xt;(function(e){e.Strict="strict",e.Loose="loose"})(xt||(xt={}));var ct;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(ct||(ct={}));var Sn;(function(e){e.Partial="partial",e.Full="full"})(Sn||(Sn={}));const Ll={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var et;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(et||(et={}));var dn;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(dn||(dn={}));var Z;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(Z||(Z={}));const aE={[Z.Left]:Z.Right,[Z.Right]:Z.Left,[Z.Top]:Z.Bottom,[Z.Bottom]:Z.Top};function hl(e){return e===null?null:e?"valid":"invalid"}const _l=e=>"id"in e&&"source"in e&&"target"in e,p_=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),hs=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),hn=(e,t=[0,0])=>{const{width:n,height:r}=ze(e),o=e.origin??t,s=n*o[0],i=r*o[1];return{x:e.position.x-s,y:e.position.y-i}},m_=(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 i=!t.nodeLookup&&!s?o:void 0;t.nodeLookup&&(i=s?t.nodeLookup.get(o):hs(o)?o:t.nodeLookup.get(o.id));const a=i?dr(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return gr(r,a)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return Pr(n)},_n=(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=gr(n,dr(o)),r=!0)}),r?Pr(n):{x:0,y:0,width:0,height:0}},_s=(e,t,[n,r,o]=[0,0,1],s=!1,i=!1)=>{const a={...mn(t,[n,r,o]),width:t.width/o,height:t.height/o},T=[];for(const l of e.values()){const{measured:R,selectable:c=!0,hidden:A=!1}=l;if(i&&!c||A)continue;const S=R.width??l.width??l.initialWidth??null,d=R.height??l.height??l.initialHeight??null,I=In(a,bt(l)),O=(S??0)*(d??0),u=s&&I>0;(!l.internals.handleBounds||u||I>=O||l.dragging)&&T.push(l)}return T},D_=(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 g_(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 P_({nodes:e,width:t,height:n,panZoom:r,minZoom:o,maxZoom:s},i){if(e.size===0)return Promise.resolve(!0);const a=g_(e,i),T=_n(a),l=ps(T,t,n,(i==null?void 0:i.minZoom)??o,(i==null?void 0:i.maxZoom)??s,(i==null?void 0:i.padding)??.1);return await r.setViewport(l,{duration:i==null?void 0:i.duration,ease:i==null?void 0:i.ease,interpolate:i==null?void 0:i.interpolate}),Promise.resolve(!0)}function pl({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:o,onError:s}){const i=n.get(e),a=i.parentId?n.get(i.parentId):void 0,{x:T,y:l}=a?a.internals.positionAbsolute:{x:0,y:0},R=i.origin??r;let c=i.extent||o;if(i.extent==="parent"&&!i.expandParent)if(!a)s==null||s("005",we.error005());else{const S=a.measured.width,d=a.measured.height;S&&d&&(c=[[T,l],[T+S,l+d]])}else a&&Gt(i.extent)&&(c=[[i.extent[0][0]+T,i.extent[0][1]+l],[i.extent[1][0]+T,i.extent[1][1]+l]]);const A=Gt(c)?St(t,c,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&(s==null||s("015",we.error015())),{position:{x:A.x-T+(i.measured.width??0)*R[0],y:A.y-l+(i.measured.height??0)*R[1]},positionAbsolute:A}}async function M_({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:o}){const s=new Set(e.map(A=>A.id)),i=[];for(const A of n){if(A.deletable===!1)continue;const S=s.has(A.id),d=!S&&A.parentId&&i.find(I=>I.id===A.parentId);(S||d)&&i.push(A)}const a=new Set(t.map(A=>A.id)),T=r.filter(A=>A.deletable!==!1),R=D_(i,T);for(const A of T)a.has(A.id)&&!R.find(d=>d.id===A.id)&&R.push(A);if(!o)return{edges:R,nodes:i};const c=await o({nodes:i,edges:R});return typeof c=="boolean"?c?{edges:R,nodes:i}:{edges:[],nodes:[]}:c}const Ut=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),St=(e={x:0,y:0},t,n)=>({x:Ut(e.x,t[0][0],t[1][0]-((n==null?void 0:n.width)??0)),y:Ut(e.y,t[0][1],t[1][1]-((n==null?void 0:n.height)??0))});function ml(e,t,n){const{width:r,height:o}=ze(n),{x:s,y:i}=n.internals.positionAbsolute;return St(e,[[s,i],[s+r,i+o]],t)}const lE=(e,t,n)=>e<t?Ut(Math.abs(e-t),1,t)/t:e>n?-Ut(Math.abs(e-n),1,t)/t:0,Dl=(e,t,n=15,r=40)=>{const o=lE(e.x,r,t.width-r)*n,s=lE(e.y,r,t.height-r)*n;return[o,s]},gr=(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)}),Zo=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),Pr=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),bt=(e,t=[0,0])=>{var o,s;const{x:n,y:r}=hs(e)?e.internals.positionAbsolute:hn(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}},dr=(e,t=[0,0])=>{var o,s;const{x:n,y:r}=hs(e)?e.internals.positionAbsolute:hn(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)}},gl=(e,t)=>Pr(gr(Zo(e),Zo(t))),In=(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)},TE=e=>ye(e.width)&&ye(e.height)&&ye(e.x)&&ye(e.y),ye=e=>!isNaN(e)&&isFinite(e),y_=(e,t)=>{},pn=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),mn=({x:e,y:t},[n,r,o],s=!1,i=[1,1])=>{const a={x:(e-n)/o,y:(t-r)/o};return s?pn(a,i):a},Ir=({x:e,y:t},[n,r,o])=>({x:e*o+n,y:t*o+r});function Lt(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 x_(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=Lt(e,n),o=Lt(e,t);return{top:r,right:o,bottom:r,left:o,x:o*2,y:r*2}}if(typeof e=="object"){const r=Lt(e.top??e.y??0,n),o=Lt(e.bottom??e.y??0,n),s=Lt(e.left??e.x??0,t),i=Lt(e.right??e.x??0,t);return{top:r,right:i,bottom:o,left:s,x:s+i,y:r+o}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function U_(e,t,n,r,o,s){const{x:i,y:a}=Ir(e,[t,n,r]),{x:T,y:l}=Ir({x:e.x+e.width,y:e.y+e.height},[t,n,r]),R=o-T,c=s-l;return{left:Math.floor(i),top:Math.floor(a),right:Math.floor(R),bottom:Math.floor(c)}}const ps=(e,t,n,r,o,s)=>{const i=x_(s,t,n),a=(t-i.x)/e.width,T=(n-i.y)/e.height,l=Math.min(a,T),R=Ut(l,r,o),c=e.x+e.width/2,A=e.y+e.height/2,S=t/2-c*R,d=n/2-A*R,I=U_(e,S,d,R,t,n),O={left:Math.min(I.left-i.left,0),top:Math.min(I.top-i.top,0),right:Math.min(I.right-i.right,0),bottom:Math.min(I.bottom-i.bottom,0)};return{x:S-O.left+O.right,y:d-O.top+O.bottom,zoom:R}},un=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0};function Gt(e){return e!=null&&e!=="parent"}function ze(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 Pl(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 Ml(e,t={width:0,height:0},n,r,o){const s={...e},i=r.get(n);if(i){const a=i.origin||o;s.x+=i.internals.positionAbsolute.x-(t.width??0)*a[0],s.y+=i.internals.positionAbsolute.y-(t.height??0)*a[1]}return s}function cE(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function b_(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}function G_(e){return{...Cl,...e||{}}}function rn(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:o}){const{x:s,y:i}=xe(e),a=mn({x:s-((o==null?void 0:o.left)??0),y:i-((o==null?void 0:o.top)??0)},r),{x:T,y:l}=n?pn(a,t):a;return{xSnapped:T,ySnapped:l,...a}}const ms=e=>({width:e.offsetWidth,height:e.offsetHeight}),yl=e=>{var t;return((t=e==null?void 0:e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},B_=["INPUT","SELECT","TEXTAREA"];function xl(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:B_.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const Ul=e=>"clientX"in e,xe=(e,t)=>{var s,i;const n=Ul(e),r=n?e.clientX:(s=e.touches)==null?void 0:s[0].clientX,o=n?e.clientY:(i=e.touches)==null?void 0:i[0].clientY;return{x:r-((t==null?void 0:t.left)??0),y:o-((t==null?void 0:t.top)??0)}},RE=(e,t,n,r,o)=>{const s=t.querySelectorAll(`.${e}`);return!s||!s.length?null:Array.from(s).map(i=>{const a=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:o,position:i.getAttribute("data-handlepos"),x:(a.left-n.left)/r,y:(a.top-n.top)/r,...ms(i)}})};function bl({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:o,sourceControlY:s,targetControlX:i,targetControlY:a}){const T=e*.125+o*.375+i*.375+n*.125,l=t*.125+s*.375+a*.375+r*.125,R=Math.abs(T-e),c=Math.abs(l-t);return[T,l,R,c]}function Yn(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function AE({pos:e,x1:t,y1:n,x2:r,y2:o,c:s}){switch(e){case Z.Left:return[t-Yn(t-r,s),n];case Z.Right:return[t+Yn(r-t,s),n];case Z.Top:return[t,n-Yn(n-o,s)];case Z.Bottom:return[t,n+Yn(o-n,s)]}}function Gl({sourceX:e,sourceY:t,sourcePosition:n=Z.Bottom,targetX:r,targetY:o,targetPosition:s=Z.Top,curvature:i=.25}){const[a,T]=AE({pos:n,x1:e,y1:t,x2:r,y2:o,c:i}),[l,R]=AE({pos:s,x1:r,y1:o,x2:e,y2:t,c:i}),[c,A,S,d]=bl({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:a,sourceControlY:T,targetControlX:l,targetControlY:R});return[`M${e},${t} C${a},${T} ${l},${R} ${r},${o}`,c,A,S,d]}function Bl({sourceX:e,sourceY:t,targetX:n,targetY:r}){const o=Math.abs(n-e)/2,s=n<e?n+o:n-o,i=Math.abs(r-t)/2,a=r<t?r+i:r-i;return[s,a,o,i]}function v_({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:o=!1,zIndexMode:s="basic"}){if(s==="manual")return r;const i=o&&n?r+1e3:r,a=Math.max(e.parentId||o&&e.selected?e.internals.z:0,t.parentId||o&&t.selected?t.internals.z:0);return i+a}function H_({sourceNode:e,targetNode:t,width:n,height:r,transform:o}){const s=gr(dr(e),dr(t));s.x===s.x2&&(s.x2+=1),s.y===s.y2&&(s.y2+=1);const i={x:-o[0]/o[2],y:-o[1]/o[2],width:n/o[2],height:r/o[2]};return In(i,Pr(s))>0}const F_=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,w_=(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)),Y_=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||F_;let o;return _l(e)?o={...e}:o={...e,id:r(e)},w_(o,t)?t:(o.sourceHandle===null&&delete o.sourceHandle,o.targetHandle===null&&delete o.targetHandle,t.concat(o))};function vl({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[o,s,i,a]=Bl({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,o,s,i,a]}const SE={[Z.Left]:{x:-1,y:0},[Z.Right]:{x:1,y:0},[Z.Top]:{x:0,y:-1},[Z.Bottom]:{x:0,y:1}},V_=({source:e,sourcePosition:t=Z.Bottom,target:n})=>t===Z.Left||t===Z.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},dE=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function W_({source:e,sourcePosition:t=Z.Bottom,target:n,targetPosition:r=Z.Top,center:o,offset:s,stepPosition:i}){const a=SE[t],T=SE[r],l={x:e.x+a.x*s,y:e.y+a.y*s},R={x:n.x+T.x*s,y:n.y+T.y*s},c=V_({source:l,sourcePosition:t,target:R}),A=c.x!==0?"x":"y",S=c[A];let d=[],I,O;const u={x:0,y:0},f={x:0,y:0},[,,N,L]=Bl({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(a[A]*T[A]===-1){A==="x"?(I=o.x??l.x+(R.x-l.x)*i,O=o.y??(l.y+R.y)/2):(I=o.x??(l.x+R.x)/2,O=o.y??l.y+(R.y-l.y)*i);const p=[{x:I,y:l.y},{x:I,y:R.y}],D=[{x:l.x,y:O},{x:R.x,y:O}];a[A]===S?d=A==="x"?p:D:d=A==="x"?D:p}else{const p=[{x:l.x,y:R.y}],D=[{x:R.x,y:l.y}];if(A==="x"?d=a.x===S?D:p:d=a.y===S?p:D,t===r){const _=Math.abs(e[A]-n[A]);if(_<=s){const U=Math.min(s-1,s-_);a[A]===S?u[A]=(l[A]>e[A]?-1:1)*U:f[A]=(R[A]>n[A]?-1:1)*U}}if(t!==r){const _=A==="x"?"y":"x",U=a[A]===T[_],h=l[_]>R[_],x=l[_]<R[_];(a[A]===1&&(!U&&h||U&&x)||a[A]!==1&&(!U&&x||U&&h))&&(d=A==="x"?p:D)}const M={x:l.x+u.x,y:l.y+u.y},B={x:R.x+f.x,y:R.y+f.y},F=Math.max(Math.abs(M.x-d[0].x),Math.abs(B.x-d[0].x)),g=Math.max(Math.abs(M.y-d[0].y),Math.abs(B.y-d[0].y));F>=g?(I=(M.x+B.x)/2,O=d[0].y):(I=d[0].x,O=(M.y+B.y)/2)}return[[e,{x:l.x+u.x,y:l.y+u.y},...d,{x:R.x+f.x,y:R.y+f.y},n],I,O,N,L]}function k_(e,t,n,r){const o=Math.min(dE(e,t)/2,dE(t,n)/2,r),{x:s,y:i}=t;if(e.x===s&&s===n.x||e.y===i&&i===n.y)return`L${s} ${i}`;if(e.y===i){const l=e.x<n.x?-1:1,R=e.y<n.y?1:-1;return`L ${s+o*l},${i}Q ${s},${i} ${s},${i+o*R}`}const a=e.x<n.x?1:-1,T=e.y<n.y?-1:1;return`L ${s},${i+o*T}Q ${s},${i} ${s+o*a},${i}`}function Qo({sourceX:e,sourceY:t,sourcePosition:n=Z.Bottom,targetX:r,targetY:o,targetPosition:s=Z.Top,borderRadius:i=5,centerX:a,centerY:T,offset:l=20,stepPosition:R=.5}){const[c,A,S,d,I]=W_({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:o},targetPosition:s,center:{x:a,y:T},offset:l,stepPosition:R});return[c.reduce((u,f,N)=>{let L="";return N>0&&N<c.length-1?L=k_(c[N-1],f,c[N+1],i):L=`${N===0?"M":"L"}${f.x} ${f.y}`,u+=L,u},""),A,S,d,I]}function IE(e){var t;return e&&!!(e.internals.handleBounds||(t=e.handles)!=null&&t.length)&&!!(e.measured.width||e.width||e.initialWidth)}function X_(e){var c;const{sourceNode:t,targetNode:n}=e;if(!IE(t)||!IE(n))return null;const r=t.internals.handleBounds||uE(t.handles),o=n.internals.handleBounds||uE(n.handles),s=NE((r==null?void 0:r.source)??[],e.sourceHandle),i=NE(e.connectionMode===xt.Strict?(o==null?void 0:o.target)??[]:((o==null?void 0:o.target)??[]).concat((o==null?void 0:o.source)??[]),e.targetHandle);if(!s||!i)return(c=e.onError)==null||c.call(e,"008",we.error008(s?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const a=(s==null?void 0:s.position)||Z.Bottom,T=(i==null?void 0:i.position)||Z.Top,l=dt(t,s,a),R=dt(n,i,T);return{sourceX:l.x,sourceY:l.y,targetX:R.x,targetY:R.y,sourcePosition:a,targetPosition:T}}function uE(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 dt(e,t,n=Z.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:i,height:a}=t??ze(e);if(r)return{x:o+i/2,y:s+a/2};switch((t==null?void 0:t.position)??n){case Z.Top:return{x:o+i/2,y:s};case Z.Right:return{x:o+i,y:s+a/2};case Z.Bottom:return{x:o+i/2,y:s+a};case Z.Left:return{x:o,y:s+a/2}}}function NE(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function es(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function j_(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:o}){const s=new Set;return e.reduce((i,a)=>([a.markerStart||r,a.markerEnd||o].forEach(T=>{if(T&&typeof T=="object"){const l=es(T,t);s.has(l)||(i.push({id:l,color:T.color||n,...T}),s.add(l))}}),i),[]).sort((i,a)=>i.id.localeCompare(a.id))}const Hl=1e3,$_=10,Ds={nodeOrigin:[0,0],nodeExtent:An,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},K_={...Ds,checkEquality:!0};function gs(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function J_(e,t,n){const r=gs(Ds,n);for(const o of e.values())if(o.parentId)Ms(o,e,t,r);else{const s=hn(o,r.nodeOrigin),i=Gt(o.extent)?o.extent:r.nodeExtent,a=St(s,i,ze(o));o.internals.positionAbsolute=a}}function z_(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 Ps(e){return e==="manual"}function ts(e,t,n,r={}){var l,R;const o=gs(K_,r),s={i:0},i=new Map(t),a=o!=null&&o.elevateNodesOnSelect&&!Ps(o.zIndexMode)?Hl:0;let T=e.length>0;t.clear(),n.clear();for(const c of e){let A=i.get(c.id);if(o.checkEquality&&c===(A==null?void 0:A.internals.userNode))t.set(c.id,A);else{const S=hn(c,o.nodeOrigin),d=Gt(c.extent)?c.extent:o.nodeExtent,I=St(S,d,ze(c));A={...o.defaults,...c,measured:{width:(l=c.measured)==null?void 0:l.width,height:(R=c.measured)==null?void 0:R.height},internals:{positionAbsolute:I,handleBounds:z_(c,A),z:Fl(c,a,o.zIndexMode),userNode:c}},t.set(c.id,A)}(A.measured===void 0||A.measured.width===void 0||A.measured.height===void 0)&&!A.hidden&&(T=!1),c.parentId&&Ms(A,t,n,r,s)}return T}function q_(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 Ms(e,t,n,r,o){const{elevateNodesOnSelect:s,nodeOrigin:i,nodeExtent:a,zIndexMode:T}=gs(Ds,r),l=e.parentId,R=t.get(l);if(!R){console.warn(`Parent node ${l} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}q_(e,n),o&&!R.parentId&&R.internals.rootParentIndex===void 0&&T==="auto"&&(R.internals.rootParentIndex=++o.i,R.internals.z=R.internals.z+o.i*$_),o&&R.internals.rootParentIndex!==void 0&&(o.i=R.internals.rootParentIndex);const c=s&&!Ps(T)?Hl:0,{x:A,y:S,z:d}=Z_(e,R,i,a,c,T),{positionAbsolute:I}=e.internals,O=A!==I.x||S!==I.y;(O||d!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:O?{x:A,y:S}:I,z:d}})}function Fl(e,t,n){const r=ye(e.zIndex)?e.zIndex:0;return Ps(n)?r:r+(e.selected?t:0)}function Z_(e,t,n,r,o,s){const{x:i,y:a}=t.internals.positionAbsolute,T=ze(e),l=hn(e,n),R=Gt(e.extent)?St(l,e.extent,T):l;let c=St({x:i+R.x,y:a+R.y},r,T);e.extent==="parent"&&(c=ml(c,T,t));const A=Fl(e,o,s),S=t.internals.z??0;return{x:c.x,y:c.y,z:S>=A?S+1:A}}function ys(e,t,n,r=[0,0]){var i;const o=[],s=new Map;for(const a of e){const T=t.get(a.parentId);if(!T)continue;const l=((i=s.get(a.parentId))==null?void 0:i.expandedRect)??bt(T),R=gl(l,a.rect);s.set(a.parentId,{expandedRect:R,parent:T})}return s.size>0&&s.forEach(({expandedRect:a,parent:T},l)=>{var N;const R=T.internals.positionAbsolute,c=ze(T),A=T.origin??r,S=a.x<R.x?Math.round(Math.abs(R.x-a.x)):0,d=a.y<R.y?Math.round(Math.abs(R.y-a.y)):0,I=Math.max(c.width,Math.round(a.width)),O=Math.max(c.height,Math.round(a.height)),u=(I-c.width)*A[0],f=(O-c.height)*A[1];(S>0||d>0||u||f)&&(o.push({id:l,type:"position",position:{x:T.position.x-S+u,y:T.position.y-d+f}}),(N=n.get(l))==null||N.forEach(L=>{e.some(m=>m.id===L.id)||o.push({id:L.id,type:"position",position:{x:L.position.x+S,y:L.position.y+d}})})),(c.width<a.width||c.height<a.height||S||d)&&o.push({id:l,type:"dimensions",setAttributes:!0,dimensions:{width:I+(S?A[0]*S-u:0),height:O+(d?A[1]*d-f:0)}})}),o}function Q_(e,t,n,r,o,s,i){const a=r==null?void 0:r.querySelector(".xyflow__viewport");let T=!1;if(!a)return{changes:[],updatedInternals:T};const l=[],R=window.getComputedStyle(a),{m22:c}=new window.DOMMatrixReadOnly(R.transform),A=[];for(const S of e.values()){const d=t.get(S.id);if(!d)continue;if(d.hidden){t.set(d.id,{...d,internals:{...d.internals,handleBounds:void 0}}),T=!0;continue}const I=ms(S.nodeElement),O=d.measured.width!==I.width||d.measured.height!==I.height;if(!!(I.width&&I.height&&(O||!d.internals.handleBounds||S.force))){const f=S.nodeElement.getBoundingClientRect(),N=Gt(d.extent)?d.extent:s;let{positionAbsolute:L}=d.internals;d.parentId&&d.extent==="parent"?L=ml(L,I,t.get(d.parentId)):N&&(L=St(L,N,I));const m={...d,measured:I,internals:{...d.internals,positionAbsolute:L,handleBounds:{source:RE("source",S.nodeElement,f,c,d.id),target:RE("target",S.nodeElement,f,c,d.id)}}};t.set(d.id,m),d.parentId&&Ms(m,t,n,{nodeOrigin:o,zIndexMode:i}),T=!0,O&&(l.push({id:d.id,type:"dimensions",dimensions:I}),d.expandParent&&d.parentId&&A.push({id:d.id,parentId:d.parentId,rect:bt(m,o)}))}}if(A.length>0){const S=ys(A,t,n,o);l.push(...S)}return{changes:l,updatedInternals:T}}async function ep({delta:e,panZoom:t,transform:n,translateExtent:r,width:o,height:s}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const i=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[o,s]],r),a=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(a)}function OE(e,t,n,r,o,s){let i=o;const a=r.get(i)||new Map;r.set(i,a.set(n,t)),i=`${o}-${e}`;const T=r.get(i)||new Map;if(r.set(i,T.set(n,t)),s){i=`${o}-${e}-${s}`;const l=r.get(i)||new Map;r.set(i,l.set(n,t))}}function wl(e,t,n){e.clear(),t.clear();for(const r of n){const{source:o,target:s,sourceHandle:i=null,targetHandle:a=null}=r,T={edgeId:r.id,source:o,target:s,sourceHandle:i,targetHandle:a},l=`${o}-${i}--${s}-${a}`,R=`${s}-${a}--${o}-${i}`;OE("source",T,R,e,o,i),OE("target",T,l,e,s,a),t.set(r.id,r)}}function Yl(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:Yl(n,t):!1}function fE(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 tp(e,t,n,r){const o=new Map;for(const[s,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!Yl(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const a=e.get(s);a&&o.set(s,{id:s,position:a.position||{x:0,y:0},distance:{x:n.x-a.internals.positionAbsolute.x,y:n.y-a.internals.positionAbsolute.y},extent:a.extent,parentId:a.parentId,origin:a.origin,expandParent:a.expandParent,internals:{positionAbsolute:a.internals.positionAbsolute||{x:0,y:0}},measured:{width:a.measured.width??0,height:a.measured.height??0}})}return o}function ho({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){var i,a,T;const o=[];for(const[l,R]of t){const c=(i=n.get(l))==null?void 0:i.internals.userNode;c&&o.push({...c,position:R.position,dragging:r})}if(!e)return[o[0],o];const s=(a=n.get(e))==null?void 0:a.internals.userNode;return[s?{...s,position:((T=t.get(e))==null?void 0:T.position)||s.position,dragging:r}:o[0],o]}function np({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},i=pn(s,t);return{x:i.x-s.x,y:i.y-s.y}}function rp({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:o}){let s={x:null,y:null},i=0,a=new Map,T=!1,l={x:0,y:0},R=null,c=!1,A=null,S=!1,d=!1,I=null;function O({noDragClassName:f,handleSelector:N,domNode:L,isSelectable:m,nodeId:p,nodeClickDistance:D=0}){A=_e(L);function M({x:_,y:U}){const{nodeLookup:h,nodeExtent:x,snapGrid:P,snapToGrid:v,nodeOrigin:b,onNodeDrag:y,onSelectionDrag:Y,onError:W,updateNodePositions:V}=t();s={x:_,y:U};let k=!1;const X=a.size>1,K=X&&x?Zo(_n(a)):null,Q=X&&v?np({dragItems:a,snapGrid:P,x:_,y:U}):null;for(const[j,$]of a){if(!h.has(j))continue;let ee={x:_-$.distance.x,y:U-$.distance.y};v&&(ee=Q?{x:Math.round(ee.x+Q.x),y:Math.round(ee.y+Q.y)}:pn(ee,P));let re=null;if(X&&x&&!$.extent&&K){const{positionAbsolute:te}=$.internals,Ee=te.x-K.x+x[0][0],le=te.x+$.measured.width-K.x2+x[1][0],se=te.y-K.y+x[0][1],Ne=te.y+$.measured.height-K.y2+x[1][1];re=[[Ee,se],[le,Ne]]}const{position:q,positionAbsolute:z}=pl({nodeId:j,nextPosition:ee,nodeLookup:h,nodeExtent:re||x,nodeOrigin:b,onError:W});k=k||$.position.x!==q.x||$.position.y!==q.y,$.position=q,$.internals.positionAbsolute=z}if(d=d||k,!!k&&(V(a,!0),I&&(r||y||!p&&Y))){const[j,$]=ho({nodeId:p,dragItems:a,nodeLookup:h});r==null||r(I,a,j,$),y==null||y(I,j,$),p||Y==null||Y(I,$)}}async function B(){if(!R)return;const{transform:_,panBy:U,autoPanSpeed:h,autoPanOnNodeDrag:x}=t();if(!x){T=!1,cancelAnimationFrame(i);return}const[P,v]=Dl(l,R,h);(P!==0||v!==0)&&(s.x=(s.x??0)-P/_[2],s.y=(s.y??0)-v/_[2],await U({x:P,y:v})&&M(s)),i=requestAnimationFrame(B)}function F(_){var X;const{nodeLookup:U,multiSelectionActive:h,nodesDraggable:x,transform:P,snapGrid:v,snapToGrid:b,selectNodesOnDrag:y,onNodeDragStart:Y,onSelectionDragStart:W,unselectNodesAndEdges:V}=t();c=!0,(!y||!m)&&!h&&p&&((X=U.get(p))!=null&&X.selected||V()),m&&y&&p&&(e==null||e(p));const k=rn(_.sourceEvent,{transform:P,snapGrid:v,snapToGrid:b,containerBounds:R});if(s=k,a=tp(U,x,k,p),a.size>0&&(n||Y||!p&&W)){const[K,Q]=ho({nodeId:p,dragItems:a,nodeLookup:U});n==null||n(_.sourceEvent,a,K,Q),Y==null||Y(_.sourceEvent,K,Q),p||W==null||W(_.sourceEvent,Q)}}const g=ol().clickDistance(D).on("start",_=>{const{domNode:U,nodeDragThreshold:h,transform:x,snapGrid:P,snapToGrid:v}=t();R=(U==null?void 0:U.getBoundingClientRect())||null,S=!1,d=!1,I=_.sourceEvent,h===0&&F(_),s=rn(_.sourceEvent,{transform:x,snapGrid:P,snapToGrid:v,containerBounds:R}),l=xe(_.sourceEvent,R)}).on("drag",_=>{const{autoPanOnNodeDrag:U,transform:h,snapGrid:x,snapToGrid:P,nodeDragThreshold:v,nodeLookup:b}=t(),y=rn(_.sourceEvent,{transform:h,snapGrid:x,snapToGrid:P,containerBounds:R});if(I=_.sourceEvent,(_.sourceEvent.type==="touchmove"&&_.sourceEvent.touches.length>1||p&&!b.has(p))&&(S=!0),!S){if(!T&&U&&c&&(T=!0,B()),!c){const Y=xe(_.sourceEvent,R),W=Y.x-l.x,V=Y.y-l.y;Math.sqrt(W*W+V*V)>v&&F(_)}(s.x!==y.xSnapped||s.y!==y.ySnapped)&&a&&c&&(l=xe(_.sourceEvent,R),M(y))}}).on("end",_=>{if(!(!c||S)&&(T=!1,c=!1,cancelAnimationFrame(i),a.size>0)){const{nodeLookup:U,updateNodePositions:h,onNodeDragStop:x,onSelectionDragStop:P}=t();if(d&&(h(a,!1),d=!1),o||x||!p&&P){const[v,b]=ho({nodeId:p,dragItems:a,nodeLookup:U,dragging:!1});o==null||o(_.sourceEvent,a,v,b),x==null||x(_.sourceEvent,v,b),p||P==null||P(_.sourceEvent,b)}}}).filter(_=>{const U=_.target;return!_.button&&(!f||!fE(U,`.${f}`,L))&&(!N||fE(U,N,L))});A.call(g)}function u(){A==null||A.on(".drag",null)}return{update:O,destroy:u}}function op(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())In(o,bt(s))>0&&r.push(s);return r}const sp=250;function ip(e,t,n,r){var a,T;let o=[],s=1/0;const i=op(e,n,t+sp);for(const l of i){const R=[...((a=l.internals.handleBounds)==null?void 0:a.source)??[],...((T=l.internals.handleBounds)==null?void 0:T.target)??[]];for(const c of R){if(r.nodeId===c.nodeId&&r.type===c.type&&r.id===c.id)continue;const{x:A,y:S}=dt(l,c,c.position,!0),d=Math.sqrt(Math.pow(A-e.x,2)+Math.pow(S-e.y,2));d>t||(d<s?(o=[{...c,x:A,y:S}],s=d):d===s&&o.push({...c,x:A,y:S}))}}if(!o.length)return null;if(o.length>1){const l=r.type==="source"?"target":"source";return o.find(R=>R.type===l)??o[0]}return o[0]}function Vl(e,t,n,r,o,s=!1){var l,R,c;const i=r.get(e);if(!i)return null;const a=o==="strict"?(l=i.internals.handleBounds)==null?void 0:l[t]:[...((R=i.internals.handleBounds)==null?void 0:R.source)??[],...((c=i.internals.handleBounds)==null?void 0:c.target)??[]],T=(n?a==null?void 0:a.find(A=>A.id===n):a==null?void 0:a[0])??null;return T&&s?{...T,...dt(i,T,T.position,!0)}:T}function Wl(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function Ep(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const kl=()=>!0;function ap(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:o,edgeUpdaterType:s,isTarget:i,domNode:a,nodeLookup:T,lib:l,autoPanOnConnect:R,flowId:c,panBy:A,cancelConnection:S,onConnectStart:d,onConnect:I,onConnectEnd:O,isValidConnection:u=kl,onReconnectEnd:f,updateConnection:N,getTransform:L,getFromHandle:m,autoPanSpeed:p,dragThreshold:D=1,handleDomNode:M}){const B=yl(e.target);let F=0,g;const{x:_,y:U}=xe(e),h=Wl(s,M),x=a==null?void 0:a.getBoundingClientRect();let P=!1;if(!x||!h)return;const v=Vl(o,h,r,T,t);if(!v)return;let b=xe(e,x),y=!1,Y=null,W=!1,V=null;function k(){if(!R||!x)return;const[q,z]=Dl(b,x,p);A({x:q,y:z}),F=requestAnimationFrame(k)}const X={...v,nodeId:o,type:h,position:v.position},K=T.get(o);let j={inProgress:!0,isValid:null,from:dt(K,X,Z.Left,!0),fromHandle:X,fromPosition:X.position,fromNode:K,to:b,toHandle:null,toPosition:aE[X.position],toNode:null,pointer:b};function $(){P=!0,N(j),d==null||d(e,{nodeId:o,handleId:r,handleType:h})}D===0&&$();function ee(q){if(!P){const{x:Ne,y:qe}=xe(q),Ve=Ne-_,it=qe-U;if(!(Ve*Ve+it*it>D*D))return;$()}if(!m()||!X){re(q);return}const z=L();b=xe(q,x),g=ip(mn(b,z,!1,[1,1]),n,T,X),y||(k(),y=!0);const te=Xl(q,{handle:g,connectionMode:t,fromNodeId:o,fromHandleId:r,fromType:i?"target":"source",isValidConnection:u,doc:B,lib:l,flowId:c,nodeLookup:T});V=te.handleDomNode,Y=te.connection,W=Ep(!!g,te.isValid);const Ee=T.get(o),le=Ee?dt(Ee,X,Z.Left,!0):j.from,se={...j,from:le,isValid:W,to:te.toHandle&&W?Ir({x:te.toHandle.x,y:te.toHandle.y},z):b,toHandle:te.toHandle,toPosition:W&&te.toHandle?te.toHandle.position:aE[X.position],toNode:te.toHandle?T.get(te.toHandle.nodeId):null,pointer:b};N(se),j=se}function re(q){if(!("touches"in q&&q.touches.length>0)){if(P){(g||V)&&Y&&W&&(I==null||I(Y));const{inProgress:z,...te}=j,Ee={...te,toPosition:j.toHandle?j.toPosition:null};O==null||O(q,Ee),s&&(f==null||f(q,Ee))}S(),cancelAnimationFrame(F),y=!1,W=!1,Y=null,V=null,B.removeEventListener("mousemove",ee),B.removeEventListener("mouseup",re),B.removeEventListener("touchmove",ee),B.removeEventListener("touchend",re)}}B.addEventListener("mousemove",ee),B.addEventListener("mouseup",re),B.addEventListener("touchmove",ee),B.addEventListener("touchend",re)}function Xl(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:o,fromType:s,doc:i,lib:a,flowId:T,isValidConnection:l=kl,nodeLookup:R}){const c=s==="target",A=t?i.querySelector(`.${a}-flow__handle[data-id="${T}-${t==null?void 0:t.nodeId}-${t==null?void 0:t.id}-${t==null?void 0:t.type}"]`):null,{x:S,y:d}=xe(e),I=i.elementFromPoint(S,d),O=I!=null&&I.classList.contains(`${a}-flow__handle`)?I:A,u={handleDomNode:O,isValid:!1,connection:null,toHandle:null};if(O){const f=Wl(void 0,O),N=O.getAttribute("data-nodeid"),L=O.getAttribute("data-handleid"),m=O.classList.contains("connectable"),p=O.classList.contains("connectableend");if(!N||!f)return u;const D={source:c?N:r,sourceHandle:c?L:o,target:c?r:N,targetHandle:c?o:L};u.connection=D;const B=m&&p&&(n===xt.Strict?c&&f==="source"||!c&&f==="target":N!==r||L!==o);u.isValid=B&&l(D),u.toHandle=Vl(N,f,L,R,n,!0)}return u}const ns={onPointerDown:ap,isValid:Xl};function lp({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const o=_e(e);function s({translateExtent:a,width:T,height:l,zoomStep:R=1,pannable:c=!0,zoomable:A=!0,inversePan:S=!1}){const d=N=>{if(N.sourceEvent.type!=="wheel"||!t)return;const L=n(),m=N.sourceEvent.ctrlKey&&un()?10:1,p=-N.sourceEvent.deltaY*(N.sourceEvent.deltaMode===1?.05:N.sourceEvent.deltaMode?1:.002)*R,D=L[2]*Math.pow(2,p*m);t.scaleTo(D)};let I=[0,0];const O=N=>{(N.sourceEvent.type==="mousedown"||N.sourceEvent.type==="touchstart")&&(I=[N.sourceEvent.clientX??N.sourceEvent.touches[0].clientX,N.sourceEvent.clientY??N.sourceEvent.touches[0].clientY])},u=N=>{const L=n();if(N.sourceEvent.type!=="mousemove"&&N.sourceEvent.type!=="touchmove"||!t)return;const m=[N.sourceEvent.clientX??N.sourceEvent.touches[0].clientX,N.sourceEvent.clientY??N.sourceEvent.touches[0].clientY],p=[m[0]-I[0],m[1]-I[1]];I=m;const D=r()*Math.max(L[2],Math.log(L[2]))*(S?-1:1),M={x:L[0]-p[0]*D,y:L[1]-p[1]*D},B=[[0,0],[T,l]];t.setViewportConstrained({x:M.x,y:M.y,zoom:L[2]},B,a)},f=Ol().on("start",O).on("zoom",c?u:null).on("zoom.wheel",A?d:null);o.call(f,{})}function i(){o.on("zoom",null)}return{update:s,destroy:i,pointer:Pe}}const Mr=e=>({x:e.x,y:e.y,zoom:e.k}),_o=({x:e,y:t,zoom:n})=>Dr.translate(e,t).scale(n),pt=(e,t)=>e.target.closest(`.${t}`),jl=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),Tp=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,po=(e,t=0,n=Tp,r=()=>{})=>{const o=typeof t=="number"&&t>0;return o||r(),o?e.transition().duration(t).ease(n).on("end",r):e},$l=e=>{const t=e.ctrlKey&&un()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function cp({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:o,panOnScrollSpeed:s,zoomOnPinch:i,onPanZoomStart:a,onPanZoom:T,onPanZoomEnd:l}){return R=>{if(pt(R,t))return R.ctrlKey&&R.preventDefault(),!1;R.preventDefault(),R.stopImmediatePropagation();const c=n.property("__zoom").k||1;if(R.ctrlKey&&i){const O=Pe(R),u=$l(R),f=c*Math.pow(2,u);r.scaleTo(n,f,O,R);return}const A=R.deltaMode===1?20:1;let S=o===ct.Vertical?0:R.deltaX*A,d=o===ct.Horizontal?0:R.deltaY*A;!un()&&R.shiftKey&&o!==ct.Vertical&&(S=R.deltaY*A,d=0),r.translateBy(n,-(S/c)*s,-(d/c)*s,{internal:!0});const I=Mr(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(T==null||T(R,I),e.panScrollTimeout=setTimeout(()=>{l==null||l(R,I),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,a==null||a(R,I))}}function Rp({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,o){const s=r.type==="wheel",i=!t&&s&&!r.ctrlKey,a=pt(r,e);if(r.ctrlKey&&s&&a&&r.preventDefault(),i||a)return null;r.preventDefault(),n.call(this,r,o)}}function Ap({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{var s,i,a;if((s=r.sourceEvent)!=null&&s.internal)return;const o=Mr(r.transform);e.mouseButton=((i=r.sourceEvent)==null?void 0:i.button)||0,e.isZoomingOrPanning=!0,e.prevViewport=o,((a=r.sourceEvent)==null?void 0:a.type)==="mousedown"&&t(!0),n&&(n==null||n(r.sourceEvent,o))}}function Sp({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:o}){return s=>{var i,a;e.usedRightMouseButton=!!(n&&jl(t,e.mouseButton??0)),(i=s.sourceEvent)!=null&&i.sync||r([s.transform.x,s.transform.y,s.transform.k]),o&&!((a=s.sourceEvent)!=null&&a.internal)&&(o==null||o(s.sourceEvent,Mr(s.transform)))}}function dp({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:o,onPaneContextMenu:s}){return i=>{var a;if(!((a=i.sourceEvent)!=null&&a.internal)&&(e.isZoomingOrPanning=!1,s&&jl(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&s(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),o)){const T=Mr(i.transform);e.prevViewport=T,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{o==null||o(i.sourceEvent,T)},n?150:0)}}}function Ip({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:o,zoomOnDoubleClick:s,userSelectionActive:i,noWheelClassName:a,noPanClassName:T,lib:l,connectionInProgress:R}){return c=>{var O;const A=e||t,S=n&&c.ctrlKey,d=c.type==="wheel";if(c.button===1&&c.type==="mousedown"&&(pt(c,`${l}-flow__node`)||pt(c,`${l}-flow__edge`)))return!0;if(!r&&!A&&!o&&!s&&!n||i||R&&!d||pt(c,a)&&d||pt(c,T)&&(!d||o&&d&&!e)||!n&&c.ctrlKey&&d)return!1;if(!n&&c.type==="touchstart"&&((O=c.touches)==null?void 0:O.length)>1)return c.preventDefault(),!1;if(!A&&!o&&!S&&d||!r&&(c.type==="mousedown"||c.type==="touchstart")||Array.isArray(r)&&!r.includes(c.button)&&c.type==="mousedown")return!1;const I=Array.isArray(r)&&r.includes(c.button)||!c.button||c.button<=1;return(!c.ctrlKey||d)&&I}}function up({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:o,onPanZoom:s,onPanZoomStart:i,onPanZoomEnd:a,onDraggingChange:T}){const l={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},R=e.getBoundingClientRect(),c=Ol().scaleExtent([t,n]).translateExtent(r),A=_e(e).call(c);f({x:o.x,y:o.y,zoom:Ut(o.zoom,t,n)},[[0,0],[R.width,R.height]],r);const S=A.on("wheel.zoom"),d=A.on("dblclick.zoom");c.wheelDelta($l);function I(g,_){return A?new Promise(U=>{c==null||c.interpolate((_==null?void 0:_.interpolate)==="linear"?nn:qn).transform(po(A,_==null?void 0:_.duration,_==null?void 0:_.ease,()=>U(!0)),g)}):Promise.resolve(!1)}function O({noWheelClassName:g,noPanClassName:_,onPaneContextMenu:U,userSelectionActive:h,panOnScroll:x,panOnDrag:P,panOnScrollMode:v,panOnScrollSpeed:b,preventScrolling:y,zoomOnPinch:Y,zoomOnScroll:W,zoomOnDoubleClick:V,zoomActivationKeyPressed:k,lib:X,onTransformChange:K,connectionInProgress:Q,paneClickDistance:j,selectionOnDrag:$}){h&&!l.isZoomingOrPanning&&u();const ee=x&&!k&&!h;c.clickDistance($?1/0:!ye(j)||j<0?0:j);const re=ee?cp({zoomPanValues:l,noWheelClassName:g,d3Selection:A,d3Zoom:c,panOnScrollMode:v,panOnScrollSpeed:b,zoomOnPinch:Y,onPanZoomStart:i,onPanZoom:s,onPanZoomEnd:a}):Rp({noWheelClassName:g,preventScrolling:y,d3ZoomHandler:S});if(A.on("wheel.zoom",re,{passive:!1}),!h){const z=Ap({zoomPanValues:l,onDraggingChange:T,onPanZoomStart:i});c.on("start",z);const te=Sp({zoomPanValues:l,panOnDrag:P,onPaneContextMenu:!!U,onPanZoom:s,onTransformChange:K});c.on("zoom",te);const Ee=dp({zoomPanValues:l,panOnDrag:P,panOnScroll:x,onPaneContextMenu:U,onPanZoomEnd:a,onDraggingChange:T});c.on("end",Ee)}const q=Ip({zoomActivationKeyPressed:k,panOnDrag:P,zoomOnScroll:W,panOnScroll:x,zoomOnDoubleClick:V,zoomOnPinch:Y,userSelectionActive:h,noPanClassName:_,noWheelClassName:g,lib:X,connectionInProgress:Q});c.filter(q),V?A.on("dblclick.zoom",d):A.on("dblclick.zoom",null)}function u(){c.on("zoom",null)}async function f(g,_,U){const h=_o(g),x=c==null?void 0:c.constrain()(h,_,U);return x&&await I(x),new Promise(P=>P(x))}async function N(g,_){const U=_o(g);return await I(U,_),new Promise(h=>h(U))}function L(g){if(A){const _=_o(g),U=A.property("__zoom");(U.k!==g.zoom||U.x!==g.x||U.y!==g.y)&&(c==null||c.transform(A,_,null,{sync:!0}))}}function m(){const g=A?Nl(A.node()):{x:0,y:0,k:1};return{x:g.x,y:g.y,zoom:g.k}}function p(g,_){return A?new Promise(U=>{c==null||c.interpolate((_==null?void 0:_.interpolate)==="linear"?nn:qn).scaleTo(po(A,_==null?void 0:_.duration,_==null?void 0:_.ease,()=>U(!0)),g)}):Promise.resolve(!1)}function D(g,_){return A?new Promise(U=>{c==null||c.interpolate((_==null?void 0:_.interpolate)==="linear"?nn:qn).scaleBy(po(A,_==null?void 0:_.duration,_==null?void 0:_.ease,()=>U(!0)),g)}):Promise.resolve(!1)}function M(g){c==null||c.scaleExtent(g)}function B(g){c==null||c.translateExtent(g)}function F(g){const _=!ye(g)||g<0?0:g;c==null||c.clickDistance(_)}return{update:O,destroy:u,setViewport:N,setViewportConstrained:f,getViewport:m,scaleTo:p,scaleBy:D,setScaleExtent:M,setTranslateExtent:B,syncViewport:L,setClickDistance:F}}var Bt;(function(e){e.Line="line",e.Handle="handle"})(Bt||(Bt={}));function Np({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:o,affectsY:s}){const i=e-t,a=n-r,T=[i>0?1:i<0?-1:0,a>0?1:a<0?-1:0];return i&&o&&(T[0]=T[0]*-1),a&&s&&(T[1]=T[1]*-1),T}function CE(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 Ze(e,t){return Math.max(0,t-e)}function Qe(e,t){return Math.max(0,e-t)}function Vn(e,t,n){return Math.max(0,t-e,e-n)}function LE(e,t){return e?!t:t}function Op(e,t,n,r,o,s,i,a){let{affectsX:T,affectsY:l}=t;const{isHorizontal:R,isVertical:c}=t,A=R&&c,{xSnapped:S,ySnapped:d}=n,{minWidth:I,maxWidth:O,minHeight:u,maxHeight:f}=r,{x:N,y:L,width:m,height:p,aspectRatio:D}=e;let M=Math.floor(R?S-e.pointerX:0),B=Math.floor(c?d-e.pointerY:0);const F=m+(T?-M:M),g=p+(l?-B:B),_=-s[0]*m,U=-s[1]*p;let h=Vn(F,I,O),x=Vn(g,u,f);if(i){let b=0,y=0;T&&M<0?b=Ze(N+M+_,i[0][0]):!T&&M>0&&(b=Qe(N+F+_,i[1][0])),l&&B<0?y=Ze(L+B+U,i[0][1]):!l&&B>0&&(y=Qe(L+g+U,i[1][1])),h=Math.max(h,b),x=Math.max(x,y)}if(a){let b=0,y=0;T&&M>0?b=Qe(N+M,a[0][0]):!T&&M<0&&(b=Ze(N+F,a[1][0])),l&&B>0?y=Qe(L+B,a[0][1]):!l&&B<0&&(y=Ze(L+g,a[1][1])),h=Math.max(h,b),x=Math.max(x,y)}if(o){if(R){const b=Vn(F/D,u,f)*D;if(h=Math.max(h,b),i){let y=0;!T&&!l||T&&!l&&A?y=Qe(L+U+F/D,i[1][1])*D:y=Ze(L+U+(T?M:-M)/D,i[0][1])*D,h=Math.max(h,y)}if(a){let y=0;!T&&!l||T&&!l&&A?y=Ze(L+F/D,a[1][1])*D:y=Qe(L+(T?M:-M)/D,a[0][1])*D,h=Math.max(h,y)}}if(c){const b=Vn(g*D,I,O)/D;if(x=Math.max(x,b),i){let y=0;!T&&!l||l&&!T&&A?y=Qe(N+g*D+_,i[1][0])/D:y=Ze(N+(l?B:-B)*D+_,i[0][0])/D,x=Math.max(x,y)}if(a){let y=0;!T&&!l||l&&!T&&A?y=Ze(N+g*D,a[1][0])/D:y=Qe(N+(l?B:-B)*D,a[0][0])/D,x=Math.max(x,y)}}}B=B+(B<0?x:-x),M=M+(M<0?h:-h),o&&(A?F>g*D?B=(LE(T,l)?-M:M)/D:M=(LE(T,l)?-B:B)*D:R?(B=M/D,l=T):(M=B*D,T=l));const P=T?N+M:N,v=l?L+B:L;return{width:m+(T?-M:M),height:p+(l?-B:B),x:s[0]*M*(T?-1:1)+P,y:s[1]*B*(l?-1:1)+v}}const Kl={width:0,height:0,x:0,y:0},fp={...Kl,pointerX:0,pointerY:0,aspectRatio:1};function Cp(e){return[[0,0],[e.measured.width,e.measured.height]]}function Lp(e,t,n){const r=t.position.x+e.position.x,o=t.position.y+e.position.y,s=e.measured.width??0,i=e.measured.height??0,a=n[0]*s,T=n[1]*i;return[[r-a,o-T],[r+s-a,o+i-T]]}function hp({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:o}){const s=_e(e);let i={controlDirection:CE("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function a({controlPosition:l,boundaries:R,keepAspectRatio:c,resizeDirection:A,onResizeStart:S,onResize:d,onResizeEnd:I,shouldResize:O}){let u={...Kl},f={...fp};i={boundaries:R,resizeDirection:A,keepAspectRatio:c,controlDirection:CE(l)};let N,L=null,m=[],p,D,M,B=!1;const F=ol().on("start",g=>{const{nodeLookup:_,transform:U,snapGrid:h,snapToGrid:x,nodeOrigin:P,paneDomNode:v}=n();if(N=_.get(t),!N)return;L=(v==null?void 0:v.getBoundingClientRect())??null;const{xSnapped:b,ySnapped:y}=rn(g.sourceEvent,{transform:U,snapGrid:h,snapToGrid:x,containerBounds:L});u={width:N.measured.width??0,height:N.measured.height??0,x:N.position.x??0,y:N.position.y??0},f={...u,pointerX:b,pointerY:y,aspectRatio:u.width/u.height},p=void 0,N.parentId&&(N.extent==="parent"||N.expandParent)&&(p=_.get(N.parentId),D=p&&N.extent==="parent"?Cp(p):void 0),m=[],M=void 0;for(const[Y,W]of _)if(W.parentId===t&&(m.push({id:Y,position:{...W.position},extent:W.extent}),W.extent==="parent"||W.expandParent)){const V=Lp(W,N,W.origin??P);M?M=[[Math.min(V[0][0],M[0][0]),Math.min(V[0][1],M[0][1])],[Math.max(V[1][0],M[1][0]),Math.max(V[1][1],M[1][1])]]:M=V}S==null||S(g,{...u})}).on("drag",g=>{const{transform:_,snapGrid:U,snapToGrid:h,nodeOrigin:x}=n(),P=rn(g.sourceEvent,{transform:_,snapGrid:U,snapToGrid:h,containerBounds:L}),v=[];if(!N)return;const{x:b,y,width:Y,height:W}=u,V={},k=N.origin??x,{width:X,height:K,x:Q,y:j}=Op(f,i.controlDirection,P,i.boundaries,i.keepAspectRatio,k,D,M),$=X!==Y,ee=K!==W,re=Q!==b&&$,q=j!==y&&ee;if(!re&&!q&&!$&&!ee)return;if((re||q||k[0]===1||k[1]===1)&&(V.x=re?Q:u.x,V.y=q?j:u.y,u.x=V.x,u.y=V.y,m.length>0)){const le=Q-b,se=j-y;for(const Ne of m)Ne.position={x:Ne.position.x-le+k[0]*(X-Y),y:Ne.position.y-se+k[1]*(K-W)},v.push(Ne)}if(($||ee)&&(V.width=$&&(!i.resizeDirection||i.resizeDirection==="horizontal")?X:u.width,V.height=ee&&(!i.resizeDirection||i.resizeDirection==="vertical")?K:u.height,u.width=V.width,u.height=V.height),p&&N.expandParent){const le=k[0]*(V.width??0);V.x&&V.x<le&&(u.x=le,f.x=f.x-(V.x-le));const se=k[1]*(V.height??0);V.y&&V.y<se&&(u.y=se,f.y=f.y-(V.y-se))}const z=Np({width:u.width,prevWidth:Y,height:u.height,prevHeight:W,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),te={...u,direction:z};(O==null?void 0:O(g,te))!==!1&&(B=!0,d==null||d(g,te),r(V,v))}).on("end",g=>{B&&(I==null||I(g,{...u}),o==null||o({...u}),B=!1)});s.call(F)}function T(){s.on(".drag",null)}return{update:a,destroy:T}}var mo={exports:{}},Do={},go={exports:{}},Po={};/**
491
- * @license React
492
- * use-sync-external-store-shim.production.js
493
- *
494
- * Copyright (c) Meta Platforms, Inc. and affiliates.
495
- *
496
- * This source code is licensed under the MIT license found in the
497
- * LICENSE file in the root directory of this source tree.
498
- */var hE;function _p(){if(hE)return Po;hE=1;var e=Cr();function t(c,A){return c===A&&(c!==0||1/c===1/A)||c!==c&&A!==A}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,s=e.useLayoutEffect,i=e.useDebugValue;function a(c,A){var S=A(),d=r({inst:{value:S,getSnapshot:A}}),I=d[0].inst,O=d[1];return s(function(){I.value=S,I.getSnapshot=A,T(I)&&O({inst:I})},[c,S,A]),o(function(){return T(I)&&O({inst:I}),c(function(){T(I)&&O({inst:I})})},[c]),i(S),S}function T(c){var A=c.getSnapshot;c=c.value;try{var S=A();return!n(c,S)}catch{return!0}}function l(c,A){return A()}var R=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?l:a;return Po.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:R,Po}var _E;function pp(){return _E||(_E=1,go.exports=_p()),go.exports}/**
499
- * @license React
500
- * use-sync-external-store-shim/with-selector.production.js
501
- *
502
- * Copyright (c) Meta Platforms, Inc. and affiliates.
503
- *
504
- * This source code is licensed under the MIT license found in the
505
- * LICENSE file in the root directory of this source tree.
506
- */var pE;function mp(){if(pE)return Do;pE=1;var e=Cr(),t=pp();function n(l,R){return l===R&&(l!==0||1/l===1/R)||l!==l&&R!==R}var r=typeof Object.is=="function"?Object.is:n,o=t.useSyncExternalStore,s=e.useRef,i=e.useEffect,a=e.useMemo,T=e.useDebugValue;return Do.useSyncExternalStoreWithSelector=function(l,R,c,A,S){var d=s(null);if(d.current===null){var I={hasValue:!1,value:null};d.current=I}else I=d.current;d=a(function(){function u(p){if(!f){if(f=!0,N=p,p=A(p),S!==void 0&&I.hasValue){var D=I.value;if(S(D,p))return L=D}return L=p}if(D=L,r(N,p))return D;var M=A(p);return S!==void 0&&S(D,M)?(N=p,D):(N=p,L=M)}var f=!1,N,L,m=c===void 0?null:c;return[function(){return u(R())},m===null?void 0:function(){return u(m())}]},[R,c,A,S]);var O=o(l,d[0],d[1]);return i(function(){I.hasValue=!0,I.value=O},[O]),T(O),O},Do}var mE;function Dp(){return mE||(mE=1,mo.exports=mp()),mo.exports}var gp=Dp();const Pp=ss(gp),Mp={},DE=e=>{let t;const n=new Set,r=(R,c)=>{const A=typeof R=="function"?R(t):R;if(!Object.is(A,t)){const S=t;t=c??(typeof A!="object"||A===null)?A:Object.assign({},t,A),n.forEach(d=>d(t,S))}},o=()=>t,T={setState:r,getState:o,getInitialState:()=>l,subscribe:R=>(n.add(R),()=>n.delete(R)),destroy:()=>{(Mp?"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()}},l=t=e(r,o,T);return T},yp=e=>e?DE(e):DE,{useDebugValue:xp}=on,{useSyncExternalStoreWithSelector:Up}=Pp,bp=e=>e;function Jl(e,t=bp,n){const r=Up(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return xp(r),r}const gE=(e,t)=>{const n=yp(e),r=(o,s=t)=>Jl(n,o,s);return Object.assign(r,n),r},Gp=(e,t)=>e?gE(e,t):gE;function Te(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}ca();const yr=C.createContext(null),Bp=yr.Provider,zl=we.error001();function oe(e,t){const n=C.useContext(yr);if(n===null)throw new Error(zl);return Jl(n,e,t)}function ce(){const e=C.useContext(yr);if(e===null)throw new Error(zl);return C.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const PE={display:"none"},vp={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},ql="react-flow__node-desc",Zl="react-flow__edge-desc",Hp="react-flow__aria-live",Fp=e=>e.ariaLiveMessage,wp=e=>e.ariaLabelConfig;function Yp({rfId:e}){const t=oe(Fp);return E.jsx("div",{id:`${Hp}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:vp,children:t})}function Vp({rfId:e,disableKeyboardA11y:t}){const n=oe(wp);return E.jsxs(E.Fragment,{children:[E.jsx("div",{id:`${ql}-${e}`,style:PE,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),E.jsx("div",{id:`${Zl}-${e}`,style:PE,children:n["edge.a11yDescription.default"]}),!t&&E.jsx(Yp,{rfId:e})]})}const Dn=C.forwardRef(({position:e="top-left",children:t,className:n,style:r,...o},s)=>{const i=`${e}`.split("-");return E.jsx("div",{className:Ae(["react-flow__panel",n,...i]),style:r,ref:s,...o,children:t})});Dn.displayName="Panel";function Wp({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:E.jsx(Dn,{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:E.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const kp=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}},Wn=e=>e.id;function Xp(e,t){return Te(e.selectedNodes.map(Wn),t.selectedNodes.map(Wn))&&Te(e.selectedEdges.map(Wn),t.selectedEdges.map(Wn))}function jp({onSelectionChange:e}){const t=ce(),{selectedNodes:n,selectedEdges:r}=oe(kp,Xp);return C.useEffect(()=>{const o={nodes:n,edges:r};e==null||e(o),t.getState().onSelectionChangeHandlers.forEach(s=>s(o))},[n,r,e]),null}const $p=e=>!!e.onSelectionChangeHandlers;function Kp({onSelectionChange:e}){const t=oe($p);return e||t?E.jsx(jp,{onSelectionChange:e}):null}const Ql=[0,0],Jp={x:0,y:0,zoom:1},zp=["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"],ME=[...zp,"rfId"],qp=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}),yE={translateExtent:An,nodeOrigin:Ql,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function Zp(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:o,setTranslateExtent:s,setNodeExtent:i,reset:a,setDefaultNodesAndEdges:T}=oe(qp,Te),l=ce();C.useEffect(()=>(T(e.defaultNodes,e.defaultEdges),()=>{R.current=yE,a()}),[]);const R=C.useRef(yE);return C.useEffect(()=>{for(const c of ME){const A=e[c],S=R.current[c];A!==S&&(typeof e[c]>"u"||(c==="nodes"?t(A):c==="edges"?n(A):c==="minZoom"?r(A):c==="maxZoom"?o(A):c==="translateExtent"?s(A):c==="nodeExtent"?i(A):c==="ariaLabelConfig"?l.setState({ariaLabelConfig:G_(A)}):c==="fitView"?l.setState({fitViewQueued:A}):c==="fitViewOptions"?l.setState({fitViewOptions:A}):l.setState({[c]:A})))}R.current=e},ME.map(c=>e[c])),null}function xE(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function Qp(e){var r;const[t,n]=C.useState(e==="system"?null:e);return C.useEffect(()=>{if(e!=="system"){n(e);return}const o=xE(),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=xE())!=null&&r.matches?"dark":"light"}const UE=typeof document<"u"?document:null;function Nn(e=null,t={target:UE,actInsideInputWithModifier:!0}){const[n,r]=C.useState(!1),o=C.useRef(!1),s=C.useRef(new Set([])),[i,a]=C.useMemo(()=>{if(e!==null){const l=(Array.isArray(e)?e:[e]).filter(c=>typeof c=="string").map(c=>c.replace("+",`
507
- `).replace(`
508
-
509
- `,`
510
- +`).split(`
511
- `)),R=l.reduce((c,A)=>c.concat(...A),[]);return[l,R]}return[[],[]]},[e]);return C.useEffect(()=>{const T=(t==null?void 0:t.target)??UE,l=(t==null?void 0:t.actInsideInputWithModifier)??!0;if(e!==null){const R=S=>{var O,u;if(o.current=S.ctrlKey||S.metaKey||S.shiftKey||S.altKey,(!o.current||o.current&&!l)&&xl(S))return!1;const I=GE(S.code,a);if(s.current.add(S[I]),bE(i,s.current,!1)){const f=((u=(O=S.composedPath)==null?void 0:O.call(S))==null?void 0:u[0])||S.target,N=(f==null?void 0:f.nodeName)==="BUTTON"||(f==null?void 0:f.nodeName)==="A";t.preventDefault!==!1&&(o.current||!N)&&S.preventDefault(),r(!0)}},c=S=>{const d=GE(S.code,a);bE(i,s.current,!0)?(r(!1),s.current.clear()):s.current.delete(S[d]),S.key==="Meta"&&s.current.clear(),o.current=!1},A=()=>{s.current.clear(),r(!1)};return T==null||T.addEventListener("keydown",R),T==null||T.addEventListener("keyup",c),window.addEventListener("blur",A),window.addEventListener("contextmenu",A),()=>{T==null||T.removeEventListener("keydown",R),T==null||T.removeEventListener("keyup",c),window.removeEventListener("blur",A),window.removeEventListener("contextmenu",A)}}},[e,r]),n}function bE(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(o=>t.has(o)))}function GE(e,t){return t.includes(e)?"code":"key"}const em=()=>{const e=ce();return C.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:i}=e.getState();return i?(await i.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:i,panZoom:a}=e.getState(),T=ps(t,r,o,s,i,(n==null?void 0:n.padding)??.1);return a?(await a.setViewport(T,{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:i}=e.getState();if(!i)return t;const{x:a,y:T}=i.getBoundingClientRect(),l={x:t.x-a,y:t.y-T},R=n.snapGrid??o,c=n.snapToGrid??s;return mn(l,r,c,R)},flowToScreenPosition:t=>{const{transform:n,domNode:r}=e.getState();if(!r)return t;const{x:o,y:s}=r.getBoundingClientRect(),i=Ir(t,n);return{x:i.x+o,y:i.y+s}}}),[])};function eT(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 i=r.get(s.id);i?i.push(s):r.set(s.id,[s])}for(const s of t){const i=r.get(s.id);if(!i){n.push(s);continue}if(i[0].type==="remove")continue;if(i[0].type==="replace"){n.push({...i[0].item});continue}const a={...s};for(const T of i)tm(T,a);n.push(a)}return o.length&&o.forEach(s=>{s.index!==void 0?n.splice(s.index,0,{...s.item}):n.push({...s.item})}),n}function tm(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 tT(e,t){return eT(e,t)}function nT(e,t){return eT(e,t)}function at(e,t){return{id:e,type:"select",selected:t}}function mt(e,t=new Set,n=!1){const r=[];for(const[o,s]of e){const i=t.has(o);!(s.selected===void 0&&!i)&&s.selected!==i&&(n&&(s.selected=i),r.push(at(s.id,i)))}return r}function BE({items:e=[],lookup:t}){var o;const n=[],r=new Map(e.map(s=>[s.id,s]));for(const[s,i]of e.entries()){const a=t.get(i.id),T=((o=a==null?void 0:a.internals)==null?void 0:o.userNode)??a;T!==void 0&&T!==i&&n.push({id:i.id,item:i,type:"replace"}),T===void 0&&n.push({item:i,type:"add",index:s})}for(const[s]of t)r.get(s)===void 0&&n.push({id:s,type:"remove"});return n}function vE(e){return{id:e.id,type:"remove"}}const HE=e=>p_(e),nm=e=>_l(e);function rT(e){return C.forwardRef(e)}const rm=typeof window<"u"?C.useLayoutEffect:C.useEffect;function FE(e){const[t,n]=C.useState(BigInt(0)),[r]=C.useState(()=>om(()=>n(o=>o+BigInt(1))));return rm(()=>{const o=r.get();o.length&&(e(o),r.reset())},[t]),r}function om(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}const oT=C.createContext(null);function sm({children:e}){const t=ce(),n=C.useCallback(a=>{const{nodes:T=[],setNodes:l,hasDefaultNodes:R,onNodesChange:c,nodeLookup:A,fitViewQueued:S,onNodesChangeMiddlewareMap:d}=t.getState();let I=T;for(const u of a)I=typeof u=="function"?u(I):u;let O=BE({items:I,lookup:A});for(const u of d.values())O=u(O);R&&l(I),O.length>0?c==null||c(O):S&&window.requestAnimationFrame(()=>{const{fitViewQueued:u,nodes:f,setNodes:N}=t.getState();u&&N(f)})},[]),r=FE(n),o=C.useCallback(a=>{const{edges:T=[],setEdges:l,hasDefaultEdges:R,onEdgesChange:c,edgeLookup:A}=t.getState();let S=T;for(const d of a)S=typeof d=="function"?d(S):d;R?l(S):c&&c(BE({items:S,lookup:A}))},[]),s=FE(o),i=C.useMemo(()=>({nodeQueue:r,edgeQueue:s}),[]);return E.jsx(oT.Provider,{value:i,children:e})}function im(){const e=C.useContext(oT);if(!e)throw new Error("useBatchContext must be used within a BatchProvider");return e}const Em=e=>!!e.panZoom;function xs(){const e=em(),t=ce(),n=im(),r=oe(Em),o=C.useMemo(()=>{const s=c=>t.getState().nodeLookup.get(c),i=c=>{n.nodeQueue.push(c)},a=c=>{n.edgeQueue.push(c)},T=c=>{var u,f;const{nodeLookup:A,nodeOrigin:S}=t.getState(),d=HE(c)?c:A.get(c.id),I=d.parentId?Ml(d.position,d.measured,d.parentId,A,S):d.position,O={...d,position:I,width:((u=d.measured)==null?void 0:u.width)??d.width,height:((f=d.measured)==null?void 0:f.height)??d.height};return bt(O)},l=(c,A,S={replace:!1})=>{i(d=>d.map(I=>{if(I.id===c){const O=typeof A=="function"?A(I):A;return S.replace&&HE(O)?O:{...I,...O}}return I}))},R=(c,A,S={replace:!1})=>{a(d=>d.map(I=>{if(I.id===c){const O=typeof A=="function"?A(I):A;return S.replace&&nm(O)?O:{...I,...O}}return I}))};return{getNodes:()=>t.getState().nodes.map(c=>({...c})),getNode:c=>{var A;return(A=s(c))==null?void 0:A.internals.userNode},getInternalNode:s,getEdges:()=>{const{edges:c=[]}=t.getState();return c.map(A=>({...A}))},getEdge:c=>t.getState().edgeLookup.get(c),setNodes:i,setEdges:a,addNodes:c=>{const A=Array.isArray(c)?c:[c];n.nodeQueue.push(S=>[...S,...A])},addEdges:c=>{const A=Array.isArray(c)?c:[c];n.edgeQueue.push(S=>[...S,...A])},toObject:()=>{const{nodes:c=[],edges:A=[],transform:S}=t.getState(),[d,I,O]=S;return{nodes:c.map(u=>({...u})),edges:A.map(u=>({...u})),viewport:{x:d,y:I,zoom:O}}},deleteElements:async({nodes:c=[],edges:A=[]})=>{const{nodes:S,edges:d,onNodesDelete:I,onEdgesDelete:O,triggerNodeChanges:u,triggerEdgeChanges:f,onDelete:N,onBeforeDelete:L}=t.getState(),{nodes:m,edges:p}=await M_({nodesToRemove:c,edgesToRemove:A,nodes:S,edges:d,onBeforeDelete:L}),D=p.length>0,M=m.length>0;if(D){const B=p.map(vE);O==null||O(p),f(B)}if(M){const B=m.map(vE);I==null||I(m),u(B)}return(M||D)&&(N==null||N({nodes:m,edges:p})),{deletedNodes:m,deletedEdges:p}},getIntersectingNodes:(c,A=!0,S)=>{const d=TE(c),I=d?c:T(c),O=S!==void 0;return I?(S||t.getState().nodes).filter(u=>{const f=t.getState().nodeLookup.get(u.id);if(f&&!d&&(u.id===c.id||!f.internals.positionAbsolute))return!1;const N=bt(O?u:f),L=In(N,I);return A&&L>0||L>=N.width*N.height||L>=I.width*I.height}):[]},isNodeIntersecting:(c,A,S=!0)=>{const I=TE(c)?c:T(c);if(!I)return!1;const O=In(I,A);return S&&O>0||O>=A.width*A.height||O>=I.width*I.height},updateNode:l,updateNodeData:(c,A,S={replace:!1})=>{l(c,d=>{const I=typeof A=="function"?A(d):A;return S.replace?{...d,data:I}:{...d,data:{...d.data,...I}}},S)},updateEdge:R,updateEdgeData:(c,A,S={replace:!1})=>{R(c,d=>{const I=typeof A=="function"?A(d):A;return S.replace?{...d,data:I}:{...d,data:{...d.data,...I}}},S)},getNodesBounds:c=>{const{nodeLookup:A,nodeOrigin:S}=t.getState();return m_(c,{nodeLookup:A,nodeOrigin:S})},getHandleConnections:({type:c,id:A,nodeId:S})=>{var d;return Array.from(((d=t.getState().connectionLookup.get(`${S}-${c}${A?`-${A}`:""}`))==null?void 0:d.values())??[])},getNodeConnections:({type:c,handleId:A,nodeId:S})=>{var d;return Array.from(((d=t.getState().connectionLookup.get(`${S}${c?A?`-${c}-${A}`:`-${c}`:""}`))==null?void 0:d.values())??[])},fitView:async c=>{const A=t.getState().fitViewResolver??b_();return t.setState({fitViewQueued:!0,fitViewOptions:c,fitViewResolver:A}),n.nodeQueue.push(S=>[...S]),A.promise}}},[]);return C.useMemo(()=>({...o,...e,viewportInitialized:r}),[r])}const wE=e=>e.selected,am=typeof window<"u"?window:void 0;function lm({deleteKeyCode:e,multiSelectionKeyCode:t}){const n=ce(),{deleteElements:r}=xs(),o=Nn(e,{actInsideInputWithModifier:!1}),s=Nn(t,{target:am});C.useEffect(()=>{if(o){const{edges:i,nodes:a}=n.getState();r({nodes:a.filter(wE),edges:i.filter(wE)}),n.setState({nodesSelectionActive:!1})}},[o]),C.useEffect(()=>{n.setState({multiSelectionActive:s})},[s])}function Tm(e){const t=ce();C.useEffect(()=>{const n=()=>{var o,s,i,a;if(!e.current||!(((s=(o=e.current).checkVisibility)==null?void 0:s.call(o))??!0))return!1;const r=ms(e.current);(r.height===0||r.width===0)&&((a=(i=t.getState()).onError)==null||a.call(i,"004",we.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 xr={position:"absolute",width:"100%",height:"100%",top:0,left:0},cm=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function Rm({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:r=!1,panOnScrollSpeed:o=.5,panOnScrollMode:s=ct.Free,zoomOnDoubleClick:i=!0,panOnDrag:a=!0,defaultViewport:T,translateExtent:l,minZoom:R,maxZoom:c,zoomActivationKeyCode:A,preventScrolling:S=!0,children:d,noWheelClassName:I,noPanClassName:O,onViewportChange:u,isControlledViewport:f,paneClickDistance:N,selectionOnDrag:L}){const m=ce(),p=C.useRef(null),{userSelectionActive:D,lib:M,connectionInProgress:B}=oe(cm,Te),F=Nn(A),g=C.useRef();Tm(p);const _=C.useCallback(U=>{u==null||u({x:U[0],y:U[1],zoom:U[2]}),f||m.setState({transform:U})},[u,f]);return C.useEffect(()=>{if(p.current){g.current=up({domNode:p.current,minZoom:R,maxZoom:c,translateExtent:l,viewport:T,onDraggingChange:P=>m.setState(v=>v.paneDragging===P?v:{paneDragging:P}),onPanZoomStart:(P,v)=>{const{onViewportChangeStart:b,onMoveStart:y}=m.getState();y==null||y(P,v),b==null||b(v)},onPanZoom:(P,v)=>{const{onViewportChange:b,onMove:y}=m.getState();y==null||y(P,v),b==null||b(v)},onPanZoomEnd:(P,v)=>{const{onViewportChangeEnd:b,onMoveEnd:y}=m.getState();y==null||y(P,v),b==null||b(v)}});const{x:U,y:h,zoom:x}=g.current.getViewport();return m.setState({panZoom:g.current,transform:[U,h,x],domNode:p.current.closest(".react-flow")}),()=>{var P;(P=g.current)==null||P.destroy()}}},[]),C.useEffect(()=>{var U;(U=g.current)==null||U.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:r,panOnScrollSpeed:o,panOnScrollMode:s,zoomOnDoubleClick:i,panOnDrag:a,zoomActivationKeyPressed:F,preventScrolling:S,noPanClassName:O,userSelectionActive:D,noWheelClassName:I,lib:M,onTransformChange:_,connectionInProgress:B,selectionOnDrag:L,paneClickDistance:N})},[e,t,n,r,o,s,i,a,F,S,O,D,I,M,_,B,L,N]),E.jsx("div",{className:"react-flow__renderer",ref:p,style:xr,children:d})}const Am=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function Sm(){const{userSelectionActive:e,userSelectionRect:t}=oe(Am,Te);return e&&t?E.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 Mo=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},dm=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,connectionInProgress:e.connection.inProgress,dragging:e.paneDragging});function Im({isSelecting:e,selectionKeyPressed:t,selectionMode:n=Sn.Full,panOnDrag:r,paneClickDistance:o,selectionOnDrag:s,onSelectionStart:i,onSelectionEnd:a,onPaneClick:T,onPaneContextMenu:l,onPaneScroll:R,onPaneMouseEnter:c,onPaneMouseMove:A,onPaneMouseLeave:S,children:d}){const I=ce(),{userSelectionActive:O,elementsSelectable:u,dragging:f,connectionInProgress:N}=oe(dm,Te),L=u&&(e||O),m=C.useRef(null),p=C.useRef(),D=C.useRef(new Set),M=C.useRef(new Set),B=C.useRef(!1),F=b=>{if(B.current||N){B.current=!1;return}T==null||T(b),I.getState().resetSelectedElements(),I.setState({nodesSelectionActive:!1})},g=b=>{if(Array.isArray(r)&&(r!=null&&r.includes(2))){b.preventDefault();return}l==null||l(b)},_=R?b=>R(b):void 0,U=b=>{B.current&&(b.stopPropagation(),B.current=!1)},h=b=>{var K,Q;const{domNode:y}=I.getState();if(p.current=y==null?void 0:y.getBoundingClientRect(),!p.current)return;const Y=b.target===m.current;if(!Y&&!!b.target.closest(".nokey")||!e||!(s&&Y||t)||b.button!==0||!b.isPrimary)return;(Q=(K=b.target)==null?void 0:K.setPointerCapture)==null||Q.call(K,b.pointerId),B.current=!1;const{x:k,y:X}=xe(b.nativeEvent,p.current);I.setState({userSelectionRect:{width:0,height:0,startX:k,startY:X,x:k,y:X}}),Y||(b.stopPropagation(),b.preventDefault())},x=b=>{const{userSelectionRect:y,transform:Y,nodeLookup:W,edgeLookup:V,connectionLookup:k,triggerNodeChanges:X,triggerEdgeChanges:K,defaultEdgeOptions:Q,resetSelectedElements:j}=I.getState();if(!p.current||!y)return;const{x:$,y:ee}=xe(b.nativeEvent,p.current),{startX:re,startY:q}=y;if(!B.current){const se=t?0:o;if(Math.hypot($-re,ee-q)<=se)return;j(),i==null||i(b)}B.current=!0;const z={startX:re,startY:q,x:$<re?$:re,y:ee<q?ee:q,width:Math.abs($-re),height:Math.abs(ee-q)},te=D.current,Ee=M.current;D.current=new Set(_s(W,z,Y,n===Sn.Partial,!0).map(se=>se.id)),M.current=new Set;const le=(Q==null?void 0:Q.selectable)??!0;for(const se of D.current){const Ne=k.get(se);if(Ne)for(const{edgeId:qe}of Ne.values()){const Ve=V.get(qe);Ve&&(Ve.selectable??le)&&M.current.add(qe)}}if(!cE(te,D.current)){const se=mt(W,D.current,!0);X(se)}if(!cE(Ee,M.current)){const se=mt(V,M.current);K(se)}I.setState({userSelectionRect:z,userSelectionActive:!0,nodesSelectionActive:!1})},P=b=>{var y,Y;b.button===0&&((Y=(y=b.target)==null?void 0:y.releasePointerCapture)==null||Y.call(y,b.pointerId),!O&&b.target===m.current&&I.getState().userSelectionRect&&(F==null||F(b)),I.setState({userSelectionActive:!1,userSelectionRect:null}),B.current&&(a==null||a(b),I.setState({nodesSelectionActive:D.current.size>0})))},v=r===!0||Array.isArray(r)&&r.includes(0);return E.jsxs("div",{className:Ae(["react-flow__pane",{draggable:v,dragging:f,selection:e}]),onClick:L?void 0:Mo(F,m),onContextMenu:Mo(g,m),onWheel:Mo(_,m),onPointerEnter:L?void 0:c,onPointerMove:L?x:A,onPointerUp:L?P:void 0,onPointerDownCapture:L?h:void 0,onClickCapture:L?U:void 0,onPointerLeave:S,ref:m,style:xr,children:[d,E.jsx(Sm,{})]})}function rs({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:o,unselectNodesAndEdges:s,multiSelectionActive:i,nodeLookup:a,onError:T}=t.getState(),l=a.get(e);if(!l){T==null||T("012",we.error012(e));return}t.setState({nodesSelectionActive:!1}),l.selected?(n||l.selected&&i)&&(s({nodes:[l],edges:[]}),requestAnimationFrame(()=>{var R;return(R=r==null?void 0:r.current)==null?void 0:R.blur()})):o([e])}function sT({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:o,isSelectable:s,nodeClickDistance:i}){const a=ce(),[T,l]=C.useState(!1),R=C.useRef();return C.useEffect(()=>{R.current=rp({getStoreItems:()=>a.getState(),onNodeMouseDown:c=>{rs({id:c,store:a,nodeRef:e})},onDragStart:()=>{l(!0)},onDragStop:()=>{l(!1)}})},[]),C.useEffect(()=>{if(!(t||!e.current||!R.current))return R.current.update({noDragClassName:n,handleSelector:r,domNode:e.current,isSelectable:s,nodeId:o,nodeClickDistance:i}),()=>{var c;(c=R.current)==null||c.destroy()}},[n,r,t,s,e,o,i]),T}const um=e=>t=>t.selected&&(t.draggable||e&&typeof t.draggable>"u");function iT(){const e=ce();return C.useCallback(n=>{const{nodeExtent:r,snapToGrid:o,snapGrid:s,nodesDraggable:i,onError:a,updateNodePositions:T,nodeLookup:l,nodeOrigin:R}=e.getState(),c=new Map,A=um(i),S=o?s[0]:5,d=o?s[1]:5,I=n.direction.x*S*n.factor,O=n.direction.y*d*n.factor;for(const[,u]of l){if(!A(u))continue;let f={x:u.internals.positionAbsolute.x+I,y:u.internals.positionAbsolute.y+O};o&&(f=pn(f,s));const{position:N,positionAbsolute:L}=pl({nodeId:u.id,nextPosition:f,nodeLookup:l,nodeExtent:r,nodeOrigin:R,onError:a});u.position=N,u.internals.positionAbsolute=L,c.set(u.id,u)}T(c)},[])}const Us=C.createContext(null),Nm=Us.Provider;Us.Consumer;const ET=()=>C.useContext(Us),Om=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),fm=(e,t,n)=>r=>{const{connectionClickStartHandle:o,connectionMode:s,connection:i}=r,{fromHandle:a,toHandle:T,isValid:l}=i,R=(T==null?void 0:T.nodeId)===e&&(T==null?void 0:T.id)===t&&(T==null?void 0:T.type)===n;return{connectingFrom:(a==null?void 0:a.nodeId)===e&&(a==null?void 0:a.id)===t&&(a==null?void 0:a.type)===n,connectingTo:R,clickConnecting:(o==null?void 0:o.nodeId)===e&&(o==null?void 0:o.id)===t&&(o==null?void 0:o.type)===n,isPossibleEndHandle:s===xt.Strict?(a==null?void 0:a.type)!==n:e!==(a==null?void 0:a.nodeId)||t!==(a==null?void 0:a.id),connectionInProcess:!!a,clickConnectionInProcess:!!o,valid:R&&l}};function Cm({type:e="source",position:t=Z.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:o=!0,isConnectableEnd:s=!0,id:i,onConnect:a,children:T,className:l,onMouseDown:R,onTouchStart:c,...A},S){var x,P;const d=i||null,I=e==="target",O=ce(),u=ET(),{connectOnClick:f,noPanClassName:N,rfId:L}=oe(Om,Te),{connectingFrom:m,connectingTo:p,clickConnecting:D,isPossibleEndHandle:M,connectionInProcess:B,clickConnectionInProcess:F,valid:g}=oe(fm(u,d,e),Te);u||(P=(x=O.getState()).onError)==null||P.call(x,"010",we.error010());const _=v=>{const{defaultEdgeOptions:b,onConnect:y,hasDefaultEdges:Y}=O.getState(),W={...b,...v};if(Y){const{edges:V,setEdges:k}=O.getState();k(Y_(W,V))}y==null||y(W),a==null||a(W)},U=v=>{if(!u)return;const b=Ul(v.nativeEvent);if(o&&(b&&v.button===0||!b)){const y=O.getState();ns.onPointerDown(v.nativeEvent,{handleDomNode:v.currentTarget,autoPanOnConnect:y.autoPanOnConnect,connectionMode:y.connectionMode,connectionRadius:y.connectionRadius,domNode:y.domNode,nodeLookup:y.nodeLookup,lib:y.lib,isTarget:I,handleId:d,nodeId:u,flowId:y.rfId,panBy:y.panBy,cancelConnection:y.cancelConnection,onConnectStart:y.onConnectStart,onConnectEnd:(...Y)=>{var W,V;return(V=(W=O.getState()).onConnectEnd)==null?void 0:V.call(W,...Y)},updateConnection:y.updateConnection,onConnect:_,isValidConnection:n||((...Y)=>{var W,V;return((V=(W=O.getState()).isValidConnection)==null?void 0:V.call(W,...Y))??!0}),getTransform:()=>O.getState().transform,getFromHandle:()=>O.getState().connection.fromHandle,autoPanSpeed:y.autoPanSpeed,dragThreshold:y.connectionDragThreshold})}b?R==null||R(v):c==null||c(v)},h=v=>{const{onClickConnectStart:b,onClickConnectEnd:y,connectionClickStartHandle:Y,connectionMode:W,isValidConnection:V,lib:k,rfId:X,nodeLookup:K,connection:Q}=O.getState();if(!u||!Y&&!o)return;if(!Y){b==null||b(v.nativeEvent,{nodeId:u,handleId:d,handleType:e}),O.setState({connectionClickStartHandle:{nodeId:u,type:e,id:d}});return}const j=yl(v.target),$=n||V,{connection:ee,isValid:re}=ns.isValid(v.nativeEvent,{handle:{nodeId:u,id:d,type:e},connectionMode:W,fromNodeId:Y.nodeId,fromHandleId:Y.id||null,fromType:Y.type,isValidConnection:$,flowId:X,doc:j,lib:k,nodeLookup:K});re&&ee&&_(ee);const q=structuredClone(Q);delete q.inProgress,q.toPosition=q.toHandle?q.toHandle.position:null,y==null||y(v,q),O.setState({connectionClickStartHandle:null})};return E.jsx("div",{"data-handleid":d,"data-nodeid":u,"data-handlepos":t,"data-id":`${L}-${u}-${d}-${e}`,className:Ae(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",N,l,{source:!I,target:I,connectable:r,connectablestart:o,connectableend:s,clickconnecting:D,connectingfrom:m,connectingto:p,valid:g,connectionindicator:r&&(!B||M)&&(B||F?s:o)}]),onMouseDown:U,onTouchStart:U,onClick:f?h:void 0,ref:S,...A,children:T})}const vt=C.memo(rT(Cm));function Lm({data:e,isConnectable:t,sourcePosition:n=Z.Bottom}){return E.jsxs(E.Fragment,{children:[e==null?void 0:e.label,E.jsx(vt,{type:"source",position:n,isConnectable:t})]})}function hm({data:e,isConnectable:t,targetPosition:n=Z.Top,sourcePosition:r=Z.Bottom}){return E.jsxs(E.Fragment,{children:[E.jsx(vt,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,E.jsx(vt,{type:"source",position:r,isConnectable:t})]})}function _m(){return null}function pm({data:e,isConnectable:t,targetPosition:n=Z.Top}){return E.jsxs(E.Fragment,{children:[E.jsx(vt,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label]})}const ur={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},YE={input:Lm,default:hm,output:pm,group:_m};function mm(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 Dm=e=>{const{width:t,height:n,x:r,y:o}=_n(e.nodeLookup,{filter:s=>!!s.selected});return{width:ye(t)?t:null,height:ye(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 gm({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=ce(),{width:o,height:s,transformString:i,userSelectionActive:a}=oe(Dm,Te),T=iT(),l=C.useRef(null);C.useEffect(()=>{var S;n||(S=l.current)==null||S.focus({preventScroll:!0})},[n]);const R=!a&&o!==null&&s!==null;if(sT({nodeRef:l,disabled:!R}),!R)return null;const c=e?S=>{const d=r.getState().nodes.filter(I=>I.selected);e(S,d)}:void 0,A=S=>{Object.prototype.hasOwnProperty.call(ur,S.key)&&(S.preventDefault(),T({direction:ur[S.key],factor:S.shiftKey?4:1}))};return E.jsx("div",{className:Ae(["react-flow__nodesselection","react-flow__container",t]),style:{transform:i},children:E.jsx("div",{ref:l,className:"react-flow__nodesselection-rect",onContextMenu:c,tabIndex:n?void 0:-1,onKeyDown:n?void 0:A,style:{width:o,height:s}})})}const VE=typeof window<"u"?window:void 0,Pm=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function aT({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:s,onPaneScroll:i,paneClickDistance:a,deleteKeyCode:T,selectionKeyCode:l,selectionOnDrag:R,selectionMode:c,onSelectionStart:A,onSelectionEnd:S,multiSelectionKeyCode:d,panActivationKeyCode:I,zoomActivationKeyCode:O,elementsSelectable:u,zoomOnScroll:f,zoomOnPinch:N,panOnScroll:L,panOnScrollSpeed:m,panOnScrollMode:p,zoomOnDoubleClick:D,panOnDrag:M,defaultViewport:B,translateExtent:F,minZoom:g,maxZoom:_,preventScrolling:U,onSelectionContextMenu:h,noWheelClassName:x,noPanClassName:P,disableKeyboardA11y:v,onViewportChange:b,isControlledViewport:y}){const{nodesSelectionActive:Y,userSelectionActive:W}=oe(Pm,Te),V=Nn(l,{target:VE}),k=Nn(I,{target:VE}),X=k||M,K=k||L,Q=R&&X!==!0,j=V||W||Q;return lm({deleteKeyCode:T,multiSelectionKeyCode:d}),E.jsx(Rm,{onPaneContextMenu:s,elementsSelectable:u,zoomOnScroll:f,zoomOnPinch:N,panOnScroll:K,panOnScrollSpeed:m,panOnScrollMode:p,zoomOnDoubleClick:D,panOnDrag:!V&&X,defaultViewport:B,translateExtent:F,minZoom:g,maxZoom:_,zoomActivationKeyCode:O,preventScrolling:U,noWheelClassName:x,noPanClassName:P,onViewportChange:b,isControlledViewport:y,paneClickDistance:a,selectionOnDrag:Q,children:E.jsxs(Im,{onSelectionStart:A,onSelectionEnd:S,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:s,onPaneScroll:i,panOnDrag:X,isSelecting:!!j,selectionMode:c,selectionKeyPressed:V,paneClickDistance:a,selectionOnDrag:Q,children:[e,Y&&E.jsx(gm,{onSelectionContextMenu:h,noPanClassName:P,disableKeyboardA11y:v})]})})}aT.displayName="FlowRenderer";const Mm=C.memo(aT),ym=e=>t=>e?_s(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 xm(e){return oe(C.useCallback(ym(e),[e]),Te)}const Um=e=>e.updateNodeInternals;function bm(){const e=oe(Um),[t]=C.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 C.useEffect(()=>()=>{t==null||t.disconnect()},[t]),t}function Gm({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){const o=ce(),s=C.useRef(null),i=C.useRef(null),a=C.useRef(e.sourcePosition),T=C.useRef(e.targetPosition),l=C.useRef(t),R=n&&!!e.internals.handleBounds;return C.useEffect(()=>{s.current&&!e.hidden&&(!R||i.current!==s.current)&&(i.current&&(r==null||r.unobserve(i.current)),r==null||r.observe(s.current),i.current=s.current)},[R,e.hidden]),C.useEffect(()=>()=>{i.current&&(r==null||r.unobserve(i.current),i.current=null)},[]),C.useEffect(()=>{if(s.current){const c=l.current!==t,A=a.current!==e.sourcePosition,S=T.current!==e.targetPosition;(c||A||S)&&(l.current=t,a.current=e.sourcePosition,T.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 Bm({id:e,onClick:t,onMouseEnter:n,onMouseMove:r,onMouseLeave:o,onContextMenu:s,onDoubleClick:i,nodesDraggable:a,elementsSelectable:T,nodesConnectable:l,nodesFocusable:R,resizeObserver:c,noDragClassName:A,noPanClassName:S,disableKeyboardA11y:d,rfId:I,nodeTypes:O,nodeClickDistance:u,onError:f}){const{node:N,internals:L,isParent:m}=oe($=>{const ee=$.nodeLookup.get(e),re=$.parentLookup.has(e);return{node:ee,internals:ee.internals,isParent:re}},Te);let p=N.type||"default",D=(O==null?void 0:O[p])||YE[p];D===void 0&&(f==null||f("003",we.error003(p)),p="default",D=(O==null?void 0:O.default)||YE.default);const M=!!(N.draggable||a&&typeof N.draggable>"u"),B=!!(N.selectable||T&&typeof N.selectable>"u"),F=!!(N.connectable||l&&typeof N.connectable>"u"),g=!!(N.focusable||R&&typeof N.focusable>"u"),_=ce(),U=Pl(N),h=Gm({node:N,nodeType:p,hasDimensions:U,resizeObserver:c}),x=sT({nodeRef:h,disabled:N.hidden||!M,noDragClassName:A,handleSelector:N.dragHandle,nodeId:e,isSelectable:B,nodeClickDistance:u}),P=iT();if(N.hidden)return null;const v=ze(N),b=mm(N),y=B||M||t||n||r||o,Y=n?$=>n($,{...L.userNode}):void 0,W=r?$=>r($,{...L.userNode}):void 0,V=o?$=>o($,{...L.userNode}):void 0,k=s?$=>s($,{...L.userNode}):void 0,X=i?$=>i($,{...L.userNode}):void 0,K=$=>{const{selectNodesOnDrag:ee,nodeDragThreshold:re}=_.getState();B&&(!ee||!M||re>0)&&rs({id:e,store:_,nodeRef:h}),t&&t($,{...L.userNode})},Q=$=>{if(!(xl($.nativeEvent)||d)){if(fl.includes($.key)&&B){const ee=$.key==="Escape";rs({id:e,store:_,unselect:ee,nodeRef:h})}else if(M&&N.selected&&Object.prototype.hasOwnProperty.call(ur,$.key)){$.preventDefault();const{ariaLabelConfig:ee}=_.getState();_.setState({ariaLiveMessage:ee["node.a11yDescription.ariaLiveMessage"]({direction:$.key.replace("Arrow","").toLowerCase(),x:~~L.positionAbsolute.x,y:~~L.positionAbsolute.y})}),P({direction:ur[$.key],factor:$.shiftKey?4:1})}}},j=()=>{var Ee;if(d||!((Ee=h.current)!=null&&Ee.matches(":focus-visible")))return;const{transform:$,width:ee,height:re,autoPanOnNodeFocus:q,setCenter:z}=_.getState();if(!q)return;_s(new Map([[e,N]]),{x:0,y:0,width:ee,height:re},$,!0).length>0||z(N.position.x+v.width/2,N.position.y+v.height/2,{zoom:$[2]})};return E.jsx("div",{className:Ae(["react-flow__node",`react-flow__node-${p}`,{[S]:M},N.className,{selected:N.selected,selectable:B,parent:m,draggable:M,dragging:x}]),ref:h,style:{zIndex:L.z,transform:`translate(${L.positionAbsolute.x}px,${L.positionAbsolute.y}px)`,pointerEvents:y?"all":"none",visibility:U?"visible":"hidden",...N.style,...b},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:Y,onMouseMove:W,onMouseLeave:V,onContextMenu:k,onClick:K,onDoubleClick:X,onKeyDown:g?Q:void 0,tabIndex:g?0:void 0,onFocus:g?j:void 0,role:N.ariaRole??(g?"group":void 0),"aria-roledescription":"node","aria-describedby":d?void 0:`${ql}-${I}`,"aria-label":N.ariaLabel,...N.domAttributes,children:E.jsx(Nm,{value:e,children:E.jsx(D,{id:e,data:N.data,type:p,positionAbsoluteX:L.positionAbsolute.x,positionAbsoluteY:L.positionAbsolute.y,selected:N.selected??!1,selectable:B,draggable:M,deletable:N.deletable??!0,isConnectable:F,sourcePosition:N.sourcePosition,targetPosition:N.targetPosition,dragging:x,dragHandle:N.dragHandle,zIndex:L.z,parentId:N.parentId,...v})})})}var vm=C.memo(Bm);const Hm=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function lT(e){const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:o,onError:s}=oe(Hm,Te),i=xm(e.onlyRenderVisibleElements),a=bm();return E.jsx("div",{className:"react-flow__nodes",style:xr,children:i.map(T=>E.jsx(vm,{id:T,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:a,nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:o,nodeClickDistance:e.nodeClickDistance,onError:s},T))})}lT.displayName="NodeRenderer";const Fm=C.memo(lT);function wm(e){return oe(C.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),i=n.nodeLookup.get(o.target);s&&i&&H_({sourceNode:s,targetNode:i,width:n.width,height:n.height,transform:n.transform})&&r.push(o.id)}return r},[e]),Te)}const Ym=({color:e="none",strokeWidth:t=1})=>{const n={strokeWidth:t,...e&&{stroke:e}};return E.jsx("polyline",{className:"arrow",style:n,strokeLinecap:"round",fill:"none",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4"})},Vm=({color:e="none",strokeWidth:t=1})=>{const n={strokeWidth:t,...e&&{stroke:e,fill:e}};return E.jsx("polyline",{className:"arrowclosed",style:n,strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"})},WE={[dn.Arrow]:Ym,[dn.ArrowClosed]:Vm};function Wm(e){const t=ce();return C.useMemo(()=>{var o,s;return Object.prototype.hasOwnProperty.call(WE,e)?WE[e]:((s=(o=t.getState()).onError)==null||s.call(o,"009",we.error009(e)),null)},[e])}const km=({id:e,type:t,color:n,width:r=12.5,height:o=12.5,markerUnits:s="strokeWidth",strokeWidth:i,orient:a="auto-start-reverse"})=>{const T=Wm(t);return T?E.jsx("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${r}`,markerHeight:`${o}`,viewBox:"-10 -10 20 20",markerUnits:s,orient:a,refX:"0",refY:"0",children:E.jsx(T,{color:n,strokeWidth:i})}):null},TT=({defaultColor:e,rfId:t})=>{const n=oe(s=>s.edges),r=oe(s=>s.defaultEdgeOptions),o=C.useMemo(()=>j_(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?E.jsx("svg",{className:"react-flow__marker","aria-hidden":"true",children:E.jsx("defs",{children:o.map(s=>E.jsx(km,{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};TT.displayName="MarkerDefinitions";var Xm=C.memo(TT);function cT({x:e,y:t,label:n,labelStyle:r,labelShowBg:o=!0,labelBgStyle:s,labelBgPadding:i=[2,4],labelBgBorderRadius:a=2,children:T,className:l,...R}){const[c,A]=C.useState({x:1,y:0,width:0,height:0}),S=Ae(["react-flow__edge-textwrapper",l]),d=C.useRef(null);return C.useEffect(()=>{if(d.current){const I=d.current.getBBox();A({x:I.x,y:I.y,width:I.width,height:I.height})}},[n]),n?E.jsxs("g",{transform:`translate(${e-c.width/2} ${t-c.height/2})`,className:S,visibility:c.width?"visible":"hidden",...R,children:[o&&E.jsx("rect",{width:c.width+2*i[0],x:-i[0],y:-i[1],height:c.height+2*i[1],className:"react-flow__edge-textbg",style:s,rx:a,ry:a}),E.jsx("text",{className:"react-flow__edge-text",y:c.height/2,dy:"0.3em",ref:d,style:r,children:n}),T]}):null}cT.displayName="EdgeText";const jm=C.memo(cT);function Ur({path:e,labelX:t,labelY:n,label:r,labelStyle:o,labelShowBg:s,labelBgStyle:i,labelBgPadding:a,labelBgBorderRadius:T,interactionWidth:l=20,...R}){return E.jsxs(E.Fragment,{children:[E.jsx("path",{...R,d:e,fill:"none",className:Ae(["react-flow__edge-path",R.className])}),l?E.jsx("path",{d:e,fill:"none",strokeOpacity:0,strokeWidth:l,className:"react-flow__edge-interaction"}):null,r&&ye(t)&&ye(n)?E.jsx(jm,{x:t,y:n,label:r,labelStyle:o,labelShowBg:s,labelBgStyle:i,labelBgPadding:a,labelBgBorderRadius:T}):null]})}function kE({pos:e,x1:t,y1:n,x2:r,y2:o}){return e===Z.Left||e===Z.Right?[.5*(t+r),n]:[t,.5*(n+o)]}function RT({sourceX:e,sourceY:t,sourcePosition:n=Z.Bottom,targetX:r,targetY:o,targetPosition:s=Z.Top}){const[i,a]=kE({pos:n,x1:e,y1:t,x2:r,y2:o}),[T,l]=kE({pos:s,x1:r,y1:o,x2:e,y2:t}),[R,c,A,S]=bl({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:i,sourceControlY:a,targetControlX:T,targetControlY:l});return[`M${e},${t} C${i},${a} ${T},${l} ${r},${o}`,R,c,A,S]}function AT(e){return C.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,sourcePosition:i,targetPosition:a,label:T,labelStyle:l,labelShowBg:R,labelBgStyle:c,labelBgPadding:A,labelBgBorderRadius:S,style:d,markerEnd:I,markerStart:O,interactionWidth:u})=>{const[f,N,L]=RT({sourceX:n,sourceY:r,sourcePosition:i,targetX:o,targetY:s,targetPosition:a}),m=e.isInternal?void 0:t;return E.jsx(Ur,{id:m,path:f,labelX:N,labelY:L,label:T,labelStyle:l,labelShowBg:R,labelBgStyle:c,labelBgPadding:A,labelBgBorderRadius:S,style:d,markerEnd:I,markerStart:O,interactionWidth:u})})}const $m=AT({isInternal:!1}),ST=AT({isInternal:!0});$m.displayName="SimpleBezierEdge";ST.displayName="SimpleBezierEdgeInternal";function dT(e){return C.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,label:i,labelStyle:a,labelShowBg:T,labelBgStyle:l,labelBgPadding:R,labelBgBorderRadius:c,style:A,sourcePosition:S=Z.Bottom,targetPosition:d=Z.Top,markerEnd:I,markerStart:O,pathOptions:u,interactionWidth:f})=>{const[N,L,m]=Qo({sourceX:n,sourceY:r,sourcePosition:S,targetX:o,targetY:s,targetPosition:d,borderRadius:u==null?void 0:u.borderRadius,offset:u==null?void 0:u.offset,stepPosition:u==null?void 0:u.stepPosition}),p=e.isInternal?void 0:t;return E.jsx(Ur,{id:p,path:N,labelX:L,labelY:m,label:i,labelStyle:a,labelShowBg:T,labelBgStyle:l,labelBgPadding:R,labelBgBorderRadius:c,style:A,markerEnd:I,markerStart:O,interactionWidth:f})})}const IT=dT({isInternal:!1}),uT=dT({isInternal:!0});IT.displayName="SmoothStepEdge";uT.displayName="SmoothStepEdgeInternal";function NT(e){return C.memo(({id:t,...n})=>{var o;const r=e.isInternal?void 0:t;return E.jsx(IT,{...n,id:r,pathOptions:C.useMemo(()=>{var s;return{borderRadius:0,offset:(s=n.pathOptions)==null?void 0:s.offset}},[(o=n.pathOptions)==null?void 0:o.offset])})})}const Km=NT({isInternal:!1}),OT=NT({isInternal:!0});Km.displayName="StepEdge";OT.displayName="StepEdgeInternal";function fT(e){return C.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,label:i,labelStyle:a,labelShowBg:T,labelBgStyle:l,labelBgPadding:R,labelBgBorderRadius:c,style:A,markerEnd:S,markerStart:d,interactionWidth:I})=>{const[O,u,f]=vl({sourceX:n,sourceY:r,targetX:o,targetY:s}),N=e.isInternal?void 0:t;return E.jsx(Ur,{id:N,path:O,labelX:u,labelY:f,label:i,labelStyle:a,labelShowBg:T,labelBgStyle:l,labelBgPadding:R,labelBgBorderRadius:c,style:A,markerEnd:S,markerStart:d,interactionWidth:I})})}const Jm=fT({isInternal:!1}),CT=fT({isInternal:!0});Jm.displayName="StraightEdge";CT.displayName="StraightEdgeInternal";function LT(e){return C.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,sourcePosition:i=Z.Bottom,targetPosition:a=Z.Top,label:T,labelStyle:l,labelShowBg:R,labelBgStyle:c,labelBgPadding:A,labelBgBorderRadius:S,style:d,markerEnd:I,markerStart:O,pathOptions:u,interactionWidth:f})=>{const[N,L,m]=Gl({sourceX:n,sourceY:r,sourcePosition:i,targetX:o,targetY:s,targetPosition:a,curvature:u==null?void 0:u.curvature}),p=e.isInternal?void 0:t;return E.jsx(Ur,{id:p,path:N,labelX:L,labelY:m,label:T,labelStyle:l,labelShowBg:R,labelBgStyle:c,labelBgPadding:A,labelBgBorderRadius:S,style:d,markerEnd:I,markerStart:O,interactionWidth:f})})}const zm=LT({isInternal:!1}),hT=LT({isInternal:!0});zm.displayName="BezierEdge";hT.displayName="BezierEdgeInternal";const XE={default:hT,straight:CT,step:OT,smoothstep:uT,simplebezier:ST},jE={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},qm=(e,t,n)=>n===Z.Left?e-t:n===Z.Right?e+t:e,Zm=(e,t,n)=>n===Z.Top?e-t:n===Z.Bottom?e+t:e,$E="react-flow__edgeupdater";function KE({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:o,onMouseEnter:s,onMouseOut:i,type:a}){return E.jsx("circle",{onMouseDown:o,onMouseEnter:s,onMouseOut:i,className:Ae([$E,`${$E}-${a}`]),cx:qm(t,r,e),cy:Zm(n,r,e),r,stroke:"transparent",fill:"transparent"})}function Qm({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:r,sourceY:o,targetX:s,targetY:i,sourcePosition:a,targetPosition:T,onReconnect:l,onReconnectStart:R,onReconnectEnd:c,setReconnecting:A,setUpdateHover:S}){const d=ce(),I=(L,m)=>{if(L.button!==0)return;const{autoPanOnConnect:p,domNode:D,connectionMode:M,connectionRadius:B,lib:F,onConnectStart:g,cancelConnection:_,nodeLookup:U,rfId:h,panBy:x,updateConnection:P}=d.getState(),v=m.type==="target",b=(W,V)=>{A(!1),c==null||c(W,n,m.type,V)},y=W=>l==null?void 0:l(n,W),Y=(W,V)=>{A(!0),R==null||R(L,n,m.type),g==null||g(W,V)};ns.onPointerDown(L.nativeEvent,{autoPanOnConnect:p,connectionMode:M,connectionRadius:B,domNode:D,handleId:m.id,nodeId:m.nodeId,nodeLookup:U,isTarget:v,edgeUpdaterType:m.type,lib:F,flowId:h,cancelConnection:_,panBy:x,isValidConnection:(...W)=>{var V,k;return((k=(V=d.getState()).isValidConnection)==null?void 0:k.call(V,...W))??!0},onConnect:y,onConnectStart:Y,onConnectEnd:(...W)=>{var V,k;return(k=(V=d.getState()).onConnectEnd)==null?void 0:k.call(V,...W)},onReconnectEnd:b,updateConnection:P,getTransform:()=>d.getState().transform,getFromHandle:()=>d.getState().connection.fromHandle,dragThreshold:d.getState().connectionDragThreshold,handleDomNode:L.currentTarget})},O=L=>I(L,{nodeId:n.target,id:n.targetHandle??null,type:"target"}),u=L=>I(L,{nodeId:n.source,id:n.sourceHandle??null,type:"source"}),f=()=>S(!0),N=()=>S(!1);return E.jsxs(E.Fragment,{children:[(e===!0||e==="source")&&E.jsx(KE,{position:a,centerX:r,centerY:o,radius:t,onMouseDown:O,onMouseEnter:f,onMouseOut:N,type:"source"}),(e===!0||e==="target")&&E.jsx(KE,{position:T,centerX:s,centerY:i,radius:t,onMouseDown:u,onMouseEnter:f,onMouseOut:N,type:"target"})]})}function eD({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:r,onClick:o,onDoubleClick:s,onContextMenu:i,onMouseEnter:a,onMouseMove:T,onMouseLeave:l,reconnectRadius:R,onReconnect:c,onReconnectStart:A,onReconnectEnd:S,rfId:d,edgeTypes:I,noPanClassName:O,onError:u,disableKeyboardA11y:f}){let N=oe(z=>z.edgeLookup.get(e));const L=oe(z=>z.defaultEdgeOptions);N=L?{...L,...N}:N;let m=N.type||"default",p=(I==null?void 0:I[m])||XE[m];p===void 0&&(u==null||u("011",we.error011(m)),m="default",p=(I==null?void 0:I.default)||XE.default);const D=!!(N.focusable||t&&typeof N.focusable>"u"),M=typeof c<"u"&&(N.reconnectable||n&&typeof N.reconnectable>"u"),B=!!(N.selectable||r&&typeof N.selectable>"u"),F=C.useRef(null),[g,_]=C.useState(!1),[U,h]=C.useState(!1),x=ce(),{zIndex:P,sourceX:v,sourceY:b,targetX:y,targetY:Y,sourcePosition:W,targetPosition:V}=oe(C.useCallback(z=>{const te=z.nodeLookup.get(N.source),Ee=z.nodeLookup.get(N.target);if(!te||!Ee)return{zIndex:N.zIndex,...jE};const le=X_({id:e,sourceNode:te,targetNode:Ee,sourceHandle:N.sourceHandle||null,targetHandle:N.targetHandle||null,connectionMode:z.connectionMode,onError:u});return{zIndex:v_({selected:N.selected,zIndex:N.zIndex,sourceNode:te,targetNode:Ee,elevateOnSelect:z.elevateEdgesOnSelect,zIndexMode:z.zIndexMode}),...le||jE}},[N.source,N.target,N.sourceHandle,N.targetHandle,N.selected,N.zIndex]),Te),k=C.useMemo(()=>N.markerStart?`url('#${es(N.markerStart,d)}')`:void 0,[N.markerStart,d]),X=C.useMemo(()=>N.markerEnd?`url('#${es(N.markerEnd,d)}')`:void 0,[N.markerEnd,d]);if(N.hidden||v===null||b===null||y===null||Y===null)return null;const K=z=>{var se;const{addSelectedEdges:te,unselectNodesAndEdges:Ee,multiSelectionActive:le}=x.getState();B&&(x.setState({nodesSelectionActive:!1}),N.selected&&le?(Ee({nodes:[],edges:[N]}),(se=F.current)==null||se.blur()):te([e])),o&&o(z,N)},Q=s?z=>{s(z,{...N})}:void 0,j=i?z=>{i(z,{...N})}:void 0,$=a?z=>{a(z,{...N})}:void 0,ee=T?z=>{T(z,{...N})}:void 0,re=l?z=>{l(z,{...N})}:void 0,q=z=>{var te;if(!f&&fl.includes(z.key)&&B){const{unselectNodesAndEdges:Ee,addSelectedEdges:le}=x.getState();z.key==="Escape"?((te=F.current)==null||te.blur(),Ee({edges:[N]})):le([e])}};return E.jsx("svg",{style:{zIndex:P},children:E.jsxs("g",{className:Ae(["react-flow__edge",`react-flow__edge-${m}`,N.className,O,{selected:N.selected,animated:N.animated,inactive:!B&&!o,updating:g,selectable:B}]),onClick:K,onDoubleClick:Q,onContextMenu:j,onMouseEnter:$,onMouseMove:ee,onMouseLeave:re,onKeyDown:D?q:void 0,tabIndex:D?0:void 0,role:N.ariaRole??(D?"group":"img"),"aria-roledescription":"edge","data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":N.ariaLabel===null?void 0:N.ariaLabel||`Edge from ${N.source} to ${N.target}`,"aria-describedby":D?`${Zl}-${d}`:void 0,ref:F,...N.domAttributes,children:[!U&&E.jsx(p,{id:e,source:N.source,target:N.target,type:N.type,selected:N.selected,animated:N.animated,selectable:B,deletable:N.deletable??!0,label:N.label,labelStyle:N.labelStyle,labelShowBg:N.labelShowBg,labelBgStyle:N.labelBgStyle,labelBgPadding:N.labelBgPadding,labelBgBorderRadius:N.labelBgBorderRadius,sourceX:v,sourceY:b,targetX:y,targetY:Y,sourcePosition:W,targetPosition:V,data:N.data,style:N.style,sourceHandleId:N.sourceHandle,targetHandleId:N.targetHandle,markerStart:k,markerEnd:X,pathOptions:"pathOptions"in N?N.pathOptions:void 0,interactionWidth:N.interactionWidth}),M&&E.jsx(Qm,{edge:N,isReconnectable:M,reconnectRadius:R,onReconnect:c,onReconnectStart:A,onReconnectEnd:S,sourceX:v,sourceY:b,targetX:y,targetY:Y,sourcePosition:W,targetPosition:V,setUpdateHover:_,setReconnecting:h})]})})}var tD=C.memo(eD);const nD=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function _T({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:r,noPanClassName:o,onReconnect:s,onEdgeContextMenu:i,onEdgeMouseEnter:a,onEdgeMouseMove:T,onEdgeMouseLeave:l,onEdgeClick:R,reconnectRadius:c,onEdgeDoubleClick:A,onReconnectStart:S,onReconnectEnd:d,disableKeyboardA11y:I}){const{edgesFocusable:O,edgesReconnectable:u,elementsSelectable:f,onError:N}=oe(nD,Te),L=wm(t);return E.jsxs("div",{className:"react-flow__edges",children:[E.jsx(Xm,{defaultColor:e,rfId:n}),L.map(m=>E.jsx(tD,{id:m,edgesFocusable:O,edgesReconnectable:u,elementsSelectable:f,noPanClassName:o,onReconnect:s,onContextMenu:i,onMouseEnter:a,onMouseMove:T,onMouseLeave:l,onClick:R,reconnectRadius:c,onDoubleClick:A,onReconnectStart:S,onReconnectEnd:d,rfId:n,onError:N,edgeTypes:r,disableKeyboardA11y:I},m))]})}_T.displayName="EdgeRenderer";const rD=C.memo(_T),oD=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function sD({children:e}){const t=oe(oD);return E.jsx("div",{className:"react-flow__viewport xyflow__viewport react-flow__container",style:{transform:t},children:e})}function iD(e){const t=xs(),n=C.useRef(!1);C.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const ED=e=>{var t;return(t=e.panZoom)==null?void 0:t.syncViewport};function aD(e){const t=oe(ED),n=ce();return C.useEffect(()=>{e&&(t==null||t(e),n.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function lD(e){return e.connection.inProgress?{...e.connection,to:mn(e.connection.to,e.transform)}:{...e.connection}}function TD(e){return lD}function cD(e){const t=TD();return oe(t,Te)}const RD=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function AD({containerStyle:e,style:t,type:n,component:r}){const{nodesConnectable:o,width:s,height:i,isValid:a,inProgress:T}=oe(RD,Te);return!(s&&o&&T)?null:E.jsx("svg",{style:e,width:s,height:i,className:"react-flow__connectionline react-flow__container",children:E.jsx("g",{className:Ae(["react-flow__connection",hl(a)]),children:E.jsx(pT,{style:t,type:n,CustomComponent:r,isValid:a})})})}const pT=({style:e,type:t=et.Bezier,CustomComponent:n,isValid:r})=>{const{inProgress:o,from:s,fromNode:i,fromHandle:a,fromPosition:T,to:l,toNode:R,toHandle:c,toPosition:A,pointer:S}=cD();if(!o)return;if(n)return E.jsx(n,{connectionLineType:t,connectionLineStyle:e,fromNode:i,fromHandle:a,fromX:s.x,fromY:s.y,toX:l.x,toY:l.y,fromPosition:T,toPosition:A,connectionStatus:hl(r),toNode:R,toHandle:c,pointer:S});let d="";const I={sourceX:s.x,sourceY:s.y,sourcePosition:T,targetX:l.x,targetY:l.y,targetPosition:A};switch(t){case et.Bezier:[d]=Gl(I);break;case et.SimpleBezier:[d]=RT(I);break;case et.Step:[d]=Qo({...I,borderRadius:0});break;case et.SmoothStep:[d]=Qo(I);break;default:[d]=vl(I)}return E.jsx("path",{d,fill:"none",className:"react-flow__connection-path",style:e})};pT.displayName="ConnectionLine";const SD={};function JE(e=SD){C.useRef(e),ce(),C.useEffect(()=>{},[e])}function dD(){ce(),C.useRef(!1),C.useEffect(()=>{},[])}function mT({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:r,onEdgeClick:o,onNodeDoubleClick:s,onEdgeDoubleClick:i,onNodeMouseEnter:a,onNodeMouseMove:T,onNodeMouseLeave:l,onNodeContextMenu:R,onSelectionContextMenu:c,onSelectionStart:A,onSelectionEnd:S,connectionLineType:d,connectionLineStyle:I,connectionLineComponent:O,connectionLineContainerStyle:u,selectionKeyCode:f,selectionOnDrag:N,selectionMode:L,multiSelectionKeyCode:m,panActivationKeyCode:p,zoomActivationKeyCode:D,deleteKeyCode:M,onlyRenderVisibleElements:B,elementsSelectable:F,defaultViewport:g,translateExtent:_,minZoom:U,maxZoom:h,preventScrolling:x,defaultMarkerColor:P,zoomOnScroll:v,zoomOnPinch:b,panOnScroll:y,panOnScrollSpeed:Y,panOnScrollMode:W,zoomOnDoubleClick:V,panOnDrag:k,onPaneClick:X,onPaneMouseEnter:K,onPaneMouseMove:Q,onPaneMouseLeave:j,onPaneScroll:$,onPaneContextMenu:ee,paneClickDistance:re,nodeClickDistance:q,onEdgeContextMenu:z,onEdgeMouseEnter:te,onEdgeMouseMove:Ee,onEdgeMouseLeave:le,reconnectRadius:se,onReconnect:Ne,onReconnectStart:qe,onReconnectEnd:Ve,noDragClassName:it,noWheelClassName:Yt,noPanClassName:Vt,disableKeyboardA11y:Wt,nodeExtent:Br,rfId:Pn,viewport:Ot,onViewportChange:kt}){return JE(e),JE(t),dD(),iD(n),aD(Ot),E.jsx(Mm,{onPaneClick:X,onPaneMouseEnter:K,onPaneMouseMove:Q,onPaneMouseLeave:j,onPaneContextMenu:ee,onPaneScroll:$,paneClickDistance:re,deleteKeyCode:M,selectionKeyCode:f,selectionOnDrag:N,selectionMode:L,onSelectionStart:A,onSelectionEnd:S,multiSelectionKeyCode:m,panActivationKeyCode:p,zoomActivationKeyCode:D,elementsSelectable:F,zoomOnScroll:v,zoomOnPinch:b,zoomOnDoubleClick:V,panOnScroll:y,panOnScrollSpeed:Y,panOnScrollMode:W,panOnDrag:k,defaultViewport:g,translateExtent:_,minZoom:U,maxZoom:h,onSelectionContextMenu:c,preventScrolling:x,noDragClassName:it,noWheelClassName:Yt,noPanClassName:Vt,disableKeyboardA11y:Wt,onViewportChange:kt,isControlledViewport:!!Ot,children:E.jsxs(sD,{children:[E.jsx(rD,{edgeTypes:t,onEdgeClick:o,onEdgeDoubleClick:i,onReconnect:Ne,onReconnectStart:qe,onReconnectEnd:Ve,onlyRenderVisibleElements:B,onEdgeContextMenu:z,onEdgeMouseEnter:te,onEdgeMouseMove:Ee,onEdgeMouseLeave:le,reconnectRadius:se,defaultMarkerColor:P,noPanClassName:Vt,disableKeyboardA11y:Wt,rfId:Pn}),E.jsx(AD,{style:I,type:d,component:O,containerStyle:u}),E.jsx("div",{className:"react-flow__edgelabel-renderer"}),E.jsx(Fm,{nodeTypes:e,onNodeClick:r,onNodeDoubleClick:s,onNodeMouseEnter:a,onNodeMouseMove:T,onNodeMouseLeave:l,onNodeContextMenu:R,nodeClickDistance:q,onlyRenderVisibleElements:B,noPanClassName:Vt,noDragClassName:it,disableKeyboardA11y:Wt,nodeExtent:Br,rfId:Pn}),E.jsx("div",{className:"react-flow__viewport-portal"})]})})}mT.displayName="GraphView";const ID=C.memo(mT),zE=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:s,fitView:i,fitViewOptions:a,minZoom:T=.5,maxZoom:l=2,nodeOrigin:R,nodeExtent:c,zIndexMode:A="basic"}={})=>{const S=new Map,d=new Map,I=new Map,O=new Map,u=r??t??[],f=n??e??[],N=R??[0,0],L=c??An;wl(I,O,u);const m=ts(f,S,d,{nodeOrigin:N,nodeExtent:L,zIndexMode:A});let p=[0,0,1];if(i&&o&&s){const D=_n(S,{filter:g=>!!((g.width||g.initialWidth)&&(g.height||g.initialHeight))}),{x:M,y:B,zoom:F}=ps(D,o,s,T,l,(a==null?void 0:a.padding)??.1);p=[M,B,F]}return{rfId:"1",width:o??0,height:s??0,transform:p,nodes:f,nodesInitialized:m,nodeLookup:S,parentLookup:d,edges:u,edgeLookup:O,connectionLookup:I,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:n!==void 0,hasDefaultEdges:r!==void 0,panZoom:null,minZoom:T,maxZoom:l,translateExtent:An,nodeExtent:L,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:xt.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:N,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:i??!1,fitViewOptions:a,fitViewResolver:null,connection:{...Ll},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:y_,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:"react",debug:!1,ariaLabelConfig:Cl,zIndexMode:A,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}},uD=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:s,fitView:i,fitViewOptions:a,minZoom:T,maxZoom:l,nodeOrigin:R,nodeExtent:c,zIndexMode:A})=>Gp((S,d)=>{async function I(){const{nodeLookup:O,panZoom:u,fitViewOptions:f,fitViewResolver:N,width:L,height:m,minZoom:p,maxZoom:D}=d();u&&(await P_({nodes:O,width:L,height:m,panZoom:u,minZoom:p,maxZoom:D},f),N==null||N.resolve(!0),S({fitViewResolver:null}))}return{...zE({nodes:e,edges:t,width:o,height:s,fitView:i,fitViewOptions:a,minZoom:T,maxZoom:l,nodeOrigin:R,nodeExtent:c,defaultNodes:n,defaultEdges:r,zIndexMode:A}),setNodes:O=>{const{nodeLookup:u,parentLookup:f,nodeOrigin:N,elevateNodesOnSelect:L,fitViewQueued:m,zIndexMode:p}=d(),D=ts(O,u,f,{nodeOrigin:N,nodeExtent:c,elevateNodesOnSelect:L,checkEquality:!0,zIndexMode:p});m&&D?(I(),S({nodes:O,nodesInitialized:D,fitViewQueued:!1,fitViewOptions:void 0})):S({nodes:O,nodesInitialized:D})},setEdges:O=>{const{connectionLookup:u,edgeLookup:f}=d();wl(u,f,O),S({edges:O})},setDefaultNodesAndEdges:(O,u)=>{if(O){const{setNodes:f}=d();f(O),S({hasDefaultNodes:!0})}if(u){const{setEdges:f}=d();f(u),S({hasDefaultEdges:!0})}},updateNodeInternals:O=>{const{triggerNodeChanges:u,nodeLookup:f,parentLookup:N,domNode:L,nodeOrigin:m,nodeExtent:p,debug:D,fitViewQueued:M,zIndexMode:B}=d(),{changes:F,updatedInternals:g}=Q_(O,f,N,L,m,p,B);g&&(J_(f,N,{nodeOrigin:m,nodeExtent:p,zIndexMode:B}),M?(I(),S({fitViewQueued:!1,fitViewOptions:void 0})):S({}),(F==null?void 0:F.length)>0&&(D&&console.log("React Flow: trigger node changes",F),u==null||u(F)))},updateNodePositions:(O,u=!1)=>{const f=[];let N=[];const{nodeLookup:L,triggerNodeChanges:m,connection:p,updateConnection:D,onNodesChangeMiddlewareMap:M}=d();for(const[B,F]of O){const g=L.get(B),_=!!(g!=null&&g.expandParent&&(g!=null&&g.parentId)&&(F!=null&&F.position)),U={id:B,type:"position",position:_?{x:Math.max(0,F.position.x),y:Math.max(0,F.position.y)}:F.position,dragging:u};if(g&&p.inProgress&&p.fromNode.id===g.id){const h=dt(g,p.fromHandle,Z.Left,!0);D({...p,from:h})}_&&g.parentId&&f.push({id:B,parentId:g.parentId,rect:{...F.internals.positionAbsolute,width:F.measured.width??0,height:F.measured.height??0}}),N.push(U)}if(f.length>0){const{parentLookup:B,nodeOrigin:F}=d(),g=ys(f,L,B,F);N.push(...g)}for(const B of M.values())N=B(N);m(N)},triggerNodeChanges:O=>{const{onNodesChange:u,setNodes:f,nodes:N,hasDefaultNodes:L,debug:m}=d();if(O!=null&&O.length){if(L){const p=tT(O,N);f(p)}m&&console.log("React Flow: trigger node changes",O),u==null||u(O)}},triggerEdgeChanges:O=>{const{onEdgesChange:u,setEdges:f,edges:N,hasDefaultEdges:L,debug:m}=d();if(O!=null&&O.length){if(L){const p=nT(O,N);f(p)}m&&console.log("React Flow: trigger edge changes",O),u==null||u(O)}},addSelectedNodes:O=>{const{multiSelectionActive:u,edgeLookup:f,nodeLookup:N,triggerNodeChanges:L,triggerEdgeChanges:m}=d();if(u){const p=O.map(D=>at(D,!0));L(p);return}L(mt(N,new Set([...O]),!0)),m(mt(f))},addSelectedEdges:O=>{const{multiSelectionActive:u,edgeLookup:f,nodeLookup:N,triggerNodeChanges:L,triggerEdgeChanges:m}=d();if(u){const p=O.map(D=>at(D,!0));m(p);return}m(mt(f,new Set([...O]))),L(mt(N,new Set,!0))},unselectNodesAndEdges:({nodes:O,edges:u}={})=>{const{edges:f,nodes:N,nodeLookup:L,triggerNodeChanges:m,triggerEdgeChanges:p}=d(),D=O||N,M=u||f,B=[];for(const g of D){if(!g.selected)continue;const _=L.get(g.id);_&&(_.selected=!1),B.push(at(g.id,!1))}const F=[];for(const g of M)g.selected&&F.push(at(g.id,!1));m(B),p(F)},setMinZoom:O=>{const{panZoom:u,maxZoom:f}=d();u==null||u.setScaleExtent([O,f]),S({minZoom:O})},setMaxZoom:O=>{const{panZoom:u,minZoom:f}=d();u==null||u.setScaleExtent([f,O]),S({maxZoom:O})},setTranslateExtent:O=>{var u;(u=d().panZoom)==null||u.setTranslateExtent(O),S({translateExtent:O})},resetSelectedElements:()=>{const{edges:O,nodes:u,triggerNodeChanges:f,triggerEdgeChanges:N,elementsSelectable:L}=d();if(!L)return;const m=u.reduce((D,M)=>M.selected?[...D,at(M.id,!1)]:D,[]),p=O.reduce((D,M)=>M.selected?[...D,at(M.id,!1)]:D,[]);f(m),N(p)},setNodeExtent:O=>{const{nodes:u,nodeLookup:f,parentLookup:N,nodeOrigin:L,elevateNodesOnSelect:m,nodeExtent:p,zIndexMode:D}=d();O[0][0]===p[0][0]&&O[0][1]===p[0][1]&&O[1][0]===p[1][0]&&O[1][1]===p[1][1]||(ts(u,f,N,{nodeOrigin:L,nodeExtent:O,elevateNodesOnSelect:m,checkEquality:!1,zIndexMode:D}),S({nodeExtent:O}))},panBy:O=>{const{transform:u,width:f,height:N,panZoom:L,translateExtent:m}=d();return ep({delta:O,panZoom:L,transform:u,translateExtent:m,width:f,height:N})},setCenter:async(O,u,f)=>{const{width:N,height:L,maxZoom:m,panZoom:p}=d();if(!p)return Promise.resolve(!1);const D=typeof(f==null?void 0:f.zoom)<"u"?f.zoom:m;return await p.setViewport({x:N/2-O*D,y:L/2-u*D,zoom:D},{duration:f==null?void 0:f.duration,ease:f==null?void 0:f.ease,interpolate:f==null?void 0:f.interpolate}),Promise.resolve(!0)},cancelConnection:()=>{S({connection:{...Ll}})},updateConnection:O=>{S({connection:O})},reset:()=>S({...zE()})}},Object.is);function ND({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:r,initialWidth:o,initialHeight:s,initialMinZoom:i,initialMaxZoom:a,initialFitViewOptions:T,fitView:l,nodeOrigin:R,nodeExtent:c,zIndexMode:A,children:S}){const[d]=C.useState(()=>uD({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:s,fitView:l,minZoom:i,maxZoom:a,fitViewOptions:T,nodeOrigin:R,nodeExtent:c,zIndexMode:A}));return E.jsx(Bp,{value:d,children:E.jsx(sm,{children:S})})}function OD({children:e,nodes:t,edges:n,defaultNodes:r,defaultEdges:o,width:s,height:i,fitView:a,fitViewOptions:T,minZoom:l,maxZoom:R,nodeOrigin:c,nodeExtent:A,zIndexMode:S}){return C.useContext(yr)?E.jsx(E.Fragment,{children:e}):E.jsx(ND,{initialNodes:t,initialEdges:n,defaultNodes:r,defaultEdges:o,initialWidth:s,initialHeight:i,fitView:a,initialFitViewOptions:T,initialMinZoom:l,initialMaxZoom:R,nodeOrigin:c,nodeExtent:A,zIndexMode:S,children:e})}const fD={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0};function CD({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:o,nodeTypes:s,edgeTypes:i,onNodeClick:a,onEdgeClick:T,onInit:l,onMove:R,onMoveStart:c,onMoveEnd:A,onConnect:S,onConnectStart:d,onConnectEnd:I,onClickConnectStart:O,onClickConnectEnd:u,onNodeMouseEnter:f,onNodeMouseMove:N,onNodeMouseLeave:L,onNodeContextMenu:m,onNodeDoubleClick:p,onNodeDragStart:D,onNodeDrag:M,onNodeDragStop:B,onNodesDelete:F,onEdgesDelete:g,onDelete:_,onSelectionChange:U,onSelectionDragStart:h,onSelectionDrag:x,onSelectionDragStop:P,onSelectionContextMenu:v,onSelectionStart:b,onSelectionEnd:y,onBeforeDelete:Y,connectionMode:W,connectionLineType:V=et.Bezier,connectionLineStyle:k,connectionLineComponent:X,connectionLineContainerStyle:K,deleteKeyCode:Q="Backspace",selectionKeyCode:j="Shift",selectionOnDrag:$=!1,selectionMode:ee=Sn.Full,panActivationKeyCode:re="Space",multiSelectionKeyCode:q=un()?"Meta":"Control",zoomActivationKeyCode:z=un()?"Meta":"Control",snapToGrid:te,snapGrid:Ee,onlyRenderVisibleElements:le=!1,selectNodesOnDrag:se,nodesDraggable:Ne,autoPanOnNodeFocus:qe,nodesConnectable:Ve,nodesFocusable:it,nodeOrigin:Yt=Ql,edgesFocusable:Vt,edgesReconnectable:Wt,elementsSelectable:Br=!0,defaultViewport:Pn=Jp,minZoom:Ot=.5,maxZoom:kt=2,translateExtent:Fs=An,preventScrolling:rc=!0,nodeExtent:vr,defaultMarkerColor:oc="#b1b1b7",zoomOnScroll:sc=!0,zoomOnPinch:ic=!0,panOnScroll:Ec=!1,panOnScrollSpeed:ac=.5,panOnScrollMode:lc=ct.Free,zoomOnDoubleClick:Tc=!0,panOnDrag:cc=!0,onPaneClick:Rc,onPaneMouseEnter:Ac,onPaneMouseMove:Sc,onPaneMouseLeave:dc,onPaneScroll:Ic,onPaneContextMenu:uc,paneClickDistance:Nc=1,nodeClickDistance:Oc=0,children:fc,onReconnect:Cc,onReconnectStart:Lc,onReconnectEnd:hc,onEdgeContextMenu:_c,onEdgeDoubleClick:pc,onEdgeMouseEnter:mc,onEdgeMouseMove:Dc,onEdgeMouseLeave:gc,reconnectRadius:Pc=10,onNodesChange:Mc,onEdgesChange:yc,noDragClassName:xc="nodrag",noWheelClassName:Uc="nowheel",noPanClassName:ws="nopan",fitView:Ys,fitViewOptions:Vs,connectOnClick:bc,attributionPosition:Gc,proOptions:Bc,defaultEdgeOptions:vc,elevateNodesOnSelect:Hc=!0,elevateEdgesOnSelect:Fc=!1,disableKeyboardA11y:Ws=!1,autoPanOnConnect:wc,autoPanOnNodeDrag:Yc,autoPanSpeed:Vc,connectionRadius:Wc,isValidConnection:kc,onError:Xc,style:jc,id:ks,nodeDragThreshold:$c,connectionDragThreshold:Kc,viewport:Jc,onViewportChange:zc,width:qc,height:Zc,colorMode:Qc="light",debug:eR,onScroll:Mn,ariaLabelConfig:tR,zIndexMode:Xs="basic",...nR},rR){const Hr=ks||"1",oR=Qp(Qc),sR=C.useCallback(js=>{js.currentTarget.scrollTo({top:0,left:0,behavior:"instant"}),Mn==null||Mn(js)},[Mn]);return E.jsx("div",{"data-testid":"rf__wrapper",...nR,onScroll:sR,style:{...jc,...fD},ref:rR,className:Ae(["react-flow",o,oR]),id:ks,role:"application",children:E.jsxs(OD,{nodes:e,edges:t,width:qc,height:Zc,fitView:Ys,fitViewOptions:Vs,minZoom:Ot,maxZoom:kt,nodeOrigin:Yt,nodeExtent:vr,zIndexMode:Xs,children:[E.jsx(ID,{onInit:l,onNodeClick:a,onEdgeClick:T,onNodeMouseEnter:f,onNodeMouseMove:N,onNodeMouseLeave:L,onNodeContextMenu:m,onNodeDoubleClick:p,nodeTypes:s,edgeTypes:i,connectionLineType:V,connectionLineStyle:k,connectionLineComponent:X,connectionLineContainerStyle:K,selectionKeyCode:j,selectionOnDrag:$,selectionMode:ee,deleteKeyCode:Q,multiSelectionKeyCode:q,panActivationKeyCode:re,zoomActivationKeyCode:z,onlyRenderVisibleElements:le,defaultViewport:Pn,translateExtent:Fs,minZoom:Ot,maxZoom:kt,preventScrolling:rc,zoomOnScroll:sc,zoomOnPinch:ic,zoomOnDoubleClick:Tc,panOnScroll:Ec,panOnScrollSpeed:ac,panOnScrollMode:lc,panOnDrag:cc,onPaneClick:Rc,onPaneMouseEnter:Ac,onPaneMouseMove:Sc,onPaneMouseLeave:dc,onPaneScroll:Ic,onPaneContextMenu:uc,paneClickDistance:Nc,nodeClickDistance:Oc,onSelectionContextMenu:v,onSelectionStart:b,onSelectionEnd:y,onReconnect:Cc,onReconnectStart:Lc,onReconnectEnd:hc,onEdgeContextMenu:_c,onEdgeDoubleClick:pc,onEdgeMouseEnter:mc,onEdgeMouseMove:Dc,onEdgeMouseLeave:gc,reconnectRadius:Pc,defaultMarkerColor:oc,noDragClassName:xc,noWheelClassName:Uc,noPanClassName:ws,rfId:Hr,disableKeyboardA11y:Ws,nodeExtent:vr,viewport:Jc,onViewportChange:zc}),E.jsx(Zp,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:S,onConnectStart:d,onConnectEnd:I,onClickConnectStart:O,onClickConnectEnd:u,nodesDraggable:Ne,autoPanOnNodeFocus:qe,nodesConnectable:Ve,nodesFocusable:it,edgesFocusable:Vt,edgesReconnectable:Wt,elementsSelectable:Br,elevateNodesOnSelect:Hc,elevateEdgesOnSelect:Fc,minZoom:Ot,maxZoom:kt,nodeExtent:vr,onNodesChange:Mc,onEdgesChange:yc,snapToGrid:te,snapGrid:Ee,connectionMode:W,translateExtent:Fs,connectOnClick:bc,defaultEdgeOptions:vc,fitView:Ys,fitViewOptions:Vs,onNodesDelete:F,onEdgesDelete:g,onDelete:_,onNodeDragStart:D,onNodeDrag:M,onNodeDragStop:B,onSelectionDrag:x,onSelectionDragStart:h,onSelectionDragStop:P,onMove:R,onMoveStart:c,onMoveEnd:A,noPanClassName:ws,nodeOrigin:Yt,rfId:Hr,autoPanOnConnect:wc,autoPanOnNodeDrag:Yc,autoPanSpeed:Vc,onError:Xc,connectionRadius:Wc,isValidConnection:kc,selectNodesOnDrag:se,nodeDragThreshold:$c,connectionDragThreshold:Kc,onBeforeDelete:Y,debug:eR,ariaLabelConfig:tR,zIndexMode:Xs}),E.jsx(Kp,{onSelectionChange:U}),fc,E.jsx(Wp,{proOptions:Bc,position:Gc}),E.jsx(Vp,{rfId:Hr,disableKeyboardA11y:Ws})]})})}var LD=rT(CD);function hD(e){const[t,n]=C.useState(e),r=C.useCallback(o=>n(s=>tT(o,s)),[]);return[t,n,r]}function _D(e){const[t,n]=C.useState(e),r=C.useCallback(o=>n(s=>nT(o,s)),[]);return[t,n,r]}function pD({dimensions:e,lineWidth:t,variant:n,className:r}){return E.jsx("path",{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:Ae(["react-flow__background-pattern",n,r])})}function mD({radius:e,className:t}){return E.jsx("circle",{cx:e,cy:e,r:e,className:Ae(["react-flow__background-pattern","dots",t])})}var rt;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(rt||(rt={}));const DD={[rt.Dots]:1,[rt.Lines]:1,[rt.Cross]:6},gD=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function DT({id:e,variant:t=rt.Dots,gap:n=20,size:r,lineWidth:o=1,offset:s=0,color:i,bgColor:a,style:T,className:l,patternClassName:R}){const c=C.useRef(null),{transform:A,patternId:S}=oe(gD,Te),d=r||DD[t],I=t===rt.Dots,O=t===rt.Cross,u=Array.isArray(n)?n:[n,n],f=[u[0]*A[2]||1,u[1]*A[2]||1],N=d*A[2],L=Array.isArray(s)?s:[s,s],m=O?[N,N]:f,p=[L[0]*A[2]||1+m[0]/2,L[1]*A[2]||1+m[1]/2],D=`${S}${e||""}`;return E.jsxs("svg",{className:Ae(["react-flow__background",l]),style:{...T,...xr,"--xy-background-color-props":a,"--xy-background-pattern-color-props":i},ref:c,"data-testid":"rf__background",children:[E.jsx("pattern",{id:D,x:A[0]%f[0],y:A[1]%f[1],width:f[0],height:f[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${p[0]},-${p[1]})`,children:I?E.jsx(mD,{radius:N/2,className:R}):E.jsx(pD,{dimensions:m,lineWidth:o,variant:t,className:R})}),E.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${D})`})]})}DT.displayName="Background";const PD=C.memo(DT);function MD(){return E.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",children:E.jsx("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"})})}function yD(){return E.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5",children:E.jsx("path",{d:"M0 0h32v4.2H0z"})})}function xD(){return E.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30",children:E.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 UD(){return E.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:E.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 bD(){return E.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:E.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 kn({children:e,className:t,...n}){return E.jsx("button",{type:"button",className:Ae(["react-flow__controls-button",t]),...n,children:e})}const GD=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function gT({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:o,onZoomIn:s,onZoomOut:i,onFitView:a,onInteractiveChange:T,className:l,children:R,position:c="bottom-left",orientation:A="vertical","aria-label":S}){const d=ce(),{isInteractive:I,minZoomReached:O,maxZoomReached:u,ariaLabelConfig:f}=oe(GD,Te),{zoomIn:N,zoomOut:L,fitView:m}=xs(),p=()=>{N(),s==null||s()},D=()=>{L(),i==null||i()},M=()=>{m(o),a==null||a()},B=()=>{d.setState({nodesDraggable:!I,nodesConnectable:!I,elementsSelectable:!I}),T==null||T(!I)},F=A==="horizontal"?"horizontal":"vertical";return E.jsxs(Dn,{className:Ae(["react-flow__controls",F,l]),position:c,style:e,"data-testid":"rf__controls","aria-label":S??f["controls.ariaLabel"],children:[t&&E.jsxs(E.Fragment,{children:[E.jsx(kn,{onClick:p,className:"react-flow__controls-zoomin",title:f["controls.zoomIn.ariaLabel"],"aria-label":f["controls.zoomIn.ariaLabel"],disabled:u,children:E.jsx(MD,{})}),E.jsx(kn,{onClick:D,className:"react-flow__controls-zoomout",title:f["controls.zoomOut.ariaLabel"],"aria-label":f["controls.zoomOut.ariaLabel"],disabled:O,children:E.jsx(yD,{})})]}),n&&E.jsx(kn,{className:"react-flow__controls-fitview",onClick:M,title:f["controls.fitView.ariaLabel"],"aria-label":f["controls.fitView.ariaLabel"],children:E.jsx(xD,{})}),r&&E.jsx(kn,{className:"react-flow__controls-interactive",onClick:B,title:f["controls.interactive.ariaLabel"],"aria-label":f["controls.interactive.ariaLabel"],children:I?E.jsx(bD,{}):E.jsx(UD,{})}),R]})}gT.displayName="Controls";const BD=C.memo(gT);function vD({id:e,x:t,y:n,width:r,height:o,style:s,color:i,strokeColor:a,strokeWidth:T,className:l,borderRadius:R,shapeRendering:c,selected:A,onClick:S}){const{background:d,backgroundColor:I}=s||{},O=i||d||I;return E.jsx("rect",{className:Ae(["react-flow__minimap-node",{selected:A},l]),x:t,y:n,rx:R,ry:R,width:r,height:o,style:{fill:O,stroke:a,strokeWidth:T},shapeRendering:c,onClick:S?u=>S(u,e):void 0})}const HD=C.memo(vD),FD=e=>e.nodes.map(t=>t.id),yo=e=>e instanceof Function?e:()=>e;function wD({nodeStrokeColor:e,nodeColor:t,nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:o,nodeComponent:s=HD,onClick:i}){const a=oe(FD,Te),T=yo(t),l=yo(e),R=yo(n),c=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return E.jsx(E.Fragment,{children:a.map(A=>E.jsx(VD,{id:A,nodeColorFunc:T,nodeStrokeColorFunc:l,nodeClassNameFunc:R,nodeBorderRadius:r,nodeStrokeWidth:o,NodeComponent:s,onClick:i,shapeRendering:c},A))})}function YD({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:r,nodeBorderRadius:o,nodeStrokeWidth:s,shapeRendering:i,NodeComponent:a,onClick:T}){const{node:l,x:R,y:c,width:A,height:S}=oe(d=>{const I=d.nodeLookup.get(e);if(!I)return{node:void 0,x:0,y:0,width:0,height:0};const O=I.internals.userNode,{x:u,y:f}=I.internals.positionAbsolute,{width:N,height:L}=ze(O);return{node:O,x:u,y:f,width:N,height:L}},Te);return!l||l.hidden||!Pl(l)?null:E.jsx(a,{x:R,y:c,width:A,height:S,style:l.style,selected:!!l.selected,className:r(l),color:t(l),borderRadius:o,strokeColor:n(l),strokeWidth:s,shapeRendering:i,onClick:T,id:l.id})}const VD=C.memo(YD);var WD=C.memo(wD);const kD=200,XD=150,jD=e=>!e.hidden,$D=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?gl(_n(e.nodeLookup,{filter:jD}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}},KD="react-flow__minimap-desc";function PT({style:e,className:t,nodeStrokeColor:n,nodeColor:r,nodeClassName:o="",nodeBorderRadius:s=5,nodeStrokeWidth:i,nodeComponent:a,bgColor:T,maskColor:l,maskStrokeColor:R,maskStrokeWidth:c,position:A="bottom-right",onClick:S,onNodeClick:d,pannable:I=!1,zoomable:O=!1,ariaLabel:u,inversePan:f,zoomStep:N=1,offsetScale:L=5}){const m=ce(),p=C.useRef(null),{boundingRect:D,viewBB:M,rfId:B,panZoom:F,translateExtent:g,flowWidth:_,flowHeight:U,ariaLabelConfig:h}=oe($D,Te),x=(e==null?void 0:e.width)??kD,P=(e==null?void 0:e.height)??XD,v=D.width/x,b=D.height/P,y=Math.max(v,b),Y=y*x,W=y*P,V=L*y,k=D.x-(Y-D.width)/2-V,X=D.y-(W-D.height)/2-V,K=Y+V*2,Q=W+V*2,j=`${KD}-${B}`,$=C.useRef(0),ee=C.useRef();$.current=y,C.useEffect(()=>{if(p.current&&F)return ee.current=lp({domNode:p.current,panZoom:F,getTransform:()=>m.getState().transform,getViewScale:()=>$.current}),()=>{var te;(te=ee.current)==null||te.destroy()}},[F]),C.useEffect(()=>{var te;(te=ee.current)==null||te.update({translateExtent:g,width:_,height:U,inversePan:f,pannable:I,zoomStep:N,zoomable:O})},[I,O,f,N,g,_,U]);const re=S?te=>{var se;const[Ee,le]=((se=ee.current)==null?void 0:se.pointer(te))||[0,0];S(te,{x:Ee,y:le})}:void 0,q=d?C.useCallback((te,Ee)=>{const le=m.getState().nodeLookup.get(Ee).internals.userNode;d(te,le)},[]):void 0,z=u??h["minimap.ariaLabel"];return E.jsx(Dn,{position:A,style:{...e,"--xy-minimap-background-color-props":typeof T=="string"?T:void 0,"--xy-minimap-mask-background-color-props":typeof l=="string"?l:void 0,"--xy-minimap-mask-stroke-color-props":typeof R=="string"?R:void 0,"--xy-minimap-mask-stroke-width-props":typeof c=="number"?c*y:void 0,"--xy-minimap-node-background-color-props":typeof r=="string"?r:void 0,"--xy-minimap-node-stroke-color-props":typeof n=="string"?n:void 0,"--xy-minimap-node-stroke-width-props":typeof i=="number"?i:void 0},className:Ae(["react-flow__minimap",t]),"data-testid":"rf__minimap",children:E.jsxs("svg",{width:x,height:P,viewBox:`${k} ${X} ${K} ${Q}`,className:"react-flow__minimap-svg",role:"img","aria-labelledby":j,ref:p,onClick:re,children:[z&&E.jsx("title",{id:j,children:z}),E.jsx(WD,{onClick:q,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:s,nodeClassName:o,nodeStrokeWidth:i,nodeComponent:a}),E.jsx("path",{className:"react-flow__minimap-mask",d:`M${k-V},${X-V}h${K+V*2}v${Q+V*2}h${-K-V*2}z
512
- M${M.x},${M.y}h${M.width}v${M.height}h${-M.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}PT.displayName="MiniMap";const JD=C.memo(PT),zD=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,qD={[Bt.Line]:"right",[Bt.Handle]:"bottom-right"};function ZD({nodeId:e,position:t,variant:n=Bt.Handle,className:r,style:o=void 0,children:s,color:i,minWidth:a=10,minHeight:T=10,maxWidth:l=Number.MAX_VALUE,maxHeight:R=Number.MAX_VALUE,keepAspectRatio:c=!1,resizeDirection:A,autoScale:S=!0,shouldResize:d,onResizeStart:I,onResize:O,onResizeEnd:u}){const f=ET(),N=typeof e=="string"?e:f,L=ce(),m=C.useRef(null),p=n===Bt.Handle,D=oe(C.useCallback(zD(p&&S),[p,S]),Te),M=C.useRef(null),B=t??qD[n];C.useEffect(()=>{if(!(!m.current||!N))return M.current||(M.current=hp({domNode:m.current,nodeId:N,getStoreItems:()=>{const{nodeLookup:g,transform:_,snapGrid:U,snapToGrid:h,nodeOrigin:x,domNode:P}=L.getState();return{nodeLookup:g,transform:_,snapGrid:U,snapToGrid:h,nodeOrigin:x,paneDomNode:P}},onChange:(g,_)=>{const{triggerNodeChanges:U,nodeLookup:h,parentLookup:x,nodeOrigin:P}=L.getState(),v=[],b={x:g.x,y:g.y},y=h.get(N);if(y&&y.expandParent&&y.parentId){const Y=y.origin??P,W=g.width??y.measured.width??0,V=g.height??y.measured.height??0,k={id:y.id,parentId:y.parentId,rect:{width:W,height:V,...Ml({x:g.x??y.position.x,y:g.y??y.position.y},{width:W,height:V},y.parentId,h,Y)}},X=ys([k],h,x,P);v.push(...X),b.x=g.x?Math.max(Y[0]*W,g.x):void 0,b.y=g.y?Math.max(Y[1]*V,g.y):void 0}if(b.x!==void 0&&b.y!==void 0){const Y={id:N,type:"position",position:{...b}};v.push(Y)}if(g.width!==void 0&&g.height!==void 0){const W={id:N,type:"dimensions",resizing:!0,setAttributes:A?A==="horizontal"?"width":"height":!0,dimensions:{width:g.width,height:g.height}};v.push(W)}for(const Y of _){const W={...Y,type:"position"};v.push(W)}U(v)},onEnd:({width:g,height:_})=>{const U={id:N,type:"dimensions",resizing:!1,dimensions:{width:g,height:_}};L.getState().triggerNodeChanges([U])}})),M.current.update({controlPosition:B,boundaries:{minWidth:a,minHeight:T,maxWidth:l,maxHeight:R},keepAspectRatio:c,resizeDirection:A,onResizeStart:I,onResize:O,onResizeEnd:u,shouldResize:d}),()=>{var g;(g=M.current)==null||g.destroy()}},[B,a,T,l,R,c,I,O,u,d]);const F=B.split("-");return E.jsx("div",{className:Ae(["react-flow__resize-control","nodrag",...F,n,r]),ref:m,style:{...o,scale:D,...i&&{[p?"backgroundColor":"borderColor"]:i}},children:s})}C.memo(ZD);var MT=Object.defineProperty,QD=(e,t,n)=>t in e?MT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,eg=(e,t)=>{for(var n in t)MT(e,n,{get:t[n],enumerable:!0})},tg=(e,t,n)=>QD(e,t+"",n),yT={};eg(yT,{Graph:()=>ge,alg:()=>bs,json:()=>UT,version:()=>og});var ng=Object.defineProperty,xT=(e,t)=>{for(var n in t)ng(e,n,{get:t[n],enumerable:!0})},ge=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,i,a,T=!1;typeof e=="object"&&e!==null&&"v"in e?(o=e.v,s=e.w,i=e.name,arguments.length===2&&(a=t,T=!0)):(o=e,s=t,i=r,arguments.length>2&&(a=n,T=!0)),o=""+o,s=""+s,i!==void 0&&(i=""+i);let l=en(this._isDirected,o,s,i);if(l in this._edgeLabels)return T&&(this._edgeLabels[l]=a),this;if(i!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(o),this.setNode(s),this._edgeLabels[l]=T?a:this._defaultEdgeLabelFn(o,s,i);let R=rg(this._isDirected,o,s,i);return o=R.v,s=R.w,Object.freeze(R),this._edgeObjs[l]=R,qE(this._preds[s],o),qE(this._sucs[o],s),this._in[s][l]=R,this._out[o][l]=R,this._edgeCount++,this}edge(e,t,n){let r=arguments.length===1?xo(this._isDirected,e):en(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?xo(this._isDirected,e):en(this._isDirected,e,t,n))in this._edgeLabels}removeEdge(e,t,n){let r=arguments.length===1?xo(this._isDirected,e):en(this._isDirected,e,t,n),o=this._edgeObjs[r];if(o){let s=o.v,i=o.w;delete this._edgeLabels[r],delete this._edgeObjs[r],ZE(this._preds[i],s),ZE(this._sucs[s],i),delete this._in[i][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 qE(e,t){e[t]?e[t]++:e[t]=1}function ZE(e,t){e[t]!==void 0&&!--e[t]&&delete e[t]}function en(e,t,n,r){let o=""+t,s=""+n;if(!e&&o>s){let i=o;o=s,s=i}return o+""+s+""+(r===void 0?"\0":r)}function rg(e,t,n,r){let o=""+t,s=""+n;if(!e&&o>s){let a=o;o=s,s=a}let i={v:o,w:s};return r&&(i.name=r),i}function xo(e,t){return en(e,t.v,t.w,t.name)}var og="4.0.1",UT={};xT(UT,{read:()=>ag,write:()=>sg});function sg(e){let t={options:{directed:e.isDirected(),multigraph:e.isMultigraph(),compound:e.isCompound()},nodes:ig(e),edges:Eg(e)},n=e.graph();return n!==void 0&&(t.value=structuredClone(n)),t}function ig(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 Eg(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 ag(e){let t=new ge(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 bs={};xT(bs,{CycleException:()=>Or,bellmanFord:()=>bT,components:()=>cg,dijkstra:()=>Nr,dijkstraAll:()=>Sg,findCycles:()=>dg,floydWarshall:()=>ug,isAcyclic:()=>Og,postorder:()=>Cg,preorder:()=>Lg,prim:()=>hg,shortestPaths:()=>_g,tarjan:()=>BT,topsort:()=>vT});var lg=()=>1;function bT(e,t,n,r){return Tg(e,String(t),n||lg,r||function(o){return e.outEdges(o)})}function Tg(e,t,n,r){let o={},s,i=0,a=e.nodes(),T=function(c){let A=n(c);o[c.v].distance+A<o[c.w].distance&&(o[c.w]={distance:o[c.v].distance+A,predecessor:c.v},s=!0)},l=function(){a.forEach(function(c){r(c).forEach(function(A){let S=A.v===c?A.v:A.w,d=S===A.v?A.w:A.v;T({v:S,w:d})})})};a.forEach(function(c){let A=c===t?0:Number.POSITIVE_INFINITY;o[c]={distance:A,predecessor:""}});let R=a.length;for(let c=1;c<R&&(s=!1,i++,l(),!!s);c++);if(i===R-1&&(s=!1,l(),s))throw new Error("The graph contains a negative weight cycle");return o}function cg(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 GT=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}},Rg=()=>1;function Nr(e,t,n,r){let o=function(s){return e.outEdges(s)};return Ag(e,String(t),n||Rg,r||o)}function Ag(e,t,n,r){let o={},s=new GT,i,a,T=function(l){let R=l.v!==i?l.v:l.w,c=o[R],A=n(l),S=a.distance+A;if(A<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+l+" Weight: "+A);S<c.distance&&(c.distance=S,c.predecessor=i,s.decrease(R,S))};for(e.nodes().forEach(function(l){let R=l===t?0:Number.POSITIVE_INFINITY;o[l]={distance:R,predecessor:""},s.add(l,R)});s.size()>0&&(i=s.removeMin(),a=o[i],a.distance!==Number.POSITIVE_INFINITY);)r(i).forEach(T);return o}function Sg(e,t,n){return e.nodes().reduce(function(r,o){return r[o]=Nr(e,o,t,n),r},{})}function BT(e){let t=0,n=[],r={},o=[];function s(i){let a=r[i]={onStack:!0,lowlink:t,index:t++};if(n.push(i),e.successors(i).forEach(function(T){T in r?r[T].onStack&&(a.lowlink=Math.min(a.lowlink,r[T].index)):(s(T),a.lowlink=Math.min(a.lowlink,r[T].lowlink))}),a.lowlink===a.index){let T=[],l;do l=n.pop(),r[l].onStack=!1,T.push(l);while(i!==l);o.push(T)}}return e.nodes().forEach(function(i){i in r||s(i)}),o}function dg(e){return BT(e).filter(function(t){return t.length>1||t.length===1&&e.hasEdge(t[0],t[0])})}var Ig=()=>1;function ug(e,t,n){return Ng(e,t||Ig,n||function(r){return e.outEdges(r)})}function Ng(e,t,n){let r={},o=e.nodes();return o.forEach(function(s){r[s]={},r[s][s]={distance:0,predecessor:""},o.forEach(function(i){s!==i&&(r[s][i]={distance:Number.POSITIVE_INFINITY,predecessor:""})}),n(s).forEach(function(i){let a=i.v===s?i.w:i.v,T=t(i);r[s][a]={distance:T,predecessor:s}})}),o.forEach(function(s){let i=r[s];o.forEach(function(a){let T=r[a];o.forEach(function(l){let R=T[s],c=i[l],A=T[l],S=R.distance+c.distance;S<A.distance&&(A.distance=S,A.predecessor=c.predecessor)})})}),r}var Or=class extends Error{constructor(...e){super(...e)}};function vT(e){let t={},n={},r=[];function o(s){if(s in n)throw new Or;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 Or;return r}function Og(e){try{vT(e)}catch(t){if(t instanceof Or)return!1;throw t}return!0}function fg(e,t,n,r,o){Array.isArray(t)||(t=[t]);let s=(a=>{var T;return(T=e.isDirected()?e.successors(a):e.neighbors(a))!=null?T:[]}),i={};return t.forEach(function(a){if(!e.hasNode(a))throw new Error("Graph does not have node: "+a);o=HT(e,a,n==="post",i,s,r,o)}),o}function HT(e,t,n,r,o,s,i){return t in r||(r[t]=!0,n||(i=s(i,t)),o(t).forEach(function(a){i=HT(e,a,n,r,o,s,i)}),n&&(i=s(i,t))),i}function FT(e,t,n){return fg(e,t,n,function(r,o){return r.push(o),r},[])}function Cg(e,t){return FT(e,t,"post")}function Lg(e,t){return FT(e,t,"pre")}function hg(e,t){let n=new ge,r={},o=new GT,s;function i(T){let l=T.v===s?T.w:T.v,R=o.priority(l);if(R!==void 0){let c=t(T);c<R&&(r[l]=s,o.decrease(l,c))}}if(e.nodeCount()===0)return n;e.nodes().forEach(function(T){o.add(T,Number.POSITIVE_INFINITY),n.setNode(T)}),o.decrease(e.nodes()[0],0);let a=!1;for(;o.size()>0;){if(s=o.removeMin(),s in r)n.setEdge(s,r[s]);else{if(a)throw new Error("Input graph is not connected: "+e);a=!0}e.nodeEdges(s).forEach(i)}return n}function _g(e,t,n,r){return pg(e,t,n,r??(o=>{let s=e.outEdges(o);return s??[]}))}function pg(e,t,n,r){if(n===void 0)return Nr(e,t,n,r);let o=!1,s=e.nodes();for(let i=0;i<s.length;i++){let a=r(s[i]);for(let T=0;T<a.length;T++){let l=a[T],R=l.v===s[i]?l.v:l.w,c=R===l.v?l.w:l.v;n({v:R,w:c})<0&&(o=!0)}if(o)return bT(e,t,n,r)}return Nr(e,t,n,r)}function wt(e,t,n,r){let o=r;for(;e.hasNode(o);)o=Gs(r);return n.dummy=t,e.setNode(o,n),o}function mg(e){let t=new ge().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 wT(e){let t=new ge({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 QE(e,t){let n=e.x,r=e.y,o=t.x-n,s=t.y-r,i=e.width/2,a=e.height/2;if(!o&&!s)throw new Error("Not possible to find intersection inside of the rectangle");let T,l;return Math.abs(s)*i>Math.abs(o)*a?(s<0&&(a=-a),T=a*o/s,l=a):(o<0&&(i=-i),T=i,l=i*s/o),{x:n+T,y:r+l}}function gn(e){let t=On(VT(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 Dg(e){let t=e.nodes().map(r=>{let o=e.node(r).rank;return o===void 0?Number.MAX_VALUE:o}),n=He(Math.min,t);e.nodes().forEach(r=>{let o=e.node(r);Object.hasOwn(o,"rank")&&(o.rank-=n)})}function gg(e){let t=e.nodes().map(i=>e.node(i).rank).filter(i=>i!==void 0),n=He(Math.min,t),r=[];e.nodes().forEach(i=>{let a=e.node(i).rank-n;r[a]||(r[a]=[]),r[a].push(i)});let o=0,s=e.graph().nodeRankFactor;Array.from(r).forEach((i,a)=>{i===void 0&&a%s!==0?--o:i!==void 0&&o&&i.forEach(T=>e.node(T).rank+=o)})}function ea(e,t,n,r){let o={width:0,height:0};return arguments.length>=4&&(o.rank=n,o.order=r),wt(e,"border",o,t)}function Pg(e,t=YT){let n=[];for(let r=0;r<e.length;r+=t){let o=e.slice(r,r+t);n.push(o)}return n}var YT=65535;function He(e,t){if(t.length>YT){let n=Pg(t);return e(...n.map(r=>e(...r)))}else return e(...t)}function VT(e){let t=e.nodes().map(n=>{let r=e.node(n).rank;return r===void 0?Number.MIN_VALUE:r});return He(Math.max,t)}function Mg(e,t){let n={lhs:[],rhs:[]};return e.forEach(r=>{t(r)?n.lhs.push(r):n.rhs.push(r)}),n}function WT(e,t){let n=Date.now();try{return t()}finally{console.log(e+" time: "+(Date.now()-n)+"ms")}}function kT(e,t){return t()}var yg=0;function Gs(e){let t=++yg;return e+(""+t)}function On(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 fr(e,t){let n={};for(let r of t)e[r]!==void 0&&(n[r]=e[r]);return n}function br(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 xg(e,t){return e.reduce((n,r,o)=>(n[r]=t[o],n),{})}var Gr="\0",Ug="3.0.0",bg=class{constructor(){tg(this,"_sentinel");let e={};e._next=e._prev=e,this._sentinel=e}dequeue(){let e=this._sentinel,t=e._prev;if(t!==e)return ta(t),t}enqueue(e){let t=this._sentinel;e._prev&&e._next&&ta(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,Gg)),n=n._prev;return"["+e.join(", ")+"]"}};function ta(e){e._prev._next=e._next,e._next._prev=e._prev,delete e._next,delete e._prev}function Gg(e,t){if(e!=="_next"&&e!=="_prev")return t}var Bg=bg,vg=()=>1;function Hg(e,t){if(e.nodeCount()<=1)return[];let n=wg(e,t||vg);return Fg(n.graph,n.buckets,n.zeroIdx).flatMap(r=>e.outEdges(r.v,r.w)||[])}function Fg(e,t,n){var r;let o=[],s=t[t.length-1],i=t[0],a;for(;e.nodeCount();){for(;a=i.dequeue();)Uo(e,t,n,a);for(;a=s.dequeue();)Uo(e,t,n,a);if(e.nodeCount()){for(let T=t.length-2;T>0;--T)if(a=(r=t[T])==null?void 0:r.dequeue(),a){o=o.concat(Uo(e,t,n,a,!0)||[]);break}}}return o}function Uo(e,t,n,r,o){let s=[],i=o?s:void 0;return(e.inEdges(r.v)||[]).forEach(a=>{let T=e.edge(a),l=e.node(a.v);o&&s.push({v:a.v,w:a.w}),l.out-=T,os(t,n,l)}),(e.outEdges(r.v)||[]).forEach(a=>{let T=e.edge(a),l=a.w,R=e.node(l);R.in-=T,os(t,n,R)}),e.removeNode(r.v),i}function wg(e,t){let n=new ge,r=0,o=0;e.nodes().forEach(a=>{n.setNode(a,{v:a,in:0,out:0})}),e.edges().forEach(a=>{let T=n.edge(a.v,a.w)||0,l=t(a),R=T+l;n.setEdge(a.v,a.w,R);let c=n.node(a.v),A=n.node(a.w);o=Math.max(o,c.out+=l),r=Math.max(r,A.in+=l)});let s=Yg(o+r+3).map(()=>new Bg),i=r+1;return n.nodes().forEach(a=>{os(s,i,n.node(a))}),{graph:n,buckets:s,zeroIdx:i}}function os(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 Yg(e){let t=[];for(let n=0;n<e;n++)t.push(n);return t}function Vg(e){(e.graph().acyclicer==="greedy"?Hg(e,t(e)):Wg(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,Gs("rev"))});function t(n){return r=>n.edge(r).weight}}function Wg(e){let t=[],n={},r={};function o(s){Object.hasOwn(r,s)||(r[s]=!0,n[s]=!0,e.outEdges(s).forEach(i=>{Object.hasOwn(n,i.w)?t.push(i):o(i.w)}),delete n[s])}return e.nodes().forEach(o),t}function kg(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 Xg(e){e.graph().dummyChains=[],e.edges().forEach(t=>jg(e,t))}function jg(e,t){let n=t.v,r=e.node(n).rank,o=t.w,s=e.node(o).rank,i=t.name,a=e.edge(t),T=a.labelRank;if(s===r+1)return;e.removeEdge(t);let l,R,c;for(c=0,++r;r<s;++c,++r)a.points=[],R={width:0,height:0,edgeLabel:a,edgeObj:t,rank:r},l=wt(e,"edge",R,"_d"),r===T&&(R.width=a.width,R.height=a.height,R.dummy="edge-label",R.labelpos=a.labelpos),e.setEdge(n,l,{weight:a.weight},i),c===0&&e.graph().dummyChains.push(l),n=l;e.setEdge(n,o,{weight:a.weight},i)}function $g(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 Bs(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),i=s?s.map(T=>T==null?Number.POSITIVE_INFINITY:n(T.w)-e.edge(T).minlen):[],a=He(Math.min,i);return a===Number.POSITIVE_INFINITY&&(a=0),o.rank=a}e.sources().forEach(n)}function Ht(e,t){return e.node(t.w).rank-e.node(t.v).rank-e.edge(t).minlen}var XT=Kg;function Kg(e){let t=new ge({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,i;for(;Jg(t,e)<o&&(s=zg(t,e),!!s);)i=t.hasNode(s.v)?Ht(e,s):-Ht(e,s),qg(t,e,i);return t}function Jg(e,t){function n(r){let o=t.nodeEdges(r);o&&o.forEach(s=>{let i=s.v,a=r===i?s.w:i;!e.hasNode(a)&&!Ht(t,s)&&(e.setNode(a,{}),e.setEdge(r,a,{}),n(a))})}return e.nodes().forEach(n),e.nodeCount()}function zg(e,t){return t.edges().reduce((n,r)=>{let o=Number.POSITIVE_INFINITY;return e.hasNode(r.v)!==e.hasNode(r.w)&&(o=Ht(t,r)),o<n[0]?[o,r]:n},[Number.POSITIVE_INFINITY,null])[1]}function qg(e,t,n){e.nodes().forEach(r=>t.node(r).rank+=n)}var{preorder:Zg,postorder:Qg}=bs,eP=Nt;Nt.initLowLimValues=Hs;Nt.initCutValues=vs;Nt.calcCutValue=jT;Nt.leaveEdge=KT;Nt.enterEdge=JT;Nt.exchangeEdges=zT;function Nt(e){e=mg(e),Bs(e);let t=XT(e);Hs(t),vs(t,e);let n,r;for(;n=KT(t);)r=JT(t,e,n),zT(t,e,n,r)}function vs(e,t){let n=Qg(e,e.nodes());n=n.slice(0,n.length-1),n.forEach(r=>tP(e,t,r))}function tP(e,t,n){let r=e.node(n).parent,o=e.edge(n,r);o.cutvalue=jT(e,t,n)}function jT(e,t,n){let r=e.node(n).parent,o=!0,s=t.edge(n,r),i=0;s||(o=!1,s=t.edge(r,n)),i=s.weight;let a=t.nodeEdges(n);return a&&a.forEach(T=>{let l=T.v===n,R=l?T.w:T.v;if(R!==r){let c=l===o,A=t.edge(T).weight;if(i+=c?A:-A,rP(e,n,R)){let S=e.edge(n,R).cutvalue;i+=c?-S:S}}}),i}function Hs(e,t){arguments.length<2&&(t=e.nodes()[0]),$T(e,{},1,t)}function $T(e,t,n,r,o){let s=n,i=e.node(r);t[r]=!0;let a=e.neighbors(r);return a&&a.forEach(T=>{Object.hasOwn(t,T)||(n=$T(e,t,n,T,r))}),i.low=s,i.lim=n++,o?i.parent=o:delete i.parent,n}function KT(e){return e.edges().find(t=>e.edge(t).cutvalue<0)}function JT(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),i=e.node(o),a=s,T=!1;return s.lim>i.lim&&(a=i,T=!0),t.edges().filter(l=>T===na(e,e.node(l.v),a)&&T!==na(e,e.node(l.w),a)).reduce((l,R)=>Ht(t,R)<Ht(t,l)?R:l)}function zT(e,t,n,r){let o=n.v,s=n.w;e.removeEdge(o,s),e.setEdge(r.v,r.w,{}),Hs(e),vs(e,t),nP(e,t)}function nP(e,t){let n=e.nodes().find(o=>!e.node(o).parent);if(!n)return;let r=Zg(e,[n]);r=r.slice(1),r.forEach(o=>{let s=e.node(o).parent,i=t.edge(o,s),a=!1;i||(i=t.edge(s,o),a=!0),t.node(o).rank=t.node(s).rank+(a?i.minlen:-i.minlen)})}function rP(e,t,n){return e.hasEdge(t,n)}function na(e,t,n){return n.low<=t.lim&&t.lim<=n.lim}var oP=sP;function sP(e){let t=e.graph().ranker;if(typeof t=="function")return t(e);switch(t){case"network-simplex":ra(e);break;case"tight-tree":EP(e);break;case"longest-path":iP(e);break;case"none":break;default:ra(e)}}var iP=Bs;function EP(e){Bs(e),XT(e)}function ra(e){eP(e)}var aP=lP;function lP(e){let t=cP(e);e.graph().dummyChains.forEach(n=>{let r=e.node(n),o=r.edgeObj,s=TP(e,t,o.v,o.w),i=s.path,a=s.lca,T=0,l=i[T],R=!0;for(;n!==o.w;){if(r=e.node(n),R){for(;(l=i[T])!==a&&e.node(l).maxRank<r.rank;)T++;l===a&&(R=!1)}if(!R){for(;T<i.length-1&&e.node(i[T+1]).minRank<=r.rank;)T++;l=i[T]}l!==void 0&&e.setParent(n,l),n=e.successors(n)[0]}})}function TP(e,t,n,r){let o=[],s=[],i=Math.min(t[n].low,t[r].low),a=Math.max(t[n].lim,t[r].lim),T;T=n;do T=e.parent(T),o.push(T);while(T&&(t[T].low>i||a>t[T].lim));let l=T,R=r;for(;(R=e.parent(R))!==l;)s.push(R);return{path:o.concat(s.reverse()),lca:l}}function cP(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(Gr).forEach(r),t}function RP(e){let t=wt(e,"root",{},"_root"),n=AP(e),r=Object.values(n),o=He(Math.max,r)-1,s=2*o+1;e.graph().nestingRoot=t,e.edges().forEach(a=>e.edge(a).minlen*=s);let i=SP(e)+1;e.children(Gr).forEach(a=>qT(e,t,s,i,o,n,a)),e.graph().nodeRankFactor=s}function qT(e,t,n,r,o,s,i){var a;let T=e.children(i);if(!T.length){i!==t&&e.setEdge(t,i,{weight:0,minlen:n});return}let l=ea(e,"_bt"),R=ea(e,"_bb"),c=e.node(i);e.setParent(l,i),c.borderTop=l,e.setParent(R,i),c.borderBottom=R,T.forEach(A=>{var S;qT(e,t,n,r,o,s,A);let d=e.node(A),I=d.borderTop?d.borderTop:A,O=d.borderBottom?d.borderBottom:A,u=d.borderTop?r:2*r,f=I!==O?1:o-((S=s[i])!=null?S:0)+1;e.setEdge(l,I,{weight:u,minlen:f,nestingEdge:!0}),e.setEdge(O,R,{weight:u,minlen:f,nestingEdge:!0})}),e.parent(i)||e.setEdge(t,l,{weight:0,minlen:o+((a=s[i])!=null?a:0)})}function AP(e){let t={};function n(r,o){let s=e.children(r);s&&s.length&&s.forEach(i=>n(i,o+1)),t[r]=o}return e.children(Gr).forEach(r=>n(r,1)),t}function SP(e){return e.edges().reduce((t,n)=>t+e.edge(n).weight,0)}function dP(e){let t=e.graph();e.removeNode(t.nestingRoot),delete t.nestingRoot,e.edges().forEach(n=>{e.edge(n).nestingEdge&&e.removeEdge(n)})}var IP=uP;function uP(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,i=o.maxRank+1;s<i;++s)oa(e,"borderLeft","_bl",n,o,s),oa(e,"borderRight","_br",n,o,s)}}e.children(Gr).forEach(t)}function oa(e,t,n,r,o,s){let i={width:0,height:0,rank:s,borderType:t},a=o[t][s-1],T=wt(e,"border",i,n);o[t][s]=T,e.setParent(T,r),a&&e.setEdge(a,T,{weight:1})}function NP(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="lr"||n==="rl")&&ZT(e)}function OP(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="bt"||n==="rl")&&fP(e),(n==="lr"||n==="rl")&&(CP(e),ZT(e))}function ZT(e){e.nodes().forEach(t=>sa(e.node(t))),e.edges().forEach(t=>sa(e.edge(t)))}function sa(e){let t=e.width;e.width=e.height,e.height=t}function fP(e){e.nodes().forEach(t=>bo(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(bo),Object.hasOwn(r,"y")&&bo(r)})}function bo(e){e.y=-e.y}function CP(e){e.nodes().forEach(t=>Go(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(Go),Object.hasOwn(r,"x")&&Go(r)})}function Go(e){let t=e.x;e.x=e.y,e.y=t}function LP(e){let t={},n=e.nodes().filter(a=>!e.children(a).length),r=n.map(a=>e.node(a).rank),o=He(Math.max,r),s=On(o+1).map(()=>[]);function i(a){if(t[a])return;t[a]=!0;let T=e.node(a);s[T.rank].push(a);let l=e.successors(a);l&&l.forEach(i)}return n.sort((a,T)=>e.node(a).rank-e.node(T).rank).forEach(i),s}function hP(e,t){let n=0;for(let r=1;r<t.length;++r)n+=_P(e,t[r-1],t[r]);return n}function _P(e,t,n){let r=xg(n,n.map((l,R)=>R)),o=t.flatMap(l=>{let R=e.outEdges(l);return R?R.map(c=>({pos:r[c.w],weight:e.edge(c).weight})).sort((c,A)=>c.pos-A.pos):[]}),s=1;for(;s<n.length;)s<<=1;let i=2*s-1;s-=1;let a=new Array(i).fill(0),T=0;return o.forEach(l=>{let R=l.pos+s;a[R]+=l.weight;let c=0;for(;R>0;)R%2&&(c+=a[R+1]),R=R-1>>1,a[R]+=l.weight;T+=l.weight*c}),T}function pP(e,t=[]){return t.map(n=>{let r=e.inEdges(n);if(!r||!r.length)return{v:n};{let o=r.reduce((s,i)=>{let a=e.edge(i),T=e.node(i.v);return{sum:s.sum+a.weight*T.order,weight:s.weight+a.weight}},{sum:0,weight:0});return{v:n,barycenter:o.sum/o.weight,weight:o.weight}}})}function mP(e,t){let n={};e.forEach((o,s)=>{let i={indegree:0,in:[],out:[],vs:[o.v],i:s};o.barycenter!==void 0&&(i.barycenter=o.barycenter,i.weight=o.weight),n[o.v]=i}),t.edges().forEach(o=>{let s=n[o.v],i=n[o.w];s!==void 0&&i!==void 0&&(i.indegree++,s.out.push(i))});let r=Object.values(n).filter(o=>!o.indegree);return DP(r)}function DP(e){let t=[];function n(o){return s=>{s.merged||(s.barycenter===void 0||o.barycenter===void 0||s.barycenter>=o.barycenter)&&gP(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=>fr(o,["vs","i","barycenter","weight"]))}function gP(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 PP(e,t){let n=Mg(e,R=>Object.hasOwn(R,"barycenter")),r=n.lhs,o=n.rhs.sort((R,c)=>c.i-R.i),s=[],i=0,a=0,T=0;r.sort(MP(!!t)),T=ia(s,o,T),r.forEach(R=>{T+=R.vs.length,s.push(R.vs),i+=R.barycenter*R.weight,a+=R.weight,T=ia(s,o,T)});let l={vs:s.flat(1)};return a&&(l.barycenter=i/a,l.weight=a),l}function ia(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 MP(e){return(t,n)=>t.barycenter<n.barycenter?-1:t.barycenter>n.barycenter?1:e?n.i-t.i:t.i-n.i}function QT(e,t,n,r){let o=e.children(t),s=e.node(t),i=s?s.borderLeft:void 0,a=s?s.borderRight:void 0,T={};i&&(o=o.filter(A=>A!==i&&A!==a));let l=pP(e,o);l.forEach(A=>{if(e.children(A.v).length){let S=QT(e,A.v,n,r);T[A.v]=S,Object.hasOwn(S,"barycenter")&&xP(A,S)}});let R=mP(l,n);yP(R,T);let c=PP(R,r);if(i&&a){c.vs=[i,c.vs,a].flat(1);let A=e.predecessors(i);if(A&&A.length){let S=e.node(A[0]),d=e.predecessors(a),I=e.node(d[0]);Object.hasOwn(c,"barycenter")||(c.barycenter=0,c.weight=0),c.barycenter=(c.barycenter*c.weight+S.order+I.order)/(c.weight+2),c.weight+=2}}return c}function yP(e,t){e.forEach(n=>{n.vs=n.vs.flatMap(r=>t[r]?t[r].vs:r)})}function xP(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 UP(e,t,n,r){r||(r=e.nodes());let o=bP(e),s=new ge({compound:!0}).setGraph({root:o}).setDefaultNodeLabel(i=>e.node(i));return r.forEach(i=>{let a=e.node(i),T=e.parent(i);if(a.rank===t||a.minRank<=t&&t<=a.maxRank){s.setNode(i),s.setParent(i,T||o);let l=e[n](i);l&&l.forEach(R=>{let c=R.v===i?R.w:R.v,A=s.edge(c,i),S=A!==void 0?A.weight:0;s.setEdge(c,i,{weight:e.edge(R).weight+S})}),Object.hasOwn(a,"minRank")&&s.setNode(i,{borderLeft:a.borderLeft[t],borderRight:a.borderRight[t]})}}),s}function bP(e){let t;for(;e.hasNode(t=Gs("_root")););return t}function GP(e,t,n){let r={},o;n.forEach(s=>{let i=e.parent(s),a,T;for(;i;){if(a=e.parent(i),a?(T=r[a],r[a]=i):(T=o,o=i),T&&T!==i){t.setEdge(T,i);return}i=a}})}function ec(e,t={}){if(typeof t.customOrder=="function"){t.customOrder(e,ec);return}let n=VT(e),r=Ea(e,On(1,n+1),"inEdges"),o=Ea(e,On(n-1,-1,-1),"outEdges"),s=LP(e);if(aa(e,s),t.disableOptimalOrderHeuristic)return;let i=Number.POSITIVE_INFINITY,a,T=t.constraints||[];for(let l=0,R=0;R<4;++l,++R){BP(l%2?r:o,l%4>=2,T),s=gn(e);let c=hP(e,s);c<i?(R=0,a=Object.assign({},s),i=c):c===i&&(a=structuredClone(s))}aa(e,a)}function Ea(e,t,n){let r=new Map,o=(s,i)=>{r.has(s)||r.set(s,[]),r.get(s).push(i)};for(let s of e.nodes()){let i=e.node(s);if(typeof i.rank=="number"&&o(i.rank,s),typeof i.minRank=="number"&&typeof i.maxRank=="number")for(let a=i.minRank;a<=i.maxRank;a++)a!==i.rank&&o(a,s)}return t.map(function(s){return UP(e,s,n,r.get(s)||[])})}function BP(e,t,n){let r=new ge;e.forEach(function(o){n.forEach(a=>r.setEdge(a.left,a.right));let s=o.graph().root,i=QT(o,s,r,t);i.vs.forEach((a,T)=>o.node(a).order=T),GP(o,r,i.vs)})}function aa(e,t){Object.values(t).forEach(n=>n.forEach((r,o)=>e.node(r).order=o))}function vP(e,t){let n={};function r(o,s){let i=0,a=0,T=o.length,l=s[s.length-1];return s.forEach((R,c)=>{let A=FP(e,R),S=A?e.node(A).order:T;(A||R===l)&&(s.slice(a,c+1).forEach(d=>{let I=e.predecessors(d);I&&I.forEach(O=>{let u=e.node(O),f=u.order;(f<i||S<f)&&!(u.dummy&&e.node(d).dummy)&&tc(n,O,d)})}),a=c+1,i=S)}),s}return t.length&&t.reduce(r),n}function HP(e,t){let n={};function r(s,i,a,T,l){On(i,a).forEach(R=>{let c=s[R];if(c!==void 0&&e.node(c).dummy){let A=e.predecessors(c);A&&A.forEach(S=>{if(S===void 0)return;let d=e.node(S);d.dummy&&(d.order<T||d.order>l)&&tc(n,S,c)})}})}function o(s,i){let a=-1,T=-1,l=0;return i.forEach((R,c)=>{if(e.node(R).dummy==="border"){let A=e.predecessors(R);if(A&&A.length){let S=A[0];if(S===void 0)return;T=e.node(S).order,r(i,l,c,a,T),l=c,a=T}}r(i,l,i.length,T,s.length)}),i}return t.length&&t.reduce(o),n}function FP(e,t){if(e.node(t).dummy){let n=e.predecessors(t);if(n)return n.find(r=>e.node(r).dummy)}}function tc(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 wP(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 YP(e,t,n,r){let o={},s={},i={};return t.forEach(a=>{a.forEach((T,l)=>{o[T]=T,s[T]=T,i[T]=l})}),t.forEach(a=>{let T=-1;a.forEach(l=>{let R=r(l);if(R&&R.length){let c=R.sort((S,d)=>{let I=i[S],O=i[d];return(I!==void 0?I:0)-(O!==void 0?O:0)}),A=(c.length-1)/2;for(let S=Math.floor(A),d=Math.ceil(A);S<=d;++S){let I=c[S];if(I===void 0)continue;let O=i[I];if(O!==void 0&&s[l]===l&&T<O&&!wP(n,l,I)){let u=o[I];u!==void 0&&(s[I]=l,s[l]=o[l]=u,T=O)}}}})}),{root:o,align:s}}function VP(e,t,n,r,o=!1){let s={},i=WP(e,t,n,o),a=o?"borderLeft":"borderRight";function T(S,d){let I=i.nodes().slice(),O={},u=I.pop();for(;u;){if(O[u])S(u);else{O[u]=!0,I.push(u);for(let f of d(u))I.push(f)}u=I.pop()}}function l(S){let d=i.inEdges(S);d?s[S]=d.reduce((I,O)=>{var u;let f=(u=s[O.v])!=null?u:0,N=i.edge(O);return Math.max(I,f+(N!==void 0?N:0))},0):s[S]=0}function R(S){let d=i.outEdges(S),I=Number.POSITIVE_INFINITY;d&&(I=d.reduce((u,f)=>{let N=s[f.w],L=i.edge(f);return Math.min(u,(N!==void 0?N:0)-(L!==void 0?L:0))},Number.POSITIVE_INFINITY));let O=e.node(S);I!==Number.POSITIVE_INFINITY&&O.borderType!==a&&(s[S]=Math.max(s[S]!==void 0?s[S]:0,I))}function c(S){return i.predecessors(S)||[]}function A(S){return i.successors(S)||[]}return T(l,c),T(R,A),Object.keys(r).forEach(S=>{var d;let I=n[S];I!==void 0&&(s[S]=(d=s[I])!=null?d:0)}),s}function WP(e,t,n,r){let o=new ge,s=e.graph(),i=KP(s.nodesep,s.edgesep,r);return t.forEach(a=>{let T;a.forEach(l=>{let R=n[l];if(R!==void 0){if(o.setNode(R),T!==void 0){let c=n[T];if(c!==void 0){let A=o.edge(c,R);o.setEdge(c,R,Math.max(i(e,l,T),A||0))}}T=l}})}),o}function kP(e,t){return Object.values(t).reduce((n,r)=>{let o=Number.NEGATIVE_INFINITY,s=Number.POSITIVE_INFINITY;Object.entries(r).forEach(([a,T])=>{let l=JP(e,a)/2;o=Math.max(T+l,o),s=Math.min(T-l,s)});let i=o-s;return i<n[0]&&(n=[i,r]),n},[Number.POSITIVE_INFINITY,null])[1]}function XP(e,t){let n=Object.values(t),r=He(Math.min,n),o=He(Math.max,n);["u","d"].forEach(s=>{["l","r"].forEach(i=>{let a=s+i,T=e[a];if(!T||T===t)return;let l=Object.values(T),R=r-He(Math.min,l);i!=="l"&&(R=o-He(Math.max,l)),R&&(e[a]=br(T,c=>c+R))})})}function jP(e,t=void 0){let n=e.ul;return n?br(n,(r,o)=>{var s,i;if(t){let T=t.toLowerCase(),l=e[T];if(l&&l[o]!==void 0)return l[o]}let a=Object.values(e).map(T=>{let l=T[o];return l!==void 0?l:0}).sort((T,l)=>T-l);return(((s=a[1])!=null?s:0)+((i=a[2])!=null?i:0))/2}):{}}function $P(e){let t=gn(e),n=Object.assign(vP(e,t),HP(e,t)),r={},o;["u","d"].forEach(i=>{o=i==="u"?t:Object.values(t).reverse(),["l","r"].forEach(a=>{a==="r"&&(o=o.map(R=>Object.values(R).reverse()));let T=YP(e,o,n,R=>(i==="u"?e.predecessors(R):e.successors(R))||[]),l=VP(e,o,T.root,T.align,a==="r");a==="r"&&(l=br(l,R=>-R)),r[i+a]=l})});let s=kP(e,r);return XP(r,s),jP(r,e.graph().align)}function KP(e,t,n){return(r,o,s)=>{let i=r.node(o),a=r.node(s),T=0,l;if(T+=i.width/2,Object.hasOwn(i,"labelpos"))switch(i.labelpos.toLowerCase()){case"l":l=-i.width/2;break;case"r":l=i.width/2;break}if(l&&(T+=n?l:-l),l=void 0,T+=(i.dummy?t:e)/2,T+=(a.dummy?t:e)/2,T+=a.width/2,Object.hasOwn(a,"labelpos"))switch(a.labelpos.toLowerCase()){case"l":l=a.width/2;break;case"r":l=-a.width/2;break}return l&&(T+=n?l:-l),T}}function JP(e,t){return e.node(t).width}function zP(e){e=wT(e),qP(e),Object.entries($P(e)).forEach(([t,n])=>e.node(t).x=n)}function qP(e){let t=gn(e),n=e.graph(),r=n.ranksep,o=n.rankalign,s=0;t.forEach(i=>{let a=i.reduce((T,l)=>{var R;let c=(R=e.node(l).height)!=null?R:0;return T>c?T:c},0);i.forEach(T=>{let l=e.node(T);o==="top"?l.y=s+l.height/2:o==="bottom"?l.y=s+a-l.height/2:l.y=s+a/2}),s+=a+r})}function ZP(e,t={}){let n=t.debugTiming?WT:kT;return n("layout",()=>{let r=n(" buildLayoutGraph",()=>aM(e));return n(" runLayout",()=>QP(r,n,t)),n(" updateInputGraph",()=>eM(e,r)),r})}function QP(e,t,n){t(" makeSpaceForEdgeLabels",()=>lM(e)),t(" removeSelfEdges",()=>NM(e)),t(" acyclic",()=>Vg(e)),t(" nestingGraph.run",()=>RP(e)),t(" rank",()=>oP(wT(e))),t(" injectEdgeLabelProxies",()=>TM(e)),t(" removeEmptyRanks",()=>gg(e)),t(" nestingGraph.cleanup",()=>dP(e)),t(" normalizeRanks",()=>Dg(e)),t(" assignRankMinMax",()=>cM(e)),t(" removeEdgeLabelProxies",()=>RM(e)),t(" normalize.run",()=>Xg(e)),t(" parentDummyChains",()=>aP(e)),t(" addBorderSegments",()=>IP(e)),t(" order",()=>ec(e,n)),t(" insertSelfEdges",()=>OM(e)),t(" adjustCoordinateSystem",()=>NP(e)),t(" position",()=>zP(e)),t(" positionSelfEdges",()=>fM(e)),t(" removeBorderNodes",()=>uM(e)),t(" normalize.undo",()=>$g(e)),t(" fixupEdgeLabelCoords",()=>dM(e)),t(" undoCoordinateSystem",()=>OP(e)),t(" translateGraph",()=>AM(e)),t(" assignNodeIntersects",()=>SM(e)),t(" reversePoints",()=>IM(e)),t(" acyclic.undo",()=>kg(e))}function eM(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 tM=["nodesep","edgesep","ranksep","marginx","marginy"],nM={ranksep:50,edgesep:20,nodesep:50,rankdir:"TB",rankalign:"center"},rM=["acyclicer","ranker","rankdir","align","rankalign"],oM=["width","height","rank"],la={width:0,height:0},sM=["minlen","weight","width","height","labeloffset"],iM={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},EM=["labelpos"];function aM(e){let t=new ge({multigraph:!0,compound:!0}),n=vo(e.graph());return t.setGraph(Object.assign({},nM,Bo(n,tM),fr(n,rM))),e.nodes().forEach(r=>{let o=vo(e.node(r)),s=Bo(o,oM);Object.keys(la).forEach(a=>{s[a]===void 0&&(s[a]=la[a])}),t.setNode(r,s);let i=e.parent(r);i!==void 0&&t.setParent(r,i)}),e.edges().forEach(r=>{let o=vo(e.edge(r));t.setEdge(r,Object.assign({},iM,Bo(o,sM),fr(o,EM)))}),t}function lM(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 TM(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};wt(e,"edge-proxy",o,"_ep")}})}function cM(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 RM(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 AM(e){let t=Number.POSITIVE_INFINITY,n=0,r=Number.POSITIVE_INFINITY,o=0,s=e.graph(),i=s.marginx||0,a=s.marginy||0;function T(l){let R=l.x,c=l.y,A=l.width,S=l.height;t=Math.min(t,R-A/2),n=Math.max(n,R+A/2),r=Math.min(r,c-S/2),o=Math.max(o,c+S/2)}e.nodes().forEach(l=>T(e.node(l))),e.edges().forEach(l=>{let R=e.edge(l);Object.hasOwn(R,"x")&&T(R)}),t-=i,r-=a,e.nodes().forEach(l=>{let R=e.node(l);R.x-=t,R.y-=r}),e.edges().forEach(l=>{let R=e.edge(l);R.points.forEach(c=>{c.x-=t,c.y-=r}),Object.hasOwn(R,"x")&&(R.x-=t),Object.hasOwn(R,"y")&&(R.y-=r)}),s.width=n-t+i,s.height=o-r+a}function SM(e){e.edges().forEach(t=>{let n=e.edge(t),r=e.node(t.v),o=e.node(t.w),s,i;n.points?(s=n.points[0],i=n.points[n.points.length-1]):(n.points=[],s=o,i=r),n.points.unshift(QE(r,s)),n.points.push(QE(o,i))})}function dM(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 IM(e){e.edges().forEach(t=>{let n=e.edge(t);n.reversed&&n.points.reverse()})}function uM(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]),i=e.node(n.borderRight[n.borderRight.length-1]);n.width=Math.abs(i.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 NM(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 OM(e){gn(e).forEach(t=>{let n=0;t.forEach((r,o)=>{let s=e.node(r);s.order=o+n,(s.selfEdges||[]).forEach(i=>{wt(e,"selfedge",{width:i.label.width,height:i.label.height,rank:s.rank,order:o+ ++n,e:i.e,label:i.label},"_se")}),delete s.selfEdges})})}function fM(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,i=o.y,a=n.x-s,T=o.height/2;e.setEdge(r.e,r.label),e.removeNode(t),r.label.points=[{x:s+2*a/3,y:i-T},{x:s+5*a/6,y:i-T},{x:s+a,y:i},{x:s+5*a/6,y:i+T},{x:s+2*a/3,y:i+T}],r.label.x=n.x,r.label.y=n.y}})}function Bo(e,t){return br(fr(e,t),Number)}function vo(e){let t={};return e&&Object.entries(e).forEach(([n,r])=>{typeof n=="string"&&(n=n.toLowerCase()),t[n]=r}),t}function CM(e){let t=gn(e),n=new ge({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((i,a)=>(n.setEdge(i,a,{style:"invis"}),a))}),n}var LM={graphlib:yT,version:Ug,layout:ZP,debug:CM,util:{time:WT,notime:kT}},Ta=LM;/*! For license information please see dagre.esm.js.LEGAL.txt */const Be={source_table:"#8b949e",block:"#56d364",metric:"#388bfd",dimension:"#e3b341",domain:"#d2a8ff",chart:"#f778ba"},tr={source_table:"TABLE",block:"BLOCK",metric:"METRIC",dimension:"DIM",domain:"DOMAIN",chart:"CHART"},nc={certified:"#56d364",draft:"#8b949e",review:"#e3b341",deprecated:"#f85149",pending_recertification:"#d29922"},Ho={reads_from:"#8b949e",feeds_into:"#56d364",aggregates:"#388bfd",visualizes:"#f778ba",crosses_domain:"#d2a8ff"};function hM(e,t,n="LR"){const r=new Ta.graphlib.Graph().setDefaultEdgeLabel(()=>({}));r.setGraph({rankdir:n,ranksep:80,nodesep:40,marginx:40,marginy:40});for(const s of e){const i=s.type==="domainGroup"?200:180,a=s.type==="domainGroup"?60:56;r.setNode(s.id,{width:i,height:a})}for(const s of t)r.setEdge(s.source,s.target);return Ta.layout(r),{nodes:e.map(s=>{const i=r.node(s.id),a=s.type==="domainGroup"?200:180,T=s.type==="domainGroup"?60:56;return{...s,position:{x:i.x-a/2,y:i.y-T/2}}}),edges:t}}function _M({data:e,selected:t}){const n=e.nodeType,r=Be[n]??"#8b949e",o=tr[n]??n.slice(0,5).toUpperCase(),s=e.label,i=e.domain,a=e.status,T=a?nc[a]:void 0,l=e.highlighted,R=e.dimmed;return E.jsxs("div",{style:{background:"#161b22",border:`2px solid ${t?"#58a6ff":l?r:"#30363d"}`,borderRadius:8,padding:"6px 10px",minWidth:140,maxWidth:200,opacity:R?.3:1,transition:"opacity 0.2s, border-color 0.2s",cursor:"pointer"},children:[E.jsx(vt,{type:"target",position:Z.Left,style:{background:r,width:6,height:6,border:"none"}}),E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginBottom:3},children:[E.jsx("span",{style:{fontSize:9,fontWeight:700,color:"#0d1117",background:r,borderRadius:3,padding:"1px 5px",letterSpacing:"0.5px"},children:o}),i&&E.jsx("span",{style:{fontSize:9,color:"#8b949e"},children:i}),T&&E.jsx("span",{style:{marginLeft:"auto",width:7,height:7,borderRadius:"50%",background:T,flexShrink:0},title:a})]}),E.jsx("div",{style:{fontSize:11,fontWeight:600,color:"#e6edf3",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:s,children:s}),E.jsx(vt,{type:"source",position:Z.Right,style:{background:r,width:6,height:6,border:"none"}})]})}const pM={dagNode:_M};function qt({label:e,color:t,active:n,count:r,onClick:o}){return E.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:[E.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:n?t:"#484f58"}}),e,E.jsx("span",{style:{fontWeight:400,opacity:.7},children:r})]})}function mM(){const{state:e}=ae(),t=ie[e.themeMode],[n,r]=C.useState(!0),[o,s]=C.useState([]),[i,a]=C.useState([]),[T,l,R]=hD([]),[c,A,S]=_D([]),[d,I]=C.useState(!0),[O,u]=C.useState(!0),[f,N]=C.useState(!0),[L,m]=C.useState(!0),[p,D]=C.useState(!0),[M,B]=C.useState(null),[F,g]=C.useState(new Set),[_,U]=C.useState(null),[h,x]=C.useState([]),[P,v]=C.useState([]),b=C.useCallback(async()=>{r(!0);const k=await Re.fetchLineage();s(k.nodes??[]),a(k.edges??[]),r(!1)},[]);C.useEffect(()=>{b()},[b]);const y=C.useMemo(()=>{const k=new Set;return d&&k.add("source_table"),O&&k.add("block"),f&&k.add("metric"),L&&k.add("dimension"),p&&k.add("chart"),k.add("domain"),k},[d,O,f,L,p]);C.useEffect(()=>{const k=o.filter(j=>y.has(j.type)),X=new Set(k.map(j=>j.id)),K=k.map(j=>({id:j.id,type:"dagNode",position:{x:0,y:0},data:{label:j.name,nodeType:j.type,domain:j.domain,status:j.status,owner:j.owner,highlighted:F.has(j.id),dimmed:F.size>0&&!F.has(j.id)}})),Q=i.filter(j=>X.has(j.source)&&X.has(j.target)&&j.type!=="crosses_domain").map((j,$)=>({id:`e-${$}`,source:j.source,target:j.target,type:"default",animated:j.type==="feeds_into",style:{stroke:Ho[j.type]??"#30363d",strokeWidth:F.size>0?F.has(j.source)&&F.has(j.target)?2.5:.5:1.5,opacity:F.size>0?F.has(j.source)&&F.has(j.target)?1:.15:.7},markerEnd:{type:dn.ArrowClosed,width:12,height:12,color:Ho[j.type]??"#30363d"}}));if(K.length>0){const j=hM(K,Q,"LR");l(j.nodes),A(j.edges)}else l([]),A([])},[o,i,y,F,l,A]);const Y=C.useCallback(async(k,X)=>{if(M===X.id){B(null),g(new Set),U(null),x([]),v([]);return}B(X.id);const K=o.find(q=>q.id===X.id);U(K??null);const Q=new Set,j=new Set;function $(q){for(const z of i)z.target===q&&z.type!=="crosses_domain"&&!Q.has(z.source)&&(Q.add(z.source),$(z.source))}function ee(q){for(const z of i)z.source===q&&z.type!=="crosses_domain"&&!j.has(z.target)&&(j.add(z.target),ee(z.target))}$(X.id),ee(X.id);const re=new Set([X.id,...Q,...j]);if(g(re),x(o.filter(q=>Q.has(q.id))),v(o.filter(q=>j.has(q.id))),(K==null?void 0:K.type)==="block"){const q=await Re.fetchBlockLineage(K.name);q&&(x(q.ancestors??[]),v(q.descendants??[]))}},[M,o,i]),W=C.useCallback(()=>{B(null),g(new Set),U(null),x([]),v([])},[]),V=C.useMemo(()=>{const k={};for(const X of o)k[X.type]=(k[X.type]??0)+1;return k},[o]);return n?E.jsx("div",{style:{padding:16,color:t.textMuted,fontSize:12,height:"100%"},children:"Loading lineage graph..."}):o.length===0?E.jsxs("div",{style:{padding:16,color:t.textMuted,fontSize:12,height:"100%"},children:["No lineage data. Add DQL blocks or run ",E.jsx("code",{children:"dql compile"})," to generate lineage."]}):E.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",background:"#0d1117"},children:[E.jsxs("div",{style:{display:"flex",gap:4,padding:"6px 8px",flexWrap:"wrap",borderBottom:`1px solid ${t.headerBorder}`,background:t.sidebarBg,flexShrink:0},children:[E.jsx(qt,{label:"Tables",color:Be.source_table,active:d,count:V.source_table??0,onClick:()=>I(!d)}),E.jsx(qt,{label:"Blocks",color:Be.block,active:O,count:V.block??0,onClick:()=>u(!O)}),E.jsx(qt,{label:"Metrics",color:Be.metric,active:f,count:V.metric??0,onClick:()=>N(!f)}),E.jsx(qt,{label:"Dims",color:Be.dimension,active:L,count:V.dimension??0,onClick:()=>m(!L)}),E.jsx(qt,{label:"Charts",color:Be.chart,active:p,count:V.chart??0,onClick:()=>D(!p)})]}),E.jsx("div",{style:{flex:1,position:"relative"},children:E.jsxs(LD,{nodes:T,edges:c,onNodesChange:R,onEdgesChange:S,onNodeClick:Y,onPaneClick:W,nodeTypes:pM,fitView:!0,fitViewOptions:{padding:.2},minZoom:.1,maxZoom:2,proOptions:{hideAttribution:!0},style:{background:"#0d1117"},children:[E.jsx(PD,{color:"#21262d",gap:24,size:1}),E.jsx(BD,{showInteractive:!1,style:{button:{background:"#161b22",color:"#e6edf3",border:"1px solid #30363d"}}}),E.jsx(JD,{nodeColor:k=>{var K;const X=(K=k.data)==null?void 0:K.nodeType;return Be[X]??"#8b949e"},maskColor:"rgba(0,0,0,0.6)",style:{background:"#0d1117",border:"1px solid #30363d"}}),E.jsx(Dn,{position:"bottom-left",children:E.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(Ho).map(([k,X])=>E.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3},children:[E.jsx("span",{style:{width:12,height:2,background:X,borderRadius:1}}),k.replace(/_/g," ")]},k))})})]})}),_&&E.jsxs("div",{style:{flexShrink:0,maxHeight:180,overflow:"auto",borderTop:`1px solid ${t.headerBorder}`,background:t.sidebarBg,padding:8,fontSize:11},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginBottom:6},children:[E.jsx("span",{style:{fontSize:9,fontWeight:700,color:"#0d1117",background:Be[_.type]??"#8b949e",borderRadius:3,padding:"1px 5px"},children:tr[_.type]??_.type}),E.jsx("span",{style:{fontWeight:600,color:t.textPrimary,flex:1},children:_.name}),E.jsx("button",{onClick:()=>{B(null),g(new Set),U(null)},style:{background:"transparent",border:"none",color:t.textMuted,cursor:"pointer",fontSize:14},children:"×"})]}),_.domain&&E.jsxs("div",{style:{color:t.textMuted,marginBottom:2},children:["Domain: ",E.jsx("span",{style:{color:"#d2a8ff"},children:_.domain})]}),_.owner&&E.jsxs("div",{style:{color:t.textMuted,marginBottom:2},children:["Owner: ",E.jsx("span",{style:{color:t.textSecondary},children:_.owner})]}),_.status&&E.jsxs("div",{style:{color:t.textMuted,marginBottom:4},children:["Status: ",E.jsx("span",{style:{color:nc[_.status]??t.textSecondary},children:_.status})]}),h.length>0&&E.jsxs("div",{style:{marginTop:4},children:[E.jsxs("div",{style:{color:t.textMuted,fontSize:9,fontWeight:600,textTransform:"uppercase",marginBottom:2},children:["Upstream (",h.length,")"]}),h.slice(0,8).map(k=>{var X;return E.jsxs("div",{style:{padding:"1px 0",color:t.textSecondary,display:"flex",alignItems:"center",gap:3},children:[E.jsx("span",{style:{color:Be[k.type],fontSize:8,fontWeight:700},children:((X=tr[k.type])==null?void 0:X.slice(0,3))??"???"}),k.name]},k.id)}),h.length>8&&E.jsxs("div",{style:{color:t.textMuted,fontSize:10},children:["+",h.length-8," more"]})]}),P.length>0&&E.jsxs("div",{style:{marginTop:4},children:[E.jsxs("div",{style:{color:t.textMuted,fontSize:9,fontWeight:600,textTransform:"uppercase",marginBottom:2},children:["Downstream (",P.length,")"]}),P.slice(0,8).map(k=>{var X;return E.jsxs("div",{style:{padding:"1px 0",color:t.textSecondary,display:"flex",alignItems:"center",gap:3},children:[E.jsx("span",{style:{color:Be[k.type],fontSize:8,fontWeight:700},children:((X=tr[k.type])==null?void 0:X.slice(0,3))??"???"}),k.name]},k.id)}),P.length>8&&E.jsxs("div",{style:{color:t.textMuted,fontSize:10},children:["+",P.length-8," more"]})]})]})]})}function DM(){const{state:e,dispatch:t}=ae(),n=ie[e.themeMode],r=C.useRef({}),o=C.useCallback(async a=>{try{const{content:T}=await Re.readNotebook(a.path),{title:l,cells:R}=oS(a.path,T);t({type:"OPEN_FILE",file:a,cells:R,title:l}),e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"})}catch(T){console.error("Failed to open file:",T),t({type:"OPEN_FILE",file:a,cells:[fe("sql")],title:a.name})}},[t,e.sidebarPanel]),s=C.useCallback(a=>{const T=r.current[a];T&&T.scrollIntoView({behavior:"smooth",block:"start"})},[]),i=C.useCallback((a,T)=>{T?r.current[a]=T:delete r.current[a]},[]);return E.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100vh",width:"100vw",background:n.appBg,fontFamily:n.font,color:n.textPrimary,overflow:"hidden"},children:[E.jsx(LS,{}),E.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[E.jsx(rA,{}),e.sidebarOpen&&E.jsx(eS,{onOpenFile:o,onNavigateToCell:s}),E.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:e.lineageFullscreen?E.jsx(mM,{}):E.jsxs(E.Fragment,{children:[E.jsx(Bf,{onOpenFile:o,registerCellRef:i}),E.jsx(mS,{})]})})]}),e.newNotebookModalOpen&&E.jsx(Vf,{onFileOpened:o}),e.newBlockModalOpen&&E.jsx(Xf,{onFileOpened:o})]})}function gM(){const{state:e,dispatch:t}=ae(),n=C.useRef(null),r=C.useRef(null);C.useEffect(()=>{var o;n.current=((o=e.activeFile)==null?void 0:o.path)??null},[e.activeFile]),C.useEffect(()=>{if(typeof EventSource>"u")return;const o=()=>{const s=new EventSource(`${window.location.origin}/api/watch`);r.current=s,s.addEventListener("change",i=>{try{const a=JSON.parse(i.data);(a.type==="file-added"||a.type==="file-deleted")&&Re.listNotebooks().then(T=>{t({type:"SET_FILES",files:T})}),a.type==="file-changed"&&Re.listNotebooks().then(T=>{t({type:"SET_FILES",files:T})}),a.type==="semantic-reload"&&(t({type:"SET_SEMANTIC_LOADING",loading:!0}),Re.getSemanticLayer().then(T=>{t({type:"SET_SEMANTIC_LAYER",layer:T})}))}catch{}}),s.addEventListener("error",()=>{s.close(),setTimeout(o,5e3)})};return o(),()=>{var s;(s=r.current)==null||s.close(),r.current=null}},[t])}function PM(){const{state:e,dispatch:t}=ae(),n=ie[e.themeMode];return C.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=`
513
- * { margin: 0; padding: 0; box-sizing: border-box; }
514
- body {
515
- font-family: ${n.font};
516
- overflow: hidden;
517
- background: ${n.appBg};
518
- color: ${n.textPrimary};
519
- }
520
- ::-webkit-scrollbar { width: 6px; height: 6px; }
521
- ::-webkit-scrollbar-track { background: transparent; }
522
- ::-webkit-scrollbar-thumb {
523
- background: ${n.scrollbarThumb};
524
- border-radius: 3px;
525
- }
526
- ::-webkit-scrollbar-thumb:hover {
527
- background: ${n.textMuted};
528
- }
529
- ::selection {
530
- background: ${n.accent}40;
531
- color: ${n.textPrimary};
532
- }
533
- `},[n]),C.useEffect(()=>{t({type:"SET_FILES_LOADING",loading:!0}),Re.listNotebooks().then(r=>{t({type:"SET_FILES",files:r}),t({type:"SET_FILES_LOADING",loading:!1})})},[t]),C.useEffect(()=>{t({type:"SET_SCHEMA_LOADING",loading:!0}),Re.getSchema().then(r=>{t({type:"SET_SCHEMA",tables:r}),t({type:"SET_SCHEMA_LOADING",loading:!1})})},[t]),gM(),E.jsx(DM,{})}function MM(){return E.jsx(XR,{children:E.jsx(PM,{})})}VR.createRoot(document.getElementById("root")).render(E.jsx(MM,{}));