@duckcodeailabs/dql-cli 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/args.js +1 -1
- package/dist/args.js.map +1 -1
- package/dist/args.test.js +3 -3
- package/dist/args.test.js.map +1 -1
- package/dist/assets/dql-notebook/assets/index-BZV40eAE.css +1 -0
- package/dist/assets/dql-notebook/assets/index-BsWoK_RX.js +532 -0
- package/dist/assets/dql-notebook/index.html +2 -1
- package/dist/commands/compile.d.ts.map +1 -1
- package/dist/commands/compile.js +4 -2
- package/dist/commands/compile.js.map +1 -1
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +104 -90
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/init.test.js +8 -10
- package/dist/commands/init.test.js.map +1 -1
- package/dist/commands/lineage.js +16 -0
- package/dist/commands/lineage.js.map +1 -1
- package/dist/commands/new.test.js +8 -8
- package/dist/commands/new.test.js.map +1 -1
- package/dist/index.js +1 -2
- package/dist/index.js.map +1 -1
- package/dist/package.json +7 -7
- package/package.json +15 -14
- package/LICENSE +0 -123
- package/dist/assets/dql-notebook/assets/index-B_X7pyPz.js +0 -510
- package/dist/assets/templates/dashboard/README.md +0 -30
- package/dist/assets/templates/dashboard/blocks/.gitkeep +0 -1
- package/dist/assets/templates/dashboard/dashboards/pipeline_overview.dql +0 -23
- package/dist/assets/templates/dashboard/data/pipeline.csv +0 -7
- package/dist/assets/templates/dashboard/dql.config.json +0 -18
- package/dist/assets/templates/dashboard/semantic-layer/.gitkeep +0 -1
- package/dist/assets/templates/dql.config.reference.json +0 -154
- package/dist/assets/templates/duckdb-local/README.md +0 -30
- package/dist/assets/templates/duckdb-local/blocks/orders_by_region.dql +0 -24
- package/dist/assets/templates/duckdb-local/data/orders.csv +0 -7
- package/dist/assets/templates/duckdb-local/dql.config.json +0 -18
- package/dist/assets/templates/duckdb-local/semantic-layer/.gitkeep +0 -1
- package/dist/assets/templates/ecommerce/README.md +0 -33
- package/dist/assets/templates/ecommerce/blocks/repeat_rate.dql +0 -26
- package/dist/assets/templates/ecommerce/blocks/revenue_by_segment.dql +0 -24
- package/dist/assets/templates/ecommerce/dashboards/revenue_command_center.dql +0 -25
- package/dist/assets/templates/ecommerce/data/customers.csv +0 -11
- package/dist/assets/templates/ecommerce/data/funnel.csv +0 -6
- package/dist/assets/templates/ecommerce/data/orders.csv +0 -16
- package/dist/assets/templates/ecommerce/dql.config.json +0 -18
- package/dist/assets/templates/ecommerce/semantic-layer/cubes/customers_cube.yaml +0 -49
- package/dist/assets/templates/ecommerce/semantic-layer/cubes/orders_cube.yaml +0 -70
- package/dist/assets/templates/ecommerce/semantic-layer/dimensions/channel.yaml +0 -8
- package/dist/assets/templates/ecommerce/semantic-layer/dimensions/order_date.yaml +0 -9
- package/dist/assets/templates/ecommerce/semantic-layer/dimensions/region.yaml +0 -9
- package/dist/assets/templates/ecommerce/semantic-layer/dimensions/segment.yaml +0 -8
- package/dist/assets/templates/ecommerce/semantic-layer/hierarchies/customer_geo.yaml +0 -18
- package/dist/assets/templates/ecommerce/semantic-layer/metrics/avg_order_value.yaml +0 -10
- package/dist/assets/templates/ecommerce/semantic-layer/metrics/gmv.yaml +0 -10
- package/dist/assets/templates/ecommerce/semantic-layer/metrics/gross_margin.yaml +0 -10
- package/dist/assets/templates/ecommerce/semantic-layer/metrics/order_count.yaml +0 -10
- package/dist/assets/templates/ecommerce/workbooks/.gitkeep +0 -1
- package/dist/assets/templates/finance-kpi/README.md +0 -31
- package/dist/assets/templates/finance-kpi/blocks/arr_kpi.dql +0 -21
- package/dist/assets/templates/finance-kpi/data/revenue.csv +0 -7
- package/dist/assets/templates/finance-kpi/dql.config.json +0 -18
- package/dist/assets/templates/finance-kpi/semantic-layer/.gitkeep +0 -1
- package/dist/assets/templates/saas/README.md +0 -32
- package/dist/assets/templates/saas/blocks/churn_pressure.dql +0 -25
- package/dist/assets/templates/saas/blocks/revenue_by_segment.dql +0 -25
- package/dist/assets/templates/saas/dashboards/growth_scorecard.dql +0 -25
- package/dist/assets/templates/saas/data/cohorts.csv +0 -7
- package/dist/assets/templates/saas/data/subscriptions.csv +0 -13
- package/dist/assets/templates/saas/dql.config.json +0 -18
- package/dist/assets/templates/saas/semantic-layer/dimensions/owner_segment.yaml +0 -8
- package/dist/assets/templates/saas/semantic-layer/dimensions/plan_tier.yaml +0 -8
- package/dist/assets/templates/saas/semantic-layer/dimensions/risk_bucket.yaml +0 -9
- package/dist/assets/templates/saas/semantic-layer/dimensions/status.yaml +0 -8
- package/dist/assets/templates/saas/semantic-layer/hierarchies/account_segments.yaml +0 -18
- package/dist/assets/templates/saas/semantic-layer/metrics/account_count.yaml +0 -10
- package/dist/assets/templates/saas/semantic-layer/metrics/expansion_mrr.yaml +0 -11
- package/dist/assets/templates/saas/semantic-layer/metrics/mrr.yaml +0 -10
- package/dist/assets/templates/saas/workbooks/.gitkeep +0 -1
- package/dist/assets/templates/starter/README.md +0 -48
- package/dist/assets/templates/starter/blocks/revenue_by_segment.dql +0 -29
- package/dist/assets/templates/starter/blocks/revenue_trend_query_only.dql +0 -20
- package/dist/assets/templates/starter/dashboards/.gitkeep +0 -1
- package/dist/assets/templates/starter/data/revenue.csv +0 -13
- package/dist/assets/templates/starter/dql.config.json +0 -18
- package/dist/assets/templates/starter/notebooks/semantic_layer_tutorial.dqlnb +0 -60
- package/dist/assets/templates/starter/semantic-layer/blocks/revenue_by_segment.yaml +0 -11
- package/dist/assets/templates/starter/semantic-layer/cubes/revenue_cube.yaml +0 -77
- package/dist/assets/templates/starter/semantic-layer/dimensions/segment_tier.yaml +0 -6
- package/dist/assets/templates/starter/semantic-layer/hierarchies/revenue_time.yaml +0 -12
- package/dist/assets/templates/starter/semantic-layer/metrics/revenue.yaml +0 -7
- package/dist/assets/templates/starter/workbooks/.gitkeep +0 -1
- package/dist/assets/templates/taxi/README.md +0 -31
- package/dist/assets/templates/taxi/blocks/airport_mix.dql +0 -25
- package/dist/assets/templates/taxi/blocks/revenue_by_segment.dql +0 -24
- package/dist/assets/templates/taxi/dashboards/city_operations.dql +0 -25
- package/dist/assets/templates/taxi/data/trips.csv +0 -13
- package/dist/assets/templates/taxi/dql.config.json +0 -18
- package/dist/assets/templates/taxi/semantic-layer/.gitkeep +0 -1
- package/dist/assets/templates/taxi/semantic-layer/dimensions/airport_flag.yaml +0 -8
- package/dist/assets/templates/taxi/semantic-layer/dimensions/dropoff_borough.yaml +0 -9
- package/dist/assets/templates/taxi/semantic-layer/dimensions/payment_type.yaml +0 -8
- package/dist/assets/templates/taxi/semantic-layer/dimensions/pickup_borough.yaml +0 -9
- package/dist/assets/templates/taxi/semantic-layer/dimensions/pickup_date.yaml +0 -9
- package/dist/assets/templates/taxi/semantic-layer/hierarchies/trip_route.yaml +0 -14
- package/dist/assets/templates/taxi/semantic-layer/metrics/avg_trip_miles.yaml +0 -10
- package/dist/assets/templates/taxi/semantic-layer/metrics/total_fare.yaml +0 -10
- package/dist/assets/templates/taxi/semantic-layer/metrics/total_tips.yaml +0 -10
- package/dist/assets/templates/taxi/semantic-layer/metrics/trip_count.yaml +0 -10
- package/dist/assets/templates/taxi/workbooks/.gitkeep +0 -1
- package/dist/assets/templates/workbook/README.md +0 -30
- package/dist/assets/templates/workbook/blocks/.gitkeep +0 -1
- package/dist/assets/templates/workbook/data/finance.csv +0 -7
- package/dist/assets/templates/workbook/dql.config.json +0 -18
- package/dist/assets/templates/workbook/semantic-layer/.gitkeep +0 -1
- package/dist/assets/templates/workbook/workbooks/quarterly_business_review.dql +0 -32
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
import{r as Cr,a as la,g as so}from"./react-CRB3T2We.js";import{S as oo,g as Ta,E as be,s as sR,a as he,b as oR,c as iR,P as ER,d as aR,e as lR,F as TR,f as cR,h as ca,V as RR,D as io,R as AR,i as SR,C as tt,j as Ra,k as me,r as dR,l as IR,m as uR,t as NR,n as fR,o as CR,p as LR,q as _R,u as hR,v as pR,w as yn,x as mR,y as DR,z as PR,A as gR,B as MR,G as yR,H as xR,I as UR,J as bR,K as GR,L as BR}from"./codemirror-CCrEt63p.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(s){if(s.ep)return;s.ep=!0;const o=n(s);fetch(s.href,o)}})();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 jo;function vR(){if(jo)return Xt;jo=1;var e=Cr(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,s=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,o={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)&&!o.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:s.current}}return Xt.Fragment=n,Xt.jsx=i,Xt.jsxs=i,Xt}var Ko;function HR(){return Ko||(Ko=1,Fr.exports=vR()),Fr.exports}var E=HR(),xn={},Jo;function FR(){if(Jo)return xn;Jo=1;var e=la();return xn.createRoot=e.createRoot,xn.hydrateRoot=e.hydrateRoot,xn}var wR=FR(),f=Cr();const sn=so(f),YR={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,executionCounter:0,savingFile:!1,lineageFullscreen:!1};function VR(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(s=>s.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(s=>s.id===t.id?{...s,...t.updates}:s),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(s=>s.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"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 Aa=f.createContext(null);function WR({children:e}){const[t,n]=f.useReducer(VR,YR);return E.jsx(Aa.Provider,{value:{state:t,dispatch:n},children:e})}function ae(){const e=f.useContext(Aa);if(!e)throw new Error("useNotebook must be used within NotebookProvider");return e}function je(){return`cell_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function De(e,t=""){const n={id:je(),type:e,content:t,status:"idle"};return e==="param"&&(n.content="",n.paramConfig={paramType:"text",label:"Parameter",defaultValue:"",options:[]}),n}const kR={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"},XR={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"},Ee={dark:kR,light:XR};function We({title:e,active:t,onClick:n,children:r,t:s}){const[o,i]=f.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 ${s.accent}`:"2px solid transparent",cursor:"pointer",color:t?s.textPrimary:o?s.textSecondary:s.textMuted,transition:"color 0.15s, border-color 0.15s",padding:0,flexShrink:0},children:r})}function $R(){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 KR(){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 JR(){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 ZR(){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 QR(){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 eA(){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 tA(){const{state:e,dispatch:t}=ae(),n=Ee[e.themeMode];function r(s){e.sidebarPanel===s&&e.sidebarOpen?t({type:"TOGGLE_SIDEBAR"}):t({type:"SET_SIDEBAR_PANEL",panel:s})}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($R,{})}),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(KR,{})}),E.jsx(We,{title:"Lineage",active:e.sidebarPanel==="lineage"&&e.sidebarOpen,onClick:()=>r("lineage"),t:n,children:E.jsx(JR,{})}),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(ZR,{})}),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(QR,{})}),E.jsx(We,{title:"Settings",active:!1,onClick:()=>{},t:n,children:E.jsx(eA,{})})]})}const wr={notebooks:"Notebooks",workbooks:"Workbooks",blocks:"Blocks",dashboards:"Dashboards"};function nA({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 rA({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 sA(e){return e.name.replace(/\.(dqlnb|dql)$/,"")}function oA({onOpenFile:e}){const{state:t,dispatch:n}=ae(),r=Ee[t.themeMode],[s,o]=f.useState({notebooks:!0,workbooks:!0,blocks:!1,dashboards:!1}),[i,a]=f.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=>{o(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=s[R];return E.jsxs("div",{children:[E.jsx(iA,{label:wr[R],count:c.length,expanded:A,onToggle:()=>l(R),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(S=>{var d;return E.jsx(EA,{file:S,active:((d=t.activeFile)==null?void 0:d.path)===S.path,onClick:()=>e(S),t:r},S.path)})})]},R)})]})}function iA({label:e,count:t,expanded:n,onToggle:r,t:s}){const[o,i]=f.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:o?s.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:s.textSecondary,fontSize:11,fontWeight:600,fontFamily:s.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(rA,{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})]})}function EA({file:e,active:t,onClick:n,t:r}){const[s,o]=f.useState(!1);return E.jsxs("button",{onClick:n,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 8px 4px 26px",background:t?r.sidebarItemActive:s?r.sidebarItemHover:"transparent",border:"none",borderLeft:t?`2px solid ${r.accent}`:"2px solid transparent",cursor:"pointer",color:t||s?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(nA,{type:e.type})}),E.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:sA(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 aA=window.location.origin;async function Oe(e,t){const n=await fetch(`${aA}${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 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(s=>typeof s=="string"?s:typeof(s==null?void 0:s.name)=="string"?s.name:String(s)):[],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 n=`DESCRIBE SELECT * FROM read_csv_auto('${e.replace(/'/g,"''")}') LIMIT 0`;try{return(await Oe("/api/query",{method:"POST",body:JSON.stringify({sql:n})})).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}}},lA={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 zo(e,t){const n=e.toLowerCase().split("(")[0].trim();return lA[n]??t}function TA({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 cA(){const{state:e,dispatch:t}=ae(),n=Ee[e.themeMode],[r,s]=f.useState(!1),o=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:o,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!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(TA,{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(RA,{table:i,t:n},i.name))})]})}function RA({table:e,t}){const{dispatch:n}=ae(),[r,s]=f.useState(!1),[o,i]=f.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:()=>s(!0),onMouseLeave:()=>s(!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.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:o?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(AA,{col:T,t},T.name))})]})}function AA({col:e,t}){const[n,r]=f.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:zo(e.type,t.accent),background:`${zo(e.type,t.accent)}18`,borderRadius:4,padding:"1px 5px",flexShrink:0},children:e.type.toLowerCase()})]})}function SA(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 Sa(e){if(e.type!=="markdown")return 0;const t=e.content.match(/^(#{1,6})\s/m);return t?t[1].length:0}function dA({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 IA({onNavigate:e}){const{state:t}=ae(),n=Ee[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(s=>({cell:s,label:SA(s)})).filter(s=>s.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:s,label:o})=>{const i=Sa(s),a=s.type==="markdown"?Math.max(0,(i-1)*12):0;return E.jsx(uA,{cell:s,label:o,indent:a,onClick:()=>e(s.id),t:n},s.id)})})}function uA({cell:e,label:t,indent:n,onClick:r,t:s}){const[o,i]=f.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:o?s.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:o?s.textPrimary:s.textSecondary,fontSize:12,fontFamily:e.type==="markdown"?s.font:s.fontMono,textAlign:"left",transition:"background 0.1s, color 0.1s",overflow:"hidden"},children:[E.jsx(dA,{cell:e,t:s}),E.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,fontWeight:e.type==="markdown"&&Sa(e)===1?600:400},children:t})]})}const NA={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"},OA={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 fA(){const{state:e}=ae(),t=Ee[e.themeMode],[n,r]=f.useState(null),[s,o]=f.useState(!1),[i,a]=f.useState(null);f.useEffect(()=>{Re.getConnections().then(r)},[]);const T=async()=>{o(!0),a(null);const S=await Re.testConnection();a(S),o(!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=OA[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:NA[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(([C])=>C!=="driver"&&C!=="type").map(([C,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:C}),E.jsx("span",{style:{fontSize:11,color:t.textSecondary,fontFamily:t.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:C.toLowerCase().includes("password")?"••••••••":String(N)})]},C))})]},S)}),E.jsx("button",{onClick:T,disabled:s,style:{width:"100%",padding:"7px 0",borderRadius:6,border:`1px solid ${t.btnBorder}`,background:t.btnBg,color:t.textSecondary,fontSize:12,fontFamily:t.font,fontWeight:500,cursor:s?"not-allowed":"pointer",marginBottom:8,opacity:s?.7:1,transition:"all 0.15s"},children:s?"Testing…":"Test Connection"}),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[s,o]=f.useState(t),[i,a]=f.useState(!1);return E.jsxs("div",{style:{borderBottom:`1px solid ${r.headerBorder}`},children:[E.jsxs("button",{onClick:()=>o(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:s?"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})]}),s&&E.jsx("div",{style:{padding:"4px 12px 10px"},children:n})]})}function CA({code:e,t}){const[n,r]=f.useState(!1);async function s(){try{await navigator.clipboard.writeText(e)}catch{const o=document.createElement("textarea");o.value=e,document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o)}r(!0),setTimeout(()=>r(!1),1500)}return E.jsx("button",{onClick:s,title:"Copy to clipboard",style:{position:"absolute",top:6,right:6,padding:"2px 6px",fontSize:10,fontFamily:t.font,background:n?`${t.success}20`:t.btnBg,border:`1px solid ${n?t.success+"50":t.btnBorder}`,borderRadius:4,cursor:"pointer",color:n?t.success:t.textMuted,transition:"all 0.15s"},children:n?"✓":"Copy"})}function 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(CA,{code:e,t})]})}function qo({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],s)=>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})]},s))})})}const LA=`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
|
+
}`,_A=`# 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`,hA=`# 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`,pA=`# 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`,mA=`# 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"`,DA=`{
|
|
111
|
+
"semanticLayer": {
|
|
112
|
+
"provider": "dql"
|
|
113
|
+
}
|
|
114
|
+
}`,PA=`{
|
|
115
|
+
"semanticLayer": {
|
|
116
|
+
"provider": "dbt",
|
|
117
|
+
"projectPath": "/path/to/your/dbt-project"
|
|
118
|
+
}
|
|
119
|
+
}`,gA=`{
|
|
120
|
+
"semanticLayer": {
|
|
121
|
+
"provider": "cubejs",
|
|
122
|
+
"projectPath": "/path/to/your/cube-project"
|
|
123
|
+
}
|
|
124
|
+
}`,MA=`{
|
|
125
|
+
"defaultConnection": {
|
|
126
|
+
"driver": "file",
|
|
127
|
+
"filepath": ":memory:"
|
|
128
|
+
}
|
|
129
|
+
}`,yA=`{
|
|
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
|
+
}`,xA=`{
|
|
141
|
+
"defaultConnection": {
|
|
142
|
+
"driver": "bigquery",
|
|
143
|
+
"project": "your-gcp-project-id",
|
|
144
|
+
"dataset": "analytics",
|
|
145
|
+
"keyFilename": "./service-account.json"
|
|
146
|
+
}
|
|
147
|
+
}`,UA=`{
|
|
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`,GA=`{
|
|
169
|
+
"semanticLayer": {
|
|
170
|
+
"provider": "snowflake",
|
|
171
|
+
"projectPath": "MY_DATABASE"
|
|
172
|
+
}
|
|
173
|
+
}`;function BA({themeMode:e}){const t=Ee[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(qo,{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:LA}),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(qo,{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:_A}),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:hA}),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:pA}),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:mA})]}),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:DA}),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:PA}),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:gA}),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:GA}),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:MA}),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:yA}),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:xA}),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:UA}),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 da={sum:"#56d364",count:"#388bfd",count_distinct:"#388bfd",avg:"#e3b341",min:"#f778ba",max:"#f778ba",custom:"#d2a8ff"};function vA(){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 HA(){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 FA(){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:s}){const[o,i]=f.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:o?s.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:s.textSecondary,fontSize:11,fontWeight:600,fontFamily:s.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:s.pillBg,color:s.textMuted,borderRadius:10,padding:"0 5px",fontSize:10,fontWeight:500},children:t})]})}function wA({metric:e,t}){const[n,r]=f.useState(!1),[s,o]=f.useState(!1),i=da[e.type]??t.accent;return E.jsxs("div",{children:[E.jsxs("button",{onClick:()=>o(!s),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(vA,{})}),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})]}),s&&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 YA({dimension:e,t}){const[n,r]=f.useState(!1),s=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(HA,{})}),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:s,background:`${s}18`,borderRadius:4,padding:"1px 4px",flexShrink:0},children:e.type})]})}function VA({hierarchy:e,t}){const[n,r]=f.useState(!1),[s,o]=f.useState(!1);return E.jsxs("div",{children:[E.jsxs("button",{onClick:()=>o(!s),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(FA,{})}),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})]}),s&&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 WA=["day","week","month","quarter","year"];function kA({t:e,metrics:t,dimensions:n,onInsertCell:r}){const[s,o]=f.useState(!1),[i,a]=f.useState(new Set),[T,l]=f.useState(new Set),[R,c]=f.useState(""),[A,S]=f.useState("month"),[d,I]=f.useState(null),[O,u]=f.useState(null),[C,N]=f.useState(!1),[_,m]=f.useState(!1),h=n.filter(p=>p.type==="date"),D=p=>{a(U=>{const L=new Set(U);return L.has(p)?L.delete(p):L.add(p),L}),I(null)},M=p=>{l(U=>{const L=new Set(U);return L.has(p)?L.delete(p):L.add(p),L}),I(null)},B=async()=>{if(i.size!==0){N(!0),u(null);try{const p=R?{name:R,granularity:A}:void 0,U=await Re.composeQuery(Array.from(i),Array.from(T),p);"error"in U?u(U.error):I(U.sql)}catch(p){u(p.message??"Failed to compose")}finally{N(!1)}}},w=()=>{d&&(navigator.clipboard.writeText(d),m(!0),setTimeout(()=>m(!1),1500))},P=p=>({width:14,height:14,borderRadius:3,border:`1.5px solid ${p?e.accent:e.cellBorder}`,background:p?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:()=>o(!s),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"6px 10px",background:s?`${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:s?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.15s"},children:E.jsx("path",{d:"M3 2l4 3-4 3V2Z"})})]}),s&&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(p=>E.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,padding:"2px 0",cursor:"pointer",color:e.textPrimary,fontSize:11},onClick:()=>D(p.name),children:[E.jsx("div",{style:P(i.has(p.name)),children:i.has(p.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:p.label||p.name}),E.jsx("span",{style:{fontSize:9,color:da[p.type]??e.accent,marginLeft:"auto",flexShrink:0},children:p.type})]},p.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(p=>E.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,padding:"2px 0",cursor:"pointer",color:e.textPrimary,fontSize:11},onClick:()=>M(p.name),children:[E.jsx("div",{style:P(T.has(p.name)),children:T.has(p.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:p.label||p.name})]},p.name))}),h.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:p=>{c(p.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"}),h.map(p=>E.jsx("option",{value:p.name,children:p.label||p.name},p.name))]}),R&&E.jsx("div",{style:{display:"flex",gap:4},children:WA.map(p=>E.jsx("button",{onClick:()=>{S(p),I(null)},style:{flex:1,padding:"2px 0",background:A===p?e.accent:e.pillBg,border:"none",borderRadius:3,color:A===p?"#fff":e.textMuted,fontSize:9,fontWeight:600,fontFamily:e.font,cursor:"pointer",textTransform:"capitalize"},children:p},p))})]}),E.jsx("button",{onClick:B,disabled:i.size===0||C,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:C?.7:1},children:C?"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:w,style:{background:"transparent",border:`1px solid ${e.cellBorder}`,borderRadius:3,color:_?"#56d364":e.textMuted,cursor:"pointer",fontSize:9,fontFamily:e.font,padding:"1px 6px"},children:_?"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 XA=["sum","count","count_distinct","avg","min","max"];function $A({t:e,onClose:t,onCreated:n}){const[r,s]=f.useState(""),[o,i]=f.useState(""),[a,T]=f.useState(""),[l,R]=f.useState("sum"),[c,A]=f.useState(""),[S,d]=f.useState(""),[I,O]=f.useState(""),[u,C]=f.useState(!1),[N,_]=f.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"},h={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()){_("Name, SQL expression, and table are required.");return}C(!0),_(null);const M=await Re.createMetric({name:r.trim(),label:o.trim()||r.trim(),description:I.trim(),domain:S.trim()||"general",sql:a.trim(),type:l,table:c.trim()});C(!1),M.ok?(n(),t()):_(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:h,children:"Name *"}),E.jsx("input",{style:m,value:r,onChange:M=>s(M.target.value),placeholder:"total_revenue"}),E.jsx("span",{style:h,children:"Label"}),E.jsx("input",{style:m,value:o,onChange:M=>i(M.target.value),placeholder:"Total Revenue"}),E.jsx("span",{style:h,children:"SQL Expression *"}),E.jsx("input",{style:m,value:a,onChange:M=>T(M.target.value),placeholder:"SUM(amount)"}),E.jsx("span",{style:h,children:"Aggregation Type *"}),E.jsx("select",{value:l,onChange:M=>R(M.target.value),style:{...m,cursor:"pointer"},children:XA.map(M=>E.jsx("option",{value:M,children:M},M))}),E.jsx("span",{style:h,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:h,children:"Domain"}),E.jsx("input",{style:m,value:S,onChange:M=>d(M.target.value),placeholder:"finance"}),E.jsx("span",{style:h,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=Ee[e.themeMode],[r,s]=f.useState(""),[o,i]=f.useState(!1),[a,T]=f.useState(!1),[l,R]=f.useState({metrics:!0,dimensions:!0,hierarchies:!1}),c=e.semanticLayer,A=async()=>{t({type:"SET_SEMANTIC_LOADING",loading:!0});try{const h=await Re.getSemanticLayer();t({type:"SET_SEMANTIC_LAYER",layer:h})}catch(h){console.error("Semantic layer refresh failed:",h)}finally{t({type:"SET_SEMANTIC_LOADING",loading:!1})}};f.useEffect(()=>{c.metrics.length===0&&!c.loading&&A()},[]);const S=r.toLowerCase(),d=f.useMemo(()=>S?c.metrics.filter(h=>h.name.toLowerCase().includes(S)||h.label.toLowerCase().includes(S)||h.description.toLowerCase().includes(S)||h.tags.some(D=>D.toLowerCase().includes(S))):c.metrics,[c.metrics,S]),I=f.useMemo(()=>S?c.dimensions.filter(h=>h.name.toLowerCase().includes(S)||h.label.toLowerCase().includes(S)||h.description.toLowerCase().includes(S)):c.dimensions,[c.dimensions,S]),O=f.useMemo(()=>S?c.hierarchies.filter(h=>h.name.toLowerCase().includes(S)||h.label.toLowerCase().includes(S)):c.hierarchies,[c.hierarchies,S]),u=h=>{R(D=>({...D,[h]:!D[h]}))},C={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},_={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:_,children:["Add ",E.jsx("code",{style:C,children:"semanticLayer"})," to your ",E.jsx("code",{style:C,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:_,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:{..._,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:_,children:["Restart ",E.jsx("code",{style:C,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($A,{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:o?n.btnHover:"transparent",border:`1px solid ${o?n.btnBorder:"transparent"}`,borderRadius:4,cursor:"pointer",color:o?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(kA,{t:n,metrics:c.metrics,dimensions:c.dimensions,onInsertCell:h=>{const D=De("sql",h);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:h=>s(h.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(h=>E.jsx("div",{style:{height:28,borderRadius:4,background:n.pillBg,opacity:.6,animation:"pulse 1.5s ease-in-out infinite"}},h)),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(h=>E.jsx(wA,{metric:h,t:n},h.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(h=>E.jsx(YA,{dimension:h,t:n},h.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(h=>E.jsx(VA,{hierarchy:h,t:n},h.name))})]})]})]})}const Ia={source_table:"#8b949e",block:"#56d364",metric:"#388bfd",dimension:"#e3b341",domain:"#d2a8ff",chart:"#f778ba"},KA={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 ua({type:e}){const t=Ia[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 JA({status:e}){if(!e)return null;const t=KA[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:s}){const[o,i]=f.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:o?s.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:s.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:s.textMuted,fontWeight:400},children:t})]})}function $t({node:e,t,onClick:n}){const[r,s]=f.useState(!1);return E.jsxs("div",{onClick:n,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!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(ua,{type:e.type}),E.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),E.jsx(JA,{status:e.status})]})}function zA(){const{state:e,dispatch:t}=ae(),n=Ee[e.themeMode],[r,s]=f.useState(!0),[o,i]=f.useState([]),[a,T]=f.useState([]),[l,R]=f.useState(null),[c,A]=f.useState(null),[S,d]=f.useState(!0),[I,O]=f.useState(!0),[u,C]=f.useState(!0),[N,_]=f.useState(!0),m=f.useCallback(async()=>{s(!0);const p=await Re.fetchLineage();i(p.nodes),T(p.edges),s(!1)},[]);f.useEffect(()=>{m()},[m]);const h=f.useCallback(async p=>{if(l===p){R(null),A(null);return}R(p);const U=await Re.fetchBlockLineage(p);U&&A({ancestors:U.ancestors,descendants:U.descendants})},[l]),D=o.filter(p=>p.type==="block"),M=o.filter(p=>p.type==="metric"),B=o.filter(p=>p.type==="source_table"),w=[...new Set(o.map(p=>p.domain).filter(Boolean))],P=a.filter(p=>p.type==="crosses_domain");return r?E.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"Loading lineage..."}):o.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"]}),P.length>0&&E.jsxs("span",{style:{color:"#d2a8ff"},children:[P.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(ua,{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(p=>E.jsx($t,{node:p,t:n},p.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(p=>E.jsx($t,{node:p,t:n},p.id))]})]}),E.jsx(Un,{label:"Blocks",count:D.length,expanded:S,onToggle:()=>d(!S),t:n}),S&&D.map(p=>E.jsx($t,{node:p,t:n,onClick:()=>h(p.name)},p.id)),E.jsx(Un,{label:"Metrics",count:M.length,expanded:I,onToggle:()=>O(!I),t:n}),I&&M.map(p=>E.jsx($t,{node:p,t:n},p.id)),E.jsx(Un,{label:"Source Tables",count:B.length,expanded:u,onToggle:()=>C(!u),t:n}),u&&B.map(p=>E.jsx($t,{node:p,t:n},p.id)),E.jsx(Un,{label:"Domains",count:w.length,expanded:N,onToggle:()=>_(!N),t:n}),N&&w.map(p=>{const U=D.filter(g=>g.domain===p),L=U.filter(g=>g.status==="certified").length,x=U.length>0?Math.round(L/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:Ia.domain,fontSize:10,fontWeight:600},children:"DOM"}),E.jsx("span",{style:{flex:1},children:p}),E.jsxs("span",{style:{color:n.textMuted,fontSize:10},children:[L,"/",U.length," (",x,"%)"]})]},p)}),P.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"}),P.map((p,U)=>E.jsxs("div",{style:{padding:"2px 8px 2px 20px",fontSize:11,color:n.textMuted},children:[p.sourceDomain," → ",p.targetDomain]},U))]})]})}const qA={files:"Explorer",schema:"Schema",semantic:"Semantic Layer",lineage:"Lineage",outline:"Outline",connection:"Connection",reference:"Quick Reference"};function ZA({onOpenFile:e,onNavigateToCell:t}){const{state:n,dispatch:r}=ae(),s=Ee[n.themeMode],[o,i]=f.useState(!1),a=n.sidebarPanel;return E.jsxs("div",{style:{width:240,flexShrink:0,background:s.sidebarBg,borderRight:`1px solid ${s.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 ${s.headerBorder}`},children:[E.jsx("span",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.06em",textTransform:"uppercase",color:s.textSecondary,fontFamily:s.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:o?s.textPrimary:s.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(oA,{onOpenFile:e}),a==="schema"&&E.jsx(cA,{}),a==="semantic"&&E.jsx(jA,{}),a==="lineage"&&E.jsx(zA,{}),a==="outline"&&E.jsx(IA,{onNavigate:t}),a==="connection"&&E.jsx(fA,{}),a==="reference"&&E.jsx(BA,{themeMode:n.themeMode})]})]})}function QA(e){try{const t=e.match(/workbook\s+"([^"]+)"/i),n=t?t[1]:"Untitled Workbook",r=[],s=/page\s+"([^"]+)"\s*\{([\s\S]*?)\}/gi;let o;for(;(o=s.exec(e))!==null;){const i=o[1],a=o[2].trim();r.push({id:je(),type:"markdown",content:`# ${i}`,status:"idle"}),a&&r.push({id:je(),type:"dql",name:i.toLowerCase().replace(/\s+/g,"_"),content:a,status:"idle"})}return r.length===0&&r.push({id:je(),type:"dql",content:e.trim(),status:"idle"}),{title:n,cells:r}}catch{return{title:"Untitled Workbook",cells:[{id:je(),type:"dql",content:e.trim(),status:"idle"}]}}}function eS(e){var t;try{const n=JSON.parse(e),r=n.title||((t=n.metadata)==null?void 0:t.title)||"Untitled",s=(n.cells||[]).map(o=>({id:o.id||je(),type:o.type||"sql",content:o.content??o.source??"",name:o.name||o.title,status:"idle",...o.paramConfig?{paramConfig:o.paramConfig}:{},...o.paramValue!==void 0?{paramValue:o.paramValue}:{},...o.chartConfig?{chartConfig:o.chartConfig}:{}}));return{title:r,cells:s}}catch{return{title:"Untitled",cells:[{id:je(),type:"sql",content:e,status:"idle"}]}}}function tS(e,t,n){const r={version:1,title:e,metadata:{...n,modifiedAt:new Date().toISOString(),createdAt:new Date().toISOString()},cells:t.map(s=>({id:s.id,type:s.type,content:s.content,...s.name?{name:s.name}:{},...s.paramConfig?{paramConfig:s.paramConfig}:{},...s.paramValue!==void 0?{paramValue:s.paramValue}:{},...s.chartConfig?{chartConfig:s.chartConfig}:{}}))};return JSON.stringify(r,null,2)}function nS(e,t){return e.endsWith(".dql")?QA(t):eS(t)}function rS(e,t){if(!t.columns.length||!t.rows.length)return`${e} AS (SELECT 1 WHERE 1=0)`;const n=t.columns,s=t.rows.slice(0,5e3).map(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
|
+
`),o=n.map(i=>`"${i.replace(/"/g,'""')}"`).join(", ");return`${e} AS (
|
|
237
|
+
SELECT * FROM (VALUES
|
|
238
|
+
${s}
|
|
239
|
+
) AS _t(${o})
|
|
240
|
+
)`}function sS(e,t){if(t==="number"){const n=Number(e);return isNaN(n)?`'${e.replace(/'/g,"''")}'`:String(n)}return`'${e.replace(/'/g,"''")}'`}function oS(){const{state:e}=ae();return{substituteVariables:f.useCallback(n=>{var R;const r=/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g,s=[...n.matchAll(r)];if(s.length===0)return{sql:n,substituted:[]};const o=[],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 s){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=sS(I,O);a=a.replace(c[0],u),o.push(A)}else l.has(A)&&(i.push(rS(A,l.get(A))),a=a.replace(c[0],`"${A}"`),o.push(A))}if(i.length===0&&o.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:o}},[e.cells])}}function iS(e){const t=e.match(/visualization\s*\{([^}]+)\}/is);if(!t)return;const n=t[1],r=o=>{var i;return(i=n.match(new RegExp(`\\b${o}\\s*=\\s*["']?([\\w-]+)["']?`,"i")))==null?void 0:i[1]},s=r("chart");if(s)return{chart:s,x:r("x"),y:r("y"),color:r("color"),title:r("title")}}function ES(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?aS(t):null}function aS(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 s=r[0];const o=s.search(/\b(visualization|tests|block)\s*\{/i);return o>0&&(s=s.slice(0,o)),s=lS(s),s.trim()||null}return null}function lS(e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];if(r==="("){t++;continue}if(r===")"){t>0&&t--;continue}if(r==="'"||r==='"'){for(n++;n<e.length&&e[n]!==r;)e[n]==="\\"&&n++,n++;continue}if(r===","&&t===0){let s=n+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(s<e.length&&/[a-zA-Z_]/.test(e[s])){for(;s<e.length&&/[a-zA-Z0-9_]/.test(e[s]);)s++;let o=s;for(;o<e.length&&/\s/.test(e[o]);)o++;if(o<e.length&&e[o]==="="&&e[o+1]!=="=")return e.slice(0,n)}}}return e}function Eo(){const{state:e,dispatch:t}=ae(),{substituteVariables:n}=oS(),r=f.useCallback(async i=>{const a=e.cells.find(c=>c.id===i);if(!a)return;const T=ES(a);if(!T)return;if(a.type==="dql"){const c=iS(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:je(),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:je(),cellName:a.name??a.id,rows:0,time:A,ts:new Date,error:S}})}},[e.cells,t]),s=f.useCallback(async()=>{for(const i of e.cells)i.type!=="markdown"&&await r(i.id)},[e.cells,r]),o=f.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:s,executeDependents:o}}function fe(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function TS(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 cS(e){const t=e.split(`
|
|
245
|
+
`),n=[];let r=!1,s=!1;for(const o of t){const i=o;if(i.startsWith("```")){s&&(n.push("</ul>"),s=!1),r?(n.push("</code></pre>"),r=!1):(n.push("<pre><code>"),r=!0);continue}if(r){n.push(fe(i));continue}if(i.startsWith("### ")){s&&(n.push("</ul>"),s=!1),n.push(`<h3>${fe(i.slice(4))}</h3>`);continue}if(i.startsWith("## ")){s&&(n.push("</ul>"),s=!1),n.push(`<h2>${fe(i.slice(3))}</h2>`);continue}if(i.startsWith("# ")){s&&(n.push("</ul>"),s=!1),n.push(`<h1>${fe(i.slice(2))}</h1>`);continue}if(i.startsWith("> ")){s&&(n.push("</ul>"),s=!1),n.push(`<blockquote><p>${fe(i.slice(2))}</p></blockquote>`);continue}if(i.startsWith("- ")||i.startsWith("* ")){s||(n.push("<ul>"),s=!0),n.push(`<li>${Zo(i.slice(2))}</li>`);continue}if(s&&(n.push("</ul>"),s=!1),i.trim()===""){n.push("<br>");continue}n.push(`<p>${Zo(i)}</p>`)}return s&&n.push("</ul>"),r&&n.push("</code></pre>"),n.join(`
|
|
246
|
+
`)}function Zo(e){return fe(e).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/`(.+?)`/g,"<code>$1</code>")}function RS(e){const{columns:t,rows:n}=e,r=n.slice(0,200),s=n.length>200,o=t.map(a=>`<th>${fe(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"':""}>${fe(A)}</td>`}).join("")}</tr>`).join("");return`
|
|
247
|
+
<div class="table-wrap">
|
|
248
|
+
<table>
|
|
249
|
+
<thead><tr>${o}</tr></thead>
|
|
250
|
+
<tbody>${i}</tbody>
|
|
251
|
+
</table>
|
|
252
|
+
${s?`<p class="truncated">Showing first 200 of ${n.length.toLocaleString()} rows</p>`:""}
|
|
253
|
+
</div>`}function AS(e){const{columns:t,rows:n}=e;if(t.length<2||n.length===0)return null;const r=t.find(o=>typeof n[0][o]=="number"),s=t.find(o=>o!==r);return!r||!s?null:{labelCol:s,valueCol:r}}function SS(e){const t=AS(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),s=28,o=6,i=140,a=440,T=n.length*(s+o)+40,l=n.map((R,c)=>{const A=c*(s+o)+20,S=Math.max(R.value/r*a,2);return`
|
|
254
|
+
<text x="${i-6}" y="${A+s/2+4}" text-anchor="end" font-size="11" fill="#8b949e">${fe(R.label.slice(0,20))}</text>
|
|
255
|
+
<rect x="${i}" y="${A}" width="${S}" height="${s}" rx="3" fill="#388bfd" />
|
|
256
|
+
<text x="${i+S+5}" y="${A+s/2+4}" font-size="11" fill="#e6edf3">${TS(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 dS(e,t){const n=t.map(r=>{if(r.type==="markdown")return`<section class="cell md-cell">${cS(r.content)}</section>`;const s=r.name?`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span><span class="cell-name">${fe(r.name)}</span></div>`:`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span></div>`,o=`<pre class="cell-code"><code>${fe(r.content)}</code></pre>`;let i="";if(r.result&&r.result.rows.length>0){const a=SS(r.result),T=RS(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">⚠ ${fe(r.error)}</div>`);return`<section class="cell sql-cell">${s}${o}${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>${fe(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">${fe(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 IS(e,t){const n=dS(e,t),r=new Blob([n],{type:"text/html;charset=utf-8"}),s=URL.createObjectURL(r),o=document.createElement("a");o.href=s,o.download=`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}-dashboard.html`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(s)}function uS(e,t){var o,i;const n=[];n.push(`workbook "${e}" {`);let r=0,s=0;for(const a of t)if(a.type!=="param"){if(a.type==="markdown"){s++;const T=`Markdown ${s}`;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=((o=a.name)==null?void 0:o.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 NS(e,t){const n=uS(e,t),r=new Blob([n],{type:"text/plain;charset=utf-8"}),s=URL.createObjectURL(r),o=document.createElement("a"),i=e.replace(/[^a-zA-Z0-9_-]/g,"_")+".dql";o.href=s,o.download=i,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(s)}function OS({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 fS(){const{state:e,dispatch:t}=ae(),n=Ee[e.themeMode],{executeAll:r}=Eo(),[s,o]=f.useState(!1),[i,a]=f.useState(""),[T,l]=f.useState(!1),[R,c]=f.useState(!1),[A,S]=f.useState(!1),[d,I]=f.useState(!1),[O,u]=f.useState(!1),[C,N]=f.useState(!1),_=f.useRef(null),m=f.useRef(null);f.useEffect(()=>{s&&m.current&&(m.current.focus(),m.current.select())},[s]),f.useEffect(()=>{if(!C)return;function P(p){_.current&&!_.current.contains(p.target)&&N(!1)}return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[C]);const h=()=>{a(e.notebookTitle),o(!0)},D=()=>{o(!1),i.trim()&&i!==e.notebookTitle&&t({type:"SET_NOTEBOOK_DIRTY",dirty:!0})},M=f.useCallback(async()=>{if(e.activeFile){t({type:"SET_SAVING",saving:!0});try{const P=tS(e.notebookTitle,e.cells);await Re.saveNotebook(e.activeFile.path,P),t({type:"SET_NOTEBOOK_DIRTY",dirty:!1}),l(!0),setTimeout(()=>l(!1),2e3)}catch(P){console.error("Save failed:",P)}finally{t({type:"SET_SAVING",saving:!1})}}},[e.activeFile,e.notebookTitle,e.cells,t]),B=()=>{t({type:"SET_THEME",mode:e.themeMode==="dark"?"light":"dark"})},w={height:28,padding:"0 10px",borderRadius:6,border:`1px solid ${n.btnBorder}`,cursor:"pointer",fontSize:12,fontWeight:500,fontFamily:n.font,display:"flex",alignItems:"center",gap:4,transition:"background 0.15s, color 0.15s",whiteSpace:"nowrap"};return 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(OS,{t:n}),E.jsx("div",{style:{width:1,height:20,background:n.headerBorder,flexShrink:0}}),e.activeFile?s?E.jsx("input",{ref:m,value:i,onChange:P=>a(P.target.value),onBlur:D,onKeyDown:P=>{P.key==="Enter"&&D(),P.key==="Escape"&&o(!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:h,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:{...w,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:{...w,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),style:{...w,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(CS,{}),"Saving…"]}):T?E.jsx(E.Fragment,{children:"✓ Saved"}):E.jsx(E.Fragment,{children:"Save"})}),E.jsx("div",{style:{width:1,height:20,background:n.headerBorder}}),E.jsxs("div",{ref:_,style:{position:"relative"},children:[E.jsxs("button",{onClick:()=>{e.activeFile&&N(P=>!P)},disabled:!e.activeFile,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),title:"Export options",style:{...w,background:(O||C)&&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"})})]}),C&&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(Qo,{label:"Export HTML",description:"Standalone dashboard",t:n,onClick:()=>{IS(e.notebookTitle||"dashboard",e.cells),N(!1)}}),E.jsx(Qo,{label:"Export .dql",description:"DQL workbook file",t:n,onClick:()=>{NS(e.notebookTitle||"notebook",e.cells),N(!1)}})]})]})]})]})}function Qo({label:e,description:t,t:n,onClick:r}){const[s,o]=f.useState(!1);return E.jsxs("button",{onClick:r,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),style:{background:s?n.btnHover:"transparent",border:"none",borderRadius:5,cursor:"pointer",padding:"6px 10px",textAlign:"left",display:"flex",flexDirection:"column",gap:1,transition:"background 0.12s"},children:[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 CS(){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 LS(e){return e.toTimeString().slice(0,8)}function _S(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}function hS(){const{state:e,dispatch:t}=ae(),n=Ee[e.themeMode],[r,s]=f.useState(!1),o=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(pS,{label:a==="errors"?`Errors${o.length>0?` (${o.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"&&(o.length===0?E.jsx(ei,{t:n,message:"No errors."}):[...o].reverse().map(a=>E.jsx(ti,{entry:a,t:n},a.id)))]})]}),E.jsxs("button",{onClick:()=>t({type:"TOGGLE_DEV_PANEL"}),onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),title:e.devPanelOpen?"Close panel":"Open dev panel",style:{position:"absolute",bottom:e.devPanelOpen?4:-28,right:8,height:22,padding:"0 8px",borderRadius:"4px 4px 0 0",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 pS({label:e,active:t,onClick:n,t:r}){const[s,o]=f.useState(!1);return E.jsx("button",{onClick:n,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),style:{background:"transparent",border:"none",borderBottom:t?`2px solid ${r.accent}`:"2px solid transparent",cursor:"pointer",color:t?r.textPrimary:s?r.textSecondary:r.textMuted,fontSize:12,fontFamily:r.font,fontWeight:t?500:400,padding:"4px 8px",height:32,transition:"color 0.15s"},children:e})}function 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:LS(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:_S(e.time)})]})]})}function mS({onOpenFile:e}){const{state:t,dispatch:n}=ae(),r=Ee[t.themeMode],s=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(gS,{}),accent:r.accent,onClick:()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}),t:r}),E.jsx(DS,{recentFiles:s,onOpenFile:e,t:r}),E.jsx(ni,{title:"Browse Examples",description:"Explore sample notebooks and DQL workbooks.",icon:E.jsx(yS,{}),accent:r.success,onClick:()=>{const o=t.files.find(i=>i.folder.toLowerCase()==="notebooks");o&&e(o)},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(([o,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:o}),E.jsx("span",{style:{fontSize:12,color:r.textMuted,fontFamily:r.font},children:i})]},o))})]})]})})}function ni({title:e,description:t,icon:n,accent:r,onClick:s,t:o}){const[i,a]=f.useState(!1);return E.jsxs("button",{onClick:s,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{background:i?o.cellBg:"transparent",border:`1px solid ${i?r:o.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:o.textPrimary,fontFamily:o.font,marginBottom:4},children:e}),E.jsx("div",{style:{fontSize:12,color:o.textSecondary,fontFamily:o.font,lineHeight:1.5},children:t})]})]})}function DS({recentFiles:e,onOpenFile:t,t:n}){const[r,s]=f.useState(!1);return E.jsxs("div",{onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),style:{background:r?n.cellBg:"transparent",border:`1px solid ${r?n.textMuted:n.cellBorder}`,borderRadius:10,padding:"20px 16px",textAlign:"left",display:"flex",flexDirection:"column",gap:10,transition:"border-color 0.2s, background 0.2s"},children:[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(MS,{})}),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(o=>E.jsx(PS,{file:o,onClick:()=>t(o),t:n},o.path))})]})]})}function PS({file:e,onClick:t,t:n}){const[r,s]=f.useState(!1);return E.jsx("button",{onClick:t,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),style:{background:"transparent",border:"none",cursor:"pointer",color:r?n.accent:n.textSecondary,fontSize:12,fontFamily:n.font,textAlign:"left",padding:"2px 0",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",transition:"color 0.15s"},children:e.name.replace(/\.(dqlnb|dql)$/,"")})}function gS(){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 MS(){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 yS(){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 on{constructor(t,n,r=0,s=t.length,o,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,s),this.bufferStart=r,this.normalize=o?a=>o(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 aR(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=SR(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=lR(t);let s=this.normalize(n);if(s.length)for(let o=0,i=r;;o++){let a=s.charCodeAt(o),T=this.match(a,i,this.bufferPos+this.bufferStart);if(o==s.length-1){if(T)return this.value=T,this;break}i==r&&o<n.length&&n.charCodeAt(o)==a&&i++}}}match(t,n,r){let s=null;for(let o=0;o<this.matches.length;o+=2){let i=this.matches[o],a=!1;this.query.charCodeAt(i)==t&&(i==this.query.length-1?s={from:this.matches[o+1],to:r}:(this.matches[o]++,a=!0)),a||(this.matches.splice(o,2),o-=2)}return this.query.charCodeAt(0)==t&&(this.query.length==1?s={from:n,to:r}:this.matches.push(1,n)),s&&this.test&&!this.test(s.from,s.to,this.buffer,this.bufferStart)&&(s=null),s}}typeof Symbol<"u"&&(on.prototype[Symbol.iterator]=function(){return this});const Na={from:-1,to:-1,match:/.*/.exec("")},ao="gm"+(/x/.unicode==null?"":"u");class Oa{constructor(t,n,r,s=0,o=t.length){if(this.text=t,this.to=o,this.curLine="",this.done=!1,this.value=Na,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new fa(t,n,r,s,o);this.re=new RegExp(n,ao+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.iter=t.iter();let i=t.lineAt(s);this.curLineStart=i.from,this.matchPos=nr(t,s),this.getLine(this.curLineStart)}getLine(t){this.iter.next(t),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let t=this.matchPos-this.curLineStart;;){this.re.lastIndex=t;let n=this.matchPos<=this.to&&this.re.exec(this.curLine);if(n){let r=this.curLineStart+n.index,s=r+n[0].length;if(this.matchPos=nr(this.text,s+(r==s?1:0)),r==this.curLineStart+this.curLine.length&&this.nextLine(),(r<s||r>this.value.to)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,match:n},this;t=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),t=0;else return this.done=!0,this}}}const 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 s=Vr.get(t);if(!s||s.from>=r||s.to<=n){let a=new Dt(n,t.sliceString(n,r));return Vr.set(t,a),a}if(s.from==n&&s.to==r)return s;let{text:o,from:i}=s;return i>n&&(o=t.sliceString(n,i)+o,i=n),s.to<r&&(o+=t.sliceString(s.to,r)),Vr.set(t,new Dt(i,o)),new Dt(n,o.slice(n-i,r-i))}}class fa{constructor(t,n,r,s,o){this.text=t,this.to=o,this.done=!1,this.value=Na,this.matchPos=nr(t,s),this.re=new RegExp(n,ao+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.flat=Dt.get(t,s,this.chunkEnd(s+5e3))}chunkEnd(t){return t>=this.to?this.to:this.text.lineAt(t).to}next(){for(;;){let t=this.re.lastIndex=this.matchPos-this.flat.from,n=this.re.exec(this.flat.text);if(n&&!n[0]&&n.index==t&&(this.re.lastIndex=t+1,n=this.re.exec(this.flat.text)),n){let r=this.flat.from+n.index,s=r+n[0].length;if((this.flat.to>=this.to||n.index+n[0].length<=this.flat.text.length-10)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,match:n},this.matchPos=nr(this.text,s+(r==s?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"&&(Oa.prototype[Symbol.iterator]=fa.prototype[Symbol.iterator]=function(){return this});function xS(e){try{return new RegExp(e,ao),!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 US=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=sR(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return s.then(o=>{let i=o&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(o.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,he.scrollIntoView(I.from,{y:"center"})],selection:I})}),!0},bS=({state:e,dispatch:t})=>{let{selection:n}=e,r=be.create(n.ranges.map(s=>e.wordAt(s.head)||be.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function GS(e,t){let{main:n,ranges:r}=e.selection,s=e.wordAt(n.head),o=s&&s.from==n.from&&s.to==n.to;for(let i=!1,a=new on(e.doc,t,r[r.length-1].to);;)if(a.next(),a.done){if(i)return null;a=new on(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(o){let T=e.wordAt(a.value.from);if(!T||T.from!=a.value.from||T.to!=a.value.to)continue}return a.value}}const BS=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(o=>o.from===o.to))return bS({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(o=>e.sliceDoc(o.from,o.to)!=r))return!1;let s=GS(e,r);return s?(t(e.update({selection:e.selection.addRange(be.range(s.from,s.to),!1),effects:he.scrollIntoView(s.to)})),!0):!1},It=TR.define({combine(e){return cR(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new qS(t),scrollToMatch:t=>he.scrollIntoView(t)})}});function vS(e){return e?[It.of(e),Fs]:Fs}class Ca{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||xS(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 WS(this):new wS(this)}getCursor(t,n=0,r){let s=t.doc?t:ca.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?ht(this,s,n,r):_t(this,s,n,r)}}class La{constructor(t){this.spec=t}}function HS(e,t,n){return(r,s,o,i)=>{if(n&&!n(r,s,o,i))return!1;let a=r>=i&&s<=i+o.length?o.slice(r-i,s-i):t.doc.sliceString(r,s);return e(a,t,r,s)}}function _t(e,t,n,r){let s;return e.wholeWord&&(s=FS(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=HS(e.test,t,s)),new on(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:o=>o.toLowerCase(),s)}function FS(e,t){return(n,r,s,o)=>((o>n||o+s.length<r)&&(o=Math.max(0,n-2),s=e.sliceString(o,Math.min(e.length,r+2))),(t(rr(s,n-o))!=tt.Word||t(sr(s,n-o))!=tt.Word)&&(t(sr(s,r-o))!=tt.Word||t(rr(s,r-o))!=tt.Word))}class wS extends La{constructor(t){super(t)}nextMatch(t,n,r){let s=_t(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let o=Math.min(t.doc.length,n+this.spec.unquoted.length);s=_t(this.spec,t,0,o).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let o=Math.max(n,s-1e4-this.spec.unquoted.length),i=_t(this.spec,t,o,s),a=null;for(;!i.nextOverlapping().done;)a=i.value;if(a)return a;if(o==n)return null;s-=1e4}}prevMatch(t,n,r){let s=this.prevMatchInRange(t,0,n);return s||(s=this.prevMatchInRange(t,Math.max(0,r-this.spec.unquoted.length),t.doc.length)),s&&(s.from!=n||s.to!=r)?s:null}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,n){let r=_t(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let o=_t(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!o.next().done;)s(o.value.from,o.value.to)}}function YS(e,t,n){return(r,s,o)=>(!n||n(r,s,o))&&e(o[0],t,r,s)}function ht(e,t,n,r){let s;return e.wholeWord&&(s=VS(t.charCategorizer(t.selection.main.head))),e.test&&(s=YS(e.test,t,s)),new Oa(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function rr(e,t){return e.slice(Ra(e,t,!1),t)}function sr(e,t){return e.slice(t,Ra(e,t))}function VS(e){return(t,n,r)=>!r[0].length||(e(rr(r.input,r.index))!=tt.Word||e(sr(r.input,r.index))!=tt.Word)&&(e(sr(r.input,r.index+r[0].length))!=tt.Word||e(rr(r.input,r.index+r[0].length))!=tt.Word)}class WS extends La{nextMatch(t,n,r){let s=ht(this.spec,t,r,t.doc.length).next();return s.done&&(s=ht(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let o=Math.max(n,r-s*1e4),i=ht(this.spec,t,o,r),a=null;for(;!i.next().done;)a=i.value;if(a&&(o==n||a.from>o+10))return a;if(o==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let o=+r.slice(0,s);if(o>0&&o<t.match.length)return t.match[o]+r.slice(s)}return n})}matchAll(t,n){let r=ht(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let o=ht(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!o.next().done;)s(o.value.from,o.value.to)}}const En=oo.define(),lo=oo.define(),nt=oR.define({create(e){return new Wr(Hs(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(lo)&&(e=new Wr(e.query,n.value?To:null));return e},provide:e=>iR.from(e,t=>t.panel)});class Wr{constructor(t,n){this.query=t,this.panel=n}}const kS=io.mark({class:"cm-searchMatch"}),XS=io.mark({class:"cm-searchMatch cm-searchMatch-selected"}),$S=RR.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 io.none;let{view:n}=this,r=new AR;for(let s=0,o=n.visibleRanges,i=o.length;s<i;s++){let{from:a,to:T}=o[s];for(;s<i-1&&T>o[s+1].from-500;)T=o[++s].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?XS:kS)})}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):pa(t)}}const or=fn((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=be.single(r.from,r.to),o=e.state.facet(It);return e.dispatch({selection:s,effects:[co(e,r),o.scrollToMatch(s.main,e)],userEvent:"select.search"}),ha(e),!0}),ir=fn((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let o=be.single(s.from,s.to),i=e.state.facet(It);return e.dispatch({selection:o,effects:[co(e,s),i.scrollToMatch(o.main,e)],userEvent:"select.search"}),ha(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)}),KS=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:s}=n.main,o=[],i=0;for(let a=new on(e.doc,e.sliceDoc(r,s));!a.next().done;){if(o.length>1e3)return!1;a.value.from==r&&(i=o.length),o.push(be.range(a.value.from,a.value.to))}return t(e.update({selection:be.create(o,i),userEvent:"select.search.matches"})),!0},si=fn((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let o=t.nextMatch(n,r,r);if(!o)return!1;let i=o,a=[],T,l,R=[];i.from==r&&i.to==s&&(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(he.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(co(e,i)),R.push(n.facet(It).scrollToMatch(T.main,e))),e.dispatch({changes:c,selection:T,effects:R,userEvent:"input.replace"}),!0}),JS=fn((e,{query:t})=>{if(e.state.readOnly)return!1;let n=t.matchAll(e.state,1e9).map(s=>{let{from:o,to:i}=s;return{from:o,to:i,insert:t.getReplacement(s)}});if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:he.announce.of(r),userEvent:"input.replace.all"}),!0});function To(e){return e.state.facet(It).createPanel(e)}function Hs(e,t){var n,r,s,o,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 Ca({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:(s=t==null?void 0:t.literal)!==null&&s!==void 0?s:l.literal,regexp:(o=t==null?void 0:t.regexp)!==null&&o!==void 0?o:l.regexp,wholeWord:(i=t==null?void 0:t.wholeWord)!==null&&i!==void 0?i:l.wholeWord})}function _a(e){let t=Ta(e,To);return t&&t.dom.querySelector("[main-field]")}function ha(e){let t=_a(e);t&&t==e.root.activeElement&&t.select()}const pa=e=>{let t=e.state.field(nt,!1);if(t&&t.panel){let n=_a(e);if(n&&n!=e.root.activeElement){let r=Hs(e.state,t.query.spec);r.valid&&e.dispatch({effects:En.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[lo.of(!0),t?En.of(Hs(e.state,t.query.spec)):oo.appendConfig.of(Fs)]});return!0},ma=e=>{let t=e.state.field(nt,!1);if(!t||!t.panel)return!1;let n=Ta(e,To);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:lo.of(!1)}),!0},zS=[{key:"Mod-f",run:pa,scope:"editor search-panel"},{key:"F3",run:or,shift:ir,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:or,shift:ir,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:ma,scope:"editor search-panel"},{key:"Mod-Shift-l",run:KS},{key:"Mod-Alt-g",run:US},{key:"Mod-d",run:BS,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=me("input",{value:n.search,placeholder:Le(t,"Find"),"aria-label":Le(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=me("input",{value:n.replace,placeholder:Le(t,"Replace"),"aria-label":Le(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=me("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=me("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=me("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,o,i){return me("button",{class:"cm-button",name:s,onclick:o,type:"button"},i)}this.dom=me("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>or(t),[Le(t,"next")]),r("prev",()=>ir(t),[Le(t,"previous")]),r("select",()=>jS(t),[Le(t,"all")]),me("label",null,[this.caseField,Le(t,"match case")]),me("label",null,[this.reField,Le(t,"regexp")]),me("label",null,[this.wordField,Le(t,"by word")]),...t.state.readOnly?[]:[me("br"),this.replaceField,r("replace",()=>si(t),[Le(t,"replace")]),r("replaceAll",()=>JS(t),[Le(t,"replace all")])],me("button",{name:"close",onclick:()=>ma(t),"aria-label":Le(t,"close"),type:"button"},["×"])])}commit(){let t=new Ca({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){dR(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?ir:or)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),si(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 Le(e,t){return e.state.phrase(t)}const bn=30,Gn=/[\s\.,:;?!]/;function co(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,o=Math.max(r.from,t-bn),i=Math.min(s,n+bn),a=e.state.sliceDoc(o,i);if(o!=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!=s){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 he.announce.of(`${e.state.phrase("current match")}. ${a} ${e.state.phrase("on line")} ${r.number}.`)}const ZS=he.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"}}),Fs=[nt,ER.low($S),ZS],QS=he.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}),ed=he.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 Da({value:e,onChange:t,onRun:n,themeMode:r,autoFocus:s,schema:o}){const i=Ee[r],a=f.useRef(null),T=f.useRef(null),l=f.useRef(n),R=f.useRef(t),c=f.useRef(new IR);return l.current=n,R.current=t,f.useEffect(()=>{if(!a.current)return;const A=uR.of([{key:"Shift-Enter",run:()=>(l.current(),!0)},{key:"Ctrl-Enter",mac:"Cmd-Enter",run:()=>(l.current(),!0)},{key:"Ctrl-/",mac:"Cmd-/",run:NR},fR,...CR,...LR,..._R,...zS,...hR,...pR]),S=he.updateListener.of(N=>{N.docChanged&&R.current(N.state.doc.toString())}),d=he.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=o?yn({schema:o,upperCaseKeywords:!1}):yn({upperCaseKeywords:!1}),O=[A,S,d,c.current.of(I),DR({closeOnBlur:!1}),PR(),gR(),MR(),yR(),xR(),UR(),bR(),he.lineWrapping,vS({top:!0}),...r==="dark"?[mR,ed]:[QS,GR(BR)]],u=ca.create({doc:e,extensions:O}),C=new he({state:u,parent:a.current});return T.current=C,s&&C.focus(),()=>{C.destroy(),T.current=null}},[r]),f.useEffect(()=>{const A=T.current;if(!A)return;const S=o?yn({schema:o,upperCaseKeywords:!1}):yn({upperCaseKeywords:!1});A.dispatch({effects:c.current.reconfigure(S)})},[o]),f.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}})}Da.displayName="SQLCellEditor";function td(e,t){const n=e.split(`
|
|
331
|
+
`),r=[];let s=0;for(;s<n.length;){const o=n[s],i=o.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:s>0?a===1?16:10:0,borderBottom:a===1?`1px solid ${t.cellBorder}`:void 0,paddingBottom:a===1?8:void 0},children:jt(T,t)},s)),s++;continue}if(/^[-*_]{3,}$/.test(o.trim())){r.push(E.jsx("hr",{style:{border:"none",borderTop:`1px solid ${t.cellBorder}`,margin:"12px 0"}},s)),s++;continue}if(o.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:jt(o.slice(2),t)},s)),s++;continue}if(o.startsWith("```")){const a=[];for(s++;s<n.length&&!n[s].startsWith("```");)a.push(n[s]),s++;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
|
+
`)},s)),s++;continue}if(/^[-*+]\s/.test(o)){const a=[];for(;s<n.length&&/^[-*+]\s/.test(n[s]);)a.push(n[s].replace(/^[-*+]\s/,"")),s++;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:jt(T,t)},l))},s));continue}if(/^\d+\.\s/.test(o)){const a=[];for(;s<n.length&&/^\d+\.\s/.test(n[s]);)a.push(n[s].replace(/^\d+\.\s/,"")),s++;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:jt(T,t)},l))},s));continue}if(!o.trim()){r.push(E.jsx("div",{style:{height:8}},s)),s++;continue}r.push(E.jsx("p",{style:{fontSize:14,lineHeight:1.7,fontFamily:t.fontSerif,color:t.textSecondary,marginBottom:6},children:jt(o,t)},s)),s++}return r}function jt(e,t){const n=[];let r=e,s=0;for(;r.length>0;){const o=r.match(/\*{3}(.+?)\*{3}/),i=r.match(/\*{2}(.+?)\*{2}/),a=r.match(/\*(.+?)\*/),T=r.match(/`(.+?)`/),l=r.match(/\[(.+?)\]\((.+?)\)/),R=[o?{match:o,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(sn.Fragment,{children:r},s++));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(sn.Fragment,{children:r.slice(0,A)},s++)),c.type){case"boldItalic":n.push(E.jsx("strong",{style:{fontStyle:"italic"},children:c.match[1]},s++));break;case"bold":n.push(E.jsx("strong",{children:c.match[1]},s++));break;case"italic":n.push(E.jsx("em",{children:c.match[1]},s++));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]},s++));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]},s++));break}r=r.slice(A+c.match[0].length)}return E.jsx(E.Fragment,{children:n})}function nd({value:e,onChange:t,onRun:n,themeMode:r}){const s=Ee[r],[o,i]=f.useState(!1),a=f.useRef(null);f.useEffect(()=>{if(o&&a.current){a.current.focus();const c=a.current;c.style.height="auto",c.style.height=`${Math.max(c.scrollHeight,80)}px`}},[o]);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 o?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:s.editorBg,color:s.textPrimary,border:"none",outline:"none",resize:"none",fontFamily:s.fontMono,fontSize:13,lineHeight:"20px",borderRadius:0,caretColor:s.accent}}):e.trim()?E.jsx("div",{onDoubleClick:()=>i(!0),title:"Double-click to edit",style:{padding:"12px 16px",cursor:"text",minHeight:48},children:td(e,s)}):E.jsx("div",{onDoubleClick:()=>i(!0),style:{padding:"12px 16px",color:s.textMuted,fontFamily:s.font,fontSize:13,fontStyle:"italic",cursor:"text",minHeight:48,display:"flex",alignItems:"center"},children:"Double-click to add markdown..."})}function rd({cell:e,themeMode:t,onApplyParam:n}){const{dispatch:r}=ae(),s=Ee[t],[o,i]=f.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:s.cellBg,border:`1px solid ${s.cellBorder}`,borderLeft:"3px solid #e3b341",borderRadius:8,overflow:"hidden"},children:[o&&E.jsxs("div",{style:{background:s.tableHeaderBg,borderBottom:`1px solid ${s.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:s.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:s.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:s.textMuted,fontFamily:s.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:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:4,color:s.textPrimary,fontSize:12,fontFamily:s.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:s.textMuted,fontFamily:s.font},children:"Display label"}),E.jsx("input",{value:a.label,onChange:S=>l({label:S.target.value}),placeholder:"e.g. Start Date",style:{background:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:4,color:s.textPrimary,fontSize:12,fontFamily:s.font,padding:"4px 7px",outline:"none"}})]}),E.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 100px"},children:[E.jsx("span",{style:{fontSize:10,color:s.textMuted,fontFamily:s.font},children:"Type"}),E.jsxs("select",{value:a.paramType,onChange:S=>l({paramType:S.target.value}),style:{background:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:4,color:s.textPrimary,fontSize:12,fontFamily:s.font,padding:"4px 7px",outline:"none"},children:[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:s.textMuted,fontFamily:s.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:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:4,color:s.textPrimary,fontSize:12,fontFamily:s.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:s.textMuted,fontFamily:s.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:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:4,color:s.textPrimary,fontSize:12,fontFamily:s.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:o?"Close config":"Configure parameter",style:{background:o?"#e3b34118":"transparent",border:`1px solid ${o?"#e3b341":s.cellBorder}`,borderRadius:5,cursor:"pointer",color:o?"#e3b341":s.textMuted,width:26,height:26,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,transition:"all 0.15s"},children:o?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:s.font,color:s.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:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:5,color:s.textPrimary,fontSize:13,fontFamily:s.font,padding:"5px 10px",outline:"none",minWidth:160},children: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:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:5,color:s.textPrimary,fontSize:13,fontFamily:a.paramType==="number"?s.fontMono:s.font,padding:"5px 10px",outline:"none",minWidth:160}}),A&&E.jsx("span",{style:{fontSize:10,fontFamily:s.fontMono,color:"#e3b341",opacity:.8},children:A})]}),T&&E.jsx("span",{style:{fontSize:12,fontFamily:s.fontMono,color:s.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:s.font,padding:"4px 12px",flexShrink:0,transition:"opacity 0.15s"},children:"Apply"})]})]})}const sd=[{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 od({onInsert:e,themeMode:t,cellType:n}){const r=Ee[t],[s,o]=f.useState(!1),[i,a]=f.useState(null),T=f.useRef(null),l=sd.filter(A=>n==="dql"?A.category==="DQL":A.category==="SQL"||A.category==="Analysis"),R=Array.from(new Set(l.map(A=>A.category)));f.useEffect(()=>{if(!s)return;function A(S){T.current&&!T.current.contains(S.target)&&o(!1)}return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[s]);function c(A){e(A),o(!1)}return E.jsxs("div",{ref:T,style:{position:"relative",display:"inline-block"},children:[E.jsxs("button",{title:"Insert template snippet",onClick:()=>o(A=>!A),style:{height:22,padding:"0 8px",fontSize:10,fontFamily:r.font,fontWeight:600,letterSpacing:"0.04em",color:s?r.accent:r.textMuted,background:s?`${r.accent}15`:"transparent",border:`1px solid ${s?r.accent+"50":r.btnBorder}`,borderRadius:4,cursor:"pointer",display:"flex",alignItems:"center",gap:4,transition:"all 0.15s",whiteSpace:"nowrap"},children:[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"]}),s&&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 id(e){return typeof e=="number"?!0:typeof e=="string"?!isNaN(Number(e))&&e.trim()!=="":!1}function Ed(e){return e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}function Pa({result:e,themeMode:t}){const n=Ee[t],[r,s]=f.useState(null),o=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:o.map((a,T)=>E.jsx("tr",{onMouseEnter:()=>s(T),onMouseLeave:()=>s(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=id(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?"—":Ed(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 ad=/date|time|at|day|month|year/i,Ro=/^(label|name|category)$/i,Ao=/^(value|count|total|revenue|amount)$/i;function ws(e){return typeof e=="number"?!0:typeof e=="string"?e.trim()!==""&&!isNaN(Number(e)):!1}function ld(e){return typeof e=="string"||typeof e=="number"}function Ys(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 Td(e)}function Td(e){const{columns:t,rows:n}=e;if(t.length<2||n.length===0)return"table";const r=t[0],s=t[1],o=n.slice(0,5),i=o.every(R=>ws(R[s])),a=o.every(R=>ld(R[r]));if(ad.test(r)&&i&&a)return"line";const T=t.find(R=>Ro.test(R)),l=t.find(R=>Ao.test(R));return T&&l&&o.every(c=>ws(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 cd({result:e,themeMode:t}){const n=Ee[t],[r,s]=f.useState(null),o=e.columns.find(O=>Ro.test(O))??e.columns[0],i=e.columns.find(O=>Ao.test(O))??e.columns[1],a=e.rows.slice(0,Xr).map(O=>({label:String(O[o]??""),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 C=d+u*(R+S),N=600-c-A-24,_=Math.max(O.value/l*N,2),m=r===u;return E.jsxs("g",{onMouseEnter:()=>s(u),onMouseLeave:()=>s(null),style:{cursor:"default"},children:[E.jsx("text",{x:c-8,y:C+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:C,width:_,height:R,rx:3,fill:m?n.accentHover:n.accent,style:{transition:"fill 0.15s"}}),E.jsx("text",{x:c+_+6,y:C+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 Rd(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 Ad({result:e,themeMode:t}){const n=Ee[t],[r,s]=f.useState(null),o=e.columns[0],i=e.columns[1],a=e.rows.map(U=>({label:String(U[o]??""),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)),C=Math.max(...a.map(U=>U.value))-O||1,N=d/(a.length-1),_=U=>R+U*N,m=U=>A+I-(U-O)/C*I,h=a.map((U,L)=>({x:_(L),y:m(U.value)})),D=h.reduce((U,L,x)=>{if(x===0)return`M ${L.x},${L.y}`;const g=h[x-1],v=g.x+(L.x-g.x)/2,b=g.y,y=g.x+(L.x-g.x)/2,Y=L.y;return`${U} C ${v},${b} ${y},${Y} ${L.x},${L.y}`},""),M=`${D} L ${h[h.length-1].x},${A+I} L ${R},${A+I} Z`,B=5,w=Array.from({length:B+1},(U,L)=>{const x=O+C*L/B,g=m(x);return{val:x,y:g}}),P=Math.ceil(a.length/8),p=a.filter((U,L)=>L%P===0||L===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:()=>s(null),children:[w.map((U,L)=>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)})]},L)),E.jsx("path",{d:M,fill:n.accent,opacity:.15}),E.jsx("path",{d:D,fill:"none",stroke:n.accent,strokeWidth:2,strokeLinejoin:"round"}),h.map((U,L)=>E.jsx("circle",{cx:U.x,cy:U.y,r:3,fill:n.accent,style:{cursor:"crosshair"},onMouseEnter:()=>s({x:U.x,y:U.y,label:a[L].label,value:a[L].value})},L)),p.map((U,L)=>{const x=a.indexOf(U);return E.jsx("text",{x:_(x),y:A+I+16,textAnchor:"middle",fontSize:10,fontFamily:n.font,fill:n.textMuted,children:Rd(U.label)},L)}),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 Sd=12,oi=["#388bfd","#56d364","#e3b341","#f78166","#a371f7","#39c5cf","#ffa657","#ff7b72","#89d185","#d2a8ff","#58a6ff","#3fb950"];function dd({result:e,themeMode:t,chartConfig:n}){const r=Ee[t],[s,o]=f.useState(null),i=(n!=null&&n.x?e.columns.find(u=>u===n.x):void 0)??e.columns.find(u=>Ro.test(u))??e.columns[0],a=(n!=null&&n.y?e.columns.find(u=>u===n.y):void 0)??e.columns.find(u=>Ao.test(u))??e.columns[1],T=e.rows.slice(0,Sd).map(u=>({label:String(u[i]??""),value:Math.abs(Number(u[a]??0))})),l=T.reduce((u,C)=>u+C.value,0)||1,R=90,c=90,A=70,S=40,d=[];let I=-Math.PI/2;T.forEach((u,C)=>{const N=u.value/l*2*Math.PI,_=I,m=I+N,h=R+A*Math.cos(_),D=c+A*Math.sin(_),M=R+A*Math.cos(m),B=c+A*Math.sin(m),w=R+S*Math.cos(_),P=c+S*Math.sin(_),p=R+S*Math.cos(m),U=c+S*Math.sin(m),L=N>Math.PI?1:0,x=[`M ${h} ${D}`,`A ${A} ${A} 0 ${L} 1 ${M} ${B}`,`L ${p} ${U}`,`A ${S} ${S} 0 ${L} 0 ${w} ${P}`,"Z"].join(" ");d.push({path:x,color:oi[C%oi.length],label:u.label,value:u.value,pct:u.value/l*100}),I=m});const O=s!==null?d[s]: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:()=>o(null),children:[d.map((u,C)=>E.jsx("path",{d:u.path,fill:u.color,opacity:s===null||s===C?1:.55,style:{cursor:"pointer",transition:"opacity 0.15s"},onMouseEnter:()=>o(C)},C)),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,C)=>E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,cursor:"default",opacity:s===null||s===C?1:.5},onMouseEnter:()=>o(C),onMouseLeave:()=>o(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),"%"]})]},C))})]})}function Id({result:e,themeMode:t,chartConfig:n}){const r=Ee[t],s=e.rows[0];if(!s)return null;const o=n!=null&&n.y&&e.columns.includes(n.y)?n.y:e.columns.find(R=>ws(s[R]))??e.columns[0],i=s[o],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&&s[n.x]?String(s[n.x]):o);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 ud({result:e,themeMode:t,chartConfig:n}){const r=Ee[t],s=Ys(e,n),o=s!=="table",[i,a]=f.useState(o?"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?Nd(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=s==="line"?"Line":s==="pie"?"Pie":s==="kpi"?"KPI":"Bar";return s==="kpi"?E.jsxs("div",{children:[c.length>0&&E.jsx(ii,{warnings:c,t:r}),E.jsx(Id,{result:e,themeMode:t,chartConfig:n})]}):E.jsxs("div",{children:[c.length>0&&E.jsx(ii,{warnings:c,t:r}),o&&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"||!o?E.jsx(Pa,{result:e,themeMode:t}):s==="line"?E.jsx(Ad,{result:R,themeMode:t}):s==="pie"?E.jsx(dd,{result:e,themeMode:t,chartConfig:n}):E.jsx(cd,{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 Nd(e,t,n){const r=e.columns,s=[];t&&r.includes(t)&&s.push(t),n&&r.includes(n)&&s.push(n);for(const o of r)s.includes(o)||s.push(o);return s.join(",")===r.join(",")?e:{...e,columns:s,rows:e.rows.map(o=>{const i={};for(const a of s)i[a]=o[a];return i})}}function Od(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 s=t.match(/LINE\s+(\d+):/i)??t.match(/\bline\s+(\d+)\b/i);s&&(r=parseInt(s[1],10));let o;const i=t.match(/at or near "([^"]+)"/i);i?o=i[1]:/at end of input/i.test(t)&&(o="end of input");let a;n==="Syntax Error"?o==='"""'||t.includes('"""')?a="Triple-quoted strings are DQL block syntax. Use a DQL cell for block syntax, or plain SQL in a SQL cell.":o==="end of input"||/at end of input/i.test(t)?a="Query is incomplete — check for unclosed parentheses, missing keywords, or a dangling comma.":(o===")"||o==="(")&&(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:o,hint:a}}function fd(e,t){const n=e.length,r=t.length,s=Array.from({length:n+1},(o,i)=>Array.from({length:r+1},(a,T)=>i===0?T:T===0?i:0));for(let o=1;o<=n;o++)for(let i=1;i<=r;i++)s[o][i]=e[o-1]===t[i-1]?s[o-1][i-1]:1+Math.min(s[o-1][i],s[o][i-1],s[o-1][i-1]);return s[n][r]}function Ei(e,t){const n=e.toLowerCase();let r=null,s=4;for(const o of t){const i=fd(n,o.toLowerCase());i<s&&(s=i,r=o)}return r}function Cd({message:e,themeMode:t,onFix:n,schemaTables:r}){const s=Ee[t],o=Od(e);let i=null;if(r&&r.length>0&&o.type==="Reference Error"){const T=/column.*not found|Referenced column/i.test(o.message),l=/table.*not found|Table.*does not exist/i.test(o.message);if(T&&o.near){const R=r.flatMap(A=>A.columns.map(S=>S.name)),c=Ei(o.near,R);c&&(i=`Did you mean column "${c}"?`)}else if(l&&o.near){const R=Ei(o.near,r.map(c=>c.name));R&&(i=`Did you mean table "${R}"?`)}}const a=n&&(o.type==="Syntax Error"||o.near===")"||o.near==="("||o.near==="end of input");return E.jsxs("div",{style:{padding:"12px 14px",background:`${s.error}10`,borderLeft:`3px solid ${s.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:s.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:s.fontMono,letterSpacing:"0.06em",textTransform:"uppercase",color:s.error,background:`${s.error}18`,border:`1px solid ${s.error}40`,borderRadius:4,padding:"1px 7px",flexShrink:0},children:o.type}),o.line!==void 0&&E.jsxs("span",{style:{fontSize:10,fontWeight:600,fontFamily:s.fontMono,color:s.textSecondary,background:`${s.textMuted}18`,border:`1px solid ${s.textMuted}30`,borderRadius:4,padding:"1px 7px",flexShrink:0},children:["Line ",o.line]}),o.near&&E.jsxs("span",{style:{fontSize:11,fontFamily:s.fontMono,color:s.textSecondary,flexShrink:0},children:["near ",E.jsxs("span",{style:{color:s.error},children:["“",o.near,"”"]})]})]}),E.jsx("pre",{style:{margin:0,fontFamily:s.fontMono,fontSize:12,color:s.error,lineHeight:1.6,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:o.message}),i&&E.jsxs("div",{style:{fontSize:12,fontFamily:s.font,color:s.textSecondary,display:"flex",alignItems:"center",gap:6},children:[E.jsx("span",{style:{color:s.accent},children:"→"}),i]}),o.hint&&E.jsxs("div",{style:{marginTop:2,padding:"8px 12px",background:`${s.warning}12`,border:`1px solid ${s.warning}40`,borderRadius:6,display:"flex",alignItems:"flex-start",gap:8},children:[E.jsx("span",{style:{flexShrink:0,fontSize:13,lineHeight:1.5},children:"💡"}),E.jsx("span",{style:{fontSize:12,fontFamily:s.font,color:s.warning,lineHeight:1.6},children:o.hint})]}),a&&E.jsxs("button",{onClick:n,style:{alignSelf:"flex-start",marginTop:2,padding:"5px 12px",background:`${s.accent}15`,border:`1px solid ${s.accent}50`,borderRadius:6,color:s.accent,fontSize:12,fontFamily:s.font,fontWeight:500,cursor:"pointer",display:"flex",alignItems:"center",gap:6,transition:"all 0.15s"},onMouseEnter:T=>{T.currentTarget.style.background=`${s.accent}25`},onMouseLeave:T=>{T.currentTarget.style.background=`${s.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"},Ld={source_table:"TBL",block:"BLK",metric:"MET",dimension:"DIM",chart:"CHT",domain:"DOM"},_d={certified:"#56d364",draft:"#8b949e",review:"#e3b341",deprecated:"#f85149"};function hd(e){const t=e.match(/^\s*block\s+"([^"]+)"/i);return t?t[1]:null}function pd(e){const t=[],n=/\b(?:FROM|JOIN)\s+([a-zA-Z_][\w.]*)/gi;for(const s of e.matchAll(n)){const o=s[1].toLowerCase();["select","where","group","order","having","limit","union","lateral"].includes(o)||t.push(o)}const r=/\bref\s*\(\s*"([^"]+)"\s*\)/gi;for(const s of e.matchAll(r))t.push(s[1]);return[...new Set(t)]}function md(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=Ld[e.type]??e.type.slice(0,3).toUpperCase(),s=e.status?_d[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}),s&&E.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:s,flexShrink:0}})]})}function Dd({cellContent:e,cellType:t,cellName:n,themeMode:r,t:s}){const[o,i]=f.useState(!1),[a,T]=f.useState(!1),[l,R]=f.useState([]),[c,A]=f.useState([]),[S,d]=f.useState([]),[I,O]=f.useState({metrics:[],dimensions:[]}),[u,C]=f.useState(null),_=(t==="dql"?hd(e):null)||n,m=f.useCallback(async()=>{if(!(!_&&t!=="sql")){T(!0),C(null);try{const D=pd(e);if(d(D),O(md(e)),_){const M=await Re.fetchBlockLineage(_);M&&(R(M.ancestors??[]),A(M.descendants??[]))}else{const B=(await Re.fetchLineage()).nodes.filter(w=>D.some(P=>w.name===P||w.id===`table:${P}`||w.id===`block:${P}`));R(B),A([])}}catch{C("Failed to load lineage")}finally{T(!1)}}},[_,e,t]);f.useEffect(()=>{o&&m()},[o,m]);const h=S.length>0||I.metrics.length>0||I.dimensions.length>0;return e.trim()?E.jsxs("div",{style:{borderTop:`1px solid ${s.cellBorder}`},children:[E.jsxs("button",{onClick:()=>i(D=>!D),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 12px",background:o?`${s.tableHeaderBg}60`:"transparent",border:"none",cursor:"pointer",color:s.textMuted,fontSize:10,fontFamily:s.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:o?"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"})})]}),o&&E.jsx("div",{style:{padding:"6px 12px 8px",fontSize:11},children:a?E.jsx("div",{style:{color:s.textMuted,padding:"4px 0"},children:"Loading lineage..."}):u?E.jsx("div",{style:{color:s.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:s.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:s.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:s.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:s.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:s.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:s.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:s.textMuted,marginBottom:3},children:["Upstream (",l.length,")"]}),l.map(D=>E.jsx(ai,{node:D,t:s},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:s.textMuted,marginBottom:3},children:["Downstream (",c.length,")"]}),c.map(D=>E.jsx(ai,{node:D,t:s},D.id))]}),!h&&l.length===0&&c.length===0&&E.jsx("div",{style:{color:s.textMuted,padding:"2px 0"},children:"No lineage dependencies detected for this cell."})]})})]}):null}const G=e=>e.flatMap(Pd),Pd=e=>$n(Md(e)).map(gd),gd=e=>e.replace(/ +/g," ").trim(),Md=e=>({type:"mandatory_block",items:So(e,0)[0]}),So=(e,t,n)=>{const r=[];for(;e[t];){const[s,o]=yd(e,t);if(r.push(s),t=o,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]},yd=(e,t)=>{const n=[];for(;;){const[r,s]=xd(e,t);if(r)n.push(r),t=s;else break}return n.length===1?[n[0],t]:[{type:"concatenation",items:n},t]},xd=(e,t)=>{if(e[t]==="{")return Ud(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]}},Ud=(e,t)=>{const[n,r]=So(e,t,"}");return[{type:"mandatory_block",items:n},r]},bd=(e,t)=>{const[n,r]=So(e,t,"]");return[{type:"optional_block",items:n},r]},$n=e=>{if(typeof e=="string")return[e];if(e.type==="concatenation")return e.items.map($n).reduce(Gd,[""]);if(e.type==="mandatory_block")return e.items.flatMap($n);if(e.type==="optional_block")return["",...e.items.flatMap($n)];throw new Error(`Unknown node type: ${e}`)},Gd=(e,t)=>{const n=[];for(const r of e)for(const s of t)n.push(r+s);return n};var F;(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"})(F=F||(F={}));const ga=e=>({type:F.EOF,raw:"«EOF»",text:"«EOF»",start:e}),st=ga(1/0),ft=e=>t=>t.type===e.type&&t.text===e.text,ot={ARRAY:ft({text:"ARRAY",type:F.RESERVED_DATA_TYPE}),BY:ft({text:"BY",type:F.RESERVED_KEYWORD}),SET:ft({text:"SET",type:F.RESERVED_CLAUSE}),STRUCT:ft({text:"STRUCT",type:F.RESERVED_DATA_TYPE}),WINDOW:ft({text:"WINDOW",type:F.RESERVED_CLAUSE}),VALUES:ft({text:"VALUES",type:F.RESERVED_CLAUSE})},Ma=e=>e===F.RESERVED_DATA_TYPE||e===F.RESERVED_KEYWORD||e===F.RESERVED_FUNCTION_NAME||e===F.RESERVED_KEYWORD_PHRASE||e===F.RESERVED_DATA_TYPE_PHRASE||e===F.RESERVED_CLAUSE||e===F.RESERVED_SELECT||e===F.RESERVED_SET_OPERATION||e===F.RESERVED_JOIN||e===F.ARRAY_KEYWORD||e===F.CASE||e===F.END||e===F.WHEN||e===F.ELSE||e===F.THEN||e===F.LIMIT||e===F.BETWEEN||e===F.AND||e===F.OR||e===F.XOR,Bd=e=>e===F.AND||e===F.OR||e===F.XOR,vd=["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"],Hd=["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"],Fd=["ARRAY","BOOL","BYTES","DATE","DATETIME","GEOGRAPHY","INTERVAL","INT64","INT","SMALLINT","INTEGER","BIGINT","TINYINT","BYTEINT","NUMERIC","DECIMAL","BIGNUMERIC","BIGDECIMAL","FLOAT64","STRING","STRUCT","TIME","TIMEZONE"],wd=G(["SELECT [ALL | DISTINCT] [AS STRUCT | AS VALUE]"]),Yd=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]"]),$r=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"]),Vd=G(["UNION {ALL | DISTINCT}","EXCEPT DISTINCT","INTERSECT DISTINCT"]),Wd=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN"]),kd=G(["TABLESAMPLE SYSTEM","ANY TYPE","ALL COLUMNS","NOT DETERMINISTIC","{ROWS | RANGE} BETWEEN","IS [NOT] DISTINCT FROM"]),Xd=G([]),$d={name:"bigquery",tokenizerOptions:{reservedSelect:wd,reservedClauses:[...Yd,...$r,...li],reservedSetOperations:Vd,reservedJoins:Wd,reservedKeywordPhrases:kd,reservedDataTypePhrases:Xd,reservedKeywords:Hd,reservedDataTypes:Fd,reservedFunctionNames:vd,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,...$r],tabularOnelineClauses:$r}};function jd(e){return Kd(Jd(e))}function Kd(e){let t=st;return e.map(n=>n.text==="OFFSET"&&t.text==="["?(t=n,Object.assign(Object.assign({},n),{type:F.RESERVED_FUNCTION_NAME})):(t=n,n))}function Jd(e){var t;const n=[];for(let r=0;r<e.length;r++){const s=e[r];if((ot.ARRAY(s)||ot.STRUCT(s))&&((t=e[r+1])===null||t===void 0?void 0:t.text)==="<"){const o=zd(e,r+1),i=e.slice(r,o+1);n.push({type:F.IDENTIFIER,raw:i.map(Ti("raw")).join(""),text:i.map(Ti("text")).join(""),start:s.start}),r=o}else n.push(s)}return n}const Ti=e=>t=>t.type===F.IDENTIFIER||t.type===F.COMMA?t[e]+" ":t[e];function zd(e,t){let n=0;for(let r=t;r<e.length;r++){const s=e[r];if(s.text==="<"?n++:s.text===">"?n--:s.text===">>"&&(n-=2),n===0)return r}return e.length-1}const 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"],Zd=["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"],Qd=["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"],eI=G(["SELECT [DISTINCT]","MODIFY QUERY SELECT [DISTINCT]"]),tI=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]"]),jr=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"]),nI=G(["UNION [ALL | DISTINCT]","PARALLEL WITH"]),rI=G(["[GLOBAL] [INNER|LEFT|RIGHT|FULL|CROSS] [OUTER|SEMI|ANTI|ANY|ALL|ASOF] JOIN","[LEFT] ARRAY JOIN"]),sI=G(["{ROWS | RANGE} BETWEEN","ALTER MATERIALIZE STATISTICS"]),oI={name:"clickhouse",tokenizerOptions:{reservedSelect:eI,reservedClauses:[...tI,...ci,...jr],reservedSetOperations:nI,reservedJoins:rI,reservedKeywordPhrases:sI,reservedKeywords:Zd,reservedDataTypes:Qd,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:iI},formatOptions:{onelineClauses:[...ci,...jr],tabularOnelineClauses:jr}};function iI(e){return e.map((t,n)=>{const r=e[n+1]||st,s=e[n-1]||st;return t.type===F.RESERVED_SELECT&&(r.type===F.COMMA||s.type===F.RESERVED_CLAUSE||s.type===F.COMMA)?Object.assign(Object.assign({},t),{type:F.RESERVED_KEYWORD}):ot.SET(t)&&r.type===F.OPEN_PAREN?Object.assign(Object.assign({},t),{type:F.RESERVED_FUNCTION_NAME}):t})}const EI=["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"],aI=["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"],lI=["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"],TI=G(["SELECT [ALL | DISTINCT]"]),cI=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"]),RI=G(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),AI=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN"]),SI=G(["ON DELETE","ON UPDATE","SET NULL","{ROWS | RANGE} BETWEEN"]),dI=G([]),II={name:"db2",tokenizerOptions:{reservedSelect:TI,reservedClauses:[...cI,...Ri,...Kr],reservedSetOperations:RI,reservedJoins:AI,reservedKeywordPhrases:SI,reservedDataTypePhrases:dI,reservedKeywords:aI,reservedDataTypes:lI,reservedFunctionNames:EI,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}},uI=["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"],NI=["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"],OI=["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"],fI=G(["SELECT [ALL | DISTINCT]"]),CI=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}"]),LI=G(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),_I=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","[LEFT | RIGHT] EXCEPTION JOIN","{INNER | CROSS} JOIN"]),hI=G(["ON DELETE","ON UPDATE","SET NULL","{ROWS | RANGE} BETWEEN"]),pI=G([]),mI={name:"db2i",tokenizerOptions:{reservedSelect:fI,reservedClauses:[...CI,...Ai,...Jr],reservedSetOperations:LI,reservedJoins:_I,reservedKeywordPhrases:hI,reservedDataTypePhrases:pI,reservedKeywords:NI,reservedDataTypes:OI,reservedFunctionNames:uI,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}},DI=["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"],PI=["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"],gI=["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"],MI=G(["SELECT [ALL | DISTINCT]"]),yI=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]"]),xI=G(["UNION [ALL | BY NAME]","EXCEPT [ALL]","INTERSECT [ALL]"]),UI=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"]),GI=G(["TIMESTAMP WITH TIME ZONE"]),BI={name:"duckdb",tokenizerOptions:{reservedSelect:MI,reservedClauses:[...yI,...Si,...zr],reservedSetOperations:xI,reservedJoins:UI,reservedKeywordPhrases:bI,reservedDataTypePhrases:GI,supportsXor:!0,reservedKeywords:PI,reservedDataTypes:gI,reservedFunctionNames:DI,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}},vI=["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"],HI=["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"],FI=["ARRAY","BIGINT","BINARY","BOOLEAN","CHAR","DATE","DECIMAL","DOUBLE","FLOAT","INT","INTEGER","INTERVAL","MAP","NUMERIC","PRECISION","SMALLINT","STRUCT","TIMESTAMP","VARCHAR"],wI=G(["SELECT [ALL | DISTINCT]"]),YI=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"]),VI=G(["UNION [ALL | DISTINCT]"]),WI=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","LEFT SEMI JOIN"]),kI=G(["{ROWS | RANGE} BETWEEN"]),XI=G([]),$I={name:"hive",tokenizerOptions:{reservedSelect:wI,reservedClauses:[...YI,...di,...qr],reservedSetOperations:VI,reservedJoins:WI,reservedKeywordPhrases:kI,reservedDataTypePhrases:XI,reservedKeywords:HI,reservedDataTypes:FI,reservedFunctionNames:vI,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]||st;if(ot.SET(t)&&r.text==="(")return Object.assign(Object.assign({},t),{type:F.RESERVED_FUNCTION_NAME});const s=e[n-1]||st;return ot.VALUES(t)&&s.text==="="?Object.assign(Object.assign({},t),{type:F.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"],KI=["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"],JI=["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"]),ZI=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]","MINUS [ALL | DISTINCT]"]),QI=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),eu=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),tu=G([]),nu={name:"mariadb",tokenizerOptions:{reservedSelect:zI,reservedClauses:[...qI,...Ii,...Zr],reservedSetOperations:ZI,reservedJoins:QI,reservedKeywordPhrases:eu,reservedDataTypePhrases:tu,supportsXor:!0,reservedKeywords:jI,reservedDataTypes:KI,reservedFunctionNames:JI,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}},ru=["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"],su=["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"],ou=["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"],iu=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),Eu=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"]),au=G(["UNION [ALL | DISTINCT]"]),lu=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),Tu=G(["ON {UPDATE | DELETE} [SET NULL]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),cu=G([]),Ru={name:"mysql",tokenizerOptions:{reservedSelect:iu,reservedClauses:[...Eu,...ui,...Qr],reservedSetOperations:au,reservedJoins:lu,reservedKeywordPhrases:Tu,reservedDataTypePhrases:cu,supportsXor:!0,reservedKeywords:ru,reservedDataTypes:su,reservedFunctionNames:ou,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}},Au=["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"],Su=["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"],du=["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"],Iu=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),uu=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]"]),es=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"]),Nu=G(["UNION [ALL | DISTINCT]"]),Ou=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),fu=G(["ON {UPDATE | DELETE} [SET NULL]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),Cu=G([]),Lu={name:"tidb",tokenizerOptions:{reservedSelect:Iu,reservedClauses:[...uu,...Ni,...es],reservedSetOperations:Nu,reservedJoins:Ou,reservedKeywordPhrases:fu,reservedDataTypePhrases:Cu,supportsXor:!0,reservedKeywords:Au,reservedDataTypes:Su,reservedFunctionNames:du,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,...es],tabularOnelineClauses:es}},_u=["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"],hu=["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"],pu=[],mu=G(["SELECT [ALL | DISTINCT]"]),Du=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"]),Pu=G(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),gu=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","INNER JOIN"]),Mu=G(["{ROWS | RANGE | GROUPS} BETWEEN"]),yu=G([]),xu={name:"n1ql",tokenizerOptions:{reservedSelect:mu,reservedClauses:[...Du,...Oi],reservedSetOperations:Pu,reservedJoins:gu,reservedKeywordPhrases:Mu,reservedDataTypePhrases:yu,supportsXor:!0,reservedKeywords:hu,reservedDataTypes:pu,reservedFunctionNames:_u,stringTypes:['""-bs',"''-bs"],identTypes:["``"],extraParens:["[]","{}"],paramTypes:{positional:!0,numbered:["$"],named:["$"]},lineCommentTypes:["#","--"],operators:["%","==",":","||"]},formatOptions:{onelineClauses:Oi}},Uu=["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"],Gu=["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"],Bu=G(["SELECT [ALL | DISTINCT | UNIQUE]"]),vu=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"]),ts=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"]),Hu=G(["UNION [ALL]","MINUS","INTERSECT"]),Fu=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN","{CROSS | OUTER} APPLY"]),wu=G(["ON {UPDATE | DELETE} [SET NULL]","ON COMMIT","{ROWS | RANGE} BETWEEN"]),Yu=G([]),Vu={name:"plsql",tokenizerOptions:{reservedSelect:Bu,reservedClauses:[...vu,...fi,...ts],reservedSetOperations:Hu,reservedJoins:Fu,reservedKeywordPhrases:wu,reservedDataTypePhrases:Yu,supportsXor:!0,reservedKeywords:Uu,reservedDataTypes:bu,reservedFunctionNames:Gu,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:Wu},formatOptions:{alwaysDenseOperators:["@"],onelineClauses:[...fi,...ts],tabularOnelineClauses:ts}};function Wu(e){let t=st;return e.map(n=>ot.SET(n)&&ot.BY(t)?Object.assign(Object.assign({},n),{type:F.RESERVED_KEYWORD}):(Ma(n.type)&&(t=n),n))}const ku=["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"],Xu=["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"],$u=["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]"]),Ku=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]"]),ns=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"]),Ju=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"]),Zu=G(["[TIMESTAMP | TIME] {WITH | WITHOUT} TIME ZONE"]),Qu={name:"postgresql",tokenizerOptions:{reservedSelect:ju,reservedClauses:[...Ku,...Ci,...ns],reservedSetOperations:Ju,reservedJoins:zu,reservedKeywordPhrases:qu,reservedDataTypePhrases:Zu,reservedKeywords:Xu,reservedDataTypes:$u,reservedFunctionNames:ku,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,...ns],tabularOnelineClauses:ns}},eN=["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"],tN=["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"],nN=["ARRAY","BIGINT","BPCHAR","CHAR","CHARACTER VARYING","CHARACTER","DECIMAL","INT","INT2","INT4","INT8","INTEGER","NCHAR","NUMERIC","NVARCHAR","SMALLINT","TEXT","VARBYTE","VARCHAR"],rN=G(["SELECT [ALL | DISTINCT]"]),sN=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]"]),rs=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"]),oN=G(["UNION [ALL]","EXCEPT","INTERSECT","MINUS"]),iN=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),EN=G(["NULL AS","DATA CATALOG","HIVE METASTORE","{ROWS | RANGE} BETWEEN"]),aN=G([]),lN={name:"redshift",tokenizerOptions:{reservedSelect:rN,reservedClauses:[...sN,...Li,...rs],reservedSetOperations:oN,reservedJoins:iN,reservedKeywordPhrases:EN,reservedDataTypePhrases:aN,reservedKeywords:tN,reservedDataTypes:nN,reservedFunctionNames:eN,extraParens:["[]"],stringTypes:["''-qq"],identTypes:['""-qq'],identChars:{first:"#"},paramTypes:{numbered:["$"]},operators:["^","%","@","|/","||/","&","|","~","<<",">>","||","::"]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...Li,...rs],tabularOnelineClauses:rs}},TN=["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"],cN=["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"],RN=["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"],AN=G(["SELECT [ALL | DISTINCT]"]),SN=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"]),_i=G(["CREATE [EXTERNAL] TABLE [IF NOT EXISTS]"]),ss=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"]),dN=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),IN=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"]),uN=G(["ON DELETE","ON UPDATE","CURRENT ROW","{ROWS | RANGE} BETWEEN"]),NN=G([]),ON={name:"spark",tokenizerOptions:{reservedSelect:AN,reservedClauses:[...SN,..._i,...ss],reservedSetOperations:dN,reservedJoins:IN,reservedKeywordPhrases:uN,reservedDataTypePhrases:NN,supportsXor:!0,reservedKeywords:TN,reservedDataTypes:cN,reservedFunctionNames:RN,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:fN},formatOptions:{onelineClauses:[..._i,...ss],tabularOnelineClauses:ss}};function fN(e){return e.map((t,n)=>{const r=e[n-1]||st,s=e[n+1]||st;return ot.WINDOW(t)&&s.type===F.OPEN_PAREN?Object.assign(Object.assign({},t),{type:F.RESERVED_FUNCTION_NAME}):t.text==="ITEMS"&&t.type===F.RESERVED_KEYWORD&&!(r.text==="COLLECTION"&&s.text==="TERMINATED")?Object.assign(Object.assign({},t),{type:F.IDENTIFIER,text:t.raw}):t})}const CN=["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"],LN=["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"],_N=["ANY","ARRAY","BLOB","CHARACTER","DECIMAL","INT","INTEGER","NATIVE CHARACTER","NCHAR","NUMERIC","NVARCHAR","REAL","TEXT","VARCHAR","VARYING CHARACTER"],hN=G(["SELECT [ALL | DISTINCT]"]),pN=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"]),hi=G(["CREATE [TEMPORARY | TEMP] TABLE [IF NOT EXISTS]"]),os=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"]),mN=G(["UNION [ALL]","EXCEPT","INTERSECT"]),DN=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),PN=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE | GROUPS} BETWEEN","DO UPDATE"]),gN=G([]),MN={name:"sqlite",tokenizerOptions:{reservedSelect:hN,reservedClauses:[...pN,...hi,...os],reservedSetOperations:mN,reservedJoins:DN,reservedKeywordPhrases:PN,reservedDataTypePhrases:gN,reservedKeywords:LN,reservedDataTypes:_N,reservedFunctionNames:CN,stringTypes:["''-qq",{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq',"``","[]"],paramTypes:{positional:!0,numbered:["?"],named:[":","@","$"]},operators:["%","~","&","|","<<",">>","==","->","->>","||"]},formatOptions:{onelineClauses:[...hi,...os],tabularOnelineClauses:os}},yN=["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"],xN=["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"],UN=["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]"]),GN=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"]),is=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"]),BN=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),vN=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),HN=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE} BETWEEN"]),FN=G([]),wN={name:"sql",tokenizerOptions:{reservedSelect:bN,reservedClauses:[...GN,...pi,...is],reservedSetOperations:BN,reservedJoins:vN,reservedKeywordPhrases:HN,reservedDataTypePhrases:FN,reservedKeywords:xN,reservedDataTypes:UN,reservedFunctionNames:yN,stringTypes:[{quote:"''-qq-bs",prefixes:["N","U&"]},{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq',"``"],paramTypes:{positional:!0},operators:["||"]},formatOptions:{onelineClauses:[...pi,...is],tabularOnelineClauses:is}},YN=["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"],VN=["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"],WN=["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"],kN=G(["SELECT [ALL | DISTINCT]"]),XN=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]"]),Es=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"]),$N=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"]),KN=G(["{ROWS | RANGE | GROUPS} BETWEEN","IS [NOT] DISTINCT FROM"]),JN=G([]),zN={name:"trino",tokenizerOptions:{reservedSelect:kN,reservedClauses:[...XN,...mi,...Es],reservedSetOperations:$N,reservedJoins:jN,reservedKeywordPhrases:KN,reservedDataTypePhrases:JN,reservedKeywords:VN,reservedDataTypes:WN,reservedFunctionNames:YN,extraParens:["[]","{}"],stringTypes:[{quote:"''-qq",prefixes:["U&"]},{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq'],paramTypes:{positional:!0},operators:["%","->","=>",":","||","|","^","$"]},formatOptions:{onelineClauses:[...mi,...Es],tabularOnelineClauses:Es}},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"],ZN=["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"],QN=["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"],eO=G(["SELECT [ALL | DISTINCT]"]),tO=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"]),as=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"]),nO=G(["UNION [ALL]","EXCEPT","INTERSECT"]),rO=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","{CROSS | OUTER} APPLY"]),sO=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE} BETWEEN"]),oO=G([]),iO={name:"transactsql",tokenizerOptions:{reservedSelect:eO,reservedClauses:[...tO,...Di,...as],reservedSetOperations:nO,reservedJoins:rO,reservedKeywordPhrases:sO,reservedDataTypePhrases:oO,reservedKeywords:ZN,reservedDataTypes:QN,reservedFunctionNames:qN,nestedBlockComments:!0,stringTypes:[{quote:"''-qq",prefixes:["N"]},"{}"],identTypes:['""-qq',"[]"],identChars:{first:"#@",rest:"#@$"},paramTypes:{named:["@"],quoted:["@"]},operators:["%","&","|","^","~","!<","!>","+=","-=","*=","/=","%=","|=","&=","^=","::",":"],propertyAccessOperators:[".."]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...Di,...as],tabularOnelineClauses:as}},EO=["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"],aO=["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"],lO=["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"],TO=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),cO=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"]),Pi=G(["CREATE [ROWSTORE] [REFERENCE | TEMPORARY | GLOBAL TEMPORARY] TABLE [IF NOT EXISTS]"]),ls=G(["CREATE VIEW","UPDATE","DELETE [FROM]","DROP [TEMPORARY] TABLE [IF EXISTS]","ALTER [ONLINE] TABLE","ADD [COLUMN]","ADD [UNIQUE] {INDEX | KEY}","DROP [COLUMN]","MODIFY [COLUMN]","CHANGE","RENAME [TO | AS]","TRUNCATE [TABLE]","ADD AGGREGATOR","ADD LEAF","AGGREGATOR SET AS MASTER","ALTER DATABASE","ALTER PIPELINE","ALTER RESOURCE POOL","ALTER USER","ALTER VIEW","ANALYZE TABLE","ATTACH DATABASE","ATTACH LEAF","ATTACH LEAF ALL","BACKUP DATABASE","BINLOG","BOOTSTRAP AGGREGATOR","CACHE INDEX","CALL","CHANGE","CHANGE MASTER TO","CHANGE REPLICATION FILTER","CHANGE REPLICATION SOURCE TO","CHECK BLOB CHECKSUM","CHECK TABLE","CHECKSUM TABLE","CLEAR ORPHAN DATABASES","CLONE","COMMIT","CREATE DATABASE","CREATE GROUP","CREATE INDEX","CREATE LINK","CREATE MILESTONE","CREATE PIPELINE","CREATE RESOURCE POOL","CREATE ROLE","CREATE USER","DEALLOCATE PREPARE","DESCRIBE","DETACH DATABASE","DETACH PIPELINE","DROP DATABASE","DROP FUNCTION","DROP INDEX","DROP LINK","DROP PIPELINE","DROP PROCEDURE","DROP RESOURCE POOL","DROP ROLE","DROP USER","DROP VIEW","EXECUTE","EXPLAIN","FLUSH","FORCE","GRANT","HANDLER","HELP","KILL CONNECTION","KILLALL QUERIES","LOAD DATA","LOAD INDEX INTO CACHE","LOAD XML","LOCK INSTANCE FOR BACKUP","LOCK TABLES","MASTER_POS_WAIT","OPTIMIZE TABLE","PREPARE","PURGE BINARY LOGS","REBALANCE PARTITIONS","RELEASE SAVEPOINT","REMOVE AGGREGATOR","REMOVE LEAF","REPAIR TABLE","REPLACE","REPLICATE DATABASE","RESET","RESET MASTER","RESET PERSIST","RESET REPLICA","RESET SLAVE","RESTART","RESTORE DATABASE","RESTORE REDUNDANCY","REVOKE","ROLLBACK","ROLLBACK TO SAVEPOINT","SAVEPOINT","SET CHARACTER SET","SET DEFAULT ROLE","SET NAMES","SET PASSWORD","SET RESOURCE GROUP","SET ROLE","SET TRANSACTION","SHOW","SHOW CHARACTER SET","SHOW COLLATION","SHOW COLUMNS","SHOW CREATE DATABASE","SHOW CREATE FUNCTION","SHOW CREATE PIPELINE","SHOW CREATE PROCEDURE","SHOW CREATE TABLE","SHOW CREATE USER","SHOW CREATE VIEW","SHOW DATABASES","SHOW ENGINE","SHOW ENGINES","SHOW ERRORS","SHOW FUNCTION CODE","SHOW FUNCTION STATUS","SHOW GRANTS","SHOW INDEX","SHOW MASTER STATUS","SHOW OPEN TABLES","SHOW PLUGINS","SHOW PRIVILEGES","SHOW PROCEDURE CODE","SHOW PROCEDURE STATUS","SHOW PROCESSLIST","SHOW PROFILE","SHOW PROFILES","SHOW RELAYLOG EVENTS","SHOW REPLICA STATUS","SHOW REPLICAS","SHOW SLAVE","SHOW SLAVE HOSTS","SHOW STATUS","SHOW TABLE STATUS","SHOW TABLES","SHOW VARIABLES","SHOW WARNINGS","SHUTDOWN","SNAPSHOT DATABASE","SOURCE_POS_WAIT","START GROUP_REPLICATION","START PIPELINE","START REPLICA","START SLAVE","START TRANSACTION","STOP GROUP_REPLICATION","STOP PIPELINE","STOP REPLICA","STOP REPLICATING","STOP SLAVE","TEST PIPELINE","UNLOCK INSTANCE","UNLOCK TABLES","USE","XA","ITERATE","LEAVE","LOOP","REPEAT","RETURN","WHILE"]),RO=G(["UNION [ALL | DISTINCT]","EXCEPT","INTERSECT","MINUS"]),AO=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),SO=G(["ON DELETE","ON UPDATE","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),dO=G([]),IO={name:"singlestoredb",tokenizerOptions:{reservedSelect:TO,reservedClauses:[...cO,...Pi,...ls],reservedSetOperations:RO,reservedJoins:AO,reservedKeywordPhrases:SO,reservedDataTypePhrases:dO,reservedKeywords:EO,reservedDataTypes:aO,reservedFunctionNames:lO,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:[...Pi,...ls],tabularOnelineClauses:ls}},uO=["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"],NO=["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"],OO=["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"],fO=G(["SELECT [ALL | DISTINCT]"]),CO=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"]),gi=G(["CREATE [OR REPLACE] [VOLATILE] TABLE [IF NOT EXISTS]","CREATE [OR REPLACE] [LOCAL | GLOBAL] {TEMP|TEMPORARY} TABLE [IF NOT EXISTS]"]),Ts=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"]),LO=G(["UNION [ALL]","MINUS","EXCEPT","INTERSECT"]),_O=G(["[INNER] JOIN","[NATURAL] {LEFT | RIGHT | FULL} [OUTER] JOIN","{CROSS | NATURAL} JOIN"]),hO=G(["{ROWS | RANGE} BETWEEN","ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]"]),pO=G([]),mO={name:"snowflake",tokenizerOptions:{reservedSelect:fO,reservedClauses:[...CO,...gi,...Ts],reservedSetOperations:LO,reservedJoins:_O,reservedKeywordPhrases:hO,reservedDataTypePhrases:pO,reservedKeywords:NO,reservedDataTypes:OO,reservedFunctionNames:uO,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:[...gi,...Ts],tabularOnelineClauses:Ts}},DO=Object.freeze(Object.defineProperty({__proto__:null,bigquery:$d,clickhouse:oI,db2:II,db2i:mI,duckdb:BI,hive:$I,mariadb:nu,mysql:Ru,n1ql:xu,plsql:Vu,postgresql:Qu,redshift:lN,singlestoredb:IO,snowflake:mO,spark:ON,sql:wN,sqlite:MN,tidb:Lu,transactsql:iO,trino:zN},Symbol.toStringTag,{value:"Module"})),tn=e=>e[e.length-1],ya=e=>e.sort((t,n)=>n.length-t.length||t.localeCompare(n)),jn=e=>e.replace(/\s+/gu," "),cs=e=>/\n/.test(e),Ue=e=>e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),Mi=/\s+/uy,ut=e=>new RegExp(`(?:${e})`,"uy"),PO=e=>e.split("").map(t=>/ /gu.test(t)?"\\s+":`[${t.toUpperCase()}${t.toLowerCase()}]`).join(""),gO=e=>e+"(?:-"+e+")*",MO=({prefixes:e,requirePrefix:t})=>`(?:${e.map(PO).join("|")}${t?"":"|"})`,yO=e=>new RegExp(`(?:${e.map(Ue).join("|")}).*?(?=\r
|
|
445
|
+
|\r|
|
|
446
|
+
|$)`,"uy"),yi=(e,t=[])=>{const n=e==="open"?0:1,r=["()",...t].map(s=>s[n]);return ut(r.map(Ue).join("|"))},xi=e=>ut(`${ya(e).map(Ue).join("|")}`),xO=({rest:e,dashes:t})=>e||t?`(?![${e||""}${t?"-":""}])`:"",Xe=(e,t={})=>{if(e.length===0)return/^\b$/u;const n=xO(t),r=ya(e).map(Ue).join("|").replace(/ /gu,"\\s+");return new RegExp(`(?:${r})${n}\\b`,"iuy")},Rs=(e,t)=>{if(!e.length)return;const n=e.map(Ue).join("|");return ut(`(?:${n})(?:${t})`)},UO=()=>{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''":UO()},xa=e=>typeof e=="string"?Ui[e]:"regex"in e?e.regex:MO(e)+Ui[e.quote],bO=e=>ut(e.map(t=>"regex"in t?t.regex:xa(t)).join("|")),Ua=e=>e.map(xa).join("|"),bi=e=>ut(Ua(e)),GO=(e={})=>ut(ba(e)),ba=({first:e,rest:t,dashes:n,allowFirstCharNumber:r}={})=>{const s="\\p{Alphabetic}\\p{Mark}_",o="\\p{Decimal_Number}",i=Ue(e??""),a=Ue(t??""),T=r?`[${s}${o}${i}][${s}${o}${a}]*`:`[${s}${i}][${s}${o}${a}]*`;return n?gO(T):T};function Ga(e,t){const n=e.slice(0,t).split(/\n/);return{line:n.length,col:n[n.length-1].length+1}}class BO{constructor(t,n){this.rules=t,this.dialectName=n,this.input="",this.index=0}tokenize(t){this.input=t,this.index=0;const n=[];let r;for(;this.index<this.input.length;){const s=this.getWhitespace();if(this.index<this.input.length){if(r=this.getNextToken(),!r)throw this.createParseError();n.push(Object.assign(Object.assign({},r),{precedingWhitespace:s}))}}return n}createParseError(){const t=this.input.slice(this.index,this.index+10),{line:n,col:r}=Ga(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],s={type:t.type,raw:r,text:t.text?t.text(r):r,start:this.index};return t.key&&(s.key=t.key(r)),this.index+=r.length,s}}}const Gi=/\/\*/uy,vO=/[\s\S]/uy,HO=/\*\//uy;class FO{constructor(){this.lastIndex=0}exec(t){let n="",r,s=0;if(r=this.matchSection(Gi,t))n+=r,s++;else return null;for(;s>0;)if(r=this.matchSection(Gi,t))n+=r,s++;else if(r=this.matchSection(HO,t))n+=r,s--;else if(r=this.matchSection(vO,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 wO{constructor(t,n){this.cfg=t,this.dialectName=n,this.rulesBeforeParams=this.buildRulesBeforeParams(t),this.rulesAfterParams=this.buildRulesAfterParams(t)}tokenize(t,n){const r=[...this.rulesBeforeParams,...this.buildParamRules(this.cfg,n),...this.rulesAfterParams],s=new BO(r,this.dialectName).tokenize(t);return this.cfg.postProcess?this.cfg.postProcess(s):s}buildRulesBeforeParams(t){var n,r,s;return this.validRules([{type:F.DISABLE_COMMENT,regex:/(\/\* *sql-formatter-disable *\*\/[\s\S]*?(?:\/\* *sql-formatter-enable *\*\/|$))/uy},{type:F.BLOCK_COMMENT,regex:t.nestedBlockComments?new FO:/(\/\*[^]*?\*\/)/uy},{type:F.LINE_COMMENT,regex:yO((n=t.lineCommentTypes)!==null&&n!==void 0?n:["--"])},{type:F.QUOTED_IDENTIFIER,regex:bi(t.identTypes)},{type:F.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:F.RESERVED_KEYWORD_PHRASE,regex:Xe((r=t.reservedKeywordPhrases)!==null&&r!==void 0?r:[],t.identChars),text:Se},{type:F.RESERVED_DATA_TYPE_PHRASE,regex:Xe((s=t.reservedDataTypePhrases)!==null&&s!==void 0?s:[],t.identChars),text:Se},{type:F.CASE,regex:/CASE\b/iuy,text:Se},{type:F.END,regex:/END\b/iuy,text:Se},{type:F.BETWEEN,regex:/BETWEEN\b/iuy,text:Se},{type:F.LIMIT,regex:t.reservedClauses.includes("LIMIT")?/LIMIT\b/iuy:void 0,text:Se},{type:F.RESERVED_CLAUSE,regex:Xe(t.reservedClauses,t.identChars),text:Se},{type:F.RESERVED_SELECT,regex:Xe(t.reservedSelect,t.identChars),text:Se},{type:F.RESERVED_SET_OPERATION,regex:Xe(t.reservedSetOperations,t.identChars),text:Se},{type:F.WHEN,regex:/WHEN\b/iuy,text:Se},{type:F.ELSE,regex:/ELSE\b/iuy,text:Se},{type:F.THEN,regex:/THEN\b/iuy,text:Se},{type:F.RESERVED_JOIN,regex:Xe(t.reservedJoins,t.identChars),text:Se},{type:F.AND,regex:/AND\b/iuy,text:Se},{type:F.OR,regex:/OR\b/iuy,text:Se},{type:F.XOR,regex:t.supportsXor?/XOR\b/iuy:void 0,text:Se},...t.operatorKeyword?[{type:F.OPERATOR,regex:/OPERATOR *\([^)]+\)/iuy}]:[],{type:F.RESERVED_FUNCTION_NAME,regex:Xe(t.reservedFunctionNames,t.identChars),text:Se},{type:F.RESERVED_DATA_TYPE,regex:Xe(t.reservedDataTypes,t.identChars),text:Se},{type:F.RESERVED_KEYWORD,regex:Xe(t.reservedKeywords,t.identChars),text:Se}])}buildRulesAfterParams(t){var n,r;return this.validRules([{type:F.VARIABLE,regex:t.variableTypes?bO(t.variableTypes):void 0},{type:F.STRING,regex:bi(t.stringTypes)},{type:F.IDENTIFIER,regex:GO(t.identChars)},{type:F.DELIMITER,regex:/[;]/uy},{type:F.COMMA,regex:/[,]/y},{type:F.OPEN_PAREN,regex:yi("open",t.extraParens)},{type:F.CLOSE_PAREN,regex:yi("close",t.extraParens)},{type:F.OPERATOR,regex:xi(["+","-","/",">","<","=","<>","<=",">=","!=",...(n=t.operators)!==null&&n!==void 0?n:[]])},{type:F.ASTERISK,regex:/[*]/uy},{type:F.PROPERTY_ACCESS_OPERATOR,regex:xi([".",...(r=t.propertyAccessOperators)!==null&&r!==void 0?r:[]])}])}buildParamRules(t,n){var r,s,o,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)||((s=t.paramTypes)===null||s===void 0?void 0:s.quoted)||[],numbered:(n==null?void 0:n.numbered)||((o=t.paramTypes)===null||o===void 0?void 0:o.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:F.NAMED_PARAMETER,regex:Rs(T.named,ba(t.paramChars||t.identChars)),key:l=>l.slice(1)},{type:F.QUOTED_PARAMETER,regex:Rs(T.quoted,Ua(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:F.NUMBERED_PARAMETER,regex:Rs(T.numbered,"[0-9]+"),key:l=>l.slice(1)},{type:F.POSITIONAL_PARAMETER,regex:T.positional?/[?]/y:void 0},...T.custom.map(l=>{var R;return{type:F.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=>jn(e.toUpperCase()),Bi=new Map,YO=e=>{let t=Bi.get(e);return t||(t=VO(e),Bi.set(e,t)),t},VO=e=>({tokenizer:new wO(e.tokenizerOptions,e.name),formatOptions:WO(e.formatOptions)}),WO=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 kO(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 XO{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:{}},$O=Kn.exports,vi;function jO(){return vi||(vi=1,(function(e){(function(t,n){e.exports?e.exports=n():t.nearley=n()})($O,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 C=d.rule.name;(this.completed[C]=this.completed[C]||[]).push(d)}}}else{var C=d.rule.symbols[d.dot];if(typeof C!="string"){this.scannable.push(d);continue}if(c[C]){if(c[C].push(d),A.hasOwnProperty(C))for(var N=A[C],O=0;O<N.length;O++){var _=N[O];this.complete(d,_)}}else c[C]=[d],this.predict(C)}}},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 s(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)})}s.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 s(A,R);return S.lexer=c,S};function o(){this.reset("")}o.prototype.reset=function(l,R){this.buffer=l,this.index=0,this.line=R?R.line:1,this.lastLineBreak=R?-R.col:0},o.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}}},o.prototype.save=function(){return{line:this.line,col:this.index-this.lastLineBreak}},o.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,C){return O(this.line-A.length+C+1,I)+" "+u},this).join(`
|
|
454
|
+
`),R+=`
|
|
455
|
+
`+O("",I+d)+`^
|
|
456
|
+
`,R}else return R+" at index "+(this.index-1);function O(u,C){var N=String(u);return Array(C-N.length+1).join(" ")+N}};function i(l,R,c){if(l instanceof s)var A=l,c=R;else var A=s.fromCompiled(l,R);this.grammar=A,this.options={keepHistory:!1,lexer:A.lexer||new o};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===o?c.value:c,C=S.scannable,N=C.length;N--;){var _=C[N],m=_.rule.symbols[_.dot];if(m.test?m.test(u):m.type?m.type===c.type:m.literal===O){var h=_.nextState({data:u,token:c,isToken:!0,reference:d-1});I.states.push(h)}}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],C=u.rule.symbols[u.dot],N=this.getSymbolDisplay(C);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:s,Rule:t}})})(Kn)),Kn.exports}var KO=jO();const JO=so(KO);function zO(e){return e.map(qO).map(ZO).map(QO).map(ef).map(tf)}const qO=(e,t,n)=>{if(Ma(e.type)){const r=nf(n,t);if(r&&r.type===F.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:F.IDENTIFIER,text:e.raw});const s=Ft(n,t);if(s&&s.type===F.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:F.IDENTIFIER,text:e.raw})}return e},ZO=(e,t,n)=>{if(e.type===F.RESERVED_FUNCTION_NAME){const r=Ft(n,t);if(!r||!Ba(r))return Object.assign(Object.assign({},e),{type:F.IDENTIFIER,text:e.raw})}return e},QO=(e,t,n)=>{if(e.type===F.RESERVED_DATA_TYPE){const r=Ft(n,t);if(r&&Ba(r))return Object.assign(Object.assign({},e),{type:F.RESERVED_PARAMETERIZED_DATA_TYPE})}return e},ef=(e,t,n)=>{if(e.type===F.IDENTIFIER){const r=Ft(n,t);if(r&&va(r))return Object.assign(Object.assign({},e),{type:F.ARRAY_IDENTIFIER})}return e},tf=(e,t,n)=>{if(e.type===F.RESERVED_DATA_TYPE){const r=Ft(n,t);if(r&&va(r))return Object.assign(Object.assign({},e),{type:F.ARRAY_KEYWORD})}return e},nf=(e,t)=>Ft(e,t,-1),Ft=(e,t,n=1)=>{let r=1;for(;e[t+r*n]&&rf(e[t+r*n]);)r++;return e[t+r*n]},Ba=e=>e.type===F.OPEN_PAREN&&e.text==="(",va=e=>e.type===F.OPEN_PAREN&&e.text==="[",rf=e=>e.type===F.BLOCK_COMMENT||e.type===F.LINE_COMMENT;class Ha{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}=Ga(this.input,t.start);return`Parse error at token: ${t.text} at line ${n} column ${r}`}has(t){return t in F}}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 As(e){return e[0]}const ne=new Ha(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),sf=(e,{leading:t,trailing:n})=>{if(t!=null&&t.length){const[r,...s]=e;e=[Ie(r,{leading:t}),...s]}if(n!=null&&n.length){const r=e.slice(0,-1),s=e[e.length-1];e=[...r,Ie(s,{trailing:n})]}return e},of={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===F.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:As},{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[s,o]=r;return{type:J.limit_clause,limitKw:Ie(de(e),{trailing:t}),offset:n,count:o}}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:As},{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,[s]])=>({type:J.property_access,object:Ie(e,{trailing:t}),operator:n.text,property:Ie(s,{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,s,o,i])=>({type:J.between_predicate,betweenKw:de(e),expr1:sf(n,{leading:t,trailing:r}),andKw:de(s),expr2:[Ie(i,{leading:o})]})},{name:"case_expression$ebnf$1",symbols:["expression_chain_"],postprocess:As},{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,s])=>({type:J.case_expression,caseKw:Ie(de(e),{trailing:t}),endKw:de(s),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,s,o])=>({type:J.case_when,whenKw:Ie(de(e),{trailing:t}),thenKw:Ie(de(r),{trailing:s}),condition:n,result:o})},{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:Ef,Grammar:af}=JO;function lf(e){let t={};const n=new Ha(s=>[...zO(e.tokenize(s,t)),ga(s.length)]),r=new Ef(af.fromCompiled(of),{lexer:n});return{parse:(s,o)=>{t=o;const{results:i}=r.feed(s);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 Fa{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(;Tf(tn(this.items));)this.items.pop()}trimWhitespace(){for(;cf(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 Tf=e=>e===H.SPACE||e===H.SINGLE_INDENT,cf=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 Bd(e)||e===F.RESERVED_CLAUSE||e===F.RESERVED_SELECT||e===F.RESERVED_SET_OPERATION||e===F.RESERVED_JOIN||e===F.LIMIT}const Ss="top-level",Rf="block-level";class wa{constructor(t){this.indent=t,this.indentTypes=[]}getSingleIndent(){return this.indent}getLevel(){return this.indentTypes.length}increaseTopLevel(){this.indentTypes.push(Ss)}increaseBlockLevel(){this.indentTypes.push(Rf)}decreaseTopLevel(){this.indentTypes.length>0&&tn(this.indentTypes)===Ss&&this.indentTypes.pop()}decreaseBlockLevel(){for(;this.indentTypes.length>0&&this.indentTypes.pop()===Ss;);}}class Af extends Fa{constructor(t){super(new wa("")),this.expressionWidth=t,this.length=0,this.trailingSpace=!1}add(...t){if(t.forEach(n=>this.addToLength(n)),this.length>this.expressionWidth)throw new Vs;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 Vs;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 Vs extends Error{}class Er{constructor({cfg:t,dialectCfg:n,params:r,layout:s,inline:o=!1}){this.inline=!1,this.nodes=[],this.index=-1,this.cfg=t,this.dialectCfg=n,this.inline=o,this.params=r,this.layout=s}format(t){for(this.nodes=t,this.index=0;this.index<this.nodes.length;this.index++)this.formatNode(this.nodes[this.index]);return this.layout}formatNode(t){this.formatComments(t.leadingComments),this.formatNodeWithoutComments(t),this.formatComments(t.trailingComments)}formatNodeWithoutComments(t){switch(t.type){case 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){cs(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 cs(t.text)||cs(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 Af(this.cfg.expressionWidth),inline:!0}).format(t)}catch(r){if(r instanceof Vs){this.params.setPositionalParameterIndex(n);return}else throw r}}formatKeywordNode(t){switch(t.tokenType){case F.RESERVED_JOIN:return this.formatJoin(t);case F.AND:case F.OR:case F.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 jn(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 jn(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 jn(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}}class Sf{constructor(t,n){this.dialect=t,this.cfg=n,this.params=new XO(this.cfg.params)}format(t){const n=this.parse(t);return this.formatAst(n).trimEnd()}parse(t){return lf(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 Fa(new wa(kO(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 df(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&&!If(e.params)&&console.warn('WARNING: All "params" option values should be strings.'),e.paramTypes&&!uf(e.paramTypes))throw new Jn("Empty regex given in custom paramTypes. That would result in matching infinite amount of parameters.");return e}function If(e){return(e instanceof Array?e:Object.values(e)).every(n=>typeof n=="string")}function uf(e){return e.custom&&Array.isArray(e.custom)?e.custom.every(t=>t.regex!==""):!0}var Nf=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]]);return n};const Ya={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"},Of=Object.keys(Ya),ff={tabWidth:2,useTabs:!1,keywordCase:"preserve",identifierCase:"preserve",dataTypeCase:"preserve",functionCase:"preserve",indentStyle:"standard",logicalOperatorNewline:"before",expressionWidth:50,linesBetweenQueries:1,denseOperators:!1,newlineBeforeSemicolon:!1},Cf=(e,t={})=>{if(typeof t.language=="string"&&!Of.includes(t.language))throw new Jn(`Unsupported SQL dialect: ${t.language}`);const n=Ya[t.language||"sql"];return Lf(e,Object.assign(Object.assign({},t),{dialect:DO[n]}))},Lf=(e,t)=>{var{dialect:n}=t,r=Nf(t,["dialect"]);if(typeof e!="string")throw new Error("Invalid query argument. Expected string, instead got "+typeof e);const s=df(Object.assign(Object.assign({},ff),r));return new Sf(YO(n),s).format(e)},_f={sql:"SQL",markdown:"MD",dql:"DQL",param:"PARAM"},ds={sql:"#388bfd",markdown:"#56d364",dql:"#e3b341",param:"#e3b341"};function hf(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 pf({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 mf(e){if(!/^\s*block\s+"/i.test(e.trim()))return null;const t=s=>{var o;return((o=e.match(new RegExp(`\\b${s}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:o[1])??""},n=e.match(/\btags\s*=\s*\[([^\]]*)\]/i),r=n?(n[1].match(/"([^"]*)"/g)??[]).map(s=>s.slice(1,-1)):[];return{domain:t("domain"),owner:t("owner"),description:t("description"),blockType:t("type")||"custom",tags:r}}function Is(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 Df(e,t){const n=t.map(s=>`"${s}"`).join(", "),r=/(\btags\s*=\s*)\[[^\]]*\]/i;return r.test(e)?e.replace(r,`$1[${n}]`):e}function Pf({content:e,onChange:t,t:n}){const r=mf(e);if(!r)return null;const s={background:n.editorBg,border:`1px solid ${n.cellBorder}`,borderRadius:3,color:n.textSecondary,fontSize:11,fontFamily:n.fontMono,padding:"2px 6px",outline:"none"},o={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:o,children:"domain"}),E.jsx("input",{style:{...s,width:80},value:r.domain,placeholder:"e.g. finance",onChange:a=>t(Is(e,"domain",a.target.value))})]}),E.jsxs("div",{style:i,children:[E.jsx("span",{style:o,children:"owner"}),E.jsx("input",{style:{...s,width:90},value:r.owner,placeholder:"e.g. data-team",onChange:a=>t(Is(e,"owner",a.target.value))})]}),E.jsxs("div",{style:i,children:[E.jsx("span",{style:o,children:"tags"}),E.jsx("input",{style:{...s,width:110},value:r.tags.join(", "),placeholder:"revenue, kpi",onChange:a=>{const T=a.target.value.split(",").map(l=>l.trim()).filter(Boolean);t(Df(e,T))}})]}),E.jsxs("div",{style:{...i,flex:1},children:[E.jsx("span",{style:o,children:"description"}),E.jsx("input",{style:{...s,flex:1,minWidth:120},value:r.description,placeholder:"What this block measures",onChange:a=>t(Is(e,"description",a.target.value))})]})]})}function gf({cell:e,index:t}){const{state:n,dispatch:r}=ae(),s=Ee[n.themeMode],{executeCell:o,executeDependents:i}=Eo(),[a,T]=f.useState(!1),[l,R]=f.useState(!1),[c,A]=f.useState(e.name??""),[S,d]=f.useState(!0),[I,O]=f.useState("table"),u=hf(e,s),C=e.type!=="markdown"&&e.type!=="param",N=f.useMemo(()=>n.schemaTables.length>0?Object.fromEntries(n.schemaTables.map(L=>[L.name,L.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(rd,{cell:e,themeMode:n.themeMode,onApplyParam:i})})]});f.useEffect(()=>{if(e.status==="success"&&e.result){const L=Ys(e.result,e.chartConfig);O(L!=="table"?"chart":"table")}},[e.status,e.result,e.chartConfig]);const _=f.useCallback(()=>{C&&o(e.id)},[e.id,o,C]),m=f.useCallback(L=>{r({type:"UPDATE_CELL",id:e.id,updates:{content:L}})},[e.id,r]),h=f.useCallback(()=>{if(e.content.trim())try{const L=Cf(e.content,{language:"sql",tabWidth:2,keywordCase:"upper",linesBetweenQueries:1});r({type:"UPDATE_CELL",id:e.id,updates:{content:L}})}catch{}},[e.content,e.id,r]),D=f.useCallback(()=>{h(),setTimeout(()=>o(e.id),80)},[h,o,e.id]),M=()=>{r({type:"DELETE_CELL",id:e.id})},B=()=>{r({type:"MOVE_CELL",id:e.id,direction:"up"})},w=()=>{r({type:"MOVE_CELL",id:e.id,direction:"down"})},P=()=>{R(!1),r({type:"UPDATE_CELL",id:e.id,updates:{name:c.trim()||void 0}})},p=(e.result||e.error)&&e.type!=="markdown",U=e.result?Ys(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(pf,{cell:e,t:s}),E.jsxs("div",{style:{flex:1,minWidth:0,borderRadius:8,border:`1px solid ${a||e.status!=="idle"?u:s.cellBorder}`,borderLeft:`2px solid ${u}`,background:s.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 ${s.cellBorder}`,background:`${s.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:s.fontMono,letterSpacing:"0.08em",color:ds[e.type]??s.accent,background:`${ds[e.type]??s.accent}18`,border:`1px solid ${ds[e.type]??s.accent}40`,borderRadius:4,padding:"1px 6px",flexShrink:0,textTransform:"uppercase"},children:_f[e.type]}),a&&(e.type==="sql"||e.type==="dql")&&E.jsx(od,{themeMode:n.themeMode,cellType:e.type,onInsert:L=>m(L)}),a&&(e.type==="sql"||e.type==="dql")&&E.jsx("button",{title:"Format SQL (clean up whitespace & keywords)",onClick:h,style:{background:"transparent",border:`1px solid ${s.btnBorder}`,borderRadius:4,color:s.textMuted,fontSize:10,fontFamily:s.font,fontWeight:600,letterSpacing:"0.04em",padding:"1px 7px",cursor:"pointer",transition:"color 0.15s, border-color 0.15s"},onMouseEnter:L=>{L.currentTarget.style.color=s.textSecondary,L.currentTarget.style.borderColor=s.accent},onMouseLeave:L=>{L.currentTarget.style.color=s.textMuted,L.currentTarget.style.borderColor=s.btnBorder},children:"Format"}),l?E.jsx("input",{autoFocus:!0,value:c,onChange:L=>A(L.target.value),onBlur:P,onKeyDown:L=>{L.key==="Enter"&&P(),L.key==="Escape"&&R(!1)},style:{background:"transparent",border:`1px solid ${s.cellBorderActive}`,borderRadius:4,color:s.textSecondary,fontSize:12,fontFamily:s.fontMono,padding:"1px 6px",outline:"none",width:140}}):e.name&&E.jsx("span",{onClick:()=>{A(e.name??""),R(!0)},title:"Click to rename",style:{color:s.textSecondary,fontSize:12,fontFamily:s.fontMono,cursor:"text",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:200},children:e.name}),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:s,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"})})}),C&&E.jsx(Kt,{title:"Run cell (Shift+Enter)",onClick:_,t:s,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:s,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:w,t:s,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:s,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(Pf,{content:e.content,onChange:m,t:s}),e.type==="markdown"?E.jsx(nd,{value:e.content,onChange:m,themeMode:n.themeMode}):E.jsx(Da,{value:e.content,onChange:m,onRun:_,themeMode:n.themeMode,schema:N}),p&&E.jsxs("div",{style:{borderTop:`1px solid ${s.cellBorder}`},children:[E.jsxs("div",{style:{height:28,display:"flex",alignItems:"center",padding:"0 12px",gap:10,borderBottom:e.result&&S?`1px solid ${s.cellBorder}`:"none",background:`${s.tableHeaderBg}60`},children:[e.result&&E.jsxs("span",{style:{fontSize:11,fontFamily:s.font,color:s.textMuted},children:[(e.result.rowCount??e.result.rows.length).toLocaleString()," rows",e.result.executionTime!==void 0&&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:s.font,color:s.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(L=>E.jsx("button",{onClick:()=>O(L),style:{padding:"1px 7px",fontSize:10,fontFamily:s.font,borderRadius:3,border:`1px solid ${I===L?s.accent:s.btnBorder}`,background:I===L?`${s.accent}20`:"transparent",color:I===L?s.accent:s.textMuted,cursor:"pointer",transition:"all 0.15s",textTransform:"capitalize"},children:L==="chart"?"Chart":"Table"},L))}),E.jsxs("button",{onClick:()=>d(L=>!L),style:{background:"transparent",border:"none",cursor:"pointer",color:s.textMuted,fontSize:11,fontFamily:s.font,padding:"2px 4px",display:"flex",alignItems:"center",gap:4},children:[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(Cd,{message:e.error,themeMode:n.themeMode,onFix:C?D:void 0,schemaTables:n.schemaTables}),e.result&&!e.error&&(I==="chart"&&U?E.jsx(ud,{result:e.result,themeMode:n.themeMode,chartConfig:e.chartConfig}):E.jsx(Pa,{result:e.result,themeMode:n.themeMode}))]})]}),C&&E.jsx(Dd,{cellContent:e.content,cellType:e.type,cellName:e.name,themeMode:n.themeMode,t:s})]})]})}function Kt({title:e,onClick:t,children:n,t:r,accent:s,danger:o}){const[i,a]=f.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?o?`${r.error}18`:s?`${r.accent}18`:r.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:i?o?r.error:s?r.accent:r.textSecondary:r.textMuted,transition:"all 0.15s",padding:0},children:n})}const Mf=[{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 us({afterId:e}){const{state:t,dispatch:n}=ae(),r=Ee[t.themeMode],[s,o]=f.useState(!1),[i,a]=f.useState(!1),T=f.useRef(null);f.useEffect(()=>{if(!i)return;function R(c){T.current&&!T.current.contains(c.target)&&a(!1)}return document.addEventListener("mousedown",R),()=>document.removeEventListener("mousedown",R)},[i]);const l=R=>{const c=De(R);n({type:"ADD_CELL",cell:c,afterId:e}),a(!1)};return E.jsxs("div",{ref:T,onMouseEnter:()=>o(!0),onMouseLeave:()=>{o(!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:s||i?r.cellBorderActive:"transparent",transition:"background 0.15s"}}),(s||i)&&E.jsxs("button",{onClick:()=>a(R=>!R),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.jsx("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",gap:4},children:Mf.map(({type:R,label:c,color:A})=>E.jsx(yf,{label:c,color:A,onClick:()=>l(R),t:r},R))})]})}function yf({label:e,color:t,onClick:n,t:r}){const[s,o]=f.useState(!1);return E.jsx("button",{onClick:n,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),style:{background:s?`${t}18`:"transparent",border:`1px solid ${s?t:r.cellBorder}`,borderRadius:6,cursor:"pointer",color:s?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 xf({registerCellRef:e}){const{state:t,dispatch:n}=ae(),{executeCell:r}=Eo(),s=Ee[t.themeMode],[o,i]=f.useState(null),a=f.useRef(0);return f.useCallback(T=>{i(T)},[]),f.useEffect(()=>{function T(l){var S;if(!o)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===o);if(A!==-1)switch(l.key){case"a":{l.preventDefault();const d=De("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=De("sql");n({type:"ADD_CELL",cell:d,afterId:o}),i(d.id);break}case"d":{l.preventDefault();const d=Date.now();if(d-a.current<=500){if(n({type:"DELETE_CELL",id:o}),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)},[o,t.cells,n,r]),f.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(us,{}),E.jsx(Uf,{t:s})]}):E.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[E.jsx(us,{afterId:void 0}),t.cells.map((T,l)=>E.jsxs(sn.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:o===T.id?`2px solid ${s.accent}40`:"none",outlineOffset:2,borderRadius:10,transition:"outline 0.1s"},children:E.jsx(gf,{cell:T,index:l})}),E.jsx(us,{afterId:T.id})]},T.id))]})}function Uf({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=Ee[n.themeMode];return n.activeFile?E.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",background:r.appBg},children:[E.jsx(Gf,{t:r}),E.jsx("div",{style:{flex:1,overflow:"auto",padding:"24px 0 40px"},children:E.jsx(xf,{registerCellRef:t})})]}):E.jsx(mS,{onOpenFile:e})}function Gf({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(Bf,{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 Bf({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,s)=>E.jsxs(sn.Fragment,{children:[s>0&&E.jsx("span",{style:{color:e.textMuted,opacity:.5},children:"/"}),E.jsx("span",{style:{color:s===n.length-1?e.textSecondary:e.textMuted,fontWeight:s===n.length-1?500:400,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:s===n.length-1?200:100},children:r})]},s))})}const Yi={blank:"Blank",revenue:"Revenue Analysis",pipeline:"Pipeline Health"},vf={blank:"Start with an empty notebook.",revenue:"Pre-built queries for revenue metrics and trends.",pipeline:"Templates for data pipeline health monitoring."};function Vi(e){return e.toLowerCase().replace(/[^a-z0-9\-_\s]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,64)}function Hf(e){return e.trim()?/^[a-zA-Z0-9\-_ ]+$/.test(e)?null:"Only letters, numbers, hyphens, underscores, and spaces allowed.":"Name is required."}function Ff(e){switch(e){case"revenue":return[De("markdown",`# Revenue Analysis
|
|
463
|
+
|
|
464
|
+
This notebook analyzes revenue metrics and trends over time.`),{...De("sql",`SELECT
|
|
465
|
+
DATE_TRUNC('month', order_date) AS month,
|
|
466
|
+
SUM(amount) AS revenue
|
|
467
|
+
FROM orders
|
|
468
|
+
GROUP BY 1
|
|
469
|
+
ORDER BY 1`),name:"monthly_revenue"},{...De("sql",`SELECT
|
|
470
|
+
product_category,
|
|
471
|
+
SUM(amount) AS total_revenue,
|
|
472
|
+
COUNT(*) AS orders
|
|
473
|
+
FROM orders
|
|
474
|
+
GROUP BY 1
|
|
475
|
+
ORDER BY 2 DESC`),name:"revenue_by_category"}];case"pipeline":return[De("markdown",`# Pipeline Health
|
|
476
|
+
|
|
477
|
+
Monitor data pipeline performance, SLA compliance, and error rates.`),{...De("sql",`SELECT
|
|
478
|
+
pipeline_name,
|
|
479
|
+
COUNT(*) AS runs,
|
|
480
|
+
AVG(duration_seconds) AS avg_duration,
|
|
481
|
+
SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failures
|
|
482
|
+
FROM pipeline_runs
|
|
483
|
+
GROUP BY 1
|
|
484
|
+
ORDER BY 4 DESC`),name:"pipeline_summary"},{...De("sql",`SELECT
|
|
485
|
+
*
|
|
486
|
+
FROM pipeline_runs
|
|
487
|
+
WHERE status = 'failed'
|
|
488
|
+
AND run_date >= CURRENT_DATE - INTERVAL '7 days'
|
|
489
|
+
ORDER BY run_date DESC`),name:"recent_failures"}];default:return[De("sql")]}}function wf({onFileOpened:e}){const{state:t,dispatch:n}=ae(),r=Ee[t.themeMode],[s,o]=f.useState(""),[i,a]=f.useState("blank"),[T,l]=f.useState(null),[R,c]=f.useState(!1),A=f.useRef(null);f.useEffect(()=>{var I;(I=A.current)==null||I.focus()},[]),f.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=Hf(s);if(I){l(I);return}c(!0),l(null);const O=Vi(s),u=Ff(i);try{const C=await Re.createNotebook(O,i),N={name:`${O}.dqlnb`,path:C.path,type:"notebook",folder:"notebooks",isNew:!0};n({type:"FILE_ADDED",file:N}),n({type:"OPEN_FILE",file:N,cells:u,title:s.trim()}),n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),e(N)}catch{const C=`notebooks/${O}.dqlnb`,N={name:`${O}.dqlnb`,path:C,type:"notebook",folder:"notebooks",isNew:!0};n({type:"FILE_ADDED",file:N}),n({type:"OPEN_FILE",file:N,cells:u,title:s.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:s,onChange:I=>{o(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}),s&&!T&&E.jsxs("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.fontMono},children:["File: ",Vi(s),".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(Yi).map(I=>E.jsx(Yf,{value:I,selected:i===I,onSelect:()=>a(I),label:Yi[I],description:vf[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||!s.trim(),style:{background:r.accent,border:`1px solid ${r.accent}`,borderRadius:6,color:"#ffffff",cursor:R||!s.trim()?"not-allowed":"pointer",fontSize:13,fontFamily:r.font,fontWeight:500,padding:"7px 20px",opacity:R||!s.trim()?.6:1,display:"flex",alignItems:"center",gap:6},children:R?"Creating…":"Create Notebook"})]})]})})}function Yf({value:e,selected:t,onSelect:n,label:r,description:s,t:o}){const[i,a]=f.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?o.cellBorderActive:i?o.textMuted:o.inputBorder}`,background:t?`${o.cellBorderActive}10`:i?o.sidebarItemHover:"transparent",cursor:"pointer",transition:"all 0.15s"},children:[E.jsx("div",{style:{width:16,height:16,borderRadius:8,border:`2px solid ${t?o.accent:o.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:o.accent}})}),E.jsxs("div",{children:[E.jsx("div",{style:{fontSize:13,fontWeight:500,color:o.textPrimary,fontFamily:o.font,marginBottom:2},children:r}),E.jsx("div",{style:{fontSize:12,color:o.textSecondary,fontFamily:o.font},children:s})]})]})}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 Vf={value:()=>{}};function _r(){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 Wf(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",s=n.indexOf(".");if(s>=0&&(r=n.slice(s+1),n=n.slice(0,s)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}zn.prototype=_r.prototype={constructor:zn,on:function(e,t){var n=this._,r=Wf(e+"",n),s,o=-1,i=r.length;if(arguments.length<2){for(;++o<i;)if((s=(e=r[o]).type)&&(s=kf(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++o<i;)if(s=(e=r[o]).type)n[s]=Wi(n[s],e.name,t);else if(t==null)for(s in n)n[s]=Wi(n[s],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new zn(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,o;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(o=this._[e],r=0,s=o.length;r<s;++r)o[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],s=0,o=r.length;s<o;++s)r[s].value.apply(t,n)}};function kf(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function Wi(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=Vf,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Ws="http://www.w3.org/1999/xhtml";const ki={svg:"http://www.w3.org/2000/svg",xhtml:Ws,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function hr(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),ki.hasOwnProperty(t)?{space:ki[t],local:e}:e}function Xf(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Ws&&t.documentElement.namespaceURI===Ws?t.createElement(e):t.createElementNS(n,e)}}function $f(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function Va(e){var t=hr(e);return(t.local?$f:Xf)(t)}function jf(){}function Io(e){return e==null?jf:function(){return this.querySelector(e)}}function Kf(e){typeof e!="function"&&(e=Io(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var o=t[s],i=o.length,a=r[s]=new Array(i),T,l,R=0;R<i;++R)(T=o[R])&&(l=e.call(T,T.__data__,R,o))&&("__data__"in T&&(l.__data__=T.__data__),a[R]=l);return new pe(r,this._parents)}function Jf(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function zf(){return[]}function Wa(e){return e==null?zf:function(){return this.querySelectorAll(e)}}function qf(e){return function(){return Jf(e.apply(this,arguments))}}function Zf(e){typeof e=="function"?e=qf(e):e=Wa(e);for(var t=this._groups,n=t.length,r=[],s=[],o=0;o<n;++o)for(var i=t[o],a=i.length,T,l=0;l<a;++l)(T=i[l])&&(r.push(e.call(T,T.__data__,l,i)),s.push(T));return new pe(r,s)}function ka(e){return function(){return this.matches(e)}}function Xa(e){return function(t){return t.matches(e)}}var Qf=Array.prototype.find;function eC(e){return function(){return Qf.call(this.children,e)}}function tC(){return this.firstElementChild}function nC(e){return this.select(e==null?tC:eC(typeof e=="function"?e:Xa(e)))}var rC=Array.prototype.filter;function sC(){return Array.from(this.children)}function oC(e){return function(){return rC.call(this.children,e)}}function iC(e){return this.selectAll(e==null?sC:oC(typeof e=="function"?e:Xa(e)))}function EC(e){typeof e!="function"&&(e=ka(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var o=t[s],i=o.length,a=r[s]=[],T,l=0;l<i;++l)(T=o[l])&&e.call(T,T.__data__,l,o)&&a.push(T);return new pe(r,this._parents)}function $a(e){return new Array(e.length)}function aC(){return new pe(this._enter||this._groups.map($a),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 lC(e){return function(){return e}}function TC(e,t,n,r,s,o){for(var i=0,a,T=t.length,l=o.length;i<l;++i)(a=t[i])?(a.__data__=o[i],r[i]=a):n[i]=new ar(e,o[i]);for(;i<T;++i)(a=t[i])&&(s[i]=a)}function cC(e,t,n,r,s,o,i){var a,T,l=new Map,R=t.length,c=o.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)?s[a]=T:l.set(S,T));for(a=0;a<c;++a)S=i.call(e,o[a],a,o)+"",(T=l.get(S))?(r[a]=T,T.__data__=o[a],l.delete(S)):n[a]=new ar(e,o[a]);for(a=0;a<R;++a)(T=t[a])&&l.get(A[a])===T&&(s[a]=T)}function RC(e){return e.__data__}function AC(e,t){if(!arguments.length)return Array.from(this,RC);var n=t?cC:TC,r=this._parents,s=this._groups;typeof e!="function"&&(e=lC(e));for(var o=s.length,i=new Array(o),a=new Array(o),T=new Array(o),l=0;l<o;++l){var R=r[l],c=s[l],A=c.length,S=SC(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 C=0,N=0,_,m;C<d;++C)if(_=I[C]){for(C>=N&&(N=C+1);!(m=O[N])&&++N<d;);_._next=m||null}}return i=new pe(i,r),i._enter=a,i._exit=T,i}function SC(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function dC(){return new pe(this._exit||this._groups.map($a),this._parents)}function IC(e,t,n){var r=this.enter(),s=this,o=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(s=t(s),s&&(s=s.selection())),n==null?o.remove():n(o),r&&s?r.merge(s).order():s}function uC(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,o=r.length,i=Math.min(s,o),a=new Array(s),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<s;++T)a[T]=n[T];return new pe(a,this._parents)}function NC(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,o=r[s],i;--s>=0;)(i=r[s])&&(o&&i.compareDocumentPosition(o)^4&&o.parentNode.insertBefore(i,o),o=i);return this}function OC(e){e||(e=fC);function t(c,A){return c&&A?e(c.__data__,A.__data__):!c-!A}for(var n=this._groups,r=n.length,s=new Array(r),o=0;o<r;++o){for(var i=n[o],a=i.length,T=s[o]=new Array(a),l,R=0;R<a;++R)(l=i[R])&&(T[R]=l);T.sort(t)}return new pe(s,this._parents).order()}function fC(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function CC(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function LC(){return Array.from(this)}function _C(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,o=r.length;s<o;++s){var i=r[s];if(i)return i}return null}function hC(){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 s=t[n],o=0,i=s.length,a;o<i;++o)(a=s[o])&&e.call(a,a.__data__,o,s);return this}function DC(e){return function(){this.removeAttribute(e)}}function PC(e){return function(){this.removeAttributeNS(e.space,e.local)}}function gC(e,t){return function(){this.setAttribute(e,t)}}function MC(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function yC(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function xC(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 UC(e,t){var n=hr(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?PC:DC:typeof t=="function"?n.local?xC:yC:n.local?MC:gC)(n,t))}function ja(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function bC(e){return function(){this.style.removeProperty(e)}}function GC(e,t,n){return function(){this.style.setProperty(e,t,n)}}function BC(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function vC(e,t,n){return arguments.length>1?this.each((t==null?bC:typeof t=="function"?BC:GC)(e,t,n??"")):Mt(this.node(),e)}function Mt(e,t){return e.style.getPropertyValue(t)||ja(e).getComputedStyle(e,null).getPropertyValue(t)}function HC(e){return function(){delete this[e]}}function FC(e,t){return function(){this[e]=t}}function wC(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function YC(e,t){return arguments.length>1?this.each((t==null?HC:typeof t=="function"?wC:FC)(e,t)):this.node()[e]}function Ka(e){return e.trim().split(/^|\s+/)}function uo(e){return e.classList||new Ja(e)}function Ja(e){this._node=e,this._names=Ka(e.getAttribute("class")||"")}Ja.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=uo(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function qa(e,t){for(var n=uo(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function VC(e){return function(){za(this,e)}}function WC(e){return function(){qa(this,e)}}function kC(e,t){return function(){(t.apply(this,arguments)?za:qa)(this,e)}}function XC(e,t){var n=Ka(e+"");if(arguments.length<2){for(var r=uo(this.node()),s=-1,o=n.length;++s<o;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?kC:t?VC:WC)(n,t))}function $C(){this.textContent=""}function jC(e){return function(){this.textContent=e}}function KC(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function JC(e){return arguments.length?this.each(e==null?$C:(typeof e=="function"?KC:jC)(e)):this.node().textContent}function zC(){this.innerHTML=""}function qC(e){return function(){this.innerHTML=e}}function ZC(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function QC(e){return arguments.length?this.each(e==null?zC:(typeof e=="function"?ZC:qC)(e)):this.node().innerHTML}function eL(){this.nextSibling&&this.parentNode.appendChild(this)}function tL(){return this.each(eL)}function nL(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function rL(){return this.each(nL)}function sL(e){var t=typeof e=="function"?e:Va(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function oL(){return null}function iL(e,t){var n=typeof e=="function"?e:Va(e),r=t==null?oL:typeof t=="function"?t:Io(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function EL(){var e=this.parentNode;e&&e.removeChild(this)}function aL(){return this.each(EL)}function lL(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function TL(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function cL(e){return this.select(e?TL:lL)}function RL(e){return arguments.length?this.property("__data__",e):this.node().__data__}function AL(e){return function(t){e.call(this,t,this.__data__)}}function SL(e){return e.trim().split(/^|\s+/).map(function(t){var n="",r=t.indexOf(".");return r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),{type:t,name:n}})}function dL(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,o;n<s;++n)o=t[n],(!e.type||o.type===e.type)&&o.name===e.name?this.removeEventListener(o.type,o.listener,o.options):t[++r]=o;++r?t.length=r:delete this.__on}}}function IL(e,t,n){return function(){var r=this.__on,s,o=AL(t);if(r){for(var i=0,a=r.length;i<a;++i)if((s=r[i]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=o,s.options=n),s.value=t;return}}this.addEventListener(e.type,o,n),s={type:e.type,name:e.name,value:t,listener:o,options:n},r?r.push(s):this.__on=[s]}}function uL(e,t,n){var r=SL(e+""),s,o=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(s=0,R=a[T];s<o;++s)if((i=r[s]).type===R.type&&i.name===R.name)return R.value}return}for(a=t?IL:dL,s=0;s<o;++s)this.each(a(r[s],t,n));return this}function Za(e,t,n){var r=ja(e),s=r.CustomEvent;typeof s=="function"?s=new s(t,n):(s=r.document.createEvent("Event"),n?(s.initEvent(t,n.bubbles,n.cancelable),s.detail=n.detail):s.initEvent(t,!1,!1)),e.dispatchEvent(s)}function NL(e,t){return function(){return Za(this,e,t)}}function OL(e,t){return function(){return Za(this,e,t.apply(this,arguments))}}function fL(e,t){return this.each((typeof t=="function"?OL:NL)(e,t))}function*CL(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,o=r.length,i;s<o;++s)(i=r[s])&&(yield i)}var Qa=[null];function pe(e,t){this._groups=e,this._parents=t}function Cn(){return new pe([[document.documentElement]],Qa)}function LL(){return this}pe.prototype=Cn.prototype={constructor:pe,select:Kf,selectAll:Zf,selectChild:nC,selectChildren:iC,filter:EC,data:AC,enter:aC,exit:dC,join:IC,merge:uC,selection:LL,order:NC,sort:OC,call:CC,nodes:LC,node:_C,size:hC,empty:pC,each:mC,attr:UC,style:vC,property:YC,classed:XC,text:JC,html:QC,raise:tL,lower:rL,append:sL,insert:iL,remove:aL,clone:cL,datum:RL,on:uL,dispatch:fL,[Symbol.iterator]:CL};function _e(e){return typeof e=="string"?new pe([[document.querySelector(e)]],[document.documentElement]):new pe([[e]],Qa)}function _L(e){let t;for(;t=e.sourceEvent;)e=t;return e}function ge(e,t){if(e=_L(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,r=r.matrixTransform(t.getScreenCTM().inverse()),[r.x,r.y]}if(t.getBoundingClientRect){var s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}}return[e.pageX,e.pageY]}const hL={passive:!1},ln={capture:!0,passive:!1};function Ns(e){e.stopImmediatePropagation()}function Pt(e){e.preventDefault(),e.stopImmediatePropagation()}function el(e){var t=e.document.documentElement,n=_e(e).on("dragstart.drag",Pt,ln);"onselectstart"in t?n.on("selectstart.drag",Pt,ln):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function tl(e,t){var n=e.document.documentElement,r=_e(e).on("dragstart.drag",null);t&&(r.on("click.drag",Pt,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 ks(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:o,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:s,enumerable:!0,configurable:!0},active:{value:o,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}})}ks.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 DL(e,t){return t??{x:e.x,y:e.y}}function PL(){return navigator.maxTouchPoints||"ontouchstart"in this}function nl(){var e=pL,t=mL,n=DL,r=PL,s={},o=_r("start","drag","end"),i=0,a,T,l,R,c=0;function A(_){_.on("mousedown.drag",S).filter(r).on("touchstart.drag",O).on("touchmove.drag",u,hL).on("touchend.drag touchcancel.drag",C).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function S(_,m){if(!(R||!e.call(this,_,m))){var h=N(this,t.call(this,_,m),_,m,"mouse");h&&(_e(_.view).on("mousemove.drag",d,ln).on("mouseup.drag",I,ln),el(_.view),Ns(_),l=!1,a=_.clientX,T=_.clientY,h("start",_))}}function d(_){if(Pt(_),!l){var m=_.clientX-a,h=_.clientY-T;l=m*m+h*h>c}s.mouse("drag",_)}function I(_){_e(_.view).on("mousemove.drag mouseup.drag",null),tl(_.view,l),Pt(_),s.mouse("end",_)}function O(_,m){if(e.call(this,_,m)){var h=_.changedTouches,D=t.call(this,_,m),M=h.length,B,w;for(B=0;B<M;++B)(w=N(this,D,_,m,h[B].identifier,h[B]))&&(Ns(_),w("start",_,h[B]))}}function u(_){var m=_.changedTouches,h=m.length,D,M;for(D=0;D<h;++D)(M=s[m[D].identifier])&&(Pt(_),M("drag",_,m[D]))}function C(_){var m=_.changedTouches,h=m.length,D,M;for(R&&clearTimeout(R),R=setTimeout(function(){R=null},500),D=0;D<h;++D)(M=s[m[D].identifier])&&(Ns(_),M("end",_,m[D]))}function N(_,m,h,D,M,B){var w=o.copy(),P=ge(B||h,m),p,U,L;if((L=n.call(_,new ks("beforestart",{sourceEvent:h,target:A,identifier:M,active:i,x:P[0],y:P[1],dx:0,dy:0,dispatch:w}),D))!=null)return p=L.x-P[0]||0,U=L.y-P[1]||0,function x(g,v,b){var y=P,Y;switch(g){case"start":s[M]=x,Y=i++;break;case"end":delete s[M],--i;case"drag":P=ge(b||v,m),Y=i;break}w.call(g,_,new ks(g,{sourceEvent:v,subject:L,target:A,identifier:M,active:Y,x:P[0]+p,y:P[1]+U,dx:P[0]-y[0],dy:P[1]-y[1],dispatch:w}),D)}}return A.filter=function(_){return arguments.length?(e=typeof _=="function"?_:Bn(!!_),A):e},A.container=function(_){return arguments.length?(t=typeof _=="function"?_:Bn(_),A):t},A.subject=function(_){return arguments.length?(n=typeof _=="function"?_:Bn(_),A):n},A.touchable=function(_){return arguments.length?(r=typeof _=="function"?_:Bn(!!_),A):r},A.on=function(){var _=o.on.apply(o,arguments);return _===o?A:_},A.clickDistance=function(_){return arguments.length?(c=(_=+_)*_,A):Math.sqrt(c)},A}function No(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function rl(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,gt="\\s*([+-]?\\d+)\\s*",cn="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Fe="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",gL=/^#([0-9a-f]{3,8})$/,ML=new RegExp(`^rgb\\(${gt},${gt},${gt}\\)$`),yL=new RegExp(`^rgb\\(${Fe},${Fe},${Fe}\\)$`),xL=new RegExp(`^rgba\\(${gt},${gt},${gt},${cn}\\)$`),UL=new RegExp(`^rgba\\(${Fe},${Fe},${Fe},${cn}\\)$`),bL=new RegExp(`^hsl\\(${cn},${Fe},${Fe}\\)$`),GL=new RegExp(`^hsla\\(${cn},${Fe},${Fe},${cn}\\)$`),Xi={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};No(Ln,Rt,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:$i,formatHex:$i,formatHex8:BL,formatHsl:vL,formatRgb:ji,toString:ji});function $i(){return this.rgb().formatHex()}function BL(){return this.rgb().formatHex8()}function vL(){return sl(this).formatHsl()}function ji(){return this.rgb().formatRgb()}function Rt(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=gL.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?Ki(t):n===3?new Ce(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=ML.exec(e))?new Ce(t[1],t[2],t[3],1):(t=yL.exec(e))?new Ce(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=xL.exec(e))?vn(t[1],t[2],t[3],t[4]):(t=UL.exec(e))?vn(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=bL.exec(e))?qi(t[1],t[2]/100,t[3]/100,1):(t=GL.exec(e))?qi(t[1],t[2]/100,t[3]/100,t[4]):Xi.hasOwnProperty(e)?Ki(Xi[e]):e==="transparent"?new Ce(NaN,NaN,NaN,0):null}function Ki(e){return new Ce(e>>16&255,e>>8&255,e&255,1)}function vn(e,t,n,r){return r<=0&&(e=t=n=NaN),new Ce(e,t,n,r)}function HL(e){return e instanceof Ln||(e=Rt(e)),e?(e=e.rgb(),new Ce(e.r,e.g,e.b,e.opacity)):new Ce}function Xs(e,t,n,r){return arguments.length===1?HL(e):new Ce(e,t,n,r??1)}function Ce(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}No(Ce,Xs,rl(Ln,{brighter(e){return e=e==null?lr:Math.pow(lr,e),new Ce(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Tn:Math.pow(Tn,e),new Ce(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Ce(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:Ji,formatHex:Ji,formatHex8:FL,formatRgb:zi,toString:zi}));function Ji(){return`#${lt(this.r)}${lt(this.g)}${lt(this.b)}`}function FL(){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 sl(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,s=Math.min(t,n,r),o=Math.max(t,n,r),i=NaN,a=o-s,T=(o+s)/2;return a?(t===o?i=(n-r)/a+(n<r)*6:n===o?i=(r-t)/a+2:i=(t-n)/a+4,a/=T<.5?o+s:2-o-s,i*=60):a=T>0&&T<1?0:i,new Me(i,a,T,e.opacity)}function wL(e,t,n,r){return arguments.length===1?sl(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}No(Me,wL,rl(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,s=2*n-r;return new Ce(Os(e>=240?e-240:e+120,s,r),Os(e,s,r),Os(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new Me(Zi(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("}${Zi(this.h)}, ${Hn(this.s)*100}%, ${Hn(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Zi(e){return e=(e||0)%360,e<0?e+360:e}function Hn(e){return Math.max(0,Math.min(1,e||0))}function Os(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 Oo=e=>()=>e;function YL(e,t){return function(n){return e+n*t}}function VL(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 WL(e){return(e=+e)==1?ol:function(t,n){return n-t?VL(t,n,e):Oo(isNaN(t)?n:t)}}function ol(e,t){var n=t-e;return n?YL(e,n):Oo(isNaN(e)?t:e)}const cr=(function e(t){var n=WL(t);function r(s,o){var i=n((s=Xs(s)).r,(o=Xs(o)).r),a=n(s.g,o.g),T=n(s.b,o.b),l=ol(s.opacity,o.opacity);return function(R){return s.r=i(R),s.g=a(R),s.b=T(R),s.opacity=l(R),s+""}}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(),s;return function(o){for(s=0;s<n;++s)r[s]=e[s]*(1-o)+t[s]*o;return r}}function XL(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function $L(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),o=new Array(n),i;for(i=0;i<r;++i)s[i]=nn(e[i],t[i]);for(;i<n;++i)o[i]=t[i];return function(a){for(i=0;i<r;++i)o[i]=s[i](a);return o}}function jL(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 KL(e,t){var n={},r={},s;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(s in t)s in e?n[s]=nn(e[s],t[s]):r[s]=t[s];return function(o){for(s in n)r[s]=n[s](o);return r}}var $s=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,fs=new RegExp($s.source,"g");function JL(e){return function(){return e}}function zL(e){return function(t){return e(t)+""}}function il(e,t){var n=$s.lastIndex=fs.lastIndex=0,r,s,o,i=-1,a=[],T=[];for(e=e+"",t=t+"";(r=$s.exec(e))&&(s=fs.exec(t));)(o=s.index)>n&&(o=t.slice(n,o),a[i]?a[i]+=o:a[++i]=o),(r=r[0])===(s=s[0])?a[i]?a[i]+=s:a[++i]=s:(a[++i]=null,T.push({i,x:ve(r,s)})),n=fs.lastIndex;return n<t.length&&(o=t.slice(n),a[i]?a[i]+=o:a[++i]=o),a.length<2?T[0]?zL(T[0].x):JL(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"?Oo(t):(n==="number"?ve:n==="string"?(r=Rt(t))?(t=r,cr):il:t instanceof Rt?cr:t instanceof Date?jL:XL(t)?kL:Array.isArray(t)?$L:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?KL:ve)(e,t)}var Qi=180/Math.PI,js={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function El(e,t,n,r,s,o){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:s,translateY:o,rotate:Math.atan2(t,e)*Qi,skewX:Math.atan(T)*Qi,scaleX:i,scaleY:a}}var Fn;function qL(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?js:El(t.a,t.b,t.c,t.d,t.e,t.f)}function ZL(e){return e==null||(Fn||(Fn=document.createElementNS("http://www.w3.org/2000/svg","g")),Fn.setAttribute("transform",e),!(e=Fn.transform.baseVal.consolidate()))?js:(e=e.matrix,El(e.a,e.b,e.c,e.d,e.e,e.f))}function al(e,t,n,r){function s(l){return l.length?l.pop()+" ":""}function o(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(s(c)+"rotate(",null,r)-2,x:ve(l,R)})):R&&c.push(s(c)+"rotate("+R+r)}function a(l,R,c,A){l!==R?A.push({i:c.push(s(c)+"skewX(",null,r)-2,x:ve(l,R)}):R&&c.push(s(c)+"skewX("+R+r)}function T(l,R,c,A,S,d){if(l!==c||R!==A){var I=S.push(s(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(s(S)+"scale("+c+","+A+")")}return function(l,R){var c=[],A=[];return l=e(l),R=e(R),o(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 QL=al(qL,"px, ","px)","deg)"),e_=al(ZL,", ",")",")"),t_=1e-12;function eE(e){return((e=Math.exp(e))+1/e)/2}function n_(e){return((e=Math.exp(e))-1/e)/2}function r_(e){return((e=Math.exp(2*e))-1)/(e+1)}const qn=(function e(t,n,r){function s(o,i){var a=o[0],T=o[1],l=o[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<t_)u=Math.log(A/l)/t,O=function(D){return[a+D*S,T+D*d,l*Math.exp(t*D*u)]};else{var C=Math.sqrt(I),N=(A*A-l*l+r*I)/(2*l*n*C),_=(A*A-l*l-r*I)/(2*A*n*C),m=Math.log(Math.sqrt(N*N+1)-N),h=Math.log(Math.sqrt(_*_+1)-_);u=(h-m)/t,O=function(D){var M=D*u,B=eE(m),w=l/(n*C)*(B*r_(t*M+m)-n_(m));return[a+w*S,T+w*d,l*B/eE(t*M+m)]}}return O.duration=u*1e3*t/Math.SQRT2,O}return s.rho=function(o){var i=Math.max(.001,+o),a=i*i,T=a*a;return e(i,a,T)},s})(Math.SQRT2,2,4);var yt=0,Zt=0,Jt=0,ll=1e3,Rr,Qt,Ar=0,At=0,pr=0,Rn=typeof performance=="object"&&performance.now?performance:Date,Tl=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function fo(){return At||(Tl(s_),At=Rn.now()+pr)}function s_(){At=0}function Sr(){this._call=this._time=this._next=null}Sr.prototype=cl.prototype={constructor:Sr,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?fo():+n)+(t==null?0:+t),!this._next&&Qt!==this&&(Qt?Qt._next=this:Rr=this,Qt=this),this._call=e,this._time=n,Ks()},stop:function(){this._call&&(this._call=null,this._time=1/0,Ks())}};function cl(e,t,n){var r=new Sr;return r.restart(e,t,n),r}function o_(){fo(),++yt;for(var e=Rr,t;e;)(t=At-e._time)>=0&&e._call.call(void 0,t),e=e._next;--yt}function tE(){At=(Ar=Rn.now())+pr,yt=Zt=0;try{o_()}finally{yt=0,E_(),At=0}}function i_(){var e=Rn.now(),t=e-Ar;t>ll&&(pr-=t,Ar=e)}function E_(){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,Ks(r)}function Ks(e){if(!yt){Zt&&(Zt=clearTimeout(Zt));var t=e-At;t>24?(e<1/0&&(Zt=setTimeout(tE,e-Rn.now()-pr)),Jt&&(Jt=clearInterval(Jt))):(Jt||(Ar=Rn.now(),Jt=setInterval(i_,ll)),yt=1,Tl(tE))}}function nE(e,t,n){var r=new Sr;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var a_=_r("start","end","cancel","interrupt"),l_=[],Rl=0,rE=1,Js=2,Zn=3,sE=4,zs=5,Qn=6;function mr(e,t,n,r,s,o){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;T_(e,n,{name:t,index:r,group:s,on:a_,tween:l_,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:Rl})}function Co(e,t){var n=Ge(e,t);if(n.state>Rl)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 T_(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=cl(o,0,n.time);function o(l){n.state=rE,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!==rE)return T();for(R in r)if(S=r[R],S.name===n.name){if(S.state===Zn)return nE(i);S.state===sE?(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(nE(function(){n.state===Zn&&(n.state=sE,n.timer.restart(a,n.delay,n.time),a(l))}),n.state=Js,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Js){for(n.state=Zn,s=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))&&(s[++c]=S);s.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=zs,1),c=-1,A=s.length;++c<A;)s[c].call(e,R);n.state===zs&&(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,s,o=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){o=!1;continue}s=r.state>Js&&r.state<zs,r.state=Qn,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}o&&delete e.__transition}}function c_(e){return this.each(function(){er(this,e)})}function R_(e,t){var n,r;return function(){var s=Ye(this,e),o=s.tween;if(o!==n){r=n=o;for(var i=0,a=r.length;i<a;++i)if(r[i].name===t){r=r.slice(),r.splice(i,1);break}}s.tween=r}}function A_(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var o=Ye(this,e),i=o.tween;if(i!==r){s=(r=i).slice();for(var a={name:t,value:n},T=0,l=s.length;T<l;++T)if(s[T].name===t){s[T]=a;break}T===l&&s.push(a)}o.tween=s}}function S_(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Ge(this.node(),n).tween,s=0,o=r.length,i;s<o;++s)if((i=r[s]).name===e)return i.value;return null}return this.each((t==null?R_:A_)(n,e,t))}function Lo(e,t,n){var r=e._id;return e.each(function(){var s=Ye(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Ge(s,r).value[t]}}function Al(e,t){var n;return(typeof t=="number"?ve:t instanceof Rt?cr:(n=Rt(t))?(t=n,cr):il)(e,t)}function d_(e){return function(){this.removeAttribute(e)}}function I_(e){return function(){this.removeAttributeNS(e.space,e.local)}}function u_(e,t,n){var r,s=n+"",o;return function(){var i=this.getAttribute(e);return i===s?null:i===r?o:o=t(r=i,n)}}function N_(e,t,n){var r,s=n+"",o;return function(){var i=this.getAttributeNS(e.space,e.local);return i===s?null:i===r?o:o=t(r=i,n)}}function O_(e,t,n){var r,s,o;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===s?o:(s=T,o=t(r=i,a)))}}function f_(e,t,n){var r,s,o;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===s?o:(s=T,o=t(r=i,a)))}}function C_(e,t){var n=hr(e),r=n==="transform"?e_:Al;return this.attrTween(e,typeof t=="function"?(n.local?f_:O_)(n,r,Lo(this,"attr."+e,t)):t==null?(n.local?I_:d_)(n):(n.local?N_:u_)(n,r,t))}function L_(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function __(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function h_(e,t){var n,r;function s(){var o=t.apply(this,arguments);return o!==r&&(n=(r=o)&&__(e,o)),n}return s._value=t,s}function p_(e,t){var n,r;function s(){var o=t.apply(this,arguments);return o!==r&&(n=(r=o)&&L_(e,o)),n}return s._value=t,s}function m_(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=hr(e);return this.tween(n,(r.local?h_:p_)(r,t))}function D_(e,t){return function(){Co(this,e).delay=+t.apply(this,arguments)}}function P_(e,t){return t=+t,function(){Co(this,e).delay=t}}function g_(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?D_:P_)(t,e)):Ge(this.node(),t).delay}function M_(e,t){return function(){Ye(this,e).duration=+t.apply(this,arguments)}}function y_(e,t){return t=+t,function(){Ye(this,e).duration=t}}function x_(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?M_:y_)(t,e)):Ge(this.node(),t).duration}function U_(e,t){if(typeof t!="function")throw new Error;return function(){Ye(this,e).ease=t}}function b_(e){var t=this._id;return arguments.length?this.each(U_(t,e)):Ge(this.node(),t).ease}function G_(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Ye(this,e).ease=n}}function B_(e){if(typeof e!="function")throw new Error;return this.each(G_(this._id,e))}function v_(e){typeof e!="function"&&(e=ka(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var o=t[s],i=o.length,a=r[s]=[],T,l=0;l<i;++l)(T=o[l])&&e.call(T,T.__data__,l,o)&&a.push(T);return new Je(r,this._parents,this._name,this._id)}function H_(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,o=Math.min(r,s),i=new Array(r),a=0;a<o;++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 F_(e){return(e+"").trim().split(/^|\s+/).every(function(t){var n=t.indexOf(".");return n>=0&&(t=t.slice(0,n)),!t||t==="start"})}function w_(e,t,n){var r,s,o=F_(t)?Co:Ye;return function(){var i=o(this,e),a=i.on;a!==r&&(s=(r=a).copy()).on(t,n),i.on=s}}function Y_(e,t){var n=this._id;return arguments.length<2?Ge(this.node(),n).on.on(e):this.each(w_(n,e,t))}function V_(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function W_(){return this.on("end.remove",V_(this._id))}function k_(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Io(e));for(var r=this._groups,s=r.length,o=new Array(s),i=0;i<s;++i)for(var a=r[i],T=a.length,l=o[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(o,this._parents,t,n)}function X_(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Wa(e));for(var r=this._groups,s=r.length,o=[],i=[],a=0;a<s;++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);o.push(A),i.push(R)}return new Je(o,i,t,n)}var $_=Cn.prototype.constructor;function j_(){return new $_(this._groups,this._parents)}function K_(e,t){var n,r,s;return function(){var o=Mt(this,e),i=(this.style.removeProperty(e),Mt(this,e));return o===i?null:o===n&&i===r?s:s=t(n=o,r=i)}}function Sl(e){return function(){this.style.removeProperty(e)}}function J_(e,t,n){var r,s=n+"",o;return function(){var i=Mt(this,e);return i===s?null:i===r?o:o=t(r=i,n)}}function z_(e,t,n){var r,s,o;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===s?o:(s=T,o=t(r=i,a))}}function q_(e,t){var n,r,s,o="style."+t,i="end."+o,a;return function(){var T=Ye(this,e),l=T.on,R=T.value[o]==null?a||(a=Sl(t)):void 0;(l!==n||s!==R)&&(r=(n=l).copy()).on(i,s=R),T.on=r}}function Z_(e,t,n){var r=(e+="")=="transform"?QL:Al;return t==null?this.styleTween(e,K_(e,r)).on("end.style."+e,Sl(e)):typeof t=="function"?this.styleTween(e,z_(e,r,Lo(this,"style."+e,t))).each(q_(this._id,e)):this.styleTween(e,J_(e,r,t),n).on("end.style."+e,null)}function Q_(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function eh(e,t,n){var r,s;function o(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&Q_(e,i,n)),r}return o._value=t,o}function th(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,eh(e,t,n??""))}function nh(e){return function(){this.textContent=e}}function rh(e){return function(){var t=e(this);this.textContent=t??""}}function sh(e){return this.tween("text",typeof e=="function"?rh(Lo(this,"text",e)):nh(e==null?"":e+""))}function oh(e){return function(t){this.textContent=e.call(this,t)}}function ih(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&oh(s)),t}return r._value=e,r}function Eh(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,ih(e))}function ah(){for(var e=this._name,t=this._id,n=dl(),r=this._groups,s=r.length,o=0;o<s;++o)for(var i=r[o],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 lh(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(o,i){var a={value:i},T={value:function(){--s===0&&o()}};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}),s===0&&o()})}var Th=0;function Je(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function dl(){return++Th}var $e=Cn.prototype;Je.prototype={constructor:Je,select:k_,selectAll:X_,selectChild:$e.selectChild,selectChildren:$e.selectChildren,filter:v_,merge:H_,selection:j_,transition:ah,call:$e.call,nodes:$e.nodes,node:$e.node,size:$e.size,empty:$e.empty,each:$e.each,on:Y_,attr:C_,attrTween:m_,style:Z_,styleTween:th,text:sh,textTween:Eh,remove:W_,tween:S_,delay:g_,duration:x_,ease:b_,easeVarying:B_,end:lh,[Symbol.iterator]:$e[Symbol.iterator]};function ch(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var Rh={time:null,delay:0,duration:250,ease:ch};function Ah(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 Sh(e){var t,n;e instanceof Je?(t=e._id,e=e._name):(t=dl(),(n=Rh).time=fo(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,o=0;o<s;++o)for(var i=r[o],a=i.length,T,l=0;l<a;++l)(T=i[l])&&mr(T,e,t,l,i,n||Ah(T,t));return new Je(r,this._parents,e,t)}Cn.prototype.interrupt=c_;Cn.prototype.transition=Sh;const wn=e=>()=>e;function dh(e,{sourceEvent:t,target:n,transform:r,dispatch:s}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:s}})}function 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);Il.prototype=Ke.prototype;function Il(e){for(;!e.__zoom;)if(!(e=e.parentNode))return Dr;return e.__zoom}function Cs(e){e.stopImmediatePropagation()}function zt(e){e.preventDefault(),e.stopImmediatePropagation()}function Ih(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function uh(){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 oE(){return this.__zoom||Dr}function Nh(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function Oh(){return navigator.maxTouchPoints||"ontouchstart"in this}function fh(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],o=e.invertY(t[0][1])-n[0][1],i=e.invertY(t[1][1])-n[1][1];return e.translate(s>r?(r+s)/2:Math.min(0,r)||Math.max(0,s),i>o?(o+i)/2:Math.min(0,o)||Math.max(0,i))}function ul(){var e=Ih,t=uh,n=fh,r=Nh,s=Oh,o=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],a=250,T=qn,l=_r("start","zoom","end"),R,c,A,S=500,d=150,I=0,O=10;function u(L){L.property("__zoom",oE).on("wheel.zoom",M,{passive:!1}).on("mousedown.zoom",B).on("dblclick.zoom",w).filter(s).on("touchstart.zoom",P).on("touchmove.zoom",p).on("touchend.zoom touchcancel.zoom",U).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}u.transform=function(L,x,g,v){var b=L.selection?L.selection():L;b.property("__zoom",oE),L!==b?m(L,x,g,v):b.interrupt().each(function(){h(this,arguments).event(v).start().zoom(null,typeof x=="function"?x.apply(this,arguments):x).end()})},u.scaleBy=function(L,x,g,v){u.scaleTo(L,function(){var b=this.__zoom.k,y=typeof x=="function"?x.apply(this,arguments):x;return b*y},g,v)},u.scaleTo=function(L,x,g,v){u.transform(L,function(){var b=t.apply(this,arguments),y=this.__zoom,Y=g==null?_(b):typeof g=="function"?g.apply(this,arguments):g,W=y.invert(Y),V=typeof x=="function"?x.apply(this,arguments):x;return n(N(C(y,V),Y,W),b,i)},g,v)},u.translateBy=function(L,x,g,v){u.transform(L,function(){return n(this.__zoom.translate(typeof x=="function"?x.apply(this,arguments):x,typeof g=="function"?g.apply(this,arguments):g),t.apply(this,arguments),i)},null,v)},u.translateTo=function(L,x,g,v,b){u.transform(L,function(){var y=t.apply(this,arguments),Y=this.__zoom,W=v==null?_(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 g=="function"?-g.apply(this,arguments):-g),y,i)},v,b)};function C(L,x){return x=Math.max(o[0],Math.min(o[1],x)),x===L.k?L:new Ke(x,L.x,L.y)}function N(L,x,g){var v=x[0]-g[0]*L.k,b=x[1]-g[1]*L.k;return v===L.x&&b===L.y?L:new Ke(L.k,v,b)}function _(L){return[(+L[0][0]+ +L[1][0])/2,(+L[0][1]+ +L[1][1])/2]}function m(L,x,g,v){L.on("start.zoom",function(){h(this,arguments).event(v).start()}).on("interrupt.zoom end.zoom",function(){h(this,arguments).event(v).end()}).tween("zoom",function(){var b=this,y=arguments,Y=h(b,y).event(v),W=t.apply(b,y),V=g==null?_(W):typeof g=="function"?g.apply(b,y):g,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($){if($===1)$=K;else{var j=Q($),ee=k/j[2];$=new Ke(ee,V[0]-j[0]*ee,V[1]-j[1]*ee)}Y.zoom(null,$)}})}function h(L,x,g){return!g&&L.__zooming||new D(L,x)}function D(L,x){this.that=L,this.args=x,this.active=0,this.sourceEvent=null,this.extent=t.apply(L,x),this.taps=0}D.prototype={event:function(L){return L&&(this.sourceEvent=L),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(L,x){return this.mouse&&L!=="mouse"&&(this.mouse[1]=x.invert(this.mouse[0])),this.touch0&&L!=="touch"&&(this.touch0[1]=x.invert(this.touch0[0])),this.touch1&&L!=="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(L){var x=_e(this.that).datum();l.call(L,this.that,new dh(L,{sourceEvent:this.sourceEvent,target:u,transform:this.that.__zoom,dispatch:l}),x)}};function M(L,...x){if(!e.apply(this,arguments))return;var g=h(this,x).event(L),v=this.__zoom,b=Math.max(o[0],Math.min(o[1],v.k*Math.pow(2,r.apply(this,arguments)))),y=ge(L);if(g.wheel)(g.mouse[0][0]!==y[0]||g.mouse[0][1]!==y[1])&&(g.mouse[1]=v.invert(g.mouse[0]=y)),clearTimeout(g.wheel);else{if(v.k===b)return;g.mouse=[y,v.invert(y)],er(this),g.start()}zt(L),g.wheel=setTimeout(Y,d),g.zoom("mouse",n(N(C(v,b),g.mouse[0],g.mouse[1]),g.extent,i));function Y(){g.wheel=null,g.end()}}function B(L,...x){if(A||!e.apply(this,arguments))return;var g=L.currentTarget,v=h(this,x,!0).event(L),b=_e(L.view).on("mousemove.zoom",V,!0).on("mouseup.zoom",k,!0),y=ge(L,g),Y=L.clientX,W=L.clientY;el(L.view),Cs(L),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]=ge(X,g),v.mouse[1]),v.extent,i))}function k(X){b.on("mousemove.zoom mouseup.zoom",null),tl(X.view,v.moved),zt(X),v.event(X).end()}}function w(L,...x){if(e.apply(this,arguments)){var g=this.__zoom,v=ge(L.changedTouches?L.changedTouches[0]:L,this),b=g.invert(v),y=g.k*(L.shiftKey?.5:2),Y=n(N(C(g,y),v,b),t.apply(this,x),i);zt(L),a>0?_e(this).transition().duration(a).call(m,Y,v,L):_e(this).call(u.transform,Y,v,L)}}function P(L,...x){if(e.apply(this,arguments)){var g=L.touches,v=g.length,b=h(this,x,L.changedTouches.length===v).event(L),y,Y,W,V;for(Cs(L),Y=0;Y<v;++Y)W=g[Y],V=ge(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 p(L,...x){if(this.__zooming){var g=h(this,x).event(L),v=L.changedTouches,b=v.length,y,Y,W,V;for(zt(L),y=0;y<b;++y)Y=v[y],W=ge(Y,this),g.touch0&&g.touch0[2]===Y.identifier?g.touch0[0]=W:g.touch1&&g.touch1[2]===Y.identifier&&(g.touch1[0]=W);if(Y=g.that.__zoom,g.touch1){var k=g.touch0[0],X=g.touch0[1],K=g.touch1[0],Q=g.touch1[1],$=($=K[0]-k[0])*$+($=K[1]-k[1])*$,j=(j=Q[0]-X[0])*j+(j=Q[1]-X[1])*j;Y=C(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(g.touch0)W=g.touch0[0],V=g.touch0[1];else return;g.zoom("touch",n(N(Y,W,V),g.extent,i))}}function U(L,...x){if(this.__zooming){var g=h(this,x).event(L),v=L.changedTouches,b=v.length,y,Y;for(Cs(L),A&&clearTimeout(A),A=setTimeout(function(){A=null},S),y=0;y<b;++y)Y=v[y],g.touch0&&g.touch0[2]===Y.identifier?delete g.touch0:g.touch1&&g.touch1[2]===Y.identifier&&delete g.touch1;if(g.touch1&&!g.touch0&&(g.touch0=g.touch1,delete g.touch1),g.touch0)g.touch0[1]=this.__zoom.invert(g.touch0[0]);else if(g.end(),g.taps===2&&(Y=ge(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(L){return arguments.length?(r=typeof L=="function"?L:wn(+L),u):r},u.filter=function(L){return arguments.length?(e=typeof L=="function"?L:wn(!!L),u):e},u.touchable=function(L){return arguments.length?(s=typeof L=="function"?L:wn(!!L),u):s},u.extent=function(L){return arguments.length?(t=typeof L=="function"?L:wn([[+L[0][0],+L[0][1]],[+L[1][0],+L[1][1]]]),u):t},u.scaleExtent=function(L){return arguments.length?(o[0]=+L[0],o[1]=+L[1],u):[o[0],o[1]]},u.translateExtent=function(L){return arguments.length?(i[0][0]=+L[0][0],i[1][0]=+L[1][0],i[0][1]=+L[0][1],i[1][1]=+L[1][1],u):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},u.constrain=function(L){return arguments.length?(n=L,u):n},u.duration=function(L){return arguments.length?(a=+L,u):a},u.interpolate=function(L){return arguments.length?(T=L,u):T},u.on=function(){var L=l.on.apply(l,arguments);return L===l?u:L},u.clickDistance=function(L){return arguments.length?(I=(L=+L)*L,u):Math.sqrt(I)},u.tapDistance=function(L){return arguments.length?(O=+L,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]],Nl=["Enter"," ","Escape"],Ol={"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 fl={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 iE={[Z.Left]:Z.Right,[Z.Right]:Z.Left,[Z.Top]:Z.Bottom,[Z.Bottom]:Z.Top};function Cl(e){return e===null?null:e?"valid":"invalid"}const Ll=e=>"id"in e&&"source"in e&&"target"in e,Ch=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),_o=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),_n=(e,t=[0,0])=>{const{width:n,height:r}=ze(e),s=e.origin??t,o=n*s[0],i=r*s[1];return{x:e.position.x-o,y:e.position.y-i}},Lh=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,s)=>{const o=typeof s=="string";let i=!t.nodeLookup&&!o?s:void 0;t.nodeLookup&&(i=o?t.nodeLookup.get(s):_o(s)?s:t.nodeLookup.get(s.id));const a=i?dr(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return Pr(r,a)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return gr(n)},hn=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(s=>{(t.filter===void 0||t.filter(s))&&(n=Pr(n,dr(s)),r=!0)}),r?gr(n):{x:0,y:0,width:0,height:0}},ho=(e,t,[n,r,s]=[0,0,1],o=!1,i=!1)=>{const a={...mn(t,[n,r,s]),width:t.width/s,height:t.height/s},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=o&&I>0;(!l.internals.handleBounds||u||I>=O||l.dragging)&&T.push(l)}return T},_h=(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 hh(e,t){const n=new Map,r=t!=null&&t.nodes?new Set(t.nodes.map(s=>s.id)):null;return e.forEach(s=>{s.measured.width&&s.measured.height&&((t==null?void 0:t.includeHiddenNodes)||!s.hidden)&&(!r||r.has(s.id))&&n.set(s.id,s)}),n}async function ph({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:o},i){if(e.size===0)return Promise.resolve(!0);const a=hh(e,i),T=hn(a),l=po(T,t,n,(i==null?void 0:i.minZoom)??s,(i==null?void 0:i.maxZoom)??o,(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 _l({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:o}){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||s;if(i.extent==="parent"&&!i.expandParent)if(!a)o==null||o("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)&&(o==null||o("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 mh({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const o=new Set(e.map(A=>A.id)),i=[];for(const A of n){if(A.deletable===!1)continue;const S=o.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=_h(i,T);for(const A of T)a.has(A.id)&&!R.find(d=>d.id===A.id)&&R.push(A);if(!s)return{edges:R,nodes:i};const c=await s({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 hl(e,t,n){const{width:r,height:s}=ze(n),{x:o,y:i}=n.internals.positionAbsolute;return St(e,[[o,i],[o+r,i+s]],t)}const EE=(e,t,n)=>e<t?Ut(Math.abs(e-t),1,t)/t:e>n?-Ut(Math.abs(e-n),1,t)/t:0,pl=(e,t,n=15,r=40)=>{const s=EE(e.x,r,t.width-r)*n,o=EE(e.y,r,t.height-r)*n;return[s,o]},Pr=(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)}),qs=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),gr=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),bt=(e,t=[0,0])=>{var s,o;const{x:n,y:r}=_o(e)?e.internals.positionAbsolute:_n(e,t);return{x:n,y:r,width:((s=e.measured)==null?void 0:s.width)??e.width??e.initialWidth??0,height:((o=e.measured)==null?void 0:o.height)??e.height??e.initialHeight??0}},dr=(e,t=[0,0])=>{var s,o;const{x:n,y:r}=_o(e)?e.internals.positionAbsolute:_n(e,t);return{x:n,y:r,x2:n+(((s=e.measured)==null?void 0:s.width)??e.width??e.initialWidth??0),y2:r+(((o=e.measured)==null?void 0:o.height)??e.height??e.initialHeight??0)}},ml=(e,t)=>gr(Pr(qs(e),qs(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)},aE=e=>ye(e.width)&&ye(e.height)&&ye(e.x)&&ye(e.y),ye=e=>!isNaN(e)&&isFinite(e),Dh=(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,s],o=!1,i=[1,1])=>{const a={x:(e-n)/s,y:(t-r)/s};return o?pn(a,i):a},Ir=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+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 Ph(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=Lt(e,n),s=Lt(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=Lt(e.top??e.y??0,n),s=Lt(e.bottom??e.y??0,n),o=Lt(e.left??e.x??0,t),i=Lt(e.right??e.x??0,t);return{top:r,right:i,bottom:s,left:o,x:o+i,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function gh(e,t,n,r,s,o){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=s-T,c=o-l;return{left:Math.floor(i),top:Math.floor(a),right:Math.floor(R),bottom:Math.floor(c)}}const po=(e,t,n,r,s,o)=>{const i=Ph(o,t,n),a=(t-i.x)/e.width,T=(n-i.y)/e.height,l=Math.min(a,T),R=Ut(l,r,s),c=e.x+e.width/2,A=e.y+e.height/2,S=t/2-c*R,d=n/2-A*R,I=gh(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 Dl(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 Pl(e,t={width:0,height:0},n,r,s){const o={...e},i=r.get(n);if(i){const a=i.origin||s;o.x+=i.internals.positionAbsolute.x-(t.width??0)*a[0],o.y+=i.internals.positionAbsolute.y-(t.height??0)*a[1]}return o}function lE(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function Mh(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function yh(e){return{...Ol,...e||{}}}function rn(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:o,y:i}=xe(e),a=mn({x:o-((s==null?void 0:s.left)??0),y:i-((s==null?void 0:s.top)??0)},r),{x:T,y:l}=n?pn(a,t):a;return{xSnapped:T,ySnapped:l,...a}}const mo=e=>({width:e.offsetWidth,height:e.offsetHeight}),gl=e=>{var t;return((t=e==null?void 0:e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},xh=["INPUT","SELECT","TEXTAREA"];function Ml(e){var r,s;const t=((s=(r=e.composedPath)==null?void 0:r.call(e))==null?void 0:s[0])||e.target;return(t==null?void 0:t.nodeType)!==1?!1:xh.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const yl=e=>"clientX"in e,xe=(e,t)=>{var o,i;const n=yl(e),r=n?e.clientX:(o=e.touches)==null?void 0:o[0].clientX,s=n?e.clientY:(i=e.touches)==null?void 0:i[0].clientY;return{x:r-((t==null?void 0:t.left)??0),y:s-((t==null?void 0:t.top)??0)}},TE=(e,t,n,r,s)=>{const o=t.querySelectorAll(`.${e}`);return!o||!o.length?null:Array.from(o).map(i=>{const a=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:s,position:i.getAttribute("data-handlepos"),x:(a.left-n.left)/r,y:(a.top-n.top)/r,...mo(i)}})};function xl({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:o,targetControlX:i,targetControlY:a}){const T=e*.125+s*.375+i*.375+n*.125,l=t*.125+o*.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 cE({pos:e,x1:t,y1:n,x2:r,y2:s,c:o}){switch(e){case Z.Left:return[t-Yn(t-r,o),n];case Z.Right:return[t+Yn(r-t,o),n];case Z.Top:return[t,n-Yn(n-s,o)];case Z.Bottom:return[t,n+Yn(s-n,o)]}}function Ul({sourceX:e,sourceY:t,sourcePosition:n=Z.Bottom,targetX:r,targetY:s,targetPosition:o=Z.Top,curvature:i=.25}){const[a,T]=cE({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[l,R]=cE({pos:o,x1:r,y1:s,x2:e,y2:t,c:i}),[c,A,S,d]=xl({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:a,sourceControlY:T,targetControlX:l,targetControlY:R});return[`M${e},${t} C${a},${T} ${l},${R} ${r},${s}`,c,A,S,d]}function bl({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,o=n<e?n+s:n-s,i=Math.abs(r-t)/2,a=r<t?r+i:r-i;return[o,a,s,i]}function Uh({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:o="basic"}){if(o==="manual")return r;const i=s&&n?r+1e3:r,a=Math.max(e.parentId||s&&e.selected?e.internals.z:0,t.parentId||s&&t.selected?t.internals.z:0);return i+a}function bh({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const o=Pr(dr(e),dr(t));o.x===o.x2&&(o.x2+=1),o.y===o.y2&&(o.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return In(i,gr(o))>0}const Gh=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,Bh=(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)),vh=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||Gh;let s;return Ll(e)?s={...e}:s={...e,id:r(e)},Bh(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function Gl({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,o,i,a]=bl({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,o,i,a]}const RE={[Z.Left]:{x:-1,y:0},[Z.Right]:{x:1,y:0},[Z.Top]:{x:0,y:-1},[Z.Bottom]:{x:0,y:1}},Hh=({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},AE=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function Fh({source:e,sourcePosition:t=Z.Bottom,target:n,targetPosition:r=Z.Top,center:s,offset:o,stepPosition:i}){const a=RE[t],T=RE[r],l={x:e.x+a.x*o,y:e.y+a.y*o},R={x:n.x+T.x*o,y:n.y+T.y*o},c=Hh({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},C={x:0,y:0},[,,N,_]=bl({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(a[A]*T[A]===-1){A==="x"?(I=s.x??l.x+(R.x-l.x)*i,O=s.y??(l.y+R.y)/2):(I=s.x??(l.x+R.x)/2,O=s.y??l.y+(R.y-l.y)*i);const h=[{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"?h:D:d=A==="x"?D:h}else{const h=[{x:l.x,y:R.y}],D=[{x:R.x,y:l.y}];if(A==="x"?d=a.x===S?D:h:d=a.y===S?h:D,t===r){const p=Math.abs(e[A]-n[A]);if(p<=o){const U=Math.min(o-1,o-p);a[A]===S?u[A]=(l[A]>e[A]?-1:1)*U:C[A]=(R[A]>n[A]?-1:1)*U}}if(t!==r){const p=A==="x"?"y":"x",U=a[A]===T[p],L=l[p]>R[p],x=l[p]<R[p];(a[A]===1&&(!U&&L||U&&x)||a[A]!==1&&(!U&&x||U&&L))&&(d=A==="x"?h:D)}const M={x:l.x+u.x,y:l.y+u.y},B={x:R.x+C.x,y:R.y+C.y},w=Math.max(Math.abs(M.x-d[0].x),Math.abs(B.x-d[0].x)),P=Math.max(Math.abs(M.y-d[0].y),Math.abs(B.y-d[0].y));w>=P?(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+C.x,y:R.y+C.y},n],I,O,N,_]}function wh(e,t,n,r){const s=Math.min(AE(e,t)/2,AE(t,n)/2,r),{x:o,y:i}=t;if(e.x===o&&o===n.x||e.y===i&&i===n.y)return`L${o} ${i}`;if(e.y===i){const l=e.x<n.x?-1:1,R=e.y<n.y?1:-1;return`L ${o+s*l},${i}Q ${o},${i} ${o},${i+s*R}`}const a=e.x<n.x?1:-1,T=e.y<n.y?-1:1;return`L ${o},${i+s*T}Q ${o},${i} ${o+s*a},${i}`}function Zs({sourceX:e,sourceY:t,sourcePosition:n=Z.Bottom,targetX:r,targetY:s,targetPosition:o=Z.Top,borderRadius:i=5,centerX:a,centerY:T,offset:l=20,stepPosition:R=.5}){const[c,A,S,d,I]=Fh({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:o,center:{x:a,y:T},offset:l,stepPosition:R});return[c.reduce((u,C,N)=>{let _="";return N>0&&N<c.length-1?_=wh(c[N-1],C,c[N+1],i):_=`${N===0?"M":"L"}${C.x} ${C.y}`,u+=_,u},""),A,S,d,I]}function SE(e){var t;return e&&!!(e.internals.handleBounds||(t=e.handles)!=null&&t.length)&&!!(e.measured.width||e.width||e.initialWidth)}function Yh(e){var c;const{sourceNode:t,targetNode:n}=e;if(!SE(t)||!SE(n))return null;const r=t.internals.handleBounds||dE(t.handles),s=n.internals.handleBounds||dE(n.handles),o=IE((r==null?void 0:r.source)??[],e.sourceHandle),i=IE(e.connectionMode===xt.Strict?(s==null?void 0:s.target)??[]:((s==null?void 0:s.target)??[]).concat((s==null?void 0:s.source)??[]),e.targetHandle);if(!o||!i)return(c=e.onError)==null||c.call(e,"008",we.error008(o?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const a=(o==null?void 0:o.position)||Z.Bottom,T=(i==null?void 0:i.position)||Z.Top,l=dt(t,o,a),R=dt(n,i,T);return{sourceX:l.x,sourceY:l.y,targetX:R.x,targetY:R.y,sourcePosition:a,targetPosition:T}}function dE(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 s=((t==null?void 0:t.x)??0)+e.internals.positionAbsolute.x,o=((t==null?void 0:t.y)??0)+e.internals.positionAbsolute.y,{width:i,height:a}=t??ze(e);if(r)return{x:s+i/2,y:o+a/2};switch((t==null?void 0:t.position)??n){case Z.Top:return{x:s+i/2,y:o};case Z.Right:return{x:s+i,y:o+a/2};case Z.Bottom:return{x:s+i/2,y:o+a};case Z.Left:return{x:s,y:o+a/2}}}function IE(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Qs(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function Vh(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const o=new Set;return e.reduce((i,a)=>([a.markerStart||r,a.markerEnd||s].forEach(T=>{if(T&&typeof T=="object"){const l=Qs(T,t);o.has(l)||(i.push({id:l,color:T.color||n,...T}),o.add(l))}}),i),[]).sort((i,a)=>i.id.localeCompare(a.id))}const Bl=1e3,Wh=10,Do={nodeOrigin:[0,0],nodeExtent:An,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},kh={...Do,checkEquality:!0};function Po(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function Xh(e,t,n){const r=Po(Do,n);for(const s of e.values())if(s.parentId)Mo(s,e,t,r);else{const o=_n(s,r.nodeOrigin),i=Gt(s.extent)?s.extent:r.nodeExtent,a=St(o,i,ze(s));s.internals.positionAbsolute=a}}function $h(e,t){if(!e.handles)return e.measured?t==null?void 0:t.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const o={id:s.id,width:s.width??1,height:s.height??1,nodeId:e.id,x:s.x,y:s.y,position:s.position,type:s.type};s.type==="source"?n.push(o):s.type==="target"&&r.push(o)}return{source:n,target:r}}function go(e){return e==="manual"}function eo(e,t,n,r={}){var l,R;const s=Po(kh,r),o={i:0},i=new Map(t),a=s!=null&&s.elevateNodesOnSelect&&!go(s.zIndexMode)?Bl:0;let T=e.length>0;t.clear(),n.clear();for(const c of e){let A=i.get(c.id);if(s.checkEquality&&c===(A==null?void 0:A.internals.userNode))t.set(c.id,A);else{const S=_n(c,s.nodeOrigin),d=Gt(c.extent)?c.extent:s.nodeExtent,I=St(S,d,ze(c));A={...s.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:$h(c,A),z:vl(c,a,s.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&&Mo(A,t,n,r,o)}return T}function jh(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 Mo(e,t,n,r,s){const{elevateNodesOnSelect:o,nodeOrigin:i,nodeExtent:a,zIndexMode:T}=Po(Do,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}jh(e,n),s&&!R.parentId&&R.internals.rootParentIndex===void 0&&T==="auto"&&(R.internals.rootParentIndex=++s.i,R.internals.z=R.internals.z+s.i*Wh),s&&R.internals.rootParentIndex!==void 0&&(s.i=R.internals.rootParentIndex);const c=o&&!go(T)?Bl:0,{x:A,y:S,z:d}=Kh(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 vl(e,t,n){const r=ye(e.zIndex)?e.zIndex:0;return go(n)?r:r+(e.selected?t:0)}function Kh(e,t,n,r,s,o){const{x:i,y:a}=t.internals.positionAbsolute,T=ze(e),l=_n(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=hl(c,T,t));const A=vl(e,s,o),S=t.internals.z??0;return{x:c.x,y:c.y,z:S>=A?S+1:A}}function yo(e,t,n,r=[0,0]){var i;const s=[],o=new Map;for(const a of e){const T=t.get(a.parentId);if(!T)continue;const l=((i=o.get(a.parentId))==null?void 0:i.expandedRect)??bt(T),R=ml(l,a.rect);o.set(a.parentId,{expandedRect:R,parent:T})}return o.size>0&&o.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],C=(O-c.height)*A[1];(S>0||d>0||u||C)&&(s.push({id:l,type:"position",position:{x:T.position.x-S+u,y:T.position.y-d+C}}),(N=n.get(l))==null||N.forEach(_=>{e.some(m=>m.id===_.id)||s.push({id:_.id,type:"position",position:{x:_.position.x+S,y:_.position.y+d}})})),(c.width<a.width||c.height<a.height||S||d)&&s.push({id:l,type:"dimensions",setAttributes:!0,dimensions:{width:I+(S?A[0]*S-u:0),height:O+(d?A[1]*d-C:0)}})}),s}function Jh(e,t,n,r,s,o,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=mo(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 C=S.nodeElement.getBoundingClientRect(),N=Gt(d.extent)?d.extent:o;let{positionAbsolute:_}=d.internals;d.parentId&&d.extent==="parent"?_=hl(_,I,t.get(d.parentId)):N&&(_=St(_,N,I));const m={...d,measured:I,internals:{...d.internals,positionAbsolute:_,handleBounds:{source:TE("source",S.nodeElement,C,c,d.id),target:TE("target",S.nodeElement,C,c,d.id)}}};t.set(d.id,m),d.parentId&&Mo(m,t,n,{nodeOrigin:s,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,s)}))}}if(A.length>0){const S=yo(A,t,n,s);l.push(...S)}return{changes:l,updatedInternals:T}}async function zh({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:o}){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],[s,o]],r),a=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(a)}function uE(e,t,n,r,s,o){let i=s;const a=r.get(i)||new Map;r.set(i,a.set(n,t)),i=`${s}-${e}`;const T=r.get(i)||new Map;if(r.set(i,T.set(n,t)),o){i=`${s}-${e}-${o}`;const l=r.get(i)||new Map;r.set(i,l.set(n,t))}}function Hl(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:o,sourceHandle:i=null,targetHandle:a=null}=r,T={edgeId:r.id,source:s,target:o,sourceHandle:i,targetHandle:a},l=`${s}-${i}--${o}-${a}`,R=`${o}-${a}--${s}-${i}`;uE("source",T,R,e,s,i),uE("target",T,l,e,o,a),t.set(r.id,r)}}function Fl(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:Fl(n,t):!1}function NE(e,t,n){var s;let r=e;do{if((s=r==null?void 0:r.matches)!=null&&s.call(r,t))return!0;if(r===n)return!1;r=r==null?void 0:r.parentElement}while(r);return!1}function qh(e,t,n,r){const s=new Map;for(const[o,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!Fl(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const a=e.get(o);a&&s.set(o,{id:o,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 s}function Ls({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){var i,a,T;const s=[];for(const[l,R]of t){const c=(i=n.get(l))==null?void 0:i.internals.userNode;c&&s.push({...c,position:R.position,dragging:r})}if(!e)return[s[0],s];const o=(a=n.get(e))==null?void 0:a.internals.userNode;return[o?{...o,position:((T=t.get(e))==null?void 0:T.position)||o.position,dragging:r}:s[0],s]}function Zh({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const o={x:n-s.distance.x,y:r-s.distance.y},i=pn(o,t);return{x:i.x-o.x,y:i.y-o.y}}function Qh({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let o={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:C,handleSelector:N,domNode:_,isSelectable:m,nodeId:h,nodeClickDistance:D=0}){A=_e(_);function M({x:p,y:U}){const{nodeLookup:L,nodeExtent:x,snapGrid:g,snapToGrid:v,nodeOrigin:b,onNodeDrag:y,onSelectionDrag:Y,onError:W,updateNodePositions:V}=t();o={x:p,y:U};let k=!1;const X=a.size>1,K=X&&x?qs(hn(a)):null,Q=X&&v?Zh({dragItems:a,snapGrid:g,x:p,y:U}):null;for(const[$,j]of a){if(!L.has($))continue;let ee={x:p-j.distance.x,y:U-j.distance.y};v&&(ee=Q?{x:Math.round(ee.x+Q.x),y:Math.round(ee.y+Q.y)}:pn(ee,g));let re=null;if(X&&x&&!j.extent&&K){const{positionAbsolute:te}=j.internals,ie=te.x-K.x+x[0][0],le=te.x+j.measured.width-K.x2+x[1][0],oe=te.y-K.y+x[0][1],Ne=te.y+j.measured.height-K.y2+x[1][1];re=[[ie,oe],[le,Ne]]}const{position:q,positionAbsolute:z}=_l({nodeId:$,nextPosition:ee,nodeLookup:L,nodeExtent:re||x,nodeOrigin:b,onError:W});k=k||j.position.x!==q.x||j.position.y!==q.y,j.position=q,j.internals.positionAbsolute=z}if(d=d||k,!!k&&(V(a,!0),I&&(r||y||!h&&Y))){const[$,j]=Ls({nodeId:h,dragItems:a,nodeLookup:L});r==null||r(I,a,$,j),y==null||y(I,$,j),h||Y==null||Y(I,j)}}async function B(){if(!R)return;const{transform:p,panBy:U,autoPanSpeed:L,autoPanOnNodeDrag:x}=t();if(!x){T=!1,cancelAnimationFrame(i);return}const[g,v]=pl(l,R,L);(g!==0||v!==0)&&(o.x=(o.x??0)-g/p[2],o.y=(o.y??0)-v/p[2],await U({x:g,y:v})&&M(o)),i=requestAnimationFrame(B)}function w(p){var X;const{nodeLookup:U,multiSelectionActive:L,nodesDraggable:x,transform:g,snapGrid:v,snapToGrid:b,selectNodesOnDrag:y,onNodeDragStart:Y,onSelectionDragStart:W,unselectNodesAndEdges:V}=t();c=!0,(!y||!m)&&!L&&h&&((X=U.get(h))!=null&&X.selected||V()),m&&y&&h&&(e==null||e(h));const k=rn(p.sourceEvent,{transform:g,snapGrid:v,snapToGrid:b,containerBounds:R});if(o=k,a=qh(U,x,k,h),a.size>0&&(n||Y||!h&&W)){const[K,Q]=Ls({nodeId:h,dragItems:a,nodeLookup:U});n==null||n(p.sourceEvent,a,K,Q),Y==null||Y(p.sourceEvent,K,Q),h||W==null||W(p.sourceEvent,Q)}}const P=nl().clickDistance(D).on("start",p=>{const{domNode:U,nodeDragThreshold:L,transform:x,snapGrid:g,snapToGrid:v}=t();R=(U==null?void 0:U.getBoundingClientRect())||null,S=!1,d=!1,I=p.sourceEvent,L===0&&w(p),o=rn(p.sourceEvent,{transform:x,snapGrid:g,snapToGrid:v,containerBounds:R}),l=xe(p.sourceEvent,R)}).on("drag",p=>{const{autoPanOnNodeDrag:U,transform:L,snapGrid:x,snapToGrid:g,nodeDragThreshold:v,nodeLookup:b}=t(),y=rn(p.sourceEvent,{transform:L,snapGrid:x,snapToGrid:g,containerBounds:R});if(I=p.sourceEvent,(p.sourceEvent.type==="touchmove"&&p.sourceEvent.touches.length>1||h&&!b.has(h))&&(S=!0),!S){if(!T&&U&&c&&(T=!0,B()),!c){const Y=xe(p.sourceEvent,R),W=Y.x-l.x,V=Y.y-l.y;Math.sqrt(W*W+V*V)>v&&w(p)}(o.x!==y.xSnapped||o.y!==y.ySnapped)&&a&&c&&(l=xe(p.sourceEvent,R),M(y))}}).on("end",p=>{if(!(!c||S)&&(T=!1,c=!1,cancelAnimationFrame(i),a.size>0)){const{nodeLookup:U,updateNodePositions:L,onNodeDragStop:x,onSelectionDragStop:g}=t();if(d&&(L(a,!1),d=!1),s||x||!h&&g){const[v,b]=Ls({nodeId:h,dragItems:a,nodeLookup:U,dragging:!1});s==null||s(p.sourceEvent,a,v,b),x==null||x(p.sourceEvent,v,b),h||g==null||g(p.sourceEvent,b)}}}).filter(p=>{const U=p.target;return!p.button&&(!C||!NE(U,`.${C}`,_))&&(!N||NE(U,N,_))});A.call(P)}function u(){A==null||A.on(".drag",null)}return{update:O,destroy:u}}function ep(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const o of t.values())In(s,bt(o))>0&&r.push(o);return r}const tp=250;function np(e,t,n,r){var a,T;let s=[],o=1/0;const i=ep(e,n,t+tp);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<o?(s=[{...c,x:A,y:S}],o=d):d===o&&s.push({...c,x:A,y:S}))}}if(!s.length)return null;if(s.length>1){const l=r.type==="source"?"target":"source";return s.find(R=>R.type===l)??s[0]}return s[0]}function wl(e,t,n,r,s,o=!1){var l,R,c;const i=r.get(e);if(!i)return null;const a=s==="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&&o?{...T,...dt(i,T,T.position,!0)}:T}function Yl(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function rp(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const Vl=()=>!0;function sp(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:o,isTarget:i,domNode:a,nodeLookup:T,lib:l,autoPanOnConnect:R,flowId:c,panBy:A,cancelConnection:S,onConnectStart:d,onConnect:I,onConnectEnd:O,isValidConnection:u=Vl,onReconnectEnd:C,updateConnection:N,getTransform:_,getFromHandle:m,autoPanSpeed:h,dragThreshold:D=1,handleDomNode:M}){const B=gl(e.target);let w=0,P;const{x:p,y:U}=xe(e),L=Yl(o,M),x=a==null?void 0:a.getBoundingClientRect();let g=!1;if(!x||!L)return;const v=wl(s,L,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]=pl(b,x,h);A({x:q,y:z}),w=requestAnimationFrame(k)}const X={...v,nodeId:s,type:L,position:v.position},K=T.get(s);let $={inProgress:!0,isValid:null,from:dt(K,X,Z.Left,!0),fromHandle:X,fromPosition:X.position,fromNode:K,to:b,toHandle:null,toPosition:iE[X.position],toNode:null,pointer:b};function j(){g=!0,N($),d==null||d(e,{nodeId:s,handleId:r,handleType:L})}D===0&&j();function ee(q){if(!g){const{x:Ne,y:qe}=xe(q),Ve=Ne-p,it=qe-U;if(!(Ve*Ve+it*it>D*D))return;j()}if(!m()||!X){re(q);return}const z=_();b=xe(q,x),P=np(mn(b,z,!1,[1,1]),n,T,X),y||(k(),y=!0);const te=Wl(q,{handle:P,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:u,doc:B,lib:l,flowId:c,nodeLookup:T});V=te.handleDomNode,Y=te.connection,W=rp(!!P,te.isValid);const ie=T.get(s),le=ie?dt(ie,X,Z.Left,!0):$.from,oe={...$,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:iE[X.position],toNode:te.toHandle?T.get(te.toHandle.nodeId):null,pointer:b};N(oe),$=oe}function re(q){if(!("touches"in q&&q.touches.length>0)){if(g){(P||V)&&Y&&W&&(I==null||I(Y));const{inProgress:z,...te}=$,ie={...te,toPosition:$.toHandle?$.toPosition:null};O==null||O(q,ie),o&&(C==null||C(q,ie))}S(),cancelAnimationFrame(w),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 Wl(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:o,doc:i,lib:a,flowId:T,isValidConnection:l=Vl,nodeLookup:R}){const c=o==="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 C=Yl(void 0,O),N=O.getAttribute("data-nodeid"),_=O.getAttribute("data-handleid"),m=O.classList.contains("connectable"),h=O.classList.contains("connectableend");if(!N||!C)return u;const D={source:c?N:r,sourceHandle:c?_:s,target:c?r:N,targetHandle:c?s:_};u.connection=D;const B=m&&h&&(n===xt.Strict?c&&C==="source"||!c&&C==="target":N!==r||_!==s);u.isValid=B&&l(D),u.toHandle=wl(N,C,_,R,n,!0)}return u}const to={onPointerDown:sp,isValid:Wl};function op({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=_e(e);function o({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 _=n(),m=N.sourceEvent.ctrlKey&&un()?10:1,h=-N.sourceEvent.deltaY*(N.sourceEvent.deltaMode===1?.05:N.sourceEvent.deltaMode?1:.002)*R,D=_[2]*Math.pow(2,h*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 _=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],h=[m[0]-I[0],m[1]-I[1]];I=m;const D=r()*Math.max(_[2],Math.log(_[2]))*(S?-1:1),M={x:_[0]-h[0]*D,y:_[1]-h[1]*D},B=[[0,0],[T,l]];t.setViewportConstrained({x:M.x,y:M.y,zoom:_[2]},B,a)},C=ul().on("start",O).on("zoom",c?u:null).on("zoom.wheel",A?d:null);s.call(C,{})}function i(){s.on("zoom",null)}return{update:o,destroy:i,pointer:ge}}const Mr=e=>({x:e.x,y:e.y,zoom:e.k}),_s=({x:e,y:t,zoom:n})=>Dr.translate(e,t).scale(n),pt=(e,t)=>e.target.closest(`.${t}`),kl=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),ip=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,hs=(e,t=0,n=ip,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},Xl=e=>{const t=e.ctrlKey&&un()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function Ep({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:o,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=ge(R),u=Xl(R),C=c*Math.pow(2,u);r.scaleTo(n,C,O,R);return}const A=R.deltaMode===1?20:1;let S=s===ct.Vertical?0:R.deltaX*A,d=s===ct.Horizontal?0:R.deltaY*A;!un()&&R.shiftKey&&s!==ct.Vertical&&(S=R.deltaY*A,d=0),r.translateBy(n,-(S/c)*o,-(d/c)*o,{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 ap({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const o=r.type==="wheel",i=!t&&o&&!r.ctrlKey,a=pt(r,e);if(r.ctrlKey&&o&&a&&r.preventDefault(),i||a)return null;r.preventDefault(),n.call(this,r,s)}}function lp({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{var o,i,a;if((o=r.sourceEvent)!=null&&o.internal)return;const s=Mr(r.transform);e.mouseButton=((i=r.sourceEvent)==null?void 0:i.button)||0,e.isZoomingOrPanning=!0,e.prevViewport=s,((a=r.sourceEvent)==null?void 0:a.type)==="mousedown"&&t(!0),n&&(n==null||n(r.sourceEvent,s))}}function Tp({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return o=>{var i,a;e.usedRightMouseButton=!!(n&&kl(t,e.mouseButton??0)),(i=o.sourceEvent)!=null&&i.sync||r([o.transform.x,o.transform.y,o.transform.k]),s&&!((a=o.sourceEvent)!=null&&a.internal)&&(s==null||s(o.sourceEvent,Mr(o.transform)))}}function cp({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:o}){return i=>{var a;if(!((a=i.sourceEvent)!=null&&a.internal)&&(e.isZoomingOrPanning=!1,o&&kl(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&o(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const T=Mr(i.transform);e.prevViewport=T,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s==null||s(i.sourceEvent,T)},n?150:0)}}}function Rp({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:s,zoomOnDoubleClick:o,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&&!s&&!o&&!n||i||R&&!d||pt(c,a)&&d||pt(c,T)&&(!d||s&&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&&!s&&!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 Ap({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:o,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=ul().scaleExtent([t,n]).translateExtent(r),A=_e(e).call(c);C({x:s.x,y:s.y,zoom:Ut(s.zoom,t,n)},[[0,0],[R.width,R.height]],r);const S=A.on("wheel.zoom"),d=A.on("dblclick.zoom");c.wheelDelta(Xl);function I(P,p){return A?new Promise(U=>{c==null||c.interpolate((p==null?void 0:p.interpolate)==="linear"?nn:qn).transform(hs(A,p==null?void 0:p.duration,p==null?void 0:p.ease,()=>U(!0)),P)}):Promise.resolve(!1)}function O({noWheelClassName:P,noPanClassName:p,onPaneContextMenu:U,userSelectionActive:L,panOnScroll:x,panOnDrag:g,panOnScrollMode:v,panOnScrollSpeed:b,preventScrolling:y,zoomOnPinch:Y,zoomOnScroll:W,zoomOnDoubleClick:V,zoomActivationKeyPressed:k,lib:X,onTransformChange:K,connectionInProgress:Q,paneClickDistance:$,selectionOnDrag:j}){L&&!l.isZoomingOrPanning&&u();const ee=x&&!k&&!L;c.clickDistance(j?1/0:!ye($)||$<0?0:$);const re=ee?Ep({zoomPanValues:l,noWheelClassName:P,d3Selection:A,d3Zoom:c,panOnScrollMode:v,panOnScrollSpeed:b,zoomOnPinch:Y,onPanZoomStart:i,onPanZoom:o,onPanZoomEnd:a}):ap({noWheelClassName:P,preventScrolling:y,d3ZoomHandler:S});if(A.on("wheel.zoom",re,{passive:!1}),!L){const z=lp({zoomPanValues:l,onDraggingChange:T,onPanZoomStart:i});c.on("start",z);const te=Tp({zoomPanValues:l,panOnDrag:g,onPaneContextMenu:!!U,onPanZoom:o,onTransformChange:K});c.on("zoom",te);const ie=cp({zoomPanValues:l,panOnDrag:g,panOnScroll:x,onPaneContextMenu:U,onPanZoomEnd:a,onDraggingChange:T});c.on("end",ie)}const q=Rp({zoomActivationKeyPressed:k,panOnDrag:g,zoomOnScroll:W,panOnScroll:x,zoomOnDoubleClick:V,zoomOnPinch:Y,userSelectionActive:L,noPanClassName:p,noWheelClassName:P,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 C(P,p,U){const L=_s(P),x=c==null?void 0:c.constrain()(L,p,U);return x&&await I(x),new Promise(g=>g(x))}async function N(P,p){const U=_s(P);return await I(U,p),new Promise(L=>L(U))}function _(P){if(A){const p=_s(P),U=A.property("__zoom");(U.k!==P.zoom||U.x!==P.x||U.y!==P.y)&&(c==null||c.transform(A,p,null,{sync:!0}))}}function m(){const P=A?Il(A.node()):{x:0,y:0,k:1};return{x:P.x,y:P.y,zoom:P.k}}function h(P,p){return A?new Promise(U=>{c==null||c.interpolate((p==null?void 0:p.interpolate)==="linear"?nn:qn).scaleTo(hs(A,p==null?void 0:p.duration,p==null?void 0:p.ease,()=>U(!0)),P)}):Promise.resolve(!1)}function D(P,p){return A?new Promise(U=>{c==null||c.interpolate((p==null?void 0:p.interpolate)==="linear"?nn:qn).scaleBy(hs(A,p==null?void 0:p.duration,p==null?void 0:p.ease,()=>U(!0)),P)}):Promise.resolve(!1)}function M(P){c==null||c.scaleExtent(P)}function B(P){c==null||c.translateExtent(P)}function w(P){const p=!ye(P)||P<0?0:P;c==null||c.clickDistance(p)}return{update:O,destroy:u,setViewport:N,setViewportConstrained:C,getViewport:m,scaleTo:h,scaleBy:D,setScaleExtent:M,setTranslateExtent:B,syncViewport:_,setClickDistance:w}}var Bt;(function(e){e.Line="line",e.Handle="handle"})(Bt||(Bt={}));function Sp({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:o}){const i=e-t,a=n-r,T=[i>0?1:i<0?-1:0,a>0?1:a<0?-1:0];return i&&s&&(T[0]=T[0]*-1),a&&o&&(T[1]=T[1]*-1),T}function OE(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),r=e.includes("left"),s=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:r,affectsY:s}}function 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 fE(e,t){return e?!t:t}function dp(e,t,n,r,s,o,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:C}=r,{x:N,y:_,width:m,height:h,aspectRatio:D}=e;let M=Math.floor(R?S-e.pointerX:0),B=Math.floor(c?d-e.pointerY:0);const w=m+(T?-M:M),P=h+(l?-B:B),p=-o[0]*m,U=-o[1]*h;let L=Vn(w,I,O),x=Vn(P,u,C);if(i){let b=0,y=0;T&&M<0?b=Ze(N+M+p,i[0][0]):!T&&M>0&&(b=Qe(N+w+p,i[1][0])),l&&B<0?y=Ze(_+B+U,i[0][1]):!l&&B>0&&(y=Qe(_+P+U,i[1][1])),L=Math.max(L,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+w,a[1][0])),l&&B>0?y=Qe(_+B,a[0][1]):!l&&B<0&&(y=Ze(_+P,a[1][1])),L=Math.max(L,b),x=Math.max(x,y)}if(s){if(R){const b=Vn(w/D,u,C)*D;if(L=Math.max(L,b),i){let y=0;!T&&!l||T&&!l&&A?y=Qe(_+U+w/D,i[1][1])*D:y=Ze(_+U+(T?M:-M)/D,i[0][1])*D,L=Math.max(L,y)}if(a){let y=0;!T&&!l||T&&!l&&A?y=Ze(_+w/D,a[1][1])*D:y=Qe(_+(T?M:-M)/D,a[0][1])*D,L=Math.max(L,y)}}if(c){const b=Vn(P*D,I,O)/D;if(x=Math.max(x,b),i){let y=0;!T&&!l||l&&!T&&A?y=Qe(N+P*D+p,i[1][0])/D:y=Ze(N+(l?B:-B)*D+p,i[0][0])/D,x=Math.max(x,y)}if(a){let y=0;!T&&!l||l&&!T&&A?y=Ze(N+P*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?L:-L),s&&(A?w>P*D?B=(fE(T,l)?-M:M)/D:M=(fE(T,l)?-B:B)*D:R?(B=M/D,l=T):(M=B*D,T=l));const g=T?N+M:N,v=l?_+B:_;return{width:m+(T?-M:M),height:h+(l?-B:B),x:o[0]*M*(T?-1:1)+g,y:o[1]*B*(l?-1:1)+v}}const $l={width:0,height:0,x:0,y:0},Ip={...$l,pointerX:0,pointerY:0,aspectRatio:1};function up(e){return[[0,0],[e.measured.width,e.measured.height]]}function Np(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,o=e.measured.width??0,i=e.measured.height??0,a=n[0]*o,T=n[1]*i;return[[r-a,s-T],[r+o-a,s+i-T]]}function Op({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const o=_e(e);let i={controlDirection:OE("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={...$l},C={...Ip};i={boundaries:R,resizeDirection:A,keepAspectRatio:c,controlDirection:OE(l)};let N,_=null,m=[],h,D,M,B=!1;const w=nl().on("start",P=>{const{nodeLookup:p,transform:U,snapGrid:L,snapToGrid:x,nodeOrigin:g,paneDomNode:v}=n();if(N=p.get(t),!N)return;_=(v==null?void 0:v.getBoundingClientRect())??null;const{xSnapped:b,ySnapped:y}=rn(P.sourceEvent,{transform:U,snapGrid:L,snapToGrid:x,containerBounds:_});u={width:N.measured.width??0,height:N.measured.height??0,x:N.position.x??0,y:N.position.y??0},C={...u,pointerX:b,pointerY:y,aspectRatio:u.width/u.height},h=void 0,N.parentId&&(N.extent==="parent"||N.expandParent)&&(h=p.get(N.parentId),D=h&&N.extent==="parent"?up(h):void 0),m=[],M=void 0;for(const[Y,W]of p)if(W.parentId===t&&(m.push({id:Y,position:{...W.position},extent:W.extent}),W.extent==="parent"||W.expandParent)){const V=Np(W,N,W.origin??g);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(P,{...u})}).on("drag",P=>{const{transform:p,snapGrid:U,snapToGrid:L,nodeOrigin:x}=n(),g=rn(P.sourceEvent,{transform:p,snapGrid:U,snapToGrid:L,containerBounds:_}),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:$}=dp(C,i.controlDirection,g,i.boundaries,i.keepAspectRatio,k,D,M),j=X!==Y,ee=K!==W,re=Q!==b&&j,q=$!==y&ⅇif(!re&&!q&&!j&&!ee)return;if((re||q||k[0]===1||k[1]===1)&&(V.x=re?Q:u.x,V.y=q?$:u.y,u.x=V.x,u.y=V.y,m.length>0)){const le=Q-b,oe=$-y;for(const Ne of m)Ne.position={x:Ne.position.x-le+k[0]*(X-Y),y:Ne.position.y-oe+k[1]*(K-W)},v.push(Ne)}if((j||ee)&&(V.width=j&&(!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),h&&N.expandParent){const le=k[0]*(V.width??0);V.x&&V.x<le&&(u.x=le,C.x=C.x-(V.x-le));const oe=k[1]*(V.height??0);V.y&&V.y<oe&&(u.y=oe,C.y=C.y-(V.y-oe))}const z=Sp({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(P,te))!==!1&&(B=!0,d==null||d(P,te),r(V,v))}).on("end",P=>{B&&(I==null||I(P,{...u}),s==null||s({...u}),B=!1)});o.call(w)}function T(){o.on(".drag",null)}return{update:a,destroy:T}}var ps={exports:{}},ms={},Ds={exports:{}},Ps={};/**
|
|
490
|
+
* @license React
|
|
491
|
+
* use-sync-external-store-shim.production.js
|
|
492
|
+
*
|
|
493
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
494
|
+
*
|
|
495
|
+
* This source code is licensed under the MIT license found in the
|
|
496
|
+
* LICENSE file in the root directory of this source tree.
|
|
497
|
+
*/var CE;function fp(){if(CE)return Ps;CE=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,s=e.useEffect,o=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 o(function(){I.value=S,I.getSnapshot=A,T(I)&&O({inst:I})},[c,S,A]),s(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 Ps.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:R,Ps}var LE;function Cp(){return LE||(LE=1,Ds.exports=fp()),Ds.exports}/**
|
|
498
|
+
* @license React
|
|
499
|
+
* use-sync-external-store-shim/with-selector.production.js
|
|
500
|
+
*
|
|
501
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
502
|
+
*
|
|
503
|
+
* This source code is licensed under the MIT license found in the
|
|
504
|
+
* LICENSE file in the root directory of this source tree.
|
|
505
|
+
*/var _E;function Lp(){if(_E)return ms;_E=1;var e=Cr(),t=Cp();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,s=t.useSyncExternalStore,o=e.useRef,i=e.useEffect,a=e.useMemo,T=e.useDebugValue;return ms.useSyncExternalStoreWithSelector=function(l,R,c,A,S){var d=o(null);if(d.current===null){var I={hasValue:!1,value:null};d.current=I}else I=d.current;d=a(function(){function u(h){if(!C){if(C=!0,N=h,h=A(h),S!==void 0&&I.hasValue){var D=I.value;if(S(D,h))return _=D}return _=h}if(D=_,r(N,h))return D;var M=A(h);return S!==void 0&&S(D,M)?(N=h,D):(N=h,_=M)}var C=!1,N,_,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=s(l,d[0],d[1]);return i(function(){I.hasValue=!0,I.value=O},[O]),T(O),O},ms}var hE;function _p(){return hE||(hE=1,ps.exports=Lp()),ps.exports}var hp=_p();const pp=so(hp),mp={},pE=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))}},s=()=>t,T={setState:r,getState:s,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,s,T);return T},Dp=e=>e?pE(e):pE,{useDebugValue:Pp}=sn,{useSyncExternalStoreWithSelector:gp}=pp,Mp=e=>e;function jl(e,t=Mp,n){const r=gp(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return Pp(r),r}const mE=(e,t)=>{const n=Dp(e),r=(s,o=t)=>jl(n,s,o);return Object.assign(r,n),r},yp=(e,t)=>e?mE(e,t):mE;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,s]of e)if(!Object.is(s,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}la();const yr=f.createContext(null),xp=yr.Provider,Kl=we.error001();function se(e,t){const n=f.useContext(yr);if(n===null)throw new Error(Kl);return jl(n,e,t)}function ce(){const e=f.useContext(yr);if(e===null)throw new Error(Kl);return f.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const DE={display:"none"},Up={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},Jl="react-flow__node-desc",zl="react-flow__edge-desc",bp="react-flow__aria-live",Gp=e=>e.ariaLiveMessage,Bp=e=>e.ariaLabelConfig;function vp({rfId:e}){const t=se(Gp);return E.jsx("div",{id:`${bp}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:Up,children:t})}function Hp({rfId:e,disableKeyboardA11y:t}){const n=se(Bp);return E.jsxs(E.Fragment,{children:[E.jsx("div",{id:`${Jl}-${e}`,style:DE,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),E.jsx("div",{id:`${zl}-${e}`,style:DE,children:n["edge.a11yDescription.default"]}),!t&&E.jsx(vp,{rfId:e})]})}const Dn=f.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},o)=>{const i=`${e}`.split("-");return E.jsx("div",{className:Ae(["react-flow__panel",n,...i]),style:r,ref:o,...s,children:t})});Dn.displayName="Panel";function Fp({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 wp=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 Yp(e,t){return Te(e.selectedNodes.map(Wn),t.selectedNodes.map(Wn))&&Te(e.selectedEdges.map(Wn),t.selectedEdges.map(Wn))}function Vp({onSelectionChange:e}){const t=ce(),{selectedNodes:n,selectedEdges:r}=se(wp,Yp);return f.useEffect(()=>{const s={nodes:n,edges:r};e==null||e(s),t.getState().onSelectionChangeHandlers.forEach(o=>o(s))},[n,r,e]),null}const Wp=e=>!!e.onSelectionChangeHandlers;function kp({onSelectionChange:e}){const t=se(Wp);return e||t?E.jsx(Vp,{onSelectionChange:e}):null}const ql=[0,0],Xp={x:0,y:0,zoom:1},$p=["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"],PE=[...$p,"rfId"],jp=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}),gE={translateExtent:An,nodeOrigin:ql,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function Kp(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:o,setNodeExtent:i,reset:a,setDefaultNodesAndEdges:T}=se(jp,Te),l=ce();f.useEffect(()=>(T(e.defaultNodes,e.defaultEdges),()=>{R.current=gE,a()}),[]);const R=f.useRef(gE);return f.useEffect(()=>{for(const c of PE){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"?s(A):c==="translateExtent"?o(A):c==="nodeExtent"?i(A):c==="ariaLabelConfig"?l.setState({ariaLabelConfig:yh(A)}):c==="fitView"?l.setState({fitViewQueued:A}):c==="fitViewOptions"?l.setState({fitViewOptions:A}):l.setState({[c]:A})))}R.current=e},PE.map(c=>e[c])),null}function ME(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function Jp(e){var r;const[t,n]=f.useState(e==="system"?null:e);return f.useEffect(()=>{if(e!=="system"){n(e);return}const s=ME(),o=()=>n(s!=null&&s.matches?"dark":"light");return o(),s==null||s.addEventListener("change",o),()=>{s==null||s.removeEventListener("change",o)}},[e]),t!==null?t:(r=ME())!=null&&r.matches?"dark":"light"}const yE=typeof document<"u"?document:null;function Nn(e=null,t={target:yE,actInsideInputWithModifier:!0}){const[n,r]=f.useState(!1),s=f.useRef(!1),o=f.useRef(new Set([])),[i,a]=f.useMemo(()=>{if(e!==null){const l=(Array.isArray(e)?e:[e]).filter(c=>typeof c=="string").map(c=>c.replace("+",`
|
|
506
|
+
`).replace(`
|
|
507
|
+
|
|
508
|
+
`,`
|
|
509
|
+
+`).split(`
|
|
510
|
+
`)),R=l.reduce((c,A)=>c.concat(...A),[]);return[l,R]}return[[],[]]},[e]);return f.useEffect(()=>{const T=(t==null?void 0:t.target)??yE,l=(t==null?void 0:t.actInsideInputWithModifier)??!0;if(e!==null){const R=S=>{var O,u;if(s.current=S.ctrlKey||S.metaKey||S.shiftKey||S.altKey,(!s.current||s.current&&!l)&&Ml(S))return!1;const I=UE(S.code,a);if(o.current.add(S[I]),xE(i,o.current,!1)){const C=((u=(O=S.composedPath)==null?void 0:O.call(S))==null?void 0:u[0])||S.target,N=(C==null?void 0:C.nodeName)==="BUTTON"||(C==null?void 0:C.nodeName)==="A";t.preventDefault!==!1&&(s.current||!N)&&S.preventDefault(),r(!0)}},c=S=>{const d=UE(S.code,a);xE(i,o.current,!0)?(r(!1),o.current.clear()):o.current.delete(S[d]),S.key==="Meta"&&o.current.clear(),s.current=!1},A=()=>{o.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 xE(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(s=>t.has(s)))}function UE(e,t){return t.includes(e)?"code":"key"}const zp=()=>{const e=ce();return f.useMemo(()=>({zoomIn:t=>{const{panZoom:n}=e.getState();return n?n.scaleBy(1.2,{duration:t==null?void 0:t.duration}):Promise.resolve(!1)},zoomOut:t=>{const{panZoom:n}=e.getState();return n?n.scaleBy(1/1.2,{duration:t==null?void 0:t.duration}):Promise.resolve(!1)},zoomTo:(t,n)=>{const{panZoom:r}=e.getState();return r?r.scaleTo(t,{duration:n==null?void 0:n.duration}):Promise.resolve(!1)},getZoom:()=>e.getState().transform[2],setViewport:async(t,n)=>{const{transform:[r,s,o],panZoom:i}=e.getState();return i?(await i.setViewport({x:t.x??r,y:t.y??s,zoom:t.zoom??o},n),Promise.resolve(!0)):Promise.resolve(!1)},getViewport:()=>{const[t,n,r]=e.getState().transform;return{x:t,y:n,zoom:r}},setCenter:async(t,n,r)=>e.getState().setCenter(t,n,r),fitBounds:async(t,n)=>{const{width:r,height:s,minZoom:o,maxZoom:i,panZoom:a}=e.getState(),T=po(t,r,s,o,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:s,snapToGrid:o,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??s,c=n.snapToGrid??o;return mn(l,r,c,R)},flowToScreenPosition:t=>{const{transform:n,domNode:r}=e.getState();if(!r)return t;const{x:s,y:o}=r.getBoundingClientRect(),i=Ir(t,n);return{x:i.x+s,y:i.y+o}}}),[])};function Zl(e,t){const n=[],r=new Map,s=[];for(const o of e)if(o.type==="add"){s.push(o);continue}else if(o.type==="remove"||o.type==="replace")r.set(o.id,[o]);else{const i=r.get(o.id);i?i.push(o):r.set(o.id,[o])}for(const o of t){const i=r.get(o.id);if(!i){n.push(o);continue}if(i[0].type==="remove")continue;if(i[0].type==="replace"){n.push({...i[0].item});continue}const a={...o};for(const T of i)qp(T,a);n.push(a)}return s.length&&s.forEach(o=>{o.index!==void 0?n.splice(o.index,0,{...o.item}):n.push({...o.item})}),n}function qp(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 Ql(e,t){return Zl(e,t)}function eT(e,t){return Zl(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[s,o]of e){const i=t.has(s);!(o.selected===void 0&&!i)&&o.selected!==i&&(n&&(o.selected=i),r.push(at(o.id,i)))}return r}function bE({items:e=[],lookup:t}){var s;const n=[],r=new Map(e.map(o=>[o.id,o]));for(const[o,i]of e.entries()){const a=t.get(i.id),T=((s=a==null?void 0:a.internals)==null?void 0:s.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:o})}for(const[o]of t)r.get(o)===void 0&&n.push({id:o,type:"remove"});return n}function GE(e){return{id:e.id,type:"remove"}}const BE=e=>Ch(e),Zp=e=>Ll(e);function tT(e){return f.forwardRef(e)}const Qp=typeof window<"u"?f.useLayoutEffect:f.useEffect;function vE(e){const[t,n]=f.useState(BigInt(0)),[r]=f.useState(()=>em(()=>n(s=>s+BigInt(1))));return Qp(()=>{const s=r.get();s.length&&(e(s),r.reset())},[t]),r}function em(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}const nT=f.createContext(null);function tm({children:e}){const t=ce(),n=f.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:C,setNodes:N}=t.getState();u&&N(C)})},[]),r=vE(n),s=f.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}))},[]),o=vE(s),i=f.useMemo(()=>({nodeQueue:r,edgeQueue:o}),[]);return E.jsx(nT.Provider,{value:i,children:e})}function nm(){const e=f.useContext(nT);if(!e)throw new Error("useBatchContext must be used within a BatchProvider");return e}const rm=e=>!!e.panZoom;function xo(){const e=zp(),t=ce(),n=nm(),r=se(rm),s=f.useMemo(()=>{const o=c=>t.getState().nodeLookup.get(c),i=c=>{n.nodeQueue.push(c)},a=c=>{n.edgeQueue.push(c)},T=c=>{var u,C;const{nodeLookup:A,nodeOrigin:S}=t.getState(),d=BE(c)?c:A.get(c.id),I=d.parentId?Pl(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:((C=d.measured)==null?void 0:C.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&&BE(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&&Zp(O)?O:{...I,...O}}return I}))};return{getNodes:()=>t.getState().nodes.map(c=>({...c})),getNode:c=>{var A;return(A=o(c))==null?void 0:A.internals.userNode},getInternalNode:o,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:C,onDelete:N,onBeforeDelete:_}=t.getState(),{nodes:m,edges:h}=await mh({nodesToRemove:c,edgesToRemove:A,nodes:S,edges:d,onBeforeDelete:_}),D=h.length>0,M=m.length>0;if(D){const B=h.map(GE);O==null||O(h),C(B)}if(M){const B=m.map(GE);I==null||I(m),u(B)}return(M||D)&&(N==null||N({nodes:m,edges:h})),{deletedNodes:m,deletedEdges:h}},getIntersectingNodes:(c,A=!0,S)=>{const d=aE(c),I=d?c:T(c),O=S!==void 0;return I?(S||t.getState().nodes).filter(u=>{const C=t.getState().nodeLookup.get(u.id);if(C&&!d&&(u.id===c.id||!C.internals.positionAbsolute))return!1;const N=bt(O?u:C),_=In(N,I);return A&&_>0||_>=N.width*N.height||_>=I.width*I.height}):[]},isNodeIntersecting:(c,A,S=!0)=>{const I=aE(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 Lh(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??Mh();return t.setState({fitViewQueued:!0,fitViewOptions:c,fitViewResolver:A}),n.nodeQueue.push(S=>[...S]),A.promise}}},[]);return f.useMemo(()=>({...s,...e,viewportInitialized:r}),[r])}const HE=e=>e.selected,sm=typeof window<"u"?window:void 0;function om({deleteKeyCode:e,multiSelectionKeyCode:t}){const n=ce(),{deleteElements:r}=xo(),s=Nn(e,{actInsideInputWithModifier:!1}),o=Nn(t,{target:sm});f.useEffect(()=>{if(s){const{edges:i,nodes:a}=n.getState();r({nodes:a.filter(HE),edges:i.filter(HE)}),n.setState({nodesSelectionActive:!1})}},[s]),f.useEffect(()=>{n.setState({multiSelectionActive:o})},[o])}function im(e){const t=ce();f.useEffect(()=>{const n=()=>{var s,o,i,a;if(!e.current||!(((o=(s=e.current).checkVisibility)==null?void 0:o.call(s))??!0))return!1;const r=mo(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},Em=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function am({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:r=!1,panOnScrollSpeed:s=.5,panOnScrollMode:o=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:C,paneClickDistance:N,selectionOnDrag:_}){const m=ce(),h=f.useRef(null),{userSelectionActive:D,lib:M,connectionInProgress:B}=se(Em,Te),w=Nn(A),P=f.useRef();im(h);const p=f.useCallback(U=>{u==null||u({x:U[0],y:U[1],zoom:U[2]}),C||m.setState({transform:U})},[u,C]);return f.useEffect(()=>{if(h.current){P.current=Ap({domNode:h.current,minZoom:R,maxZoom:c,translateExtent:l,viewport:T,onDraggingChange:g=>m.setState(v=>v.paneDragging===g?v:{paneDragging:g}),onPanZoomStart:(g,v)=>{const{onViewportChangeStart:b,onMoveStart:y}=m.getState();y==null||y(g,v),b==null||b(v)},onPanZoom:(g,v)=>{const{onViewportChange:b,onMove:y}=m.getState();y==null||y(g,v),b==null||b(v)},onPanZoomEnd:(g,v)=>{const{onViewportChangeEnd:b,onMoveEnd:y}=m.getState();y==null||y(g,v),b==null||b(v)}});const{x:U,y:L,zoom:x}=P.current.getViewport();return m.setState({panZoom:P.current,transform:[U,L,x],domNode:h.current.closest(".react-flow")}),()=>{var g;(g=P.current)==null||g.destroy()}}},[]),f.useEffect(()=>{var U;(U=P.current)==null||U.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:r,panOnScrollSpeed:s,panOnScrollMode:o,zoomOnDoubleClick:i,panOnDrag:a,zoomActivationKeyPressed:w,preventScrolling:S,noPanClassName:O,userSelectionActive:D,noWheelClassName:I,lib:M,onTransformChange:p,connectionInProgress:B,selectionOnDrag:_,paneClickDistance:N})},[e,t,n,r,s,o,i,a,w,S,O,D,I,M,p,B,_,N]),E.jsx("div",{className:"react-flow__renderer",ref:h,style:xr,children:d})}const lm=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function Tm(){const{userSelectionActive:e,userSelectionRect:t}=se(lm,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 gs=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},cm=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,connectionInProgress:e.connection.inProgress,dragging:e.paneDragging});function Rm({isSelecting:e,selectionKeyPressed:t,selectionMode:n=Sn.Full,panOnDrag:r,paneClickDistance:s,selectionOnDrag:o,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:C,connectionInProgress:N}=se(cm,Te),_=u&&(e||O),m=f.useRef(null),h=f.useRef(),D=f.useRef(new Set),M=f.useRef(new Set),B=f.useRef(!1),w=b=>{if(B.current||N){B.current=!1;return}T==null||T(b),I.getState().resetSelectedElements(),I.setState({nodesSelectionActive:!1})},P=b=>{if(Array.isArray(r)&&(r!=null&&r.includes(2))){b.preventDefault();return}l==null||l(b)},p=R?b=>R(b):void 0,U=b=>{B.current&&(b.stopPropagation(),B.current=!1)},L=b=>{var K,Q;const{domNode:y}=I.getState();if(h.current=y==null?void 0:y.getBoundingClientRect(),!h.current)return;const Y=b.target===m.current;if(!Y&&!!b.target.closest(".nokey")||!e||!(o&&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,h.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:$}=I.getState();if(!h.current||!y)return;const{x:j,y:ee}=xe(b.nativeEvent,h.current),{startX:re,startY:q}=y;if(!B.current){const oe=t?0:s;if(Math.hypot(j-re,ee-q)<=oe)return;$(),i==null||i(b)}B.current=!0;const z={startX:re,startY:q,x:j<re?j:re,y:ee<q?ee:q,width:Math.abs(j-re),height:Math.abs(ee-q)},te=D.current,ie=M.current;D.current=new Set(ho(W,z,Y,n===Sn.Partial,!0).map(oe=>oe.id)),M.current=new Set;const le=(Q==null?void 0:Q.selectable)??!0;for(const oe of D.current){const Ne=k.get(oe);if(Ne)for(const{edgeId:qe}of Ne.values()){const Ve=V.get(qe);Ve&&(Ve.selectable??le)&&M.current.add(qe)}}if(!lE(te,D.current)){const oe=mt(W,D.current,!0);X(oe)}if(!lE(ie,M.current)){const oe=mt(V,M.current);K(oe)}I.setState({userSelectionRect:z,userSelectionActive:!0,nodesSelectionActive:!1})},g=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&&(w==null||w(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:C,selection:e}]),onClick:_?void 0:gs(w,m),onContextMenu:gs(P,m),onWheel:gs(p,m),onPointerEnter:_?void 0:c,onPointerMove:_?x:A,onPointerUp:_?g:void 0,onPointerDownCapture:_?L:void 0,onClickCapture:_?U:void 0,onPointerLeave:S,ref:m,style:xr,children:[d,E.jsx(Tm,{})]})}function no({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:s,unselectNodesAndEdges:o,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)&&(o({nodes:[l],edges:[]}),requestAnimationFrame(()=>{var R;return(R=r==null?void 0:r.current)==null?void 0:R.blur()})):s([e])}function rT({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:s,isSelectable:o,nodeClickDistance:i}){const a=ce(),[T,l]=f.useState(!1),R=f.useRef();return f.useEffect(()=>{R.current=Qh({getStoreItems:()=>a.getState(),onNodeMouseDown:c=>{no({id:c,store:a,nodeRef:e})},onDragStart:()=>{l(!0)},onDragStop:()=>{l(!1)}})},[]),f.useEffect(()=>{if(!(t||!e.current||!R.current))return R.current.update({noDragClassName:n,handleSelector:r,domNode:e.current,isSelectable:o,nodeId:s,nodeClickDistance:i}),()=>{var c;(c=R.current)==null||c.destroy()}},[n,r,t,o,e,s,i]),T}const Am=e=>t=>t.selected&&(t.draggable||e&&typeof t.draggable>"u");function sT(){const e=ce();return f.useCallback(n=>{const{nodeExtent:r,snapToGrid:s,snapGrid:o,nodesDraggable:i,onError:a,updateNodePositions:T,nodeLookup:l,nodeOrigin:R}=e.getState(),c=new Map,A=Am(i),S=s?o[0]:5,d=s?o[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 C={x:u.internals.positionAbsolute.x+I,y:u.internals.positionAbsolute.y+O};s&&(C=pn(C,o));const{position:N,positionAbsolute:_}=_l({nodeId:u.id,nextPosition:C,nodeLookup:l,nodeExtent:r,nodeOrigin:R,onError:a});u.position=N,u.internals.positionAbsolute=_,c.set(u.id,u)}T(c)},[])}const Uo=f.createContext(null),Sm=Uo.Provider;Uo.Consumer;const oT=()=>f.useContext(Uo),dm=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),Im=(e,t,n)=>r=>{const{connectionClickStartHandle:s,connectionMode:o,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:(s==null?void 0:s.nodeId)===e&&(s==null?void 0:s.id)===t&&(s==null?void 0:s.type)===n,isPossibleEndHandle:o===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:!!s,valid:R&&l}};function um({type:e="source",position:t=Z.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:s=!0,isConnectableEnd:o=!0,id:i,onConnect:a,children:T,className:l,onMouseDown:R,onTouchStart:c,...A},S){var x,g;const d=i||null,I=e==="target",O=ce(),u=oT(),{connectOnClick:C,noPanClassName:N,rfId:_}=se(dm,Te),{connectingFrom:m,connectingTo:h,clickConnecting:D,isPossibleEndHandle:M,connectionInProcess:B,clickConnectionInProcess:w,valid:P}=se(Im(u,d,e),Te);u||(g=(x=O.getState()).onError)==null||g.call(x,"010",we.error010());const p=v=>{const{defaultEdgeOptions:b,onConnect:y,hasDefaultEdges:Y}=O.getState(),W={...b,...v};if(Y){const{edges:V,setEdges:k}=O.getState();k(vh(W,V))}y==null||y(W),a==null||a(W)},U=v=>{if(!u)return;const b=yl(v.nativeEvent);if(s&&(b&&v.button===0||!b)){const y=O.getState();to.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:p,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)},L=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&&!s)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 $=gl(v.target),j=n||V,{connection:ee,isValid:re}=to.isValid(v.nativeEvent,{handle:{nodeId:u,id:d,type:e},connectionMode:W,fromNodeId:Y.nodeId,fromHandleId:Y.id||null,fromType:Y.type,isValidConnection:j,flowId:X,doc:$,lib:k,nodeLookup:K});re&&ee&&p(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":`${_}-${u}-${d}-${e}`,className:Ae(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",N,l,{source:!I,target:I,connectable:r,connectablestart:s,connectableend:o,clickconnecting:D,connectingfrom:m,connectingto:h,valid:P,connectionindicator:r&&(!B||M)&&(B||w?o:s)}]),onMouseDown:U,onTouchStart:U,onClick:C?L:void 0,ref:S,...A,children:T})}const vt=f.memo(tT(um));function Nm({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 Om({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 fm(){return null}function Cm({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}},FE={input:Nm,default:Om,output:Cm,group:fm};function Lm(e){var t,n,r,s;return e.internals.handleBounds===void 0?{width:e.width??e.initialWidth??((t=e.style)==null?void 0:t.width),height:e.height??e.initialHeight??((n=e.style)==null?void 0:n.height)}:{width:e.width??((r=e.style)==null?void 0:r.width),height:e.height??((s=e.style)==null?void 0:s.height)}}const _m=e=>{const{width:t,height:n,x:r,y:s}=hn(e.nodeLookup,{filter:o=>!!o.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,${s}px)`}};function hm({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=ce(),{width:s,height:o,transformString:i,userSelectionActive:a}=se(_m,Te),T=sT(),l=f.useRef(null);f.useEffect(()=>{var S;n||(S=l.current)==null||S.focus({preventScroll:!0})},[n]);const R=!a&&s!==null&&o!==null;if(rT({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:s,height:o}})})}const wE=typeof window<"u"?window:void 0,pm=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function iT({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:s,onPaneContextMenu:o,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:C,zoomOnPinch:N,panOnScroll:_,panOnScrollSpeed:m,panOnScrollMode:h,zoomOnDoubleClick:D,panOnDrag:M,defaultViewport:B,translateExtent:w,minZoom:P,maxZoom:p,preventScrolling:U,onSelectionContextMenu:L,noWheelClassName:x,noPanClassName:g,disableKeyboardA11y:v,onViewportChange:b,isControlledViewport:y}){const{nodesSelectionActive:Y,userSelectionActive:W}=se(pm,Te),V=Nn(l,{target:wE}),k=Nn(I,{target:wE}),X=k||M,K=k||_,Q=R&&X!==!0,$=V||W||Q;return om({deleteKeyCode:T,multiSelectionKeyCode:d}),E.jsx(am,{onPaneContextMenu:o,elementsSelectable:u,zoomOnScroll:C,zoomOnPinch:N,panOnScroll:K,panOnScrollSpeed:m,panOnScrollMode:h,zoomOnDoubleClick:D,panOnDrag:!V&&X,defaultViewport:B,translateExtent:w,minZoom:P,maxZoom:p,zoomActivationKeyCode:O,preventScrolling:U,noWheelClassName:x,noPanClassName:g,onViewportChange:b,isControlledViewport:y,paneClickDistance:a,selectionOnDrag:Q,children:E.jsxs(Rm,{onSelectionStart:A,onSelectionEnd:S,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:s,onPaneContextMenu:o,onPaneScroll:i,panOnDrag:X,isSelecting:!!$,selectionMode:c,selectionKeyPressed:V,paneClickDistance:a,selectionOnDrag:Q,children:[e,Y&&E.jsx(hm,{onSelectionContextMenu:L,noPanClassName:g,disableKeyboardA11y:v})]})})}iT.displayName="FlowRenderer";const mm=f.memo(iT),Dm=e=>t=>e?ho(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 Pm(e){return se(f.useCallback(Dm(e),[e]),Te)}const gm=e=>e.updateNodeInternals;function Mm(){const e=se(gm),[t]=f.useState(()=>typeof ResizeObserver>"u"?null:new ResizeObserver(n=>{const r=new Map;n.forEach(s=>{const o=s.target.getAttribute("data-id");r.set(o,{id:o,nodeElement:s.target,force:!0})}),e(r)}));return f.useEffect(()=>()=>{t==null||t.disconnect()},[t]),t}function ym({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){const s=ce(),o=f.useRef(null),i=f.useRef(null),a=f.useRef(e.sourcePosition),T=f.useRef(e.targetPosition),l=f.useRef(t),R=n&&!!e.internals.handleBounds;return f.useEffect(()=>{o.current&&!e.hidden&&(!R||i.current!==o.current)&&(i.current&&(r==null||r.unobserve(i.current)),r==null||r.observe(o.current),i.current=o.current)},[R,e.hidden]),f.useEffect(()=>()=>{i.current&&(r==null||r.unobserve(i.current),i.current=null)},[]),f.useEffect(()=>{if(o.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,s.getState().updateNodeInternals(new Map([[e.id,{id:e.id,nodeElement:o.current,force:!0}]])))}},[e.id,t,e.sourcePosition,e.targetPosition]),o}function xm({id:e,onClick:t,onMouseEnter:n,onMouseMove:r,onMouseLeave:s,onContextMenu:o,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:C}){const{node:N,internals:_,isParent:m}=se(j=>{const ee=j.nodeLookup.get(e),re=j.parentLookup.has(e);return{node:ee,internals:ee.internals,isParent:re}},Te);let h=N.type||"default",D=(O==null?void 0:O[h])||FE[h];D===void 0&&(C==null||C("003",we.error003(h)),h="default",D=(O==null?void 0:O.default)||FE.default);const M=!!(N.draggable||a&&typeof N.draggable>"u"),B=!!(N.selectable||T&&typeof N.selectable>"u"),w=!!(N.connectable||l&&typeof N.connectable>"u"),P=!!(N.focusable||R&&typeof N.focusable>"u"),p=ce(),U=Dl(N),L=ym({node:N,nodeType:h,hasDimensions:U,resizeObserver:c}),x=rT({nodeRef:L,disabled:N.hidden||!M,noDragClassName:A,handleSelector:N.dragHandle,nodeId:e,isSelectable:B,nodeClickDistance:u}),g=sT();if(N.hidden)return null;const v=ze(N),b=Lm(N),y=B||M||t||n||r||s,Y=n?j=>n(j,{..._.userNode}):void 0,W=r?j=>r(j,{..._.userNode}):void 0,V=s?j=>s(j,{..._.userNode}):void 0,k=o?j=>o(j,{..._.userNode}):void 0,X=i?j=>i(j,{..._.userNode}):void 0,K=j=>{const{selectNodesOnDrag:ee,nodeDragThreshold:re}=p.getState();B&&(!ee||!M||re>0)&&no({id:e,store:p,nodeRef:L}),t&&t(j,{..._.userNode})},Q=j=>{if(!(Ml(j.nativeEvent)||d)){if(Nl.includes(j.key)&&B){const ee=j.key==="Escape";no({id:e,store:p,unselect:ee,nodeRef:L})}else if(M&&N.selected&&Object.prototype.hasOwnProperty.call(ur,j.key)){j.preventDefault();const{ariaLabelConfig:ee}=p.getState();p.setState({ariaLiveMessage:ee["node.a11yDescription.ariaLiveMessage"]({direction:j.key.replace("Arrow","").toLowerCase(),x:~~_.positionAbsolute.x,y:~~_.positionAbsolute.y})}),g({direction:ur[j.key],factor:j.shiftKey?4:1})}}},$=()=>{var ie;if(d||!((ie=L.current)!=null&&ie.matches(":focus-visible")))return;const{transform:j,width:ee,height:re,autoPanOnNodeFocus:q,setCenter:z}=p.getState();if(!q)return;ho(new Map([[e,N]]),{x:0,y:0,width:ee,height:re},j,!0).length>0||z(N.position.x+v.width/2,N.position.y+v.height/2,{zoom:j[2]})};return E.jsx("div",{className:Ae(["react-flow__node",`react-flow__node-${h}`,{[S]:M},N.className,{selected:N.selected,selectable:B,parent:m,draggable:M,dragging:x}]),ref:L,style:{zIndex:_.z,transform:`translate(${_.positionAbsolute.x}px,${_.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:P?Q:void 0,tabIndex:P?0:void 0,onFocus:P?$:void 0,role:N.ariaRole??(P?"group":void 0),"aria-roledescription":"node","aria-describedby":d?void 0:`${Jl}-${I}`,"aria-label":N.ariaLabel,...N.domAttributes,children:E.jsx(Sm,{value:e,children:E.jsx(D,{id:e,data:N.data,type:h,positionAbsoluteX:_.positionAbsolute.x,positionAbsoluteY:_.positionAbsolute.y,selected:N.selected??!1,selectable:B,draggable:M,deletable:N.deletable??!0,isConnectable:w,sourcePosition:N.sourcePosition,targetPosition:N.targetPosition,dragging:x,dragHandle:N.dragHandle,zIndex:_.z,parentId:N.parentId,...v})})})}var Um=f.memo(xm);const bm=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function ET(e){const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:s,onError:o}=se(bm,Te),i=Pm(e.onlyRenderVisibleElements),a=Mm();return E.jsx("div",{className:"react-flow__nodes",style:xr,children:i.map(T=>E.jsx(Um,{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:s,nodeClickDistance:e.nodeClickDistance,onError:o},T))})}ET.displayName="NodeRenderer";const Gm=f.memo(ET);function Bm(e){return se(f.useCallback(n=>{if(!e)return n.edges.map(s=>s.id);const r=[];if(n.width&&n.height)for(const s of n.edges){const o=n.nodeLookup.get(s.source),i=n.nodeLookup.get(s.target);o&&i&&bh({sourceNode:o,targetNode:i,width:n.width,height:n.height,transform:n.transform})&&r.push(s.id)}return r},[e]),Te)}const vm=({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"})},Hm=({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"})},YE={[dn.Arrow]:vm,[dn.ArrowClosed]:Hm};function Fm(e){const t=ce();return f.useMemo(()=>{var s,o;return Object.prototype.hasOwnProperty.call(YE,e)?YE[e]:((o=(s=t.getState()).onError)==null||o.call(s,"009",we.error009(e)),null)},[e])}const wm=({id:e,type:t,color:n,width:r=12.5,height:s=12.5,markerUnits:o="strokeWidth",strokeWidth:i,orient:a="auto-start-reverse"})=>{const T=Fm(t);return T?E.jsx("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${r}`,markerHeight:`${s}`,viewBox:"-10 -10 20 20",markerUnits:o,orient:a,refX:"0",refY:"0",children:E.jsx(T,{color:n,strokeWidth:i})}):null},aT=({defaultColor:e,rfId:t})=>{const n=se(o=>o.edges),r=se(o=>o.defaultEdgeOptions),s=f.useMemo(()=>Vh(n,{id:t,defaultColor:e,defaultMarkerStart:r==null?void 0:r.markerStart,defaultMarkerEnd:r==null?void 0:r.markerEnd}),[n,r,t,e]);return s.length?E.jsx("svg",{className:"react-flow__marker","aria-hidden":"true",children:E.jsx("defs",{children:s.map(o=>E.jsx(wm,{id:o.id,type:o.type,color:o.color,width:o.width,height:o.height,markerUnits:o.markerUnits,strokeWidth:o.strokeWidth,orient:o.orient},o.id))})}):null};aT.displayName="MarkerDefinitions";var Ym=f.memo(aT);function lT({x:e,y:t,label:n,labelStyle:r,labelShowBg:s=!0,labelBgStyle:o,labelBgPadding:i=[2,4],labelBgBorderRadius:a=2,children:T,className:l,...R}){const[c,A]=f.useState({x:1,y:0,width:0,height:0}),S=Ae(["react-flow__edge-textwrapper",l]),d=f.useRef(null);return f.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:[s&&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:o,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}lT.displayName="EdgeText";const Vm=f.memo(lT);function Ur({path:e,labelX:t,labelY:n,label:r,labelStyle:s,labelShowBg:o,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(Vm,{x:t,y:n,label:r,labelStyle:s,labelShowBg:o,labelBgStyle:i,labelBgPadding:a,labelBgBorderRadius:T}):null]})}function VE({pos:e,x1:t,y1:n,x2:r,y2:s}){return e===Z.Left||e===Z.Right?[.5*(t+r),n]:[t,.5*(n+s)]}function TT({sourceX:e,sourceY:t,sourcePosition:n=Z.Bottom,targetX:r,targetY:s,targetPosition:o=Z.Top}){const[i,a]=VE({pos:n,x1:e,y1:t,x2:r,y2:s}),[T,l]=VE({pos:o,x1:r,y1:s,x2:e,y2:t}),[R,c,A,S]=xl({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:i,sourceControlY:a,targetControlX:T,targetControlY:l});return[`M${e},${t} C${i},${a} ${T},${l} ${r},${s}`,R,c,A,S]}function cT(e){return f.memo(({id:t,sourceX:n,sourceY:r,targetX:s,targetY:o,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[C,N,_]=TT({sourceX:n,sourceY:r,sourcePosition:i,targetX:s,targetY:o,targetPosition:a}),m=e.isInternal?void 0:t;return E.jsx(Ur,{id:m,path:C,labelX:N,labelY:_,label:T,labelStyle:l,labelShowBg:R,labelBgStyle:c,labelBgPadding:A,labelBgBorderRadius:S,style:d,markerEnd:I,markerStart:O,interactionWidth:u})})}const Wm=cT({isInternal:!1}),RT=cT({isInternal:!0});Wm.displayName="SimpleBezierEdge";RT.displayName="SimpleBezierEdgeInternal";function AT(e){return f.memo(({id:t,sourceX:n,sourceY:r,targetX:s,targetY:o,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:C})=>{const[N,_,m]=Zs({sourceX:n,sourceY:r,sourcePosition:S,targetX:s,targetY:o,targetPosition:d,borderRadius:u==null?void 0:u.borderRadius,offset:u==null?void 0:u.offset,stepPosition:u==null?void 0:u.stepPosition}),h=e.isInternal?void 0:t;return E.jsx(Ur,{id:h,path:N,labelX:_,labelY:m,label:i,labelStyle:a,labelShowBg:T,labelBgStyle:l,labelBgPadding:R,labelBgBorderRadius:c,style:A,markerEnd:I,markerStart:O,interactionWidth:C})})}const ST=AT({isInternal:!1}),dT=AT({isInternal:!0});ST.displayName="SmoothStepEdge";dT.displayName="SmoothStepEdgeInternal";function IT(e){return f.memo(({id:t,...n})=>{var s;const r=e.isInternal?void 0:t;return E.jsx(ST,{...n,id:r,pathOptions:f.useMemo(()=>{var o;return{borderRadius:0,offset:(o=n.pathOptions)==null?void 0:o.offset}},[(s=n.pathOptions)==null?void 0:s.offset])})})}const km=IT({isInternal:!1}),uT=IT({isInternal:!0});km.displayName="StepEdge";uT.displayName="StepEdgeInternal";function NT(e){return f.memo(({id:t,sourceX:n,sourceY:r,targetX:s,targetY:o,label:i,labelStyle:a,labelShowBg:T,labelBgStyle:l,labelBgPadding:R,labelBgBorderRadius:c,style:A,markerEnd:S,markerStart:d,interactionWidth:I})=>{const[O,u,C]=Gl({sourceX:n,sourceY:r,targetX:s,targetY:o}),N=e.isInternal?void 0:t;return E.jsx(Ur,{id:N,path:O,labelX:u,labelY:C,label:i,labelStyle:a,labelShowBg:T,labelBgStyle:l,labelBgPadding:R,labelBgBorderRadius:c,style:A,markerEnd:S,markerStart:d,interactionWidth:I})})}const Xm=NT({isInternal:!1}),OT=NT({isInternal:!0});Xm.displayName="StraightEdge";OT.displayName="StraightEdgeInternal";function fT(e){return f.memo(({id:t,sourceX:n,sourceY:r,targetX:s,targetY:o,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:C})=>{const[N,_,m]=Ul({sourceX:n,sourceY:r,sourcePosition:i,targetX:s,targetY:o,targetPosition:a,curvature:u==null?void 0:u.curvature}),h=e.isInternal?void 0:t;return E.jsx(Ur,{id:h,path:N,labelX:_,labelY:m,label:T,labelStyle:l,labelShowBg:R,labelBgStyle:c,labelBgPadding:A,labelBgBorderRadius:S,style:d,markerEnd:I,markerStart:O,interactionWidth:C})})}const $m=fT({isInternal:!1}),CT=fT({isInternal:!0});$m.displayName="BezierEdge";CT.displayName="BezierEdgeInternal";const WE={default:CT,straight:OT,step:uT,smoothstep:dT,simplebezier:RT},kE={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},jm=(e,t,n)=>n===Z.Left?e-t:n===Z.Right?e+t:e,Km=(e,t,n)=>n===Z.Top?e-t:n===Z.Bottom?e+t:e,XE="react-flow__edgeupdater";function $E({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:s,onMouseEnter:o,onMouseOut:i,type:a}){return E.jsx("circle",{onMouseDown:s,onMouseEnter:o,onMouseOut:i,className:Ae([XE,`${XE}-${a}`]),cx:jm(t,r,e),cy:Km(n,r,e),r,stroke:"transparent",fill:"transparent"})}function Jm({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:r,sourceY:s,targetX:o,targetY:i,sourcePosition:a,targetPosition:T,onReconnect:l,onReconnectStart:R,onReconnectEnd:c,setReconnecting:A,setUpdateHover:S}){const d=ce(),I=(_,m)=>{if(_.button!==0)return;const{autoPanOnConnect:h,domNode:D,connectionMode:M,connectionRadius:B,lib:w,onConnectStart:P,cancelConnection:p,nodeLookup:U,rfId:L,panBy:x,updateConnection:g}=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(_,n,m.type),P==null||P(W,V)};to.onPointerDown(_.nativeEvent,{autoPanOnConnect:h,connectionMode:M,connectionRadius:B,domNode:D,handleId:m.id,nodeId:m.nodeId,nodeLookup:U,isTarget:v,edgeUpdaterType:m.type,lib:w,flowId:L,cancelConnection:p,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:g,getTransform:()=>d.getState().transform,getFromHandle:()=>d.getState().connection.fromHandle,dragThreshold:d.getState().connectionDragThreshold,handleDomNode:_.currentTarget})},O=_=>I(_,{nodeId:n.target,id:n.targetHandle??null,type:"target"}),u=_=>I(_,{nodeId:n.source,id:n.sourceHandle??null,type:"source"}),C=()=>S(!0),N=()=>S(!1);return E.jsxs(E.Fragment,{children:[(e===!0||e==="source")&&E.jsx($E,{position:a,centerX:r,centerY:s,radius:t,onMouseDown:O,onMouseEnter:C,onMouseOut:N,type:"source"}),(e===!0||e==="target")&&E.jsx($E,{position:T,centerX:o,centerY:i,radius:t,onMouseDown:u,onMouseEnter:C,onMouseOut:N,type:"target"})]})}function zm({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:r,onClick:s,onDoubleClick:o,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:C}){let N=se(z=>z.edgeLookup.get(e));const _=se(z=>z.defaultEdgeOptions);N=_?{..._,...N}:N;let m=N.type||"default",h=(I==null?void 0:I[m])||WE[m];h===void 0&&(u==null||u("011",we.error011(m)),m="default",h=(I==null?void 0:I.default)||WE.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"),w=f.useRef(null),[P,p]=f.useState(!1),[U,L]=f.useState(!1),x=ce(),{zIndex:g,sourceX:v,sourceY:b,targetX:y,targetY:Y,sourcePosition:W,targetPosition:V}=se(f.useCallback(z=>{const te=z.nodeLookup.get(N.source),ie=z.nodeLookup.get(N.target);if(!te||!ie)return{zIndex:N.zIndex,...kE};const le=Yh({id:e,sourceNode:te,targetNode:ie,sourceHandle:N.sourceHandle||null,targetHandle:N.targetHandle||null,connectionMode:z.connectionMode,onError:u});return{zIndex:Uh({selected:N.selected,zIndex:N.zIndex,sourceNode:te,targetNode:ie,elevateOnSelect:z.elevateEdgesOnSelect,zIndexMode:z.zIndexMode}),...le||kE}},[N.source,N.target,N.sourceHandle,N.targetHandle,N.selected,N.zIndex]),Te),k=f.useMemo(()=>N.markerStart?`url('#${Qs(N.markerStart,d)}')`:void 0,[N.markerStart,d]),X=f.useMemo(()=>N.markerEnd?`url('#${Qs(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 oe;const{addSelectedEdges:te,unselectNodesAndEdges:ie,multiSelectionActive:le}=x.getState();B&&(x.setState({nodesSelectionActive:!1}),N.selected&&le?(ie({nodes:[],edges:[N]}),(oe=w.current)==null||oe.blur()):te([e])),s&&s(z,N)},Q=o?z=>{o(z,{...N})}:void 0,$=i?z=>{i(z,{...N})}:void 0,j=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(!C&&Nl.includes(z.key)&&B){const{unselectNodesAndEdges:ie,addSelectedEdges:le}=x.getState();z.key==="Escape"?((te=w.current)==null||te.blur(),ie({edges:[N]})):le([e])}};return E.jsx("svg",{style:{zIndex:g},children:E.jsxs("g",{className:Ae(["react-flow__edge",`react-flow__edge-${m}`,N.className,O,{selected:N.selected,animated:N.animated,inactive:!B&&!s,updating:P,selectable:B}]),onClick:K,onDoubleClick:Q,onContextMenu:$,onMouseEnter:j,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:w,...N.domAttributes,children:[!U&&E.jsx(h,{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(Jm,{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:p,setReconnecting:L})]})})}var qm=f.memo(zm);const Zm=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function LT({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:r,noPanClassName:s,onReconnect:o,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:C,onError:N}=se(Zm,Te),_=Bm(t);return E.jsxs("div",{className:"react-flow__edges",children:[E.jsx(Ym,{defaultColor:e,rfId:n}),_.map(m=>E.jsx(qm,{id:m,edgesFocusable:O,edgesReconnectable:u,elementsSelectable:C,noPanClassName:s,onReconnect:o,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))]})}LT.displayName="EdgeRenderer";const Qm=f.memo(LT),eD=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function tD({children:e}){const t=se(eD);return E.jsx("div",{className:"react-flow__viewport xyflow__viewport react-flow__container",style:{transform:t},children:e})}function nD(e){const t=xo(),n=f.useRef(!1);f.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const rD=e=>{var t;return(t=e.panZoom)==null?void 0:t.syncViewport};function sD(e){const t=se(rD),n=ce();return f.useEffect(()=>{e&&(t==null||t(e),n.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function oD(e){return e.connection.inProgress?{...e.connection,to:mn(e.connection.to,e.transform)}:{...e.connection}}function iD(e){return oD}function ED(e){const t=iD();return se(t,Te)}const aD=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function lD({containerStyle:e,style:t,type:n,component:r}){const{nodesConnectable:s,width:o,height:i,isValid:a,inProgress:T}=se(aD,Te);return!(o&&s&&T)?null:E.jsx("svg",{style:e,width:o,height:i,className:"react-flow__connectionline react-flow__container",children:E.jsx("g",{className:Ae(["react-flow__connection",Cl(a)]),children:E.jsx(_T,{style:t,type:n,CustomComponent:r,isValid:a})})})}const _T=({style:e,type:t=et.Bezier,CustomComponent:n,isValid:r})=>{const{inProgress:s,from:o,fromNode:i,fromHandle:a,fromPosition:T,to:l,toNode:R,toHandle:c,toPosition:A,pointer:S}=ED();if(!s)return;if(n)return E.jsx(n,{connectionLineType:t,connectionLineStyle:e,fromNode:i,fromHandle:a,fromX:o.x,fromY:o.y,toX:l.x,toY:l.y,fromPosition:T,toPosition:A,connectionStatus:Cl(r),toNode:R,toHandle:c,pointer:S});let d="";const I={sourceX:o.x,sourceY:o.y,sourcePosition:T,targetX:l.x,targetY:l.y,targetPosition:A};switch(t){case et.Bezier:[d]=Ul(I);break;case et.SimpleBezier:[d]=TT(I);break;case et.Step:[d]=Zs({...I,borderRadius:0});break;case et.SmoothStep:[d]=Zs(I);break;default:[d]=Gl(I)}return E.jsx("path",{d,fill:"none",className:"react-flow__connection-path",style:e})};_T.displayName="ConnectionLine";const TD={};function jE(e=TD){f.useRef(e),ce(),f.useEffect(()=>{},[e])}function cD(){ce(),f.useRef(!1),f.useEffect(()=>{},[])}function hT({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:r,onEdgeClick:s,onNodeDoubleClick:o,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:C,selectionOnDrag:N,selectionMode:_,multiSelectionKeyCode:m,panActivationKeyCode:h,zoomActivationKeyCode:D,deleteKeyCode:M,onlyRenderVisibleElements:B,elementsSelectable:w,defaultViewport:P,translateExtent:p,minZoom:U,maxZoom:L,preventScrolling:x,defaultMarkerColor:g,zoomOnScroll:v,zoomOnPinch:b,panOnScroll:y,panOnScrollSpeed:Y,panOnScrollMode:W,zoomOnDoubleClick:V,panOnDrag:k,onPaneClick:X,onPaneMouseEnter:K,onPaneMouseMove:Q,onPaneMouseLeave:$,onPaneScroll:j,onPaneContextMenu:ee,paneClickDistance:re,nodeClickDistance:q,onEdgeContextMenu:z,onEdgeMouseEnter:te,onEdgeMouseMove:ie,onEdgeMouseLeave:le,reconnectRadius:oe,onReconnect:Ne,onReconnectStart:qe,onReconnectEnd:Ve,noDragClassName:it,noWheelClassName:Yt,noPanClassName:Vt,disableKeyboardA11y:Wt,nodeExtent:Br,rfId:gn,viewport:Ot,onViewportChange:kt}){return jE(e),jE(t),cD(),nD(n),sD(Ot),E.jsx(mm,{onPaneClick:X,onPaneMouseEnter:K,onPaneMouseMove:Q,onPaneMouseLeave:$,onPaneContextMenu:ee,onPaneScroll:j,paneClickDistance:re,deleteKeyCode:M,selectionKeyCode:C,selectionOnDrag:N,selectionMode:_,onSelectionStart:A,onSelectionEnd:S,multiSelectionKeyCode:m,panActivationKeyCode:h,zoomActivationKeyCode:D,elementsSelectable:w,zoomOnScroll:v,zoomOnPinch:b,zoomOnDoubleClick:V,panOnScroll:y,panOnScrollSpeed:Y,panOnScrollMode:W,panOnDrag:k,defaultViewport:P,translateExtent:p,minZoom:U,maxZoom:L,onSelectionContextMenu:c,preventScrolling:x,noDragClassName:it,noWheelClassName:Yt,noPanClassName:Vt,disableKeyboardA11y:Wt,onViewportChange:kt,isControlledViewport:!!Ot,children:E.jsxs(tD,{children:[E.jsx(Qm,{edgeTypes:t,onEdgeClick:s,onEdgeDoubleClick:i,onReconnect:Ne,onReconnectStart:qe,onReconnectEnd:Ve,onlyRenderVisibleElements:B,onEdgeContextMenu:z,onEdgeMouseEnter:te,onEdgeMouseMove:ie,onEdgeMouseLeave:le,reconnectRadius:oe,defaultMarkerColor:g,noPanClassName:Vt,disableKeyboardA11y:Wt,rfId:gn}),E.jsx(lD,{style:I,type:d,component:O,containerStyle:u}),E.jsx("div",{className:"react-flow__edgelabel-renderer"}),E.jsx(Gm,{nodeTypes:e,onNodeClick:r,onNodeDoubleClick:o,onNodeMouseEnter:a,onNodeMouseMove:T,onNodeMouseLeave:l,onNodeContextMenu:R,nodeClickDistance:q,onlyRenderVisibleElements:B,noPanClassName:Vt,noDragClassName:it,disableKeyboardA11y:Wt,nodeExtent:Br,rfId:gn}),E.jsx("div",{className:"react-flow__viewport-portal"})]})})}hT.displayName="GraphView";const RD=f.memo(hT),KE=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:s,height:o,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??[],C=n??e??[],N=R??[0,0],_=c??An;Hl(I,O,u);const m=eo(C,S,d,{nodeOrigin:N,nodeExtent:_,zIndexMode:A});let h=[0,0,1];if(i&&s&&o){const D=hn(S,{filter:P=>!!((P.width||P.initialWidth)&&(P.height||P.initialHeight))}),{x:M,y:B,zoom:w}=po(D,s,o,T,l,(a==null?void 0:a.padding)??.1);h=[M,B,w]}return{rfId:"1",width:s??0,height:o??0,transform:h,nodes:C,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:_,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:{...fl},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:Dh,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:"react",debug:!1,ariaLabelConfig:Ol,zIndexMode:A,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}},AD=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:s,height:o,fitView:i,fitViewOptions:a,minZoom:T,maxZoom:l,nodeOrigin:R,nodeExtent:c,zIndexMode:A})=>yp((S,d)=>{async function I(){const{nodeLookup:O,panZoom:u,fitViewOptions:C,fitViewResolver:N,width:_,height:m,minZoom:h,maxZoom:D}=d();u&&(await ph({nodes:O,width:_,height:m,panZoom:u,minZoom:h,maxZoom:D},C),N==null||N.resolve(!0),S({fitViewResolver:null}))}return{...KE({nodes:e,edges:t,width:s,height:o,fitView:i,fitViewOptions:a,minZoom:T,maxZoom:l,nodeOrigin:R,nodeExtent:c,defaultNodes:n,defaultEdges:r,zIndexMode:A}),setNodes:O=>{const{nodeLookup:u,parentLookup:C,nodeOrigin:N,elevateNodesOnSelect:_,fitViewQueued:m,zIndexMode:h}=d(),D=eo(O,u,C,{nodeOrigin:N,nodeExtent:c,elevateNodesOnSelect:_,checkEquality:!0,zIndexMode:h});m&&D?(I(),S({nodes:O,nodesInitialized:D,fitViewQueued:!1,fitViewOptions:void 0})):S({nodes:O,nodesInitialized:D})},setEdges:O=>{const{connectionLookup:u,edgeLookup:C}=d();Hl(u,C,O),S({edges:O})},setDefaultNodesAndEdges:(O,u)=>{if(O){const{setNodes:C}=d();C(O),S({hasDefaultNodes:!0})}if(u){const{setEdges:C}=d();C(u),S({hasDefaultEdges:!0})}},updateNodeInternals:O=>{const{triggerNodeChanges:u,nodeLookup:C,parentLookup:N,domNode:_,nodeOrigin:m,nodeExtent:h,debug:D,fitViewQueued:M,zIndexMode:B}=d(),{changes:w,updatedInternals:P}=Jh(O,C,N,_,m,h,B);P&&(Xh(C,N,{nodeOrigin:m,nodeExtent:h,zIndexMode:B}),M?(I(),S({fitViewQueued:!1,fitViewOptions:void 0})):S({}),(w==null?void 0:w.length)>0&&(D&&console.log("React Flow: trigger node changes",w),u==null||u(w)))},updateNodePositions:(O,u=!1)=>{const C=[];let N=[];const{nodeLookup:_,triggerNodeChanges:m,connection:h,updateConnection:D,onNodesChangeMiddlewareMap:M}=d();for(const[B,w]of O){const P=_.get(B),p=!!(P!=null&&P.expandParent&&(P!=null&&P.parentId)&&(w!=null&&w.position)),U={id:B,type:"position",position:p?{x:Math.max(0,w.position.x),y:Math.max(0,w.position.y)}:w.position,dragging:u};if(P&&h.inProgress&&h.fromNode.id===P.id){const L=dt(P,h.fromHandle,Z.Left,!0);D({...h,from:L})}p&&P.parentId&&C.push({id:B,parentId:P.parentId,rect:{...w.internals.positionAbsolute,width:w.measured.width??0,height:w.measured.height??0}}),N.push(U)}if(C.length>0){const{parentLookup:B,nodeOrigin:w}=d(),P=yo(C,_,B,w);N.push(...P)}for(const B of M.values())N=B(N);m(N)},triggerNodeChanges:O=>{const{onNodesChange:u,setNodes:C,nodes:N,hasDefaultNodes:_,debug:m}=d();if(O!=null&&O.length){if(_){const h=Ql(O,N);C(h)}m&&console.log("React Flow: trigger node changes",O),u==null||u(O)}},triggerEdgeChanges:O=>{const{onEdgesChange:u,setEdges:C,edges:N,hasDefaultEdges:_,debug:m}=d();if(O!=null&&O.length){if(_){const h=eT(O,N);C(h)}m&&console.log("React Flow: trigger edge changes",O),u==null||u(O)}},addSelectedNodes:O=>{const{multiSelectionActive:u,edgeLookup:C,nodeLookup:N,triggerNodeChanges:_,triggerEdgeChanges:m}=d();if(u){const h=O.map(D=>at(D,!0));_(h);return}_(mt(N,new Set([...O]),!0)),m(mt(C))},addSelectedEdges:O=>{const{multiSelectionActive:u,edgeLookup:C,nodeLookup:N,triggerNodeChanges:_,triggerEdgeChanges:m}=d();if(u){const h=O.map(D=>at(D,!0));m(h);return}m(mt(C,new Set([...O]))),_(mt(N,new Set,!0))},unselectNodesAndEdges:({nodes:O,edges:u}={})=>{const{edges:C,nodes:N,nodeLookup:_,triggerNodeChanges:m,triggerEdgeChanges:h}=d(),D=O||N,M=u||C,B=[];for(const P of D){if(!P.selected)continue;const p=_.get(P.id);p&&(p.selected=!1),B.push(at(P.id,!1))}const w=[];for(const P of M)P.selected&&w.push(at(P.id,!1));m(B),h(w)},setMinZoom:O=>{const{panZoom:u,maxZoom:C}=d();u==null||u.setScaleExtent([O,C]),S({minZoom:O})},setMaxZoom:O=>{const{panZoom:u,minZoom:C}=d();u==null||u.setScaleExtent([C,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:C,triggerEdgeChanges:N,elementsSelectable:_}=d();if(!_)return;const m=u.reduce((D,M)=>M.selected?[...D,at(M.id,!1)]:D,[]),h=O.reduce((D,M)=>M.selected?[...D,at(M.id,!1)]:D,[]);C(m),N(h)},setNodeExtent:O=>{const{nodes:u,nodeLookup:C,parentLookup:N,nodeOrigin:_,elevateNodesOnSelect:m,nodeExtent:h,zIndexMode:D}=d();O[0][0]===h[0][0]&&O[0][1]===h[0][1]&&O[1][0]===h[1][0]&&O[1][1]===h[1][1]||(eo(u,C,N,{nodeOrigin:_,nodeExtent:O,elevateNodesOnSelect:m,checkEquality:!1,zIndexMode:D}),S({nodeExtent:O}))},panBy:O=>{const{transform:u,width:C,height:N,panZoom:_,translateExtent:m}=d();return zh({delta:O,panZoom:_,transform:u,translateExtent:m,width:C,height:N})},setCenter:async(O,u,C)=>{const{width:N,height:_,maxZoom:m,panZoom:h}=d();if(!h)return Promise.resolve(!1);const D=typeof(C==null?void 0:C.zoom)<"u"?C.zoom:m;return await h.setViewport({x:N/2-O*D,y:_/2-u*D,zoom:D},{duration:C==null?void 0:C.duration,ease:C==null?void 0:C.ease,interpolate:C==null?void 0:C.interpolate}),Promise.resolve(!0)},cancelConnection:()=>{S({connection:{...fl}})},updateConnection:O=>{S({connection:O})},reset:()=>S({...KE()})}},Object.is);function SD({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:r,initialWidth:s,initialHeight:o,initialMinZoom:i,initialMaxZoom:a,initialFitViewOptions:T,fitView:l,nodeOrigin:R,nodeExtent:c,zIndexMode:A,children:S}){const[d]=f.useState(()=>AD({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:s,height:o,fitView:l,minZoom:i,maxZoom:a,fitViewOptions:T,nodeOrigin:R,nodeExtent:c,zIndexMode:A}));return E.jsx(xp,{value:d,children:E.jsx(tm,{children:S})})}function dD({children:e,nodes:t,edges:n,defaultNodes:r,defaultEdges:s,width:o,height:i,fitView:a,fitViewOptions:T,minZoom:l,maxZoom:R,nodeOrigin:c,nodeExtent:A,zIndexMode:S}){return f.useContext(yr)?E.jsx(E.Fragment,{children:e}):E.jsx(SD,{initialNodes:t,initialEdges:n,defaultNodes:r,defaultEdges:s,initialWidth:o,initialHeight:i,fitView:a,initialFitViewOptions:T,initialMinZoom:l,initialMaxZoom:R,nodeOrigin:c,nodeExtent:A,zIndexMode:S,children:e})}const ID={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0};function uD({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:s,nodeTypes:o,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:C,onNodeMouseMove:N,onNodeMouseLeave:_,onNodeContextMenu:m,onNodeDoubleClick:h,onNodeDragStart:D,onNodeDrag:M,onNodeDragStop:B,onNodesDelete:w,onEdgesDelete:P,onDelete:p,onSelectionChange:U,onSelectionDragStart:L,onSelectionDrag:x,onSelectionDragStop:g,onSelectionContextMenu:v,onSelectionStart:b,onSelectionEnd:y,onBeforeDelete:Y,connectionMode:W,connectionLineType:V=et.Bezier,connectionLineStyle:k,connectionLineComponent:X,connectionLineContainerStyle:K,deleteKeyCode:Q="Backspace",selectionKeyCode:$="Shift",selectionOnDrag:j=!1,selectionMode:ee=Sn.Full,panActivationKeyCode:re="Space",multiSelectionKeyCode:q=un()?"Meta":"Control",zoomActivationKeyCode:z=un()?"Meta":"Control",snapToGrid:te,snapGrid:ie,onlyRenderVisibleElements:le=!1,selectNodesOnDrag:oe,nodesDraggable:Ne,autoPanOnNodeFocus:qe,nodesConnectable:Ve,nodesFocusable:it,nodeOrigin:Yt=ql,edgesFocusable:Vt,edgesReconnectable:Wt,elementsSelectable:Br=!0,defaultViewport:gn=Xp,minZoom:Ot=.5,maxZoom:kt=2,translateExtent:Fo=An,preventScrolling:tc=!0,nodeExtent:vr,defaultMarkerColor:nc="#b1b1b7",zoomOnScroll:rc=!0,zoomOnPinch:sc=!0,panOnScroll:oc=!1,panOnScrollSpeed:ic=.5,panOnScrollMode:Ec=ct.Free,zoomOnDoubleClick:ac=!0,panOnDrag:lc=!0,onPaneClick:Tc,onPaneMouseEnter:cc,onPaneMouseMove:Rc,onPaneMouseLeave:Ac,onPaneScroll:Sc,onPaneContextMenu:dc,paneClickDistance:Ic=1,nodeClickDistance:uc=0,children:Nc,onReconnect:Oc,onReconnectStart:fc,onReconnectEnd:Cc,onEdgeContextMenu:Lc,onEdgeDoubleClick:_c,onEdgeMouseEnter:hc,onEdgeMouseMove:pc,onEdgeMouseLeave:mc,reconnectRadius:Dc=10,onNodesChange:Pc,onEdgesChange:gc,noDragClassName:Mc="nodrag",noWheelClassName:yc="nowheel",noPanClassName:wo="nopan",fitView:Yo,fitViewOptions:Vo,connectOnClick:xc,attributionPosition:Uc,proOptions:bc,defaultEdgeOptions:Gc,elevateNodesOnSelect:Bc=!0,elevateEdgesOnSelect:vc=!1,disableKeyboardA11y:Wo=!1,autoPanOnConnect:Hc,autoPanOnNodeDrag:Fc,autoPanSpeed:wc,connectionRadius:Yc,isValidConnection:Vc,onError:Wc,style:kc,id:ko,nodeDragThreshold:Xc,connectionDragThreshold:$c,viewport:jc,onViewportChange:Kc,width:Jc,height:zc,colorMode:qc="light",debug:Zc,onScroll:Mn,ariaLabelConfig:Qc,zIndexMode:Xo="basic",...eR},tR){const Hr=ko||"1",nR=Jp(qc),rR=f.useCallback($o=>{$o.currentTarget.scrollTo({top:0,left:0,behavior:"instant"}),Mn==null||Mn($o)},[Mn]);return E.jsx("div",{"data-testid":"rf__wrapper",...eR,onScroll:rR,style:{...kc,...ID},ref:tR,className:Ae(["react-flow",s,nR]),id:ko,role:"application",children:E.jsxs(dD,{nodes:e,edges:t,width:Jc,height:zc,fitView:Yo,fitViewOptions:Vo,minZoom:Ot,maxZoom:kt,nodeOrigin:Yt,nodeExtent:vr,zIndexMode:Xo,children:[E.jsx(RD,{onInit:l,onNodeClick:a,onEdgeClick:T,onNodeMouseEnter:C,onNodeMouseMove:N,onNodeMouseLeave:_,onNodeContextMenu:m,onNodeDoubleClick:h,nodeTypes:o,edgeTypes:i,connectionLineType:V,connectionLineStyle:k,connectionLineComponent:X,connectionLineContainerStyle:K,selectionKeyCode:$,selectionOnDrag:j,selectionMode:ee,deleteKeyCode:Q,multiSelectionKeyCode:q,panActivationKeyCode:re,zoomActivationKeyCode:z,onlyRenderVisibleElements:le,defaultViewport:gn,translateExtent:Fo,minZoom:Ot,maxZoom:kt,preventScrolling:tc,zoomOnScroll:rc,zoomOnPinch:sc,zoomOnDoubleClick:ac,panOnScroll:oc,panOnScrollSpeed:ic,panOnScrollMode:Ec,panOnDrag:lc,onPaneClick:Tc,onPaneMouseEnter:cc,onPaneMouseMove:Rc,onPaneMouseLeave:Ac,onPaneScroll:Sc,onPaneContextMenu:dc,paneClickDistance:Ic,nodeClickDistance:uc,onSelectionContextMenu:v,onSelectionStart:b,onSelectionEnd:y,onReconnect:Oc,onReconnectStart:fc,onReconnectEnd:Cc,onEdgeContextMenu:Lc,onEdgeDoubleClick:_c,onEdgeMouseEnter:hc,onEdgeMouseMove:pc,onEdgeMouseLeave:mc,reconnectRadius:Dc,defaultMarkerColor:nc,noDragClassName:Mc,noWheelClassName:yc,noPanClassName:wo,rfId:Hr,disableKeyboardA11y:Wo,nodeExtent:vr,viewport:jc,onViewportChange:Kc}),E.jsx(Kp,{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:Bc,elevateEdgesOnSelect:vc,minZoom:Ot,maxZoom:kt,nodeExtent:vr,onNodesChange:Pc,onEdgesChange:gc,snapToGrid:te,snapGrid:ie,connectionMode:W,translateExtent:Fo,connectOnClick:xc,defaultEdgeOptions:Gc,fitView:Yo,fitViewOptions:Vo,onNodesDelete:w,onEdgesDelete:P,onDelete:p,onNodeDragStart:D,onNodeDrag:M,onNodeDragStop:B,onSelectionDrag:x,onSelectionDragStart:L,onSelectionDragStop:g,onMove:R,onMoveStart:c,onMoveEnd:A,noPanClassName:wo,nodeOrigin:Yt,rfId:Hr,autoPanOnConnect:Hc,autoPanOnNodeDrag:Fc,autoPanSpeed:wc,onError:Wc,connectionRadius:Yc,isValidConnection:Vc,selectNodesOnDrag:oe,nodeDragThreshold:Xc,connectionDragThreshold:$c,onBeforeDelete:Y,debug:Zc,ariaLabelConfig:Qc,zIndexMode:Xo}),E.jsx(kp,{onSelectionChange:U}),Nc,E.jsx(Fp,{proOptions:bc,position:Uc}),E.jsx(Hp,{rfId:Hr,disableKeyboardA11y:Wo})]})})}var ND=tT(uD);function OD(e){const[t,n]=f.useState(e),r=f.useCallback(s=>n(o=>Ql(s,o)),[]);return[t,n,r]}function fD(e){const[t,n]=f.useState(e),r=f.useCallback(s=>n(o=>eT(s,o)),[]);return[t,n,r]}function CD({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 LD({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 _D={[rt.Dots]:1,[rt.Lines]:1,[rt.Cross]:6},hD=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function pT({id:e,variant:t=rt.Dots,gap:n=20,size:r,lineWidth:s=1,offset:o=0,color:i,bgColor:a,style:T,className:l,patternClassName:R}){const c=f.useRef(null),{transform:A,patternId:S}=se(hD,Te),d=r||_D[t],I=t===rt.Dots,O=t===rt.Cross,u=Array.isArray(n)?n:[n,n],C=[u[0]*A[2]||1,u[1]*A[2]||1],N=d*A[2],_=Array.isArray(o)?o:[o,o],m=O?[N,N]:C,h=[_[0]*A[2]||1+m[0]/2,_[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]%C[0],y:A[1]%C[1],width:C[0],height:C[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${h[0]},-${h[1]})`,children:I?E.jsx(LD,{radius:N/2,className:R}):E.jsx(CD,{dimensions:m,lineWidth:s,variant:t,className:R})}),E.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${D})`})]})}pT.displayName="Background";const pD=f.memo(pT);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 DD(){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 PD(){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 gD(){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 MD(){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 yD=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function mT({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:s,onZoomIn:o,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:C}=se(yD,Te),{zoomIn:N,zoomOut:_,fitView:m}=xo(),h=()=>{N(),o==null||o()},D=()=>{_(),i==null||i()},M=()=>{m(s),a==null||a()},B=()=>{d.setState({nodesDraggable:!I,nodesConnectable:!I,elementsSelectable:!I}),T==null||T(!I)},w=A==="horizontal"?"horizontal":"vertical";return E.jsxs(Dn,{className:Ae(["react-flow__controls",w,l]),position:c,style:e,"data-testid":"rf__controls","aria-label":S??C["controls.ariaLabel"],children:[t&&E.jsxs(E.Fragment,{children:[E.jsx(kn,{onClick:h,className:"react-flow__controls-zoomin",title:C["controls.zoomIn.ariaLabel"],"aria-label":C["controls.zoomIn.ariaLabel"],disabled:u,children:E.jsx(mD,{})}),E.jsx(kn,{onClick:D,className:"react-flow__controls-zoomout",title:C["controls.zoomOut.ariaLabel"],"aria-label":C["controls.zoomOut.ariaLabel"],disabled:O,children:E.jsx(DD,{})})]}),n&&E.jsx(kn,{className:"react-flow__controls-fitview",onClick:M,title:C["controls.fitView.ariaLabel"],"aria-label":C["controls.fitView.ariaLabel"],children:E.jsx(PD,{})}),r&&E.jsx(kn,{className:"react-flow__controls-interactive",onClick:B,title:C["controls.interactive.ariaLabel"],"aria-label":C["controls.interactive.ariaLabel"],children:I?E.jsx(MD,{}):E.jsx(gD,{})}),R]})}mT.displayName="Controls";const xD=f.memo(mT);function UD({id:e,x:t,y:n,width:r,height:s,style:o,color:i,strokeColor:a,strokeWidth:T,className:l,borderRadius:R,shapeRendering:c,selected:A,onClick:S}){const{background:d,backgroundColor:I}=o||{},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:s,style:{fill:O,stroke:a,strokeWidth:T},shapeRendering:c,onClick:S?u=>S(u,e):void 0})}const bD=f.memo(UD),GD=e=>e.nodes.map(t=>t.id),Ms=e=>e instanceof Function?e:()=>e;function BD({nodeStrokeColor:e,nodeColor:t,nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:s,nodeComponent:o=bD,onClick:i}){const a=se(GD,Te),T=Ms(t),l=Ms(e),R=Ms(n),c=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return E.jsx(E.Fragment,{children:a.map(A=>E.jsx(HD,{id:A,nodeColorFunc:T,nodeStrokeColorFunc:l,nodeClassNameFunc:R,nodeBorderRadius:r,nodeStrokeWidth:s,NodeComponent:o,onClick:i,shapeRendering:c},A))})}function vD({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:r,nodeBorderRadius:s,nodeStrokeWidth:o,shapeRendering:i,NodeComponent:a,onClick:T}){const{node:l,x:R,y:c,width:A,height:S}=se(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:C}=I.internals.positionAbsolute,{width:N,height:_}=ze(O);return{node:O,x:u,y:C,width:N,height:_}},Te);return!l||l.hidden||!Dl(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:s,strokeColor:n(l),strokeWidth:o,shapeRendering:i,onClick:T,id:l.id})}const HD=f.memo(vD);var FD=f.memo(BD);const wD=200,YD=150,VD=e=>!e.hidden,WD=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?ml(hn(e.nodeLookup,{filter:VD}),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 DT({style:e,className:t,nodeStrokeColor:n,nodeColor:r,nodeClassName:s="",nodeBorderRadius:o=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:C,zoomStep:N=1,offsetScale:_=5}){const m=ce(),h=f.useRef(null),{boundingRect:D,viewBB:M,rfId:B,panZoom:w,translateExtent:P,flowWidth:p,flowHeight:U,ariaLabelConfig:L}=se(WD,Te),x=(e==null?void 0:e.width)??wD,g=(e==null?void 0:e.height)??YD,v=D.width/x,b=D.height/g,y=Math.max(v,b),Y=y*x,W=y*g,V=_*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,$=`${kD}-${B}`,j=f.useRef(0),ee=f.useRef();j.current=y,f.useEffect(()=>{if(h.current&&w)return ee.current=op({domNode:h.current,panZoom:w,getTransform:()=>m.getState().transform,getViewScale:()=>j.current}),()=>{var te;(te=ee.current)==null||te.destroy()}},[w]),f.useEffect(()=>{var te;(te=ee.current)==null||te.update({translateExtent:P,width:p,height:U,inversePan:C,pannable:I,zoomStep:N,zoomable:O})},[I,O,C,N,P,p,U]);const re=S?te=>{var oe;const[ie,le]=((oe=ee.current)==null?void 0:oe.pointer(te))||[0,0];S(te,{x:ie,y:le})}:void 0,q=d?f.useCallback((te,ie)=>{const le=m.getState().nodeLookup.get(ie).internals.userNode;d(te,le)},[]):void 0,z=u??L["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:g,viewBox:`${k} ${X} ${K} ${Q}`,className:"react-flow__minimap-svg",role:"img","aria-labelledby":$,ref:h,onClick:re,children:[z&&E.jsx("title",{id:$,children:z}),E.jsx(FD,{onClick:q,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:o,nodeClassName:s,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
|
|
511
|
+
M${M.x},${M.y}h${M.width}v${M.height}h${-M.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}DT.displayName="MiniMap";const XD=f.memo(DT),$D=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,jD={[Bt.Line]:"right",[Bt.Handle]:"bottom-right"};function KD({nodeId:e,position:t,variant:n=Bt.Handle,className:r,style:s=void 0,children:o,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 C=oT(),N=typeof e=="string"?e:C,_=ce(),m=f.useRef(null),h=n===Bt.Handle,D=se(f.useCallback($D(h&&S),[h,S]),Te),M=f.useRef(null),B=t??jD[n];f.useEffect(()=>{if(!(!m.current||!N))return M.current||(M.current=Op({domNode:m.current,nodeId:N,getStoreItems:()=>{const{nodeLookup:P,transform:p,snapGrid:U,snapToGrid:L,nodeOrigin:x,domNode:g}=_.getState();return{nodeLookup:P,transform:p,snapGrid:U,snapToGrid:L,nodeOrigin:x,paneDomNode:g}},onChange:(P,p)=>{const{triggerNodeChanges:U,nodeLookup:L,parentLookup:x,nodeOrigin:g}=_.getState(),v=[],b={x:P.x,y:P.y},y=L.get(N);if(y&&y.expandParent&&y.parentId){const Y=y.origin??g,W=P.width??y.measured.width??0,V=P.height??y.measured.height??0,k={id:y.id,parentId:y.parentId,rect:{width:W,height:V,...Pl({x:P.x??y.position.x,y:P.y??y.position.y},{width:W,height:V},y.parentId,L,Y)}},X=yo([k],L,x,g);v.push(...X),b.x=P.x?Math.max(Y[0]*W,P.x):void 0,b.y=P.y?Math.max(Y[1]*V,P.y):void 0}if(b.x!==void 0&&b.y!==void 0){const Y={id:N,type:"position",position:{...b}};v.push(Y)}if(P.width!==void 0&&P.height!==void 0){const W={id:N,type:"dimensions",resizing:!0,setAttributes:A?A==="horizontal"?"width":"height":!0,dimensions:{width:P.width,height:P.height}};v.push(W)}for(const Y of p){const W={...Y,type:"position"};v.push(W)}U(v)},onEnd:({width:P,height:p})=>{const U={id:N,type:"dimensions",resizing:!1,dimensions:{width:P,height:p}};_.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 P;(P=M.current)==null||P.destroy()}},[B,a,T,l,R,c,I,O,u,d]);const w=B.split("-");return E.jsx("div",{className:Ae(["react-flow__resize-control","nodrag",...w,n,r]),ref:m,style:{...s,scale:D,...i&&{[h?"backgroundColor":"borderColor"]:i}},children:o})}f.memo(KD);var PT=Object.defineProperty,JD=(e,t,n)=>t in e?PT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,zD=(e,t)=>{for(var n in t)PT(e,n,{get:t[n],enumerable:!0})},qD=(e,t,n)=>JD(e,t+"",n),gT={};zD(gT,{Graph:()=>Pe,alg:()=>bo,json:()=>yT,version:()=>eP});var ZD=Object.defineProperty,MT=(e,t)=>{for(var n in t)ZD(e,n,{get:t[n],enumerable:!0})},Pe=class{constructor(e){this._isDirected=!0,this._isMultigraph=!1,this._isCompound=!1,this._nodes={},this._in={},this._preds={},this._out={},this._sucs={},this._edgeObjs={},this._edgeLabels={},this._nodeCount=0,this._edgeCount=0,this._defaultNodeLabelFn=()=>{},this._defaultEdgeLabelFn=()=>{},e&&(this._isDirected="directed"in e?e.directed:!0,this._isMultigraph="multigraph"in e?e.multigraph:!1,this._isCompound="compound"in e?e.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children["\0"]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(e){return this._label=e,this}graph(){return this._label}setDefaultNodeLabel(e){return typeof e!="function"?this._defaultNodeLabelFn=()=>e:this._defaultNodeLabelFn=e,this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){return this.nodes().filter(e=>Object.keys(this._in[e]).length===0)}sinks(){return this.nodes().filter(e=>Object.keys(this._out[e]).length===0)}setNodes(e,t){return e.forEach(n=>{t!==void 0?this.setNode(n,t):this.setNode(n)}),this}setNode(e,t){return e in this._nodes?(arguments.length>1&&(this._nodes[e]=t),this):(this._nodes[e]=arguments.length>1?t:this._defaultNodeLabelFn(e),this._isCompound&&(this._parent[e]="\0",this._children[e]={},this._children["\0"][e]=!0),this._in[e]={},this._preds[e]={},this._out[e]={},this._sucs[e]={},++this._nodeCount,this)}node(e){return this._nodes[e]}hasNode(e){return e in this._nodes}removeNode(e){if(e in this._nodes){let t=n=>this.removeEdge(this._edgeObjs[n]);delete this._nodes[e],this._isCompound&&(this._removeFromParentsChildList(e),delete this._parent[e],this.children(e).forEach(n=>{this.setParent(n)}),delete this._children[e]),Object.keys(this._in[e]).forEach(t),delete this._in[e],delete this._preds[e],Object.keys(this._out[e]).forEach(t),delete this._out[e],delete this._sucs[e],--this._nodeCount}return this}setParent(e,t){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(t===void 0)t="\0";else{t+="";for(let n=t;n!==void 0;n=this.parent(n))if(n===e)throw new Error("Setting "+t+" as parent of "+e+" would create a cycle");this.setNode(t)}return this.setNode(e),this._removeFromParentsChildList(e),this._parent[e]=t,this._children[t][e]=!0,this}parent(e){if(this._isCompound){let t=this._parent[e];if(t!=="\0")return t}}children(e="\0"){if(this._isCompound){let t=this._children[e];if(t)return Object.keys(t)}else{if(e==="\0")return this.nodes();if(this.hasNode(e))return[]}return[]}predecessors(e){let t=this._preds[e];if(t)return Object.keys(t)}successors(e){let t=this._sucs[e];if(t)return Object.keys(t)}neighbors(e){let t=this.predecessors(e);if(t){let n=new Set(t);for(let r of this.successors(e))n.add(r);return Array.from(n.values())}}isLeaf(e){let t;return this.isDirected()?t=this.successors(e):t=this.neighbors(e),t.length===0}filterNodes(e){let t=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});t.setGraph(this.graph()),Object.entries(this._nodes).forEach(([s,o])=>{e(s)&&t.setNode(s,o)}),Object.values(this._edgeObjs).forEach(s=>{t.hasNode(s.v)&&t.hasNode(s.w)&&t.setEdge(s,this.edge(s))});let n={},r=s=>{let o=this.parent(s);return!o||t.hasNode(o)?(n[s]=o??void 0,o??void 0):o in n?n[o]:r(o)};return this._isCompound&&t.nodes().forEach(s=>t.setParent(s,r(s))),t}setDefaultEdgeLabel(e){return typeof e!="function"?this._defaultEdgeLabelFn=()=>e:this._defaultEdgeLabelFn=e,this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(e,t){return e.reduce((n,r)=>(t!==void 0?this.setEdge(n,r,t):this.setEdge(n,r),r)),this}setEdge(e,t,n,r){let s,o,i,a,T=!1;typeof e=="object"&&e!==null&&"v"in e?(s=e.v,o=e.w,i=e.name,arguments.length===2&&(a=t,T=!0)):(s=e,o=t,i=r,arguments.length>2&&(a=n,T=!0)),s=""+s,o=""+o,i!==void 0&&(i=""+i);let l=en(this._isDirected,s,o,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(s),this.setNode(o),this._edgeLabels[l]=T?a:this._defaultEdgeLabelFn(s,o,i);let R=QD(this._isDirected,s,o,i);return s=R.v,o=R.w,Object.freeze(R),this._edgeObjs[l]=R,JE(this._preds[o],s),JE(this._sucs[s],o),this._in[o][l]=R,this._out[s][l]=R,this._edgeCount++,this}edge(e,t,n){let r=arguments.length===1?ys(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?ys(this._isDirected,e):en(this._isDirected,e,t,n))in this._edgeLabels}removeEdge(e,t,n){let r=arguments.length===1?ys(this._isDirected,e):en(this._isDirected,e,t,n),s=this._edgeObjs[r];if(s){let o=s.v,i=s.w;delete this._edgeLabels[r],delete this._edgeObjs[r],zE(this._preds[i],o),zE(this._sucs[o],i),delete this._in[i][r],delete this._out[o][r],this._edgeCount--}return this}inEdges(e,t){return this.isDirected()?this.filterEdges(this._in[e],e,t):this.nodeEdges(e,t)}outEdges(e,t){return this.isDirected()?this.filterEdges(this._out[e],e,t):this.nodeEdges(e,t)}nodeEdges(e,t){if(e in this._nodes)return this.filterEdges({...this._in[e],...this._out[e]},e,t)}_removeFromParentsChildList(e){delete this._children[this._parent[e]][e]}filterEdges(e,t,n){if(!e)return;let r=Object.values(e);return n?r.filter(s=>s.v===t&&s.w===n||s.v===n&&s.w===t):r}};function JE(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 s=""+t,o=""+n;if(!e&&s>o){let i=s;s=o,o=i}return s+""+o+""+(r===void 0?"\0":r)}function QD(e,t,n,r){let s=""+t,o=""+n;if(!e&&s>o){let a=s;s=o,o=a}let i={v:s,w:o};return r&&(i.name=r),i}function ys(e,t){return en(e,t.v,t.w,t.name)}var eP="4.0.1",yT={};MT(yT,{read:()=>sP,write:()=>tP});function tP(e){let t={options:{directed:e.isDirected(),multigraph:e.isMultigraph(),compound:e.isCompound()},nodes:nP(e),edges:rP(e)},n=e.graph();return n!==void 0&&(t.value=structuredClone(n)),t}function nP(e){return e.nodes().map(t=>{let n=e.node(t),r=e.parent(t),s={v:t};return n!==void 0&&(s.value=n),r!==void 0&&(s.parent=r),s})}function rP(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 sP(e){let t=new Pe(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 bo={};MT(bo,{CycleException:()=>Or,bellmanFord:()=>xT,components:()=>EP,dijkstra:()=>Nr,dijkstraAll:()=>TP,findCycles:()=>cP,floydWarshall:()=>AP,isAcyclic:()=>dP,postorder:()=>uP,preorder:()=>NP,prim:()=>OP,shortestPaths:()=>fP,tarjan:()=>bT,topsort:()=>GT});var oP=()=>1;function xT(e,t,n,r){return iP(e,String(t),n||oP,r||function(s){return e.outEdges(s)})}function iP(e,t,n,r){let s={},o,i=0,a=e.nodes(),T=function(c){let A=n(c);s[c.v].distance+A<s[c.w].distance&&(s[c.w]={distance:s[c.v].distance+A,predecessor:c.v},o=!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;s[c]={distance:A,predecessor:""}});let R=a.length;for(let c=1;c<R&&(o=!1,i++,l(),!!o);c++);if(i===R-1&&(o=!1,l(),o))throw new Error("The graph contains a negative weight cycle");return s}function EP(e){let t={},n=[],r;function s(o){o in t||(t[o]=!0,r.push(o),e.successors(o).forEach(s),e.predecessors(o).forEach(s))}return e.nodes().forEach(function(o){r=[],s(o),r.length&&n.push(r)}),n}var UT=class{constructor(){this._arr=[],this._keyIndices={}}size(){return this._arr.length}keys(){return this._arr.map(e=>e.key)}has(e){return e in this._keyIndices}priority(e){let t=this._keyIndices[e];if(t!==void 0)return this._arr[t].priority}min(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key}add(e,t){let n=this._keyIndices,r=String(e);if(!(r in n)){let s=this._arr,o=s.length;return n[r]=o,s.push({key:r,priority:t}),this._decrease(o),!0}return!1}removeMin(){this._swap(0,this._arr.length-1);let e=this._arr.pop();return delete this._keyIndices[e.key],this._heapify(0),e.key}decrease(e,t){let n=this._keyIndices[e];if(n===void 0)throw new Error(`Key not found: ${e}`);let r=this._arr[n].priority;if(t>r)throw new Error(`New priority is greater than current priority. Key: ${e} Old: ${r} New: ${t}`);this._arr[n].priority=t,this._decrease(n)}_heapify(e){let t=this._arr,n=2*e,r=n+1,s=e;n<t.length&&(s=t[n].priority<t[s].priority?n:s,r<t.length&&(s=t[r].priority<t[s].priority?r:s),s!==e&&(this._swap(e,s),this._heapify(s)))}_decrease(e){let t=this._arr,n=t[e].priority,r;for(;e!==0&&(r=e>>1,!(t[r].priority<n));)this._swap(e,r),e=r}_swap(e,t){let n=this._arr,r=this._keyIndices,s=n[e],o=n[t];n[e]=o,n[t]=s,r[o.key]=e,r[s.key]=t}},aP=()=>1;function Nr(e,t,n,r){let s=function(o){return e.outEdges(o)};return lP(e,String(t),n||aP,r||s)}function lP(e,t,n,r){let s={},o=new UT,i,a,T=function(l){let R=l.v!==i?l.v:l.w,c=s[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,o.decrease(R,S))};for(e.nodes().forEach(function(l){let R=l===t?0:Number.POSITIVE_INFINITY;s[l]={distance:R,predecessor:""},o.add(l,R)});o.size()>0&&(i=o.removeMin(),a=s[i],a.distance!==Number.POSITIVE_INFINITY);)r(i).forEach(T);return s}function TP(e,t,n){return e.nodes().reduce(function(r,s){return r[s]=Nr(e,s,t,n),r},{})}function bT(e){let t=0,n=[],r={},s=[];function o(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)):(o(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);s.push(T)}}return e.nodes().forEach(function(i){i in r||o(i)}),s}function cP(e){return bT(e).filter(function(t){return t.length>1||t.length===1&&e.hasEdge(t[0],t[0])})}var RP=()=>1;function AP(e,t,n){return SP(e,t||RP,n||function(r){return e.outEdges(r)})}function SP(e,t,n){let r={},s=e.nodes();return s.forEach(function(o){r[o]={},r[o][o]={distance:0,predecessor:""},s.forEach(function(i){o!==i&&(r[o][i]={distance:Number.POSITIVE_INFINITY,predecessor:""})}),n(o).forEach(function(i){let a=i.v===o?i.w:i.v,T=t(i);r[o][a]={distance:T,predecessor:o}})}),s.forEach(function(o){let i=r[o];s.forEach(function(a){let T=r[a];s.forEach(function(l){let R=T[o],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 GT(e){let t={},n={},r=[];function s(o){if(o in n)throw new Or;o in t||(n[o]=!0,t[o]=!0,e.predecessors(o).forEach(s),delete n[o],r.push(o))}if(e.sinks().forEach(s),Object.keys(t).length!==e.nodeCount())throw new Or;return r}function dP(e){try{GT(e)}catch(t){if(t instanceof Or)return!1;throw t}return!0}function IP(e,t,n,r,s){Array.isArray(t)||(t=[t]);let o=(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);s=BT(e,a,n==="post",i,o,r,s)}),s}function BT(e,t,n,r,s,o,i){return t in r||(r[t]=!0,n||(i=o(i,t)),s(t).forEach(function(a){i=BT(e,a,n,r,s,o,i)}),n&&(i=o(i,t))),i}function vT(e,t,n){return IP(e,t,n,function(r,s){return r.push(s),r},[])}function uP(e,t){return vT(e,t,"post")}function NP(e,t){return vT(e,t,"pre")}function OP(e,t){let n=new Pe,r={},s=new UT,o;function i(T){let l=T.v===o?T.w:T.v,R=s.priority(l);if(R!==void 0){let c=t(T);c<R&&(r[l]=o,s.decrease(l,c))}}if(e.nodeCount()===0)return n;e.nodes().forEach(function(T){s.add(T,Number.POSITIVE_INFINITY),n.setNode(T)}),s.decrease(e.nodes()[0],0);let a=!1;for(;s.size()>0;){if(o=s.removeMin(),o in r)n.setEdge(o,r[o]);else{if(a)throw new Error("Input graph is not connected: "+e);a=!0}e.nodeEdges(o).forEach(i)}return n}function fP(e,t,n,r){return CP(e,t,n,r??(s=>{let o=e.outEdges(s);return o??[]}))}function CP(e,t,n,r){if(n===void 0)return Nr(e,t,n,r);let s=!1,o=e.nodes();for(let i=0;i<o.length;i++){let a=r(o[i]);for(let T=0;T<a.length;T++){let l=a[T],R=l.v===o[i]?l.v:l.w,c=R===l.v?l.w:l.v;n({v:R,w:c})<0&&(s=!0)}if(s)return xT(e,t,n,r)}return Nr(e,t,n,r)}function wt(e,t,n,r){let s=r;for(;e.hasNode(s);)s=Go(r);return n.dummy=t,e.setNode(s,n),s}function LP(e){let t=new Pe().setGraph(e.graph());return e.nodes().forEach(n=>t.setNode(n,e.node(n))),e.edges().forEach(n=>{let r=t.edge(n.v,n.w)||{weight:0,minlen:1},s=e.edge(n);t.setEdge(n.v,n.w,{weight:r.weight+s.weight,minlen:Math.max(r.minlen,s.minlen)})}),t}function HT(e){let t=new Pe({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,s=t.x-n,o=t.y-r,i=e.width/2,a=e.height/2;if(!s&&!o)throw new Error("Not possible to find intersection inside of the rectangle");let T,l;return Math.abs(o)*i>Math.abs(s)*a?(o<0&&(a=-a),T=a*s/o,l=a):(s<0&&(i=-i),T=i,l=i*o/s),{x:n+T,y:r+l}}function Pn(e){let t=On(wT(e)+1).map(()=>[]);return e.nodes().forEach(n=>{let r=e.node(n),s=r.rank;s!==void 0&&(t[s]||(t[s]=[]),t[s][r.order]=n)}),t}function _P(e){let t=e.nodes().map(r=>{let s=e.node(r).rank;return s===void 0?Number.MAX_VALUE:s}),n=He(Math.min,t);e.nodes().forEach(r=>{let s=e.node(r);Object.hasOwn(s,"rank")&&(s.rank-=n)})}function hP(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 s=0,o=e.graph().nodeRankFactor;Array.from(r).forEach((i,a)=>{i===void 0&&a%o!==0?--s:i!==void 0&&s&&i.forEach(T=>e.node(T).rank+=s)})}function ZE(e,t,n,r){let s={width:0,height:0};return arguments.length>=4&&(s.rank=n,s.order=r),wt(e,"border",s,t)}function pP(e,t=FT){let n=[];for(let r=0;r<e.length;r+=t){let s=e.slice(r,r+t);n.push(s)}return n}var FT=65535;function He(e,t){if(t.length>FT){let n=pP(t);return e(...n.map(r=>e(...r)))}else return e(...t)}function wT(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 mP(e,t){let n={lhs:[],rhs:[]};return e.forEach(r=>{t(r)?n.lhs.push(r):n.rhs.push(r)}),n}function YT(e,t){let n=Date.now();try{return t()}finally{console.log(e+" time: "+(Date.now()-n)+"ms")}}function VT(e,t){return t()}var DP=0;function Go(e){let t=++DP;return e+(""+t)}function On(e,t,n=1){t==null&&(t=e,e=0);let r=o=>o<t;n<0&&(r=o=>t<o);let s=[];for(let o=e;r(o);o+=n)s.push(o);return s}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,[s,o])=>(r[s]=n(o,s),r),{})}function PP(e,t){return e.reduce((n,r,s)=>(n[r]=t[s],n),{})}var Gr="\0",gP="3.0.0",MP=class{constructor(){qD(this,"_sentinel");let e={};e._next=e._prev=e,this._sentinel=e}dequeue(){let e=this._sentinel,t=e._prev;if(t!==e)return QE(t),t}enqueue(e){let t=this._sentinel;e._prev&&e._next&&QE(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,yP)),n=n._prev;return"["+e.join(", ")+"]"}};function QE(e){e._prev._next=e._next,e._next._prev=e._prev,delete e._next,delete e._prev}function yP(e,t){if(e!=="_next"&&e!=="_prev")return t}var xP=MP,UP=()=>1;function bP(e,t){if(e.nodeCount()<=1)return[];let n=BP(e,t||UP);return GP(n.graph,n.buckets,n.zeroIdx).flatMap(r=>e.outEdges(r.v,r.w)||[])}function GP(e,t,n){var r;let s=[],o=t[t.length-1],i=t[0],a;for(;e.nodeCount();){for(;a=i.dequeue();)xs(e,t,n,a);for(;a=o.dequeue();)xs(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){s=s.concat(xs(e,t,n,a,!0)||[]);break}}}return s}function xs(e,t,n,r,s){let o=[],i=s?o:void 0;return(e.inEdges(r.v)||[]).forEach(a=>{let T=e.edge(a),l=e.node(a.v);s&&o.push({v:a.v,w:a.w}),l.out-=T,ro(t,n,l)}),(e.outEdges(r.v)||[]).forEach(a=>{let T=e.edge(a),l=a.w,R=e.node(l);R.in-=T,ro(t,n,R)}),e.removeNode(r.v),i}function BP(e,t){let n=new Pe,r=0,s=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);s=Math.max(s,c.out+=l),r=Math.max(r,A.in+=l)});let o=vP(s+r+3).map(()=>new xP),i=r+1;return n.nodes().forEach(a=>{ro(o,i,n.node(a))}),{graph:n,buckets:o,zeroIdx:i}}function ro(e,t,n){var r,s,o;n.out?n.in?(o=e[n.out-n.in+t])==null||o.enqueue(n):(s=e[e.length-1])==null||s.enqueue(n):(r=e[0])==null||r.enqueue(n)}function vP(e){let t=[];for(let n=0;n<e;n++)t.push(n);return t}function HP(e){(e.graph().acyclicer==="greedy"?bP(e,t(e)):FP(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,Go("rev"))});function t(n){return r=>n.edge(r).weight}}function FP(e){let t=[],n={},r={};function s(o){Object.hasOwn(r,o)||(r[o]=!0,n[o]=!0,e.outEdges(o).forEach(i=>{Object.hasOwn(n,i.w)?t.push(i):s(i.w)}),delete n[o])}return e.nodes().forEach(s),t}function wP(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 YP(e){e.graph().dummyChains=[],e.edges().forEach(t=>VP(e,t))}function VP(e,t){let n=t.v,r=e.node(n).rank,s=t.w,o=e.node(s).rank,i=t.name,a=e.edge(t),T=a.labelRank;if(o===r+1)return;e.removeEdge(t);let l,R,c;for(c=0,++r;r<o;++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,s,{weight:a.weight},i)}function WP(e){e.graph().dummyChains.forEach(t=>{let n=e.node(t),r=n.edgeLabel,s;for(e.setEdge(n.edgeObj,r);n.dummy;)s=e.successors(t)[0],e.removeNode(t),r.points.push({x:n.x,y:n.y}),n.dummy==="edge-label"&&(r.x=n.x,r.y=n.y,r.width=n.width,r.height=n.height),t=s,n=e.node(t)})}function Bo(e){let t={};function n(r){let s=e.node(r);if(Object.hasOwn(t,r))return s.rank;t[r]=!0;let o=e.outEdges(r),i=o?o.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),s.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 WT=kP;function kP(e){let t=new Pe({directed:!1}),n=e.nodes();if(n.length===0)throw new Error("Graph must have at least one node");let r=n[0],s=e.nodeCount();t.setNode(r,{});let o,i;for(;XP(t,e)<s&&(o=$P(t,e),!!o);)i=t.hasNode(o.v)?Ht(e,o):-Ht(e,o),jP(t,e,i);return t}function XP(e,t){function n(r){let s=t.nodeEdges(r);s&&s.forEach(o=>{let i=o.v,a=r===i?o.w:i;!e.hasNode(a)&&!Ht(t,o)&&(e.setNode(a,{}),e.setEdge(r,a,{}),n(a))})}return e.nodes().forEach(n),e.nodeCount()}function $P(e,t){return t.edges().reduce((n,r)=>{let s=Number.POSITIVE_INFINITY;return e.hasNode(r.v)!==e.hasNode(r.w)&&(s=Ht(t,r)),s<n[0]?[s,r]:n},[Number.POSITIVE_INFINITY,null])[1]}function jP(e,t,n){e.nodes().forEach(r=>t.node(r).rank+=n)}var{preorder:KP,postorder:JP}=bo,zP=Nt;Nt.initLowLimValues=Ho;Nt.initCutValues=vo;Nt.calcCutValue=kT;Nt.leaveEdge=$T;Nt.enterEdge=jT;Nt.exchangeEdges=KT;function Nt(e){e=LP(e),Bo(e);let t=WT(e);Ho(t),vo(t,e);let n,r;for(;n=$T(t);)r=jT(t,e,n),KT(t,e,n,r)}function vo(e,t){let n=JP(e,e.nodes());n=n.slice(0,n.length-1),n.forEach(r=>qP(e,t,r))}function qP(e,t,n){let r=e.node(n).parent,s=e.edge(n,r);s.cutvalue=kT(e,t,n)}function kT(e,t,n){let r=e.node(n).parent,s=!0,o=t.edge(n,r),i=0;o||(s=!1,o=t.edge(r,n)),i=o.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===s,A=t.edge(T).weight;if(i+=c?A:-A,QP(e,n,R)){let S=e.edge(n,R).cutvalue;i+=c?-S:S}}}),i}function Ho(e,t){arguments.length<2&&(t=e.nodes()[0]),XT(e,{},1,t)}function XT(e,t,n,r,s){let o=n,i=e.node(r);t[r]=!0;let a=e.neighbors(r);return a&&a.forEach(T=>{Object.hasOwn(t,T)||(n=XT(e,t,n,T,r))}),i.low=o,i.lim=n++,s?i.parent=s:delete i.parent,n}function $T(e){return e.edges().find(t=>e.edge(t).cutvalue<0)}function jT(e,t,n){let r=n.v,s=n.w;t.hasEdge(r,s)||(r=n.w,s=n.v);let o=e.node(r),i=e.node(s),a=o,T=!1;return o.lim>i.lim&&(a=i,T=!0),t.edges().filter(l=>T===ea(e,e.node(l.v),a)&&T!==ea(e,e.node(l.w),a)).reduce((l,R)=>Ht(t,R)<Ht(t,l)?R:l)}function KT(e,t,n,r){let s=n.v,o=n.w;e.removeEdge(s,o),e.setEdge(r.v,r.w,{}),Ho(e),vo(e,t),ZP(e,t)}function ZP(e,t){let n=e.nodes().find(s=>!e.node(s).parent);if(!n)return;let r=KP(e,[n]);r=r.slice(1),r.forEach(s=>{let o=e.node(s).parent,i=t.edge(s,o),a=!1;i||(i=t.edge(o,s),a=!0),t.node(s).rank=t.node(o).rank+(a?i.minlen:-i.minlen)})}function QP(e,t,n){return e.hasEdge(t,n)}function ea(e,t,n){return n.low<=t.lim&&t.lim<=n.lim}var eg=tg;function tg(e){let t=e.graph().ranker;if(typeof t=="function")return t(e);switch(t){case"network-simplex":ta(e);break;case"tight-tree":rg(e);break;case"longest-path":ng(e);break;case"none":break;default:ta(e)}}var ng=Bo;function rg(e){Bo(e),WT(e)}function ta(e){zP(e)}var sg=og;function og(e){let t=Eg(e);e.graph().dummyChains.forEach(n=>{let r=e.node(n),s=r.edgeObj,o=ig(e,t,s.v,s.w),i=o.path,a=o.lca,T=0,l=i[T],R=!0;for(;n!==s.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 ig(e,t,n,r){let s=[],o=[],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),s.push(T);while(T&&(t[T].low>i||a>t[T].lim));let l=T,R=r;for(;(R=e.parent(R))!==l;)o.push(R);return{path:s.concat(o.reverse()),lca:l}}function Eg(e){let t={},n=0;function r(s){let o=n;e.children(s).forEach(r),t[s]={low:o,lim:n++}}return e.children(Gr).forEach(r),t}function ag(e){let t=wt(e,"root",{},"_root"),n=lg(e),r=Object.values(n),s=He(Math.max,r)-1,o=2*s+1;e.graph().nestingRoot=t,e.edges().forEach(a=>e.edge(a).minlen*=o);let i=Tg(e)+1;e.children(Gr).forEach(a=>JT(e,t,o,i,s,n,a)),e.graph().nodeRankFactor=o}function JT(e,t,n,r,s,o,i){var a;let T=e.children(i);if(!T.length){i!==t&&e.setEdge(t,i,{weight:0,minlen:n});return}let l=ZE(e,"_bt"),R=ZE(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;JT(e,t,n,r,s,o,A);let d=e.node(A),I=d.borderTop?d.borderTop:A,O=d.borderBottom?d.borderBottom:A,u=d.borderTop?r:2*r,C=I!==O?1:s-((S=o[i])!=null?S:0)+1;e.setEdge(l,I,{weight:u,minlen:C,nestingEdge:!0}),e.setEdge(O,R,{weight:u,minlen:C,nestingEdge:!0})}),e.parent(i)||e.setEdge(t,l,{weight:0,minlen:s+((a=o[i])!=null?a:0)})}function lg(e){let t={};function n(r,s){let o=e.children(r);o&&o.length&&o.forEach(i=>n(i,s+1)),t[r]=s}return e.children(Gr).forEach(r=>n(r,1)),t}function Tg(e){return e.edges().reduce((t,n)=>t+e.edge(n).weight,0)}function cg(e){let t=e.graph();e.removeNode(t.nestingRoot),delete t.nestingRoot,e.edges().forEach(n=>{e.edge(n).nestingEdge&&e.removeEdge(n)})}var Rg=Ag;function Ag(e){function t(n){let r=e.children(n),s=e.node(n);if(r.length&&r.forEach(t),Object.hasOwn(s,"minRank")){s.borderLeft=[],s.borderRight=[];for(let o=s.minRank,i=s.maxRank+1;o<i;++o)na(e,"borderLeft","_bl",n,s,o),na(e,"borderRight","_br",n,s,o)}}e.children(Gr).forEach(t)}function na(e,t,n,r,s,o){let i={width:0,height:0,rank:o,borderType:t},a=s[t][o-1],T=wt(e,"border",i,n);s[t][o]=T,e.setParent(T,r),a&&e.setEdge(a,T,{weight:1})}function Sg(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="lr"||n==="rl")&&zT(e)}function dg(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="bt"||n==="rl")&&Ig(e),(n==="lr"||n==="rl")&&(ug(e),zT(e))}function zT(e){e.nodes().forEach(t=>ra(e.node(t))),e.edges().forEach(t=>ra(e.edge(t)))}function ra(e){let t=e.width;e.width=e.height,e.height=t}function Ig(e){e.nodes().forEach(t=>Us(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(Us),Object.hasOwn(r,"y")&&Us(r)})}function Us(e){e.y=-e.y}function ug(e){e.nodes().forEach(t=>bs(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(bs),Object.hasOwn(r,"x")&&bs(r)})}function bs(e){let t=e.x;e.x=e.y,e.y=t}function Ng(e){let t={},n=e.nodes().filter(a=>!e.children(a).length),r=n.map(a=>e.node(a).rank),s=He(Math.max,r),o=On(s+1).map(()=>[]);function i(a){if(t[a])return;t[a]=!0;let T=e.node(a);o[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),o}function Og(e,t){let n=0;for(let r=1;r<t.length;++r)n+=fg(e,t[r-1],t[r]);return n}function fg(e,t,n){let r=PP(n,n.map((l,R)=>R)),s=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):[]}),o=1;for(;o<n.length;)o<<=1;let i=2*o-1;o-=1;let a=new Array(i).fill(0),T=0;return s.forEach(l=>{let R=l.pos+o;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 Cg(e,t=[]){return t.map(n=>{let r=e.inEdges(n);if(!r||!r.length)return{v:n};{let s=r.reduce((o,i)=>{let a=e.edge(i),T=e.node(i.v);return{sum:o.sum+a.weight*T.order,weight:o.weight+a.weight}},{sum:0,weight:0});return{v:n,barycenter:s.sum/s.weight,weight:s.weight}}})}function Lg(e,t){let n={};e.forEach((s,o)=>{let i={indegree:0,in:[],out:[],vs:[s.v],i:o};s.barycenter!==void 0&&(i.barycenter=s.barycenter,i.weight=s.weight),n[s.v]=i}),t.edges().forEach(s=>{let o=n[s.v],i=n[s.w];o!==void 0&&i!==void 0&&(i.indegree++,o.out.push(i))});let r=Object.values(n).filter(s=>!s.indegree);return _g(r)}function _g(e){let t=[];function n(s){return o=>{o.merged||(o.barycenter===void 0||s.barycenter===void 0||o.barycenter>=s.barycenter)&&hg(s,o)}}function r(s){return o=>{o.in.push(s),--o.indegree===0&&e.push(o)}}for(;e.length;){let s=e.pop();t.push(s),s.in.reverse().forEach(n(s)),s.out.forEach(r(s))}return t.filter(s=>!s.merged).map(s=>fr(s,["vs","i","barycenter","weight"]))}function hg(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 pg(e,t){let n=mP(e,R=>Object.hasOwn(R,"barycenter")),r=n.lhs,s=n.rhs.sort((R,c)=>c.i-R.i),o=[],i=0,a=0,T=0;r.sort(mg(!!t)),T=sa(o,s,T),r.forEach(R=>{T+=R.vs.length,o.push(R.vs),i+=R.barycenter*R.weight,a+=R.weight,T=sa(o,s,T)});let l={vs:o.flat(1)};return a&&(l.barycenter=i/a,l.weight=a),l}function sa(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 mg(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 s=e.children(t),o=e.node(t),i=o?o.borderLeft:void 0,a=o?o.borderRight:void 0,T={};i&&(s=s.filter(A=>A!==i&&A!==a));let l=Cg(e,s);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")&&Pg(A,S)}});let R=Lg(l,n);Dg(R,T);let c=pg(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 Dg(e,t){e.forEach(n=>{n.vs=n.vs.flatMap(r=>t[r]?t[r].vs:r)})}function Pg(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 gg(e,t,n,r){r||(r=e.nodes());let s=Mg(e),o=new Pe({compound:!0}).setGraph({root:s}).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){o.setNode(i),o.setParent(i,T||s);let l=e[n](i);l&&l.forEach(R=>{let c=R.v===i?R.w:R.v,A=o.edge(c,i),S=A!==void 0?A.weight:0;o.setEdge(c,i,{weight:e.edge(R).weight+S})}),Object.hasOwn(a,"minRank")&&o.setNode(i,{borderLeft:a.borderLeft[t],borderRight:a.borderRight[t]})}}),o}function Mg(e){let t;for(;e.hasNode(t=Go("_root")););return t}function yg(e,t,n){let r={},s;n.forEach(o=>{let i=e.parent(o),a,T;for(;i;){if(a=e.parent(i),a?(T=r[a],r[a]=i):(T=s,s=i),T&&T!==i){t.setEdge(T,i);return}i=a}})}function ZT(e,t={}){if(typeof t.customOrder=="function"){t.customOrder(e,ZT);return}let n=wT(e),r=oa(e,On(1,n+1),"inEdges"),s=oa(e,On(n-1,-1,-1),"outEdges"),o=Ng(e);if(ia(e,o),t.disableOptimalOrderHeuristic)return;let i=Number.POSITIVE_INFINITY,a,T=t.constraints||[];for(let l=0,R=0;R<4;++l,++R){xg(l%2?r:s,l%4>=2,T),o=Pn(e);let c=Og(e,o);c<i?(R=0,a=Object.assign({},o),i=c):c===i&&(a=structuredClone(o))}ia(e,a)}function oa(e,t,n){let r=new Map,s=(o,i)=>{r.has(o)||r.set(o,[]),r.get(o).push(i)};for(let o of e.nodes()){let i=e.node(o);if(typeof i.rank=="number"&&s(i.rank,o),typeof i.minRank=="number"&&typeof i.maxRank=="number")for(let a=i.minRank;a<=i.maxRank;a++)a!==i.rank&&s(a,o)}return t.map(function(o){return gg(e,o,n,r.get(o)||[])})}function xg(e,t,n){let r=new Pe;e.forEach(function(s){n.forEach(a=>r.setEdge(a.left,a.right));let o=s.graph().root,i=qT(s,o,r,t);i.vs.forEach((a,T)=>s.node(a).order=T),yg(s,r,i.vs)})}function ia(e,t){Object.values(t).forEach(n=>n.forEach((r,s)=>e.node(r).order=s))}function Ug(e,t){let n={};function r(s,o){let i=0,a=0,T=s.length,l=o[o.length-1];return o.forEach((R,c)=>{let A=Gg(e,R),S=A?e.node(A).order:T;(A||R===l)&&(o.slice(a,c+1).forEach(d=>{let I=e.predecessors(d);I&&I.forEach(O=>{let u=e.node(O),C=u.order;(C<i||S<C)&&!(u.dummy&&e.node(d).dummy)&&QT(n,O,d)})}),a=c+1,i=S)}),o}return t.length&&t.reduce(r),n}function bg(e,t){let n={};function r(o,i,a,T,l){On(i,a).forEach(R=>{let c=o[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)&&QT(n,S,c)})}})}function s(o,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,o.length)}),i}return t.length&&t.reduce(s),n}function Gg(e,t){if(e.node(t).dummy){let n=e.predecessors(t);if(n)return n.find(r=>e.node(r).dummy)}}function QT(e,t,n){if(t>n){let s=t;t=n,n=s}let r=e[t];r||(e[t]=r={}),r[n]=!0}function Bg(e,t,n){if(t>n){let s=t;t=n,n=s}let r=e[t];return r!==void 0&&Object.hasOwn(r,n)}function vg(e,t,n,r){let s={},o={},i={};return t.forEach(a=>{a.forEach((T,l)=>{s[T]=T,o[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&&o[l]===l&&T<O&&!Bg(n,l,I)){let u=s[I];u!==void 0&&(o[I]=l,o[l]=s[l]=u,T=O)}}}})}),{root:s,align:o}}function Hg(e,t,n,r,s=!1){let o={},i=Fg(e,t,n,s),a=s?"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 C of d(u))I.push(C)}u=I.pop()}}function l(S){let d=i.inEdges(S);d?o[S]=d.reduce((I,O)=>{var u;let C=(u=o[O.v])!=null?u:0,N=i.edge(O);return Math.max(I,C+(N!==void 0?N:0))},0):o[S]=0}function R(S){let d=i.outEdges(S),I=Number.POSITIVE_INFINITY;d&&(I=d.reduce((u,C)=>{let N=o[C.w],_=i.edge(C);return Math.min(u,(N!==void 0?N:0)-(_!==void 0?_:0))},Number.POSITIVE_INFINITY));let O=e.node(S);I!==Number.POSITIVE_INFINITY&&O.borderType!==a&&(o[S]=Math.max(o[S]!==void 0?o[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&&(o[S]=(d=o[I])!=null?d:0)}),o}function Fg(e,t,n,r){let s=new Pe,o=e.graph(),i=kg(o.nodesep,o.edgesep,r);return t.forEach(a=>{let T;a.forEach(l=>{let R=n[l];if(R!==void 0){if(s.setNode(R),T!==void 0){let c=n[T];if(c!==void 0){let A=s.edge(c,R);s.setEdge(c,R,Math.max(i(e,l,T),A||0))}}T=l}})}),s}function wg(e,t){return Object.values(t).reduce((n,r)=>{let s=Number.NEGATIVE_INFINITY,o=Number.POSITIVE_INFINITY;Object.entries(r).forEach(([a,T])=>{let l=Xg(e,a)/2;s=Math.max(T+l,s),o=Math.min(T-l,o)});let i=s-o;return i<n[0]&&(n=[i,r]),n},[Number.POSITIVE_INFINITY,null])[1]}function Yg(e,t){let n=Object.values(t),r=He(Math.min,n),s=He(Math.max,n);["u","d"].forEach(o=>{["l","r"].forEach(i=>{let a=o+i,T=e[a];if(!T||T===t)return;let l=Object.values(T),R=r-He(Math.min,l);i!=="l"&&(R=s-He(Math.max,l)),R&&(e[a]=br(T,c=>c+R))})})}function Vg(e,t=void 0){let n=e.ul;return n?br(n,(r,s)=>{var o,i;if(t){let T=t.toLowerCase(),l=e[T];if(l&&l[s]!==void 0)return l[s]}let a=Object.values(e).map(T=>{let l=T[s];return l!==void 0?l:0}).sort((T,l)=>T-l);return(((o=a[1])!=null?o:0)+((i=a[2])!=null?i:0))/2}):{}}function Wg(e){let t=Pn(e),n=Object.assign(Ug(e,t),bg(e,t)),r={},s;["u","d"].forEach(i=>{s=i==="u"?t:Object.values(t).reverse(),["l","r"].forEach(a=>{a==="r"&&(s=s.map(R=>Object.values(R).reverse()));let T=vg(e,s,n,R=>(i==="u"?e.predecessors(R):e.successors(R))||[]),l=Hg(e,s,T.root,T.align,a==="r");a==="r"&&(l=br(l,R=>-R)),r[i+a]=l})});let o=wg(e,r);return Yg(r,o),Vg(r,e.graph().align)}function kg(e,t,n){return(r,s,o)=>{let i=r.node(s),a=r.node(o),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 Xg(e,t){return e.node(t).width}function $g(e){e=HT(e),jg(e),Object.entries(Wg(e)).forEach(([t,n])=>e.node(t).x=n)}function jg(e){let t=Pn(e),n=e.graph(),r=n.ranksep,s=n.rankalign,o=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);s==="top"?l.y=o+l.height/2:s==="bottom"?l.y=o+a-l.height/2:l.y=o+a/2}),o+=a+r})}function Kg(e,t={}){let n=t.debugTiming?YT:VT;return n("layout",()=>{let r=n(" buildLayoutGraph",()=>sM(e));return n(" runLayout",()=>Jg(r,n,t)),n(" updateInputGraph",()=>zg(e,r)),r})}function Jg(e,t,n){t(" makeSpaceForEdgeLabels",()=>oM(e)),t(" removeSelfEdges",()=>SM(e)),t(" acyclic",()=>HP(e)),t(" nestingGraph.run",()=>ag(e)),t(" rank",()=>eg(HT(e))),t(" injectEdgeLabelProxies",()=>iM(e)),t(" removeEmptyRanks",()=>hP(e)),t(" nestingGraph.cleanup",()=>cg(e)),t(" normalizeRanks",()=>_P(e)),t(" assignRankMinMax",()=>EM(e)),t(" removeEdgeLabelProxies",()=>aM(e)),t(" normalize.run",()=>YP(e)),t(" parentDummyChains",()=>sg(e)),t(" addBorderSegments",()=>Rg(e)),t(" order",()=>ZT(e,n)),t(" insertSelfEdges",()=>dM(e)),t(" adjustCoordinateSystem",()=>Sg(e)),t(" position",()=>$g(e)),t(" positionSelfEdges",()=>IM(e)),t(" removeBorderNodes",()=>AM(e)),t(" normalize.undo",()=>WP(e)),t(" fixupEdgeLabelCoords",()=>cM(e)),t(" undoCoordinateSystem",()=>dg(e)),t(" translateGraph",()=>lM(e)),t(" assignNodeIntersects",()=>TM(e)),t(" reversePoints",()=>RM(e)),t(" acyclic.undo",()=>wP(e))}function zg(e,t){e.nodes().forEach(n=>{let r=e.node(n),s=t.node(n);r&&(r.x=s.x,r.y=s.y,r.order=s.order,r.rank=s.rank,t.children(n).length&&(r.width=s.width,r.height=s.height))}),e.edges().forEach(n=>{let r=e.edge(n),s=t.edge(n);r.points=s.points,Object.hasOwn(s,"x")&&(r.x=s.x,r.y=s.y)}),e.graph().width=t.graph().width,e.graph().height=t.graph().height}var qg=["nodesep","edgesep","ranksep","marginx","marginy"],Zg={ranksep:50,edgesep:20,nodesep:50,rankdir:"TB",rankalign:"center"},Qg=["acyclicer","ranker","rankdir","align","rankalign"],eM=["width","height","rank"],Ea={width:0,height:0},tM=["minlen","weight","width","height","labeloffset"],nM={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},rM=["labelpos"];function sM(e){let t=new Pe({multigraph:!0,compound:!0}),n=Bs(e.graph());return t.setGraph(Object.assign({},Zg,Gs(n,qg),fr(n,Qg))),e.nodes().forEach(r=>{let s=Bs(e.node(r)),o=Gs(s,eM);Object.keys(Ea).forEach(a=>{o[a]===void 0&&(o[a]=Ea[a])}),t.setNode(r,o);let i=e.parent(r);i!==void 0&&t.setParent(r,i)}),e.edges().forEach(r=>{let s=Bs(e.edge(r));t.setEdge(r,Object.assign({},nM,Gs(s,tM),fr(s,rM)))}),t}function oM(e){let t=e.graph();t.ranksep/=2,e.edges().forEach(n=>{let r=e.edge(n);r.minlen*=2,r.labelpos.toLowerCase()!=="c"&&(t.rankdir==="TB"||t.rankdir==="BT"?r.width+=r.labeloffset:r.height+=r.labeloffset)})}function iM(e){e.edges().forEach(t=>{let n=e.edge(t);if(n.width&&n.height){let r=e.node(t.v),s={rank:(e.node(t.w).rank-r.rank)/2+r.rank,e:t};wt(e,"edge-proxy",s,"_ep")}})}function EM(e){let t=0;e.nodes().forEach(n=>{let r=e.node(n);r.borderTop&&(r.minRank=e.node(r.borderTop).rank,r.maxRank=e.node(r.borderBottom).rank,t=Math.max(t,r.maxRank))}),e.graph().maxRank=t}function aM(e){e.nodes().forEach(t=>{let n=e.node(t);if(n.dummy==="edge-proxy"){let r=n;e.edge(r.e).labelRank=n.rank,e.removeNode(t)}})}function lM(e){let t=Number.POSITIVE_INFINITY,n=0,r=Number.POSITIVE_INFINITY,s=0,o=e.graph(),i=o.marginx||0,a=o.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),s=Math.max(s,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)}),o.width=n-t+i,o.height=s-r+a}function TM(e){e.edges().forEach(t=>{let n=e.edge(t),r=e.node(t.v),s=e.node(t.w),o,i;n.points?(o=n.points[0],i=n.points[n.points.length-1]):(n.points=[],o=s,i=r),n.points.unshift(qE(r,o)),n.points.push(qE(s,i))})}function cM(e){e.edges().forEach(t=>{let n=e.edge(t);if(Object.hasOwn(n,"x"))switch((n.labelpos==="l"||n.labelpos==="r")&&(n.width-=n.labeloffset),n.labelpos){case"l":n.x-=n.width/2+n.labeloffset;break;case"r":n.x+=n.width/2+n.labeloffset;break}})}function RM(e){e.edges().forEach(t=>{let n=e.edge(t);n.reversed&&n.points.reverse()})}function AM(e){e.nodes().forEach(t=>{if(e.children(t).length){let n=e.node(t),r=e.node(n.borderTop),s=e.node(n.borderBottom),o=e.node(n.borderLeft[n.borderLeft.length-1]),i=e.node(n.borderRight[n.borderRight.length-1]);n.width=Math.abs(i.x-o.x),n.height=Math.abs(s.y-r.y),n.x=o.x+n.width/2,n.y=r.y+n.height/2}}),e.nodes().forEach(t=>{e.node(t).dummy==="border"&&e.removeNode(t)})}function SM(e){e.edges().forEach(t=>{if(t.v===t.w){let n=e.node(t.v);n.selfEdges||(n.selfEdges=[]),n.selfEdges.push({e:t,label:e.edge(t)}),e.removeEdge(t)}})}function dM(e){Pn(e).forEach(t=>{let n=0;t.forEach((r,s)=>{let o=e.node(r);o.order=s+n,(o.selfEdges||[]).forEach(i=>{wt(e,"selfedge",{width:i.label.width,height:i.label.height,rank:o.rank,order:s+ ++n,e:i.e,label:i.label},"_se")}),delete o.selfEdges})})}function IM(e){e.nodes().forEach(t=>{let n=e.node(t);if(n.dummy==="selfedge"){let r=n,s=e.node(r.e.v),o=s.x+s.width/2,i=s.y,a=n.x-o,T=s.height/2;e.setEdge(r.e,r.label),e.removeNode(t),r.label.points=[{x:o+2*a/3,y:i-T},{x:o+5*a/6,y:i-T},{x:o+a,y:i},{x:o+5*a/6,y:i+T},{x:o+2*a/3,y:i+T}],r.label.x=n.x,r.label.y=n.y}})}function Gs(e,t){return br(fr(e,t),Number)}function Bs(e){let t={};return e&&Object.entries(e).forEach(([n,r])=>{typeof n=="string"&&(n=n.toLowerCase()),t[n]=r}),t}function uM(e){let t=Pn(e),n=new Pe({compound:!0,multigraph:!0}).setGraph({});return e.nodes().forEach(r=>{n.setNode(r,{label:r}),n.setParent(r,"layer"+e.node(r).rank)}),e.edges().forEach(r=>n.setEdge(r.v,r.w,{},r.name)),t.forEach((r,s)=>{let o="layer"+s;n.setNode(o,{rank:"same"}),r.reduce((i,a)=>(n.setEdge(i,a,{style:"invis"}),a))}),n}var NM={graphlib:gT,version:gP,layout:Kg,debug:uM,util:{time:YT,notime:VT}},aa=NM;/*! 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"},ec={certified:"#56d364",draft:"#8b949e",review:"#e3b341",deprecated:"#f85149",pending_recertification:"#d29922"},vs={reads_from:"#8b949e",feeds_into:"#56d364",aggregates:"#388bfd",visualizes:"#f778ba",crosses_domain:"#d2a8ff"};function OM(e,t,n="LR"){const r=new aa.graphlib.Graph().setDefaultEdgeLabel(()=>({}));r.setGraph({rankdir:n,ranksep:80,nodesep:40,marginx:40,marginy:40});for(const o of e){const i=o.type==="domainGroup"?200:180,a=o.type==="domainGroup"?60:56;r.setNode(o.id,{width:i,height:a})}for(const o of t)r.setEdge(o.source,o.target);return aa.layout(r),{nodes:e.map(o=>{const i=r.node(o.id),a=o.type==="domainGroup"?200:180,T=o.type==="domainGroup"?60:56;return{...o,position:{x:i.x-a/2,y:i.y-T/2}}}),edges:t}}function fM({data:e,selected:t}){const n=e.nodeType,r=Be[n]??"#8b949e",s=tr[n]??n.slice(0,5).toUpperCase(),o=e.label,i=e.domain,a=e.status,T=a?ec[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:s}),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:o,children:o}),E.jsx(vt,{type:"source",position:Z.Right,style:{background:r,width:6,height:6,border:"none"}})]})}const CM={dagNode:fM};function qt({label:e,color:t,active:n,count:r,onClick:s}){return E.jsxs("button",{onClick:s,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 LM(){const{state:e}=ae(),t=Ee[e.themeMode],[n,r]=f.useState(!0),[s,o]=f.useState([]),[i,a]=f.useState([]),[T,l,R]=OD([]),[c,A,S]=fD([]),[d,I]=f.useState(!0),[O,u]=f.useState(!0),[C,N]=f.useState(!0),[_,m]=f.useState(!0),[h,D]=f.useState(!0),[M,B]=f.useState(null),[w,P]=f.useState(new Set),[p,U]=f.useState(null),[L,x]=f.useState([]),[g,v]=f.useState([]),b=f.useCallback(async()=>{r(!0);const k=await Re.fetchLineage();o(k.nodes??[]),a(k.edges??[]),r(!1)},[]);f.useEffect(()=>{b()},[b]);const y=f.useMemo(()=>{const k=new Set;return d&&k.add("source_table"),O&&k.add("block"),C&&k.add("metric"),_&&k.add("dimension"),h&&k.add("chart"),k.add("domain"),k},[d,O,C,_,h]);f.useEffect(()=>{const k=s.filter($=>y.has($.type)),X=new Set(k.map($=>$.id)),K=k.map($=>({id:$.id,type:"dagNode",position:{x:0,y:0},data:{label:$.name,nodeType:$.type,domain:$.domain,status:$.status,owner:$.owner,highlighted:w.has($.id),dimmed:w.size>0&&!w.has($.id)}})),Q=i.filter($=>X.has($.source)&&X.has($.target)&&$.type!=="crosses_domain").map(($,j)=>({id:`e-${j}`,source:$.source,target:$.target,type:"default",animated:$.type==="feeds_into",style:{stroke:vs[$.type]??"#30363d",strokeWidth:w.size>0?w.has($.source)&&w.has($.target)?2.5:.5:1.5,opacity:w.size>0?w.has($.source)&&w.has($.target)?1:.15:.7},markerEnd:{type:dn.ArrowClosed,width:12,height:12,color:vs[$.type]??"#30363d"}}));if(K.length>0){const $=OM(K,Q,"LR");l($.nodes),A($.edges)}else l([]),A([])},[s,i,y,w,l,A]);const Y=f.useCallback(async(k,X)=>{if(M===X.id){B(null),P(new Set),U(null),x([]),v([]);return}B(X.id);const K=s.find(q=>q.id===X.id);U(K??null);const Q=new Set,$=new Set;function j(q){for(const z of i)z.target===q&&z.type!=="crosses_domain"&&!Q.has(z.source)&&(Q.add(z.source),j(z.source))}function ee(q){for(const z of i)z.source===q&&z.type!=="crosses_domain"&&!$.has(z.target)&&($.add(z.target),ee(z.target))}j(X.id),ee(X.id);const re=new Set([X.id,...Q,...$]);if(P(re),x(s.filter(q=>Q.has(q.id))),v(s.filter(q=>$.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,s,i]),W=f.useCallback(()=>{B(null),P(new Set),U(null),x([]),v([])},[]),V=f.useMemo(()=>{const k={};for(const X of s)k[X.type]=(k[X.type]??0)+1;return k},[s]);return n?E.jsx("div",{style:{padding:16,color:t.textMuted,fontSize:12,height:"100%"},children:"Loading lineage graph..."}):s.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:C,count:V.metric??0,onClick:()=>N(!C)}),E.jsx(qt,{label:"Dims",color:Be.dimension,active:_,count:V.dimension??0,onClick:()=>m(!_)}),E.jsx(qt,{label:"Charts",color:Be.chart,active:h,count:V.chart??0,onClick:()=>D(!h)})]}),E.jsx("div",{style:{flex:1,position:"relative"},children:E.jsxs(ND,{nodes:T,edges:c,onNodesChange:R,onEdgesChange:S,onNodeClick:Y,onPaneClick:W,nodeTypes:CM,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(xD,{showInteractive:!1,style:{button:{background:"#161b22",color:"#e6edf3",border:"1px solid #30363d"}}}),E.jsx(XD,{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(vs).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))})})]})}),p&&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[p.type]??"#8b949e",borderRadius:3,padding:"1px 5px"},children:tr[p.type]??p.type}),E.jsx("span",{style:{fontWeight:600,color:t.textPrimary,flex:1},children:p.name}),E.jsx("button",{onClick:()=>{B(null),P(new Set),U(null)},style:{background:"transparent",border:"none",color:t.textMuted,cursor:"pointer",fontSize:14},children:"×"})]}),p.domain&&E.jsxs("div",{style:{color:t.textMuted,marginBottom:2},children:["Domain: ",E.jsx("span",{style:{color:"#d2a8ff"},children:p.domain})]}),p.owner&&E.jsxs("div",{style:{color:t.textMuted,marginBottom:2},children:["Owner: ",E.jsx("span",{style:{color:t.textSecondary},children:p.owner})]}),p.status&&E.jsxs("div",{style:{color:t.textMuted,marginBottom:4},children:["Status: ",E.jsx("span",{style:{color:ec[p.status]??t.textSecondary},children:p.status})]}),L.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 (",L.length,")"]}),L.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)}),L.length>8&&E.jsxs("div",{style:{color:t.textMuted,fontSize:10},children:["+",L.length-8," more"]})]}),g.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 (",g.length,")"]}),g.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)}),g.length>8&&E.jsxs("div",{style:{color:t.textMuted,fontSize:10},children:["+",g.length-8," more"]})]})]})]})}function _M(){const{state:e,dispatch:t}=ae(),n=Ee[e.themeMode],r=f.useRef({}),s=f.useCallback(async a=>{try{const{content:T}=await Re.readNotebook(a.path),{title:l,cells:R}=nS(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:[De("sql")],title:a.name})}},[t,e.sidebarPanel]),o=f.useCallback(a=>{const T=r.current[a];T&&T.scrollIntoView({behavior:"smooth",block:"start"})},[]),i=f.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(fS,{}),E.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[E.jsx(tA,{}),e.sidebarOpen&&E.jsx(ZA,{onOpenFile:s,onNavigateToCell:o}),E.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:e.lineageFullscreen?E.jsx(LM,{}):E.jsxs(E.Fragment,{children:[E.jsx(bf,{onOpenFile:s,registerCellRef:i}),E.jsx(hS,{})]})})]}),e.newNotebookModalOpen&&E.jsx(wf,{onFileOpened:s})]})}function hM(){const{state:e,dispatch:t}=ae(),n=f.useRef(null),r=f.useRef(null);f.useEffect(()=>{var s;n.current=((s=e.activeFile)==null?void 0:s.path)??null},[e.activeFile]),f.useEffect(()=>{if(typeof EventSource>"u")return;const s=()=>{const o=new EventSource(`${window.location.origin}/api/watch`);r.current=o,o.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{}}),o.addEventListener("error",()=>{o.close(),setTimeout(s,5e3)})};return s(),()=>{var o;(o=r.current)==null||o.close(),r.current=null}},[t])}function pM(){const{state:e,dispatch:t}=ae(),n=Ee[e.themeMode];return f.useEffect(()=>{const r="dql-global-styles";let s=document.getElementById(r);s||(s=document.createElement("style"),s.id=r,document.head.appendChild(s)),s.textContent=`
|
|
512
|
+
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
513
|
+
body {
|
|
514
|
+
font-family: ${n.font};
|
|
515
|
+
overflow: hidden;
|
|
516
|
+
background: ${n.appBg};
|
|
517
|
+
color: ${n.textPrimary};
|
|
518
|
+
}
|
|
519
|
+
::-webkit-scrollbar { width: 6px; height: 6px; }
|
|
520
|
+
::-webkit-scrollbar-track { background: transparent; }
|
|
521
|
+
::-webkit-scrollbar-thumb {
|
|
522
|
+
background: ${n.scrollbarThumb};
|
|
523
|
+
border-radius: 3px;
|
|
524
|
+
}
|
|
525
|
+
::-webkit-scrollbar-thumb:hover {
|
|
526
|
+
background: ${n.textMuted};
|
|
527
|
+
}
|
|
528
|
+
::selection {
|
|
529
|
+
background: ${n.accent}40;
|
|
530
|
+
color: ${n.textPrimary};
|
|
531
|
+
}
|
|
532
|
+
`},[n]),f.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]),f.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]),hM(),E.jsx(_M,{})}function mM(){return E.jsx(WR,{children:E.jsx(pM,{})})}wR.createRoot(document.getElementById("root")).render(E.jsx(mM,{}));
|