erdbpro 3.4.7-rc.68 → 3.4.7-rc.69
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AdminRoute-B0jcm3y0.js → AdminRoute-DTVZl0wJ.js} +2 -2
- package/dist/assets/{Combination-BrGssyQ_.js → Combination-DjM6bpkT.js} +1 -1
- package/dist/assets/DataViewerModeToolbar-BTwWp1-O.js +106 -0
- package/dist/assets/{DbClientEditorRoute-MAub9z3U.js → DbClientEditorRoute-DNr7Z8An.js} +1 -1
- package/dist/assets/{DiagramEditorRoute-CImsnhUi.js → DiagramEditorRoute-D9ZA196h.js} +1 -1
- package/dist/assets/{DrawingEditorRoute-DZC9jYFI.js → DrawingEditorRoute-hqLYwgJJ.js} +2 -2
- package/dist/assets/{DrawingsView-CcDDpDnU.js → DrawingsView--VaCC3S0.js} +8 -8
- package/dist/assets/{ERDComments-D-82XdeD.js → ERDComments-qHrQEP9o.js} +1 -1
- package/dist/assets/FlowchartEditorRoute-BMP5LLy3.js +37 -0
- package/dist/assets/{LibraryRoute-BpBU5afN.js → LibraryRoute-YN_31QqE.js} +1 -1
- package/dist/assets/{NoteEditorRoute-LOd9AmhB.js → NoteEditorRoute-cADL-2Ni.js} +2 -2
- package/dist/assets/{NotesView-DfF0eFYg.js → NotesView-q059-fnh.js} +2 -2
- package/dist/assets/{TeamInventoryRoute-DCrW4U6d.js → TeamInventoryRoute-DntLUnuL.js} +1 -1
- package/dist/assets/{TeamManagementRoute-CNqL3r53.js → TeamManagementRoute-CMzEDWT3.js} +1 -1
- package/dist/assets/{TrashView-CJDZpreO.js → TrashView-CWQ7RgmQ.js} +1 -1
- package/dist/assets/{UserManagementRoute-CaWNRx91.js → UserManagementRoute-Chc8vRam.js} +1 -1
- package/dist/assets/WorkspaceProvider-MOKVftiM.js +73 -0
- package/dist/assets/{abnfDiagram-VCTEODGH-Bt4mymL0.js → abnfDiagram-VCTEODGH-DHUqX1Ti.js} +1 -1
- package/dist/assets/{ar-SA-G6X2FPQ2--azOyVSw.js → ar-SA-G6X2FPQ2-Cvq-cYDD.js} +1 -1
- package/dist/assets/{architectureDiagram-5GKGNRK7-DkJBNMa5.js → architectureDiagram-5GKGNRK7-BIFSNxLJ.js} +1 -1
- package/dist/assets/{az-AZ-76LH7QW2-DDOwJYD8.js → az-AZ-76LH7QW2-BFEyhAU6.js} +1 -1
- package/dist/assets/{bg-BG-XCXSNQG7-B7VbPFig.js → bg-BG-XCXSNQG7-CAapyVJP.js} +1 -1
- package/dist/assets/{blockDiagram-I7D4REHJ-CoEmyT7V.js → blockDiagram-I7D4REHJ-C2DfdaK1.js} +1 -1
- package/dist/assets/{bn-BD-2XOGV67Q-D16dowCJ.js → bn-BD-2XOGV67Q-sG99UBZk.js} +1 -1
- package/dist/assets/{c4Diagram-7LVT6UL2-C4Wy_uNM.js → c4Diagram-7LVT6UL2-BG_swUrN.js} +1 -1
- package/dist/assets/{ca-ES-6MX7JW3Y-v4sFkH6n.js → ca-ES-6MX7JW3Y-DOB4Yw9w.js} +1 -1
- package/dist/assets/channel-NhxhaySc.js +1 -0
- package/dist/assets/{chunk-4HAMMTFA-RPio54rT.js → chunk-4HAMMTFA-BJ3ie_Gy.js} +1 -1
- package/dist/assets/{chunk-75Z2AOVW-BLMUNiom.js → chunk-75Z2AOVW-B9Wj4cUh.js} +1 -1
- package/dist/assets/{chunk-DU6HZSFF-D7_ZfhjI.js → chunk-DU6HZSFF-DkXZenN4.js} +1 -1
- package/dist/assets/{chunk-EIO257PC-DWN0ivBC.js → chunk-EIO257PC-B9cEgHGL.js} +1 -1
- package/dist/assets/{chunk-F27PBJKO-_0tt9b8a.js → chunk-F27PBJKO-CT7IwqbU.js} +1 -1
- package/dist/assets/{chunk-GMAD6QVW-DUxXGdK9.js → chunk-GMAD6QVW-CcN_tAyS.js} +1 -1
- package/dist/assets/{chunk-GVQU2GXP-CG7jp5n9.js → chunk-GVQU2GXP-B13Zffck.js} +1 -1
- package/dist/assets/{chunk-IMKFNOWR-CIhLSxGr.js → chunk-IMKFNOWR-CkgoyW5o.js} +1 -1
- package/dist/assets/{chunk-L3NEJ4N5-BlWDW_Ts.js → chunk-L3NEJ4N5-HOCrXgXY.js} +1 -1
- package/dist/assets/{chunk-OSK3NFVY-DMoUJoPJ.js → chunk-OSK3NFVY-C2uJt6ru.js} +1 -1
- package/dist/assets/{chunk-P2QGCYS3-eZMEv2_y.js → chunk-P2QGCYS3-BVYtLkw3.js} +1 -1
- package/dist/assets/{chunk-POPQ4Y6H-BXSf-QLR.js → chunk-POPQ4Y6H-SEk5hbWj.js} +1 -1
- package/dist/assets/{chunk-PWAF6VOD-Bjp9h-x9.js → chunk-PWAF6VOD-8foZ2big.js} +1 -1
- package/dist/assets/{chunk-SHT3W25Y-CrVsiMbi.js → chunk-SHT3W25Y-CF25J551.js} +1 -1
- package/dist/assets/{chunk-SVP7TREG-CyNjcmTn.js → chunk-SVP7TREG-BZcrM1Mw.js} +1 -1
- package/dist/assets/{chunk-TICWLB2K-CAoqQUvb.js → chunk-TICWLB2K-B8TlIIWb.js} +1 -1
- package/dist/assets/classDiagram-ZZMXUADV-Dz3KqZ0Z.js +1 -0
- package/dist/assets/classDiagram-v2-VYDZK3BY-Dz3KqZ0Z.js +1 -0
- package/dist/assets/{cs-CZ-2BRQDIVT-BGUugZ9-.js → cs-CZ-2BRQDIVT-2aA0NByP.js} +1 -1
- package/dist/assets/{cynefinDiagram-5FMLGOSQ-CdGx9ofP.js → cynefinDiagram-5FMLGOSQ-C21UsDxR.js} +1 -1
- package/dist/assets/{da-DK-5WZEPLOC-Zjm3FurR.js → da-DK-5WZEPLOC-Bob5swYI.js} +1 -1
- package/dist/assets/{dagre-GXQ25YYZ-CQ0gUMfh.js → dagre-GXQ25YYZ-CmIoiVuU.js} +1 -1
- package/dist/assets/{de-DE-XR44H4JA-GfGoohG6.js → de-DE-XR44H4JA-BelOvJ1n.js} +1 -1
- package/dist/assets/{diagram-S7CK7UJ4-D9qE59Q7.js → diagram-S7CK7UJ4-C7Lfby4N.js} +1 -1
- package/dist/assets/{diagram-UQ7AKVKN-B82IptWs.js → diagram-UQ7AKVKN-DbSJW_7W.js} +1 -1
- package/dist/assets/{diagram-VSXAHHWV-CKSKxEbu.js → diagram-VSXAHHWV-CtcMdL2b.js} +1 -1
- package/dist/assets/{diagram-VX7I27RA-LwQIcbfC.js → diagram-VX7I27RA-Ddz1unV1.js} +1 -1
- package/dist/assets/{diagram-Z3DM3KII-D_r80QkN.js → diagram-Z3DM3KII-BlPgtXQv.js} +1 -1
- package/dist/assets/{dist-DOUio6Pp.js → dist-CHbb7HXs.js} +4 -4
- package/dist/assets/{ebnfDiagram-PWID7BFC-9rHK0dms.js → ebnfDiagram-PWID7BFC-BxQLZ0BZ.js} +1 -1
- package/dist/assets/{el-GR-BZB4AONW-5fn2HiOK.js → el-GR-BZB4AONW-BgyGUFhg.js} +1 -1
- package/dist/assets/{en-B4ZKOASM-BytYmYl2.js → en-B4ZKOASM-DZnnFHRX.js} +1 -1
- package/dist/assets/{erDiagram-RLTQ6QDP-Dc8zDi7B.js → erDiagram-RLTQ6QDP-SYUmAkyJ.js} +1 -1
- package/dist/assets/{erdActions-DiljTo15.js → erdActions-inhuxtvA.js} +1 -1
- package/dist/assets/{es-ES-U4NZUMDT-CX2E2iaN.js → es-ES-U4NZUMDT-Ck2DCode.js} +1 -1
- package/dist/assets/{eu-ES-A7QVB2H4-BrJ6rlzq.js → eu-ES-A7QVB2H4-BFGR1MzD.js} +1 -1
- package/dist/assets/{fa-IR-HGAKTJCU-B2KPvpKe.js → fa-IR-HGAKTJCU-BjZgBVHE.js} +1 -1
- package/dist/assets/{fi-FI-Z5N7JZ37-Bdgkf0r0.js → fi-FI-Z5N7JZ37-DbfV8hnV.js} +1 -1
- package/dist/assets/flowDiagram-HODETNUW-BmLDwhx3.js +1 -0
- package/dist/assets/{fr-FR-RHASNOE6-l4KPgMRJ.js → fr-FR-RHASNOE6-P7Vq0G2x.js} +1 -1
- package/dist/assets/{ganttDiagram-EL5Y4UJY-DuQWL-co.js → ganttDiagram-EL5Y4UJY-ChyTGYvX.js} +1 -1
- package/dist/assets/{gitGraphDiagram-WWUBYQGX-DBy-Eb35.js → gitGraphDiagram-WWUBYQGX-CN_C-W2Z.js} +1 -1
- package/dist/assets/{gl-ES-HMX3MZ6V-AvcL60PB.js → gl-ES-HMX3MZ6V-p4s08XfQ.js} +1 -1
- package/dist/assets/{he-IL-6SHJWFNN-C5Omikh4.js → he-IL-6SHJWFNN-BSEYgh6W.js} +1 -1
- package/dist/assets/{hi-IN-IWLTKZ5I-BlofyRu8.js → hi-IN-IWLTKZ5I-BtkKDlp-.js} +1 -1
- package/dist/assets/{hu-HU-A5ZG7DT2-DK8gZT4q.js → hu-HU-A5ZG7DT2-Cd5UGDXo.js} +1 -1
- package/dist/assets/{id-ID-SAP4L64H-DhJHTRIg.js → id-ID-SAP4L64H-CfVM83IB.js} +1 -1
- package/dist/assets/{image-GAAHSSAO-broGMmPn.js → image-GAAHSSAO-Tc7WHLNL.js} +1 -1
- package/dist/assets/{index-BmzYcDUd.js → index-DyoIlfgs.js} +32 -32
- package/dist/assets/{infoDiagram-27XIBGKW-BCHEzhoL.js → infoDiagram-27XIBGKW-B5aNccuK.js} +1 -1
- package/dist/assets/{ishikawaDiagram-5VMMS53U-BUd1eLvv.js → ishikawaDiagram-5VMMS53U-hNyGEy7_.js} +1 -1
- package/dist/assets/{it-IT-JPQ66NNP-BwJ8lUkg.js → it-IT-JPQ66NNP-DX6d_hcf.js} +1 -1
- package/dist/assets/{ja-JP-DBVTYXUO-EpjPHHZc.js → ja-JP-DBVTYXUO-DJjxF5Fb.js} +1 -1
- package/dist/assets/{journeyDiagram-3NMN7TZE-BbcTITSt.js → journeyDiagram-3NMN7TZE-DAoNh31I.js} +1 -1
- package/dist/assets/{kaa-6HZHGXH3-BMfUlPZO.js → kaa-6HZHGXH3-4SMtQ6Dg.js} +1 -1
- package/dist/assets/{kab-KAB-ZGHBKWFO-C6dajw5f.js → kab-KAB-ZGHBKWFO-BdzyFWnk.js} +1 -1
- package/dist/assets/{kanban-definition-UXKFOSKX-C3_R55PH.js → kanban-definition-UXKFOSKX-BYuNHrVZ.js} +1 -1
- package/dist/assets/{kk-KZ-P5N5QNE5-C81BWanE.js → kk-KZ-P5N5QNE5-a3k1yfBG.js} +1 -1
- package/dist/assets/{km-KH-HSX4SM5Z-9awPrpeZ.js → km-KH-HSX4SM5Z-s3wdExLB.js} +1 -1
- package/dist/assets/{ko-KR-MTYHY66A-Bs5QO755.js → ko-KR-MTYHY66A-Bap1OLdO.js} +1 -1
- package/dist/assets/{ku-TR-6OUDTVRD-COEi6mEM.js → ku-TR-6OUDTVRD-CRt84VEc.js} +1 -1
- package/dist/assets/{line-BzUfGmLO.js → line-CL_PYajL.js} +1 -1
- package/dist/assets/{lt-LT-XHIRWOB4-CW3IUvlE.js → lt-LT-XHIRWOB4-BlkV6pN3.js} +1 -1
- package/dist/assets/{lv-LV-5QDEKY6T-CgVgw9-V.js → lv-LV-5QDEKY6T-CT3isjOE.js} +1 -1
- package/dist/assets/{mindmap-definition-YA3MSWOX-q2IqZX9T.js → mindmap-definition-YA3MSWOX-CDI8ZMPN.js} +1 -1
- package/dist/assets/{mr-IN-CRQNXWMA-sZlmN46K.js → mr-IN-CRQNXWMA-CuQmIXX2.js} +1 -1
- package/dist/assets/{my-MM-5M5IBNSE-fnbbMdxt.js → my-MM-5M5IBNSE-xHpNidNX.js} +1 -1
- package/dist/assets/{nb-NO-T6EIAALU-oZZyl0AF.js → nb-NO-T6EIAALU-BUd_Az2f.js} +1 -1
- package/dist/assets/{nl-NL-IS3SIHDZ-DxN9t62l.js → nl-NL-IS3SIHDZ-CkbWJlSl.js} +1 -1
- package/dist/assets/{nn-NO-6E72VCQL-CU4BFtht.js → nn-NO-6E72VCQL-ZOSRMxxs.js} +1 -1
- package/dist/assets/{note-importer-CXF4vGwS.js → note-importer-BVSMXTRI.js} +2 -2
- package/dist/assets/{oc-FR-POXYY2M6-DrqGbo5c.js → oc-FR-POXYY2M6-Cmoj8lMy.js} +1 -1
- package/dist/assets/{pa-IN-N4M65BXN-Ce9AMnKQ.js → pa-IN-N4M65BXN-BPfBdbre.js} +1 -1
- package/dist/assets/{pegDiagram-XKGWAZYB-CkxpQ_DM.js → pegDiagram-XKGWAZYB-CfuWczeB.js} +1 -1
- package/dist/assets/percentages-BXMCSKIN-Cog3LV23.js +1 -0
- package/dist/assets/{pieDiagram-E7YTZNPT-YXfNOWA2.js → pieDiagram-E7YTZNPT-CkI29A8c.js} +1 -1
- package/dist/assets/{pl-PL-T2D74RX3-DThbuUC6.js → pl-PL-T2D74RX3-XdE4y2Wv.js} +1 -1
- package/dist/assets/{popover-KvEB-gKU.js → popover-Z8Yqyyr4.js} +1 -1
- package/dist/assets/{pt-BR-5N22H2LF-BOsgDpMr.js → pt-BR-5N22H2LF-BK1a_AsU.js} +1 -1
- package/dist/assets/{pt-PT-UZXXM6DQ-BFr_TbS3.js → pt-PT-UZXXM6DQ-CEnOctW4.js} +1 -1
- package/dist/assets/{quadrantDiagram-AXDQQJYC-D7Wjx2KQ.js → quadrantDiagram-AXDQQJYC-CS5SjC2o.js} +1 -1
- package/dist/assets/{railroadDiagram-O6MQD6OU-DpFZbEvK.js → railroadDiagram-O6MQD6OU-c2C19s7v.js} +1 -1
- package/dist/assets/{requirementDiagram-BXWQKSXE-D047Ipe-.js → requirementDiagram-BXWQKSXE-DZzcVjRs.js} +1 -1
- package/dist/assets/{ro-RO-JPDTUUEW-DLJxUpAq.js → ro-RO-JPDTUUEW-B73QPD04.js} +1 -1
- package/dist/assets/{ru-RU-B4JR7IUQ-IhX7xL7S.js → ru-RU-B4JR7IUQ-DNfOF7KC.js} +1 -1
- package/dist/assets/{sankeyDiagram-P5KCCOFB-B6-qg4sh.js → sankeyDiagram-P5KCCOFB-B7ouF0-d.js} +1 -1
- package/dist/assets/{sequenceDiagram-WJ2MYXX4-2LUkCuZO.js → sequenceDiagram-WJ2MYXX4-z0FTW9cy.js} +1 -1
- package/dist/assets/{si-LK-N5RQ5JYF-HzzbW2B4.js → si-LK-N5RQ5JYF-r6ECervK.js} +1 -1
- package/dist/assets/{sk-SK-C5VTKIMK-tbaEai2g.js → sk-SK-C5VTKIMK-9tZaW--1.js} +1 -1
- package/dist/assets/{sl-SI-NN7IZMDC-Da3SkD_q.js → sl-SI-NN7IZMDC-DJc9Nl4H.js} +1 -1
- package/dist/assets/{stateDiagram-D77RDMKH-C_h2n4j0.js → stateDiagram-D77RDMKH-Bk9uyF0P.js} +1 -1
- package/dist/assets/stateDiagram-v2-MP3YSRHH-DGVOd7oY.js +1 -0
- package/dist/assets/subset-shared.chunk-Ccbubijt.js +1 -0
- package/dist/assets/{subset-worker.chunk-lRsT31Ad.js → subset-worker.chunk-sFSCZQeg.js} +1 -1
- package/dist/assets/{sv-SE-XGPEYMSR-B3ugNLyS.js → sv-SE-XGPEYMSR-BFq225pT.js} +1 -1
- package/dist/assets/{swimlanes-42K2YHIH-aT3DZzpB.js → swimlanes-42K2YHIH-Dd1AKEMx.js} +1 -1
- package/dist/assets/swimlanesDiagram-VR7AAH4N-C8Hwv-MB.js +8 -0
- package/dist/assets/{ta-IN-2NMHFXQM-BsWzJE8n.js → ta-IN-2NMHFXQM-D32uDt2k.js} +1 -1
- package/dist/assets/{th-TH-HPSO5L25-QGRu9Gh7.js → th-TH-HPSO5L25-DqykOcUQ.js} +1 -1
- package/dist/assets/{timeline-definition-24CTP7MA-D3ELQSb4.js → timeline-definition-24CTP7MA-0oiBE0Uo.js} +1 -1
- package/dist/assets/{tr-TR-DEFEU3FU-BnkuiXgs.js → tr-TR-DEFEU3FU-mTOptPjT.js} +1 -1
- package/dist/assets/{uk-UA-QMV73CPH-DBlYBJ6x.js → uk-UA-QMV73CPH-BLxmnvYy.js} +1 -1
- package/dist/assets/{useLeaveGuard-CIvnBiTC.js → useLeaveGuard-CiGeeiIG.js} +1 -1
- package/dist/assets/{vennDiagram-4TSXK5OY-ad8x8Wjc.js → vennDiagram-4TSXK5OY-DILhzDZH.js} +1 -1
- package/dist/assets/{vi-VN-M7AON7JQ-C7nM8d7I.js → vi-VN-M7AON7JQ-Bbbs76u8.js} +1 -1
- package/dist/assets/{w3c-keyname-CoFQoJdm.js → w3c-keyname-fq7KcIwM.js} +1 -1
- package/dist/assets/{wardleyDiagram-VM6X3IG4-DFFusrjK.js → wardleyDiagram-VM6X3IG4-Cakg2cgm.js} +1 -1
- package/dist/assets/{xychartDiagram-S5SC5T6Z-1juzmiPV.js → xychartDiagram-S5SC5T6Z-tDqsJyoQ.js} +1 -1
- package/dist/assets/{zh-CN-LNUGB5OW-CbWZCdmx.js → zh-CN-LNUGB5OW-CuNQt9Vl.js} +1 -1
- package/dist/assets/{zh-HK-E62DVLB3-C9zlSsbH.js → zh-HK-E62DVLB3-BZ6cIm63.js} +1 -1
- package/dist/assets/{zh-TW-RAJ6MFWO-D7DSfYlB.js → zh-TW-RAJ6MFWO-BMhYC2Ij.js} +1 -1
- package/dist/index.html +7 -7
- package/dist-server/index.js +167 -164
- package/package.json +1 -1
- package/dist/assets/DataViewerModeToolbar-Xpdkr995.js +0 -106
- package/dist/assets/FlowchartEditorRoute-BYC11sHI.js +0 -37
- package/dist/assets/WorkspaceProvider-8C3zmjQf.js +0 -73
- package/dist/assets/channel-Da9ipVH7.js +0 -1
- package/dist/assets/classDiagram-ZZMXUADV-kif6o-GI.js +0 -1
- package/dist/assets/classDiagram-v2-VYDZK3BY-kif6o-GI.js +0 -1
- package/dist/assets/flowDiagram-HODETNUW-BXb9iJR0.js +0 -1
- package/dist/assets/percentages-BXMCSKIN-BPoKmL6Q.js +0 -1
- package/dist/assets/stateDiagram-v2-MP3YSRHH-Bv-HnQDe.js +0 -1
- package/dist/assets/subset-shared.chunk-tzGmQSAx.js +0 -1
- package/dist/assets/swimlanesDiagram-VR7AAH4N-Bpm8srly.js +0 -8
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import{o as e}from"./rolldown-runtime-BCiCTKAo.js";import{n as t,t as n}from"./jsx-runtime-Cl3nUQcN.js";import{a as r,i,o as a,s as o}from"./createLucideIcon-DCn6SI1F.js";import{d as s}from"./chunk-BV7QT456-B3UxAK3W.js";import{A as c,C as l,Ct as u,D as d,Dt as f,E as p,F as m,M as h,N as g,O as _,Ot as v,P as y,S as b,St as x,T as S,Tt as C,_ as w,a as T,b as E,bt as D,c as O,ct as k,d as A,dt as ee,f as j,ft as M,g as N,h as P,ht as F,it as te,j as I,l as ne,lt as L,m as re,o as R,p as z,s as B,st as V,u as ie,ut as H,vt as U,w as ae,wt as oe,x as se,xt as ce,yt as le}from"./note-importer-BVSMXTRI.js";import{t as W}from"./button-CYI0LXM3.js";import{s as ue}from"./useField-E2Vk7I_Z.js";import{c as de,d as fe,l as pe,n as me,o as he,r as ge,t as _e}from"./popover-Z8Yqyyr4.js";import{a as G,d as ve,f as ye,l as be,r as xe,s as Se,t as Ce,u as we}from"./dropdown-menu-BoXeiuAZ.js";import{t as Te}from"./check-BwjD7EK2.js";import{r as Ee}from"./getPseudoElementBounds-BEHunO5c.js";import{A as De,Ct as Oe,D as ke,Et as K,O as q,P as Ae,Tt as je,Y as J,a as Me,at as Ne,i as Pe,k as Fe,n as Ie,ot as Le,r as Re,t as ze}from"./ERDComments-qHrQEP9o.js";import{A as Be,C as Ve,D as He,E as Ue,O as We,S as Ge,T as Ke,_ as qe,b as Je,g as Ye,h as Xe,i as Ze,k as Qe,v as $e,w as et,x as tt,y as nt}from"./w3c-keyname-fq7KcIwM.js";import{n as rt,t as Y}from"./refresh-cw-DyBeWpoi.js";import{t as it}from"./chevron-left-D_Hf28gP.js";import{i as at,n as ot,o as st,s as ct,t as X}from"./select-CdQCv8yP.js";import{n as lt,t as ut}from"./ConfirmModal-pEN41Kyx.js";import{a as dt,c as ft,d as pt,f as mt,h as ht,i as gt,l as _t,m as vt,n as yt,o as bt,p as xt,s as St,t as Ct,u as wt}from"./erdActions-inhuxtvA.js";import{r as Tt}from"./pen-tool-CoHyO7pC.js";import{t as Et}from"./ellipsis-CfqIMSId.js";import{a as Dt,i as Ot,o as kt,r as At,t as jt}from"./field-BXvmJTfd.js";import{n as Mt,r as Nt,t as Pt}from"./redo-2-CUB0gf4Y.js";import{t as Ft}from"./message-square-B1YYK_eY.js";import{_ as It,a as Lt,d as Rt,i as zt,l as Bt,n as Vt,o as Ht,s as Ut,t as Wt,v as Gt}from"./dialog-BIk9Y-3N.js";import{t as Kt}from"./sparkles-BTRhjhc4.js";import{t as qt}from"./trash-2-CV7XVyhd.js";import{C as Jt,a as Yt,c as Xt,i as Zt,l as Qt,n as $t,o as en,r as tn,s as nn,t as rn,u as an}from"./alert-dialog-DXnJdv-M.js";import{t as on}from"./undo-2-eBLOetyj.js";import{c as sn,n as cn,o as ln}from"./api-DuV0sTuY.js";import{t as Z}from"./input-CMgoax5D.js";import{C as un,D as dn,E as fn,S as pn,T as mn,_ as hn,b as gn,c as _n,d as vn,f as yn,g as bn,h as xn,l as Sn,m as Cn,n as wn,o as Tn,p as En,r as Dn,t as On,u as kn,v as An,w as jn,x as Mn,y as Nn}from"./useLeaveGuard-CiGeeiIG.js";import{A as Pn,C as Fn,D as In,E as Ln,G as Rn,S as zn,T as Bn,a as Vn,b as Hn,d as Un,f as Wn,i as Gn,j as Kn,k as qn,m as Jn,p as Yn,u as Xn,w as Zn,x as Qn,y as $n}from"./WorkspaceProvider-MOKVftiM.js";import{t as er}from"./localPersistence-CGAJ2Ky5.js";import{n as tr}from"./WorkspaceContext-CitlpD55.js";import{t as nr}from"./label-CfaCFYRS.js";import{A as rr,B as ir,F as ar,H as or,I as sr,L as cr,M as lr,N as ur,R as dr,U as fr,Y as pr,k as mr,ln as hr,z as gr}from"./index-DyoIlfgs.js";/* empty css */var Q=e(t(),1),$=n(),_r=e=>e?.replace(/^col-/,``).replace(/-(source|target)(-(l|r))?$/,``);function vr(e,t){return e.source===t.source&&e.target===t.target&&_r(e.sourceHandle)===_r(t.sourceHandle)&&_r(e.targetHandle)===_r(t.targetHandle)}function yr(e,t){let n=t?.nodes||{},r=new Set(e.flatMap(e=>(e.foreign_keys||[]).map(e=>`${e.ref_table}.${e.ref_column}`))),i=e.map((e,t)=>{let i=n[e.table_name]||{};return{id:e.table_name,type:`entity`,position:{x:i.x??t%4*280+50,y:i.y??Math.floor(t/4)*220+50},data:{id:e.table_name,name:e.table_name,x:i.x??0,y:i.y??0,color:i.color??`#6b7280`,columns:(e.columns||[]).map(t=>({...p(t,`${e.table_name}.${t.name}`),_is_fk:(e.foreign_keys||[]).some(e=>e.column===t.name),_is_ref:r.has(`${e.table_name}.${t.name}`)})),collapsed:i.collapsed??!1,hidden_columns:i.hidden_columns??[],note:i.note??``,isReadOnly:!0}}}),a=[],o=new Map(i.map(e=>[e.id,new Set(e.data.columns.map(e=>e.name))]));for(let n of e)for(let e of n.foreign_keys||[]){if(!o.get(n.table_name)?.has(e.column)||!o.get(e.ref_table)?.has(e.ref_column))continue;let r=`${n.table_name}.${e.column}->${e.ref_table}.${e.ref_column}`,i=t?.edgeHandles?.[r]||{};a.push({id:r,source:n.table_name,target:e.ref_table,sourceHandle:i.sourceHandle||`col-${n.table_name}.${e.column}-source`,targetHandle:i.targetHandle||`col-${e.ref_table}.${e.ref_column}-target`,type:`smoothstep`,data:{constraint_name:e.constraint_name,on_delete:e.on_delete,on_update:e.on_update}})}if(!Object.keys(n).length){let e=E(i,a);return{nodes:e,edges:se(e,a)}}return{nodes:i,edges:a}}function br(e,t,n,r){let i=Object.fromEntries(e.map(e=>[e.id,{x:e.position.x,y:e.position.y,color:e.data.color,collapsed:e.data.collapsed??!1,hidden_columns:e.data.hidden_columns??[],note:e.data.note??``}])),a=r&&Object.fromEntries(r.map(e=>[e.id,{sourceHandle:e.sourceHandle,targetHandle:e.targetHandle}]));return{...n,nodes:i,viewport:t,...a?{edgeHandles:a}:{},_type:`production_db_positions`}}var xr=`erd-production-db-tabs:`,Sr=new Map,Cr=new Map;function wr(e){let t=Sr.get(e);return t||(t=new Map,Sr.set(e,t),Sr.size>5&&Sr.delete(Sr.keys().next().value)),t}var Tr=e=>Cr.get(e),Er=(e,t)=>{Cr.set(e,t),Cr.size>5&&Cr.delete(Cr.keys().next().value)},Dr=e=>Cr.delete(e),Or=(e=``)=>({id:crypto.randomUUID(),enabled:!0,column:e,operator:`CONTAINS`,value:``,value2:``}),kr=(0,Q.createContext)(null),Ar=()=>(0,Q.useContext)(kr),jr=`erdbpro:notes-companion-edit-entity`,Mr=`!w-2 !h-2 !border-none cursor-crosshair opacity-0 transition-opacity duration-150 group-hover:!opacity-100 group-focus-within:!opacity-100`,Nr=(0,Q.memo)(({col:e,borderColor:t,typeColor:n,hideHandles:r,onDoubleClick:i})=>{let a=e._is_fk,s=e.diffState,c=(0,Q.useMemo)(()=>({top:`50%`,left:`-4px`,transform:`translate(-50%, -50%)`,backgroundColor:t,zIndex:50}),[t]),l=(0,Q.useMemo)(()=>({top:`50%`,right:`-4px`,transform:`translate(50%, -50%)`,backgroundColor:t,zIndex:50}),[t]),u=(0,Q.useMemo)(()=>s===`new`?`bg-emerald-500/10 hover:bg-emerald-500/15 border-b border-emerald-500/20`:s===`deleted`?`bg-red-500/10 hover:bg-red-500/15 line-through opacity-50 border-b border-red-500/20`:`border-border/50 hover:bg-muted`,[s]);return(0,$.jsxs)(`div`,{className:o(`erd-column-row group relative px-3 py-2 flex items-center justify-between transition-colors border-b last:border-b-0`,u),title:e.comment||void 0,onDoubleClick:i,children:[r?(0,$.jsxs)($.Fragment,{children:[e._is_ref&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(M,{type:`target`,position:C.Left,id:`col-${e.id}-target`,className:Mr,style:c}),(0,$.jsx)(M,{type:`target`,position:C.Right,id:`col-${e.id}-target-r`,className:Mr,style:l})]}),e._is_fk&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(M,{type:`source`,position:C.Left,id:`col-${e.id}-source-l`,className:Mr,style:c}),(0,$.jsx)(M,{type:`source`,position:C.Right,id:`col-${e.id}-source`,className:Mr,style:l})]})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(M,{type:`target`,position:C.Left,id:`col-${e.id}-target`,className:Mr,style:c}),(0,$.jsx)(M,{type:`source`,position:C.Left,id:`col-${e.id}-source-l`,className:Mr,style:c}),(0,$.jsx)(M,{type:`source`,position:C.Right,id:`col-${e.id}-source`,className:Mr,style:l}),(0,$.jsx)(M,{type:`target`,position:C.Right,id:`col-${e.id}-target-r`,className:Mr,style:l})]}),(0,$.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,$.jsx)(`span`,{className:o(`text-sm font-medium`,e.is_pk?`text-foreground`:`text-foreground/80`,s===`new`&&`text-emerald-400 font-semibold`,s===`deleted`&&`text-red-400/80 line-through`),children:s===`new`?`+ ${e.name}`:s===`deleted`?`- ${e.name}`:e.name})}),(0,$.jsxs)(`div`,{className:`flex flex-col items-end gap-0.5 max-w-35`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:`text-[11px] font-mono font-semibold`,style:{color:s===`new`?`#10b981`:s===`deleted`?`#ef4444`:n},children:d(e.type,e.max_length,e.numeric_precision,e.numeric_scale).toLowerCase()}),e.comment&&(0,$.jsx)(Ft,{className:`w-3 h-3 text-muted-foreground`}),(e.is_pk||a)&&(0,$.jsxs)(`div`,{className:`flex items-center gap-1`,children:[e.is_pk&&(0,$.jsx)(`span`,{className:`text-[10px] font-bold text-foreground/40 uppercase tracking-tighter`,children:`pk`}),a&&(0,$.jsx)(`span`,{className:`text-[10px] font-bold text-foreground/40 uppercase tracking-tighter`,children:`fk`})]})]}),e.type.toUpperCase()===`ENUM`&&e.enum_values&&(0,$.jsxs)(`span`,{className:`font-mono italic text-right leading-tight wrap-break-word max-w-full text-[8.5px] text-muted-foreground`,children:[`(`,e.enum_values,`)`]})]})]})}),Pr=(0,Q.memo)(({data:e,id:t,selected:n})=>{let r=Me(),{isReadOnly:i,duplicateEntity:a,sourceType:s,setSelectedNodeId:c}=Rn(),l=Ar(),u=!!e._notesCompanion,d=!u&&(s===`production_db`||!!e.isReadOnly),f=i||!!e.isDiffMode||d,[p,m]=(0,Q.useState)(!1),h=ce(),g=(0,Q.useMemo)(()=>e.columns.map(e=>`${e.id}-${e.name}-${e.sort_order}`).join(`,`),[e.columns]);(0,Q.useEffect)(()=>{h(t)},[t,g,h]);let _=(0,Q.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),!f&&(u?window.dispatchEvent(new CustomEvent(jr,{detail:{id:t}})):(c(t),l?.(t)))},[f,u,t,c,l]),v=(0,Q.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),!f&&m(!0)},[f]),y=(0,Q.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),!f&&a(t)},[f,a,t]),b=e=>{e.preventDefault(),e.stopPropagation(),window.dispatchEvent(new CustomEvent(Re,{detail:{type:`table`,id:t}}))},x=()=>{window.dispatchEvent(new CustomEvent(`deleteEntity`,{detail:t})),m(!1)},S=e.diffState,{borderColor:C,headerBg:w,typeColor:T}=(0,Q.useMemo)(()=>S===`new`?{borderColor:`#10b981`,headerBg:`rgba(16, 185, 129, 0.15)`,typeColor:`#10b981`}:S===`deleted`?{borderColor:`#ef4444`,headerBg:`rgba(239, 68, 68, 0.15)`,typeColor:`#ef4444`}:S===`modified`?{borderColor:`#f59e0b`,headerBg:`rgba(245, 158, 11, 0.15)`,typeColor:`#f59e0b`}:{borderColor:e.color,headerBg:`${e.color}20`,typeColor:e.color},[e.color,S]),E=(0,Q.useMemo)(()=>o(`bg-card text-foreground rounded-lg border-2 min-w-[220px] erd-node-container`,n&&`ring-2 ring-primary/50`,S===`new`&&`shadow-[0_0_20px_rgba(16,185,129,0.35)] border-emerald-500/50`,S===`deleted`&&`opacity-40 shadow-[0_0_15px_rgba(239,68,68,0.25)] border-red-500/50`,S===`modified`&&`shadow-[0_0_20px_rgba(245,158,11,0.3)] border-amber-500/50`),[n,S]),D=(0,Q.useMemo)(()=>[...e.columns].sort((e,t)=>(e.sort_order||0)-(t.sort_order||0)),[e.columns]),O=(!i||!!r)&&!u&&!d&&!e.isDiffMode,k=(0,$.jsxs)(`div`,{className:`relative`,children:[!e.isDiffMode&&(0,$.jsx)(`div`,{className:`absolute -right-1 -top-1 z-20`,children:(0,$.jsx)(ze,{anchor:{type:`table`,id:t}})}),(0,$.jsxs)(`div`,{className:E,style:{borderColor:C,overflow:`visible`},children:[(0,$.jsxs)(`div`,{className:`px-3 py-2 flex items-center justify-between border-b-2 cursor-pointer group/header`,style:{backgroundColor:w,borderColor:C},onDoubleClick:f?void 0:_,title:f?void 0:`Double-click to edit table`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Tt,{className:`w-4 h-4 transition-transform group-hover/header:rotate-12`,style:{color:C}}),(0,$.jsx)(`span`,{className:o(`font-bold text-sm tracking-wide uppercase`,S===`deleted`&&`line-through text-red-400`),children:e.name}),S===`new`&&(0,$.jsx)(`span`,{className:`px-1 py-0.5 text-[8px] font-bold bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 rounded uppercase tracking-wider`,children:`NEW`}),S===`deleted`&&(0,$.jsx)(`span`,{className:`px-1 py-0.5 text-[8px] font-bold bg-red-500/20 text-red-400 border border-red-500/30 rounded uppercase tracking-wider`,children:`DEL`}),S===`modified`&&(0,$.jsx)(`span`,{className:`px-1 py-0.5 text-[8px] font-bold bg-amber-500/20 text-amber-400 border border-amber-500/30 rounded uppercase tracking-wider`,children:`MOD`})]}),!u&&(!f||i&&!!r&&!e.isDiffMode&&!d)&&(0,$.jsxs)(Ce,{children:[(0,$.jsx)(ye,{className:`nodrag nopan p-1 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors focus:outline-none`,onPointerDown:e=>e.stopPropagation(),onPointerUp:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),onDoubleClick:e=>e.stopPropagation(),children:(0,$.jsx)(Et,{className:`w-4 h-4`})}),(0,$.jsxs)(xe,{align:`end`,className:`w-44 bg-popover border-border text-popover-foreground z-1000`,onPointerDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),children:[!f&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(G,{onClick:_,className:`cursor-pointer hover:bg-muted focus:bg-muted`,children:[(0,$.jsx)(tt,{className:`w-4 h-4 mr-2`}),`Edit`]}),(0,$.jsxs)(G,{onClick:y,className:`cursor-pointer hover:bg-muted focus:bg-muted`,children:[(0,$.jsx)(hr,{className:`w-4 h-4 mr-2`}),`Duplicate`]})]}),r&&(0,$.jsxs)(G,{onClick:b,className:`cursor-pointer hover:bg-muted focus:bg-muted`,children:[(0,$.jsx)(Ft,{className:`w-4 h-4 mr-2`}),`Comment`]}),!f&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Se,{className:`bg-border`}),(0,$.jsxs)(G,{onClick:v,className:`cursor-pointer text-destructive focus:text-destructive hover:bg-destructive/10 focus:bg-destructive/10`,children:[(0,$.jsx)(qt,{className:`w-4 h-4 mr-2`}),`Delete Table`]})]})]})]})]}),(0,$.jsx)(`div`,{className:o(`flex flex-col`,!f&&`cursor-pointer`),onDoubleClick:f?void 0:_,title:f?void 0:`Double-click to edit table`,children:D.map(e=>(0,$.jsx)(Nr,{col:e,borderColor:C,typeColor:T,hideHandles:d,onDoubleClick:f?void 0:_},e.id))})]})]});return(0,$.jsxs)($.Fragment,{children:[O?(0,$.jsxs)(ke,{children:[(0,$.jsx)(Ae,{className:`contents`,children:k}),(0,$.jsxs)(q,{className:`w-48`,children:[!f&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(Fe,{onClick:_,children:[(0,$.jsx)(tt,{"aria-hidden":`true`}),`Edit`]}),(0,$.jsxs)(Fe,{onClick:y,children:[(0,$.jsx)(hr,{"aria-hidden":`true`}),`Duplicate`]})]}),r&&(0,$.jsxs)(Fe,{onClick:b,children:[(0,$.jsx)(Ft,{"aria-hidden":`true`}),`Comment`]}),!f&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(De,{}),(0,$.jsxs)(Fe,{variant:`destructive`,onClick:v,children:[(0,$.jsx)(qt,{"aria-hidden":`true`}),`Delete`]})]})]})]}):k,(0,$.jsx)(rn,{open:p,onOpenChange:m,children:(0,$.jsxs)(Yt,{size:`sm`,className:`max-w-100`,children:[(0,$.jsxs)(Xt,{children:[(0,$.jsx)(Qt,{className:`bg-destructive/10`,children:(0,$.jsx)(Jt,{className:`w-5 h-5 text-destructive`})}),(0,$.jsx)(an,{children:`Delete Table`})]}),(0,$.jsx)(tn,{children:(0,$.jsxs)(en,{children:[`Are you sure you want to delete the table `,(0,$.jsx)(`strong`,{children:e.name}),`? This action cannot be undone.`]})}),(0,$.jsxs)(nn,{children:[(0,$.jsx)(Zt,{onClick:e=>{e.stopPropagation(),m(!1)},children:`Cancel`}),(0,$.jsx)($t,{onClick:e=>{e.stopPropagation(),x()},className:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,children:`Delete`})]})]})})]})});function Fr(e){if(e.kind===`column`){let t=e.id.replace(/^column:/,``);return t.slice(0,t.lastIndexOf(`.`))}return e.kind===`relation`?e.label.split(`.`)[0]:e.label}function Ir(e){return e.kind===`column`?e.label.slice(e.label.lastIndexOf(`.`)+1):e.kind===`table`?`Table definition`:e.label}function Lr(e){if(e.kind===`table`)return`TABLE`;if(e.kind===`relation`)return`FK`;let t=e.proposed??e.current;return t&&`is_pk`in t?t.type:`—`}function Rr({diff:e,approvedIds:t,showChecklist:n,label:r,rejectLabel:i=`Reject All`,canMerge:a=!0,selectable:s=a,checklistTitle:c=`Select changes to merge:`,onApprovedIdsChange:l,onShowChecklistChange:u,onReject:d,onMerge:f}){let p=(0,Q.useMemo)(()=>e.changes.map(e=>e.id),[e.changes]),m=(0,Q.useMemo)(()=>{let t=new Map;for(let n of e.changes){let e=Fr(n);t.set(e,[...t.get(e)||[],n])}return[...t]},[e.changes]),h=(0,Q.useMemo)(()=>[`table`,`column`,`relation`].map(t=>{let n=e.changes.filter(e=>e.kind===t).length;return n?`${n} ${t}${n===1?``:`s`}`:null}).filter(Boolean).join(` · `),[e.changes]),g=t.length===p.length;return(0,$.jsxs)(`div`,{"data-pending-review":!0,className:`pointer-events-none absolute inset-x-0 bottom-4 z-50 flex flex-col items-center justify-center gap-2.5 px-3`,children:[n&&(0,$.jsxs)(`div`,{className:`pointer-events-auto w-[min(560px,100%)] rounded-2xl border bg-popover/95 p-4 shadow-2xl backdrop-blur-md`,children:[(0,$.jsxs)(`div`,{className:`mb-3 flex items-center justify-between gap-3`,children:[(0,$.jsx)(`span`,{className:`text-[10px] font-bold uppercase tracking-wider text-muted-foreground`,children:c}),s&&(0,$.jsx)(W,{variant:`link`,size:`xs`,onClick:()=>l(g?[]:p),children:g?`Unselect All`:`Select All`})]}),(0,$.jsx)(`div`,{className:`flex max-h-75 flex-col gap-3 overflow-y-auto pr-1 custom-scrollbar`,children:m.map(([e,n])=>(0,$.jsxs)(`section`,{className:`shrink-0 overflow-hidden rounded-lg border`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between border-b bg-muted/50 px-3 py-2`,children:[(0,$.jsx)(`span`,{className:`text-xs font-semibold`,children:e}),(0,$.jsxs)(`span`,{className:`text-[10px] text-muted-foreground`,children:[n.length,` change`,n.length===1?``:`s`]})]}),(0,$.jsxs)(`div`,{className:`grid grid-cols-[auto_minmax(0,1fr)_minmax(72px,auto)_auto] gap-3 border-b px-3 py-1.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground`,children:[(0,$.jsx)(`span`,{}),(0,$.jsx)(`span`,{children:`Column`}),(0,$.jsx)(`span`,{children:`Type`}),(0,$.jsx)(`span`,{children:`Change`})]}),(0,$.jsx)(`div`,{className:`divide-y divide-border`,children:n.map(e=>{let n=t.includes(e.id);return(0,$.jsxs)(`label`,{className:o(`grid cursor-pointer grid-cols-[auto_minmax(0,1fr)_minmax(72px,auto)_auto] items-center gap-3 px-3 py-2.5 transition-colors`,n?`bg-background text-foreground hover:bg-muted/50`:`bg-muted/20 text-muted-foreground hover:bg-muted/40`),children:[s?(0,$.jsx)(or,{checked:n,onCheckedChange:()=>l(n?t.filter(t=>t!==e.id):[...t,e.id]),className:`border-border bg-transparent data-checked:border-emerald-500 data-checked:bg-emerald-500`}):(0,$.jsx)(`span`,{className:`size-2 rounded-full bg-muted-foreground/50`}),(0,$.jsx)(`span`,{className:`min-w-0 truncate text-sm font-medium`,children:Ir(e)}),(0,$.jsx)(`code`,{className:`truncate font-mono text-xs text-muted-foreground`,children:Lr(e)}),(0,$.jsx)(`span`,{className:o(`rounded border px-1.5 py-0.5 text-[10px] font-semibold uppercase`,e.state===`new`&&`border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400`,e.state===`deleted`&&`border-destructive/30 bg-destructive/10 text-destructive`,e.state===`modified`&&`border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400`),children:e.state})]},e.id)})})]},e))})]}),(0,$.jsxs)(`div`,{className:`pointer-events-auto flex max-w-full items-center gap-2 overflow-x-auto rounded-2xl border bg-popover/95 p-2.5 shadow-2xl backdrop-blur-md no-scrollbar`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 px-1.5`,children:[r&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`size-2 rounded-full bg-emerald-500`}),(0,$.jsx)(`span`,{className:`max-w-52 truncate text-[10px] font-bold uppercase tracking-widest text-muted-foreground`,children:r}),(0,$.jsx)(dn,{orientation:`vertical`,className:`mx-1 h-4`})]}),(0,$.jsxs)(`div`,{className:`flex gap-2 text-[11px] font-bold`,children:[e.newCount>0&&(0,$.jsxs)(`span`,{className:`text-emerald-500`,children:[e.newCount,` New`]}),e.modifiedCount>0&&(0,$.jsxs)(`span`,{className:`text-amber-500`,children:[e.modifiedCount,` Mod`]}),e.deletedCount>0&&(0,$.jsxs)(`span`,{className:`text-destructive`,children:[e.deletedCount,` Del`]})]}),h&&(0,$.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:h})]}),(0,$.jsx)(dn,{orientation:`vertical`,className:`h-6`}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[(0,$.jsx)(W,{variant:`outline`,onClick:()=>u(!n),children:`Review Changes`}),(0,$.jsx)(W,{variant:`destructive`,onClick:d,children:i}),a&&(0,$.jsx)(W,{onClick:f,disabled:t.length===0,children:`Merge Selected`})]})]})]})}var zr=e=>e.trim().toLowerCase(),Br=e=>e?.replace(/^col-/,``).replace(/-(source|target)(-(l|r))?$/,``),Vr=(e,t)=>e.data.columns.find(e=>String(e.id)===Br(t));function Hr(e,t){let n=t.find(t=>t.id===e.source),r=t.find(t=>t.id===e.target);if(!n||!r)return null;let i=Vr(n,e.sourceHandle),a=Vr(r,e.targetHandle);return!i||!a?null:`${zr(n.data.name)}.${zr(i.name)}>${zr(r.data.name)}.${zr(a.name)}`}function Ur(e,t){return e.type.toLowerCase()!==t.type.toLowerCase()||!!e.is_pk!=!!t.is_pk||!!e.is_nullable!=!!t.is_nullable||!!e.is_unique!=!!t.is_unique||(e.default_value??null)!==(t.default_value??null)||(e.comment||``)!==(t.comment||``)||(e.max_length??null)!==(t.max_length??null)||(e.numeric_precision??null)!==(t.numeric_precision??null)||(e.numeric_scale??null)!==(t.numeric_scale??null)||(e.enum_name||``)!==(t.enum_name||``)||(e.enum_values||``)!==(t.enum_values||``)}function Wr(e){let t=t=>zr(e.data.columns.find(e=>String(e.id)===String(t))?.name||t);return JSON.stringify({comment:e.data.comment||``,constraints:(e.data.constraints||[]).map(e=>({kind:e.kind,name:e.name||``,columns:(e.column_ids||[]).map(t),expression:e.expression||``})).sort((e,t)=>JSON.stringify(e).localeCompare(JSON.stringify(t))),indexes:(e.data.indexes||[]).map(e=>({name:e.name||``,columns:e.column_ids.map(t),unique:!!e.is_unique,algorithm:e.algorithm||``})).sort((e,t)=>JSON.stringify(e).localeCompare(JSON.stringify(t)))})}function Gr(e,t){let n=(e,t)=>String(e.data?.[t]||``).toLowerCase();return(e.label||``)!==(t.label||``)||n(e,`on_delete`)!==n(t,`on_delete`)||n(e,`on_update`)!==n(t,`on_update`)||n(e,`constraint_name`)!==n(t,`constraint_name`)}function Kr(e,t,n,r){let i=[],a=new Map(e.map(e=>[zr(e.data.name),e])),o=new Map(n.map(e=>[zr(e.data.name),e])),s=new Set([...a.keys(),...o.keys()]),c=[];for(let e of s){let t=a.get(e),n=o.get(e),r=`table:${e}`;if(!t&&n){i.push({id:r,kind:`table`,state:`new`,label:n.data.name,proposed:n}),c.push({...n,data:{...n.data,diffState:`new`}});continue}if(t&&!n){i.push({id:r,kind:`table`,state:`deleted`,label:t.data.name,current:t}),c.push({...t,data:{...t.data,columns:t.data.columns.map(e=>({...e,diffState:`deleted`})),diffState:`deleted`}});continue}if(!t||!n)continue;let s=new Map(t.data.columns.map(e=>[zr(e.name),e])),l=new Map(n.data.columns.map(e=>[zr(e.name),e])),u=new Set([...s.keys(),...l.keys()]),d=Wr(t)!==Wr(n);d&&i.push({id:r,kind:`table`,state:`modified`,label:t.data.name,current:t,proposed:n});let f=[];for(let n of u){let r=s.get(n),a=l.get(n),o=`column:${e}.${n}`,c=`${t.data.name}.${r?.name||a?.name||n}`;!r&&a?(d=!0,i.push({id:o,kind:`column`,state:`new`,label:c,proposed:a}),f.push({...a,diffState:`new`})):r&&!a?(d=!0,i.push({id:o,kind:`column`,state:`deleted`,label:c,current:r}),f.push({...r,diffState:`deleted`})):r&&a&&Ur(r,a)?(d=!0,i.push({id:o,kind:`column`,state:`modified`,label:c,current:r,proposed:a}),f.push({...a,diffState:`new`})):r&&f.push(r)}c.push({...t,data:{...t.data,columns:f,diffState:d?`modified`:void 0}})}let l=new Map(t.flatMap(t=>{let n=Hr(t,e);return n?[[n,t]]:[]})),u=new Map(r.flatMap(e=>{let t=Hr(e,n);return t?[[t,e]]:[]})),d=new Set([...l.keys(),...u.keys()]);for(let e of d){let t=l.get(e),n=u.get(e),r=`relation:${e}`;!t&&n?i.push({id:r,kind:`relation`,state:`new`,label:e,proposed:n}):t&&!n?i.push({id:r,kind:`relation`,state:`deleted`,label:e,current:t}):t&&n&&Gr(t,n)&&i.push({id:r,kind:`relation`,state:`modified`,label:e,current:t,proposed:n})}return{nodes:c,edges:r,changes:i,newCount:i.filter(e=>e.state===`new`).length,modifiedCount:i.filter(e=>e.state===`modified`).length,deletedCount:i.filter(e=>e.state===`deleted`).length}}var qr=e=>e.trim().toLowerCase(),Jr=e=>e?.replace(/^col-/,``).replace(/-(source|target)(-(l|r))?$/,``),Yr=(e,t,n)=>`col-${t}${e?.match(/-(source|target)(-(l|r))?$/)?.[0]||`-${n}`}`;function Xr(e,t,n){let r=t.find(t=>t.id===e.source),i=t.find(t=>t.id===e.target),a=r?.data.columns.find(t=>t.id===Jr(e.sourceHandle)),o=i?.data.columns.find(t=>t.id===Jr(e.targetHandle)),s=r&&n.find(e=>qr(e.data.name)===qr(r.data.name)),c=i&&n.find(e=>qr(e.data.name)===qr(i.data.name)),l=s&&a&&s.data.columns.find(e=>qr(e.name)===qr(a.name)),u=c&&o&&c.data.columns.find(e=>qr(e.name)===qr(o.name));return!s||!c||!l||!u?null:{...e,source:s.id,target:c.id,sourceHandle:Yr(e.sourceHandle,l.id,`source`),targetHandle:Yr(e.targetHandle,u.id,`target`)}}function Zr(e,t,n,r,i,a){let o=new Set(a),s=new Map(i.changes.map(e=>[e.id,e])),c=new Map(n.map(e=>[qr(e.data.name),e])),l=new Map(e.map(e=>[qr(e.data.name),e])),u=[];for(let[e,t]of l){let n=c.get(e),r=s.get(`table:${e}`);if(!n){r&&o.has(r.id)||u.push(t);continue}let i=!!r&&o.has(r.id),a=t.data.columns.flatMap(t=>{let r=qr(t.name),i=n.data.columns.find(e=>qr(e.name)===r),a=s.get(`column:${e}.${r}`);return i?[a&&o.has(a.id)?i:t]:a&&o.has(a.id)?[]:[t]});for(let r of n.data.columns){let n=qr(r.name);if(t.data.columns.some(e=>qr(e.name)===n))continue;let i=s.get(`column:${e}.${n}`);i&&o.has(i.id)&&a.push(r)}let l=new Set(a.map(e=>String(e.id))),d=(e=[])=>e.every(e=>l.has(String(e)));u.push({...t,data:{...t.data,...i?{comment:n.data.comment,constraints:(n.data.constraints||[]).filter(e=>d(e.column_ids)),indexes:(n.data.indexes||[]).filter(e=>d(e.column_ids))}:{},columns:a}})}for(let[e,t]of c){if(l.has(e))continue;let n=s.get(`table:${e}`);n&&o.has(n.id)&&u.push(t)}let d=t.filter(t=>Xr(t,e,u)),f=new Map(t.flatMap(t=>{let n=Hr(t,e);return n?[[n,t]]:[]}));for(let t of i.changes.filter(e=>e.kind===`relation`&&o.has(e.id))){let r=t.id.replace(/^relation:/,``);if(f.get(r)){let t=d.findIndex(t=>Hr(t,e)===r);t>=0&&d.splice(t,1)}if(t.state!==`deleted`&&t.proposed&&`source`in t.proposed){let e=Xr(t.proposed,n,u);e&&d.push(e)}}return{nodes:ae(u),edges:d}}function Qr(e,t){let[n,r]=(0,Q.useState)(!1),a=(0,Q.useRef)(null),o=(0,Q.useRef)(e),s=(0,Q.useRef)(t);return o.current=e,s.current=t,(0,Q.useEffect)(()=>(r(!1),()=>{a.current?.abort(),a.current=null}),[e]),{sync:(0,Q.useCallback)(async()=>{if(!e||a.current)return;let t=new AbortController,n=ln();a.current=t;let c=()=>a.current===t&&o.current===e&&ln()===n&&!t.signal.aborted;r(!0);try{let n=await cn(`/api/catalogs/${e}/schema`,{method:`POST`,signal:t.signal}),r=await n.json();if(!c())return;if(!n.ok)throw Error(r.error||`Failed to sync schema`);if(!Array.isArray(r.schema))throw Error(`Invalid database schema response`);s.current(r)}catch(e){c()&&i.error(e instanceof Error?e.message:`Failed to sync schema`)}finally{a.current===t&&(a.current=null,r(!1))}},[e]),isSyncing:n}}function $r(e,t=[],n=null){let r=t.length>0,i=Math.max(0,...e.map(e=>e.zIndex??0)),a=i+1e3,o=i+1001;return e.map(e=>{let i=r&&t.some(t=>e.source===t||e.target===t),s=i||e.selected||e.id===n?`var(--edge-selected)`:`var(--edge-color)`,c=[e.className];return i?c.push(`edge-animated-active`):r&&c.push(`edge-dimmed`),{...e,...e.selected?{zIndex:a}:{},...e.id===n?{zIndex:o}:{},type:`smoothstep`,style:{...e.style,stroke:s,strokeWidth:2},markerEnd:{type:oe.Arrow,color:s,width:10,height:10},className:c.filter(Boolean).join(` `)}})}function ei(e){let t=[];for(let n of e){let e=t.at(-1),r=t.at(-2);(e?.x!==n.x||e.y!==n.y)&&(r&&e&&(r.x===e.x&&e.x===n.x||r.y===e.y&&e.y===n.y)&&t.pop(),t.push(n))}return t}function ti(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function ni(e,t,n=[]){let r=ei(e),i=r[t.segment],a=r[t.segment+1];if(!i||!a)return null;let o=Math.abs(a.x-i.x)+Math.abs(a.y-i.y),s=(i.y===a.y?t.width:t.height)/2+12;if(o<s*2)return null;let c=Math.min(1-s/o,Math.max(s/o,t.ratio)),l={x:i.x+(a.x-i.x)*c,y:i.y+(a.y-i.y)*c};return n.some(e=>ti(ri(l,t),e))?null:l}function ri(e,t){return{x:e.x-t.width/2-4,y:e.y-t.height/2-4,width:t.width+8,height:t.height+8}}function ii(e){let t=ei(e.points),n=Math.max(32,e.label.length*7+8);return t.slice(1).flatMap((e,r)=>{let i=t[r],a=Math.abs(e.x-i.x)+Math.abs(e.y-i.y),o=i.y===e.y?n:22,s=o/2+12;if(a<s*2)return[];let c=new Set([a/2,s,a-s]);for(let e=s;e<=a-s;e+=o+12)c.add(e);return[...c].sort((e,t)=>Math.abs(e-a/2)-Math.abs(t-a/2)).map(e=>({segment:r,ratio:e/a,width:n,height:22,shared:!1}))}).sort((e,n)=>Number(t[e.segment].x===t[e.segment+1].x)-Number(t[n.segment].x===t[n.segment+1].x))}function ai(e,t){let n=new Map,r=[],i=[];for(let a of[...e].sort((e,t)=>e.id.localeCompare(t.id))){let o=ii(a).filter(e=>{let n=ri(ni(a.points,e),e);return![...t,...r].some(e=>ti(n,e))}),s=o.find(t=>{let n=ri(ni(a.points,t),t);return!e.some(e=>e.id!==a.id&&e.points.slice(1).some((t,r)=>Jn(e.points[r],t,[n])))});s?(n.set(a.id,s),r.push(ri(ni(a.points,s),s))):o[0]&&i.push(a)}for(let e of i){let i=ii(e).find(n=>{let i=ri(ni(e.points,n),n);return![...t,...r].some(e=>ti(i,e))});i&&n.set(e.id,{...i,shared:!0})}return n}function oi(e,t,n){let r=t.get(e);return r?!r.shared||e===n:!1}var si=(0,Q.createContext)({anchors:new Map,activeId:null});function ci({nodes:e,edges:t,tables:n,activeId:r,children:i}){let{getInternalNode:a}=U(),o=(0,Q.useMemo)(()=>{let r=new Map(e.map(e=>[e.id,e])),i=e=>{let t=a(e),n=r.get(e);return t&&n?{...t,internals:{...t.internals,positionAbsolute:n.position}}:void 0};return ai(t.flatMap(e=>{if(e.label===void 0||e.label===null||e.label===``)return[];let t=i(e.source),r=i(e.target);if(!t||!r)return[];let a=f({id:e.id,sourceNode:t,targetNode:r,sourceHandle:e.sourceHandle??null,targetHandle:e.targetHandle??null,connectionMode:u.Strict});return a?[{id:e.id,label:String(e.label),points:Wn({x:a.sourceX,y:a.sourceY},{x:a.targetX,y:a.targetY},a.sourcePosition===C.Right,a.targetPosition===C.Right,n)}]:[]}),n)},[e,t,n,a]),s=(0,Q.useMemo)(()=>({anchors:o,activeId:r}),[o,r]);return(0,$.jsx)(si.Provider,{value:s,children:i})}var li=(0,Q.createContext)([]);function ui(e){let t=(0,Q.useContext)(li),n=(0,Q.useContext)(si),{getInternalNode:r}=U(),i=le(t=>!!(t.nodeLookup.get(e.source)?.dragging||t.nodeLookup.get(e.target)?.dragging)),{points:a,obstacles:o}=(0,Q.useMemo)(()=>{let n=[r(e.source),r(e.target)].flatMap(e=>e?[{id:e.id,...e.internals.positionAbsolute,...S(e)}]:[]),a=Xn(t,n);return{points:(i?Yn:Wn)({x:e.sourceX,y:e.sourceY},{x:e.targetX,y:e.targetY},e.sourcePosition===C.Right,e.targetPosition===C.Right,a),obstacles:a}},[e.source,e.target,e.sourceX,e.sourceY,e.targetX,e.targetY,e.sourcePosition,e.targetPosition,t,r,i]),s=Un(a),c=n.anchors.get(e.id),l=c?ni(a,c,o):null,u=l&&oi(e.id,n.anchors,n.activeId),d=n.activeId===e.id||e.selected;return(0,$.jsxs)(`g`,{className:d?`erd-edge-active`:void 0,children:[e.label!=null&&(0,$.jsx)(`title`,{children:String(e.label)}),(0,$.jsx)(L,{id:e.id,path:s,markerStart:e.markerStart,markerEnd:e.markerEnd,style:e.style,interactionWidth:e.interactionWidth,label:u?e.label:void 0,labelX:l?.x,labelY:l?.y,labelStyle:d?{...e.labelStyle,fill:`var(--edge-selected)`,fontWeight:600}:e.labelStyle,labelShowBg:e.labelShowBg,labelBgStyle:e.labelBgStyle})]})}function di(e,t){return e===t||e.length===t.length&&e.every((e,n)=>e===t[n])}function fi({isReadOnly:e,isProductionDb:t,addEntity:n,onImportSQL:r,onAutoLayout:i,explorerOpen:a,explorerShortcut:s,onToggleExplorer:c,onOpenDBML:l,onOpenRepository:u,handleSync:d,isSyncing:f,handleExportImage:p,undo:m,redo:h,canUndo:g,canRedo:_}){let v=pr(),y=typeof navigator<`u`&&/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent),b=`Undo (${y?`⌘Z`:`Ctrl+Z`})`,x=`Redo (${y?`⇧⌘Z`:`Ctrl+Y`})`,S=(e,t)=>v?t:(0,$.jsxs)(de,{children:[(0,$.jsx)(fe,{render:t.props.disabled?(0,$.jsx)(`span`,{className:`inline-flex`,children:t}):t}),(0,$.jsx)(pe,{side:`right`,children:e})]}),C=`h-9 px-3 border-border hover:bg-muted bg-muted/50 text-xs font-semibold cursor-pointer`,w=o(`size-3.5`,v&&`sm:mr-1.5`),T=e=>v&&(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:e});return(0,$.jsx)(`div`,{className:o(`absolute z-10 pointer-events-none flex`,v?`top-6 inset-x-0 justify-center px-3`:`top-4 left-4 bottom-28 items-start`),children:(0,$.jsxs)(`div`,{role:`group`,"aria-label":`ERD tools`,className:o(`flex gap-1.5 p-1.5 bg-background/95 backdrop-blur-md border border-border/50 rounded-2xl shadow-2xl pointer-events-auto no-scrollbar`,v?`items-center max-w-full overflow-x-auto`:`flex-col items-center max-h-full overflow-y-auto`),children:[S(`Explorer (${s.label})`,(0,$.jsxs)(W,{onClick:c,variant:a?`secondary`:`outline`,size:v?`sm`:`icon-lg`,"aria-label":`Explorer: tables and relationships`,"aria-pressed":a,"aria-keyshortcuts":t?void 0:s.ariaKeyShortcuts,className:v?C:void 0,children:[(0,$.jsx)(pt,{className:w}),T(`Explorer`)]})),!e&&(0,$.jsx)(`div`,{className:o(`bg-border shrink-0`,v?`w-px h-6 mx-0.5`:`h-px w-6 my-0.5`)}),!e&&S(`Add Table`,(0,$.jsxs)(W,{onClick:n,size:v?`sm`:`icon-lg`,"aria-label":`Add Table`,className:v?`h-9 px-3 sm:px-4 font-bold shadow-lg shadow-primary/20 cursor-pointer`:void 0,children:[(0,$.jsx)(he,{className:o(`size-4`,v&&`sm:mr-2`)}),T(`Add Table`)]})),!e&&S(`Import SQL`,(0,$.jsxs)(W,{onClick:r,variant:`outline`,size:v?`sm`:`icon-lg`,"aria-label":`Import SQL`,className:v?C:void 0,children:[(0,$.jsx)(qe,{className:w}),T(`Import SQL`)]})),!t&&!e&&S(`DBML`,(0,$.jsxs)(W,{onClick:l,variant:`outline`,size:v?`sm`:`icon-lg`,"aria-label":`DBML`,className:v?C:void 0,children:[(0,$.jsx)(Tt,{className:w}),T(`DBML`)]})),!e&&!t&&sn()&&S(`Repository`,(0,$.jsxs)(W,{onClick:u,variant:`outline`,size:v?`sm`:`icon-lg`,"aria-label":`Repository`,className:v?C:void 0,children:[(0,$.jsx)(et,{className:w}),T(`Repository`)]})),i&&(!e||t)&&S(`Auto Layout`,(0,$.jsxs)(W,{onClick:i,variant:`outline`,size:v?`sm`:`icon-lg`,"aria-label":`Auto Layout`,className:v?C:void 0,children:[(0,$.jsx)(Nt,{className:w}),T(`Auto Layout`)]})),t&&S(f?`Syncing...`:`Sync`,(0,$.jsxs)(W,{onClick:d,variant:`outline`,size:v?`sm`:`icon-lg`,"aria-label":f?`Syncing...`:`Sync`,disabled:f,className:v?`h-9 px-3 border-amber-500/50 hover:bg-amber-500/10 bg-amber-500/5 text-amber-600 dark:text-amber-400 text-xs font-semibold cursor-pointer`:void 0,children:[(0,$.jsx)(Y,{className:o(w,f&&`animate-spin`)}),T(f?`Syncing...`:`Sync`)]})),t&&S(`Export SVG`,(0,$.jsxs)(W,{onClick:p,variant:`outline`,size:v?`sm`:`icon-lg`,"aria-label":`Export SVG`,title:v?`Export SVG`:void 0,className:v?C:void 0,children:[(0,$.jsx)(Oe,{className:w}),T(`Export SVG`)]})),!e&&(0,$.jsxs)(`div`,{className:o(`flex gap-0.5`,v?`items-center ml-auto`:`flex-col items-center`),children:[S(b,(0,$.jsx)(W,{variant:`ghost`,size:`icon`,onClick:m,disabled:!g,"aria-label":b,title:v?b:void 0,className:v?`h-8 w-8 text-muted-foreground hover:text-foreground disabled:opacity-30`:void 0,children:(0,$.jsx)(on,{className:`size-4`})})),S(x,(0,$.jsx)(W,{variant:`ghost`,size:`icon`,onClick:h,disabled:!_,"aria-label":x,title:v?x:void 0,className:v?`h-8 w-8 text-muted-foreground hover:text-foreground disabled:opacity-30`:void 0,children:(0,$.jsx)(Pt,{className:`size-4`})}))]})]})})}var pi=e=>e?e.replace(/^col-/,``).replace(/-(source|target)(-(l|r))?$/,``):null;function mi(e,t){let n=pi(t),r=n?e.data.columns.find(e=>e.id===n):void 0;return{nodeId:e.id,table:e.data.name,column:r?.name??n??``,isPk:!!r?.is_pk}}function hi(e,t){let n=new Map(e.map(e=>[e.id,e])),r=a[1].shortLabel;return t.flatMap(e=>{let t=n.get(e.source),i=n.get(e.target);if(!t||!i)return[];let o=mi(t,e.sourceHandle),s=mi(i,e.targetHandle),[c,l]=o.isPk&&!s.isPk?[s,o]:[o,s],u=a.find(t=>t.shortLabel===e.label)?.shortLabel??r,d=String(e.data?.constraint_name??``).trim();return[{id:e.id,fromNodeId:c.nodeId,fromTable:c.table,fromColumn:c.column,toNodeId:l.nodeId,toTable:l.table,toColumn:l.column,type:u,...d?{constraintName:d}:{}}]})}function gi(e,t){let n=t.trim().toLowerCase();return e.filter(e=>!n||`${e.fromTable}.${e.fromColumn} ${e.toTable}.${e.toColumn}`.toLowerCase().includes(n)).sort((e,t)=>e.fromTable.localeCompare(t.fromTable)||e.fromColumn.localeCompare(t.fromColumn)||e.toTable.localeCompare(t.toTable))}function _i(e){(0,Q.useEffect)(()=>{e.current?.querySelector(`[aria-current="true"]`)?.scrollIntoView({block:`nearest`})},[e])}var vi=e=>`${e.fromTable}.${e.fromColumn} → ${e.toTable}.${e.toColumn}`;function yi({rows:e,search:t,onSearchChange:n,activeId:r,onSelect:i,onEdit:a}){let o=(0,Q.useMemo)(()=>gi(e,t),[e,t]),s=(0,Q.useRef)(null);return _i(s),(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`shrink-0 space-y-3 border-b p-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Relationships`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:a?`Find a relationship or edit its properties.`:`Find a relationship on the canvas.`})]}),(0,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsx)(Gt,{className:`absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground`}),(0,$.jsx)(Z,{value:t,onChange:e=>n(e.target.value),placeholder:`Search tables or columns...`,className:`pl-9`,autoFocus:!0})]}),(0,$.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Showing `,o.length,` of `,e.length,` relationships`]})]}),(0,$.jsxs)(`div`,{ref:s,className:`min-h-0 flex-1 space-y-1 overflow-y-auto p-2`,children:[o.map(e=>{let t=vi(e);return(0,$.jsxs)(`div`,{className:`group flex items-center gap-1 rounded-md border border-transparent px-1 hover:border-border hover:bg-muted/50 has-[[aria-current=true]]:bg-muted has-[[aria-current=true]]:shadow-[inset_2px_0_0_var(--primary)]`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>i(e.id),"aria-current":e.id===r?`true`:void 0,className:`flex min-w-0 flex-1 items-start gap-2 px-2 py-2.5 text-left`,title:`Show ${t}`,children:[(0,$.jsx)(Ve,{className:`mt-0.5 size-3.5 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`block truncate font-mono text-xs font-medium`,children:t}),e.constraintName&&(0,$.jsx)(`span`,{className:`block truncate text-[11px] text-muted-foreground`,children:e.constraintName})]}),(0,$.jsx)(fr,{variant:`outline`,className:`shrink-0 font-mono text-[10px]`,children:e.type})]}),a&&(0,$.jsx)(W,{type:`button`,variant:`ghost`,size:`icon-sm`,onClick:()=>a(e.id),title:`Edit ${t}`,"aria-label":`Edit relationship ${t}`,children:(0,$.jsx)(tt,{className:`size-3.5`})})]},e.id)}),o.length===0&&(0,$.jsx)(`div`,{className:`px-3 py-10 text-center text-sm text-muted-foreground`,children:e.length===0?`No relationships yet.`:`No matching relationships found.`})]})]})}function bi(e,t){let n=t.trim().toLowerCase();return e.filter(e=>!n||e.data.name.toLowerCase().includes(n)).sort((e,t)=>e.data.name.localeCompare(t.data.name))}function xi({nodes:e,search:t,onSearchChange:n,activeId:r,onSelect:i,onEdit:a}){let o=(0,Q.useMemo)(()=>bi(e,t),[e,t]),s=(0,Q.useRef)(null);return _i(s),(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`shrink-0 space-y-3 border-b p-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Tables`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:a?`Find a table or open its properties.`:`Find a table on the canvas.`})]}),(0,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsx)(Gt,{className:`absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground`}),(0,$.jsx)(Z,{value:t,onChange:e=>n(e.target.value),placeholder:`Search tables...`,className:`pl-9`,autoFocus:!0})]}),(0,$.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Showing `,o.length,` of `,e.length,` tables`]})]}),(0,$.jsxs)(`div`,{ref:s,className:`min-h-0 flex-1 space-y-1 overflow-y-auto p-2`,children:[o.map(e=>(0,$.jsxs)(`div`,{className:`group flex items-center gap-1 rounded-md border border-transparent px-1 hover:border-border hover:bg-muted/50 has-[[aria-current=true]]:bg-muted has-[[aria-current=true]]:shadow-[inset_2px_0_0_var(--primary)]`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>i(e.id),"aria-current":e.id===r?`true`:void 0,className:`flex min-w-0 flex-1 items-center gap-2 px-2 py-2.5 text-left`,title:`Jump to ${e.data.name}`,children:[(0,$.jsx)(Mt,{className:`size-3.5 shrink-0 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm font-medium`,children:e.data.name}),(0,$.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:e.data.columns.length})]}),a&&(0,$.jsx)(W,{type:`button`,variant:`ghost`,size:`icon-sm`,onClick:()=>a(e.id),title:`Edit ${e.data.name} properties`,"aria-label":`Edit ${e.data.name} properties`,children:(0,$.jsx)(tt,{className:`size-3.5`})})]},e.id)),o.length===0&&(0,$.jsx)(`div`,{className:`px-3 py-10 text-center text-sm text-muted-foreground`,children:`No matching tables found.`})]})]})}var Si={tab:`tables`,tableSearch:``,relationshipSearch:``,activeTableId:null,activeRelationshipId:null,editingEdgeId:null};function Ci({nodes:e,edges:t,state:n,onChange:r,editing:i,onHighlight:a,onClose:s,shortcutLabel:c}){let l=(0,Q.useMemo)(()=>hi(e,t),[e,t]),u=i&&n.editingEdgeId?t.find(e=>e.id===n.editingEdgeId)??null:null,d=u?l.find(e=>e.id===u.id):void 0;return(0,Q.useEffect)(()=>{let i={};n.editingEdgeId&&!t.some(e=>e.id===n.editingEdgeId)&&(i.editingEdgeId=null),n.activeRelationshipId&&!t.some(e=>e.id===n.activeRelationshipId)&&(i.activeRelationshipId=null),n.activeTableId&&!e.some(e=>e.id===n.activeTableId)&&(i.activeTableId=null),Object.keys(i).length&&r(i)},[n.editingEdgeId,n.activeRelationshipId,n.activeTableId,e,t,r]),(0,$.jsxs)(`aside`,{"aria-label":`Explorer`,className:o(`nowheel absolute left-[4.5rem] top-3 bottom-3 z-20 flex w-[300px] max-w-[calc(100%-5.5rem)] flex-col overflow-hidden rounded-xl border bg-popover text-popover-foreground shadow-2xl`,`max-md:left-2 max-md:right-2 max-md:top-20 max-md:w-auto max-md:max-w-none`),children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`text-sm font-semibold`,children:`Explorer`}),(0,$.jsx)(mn,{children:c})]}),(0,$.jsx)(W,{type:`button`,variant:`ghost`,size:`icon-sm`,onClick:s,"aria-label":`Close Explorer`,title:`Close Explorer`,children:(0,$.jsx)(It,{className:`size-4`})})]}),(0,$.jsx)(`div`,{className:`shrink-0 border-b px-3 pt-2 pb-2`,children:(0,$.jsx)(rr,{value:n.tab,onValueChange:e=>r({tab:e}),className:`w-full`,children:(0,$.jsxs)(lr,{className:`w-full`,children:[(0,$.jsxs)(ur,{value:`tables`,children:[`Tables (`,e.length,`)`]}),(0,$.jsxs)(ur,{value:`relationships`,children:[`Relationships (`,l.length,`)`]})]})})}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1`,children:n.tab===`tables`?(0,$.jsx)(xi,{nodes:e,search:n.tableSearch,onSearchChange:e=>r({tableSearch:e}),activeId:n.activeTableId,onSelect:e=>{r({activeTableId:e}),a({type:`table`,id:e})},onEdit:i?e=>{r({activeTableId:e}),i.onEditTable(e)}:void 0}):i&&u?(0,$.jsxs)(`div`,{className:`flex h-full flex-col overflow-hidden`,children:[(0,$.jsx)(`div`,{className:`shrink-0 border-b px-4 py-3`,children:(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 text-xs`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>r({editingEdgeId:null}),className:`flex shrink-0 items-center gap-1 font-medium text-muted-foreground hover:text-foreground`,children:[(0,$.jsx)(rt,{className:`size-3.5`}),` Relationships`]}),(0,$.jsx)(`span`,{className:`text-muted-foreground/50`,children:`/`}),(0,$.jsx)(`span`,{className:`truncate font-mono font-medium text-foreground`,title:d?vi(d):void 0,children:d?vi(d):`Relationship`})]})}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto px-4 py-2`,children:(0,$.jsx)(_n,{selectedEdge:u,nodes:e,onUpdateEdge:i.onUpdateEdge,onFlipEdge:i.onFlipEdge,onDeleteEdge:i.onDeleteEdge})})]}):(0,$.jsx)(yi,{rows:l,search:n.relationshipSearch,onSearchChange:e=>r({relationshipSearch:e}),activeId:n.activeRelationshipId,onSelect:e=>{r({activeRelationshipId:e}),a({type:`relationship`,id:e})},onEdit:i?e=>{r({activeRelationshipId:e,editingEdgeId:e}),a({type:`relationship`,id:e})}:void 0})}),(0,$.jsx)(`p`,{className:`shrink-0 border-t px-3 py-2 text-[11px] text-muted-foreground`,children:i?`Click a row to highlight it on the canvas · ✎ to edit`:`Click a row to highlight it on the canvas`})]})}var wi=[...r].sort((e,t)=>e.localeCompare(t));function Ti({value:e,onValueChange:t,className:n}){return(0,$.jsx)(Xe,{value:e,onChange:t,items:wi,placeholder:`Type`,searchPlaceholder:`Search type...`,emptyMessage:`No types found`,className:n,getItemValue:e=>e,getItemLabel:e=>e,filterItem:(e,t)=>e.toLowerCase().includes(t.toLowerCase())})}var Ei=[{id:`sql`,label:`SQL`,formats:[{id:`mysql`,label:`MySQL`},{id:`postgresql`,label:`PostgreSQL`}]},{id:`laravel`,label:`Laravel`,formats:[{id:`laravel_migration`,label:`Migration`},{id:`laravel_model`,label:`Model`}]},{id:`goravel`,label:`Goravel`,formats:[{id:`goravel`,label:`Model`},{id:`goravel_migration`,label:`Migration`}]},{id:`typescript`,label:`TypeScript`,formats:[{id:`typescript`,label:`Interface`},{id:`zod`,label:`Zod`}]},{id:`prisma`,label:`Prisma`,formats:[{id:`prisma`,label:`Schema`}]}],Di={mysql:Fn,postgresql:Zn,laravel_migration:Qn,laravel_model:zn,goravel:Hn,goravel_migration:$n,typescript:Ln,zod:In,prisma:Bn},Oi={mysql:`sql`,postgresql:`sql`,laravel_migration:`php`,laravel_model:`php`,goravel:`go`,goravel_migration:`go`,typescript:`typescript`,zod:`typescript`,prisma:`prisma`},ki={mysql:`sql`,postgresql:`sql`,laravel_migration:`php`,laravel_model:`php`,goravel:`go`,goravel_migration:`go`,typescript:`ts`,zod:`ts`,prisma:`prisma`};function Ai({entity:e,mode:t,onUpdateEntity:n,dbmlReadOnly:r=!1}){let{resolvedTheme:i}=tr(),[a,s]=Q.useState(Ei[0].id),[c,l]=Q.useState(Ei[0].formats[0].id),[u,d]=Q.useState(!1),f=Q.useMemo(()=>({id:e.id,type:`entity`,position:{x:e.x,y:e.y},data:e}),[e]),p=Q.useMemo(()=>R([f],[]),[f]),[h,g]=Q.useState(p);Q.useEffect(()=>g(p),[e.id,p]);let _=Ei.find(e=>e.id===a)??Ei[0],v=Di[c](e),y=Oi[c]||`sql`,b=m(),x=Q.useMemo(()=>{if(!b)return{entity:null,error:`Loading the DBML parser…`};if(!h.trim())return{entity:null,error:`DBML cannot be empty.`};try{let t=T(h);if(t.nodes.length!==1)return{entity:null,error:`DBML must contain exactly one Table block.`};let n=t.nodes[0].data;return n.name===e.name?{entity:n,error:``}:{entity:null,error:`The table name must be exactly "${e.name}".`}}catch(e){return{entity:null,error:e instanceof Error?e.message:`Invalid DBML.`}}},[h,e,b]),S=Q.useMemo(()=>{if(t===`dbml`)return[En()];switch(y){case`sql`:return[En()];case`php`:return[vn()];case`go`:return[kn(),...Sn(i)];case`typescript`:case`prisma`:return[yn({typescript:!0})];default:return[]}},[y,t,i]),C=async()=>{await navigator.clipboard.writeText(t===`dbml`?p:v),d(!0),window.setTimeout(()=>d(!1),2e3)},w=()=>{let t=new Blob([v],{type:`text/plain`}),n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=`${e.name.toLowerCase()}_${c}.${ki[c]||`txt`}`,r.click(),URL.revokeObjectURL(n)},E=()=>{let t=x.entity;if(!t)return;let r=new Map(e.columns.map(e=>[e.name.toLowerCase(),e])),i=(e=[])=>e.map(e=>{let n=t.columns.find(t=>t.id===e);return n?r.get(n.name.toLowerCase())?.id??e:e}),a={...e,comment:t.comment,columns:t.columns.map((e,t)=>({...e,id:r.get(e.name.toLowerCase())?.id??crypto.randomUUID(),_is_fk:r.get(e.name.toLowerCase())?._is_fk,sort_order:t})),constraints:(t.constraints||[]).map(t=>({...t,entity_id:e.id,column_ids:i(t.column_ids)})),indexes:(t.indexes||[]).map(t=>({...t,entity_id:e.id,column_ids:i(t.column_ids)}))};n(a),g(R([{id:a.id,type:`entity`,position:{x:a.x,y:a.y},data:a}],[]))};if(t===`dbml`){let t=h!==p;return(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`shrink-0 border-b border-border px-4 py-3`,children:[(0,$.jsx)(`p`,{className:`text-sm font-semibold`,children:`Table DBML`}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:r?`Read only. Edit the full schema from DBML in the toolbar.`:`Only the DBML for “${e.name}” can be edited.`})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden bg-muted`,children:(0,$.jsx)(Cn,{value:r?p:h,onChange:g,editable:!r,readOnly:r,extensions:S,theme:i===`dark`?xn:void 0,height:`100%`,basicSetup:{lineNumbers:!0,foldGutter:!1},className:`h-full text-[13px] text-foreground/90`})}),r?(0,$.jsx)(`div`,{className:`flex shrink-0 justify-end border-t border-border bg-muted/20 p-3`,children:(0,$.jsxs)(W,{variant:`outline`,onClick:C,children:[u?(0,$.jsx)(Te,{className:`mr-2 size-3.5 text-green-500`}):(0,$.jsx)(hr,{className:`mr-2 size-3.5`}),u?`Copied`:`Copy`]})}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`min-h-8 px-4 py-2 text-xs text-destructive`,children:x.error}),(0,$.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2 border-t border-border bg-muted/20 p-3`,children:[(0,$.jsx)(W,{variant:`outline`,onClick:()=>g(p),children:`Reset`}),(0,$.jsx)(W,{onClick:E,disabled:!!x.error||!t,children:`Apply DBML`})]})]})]})}return(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b border-border px-4 py-3`,children:[(0,$.jsx)(`div`,{className:`flex items-center gap-1 overflow-x-auto`,children:Ei.map(e=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>{s(e.id),l(e.formats[0].id)},className:o(`rounded-md px-2.5 py-1.5 text-[11px] font-semibold whitespace-nowrap`,a===e.id?`bg-muted text-foreground`:`text-muted-foreground hover:text-foreground`),children:e.label},e.id))}),(0,$.jsx)(`div`,{className:`flex items-center gap-1 overflow-x-auto rounded-lg bg-muted p-1`,children:_.formats.map(e=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>l(e.id),className:o(`flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-semibold whitespace-nowrap`,c===e.id?`bg-background text-foreground shadow-sm`:`text-muted-foreground hover:text-foreground`),children:[(0,$.jsx)(Ue,{className:`size-3.5`}),e.label]},e.id))})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden bg-muted`,children:(0,$.jsx)(Cn,{value:v,extensions:S,theme:i===`dark`?xn:void 0,readOnly:!0,height:`100%`,basicSetup:{lineNumbers:!0,foldGutter:!1,highlightActiveLine:!1},className:`h-full text-[13px] text-foreground/90`})}),(0,$.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2 border-t border-border bg-muted/20 p-3`,children:[(0,$.jsxs)(W,{variant:`outline`,onClick:w,children:[(0,$.jsx)(Oe,{className:`mr-2 size-3.5`}),`Download`]}),(0,$.jsxs)(W,{variant:`outline`,onClick:C,children:[u?(0,$.jsx)(Te,{className:`mr-2 size-3.5 text-green-500`}):(0,$.jsx)(hr,{className:`mr-2 size-3.5`}),u?`Copied`:`Copy`]})]})]})}function ji(e,t,n,r){if(t===n)return null;let i=[...e].sort((e,t)=>(e.sort_order??0)-(t.sort_order??0)),a=i.find(e=>e.id===t);if(!a)return null;let o=i.filter(e=>e.id!==t),s=o.findIndex(e=>e.id===n);return s===-1?null:(o.splice(s+ +(r===`after`),0,a),o.map((e,t)=>({...e,sort_order:t})))}var Mi=[`#6366f1`,`#8b5cf6`,`#ec4899`,`#3b82f6`,`#10b981`,`#f59e0b`,`#ef4444`],Ni=255,Pi=[{name:`created_at`,type:`TIMESTAMP`,is_nullable:!1},{name:`updated_at`,type:`TIMESTAMP`,is_nullable:!1},{name:`deleted_at`,type:`TIMESTAMP`,is_nullable:!0}],Fi=e=>{let t=e.trim();if(!t)return null;let n=Number.parseInt(t,10);return Number.isFinite(n)&&n>=0?n:null};function Ii({selectedEntity:e,onUpdateEntity:t,onDeleteEntity:n,onBackToTables:r,propertiesOnly:a=!1,headerActions:s,dbmlReadOnly:l=!1}){let[u,d]=(0,Q.useState)(e),[f,p]=(0,Q.useState)(`properties`),[m,h]=(0,Q.useState)(null),[g,v]=(0,Q.useState)(Object.fromEntries(Pi.map(e=>[e.name,!0]))),[y,b]=(0,Q.useState)(!1),[x,S]=(0,Q.useState)(null),[C,w]=(0,Q.useState)(null),T=(0,Q.useRef)(null),E=(0,Q.useRef)(null),D=(0,Q.useRef)(null),O=(0,Q.useRef)(!1),k=(0,Q.useRef)(null),A=(0,Q.useRef)(u?.columns?.length||0),ee=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=u?.columns?.length||0;e>A.current&&requestAnimationFrame(()=>{k.current?.scrollIntoView({behavior:`smooth`,block:`end`})}),A.current=e},[u?.columns?.length]);let[j,M]=(0,Q.useState)({isOpen:!1,title:``,message:``,onConfirm:()=>{}});if((0,Q.useEffect)(()=>{e?.id!==u?.id&&d(e)},[e?.id]),!e||!u)return null;let N=(e,n=!1)=>{n?(D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{t(e,{immediate:!0})},300)):t(e)},P=e=>{d({...u,name:e})},F=e=>{let t={...u,color:e};d(t),N(t,!0)},te=()=>{let e=u.columns.reduce((e,t)=>Math.max(e,t.sort_order||0),-1),t={id:Math.random().toString(36).substring(2,11),name:`new_column`,type:`VARCHAR`,max_length:Ni,is_pk:!1,is_nullable:!0,default_value:`NULL`,sort_order:e+1},n={...u,columns:[...u.columns,t]};ee.current=t.id,d(n),N(n,!0)},ne=()=>{let e=new Set(u.columns.map(e=>e.name.toLowerCase())),t=Pi.filter(t=>g[t.name]&&!e.has(t.name));if(t.length===0){i.info(`Selected audit columns already exist or none were selected`);return}let n=u.columns.reduce((e,t)=>Math.max(e,t.sort_order||0),-1)+1,r=t.map((e,t)=>({id:crypto.randomUUID(),name:e.name,type:e.type,is_pk:!1,is_nullable:e.is_nullable,default_value:_(e.is_nullable?`NULL`:null,e.is_nullable),sort_order:n+t})),a={...u,columns:[...u.columns,...r]};ee.current=r[r.length-1].id,d(a),N(a,!0),b(!1),i.success(`${r.length} audit column${r.length===1?``:`s`} added`)},L=()=>{let e=u.columns.filter(e=>e.is_pk).sort((e,t)=>(e.sort_order||0)-(t.sort_order||0)),t=u.columns.filter(e=>!e.is_pk).sort((e,t)=>(e.sort_order||0)-(t.sort_order||0)),n=[...e,...t].map((e,t)=>({...e,sort_order:t})),r={...u,columns:n};d(r),N(r,!0)},re=(e,t)=>{d({...u,columns:u.columns.map(n=>n.id===e?{...n,...t}:n)})},R=(e,t,n=!1)=>{if(O.current){O.current=!1;return}if(`name`in t&&typeof t.name==`string`){let n=t.name.trim();if(u.columns.some(t=>t.id!==e&&t.name.toLowerCase()===n.toLowerCase())){i.error(`Column name "${n}" already exists in this table`);let t=u.columns.find(t=>t.id===e);t&&d({...u,columns:u.columns.map(n=>n.id===e?t:n)});return}t={...t,name:n}}if(`type`in t){let n=u.columns.find(t=>t.id===e);t={...t,.../^varchar$/i.test(String(t.type))&&n?.max_length==null&&{max_length:Ni},...!c(t.type)&&{max_length:null},...!I(t.type)&&{numeric_precision:null,numeric_scale:null}}}let r={...u,columns:u.columns.map(n=>{if(n.id!==e)return n;let r={...n,...t},i=_(r.default_value,!!r.is_nullable);return r.is_nullable&&!i?{...r,default_value:`NULL`}:{...r,default_value:i}})};d(r),N(r,n)},z=e=>{let t={...u,columns:e};d(t),N(t,!0)},B=()=>{T.current=null,E.current=null,w(null),S(null)},V=(e,t)=>{e.button===0&&(e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),T.current=t,S(t))},ie=e=>{if(!T.current)return;e.preventDefault();let t=document.elementFromPoint(e.clientX,e.clientY)?.closest(`[data-column-id]`),n=t?.dataset.columnId;if(!t||!n)return;let r=t.getBoundingClientRect(),i=e.clientY<r.top+r.height/2?`before`:`after`,a={id:n,position:i};E.current=a,w(e=>e?.id===n&&e.position===i?e:a)},H=(e,t)=>{e.preventDefault();let n=E.current,r=n&&ji(u.columns,t,n.id,n.position);r&&z(r),B()},U=e=>{let t={...u,columns:u.columns.filter(t=>t.id!==e)};d(t),N(t,!0)};return(0,$.jsxs)(`div`,{className:`flex flex-col h-full overflow-hidden`,children:[(0,$.jsxs)(`div`,{className:`shrink-0 border-b border-border bg-background px-4 py-3`,children:[(0,$.jsxs)(`div`,{className:`mb-3 flex min-w-0 items-center gap-2 text-xs`,children:[r?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:r,className:`flex shrink-0 items-center gap-1 font-medium text-muted-foreground hover:text-foreground`,children:[(0,$.jsx)(rt,{className:`size-3.5`}),` Tables`]}),(0,$.jsx)(`span`,{className:`text-muted-foreground/50`,children:`/`}),(0,$.jsx)(`span`,{className:`truncate font-medium text-foreground`,children:u.name})]}):(0,$.jsx)(`span`,{className:`truncate font-medium text-foreground`,children:u.name}),(0,$.jsx)(W,{type:`button`,variant:`ghost`,size:`icon-xs`,className:`ml-auto shrink-0 text-destructive hover:bg-destructive/10 hover:text-destructive`,title:`Delete table`,"aria-label":`Delete table ${u.name}`,onClick:()=>M({isOpen:!0,title:`Delete Table`,message:`Are you sure you want to delete the table "${u.name}"? This action cannot be undone.`,onConfirm:()=>{D.current&&clearTimeout(D.current),n(u.id),M(e=>({...e,isOpen:!1}))}}),children:(0,$.jsx)(qt,{className:`size-4`})}),s]}),!a&&(0,$.jsx)(`div`,{className:`flex w-full gap-1 rounded-lg border border-border bg-muted p-1`,"aria-label":`Table editor sections`,children:[[`properties`,`Properties`],[`schema`,`Schema`],[`dbml`,`DBML`]].map(([e,t])=>(0,$.jsx)(`button`,{type:`button`,"aria-pressed":f===e,onClick:()=>p(e),className:o(`flex flex-1 items-center justify-center rounded-md px-3 py-2 text-xs font-semibold transition-colors`,f===e?`bg-background text-foreground shadow-sm`:`text-muted-foreground hover:bg-background/60 hover:text-foreground`),children:t},e))})]}),!a&&f!==`properties`?(0,$.jsx)(Ai,{entity:u,mode:f,dbmlReadOnly:l,onUpdateEntity:e=>{d(e),t(e)}}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`shrink-0 bg-background pt-6 px-6 pb-4 border-b border-border/50 shadow-sm z-10`,children:(0,$.jsxs)(`section`,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(nr,{className:`text-[10px] font-bold uppercase tracking-widest text-muted-foreground`,children:`Table Name`}),(0,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsx)($e,{className:`absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground z-10`}),(0,$.jsx)(Z,{type:`text`,value:u.name,onChange:e=>P(e.target.value),onBlur:()=>N(u),className:`pl-10 h-10 transition-all focus:ring-1`})]})]}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(nr,{className:`text-[10px] font-bold uppercase tracking-widest text-muted-foreground`,children:`Theme Color`}),(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-2 pt-1`,children:[Mi.map(e=>(0,$.jsx)(`button`,{onClick:()=>F(e),className:o(`w-7 h-7 rounded-full border-2 transition-all shadow-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2`,u.color===e?`border-foreground scale-110 shadow-md`:`border-transparent hover:scale-105`),style:{backgroundColor:e}},e)),(0,$.jsx)(`label`,{className:o(`relative w-7 h-7 rounded-full border-2 transition-all shadow-sm cursor-pointer ring-offset-background focus-within:outline-none focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2`,Mi.includes(u.color)?`hover:scale-105`:`border-foreground scale-110 shadow-md`),style:{borderColor:Mi.includes(u.color)?u.color:void 0,backgroundColor:Mi.includes(u.color)?`transparent`:u.color},title:`Custom color`,children:(0,$.jsx)(Z,{type:`color`,value:u.color,onChange:e=>F(e.target.value),className:`absolute inset-0 h-full w-full cursor-pointer opacity-0`})})]})]})]})}),(0,$.jsxs)(`div`,{className:`shrink-0 flex items-center justify-between bg-popover/95 py-2 px-6 border-b border-border/50 z-10 shadow-sm`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsxs)(nr,{className:`text-[10px] font-bold uppercase tracking-widest text-muted-foreground`,children:[`Columns (`,u.columns.length,`)`]}),(0,$.jsx)(W,{variant:`ghost`,size:`icon`,onClick:L,className:`h-6 w-6 text-muted-foreground hover:text-primary transition-colors`,title:`Normalize (PKs to top)`,children:(0,$.jsx)(Ye,{className:`w-3.5 h-3.5`})}),(0,$.jsxs)(_e,{open:y,onOpenChange:b,children:[(0,$.jsx)(ge,{render:(0,$.jsx)(W,{variant:`ghost`,size:`icon`,className:`h-6 w-6 text-muted-foreground hover:text-primary`,title:`Generate audit columns`,"aria-label":`Generate audit columns`,children:(0,$.jsx)(ht,{className:`w-3.5 h-3.5`})})}),(0,$.jsxs)(me,{align:`start`,className:`w-56 space-y-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-sm font-semibold`,children:`Generate audit columns`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Add common timestamp fields.`})]}),(0,$.jsx)(`div`,{className:`space-y-2`,children:Pi.map(e=>{let t=u.columns.some(t=>t.name.toLowerCase()===e.name);return(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,$.jsx)(or,{checked:g[e.name],disabled:t,onCheckedChange:t=>v(n=>({...n,[e.name]:t===!0}))}),(0,$.jsx)(`span`,{className:o(t&&`text-muted-foreground line-through`),children:e.name}),t&&(0,$.jsx)(`span`,{className:`ml-auto text-[10px] text-muted-foreground`,children:`Exists`})]},e.name)})}),(0,$.jsx)(W,{type:`button`,size:`sm`,className:`w-full`,onClick:ne,children:`Generate selected`})]})]})]}),(0,$.jsx)(W,{onClick:te,className:`h-8 w-8 rounded-full shadow-sm hover:shadow-md transition-all bg-white text-black hover:bg-white/90`,size:`icon`,children:(0,$.jsx)(he,{className:`w-4 h-4`})})]}),(0,$.jsx)(`section`,{className:`flex-1 overflow-y-auto custom-scrollbar p-4 space-y-2 min-h-0`,children:(0,$.jsxs)(`div`,{className:`space-y-2`,children:[[...u.columns].sort((e,t)=>(e.sort_order||0)-(t.sort_order||0)).map(e=>(0,$.jsxs)(Rt,{"data-column-id":e.id,className:o(`gap-1 p-2 bg-muted/10 border border-border/30 shadow-none hover:border-primary/30 transition-all`,x===e.id&&`opacity-50`,C?.id===e.id&&C.position===`before`&&`border-t-2 border-t-primary`,C?.id===e.id&&C.position===`after`&&`border-b-2 border-b-primary`),children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`button`,{type:`button`,"aria-label":`Drag ${e.name} to reorder`,title:`Drag to reorder`,onPointerDown:t=>V(t,e.id),onPointerMove:ie,onPointerUp:t=>H(t,e.id),onPointerCancel:B,className:`h-7 w-6 shrink-0 touch-none select-none cursor-grab rounded text-muted-foreground hover:bg-primary/10 hover:text-primary active:cursor-grabbing`,children:(0,$.jsx)(xt,{className:`mx-auto h-4 w-4`})}),(0,$.jsx)(Z,{ref:t=>{t&&e.id===ee.current&&(t.focus(),t.select(),ee.current=null)},placeholder:`Column name`,value:e.name,onChange:t=>re(e.id,{name:t.target.value}),onBlur:t=>R(e.id,{name:t.target.value}),className:`h-8 min-w-0 flex-1 text-xs font-bold bg-background/50 border-border/50 focus-visible:ring-1 shadow-sm transition-all`}),(0,$.jsx)(W,{variant:`ghost`,size:`icon`,onClick:()=>M({isOpen:!0,title:`Delete Column`,message:`Are you sure you want to delete the column "${e.name}"?`,onConfirm:()=>{U(e.id),M(e=>({...e,isOpen:!1}))}}),className:`h-8 w-8 text-destructive/70 hover:text-destructive hover:bg-destructive/10 shrink-0`,title:`Delete column`,children:(0,$.jsx)(qt,{className:`w-4 h-4`})})]}),(0,$.jsxs)(`div`,{className:o(`grid gap-1`,I(e.type)?`grid-cols-[minmax(0,1fr)_3.75rem_3.75rem_2rem_2rem_2rem]`:c(e.type)?`grid-cols-[minmax(0,1fr)_3.75rem_2rem_2rem_2rem]`:`grid-cols-[minmax(0,1fr)_2rem_2rem_2rem]`),children:[(0,$.jsx)(Ti,{value:e.type,onValueChange:t=>R(e.id,{type:t},!0),className:`min-w-0`}),c(e.type)&&(0,$.jsx)(Z,{type:`number`,min:1,value:e.max_length??``,onChange:t=>re(e.id,{max_length:Fi(t.target.value)}),onBlur:t=>R(e.id,{max_length:Fi(t.target.value)}),placeholder:`Max`,className:`h-8 px-2 text-[10px] bg-background/50 border-border/50`}),I(e.type)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{type:`number`,min:1,value:e.numeric_precision??``,onChange:t=>re(e.id,{numeric_precision:Fi(t.target.value)}),onBlur:t=>R(e.id,{numeric_precision:Fi(t.target.value)}),placeholder:`Prec`,className:`h-8 px-2 text-[10px] bg-background/50 border-border/50`}),(0,$.jsx)(Z,{type:`number`,min:0,value:e.numeric_scale??``,onChange:t=>re(e.id,{numeric_scale:Fi(t.target.value)}),onBlur:t=>R(e.id,{numeric_scale:Fi(t.target.value)}),placeholder:`Scale`,className:`h-8 px-2 text-[10px] bg-background/50 border-border/50`})]}),(0,$.jsx)(W,{variant:e.is_pk?`default`:`outline`,size:`icon`,onClick:()=>R(e.id,{is_pk:!e.is_pk},!0),className:o(`h-8 w-8 transition-all`,e.is_pk?`bg-yellow-500 hover:bg-yellow-600 text-white`:`text-muted-foreground hover:text-foreground bg-background/50`),title:`Primary Key`,children:(0,$.jsx)(mt,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(W,{variant:e.is_nullable?`outline`:`default`,size:`icon`,onClick:()=>R(e.id,{is_nullable:!e.is_nullable},!0),className:o(`h-8 w-8 transition-all`,e.is_nullable?`text-muted-foreground hover:text-foreground bg-background/50`:`bg-primary hover:bg-primary/90 text-primary-foreground`),title:`Not Null`,children:e.is_nullable?(0,$.jsx)(It,{className:`w-3.5 h-3.5`}):(0,$.jsx)(Te,{className:`w-3.5 h-3.5`})}),(0,$.jsxs)(_e,{open:m===e.id,onOpenChange:t=>h(t?e.id:null),children:[(0,$.jsx)(ge,{render:(0,$.jsx)(W,{type:`button`,variant:`outline`,size:`icon`,"aria-expanded":m===e.id,onMouseDown:()=>{O.current=!0,window.setTimeout(()=>{O.current=!1},0)},className:o(`h-8 w-8 transition-colors`,m===e.id?`border-primary bg-primary text-primary-foreground hover:bg-primary/90`:`text-muted-foreground hover:text-foreground bg-background/50`,e.comment&&m!==e.id&&`border-primary/60`),title:`Field attributes`,"aria-label":`Field attributes`,children:(0,$.jsx)(Et,{className:`w-3.5 h-3.5`})})}),(0,$.jsxs)(me,{align:`end`,side:`left`,className:`w-72 space-y-2`,children:[(0,$.jsx)(nr,{className:`text-xs font-semibold`,children:`Field Attributes`}),(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,$.jsx)(or,{checked:!!e.is_unique,onCheckedChange:t=>R(e.id,{is_unique:t===!0},!0)}),`Unique`]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{htmlFor:`default-${e.id}`,className:`text-xs text-muted-foreground`,children:`Default value`}),(0,$.jsx)(Z,{id:`default-${e.id}`,value:e.default_value??(e.is_nullable?`NULL`:``),onChange:t=>re(e.id,{default_value:t.target.value}),onBlur:t=>R(e.id,{default_value:t.target.value.trim()||null}),placeholder:`NULL, 0, CURRENT_TIMESTAMP, 'pending'`,className:`h-8 text-sm`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{htmlFor:`comment-${e.id}`,className:`text-xs text-muted-foreground`,children:`Comment`}),(0,$.jsx)(jn,{id:`comment-${e.id}`,value:e.comment||``,onChange:t=>re(e.id,{comment:t.target.value}),onBlur:t=>R(e.id,{comment:t.target.value.trim()}),placeholder:`Add a comment`,className:`min-h-20 resize-y text-sm`})]})]})]})]}),e.type===`ENUM`&&(0,$.jsx)(Z,{type:`text`,value:e.enum_values||``,onChange:t=>re(e.id,{enum_values:t.target.value}),onBlur:()=>N(u),placeholder:`Enum values: active, inactive...`,className:`h-8 text-[10px] bg-background/50 border-border/50`})]},e.id)),(0,$.jsx)(`div`,{ref:k})]})})]}),(0,$.jsx)(ut,{isOpen:j.isOpen,title:j.title,message:j.message,onConfirm:j.onConfirm,onCancel:()=>M(e=>({...e,isOpen:!1}))})]})}function Li({entity:e,floating:t,onTogglePin:n,onClose:r,onBackToExplorer:i}){let{handleEntityUpdate:a,deleteEntity:s,setSelectedNodeId:c}=tr(),l=t?{left:t.left,top:t.top,maxHeight:`calc(100% - ${t.top+12}px)`}:void 0;return(0,$.jsx)(`aside`,{"aria-label":`Table ${e.name}`,"data-side":t?.side,style:l,className:o(`nowheel nodrag flex flex-col overflow-hidden border bg-popover text-popover-foreground`,t?`absolute z-30 h-[min(36rem,calc(100%-1.5rem))] w-96 rounded-xl shadow-2xl`:`w-85 shrink-0 rounded-xl max-md:absolute max-md:inset-y-0 max-md:right-0 max-md:z-30 max-md:w-[min(21.25rem,100%)] max-md:shadow-xl`),children:(0,$.jsx)(Ii,{selectedEntity:e,onUpdateEntity:a,onBackToTables:i,dbmlReadOnly:!0,onDeleteEntity:e=>{s(e),c(null),r()},headerActions:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(W,{type:`button`,variant:`ghost`,size:`icon-xs`,onClick:n,"aria-pressed":!t,"aria-label":t?`Pin the table editor beside the canvas`:`Unpin the table editor`,title:t?`Pin`:`Unpin`,children:t?(0,$.jsx)(ft,{className:`size-4`}):(0,$.jsx)(_t,{className:`size-4`})}),(0,$.jsx)(W,{type:`button`,variant:`ghost`,size:`icon-xs`,onClick:r,"aria-label":`Close table editor`,title:`Close (Esc)`,children:(0,$.jsx)(It,{className:`size-4`})})]})},e.id)})}function Ri(e,t,n){if(!e.sliceDoc(t,n).includes(`{`))return null;let r=e.doc.toString(),i=``,a=!1,o=!1,s=[];for(let e=0;e<r.length;e++){let c=r[e],l=r[e+1];if(a)c===`
|
|
2
|
+
`&&(a=!1);else if(o)c===`*`&&l===`/`&&(o=!1,e++);else if(i){if(c===`\\`){e++;continue}c===i&&(i=``)}else if(c===`/`&&l===`*`)o=!0,e++;else if(c===`/`&&l===`/`||c===`-`&&l===`-`)a=!0,e++;else if(c===`"`||c===`'`||c==="`")i=c;else if(c===`{`&&s.push(e),c===`}`){let r=s.pop();if(r!==void 0&&r>=t&&r<=n&&e>n)return{from:r+1,to:e}}}return null}var zi=[{label:`Table`,type:`keyword`,detail:`table definition`},{label:`Ref`,type:`keyword`,detail:`relationship`},{label:`Enum`,type:`keyword`,detail:`enum definition`},{label:`TableGroup`,type:`keyword`,detail:`table group`},{label:`Note`,type:`keyword`,detail:`project note`},{label:`Indexes`,type:`keyword`,detail:`index block`}],Bi=[{label:`pk`,type:`keyword`,detail:`primary key`},{label:`unique`,type:`keyword`,detail:`unique constraint`},{label:`not null`,type:`keyword`,detail:`not null`},{label:`note`,type:`keyword`,detail:`column note: 'text'`},{label:`default`,type:`keyword`,detail:`default value`},{label:`increment`,type:`keyword`,detail:`auto-increment`},{label:`ref`,type:`keyword`,detail:`inline FK: > table.col`},{label:`headerColor`,type:`keyword`,detail:`table header color`}],Vi=r.map(e=>({label:e,type:`type`,detail:`column type`}));function Hi(e,t){let n=e.names.find(e=>e.toLowerCase()===t.toLowerCase());return n?{name:n,columns:e.cols.get(n)||[]}:null}function Ui(e,t,n,r=8){let i=e.lastIndexOf(`
|
|
3
|
+
`,Math.max(0,t-1))+1,a=e.indexOf(`
|
|
4
|
+
`,t),o=e.slice(i,a===-1?void 0:a),s=e.slice(i,t),c=s.match(/\w+$/)?.[0];if(!c)return[];let l=c.toLowerCase(),u=t-c.length,d=e=>e.filter(e=>e.label.toLowerCase().startsWith(l)).slice(0,r).map(e=>({...e,from:u,to:t})),f=s.slice(0,s.length-c.length).trimEnd(),p=!f||f.startsWith(`//`),m=/^\s/.test(o)&&!/^\s*(Table|Ref|Enum|TableGroup|Note|Indexes)\b/i.test(o),h=/^\s+"[^"]+"\s+\w*$/.test(s)||/^\s+\w+\s+\w*$/.test(s);if(/^\s*Ref:\s/i.test(o)){let e=s.replace(/^\s*Ref:\s*/,``);if(!/[><]/.test(e)){let t=e.match(/^(\w+)\.(\w*)$/);if(t){let e=Hi(n,t[1]);return e?d(e.columns.map(t=>({label:t,type:`property`,detail:e.name}))):[]}return d(n.names.map(e=>({label:e,type:`class`})))}}let g=s.match(/[><]\s*(\w+)\.(\w*)$/i);if(g){let e=Hi(n,g[1]);return e?d(e.columns.map(t=>({label:t,type:`property`,detail:e.name}))):[]}return/[><]\s*\w*$/i.test(s)?d(n.names.map(e=>({label:e,type:`class`}))):m&&h?d(Vi):/\[[^\]]*\w*$/.test(s)?d(Bi):p?d(zi):[]}var Wi=new Set(r.map(e=>e.toUpperCase()));function Gi(){return bn(async e=>{let t=e.state.doc,n=t.toString(),r=[],i=n.split(`
|
|
5
|
+
`);return Ki(i,t,w(i),r),qi(i,t,r),Ji(n,i,t,r),await Yi(n,i,t,r),r},{delay:500})}function Ki(e,t,n,r){let i=``,a=!1,o=0;for(let s=0;s<e.length;s+=1){let c=e[s],l=c.trim(),u=t.line(s+1).from,d=N(c);if(d){i=d,a=!0,o=0;continue}if(a&&/^(checks|indexes)\s*\{/i.test(l)){o=1;continue}if(o>0){l===`}`&&--o;continue}if(l===`}`||l.startsWith(`}`)){a=!1,i=``;continue}if(!a||!l||l.startsWith(`//`))continue;let f=re(l);if(!f)continue;let p=z(f.type);if(!p||Wi.has(p.toUpperCase())||n.has(p.toLowerCase()))continue;let m=c.indexOf(f.type);r.push({from:u+m,to:u+m+f.type.length,severity:`error`,message:`Invalid type "${f.type}" in "${i}.${f.name}"`})}}function qi(e,t,n){let{tableDefs:r,lineTables:i}=ie(e);for(let a=0;a<e.length;a+=1){let o=e[a],s=t.line(a+1).from,c=P(o,i[a]);if(!c)continue;let{fkTable:l,fkCol:u,pkTable:d,pkCol:f}=c,p=r.get(l);if(!p)continue;if(u&&!p.has(u)){Xi(n,o,s,u,`Column "${u}" not found in "${l}"`);continue}let m=r.get(d);if(!m)Xi(n,o,s,d,`Table "${d}" not found`);else if(!m.has(f))Xi(n,o,s,f,`Column "${f}" not found in "${d}"`);else if(u&&p.has(u)){let e=(p.get(u)||``).toUpperCase().replace(/\s+/g,``),t=(m.get(f)||``).toUpperCase().replace(/\s+/g,``);e&&t&&e!==t&&Xi(n,o,s,u,`Type mismatch: "${l}.${u}" is ${p.get(u)} but "${d}.${f}" is ${m.get(f)}`)}}}function Ji(e,t,n,r){for(let i of j(e)){let e=t[i.line-1]||``,a=n.line(i.line).from,o=e.indexOf(i.actual),s=a+Math.max(0,o);r.push({from:s,to:s+i.actual.length,severity:`warning`,message:`Recommended enum name is "${i.expected}". Rename "${i.actual}" to avoid duplicate enum blocks; save is paused until fixed.`})}}async function Yi(e,t,n,r){let i=0;for(let t of e)t===`{`&&(i+=1),t===`}`&&--i;if(i!==0||!/\bTable\b/i.test(e))return;let{Parser:a}=await g();try{a.parse(O(ne(e)),`dbml`)}catch(e){for(let i of e?.diags||[]){let e=i.location?.start?.line,a=(i.location?.start?.column||1)-1;if(!e||e>t.length)continue;let o=n.line(e).from;r.push({from:o+a,to:o+a+1,severity:`error`,message:i.message})}}}function Xi(e,t,n,r,i){let a=t.indexOf(r);a<0||e.push({from:n+a,to:n+a+r.length,severity:`error`,message:i})}var Zi=`// ERD Builder DBML reference.
|
|
6
|
+
// Table, Enum, Ref, indexes, constraints, defaults, and notes can be
|
|
7
|
+
// edited here and are applied to the ERD canvas after the DBML is valid.
|
|
8
|
+
|
|
9
|
+
Table users {
|
|
10
|
+
id BIGINT [pk, not null, increment]
|
|
11
|
+
name VARCHAR(255) [not null]
|
|
12
|
+
email VARCHAR(255) [not null, note: 'Must be unique']
|
|
13
|
+
role users_role [not null, default: 'member']
|
|
14
|
+
created_at TIMESTAMP [not null]
|
|
15
|
+
updated_at TIMESTAMP [not null]
|
|
16
|
+
deleted_at TIMESTAMP [default: NULL]
|
|
17
|
+
Note: 'Account table'
|
|
18
|
+
|
|
19
|
+
Indexes {
|
|
20
|
+
(email) [unique, name: "users_email_unique"]
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
Table posts {
|
|
25
|
+
id BIGINT [pk, not null, increment]
|
|
26
|
+
user_id BIGINT [not null]
|
|
27
|
+
status posts_status [not null, default: 'draft']
|
|
28
|
+
title VARCHAR(255) [not null]
|
|
29
|
+
body TEXT
|
|
30
|
+
|
|
31
|
+
Indexes {
|
|
32
|
+
(user_id, status) [name: "posts_user_status_index"]
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
Enum users_role {
|
|
37
|
+
admin
|
|
38
|
+
member
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
Enum posts_status {
|
|
42
|
+
draft
|
|
43
|
+
published
|
|
44
|
+
archived
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// The foreign-key column is on the left; the referenced column is on the right.
|
|
48
|
+
Ref "posts_user_id_fk": posts.user_id > users.id [delete: cascade, update: cascade]`;function Qi({open:e,onOpenChange:t,resolvedTheme:n}){return(0,$.jsx)(Wt,{open:e,onOpenChange:t,children:(0,$.jsxs)(zt,{className:`max-w-xl max-h-[80vh]`,children:[(0,$.jsxs)(Ut,{children:[(0,$.jsx)(Bt,{children:`DBML Reference`}),(0,$.jsx)(Lt,{children:`Use this example as a starting point for tables, column metadata, enums, indexes, and relationships.`})]}),(0,$.jsxs)(Vt,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`space-y-1 text-xs text-muted-foreground`,children:[(0,$.jsxs)(`p`,{children:[`Every entry inside an `,(0,$.jsx)(`code`,{children:`Indexes`}),` block must wrap its column list in parentheses, including a single-column index such as `,(0,$.jsx)(`code`,{children:`(email)`}),`.`]}),(0,$.jsxs)(`p`,{children:[`Use column-level `,(0,$.jsx)(`code`,{children:`unique`}),` for a simple unnamed constraint. Use `,(0,$.jsx)(`code`,{children:`Indexes`}),` when you need a name, a composite index, or an explicit index definition.`]}),(0,$.jsxs)(`p`,{children:[`A `,(0,$.jsx)(`code`,{children:`Ref`}),` line keeps the foreign-key column on the left and supports optional delete and update actions.`]})]}),(0,$.jsx)(`div`,{className:`rounded-lg overflow-hidden border border-border/50`,children:(0,$.jsx)(Cn,{value:Zi,height:`420px`,theme:n===`dark`?xn:void 0,extensions:[En()],editable:!1,basicSetup:{lineNumbers:!1,foldGutter:!1,highlightActiveLine:!1}})})]})]})})}function $i(e,t){return`${e.map(e=>`${e.data.name}:${e.data.columns.map(e=>`${e.name}:${e.type}:${e.enum_name||``}:${e.enum_values||``}:${e.comment||``}:${e.max_length||``}:${e.numeric_precision||``}:${e.numeric_scale||``}:${e.is_pk}:${e.is_nullable}:${e.default_value||``}:${e.is_unique||!1}`).join(`,`)}`).sort().join(`|`)}|${e.map(e=>JSON.stringify({table:e.data.name,comment:e.data.comment||``,constraints:(e.data.constraints||[]).map(t=>({kind:t.kind,name:t.name||``,columns:(t.column_ids||[]).map(t=>e.data.columns.find(e=>e.id===t)?.name||t).sort(),expression:t.expression||``})).sort((e,t)=>JSON.stringify(e).localeCompare(JSON.stringify(t))),indexes:(e.data.indexes||[]).map(t=>({name:t.name,unique:!!t.is_unique,algorithm:t.algorithm||``,columns:(t.column_ids||[]).map(t=>e.data.columns.find(e=>e.id===t)?.name||t).sort()})).sort((e,t)=>JSON.stringify(e).localeCompare(JSON.stringify(t)))})).sort().join(`|`)}|${t.map(e=>JSON.stringify({source:e.source,target:e.target,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle,on_delete:e.data?.on_delete||``,on_update:e.data?.on_update||``,constraint_name:e.data?.constraint_name||``})).sort().join(`|`)}`}function ea(e){let t=0;for(let n of e)if(n===`{`&&(t+=1),n===`}`&&--t,t<0)return!1;return t===0&&/\bTable\b/i.test(e)}var ta=1500,na=800,ra=8,ia=176,aa=320,oa={lineNumbers:!0,foldGutter:!0,highlightActiveLine:!0,bracketMatching:!0,closeBrackets:!0,indentOnInput:!0,autocompletion:!1},sa=(0,Q.memo)(function({value:e,onChange:t,onApply:n,nodes:r,edges:i,onSelectTable:a,headerActions:s,parserReady:c=!0}){let[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)([]),[p,m]=(0,Q.useState)(0),[h,g]=(0,Q.useState)({top:16,left:16}),{resolvedTheme:_}=tr(),v=(0,Q.useRef)(!1),y=(0,Q.useRef)(!1),b=(0,Q.useRef)(void 0),x=(0,Q.useRef)(void 0),S=(0,Q.useRef)($i(r,i)),C=(0,Q.useRef)(null),w=(0,Q.useRef)(null),E=(0,Q.useRef)([]),D=(0,Q.useRef)(0),O=(0,Q.useRef)({names:[],cols:new Map});O.current=(0,Q.useMemo)(()=>({names:r.map(e=>e.data.name),cols:new Map(r.map(e=>[e.data.name,e.data.columns.map(e=>e.name)]))}),[r]);let k=(0,Q.useMemo)(()=>Gi(),[]),ee=(0,Q.useRef)(a);ee.current=a;let j=(0,Q.useRef)(``),M=(0,Q.useMemo)(()=>gn.updateListener.of(e=>{if(!e.selectionSet&&!e.docChanged)return;let t=ee.current;if(!t)return;let n=e.state.selection.main.head,r=e.state.doc.lineAt(n).text.match(/^\s*(?:Table|table)\s+["']?(\w+)["']?\s*\{/);r&&r[1]!==j.current?(j.current=r[1],t(r[1])):r||(j.current=``)}),[]),N=(0,Q.useRef)(n);N.current=n;let P=(0,Q.useRef)(t);P.current=t;let F=(0,Q.useRef)(e),te=(0,Q.useRef)(e),I=(0,Q.useRef)(!1),ne=(0,Q.useCallback)((e,t=E.current.length)=>{if(!t||!C.current)return;let n=e.coordsAtPos(e.state.selection.main.head);if(!n)return;let r=C.current.getBoundingClientRect(),i=Math.min(aa,Math.max(0,r.width-16)),a=Math.min(ia,t*30+8),o=Math.max(8,Math.min(n.left-r.left,r.width-i-8)),s=n.bottom-r.top+4,c=n.top-r.top-a-4,l=r.bottom-n.bottom>=a+8;g({left:o,top:l||n.top-r.top<=a+8?s:c})},[]),L=(0,Q.useCallback)(e=>{let t=w.current;t&&(t.dispatch({changes:{from:e.from,to:e.to,insert:e.label},selection:{anchor:e.from+e.label.length},annotations:un.userEvent.of(`input.complete`)}),E.current=[],f([]),t.focus())},[]),re=(0,Q.useCallback)((e,n)=>{if(!n.transactions.some(e=>e.annotation(un.userEvent)))return;I.current=!0,F.current=e,clearTimeout(x.current),t(e);let r=Ui(e,n.state.selection.main.head,O.current,ra);E.current=r,D.current=0,f(r),m(0),r.length&&ne(n.view,r.length)},[t,ne]),z=(0,Q.useCallback)(e=>{if(e.focusChanged&&!e.view.hasFocus){if(!E.current.length)return;E.current=[],f([])}else E.current.length&&ne(e.view)},[ne]),B=(0,Q.useMemo)(()=>[En(),An({top:!0}),Nn.of(Ri),k,M,pn.highest(Mn.of([{key:`Mod-f`,scope:`editor search-panel`,run:hn,preventDefault:!0},{key:`ArrowDown`,run:()=>{if(!E.current.length)return!1;let e=Math.min(D.current+1,E.current.length-1);return D.current=e,m(e),!0}},{key:`ArrowUp`,run:()=>{if(!E.current.length)return!1;let e=Math.max(D.current-1,0);return D.current=e,m(e),!0}},{key:`Escape`,run:()=>E.current.length?(E.current=[],f([]),!0):!1},...[`Enter`,`Tab`].map(e=>({key:e,run:()=>{let e=E.current[D.current];return e?(L(e),!0):!1}}))]))],[L,M,k]);(0,Q.useEffect)(()=>{I.current||(F.current=e,te.current=e);let t=w.current;if(!t||t.hasFocus)return;let n=t.state.doc.toString();e!==n&&t.dispatch({changes:{from:0,to:n.length,insert:e}})},[e]),(0,Q.useEffect)(()=>{if(c&&I.current&&e.trim()){if(e===te.current)I.current=!1;else if(ea(e))return clearTimeout(b.current),b.current=setTimeout(()=>{try{let t=T(e);te.current=e,I.current=!1,v.current=!0,N.current(t.nodes,t.edges,e),setTimeout(()=>{v.current=!1},0)}catch{}},ta),()=>clearTimeout(b.current)}},[e,c]);let V=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{if(r.length===0||I.current)return;if(v.current){v.current=!1;return}let e=V.current;if(V.current={data:new Map(r.map(e=>[e.id,e.data])),edges:i},!(e&&e.edges===i&&e.data.size===r.length&&r.every(t=>e.data.get(t.id)===t.data))&&$i(r,i)!==S.current)return clearTimeout(x.current),x.current=setTimeout(()=>{if(!y.current){y.current=!0;try{let e=R(r,i),t=F.current||``,n=new Set([...e.matchAll(/^\s*Enum\s+(?:"([^"]+)"|(\w+))\s*\{/gim)].map(e=>(e[1]||e[2]).toLowerCase())),a=(t.match(/^\s*Enum\s+(?:"[^"]+"|\w+)\s*\{[\s\S]*?^\s*\}/gim)||[]).filter(e=>{let t=e.match(/^\s*Enum\s+(?:"([^"]+)"|(\w+))\s*\{/i);return t&&!n.has((t[1]||t[2]).toLowerCase())}),o=t.match(/^(Note|TableGroup)\s+\S[\s\S]*?\}/gm)||[];if(a.length||o.length){let t=a.map(e=>e.trim()).join(`
|
|
49
|
+
|
|
50
|
+
`),n=o.length?`
|
|
51
|
+
|
|
52
|
+
`+o.map(e=>e.trim()).join(`
|
|
53
|
+
|
|
54
|
+
`):``,r=e.match(/^Ref:/m);if(r&&r.index!==void 0){let i=e.slice(0,r.index).trimEnd(),a=e.slice(r.index);e=i+(t?`
|
|
55
|
+
|
|
56
|
+
`+t:``)+`
|
|
57
|
+
|
|
58
|
+
`+a+n+`
|
|
59
|
+
`}else{let n=[t,...o.map(e=>e.trim())].filter(Boolean);e=e.trimEnd()+`
|
|
60
|
+
|
|
61
|
+
`+n.join(`
|
|
62
|
+
|
|
63
|
+
`)+`
|
|
64
|
+
`}}e=A(e),S.current=$i(r,i),e!==F.current&&P.current(e,!0)}catch{}finally{y.current=!1}}},na),()=>clearTimeout(x.current)},[r,i]),(0,$.jsxs)(`div`,{className:`h-full flex flex-col`,children:[(0,$.jsxs)(`div`,{className:`shrink-0 flex items-center justify-between px-4 py-3 border-b bg-muted/20`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Tt,{className:`size-4 text-primary`}),(0,$.jsx)(`h3`,{className:`text-sm font-semibold tracking-tight`,children:`DBML Editor`})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(W,{variant:`ghost`,size:`icon`,className:`size-8`,onClick:()=>u(!0),title:`DBML Reference`,children:(0,$.jsx)(He,{className:`size-3.5`})}),s]})]}),(0,$.jsxs)(`div`,{ref:C,className:`relative flex-1 min-h-0 overflow-hidden`,children:[(0,$.jsx)(Cn,{value:e,height:`100%`,theme:_===`dark`?xn:void 0,extensions:B,placeholder:`// DBML (Database Markup Language)
|
|
65
|
+
// Type your schema — live preview on canvas
|
|
66
|
+
|
|
67
|
+
Table users {
|
|
68
|
+
id integer [pk]
|
|
69
|
+
name varchar
|
|
70
|
+
}
|
|
71
|
+
`,className:`h-full text-sm`,basicSetup:oa,onCreateEditor:e=>{w.current=e},onChange:re,onUpdate:z}),d.length>0&&(0,$.jsx)(`div`,{role:`listbox`,"aria-label":`DBML suggestions`,style:{top:h.top,left:h.left},className:`absolute z-20 max-h-44 w-80 max-w-[calc(100%-1rem)] overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-lg`,children:d.map((e,t)=>(0,$.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":t===p,className:o(`flex w-full items-center justify-between gap-3 rounded px-2 py-1.5 text-left text-xs`,t===p?`bg-accent text-accent-foreground`:`hover:bg-accent/60`),onMouseDown:t=>{t.preventDefault(),L(e)},children:[(0,$.jsx)(`span`,{className:`truncate font-mono`,children:e.label}),(0,$.jsx)(`span`,{className:`shrink-0 text-[10px] text-muted-foreground`,children:e.detail||e.type})]},`${e.label}-${t}`))})]}),(0,$.jsx)(Qi,{open:l,onOpenChange:u,resolvedTheme:_})]})},(e,t)=>e.value===t.value&&e.nodes===t.nodes&&e.edges===t.edges);function ca(e,t){return e&&e.replace(/^(col-)([\w-]+)(-source|-target)(-[lr])?$/,(e,n,r,i,a)=>{let o=t.get(r);return o?`${n}${o}${i}${a||``}`:e})}function la(e,t,n,r){let i=new Map,a=t.map(e=>({...e})),o=e.map(e=>{let t=n.find(t=>t.data.name.toLowerCase()===e.data.name.toLowerCase());if(t){i.set(e.id,t.id);let n=new Map;e.data.columns=e.data.columns.map(e=>{let r=t.data.columns.find(t=>t.name.toLowerCase()===e.name.toLowerCase());return r?(n.set(e.id,r.id),{...e,id:r.id,name:r.name,enum_name:e.enum_name||r.enum_name,enum_values:e.enum_values||r.enum_values,comment:e.comment||r.comment,max_length:e.max_length??r.max_length,numeric_precision:e.numeric_precision??r.numeric_precision,numeric_scale:e.numeric_scale??r.numeric_scale,type:r.type.toUpperCase()===`ENUM`&&r.enum_values&&e.type.toUpperCase()!==`ENUM`?r.type:e.type}):e}),e.data.constraints=(e.data.constraints||[]).map(e=>({...e,entity_id:t.id,column_ids:(e.column_ids||[]).map(e=>n.get(e)||e)})),e.data.indexes=(e.data.indexes||[]).map(e=>({...e,entity_id:t.id,column_ids:(e.column_ids||[]).map(e=>n.get(e)||e)}));for(let t of a)t.source===e.id&&(t.sourceHandle=ca(t.sourceHandle,n)),t.target===e.id&&(t.targetHandle=ca(t.targetHandle,n));return{...e,id:t.id,position:t.position,data:{...e.data,name:t.data.name,comment:e.data.comment??t.data.comment,id:t.data.id,x:t.data.x,y:t.data.y,color:t.data.color,collapsed:t.data.collapsed,hidden_columns:t.data.hidden_columns,note:t.data.note}}}return e}),s=a.map(e=>{let t=i.get(e.source)||e.source,n=i.get(e.target)||e.target,a=e.sourceHandle?.replace(/^col-/,``).replace(/-(source|target)(-[lr])?$/,``)||``,s=e.targetHandle?.replace(/^col-/,``).replace(/-(source|target)(-[lr])?$/,``)||``,c=B(r,t,n,e.sourceHandle,e.targetHandle);if(c)return{...e,id:c.id,source:t,target:n,sourceHandle:c.sourceHandle,targetHandle:c.targetHandle};let l=o.find(e=>e.id===t),u=o.find(e=>e.id===n),d=l?.position.x??0,f=u?.position.x??0,p=d<f?`source`:`source-l`,m=d<f?`target`:`target-r`;return{...e,source:t,target:n,sourceHandle:a?`col-${a}-${p}`:void 0,targetHandle:s?`col-${s}-${m}`:void 0}});return{nodes:ae(o),edges:s}}function ua(e){if(!e.trim())return!1;try{return T(e),!0}catch{return!1}}function da(e){return JSON.stringify({name:e.name,columns:e.columns.map(e=>({name:e.name,type:e.type,is_pk:e.is_pk,is_nullable:e.is_nullable,default_value:e.default_value||null,is_unique:!!e.is_unique,comment:e.comment||``,max_length:e.max_length??null,numeric_precision:e.numeric_precision??null,numeric_scale:e.numeric_scale??null})),comment:e.comment||``,constraints:(e.constraints||[]).map(t=>({kind:t.kind,name:t.name||``,columns:(t.column_ids||[]).map(t=>e.columns.find(e=>e.id===t)?.name||t).sort(),expression:t.expression||``})).sort((e,t)=>JSON.stringify(e).localeCompare(JSON.stringify(t))),indexes:(e.indexes||[]).map(t=>({name:t.name,is_unique:!!t.is_unique,algorithm:t.algorithm||``,columns:(t.column_ids||[]).map(t=>e.columns.find(e=>e.id===t)?.name||t).sort()})).sort((e,t)=>JSON.stringify(e).localeCompare(JSON.stringify(t)))})}var fa=20,pa=85,ma=(0,Q.memo)(function({open:e,onClose:t}){let{id:n}=s(),{activeDiagram:r,saveDiagram:i,viewportRef:a,isGuest:c,triggerDebouncedSync:l,setNodes:u,setEdges:d,takeSnapshot:f,setSelectedNodeId:p}=tr(),{nodes:h,edges:g}=Gn(),_=m(e),[v,y]=(0,Q.useState)(48),b=(0,Q.useRef)(null),[x,S]=(0,Q.useState)(``),C=(0,Q.useRef)(``),w=(0,Q.useRef)(!1),T=(0,Q.useRef)(null),E=(0,Q.useCallback)(e=>{C.current=e,S(e)},[]),D=n?`erd-builder-dbml:${n}`:null,O=r?.dbml_source??r?.dbmlSource??``;(0,Q.useEffect)(()=>{let e=T.current!==D;if(e&&(T.current=D,w.current=!1),!D)E(``);else if(O)!e&&w.current&&C.current.trim()||E(O);else if(e||!w.current)try{let e=localStorage.getItem(D)||``;E(e)}catch{E(``)}},[D,O,E]),(0,Q.useEffect)(()=>{if(e&&h.length>0&&!x.trim())try{let e=R(h,g);e.trim()&&E(e)}catch{}},[e,h,g,x,E]),(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail;t?.diagramUid&&t.diagramUid!==r?.uid||t?.dbmlSource&&E(t.dbmlSource)};return window.addEventListener(wn,e),()=>window.removeEventListener(wn,e)},[r?.uid,E]);let k=(0,Q.useCallback)((e,t=!1)=>{E(e),w.current=!t,t&&ua(e)&&i(h,g,a.current,{dbmlSource:e}).then(()=>{c||l()})},[i,h,g,a,c,l,E]),A=(0,Q.useCallback)((e,t,n)=>{let{nodes:r,edges:o}=la(e,t,h,g),s=r.length===h.length&&r.every(e=>{let t=h.find(t=>t.id===e.id);return!t||e.data.name!==t.data.name?!1:da(e.data)===da(t.data)}),c=e=>JSON.stringify({source:e.source,target:e.target,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle,label:e.label,data:e.data}),p=o.map(c).sort(),m=g.map(c).sort(),_=JSON.stringify(p)===JSON.stringify(m);s&&_?(i(h,g,a.current,{dbmlSource:n}).then(()=>l()),w.current=!1):(f?.(h,g),u(r),d(o),w.current=!1,i?.(r,o,a?.current,{dbmlSource:n})?.then(()=>l?.()))},[h,g,u,d,f,i,a,l]),ee=(0,Q.useRef)(null);return(0,$.jsxs)(`div`,{ref:b,role:`dialog`,"aria-label":`DBML drawer`,"aria-hidden":!e||void 0,style:{height:`${v}%`},className:o(`nowheel nodrag absolute inset-x-2 bottom-2 z-30 flex flex-col overflow-hidden rounded-xl border bg-card text-card-foreground shadow-2xl`,!e&&`hidden`),children:[(0,$.jsx)(`div`,{role:`separator`,"aria-orientation":`horizontal`,"aria-label":`Resize DBML drawer`,"aria-valuemin":fa,"aria-valuemax":pa,"aria-valuenow":v,tabIndex:0,onPointerDown:e=>{let t=b.current?.parentElement;t&&(e.currentTarget.setPointerCapture(e.pointerId),ee.current=t.getBoundingClientRect())},onPointerMove:e=>{let t=ee.current;if(!t)return;let n=(t.bottom-e.clientY)/t.height*100;y(Math.round(Math.max(fa,Math.min(pa,n))))},onLostPointerCapture:()=>{ee.current=null},onKeyDown:e=>{(e.key===`ArrowUp`||e.key===`ArrowDown`)&&(e.preventDefault(),y(t=>Math.max(fa,Math.min(pa,t+(e.key===`ArrowUp`?5:-5)))))},className:`flex h-3 shrink-0 cursor-row-resize touch-none items-center justify-center focus-visible:bg-accent`,children:(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`h-1 w-10 rounded-full bg-border`})}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,$.jsx)(sa,{parserReady:_,value:x,onChange:k,onApply:A,nodes:h,edges:g,onSelectTable:e=>{let t=h.find(t=>t.data.name.toLowerCase()===e.toLowerCase());t&&p(t.id)},headerActions:(0,$.jsx)(W,{type:`button`,variant:`ghost`,size:`icon`,className:`size-8`,onClick:t,"aria-label":`Close DBML drawer`,title:`Close`,children:(0,$.jsx)(It,{className:`size-3.5`})})})})]})}),ha=.5,ga=1.2;function _a(e,t){let n=new Set;for(let r of t)r.source===e&&r.target!==e&&n.add(r.target),r.target===e&&r.source!==e&&n.add(r.source);return[...n]}var va=16,ya=(e,t)=>e.x<t.x+t.width&&t.x<e.x+e.width&&e.y<t.y+t.height&&t.y<e.y+e.height;function ba(e,t,n){return e.x>=n+va&&e.y>=va&&e.x+e.width<=t.width-va&&e.y+e.height<=t.height-va}function xa(e,t){let n=Math.min(576,t.height-32);return{top:Math.max(va,Math.min(e.y,t.height-va-n)),height:n}}function Sa(e,t,n,r=va,i=384){let{top:a,height:o}=xa(e,t),s=[`right`,`left`].map(s=>{let c={x:s===`right`?e.x+e.width+12:e.x-12-i,y:a,width:i,height:o};return{side:s,fits:c.x>=r&&c.x+i<=t.width-va,covered:n.filter(e=>ya(c,e)).length}}).filter(e=>e.fits);return s.length===0?null:s.reduce((e,t)=>t.covered<e.covered?t:e).side}var Ca=400,wa=()=>window.matchMedia(`(prefers-reduced-motion: reduce)`).matches?0:Ca;function Ta(){let{getNodesBounds:e,getViewport:t,setViewport:n}=U(),r=D(),i=(0,Q.useCallback)(()=>{let{width:e,height:t}=r.getState();return{width:e,height:t}},[r]),a=(0,Q.useCallback)(n=>{let r=e(n),{x:i,y:a,zoom:o}=t();return{x:r.x*o+i,y:r.y*o+a,width:r.width*o,height:r.height*o}},[e,t]),o=(0,Q.useCallback)(async(e,r,a=0)=>{let{width:o,height:s}=i(),c=Math.max(1,o-r-a),l=t().zoom,u=Math.min((c-96)/e.width,(s-96)/e.height),d=Math.max(ha,Math.min(ga,Math.min(l,u))),f={x:r+c/2-(e.x+e.width/2)*d,y:s/2-(e.y+e.height/2)*d,zoom:d},p=wa();n(f,{duration:p}),p&&await new Promise(e=>window.setTimeout(e,p+50));let m=t();(Math.abs(m.x-f.x)>1||Math.abs(m.y-f.y)>1||Math.abs(m.zoom-f.zoom)>.001)&&await n(f)},[i,t,n]);return{reveal:(0,Q.useCallback)(async(t,n)=>{t.length!==0&&(ba(a(t),i(),n)||await o(e(t),n))},[i,e,o,a]),placePopover:(0,Q.useCallback)(async(t,n)=>{let r=i(),s=()=>n.map(e=>a([e])),c=a([t]),l=ba(c,r,72)?Sa(c,r,s(),72):null;return l||=(await o(e([t]),72,396),c=a([t]),Sa(c,r,s(),72)??`right`),{side:l,anchor:c,top:xa(c,r).top}},[i,e,o,a])}}function Ea(e,t){let n=te(),r=typeof navigator<`u`&&/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent);return(0,Q.useEffect)(()=>{if(!e)return;let i=e=>{n()&&(!(r?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey)||e.key.toLowerCase()!==`f`||!e.shiftKey||e.altKey||e.isComposing||e.defaultPrevented||e.target?.closest(`.cm-editor, [role="dialog"], [role="alertdialog"]`)||(e.preventDefault(),e.stopPropagation(),t()))};return window.addEventListener(`keydown`,i,!0),()=>window.removeEventListener(`keydown`,i,!0)},[e,r,t]),{label:r?`⇧⌘F`:`Ctrl+Shift+F`,ariaKeyShortcuts:r?`Meta+Shift+F`:`Control+Shift+F`}}function Da({nodes:e,edges:t,canEdit:n,isActive:r,shortcutEnabled:i,diffPending:a}){let o=te(),{getEdges:s}=U(),{setSelectedNodeId:c}=tr(),{reveal:l,placePopover:u}=Ta(),d=pr(),f=(0,Q.useRef)(null),p=(0,Q.useRef)(null),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(Si),v=(0,Q.useCallback)(e=>_(t=>({...t,...e})),[]),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)(null),[C,w]=(0,Q.useState)(!1),T=(0,Q.useRef)(null),E=(0,Q.useRef)(0),D=(0,Q.useRef)({canEdit:n,diffPending:a,isMobile:d,inspector:x});D.current={canEdit:n,diffPending:a,isMobile:d,inspector:x};let O=!!x?.floating,k=(0,Q.useCallback)(()=>{E.current++,S(e=>e?.floating?null:e)},[]),A=(0,Q.useCallback)(()=>{E.current++,S(null)},[]),ee=(0,Q.useCallback)(()=>{D.current.diffPending||(h(!0),w(!1),k(),requestAnimationFrame(()=>p.current?.querySelector(`input`)?.focus()))},[k]),j=(0,Q.useCallback)(()=>{h(!1),b(null)},[]),M=Ea(r&&i,ee),N=(0,Q.useCallback)(e=>{b(e);let t=e.type===`relationship`?s().find(t=>t.id===e.id):void 0;l(t?[t.source,t.target]:[e.id],D.current.isMobile?0:372)},[s,l]),P=(0,Q.useCallback)(async(e,t)=>{if(!D.current.canEdit||D.current.diffPending)return;let n=++E.current,r=t??T.current??(D.current.isMobile||(f.current?.clientWidth??0)>=1100);if(w(!1),h(!1),b(null),r){S({id:e,floating:null}),c(e),l([e],72);return}let{side:i,anchor:a,top:o}=await u(e,_a(e,s()));n!==E.current||D.current.diffPending||(S({id:e,floating:{side:i,left:i===`right`?a.x+a.width+12:a.x-12-384,top:o}}),c(e))},[s,u,l,c]),F=(0,Q.useRef)(P);F.current=P;let I=(0,Q.useCallback)(e=>void F.current(e),[]),ne=(0,Q.useCallback)(()=>{let e=D.current.inspector;if(!e)return;let t=e.floating!==null;T.current=t,P(e.id,t)},[P]),L=(0,Q.useCallback)(()=>{A(),h(!0),v({tab:`tables`})},[A,v]),re=(0,Q.useCallback)(()=>{D.current.diffPending||(w(e=>!e),A(),h(!1),b(null))},[A]),R=(0,Q.useCallback)(()=>w(!1),[]),z=(0,Q.useCallback)(e=>{j();let t=D.current.inspector;t&&t.id!==e&&P(e,t.floating===null)},[j,P]),B=(0,Q.useCallback)((e,t)=>{t instanceof Element&&t.closest(`.nodrag`)||P(e)},[P]),V=(0,Q.useCallback)(()=>{j(),k()},[j,k]),ie=(0,Q.useCallback)(e=>{D.current.canEdit&&!D.current.diffPending&&(h(!0),w(!1),k(),v({tab:`relationships`,activeRelationshipId:e,editingEdgeId:e}),b({type:`relationship`,id:e}))},[k,v]);(0,Q.useEffect)(()=>{a&&(E.current++,S(null),w(!1),h(!1),b(null))},[a]),(0,Q.useEffect)(()=>{if(!x)return;let e=e=>{if(e.key!==`Escape`||e.defaultPrevented||!o())return;let t=e.target instanceof HTMLElement?e.target:null;t?.closest(`[role="dialog"], [role="alertdialog"], [role="listbox"], [role="menu"]`)||(t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.tagName===`SELECT`||t.isContentEditable||t.closest(`.cm-editor`))?t.blur():A())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[x,o,A]),(0,Q.useEffect)(()=>{!x||n&&e.some(e=>e.id===x.id)||A(),n||w(!1)},[x,e,n,A]);let H=(0,Q.useMemo)(()=>{let n=n=>e.some(e=>e.id===n)?{tables:new Set([n]),edges:new Set(t.filter(e=>e.source===n||e.target===n).map(e=>e.id))}:null;if(x)return n(x.id);if(!m||!y)return null;if(y.type===`table`)return n(y.id);let r=t.find(e=>e.id===y.id);return r?{tables:new Set([r.source,r.target]),edges:new Set([r.id])}:null},[x,m,y,e,t]),ae=x?e.find(e=>e.id===x.id):void 0;return{layoutRef:f,explorerRef:p,explorerOpen:m,explorer:g,patchExplorer:v,explorerShortcut:M,openExplorer:ee,closeExplorer:j,highlightTarget:N,inspector:x,inspectorEntity:(0,Q.useMemo)(()=>ae?ae.data.id===ae.id?ae.data:{...ae.data,id:ae.id}:null,[ae?.data,ae?.id]),popoverFloating:O,editTable:P,openTableEditor:I,togglePin:ne,closeInspector:A,backToExplorer:L,dbmlOpen:C,toggleDBML:re,closeDBML:R,focus:H,onNodeClick:z,onNodeDoubleClick:B,onPaneClick:V,onEdgeClick:ie}}var Oa={entity:Pr},ka={padding:.3};function Aa(e){let t=e.sourceX+(e.sourcePosition===C.Right?16:e.sourcePosition===C.Left?-16:0),n=e.sourceY+(e.sourcePosition===C.Bottom?16:e.sourcePosition===C.Top?-16:0);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ui,{...e}),(0,$.jsx)(ee,{children:(0,$.jsx)(`div`,{className:`nodrag nopan pointer-events-auto absolute`,style:{transform:`translate(-50%, -50%) translate(${t}px, ${n}px)`},children:(0,$.jsx)(ze,{anchor:{type:`relationship`,id:e.id}})})})]})}var ja={commentable:Aa,smoothstep:ui},Ma=Q.memo(({nodes:e,edges:t,setNodes:n,setEdges:r,onNodesChange:a,onEdgesChange:o,onConnect:s,onNodeClick:c,onNodeDoubleClick:u,onEdgeClick:d,onPaneClick:f,onMove:p,addEntity:m,onImportSQL:_,onAutoLayout:C,onDatabaseSchemaApplied:w,handleExportImage:T,isReadOnly:E=!1,isDbClient:D=!1,isActive:O=!0,sourceConnectionId:A,undo:ee,redo:j,canUndo:M,canRedo:N,takeSnapshot:P,selectedNodeId:I,onNodeDragStop:ne,onMoveEnd:L,initialViewport:re,isLoading:z,saveDiagram:B,triggerDebouncedSync:ie,pendingErdDiffTrigger:ae,extractColumnIdFromHandle:se,getRelationKey:ce,dedupeEdgesByRelation:le,onEdgeReconnect:W,comments:ue})=>{let{registerContentHandler:de,setSelectionText:fe,setActionContextData:pe,setRightPanelMode:me}=Ne(),he=te(),{getViewport:ge,getNodes:_e,getEdges:G,setViewport:ve,setCenter:ye}=U(),{resolvedTheme:be,activeDiagram:xe,syncDrafts:Se,hasPendingSyncs:Ce,isLocalSaving:we,handleEdgeUpdate:Te,handleEdgeFlip:Ee,deleteEdge:De}=tr(),Oe=be===`dark`?`#222`:`#ccc`,K=D,je=async e=>{let t=e.type===`table`?_e():G();!E&&!K&&B&&t.some(t=>t.id===e.id)&&(!J(xe?.data,e)||we||Ce)&&(await B(_e(),G(),ge()),await Se())},[Me,Le]=(0,Q.useState)(!1),[ze,Be]=(0,Q.useState)(null),Ve=(0,Q.useCallback)((e,t)=>Be(t.id),[]),He=(0,Q.useCallback)(()=>Be(null),[]),[Ue,We]=(0,Q.useState)(null),Ke=Q.useMemo(()=>Ue?{getBoundingClientRect:()=>new DOMRect(Ue.x,Ue.y,0,0)}:null,[Ue]),qe=Q.useRef(null),Je=!E&&!K,Ye=Q.useRef(!1),Xe=(0,Q.useCallback)((e,t)=>{ue&&(e.preventDefault(),We({x:e.clientX,y:e.clientY,id:t.id}))},[ue]),Ze=(0,Q.useCallback)(()=>{Ue&&(window.dispatchEvent(new CustomEvent(Re,{detail:{type:`relationship`,id:Ue.id}})),We(null))},[Ue]),Qe=(0,Q.useCallback)((e,t)=>{let n=t.zoom<.35;n!==Ye.current&&(Ye.current=n,qe.current?.classList.toggle(`erd-canvas-low-detail`,n)),p(e,t)},[p]),$e=(0,Q.useCallback)((e,t)=>{if(!t||e===`general`)return;let n=_e(),r=e=>({x:e.position.x+(e.measured?.width??e.width??180)/2,y:e.position.y+(e.measured?.height??e.height??120)/2});if(e===`table`){let e=n.find(e=>e.id===t);if(e){let t=r(e);ye(t.x,t.y,{zoom:ge().zoom,duration:0})}return}let i=G().find(e=>e.id===t);if(!i)return;let a=n.find(e=>e.id===i.source),o=n.find(e=>e.id===i.target);if(!a||!o)return;let s=r(a),c=r(o);ye((s.x+c.x)/2,(s.y+c.y)/2,{zoom:ge().zoom,duration:0})},[G,_e,ge,ye]);Q.useEffect(()=>{let e=e=>{let t=e.detail;(t?.fileId?String(xe?.uid??xe?.id)!==t.fileId:!he())||t?.type&&$e(t.type,t.id??null)};return window.addEventListener(`erd-discussion-anchor-selected`,e),()=>window.removeEventListener(`erd-discussion-anchor-selected`,e)},[$e,xe?.uid,xe?.id]);let et=(0,Q.useCallback)(()=>{if(!B)return;let e=_e();e.length!==0&&B(e,G(),ge()).then(()=>ie?.()).catch(e=>console.error(`Error saving ERD after node drag:`,e))},[G,_e,ge,B,ie]),tt=(0,Q.useCallback)(()=>{ne?.(),B&&requestAnimationFrame(et)},[ne,et,B]);Q.useEffect(()=>{if(z||!re)return;let e=requestAnimationFrame(()=>{ve(re,{duration:0})});return()=>cancelAnimationFrame(e)},[re,z,ve]);let[nt,rt]=(0,Q.useState)([]),[Y,it]=(0,Q.useState)(null),[at,ot]=(0,Q.useState)([]),[st,ct]=(0,Q.useState)(!1),X=Da({nodes:e,edges:t,canEdit:Je,isActive:O,shortcutEnabled:!K,diffPending:Y!==null}),{onNodeClick:lt,onNodeDoubleClick:ut,onPaneClick:dt,onEdgeClick:ft}=X,pt=(0,Q.useCallback)((e,t)=>{e.ctrlKey||e.metaKey?(e.stopPropagation(),rt(e=>e.includes(t.id)?e.filter(e=>e!==t.id):[...e,t.id])):(rt([]),c(e,t),lt(t.id))},[c,lt]),mt=(0,Q.useCallback)((e,t)=>{u?.(e,t),ut(t.id,e.target)},[u,ut]),ht=(0,Q.useCallback)(()=>{rt([]),f(),dt()},[f,dt]),gt=(0,Q.useCallback)((e,t)=>{d?.(e,t),ft(t.id)},[d,ft]),_t=Q.useMemo(()=>nt.length>0?nt:I?[I]:[],[nt,I]),{focus:vt}=X,yt=Q.useRef(new Map),bt=Q.useMemo(()=>{let t=yt.current,n=new Map,r=e.map(e=>{let r=_t.includes(e.id),i=vt?.tables.has(e.id)?`erd-node-focus`:void 0;if(!!e.selected===r&&e.className===i)return e;let a=t.get(e.id),o=a&&a.node===e&&a.selected===r&&a.className===i?a.styled:{...e,selected:r,className:i};return n.set(e.id,{node:e,selected:r,className:i,styled:o}),o});return yt.current=n,r},[e,_t,vt]),xt=Q.useMemo(()=>Y?Y.diffNodes.map(e=>({...e,data:{...e.data,isDiffMode:!0}})):[],[Y]),St=!!ue,wt=Q.useMemo(()=>$r(t,_t,ze).map(e=>{let t=vt?.edges.has(e.id)?{...e,className:[...(e.className??``).split(` `).filter(e=>e&&e!==`edge-animated-active`&&e!==`edge-dimmed`),`edge-animated-active`].join(` `)}:e;return St?{...t,type:`commentable`}:t}),[t,_t,St,ze,vt]),Tt=Q.useMemo(()=>Y?$r(Y.diffEdges):[],[Y]),Et=(0,Q.useCallback)(e=>{let t=e.filter(e=>e.type!==`select`);if(t.length===0)return;let n=K?b(t,Dt.current):E?t:l(t,Dt.current);a(n),n!==t&&t.some(e=>e.type===`dimensions`)&&requestAnimationFrame(()=>{ne?.(),et()})},[a,E,K,ne,et]),Dt=Q.useRef(e),Ot=Q.useRef(t),At=Q.useRef(I),jt=Q.useRef(_t);Dt.current=e,Ot.current=t,At.current=I,jt.current=_t,Q.useEffect(()=>{if(!O)fe(null);else if(_t.length>0){let e=_t.map(e=>Dt.current.find(t=>t.id===e)).filter(e=>!!e);if(e.length===0)return;let t=e.map(e=>`${e.data.name||e.data.label||e.id} (${(e.data.columns||[]).map(e=>`${e.name}: ${e.type}${e.max_length?`(${e.max_length})`:``}${e.numeric_precision?`(${e.numeric_precision}${e.numeric_scale!==null&&e.numeric_scale!==void 0?`,${e.numeric_scale}`:``})`:``}${e.is_pk?` PK`:``}${e.is_nullable?` NULL`:``}${e.comment?` -- ${e.comment}`:``}`).join(`, `)})`).join(`; `);fe(`Tables: ${t}`)}else fe(null)},[_t,fe,O]),Q.useEffect(()=>{if(!O)return;let e=I?Dt.current.find(e=>e.id===I)??null:null,t=_t.map(e=>Dt.current.find(t=>t.id===e)).filter(e=>!!e);pe({nodes:Dt.current,edges:Ot.current,selectedNode:e,multiSelectedNodes:t})},[I,_t,pe,O]);let Mt=Q.useRef(P);Mt.current=P;let Nt=(0,Q.useCallback)(()=>{Mt.current?.(Dt.current,Ot.current)},[]),Pt=(0,Q.useCallback)(()=>{K&&Le(!0)},[K]),Ft=(0,Q.useCallback)(()=>Le(!1),[]),It=(0,Q.useCallback)((e,t)=>{if(Y||!t.sourceHandle||!t.targetHandle)return;if(K){if(!vr(e,t)){i.info(`Only the connector position can be changed`);return}let n=v(e,t,Ot.current);r(n),W?.(n);return}if(E)return;let n=qn(Dt.current,Ot.current),a=n.nodesById.get(t.source),o=n.nodesById.get(t.target);if(a&&o){let r=String(t.sourceHandle).replace(/^col-/,``).replace(/-(source|target)(-(l|r))?$/,``),s=String(t.targetHandle).replace(/^col-/,``).replace(/-(source|target)(-(l|r))?$/,``),c=n.columnsByNodeAndId.get(Pn(a.id,r)),l=n.columnsByNodeAndId.get(Pn(o.id,s));if(c&&l&&c.type!==l.type){i.error(`Type Mismatch`,{description:`Cannot reconnect ${c.type} to ${l.type}`});return}if(se&&ce){let r=se(t.sourceHandle),a=se(t.targetHandle);if(r&&a){let o=c?.name?.toLowerCase(),s=l?.name?.toLowerCase(),u=o?`${t.source}:${o}`:null,d=s?`${t.target}:${s}`:null,f=`${[t.source,t.target].sort().join(`:`)}:${[r,a].sort().join(`:`)}`,p=n.edgesByRelationKey.get(f)?.some(t=>t.id!==e.id)??!1,m=u&&d?[u,d].sort().join(`::`):null,h=m?n.edgesByRelationName.get(m)?.some(t=>t.id!==e.id)??!1:!1;if(p||h){i.info(`Relation already exists`);return}}}if(se&&c?.name){let t=n.edgesBySourceColumnName.get(Kn(a.data.name,c.name))?.find(t=>t.id!==e.id);if(t){let e=n.nodesById.get(t.target);i.error(`FK already related`,{description:`This column is already related to ${e?.data.name||`another table`}. One FK column can only point to one PK.`,duration:4e3});return}}}Mt.current?.(Dt.current,Ot.current);let s=v(e,t,Ot.current);r(le?le(s):s)},[Y,K,E,r,W,se,ce,le]),Lt=(0,Q.useCallback)((e,t,n,r,a={})=>{let o=Kr(e,t,n,r),s=a.source||`proposal`;o.changes.length===0?(it(null),i.success(s.startsWith(`repository`)?`Repository schema matches the comparison source`:`No schema changes found`)):(ot(o.changes.map(e=>e.id)),it({originalNodes:e,originalEdges:t,proposedNodes:n,proposedEdges:r,diffNodes:o.nodes,diffEdges:o.edges,diffResult:o,source:s,version:a.version,sourceLabel:a.sourceLabel,commit:a.commit,dbmlSource:a.dbmlSource}),ct(s!==`proposal`))},[]);Q.useEffect(()=>{let e=e=>{if(K)return;let t=e.detail;t?he()&&Lt(Dt.current,Ot.current,t.nodes,t.edges,{source:`history`,version:t.version}):it(e=>e?.source===`history`?null:e)};return window.addEventListener(Tn,e),()=>window.removeEventListener(Tn,e)},[Lt,K]),Q.useEffect(()=>{let e=e=>{if(K||!he())return;let t=e.detail;t?Lt(t.originalNodes||Dt.current,t.originalEdges||Ot.current,t.proposedNodes,t.proposedEdges,{source:t.canApply?`repository`:`repository-compare`,sourceLabel:t.sourceLabel,commit:t.commit,dbmlSource:t.dbmlSource}):it(e=>e?.source.startsWith(`repository`)?null:e)};return window.addEventListener(Dn,e),()=>window.removeEventListener(Dn,e)},[Lt,K]);let Rt=Q.useRef(null),{sync:zt,isSyncing:Bt}=Qr(O?A:void 0,e=>{Rt.current=e;let t=yr(e.schema,br(Dt.current,ge(),{},Ot.current));Lt(Dt.current,Ot.current,t.nodes,t.edges,{source:`database`})}),Vt=(0,Q.useCallback)(()=>{it(null),Y?.source===`history`?(me(`closed`),i.info(`Version preview closed`)):Y?.source.startsWith(`repository`)?i.info(`Repository preview closed`):i.info(Y?.source===`database`?`Database schema preview closed`:`AI schema update rejected`)},[Y?.source,me]),Ht=(0,Q.useCallback)(()=>{if(!Y||E&&!(K&&Y.source===`database`))return;let{originalNodes:e,originalEdges:t,proposedNodes:a,proposedEdges:o,diffResult:s}=Y,{nodes:c,edges:l}=Zr(e,t,a,o,s,at);if(Mt.current?.(Dt.current,Ot.current),n(c),r(l),it(null),Y.source===`database`){let e=Rt.current;e&&A&&Er(A,e),w?.(c,l,e)}if(i.success(Y.source===`database`?`Database schema view updated`:Y.source===`repository`?`Repository schema merged successfully`:`AI changes merged successfully!`),B){let e=Y.source===`repository`?at.length===s.changes.length&&Y.dbmlSource?Y.dbmlSource:R(c,l):void 0,t=e?{dbmlSource:e}:void 0;B(c,l,ge(),t).then(()=>{ie?.(),Y.source===`repository`&&window.dispatchEvent(new CustomEvent(wn,{detail:{dbmlSource:e,commit:Y.commit,diagramUid:xe?.uid}}))}).catch(e=>console.error(`Error saving after merge:`,e))}},[Y,at,n,r,B,ie,ge,E,K,w,A,xe?.uid]),Ut=Q.useMemo(()=>({type:`smoothstep`,animated:!1,reconnectable:!E||K,style:{stroke:`var(--edge-color)`,strokeWidth:2},markerEnd:{type:oe.Arrow,color:`var(--edge-color)`,width:10,height:10}}),[K,E]);Q.useEffect(()=>{if(!(E||K))return de((e,t,n)=>{if(!e)return;let r=null,a={selectedNodeId:At.current,selectedNodeIds:jt.current};try{n?r=Ct(Dt.current,Ot.current,n,e,a):(r=Ct(Dt.current,Ot.current,`erd-generate-sql`,e,a),r||=Ct(Dt.current,Ot.current,`erd-edit-column`,e,a))}catch(e){i.error(`Invalid ERD schema in AI response`,{description:e?.message||`Fix the DBML/SQL block and try Append again.`});return}r?Lt(Dt.current,Ot.current,r.nodes,r.edges):i.error(`No valid changes found in response`)},[`append`])},[de,Lt,E,K]),Q.useEffect(()=>{E||K||z||y()},[E,K,z]);let[Wt,Gt]=Q.useState(0),Kt=Q.useCallback(()=>!h()&&(g().then(()=>Gt(e=>e+1),()=>{}),!0),[]);Q.useEffect(()=>{if(E||K)return;let e=localStorage.getItem(`pending_create_erd_schema`)||localStorage.getItem(`pending_create_erd_ddl`);if(e){if(Kt())return;localStorage.removeItem(`pending_create_erd_schema`),localStorage.removeItem(`pending_create_erd_ddl`);let t=Ct(Dt.current,Ot.current,`erd-generate-sql`,e);t&&(Dt.current.length===0?(Mt.current?.([],[]),n(t.nodes),r(t.edges),B&&B(t.nodes,t.edges,{x:0,y:0,zoom:1}).then(()=>{ie?.()}).catch(e=>{console.error(`Error saving generated diagram:`,e)}),i.success(`Applied generated schema to new diagram`)):Lt(Dt.current,Ot.current,t.nodes,t.edges))}},[n,r,Lt,B,ie,E,K,Kt,Wt]),Q.useEffect(()=>{if(E||K)return;let t=localStorage.getItem(`pending_update_erd_schema`)||localStorage.getItem(`pending_update_erd_ddl`);if(!t||e.length===0||Kt())return;localStorage.removeItem(`pending_update_erd_schema`),localStorage.removeItem(`pending_update_erd_ddl`);let n=Ct(Dt.current,Ot.current,`erd-generate-sql`,t);n?(Lt(Dt.current,Ot.current,n.nodes,n.edges),i.info(`Review the schema changes and merge when ready`)):i.error(`Could not parse the schema for diff`)},[e,Lt,ae,E,K,Kt,Wt]);let qt=(0,$.jsxs)(`div`,{className:`flex-1 min-w-0 relative flex flex-col overflow-hidden border rounded-xl bg-muted/20`,style:{contain:`paint layout`},children:[(0,$.jsx)(Pe,{prepare:je}),E&&K&&(0,$.jsx)(`div`,{className:`absolute bottom-4 inset-x-0 z-20 flex justify-center pointer-events-none`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2 px-4 py-2 bg-amber-500/10 border border-amber-500/30 rounded-lg pointer-events-auto text-sm text-amber-700 dark:text-amber-400 shadow-lg`,children:[(0,$.jsx)(kt,{className:`h-4 w-4 shrink-0`}),(0,$.jsx)(`span`,{children:`Schema is read-only. Layout changes do not modify the database.`})]})}),!Y&&(0,$.jsx)(fi,{isReadOnly:E,isProductionDb:K,addEntity:m,onImportSQL:_,onAutoLayout:C,explorerOpen:X.explorerOpen,explorerShortcut:X.explorerShortcut,onToggleExplorer:X.explorerOpen?X.closeExplorer:X.openExplorer,onOpenDBML:X.toggleDBML,onOpenRepository:()=>me(`repository`),handleSync:zt,isSyncing:Bt,handleExportImage:T,undo:ee,redo:j,canUndo:M,canRedo:N}),z&&(0,$.jsx)(`div`,{className:`absolute inset-0 z-20 flex items-center justify-center bg-background/60 backdrop-blur-[1px] transition-opacity duration-150`,children:(0,$.jsx)(`div`,{className:`w-5 h-5 border-2 border-primary/30 border-t-primary rounded-full animate-spin`})}),(0,$.jsx)(`div`,{ref:qe,className:`flex-1`,children:(0,$.jsxs)(F,{id:K?`db-client-${A}`:xe?.uid?`erd-${xe.uid}`:void 0,nodes:Y?xt:bt,edges:Y?Tt:wt,onNodesChange:Et,onEdgesChange:o,onConnect:s,onReconnectStart:Pt,onReconnectEnd:Ft,onReconnect:It,nodeTypes:Oa,edgeTypes:ja,onNodeClick:pt,onNodeDoubleClick:mt,onEdgeClick:gt,onEdgeMouseEnter:Ve,onEdgeMouseLeave:He,onEdgeContextMenu:ue&&!Y?Xe:void 0,onPaneClick:ht,onMove:Qe,colorMode:be,onlyRenderVisibleElements:!0,nodesDraggable:!Y&&!X.popoverFloating&&(!E||K),panOnDrag:!X.popoverFloating,zoomOnScroll:!X.popoverFloating,zoomOnPinch:!X.popoverFloating,zoomOnDoubleClick:!X.popoverFloating,nodesConnectable:!Y&&(!E||K&&Me),elementsSelectable:!Y&&(!E||K),edgesReconnectable:!Y&&(!E||K),onNodeDragStart:Nt,onNodeDragStop:tt,onMoveEnd:L,minZoom:.1,maxZoom:2.5,defaultEdgeOptions:Ut,defaultViewport:re,connectionLineType:x.SmoothStep,connectionLineStyle:Ut.style,deleteKeyCode:null,children:[(0,$.jsx)(V,{variant:k.Lines,gap:50,size:1,color:Oe}),!X.popoverFloating&&(0,$.jsx)(H,{position:`bottom-left`,showInteractive:!1,fitViewOptions:ka})]})}),X.explorerOpen&&!Y&&(0,$.jsx)(`div`,{ref:X.explorerRef,className:`contents`,children:(0,$.jsx)(Ci,{nodes:e,edges:t,state:X.explorer,onChange:X.patchExplorer,editing:Je?{onEditTable:e=>void X.editTable(e),onUpdateEdge:Te,onFlipEdge:Ee,onDeleteEdge:De}:void 0,onHighlight:X.highlightTarget,onClose:X.closeExplorer,shortcutLabel:X.explorerShortcut.label})}),!Y&&X.inspectorEntity&&X.inspector?.floating&&(0,$.jsx)(Li,{entity:X.inspectorEntity,floating:X.inspector.floating,onTogglePin:X.togglePin,onClose:X.closeInspector,onBackToExplorer:X.backToExplorer}),Je&&(0,$.jsx)(ma,{open:X.dbmlOpen&&!Y,onClose:X.closeDBML}),Ue&&(0,$.jsxs)(ke,{open:!0,onOpenChange:e=>{e||We(null)},children:[(0,$.jsx)(Ae,{className:`fixed size-px opacity-0`,style:{left:Ue.x,top:Ue.y},onContextMenu:e=>e.preventDefault()}),(0,$.jsx)(q,{anchor:Ke,children:(0,$.jsxs)(Fe,{onClick:Ze,children:[(0,$.jsx)(Ge,{"aria-hidden":`true`}),`Comment`]})})]}),Y&&(0,$.jsx)(Rr,{diff:Y.diffResult,approvedIds:at,showChecklist:st,label:Y.source===`history`?`Version ${Y.version} Preview`:Y.source===`repository-compare`?`Git Comparison · ${Y.sourceLabel}`:Y.source===`repository`?`Repository Schema · ${Y.sourceLabel}`:void 0,rejectLabel:Y.source===`proposal`?`Reject All`:`Close Preview`,canMerge:(!E||K&&Y.source===`database`)&&Y.source!==`history`&&Y.source!==`repository-compare`,selectable:(!E||K&&Y.source===`database`)&&Y.source!==`history`&&Y.source!==`repository-compare`,checklistTitle:Y.source===`history`?`Changes in this version:`:`Select changes to merge:`,onApprovedIdsChange:ot,onShowChecklistChange:ct,onReject:Vt,onMerge:Ht})]}),Jt=Y?xt:e,Yt=Vn(Q.useMemo(()=>({nodes:Jt,edges:t}),[Jt,t])),Xt=Q.useMemo(()=>Yt.nodes.map(e=>({id:e.id,...e.position,...S(e)})),[Yt.nodes]),Zt=ze??t.find(e=>e.selected)?.id??null,Qt=(0,$.jsx)(li.Provider,{value:Xt,children:(0,$.jsx)(ci,{nodes:Yt.nodes,edges:Y?Tt:Yt.edges,tables:Xt,activeId:Zt,children:(0,$.jsx)(kr.Provider,{value:X.openTableEditor,children:(0,$.jsxs)(`div`,{ref:X.layoutRef,className:`relative flex min-h-0 min-w-0 flex-1 gap-2`,children:[qt,!Y&&X.inspectorEntity&&X.inspector&&!X.inspector.floating&&(0,$.jsx)(Li,{entity:X.inspectorEntity,floating:null,onTogglePin:X.togglePin,onClose:X.closeInspector,onBackToExplorer:X.backToExplorer})]})})})});return ue?(0,$.jsx)(Ie,{config:ue,children:Qt}):Qt},(e,t)=>{let n=e.isLoading!==t.isLoading,r=t.nodes.length>0,i=e.nodes.length===0,a=n&&r&&!i,o=e.initialViewport?.x===t.initialViewport?.x&&e.initialViewport?.y===t.initialViewport?.y&&e.initialViewport?.zoom===t.initialViewport?.zoom;return di(e.nodes,t.nodes)&&di(e.edges,t.edges)&&(a||e.isLoading===t.isLoading)&&e.isReadOnly===t.isReadOnly&&e.isDbClient===t.isDbClient&&e.sourceConnectionId===t.sourceConnectionId&&e.isActive===t.isActive&&e.onAutoLayout===t.onAutoLayout&&e.onDatabaseSchemaApplied===t.onDatabaseSchemaApplied&&e.comments?.projectId===t.comments?.projectId&&e.comments?.teamId===t.comments?.teamId&&e.comments?.fileId===t.comments?.fileId&&e.comments?.userId===t.comments?.userId&&o&&e.selectedNodeId===t.selectedNodeId&&e.canUndo===t.canUndo&&e.canRedo===t.canRedo&&e.onMoveEnd===t.onMoveEnd&&e.pendingErdDiffTrigger===t.pendingErdDiffTrigger&&e.extractColumnIdFromHandle===t.extractColumnIdFromHandle&&e.getRelationKey===t.getRelationKey&&e.dedupeEdgesByRelation===t.dedupeEdgesByRelation});function Na(e,t){let[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)([]),[c,l]=(0,Q.useState)([]),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(null),[g,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)({environment:`development`,safeMode:`protected`,sslMode:`disable`,queryTimeoutMs:3e4}),[b,x]=(0,Q.useState)(1),[S,C]=(0,Q.useState)(!1),[w,T]=(0,Q.useState)(!1),[E,D]=(0,Q.useState)(null),O=`__new_table__`,k=(0,Q.useRef)(null),A=(0,Q.useRef)(null),ee=(0,Q.useRef)(e);A.current=i,ee.current=e;let j=e?wr(e):null,M=(0,Q.useRef)([]),N=(0,Q.useRef)(null),P=(0,Q.useRef)([]),F=(0,Q.useRef)({}),te=(0,Q.useRef)({}),I=(0,Q.useRef)(null),ne=(0,Q.useRef)(!1),L=t?`${xr}${t}`:null,re=(t,n,r,i)=>JSON.stringify([e,t,n,r,i]),R=(0,Q.useRef)(new Map),z=(0,Q.useCallback)(()=>{j?.clear(),R.current.clear()},[j]),B=(0,Q.useCallback)(async(t=!1)=>{if(!e)return;let n=!t&&Tr(e);if(n)r(n.schema||[]),_(n.dbType||null),y(n.connectionSecurity||{environment:`development`,safeMode:`protected`,sslMode:`disable`,queryTimeoutMs:3e4}),C(!1),D(null);else{C(!0),D(null);try{let t=await cn(`/api/catalogs/${e}/schema`,{method:`POST`}),n=await t.json();if(ee.current!==e)return;if(!t.ok)throw Error(n.error||`Failed to fetch tables`);Er(e,n),r(n.schema||[]),_(n.dbType||null),y(n.connectionSecurity||{environment:`development`,safeMode:`protected`,sslMode:`disable`,queryTimeoutMs:3e4})}catch(t){ee.current===e&&D(t.message)}finally{ee.current===e&&C(!1)}}},[e]);(0,Q.useEffect)(()=>{P.current=c},[c]),(0,Q.useEffect)(()=>()=>k.current?.abort(),[]);let V=(0,Q.useCallback)(async(t,n=1,r=M.current,i=N.current)=>{if(!e)return;let a=re(t,n,r,i),o=j?.get(a);if(M.current=r,d(r),N.current=i,p(i),h(o||null),x(n),k.current?.abort(),o){F.current[t]=n,T(!1),D(null);return}let s=new AbortController;k.current=s;let c=JSON.stringify([e,t,r]),l=R.current.get(c);T(!0),D(null);try{let o=await cn(`/api/catalogs/${e}/records`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({table:t,page:n,pageSize:50,filters:r,sort:i,withTotal:!l}),signal:s.signal}),u=await o.json();if(k.current!==s)return;if(!o.ok)throw Error(u.error||`Failed to fetch records`);l?Object.assign(u,l):R.current.set(c,{total:u.total,tableInfo:u.tableInfo}),F.current[t]=n,j?.set(a,u),j&&j.size>20&&j.delete(j.keys().next().value),h(u),x(n)}catch(e){if(e.name===`AbortError`||k.current!==s)return;D(e.message)}finally{k.current===s&&T(!1)}},[e,j]),ie=(0,Q.useCallback)(e=>{e&&(te.current[e]={filters:P.current,appliedFilters:M.current,sort:N.current})},[]),H=(0,Q.useCallback)(e=>{let t=te.current[e]||{filters:[],appliedFilters:[],sort:null};return l(t.filters),M.current=t.appliedFilters,d(t.appliedFilters),N.current=t.sort,p(t.sort),t},[]);(0,Q.useEffect)(()=>{if(!L)return;let e=[],t=null,n={},r={};try{let i=JSON.parse(sessionStorage.getItem(L)||`{}`);e=Array.isArray(i.openTabs)?i.openTabs.filter(e=>e?.name):[],t=typeof i.activeTable==`string`?i.activeTable:null,i.pageByTable&&typeof i.pageByTable==`object`&&(n=Object.fromEntries(Object.entries(i.pageByTable).filter(([,e])=>Number.isInteger(e)&&Number(e)>0).map(([e,t])=>[e,Number(t)]))),i.tableState&&typeof i.tableState==`object`&&(r=Object.fromEntries(Object.entries(i.tableState).filter(([,e])=>Array.isArray(e?.filters)&&Array.isArray(e?.appliedFilters)).map(([e,t])=>[e,{filters:t.filters,appliedFilters:t.appliedFilters,sort:t.sort||null}])))}catch{}k.current?.abort(),k.current=null,ne.current=!0,I.current=L,s(e),a(t),F.current=n,te.current=r;let i=t?r[t]:null;l(i?.filters||[]),d(i?.appliedFilters||[]),M.current=i?.appliedFilters||[],N.current=i?.sort||null,p(i?.sort||null),h(null),x(1);let o=t&&n[t]||1,c=null;return t&&t!==O&&(x(o),c=setTimeout(()=>V(t,o,i?.appliedFilters||[],i?.sort||null))),()=>{c&&clearTimeout(c)}},[L,V]),(0,Q.useEffect)(()=>{if(L&&I.current===L){if(ne.current)ne.current=!1;else try{i&&(te.current[i]={filters:c,appliedFilters:u,sort:f}),sessionStorage.setItem(L,JSON.stringify({openTabs:o,activeTable:i,pageByTable:F.current,tableState:te.current}))}catch{}}},[L,o,i,b,c,u,f]);let U=(0,Q.useCallback)(()=>{ie(i),s(e=>e.some(e=>e.name===O)?e:[...e,{name:O,pinned:!0,label:`New table`}]),a(O)},[i,ie]),ae=(0,Q.useCallback)(e=>{if(e===O)return U();ie(i);let t=o.some(t=>t.name===e)?F.current[e]??1:1;s(t=>{if(t.some(t=>t.name===e))return t;let n=t.findIndex(e=>!e.pinned);if(n===-1)return[...t,{name:e,pinned:!1}];let r=[...t];return r[n]={name:e,pinned:!1},r}),a(e);let n=H(e);x(t),V(e,t,n.appliedFilters,n.sort)},[i,V,U,o,H,ie]),oe=(0,Q.useCallback)(e=>{s(t=>t.map(t=>t.name===e?{...t,pinned:!0}:t))},[]),se=(0,Q.useCallback)(e=>{let t=o.filter(t=>t.name!==e);if(delete F.current[e],delete te.current[e],s(t),i!==e)return;let n=t[t.length-1]?.name??null,r=n?F.current[n]??1:1;a(n);let c=n?H(n):{appliedFilters:[],sort:null};n||(l([]),d([]),M.current=[],N.current=null,p(null)),x(r),n&&n!==O&&V(n,r,c.appliedFilters,c.sort)},[i,o,V,H]),ce=(0,Q.useCallback)(()=>{if(!i||!m)return;let e=b+1;V(i,e)},[i,m,b,V]),le=(0,Q.useCallback)(()=>{if(!i||b<=1)return;let e=b-1;V(i,e)},[i,b,V]),W=m?Math.ceil(m.total/(m.pageSize||50)):0,ue=(0,Q.useCallback)((e=``)=>{l(t=>{let n=[...t,Or(e)];return P.current=n,n})},[]),de=(0,Q.useCallback)(e=>{l(t=>{let n=t.filter(t=>t.id!==e);return P.current=n,n})},[]),fe=(0,Q.useCallback)((e,t)=>{l(n=>{let r=n.map(n=>n.id===e?{...n,...t}:n);return P.current=r,r})},[]),pe=(0,Q.useCallback)((e=P.current)=>{i&&(oe(i),V(i,1,e))},[i,V,oe]),me=(0,Q.useCallback)(e=>{i&&(oe(i),V(i,1,[{...e,enabled:!0}]))},[i,V,oe]),he=(0,Q.useCallback)((e,t,n)=>{let r=[Or(t)];r[0].operator=`=`,r[0].value=String(n),s(t=>t.some(t=>t.name===e)?t.map(t=>t.name===e?{...t,pinned:!0}:t):[...t,{name:e,pinned:!0}]),ie(i),a(e),l(r),M.current=r,d(r),N.current=null,p(null),x(1),V(e,1,r)},[i,V,ie]),ge=(0,Q.useCallback)(async(t,n,r)=>{if(!e)return;let i=await cn(`/api/catalogs/${e}/records`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({table:t,key:n,values:r})}),a=await i.json();if(!i.ok)throw Error(a.error||`Failed to update record`);return z(),A.current===t&&V(t,F.current[t]??b),a},[i,z,e,V,b]),_e=(0,Q.useCallback)(async(t,n)=>{if(e&&n.length!==0)try{let r=await cn(`/api/catalogs/${e}/records`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({table:t,updates:n})}),i=await r.json();if(!r.ok)throw Error(i.error||`Failed to update records`)}finally{z(),A.current===t&&V(t,F.current[t]??b)}},[i,z,e,V,b]),G=(0,Q.useCallback)(async(t,n)=>{if(!e)return;let r=await cn(`/api/catalogs/${e}/records/create`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({table:t,values:n})}),i=await r.json();if(!r.ok)throw Error(i.error||`Failed to create record`);return z(),A.current===t&&V(t,F.current[t]??b),i},[i,z,e,V,b]),ve=(0,Q.useCallback)(async(t,n,r)=>{if(e)try{let i=await cn(`/api/catalogs/${e}/records`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify(Array.isArray(n)?{table:t,keys:n,confirmation:r}:{table:t,key:n,confirmation:r})}),a=await i.json();if(!i.ok)throw Error(a.error||`Failed to delete record`);return a}finally{z(),A.current===t&&V(t,F.current[t]??b)}},[i,z,e,V,b]),ye=(0,Q.useCallback)(async t=>{if(!e)return;let n=await cn(`/api/catalogs/${e}/structure`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({table:t.deleteTables?.[0]||t.truncateTables?.[0]||t.cloneTable?.source||`__table_action__`,...t})}),r=await n.json();if(!n.ok)throw Error(r.error||`Failed to update tables`);z(),Dr(e),await B();let i=A.current;return i&&t.truncateTables?.includes(i)&&V(i,1),r},[z,e,V,B]);return{tables:n,activeTable:i,openTabs:o,filters:c,appliedFilters:u,sort:f,records:m,dbType:g,connectionSecurity:v,page:b,totalPages:W,isLoadingTables:S,isLoadingRecords:w,error:E,fetchTables:B,selectTable:ae,openNewTableTab:U,pinTable:oe,closeTable:se,addFilter:ue,removeFilter:de,updateFilter:fe,applyFilter:me,applyFilters:pe,openRelatedRecord:he,createRecord:G,deleteRecord:ve,deleteTables:(0,Q.useCallback)(async(t,n)=>{if(!e||t.length===0)return;let r=await ye({deleteTables:t,...n});z();let i=new Set(t);s(e=>e.filter(e=>!i.has(e.name))),t.forEach(e=>{delete F.current[e],delete te.current[e]});let c=A.current;if(c&&i.has(c)){let e=o.find(e=>!i.has(e.name))?.name??null;a(e),h(null),l([]),d([]),M.current=[],N.current=null,p(null),e&&V(e,F.current[e]??1)}return r},[z,e,V,ye,o]),mutateTables:ye,updateRecord:ge,updateRecords:_e,updateStructure:(0,Q.useCallback)(async t=>{let r=i||(t.createTable?`__new__`:null);if(!e||!r)return;let o=await cn(`/api/catalogs/${e}/structure`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({table:r,...t})}),c=await o.json();if(!o.ok)throw Error(c.error||`Failed to update structure`);z(),Dr(e);let l=n.find(e=>e.table_name===i),u=l?.base_name&&l.base_name!==l.table_name?`${l.table_schema}.`:``,d=t.tableName&&u&&!String(t.tableName).startsWith(u)?`${u}${t.tableName}`:t.tableName,f=t.createTable?.name||d||i,p=A.current===i;return p&&(a(f),A.current=f),s(e=>e.some(e=>e.name===f)?e.map(e=>e.name===i?{...e,name:f,pinned:!0}:e):p?[...e,{name:f,pinned:!0}]:e.map(e=>e.name===i?{...e,name:f}:e)),F.current[f]=i?F.current[i]??b:1,i&&f!==i&&delete F.current[i],await B(),A.current===f&&V(f,F.current[f]??b),c},[i,z,e,V,B,b,n]),refreshAll:(0,Q.useCallback)(async()=>{z(),e&&Dr(e),await B();let t=A.current;ee.current===e&&t&&t!==O&&V(t,F.current[t]??b)},[z,e,V,B,b]),clearFilters:(0,Q.useCallback)(()=>{P.current=[],l([]),M.current=[],d([]),i&&V(i,1,[])},[i,V]),toggleSort:(0,Q.useCallback)(e=>{if(!i)return;let t=N.current,n=t?.column===e?t.direction===`asc`?{column:e,direction:`desc`}:null:{column:e,direction:`asc`};V(i,1,M.current,n)},[i,V]),nextPage:ce,prevPage:le}}var Pa=[`=`,`!=`,`<>`,`>`,`>=`,`<`,`<=`,`LIKE`,`NOT LIKE`,`CONTAINS`,`NOT CONTAINS`,`IN`,`NOT IN`,`BETWEEN`,`NOT BETWEEN`,`IS`,`IS NOT`];function Fa(e){if(e==null)return`Unavailable`;if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`,`TB`],n=e/1024,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n.toFixed(n>=10?1:2)} ${t[r]}`}var Ia=Object.freeze({sqlDefault:!0}),La=e=>e===Ia;function Ra(e,t){let n=t=>e===`mysql`?`\`${t.replace(/`/g,"``")}\``:`"${t.replace(/"/g,`""`)}"`;return t.base_name&&t.table_schema&&t.base_name!==t.table_name?`${n(t.table_schema)}.${n(t.base_name)}`:n(t.table_name)}function za(e){return e===null?`NULL`:e===void 0?``:typeof e==`object`?JSON.stringify(e):String(e)}function Ba(e){return e==null?``:typeof e==`object`?JSON.stringify(e):String(e)}function Va(e){if(Array.isArray(e))return e.map(String);let t=String(e||``).match(/^(?:enum|set)\((.*)\)$/i);return t?[...t[1].matchAll(/'((?:''|[^'])*)'/g)].map(e=>e[1].replace(/''/g,`'`)):[]}function Ha(e){let t=t=>e.get(t),n=e=>String(t(e)?.type||``).toLowerCase(),r=e=>String(t(e)?.full_type||t(e)?.enum_values||``).toLowerCase(),i=e=>/bool/.test(n(e))||/^tinyint\(1\)/.test(r(e)),a=e=>!i(e)&&/int|decimal|numeric|float|double|real|serial|money/.test(n(e)),o=e=>/date/.test(n(e))&&!/time/.test(n(e)),s=e=>/timestamp|datetime/.test(n(e)),c=e=>/text|json|xml/.test(n(e)),l=e=>Va(t(e)?.enum_values);return{columnType:n,isBooleanColumn:i,isNumericColumn:a,isDateColumn:o,isDateTimeColumn:s,isLongColumn:c,enumValues:l,isEnumColumn:e=>l(e).length>0,isInsertableColumn:e=>{let n=t(e),r=String(n?.extra||``).toLowerCase(),i=String(n?.column_default||``).toLowerCase();return!n?.is_generated&&!(n?.is_pk&&(r.includes(`auto_increment`)||i.includes(`nextval`)||i.includes(`autoincrement`)))},isReadOnlyColumn:(e,n=!1)=>{let r=t(e);return!!(r?.is_pk&&!n||r?.is_generated)}}}function Ua(e){return String(e||``).split(/[T ]/)[0]||``}function Wa(e){let t=String(e||``).match(/[T ](\d{2}:\d{2}(?::\d{2})?)/);return t?.[1].length===5?`${t[1]}:00`:t?.[1]||`00:00:00`}function Ga(e){let t=Ua(e);return t?`${t} ${Wa(e)}`:``}function Ka(e,t,n){return t===null?`NULL`:n.isDateTimeColumn(e)?Ga(t):n.isDateColumn(e)?Ua(t):za(t)}function qa(e,t,n){return n.isBooleanColumn(e)?t==null||t===``?``:t===!0||t===1||t===`1`?`1`:`0`:n.isDateTimeColumn(e)?Ga(t):n.isDateColumn(e)?Ua(t):Ba(t)}function Ja(e,t,n){if(n.isBooleanColumn(e))return t===``?null:Number(t);if(n.isDateTimeColumn(e))return String(t||``).replace(`T`,` `);if(n.isDateColumn(e))return Ua(t);if(n.isNumericColumn(e)&&t!==``)return/float|double|real|money/.test(n.columnType(e))?Number(t):String(t).trim();if(/json/.test(n.columnType(e))&&t!==``)try{return JSON.parse(t)}catch{}return t}function Ya(e){let[t]=String(e||``).split(/[T ]/),[n,r,i]=t.split(`-`).map(Number);if(n&&r&&i)return new Date(n,r-1,i)}function Xa(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}var Za=e=>`erd-db-column-widths:${e}`;function Qa(e,t=globalThis.localStorage){try{let n=JSON.parse(t?.getItem(Za(e))||`{}`);if(!n||typeof n!=`object`||Array.isArray(n))return{};let r={};for(let[e,t]of Object.entries(n))t&&typeof t==`object`&&(r[e]=Object.fromEntries(Object.entries(t).filter(([,e])=>typeof e==`number`&&Number.isFinite(e))));return r}catch{return{}}}function $a(e,t,n=globalThis.localStorage){try{n?.setItem(Za(e),JSON.stringify(t))}catch{}}function eo({activeTable:e,columnHelpers:t,primaryKeyColumns:n,updateRecords:r}){let[a,o]=(0,Q.useState)({}),s=Object.keys(a).length,c=(0,Q.useCallback)((e,r,i)=>{if(n.length===0||t.isReadOnlyColumn(r))return;let a=JSON.stringify(n.map(t=>e[t])),s=Object.fromEntries(n.map(t=>[t,e[t]])),c=`${a}:${r}`;i!==null&&i===qa(r,e[r],t)?o(e=>{if(!(c in e))return e;let{[c]:t,...n}=e;return n}):o(e=>({...e,[c]:{rowKey:a,column:r,key:s,value:i}}))},[t,n]),l=(0,Q.useCallback)(async()=>{if(!e||s===0)return;let n=new Map;Object.values(a).forEach(e=>{let r=n.get(e.rowKey)||{key:e.key,values:{},defaults:[]};La(e.value)?r.defaults.push(e.column):r.values[e.column]=e.value===null?null:Ja(e.column,e.value,t),n.set(e.rowKey,r)});try{await r(e,[...n.values()].map(({defaults:e,...t})=>e.length?{...t,defaults:e}:t)),o({}),i.success(`${s} cell${s===1?``:`s`} updated`)}catch(e){i.error(e.message||`Failed to update records`)}},[e,t,s,a,r]);return{clear:(0,Q.useCallback)(()=>o({}),[]),count:s,draftCell:c,drafts:a,save:l}}function to({activeTable:e,columnHelpers:t,createRecord:n,deleteRecord:r,primaryKeyColumns:a,records:o,updateRecord:s}){let[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)({}),[m,h]=(0,Q.useState)(null),[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)([]),S=(0,Q.useMemo)(()=>o?.columns?.filter(e=>t.isInsertableColumn(e))||[],[t,o]),C=(0,Q.useCallback)(e=>JSON.stringify(a.map(t=>e[t])),[a]),w=(0,Q.useMemo)(()=>new Set(b.map(C)),[C,b]),T=(0,Q.useMemo)(()=>g?S.some(e=>f[e]!==``):!u||!o?!1:o.columns.some(e=>(f[e]??``)!==qa(e,u[e],t)),[t,f,S,g,o,u]),E=(0,Q.useMemo)(()=>!u||!o?{}:Object.fromEntries(o.columns.filter(e=>(f[e]??``)!==qa(e,u[e],t)).map(e=>[e,Ja(e,f[e]??``,t)])),[t,f,o,u]),D=(0,Q.useCallback)(e=>{_(!1),d(e)},[]),O=(0,Q.useCallback)(()=>{p(!u||!o?{}:Object.fromEntries(o.columns.map(e=>[e,qa(e,u[e],t)])))},[t,o,u]),k=(0,Q.useCallback)(()=>{o&&(d(null),_(!0),p(Object.fromEntries(S.map(e=>[e,``]))),l(!0))},[S,o]),A=(0,Q.useCallback)(()=>{_(!1),p({}),l(!1)},[]),ee=(0,Q.useCallback)(async()=>{if(!e||!u||!o)return;let t=Object.fromEntries(a.map(e=>[e,u[e]]));if(a.length!==0&&Object.keys(E).length!==0){y(!0);try{await s(e,t,E),i.success(`Record updated`),d(null),p({}),l(!1)}catch(e){i.error(e.message||`Failed to update record`)}finally{y(!1)}}},[e,E,a,o,u,s]),j=(0,Q.useCallback)(async()=>{if(!e||!o)return;let r=Object.fromEntries(S.filter(e=>f[e]!==``).map(e=>[e,Ja(e,f[e],t)]));y(!0);try{await n(e,r),i.success(`Record created`),A()}catch(e){i.error(e.message||`Failed to create record`)}finally{y(!1)}},[e,A,t,n,f,S,o]),M=(0,Q.useCallback)(async t=>{if(!e||!u)return;let n=Object.fromEntries(a.map(e=>[e,u[e]]));y(!0);try{await r(e,n,t),i.success(`Record deleted`),d(null),l(!1)}catch(e){i.error(e.message||`Failed to delete record`)}finally{y(!1)}},[e,r,a,u]),N=(0,Q.useCallback)((e,t)=>{x(n=>t?[...n.filter(t=>C(t)!==C(e)),e]:n.filter(t=>C(t)!==C(e)))},[C]),P=(0,Q.useCallback)((e,t)=>{x(n=>{let r=new Set(e.map(C));return t?[...n.filter(e=>!r.has(C(e))),...e]:n.filter(e=>!r.has(C(e)))})},[C]),F=(0,Q.useCallback)(async t=>{if(!e||b.length===0)return;let n=b.map(e=>Object.fromEntries(a.map(t=>[t,e[t]])));y(!0);try{await r(e,n,t),i.success(`${b.length} record${b.length===1?``:`s`} deleted`),x([]),d(null),l(!1)}catch(e){i.error(e.message||`Failed to delete records`)}finally{y(!1)}},[e,r,a,b]),te=(0,Q.useCallback)(()=>x([]),[]),I=(0,Q.useCallback)(e=>{x(e)},[]),ne=(0,Q.useCallback)(()=>{d(null),_(!1),x([])},[]);return{datePickerOpenColumn:m,detailsOpen:c,draftRow:f,isCreatingRecord:g,isRecordDirty:T,isSavingRecord:v,selectedRow:u,selectedRowKeys:w,selectedRows:b,selectedRecordCount:b.length,addRecord:k,cancelCreateRecord:A,clearSelectedRows:te,removeRecord:M,removeSelectedRecords:F,resetRecordEditor:ne,selectRow:D,selectRows:I,setDatePickerOpenColumn:h,setDetailsOpen:l,setDraftRow:p,submitCreateRecord:j,submitRecord:ee,syncSelectedRowDraft:O,toggleSelectedRow:N,toggleSelectedRows:P}}var no=`__none__`,ro=`__custom__`;function io(e){return/^(char|varchar|character|character varying|text|tinytext|mediumtext|longtext)$/i.test(e.replace(/\(.*/,``).trim())}function ao(e){let t=e.trim().match(/^'((?:''|[^'])*)'(?:\s*::\s*(?:text|character(?: varying)?|varchar(?:\(\d+\))?))?$/i);return t?t[1].replace(/''/g,`'`):e}function oo(e,t){return!t||t.toUpperCase()===`NULL`||!io(e)?t:`'${t.replace(/'/g,`''`)}'`}function so(e,t,n=``){let r=e.toLowerCase().replace(/\(.*/,``).replace(/\b(unsigned|zerofill)\b/g,``).replace(/\s+/g,` `).trim(),i=[{value:no,label:`No default`}];t&&i.push({value:`NULL`,label:`NULL`}),/^(tinyint|smallint|mediumint|int|integer|bigint|int2|int4|int8|smallserial|serial|bigserial|decimal|numeric|real|float|double|double precision|money)$/.test(r)&&i.push({value:`0`,label:`0`},{value:`1`,label:`1`}),/^(bool|boolean)$/.test(r)&&i.push({value:`TRUE`,label:`TRUE`},{value:`FALSE`,label:`FALSE`}),r===`date`&&i.push({value:`CURRENT_DATE`,label:`CURRENT_DATE`}),/^(time\b|timetz$)/.test(r)&&i.push({value:`CURRENT_TIME`,label:`CURRENT_TIME`}),/^(timestamp\b|timestamptz$|datetime$)/.test(r)&&i.push({value:`CURRENT_TIMESTAMP`,label:`CURRENT_TIMESTAMP`}),io(e)&&i.push({value:ro,label:`Custom value…`});let a=n.trim();return a&&!io(e)&&!i.some(e=>e.value.toUpperCase()===a.toUpperCase())&&i.push({value:n,label:`${n} (current)`}),i}var co=`SMALLINT.INTEGER.BIGINT.SMALLSERIAL.SERIAL.BIGSERIAL.DECIMAL.NUMERIC.REAL.DOUBLE PRECISION.MONEY.BOOLEAN.CHAR.VARCHAR.TEXT.BYTEA.DATE.TIME.TIMETZ.TIMESTAMP.TIMESTAMPTZ.INTERVAL.UUID.JSON.JSONB.XML.BIT.BIT VARYING.CIDR.INET.MACADDR.MACADDR8.TSVECTOR.TSQUERY`.split(`.`),lo=`TINYINT.SMALLINT.MEDIUMINT.INT.BIGINT.DECIMAL.NUMERIC.FLOAT.DOUBLE.REAL.BIT.BOOLEAN.CHAR.VARCHAR.BINARY.VARBINARY.TINYTEXT.TEXT.MEDIUMTEXT.LONGTEXT.TINYBLOB.BLOB.MEDIUMBLOB.LONGBLOB.ENUM.SET.DATE.TIME.DATETIME.TIMESTAMP.YEAR.JSON.GEOMETRY.POINT.LINESTRING.POLYGON.MULTIPOINT.MULTILINESTRING.MULTIPOLYGON.GEOMETRYCOLLECTION`.split(`.`),uo={int:`INTEGER`,int2:`SMALLINT`,int4:`INTEGER`,int8:`BIGINT`,serial2:`SMALLSERIAL`,serial4:`SERIAL`,serial8:`BIGSERIAL`,bool:`BOOLEAN`,char:`CHAR`,"character varying":`VARCHAR`,character:`CHAR`,float4:`REAL`,float8:`DOUBLE PRECISION`,"time without time zone":`TIME`,"time with time zone":`TIMETZ`,"timestamp without time zone":`TIMESTAMP`,"timestamp with time zone":`TIMESTAMPTZ`},fo={integer:`INT`,bool:`BOOLEAN`,dec:`DECIMAL`,fixed:`DECIMAL`,"double precision":`DOUBLE`};function po(e,t){let n=t.trim(),r=n.replace(/\([^)]*\)/,``).replace(/\s+/g,` `).trim();if(e===`postgresql`){let e=r.toLowerCase();return uo[e]||co.find(t=>t.toLowerCase()===e)||n}if(e===`mysql`){let e=r.match(/\b(?:unsigned|zerofill)\b/gi)?.map(e=>e.toUpperCase())||[],t=r.replace(/\b(?:unsigned|zerofill)\b/gi,``).replace(/\s+/g,` `).trim().toLowerCase(),i=fo[t]||lo.find(e=>e.toLowerCase()===t);return i?[i,...e].join(` `):n}return r.toUpperCase()}var mo=e=>/^(var)?char$|^character varying$|^(var)?binary$/i.test(po(null,e)),ho=e=>/^(decimal|numeric)$/i.test(po(null,e)),go=(e,t)=>{let n=po(e,t);return e===`postgresql`?/^(TIME|TIMETZ|TIMESTAMP|TIMESTAMPTZ)$/.test(n):e===`mysql`&&/^(TIME|DATETIME|TIMESTAMP)$/.test(n)};function _o(e,t,n,r,i){let a=po(e,t);return mo(a)?`${a}(${n||255})`:ho(a)&&r?`${a}(${i?`${r},${i}`:r})`:go(e,a)&&r?`${a}(${r})`:a}var vo=e=>String(e?.full_type===`USER-DEFINED`?e?.type:e?.full_type||e?.type||``),yo=e=>{if(Array.isArray(e))return e.map(String);let t=String(e||``).match(/^(?:enum|set)\((.*)\)$/i);return t?[...t[1].matchAll(/'((?:''|[^'])*)'/g)].map(e=>e[1].replace(/''/g,`'`)):[]},bo=e=>e.match(/\((\d+)\)/)?.[1]||``,xo=e=>{let[,t=``,n=``]=e.match(/\((\d+)(?:\s*,\s*(\d+))?\)/)||[];return{precision:t,scale:n}},So=(e,t)=>po(e,t).toLowerCase().replace(/\([^)]*\)/g,``).replace(/[`"]/g,``).replace(/\s+/g,` `).replace(/^int4$/,`integer`).replace(/^int8$/,`bigint`).replace(/^int2$/,`smallint`).replace(/^serial$/,`integer`).replace(/^bigserial$/,`bigint`).replace(/^smallserial$/,`smallint`).replace(/^character varying/,`varchar`).trim(),Co=(e,t,n)=>So(e,t)===So(e,n);function wo(e,t,n,r){let[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(!1),u=(0,Q.useMemo)(()=>i?.kind===`column`&&e?.columns?.find(e=>e.name===i.columnName)||null,[e,i]),d=(0,Q.useMemo)(()=>u&&e?.foreign_keys?.find(e=>e.column===u.name)||null,[e,u]),f=(0,Q.useMemo)(()=>i?.kind===`index`&&e?.indexes?.find(e=>e.name===i.indexName)||null,[e,i]),p=(0,Q.useMemo)(()=>i?.kind===`check`&&e?.checks?.find(e=>e.name===i.checkName)||null,[e,i]);(0,Q.useEffect)(()=>{if(i?.kind===`addTable`){s({tableName:``,tableComment:``,columnName:`id`,columnType:`BIGINT`,characterLength:``,numericPrecision:``,numericScale:``,isNullable:!1,columnDefault:``,columnExtra:``,columnComment:``,enumValues:[],fkEnabled:!1,refTable:``,refColumn:``,fkConstraintName:``,fkOnDelete:`NO ACTION`,fkOnUpdate:`NO ACTION`,indexName:``,indexColumns:[],indexUnique:!1,indexAlgorithm:``,checkName:``,checkExpression:``});return}if(!e||!i){s(null);return}let t=i.kind===`column`?e.columns?.find(e=>e.name===i.columnName):null,n=t?e.foreign_keys?.find(e=>e.column===t.name):null,r=i.kind===`index`?e.indexes?.find(e=>e.name===i.indexName):null,a=i.kind===`check`?e.checks?.find(e=>e.name===i.checkName):null,o=xo(vo(t));s({tableName:e.table_name||``,tableComment:e.comment??``,columnName:t?.name||``,columnType:vo(t),characterLength:String(t?.max_length||bo(vo(t))||``),numericPrecision:String(t?.numeric_precision||o.precision||``),numericScale:String(t?.numeric_scale||o.scale||``),isNullable:!!t?.is_nullable,columnDefault:ao(t?.column_default??``),columnExtra:t?.extra??``,columnComment:t?.comment??``,enumValues:yo(t?.enum_values),fkEnabled:!!n,refTable:n?.ref_table||``,refColumn:n?.ref_column||``,fkConstraintName:n?.constraint_name||``,fkOnDelete:n?.on_delete||`NO ACTION`,fkOnUpdate:n?.on_update||`NO ACTION`,indexName:r?.name||``,indexColumns:String(r?.column_name||``).split(`,`).map(e=>e.trim()).filter(Boolean),indexUnique:!!r?.is_unique,indexAlgorithm:String(r?.algorithm||``).toLowerCase(),checkName:a?.name||``,checkExpression:a?.expression||``})},[e,i]);let m=(0,Q.useMemo)(()=>!i||!o?!1:i.kind===`addTable`?!!(o.tableName.trim()&&o.columnName.trim()&&o.columnType.trim()):e?o.tableName!==e.table_name||o.tableComment!==(e.comment??``)?!0:i.kind===`addColumn`?!!(o.columnName.trim()&&o.columnType.trim()):i.kind===`addIndex`?!!(o.indexName.trim()&&o.indexColumns.length>0):i.kind===`addCheck`?!!o.checkExpression.trim():i.kind===`index`&&f?o.indexName!==f.name||o.indexUnique!==!!f.is_unique||o.indexAlgorithm!==String(f.algorithm||``).toLowerCase()||o.indexColumns.join(`,`)!==String(f.column_name||``):i.kind===`check`&&p?o.checkName!==p.name||o.checkExpression!==p.expression:i.kind!==`column`||!u?!1:o.columnName!==u.name||_o(r,o.columnType,o.characterLength,o.numericPrecision,o.numericScale)!==_o(r,vo(u),String(u.max_length||bo(vo(u))||``),String(u.numeric_precision||xo(vo(u)).precision||``),String(u.numeric_scale||xo(vo(u)).scale||``))||o.isNullable!==!!u.is_nullable||o.columnDefault!==ao(u.column_default??``)||o.columnExtra!==(u.extra??``)||o.columnComment!==(u.comment??``)||o.enumValues.join(`\0`)!==yo(u.enum_values).join(`\0`)||o.fkEnabled!==!!d||o.refTable!==(d?.ref_table||``)||o.refColumn!==(d?.ref_column||``)||o.fkConstraintName!==(d?.constraint_name||``)||o.fkOnDelete!==(d?.on_delete||`NO ACTION`)||o.fkOnUpdate!==(d?.on_update||`NO ACTION`):!1,[e,d,r,o,p,u,f,i]),h=(0,Q.useMemo)(()=>(t.find(e=>e.table_name===o?.refTable)?.columns||[]).filter(e=>Co(r,o?.columnType||``,vo(e))),[r,o?.columnType,o?.refTable,t]),g=(0,Q.useCallback)(async()=>{if(i&&o&&m){l(!0);try{await n({createTable:i.kind===`addTable`?{name:o.tableName,comment:o.tableComment,column:{name:o.columnName,type:_o(r,o.columnType,o.characterLength,o.numericPrecision,o.numericScale),is_nullable:o.isNullable,column_default:oo(o.columnType,o.columnDefault),extra:o.columnExtra,comment:o.columnComment,enum_values:o.enumValues}}:void 0,tableName:o.tableName,tableComment:o.tableComment,columnName:i.kind===`column`?i.columnName:i.kind===`addColumn`?`__new__`:void 0,column:i.kind===`column`||i.kind===`addColumn`?{name:o.columnName,type:_o(r,o.columnType,o.characterLength,o.numericPrecision,o.numericScale),is_nullable:o.isNullable,column_default:oo(o.columnType,o.columnDefault),extra:o.columnExtra,comment:o.columnComment,enum_values:o.enumValues}:void 0,foreignKey:i.kind===`column`||i.kind===`addColumn`?{enabled:o.fkEnabled,ref_table:o.refTable,ref_column:o.refColumn,constraint_name:o.fkConstraintName,on_delete:o.fkOnDelete,on_update:o.fkOnUpdate}:void 0,indexName:i.kind===`index`?i.indexName:i.kind===`addIndex`?`__new__`:void 0,index:i.kind===`index`||i.kind===`addIndex`?{name:o.indexName,columns:o.indexColumns,is_unique:o.indexUnique,algorithm:o.indexAlgorithm}:void 0,checkName:i.kind===`check`?i.checkName:i.kind===`addCheck`?`__new__`:void 0,check:i.kind===`check`||i.kind===`addCheck`?{name:o.checkName,expression:o.checkExpression}:void 0}),i.kind===`addTable`&&a(null),(i.kind===`addColumn`||i.kind===`column`)&&a({kind:`column`,columnName:o.columnName}),(i.kind===`addIndex`||i.kind===`index`)&&a({kind:`index`,indexName:o.indexName}),(i.kind===`addCheck`||i.kind===`check`)&&a({kind:`check`,checkName:o.checkName})}finally{l(!1)}}},[r,o,m,i,n]);return{target:i,draft:o,isDirty:m,isSaving:c,selectedColumn:u,selectedIndex:f,selectedCheck:p,referenceColumns:h,setDraft:s,editTable:()=>a({kind:`table`}),editColumn:e=>a({kind:`column`,columnName:e}),addColumn:()=>a({kind:`addColumn`}),addTable:(0,Q.useCallback)(()=>a({kind:`addTable`}),[]),editIndex:e=>a({kind:`index`,indexName:e}),addIndex:()=>a({kind:`addIndex`}),editCheck:e=>a({kind:`check`,checkName:e}),addCheck:()=>a({kind:`addCheck`}),close:()=>a(null),save:g}}function To({expected:e,value:t,onChange:n}){return(0,$.jsxs)(`label`,{className:`block space-y-1.5 text-sm`,children:[(0,$.jsxs)(`span`,{children:[`Type `,(0,$.jsx)(`strong`,{className:`font-mono`,children:e}),` to confirm`]}),(0,$.jsx)(Z,{value:t,onChange:e=>n(e.target.value),autoComplete:`off`})]})}function Eo({action:e,onCancel:t,onDeleteRecords:n,onDeleteStructure:r,confirmationTarget:i,recordCount:a=0,tableName:o}){let[s,c]=(0,Q.useState)(``),l=`${a} record${a===1?``:`s`}`,u=`${l} selected in ${o||`this table`} will be permanently deleted.`;return(0,Q.useEffect)(()=>c(``),[e]),e===`records`&&i?(0,$.jsx)(rn,{open:!0,onOpenChange:e=>!e&&t(),children:(0,$.jsxs)(Yt,{size:`sm`,children:[(0,$.jsx)(Xt,{children:(0,$.jsx)(an,{children:`Delete Records`})}),(0,$.jsxs)(tn,{className:`space-y-3`,children:[(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:u}),(0,$.jsx)(To,{expected:i,value:s,onChange:c})]}),(0,$.jsxs)(nn,{children:[(0,$.jsx)(Zt,{onClick:t,children:`Cancel`}),(0,$.jsxs)($t,{className:`bg-destructive hover:bg-destructive/90`,disabled:s!==i,onClick:()=>n(s),children:[`Delete `,l]})]})]})}):(0,$.jsx)(ut,{isOpen:e!==null,title:e===`records`?`Delete Records`:e===`column`?`Delete Column`:e===`check`?`Delete Check`:`Delete Index`,message:e===`records`?u:e===`column`?`This column and its data will be permanently deleted.`:e===`check`?`This check constraint will be permanently deleted.`:`This index will be permanently deleted.`,confirmText:e===`records`?`Delete ${l}`:`Delete`,onCancel:t,onConfirm:e===`records`?n:r})}function Do({column:e,columnHelpers:t,datePickerOpenColumn:n,draftRow:r,fkOptionsByColumn:i,fkSearch:a=``,onFkSearch:o,foreignKeyByColumn:s,selectedRow:c,allowPrimaryKey:l=!1,setDatePickerOpenColumn:u,setDraftRow:d}){let f=`record-field-${e}`,{enumValues:p,isBooleanColumn:m,isDateColumn:h,isDateTimeColumn:g,isEnumColumn:_,isLongColumn:v,isNumericColumn:y,isReadOnlyColumn:b}=t;if(b(e,l))return(0,$.jsx)(Z,{id:f,value:String(r[e]??``),disabled:!0,className:`mt-1 h-8 font-mono text-xs`,placeholder:c?.[e]===null?`NULL`:``});if(_(e)){let t=p(e),n=String(r[e]??``);return(0,$.jsxs)(X,{value:n,onValueChange:t=>d(n=>({...n,[e]:t})),children:[(0,$.jsx)(st,{id:f,className:`mt-1 h-8 font-mono text-xs`,children:(0,$.jsx)(ct,{children:n})}),(0,$.jsx)(ot,{alignItemWithTrigger:!1,className:`max-h-64`,children:t.map(e=>(0,$.jsx)(at,{value:e,className:`text-xs`,children:e},e))})]})}let x=s.get(e);if(x){let n=i[e]||[],s=r[e]??``,c=new Set(n.map(e=>String(e[x.ref_column]))),l=s!==``&&!c.has(String(s))?[{[x.ref_column]:s},...n]:n;return(0,$.jsxs)($.Fragment,{children:[o&&(0,$.jsx)(Z,{type:`search`,value:a,onChange:e=>o(e.target.value),"aria-label":`Search ${x.ref_table} for ${e}`,placeholder:`Search ${x.ref_table}…`,className:`mt-1 h-7 text-xs`}),(0,$.jsxs)(X,{value:String(s),onValueChange:t=>d(n=>({...n,[e]:t})),children:[(0,$.jsx)(st,{id:f,className:`mt-1 h-8 font-mono text-xs`,children:(0,$.jsx)(ct,{children:String(s)})}),(0,$.jsx)(ot,{alignItemWithTrigger:!1,className:`max-h-64`,children:l.length===0?(0,$.jsx)(`div`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:a?`No matching parent records`:`No parent records`}):l.map(e=>{let n=String(e[x.ref_column]),r=Object.keys(e).find(t=>t!==x.ref_column&&e[t]!==null&&e[t]!==void 0),i=r?`${n} - ${Ka(r,e[r],t)}`:n;return(0,$.jsx)(at,{value:n,className:`text-xs`,children:i},n)})})]})]})}if(m(e))return(0,$.jsx)(Z,{id:f,type:`number`,min:0,max:1,step:1,value:r[e]??``,onChange:t=>d(n=>({...n,[e]:t.target.value})),className:`mt-1 h-8 font-mono text-xs`,placeholder:c?.[e]===null?`NULL`:`0 or 1`});if(v(e))return(0,$.jsx)(jn,{id:f,value:r[e]??``,onChange:t=>d(n=>({...n,[e]:t.target.value})),className:`mt-1 min-h-16 resize-y font-mono text-xs`,placeholder:c?.[e]===null?`NULL`:``});if(h(e)||g(e)){let t=String(r[e]??``),i=Ya(t);return(0,$.jsxs)(At,{className:`mt-1 gap-2 ${g(e)?`grid-cols-[minmax(0,1fr)_minmax(0,6.5rem)]`:``}`,children:[(0,$.jsx)(jt,{className:`min-w-0`,children:(0,$.jsxs)(_e,{open:n===e,onOpenChange:t=>u(t?e:null),children:[(0,$.jsx)(ge,{render:(0,$.jsxs)(W,{id:f,type:`button`,variant:`outline`,className:`h-8 w-full min-w-0 justify-between font-mono text-xs font-normal`,children:[(0,$.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2 truncate`,children:[(0,$.jsx)(Qe,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),i?Ze(i,`PPP`):`Select date`]}),(0,$.jsx)(Ee,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`})]})}),(0,$.jsx)(me,{align:`start`,className:`w-auto overflow-hidden p-0`,children:(0,$.jsx)(yt,{mode:`single`,selected:i,captionLayout:`dropdown`,defaultMonth:i,onSelect:t=>{if(!t)return;let n=Xa(t);d(t=>({...t,[e]:g(e)?`${n} ${Wa(t[e])}`:n})),u(null)},classNames:{month_caption:`flex justify-center px-2 pt-2`,caption_label:`pointer-events-none relative z-[1] inline-flex whitespace-nowrap text-sm font-medium leading-none`,dropdowns:`flex items-center gap-2`,dropdown_root:`relative flex h-8 min-w-24 flex-row items-center justify-center gap-2 rounded-md border bg-background px-3 text-sm font-medium shadow-sm [&>svg]:h-3.5 [&>svg]:w-3.5 [&>svg]:shrink-0 [&>svg]:text-muted-foreground`,dropdown:`absolute inset-0 z-10 h-full w-full cursor-pointer opacity-0`}})})]})}),g(e)&&(0,$.jsxs)(jt,{className:`min-w-0`,children:[(0,$.jsx)(Ot,{htmlFor:`${f}-time`,className:`sr-only`,children:`Time`}),(0,$.jsx)(Z,{id:`${f}-time`,type:`time`,step:`1`,value:Wa(t),onChange:t=>{let n=t.target.value.length===5?`${t.target.value}:00`:t.target.value;d(t=>({...t,[e]:`${Ua(t[e])||Xa(new Date)} ${n}`}))},className:`h-8 min-w-0 bg-background px-2 font-mono text-xs`})]})]})}return(0,$.jsx)(Z,{id:f,type:y(e)?`number`:`text`,value:String(r[e]??``),onChange:t=>d(n=>({...n,[e]:t.target.value})),className:`mt-1 h-8 font-mono text-xs`,placeholder:c?.[e]===null?`NULL`:``})}function Oo({activeTable:e,columnHelpers:t,datePickerOpenColumn:n,draftRow:r,fkOptionsByColumn:i,fkSearchByColumn:a,onFkSearch:o,foreignKeyByColumn:s,isRecordDirty:c,isCreatingRecord:l,isSavingRecord:u,primaryKeyColumns:d,records:f,selectedRow:p,setDatePickerOpenColumn:m,setDetailsOpen:h,setDraftRow:g,onCancelCreateRecord:_,onSubmitCreateRecord:v,onSubmitRecord:y,warnUnsaved:b,readOnlyReason:x=null}){let S=l?{}:p;return(0,$.jsx)(`aside`,{className:`w-80 shrink-0 border-l bg-background`,children:(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-3 border-b p-4`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`h3`,{className:`truncate text-sm font-medium`,children:l?`New Record`:p?`Record Details`:`Table Information`}),(0,$.jsx)(`p`,{className:`truncate text-xs text-muted-foreground`,children:e||`No table selected`})]}),(0,$.jsx)(W,{variant:`ghost`,size:`icon-xs`,onClick:()=>b()&&h(!1),title:`Close details`,children:(0,$.jsx)(It,{className:`h-3.5 w-3.5`})})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden`,children:(p||l)&&f?(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-2 overflow-y-auto p-3`,children:[f.columns.filter(e=>!l||t.isInsertableColumn(e)).map(e=>(0,$.jsxs)(`div`,{className:`rounded-md border px-3 py-2`,children:[(0,$.jsx)(`label`,{className:`truncate font-mono text-xs text-muted-foreground`,htmlFor:`record-field-${e}`,children:e}),(0,$.jsx)(Do,{column:e,columnHelpers:t,datePickerOpenColumn:n,draftRow:r,fkOptionsByColumn:i,fkSearch:a[e]??``,onFkSearch:t=>o(e,t),foreignKeyByColumn:s,selectedRow:S,allowPrimaryKey:l,setDatePickerOpenColumn:m,setDraftRow:g})]},e)),d.length===0&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This table has no primary key, so record editing is disabled.`}),x&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:x})]}),(0,$.jsxs)(`div`,{className:`sticky bottom-0 grid grid-cols-2 gap-2 border-t bg-background p-3`,children:[(0,$.jsx)(W,{variant:`outline`,onClick:()=>l?_():g(Object.fromEntries(f.columns.map(e=>[e,qa(e,p?.[e],t)]))),disabled:!l&&!c||u,children:`Cancel`}),(0,$.jsx)(W,{onClick:l?v:y,disabled:!!x||u||!c||!l&&d.length===0,children:`Submit`})]})]}):(0,$.jsx)(`div`,{className:`p-3`,children:(0,$.jsx)(`div`,{className:`divide-y rounded-md border`,children:[[`Data size`,Fa(f?.tableInfo?.dataSize)],[`Index size`,Fa(f?.tableInfo?.indexSize)],[`Total size`,Fa(f?.tableInfo?.totalSize)]].map(([e,t])=>(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3 px-3 py-2 text-sm`,children:[(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:e}),(0,$.jsx)(`span`,{className:`font-mono text-xs`,children:t})]},e))})})})]})})}function ko({columnOptions:e,filters:t,addFilter:n,applyFilter:r,applyFilters:i,clearFilters:a,removeFilter:o,setShowFilters:s,updateFilter:c,warnUnsaved:l}){return(0,$.jsx)(`div`,{className:`shrink-0 border-b bg-muted/10 px-3 py-2`,children:(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[t.map(i=>{let a=i.operator===`IS`||i.operator===`IS NOT`,s=i.operator===`BETWEEN`||i.operator===`NOT BETWEEN`;return(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,$.jsx)(or,{checked:i.enabled,onCheckedChange:e=>c(i.id,{enabled:e}),"aria-label":`Enable filter`}),(0,$.jsxs)(X,{value:i.column,onValueChange:e=>e&&c(i.id,{column:e}),children:[(0,$.jsx)(st,{className:`h-8 min-w-32 max-w-48 text-xs`,children:(0,$.jsx)(ct,{children:i.column||`Column`})}),(0,$.jsx)(ot,{children:e.map(e=>(0,$.jsx)(at,{value:e,className:`text-xs`,children:e},e))})]}),(0,$.jsxs)(X,{value:i.operator,onValueChange:e=>e&&c(i.id,{operator:e}),children:[(0,$.jsx)(st,{className:`h-8 w-36 text-xs`,children:(0,$.jsx)(ct,{children:i.operator})}),(0,$.jsx)(ot,{children:Pa.map(e=>(0,$.jsx)(at,{value:e,className:`text-xs`,children:e},e))})]}),(0,$.jsx)(Z,{value:a?`NULL`:i.value,disabled:a,onChange:e=>c(i.id,{value:e.target.value}),placeholder:i.operator.includes(`IN`)?`a, b, c`:`Value`,className:`h-8 min-w-28 flex-1 text-xs`}),s&&(0,$.jsx)(Z,{value:i.value2||``,onChange:e=>c(i.id,{value2:e.target.value}),placeholder:`And`,className:`h-8 min-w-28 flex-1 text-xs`}),(0,$.jsx)(W,{variant:`secondary`,size:`sm`,className:`h-8`,onClick:()=>l()&&r(i),children:`Apply`}),(0,$.jsx)(W,{variant:`outline`,size:`icon-xs`,disabled:t.length<=1,onClick:()=>o(i.id),title:`Remove filter`,children:(0,$.jsx)(Dt,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(W,{variant:`outline`,size:`icon-xs`,onClick:()=>n(i.column||e[0]||``),title:`Add filter`,children:(0,$.jsx)(he,{className:`h-3.5 w-3.5`})})]},i.id)}),(0,$.jsxs)(`div`,{className:`flex items-center justify-end gap-2 pt-1`,children:[(0,$.jsx)(W,{variant:`ghost`,size:`sm`,className:`h-8`,onClick:()=>{l()&&(a(),s(!1))},children:`Clear`}),(0,$.jsx)(W,{size:`sm`,className:`h-8`,onClick:()=>l()&&i(t),children:`Apply All`})]})]})})}function Ao({activeView:e,page:t,records:n,tableColumnCount:r,totalPages:i,warnUnsaved:a,onAddColumn:o,onAddIndex:s,onAddCheck:c,onInfo:l,onNextPage:u,onPrevPage:d,onViewChange:f}){return(0,$.jsxs)(`div`,{className:`grid grid-cols-[1fr_auto_1fr] items-center gap-2 px-4 py-2 border-t bg-muted/10 shrink-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1 justify-self-start`,children:[[`data`,`structure`].map(t=>(0,$.jsx)(W,{variant:e===t?`secondary`:`ghost`,size:`sm`,className:`h-7 px-3 capitalize`,onClick:()=>f(t),children:t},t)),e===`structure`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(W,{variant:`outline`,size:`sm`,className:`h-7 px-2`,onClick:o,children:[(0,$.jsx)(he,{className:`mr-1 h-3.5 w-3.5`}),`Column`]}),(0,$.jsxs)(W,{variant:`outline`,size:`sm`,className:`h-7 px-2`,onClick:s,children:[(0,$.jsx)(he,{className:`mr-1 h-3.5 w-3.5`}),`Index`]}),(0,$.jsxs)(W,{variant:`outline`,size:`sm`,className:`h-7 px-2`,onClick:c,children:[(0,$.jsx)(he,{className:`mr-1 h-3.5 w-3.5`}),`Check`]}),(0,$.jsx)(W,{variant:`ghost`,size:`icon-xs`,onClick:l,title:`Show table SQL`,children:(0,$.jsx)(lt,{className:`h-4 w-4`})})]})]}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground justify-self-center`,children:e===`structure`?`${r} columns`:n&&n.total>0?`${((t||1)-1)*(n.pageSize||50)+1}-${Math.min((t||1)*(n.pageSize||50),Number(n.total))} of ${n.total} rows`:`0 rows`}),e===`data`&&n&&(0,$.jsxs)(`div`,{className:`flex items-center gap-1 justify-self-end`,children:[(0,$.jsx)(W,{variant:`outline`,size:`icon-xs`,disabled:t<=1,onClick:()=>a()&&d(),children:(0,$.jsx)(it,{className:`h-4 w-4`})}),(0,$.jsx)(W,{variant:`outline`,size:`icon-xs`,disabled:t>=i,onClick:()=>a()&&u(),children:(0,$.jsx)(ue,{className:`h-4 w-4`})})]})]})}var jo=new WeakMap;function Mo(e,t){let n=e.closest(`[data-records-scroll]`);if(!n||typeof IntersectionObserver>`u`)return()=>{};let r=jo.get(n);if(!r){let e=new Map;r={observer:new IntersectionObserver(t=>{for(let n of t)e.get(n.target)?.(n)},{root:n,rootMargin:`160px 0px`}),listeners:e},jo.set(n,r)}return r.listeners.set(e,t),r.observer.observe(e),()=>{r.listeners.delete(e),r.observer.unobserve(e),r.listeners.size===0&&(r.observer.disconnect(),jo.delete(n))}}function No(){let e=(0,Q.useRef)(null),[t,n]=(0,Q.useState)({visible:!0,height:0});(0,Q.useLayoutEffect)(()=>{let t=e.current;if(t)return Mo(t,e=>{let r=e.boundingClientRect.height;r<=0||!e.isIntersecting&&t.contains(t.ownerDocument.activeElement)||n(t=>t.visible===e.isIntersecting&&(e.isIntersecting||t.height===r)?t:{visible:e.isIntersecting,height:r})})},[]);let r=(0,Q.useCallback)(()=>n(e=>e.visible?e:{...e,visible:!0}),[]);return{rowRef:e,...t,reveal:r}}var Po=e=>e===`mysql`,Fo=e=>e===`postgresql`,Io=(e,t)=>Po(e)?`\`${t.replace(/`/g,"``")}\``:`"${t.replace(/"/g,`""`)}"`,Lo=e=>e.replace(/[^A-Za-z0-9_.-]+/g,`_`),Ro=200,zo=20,Bo=(e,t)=>JSON.stringify(e,null,2).split(`
|
|
72
|
+
`).map(e=>t+e).join(`
|
|
73
|
+
`),Vo=e=>e===`tab`?`Tab`:e===`;`?`Semicolon (;)`:`Comma (,)`,Ho=e=>e===`,`?`Comma decimal (,)`:`Dot decimal (.)`;function Uo(e,t){return e==null?``:t===`,`&&typeof e==`number`&&!Number.isInteger(e)?String(e).replace(`.`,`,`):String(e)}function Wo(e,t,n){let r=Uo(e,n);return/["\n\r]/.test(r)||r.includes(t)?`"${r.replace(/"/g,`""`)}"`:r}function Go(e){return e==null?`NULL`:typeof e==`number`?String(e):typeof e==`boolean`?e?`TRUE`:`FALSE`:`'${String(e).replace(/'/g,`''`)}'`}async function Ko(e){let t=window.CompressionStream;if(!t)throw Error(`Gzip is not supported in this browser`);let n=e.stream().pipeThrough(new t(`gzip`));return new Response(n).blob()}function qo(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),URL.revokeObjectURL(n)}function Jo({connectionId:e,dbType:t,table:n,tables:r,exportTables:a,exportRows:o,exportSelectedRows:s,label:c=`Export`,mode:l=`menu`,buttonClassName:u=`h-8 px-2`,disabled:d=!1,readOnlyReason:f=null,onDeleteTables:p,onMutateTables:m}){let h=n.table_name,g=(0,Q.useMemo)(()=>(n.columns||[]).map(e=>String(e.name||``)).filter(Boolean),[n]),[_,v]=(0,Q.useState)(null),[y,b]=(0,Q.useState)(`csv`),[x,S]=(0,Q.useState)(g),[C,w]=(0,Q.useState)(`,`),[T,E]=(0,Q.useState)(`.`),[D,O]=(0,Q.useState)(!0),[k,A]=(0,Q.useState)(!0),[ee,j]=(0,Q.useState)(!1),[M,N]=(0,Q.useState)(`${h}_copy`),[P,F]=(0,Q.useState)(!1),[te,I]=(0,Q.useState)(!1),[ne,L]=(0,Q.useState)(!1),[re,R]=(0,Q.useState)(!1),[z,B]=(0,Q.useState)(``),[V,ie]=(0,Q.useState)(null),H=a?.length?a:[n],U=H.length===1,ae=!f&&(Po(t)||Fo(t)),oe=(0,Q.useRef)(null),[se,ce]=(0,Q.useState)(null),le=async(t,n,r)=>{let i=t.table_name;if(V){r((t.columns||[]).map(e=>String(e.name||``)).filter(Boolean),V);return}let a=1,o=0,s=0,c=0;for(;;){let t=await cn(`/api/catalogs/${e}/records`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({table:i,page:a,pageSize:Ro,withTotal:a===1}),signal:n});if(t.status===429&&c<zo){c+=1;let e=Math.min(Math.max(Number(t.headers.get(`Retry-After`))||10,1),60);ce(`${i}: ${o.toLocaleString()} of ${s.toLocaleString()} rows (rate limited, retrying in ${e}s)`),await new Promise((t,r)=>{let i=setTimeout(t,e*1e3);n.addEventListener(`abort`,()=>{clearTimeout(i),r(new DOMException(`Aborted`,`AbortError`))},{once:!0})});continue}let l=await t.json();if(!t.ok)throw Error(`${i}: ${l.error||`Failed to fetch records`} after ${o} rows`);a===1&&(s=Number(l.total||0));let u=l.rows||[];if(r((l.columns||[]).map(String),u),o+=u.length,ce(`${i}: ${o.toLocaleString()} of ${s.toLocaleString()} rows`),u.length<Ro||o>=s)return;a+=1}},ue=async(n,r,i)=>{let a=n.table_name,o=U?x:(n.columns||[]).map(e=>String(e.name||``)).filter(Boolean),s=C===`tab`?` `:C;if(y===`sql`&&D){let t=await cn(`/api/catalogs/${e}/structure/sql`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({table:a}),signal:r}),n=await t.json();if(!t.ok)throw Error(n.error||`Failed to fetch table SQL`);i.push(n.sql,`
|
|
74
|
+
`)}if(y===`sql`&&!k)return;let c=!1,l=0;if(await le(n,r,(e,r)=>{let a=o.length?o:e;y===`csv`&&!c&&(i.push(a.join(s)),c=!0);for(let e of r)y===`json`?i.push(l?`,
|
|
75
|
+
`:`
|
|
76
|
+
`,Bo(Object.fromEntries(a.map(t=>[t,e[t]])),U?` `:` `)):y===`csv`?i.push(`
|
|
77
|
+
`,a.map(t=>Wo(e[t],s,T)).join(s)):i.push(`INSERT INTO ${Ra(t,n)} (${a.map(e=>Io(t,e)).join(`, `)}) VALUES (${a.map(t=>Go(e[t])).join(`, `)});`,`
|
|
78
|
+
`),l+=1}),y===`csv`&&!c&&i.push(o.join(s)),y===`json`)return l},de=e=>{ie(e??o??null),S(g),v(`export`)},fe=async()=>{let e=new AbortController;oe.current=e;try{R(!0),ce(`Starting export…`);let t=[],n=y===`json`&&!U;n&&t.push(`{`);for(let[r,i]of H.entries())if(y===`json`){n&&t.push(r?`,
|
|
79
|
+
`:`
|
|
80
|
+
`,JSON.stringify(i.table_name),`: `),t.push(`[`);let a=await ue(i,e.signal,t);t.push(a?`\n${n?` `:``}]`:`]`)}else r&&t.push(`
|
|
81
|
+
|
|
82
|
+
`),await ue(i,e.signal,t);n&&t.push(H.length?`
|
|
83
|
+
}`:`}`);let r=y===`sql`?`sql`:y,a=new Blob(t,{type:y===`json`?`application/json;charset=utf-8`:`text/plain;charset=utf-8`});y===`sql`&&ee&&(a=await Ko(a));let o=n?`selected_tables.json`:`${Lo(U?h:`selected_tables`)}.${r}${y===`sql`&&ee?`.gz`:``}`;qo(a,o),i.success(`Export saved to your browser Downloads folder: ${o}`),v(null)}catch(e){e?.name===`AbortError`?i.info(`Export cancelled; no file was saved.`):i.error(`${e.message||`Export failed`}; no file was saved.`)}finally{oe.current===e&&(oe.current=null),ce(null),R(!1)}},pe=()=>{oe.current?oe.current.abort():v(null)},me=e=>(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`rounded-md border bg-muted/30 px-3 py-2 text-xs`,children:[(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`Table: `}),(0,$.jsx)(`span`,{className:`font-mono font-medium`,children:h})]}),Po(t)&&(0,$.jsxs)(`label`,{className:`flex items-start gap-3 text-sm`,children:[(0,$.jsx)(or,{className:`mt-0.5`,checked:te,onCheckedChange:e=>{I(e),e&&L(!1)}}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`block font-medium`,children:`Disable foreign key checks`}),(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[`Use only when related tables block this `,e,`.`]})]})]}),Fo(t)&&(0,$.jsxs)(`label`,{className:`flex items-start gap-3 text-sm`,children:[(0,$.jsx)(or,{className:`mt-0.5`,checked:ne,onCheckedChange:e=>L(e)}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`block font-medium`,children:`Cascade dependent tables`}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Include tables connected by foreign keys.`})]})]})]}),he=async()=>{let e=M.trim();if(!e||r.some(t=>t.table_name===e))return i.error(`Table name already exists`);try{R(!0),await m({cloneTable:{source:h,target:e,withData:P}}),i.success(`Table cloned`),v(null)}catch(e){i.error(e.message||`Clone failed`)}finally{R(!1)}},ge=async e=>{try{R(!0);let n={ignoreForeignKeys:Po(t)?te:!1,cascade:Fo(t)?ne:!1,confirmation:z};e===`delete`?await p([h],n):await m({truncateTables:[h],...n}),i.success(e===`delete`?`Table deleted`:`Table truncated`),v(null)}catch(t){i.error(t.message||`${e} failed`)}finally{R(!1)}},_e=l===`button`?(0,$.jsxs)(W,{type:`button`,variant:`outline`,size:`sm`,className:u,disabled:d||H.length===0,onClick:e=>{e.stopPropagation(),de()},children:[(0,$.jsx)(Oe,{className:`mr-1 h-3.5 w-3.5`}),c]}):l===`dropdown`?(0,$.jsxs)(Ce,{children:[(0,$.jsxs)(ye,{render:(0,$.jsx)(W,{type:`button`,variant:`outline`,size:`sm`,className:u,disabled:d||H.length===0}),children:[(0,$.jsx)(Oe,{className:`mr-1 h-3.5 w-3.5`}),c]}),(0,$.jsxs)(xe,{align:`end`,className:`w-40`,children:[(0,$.jsx)(G,{onClick:()=>de(),children:`Export All`}),(0,$.jsx)(G,{disabled:!s?.length,onClick:()=>de(s),children:`Export Selected`})]})]}):l===`context-item`?(0,$.jsxs)(Fe,{onClick:()=>de(),children:[(0,$.jsx)(Oe,{className:`h-3.5 w-3.5`}),`Export`]}):(0,$.jsx)(`span`,{onClick:e=>e.stopPropagation(),children:(0,$.jsxs)(Ce,{children:[(0,$.jsx)(ye,{render:(0,$.jsx)(W,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`h-6 w-6 opacity-70 hover:opacity-100`}),children:(0,$.jsx)(Et,{className:`h-3.5 w-3.5`})}),(0,$.jsxs)(xe,{align:`end`,className:`w-36`,children:[(0,$.jsxs)(G,{onClick:()=>de(),children:[(0,$.jsx)(Oe,{className:`h-3.5 w-3.5`}),`Export`]}),(0,$.jsxs)(G,{disabled:!ae,title:f??void 0,onClick:()=>{N(`${h}_copy`),v(`clone`)},children:[(0,$.jsx)(hr,{className:`h-3.5 w-3.5`}),`Clone`]}),(0,$.jsxs)(G,{disabled:!ae,title:f??void 0,onClick:()=>v(`truncate`),children:[(0,$.jsx)(bt,{className:`h-3.5 w-3.5`}),`Truncate`]}),(0,$.jsx)(Se,{}),(0,$.jsxs)(G,{disabled:!ae,title:f??void 0,variant:`destructive`,onClick:()=>v(`delete`),children:[(0,$.jsx)(qt,{className:`h-3.5 w-3.5`}),`Delete`]})]})]})});return(0,$.jsxs)($.Fragment,{children:[_e,(0,$.jsx)(Wt,{open:_===`export`,onOpenChange:e=>{e||(oe.current?.abort(),v(null))},children:(0,$.jsxs)(zt,{size:`lg`,children:[(0,$.jsx)(Ut,{children:(0,$.jsx)(Bt,{children:U?`Export ${h}`:`Export ${H.length} tables`})}),(0,$.jsxs)(Vt,{className:`space-y-4`,children:[(0,$.jsx)(`div`,{className:`rounded-md border bg-muted/30 px-3 py-2 text-xs text-muted-foreground`,children:`File will be saved by the browser, usually in Downloads.`}),(0,$.jsx)(mr,{children:[`csv`,`json`,`sql`].map(e=>(0,$.jsx)(W,{type:`button`,variant:y===e?`default`:`outline`,size:`sm`,className:`h-7 px-3 text-xs uppercase`,onClick:()=>b(e),children:e},e))}),U&&(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Select the columns to include. `,x.length,` of `,g.length,` columns selected.`]}),(0,$.jsx)(`div`,{className:`grid max-h-36 grid-cols-2 gap-2 overflow-y-auto rounded-md border p-2`,children:g.map(e=>(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,$.jsx)(or,{checked:x.includes(e),onCheckedChange:t=>S(n=>t?[...n,e]:n.filter(t=>t!==e))}),e]},e))})]}),y===`csv`&&(0,$.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,$.jsxs)(`label`,{className:`space-y-1.5 text-xs font-medium`,children:[`Field delimiter`,(0,$.jsxs)(X,{value:C,onValueChange:e=>w(e||`,`),children:[(0,$.jsx)(st,{children:(0,$.jsx)(ct,{children:Vo(C)})}),(0,$.jsxs)(ot,{children:[(0,$.jsx)(at,{value:`,`,children:`Comma (,)`}),(0,$.jsx)(at,{value:`;`,children:`Semicolon (;)`}),(0,$.jsx)(at,{value:`tab`,children:`Tab`})]})]})]}),(0,$.jsxs)(`label`,{className:`space-y-1.5 text-xs font-medium`,children:[`Decimal format`,(0,$.jsxs)(X,{value:T,onValueChange:e=>E(e||`.`),children:[(0,$.jsx)(st,{children:(0,$.jsx)(ct,{children:Ho(T)})}),(0,$.jsxs)(ot,{children:[(0,$.jsx)(at,{value:`.`,children:`Dot decimal (.)`}),(0,$.jsx)(at,{value:`,`,children:`Comma decimal (,)`})]})]})]})]}),y===`sql`&&(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,$.jsx)(or,{checked:D,onCheckedChange:e=>O(e)}),`Include table structure`]}),(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,$.jsx)(or,{checked:k,onCheckedChange:e=>A(e)}),`Include table contents`]}),(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,$.jsx)(or,{checked:ee,onCheckedChange:e=>j(e)}),`Compress Gzip`]})]})]}),(0,$.jsxs)(Ht,{children:[se&&(0,$.jsx)(`span`,{role:`status`,"aria-live":`polite`,className:`mr-auto self-center text-xs text-muted-foreground`,children:se}),(0,$.jsx)(W,{variant:`outline`,onClick:pe,children:re?`Stop export`:`Cancel`}),(0,$.jsx)(W,{onClick:fe,disabled:re||U&&x.length===0,children:re?`Exporting…`:`Export`})]})]})}),(0,$.jsx)(Wt,{open:_===`clone`,onOpenChange:e=>!e&&v(null),children:(0,$.jsxs)(zt,{size:`sm`,children:[(0,$.jsx)(Ut,{children:(0,$.jsx)(Bt,{children:`Clone table`})}),(0,$.jsxs)(Vt,{className:`space-y-3`,children:[(0,$.jsx)(Z,{value:M,onChange:e=>N(e.target.value)}),(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,$.jsx)(or,{checked:P,onCheckedChange:e=>F(e)}),`Copy records`]})]}),(0,$.jsxs)(Ht,{children:[(0,$.jsx)(W,{variant:`outline`,onClick:()=>v(null),children:`Cancel`}),(0,$.jsx)(W,{onClick:he,disabled:re,children:`Clone`})]})]})}),[`truncate`,`delete`].map(e=>(0,$.jsx)(rn,{open:_===e,onOpenChange:e=>!e&&v(null),children:(0,$.jsxs)(Yt,{size:`sm`,children:[(0,$.jsx)(Xt,{children:(0,$.jsx)(an,{children:e===`delete`?`Delete table`:`Truncate table`})}),(0,$.jsxs)(tn,{className:`space-y-3`,children:[me(e),(0,$.jsx)(To,{expected:h,value:z,onChange:B})]}),(0,$.jsxs)(nn,{children:[(0,$.jsx)(Zt,{children:`Cancel`}),(0,$.jsx)($t,{className:`bg-destructive hover:bg-destructive/90`,disabled:re||z!==h,onClick:()=>ge(e),children:e===`delete`?`Delete`:`Truncate`})]})]})},e))]})}function Yo(e,t,n,r=0,i=200){if(n<=0)return{start:0,end:Math.min(12,e.length)};let a=Math.max(0,t-r-i),o=Math.max(a+1,t+n-r+i),s=0,c=0,l=0;for(;s<e.length&&l+e[s]<=a;)l+=e[s++];for(c=s;c<e.length&&l<o;)l+=e[c++];return{start:s,end:c}}function Xo(e,t,n){let r=Math.min(e.start,t.length),i=Math.min(e.end,t.length);for(let e of n){let n=e===null?-1:t.indexOf(e);n<0||(r=Math.min(r,n),i=Math.max(i,n+1))}return{start:r,end:i}}var Zo=e=>{let t=za(e);return/[",\n\r]/.test(t)?`"${t.replace(/"/g,`""`)}"`:t},Qo=e=>e===null?`NULL`:typeof e==`number`?String(e):`'${String(e).replace(/'/g,`''`)}'`,$o=(e,t)=>t.map(t=>e[t]),es=`absolute right-1 top-1/2 size-6 -translate-y-1/2 bg-background/90`,ts=(0,Q.memo)(function({activeTable:e,connectionId:t,dbType:n,columns:r,columnWindow:a,measureColumn:o,columnHelpers:s,foreignKeyByColumn:c,pageRows:l,row:u,rowKeyValue:d,tableSchema:f,canSelectRows:p,isActive:m,isSelected:h,recordDrafts:g,handleSelectRow:_,onEditRecord:v,onDeleteTables:y,onMutateTables:b,openRelatedRecord:x,onDraftCell:S,onToggleSelectedRow:C,warnUnsaved:w,readOnly:T=!1}){let[E,D]=(0,Q.useState)(null),[O,k]=(0,Q.useState)(null),[A,ee]=(0,Q.useState)(!1),j=No(),M=j.visible||m||E!==null||O!==null||A||o!==null,N=Xo(a,r,[E,O,o]),P=async(e,t=`Copied`)=>{await navigator.clipboard.writeText(e),i.success(t)},F=(t,i)=>{if(t.length===0)return;let a=i===`json`?JSON.stringify(t,null,2):i===`html`?`<table><thead><tr>${r.map(e=>`<th>${e}</th>`).join(``)}</tr></thead><tbody>${t.map(e=>`<tr>${r.map(t=>`<td>${za(e[t])}</td>`).join(``)}</tr>`).join(``)}</tbody></table>`:i===`markdown`?`| ${r.join(` | `)} |\n| ${r.map(()=>`---`).join(` | `)} |\n${t.map(e=>`| ${r.map(t=>za(e[t])).join(` | `)} |`).join(`
|
|
84
|
+
`)}`:i===`csv`?t.map(e=>$o(e,r).map(Zo).join(`,`)).join(`
|
|
85
|
+
`):i===`csv-header`?[r.join(`,`),...t.map(e=>$o(e,r).map(Zo).join(`,`))].join(`
|
|
86
|
+
`):i===`insert`?t.map(t=>`INSERT INTO ${Ra(n,f||{table_name:e})} (${r.map(e=>`"${e}"`).join(`, `)}) VALUES (${$o(t,r).map(Qo).join(`, `)});`).join(`
|
|
87
|
+
`):t.map(e=>$o(e,r).map(za).join(` `)).join(`
|
|
88
|
+
`);P(a)};return(0,$.jsxs)(ke,{onOpenChange:ee,children:[(0,$.jsx)(Ae,{render:(0,$.jsxs)(ir,{ref:j.rowRef,style:M?void 0:{height:j.height},tabIndex:!M&&!p?0:void 0,"aria-label":!M&&!p?`Show record`:void 0,onFocusCapture:j.reveal,className:`cursor-pointer transition-none hover:bg-muted/50 ${m?`bg-muted/70`:h?`bg-primary/10`:``}`,onMouseDown:e=>{(e.shiftKey||e.metaKey||e.ctrlKey)&&e.preventDefault()},onClick:e=>_(u,e),children:[p&&(0,$.jsx)(cr,{className:`w-10 px-3`,onClick:e=>e.stopPropagation(),children:(0,$.jsx)(or,{checked:h,onClick:e=>C(u,!h,e)})}),M?(0,$.jsxs)($.Fragment,{children:[N.start>0&&(0,$.jsx)(cr,{"aria-hidden":`true`,colSpan:N.start,className:`p-0`}),r.slice(N.start,N.end).map((e,t)=>{let n=u[e],r=g[`${d}:${e}`],i=r?r.value:n,a=c.get(e),o=E===e,f=p&&!T&&!s.isReadOnlyColumn(e);return(0,$.jsx)(cr,{"data-column":e,"aria-colindex":N.start+t+(p?2:1),className:`group relative overflow-hidden text-sm font-mono ${o?`p-0.5`:``} ${r?`bg-primary/10 ring-1 ring-inset ring-primary/30`:``}`,onDoubleClick:t=>{t.stopPropagation(),f&&(S(u,e,r?r.value:qa(e,n,s)),D(e))},children:(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center ${o?``:`gap-2`}`,children:[o?(0,$.jsx)(`input`,{autoFocus:!0,value:r?La(r.value)?``:r.value??``:qa(e,n,s),onChange:t=>S(u,e,t.target.value),onClick:e=>e.stopPropagation(),onBlur:()=>D(null),onKeyDown:e=>{e.key===`Escape`&&D(null),e.key===`Enter`&&D(null)},className:`h-7 min-w-0 flex-1 rounded border border-primary/50 bg-background px-1.5 font-mono text-sm outline-none`}):(0,$.jsx)(`span`,{"data-fit":!0,className:`min-w-0 flex-1 truncate`,children:i===null?(0,$.jsx)(`span`,{className:`text-muted-foreground/40 italic`,children:`NULL`}):La(i)?(0,$.jsx)(`span`,{className:`italic text-primary/70`,children:`DEFAULT`}):typeof i==`object`?(0,$.jsx)(`span`,{className:`text-xs`,children:JSON.stringify(i)}):Ka(e,i,s)}),!o&&a&&n!=null&&(0,$.jsx)(W,{variant:`ghost`,size:`icon-xs`,className:`size-6 shrink-0 opacity-60 hover:opacity-100`,onClick:e=>{e.stopPropagation(),w()&&x(a.ref_table,a.ref_column,n)},title:`Open ${a.ref_table}.${a.ref_column} = ${String(n)}`,children:(0,$.jsx)(Be,{className:`h-3.5 w-3.5`})}),!o&&(O===e?(0,$.jsxs)(Ce,{open:!0,onOpenChange:e=>{e||k(null)},children:[(0,$.jsx)(ye,{render:(0,$.jsx)(W,{type:`button`,variant:`ghost`,size:`icon-xs`,className:es,"aria-label":`Actions for ${e}`,onClick:e=>e.stopPropagation()}),children:(0,$.jsx)(Et,{className:`h-3.5 w-3.5`})}),(0,$.jsxs)(xe,{align:`end`,className:`w-56`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(be,{children:[(0,$.jsx)(ve,{disabled:!f,children:`Set Value`}),(0,$.jsxs)(we,{className:`w-44`,children:[(0,$.jsx)(G,{onClick:()=>S(u,e,``),children:`EMPTY`}),(0,$.jsx)(G,{onClick:()=>S(u,e,null),children:`NULL`}),(0,$.jsx)(G,{onClick:()=>S(u,e,Ia),children:`DEFAULT`})]})]}),(0,$.jsx)(Se,{}),(0,$.jsx)(G,{onClick:()=>P(za(u[e]),`Cell copied`),children:`Copy Cell Value`}),(0,$.jsx)(G,{onClick:()=>P(l.map(t=>za(t[e])).join(`
|
|
89
|
+
`),`Column copied`),children:`Copy Column`}),(0,$.jsx)(Se,{}),(0,$.jsx)(G,{onClick:()=>F([u],`plain`),children:`Copy`}),(0,$.jsxs)(be,{children:[(0,$.jsx)(ve,{children:`Copy Row As`}),(0,$.jsxs)(we,{className:`w-44`,children:[(0,$.jsx)(G,{onClick:()=>F([u],`plain`),children:`Plain Text`}),(0,$.jsx)(Se,{}),(0,$.jsx)(G,{onClick:()=>F([u],`json`),children:`JSON`}),(0,$.jsx)(G,{onClick:()=>F([u],`html`),children:`HTML`}),(0,$.jsx)(Se,{}),(0,$.jsx)(G,{onClick:()=>F([u],`markdown`),children:`Markdown Table`}),(0,$.jsx)(Se,{}),(0,$.jsx)(G,{onClick:()=>F([u],`csv`),children:`CSV`}),(0,$.jsx)(G,{onClick:()=>F([u],`csv-header`),children:`CSV with Header`}),(0,$.jsx)(Se,{}),(0,$.jsx)(G,{onClick:()=>F([u],`insert`),children:`INSERT Statement`})]})]})]})]}):m?(0,$.jsx)(W,{type:`button`,variant:`ghost`,size:`icon-xs`,className:`${es} opacity-0 group-hover:opacity-100 focus-visible:opacity-100`,"aria-label":`Actions for ${e}`,onClick:t=>{t.stopPropagation(),k(e)},children:(0,$.jsx)(Et,{className:`h-3.5 w-3.5`})}):null)]})},e)}),N.end<r.length&&(0,$.jsx)(cr,{"aria-hidden":`true`,colSpan:r.length-N.end,className:`p-0`})]}):(0,$.jsx)(cr,{"aria-hidden":`true`,colSpan:r.length,className:`p-0`})]},d)}),(0,$.jsxs)(q,{className:`min-w-36`,children:[(0,$.jsxs)(Fe,{onClick:()=>v(u),children:[(0,$.jsx)(tt,{className:`h-3.5 w-3.5`}),`Edit`]}),(0,$.jsx)(De,{}),(0,$.jsx)(Jo,{connectionId:t,dbType:n,table:f||{table_name:e,columns:r.map(e=>({name:e}))},tables:[f].filter(Boolean),exportRows:[u],mode:`context-item`,onDeleteTables:y,onMutateTables:b})]})]})},(e,t)=>e.activeTable!==t.activeTable||e.connectionId!==t.connectionId||e.dbType!==t.dbType||e.columns!==t.columns||e.columnWindow!==t.columnWindow||e.measureColumn!==t.measureColumn||e.columnHelpers!==t.columnHelpers||e.foreignKeyByColumn!==t.foreignKeyByColumn||e.pageRows!==t.pageRows||e.row!==t.row||e.rowKeyValue!==t.rowKeyValue||e.tableSchema!==t.tableSchema||e.canSelectRows!==t.canSelectRows||e.readOnly!==t.readOnly||e.isActive!==t.isActive||e.isSelected!==t.isSelected||e.handleSelectRow!==t.handleSelectRow||e.onEditRecord!==t.onEditRecord||e.onDeleteTables!==t.onDeleteTables||e.onMutateTables!==t.onMutateTables||e.openRelatedRecord!==t.openRelatedRecord||e.onDraftCell!==t.onDraftCell||e.onToggleSelectedRow!==t.onToggleSelectedRow||e.warnUnsaved!==t.warnUnsaved?!1:e.recordDrafts===t.recordDrafts||e.columns.every(n=>Object.is(e.recordDrafts[`${e.rowKeyValue}:${n}`]?.value,t.recordDrafts[`${t.rowKeyValue}:${n}`]?.value)));function ns(e,t){let[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)({start:0,end:0}),o=(0,Q.useRef)(i);return(0,Q.useLayoutEffect)(()=>{if(!n)return;let r=null,i=(r=!1)=>{let i=Math.min(400,Math.max(200,n.clientWidth/2)),s=Yo(e,n.scrollLeft,n.clientWidth,t,i/2);if(!r&&s.start>=o.current.start&&s.end<=o.current.end)return;let c=Yo(e,n.scrollLeft,n.clientWidth,t,i);(c.start!==o.current.start||c.end!==o.current.end)&&(o.current=c,a(c))},s=()=>{r===null&&(r=requestAnimationFrame(()=>{r=null,i()}))};i(!0),n.addEventListener(`scroll`,s,{passive:!0});let c=new ResizeObserver(()=>i(!0));return c.observe(n),()=>{n.removeEventListener(`scroll`,s),c.disconnect(),r!==null&&cancelAnimationFrame(r)}},[e,t,n]),{scrollRef:r,columnWindow:i}}var rs=50,is=32,as=1e3,os=e=>Math.max(is,Math.round(e)),ss={},cs=[];function ls(e,t){if(!e)return rs;let n=is,r=document.createRange();return e.querySelectorAll(`[data-column="${CSS.escape(t)}"]`).forEach(e=>{let t=e.querySelector(`[data-fit]`);t&&(r.selectNodeContents(t),n=Math.max(n,Math.ceil(r.getBoundingClientRect().width)+e.clientWidth-t.clientWidth))}),Math.min(as,os(n+1))}function us({active:e}){return(0,$.jsx)(`div`,{className:`h-0.5 overflow-hidden bg-transparent`,children:e&&(0,$.jsx)(`div`,{className:`h-full w-full animate-pulse bg-primary`})})}var ds=(0,Q.memo)(function({activeTable:e,connectionId:t,dbType:n,columnHelpers:r,error:i,foreignKeyByColumn:a,isLoadingRecords:o,records:s,tableSchema:c,primaryKeyColumns:l,selectedRow:u,selectedRowKeys:d,sort:f,recordDrafts:p,handleSelectRow:m,onEditRecord:h,onDeleteTables:g,onMutateTables:_,openRelatedRecord:v,onAddRecord:y,onDraftCell:b,onDeleteSelectedRecords:x,onTogglePageRows:S,onToggleSelectedRow:C,toggleSort:w,warnUnsaved:T,readOnlyReason:E=null,hasActiveFilters:D=!1,headerAction:O,children:k}){let A=l.length>0,ee=e=>JSON.stringify(l.map(t=>e[t])),j=s?.rows||[],M=s?.columns||cs,N=A&&j.length>0&&j.every(e=>d.has(ee(e))),P=(0,Q.useRef)(null),[F,te]=(0,Q.useState)(()=>({connectionId:t,widthsByTable:Qa(t)}));F.connectionId!==t&&te({connectionId:t,widthsByTable:Qa(t)});let I=F.widthsByTable[e]||ss,ne=e=>os(I[e]??rs),{scrollRef:L,columnWindow:re}=ns((0,Q.useMemo)(()=>M.map(e=>os(I[e]??rs)),[M,I]),A?40:0),[R,z]=(0,Q.useState)(null),B=R?.table===e&&R.connectionId===t?R.column:null,V=(t,n)=>te(r=>{let i={...r.widthsByTable,[e]:{...r.widthsByTable[e],[t]:os(n)}};return $a(r.connectionId,i),{...r,widthsByTable:i}});(0,Q.useLayoutEffect)(()=>{R&&(B&&V(B,ls(P.current,B)),z(null))},[R,B]);let ie=n=>z({column:n,table:e,connectionId:t}),H=(e,t)=>{e.preventDefault(),e.stopPropagation();let n=e.currentTarget,r=e.clientX,i=ne(t);n.setPointerCapture(e.pointerId);let a=e=>V(t,i+e.clientX-r),o=()=>{n.removeEventListener(`pointermove`,a),n.removeEventListener(`pointerup`,o),n.removeEventListener(`pointercancel`,o)};n.addEventListener(`pointermove`,a),n.addEventListener(`pointerup`,o),n.addEventListener(`pointercancel`,o)},U=M.reduce((e,t)=>e+ne(t),A?40:0);return(0,$.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-hidden flex flex-col`,"data-db-client-records":!0,children:[k,i?(0,$.jsx)(`div`,{className:`flex-1 flex items-center justify-center text-sm`,children:(0,$.jsx)(`div`,{className:`flex flex-col items-center gap-3 max-w-xs text-center`,children:i.includes(`Catalog not found`)?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Tt,{className:`w-8 h-8 text-muted-foreground/40`}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`font-medium text-foreground mb-1`,children:`Connection was removed`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This diagram is no longer connected to the database. The ERD data is still saved.`})]}),(0,$.jsx)(W,{variant:`outline`,size:`sm`,className:`mt-1`,onClick:()=>window.history.replaceState(null,``,`?tab=erd`),children:`Switch to ERD`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(We,{className:`w-5 h-5 text-destructive`}),(0,$.jsx)(`span`,{className:`text-destructive`,children:i})]})})}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`sticky top-0 z-20 px-4 py-2 border-b bg-background flex flex-wrap items-center justify-between gap-2 shrink-0`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,$.jsx)(`h3`,{className:`truncate text-sm font-medium`,children:e}),s&&(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[s.total,` row`,s.total===1?``:`s`]})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1`,children:[O,(0,$.jsx)(`span`,{className:`flex`,title:E??void 0,children:(0,$.jsxs)(W,{variant:`outline`,size:`sm`,className:`h-8 px-2 text-destructive hover:bg-destructive/10 hover:text-destructive`,disabled:!!E||d.size===0,onClick:x,children:[(0,$.jsx)(qt,{className:`mr-1 h-3.5 w-3.5`}),`Delete selected`,d.size>0?` (${d.size})`:``]})}),(0,$.jsx)(`span`,{className:`flex`,title:E??void 0,children:(0,$.jsxs)(W,{variant:`outline`,size:`sm`,className:`h-8 px-2`,disabled:!!E,onClick:y,children:[(0,$.jsx)(he,{className:`mr-1 h-3.5 w-3.5`}),`Record`]})})]})]}),(0,$.jsx)(us,{active:o}),(0,$.jsxs)(`div`,{ref:L,"data-records-scroll":!0,className:`flex-1 overflow-auto custom-scrollbar min-h-0 isolate`,style:{contain:`layout paint`},children:[!s&&o&&(0,$.jsx)(`div`,{role:`status`,className:`flex h-32 items-center justify-center text-sm text-muted-foreground`,children:`Loading records…`}),s&&(0,$.jsx)(`div`,{className:`min-w-fit inline-block align-middle`,children:(0,$.jsxs)(`table`,{ref:P,"aria-colcount":M.length+ +!!A,className:`table-fixed caption-bottom text-sm`,style:{width:U},children:[(0,$.jsxs)(`colgroup`,{children:[A&&(0,$.jsx)(`col`,{style:{width:40}}),M.map(e=>(0,$.jsx)(`col`,{style:{width:ne(e)}},e))]}),(0,$.jsx)(gr,{className:`sticky top-0 z-20 bg-background`,children:(0,$.jsxs)(ir,{className:`bg-background`,children:[A&&(0,$.jsx)(dr,{className:`w-10 bg-background px-3`,children:(0,$.jsx)(or,{checked:N,disabled:j.length===0,onCheckedChange:e=>S(j,e)})}),M.map(e=>(0,$.jsxs)(dr,{"aria-sort":f?.column===e?f.direction===`asc`?`ascending`:`descending`:`none`,"data-column":e,className:`relative cursor-pointer select-none overflow-hidden whitespace-nowrap bg-background px-2 py-0 hover:bg-muted/60`,onClick:()=>T()&&w(e),title:`Sort by ${e}`,children:[(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),T()&&w(e))},className:`flex h-10 min-w-0 items-center gap-1.5 font-mono text-xs font-medium`,children:[(0,$.jsx)(`span`,{"data-fit":!0,className:`min-w-0 flex-1 truncate`,children:e}),(0,$.jsx)(`span`,{className:`flex h-3 w-3 shrink-0 items-center justify-center`,children:f?.column===e&&(f.direction===`asc`?(0,$.jsx)(je,{className:`h-3 w-3 text-primary`}):(0,$.jsx)(K,{className:`h-3 w-3 text-primary`}))})]}),(0,$.jsx)(`div`,{role:`separator`,"aria-orientation":`vertical`,"aria-label":`Resize column ${e}`,"aria-valuenow":ne(e),"aria-valuemin":is,tabIndex:0,title:`Drag to resize, double-click to fit`,className:`absolute inset-y-0 right-0 z-10 w-1.5 cursor-col-resize touch-none border-r border-border hover:bg-primary/40 focus-visible:bg-primary/40 focus-visible:outline-none`,onPointerDown:t=>H(t,e),onClick:e=>e.stopPropagation(),onDoubleClick:t=>{t.stopPropagation(),ie(e)},onKeyDown:t=>{(t.key===`ArrowLeft`||t.key===`ArrowRight`)&&(t.preventDefault(),t.stopPropagation(),V(e,ne(e)+(t.key===`ArrowLeft`?-10:10))),t.key===`Enter`&&(t.preventDefault(),t.stopPropagation(),ie(e))}})]},e))]})}),(0,$.jsx)(sr,{children:s.rows.length===0?(0,$.jsx)(ir,{children:(0,$.jsx)(cr,{colSpan:s.columns.length+ +!!A,className:`h-24 text-center text-muted-foreground text-sm`,children:D?`No rows match the current filters`:`No rows`})}):j.map((i,o)=>{let s=A?ee(i):`row:${o}`;return(0,$.jsx)(ts,{activeTable:e,connectionId:t,dbType:n,columns:M,columnWindow:re,measureColumn:B,columnHelpers:r,foreignKeyByColumn:a,pageRows:j,row:i,rowKeyValue:s,tableSchema:c,canSelectRows:A,isActive:u===i,isSelected:d.has(s),recordDrafts:p,handleSelectRow:m,onEditRecord:h,onDeleteTables:g,onMutateTables:_,openRelatedRecord:v,onDraftCell:b,onToggleSelectedRow:C,warnUnsaved:T,readOnly:!!E},s)})})]})})]})]})]})}),fs=26214400,ps=(0,Q.memo)(function({activeTable:e,connectionId:t,dbType:n,error:r,filteredTables:a,isLoadingTables:o,searchRef:s,shortcutLabel:c,tableSearch:l,tables:u,onAddTable:d,onDeleteTables:f,onMutateTables:p,onRefreshTables:m,onSelectTable:h,setTableSearch:g,readOnlyReason:_=null}){let[v,y]=(0,Q.useState)([]),[b,x]=(0,Q.useState)(!1),[S,C]=(0,Q.useState)(!1),[w,T]=(0,Q.useState)(null),[E,D]=(0,Q.useState)(0),[O,k]=(0,Q.useState)(!1),[A,ee]=(0,Q.useState)(!1),[j,M]=(0,Q.useState)(!1),[N,P]=(0,Q.useState)(!1),[F,te]=(0,Q.useState)(``),[I,ne]=(0,Q.useState)(``),L=new Set(v),re=v.length>0,R=n===`mysql`||n===`postgresql`,z=a.map(e=>e.table_name),B=u.filter(e=>L.has(e.table_name)),V=e=>{if(e&&!/\.sql$/i.test(e.name))return i.error(`Choose a .sql file`);if(e&&e.size>fs)return i.error(`SQL file is too large. Maximum size is 25 MB`);T(e)},ie=e=>{h(e)},H=(e,t)=>{y(n=>t?[...new Set([...n,e])]:n.filter(t=>t!==e))},U=e=>n?e.trim()?n===`postgresql`&&/`|auto_increment|engine\s*=|pragma\s+/i.test(e)?`This file looks like MySQL/SQLite SQL, not PostgreSQL`:n===`mysql`&&/\bserial\b|::|create\s+extension|pragma\s+/i.test(e)?`This file looks like PostgreSQL/SQLite SQL, not MySQL`:n===`sqlite`&&/engine\s*=|auto_increment|create\s+extension|\bserial\b|set\s+foreign_key_checks/i.test(e)?`This file looks incompatible with SQLite`:``:`SQL file is empty`:`Database driver is unknown`;return(0,$.jsxs)(`div`,{className:`w-40 shrink-0 border-r bg-muted/20 flex flex-col overflow-hidden sm:w-52 md:w-64`,"data-db-client-sidebar":!0,tabIndex:-1,onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`a`&&(e.preventDefault(),y(z))},children:[(0,$.jsxs)(`div`,{className:`px-3 py-2.5 border-b`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsxs)(`h3`,{className:`min-w-0 flex-1 text-xs font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-1.5`,children:[(0,$.jsx)(Tt,{className:`w-3.5 h-3.5 shrink-0`}),(0,$.jsx)(`span`,{className:`truncate`,children:`Tables`})]}),(0,$.jsxs)(Ce,{children:[(0,$.jsxs)(ye,{title:_??void 0,disabled:!!_,render:(0,$.jsx)(W,{type:`button`,variant:`outline`,size:`sm`,className:`h-7 shrink-0 px-2 text-xs`,"aria-label":`Create`}),children:[(0,$.jsx)(he,{className:`h-3.5 w-3.5 sm:mr-1`}),(0,$.jsx)(`span`,{className:`max-sm:sr-only`,children:`Create`}),(0,$.jsx)(Ee,{className:`ml-1 h-3 w-3`})]}),(0,$.jsxs)(xe,{align:`end`,className:`w-44`,children:[(0,$.jsxs)(G,{onClick:()=>C(!0),children:[(0,$.jsx)(Ke,{className:`h-3.5 w-3.5`}),`Import SQL`]}),(0,$.jsxs)(G,{onClick:d,children:[(0,$.jsx)(he,{className:`h-3.5 w-3.5`}),`Create new Table`]})]})]})]}),(0,$.jsxs)(`div`,{className:`relative mt-2`,children:[(0,$.jsx)(Gt,{className:`pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground/60`}),(0,$.jsx)(Z,{ref:s,value:l,onChange:e=>g(e.target.value),placeholder:`Search tables... (${c})`,className:`h-8 pl-8 text-xs`})]})]}),(0,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto custom-scrollbar`,children:[(0,$.jsxs)(`div`,{className:`sticky top-0 z-10 flex items-center gap-2 border-b bg-background/95 p-2`,children:[(0,$.jsxs)(`span`,{className:`min-w-0 flex-1 text-xs text-muted-foreground`,children:[v.length,` selected`]}),v.length>0&&(0,$.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,$.jsx)(or,{checked:z.length>0&&z.every(e=>L.has(e)),onCheckedChange:e=>y(e?[...new Set([...v,...z])]:v.filter(e=>!z.includes(e)))}),`Select all`]}),v.length>0&&(0,$.jsx)(W,{type:`button`,variant:`ghost`,size:`sm`,className:`h-6 px-1.5 text-xs`,onClick:()=>y([]),children:`Clear`})]}),(0,$.jsx)(`div`,{className:`p-1.5 space-y-0.5`,children:o?(0,$.jsx)(`div`,{className:`p-3 space-y-2`,children:[1,2,3,4].map(e=>(0,$.jsx)(fn,{className:`h-8 w-full rounded-md`},e))}):u.length===0?(0,$.jsx)(`div`,{className:`p-3 text-center text-xs text-muted-foreground`,children:r?(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-2 text-destructive`,children:[(0,$.jsx)(We,{className:`w-4 h-4`}),(0,$.jsx)(`span`,{children:r})]}):`No tables found`}):a.length===0?(0,$.jsx)(`div`,{className:`p-3 text-center text-xs text-muted-foreground`,children:`No matching tables`}):a.map(r=>(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,onClick:()=>ie(r.table_name),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),ie(r.table_name))},className:`group w-full cursor-pointer text-left px-2.5 py-1.5 rounded-md text-sm transition-colors flex items-center gap-2 ${e===r.table_name?`bg-accent text-accent-foreground font-medium`:`text-muted-foreground hover:text-foreground hover:bg-accent/50`}`,children:[(0,$.jsxs)(`div`,{className:`relative h-3.5 w-3.5 shrink-0`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:[(0,$.jsx)(gt,{className:`absolute inset-0 h-3.5 w-3.5 opacity-60 transition-opacity ${re?`opacity-0`:`group-hover:opacity-0`}`}),(0,$.jsx)(or,{"aria-label":`Select ${r.table_name}`,checked:L.has(r.table_name),className:`absolute inset-0 size-3.5 transition-opacity ${re?`opacity-100`:`opacity-0 group-hover:opacity-100`}`,onCheckedChange:e=>H(r.table_name,e)})]}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:r.table_name}),(0,$.jsx)(Jo,{connectionId:t,dbType:n,table:r,tables:u,readOnlyReason:_,onDeleteTables:f,onMutateTables:p})]},r.table_name))})]}),(0,$.jsx)(`div`,{className:`border-t bg-background/95 p-2`,children:(0,$.jsxs)(mr,{className:`flex w-full`,children:[(0,$.jsx)(Jo,{connectionId:t,dbType:n,table:B[0]||u[0]||{table_name:`tables`,columns:[]},tables:u,exportTables:B,label:`Export All`,mode:`button`,buttonClassName:`h-8 min-w-0 flex-1 px-1.5 text-[11px] max-sm:[&_svg]:hidden`,disabled:v.length<=1,onDeleteTables:f,onMutateTables:p}),(0,$.jsx)(`span`,{className:`flex min-w-0 flex-1`,title:_??void 0,children:(0,$.jsxs)(W,{type:`button`,variant:`outline`,className:`h-8 min-w-0 flex-1 px-1.5 text-[11px] text-destructive max-sm:[&_svg]:hidden hover:bg-destructive/10 hover:text-destructive`,disabled:!!_||!R||v.length===0,onClick:()=>x(!0),children:[(0,$.jsx)(qt,{className:`mr-1 h-3.5 w-3.5`}),`Delete All`]})})]})}),(0,$.jsx)(Wt,{open:S,onOpenChange:e=>!e&&C(!1),children:(0,$.jsxs)(zt,{size:`md`,children:[(0,$.jsx)(Ut,{children:(0,$.jsx)(Bt,{children:`Import SQL`})}),(0,$.jsxs)(Vt,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`rounded-md border bg-muted/30 px-3 py-2 text-xs text-muted-foreground`,children:[`Only table import SQL for `,n||`the selected driver`,` is supported.`]}),(0,$.jsxs)(`label`,{className:`flex min-h-32 cursor-pointer flex-col items-center justify-center rounded-lg border border-dashed px-4 py-6 text-center text-sm transition-colors ${O?`border-primary bg-primary/10`:`border-border bg-background hover:bg-muted/50`}`,onDragOver:e=>{e.preventDefault(),k(!0)},onDragLeave:()=>k(!1),onDrop:e=>{e.preventDefault(),k(!1),V(e.dataTransfer.files?.[0]||null)},children:[(0,$.jsx)(Ke,{className:`mb-2 h-6 w-6 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`font-medium`,children:w?.name||`Drop SQL file here`}),(0,$.jsx)(`span`,{className:`mt-1 text-xs text-muted-foreground`,children:`or click to choose a .sql file`}),(0,$.jsx)(`input`,{type:`file`,accept:`.sql,text/sql,text/plain`,className:`hidden`,onChange:e=>V(e.target.files?.[0]||null)})]}),A&&(0,$.jsx)(`div`,{className:`h-2 overflow-hidden rounded-full bg-muted`,children:(0,$.jsx)(`div`,{className:`h-full bg-primary transition-all`,style:{width:`${E}%`}})}),(0,$.jsx)(To,{expected:`IMPORT`,value:I,onChange:ne})]}),(0,$.jsxs)(Ht,{children:[(0,$.jsx)(W,{variant:`outline`,onClick:()=>C(!1),disabled:A,children:`Cancel`}),(0,$.jsx)(W,{onClick:async()=>{if(!w)return i.error(`Choose a .sql file first`);try{ee(!0),D(20);let e=await w.text();D(45);let n=U(e);if(n)throw Error(n);let r=await cn(`/api/catalogs/${t}/structure/import-sql`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({sql:e,confirmation:I})});D(80);let a=await r.json();if(!r.ok)throw Error(a.error||`Failed to import SQL`);i.success(`Imported ${a.statements||0} SQL statement${a.statements===1?``:`s`}`),C(!1),T(null),D(100),m()}catch(e){i.error(e.message||`Failed to import SQL`)}finally{ee(!1)}},disabled:!w||A||I!==`IMPORT`,children:A?`Importing...`:`Import SQL`})]})]})}),(0,$.jsx)(rn,{open:b,onOpenChange:e=>!e&&x(!1),children:(0,$.jsxs)(Yt,{size:`sm`,children:[(0,$.jsx)(Xt,{children:(0,$.jsx)(an,{children:`Delete tables`})}),(0,$.jsxs)(tn,{className:`space-y-3`,children:[n===`mysql`&&(0,$.jsxs)(`label`,{className:`flex items-start gap-3 text-sm`,children:[(0,$.jsx)(or,{className:`mt-0.5`,checked:j,onCheckedChange:e=>{M(e),e&&P(!1)}}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`block font-medium`,children:`Ignore foreign key checks`}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Disable MySQL FK checks during delete.`})]})]}),(0,$.jsxs)(`label`,{className:`flex items-start gap-3 text-sm`,children:[(0,$.jsx)(or,{className:`mt-0.5`,checked:N,disabled:n===`mysql`&&j,onCheckedChange:e=>P(e)}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`block font-medium`,children:`Cascade`}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Drop dependent foreign keys where the database supports it.`})]})]}),(0,$.jsx)(To,{expected:v.join(`, `),value:F,onChange:te})]}),(0,$.jsxs)(nn,{children:[(0,$.jsx)(Zt,{children:`Cancel`}),(0,$.jsx)($t,{className:`bg-destructive hover:bg-destructive/90`,disabled:F!==v.join(`, `),onClick:async()=>{try{await f(v,{ignoreForeignKeys:n===`mysql`&&j,cascade:N,confirmation:F}),i.success(`${v.length} table${v.length===1?``:`s`} deleted`),y([]),x(!1)}catch(e){i.error(e.message||`Failed to delete tables`)}},children:`Delete`})]})]})})]})}),ms=e=>e===null?`NULL`:e===void 0||e===``?`EMPTY`:String(e),hs=e=>e?`YES`:`NO`,gs=e=>e==null||e===``?`text-muted-foreground`:`text-foreground`;function _s({value:e,className:t=``}){return(0,$.jsx)(cr,{className:`font-mono ${gs(e)} ${t}`,children:ms(e)})}function vs({active:e}){return(0,$.jsx)(`div`,{className:`h-0.5 overflow-hidden bg-transparent`,children:e&&(0,$.jsx)(`div`,{className:`h-full w-full animate-pulse bg-primary`})})}function ys({table:e,isLoading:t=!1,selectedColumnName:n,selectedIndexName:r,selectedCheckName:i,onEditTable:a,onSelectColumn:o,onSelectIndex:s,onSelectCheck:c}){let l=(e?.columns||[]).map((e,t)=>({column:e,index:t})).sort((e,t)=>(Number(e.column.sort_order)||e.index+1)-(Number(t.column.sort_order)||t.index+1)).map(e=>e.column),u=e?.foreign_keys||[],d=e?.indexes||[],f=e?.checks||[];return(0,$.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-hidden flex flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-4 border-b bg-muted/10 px-4 py-2`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Name`}),(0,$.jsx)(`button`,{className:`h-8 w-64 max-w-[32vw] truncate rounded-md border bg-background px-3 py-1.5 text-left text-sm font-medium hover:bg-muted/50`,onClick:a,children:e.table_name})]}),(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Primary`}),(0,$.jsx)(`div`,{className:`h-8 min-w-32 flex-1 truncate rounded-md border bg-background px-3 py-1.5 text-sm`,children:l.filter(e=>e.is_pk).map(e=>e.name).join(`, `)||`EMPTY`})]}),e.comment&&(0,$.jsx)(`div`,{className:`max-w-[28vw] truncate text-xs text-muted-foreground`,title:e.comment,children:e.comment})]}),(0,$.jsx)(vs,{active:t}),(0,$.jsx)(`div`,{className:`min-h-0 flex-3 overflow-auto custom-scrollbar`,children:(0,$.jsxs)(ar,{children:[(0,$.jsx)(gr,{children:(0,$.jsx)(ir,{className:`sticky top-0 z-10 bg-background`,children:[`#`,`column_name`,`data_type`,`character_set`,`collation`,`is_nullable`,`column_default`,`extra`,`foreign_key`,`comment`].map(e=>(0,$.jsx)(dr,{className:`font-mono text-xs`,children:e},e))})}),(0,$.jsx)(sr,{children:l.map((e,t)=>{let r=u.find(t=>t.column===e.name);return(0,$.jsxs)(ir,{className:`cursor-pointer ${n===e.name?`bg-muted/70`:``}`,onClick:()=>o(e.name),children:[(0,$.jsx)(cr,{className:`w-14 text-right font-mono text-muted-foreground`,children:t+1}),(0,$.jsx)(cr,{className:`font-mono font-medium text-foreground`,children:e.name}),(0,$.jsx)(_s,{value:e.full_type||e.type}),(0,$.jsx)(_s,{value:e.character_set}),(0,$.jsx)(_s,{value:e.collation}),(0,$.jsx)(cr,{className:`font-mono`,children:hs(e.is_nullable)}),(0,$.jsx)(_s,{value:e.column_default}),(0,$.jsx)(_s,{value:e.extra||(e.is_generated?`generated`:``)}),(0,$.jsx)(_s,{value:r?`${r.ref_table}(${r.ref_column})`:``}),(0,$.jsx)(_s,{value:e.comment})]},e.name)})})]})}),(0,$.jsxs)(`div`,{className:`grid min-h-56 flex-2 grid-cols-3 border-t`,children:[(0,$.jsx)(`div`,{className:`min-w-0 overflow-auto custom-scrollbar border-r`,children:(0,$.jsxs)(ar,{children:[(0,$.jsx)(gr,{children:(0,$.jsx)(ir,{className:`sticky top-0 z-10 bg-background`,children:[`relation_name`,`column_name`,`reference`,`on_delete`,`on_update`].map(e=>(0,$.jsx)(dr,{className:`font-mono text-xs`,children:e},e))})}),(0,$.jsx)(sr,{children:u.length===0?(0,$.jsx)(ir,{children:(0,$.jsx)(cr,{colSpan:5,className:`h-20 text-center text-muted-foreground`,children:`No relations`})}):u.map(e=>(0,$.jsxs)(ir,{children:[(0,$.jsx)(_s,{value:e.constraint_name}),(0,$.jsx)(_s,{value:e.column}),(0,$.jsx)(_s,{value:`${e.ref_table}(${e.ref_column})`}),(0,$.jsx)(_s,{value:e.on_delete}),(0,$.jsx)(_s,{value:e.on_update})]},`${e.constraint_name||e.column}-${e.ref_table}`))})]})}),(0,$.jsx)(`div`,{className:`min-w-0 overflow-auto custom-scrollbar`,children:(0,$.jsxs)(ar,{children:[(0,$.jsx)(gr,{children:(0,$.jsx)(ir,{className:`sticky top-0 z-10 bg-background`,children:[`index_name`,`index_algorithm`,`is_unique`,`column_name`].map(e=>(0,$.jsx)(dr,{className:`font-mono text-xs`,children:e},e))})}),(0,$.jsx)(sr,{children:d.length===0?(0,$.jsx)(ir,{children:(0,$.jsx)(cr,{colSpan:4,className:`h-20 text-center text-muted-foreground`,children:`No indexes`})}):d.map(e=>(0,$.jsxs)(ir,{className:`cursor-pointer ${r===e.name?`bg-muted/70`:``}`,onClick:()=>s(e.name),children:[(0,$.jsx)(_s,{value:e.name}),(0,$.jsx)(_s,{value:e.algorithm}),(0,$.jsx)(cr,{className:`font-mono`,children:String(!!e.is_unique).toUpperCase()}),(0,$.jsx)(_s,{value:e.column_name})]},e.name))})]})}),(0,$.jsx)(`div`,{className:`min-w-0 overflow-auto custom-scrollbar border-l`,children:(0,$.jsxs)(ar,{children:[(0,$.jsx)(gr,{children:(0,$.jsx)(ir,{className:`sticky top-0 z-10 bg-background`,children:[`check_name`,`expression`].map(e=>(0,$.jsx)(dr,{className:`font-mono text-xs`,children:e},e))})}),(0,$.jsx)(sr,{children:f.length===0?(0,$.jsx)(ir,{children:(0,$.jsx)(cr,{colSpan:2,className:`h-20 text-center text-muted-foreground`,children:`No checks`})}):f.map(e=>(0,$.jsxs)(ir,{className:`cursor-pointer ${i===e.name?`bg-muted/70`:``}`,onClick:()=>e.name&&c(e.name),children:[(0,$.jsx)(_s,{value:e.name}),(0,$.jsx)(_s,{value:e.expression})]},e.name||e.expression))})]})})]})]})}var bs=(e,t)=>{e(e=>e&&{...e,...t})};function xs({target:e,draft:t,tableColumns:n,setDraft:r}){return e.kind===`index`||e.kind===`addIndex`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{htmlFor:`structure-index-name`,children:`Index name`}),(0,$.jsx)(Z,{id:`structure-index-name`,value:t.indexName,onChange:e=>bs(r,{indexName:e.target.value})})]}),(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,$.jsx)(or,{checked:t.indexUnique,onCheckedChange:e=>bs(r,{indexUnique:e})}),`Unique`]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{children:`Algorithm`}),(0,$.jsxs)(X,{value:t.indexAlgorithm||`default`,onValueChange:e=>bs(r,{indexAlgorithm:e==="default"?``:e??``}),children:[(0,$.jsx)(st,{children:(0,$.jsx)(ct,{children:t.indexAlgorithm?t.indexAlgorithm.toUpperCase():`Default`})}),(0,$.jsxs)(ot,{children:[(0,$.jsx)(at,{value:`default`,children:`Default`}),(0,$.jsx)(at,{value:`btree`,children:`BTREE`}),(0,$.jsx)(at,{value:`hash`,children:`HASH`})]})]})]}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(nr,{children:`Columns`}),(0,$.jsx)(`div`,{className:`max-h-60 space-y-2 overflow-y-auto rounded-md border p-2`,children:n.map(e=>(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,$.jsx)(or,{checked:t.indexColumns.includes(e.name),onCheckedChange:n=>bs(r,{indexColumns:n?[...t.indexColumns,e.name]:t.indexColumns.filter(t=>t!==e.name)})}),(0,$.jsx)(`span`,{className:`font-mono`,children:e.name})]},e.name))})]})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{htmlFor:`structure-check-name`,children:`Constraint name`}),(0,$.jsx)(Z,{id:`structure-check-name`,value:t.checkName,placeholder:`check_name`,onChange:e=>bs(r,{checkName:e.target.value})})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{htmlFor:`structure-check-expression`,children:`Expression`}),(0,$.jsx)(jn,{id:`structure-check-expression`,value:t.checkExpression,placeholder:`price >= 0`,onChange:e=>bs(r,{checkExpression:e.target.value})}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`SQL expression without a trailing semicolon.`})]})]})}var Ss=(e,t)=>{e(e=>e&&{...e,...t})},Cs=[`INTEGER`,`TEXT`,`REAL`,`BLOB`,`NUMERIC`],ws=new Set([...lo,...co]),Ts=[``,`AUTO_INCREMENT`,`ON UPDATE CURRENT_TIMESTAMP`],Es=[`NO ACTION`,`CASCADE`,`SET NULL`,`SET DEFAULT`,`RESTRICT`];function Ds(e,t){let n=e===`sqlite`?Cs:e===`postgresql`?co:lo,r=po(e,t);return[...new Set(r?[r,...n.map(t=>po(e,t))]:n.map(t=>po(e,t)))].sort((e,t)=>e.localeCompare(t))}var Os=e=>e.kind===`column`||e.kind===`addColumn`||e.kind===`addTable`,ks=(e,t,n)=>{let r=po(e,t);return/^(ENUM|SET)$/.test(r)||n.length>0&&!ws.has(r)},As=e=>(e?.columns||[]).map((e,t)=>({column:e,index:t})).sort((e,t)=>(Number(e.column.sort_order)||e.index+1)-(Number(t.column.sort_order)||t.index+1)).map(e=>e.column),js=e=>e.kind===`table`?`Edit Table`:e.kind===`addTable`?`Add Table`:e.kind===`addColumn`?`Add Column`:e.kind===`addIndex`?`Add Index`:e.kind===`index`?`Edit Index`:e.kind===`addCheck`?`Add Check Constraint`:e.kind===`check`?`Edit Check Constraint`:`Edit Column`;function Ms({target:e,draft:t,isDirty:n,isSaving:r,readOnlyReason:i=null,tables:a,dbType:o,referenceColumns:s,setDraft:c,onClose:l,onDeleteColumn:u,onDeleteIndex:d,onDeleteCheck:f,onSave:p}){let[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(``),v=As(a.find(e=>e.table_name===t.tableName)),y=a.map(e=>e.table_name).filter(Boolean),b=o===`mysql`?[...new Set(t.columnExtra?[t.columnExtra,...Ts]:Ts)]:[],x=so(t.columnType,t.isNullable,t.columnDefault),S=`${e.kind}:${`columnName`in e?e.columnName:t.tableName}`,C=x.find(e=>e.value.toUpperCase()===t.columnDefault.toUpperCase()),w=io(t.columnType)&&(g===S||!(!t.columnDefault||C)),T=w?ro:C?.value??`__none__`;return(0,$.jsx)(`aside`,{className:`w-80 shrink-0 border-l bg-background`,children:(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-3 border-b p-4`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`h3`,{className:`truncate text-sm font-medium`,children:js(e)}),(0,$.jsx)(`p`,{className:`truncate text-xs text-muted-foreground`,children:t.tableName})]}),(0,$.jsx)(W,{variant:`ghost`,size:`icon-xs`,onClick:l,title:`Close details`,children:(0,$.jsx)(It,{className:`h-3.5 w-3.5`})})]}),(0,$.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-4 overflow-y-auto p-3`,children:[(e.kind===`table`||e.kind===`addTable`)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{htmlFor:`structure-table-name`,children:`Table name`}),(0,$.jsx)(Z,{id:`structure-table-name`,value:t.tableName,onChange:e=>Ss(c,{tableName:e.target.value})})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{htmlFor:`structure-table-comment`,children:`Table comment`}),(0,$.jsx)(jn,{id:`structure-table-comment`,value:t.tableComment,onChange:e=>Ss(c,{tableComment:e.target.value})})]})]}),Os(e)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{htmlFor:`structure-column-name`,children:`Column name`}),(0,$.jsx)(Z,{id:`structure-column-name`,value:t.columnName,onChange:e=>Ss(c,{columnName:e.target.value})})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{htmlFor:`structure-column-type`,children:`Data type`}),(0,$.jsx)(Xe,{value:po(o,t.columnType),onChange:e=>{let n=so(e,t.isNullable);Ss(c,{columnType:e,characterLength:mo(e)?t.characterLength||`255`:``,numericPrecision:ho(e)||go(o,e)?t.numericPrecision:``,numericScale:ho(e)?t.numericScale:``,columnDefault:n.some(e=>e.value.toUpperCase()===T.toUpperCase())?t.columnDefault:``,refColumn:``})},items:Ds(o,t.columnType),placeholder:`Type`,searchPlaceholder:`Search type...`,emptyMessage:`No valid types`,className:`h-9 text-sm`,getItemValue:e=>e,getItemLabel:e=>e,filterItem:(e,t)=>e.toLowerCase().includes(t.toLowerCase())})]}),mo(po(o,t.columnType))&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{htmlFor:`structure-column-length`,children:`Length`}),(0,$.jsx)(Z,{id:`structure-column-length`,type:`number`,min:1,value:t.characterLength,placeholder:`255`,onChange:e=>Ss(c,{characterLength:e.target.value.replace(/\D/g,``)})})]}),ho(po(o,t.columnType))&&(0,$.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{htmlFor:`structure-column-precision`,children:`Precision`}),(0,$.jsx)(Z,{id:`structure-column-precision`,type:`number`,min:1,value:t.numericPrecision,placeholder:`10`,onChange:e=>Ss(c,{numericPrecision:e.target.value.replace(/\D/g,``)})})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{htmlFor:`structure-column-scale`,children:`Scale`}),(0,$.jsx)(Z,{id:`structure-column-scale`,type:`number`,min:0,value:t.numericScale,placeholder:`2`,onChange:e=>Ss(c,{numericScale:e.target.value.replace(/\D/g,``)})})]})]}),go(o,t.columnType)&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{htmlFor:`structure-column-time-precision`,children:`Fractional precision`}),(0,$.jsx)(Z,{id:`structure-column-time-precision`,type:`number`,min:0,max:6,value:t.numericPrecision,placeholder:o===`postgresql`?`6`:`0`,onChange:e=>{let t=e.target.value.replace(/\D/g,``).slice(0,1);Ss(c,{numericPrecision:t&&Number(t)>6?`6`:t,numericScale:``})}})]}),ks(o,t.columnType,t.enumValues)&&(0,$.jsxs)(`div`,{className:`space-y-2 rounded-md border p-3`,children:[(0,$.jsx)(nr,{htmlFor:`structure-enum-value`,children:`Enum values`}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Z,{id:`structure-enum-value`,value:m,onChange:e=>h(e.target.value),placeholder:`new_value`}),(0,$.jsx)(W,{type:`button`,variant:`outline`,onClick:()=>{let e=m.trim();e&&!t.enumValues.includes(e)&&(Ss(c,{enumValues:[...t.enumValues,e]}),h(``))},children:`Add`})]}),(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:t.enumValues.map(e=>(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded border bg-muted/40 px-2 py-0.5 font-mono text-xs`,children:[e,(0,$.jsx)(`button`,{type:`button`,className:`rounded-sm text-muted-foreground hover:text-destructive`,title:`Remove ${e}`,onClick:()=>Ss(c,{enumValues:t.enumValues.filter(t=>t!==e)}),children:(0,$.jsx)(It,{className:`h-3 w-3`})})]},e))})]}),(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,$.jsx)(or,{checked:t.isNullable,onCheckedChange:e=>Ss(c,{isNullable:e,columnDefault:!e&&t.columnDefault.toUpperCase()===`NULL`?``:t.columnDefault})}),`Nullable`]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{htmlFor:`structure-column-default`,children:`Default`}),(0,$.jsxs)(X,{value:T,onValueChange:e=>{_(e===`__custom__`?S:``),Ss(c,{columnDefault:e===`__none__`||e===`__custom__`?``:e??``})},children:[(0,$.jsx)(st,{id:`structure-column-default`,children:(0,$.jsx)(ct,{children:x.find(e=>e.value===T)?.label})}),(0,$.jsx)(ot,{children:x.map(e=>(0,$.jsx)(at,{value:e.value,children:e.label},e.value))})]}),w&&(0,$.jsx)(Z,{value:t.columnDefault,placeholder:`Enter text default`,"aria-label":`Custom default value`,onChange:e=>Ss(c,{columnDefault:e.target.value})})]}),b.length>0&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{children:`Extra`}),(0,$.jsxs)(X,{value:t.columnExtra||`none`,onValueChange:e=>Ss(c,{columnExtra:e===`none`?``:e??``}),children:[(0,$.jsx)(st,{children:(0,$.jsx)(ct,{children:t.columnExtra||`None`})}),(0,$.jsx)(ot,{children:b.map(e=>(0,$.jsx)(at,{value:e||`none`,children:e||`None`},e||`none`))})]})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{htmlFor:`structure-column-comment`,children:`Comment`}),(0,$.jsx)(jn,{id:`structure-column-comment`,value:t.columnComment,onChange:e=>Ss(c,{columnComment:e.target.value})})]}),e.kind!==`addTable`&&(0,$.jsxs)(`div`,{className:`space-y-3 rounded-md border p-3`,children:[(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,$.jsx)(or,{checked:t.fkEnabled,onCheckedChange:e=>Ss(c,{fkEnabled:e})}),`Foreign key`]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{children:`Reference table`}),(0,$.jsx)(Xe,{value:t.refTable,onChange:e=>Ss(c,{refTable:e,refColumn:``}),items:y,placeholder:`Select table`,searchPlaceholder:`Search table...`,emptyMessage:`No tables`,className:`h-9 text-sm`,getItemValue:e=>e,getItemLabel:e=>e,filterItem:(e,t)=>e.toLowerCase().includes(t.toLowerCase())})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{children:`Reference column`}),(0,$.jsxs)(X,{value:t.refColumn,onValueChange:e=>Ss(c,{refColumn:e??``}),children:[(0,$.jsx)(st,{children:(0,$.jsx)(ct,{placeholder:`Select column`})}),(0,$.jsx)(ot,{children:s.map(e=>(0,$.jsx)(at,{value:e.name,children:e.name},e.name))})]}),t.refTable&&s.length===0&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No compatible columns for this type.`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{children:`Constraint name`}),(0,$.jsx)(Z,{value:t.fkConstraintName,placeholder:`Auto-generated`,onChange:e=>Ss(c,{fkConstraintName:e.target.value})})]}),(0,$.jsx)(`div`,{className:`grid grid-cols-2 gap-2`,children:[`fkOnDelete`,`fkOnUpdate`].map(e=>(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(nr,{children:e===`fkOnDelete`?`On delete`:`On update`}),(0,$.jsxs)(X,{value:t[e],onValueChange:t=>Ss(c,{[e]:t??`NO ACTION`}),children:[(0,$.jsx)(st,{children:(0,$.jsx)(ct,{})}),(0,$.jsx)(ot,{children:Es.map(e=>(0,$.jsx)(at,{value:e,children:e},e))})]})]},e))})]})]}),(e.kind===`index`||e.kind===`addIndex`||e.kind===`check`||e.kind===`addCheck`)&&(0,$.jsx)(xs,{target:e,draft:t,tableColumns:v,setDraft:c})]}),(0,$.jsxs)(`div`,{className:`sticky bottom-0 grid grid-cols-2 gap-2 border-t bg-background p-3`,children:[i&&(0,$.jsx)(`p`,{className:`col-span-2 text-xs text-muted-foreground`,children:i}),e.kind===`column`&&(0,$.jsxs)(W,{variant:`destructive`,className:`col-span-2`,onClick:u,disabled:!!i||r,children:[(0,$.jsx)(qt,{className:`mr-2 h-4 w-4`}),`Delete Column`]}),e.kind===`index`&&(0,$.jsxs)(W,{variant:`destructive`,className:`col-span-2`,onClick:d,disabled:!!i||r,children:[(0,$.jsx)(qt,{className:`mr-2 h-4 w-4`}),`Delete Index`]}),e.kind===`check`&&(0,$.jsxs)(W,{variant:`destructive`,className:`col-span-2`,onClick:f,disabled:!!i||r,children:[(0,$.jsx)(qt,{className:`mr-2 h-4 w-4`}),`Delete Check`]}),(0,$.jsx)(W,{variant:`outline`,onClick:l,disabled:r,children:`Cancel`}),(0,$.jsx)(W,{onClick:p,disabled:!!i||!n||r,children:`Submit`})]})]})})}function Ns({activeTable:e,isLoading:t,open:n,sql:r,onOpenChange:i}){return(0,$.jsx)(Wt,{open:n,onOpenChange:i,children:(0,$.jsxs)(zt,{size:`3xl`,children:[(0,$.jsx)(Ut,{children:(0,$.jsxs)(Bt,{children:[e,` SQL`]})}),(0,$.jsx)(Vt,{children:(0,$.jsx)(`pre`,{className:`max-h-[60vh] overflow-auto rounded-md border bg-muted/30 p-3 text-xs leading-relaxed`,children:(0,$.jsx)(`code`,{children:t?`Loading...`:r})})})]})})}function Ps({activeTable:e,openTabs:t,onCloseTable:n,onSelectTable:r,onPinTable:i,rightActions:a}){return t.length===0?null:(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b bg-muted/10 px-2 py-1`,children:[(0,$.jsx)(`div`,{className:`flex min-w-0 flex-1 items-center gap-1 overflow-x-auto scrollbar-hide`,children:t.map(t=>(()=>{let a=t.label||t.name;return(0,$.jsxs)(`button`,{onClick:()=>r(t.name),onDoubleClick:()=>i(t.name),className:`group flex h-8 max-w-48 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs font-medium transition-colors ${e===t.name?`bg-background text-foreground shadow-sm`:`text-muted-foreground hover:bg-accent hover:text-accent-foreground`}`,title:t.pinned?`${a} (pinned)`:`${a} (double click to pin)`,children:[(0,$.jsx)(`span`,{className:`truncate ${t.pinned?`not-italic`:`italic`}`,children:a}),(0,$.jsx)(`span`,{role:`button`,tabIndex:0,onClick:e=>{e.stopPropagation(),n(t.name)},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),e.stopPropagation(),n(t.name))},className:`ml-1 rounded p-0.5 opacity-60 hover:bg-muted hover:opacity-100`,title:`Close table`,children:(0,$.jsx)(It,{className:`h-3 w-3`})})]},t.name)})())}),a]})}function Fs({dbType:e,activeView:t,table:n,tableCount:r}){let i=[`[DB Client live context]`,`Dialect: ${e||`unknown`}`,`Current tab: Data / ${t===`structure`?`Structure`:`Records`}`,`Tables available: ${r}`];if(!n)return[...i,`Selected table: none`].join(`
|
|
90
|
+
`);i.push(`Selected table: ${n.table_schema?`${n.table_schema}.`:``}${n.table_name}`),n.comment&&i.push(`Table comment: ${n.comment}`),i.push(`Columns:`);for(let e of n.columns||[]){let t=[e.is_pk?`PK`:``,e.is_nullable?`NULL`:`NOT NULL`,e.column_default==null?``:`DEFAULT ${e.column_default}`,e.is_generated?`GENERATED`:``].filter(Boolean).join(`, `);i.push(` - ${e.name}: ${e.full_type||e.type||`unknown`}${t?` [${t}]`:``}${e.comment?` -- ${e.comment}`:``}`)}return n.foreign_keys?.length&&i.push(`Foreign keys:`,...n.foreign_keys.map(e=>` - ${e.column} -> ${e.ref_table}.${e.ref_column}${e.on_delete?` ON DELETE ${e.on_delete}`:``}${e.on_update?` ON UPDATE ${e.on_update}`:``}`)),n.indexes?.length&&i.push(`Indexes:`,...n.indexes.map(e=>` - ${e.name}: ${e.column_name}${e.is_primary?` PRIMARY`:e.is_unique?` UNIQUE`:``}${e.algorithm?` ${e.algorithm}`:``}`)),n.checks?.length&&i.push(`Checks:`,...n.checks.map(e=>` - ${e.name||`(unnamed)`}: ${e.expression}`)),i.push(`Safety: metadata only; no record values or credentials are included. Treat changes as proposals until the user confirms them.`),i.join(`
|
|
91
|
+
`).slice(0,6e3)}function Is(e,t,n){let r=n.map(e=>{let t=(e.columns||[]).map(e=>e.name).filter(Boolean).join(`, `);return` - ${e.table_name}${t?` (${t})`:``}`}).join(`
|
|
92
|
+
`);return`[DB Client live context]
|
|
93
|
+
Dialect: ${e||`unknown`}
|
|
94
|
+
Current tab: Query
|
|
95
|
+
Active query: ${t?.name||`(untitled)`}
|
|
96
|
+
SQL:
|
|
97
|
+
\`\`\`sql
|
|
98
|
+
${String(t?.script||``).slice(0,4e3)}
|
|
99
|
+
\`\`\`
|
|
100
|
+
Available schema:
|
|
101
|
+
${r||` (none)`}
|
|
102
|
+
Safety: the SQL above has not been executed by the AI. Treat generated SQL as a proposal until the user reviews and confirms it.`.slice(0,8e3)}var Ls=(0,Q.memo)(function({connectionId:e,stateKey:t,onDbTypeChange:n,active:r=!0}){let a=Le(),{tables:o,activeTable:s,openTabs:c,filters:l,appliedFilters:u,sort:d,records:f,dbType:p,connectionSecurity:m,page:h,totalPages:g,isLoadingTables:_,isLoadingRecords:v,error:y,fetchTables:b,refreshAll:x,selectTable:S,openNewTableTab:C,pinTable:w,closeTable:T,addFilter:E,removeFilter:D,updateFilter:O,applyFilter:k,applyFilters:A,openRelatedRecord:ee,createRecord:j,deleteRecord:M,deleteTables:N,mutateTables:P,updateRecord:F,updateRecords:te,updateStructure:I,clearFilters:ne,toggleSort:L,nextPage:re,prevPage:R}=Na(e,t),[z,B]=(0,Q.useState)(``),[V,ie]=(0,Q.useState)(!1),[H,U]=(0,Q.useState)(`data`),[ae,oe]=(0,Q.useState)({}),[se,ce]=(0,Q.useState)({}),le=(0,Q.useCallback)((e,t)=>ce(n=>({...n,[e]:t})),[]),[W,ue]=(0,Q.useState)(null),[de,fe]=(0,Q.useState)(!1),[pe,me]=(0,Q.useState)(``),[he,ge]=(0,Q.useState)(!1),[_e,G]=(0,Q.useState)(!1),[ve,ye]=(0,Q.useState)(!1),be=(0,Q.useRef)(null),xe=(0,Q.useRef)({}),Se=(0,Q.useRef)(null),Ce=(0,Q.useRef)(!1),we=(0,Q.useCallback)(n=>`${t||e}:${n}`,[e,t]),Te=(0,Q.useMemo)(()=>typeof navigator>`u`?`Ctrl+P`:/mac|iphone|ipad|ipod/i.test(navigator.platform)?`⌘P`:`Ctrl+P`,[]),Ee=(0,Q.useMemo)(()=>{let e=z.trim().toLowerCase();return e?o.filter(t=>String(t.table_name).toLowerCase().includes(e)):o},[o,z]),De=(0,Q.useMemo)(()=>(o.find(e=>e.table_name===s)?.columns||f?.columns||[]).map(e=>typeof e==`string`?e:e.name).filter(Boolean),[s,o,f]),Oe=(0,Q.useMemo)(()=>{let e=o.find(e=>e.table_name===s);return new Map((e?.foreign_keys||[]).map(e=>[e.column,e]))},[s,o]),ke=(0,Q.useMemo)(()=>o.find(e=>e.table_name===s),[s,o]),K=s===`__new_table__`,q=wo(ke,o,I,p),Ae=(0,Q.useMemo)(()=>{let e=o.find(e=>e.table_name===s);return Ha(new Map((e?.columns||[]).map(e=>[e.name,e])))},[s,o]),je=(0,Q.useMemo)(()=>(o.find(e=>e.table_name===s)?.columns||[]).filter(e=>e.is_pk).map(e=>e.name),[s,o]),J=to({activeTable:s,columnHelpers:Ae,createRecord:j,deleteRecord:M,primaryKeyColumns:je,records:f,updateRecord:F}),Me=(0,Q.useRef)(J.selectedRow),Ne=eo({activeTable:s,columnHelpers:Ae,primaryKeyColumns:je,updateRecords:te}),Pe=Ne.count,Fe=(0,Q.useRef)(Pe),Ie=(0,Q.useRef)(J.isRecordDirty),Re=(0,Q.useRef)(q.isDirty);Fe.current=Pe,Ie.current=J.isRecordDirty,Me.current=J.selectedRow,Re.current=q.isDirty;let ze=m.safeMode===`read-only`?`Read-only connection: Safe Mode blocks changes. Edit the connection to allow writes.`:null;On(Pe>0||J.isRecordDirty||q.isDirty,`You have unsaved DB Client changes. Leave this page and discard them?`);let Be=(0,Q.useCallback)(()=>Fe.current>0?(i.warning(`Save or discard inline record changes first.`),!1):!Ie.current&&!Re.current||(i.warning(`Save the ${Ie.current?`record`:`structure`} changes before switching.`),!1),[]),Ve=(0,Q.useCallback)(()=>{s&&(ie(!0),l.length===0&&De.length>0&&E(De[0]))},[s,l.length,De,E]),He=(0,Q.useCallback)(()=>{V?ie(!1):(U(`data`),Ve())},[Ve,V]),Ue=(0,Q.useCallback)(e=>{Be()&&(U(xe.current[we(e)]||`data`),S(e))},[S,we,Be]),We=(0,Q.useCallback)(e=>{Be()&&(delete xe.current[we(e)],T(e))},[T,we,Be]),Ge=(0,Q.useCallback)(e=>JSON.stringify(je.map(t=>e[t])),[je]),Ke=(0,Q.useCallback)(e=>{let t=f?.rows||[],n=t.findIndex(e=>Ge(e)===Se.current),r=t.findIndex(t=>Ge(t)===Ge(e));if(n===-1||r===-1)return!1;let[i,a]=n<r?[n,r]:[r,n];return J.selectRows(t.slice(i,a+1)),!0},[J.selectRows,f,Ge]),qe=(0,Q.useCallback)(e=>{if(Me.current===e||!Ie.current||Be())return J.selectRow(e),!0},[J.selectRow,Be]),Je=(0,Q.useCallback)(e=>{qe(e)&&J.setDetailsOpen(!0)},[J.setDetailsOpen,qe]),Ye=(0,Q.useCallback)(e=>{qe(e)},[qe]),Xe=(0,Q.useCallback)((e,t,n)=>{Me.current!==e&&Ie.current&&!Be()||t&&n?.shiftKey&&Ke(e)||(Se.current=t?Ge(e):null,J.toggleSelectedRow(e,t))},[J.toggleSelectedRow,Ge,Ke,Be]),Ze=(0,Q.useCallback)((e,t)=>{(!Ie.current||Be())&&(J.toggleSelectedRows(e,t),Se.current=t&&e[0]?Ge(e[0]):null)},[J.toggleSelectedRows,Ge,Be]),Qe=(0,Q.useCallback)(()=>{Be()&&J.addRecord()},[J.addRecord,Be]),$e=(0,Q.useCallback)(()=>{Be()&&(C(),U(`structure`),q.addTable())},[C,q.addTable,Be]),et=(0,Q.useCallback)(()=>{Be()&&ue(`records`)},[Be]),tt=(0,Q.useCallback)(e=>{e!==H&&Be()&&(s&&(xe.current[we(s)]=e),U(e),e===`structure`&&J.setDetailsOpen(!1))},[s,H,we,Be]),nt=(0,Q.useCallback)(async()=>{if(q.isDirty)try{await q.save(),i.success(`Structure updated`)}catch(e){i.error(e.message||`Failed to update structure`)}},[q]),rt=(0,Q.useCallback)(async()=>{if(s){fe(!0),ge(!0),me(``);try{let t=await cn(`/api/catalogs/${e}/structure/sql`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({table:s})}),n=await t.json();if(!t.ok)throw Error(n.error||`Failed to load table SQL`);me(n.sql||``)}catch(e){i.error(e.message||`Failed to load table SQL`),me(``)}finally{ge(!1)}}},[s,e]),Y=(0,Q.useCallback)(async()=>{let e=q.target;if(!(!e||e.kind!==`column`&&e.kind!==`index`&&e.kind!==`check`))try{await I(e.kind===`column`?{deleteColumnName:e.columnName}:e.kind===`index`?{deleteIndexName:e.indexName}:{deleteCheckName:e.checkName}),i.success(e.kind===`column`?`Column deleted`:e.kind===`index`?`Index deleted`:`Check deleted`),q.close()}catch(e){i.error(e.message||`Failed to delete structure item`)}finally{ue(null)}},[q,I]),it=(0,Q.useCallback)(async e=>{await J.removeSelectedRecords(e),ue(null)},[J.removeSelectedRecords]),at=(0,Q.useCallback)(()=>{Pe>0?G(!0):Be()&&x()},[Pe,x,Be]),ot=(0,Q.useCallback)(async e=>{let t=await P(e);return s&&e.truncateTables?.includes(s)&&J.resetRecordEditor(),t},[s,P,J.resetRecordEditor]);return(0,Q.useEffect)(()=>{if(!r)return;let e=setTimeout(()=>b());return()=>clearTimeout(e)},[r,b]),(0,Q.useEffect)(()=>{n?.(p)},[p,n]),(0,Q.useEffect)(()=>{if(r)return a({aiContextText:Fs({dbType:p,activeView:H,table:ke,tableCount:o.length})}),()=>a(null)},[r,ke,H,p,a,o.length]),(0,Q.useEffect)(()=>{J.syncSelectedRowDraft()},[J.syncSelectedRowDraft]),(0,Q.useEffect)(()=>{ce({})},[s,J.selectedRow,J.isCreatingRecord]),(0,Q.useEffect)(()=>{if(!s||!J.detailsOpen||!J.selectedRow&&!J.isCreatingRecord||Oe.size===0){oe({});return}let t=!1,n=setTimeout(()=>{Promise.all([...Oe.entries()].map(async([t,n])=>{let r=se[t]?.trim(),i=await cn(`/api/catalogs/${e}/records`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({table:n.ref_table,page:1,pageSize:50,withTotal:!1,sort:{column:n.ref_column,direction:`asc`},...r?{search:{value:r}}:{}})}),a=await i.json();if(!i.ok)throw Error(a.error||`Failed to load related records`);return[t,a.rows||[]]})).then(e=>{t||oe(Object.fromEntries(e))}).catch(()=>{t||oe({})})},Object.keys(se).length?250:0);return()=>{t=!0,clearTimeout(n)}},[s,e,se,Oe,J.detailsOpen,J.isCreatingRecord,J.selectedRow]),(0,Q.useEffect)(()=>{J.resetRecordEditor(),Ne.clear(),K||q.close()},[s,K]),(0,Q.useEffect)(()=>{J.resetRecordEditor(),Ne.clear(),Se.current=null},[h]),(0,Q.useEffect)(()=>{K&&q.target?.kind!==`addTable`&&We(`__new_table__`)},[We,K,q.target?.kind]),(0,Q.useEffect)(()=>{if(!r)return;let e=[[`db-connect-refresh-records`,()=>at()],[`db-connect-toggle-filters`,()=>He()],[`db-connect-toggle-details`,()=>J.setDetailsOpen(e=>!e||!Be())]];return e.forEach(([e,t])=>window.addEventListener(e,t)),()=>{e.forEach(([e,t])=>window.removeEventListener(e,t))}},[r,at,J.setDetailsOpen,He,Be]),(0,Q.useEffect)(()=>{if(!r)return;let e=e=>{if(e.key===`Escape`&&Pe>0){e.preventDefault(),ye(!0);return}if(!(e.metaKey||e.ctrlKey))return;let t=e.key.toLowerCase(),n=e.target,r=n&&(n.tagName===`INPUT`||n.tagName===`TEXTAREA`||n.isContentEditable),a=!!n?.closest(`[data-db-client-sidebar]`),o=!!n?.closest(`[data-db-client-records]`)||Ce.current;t===`p`&&!r?(e.preventDefault(),be.current?.focus(),be.current?.select()):t===`f`&&s?(e.preventDefault(),He()):t===`r`&&(!r||Pe>0)?(e.preventDefault(),at()):t===`a`&&H===`data`&&s&&!r&&!a&&o?(e.preventDefault(),J.selectRows(f?.rows||[]),J.selectRow(f?.rows?.[0]||null)):t===`s`&&(e.preventDefault(),ze?i.warning(ze):Pe>0?Ne.save():H===`structure`?nt():J.submitRecord())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[r,s,H,at,nt,Ne.save,ze,Pe,He,J.selectRows,J.submitRecord,f,Be]),(0,$.jsxs)(`div`,{className:`flex flex-1 overflow-hidden`,onMouseDownCapture:e=>{Ce.current=!!e.target?.closest(`[data-db-client-records]`)},children:[(0,$.jsx)(ps,{activeTable:s,connectionId:e,dbType:p,error:y,filteredTables:Ee,isLoadingTables:_,searchRef:be,shortcutLabel:Te,tableSearch:z,tables:o,onAddTable:$e,onDeleteTables:N,onMutateTables:ot,onRefreshTables:x,onSelectTable:Ue,setTableSearch:B,readOnlyReason:ze}),(0,$.jsxs)(`div`,{className:`flex-1 grid grid-rows-[auto_1fr_auto] overflow-hidden`,children:[(0,$.jsxs)(`div`,{className:`flex h-7 items-center gap-2 overflow-hidden whitespace-nowrap border-b bg-muted/20 px-3 text-[10px] font-semibold uppercase`,children:[(0,$.jsx)(`span`,{className:m.environment===`production`?`text-red-600`:`text-muted-foreground`,children:m.environment}),(0,$.jsx)(`span`,{className:m.safeMode===`read-only`?`text-emerald-600`:`text-muted-foreground`,children:m.safeMode}),(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:m.sslMode===`disable`?`TLS OFF`:`TLS ${m.sslMode}`}),(0,$.jsxs)(`span`,{className:`ml-auto hidden text-muted-foreground sm:inline`,children:[`Timeout `,m.queryTimeoutMs,`ms`]})]}),s?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`min-h-0 overflow-hidden flex flex-col`,children:[(0,$.jsx)(Ps,{activeTable:s,openTabs:c,onCloseTable:We,onSelectTable:Ue,onPinTable:w}),H===`structure`&&K?(0,$.jsx)(`div`,{className:`flex flex-1 items-center justify-center text-sm text-muted-foreground`,children:`Create a new table`}):H===`structure`&&ke?(0,$.jsx)(ys,{table:ke,isLoading:_,selectedColumnName:q.target?.kind===`column`?q.target.columnName:null,selectedIndexName:q.target?.kind===`index`?q.target.indexName:null,selectedCheckName:q.target?.kind===`check`?q.target.checkName:null,onEditTable:q.editTable,onSelectColumn:q.editColumn,onSelectIndex:q.editIndex,onSelectCheck:q.editCheck}):null,H===`data`&&!K&&(0,$.jsx)(ds,{activeTable:s,connectionId:e,dbType:p,columnHelpers:Ae,error:y,foreignKeyByColumn:Oe,isLoadingRecords:v,records:f,tableSchema:ke,primaryKeyColumns:je,selectedRow:J.selectedRow,selectedRowKeys:J.selectedRowKeys,sort:d,recordDrafts:Ne.drafts,handleSelectRow:Ye,onEditRecord:Je,onDeleteTables:N,onMutateTables:ot,openRelatedRecord:ee,onAddRecord:Qe,onDraftCell:Ne.draftCell,onDeleteSelectedRecords:et,onTogglePageRows:Ze,onToggleSelectedRow:Xe,toggleSort:L,warnUnsaved:Be,readOnlyReason:ze,hasActiveFilters:u.some(e=>e.enabled),headerAction:(0,$.jsx)(Jo,{connectionId:e,dbType:p,table:ke||{table_name:s,columns:[]},tables:o,exportSelectedRows:J.selectedRows,label:`Export`,mode:`dropdown`,onDeleteTables:N,onMutateTables:ot}),children:V&&l.length>0&&(0,$.jsx)(ko,{columnOptions:De,filters:l,addFilter:E,applyFilter:k,applyFilters:A,clearFilters:ne,removeFilter:D,setShowFilters:ie,updateFilter:O,warnUnsaved:Be})})]}),(f||ke)&&(0,$.jsx)(Ao,{activeView:H,page:h,records:f,tableColumnCount:ke?.columns?.length||0,totalPages:g,warnUnsaved:Be,onAddColumn:q.addColumn,onAddIndex:q.addIndex,onAddCheck:q.addCheck,onInfo:rt,onNextPage:re,onPrevPage:R,onViewChange:tt})]}):(0,$.jsx)(`div`,{className:`h-full flex items-center justify-center text-sm text-muted-foreground`,children:(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[(0,$.jsx)(Tt,{className:`w-8 h-8 text-muted-foreground/30`}),(0,$.jsx)(`span`,{children:`Select a table to view records`})]})})]}),H===`data`&&J.detailsOpen&&(0,$.jsx)(Oo,{activeTable:s,columnHelpers:Ae,datePickerOpenColumn:J.datePickerOpenColumn,draftRow:J.draftRow,fkOptionsByColumn:ae,fkSearchByColumn:se,onFkSearch:le,foreignKeyByColumn:Oe,isRecordDirty:J.isRecordDirty,isCreatingRecord:J.isCreatingRecord,isSavingRecord:J.isSavingRecord,primaryKeyColumns:je,records:f,selectedRow:J.selectedRow,setDatePickerOpenColumn:J.setDatePickerOpenColumn,setDetailsOpen:J.setDetailsOpen,setDraftRow:J.setDraftRow,onCancelCreateRecord:J.cancelCreateRecord,onSubmitCreateRecord:J.submitCreateRecord,onSubmitRecord:J.submitRecord,warnUnsaved:Be,readOnlyReason:ze}),H===`structure`&&q.target&&q.draft&&(0,$.jsx)(Ms,{target:q.target,draft:q.draft,isDirty:q.isDirty,isSaving:q.isSaving,readOnlyReason:ze,tables:o,dbType:p,referenceColumns:q.referenceColumns,setDraft:q.setDraft,onClose:()=>{q.close(),K&&We(`__new_table__`)},onDeleteColumn:()=>ue(`column`),onDeleteIndex:()=>ue(`index`),onDeleteCheck:()=>ue(`check`),onSave:nt}),(0,$.jsx)(Ns,{activeTable:s,isLoading:he,open:de,sql:pe,onOpenChange:fe}),(0,$.jsx)(Eo,{action:W,onCancel:()=>ue(null),onDeleteRecords:it,onDeleteStructure:Y,confirmationTarget:m.environment===`production`||m.safeMode===`protected`?s:null,recordCount:J.selectedRowKeys.size,tableName:s}),(0,$.jsx)(ut,{isOpen:_e,title:`Discard all changes?`,message:`Refresh will discard unsaved inline record changes.`,confirmText:`Discard`,cancelText:`Cancel`,onCancel:()=>G(!1),onConfirm:()=>{Ne.clear(),G(!1),x()}}),(0,$.jsx)(ut,{isOpen:ve,title:`Discard inline changes?`,message:`This will discard all unsaved inline record changes.`,confirmText:`Discard`,cancelText:`Keep editing`,variant:`warning`,onCancel:()=>ye(!1),onConfirm:()=>{Ne.clear(),ye(!1)}})]})}),Rs=50,zs=e=>e.replace(/[^A-Za-z0-9_.-]+/g,`_`)||`sql_query`,Bs=e=>{let t=e==null?``:typeof e==`object`?JSON.stringify(e):String(e);return/[",\n\r]/.test(t)?`"${t.replace(/"/g,`""`)}"`:t};function Vs(e,t,n){let r=e.rows.map(t=>Object.fromEntries(e.columns.map(e=>[e,t[e]]))),a=n===`json`?JSON.stringify(r,null,2):[e.columns.map(Bs).join(`,`),...e.rows.map(t=>e.columns.map(e=>Bs(t[e])).join(`,`))].join(`
|
|
103
|
+
`),o=new Blob([a],{type:n===`json`?`application/json;charset=utf-8`:`text/csv;charset=utf-8`}),s=URL.createObjectURL(o),c=document.createElement(`a`);c.href=s,c.download=`${zs(t)}.${n}`,c.click(),URL.revokeObjectURL(s),i.success(`${n.toUpperCase()} export downloaded`)}var Hs=(0,Q.memo)(function({error:e,emptyText:t,result:n,resultPage:r,onPageChange:i}){if(e)return(0,$.jsx)(`div`,{className:`p-3 text-sm text-destructive`,children:e});if(!n)return(0,$.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:t});let a=n.rows,o=Math.max(1,Math.ceil(a.length/Rs)),s=Math.min(r||1,o),c=(s-1)*Rs,l=a.slice(c,c+Rs);return(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col overflow-hidden`,children:[(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:(0,$.jsxs)(`table`,{className:`w-max min-w-full border-collapse text-xs`,children:[(0,$.jsx)(`thead`,{className:`sticky top-0 bg-background`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`w-12 whitespace-nowrap border-b px-2 py-1.5 text-right font-medium text-muted-foreground`,children:`#`}),n.columns.map(e=>(0,$.jsx)(`th`,{className:`whitespace-nowrap border-b px-2 py-1.5 text-left font-medium`,children:e},e))]})}),(0,$.jsx)(`tbody`,{children:l.map((e,t)=>(0,$.jsxs)(`tr`,{className:`odd:bg-muted/30`,children:[(0,$.jsx)(`td`,{className:`w-12 whitespace-nowrap border-b px-2 py-1.5 text-right text-muted-foreground`,children:c+t+1}),n.columns.map(t=>(0,$.jsx)(`td`,{className:`max-w-64 truncate whitespace-nowrap border-b px-2 py-1.5`,children:String(e[t]??``)},t))]},c+t))})]})}),(0,$.jsxs)(`div`,{className:`flex h-9 shrink-0 items-center justify-between border-t px-2 text-xs text-muted-foreground`,children:[(0,$.jsx)(`span`,{children:n.mode===`explain`?`Query plan`:a.length===0?`0 rows`:`${c+1}-${Math.min(c+Rs,a.length)} of ${a.length} rows${n.truncated?` (limited)`:``}`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(W,{variant:`outline`,size:`icon-xs`,disabled:s<=1,onClick:()=>i(s-1),children:(0,$.jsx)(it,{className:`h-4 w-4`})}),(0,$.jsxs)(`span`,{className:`min-w-16 text-center`,children:[`Page `,s,` / `,o]}),(0,$.jsx)(W,{variant:`outline`,size:`icon-xs`,disabled:s>=o,onClick:()=>i(s+1),children:(0,$.jsx)(ue,{className:`h-4 w-4`})})]})]})]})});function Us({groupName:e,name:t,result:n,onGroupChange:r,onNameChange:i,onDelete:a,onSave:o,security:s}){return(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 overflow-x-auto border-b px-2 py-1`,children:[(0,$.jsx)(Z,{className:`h-8 w-36 shrink-0`,value:e,onChange:e=>r(e.target.value),placeholder:`Group`}),(0,$.jsx)(Z,{className:`h-8 w-64 shrink-0`,value:t,onChange:e=>i(e.target.value),placeholder:`Query name`}),(0,$.jsx)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] font-semibold uppercase ${s?.environment===`production`?`border-red-500/30 bg-red-500/10 text-red-600`:`text-muted-foreground`}`,children:s?.environment||`development`}),s?.safeMode===`read-only`&&(0,$.jsx)(`span`,{className:`rounded border border-emerald-500/30 bg-emerald-500/10 px-1.5 py-0.5 text-[10px] font-semibold text-emerald-600`,children:`READ ONLY`}),s?.sslMode&&s.sslMode!==`disable`&&(0,$.jsxs)(`span`,{className:`rounded border px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:[`TLS `,s.sslMode]}),(0,$.jsxs)(`div`,{className:`ml-auto flex shrink-0 items-center gap-2`,children:[(0,$.jsxs)(W,{size:`sm`,variant:`destructive`,onClick:a,disabled:!a,title:a?`Delete query`:`Save the query before deleting it`,children:[(0,$.jsx)(qt,{className:`mr-1.5 h-3.5 w-3.5`}),` Delete`]}),(0,$.jsxs)(W,{size:`sm`,variant:`outline`,onClick:o,children:[(0,$.jsx)(Je,{className:`mr-1.5 h-3.5 w-3.5`}),` Save`]}),(0,$.jsxs)(Ce,{children:[(0,$.jsxs)(ye,{render:(0,$.jsx)(W,{size:`sm`,variant:`outline`,disabled:!n}),children:[(0,$.jsx)(Oe,{className:`mr-1.5 h-3.5 w-3.5`}),` Export`]}),(0,$.jsxs)(xe,{align:`end`,children:[(0,$.jsx)(G,{onClick:()=>n&&Vs(n,t,`json`),className:`cursor-pointer`,children:`JSON`}),(0,$.jsx)(G,{onClick:()=>n&&Vs(n,t,`csv`),className:`cursor-pointer`,children:`CSV`})]})]})]})]})}function Ws({beautifying:e,runningMode:t,onBeautify:n,onExplain:r,onRun:i,onStop:a}){return(0,$.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2 border-t px-2 py-1`,children:[(0,$.jsxs)(W,{size:`sm`,variant:`outline`,onClick:n,disabled:e||t!==null,children:[(0,$.jsx)(Kt,{className:`mr-1.5 h-3.5 w-3.5`}),` `,e?`Beautifying`:`Beautify`]}),(0,$.jsxs)(W,{size:`sm`,variant:`outline`,onClick:r,disabled:t!==null,title:`Explain selection or current statement without executing it`,children:[(0,$.jsx)(pt,{className:`mr-1.5 h-3.5 w-3.5`}),` Explain`]}),(0,$.jsxs)(W,{size:`sm`,variant:t?`destructive`:`default`,title:`Run selection or current statement (Cmd/Ctrl+Enter)`,onClick:t?a:i,children:[t?(0,$.jsx)(dt,{className:`mr-1.5 h-3.5 w-3.5`}):(0,$.jsx)(St,{className:`mr-1.5 h-3.5 w-3.5`}),t?`Stop`:`Run`]})]})}var Gs={tabs:[],activeKey:``},Ks=new Map,qs=e=>Ks.get(e),Js=(e,t)=>(Ks.set(e,t),t),Ys=e=>({key:crypto.randomUUID(),id:null,groupName:`Ungrouped`,name:`New SQL Query`,script:`SELECT *\nFROM ${e||``}`,result:null,resultPage:1,error:null}),Xs=e=>e.replace(/\s+/g,` `).replace(/\s*,\s*/g,`,
|
|
104
|
+
`).replace(/\s+(SELECT|FROM|WHERE|LEFT JOIN|RIGHT JOIN|INNER JOIN|JOIN|GROUP BY|ORDER BY|HAVING|LIMIT|OFFSET|VALUES|SET)\b/gi,`
|
|
105
|
+
$1`).replace(/\b(SELECT|FROM|WHERE|LEFT JOIN|RIGHT JOIN|INNER JOIN|JOIN|GROUP BY|ORDER BY|HAVING|LIMIT|OFFSET|VALUES|SET|AND|OR|ON|AS)\b/gi,e=>e.toUpperCase()).trim(),Zs=e=>{let t=[],n=0;for(;n<e.length;){let r=e[n];if(r===`'`||r===`"`||r==="`")for(n+=1;n<e.length;)if(e[n]===`\\`&&r!=="`")n+=2;else{if(e[n]===r){if(e[n+1]===r){n+=2;continue}break}n+=1}else if(r===`-`&&e[n+1]===`-`){let t=e.indexOf(`
|
|
106
|
+
`,n);n=t===-1?e.length:t;continue}else if(r===`/`&&e[n+1]===`*`){let t=e.indexOf(`*/`,n+2);n=t===-1?e.length:t+1}else r===`;`&&t.push(n);n+=1}return t},Qs=(e,t,n)=>{let r=e.slice(t,n).trim();if(r)return r;let i=Zs(e),a=e=>[...i].reverse().find(t=>t<=e)??-1,o=a(Math.max(0,t-1))+1,s=i.find(e=>e>=t)??-1,c=e.slice(o,s===-1?void 0:s).trim();if(c)return c;let l=Math.max(0,o-1),u=a(Math.max(0,l-1))+1;return e.slice(u,l).trim()||e.trim()},$s=(e,t)=>{if(!e)return t;let{from:n,to:r}=e.state.selection.main;return Qs(e.state.doc.toString(),n,r)},ec=(e,t)=>e&&t?.key===e.key?{...e,script:t.script}:e,tc=e=>{try{let t=JSON.parse(sessionStorage.getItem(e)||`{}`),n=Array.isArray(t.tabs)?t.tabs.filter(e=>e?.key).map(e=>({...e,result:null,resultPage:1,error:null})):[];if(n.length)return{tabs:n,activeKey:n.some(e=>e.key===t.activeKey)?t.activeKey:n[0].key}}catch{}return Gs},nc=e=>{let t=Array.isArray(e?.tabs)?e.tabs.filter(e=>e?.key).map(e=>({...e,result:null,resultPage:e.resultPage||1,error:null})):[];return t.length?{tabs:t,activeKey:t.some(t=>t.key===e.activeKey)?e.activeKey:t[0].key}:null},rc=[`SELECT`,`FROM`,`WHERE`,`JOIN`,`LEFT JOIN`,`INNER JOIN`,`GROUP BY`,`ORDER BY`,`LIMIT`,`OFFSET`,`ON`,`AS`,`AND`,`OR`,`COUNT`,`SUM`,`AVG`,`MIN`,`MAX`],ic=new Set([...rc,`LEFT`,`RIGHT`,`FULL`,`CROSS`,`OUTER`,`HAVING`,`SET`,`VALUES`].map(e=>e.split(` `)[0])),ac=[...ic,`UPDATE`,`INTO`,`UNION`].join(`|`),oc=RegExp(`\\b(?:from|join|update|into)\\s+((?:"[^"]+"|\`[^\`]+\`|\\[[^\\]]+\\]|[\\w$]+)(?:\\s*\\.\\s*(?:"[^"]+"|\`[^\`]+\`|\\[[^\\]]+\\]|[\\w$]+))?)(?:\\s+(?:as\\s+)?((?!(?:${ac})\\b)[a-z_$][\\w$]*))?`,`gi`);function sc(e){return e.split(`.`).map(e=>e.trim().replace(/^["`\[]|["`\]]$/g,``)).join(`.`)}function cc(e,t){let n=e.lastIndexOf(`;`,Math.max(0,t-1))+1,r=e.indexOf(`;`,t);return e.slice(n,r===-1?void 0:r)}function lc(e,t){let n=new Map;for(let e of t)n.set(e.table_name.toLowerCase(),e),n.set(e.table_name.split(`.`).at(-1).toLowerCase(),e);let r=[];for(let t of e.matchAll(oc)){let e=sc(t[1]),i=n.get(e.toLowerCase())||n.get(e.split(`.`).at(-1).toLowerCase());if(!i)continue;let a=sc(t[2]||``),o=a&&!ic.has(a.toUpperCase())?a:i.table_name;r.some(e=>e.table===i&&e.qualifier===o)||r.push({table:i,qualifier:o})}return r}function uc(e,t){let n=new Map(t.map(e=>[e.table_name.toLowerCase(),e])),r=new Map;for(let{table:t,qualifier:i}of e)for(let e of t.foreign_keys||[]){let t=n.get(e.ref_table.toLowerCase())?.table_name||e.ref_table;r.set(t.toLowerCase(),{label:t,type:`class`,detail:`${i}.${e.column} = ${t}.${e.ref_column}`,apply:`${t} ON ${i}.${e.column} = ${t}.${e.ref_column}`,boost:10})}return[...r.values()]}function dc(e){let t=e.map(e=>({label:e.table_name,type:`class`,detail:`table`})),n=rc.map(e=>({label:e,type:`keyword`})),r=``,i=n;return a=>{let o=a.matchBefore(/[\w.]+$/);if(!a.explicit&&!o)return null;let s=a.state.doc.toString(),c=s.lastIndexOf(`;`,Math.max(0,a.pos-1))+1,l=cc(s,a.pos),u=s.slice(s.lastIndexOf(`;`,Math.max(0,a.pos-1))+1,a.pos),d=/\b(?:from|join|update|into)\s+["`\[\]\w$.]*$/i.test(u),f=/\bjoin\s+["`\[\]\w$.]*$/i.test(u),p=o?.text||``,m=a.pos-c,h=Math.max(0,m-p.length),g=p&&l.slice(h,m)===p?l.slice(0,h)+l.slice(m):l,_=`${g}\0${d}\0${f}`;if(_!==r){r=_;let a=lc(g,e),o=a.flatMap(({table:e,qualifier:t})=>(e.columns||[]).map(n=>({label:`${t}.${n.name}`,type:`property`,detail:`${e.table_name} column`}))),s=a.map(({table:e})=>({label:e.table_name,type:`class`,detail:`referenced table`})),c=f?uc(a,e):[],l=new Set(c.map(e=>e.label.toLowerCase())),u=d?t.filter(e=>!l.has(e.label.toLowerCase())):s;i=[...n,...c,...u,...o]}return{from:o?.from??a.pos,options:i}}}function fc(e){let t=dc(e);return(e,n,r=24)=>{let i=e.slice(0,n).match(/[\w.]+$/);if(!i)return[];let a=t({explicit:!1,pos:n,state:{doc:{toString:()=>e}},matchBefore:()=>({from:n-i[0].length,to:n,text:i[0]})}),o=i[0].toLowerCase();return(a?.options||[]).filter(e=>e.label.toLowerCase().includes(o)).slice(0,r).map(e=>({label:e.label,detail:e.detail,type:e.type,apply:typeof e.apply==`string`?e.apply:void 0}))}}var pc=8,mc=176,hc=320;function gc({value:e,tables:t,resolvedTheme:n,editorRef:r,onChange:i,onRun:a,onBeautify:o}){let s=(0,Q.useMemo)(()=>fc(t),[t]),c=(0,Q.useMemo)(()=>({autocompletion:!1,lineNumbers:!0}),[]),l=(0,Q.useRef)(null),u=(0,Q.useRef)([]),d=(0,Q.useRef)(0),[f,p]=(0,Q.useState)([]),[m,h]=(0,Q.useState)(0),[g,_]=(0,Q.useState)({top:16,left:16});(0,Q.useEffect)(()=>{u.current=f},[f]),(0,Q.useEffect)(()=>{d.current=m},[m]);let v=(0,Q.useCallback)((e,t=u.current.length)=>{if(!t)return;let n=l.current,r=e.coordsAtPos(e.state.selection.main.head);if(!n||!r)return;let i=n.getBoundingClientRect(),a=Math.min(hc,Math.max(0,i.width-16)),o=Math.min(mc,t*30+8),s=Math.max(8,Math.min(r.left-i.left,i.width-a-8)),c=r.bottom-i.top+4,d=r.top-i.top-o-4,f=i.bottom-r.bottom>=o+8;_({left:s,top:f||r.top-i.top<=o+8?c:d})},[]),y=(0,Q.useCallback)(e=>{let t=r.current;if(!t)return;let n=t.state.selection.main.head,i=t.state.sliceDoc(0,n).match(/[\w.]+$/);if(!i)return;let a=e.apply||e.label,o=n-i[0].length;t.dispatch({changes:{from:o,to:n,insert:a},selection:{anchor:o+a.length}}),u.current=[],p([]),t.focus()},[r]),b=(0,Q.useCallback)((e,t)=>{i(e);let n=t.state.selection.main.head,r=s(e,n,pc);u.current=r,d.current=0,p(r),h(0),r.length&&v(t.view,r.length)},[i,s,v]),x=(0,Q.useCallback)(e=>{e.focusChanged&&!e.view.hasFocus?(u.current=[],p([])):u.current.length&&v(e.view)},[v]),S=(0,Q.useMemo)(()=>[En(),pn.highest(Mn.of([{key:`ArrowDown`,run:()=>{if(!u.current.length)return!1;let e=Math.min(d.current+1,u.current.length-1);return d.current=e,h(e),!0}},{key:`ArrowUp`,run:()=>{if(!u.current.length)return!1;let e=Math.max(d.current-1,0);return d.current=e,h(e),!0}},{key:`Escape`,run:()=>u.current.length?(u.current=[],p([]),!0):!1},{key:`Enter`,run:()=>{let e=u.current[d.current];return e?(y(e),!0):!1}},{key:`Tab`,run:()=>{let e=u.current[d.current];return e?(y(e),!0):!1}},{key:`Mod-Enter`,run:e=>(a($s(e,``)),!0)},{key:`Mod-i`,run:e=>(o(e.state.doc.toString()),!0)}]))],[y,o,a]);return(0,$.jsxs)(`div`,{ref:l,className:`relative h-full`,children:[(0,$.jsx)(Cn,{value:e,height:`100%`,theme:n===`dark`?xn:void 0,basicSetup:c,extensions:S,onCreateEditor:e=>{r.current=e},onChange:b,onUpdate:x,className:`h-full text-sm`}),f.length>0&&(0,$.jsx)(`div`,{role:`listbox`,"aria-label":`SQL suggestions`,style:{top:g.top,left:g.left},className:`absolute z-20 max-h-44 w-80 max-w-[calc(100%-1rem)] overflow-y-auto rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-lg`,children:f.map((e,t)=>(0,$.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":t===m,className:`flex w-full items-center justify-between gap-3 rounded px-2 py-1.5 text-left text-xs ${t===m?`bg-accent text-accent-foreground`:`hover:bg-accent/60`}`,onMouseDown:t=>{t.preventDefault(),y(e)},children:[(0,$.jsx)(`span`,{className:`truncate font-mono`,children:e.label}),(0,$.jsx)(`span`,{className:`shrink-0 text-[10px] text-muted-foreground`,children:e.detail||e.type})]},`${e.label}-${t}`))})]})}function _c({groups:e,history:t,activeQueryId:n,dirtyQueryIds:r,onOpenQuery:i,onOpenHistory:a}){return(0,$.jsxs)(`aside`,{className:`w-60 shrink-0 overflow-y-auto border-r bg-muted/10 p-2`,children:[(0,$.jsx)(`div`,{className:`mb-2 text-xs font-semibold text-muted-foreground`,children:`Saved Queries`}),(0,$.jsxs)(`div`,{className:`space-y-3`,children:[e.map(([e,t])=>(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{className:`mb-1 truncate text-xs font-medium`,children:e}),t.map(e=>(0,$.jsxs)(`button`,{onClick:()=>i(e),className:`flex w-full items-center rounded px-2 py-1.5 text-left text-xs ${n===e.id?`bg-accent`:`hover:bg-accent/50`}`,children:[(0,$.jsx)(`span`,{className:`truncate`,children:e.name}),r.has(e.id)&&(0,$.jsx)(`span`,{className:`ml-1 h-1.5 w-1.5 rounded-full bg-amber-500`})]},e.id))]},e)),e.length===0&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`No saved queries`})]}),(0,$.jsx)(`div`,{className:`mb-2 mt-5 text-xs font-semibold text-muted-foreground`,children:`Execution History`}),(0,$.jsxs)(`div`,{className:`space-y-1`,children:[t.map(e=>(0,$.jsxs)(`button`,{onClick:()=>a(e),className:`w-full rounded px-2 py-1.5 text-left hover:bg-accent/50`,children:[(0,$.jsx)(`div`,{className:`truncate font-mono text-[11px]`,children:e.script.replace(/\s+/g,` `)}),(0,$.jsxs)(`div`,{className:`text-[10px] ${e.status===`success`?`text-emerald-600`:`text-destructive`}`,children:[e.mode||`run`,` · `,e.status,` · `,e.durationMs,`ms`]})]},e.id)),t.length===0&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`No executions yet`})]})]})}var vc=`sql_query_tabs`,yc=(e,t)=>!t||e.groupName!==(t.groupName||`Ungrouped`)||e.name!==(t.name||`SQL Query`)||e.script!==(t.script||``),bc=(0,Q.memo)(function({connectionId:e,dbClientId:t,initialTable:n,openNonce:r=0}){let{resolvedTheme:a}=tr(),o=Le(),s=`db-client-query-tabs:${t}:${e}`,c=`${t}:${e}`,[l,u]=(0,Q.useState)([]),[d,f]=(0,Q.useState)([]),[p,m]=(0,Q.useState)(!1),[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(()=>tc(s)),y=(0,Q.useRef)(_),{tabs:b,activeKey:x}=_,S=b.find(e=>e.key===x)||b[0]||null,[C,w]=(0,Q.useState)(null),[T,E]=(0,Q.useState)(null),[D,O]=(0,Q.useState)(null),[k,A]=(0,Q.useState)(null),[ee,j]=(0,Q.useState)(()=>{try{return JSON.parse(localStorage.getItem(`erd-db-query-history:${e}`)||`[]`)}catch{return[]}}),M=(0,Q.useRef)(null),N=(0,Q.useRef)(null),P=(0,Q.useRef)(null),[F,te]=(0,Q.useState)(!1),[I,ne]=(0,Q.useState)(!1),L=(0,Q.useRef)(S),re=(0,Q.useRef)(null),R=(0,Q.useRef)(null),z=(0,Q.useRef)(!1),B=(0,Q.useMemo)(()=>{let e=new Map;for(let t of d){let n=t.groupName||`Ungrouped`;e.set(n,[...e.get(n)||[],t])}return[...e.entries()]},[d]),V=(0,Q.useMemo)(()=>new Map(d.map(e=>[e.id,e])),[d]),ie=(0,Q.useMemo)(()=>new Set(b.flatMap(e=>e.id!==null&&yc(e,V.get(e.id))?[e.id]:[])),[V,b]),H=(0,Q.useCallback)(async()=>{m(!1);let n=Tr(e),r=qs(c),[i,a]=await Promise.all([n?null:cn(`/api/catalogs/${e}/schema`,{method:`POST`}),r?null:cn(`/api/catalogs/${e}/queries?dbClientId=${t}`)]),o=n||await i.json(),s=r?{queries:r}:await a.json();if(i&&!i.ok)throw Error(o.error||`Failed to load schema`);if(a&&!a.ok)throw Error(s.error||`Failed to load SQL queries`);n||Er(e,o),r||Js(c,s.queries||[]),u(o.schema||[]),E(o.dbType||null),O(o.connectionSecurity||null),f(s.queries||[]),m(!0)},[e,t,c]);(0,Q.useEffect)(()=>{let e=setTimeout(()=>{H().catch(e=>w(e.message))});return()=>clearTimeout(e)},[H]),(0,Q.useEffect)(()=>{y.current=_},[_]),(0,Q.useEffect)(()=>{L.current=ec(S,L.current)},[S]),(0,Q.useEffect)(()=>{let e=setTimeout(()=>{o({aiContextText:Is(T,S,l)})},300);return()=>clearTimeout(e)},[S,T,o,l]),(0,Q.useEffect)(()=>()=>o(null),[o]),(0,Q.useEffect)(()=>{let e=!1;return z.current=!1,g(!1),er.getResource(s).then(t=>{if(e||z.current)return;let n=nc(t?.data);v(n||tc(s))}).catch(()=>{!e&&!z.current&&v(tc(s))}).finally(()=>{e||g(!0)}),()=>{e=!0}},[s]),(0,Q.useEffect)(()=>{if(h)return re.current&&clearTimeout(re.current),re.current=setTimeout(()=>{try{sessionStorage.setItem(s,JSON.stringify({tabs:b.map(e=>({...e,result:null,error:null})),activeKey:x})),er.saveResource({id:s,type:vc,data:{tabs:b.map(e=>({...e,result:null,error:null})),activeKey:x},updated_at:Date.now()}).catch(()=>{})}catch{}},400),()=>{re.current&&clearTimeout(re.current)}},[x,h,s,b]),(0,Q.useEffect)(()=>()=>{if(R.current!==null&&cancelAnimationFrame(R.current),z.current){let e=y.current,t={tabs:e.tabs.map(e=>({...e,result:null,error:null})),activeKey:e.activeKey};try{sessionStorage.setItem(s,JSON.stringify(t))}catch{}er.saveResource({id:s,type:vc,data:t,updated_at:Date.now()}).catch(()=>{})}},[s]);let U=(0,Q.useCallback)((e,t)=>{t.script!==void 0&&L.current?.key===e&&(L.current={...L.current,...t}),v(n=>{let r={...n,tabs:n.tabs.map(n=>n.key===e?{...n,...t}:n)};return y.current=r,r})},[]),ae=e=>{x&&U(x,e)},oe=(0,Q.useCallback)(e=>{let t=L.current;t&&(z.current=!0,U(t.key,{script:e}))},[U]),se=(0,Q.useCallback)(e=>{let t=Ys(e);v(e=>({tabs:[...e.tabs,t],activeKey:t.key}))},[]),ce=e=>{let t=b.find(t=>t.id===e.id);if(t)return v(e=>({...e,activeKey:t.key}));let n={key:crypto.randomUUID(),id:e.id,groupName:e.groupName||`Ungrouped`,name:e.name||`SQL Query`,script:e.script||``,result:null,resultPage:1,error:null};v(e=>({tabs:[...e.tabs,n],activeKey:n.key}))},le=e=>{v(t=>{let n=t.tabs.filter(t=>t.key!==e);return n.length?{tabs:n,activeKey:t.activeKey===e?n.at(-1).key:t.activeKey}:Gs})};(0,Q.useEffect)(()=>{if(r<=0)return;let e=`${s}:openNonce`;sessionStorage.getItem(e)!==String(r)&&(sessionStorage.setItem(e,String(r)),se(n))},[r,n,se,s]),(0,Q.useEffect)(()=>{h&&p&&d.length===0&&b.length===0&&se(n)},[se,h,n,d.length,p,b.length]);let ue=async()=>{let n=L.current;if(!n)return;let r=await cn(`/api/catalogs/${e}/queries`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:n.id,dbClientId:t,groupName:n.groupName,name:n.name,script:n.script})}),a=await r.json();if(!r.ok)throw Error(a.error||`Failed to save SQL query`);U(n.key,{id:a.query.id}),f(e=>Js(c,[...e.filter(e=>e.id!==a.query.id),a.query])),i.success(`SQL query saved`)},de=async()=>{if(!S?.id)return;let n=await cn(`/api/catalogs/${e}/queries/${S.id}?dbClientId=${t}`,{method:`DELETE`}),r=await n.json();if(!n.ok)throw Error(r.error||`Failed to delete SQL query`);f(e=>Js(c,e.filter(e=>e.id!==S.id))),v(e=>{let t=e.tabs.filter(e=>e.id!==S.id);return t.length?{tabs:t,activeKey:t.at(-1).key}:Gs}),i.success(`SQL query deleted`)},fe=(0,Q.useCallback)(async(t,n)=>{let r=L.current;if(!r)return;let i=n??r.script;if(M.current)return;let a=crypto.randomUUID();M.current=a,A(t);let o=Date.now(),s=`success`;U(r.key,{error:null});try{let n=await cn(`/api/catalogs/${e}/query/run`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({script:i,runId:a,mode:t,...t===`run`?{maxRows:200}:{}})}),o=await n.json();if(!n.ok)throw Error(o.error||`Failed to run SQL query`);U(r.key,{result:o,resultPage:1})}catch(e){s=N.current===a?`cancelled`:`error`,U(r.key,{error:s===`cancelled`?`Query cancelled`:e.message})}finally{let n={id:a,script:i,mode:t,status:s,durationMs:Date.now()-o,executedAt:new Date().toISOString()};j(t=>{let r=[n,...t].slice(0,100);try{localStorage.setItem(`erd-db-query-history:${e}`,JSON.stringify(r))}catch{}return r}),M.current===a&&(M.current=null,A(null)),N.current===a&&(N.current=null)}},[e,U]),pe=(0,Q.useCallback)(e=>fe(`run`,e),[fe]),me=(0,Q.useCallback)(e=>fe(`explain`,e),[fe]),ge=(0,Q.useCallback)(async()=>{let t=M.current;if(t&&N.current!==t){N.current=t;try{let n=await cn(`/api/catalogs/${e}/query/cancel/${t}`,{method:`POST`});if(!n.ok&&n.status!==404)throw Error((await n.json().catch(()=>({}))).error||`HTTP ${n.status}`)}catch(e){N.current===t&&(N.current=null),i.error(`Could not stop the query: ${e instanceof Error?e.message:`network error`}`)}}},[e]),_e=(0,Q.useCallback)(e=>{let t=L.current;if(!t)return;let n=e??t.script;R.current!==null&&cancelAnimationFrame(R.current),te(!0),R.current=requestAnimationFrame(()=>{let e=Xs(n);(0,Q.startTransition)(()=>{e!==n&&U(t.key,{script:e}),te(!1)})})},[U]),G=()=>{let e=L.current;return e?$s(P.current,e.script):``};return(0,$.jsxs)(`div`,{className:`flex min-h-0 flex-1 overflow-hidden`,children:[(0,$.jsx)(_c,{groups:B,history:ee,activeQueryId:S?.id||null,dirtyQueryIds:ie,onOpenQuery:ce,onOpenHistory:e=>ae({script:e.script})}),(0,$.jsxs)(`main`,{className:`grid min-h-0 min-w-0 flex-1 grid-rows-[auto_auto_minmax(120px,30%)_minmax(0,1fr)] overflow-hidden`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1 overflow-x-auto border-b bg-muted/10 px-2 py-1`,children:[b.map(e=>(0,$.jsxs)(`button`,{onClick:()=>v(t=>({...t,activeKey:e.key})),className:`group flex h-8 max-w-48 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs font-medium ${x===e.key?`bg-background text-foreground shadow-sm`:`text-muted-foreground hover:bg-accent hover:text-accent-foreground`}`,children:[(0,$.jsx)(`span`,{className:`truncate`,children:e.name}),yc(e,e.id?V.get(e.id):void 0)&&(0,$.jsx)(`span`,{className:`h-1.5 w-1.5 shrink-0 rounded-full bg-amber-500`,title:`Not synced to database`}),(0,$.jsx)(`span`,{role:`button`,tabIndex:0,onClick:t=>{t.stopPropagation(),le(e.key)},className:`ml-1 rounded p-0.5 opacity-60 hover:bg-muted hover:opacity-100`,title:`Close query`,children:(0,$.jsx)(It,{className:`h-3 w-3`})})]},e.key)),(0,$.jsx)(W,{size:`icon-sm`,variant:`ghost`,className:`h-8 w-8 shrink-0`,onClick:()=>se(n),title:`New SQL query`,children:(0,$.jsx)(he,{className:`h-4 w-4`})})]}),S?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Us,{groupName:S.groupName,name:S.name,result:S.result,onGroupChange:e=>ae({groupName:e}),onNameChange:e=>ae({name:e}),onDelete:S.id?()=>ne(!0):void 0,onSave:()=>ue().catch(e=>i.error(e.message)),security:D}),(0,$.jsx)(`div`,{className:`min-h-0 overflow-hidden`,children:(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,$.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,$.jsx)(gc,{editorRef:P,value:ec(S,L.current)?.script||``,tables:l,resolvedTheme:a,onChange:oe,onRun:pe,onBeautify:_e},S.key)}),(0,$.jsx)(Ws,{beautifying:F,runningMode:k,onBeautify:()=>_e(),onStop:()=>void ge(),onExplain:()=>me(G()),onRun:()=>pe(G())})]})})]}):(0,$.jsx)(`div`,{className:`min-h-0 border-b p-3 text-sm text-muted-foreground`,children:`No SQL query tab open`}),(0,$.jsx)(`div`,{className:`min-h-0 overflow-hidden border-t`,children:(0,$.jsx)(Hs,{emptyText:S?`Run a query to view results`:`Open or create a SQL query`,error:C||S?.error||null,result:S?.result||null,resultPage:S?.resultPage||1,onPageChange:e=>S&&U(S.key,{resultPage:e})})})]}),(0,$.jsx)(ut,{isOpen:I,title:`Delete SQL Query?`,message:`This will permanently delete "${S?.name||`SQL Query`}". This action cannot be undone.`,confirmText:`Delete Query`,variant:`danger`,onCancel:()=>ne(!1),onConfirm:()=>{ne(!1),de().catch(e=>i.error(e.message))}})]})}),xc=[{value:`data`,label:`Data`,icon:gt},{value:`erd`,label:`ERD`,icon:vt},{value:`query`,label:`Query`,icon:nt}];function Sc({dbType:e}){return e?(0,$.jsx)(fr,{className:e===`mysql`?`bg-green-50 text-green-700 dark:bg-green-950 dark:text-green-300`:e===`postgresql`?`bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300`:e===`sqlite`?`bg-yellow-50 text-yellow-700 dark:bg-yellow-950 dark:text-yellow-300`:`bg-muted text-muted-foreground`,children:e===`postgresql`?`PG`:e===`mysql`?`MySQL`:e===`sqlite`?`SQLite`:e}):null}function Cc({activeMode:e,dbType:t,onModeChange:n}){return(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3 px-3 py-1.5 border-b bg-muted/5 shrink-0`,children:[(0,$.jsx)(`div`,{className:`flex items-center gap-1`,children:xc.map(({value:t,label:r,icon:i})=>(0,$.jsxs)(`button`,{onClick:()=>n(t),className:o(`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors`,e===t?`bg-accent text-accent-foreground shadow-sm`:`text-muted-foreground hover:text-foreground hover:bg-accent/50`),children:[(0,$.jsx)(i,{className:`w-3.5 h-3.5`}),r]},t))}),e===`data`&&(0,$.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(Sc,{dbType:t}),(0,$.jsx)(W,{variant:`ghost`,size:`icon-sm`,onClick:()=>window.dispatchEvent(new Event(`db-connect-refresh-records`)),title:`Refresh records`,children:(0,$.jsx)(Y,{className:`h-4 w-4`})}),(0,$.jsx)(W,{variant:`ghost`,size:`icon-sm`,onClick:()=>window.dispatchEvent(new Event(`db-connect-toggle-filters`)),title:`Toggle record filters`,children:(0,$.jsx)(Gt,{className:`h-4 w-4`})}),(0,$.jsx)(W,{variant:`ghost`,size:`icon-sm`,onClick:()=>window.dispatchEvent(new Event(`db-connect-toggle-details`)),title:`Toggle record panel`,children:(0,$.jsx)(wt,{className:`h-4 w-4`})})]})]})}export{Tr as a,yr as c,Ma as i,bc as n,Er as o,Ls as r,br as s,Cc as t};
|