db-studio 2.1.0 → 2.2.1
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/index.js +69 -69
- package/dist/index.js.map +1 -1
- package/dist/web-dist/assets/_pathlessLayout-1KXlcJn5.js +1 -0
- package/dist/web-dist/assets/_pathlessLayout-D4dS7_ZZ.js +2 -0
- package/dist/web-dist/assets/_queryId-DfjPCkx7.js +1 -0
- package/dist/web-dist/assets/_table-ChX0JQnV.js +1 -0
- package/dist/web-dist/assets/{_table-BUNHOVIK.js → _table-DQvTfc38.js} +1 -1
- package/dist/web-dist/assets/_table-M7xRcFSl.js +1 -0
- package/dist/web-dist/assets/{abap-B-HzHdT_.js → abap-DYZIj1QT.js} +1 -1
- package/dist/web-dist/assets/{apex-t5VcK3BF.js → apex-CaiB2cHW.js} +1 -1
- package/dist/web-dist/assets/{azcli-Ce3iuV2p.js → azcli-BSMSllBA.js} +1 -1
- package/dist/web-dist/assets/{badge-COF6gx-2.js → badge-DAJ-55CZ.js} +1 -1
- package/dist/web-dist/assets/{bat-bOBZcLbK.js → bat-DslF3aSP.js} +1 -1
- package/dist/web-dist/assets/{bicep-TSicgsnM.js → bicep-BaONjKcy.js} +1 -1
- package/dist/web-dist/assets/{browser-B-fV6CZb.js → browser-BXjW1U6_.js} +1 -1
- package/dist/web-dist/assets/bundle-mjs-DGKUXiQC.js +1 -0
- package/dist/web-dist/assets/{cameligo-D-9xpPXV.js → cameligo-B-VCpHXR.js} +1 -1
- package/dist/web-dist/assets/chat-sidebar-DhhMmf_h.js +161 -0
- package/dist/web-dist/assets/{clojure-9X3x3csE.js → clojure-CQdNGvuT.js} +1 -1
- package/dist/web-dist/assets/{code-editor-tPwHd3zF.js → code-editor-B9_5weuZ.js} +2 -2
- package/dist/web-dist/assets/{codicon-Brq4_Ui5.ttf → codicon-DF1abBS2.ttf} +0 -0
- package/dist/web-dist/assets/{coffee-anOch8Z-.js → coffee-GJxdv8v9.js} +1 -1
- package/dist/web-dist/assets/connect-CCHOGwiQ.js +1 -0
- package/dist/web-dist/assets/constants-CJqw7w68.js +20 -0
- package/dist/web-dist/assets/{cpp-oW293AoF.js → cpp-bdOuYgjm.js} +1 -1
- package/dist/web-dist/assets/{csharp-BOXMgm5k.js → csharp-DtT4S3qG.js} +1 -1
- package/dist/web-dist/assets/{csp-D67JhNKT.js → csp-DcT8MidV.js} +1 -1
- package/dist/web-dist/assets/{css-Bk6H7_K_.js → css-aK0ks7hY.js} +1 -1
- package/dist/web-dist/assets/{css.worker-B-fFSVTK.js → css.worker-bHD0dlJO.js} +1507 -1453
- package/dist/web-dist/assets/cssMode-5aGt4Xk4.js +1 -0
- package/dist/web-dist/assets/{cypher-DB0LBjic.js → cypher-gkqrqdhb.js} +1 -1
- package/dist/web-dist/assets/{dart-CS3MbwLP.js → dart-D55faCn9.js} +1 -1
- package/dist/web-dist/assets/database.store-BOgNcBMG.js +57 -0
- package/dist/web-dist/assets/dist-BA0_BdMR.js +1 -0
- package/dist/web-dist/assets/dist-DAuUtATJ.js +2 -0
- package/dist/web-dist/assets/{dockerfile-BGz3qsmk.js → dockerfile-CsHs8WRI.js} +1 -1
- package/dist/web-dist/assets/{ecl-lt3qcklx.js → ecl-CQKiIf56.js} +1 -1
- package/dist/web-dist/assets/editor-g1MJRkXV.css +1 -0
- package/dist/web-dist/assets/editor.api-BZk1XbZs.js +926 -0
- package/dist/web-dist/assets/{editor.worker-BYfbSb3U.js → editor.worker-ByY_fgkM.js} +1328 -1274
- package/dist/web-dist/assets/{elixir-cMyUafed.js → elixir-CfFxQLCK.js} +1 -1
- package/dist/web-dist/assets/esm-BhcGPxbM.js +1 -0
- package/dist/web-dist/assets/{esm-B-4Q6MuQ.js → esm-C1Qg-CCP.js} +1 -1
- package/dist/web-dist/assets/{flow9-BI9V6TuS.js → flow9-CLkaJU-U.js} +1 -1
- package/dist/web-dist/assets/format-cell-value-BcH_SExw.js +1 -0
- package/dist/web-dist/assets/{freemarker2-mnCFA3xV.js → freemarker2-Dbf5KAvd.js} +2 -2
- package/dist/web-dist/assets/{fsharp-I1kqnt0E.js → fsharp-4RCsDl1X.js} +1 -1
- package/dist/web-dist/assets/{go-Cg4qMFVj.js → go-BCuLk40y.js} +1 -1
- package/dist/web-dist/assets/{graphql-CvtHcP49.js → graphql-Cuc1fjZl.js} +1 -1
- package/dist/web-dist/assets/{handlebars-BUcE6Uyy.js → handlebars-Bc8nHcpq.js} +1 -1
- package/dist/web-dist/assets/{hcl-BkvCdKNu.js → hcl-BqquCvZs.js} +1 -1
- package/dist/web-dist/assets/highlighted-body-JLMTFACH-Q1Yc-gaw.js +1 -0
- package/dist/web-dist/assets/{html-BBqcfykD.js → html-ZcQmh2HM.js} +1 -1
- package/dist/web-dist/assets/{html.worker-CdalOg9p.js → html.worker-CHVREBCJ.js} +1527 -1473
- package/dist/web-dist/assets/{htmlMode-D8je66Rk.js → htmlMode-BkwHscgL.js} +1 -1
- package/dist/web-dist/assets/icons-IBpZgbE4.js +1 -0
- package/dist/web-dist/assets/index-DTVRtzpz.css +2 -0
- package/dist/web-dist/assets/index-DfnmlclA.js +34 -0
- package/dist/web-dist/assets/indexes-DUzB2YOr.js +1 -0
- package/dist/web-dist/assets/{ini-CPc8BCWu.js → ini-DK3PnweE.js} +1 -1
- package/dist/web-dist/assets/{java-C9Yie4SH.js → java-CCKilWzS.js} +1 -1
- package/dist/web-dist/assets/{javascript-CuGq5ydO.js → javascript-Cy_Mv9Jz.js} +1 -1
- package/dist/web-dist/assets/{json-editor-Dc1E8Fc-.js → json-editor-CE8bI5n-.js} +1 -1
- package/dist/web-dist/assets/{json.worker-DI02pyM8.js → json.worker-BKCy_srb.js} +2747 -2693
- package/dist/web-dist/assets/{jsonMode-BgdTmYik.js → jsonMode-wvGZQK-h.js} +4 -4
- package/dist/web-dist/assets/{julia--qJGRfN8.js → julia-yMXHdeoG.js} +1 -1
- package/dist/web-dist/assets/{keys-Bs0DRbCB.js → keys-B1bnQf8h.js} +1 -1
- package/dist/web-dist/assets/{kotlin-C3MSe-0N.js → kotlin-BbY6gpqm.js} +1 -1
- package/dist/web-dist/assets/{label-DzHJlGAx.js → label-B5lrF5vb.js} +1 -1
- package/dist/web-dist/assets/{less-DOBYgWSY.js → less-rp9k6ONg.js} +1 -1
- package/dist/web-dist/assets/{lexon-Djd2rGvJ.js → lexon-rRyNfudJ.js} +1 -1
- package/dist/web-dist/assets/{liquid-DXfHmR66.js → liquid-TDvflZF7.js} +1 -1
- package/dist/web-dist/assets/{logs-BortjBc-.js → logs-C2iyjCnP.js} +1 -1
- package/dist/web-dist/assets/{lspLanguageFeatures-C7-iyD6G.js → lspLanguageFeatures-DkWvqpF_.js} +1 -1
- package/dist/web-dist/assets/{lua-Ck8vNcPw.js → lua-DInTck7-.js} +1 -1
- package/dist/web-dist/assets/{m3-a6Kl4TV0.js → m3-D1zMDYBU.js} +1 -1
- package/dist/web-dist/assets/{markdown-DkcRBwO0.js → markdown-DTHzen51.js} +1 -1
- package/dist/web-dist/assets/{mdx-QI5o45qz.js → mdx-D9pd4Hjw.js} +1 -1
- package/dist/web-dist/assets/mermaid-WFAXDIZX-B2YMTdfH.js +1 -0
- package/dist/web-dist/assets/middleware-gB5jp1rF.js +1 -0
- package/dist/web-dist/assets/{mips-Cc1YVI2p.js → mips-7Slzy87X.js} +1 -1
- package/dist/web-dist/assets/module-BHjgyYxe.js +3 -0
- package/dist/web-dist/assets/monaco-theme-CFrVB-OG.js +68 -0
- package/dist/web-dist/assets/monaco-theme-DtsiNm_H.css +1 -0
- package/dist/web-dist/assets/{msdax-Bh41xUoQ.js → msdax-CVw_oFJe.js} +1 -1
- package/dist/web-dist/assets/{mysql-BZTZMxPa.js → mysql-92xfRPFN.js} +1 -1
- package/dist/web-dist/assets/{objective-c-CxZIMOHQ.js → objective-c-BXnCggXS.js} +1 -1
- package/dist/web-dist/assets/{overlay.store-DsUdwZjE.js → overlay.store-wgNV6JkK.js} +1 -1
- package/dist/web-dist/assets/{pascal-I-WmLkmD.js → pascal-3fByeJdZ.js} +1 -1
- package/dist/web-dist/assets/{pascaligo-DEZ-6bwf.js → pascaligo-BdC4YsoB.js} +1 -1
- package/dist/web-dist/assets/{perl-DfeHQJxJ.js → perl-ClTLOqGp.js} +1 -1
- package/dist/web-dist/assets/{personal-preferences.store-DXSnKmVN.js → personal-preferences.store-dG5rDcRw.js} +1 -1
- package/dist/web-dist/assets/{pgsql-OdOoQYPW.js → pgsql-DEzB6Ucu.js} +1 -1
- package/dist/web-dist/assets/{php-CF1bUutw.js → php-DVFKZpKp.js} +1 -1
- package/dist/web-dist/assets/{pla-BHZr0GrY.js → pla-0ER0Ntvs.js} +1 -1
- package/dist/web-dist/assets/{postiats-BSB6a63H.js → postiats-CEuE_fTP.js} +1 -1
- package/dist/web-dist/assets/{powerquery-Bu0p84Ye.js → powerquery-IX0j-GcX.js} +1 -1
- package/dist/web-dist/assets/{powershell-Dcq3YM6T.js → powershell-PrZfSRSf.js} +1 -1
- package/dist/web-dist/assets/preload-helper-Bpqt02Xx.js +1 -0
- package/dist/web-dist/assets/{protobuf-CsWrQxqX.js → protobuf-CCWom7A4.js} +1 -1
- package/dist/web-dist/assets/{pug-DLQiv3Bp.js → pug-B-mwU8C7.js} +1 -1
- package/dist/web-dist/assets/{python-BvKEpyP9.js → python-B-RGw6sh.js} +1 -1
- package/dist/web-dist/assets/{qsharp-D8nrRUNu.js → qsharp-zXtiGbGZ.js} +1 -1
- package/dist/web-dist/assets/{queries.store-BaeyNA64.js → queries.store-CL_QZ9kV.js} +1 -1
- package/dist/web-dist/assets/query-runner-__vttAd8.js +17 -0
- package/dist/web-dist/assets/{r-xhyKpGTk.js → r-ff7AzNUE.js} +1 -1
- package/dist/web-dist/assets/radix-ui-BLYTVDm9.js +41 -0
- package/dist/web-dist/assets/{razor-Ceb9S1Rz.js → razor-f0SZhWBH.js} +1 -1
- package/dist/web-dist/assets/react-Cuc8VqJk.js +1 -0
- package/dist/web-dist/assets/react-dom-Cx6AFOpM.js +9 -0
- package/dist/web-dist/assets/{redis-BnpkEvbr.js → redis-3WrJd2UX.js} +1 -1
- package/dist/web-dist/assets/{redis-value-DMk0-Zuc.js → redis-value-DvCMBdEM.js} +1 -1
- package/dist/web-dist/assets/{redshift-BpxVXjAI.js → redshift-BFFZqrqe.js} +1 -1
- package/dist/web-dist/assets/{restructuredtext-5afXtW7D.js → restructuredtext-BRpKlTYP.js} +1 -1
- package/dist/web-dist/assets/rolldown-runtime-v8MIZ6et.js +1 -0
- package/dist/web-dist/assets/{ruby-CHaoWUHT.js → ruby-Dik41UlM.js} +1 -1
- package/dist/web-dist/assets/runner-DIQss6Kz.js +1 -0
- package/dist/web-dist/assets/{rust-Bw0WVsLy.js → rust-DADSh0Pc.js} +1 -1
- package/dist/web-dist/assets/{sb-CEjXmIyG.js → sb-DuvpHrMN.js} +1 -1
- package/dist/web-dist/assets/{scala-BuaCSaU6.js → scala-CtuFqcla.js} +1 -1
- package/dist/web-dist/assets/schema-BqwkN_6u.js +1 -0
- package/dist/web-dist/assets/schema-qGsKd6zv.js +1 -0
- package/dist/web-dist/assets/{scheme-DIKzlmFG.js → scheme-hPwS1w0C.js} +1 -1
- package/dist/web-dist/assets/{scss-C2_UsWzg.js → scss-477oFtwU.js} +1 -1
- package/dist/web-dist/assets/{select-C-nrz7Tx.js → select-DDjmR6pO.js} +1 -1
- package/dist/web-dist/assets/{separator-DnB61XAO.js → separator-CGjaYtx-.js} +1 -1
- package/dist/web-dist/assets/{sheet-sidebar-BGxJGRbd.js → sheet-sidebar-Cde4bLIJ.js} +1 -1
- package/dist/web-dist/assets/{shell-2aEL2EVH.js → shell-n9PWT21s.js} +1 -1
- package/dist/web-dist/assets/{solidity-D-5XfYE1.js → solidity-BUjaJYHp.js} +1 -1
- package/dist/web-dist/assets/{sophia-s4MFSvUF.js → sophia-BCcvs9t1.js} +1 -1
- package/dist/web-dist/assets/{sparql-Dkv46wS5.js → sparql-BflQKwzI.js} +1 -1
- package/dist/web-dist/assets/spinner-ioIImnLq.js +1 -0
- package/dist/web-dist/assets/{sql-Dz9Xhs8s.js → sql-B-t7xHK1.js} +1 -1
- package/dist/web-dist/assets/{st-Cbo0XVmr.js → st-CSYG-jYM.js} +1 -1
- package/dist/web-dist/assets/{swift-B66X97nW.js → swift-CKmn3JdQ.js} +1 -1
- package/dist/web-dist/assets/{systemverilog-gGKga8Gf.js → systemverilog-rn_hwEIB.js} +1 -1
- package/dist/web-dist/assets/table-BWy367NZ.js +1 -0
- package/dist/web-dist/assets/tables-geLC-tRf.js +16 -0
- package/dist/web-dist/assets/tanstack-2cKzRGRb.js +5 -0
- package/dist/web-dist/assets/{tcl-BtbeJsUN.js → tcl-Fn2CV_28.js} +1 -1
- package/dist/web-dist/assets/{ts.worker-r_qbh1JO.js → ts.worker-BLC4EdqU.js} +18311 -18257
- package/dist/web-dist/assets/{tsMode-BgtcNcpl.js → tsMode-C-8HcC0f.js} +4 -4
- package/dist/web-dist/assets/{twig-0_nXiuYs.js → twig-CLjUHOwE.js} +1 -1
- package/dist/web-dist/assets/{typescript-Cy_CzC_-.js → typescript-BubYBQa0.js} +1 -1
- package/dist/web-dist/assets/{typespec-DBO6_WMJ.js → typespec-IO61FhU-.js} +1 -1
- package/dist/web-dist/assets/use-database-engine-C1fvJDyS.js +1 -0
- package/dist/web-dist/assets/{use-theme-DBhPknw6.js → use-theme-uud1RcFP.js} +1 -1
- package/dist/web-dist/assets/utils-D49oYrWW.js +1 -0
- package/dist/web-dist/assets/{vb-DFJjBsW2.js → vb-Lm9DdJMK.js} +1 -1
- package/dist/web-dist/assets/visualizer-Bd-PB2Fm.js +1 -0
- package/dist/web-dist/assets/{wgsl-U3RBM2M0.js → wgsl-CG8088eu.js} +1 -1
- package/dist/web-dist/assets/{workers-ClRH6A2w.js → workers-H_G6sPzI.js} +1 -1
- package/dist/web-dist/assets/{xml-D11j3J2_.js → xml-Da0DCKCb.js} +1 -1
- package/dist/web-dist/assets/{yaml-D7Z_4mnx.js → yaml-C-84Dbfu.js} +1 -1
- package/dist/web-dist/index.html +31 -31
- package/package.json +22 -22
- package/dist/web-dist/assets/_pathlessLayout-CUDS1e28.js +0 -1
- package/dist/web-dist/assets/_pathlessLayout-WZkezfN7.js +0 -2
- package/dist/web-dist/assets/_queryId-CEJb62Vl.js +0 -1
- package/dist/web-dist/assets/_table-6SZEx92j.js +0 -1
- package/dist/web-dist/assets/_table-CwyP_2EP.js +0 -1
- package/dist/web-dist/assets/bundle-mjs-CZwf2xtr.js +0 -1
- package/dist/web-dist/assets/chat-sidebar-DwzCElBd.js +0 -132
- package/dist/web-dist/assets/connect-l3LjAClZ.js +0 -1
- package/dist/web-dist/assets/constants-CKAehpPm.js +0 -12
- package/dist/web-dist/assets/cssMode-G6latsS7.js +0 -1
- package/dist/web-dist/assets/database.store-BuqVJMY6.js +0 -57
- package/dist/web-dist/assets/dist-Bz0qAN0x.js +0 -2
- package/dist/web-dist/assets/dist-Cf0L32Jd.js +0 -1
- package/dist/web-dist/assets/editor-1FQrmyyI.css +0 -1
- package/dist/web-dist/assets/editor.api-BTIrAcm5.js +0 -865
- package/dist/web-dist/assets/format-cell-value-CgUtYv8B.js +0 -1
- package/dist/web-dist/assets/highlighted-body-OFNGDK62-t8UIAZOZ.js +0 -1
- package/dist/web-dist/assets/icons-DxFtdMXW.js +0 -1
- package/dist/web-dist/assets/index-QVi4Lb9U.css +0 -2
- package/dist/web-dist/assets/index-WFVurGCI.js +0 -34
- package/dist/web-dist/assets/indexes-C3Qddb5L.js +0 -1
- package/dist/web-dist/assets/mermaid-GHXKKRXX-D35eppUc.js +0 -1
- package/dist/web-dist/assets/middleware-CXk7SlTF.js +0 -1
- package/dist/web-dist/assets/module-D_kjbMCc.js +0 -2
- package/dist/web-dist/assets/monaco-theme-BnSsSzUH.css +0 -1
- package/dist/web-dist/assets/monaco-theme-C2k_taVU.js +0 -64
- package/dist/web-dist/assets/preload-helper-DF7hIgef.js +0 -1
- package/dist/web-dist/assets/query-runner-f473QQSD.js +0 -17
- package/dist/web-dist/assets/radix-ui-CxCv--D1.js +0 -51
- package/dist/web-dist/assets/react-DEQ0BgTL.js +0 -1
- package/dist/web-dist/assets/react-dom-ITw3Lqwx.js +0 -9
- package/dist/web-dist/assets/rolldown-runtime-fzu9RN21.js +0 -1
- package/dist/web-dist/assets/runner-NsYjzIZs.js +0 -1
- package/dist/web-dist/assets/schema-CE1yGygf.js +0 -1
- package/dist/web-dist/assets/schema-rxLBue8Q.js +0 -1
- package/dist/web-dist/assets/spinner-CNnB5r0X.js +0 -1
- package/dist/web-dist/assets/table-C8WK3uAc.js +0 -1
- package/dist/web-dist/assets/tables-D98Kbmcb.js +0 -16
- package/dist/web-dist/assets/tanstack-RwHFfmqj.js +0 -8
- package/dist/web-dist/assets/use-database-engine-DZZj7-4J.js +0 -1
- package/dist/web-dist/assets/utils-EJLOIroS.js +0 -1
- package/dist/web-dist/assets/visualizer-CgYlDJ_-.js +0 -1
- package/dist/web-dist/assets/vscode-wuSgCuZI.js +0 -1
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/_pathlessLayout-D4dS7_ZZ.js","assets/rolldown-runtime-v8MIZ6et.js","assets/tanstack-2cKzRGRb.js","assets/icons-IBpZgbE4.js","assets/radix-ui-BLYTVDm9.js","assets/constants-CJqw7w68.js","assets/database.store-BOgNcBMG.js","assets/react-Cuc8VqJk.js","assets/preload-helper-Bpqt02Xx.js","assets/schema-qGsKd6zv.js","assets/badge-DAJ-55CZ.js","assets/utils-D49oYrWW.js","assets/bundle-mjs-DGKUXiQC.js","assets/overlay.store-wgNV6JkK.js","assets/label-B5lrF5vb.js","assets/sheet-sidebar-Cde4bLIJ.js","assets/use-database-engine-C1fvJDyS.js","assets/dist-BA0_BdMR.js","assets/keys-B1bnQf8h.js","assets/spinner-ioIImnLq.js","assets/format-cell-value-BcH_SExw.js","assets/use-theme-uud1RcFP.js","assets/personal-preferences.store-dG5rDcRw.js","assets/middleware-gB5jp1rF.js","assets/separator-CGjaYtx-.js","assets/dist-DAuUtATJ.js","assets/tables-geLC-tRf.js","assets/select-DDjmR6pO.js","assets/esm-BhcGPxbM.js","assets/queries.store-CL_QZ9kV.js","assets/redis-value-DvCMBdEM.js","assets/_pathlessLayout-1KXlcJn5.js","assets/browser-BXjW1U6_.js","assets/logs-C2iyjCnP.js","assets/visualizer-Bd-PB2Fm.js","assets/indexes-DUzB2YOr.js","assets/_table-DQvTfc38.js","assets/runner-DIQss6Kz.js","assets/query-runner-__vttAd8.js","assets/_queryId-DfjPCkx7.js","assets/schema-BqwkN_6u.js","assets/_table-M7xRcFSl.js","assets/table-BWy367NZ.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as wr,t as xl}from"./rolldown-runtime-v8MIZ6et.js";import{C as Ft,D as Wh,E as Xh,O as Qs,T as Qh,_ as Jh,b as Zh,c as ef,d as tf,f as Sl,g as Er,h as nf,m as we,p as Ee,s as Il,t as rf,u as sf,v as Js,w as zt,x as of}from"./tanstack-2cKzRGRb.js";import{A as af,At as lf,B as qo,D as Vo,Et as wl,Ft as cf,G as Zs,I as uf,It as df,K as hf,M as ff,N as pf,Nt as gf,O as mf,P as vf,R as eo,T as yf,Tt as bf,U as El,X as xf,at as Ko,b as Sf,c as If,ht as wf,i as Ef,j as Cf,k as Nf,m as Rf,mt as _f,n as Tf,ot as ws,p as Es,rt as Af,s as Mf,st as Xr,ut as kf,v as Of,vt as jf,w as Pf,wt as Lf,x as Cl,y as Df,z as $f,zt as Ff}from"./icons-IBpZgbE4.js";import{t as zf}from"./react-dom-Cx6AFOpM.js";import{n as he,t as Hf}from"./dist-BA0_BdMR.js";import{At as Bf,a as Gf,i as Uf,jt as qf,o as Vf}from"./radix-ui-BLYTVDm9.js";import{t as to}from"./spinner-ioIImnLq.js";import{i as Nl,n as ct,s as Kf,t as ut}from"./overlay.store-wgNV6JkK.js";import{a as Yf,c as Wf,i as Yo,l as Rl,n as _l,o as Xf,r as Qf,s as Tl}from"./dist-DAuUtATJ.js";import{A as Jf,B as se,D as Zf,E as Al,F as ep,H as rn,I as tp,L as Ml,M as np,N as qe,O as rp,P as Cr,R as it,T as sp,U as op,V as kl,a as ip,c as Ol,d as jl,f as ap,g as lp,h as Pl,i as cp,j as Cs,k as en,m as up,n as dp,o as hp,p as fp,r as pp,s as Ll,u as tr,v as gp,w as mp,z as Dl}from"./schema-qGsKd6zv.js";import{c as $l,f as Fl,g as Je,l as vp,m as yp,s as bp,u as xp}from"./tables-geLC-tRf.js";import{t as zl}from"./react-Cuc8VqJk.js";import{F as Sp,G as Hl,I as Ip,K as wp,L as Ep,M as Cp,N as Np,P as Bl,R as Rp,W as Gl,f as _p,g as Tp,s as Ap,t as bt,z as Mp}from"./constants-CJqw7w68.js";import{_ as sn,b as St,c as kp,d as Wo,f as Xo,g as Qo,h as Jo,i as Nr,l as Op,r as jp,s as Ht,t as ht,v as no,y as Pp}from"./database.store-BOgNcBMG.js";import{a as Lp,i as Dp,n as $p,o as Fp,t as Ul}from"./sheet-sidebar-Cde4bLIJ.js";import{a as zp,i as Hp,m as Bp,n as Gp}from"./badge-DAJ-55CZ.js";import{n as ro,t as fe}from"./label-B5lrF5vb.js";import{a as Bt,i as Gt,n as Ut,r as dt,t as qt}from"./select-DDjmR6pO.js";import{t as me}from"./utils-D49oYrWW.js";import{n as mn,r as nr,s as Ns}from"./keys-B1bnQf8h.js";import{t as so}from"./use-theme-uud1RcFP.js";import{n as Up,r as ql,t as qp}from"./personal-preferences.store-dG5rDcRw.js";import{t as Vp}from"./use-database-engine-C1fvJDyS.js";import{n as Vl,t as Kp}from"./separator-CGjaYtx-.js";import{t as Yp}from"./middleware-gB5jp1rF.js";import{t as Ce}from"./preload-helper-Bpqt02Xx.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};e.SENTRY_RELEASE={id:"db-studio@2.2.1"};var t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="88ff1494-f565-473f-94da-a67202f7cc7a",e._sentryDebugIdIdentifier="sentry-dbid-88ff1494-f565-473f-94da-a67202f7cc7a")}catch{}})();(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(s){if(s.ep)return;s.ep=!0;const o=n(s);fetch(s.href,o)}})();var C=wr(Ff(),1),Wp=wr(zf(),1),Qr,Zo=()=>new Qh({defaultOptions:{queries:{staleTime:3e4,gcTime:3e5,retry:0,retryDelay:e=>Math.min(1e3*2**e,3e4),refetchOnWindowFocus:!1,refetchOnMount:!1,refetchOnReconnect:!0},mutations:{retry:0,networkMode:"online"},dehydrate:{shouldDehydrateQuery:e=>Xh(e)||e.state.status==="pending"}}}),Kl=()=>typeof window>"u"?Zo():(Qr||(Qr=Zo()),Qr),Xp=(e,t,n,r,s,o,i,a)=>{let l=document.documentElement,c=["light","dark"];function u(g){(Array.isArray(e)?e:[e]).forEach(p=>{let y=p==="class",x=y&&o?s.map(v=>o[v]||v):s;y?(l.classList.remove(...x),l.classList.add(o&&o[g]?o[g]:g)):l.setAttribute(p,g)}),d(g)}function d(g){a&&c.includes(g)&&(l.style.colorScheme=g)}function f(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)u(r);else try{let g=localStorage.getItem(t)||n;u(i&&g==="system"?f():g)}catch{}},Qp=C.createContext(void 0),Jp={setTheme:e=>{},themes:[]},Zp=()=>{var e;return(e=C.useContext(Qp))!=null?e:Jp},j_=C.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:s,defaultTheme:o,value:i,themes:a,nonce:l,scriptProps:c})=>{let u=JSON.stringify([n,t,o,e,a,i,r,s]).slice(1,-1);return C.createElement("script",{...c,suppressHydrationWarning:!0,nonce:typeof window>"u"?l:"",dangerouslySetInnerHTML:{__html:`(${Xp.toString()})(${u})`}})}),h=qf(),eg=({...e})=>{const{theme:t="system"}=Zp();return(0,h.jsx)(Hf,{theme:t,className:"toaster group",icons:{success:(0,h.jsx)(jf,{className:"size-4 text-emerald-500"}),info:(0,h.jsx)(hf,{className:"size-4 text-blue-500"}),warning:(0,h.jsx)(Mf,{className:"size-4 text-amber-500"}),error:(0,h.jsx)(pf,{className:"size-4 text-red-500"}),loading:(0,h.jsx)($f,{className:"size-4 animate-spin text-blue-500"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius)"},toastOptions:{classNames:{toast:"cn-toast"}},...e})},P_=Tl("queue-reset",()=>({mutex:0}));function ei(){Rl(19),Yo.abortAll(),Yf.abort().forEach(e=>Yo.queuedQuerySync.emit(e))}function tg(e,t,n){if(t.length===0)return e;const r=n?new URLSearchParams(e):e;for(const s of Array.from(e.keys()))t.includes(s)||r.delete(s);return r}function ng(e){return Tl(`history-emitter.${e}`,()=>Qf())}var rg="__nuqs__",Rs=ng("react");function sg(e){return function(n,r){const s=new URL(location.href);s.search=Wf(n),Rl(20,"react",s),e&&r.shallow===!1?(r.history==="push"?location.assign:location.replace).call(location,s):(r.history==="push"?history.pushState:history.replaceState).call(history,history.state,rg,s),Rs.emit("update",n),r.scroll===!0&&window.scrollTo({top:0})}}var Yl=(0,C.createContext)({fullPageNavigationOnShallowFalseUpdates:!1});function og(e){return Rs.on("update",e),window.addEventListener("popstate",e),()=>{Rs.off("update",e),window.removeEventListener("popstate",e)}}function ig(){return(0,C.useEffect)(()=>(window.addEventListener("popstate",ei),()=>window.removeEventListener("popstate",ei)),[]),null}function ag(e){const{fullPageNavigationOnShallowFalseUpdates:t,serverSearch:n}=(0,C.useContext)(Yl),r=(0,C.useRef)(null);function s(o){const i=tg(new URLSearchParams(o),e,!1),a=i.toString();return r.current?.key===a?r.current.search:(r.current={key:a,search:i},i)}return{searchParams:(0,C.useSyncExternalStore)(og,()=>s(location.search),()=>s(n??"")),updateUrl:(0,C.useMemo)(()=>sg(t),[t])}}var lg=Xf(ag);function cg({children:e,fullPageNavigationOnShallowFalseUpdates:t=!1,serverSearch:n,...r}){return(0,C.createElement)(Yl.Provider,{value:{fullPageNavigationOnShallowFalseUpdates:t,serverSearch:n}},(0,C.createElement)(lg,{...r,children:[(0,C.createElement)(ig,{key:"nuqs-adapter-queue-reset"}),e]}))}var ug=zl()(e=>({pendingPrompt:null,requestAssistant:t=>e({pendingPrompt:t}),consumePrompt:()=>e({pendingPrompt:null})})),dg=()=>{const{selectedDatabase:e}=ht(),{mutateAsync:t,isPending:n}=Ft({mutationFn:async({tableName:s,schemaName:o})=>{const i=(await Tp(s,e,o)).data.data.schema;return await navigator.clipboard.writeText(i),i}});return{copyTableSchema:async(s,o)=>he.promise(t({tableName:s,schemaName:o}),{loading:"Copying table schema...",success:"Table schema copied to clipboard",error:i=>i.message||"Failed to copy table schema"}),isCopyingSchema:n}},hg=({index:e})=>{const{control:t,watch:n}=qe(),r=n("fields")?.filter(o=>o.columnName?.trim()),s=n(`fields.${e}.columnName`);return(0,h.jsx)(en,{control:t,name:`foreignKeys.${e}`,render:({field:o})=>(0,h.jsx)("div",{className:"flex flex-col gap-2 flex-1",children:(0,h.jsxs)(qt,{defaultValue:s||"none",value:o.value?.columnName,onValueChange:i=>o.onChange({...o.value,columnName:i}),children:[(0,h.jsx)(Gt,{className:"w-full flex-1",children:(0,h.jsx)(Bt,{placeholder:r?.length?"Select a column":"No columns found"})}),(0,h.jsx)(Ut,{children:r?.length>0?r.map(i=>(0,h.jsx)(dt,{value:i.columnName,children:i.columnName},i.columnName)):(0,h.jsx)(dt,{value:"none",disabled:!0,children:"No columns found"})})]})})})},fg=({index:e,tableName:t})=>{const{tableCols:n,isLoadingTableCols:r}=mp({tableName:t,schemaName:void 0}),{control:s}=qe();return Cr({control:s,name:`foreignKeys.${e}`})?(0,h.jsx)(en,{control:s,name:`foreignKeys.${e}`,render:({field:o})=>(0,h.jsxs)(qt,{value:o.value?.referencedColumn,onValueChange:i=>o.onChange({...o.value,referencedColumn:i}),disabled:r,children:[(0,h.jsx)(Gt,{className:"w-full flex-1",disabled:r||!n?.length,children:(0,h.jsx)(Bt,{placeholder:n?.length?"Select a column":"No columns found"})}),(0,h.jsx)(Ut,{children:n&&n.length>0&&r?(0,h.jsx)(dt,{value:"none",disabled:!0,children:"No columns found"}):n?.flatMap(i=>i.columnName?.trim()?[(0,h.jsx)(dt,{value:i.columnName,children:i.columnName},i.columnName)]:[])})]})}):null},pg=({index:e})=>{const{control:t}=qe();return(0,h.jsx)(en,{control:t,name:`foreignKeys.${e}.onDelete`,defaultValue:"NO ACTION",render:({field:n})=>(0,h.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,h.jsx)(fe,{htmlFor:`foreignKeys.${e}.onDelete`,children:"Action if referenced row is deleted"}),(0,h.jsxs)(qt,{value:n.value,onValueChange:r=>n.onChange(r),children:[(0,h.jsx)(Gt,{className:"w-full flex-1",children:(0,h.jsx)(Bt,{placeholder:"Select an action"})}),(0,h.jsx)(Ut,{children:Al.map(r=>(0,h.jsx)(dt,{value:r.value,children:r.label},r.value))})]})]})})},gg=({index:e})=>{const{control:t}=qe();return(0,h.jsx)(en,{control:t,name:`foreignKeys.${e}.onUpdate`,defaultValue:"NO ACTION",render:({field:n})=>(0,h.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,h.jsx)(fe,{htmlFor:`foreignKeys.${e}.onUpdate`,children:"Action if referenced row is updated"}),(0,h.jsxs)(qt,{value:n.value,onValueChange:r=>n.onChange(r),children:[(0,h.jsx)(Gt,{className:"w-full flex-1",children:(0,h.jsx)(Bt,{placeholder:"Select an action"})}),(0,h.jsx)(Ut,{children:Al.map(r=>(0,h.jsx)(dt,{value:r.value,children:r.label},r.value))})]})]})})},mg=({index:e})=>{const{control:t,watch:n}=qe(),r=n(`foreignKeys.${e}.referencedTable`),s=Cr({control:t,name:`foreignKeys.${e}`});return!r||!s?null:(0,h.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,h.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Select columns from"," ",(0,h.jsx)("span",{className:"font-mono text-primary",children:s.referencedTable||"Unnamed table"})," ","to reference to"]}),(0,h.jsxs)("div",{className:"space-y-2",children:[(0,h.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,h.jsx)(fe,{htmlFor:`foreignKeys.${e}.columnName`,children:n("tableName")||"Unnamed table"}),(0,h.jsx)(fe,{htmlFor:`foreignKeys.${e}.referencedColumn`,children:s.referencedTable||"Unnamed table"})]}),(0,h.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,h.jsxs)("div",{className:"flex items-center gap-2 flex-1",children:[(0,h.jsx)(hg,{index:e}),(0,h.jsx)(cf,{className:"size-4 aspect-square text-muted-foreground"})]}),(0,h.jsx)("div",{className:"flex items-center gap-2 flex-1",children:(0,h.jsx)(fg,{index:e,tableName:s.referencedTable})})]}),(0,h.jsx)("hr",{className:"my-8 border-border"}),(0,h.jsxs)("div",{className:"flex flex-col gap-6",children:[(0,h.jsx)(gg,{index:e}),(0,h.jsx)(pg,{index:e})]})]})]})},vg=({index:e})=>{const[t,n]=(0,C.useState)(!1),{tablesList:r,isLoadingTablesList:s}=Fl(),{control:o,watch:i,setValue:a,getValues:l}=qe(),c=i(`fields.${e}.columnName`),u=()=>{const d=l("foreignKeys")||[];if(!d[e]){const f=[...d];f.push({columnName:"",referencedTable:"",referencedColumn:"",onUpdate:"NO ACTION",onDelete:"NO ACTION"}),a("foreignKeys",f)}};return(0,h.jsx)(en,{control:o,name:`foreignKeys.${e}`,render:({field:d})=>(0,h.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,h.jsx)(fe,{htmlFor:"referencedTable",children:"Select a table to reference to"}),(0,h.jsxs)(Gp,{modal:!0,onOpenChange:f=>{f&&u(),n(f)},open:t,children:[(0,h.jsx)(zp,{asChild:!0,children:(0,h.jsxs)(ct,{"aria-expanded":t,"aria-controls":"referencedTable-listbox",className:"w-full justify-between border-input bg-background px-3 font-normal outline-none outline-offset-0 hover:bg-background focus-visible:outline-[3px]",id:"referencedTable",role:"combobox",variant:"outline",disabled:s,children:[(0,h.jsx)("span",{className:me("truncate",!d.value?.referencedTable&&"text-muted-foreground"),children:d.value?.referencedTable||"---"}),(0,h.jsx)(bf,{"aria-hidden":"true",className:"shrink-0 text-muted-foreground/80",size:16})]})}),(0,h.jsx)(Hp,{id:"referencedTable-listbox",align:"start",className:"w-full min-w-(--radix-popper-anchor-width) border-input p-0",children:(0,h.jsxs)(ep,{children:[(0,h.jsx)(Dl,{placeholder:"Search table..."}),(0,h.jsxs)(kl,{children:[(0,h.jsx)(Ml,{children:"No table found."}),(0,h.jsx)(it,{children:r?.map(f=>(0,h.jsxs)(se,{onSelect:()=>{d.onChange({...d.value,referencedTable:f.tableName}),a(`foreignKeys.${e}.columnName`,c),n(!1)},value:f.tableName,children:[f.tableName,d.value?.referencedTable===f.tableName&&(0,h.jsx)(wl,{className:"ml-auto",size:16})]},f.tableName))})]})]})})]})]})})},yg=({index:e})=>{const{closeOverlay:t,isOverlayOpen:n}=ut(),{control:r}=qe(),{remove:s}=Cs({control:r,name:"foreignKeys"}),o=()=>{s(e),t(`table-builder.add-foreign-key-${e}`)};return(0,h.jsx)($p,{open:n(`table-builder.add-foreign-key-${e}`),onOpenChange:i=>{i||t(`table-builder.add-foreign-key-${e}`)},children:(0,h.jsxs)(Dp,{className:"max-w-lg!",children:[(0,h.jsx)(Lp,{children:(0,h.jsx)(Fp,{children:"Add foreign key relationship"})}),(0,h.jsxs)("div",{className:"flex flex-col justify-between px-5 py-6 h-full flex-1",children:[(0,h.jsxs)("div",{className:"space-y-6 flex-1",children:[(0,h.jsx)(vg,{index:e}),(0,h.jsx)(mg,{index:e})]}),(0,h.jsx)(ct,{type:"button",variant:"outline",size:"sm",onClick:o,children:(0,h.jsx)("span",{className:"text-xs",children:"Reset Foreign Key"})})]})]})})},ti=({index:e,onRemove:t,canRemove:n})=>{const{control:r}=qe(),s=Cr({control:r,name:`fields.${e}.isPrimaryKey`});return(0,h.jsxs)("div",{className:"grid grid-cols-4 gap-4",children:[(0,h.jsx)(ip,{index:e}),(0,h.jsx)(sp,{index:e}),(0,h.jsx)(cp,{index:e}),(0,h.jsxs)("div",{className:"flex gap-2",children:[(0,h.jsx)(pp,{index:e}),(0,h.jsx)(hp,{index:e,isDisabled:!!s}),(0,h.jsx)("div",{className:"flex items-end justify-center",children:(0,h.jsx)(ct,{type:"button",variant:"ghost",className:"size-9",onClick:t,disabled:!n,children:(0,h.jsx)(Tf,{className:"size-4"})})}),(0,h.jsx)(yg,{index:e})]})]})},bg=()=>{const{control:e}=qe(),{fields:t,append:n,remove:r}=Cs({control:e,name:"fields"}),{remove:s}=Cs({control:e,name:"foreignKeys"}),o=Cr({control:e,name:"fields"}),i=()=>{n({columnName:"",columnType:"",defaultValue:"",isPrimaryKey:!1,isNullable:!0,isUnique:!1,isIdentity:!1,isArray:!1})},a=u=>{t.length>1&&(r(u),s(u))},l=t.reduce((u,d,f)=>(o?.[f]?.isPrimaryKey&&u.push({field:d,index:f}),u),[]),c=t.reduce((u,d,f)=>(o?.[f]?.isPrimaryKey||u.push({field:d,index:f}),u),[]);return(0,h.jsxs)("div",{className:"space-y-2",children:[l.length>1&&(0,h.jsx)(Bp,{variant:"info",title:"Composite primary key selected",className:"mb-6"}),(0,h.jsxs)("div",{className:"grid grid-cols-4 px-2",children:[(0,h.jsx)(fe,{className:"text-xs",children:"Column Name"}),(0,h.jsx)(fe,{className:"text-xs",children:"Column Type"}),(0,h.jsx)(fe,{className:"text-xs",children:"Default Value"}),(0,h.jsx)(fe,{className:"text-xs",children:"Primary"})]}),(0,h.jsxs)("div",{className:"space-y-2",children:[l.length>0&&(0,h.jsx)("div",{className:"bg-primary/10 rounded-lg px-2 py-3 space-y-2",children:l.map(({field:u,index:d})=>(0,h.jsx)(ti,{index:d,onRemove:()=>a(d),canRemove:t.length>1},u.id))}),c.length>0&&(0,h.jsx)("div",{className:"space-y-2 px-2 py-3",children:c.map(({field:u,index:d})=>(0,h.jsx)(ti,{index:d,onRemove:()=>a(d),canRemove:t.length>1},u.id))})]}),(0,h.jsx)("div",{className:"border border-dashed border-input rounded-lg flex justify-center items-center p-6",children:(0,h.jsx)(ct,{type:"button",variant:"secondary",size:"sm",onClick:i,children:"Add New Column"})})]})};function L_({className:e,...t}){return(0,h.jsx)("div",{"data-slot":"field-group",className:me("gap-4 data-[slot=checkbox-group]:gap-3 [&>[data-slot=field-group]]:gap-4 group/field-group @container/field-group flex w-full flex-col",e),...t})}var xg=Nl("data-[invalid=true]:text-destructive gap-2 group/field flex w-full",{variants:{orientation:{vertical:"flex-col [&>*]:w-full [&>.sr-only]:w-auto",horizontal:"flex-row items-center [&>[data-slot=field-label]]:flex-auto has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",responsive:"flex-col [&>*]:w-full [&>.sr-only]:w-auto @md/field-group:flex-row @md/field-group:items-center @md/field-group:[&>*]:w-auto @md/field-group:[&>[data-slot=field-label]]:flex-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px"}},defaultVariants:{orientation:"vertical"}});function D_({className:e,orientation:t="vertical",...n}){return(0,h.jsx)("div",{role:"group","data-slot":"field","data-orientation":t,className:me(xg({orientation:t}),e),...n})}function $_({className:e,...t}){return(0,h.jsx)(fe,{"data-slot":"field-label",className:me("has-data-checked:bg-primary/5 dark:has-data-checked:bg-primary/10 gap-2 group-data-[disabled=true]/field:opacity-50 has-[>[data-slot=field]]:rounded-sm has-[>[data-slot=field]]:border [&>*]:data-[slot=field]:p-2 group/field-label peer/field-label flex w-fit leading-snug","has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col",e),...t})}function F_({className:e,...t}){return(0,h.jsx)("p",{"data-slot":"field-description",className:me("text-muted-foreground text-left text-xs/relaxed [[data-variant=legend]+&]:-mt-1.5 leading-normal font-normal group-has-[[data-orientation=horizontal]]/field:text-balance","last:mt-0 nth-last-2:-mt-1","[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",e),...t})}var Sg=C.memo(function({errors:t}){const n=[...new Map(t.map(r=>[r?.message,r])).values()];return n.length===1?(0,h.jsx)(h.Fragment,{children:n[0]?.message}):(0,h.jsx)("ul",{className:"ml-4 flex list-disc flex-col gap-1",children:n.map((r,s)=>r?.message&&(0,h.jsx)("li",{children:r.message},r?.message??s))})});function Ig({className:e,children:t,errors:n,...r}){return t!=null||(n?.length??0)>0?(0,h.jsx)("div",{role:"alert","data-slot":"field-error",className:me("text-destructive text-xs/relaxed font-normal",e),...r,children:t??(n&&(0,h.jsx)(Sg,{errors:n}))}):null}var wg=()=>{const{control:e,register:t,formState:{errors:n}}=qe();return(0,h.jsx)(en,{control:e,name:"tableName",render:()=>(0,h.jsxs)("div",{className:"flex gap-24 px-2",children:[(0,h.jsx)(fe,{htmlFor:"tableName",children:"Table Name"}),(0,h.jsxs)("div",{className:"flex-1 space-y-1",children:[(0,h.jsx)(ro,{id:"tableName",...t("tableName",{required:"Table name is required"}),className:n.tableName?"border-destructive ring-destructive ring-1":""}),n.tableName&&(0,h.jsx)(Ig,{errors:[n.tableName]})]})]})})},Eg=()=>{const{closeOverlay:e}=ut(),t=Qs(),{selectedDatabase:n,dbType:r}=ht(),{mutateAsync:s,isPending:o}=Ft({mutationFn:async a=>(await Ap(a,n)).data.data,onSuccess:async()=>{await Promise.all([t.invalidateQueries({queryKey:Ns.lists()}),t.invalidateQueries({queryKey:Ns.columns()})]),e("table-builder.create-table"),r&&Nr.capture("table_created",{db_type:r})}});return{createTable:async(a,l)=>he.promise(s(a,l),{loading:"Creating table...",success:c=>c||"Table created successfully",error:c=>c.detail||c.message||"Failed to create table"}),isCreatingTable:o}},Cg=no({columnName:St().min(1,"Column name is required"),columnType:St().min(1,"Column type is required"),defaultValue:St(),isPrimaryKey:sn(),isNullable:sn(),isUnique:sn(),isIdentity:sn(),isArray:sn()}),Ng=no({columnName:St().min(1,"Column name is required"),referencedTable:St().min(1,"Referenced table is required"),referencedColumn:St().min(1,"Referenced column is required"),onUpdate:Jo(["CASCADE","SET NULL","SET DEFAULT","RESTRICT","NO ACTION"]).default("NO ACTION"),onDelete:Jo(["CASCADE","SET NULL","SET DEFAULT","RESTRICT","NO ACTION"]).default("NO ACTION")}),Rg=no({tableName:St().min(1,"Table name is required"),fields:Qo(Cg).min(1,"At least one column is required"),foreignKeys:Pp(e=>{if(Array.isArray(e))return e.filter(t=>t==null?!1:typeof t=="object"?t.columnName&&t.referencedTable&&t.referencedColumn:!1)},Qo(Ng).optional())}),_g={tableName:"",fields:[{columnName:"",columnType:"",defaultValue:"",isPrimaryKey:!1,isNullable:!0,isUnique:!1,isIdentity:!1,isArray:!1}],foreignKeys:void 0},Tg=()=>{const{closeOverlay:e,isOverlayOpen:t}=ut(),{createTable:n,isCreatingTable:r}=Eg(),s=np({mode:"onSubmit",defaultValues:_g,resolver:rp(Rg)}),o=async l=>{const c={...l,foreignKeys:l.foreignKeys?.filter(u=>u===null?!0:u.columnName&&u.referencedTable&&u.referencedColumn)};try{await n(c,{onSuccess:()=>{s.reset()},onError:u=>{console.error("Error creating table:",u)}})}catch(u){console.error("Error creating table:",u)}},i=l=>{if(l.tableName?.message){he.error(l.tableName.message);return}if(l.fields&&Array.isArray(l.fields))for(const c of l.fields){if(c?.columnName?.message){he.error(c.columnName.message);return}if(c?.columnType?.message){he.error(c.columnType.message);return}}if(l.foreignKeys&&Array.isArray(l.foreignKeys))for(const c of l.foreignKeys){if(c?.columnName?.message){he.error(c.columnName.message);return}if(c?.referencedTable?.message){he.error(c.referencedTable.message);return}if(c?.referencedColumn?.message){he.error(c.referencedColumn.message);return}}he.error("Please check the form for errors")},a=()=>{s.reset(),e("table-builder.create-table")};return(0,h.jsx)(Ul,{title:"Create a new table",open:t("table-builder.create-table"),onOpenChange:l=>{l||a()},children:(0,h.jsx)(Jf,{...s,children:(0,h.jsxs)("form",{onSubmit:s.handleSubmit(o,i),className:"space-y-6",children:[(0,h.jsx)(wg,{}),(0,h.jsx)(bg,{}),(0,h.jsx)(Zf,{onCancel:a,isLoading:r})]})})})},Wl=Object.defineProperty,Ag=(e,t,n)=>t in e?Wl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Mg=(e,t)=>{for(var n in t)Wl(e,n,{get:t[n],enumerable:!0})},kg=(e,t,n)=>Ag(e,typeof t!="symbol"?t+"":t,n),Xl={};Mg(Xl,{Graph:()=>Ve,alg:()=>io});var Og=Object.defineProperty,Ql=(e,t)=>{for(var n in t)Og(e,n,{get:t[n],enumerable:!0})},oo=class{constructor(e){this._isDirected=!0,this._isMultigraph=!1,this._isCompound=!1,this._nodes={},this._in={},this._preds={},this._out={},this._sucs={},this._edgeObjs={},this._edgeLabels={},this._nodeCount=0,this._edgeCount=0,this._defaultNodeLabelFn=()=>{},this._defaultEdgeLabelFn=()=>{},e&&(this._isDirected="directed"in e?e.directed:!0,this._isMultigraph="multigraph"in e?e.multigraph:!1,this._isCompound="compound"in e?e.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children["\0"]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(e){return this._label=e,this}graph(){return this._label}setDefaultNodeLabel(e){return typeof e!="function"?this._defaultNodeLabelFn=()=>e:this._defaultNodeLabelFn=e,this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){return this.nodes().filter(e=>Object.keys(this._in[e]).length===0)}sinks(){return this.nodes().filter(e=>Object.keys(this._out[e]).length===0)}setNodes(e,t){return e.forEach(n=>{t!==void 0?this.setNode(n,t):this.setNode(n)}),this}setNode(e,t){return e in this._nodes?(arguments.length>1&&(this._nodes[e]=t),this):(this._nodes[e]=arguments.length>1?t:this._defaultNodeLabelFn(e),this._isCompound&&(this._parent[e]="\0",this._children[e]={},this._children["\0"][e]=!0),this._in[e]={},this._preds[e]={},this._out[e]={},this._sucs[e]={},++this._nodeCount,this)}node(e){return this._nodes[e]}hasNode(e){return e in this._nodes}removeNode(e){if(e in this._nodes){let t=n=>this.removeEdge(this._edgeObjs[n]);delete this._nodes[e],this._isCompound&&(this._removeFromParentsChildList(e),delete this._parent[e],this.children(e).forEach(n=>{this.setParent(n)}),delete this._children[e]),Object.keys(this._in[e]).forEach(t),delete this._in[e],delete this._preds[e],Object.keys(this._out[e]).forEach(t),delete this._out[e],delete this._sucs[e],--this._nodeCount}return this}setParent(e,t){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(t===void 0)t="\0";else{t+="";for(let n=t;n!==void 0;n=this.parent(n))if(n===e)throw new Error("Setting "+t+" as parent of "+e+" would create a cycle");this.setNode(t)}return this.setNode(e),this._removeFromParentsChildList(e),this._parent[e]=t,this._children[t][e]=!0,this}parent(e){if(this._isCompound){let t=this._parent[e];if(t!=="\0")return t}}children(e="\0"){if(this._isCompound){let t=this._children[e];if(t)return Object.keys(t)}else{if(e==="\0")return this.nodes();if(this.hasNode(e))return[]}return[]}predecessors(e){let t=this._preds[e];if(t)return Object.keys(t)}successors(e){let t=this._sucs[e];if(t)return Object.keys(t)}neighbors(e){let t=this.predecessors(e);if(t){let n=new Set(t),r=this.successors(e);if(r)for(let s of r)n.add(s);return Array.from(n.values())}}isLeaf(e){var t;let n;return this.isDirected()?n=this.successors(e):n=this.neighbors(e),((t=n?.length)!=null?t:0)===0}filterNodes(e){let t=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});t.setGraph(this.graph()),Object.entries(this._nodes).forEach(([s,o])=>{e(s)&&t.setNode(s,o)}),Object.values(this._edgeObjs).forEach(s=>{t.hasNode(s.v)&&t.hasNode(s.w)&&t.setEdge(s,this.edge(s))});let n={},r=s=>{let o=this.parent(s);return!o||t.hasNode(o)?(n[s]=o,o):o in n?n[o]:r(o)};return this._isCompound&&t.nodes().forEach(s=>t.setParent(s,r(s))),t}setDefaultEdgeLabel(e){return typeof e!="function"?this._defaultEdgeLabelFn=()=>e:this._defaultEdgeLabelFn=e,this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(e,t){return e.reduce((n,r)=>(t!==void 0?this.setEdge(n,r,t):this.setEdge(n,r),r)),this}setEdge(e,t,n,r){let s,o,i,a,l=!1;typeof e=="object"&&e!==null&&"v"in e?(s=e.v,o=e.w,i=e.name,arguments.length===2&&(a=t,l=!0)):(s=e,o=t,i=r,arguments.length>2&&(a=n,l=!0)),s=""+s,o=""+o,i!==void 0&&(i=""+i);let c=cn(this._isDirected,s,o,i);if(c in this._edgeLabels)return l&&(this._edgeLabels[c]=a),this;if(i!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(s),this.setNode(o),this._edgeLabels[c]=l?a:this._defaultEdgeLabelFn(s,o,i);let u=jg(this._isDirected,s,o,i);return s=u.v,o=u.w,Object.freeze(u),this._edgeObjs[c]=u,ni(this._preds[o],s),ni(this._sucs[s],o),this._in[o][c]=u,this._out[s][c]=u,this._edgeCount++,this}edge(e,t,n){let r=arguments.length===1?Jr(this._isDirected,e):cn(this._isDirected,e,t,n);return this._edgeLabels[r]}edgeAsObj(e,t,n){let r=arguments.length===1?this.edge(e):this.edge(e,t,n);return typeof r!="object"||r===null?{label:r}:r}hasEdge(e,t,n){return(arguments.length===1?Jr(this._isDirected,e):cn(this._isDirected,e,t,n))in this._edgeLabels}removeEdge(e,t,n){let r=arguments.length===1?Jr(this._isDirected,e):cn(this._isDirected,e,t,n),s=this._edgeObjs[r];if(s){let o=s.v,i=s.w;delete this._edgeLabels[r],delete this._edgeObjs[r],ri(this._preds[i],o),ri(this._sucs[o],i),delete this._in[i][r],delete this._out[o][r],this._edgeCount--}return this}inEdges(e,t){return this.isDirected()?this.filterEdges(this._in[e],e,t):this.nodeEdges(e,t)}outEdges(e,t){return this.isDirected()?this.filterEdges(this._out[e],e,t):this.nodeEdges(e,t)}nodeEdges(e,t){if(e in this._nodes)return this.filterEdges({...this._in[e],...this._out[e]},e,t)}_removeFromParentsChildList(e){delete this._children[this._parent[e]][e]}filterEdges(e,t,n){if(!e)return;let r=Object.values(e);return n?r.filter(s=>s.v===t&&s.w===n||s.v===n&&s.w===t):r}};function ni(e,t){e[t]?e[t]++:e[t]=1}function ri(e,t){e[t]!==void 0&&!--e[t]&&delete e[t]}function cn(e,t,n,r){let s=""+t,o=""+n;if(!e&&s>o){let i=s;s=o,o=i}return s+""+o+""+(r===void 0?"\0":r)}function jg(e,t,n,r){let s=""+t,o=""+n;if(!e&&s>o){let a=s;s=o,o=a}let i={v:s,w:o};return r&&(i.name=r),i}function Jr(e,t){return cn(e,t.v,t.w,t.name)}Ql({},{read:()=>$g,write:()=>Pg});function Pg(e){let t={options:{directed:e.isDirected(),multigraph:e.isMultigraph(),compound:e.isCompound()},nodes:Lg(e),edges:Dg(e)},n=e.graph();return n!==void 0&&(t.value=structuredClone(n)),t}function Lg(e){return e.nodes().map(t=>{let n=e.node(t),r=e.parent(t),s={v:t};return n!==void 0&&(s.value=n),r!==void 0&&(s.parent=r),s})}function Dg(e){return e.edges().map(t=>{let n=e.edge(t),r={v:t.v,w:t.w};return t.name!==void 0&&(r.name=t.name),n!==void 0&&(r.value=n),r})}function $g(e){let t=new oo(e.options);return e.value!==void 0&&t.setGraph(e.value),e.nodes.forEach(n=>{t.setNode(n.v,n.value),n.parent&&t.setParent(n.v,n.parent)}),e.edges.forEach(n=>{t.setEdge({v:n.v,w:n.w,name:n.name},n.value)}),t}var io={};Ql(io,{CycleException:()=>sr,bellmanFord:()=>Jl,components:()=>Hg,dijkstra:()=>rr,dijkstraAll:()=>Ug,findCycles:()=>qg,floydWarshall:()=>Kg,isAcyclic:()=>Wg,postorder:()=>Qg,preorder:()=>Jg,prim:()=>Zg,shortestPaths:()=>em,tarjan:()=>ec,topsort:()=>tc});var Fg=()=>1;function Jl(e,t,n,r){return zg(e,String(t),n||Fg,r||function(s){var o;return(o=e.outEdges(s))!=null?o:[]})}function zg(e,t,n,r){let s={},o,i=0,a=e.nodes(),l=function(d){let f=s[d.v],g=s[d.w];if(!f||!g)return;let p=n(d);f.distance+p<g.distance&&(s[d.w]={distance:f.distance+p,predecessor:d.v},o=!0)},c=function(){a.forEach(function(d){r(d).forEach(function(f){let g=f.v===d?f.v:f.w,p=g===f.v?f.w:f.v;l({v:g,w:p})})})};a.forEach(function(d){s[d]={distance:d===t?0:Number.POSITIVE_INFINITY,predecessor:""}});let u=a.length;for(let d=1;d<u&&(o=!1,i++,c(),!!o);d++);if(i===u-1&&(o=!1,c(),o))throw new Error("The graph contains a negative weight cycle");return s}function Hg(e){let t={},n=[],r;function s(o){var i,a;o in t||(t[o]=!0,r.push(o),(i=e.successors(o))==null||i.forEach(s),(a=e.predecessors(o))==null||a.forEach(s))}return e.nodes().forEach(function(o){r=[],s(o),r.length&&n.push(r)}),n}var Zl=class{constructor(){this._arr=[],this._keyIndices={}}size(){return this._arr.length}keys(){return this._arr.map(e=>e.key)}has(e){return e in this._keyIndices}priority(e){let t=this._keyIndices[e];if(t!==void 0)return this._arr[t].priority}min(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key}add(e,t){let n=this._keyIndices,r=String(e);if(!(r in n)){let s=this._arr,o=s.length;return n[r]=o,s.push({key:r,priority:t}),this._decrease(o),!0}return!1}removeMin(){if(this.size()===0)throw new Error("Queue underflow");this._swap(0,this._arr.length-1);let e=this._arr.pop();return delete this._keyIndices[e.key],this._heapify(0),e.key}decrease(e,t){let n=this._keyIndices[e];if(n===void 0)throw new Error(`Key not found: ${e}`);let r=this._arr[n].priority;if(t>r)throw new Error(`New priority is greater than current priority. Key: ${e} Old: ${r} New: ${t}`);this._arr[n].priority=t,this._decrease(n)}_heapify(e){let t=this._arr,n=2*e,r=n+1,s=e;n<t.length&&(s=t[n].priority<t[s].priority?n:s,r<t.length&&(s=t[r].priority<t[s].priority?r:s),s!==e&&(this._swap(e,s),this._heapify(s)))}_decrease(e){let t=this._arr,n=t[e].priority,r;for(;e!==0&&(r=e>>1,!(t[r].priority<n));)this._swap(e,r),e=r}_swap(e,t){let n=this._arr,r=this._keyIndices,s=n[e],o=n[t];n[e]=o,n[t]=s,r[o.key]=e,r[s.key]=t}},Bg=()=>1;function rr(e,t,n,r){let s=function(o){var i;return(i=e.outEdges(o))!=null?i:[]};return Gg(e,String(t),n||Bg,r||s)}function Gg(e,t,n,r){let s={},o=new Zl,i,a,l=function(c){let u=c.v!==i?c.v:c.w,d=s[u];if(!d)return;let f=n(c),g=a.distance+f;if(f<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+c+" Weight: "+f);g<d.distance&&(d.distance=g,d.predecessor=i,o.decrease(u,g))};for(e.nodes().forEach(function(c){let u=c===t?0:Number.POSITIVE_INFINITY;s[c]={distance:u,predecessor:""},o.add(c,u)});o.size()>0;){i=o.removeMin();let c=s[i];if(!c||c.distance===Number.POSITIVE_INFINITY)break;a=c,r(i).forEach(l)}return s}function Ug(e,t,n){return e.nodes().reduce(function(r,s){return r[s]=rr(e,s,t,n),r},{})}function ec(e){let t=0,n=[],r={},s=[];function o(i){var a;let l=r[i]={onStack:!0,lowlink:t,index:t++};if(n.push(i),(a=e.successors(i))==null||a.forEach(function(c){if(c in r){let u=r[c];u!=null&&u.onStack&&(l.lowlink=Math.min(l.lowlink,u.index))}else{o(c);let u=r[c];u&&(l.lowlink=Math.min(l.lowlink,u.lowlink))}}),l.lowlink===l.index){let c=[],u;do{u=n.pop();let d=r[u];d&&(d.onStack=!1),c.push(u)}while(i!==u);s.push(c)}}return e.nodes().forEach(function(i){i in r||o(i)}),s}function qg(e){return ec(e).filter(function(t){var n;let r=t[0];return r?t.length>1||t.length===1&&((n=e.outEdges(r,r))!=null?n:[]).length>0:!1})}var Vg=()=>1;function Kg(e,t,n){return Yg(e,t||Vg,n||function(r){var s;return(s=e.outEdges(r))!=null?s:[]})}function Yg(e,t,n){let r={},s=e.nodes();return s.forEach(function(o){let i={};r[o]=i,i[o]={distance:0,predecessor:""},s.forEach(function(a){o!==a&&(i[a]={distance:Number.POSITIVE_INFINITY,predecessor:""})}),n(o).forEach(function(a){let l=a.v===o?a.w:a.v,c=t(a);i[l]={distance:c,predecessor:o}})}),s.forEach(function(o){let i=r[o];i&&s.forEach(function(a){let l=r[a];l&&s.forEach(function(c){let u=l[o],d=i[c],f=l[c];if(u&&d&&f){let g=u.distance+d.distance;g<f.distance&&(f.distance=g,f.predecessor=d.predecessor)}})})}),r}var sr=class extends Error{constructor(e){super(e),this.name="CycleException"}};function tc(e){let t={},n={},r=[];function s(o){var i;if(o in n)throw new sr;o in t||(n[o]=!0,t[o]=!0,(i=e.predecessors(o))==null||i.forEach(s),delete n[o],r.push(o))}if(e.sinks().forEach(s),Object.keys(t).length!==e.nodeCount())throw new sr;return r}function Wg(e){try{tc(e)}catch(t){if(t instanceof sr)return!1;throw t}return!0}function Xg(e,t,n,r,s){Array.isArray(t)||(t=[t]);let o=(a=>{var l;return(l=e.isDirected()?e.successors(a):e.neighbors(a))!=null?l:[]}),i={};return t.forEach(function(a){if(!e.hasNode(a))throw new Error("Graph does not have node: "+a);s=nc(e,a,n==="post",i,o,r,s)}),s}function nc(e,t,n,r,s,o,i){return t in r||(r[t]=!0,n||(i=o(i,t)),s(t).forEach(function(a){i=nc(e,a,n,r,s,o,i)}),n&&(i=o(i,t))),i}function rc(e,t,n){return Xg(e,t,n,function(r,s){return r.push(s),r},[])}function Qg(e,t){return rc(e,t,"post")}function Jg(e,t){return rc(e,t,"pre")}function Zg(e,t){var n;let r=new oo,s={},o=new Zl,i;function a(u){let d=u.v===i?u.w:u.v,f=o.priority(d);if(f!==void 0){let g=t(u);g<f&&(s[d]=i,o.decrease(d,g))}}if(e.nodeCount()===0)return r;e.nodes().forEach(function(u){o.add(u,Number.POSITIVE_INFINITY),r.setNode(u)});let l=e.nodes()[0];l!==void 0&&o.decrease(l,0);let c=!1;for(;o.size()>0;){if(i=o.removeMin(),i in s)r.setEdge(i,s[i]);else{if(c)throw new Error("Input graph is not connected: "+e);c=!0}(n=e.nodeEdges(i))==null||n.forEach(a)}return r}function em(e,t,n,r){return tm(e,t,n,r??(s=>{var o;return(o=e.outEdges(s))!=null?o:[]}))}function tm(e,t,n,r){if(n===void 0)return rr(e,t,n,r);let s=!1,o=e.nodes();for(let i=0;i<o.length;i++){let a=o[i];if(a===void 0)continue;let l=r(a);for(let c=0;c<l.length;c++){let u=l[c];if(!u)continue;let d=u.v===a?u.v:u.w;n({v:d,w:d===u.v?u.w:u.v})<0&&(s=!0)}if(s)return Jl(e,t,n,r)}return rr(e,t,n,r)}var Ve=oo;function tn(e,t,n,r){let s=r;for(;e.hasNode(s);)s=ao(r);return n.dummy=t,e.setNode(s,n),s}function nm(e){let t=new Ve().setGraph(e.graph());return e.nodes().forEach(n=>t.setNode(n,e.node(n))),e.edges().forEach(n=>{let r=t.edge(n.v,n.w)||{weight:0,minlen:1},s=e.edge(n);t.setEdge(n.v,n.w,{weight:r.weight+s.weight,minlen:Math.max(r.minlen,s.minlen)})}),t}function sc(e){let t=new Ve({multigraph:e.isMultigraph()}).setGraph(e.graph());return e.nodes().forEach(n=>{e.children(n).length||t.setNode(n,e.node(n))}),e.edges().forEach(n=>{t.setEdge(n,e.edge(n))}),t}function si(e,t){let n=e.x,r=e.y,s=t.x-n,o=t.y-r,i=e.width/2,a=e.height/2;if(!s&&!o)throw new Error("Not possible to find intersection inside of the rectangle");let l,c;return s===0||Math.abs(o)*i>Math.abs(s)*a?(o<0&&(a=-a),l=a*s/o,c=a):(s<0&&(i=-i),l=i,c=i*o/s),{x:n+l,y:r+c}}function Rr(e){let t=xn(ic(e)+1).map(()=>[]);return e.nodes().forEach(n=>{let r=e.node(n),s=r.rank;s!==void 0&&(t[s]||(t[s]=[]),t[s][r.order]=n)}),t}function rm(e){let t=e.nodes().map(r=>{let s=e.node(r).rank;return s===void 0?Number.MAX_VALUE:s}),n=Ge(Math.min,t);e.nodes().forEach(r=>{let s=e.node(r);Object.hasOwn(s,"rank")&&(s.rank-=n)})}function sm(e){let t=e.nodes().map(i=>e.node(i).rank).filter(i=>i!==void 0),n=Ge(Math.min,t),r=[];e.nodes().forEach(i=>{let a=e.node(i).rank-n;r[a]||(r[a]=[]),r[a].push(i)});let s=0,o=e.graph().nodeRankFactor;Array.from(r).forEach((i,a)=>{i===void 0&&a%o!==0?--s:i!==void 0&&s&&i.forEach(l=>e.node(l).rank+=s)})}function oi(e,t,n,r){let s={width:0,height:0};return arguments.length>=4&&(s.rank=n,s.order=r),tn(e,"border",s,t)}function om(e,t=oc){let n=[];for(let r=0;r<e.length;r+=t){let s=e.slice(r,r+t);n.push(s)}return n}var oc=65535;function Ge(e,t){return t.length>oc?e(...om(t).map(n=>e(...n))):e(...t)}function ic(e){let t=e.nodes().map(n=>{let r=e.node(n).rank;return r===void 0?Number.MIN_VALUE:r});return Ge(Math.max,t)}function im(e,t){let n={lhs:[],rhs:[]};return e.forEach(r=>{t(r)?n.lhs.push(r):n.rhs.push(r)}),n}function am(e,t){return t()}var lm=0;function ao(e){return e+(""+ ++lm)}function xn(e,t,n=1){t??(t=e,e=0);let r=o=>o<t;n<0&&(r=o=>t<o);let s=[];for(let o=e;r(o);o+=n)s.push(o);return s}function or(e,t){let n={};for(let r of t)e[r]!==void 0&&(n[r]=e[r]);return n}function _r(e,t){let n;return typeof t=="string"?n=r=>r[t]:n=t,Object.entries(e).reduce((r,[s,o])=>(r[s]=n(o,s),r),{})}function cm(e,t){return e.reduce((n,r,s)=>(n[r]=t[s],n),{})}var Tr="\0";function ac(e,t,n){var r,s,o,i,a,l;if(!(e&&t&&n&&t.dummy==="edge"&&n.dummy==="edge"&&t.edgeObj&&n.edgeObj&&e[t.edgeObj.v]&&e[n.edgeObj.v]&&e[t.edgeObj.w]&&e[n.edgeObj.w]))return 0;let c=!0;t.edgeObj.w===n.edgeObj.w&&(c=!1);let u=c?(s=(r=e[t.edgeObj.v])==null?void 0:r.rank)!=null?s:NaN:(i=(o=e[t.edgeObj.w])==null?void 0:o.rank)!=null?i:NaN,d=Object.entries(e).find(y=>{var x,v;return((x=y[1].edgeObj)==null?void 0:x.v)===t.edgeObj.v&&((v=y[1].edgeObj)==null?void 0:v.w)===t.edgeObj.w&&y[1].rank===u}),f=Object.entries(e).find(y=>{var x,v;return((x=y[1].edgeObj)==null?void 0:x.v)===n.edgeObj.v&&((v=y[1].edgeObj)==null?void 0:v.w)===n.edgeObj.w&&y[1].rank===u});if(!d||!f)return 0;let g=(a=d[1].order)!=null?a:NaN,p=(l=f[1].order)!=null?l:NaN;return isNaN(g-p)?0:g-p}var um=class{constructor(){kg(this,"_sentinel");let e={};e._next=e._prev=e,this._sentinel=e}dequeue(){let e=this._sentinel,t=e._prev;if(t!==e)return ii(t),t}enqueue(e){let t=this._sentinel;e._prev&&e._next&&ii(e),e._next=t._next,t._next._prev=e,t._next=e,e._prev=t}toString(){let e=[],t=this._sentinel,n=t._prev;for(;n!==t;)e.push(JSON.stringify(n,dm)),n=n._prev;return"["+e.join(", ")+"]"}};function ii(e){e._prev._next=e._next,e._next._prev=e._prev,delete e._next,delete e._prev}function dm(e,t){if(e!=="_next"&&e!=="_prev")return t}var hm=um,fm=()=>1;function pm(e,t){if(e.nodeCount()<=1)return[];let n=mm(e,t||fm);return gm(n.graph,n.buckets,n.zeroIdx).flatMap(r=>e.outEdges(r.v,r.w)||[])}function gm(e,t,n){var r;let s=[],o=t[t.length-1],i=t[0],a;for(;e.nodeCount();){for(;a=i.dequeue();)Zr(e,t,n,a);for(;a=o.dequeue();)Zr(e,t,n,a);if(e.nodeCount()){for(let l=t.length-2;l>0;--l)if(a=(r=t[l])==null?void 0:r.dequeue(),a){s=s.concat(Zr(e,t,n,a,!0)||[]);break}}}return s}function Zr(e,t,n,r,s){let o=[],i=s?o:void 0;return(e.inEdges(r.v)||[]).forEach(a=>{let l=e.edge(a),c=e.node(a.v);s&&o.push({v:a.v,w:a.w}),c.out-=l,_s(t,n,c)}),(e.outEdges(r.v)||[]).forEach(a=>{let l=e.edge(a),c=a.w,u=e.node(c);u.in-=l,_s(t,n,u)}),e.removeNode(r.v),i}function mm(e,t){let n=new Ve,r=0,s=0;e.nodes().forEach(a=>{n.setNode(a,{v:a,in:0,out:0})}),e.edges().forEach(a=>{let l=n.edge(a.v,a.w)||0,c=t(a),u=l+c;n.setEdge(a.v,a.w,u);let d=n.node(a.v),f=n.node(a.w);s=Math.max(s,d.out+=c),r=Math.max(r,f.in+=c)});let o=vm(s+r+3).map(()=>new hm),i=r+1;return n.nodes().forEach(a=>{_s(o,i,n.node(a))}),{graph:n,buckets:o,zeroIdx:i}}function _s(e,t,n){var r,s,o;n.out?n.in?(o=e[n.out-n.in+t])==null||o.enqueue(n):(s=e[e.length-1])==null||s.enqueue(n):(r=e[0])==null||r.enqueue(n)}function vm(e){let t=[];for(let n=0;n<e;n++)t.push(n);return t}function ym(e,t){(e.graph().acyclicer==="greedy"?pm(e,n(e)):bm(e,t??null)).forEach(r=>{let s=e.edge(r);e.removeEdge(r),s.forwardName=r.name,s.reversed=!0,e.setEdge(r.w,r.v,s,ao("rev"))});function n(r){return s=>r.edge(s).weight}}function bm(e,t){let n=[],r={},s={};function o(l){Object.hasOwn(s,l)||(s[l]=!0,r[l]=!0,e.outEdges(l).forEach(c=>{Object.hasOwn(r,c.w)?n.push(c):o(c.w)}),delete r[l])}function i(l){var c;Object.hasOwn(s,l)||(s[l]=!0,r[l]=!0,(c=e.outEdges(l))==null||c.forEach(u=>{var d,f;Object.hasOwn(r,u.w)||((d=t.node(l))==null?void 0:d.rank)>((f=t.node(u.w))==null?void 0:f.rank)&&Sm(e,u.w,u)?n.push(u):i(u.w)}),delete r[l])}let a=o;return t&&typeof t.node=="function"&&(a=i),e.sources().forEach(a),e.nodes().forEach(a),n}function xm(e){e.edges().forEach(t=>{let n=e.edge(t);if(n.reversed){e.removeEdge(t);let r=n.forwardName;delete n.reversed,delete n.forwardName,e.setEdge(t.w,t.v,n,r)}})}function Sm(e,t,n){let r=new Set;function s(o){var i;if(e.sources().includes(o))return!0;r.add(o);for(let a of(i=e.inEdges(o))!=null?i:[])if(!(a.v===n.v&&a.w===n.w)&&!r.has(a.v)&&s(a.v))return!0;return!1}return s(t)}function Im(e){e.graph().dummyChains=[],e.edges().forEach(t=>wm(e,t))}function wm(e,t){let n=t.v,r=e.node(n).rank,s=t.w,o=e.node(s).rank,i=t.name,a=e.edge(t),l=a.labelRank;if(o===r+1)return;e.removeEdge(t);let c,u,d=0;for(++r;r<o;++d,++r)a.points=[],u={width:0,height:0,edgeLabel:a,edgeObj:t,rank:r},c=tn(e,"edge",u,"_d"),r===l&&(u.width=a.width,u.height=a.height,u.dummy="edge-label",u.labelpos=a.labelpos),e.setEdge(n,c,{weight:a.weight},i),d===0&&e.graph().dummyChains.push(c),n=c;e.setEdge(n,s,{weight:a.weight},i)}function Em(e){e.graph().dummyChains.forEach(t=>{let n=e.node(t),r=n.edgeLabel,s;for(e.setEdge(n.edgeObj,r);n.dummy;)s=e.successors(t)[0],e.removeNode(t),r.points.push({x:n.x,y:n.y}),n.dummy==="edge-label"&&(r.x=n.x,r.y=n.y,r.width=n.width,r.height=n.height),t=s,n=e.node(t)})}function lo(e){let t={};function n(r){let s=e.node(r);if(Object.hasOwn(t,r))return s.rank;t[r]=!0;let o=e.outEdges(r),i=o?o.map(l=>l==null?Number.POSITIVE_INFINITY:n(l.w)-e.edge(l).minlen):[],a=Ge(Math.min,i);return a===Number.POSITIVE_INFINITY&&(a=0),s.rank=a}e.sources().forEach(n)}function Vt(e,t){return e.node(t.w).rank-e.node(t.v).rank-e.edge(t).minlen}var lc=Cm;function Cm(e){let t=new Ve({directed:!1}),n=e.nodes();if(n.length===0)throw new Error("Graph must have at least one node");let r=n[0],s=e.nodeCount();t.setNode(r,{});let o,i;for(;Nm(t,e)<s&&(o=Rm(t,e),!!o);)i=t.hasNode(o.v)?Vt(e,o):-Vt(e,o),_m(t,e,i);return t}function Nm(e,t){function n(r){let s=t.nodeEdges(r);s&&s.forEach(o=>{let i=o.v,a=r===i?o.w:i;!e.hasNode(a)&&!Vt(t,o)&&(e.setNode(a,{}),e.setEdge(r,a,{}),n(a))})}return e.nodes().forEach(n),e.nodeCount()}function Rm(e,t){return t.edges().reduce((n,r)=>{let s=Number.POSITIVE_INFINITY;return e.hasNode(r.v)!==e.hasNode(r.w)&&(s=Vt(t,r)),s<n[0]?[s,r]:n},[Number.POSITIVE_INFINITY,null])[1]}function _m(e,t,n){e.nodes().forEach(r=>t.node(r).rank+=n)}var{preorder:Tm,postorder:Am}=io,Mm=kt;kt.initLowLimValues=uo;kt.initCutValues=co;kt.calcCutValue=cc;kt.leaveEdge=dc;kt.enterEdge=hc;kt.exchangeEdges=fc;function kt(e){e=nm(e),lo(e);let t=lc(e);uo(t),co(t,e);let n,r;for(;n=dc(t);)r=hc(t,e,n),fc(t,e,n,r)}function co(e,t){let n=Am(e,e.nodes());n=n.slice(0,n.length-1),n.forEach(r=>km(e,t,r))}function km(e,t,n){let r=e.node(n).parent,s=e.edge(n,r);s.cutvalue=cc(e,t,n)}function cc(e,t,n){let r=e.node(n).parent,s=!0,o=t.edge(n,r),i=0;o||(s=!1,o=t.edge(r,n)),i=o.weight;let a=t.nodeEdges(n);return a&&a.forEach(l=>{let c=l.v===n,u=c?l.w:l.v;if(u!==r){let d=c===s,f=t.edge(l).weight;if(i+=d?f:-f,jm(e,n,u)){let g=e.edge(n,u).cutvalue;i+=d?-g:g}}}),i}function uo(e,t){arguments.length<2&&(t=e.nodes()[0]),uc(e,{},1,t)}function uc(e,t,n,r,s){let o=n,i=e.node(r);t[r]=!0;let a=e.neighbors(r);return a&&a.forEach(l=>{Object.hasOwn(t,l)||(n=uc(e,t,n,l,r))}),i.low=o,i.lim=n++,s?i.parent=s:delete i.parent,n}function dc(e){return e.edges().find(t=>e.edge(t).cutvalue<0)}function hc(e,t,n){let r=n.v,s=n.w;t.hasEdge(r,s)||(r=n.w,s=n.v);let o=e.node(r),i=e.node(s),a=o,l=!1;return o.lim>i.lim&&(a=i,l=!0),t.edges().filter(c=>l===ai(e,e.node(c.v),a)&&l!==ai(e,e.node(c.w),a)).reduce((c,u)=>Vt(t,u)<Vt(t,c)?u:c)}function fc(e,t,n,r){let s=n.v,o=n.w;e.removeEdge(s,o),e.setEdge(r.v,r.w,{}),uo(e),co(e,t),Om(e,t)}function Om(e,t){let n=e.nodes().find(s=>!e.node(s).parent);if(!n)return;let r=Tm(e,[n]);r=r.slice(1),r.forEach(s=>{let o=e.node(s).parent,i=t.edge(s,o),a=!1;i||(i=t.edge(o,s),a=!0),t.node(s).rank=t.node(o).rank+(a?i.minlen:-i.minlen)})}function jm(e,t,n){return e.hasEdge(t,n)}function ai(e,t,n){return n.low<=t.lim&&t.lim<=n.lim}var Pm=Lm;function Lm(e){let t=e.graph().ranker;if(typeof t=="function")return t(e);switch(t){case"network-simplex":li(e);break;case"tight-tree":$m(e);break;case"longest-path":Dm(e);break;case"none":break;default:li(e)}}var Dm=lo;function $m(e){lo(e),lc(e)}function li(e){Mm(e)}var Fm=zm;function zm(e){let t=Bm(e),n=e.graph();Array.isArray(n.dummyChains)&&n.dummyChains.forEach(r=>{let s=e.node(r),o=s.edgeObj,i=Hm(e,t,o.v,o.w),a=i.path,l=i.lca,c=0,u=a[c],d=!0;for(;r!==o.w;){if(s=e.node(r),d){for(;(u=a[c])!==l&&e.node(u).maxRank<s.rank;)c++;u===l&&(d=!1)}if(!d){for(;c<a.length-1&&e.node(a[c+1]).minRank<=s.rank;)c++;u=a[c]}u!==void 0&&e.setParent(r,u),r=e.successors(r)[0]}})}function Hm(e,t,n,r){let s=[],o=[],i=Math.min(t[n].low,t[r].low),a=Math.max(t[n].lim,t[r].lim),l;l=n;do l=e.parent(l),s.push(l);while(l&&(t[l].low>i||a>t[l].lim));let c=l,u=r;for(;(u=e.parent(u))!==c;)o.push(u);return{path:s.concat(o.reverse()),lca:c}}function Bm(e){let t={},n=0;function r(s){let o=n;e.children(s).forEach(r),t[s]={low:o,lim:n++}}return e.children(Tr).forEach(r),t}function Gm(e){let t=tn(e,"root",{},"_root"),n=Um(e),r=Object.values(n),s=Ge(Math.max,r)-1,o=2*s+1;e.graph().nestingRoot=t,e.edges().forEach(a=>e.edge(a).minlen*=o);let i=qm(e)+1;e.children(Tr).forEach(a=>{pc(e,t,o,i,s,n,a)}),e.graph().nodeRankFactor=o}function pc(e,t,n,r,s,o,i){var a;let l=e.children(i);if(!l.length){i!==t&&e.setEdge(t,i,{weight:0,minlen:n});return}let c=oi(e,"_bt"),u=oi(e,"_bb"),d=e.node(i);e.setParent(c,i),d.borderTop=c,e.setParent(u,i),d.borderBottom=u,l.forEach(f=>{var g;pc(e,t,n,r,s,o,f);let p=e.node(f),y=p.borderTop?p.borderTop:f,x=p.borderBottom?p.borderBottom:f,v=p.borderTop?r:2*r,I=y!==x?1:s-((g=o[i])!=null?g:0)+1;e.setEdge(c,y,{weight:v,minlen:I,nestingEdge:!0}),e.setEdge(x,u,{weight:v,minlen:I,nestingEdge:!0})}),e.parent(i)||e.setEdge(t,c,{weight:0,minlen:s+((a=o[i])!=null?a:0)})}function Um(e){let t={};function n(r,s){let o=e.children(r);o&&o.length&&o.forEach(i=>n(i,s+1)),t[r]=s}return e.children(Tr).forEach(r=>n(r,1)),t}function qm(e){return e.edges().reduce((t,n)=>t+e.edge(n).weight,0)}function Vm(e){let t=e.graph();e.removeNode(t.nestingRoot),delete t.nestingRoot,e.edges().forEach(n=>{e.edge(n).nestingEdge&&e.removeEdge(n)})}var Km=Ym;function Ym(e){function t(n){let r=e.children(n),s=e.node(n);if(r.length&&r.forEach(t),s&&Object.hasOwn(s,"minRank")){s.borderLeft=[],s.borderRight=[];for(let o=s.minRank,i=s.maxRank+1;o<i;++o)ci(e,"borderLeft","_bl",n,s,o),ci(e,"borderRight","_br",n,s,o)}}e.children(Tr).forEach(t)}function ci(e,t,n,r,s,o){let i={width:0,height:0,rank:o,borderType:t},a=s[t][o-1],l=tn(e,"border",i,n);s[t][o]=l,e.setParent(l,r),a&&e.setEdge(a,l,{weight:1})}function Wm(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="lr"||n==="rl")&&gc(e)}function Xm(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="bt"||n==="rl")&&Qm(e),(n==="lr"||n==="rl")&&(Jm(e),gc(e))}function gc(e){e.nodes().forEach(t=>ui(e.node(t))),e.edges().forEach(t=>ui(e.edge(t)))}function ui(e){let t=e.width;e.width=e.height,e.height=t}function Qm(e){e.nodes().forEach(t=>es(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(es),Object.hasOwn(r,"y")&&es(r)})}function es(e){e.y=-e.y}function Jm(e){e.nodes().forEach(t=>ts(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(ts),Object.hasOwn(r,"x")&&ts(r)})}function ts(e){let t=e.x;e.x=e.y,e.y=t}function Zm(e,t=null){let n={},r=e.nodes().filter(l=>!e.children(l).length),s=r.map(l=>e.node(l).rank),o=xn(Ge(Math.max,s)+1).map(()=>[]);function i(l){if(n[l])return;n[l]=!0;let c=e.node(l);o[c.rank].push(l);let u=e.successors(l);u&&[...u].sort((d,f)=>a(d,f)).forEach(i)}r.sort((l,c)=>e.node(l).rank-e.node(c).rank).forEach(i);function a(l,c){return ac(t,e.node(l),e.node(c))}return o}function e0(e,t){let n=0;for(let r=1;r<t.length;++r)n+=t0(e,t[r-1],t[r]);return n}function t0(e,t,n){let r=cm(n,n.map((c,u)=>u)),s=t.flatMap(c=>{let u=e.outEdges(c);return u?u.map(d=>({pos:r[d.w],weight:e.edge(d).weight})).sort((d,f)=>d.pos-f.pos):[]}),o=1;for(;o<n.length;)o<<=1;let i=2*o-1;o-=1;let a=new Array(i).fill(0),l=0;return s.forEach(c=>{let u=c.pos+o;a[u]+=c.weight;let d=0;for(;u>0;)u%2&&(d+=a[u+1]),u=u-1>>1,a[u]+=c.weight;l+=c.weight*d}),l}function n0(e,t=[]){return t.map(n=>{let r=e.inEdges(n);if(!r||!r.length)return{v:n};{let s=r.reduce((o,i)=>{let a=e.edge(i),l=e.node(i.v);return{sum:o.sum+a.weight*l.order,weight:o.weight+a.weight}},{sum:0,weight:0});return{v:n,barycenter:s.sum/s.weight,weight:s.weight}}})}function r0(e,t){let n={};return e.forEach((r,s)=>{let o={indegree:0,in:[],out:[],vs:[r.v],i:s};r.barycenter!==void 0&&(o.barycenter=r.barycenter,o.weight=r.weight),n[r.v]=o}),t.edges().forEach(r=>{let s=n[r.v],o=n[r.w];s!==void 0&&o!==void 0&&(o.indegree++,s.out.push(o))}),s0(Object.values(n).filter(r=>!r.indegree))}function s0(e){let t=[];function n(s){return o=>{o.merged||(o.barycenter===void 0||s.barycenter===void 0||o.barycenter>=s.barycenter)&&o0(s,o)}}function r(s){return o=>{o.in.push(s),--o.indegree===0&&e.push(o)}}for(;e.length;){let s=e.pop();t.push(s),s.in.reverse().forEach(n(s)),s.out.forEach(r(s))}return t.filter(s=>!s.merged).map(s=>or(s,["vs","i","barycenter","weight"]))}function o0(e,t){let n=0,r=0;e.weight&&(n+=e.barycenter*e.weight,r+=e.weight),t.weight&&(n+=t.barycenter*t.weight,r+=t.weight),e.vs=t.vs.concat(e.vs),e.barycenter=n/r,e.weight=r,e.i=Math.min(t.i,e.i),t.merged=!0}function i0(e,t,n,r,s){let o={},i=null,a=null,l=s;typeof t=="boolean"?(l=t,o={}):t&&(o=t,i=n??null,a=r??null);let c=im(e,v=>Object.hasOwn(v,"barycenter")),u=c.lhs,d=c.rhs.sort((v,I)=>I.i-v.i),f=[],g=0,p=0,y=0;u.sort(a0(a,i,!!l));for(let[v,I]of Object.entries(o)){let m=u.findIndex(S=>S.vs[0]===v);u.splice(m+1,0,I)}y=di(f,d,y),u.forEach(v=>{y+=v.vs.length,f.push(v.vs),g+=v.barycenter*v.weight,p+=v.weight,y=di(f,d,y)});let x={vs:f.flat(1)};return p&&(x.barycenter=g/p,x.weight=p),x}function di(e,t,n){let r;for(;t.length&&(r=t[t.length-1]).i<=n;)t.pop(),e.push(r.vs),n++;return n}function a0(e,t,n){return(r,s)=>{if(r.barycenter<s.barycenter)return-1;if(r.barycenter>s.barycenter)return 1;if(e&&(typeof r.vs[0]=="string"||typeof s.vs[0]=="string")){let o=ac(t,e.node(r.vs[0]),e.node(s.vs[0]));if(o!==0)return o}return n?s.i-r.i:r.i-s.i}}function mc(e,t,n,r,s){var o,i,a,l,c,u,d,f,g,p,y;let x=null,v=s;typeof r=="boolean"?(v=r,x=null):r!==void 0&&(x=r);let I=e.children(t),m=e.node(t),S=m?m.borderLeft:void 0,E=m?m.borderRight:void 0,N={};S&&(I=I.filter(M=>M!==S&&M!==E));let R=n0(e,I);R.forEach(M=>{if(e.children(M.v).length){let{result:O}=mc(e,M.v,n,x,v);N[M.v]=O,Object.hasOwn(O,"barycenter")&&c0(M,O)}});let A=r0(R,n);l0(A,N);let k={},P=!1;for(let M=0;M<A.length;M++)for(let O=M+1;O<A.length;O++)if(!(!A[M]||!A[O]||!((o=A[M])!=null&&o.barycenter)||!((i=A[O])!=null&&i.barycenter))&&((a=A[M])==null?void 0:a.barycenter)===A[O].barycenter){let b=(c=(l=A[M])==null?void 0:l.vs[0])!=null?c:"",w=(d=(u=A[O])==null?void 0:u.vs[0])!=null?d:"",T=e.node(b),j=e.node(w);if(T.dummy==="edge"&&j.dummy==="edge"&&((f=T.edgeObj)==null?void 0:f.v)===((g=j.edgeObj)==null?void 0:g.v)&&((p=T.edgeObj)==null?void 0:p.w)===((y=j.edgeObj)==null?void 0:y.w))if(T.edgeLabel.reversed){k[w]=A[M],A.splice(M,1),M--;break}else k[b]||(k[b]=A[O],A.splice(O,1),O--);else P=!0}let _=i0(A,k,x,e,v);if(S&&E){_.vs=[S,_.vs,E].flat(1);let M=e.predecessors(S);if(M&&M.length){let O=e.node(M[0]),b=e.predecessors(E),w=e.node(b[0]);Object.hasOwn(_,"barycenter")||(_.barycenter=0,_.weight=0),_.barycenter=(_.barycenter*_.weight+O.order+w.order)/(_.weight+2),_.weight+=2}}return Object.defineProperty(_,"result",{value:_,enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(_,"usedBias",{value:P,enumerable:!1,configurable:!0,writable:!0}),_}function l0(e,t){e.forEach(n=>{n.vs=n.vs.flatMap(r=>t[r]?t[r].vs:r)})}function c0(e,t){e.barycenter!==void 0?(e.barycenter=(e.barycenter*e.weight+t.barycenter*t.weight)/(e.weight+t.weight),e.weight+=t.weight):(e.barycenter=t.barycenter,e.weight=t.weight)}function u0(e,t,n,r){r||(r=e.nodes());let s=d0(e),o=new Ve({compound:!0}).setGraph({root:s}).setDefaultNodeLabel(i=>e.node(i));return r.forEach(i=>{let a=e.node(i),l=e.parent(i);if(a.rank===t||a.minRank<=t&&t<=a.maxRank){o.setNode(i),o.setParent(i,l||s);let c=e[n](i);c&&c.forEach(u=>{let d=u.v===i?u.w:u.v,f=o.edge(d,i),g=f!==void 0?f.weight:0;o.setEdge(d,i,{weight:e.edge(u).weight+g})}),Object.hasOwn(a,"minRank")&&o.setNode(i,{borderLeft:a.borderLeft[t],borderRight:a.borderRight[t]})}}),o}function d0(e){let t;for(;e.hasNode(t=ao("_root")););return t}function h0(e,t,n){let r={},s;n.forEach(o=>{let i=e.parent(o),a,l;for(;i;){if(a=e.parent(i),a?(l=r[a],r[a]=i):(l=s,s=i),l&&l!==i){t.setEdge(l,i);return}i=a}})}function vc(e,t={},n=null){if(typeof t.customOrder=="function"){t.customOrder(e,vc);return}let r=ic(e),s=hi(e,xn(1,r+1),"inEdges"),o=hi(e,xn(r-1,-1,-1),"outEdges"),i=Zm(e,n);if(fi(e,i),t.disableOptimalOrderHeuristic)return;let a=Number.POSITIVE_INFINITY,l,c=t.constraints||[];for(let u=0,d=0;d<4;++u,++d){f0(u%2?s:o,u%4>=2,c,n),i=Rr(e);let f=e0(e,i);f<a?(d=0,l=Object.assign({},i),a=f):f===a&&(l=structuredClone(i))}fi(e,l)}function hi(e,t,n){let r=new Map,s=(o,i)=>{r.has(o)||r.set(o,[]),r.get(o).push(i)};for(let o of e.nodes()){let i=e.node(o);if(typeof i.rank=="number"&&s(i.rank,o),typeof i.minRank=="number"&&typeof i.maxRank=="number")for(let a=i.minRank;a<=i.maxRank;a++)a!==i.rank&&s(a,o)}return t.map(function(o){return u0(e,o,n,r.get(o)||[])})}function f0(e,t,n,r){let s=!0,o=new Ve;e.forEach(function(i){n.forEach(u=>o.setEdge(u.left,u.right));let a=i.graph().root,{result:l,usedBias:c}=mc(i,a,o,r,s);t&&c&&(s=!s),l.vs.forEach((u,d)=>i.node(u).order=d),h0(i,o,l.vs)})}function fi(e,t){Object.values(t).forEach(n=>n.forEach((r,s)=>e.node(r).order=s))}function p0(e,t){let n={};function r(s,o){let i=0,a=0,l=s.length,c=o[o.length-1];return o.forEach((u,d)=>{let f=m0(e,u),g=f?e.node(f).order:l;(f||u===c)&&(o.slice(a,d+1).forEach(p=>{let y=e.predecessors(p);y&&y.forEach(x=>{let v=e.node(x),I=v.order;(I<i||g<I)&&!(v.dummy&&e.node(p).dummy)&&yc(n,x,p)})}),a=d+1,i=g)}),o}return t.length&&t.reduce(r),n}function g0(e,t){let n={};function r(i){var a;return((a=e.node(i))==null?void 0:a.dummy)==="border"}if(!e.nodes().some(r))return n;function s(i,a,l,c,u){xn(a,l).forEach(d=>{let f=i[d];if(f!==void 0&&e.node(f).dummy){let g=e.predecessors(f);g&&g.forEach(p=>{if(p===void 0)return;let y=e.node(p);y.dummy&&(y.order<c||y.order>u)&&yc(n,p,f)})}})}function o(i,a){let l=-1,c=-1,u=0;return a.forEach((d,f)=>{if(r(d)){let g=e.predecessors(d);if(g&&g.length){let p=g[0];if(p===void 0)return;c=e.node(p).order,s(a,u,f,l,c),u=f,l=c}}s(a,u,a.length,c,i.length)}),a}return t.length&&t.reduce(o),n}function m0(e,t){if(e.node(t).dummy){let n=e.predecessors(t);if(n)return n.find(r=>e.node(r).dummy)}}function yc(e,t,n){if(t>n){let s=t;t=n,n=s}let r=e[t];r||(e[t]=r={}),r[n]=!0}function v0(e,t,n){if(t>n){let s=t;t=n,n=s}let r=e[t];return r!==void 0&&Object.hasOwn(r,n)}function y0(e,t,n,r,s){let o={},i={},a={};return t.forEach(l=>{l.forEach((c,u)=>{o[c]=c,i[c]=c,a[c]=u})}),t.forEach(l=>{let c=-1,u=-1,d=!1,f=l,g=l.findIndex(p=>s?.includes(p)||pi(p,e,s));g>0&&(f=[l[g],...l.slice(0,g),...l.slice(g+1)],d=!0),f.forEach(p=>{var y;let x=r(p);if(x&&x.length){s!=null&&s.includes(p)&&(x=x.filter(m=>pi(m,e,s)));let v=x.sort((m,S)=>{let E=a[m],N=a[S];return(E!==void 0?E:0)-(N!==void 0?N:0)}),I=(v.length-1)/2;for(let m=Math.floor(I),S=Math.ceil(I);m<=S;++m){let E=v[m];if(E===void 0)continue;let N=a[E];if(N!==void 0&&i[p]===p&&c<N&&a[E]!==u&&!v0(n,p,E)){let R=o[E];R!==void 0&&(i[E]=p,i[p]=o[p]=R,c=N,d&&(c=-1,u=(y=a[E])!=null?y:-1,d=!1))}}}})}),{root:o,align:i}}function b0(e,t,n,r,s=!1){let o={},i=x0(e,t,n,s),a=s?"borderLeft":"borderRight";function l(g,p){let y=i.nodes().slice(),x={},v=y.pop();for(;v;){if(x[v])g(v);else{x[v]=!0,y.push(v);for(let I of p(v))y.push(I)}v=y.pop()}}function c(g){let p=i.inEdges(g);p?o[g]=p.reduce((y,x)=>{var v;let I=(v=o[x.v])!=null?v:0,m=i.edge(x);return Math.max(y,I+(m!==void 0?m:0))},0):o[g]=0}function u(g){let p=i.outEdges(g),y=Number.POSITIVE_INFINITY;p&&(y=p.reduce((v,I)=>{let m=o[I.w],S=i.edge(I);return Math.min(v,(m!==void 0?m:0)-(S!==void 0?S:0))},Number.POSITIVE_INFINITY));let x=e.node(g);y!==Number.POSITIVE_INFINITY&&x.borderType!==a&&(o[g]=Math.max(o[g]!==void 0?o[g]:0,y))}function d(g){return i.predecessors(g)||[]}function f(g){return i.successors(g)||[]}return l(c,d),l(u,f),Object.keys(r).forEach(g=>{var p;let y=n[g];y!==void 0&&(o[g]=(p=o[y])!=null?p:0)}),o}function x0(e,t,n,r){let s=new Ve,o=e.graph(),i=C0(o.nodesep,o.edgesep,r);return t.forEach(a=>{let l;a.forEach(c=>{let u=n[c];if(u!==void 0){if(s.setNode(u),l!==void 0){let d=n[l];if(d!==void 0){let f=s.edge(d,u);s.setEdge(d,u,Math.max(i(e,c,l),f||0))}}l=c}})}),s}function S0(e,t){return Object.values(t).reduce((n,r)=>{let s=Number.NEGATIVE_INFINITY,o=Number.POSITIVE_INFINITY;Object.entries(r).forEach(([a,l])=>{let c=N0(e,a)/2;s=Math.max(l+c,s),o=Math.min(l-c,o)});let i=s-o;return i<n[0]&&(n=[i,r]),n},[Number.POSITIVE_INFINITY,null])[1]}function I0(e,t){let n=Object.values(t),r=Ge(Math.min,n),s=Ge(Math.max,n);["u","d"].forEach(o=>{["l","r"].forEach(i=>{let a=o+i,l=e[a];if(!l||l===t)return;let c=Object.values(l),u=r-Ge(Math.min,c);i!=="l"&&(u=s-Ge(Math.max,c)),u&&(e[a]=_r(l,d=>d+u))})})}function w0(e,t=void 0){let n=e.ul;return n?_r(n,(r,s)=>{var o,i;if(t){let l=e[t.toLowerCase()];if(l&&l[s]!==void 0)return l[s]}let a=Object.values(e).map(l=>{let c=l[s];return c!==void 0?c:0}).sort((l,c)=>l-c);return(((o=a[1])!=null?o:0)+((i=a[2])!=null?i:0))/2}):{}}function E0(e,t){let n=Rr(e),r=Object.assign(p0(e,n),g0(e,n)),s={},o;return["u","d"].forEach(i=>{o=i==="u"?n:Object.values(n).reverse(),["l","r"].forEach(a=>{a==="r"&&(o=o.map(u=>Object.values(u).reverse()));let l=y0(e,o,r,u=>(i==="u"?e.predecessors(u):e.successors(u))||[],t),c=b0(e,o,l.root,l.align,a==="r");a==="r"&&(c=_r(c,u=>-u)),s[i+a]=c})}),I0(s,S0(e,s)),w0(s,e.graph().align)}function C0(e,t,n){return(r,s,o)=>{let i=r.node(s),a=r.node(o),l=0,c;if(l+=i.width/2,Object.hasOwn(i,"labelpos"))switch(i.labelpos.toLowerCase()){case"l":c=-i.width/2;break;case"r":c=i.width/2}if(c&&(l+=n?c:-c),c=void 0,l+=(i.dummy?t:e)/2,l+=(a.dummy?t:e)/2,l+=a.width/2,Object.hasOwn(a,"labelpos"))switch(a.labelpos.toLowerCase()){case"l":c=a.width/2;break;case"r":c=-a.width/2}return c&&(l+=n?c:-c),l}}function N0(e,t){return e.node(t).width}function pi(e,t,n){var r;if(!n)return!1;let s=(r=t.node(e))==null?void 0:r.edgeObj;if(!s||t.node(e).edgeLabel.reversed)return!1;let o=n.indexOf(s?.v),i=n.indexOf(s?.w);return o!==-1&&i!==-1&&o===(i+1)%n.length||o===(i-1)%n.length}function R0(e,t){e=sc(e),_0(e),Object.entries(E0(e,t)).forEach(([n,r])=>e.node(n).x=r)}function _0(e){let t=Rr(e),n=e.graph(),r=n.ranksep,s=n.rankalign,o=0;t.forEach(i=>{let a=i.reduce((l,c)=>{var u;let d=(u=e.node(c).height)!=null?u:0;return l>d?l:d},0);i.forEach(l=>{let c=e.node(l);s==="top"?c.y=o+c.height/2:s==="bottom"?c.y=o+a-c.height/2:c.y=o+a/2}),o+=a+r})}var gi=new WeakMap;function T0(e,t={}){return bc(e,am,t),e}function mi(e,t,n){let r=t;for(;r!==void 0;){let s=e.parent(r);if(s===n)return r;r=s}}function bc(e,t,n){var r;let s=e.nodes().filter(I=>e.children(I).length),o={};s.forEach(I=>{let m=e.node(I);if(m&&m.rankdir){let S=new Ve({multigraph:!0,compound:!0});S.setGraph({rankdir:m.rankdir});let E=e.children(I);E.forEach(b=>{let w={...e.node(b)};S.setNode(b,w);let T=e.parent(b);T&&T!==I&&E.includes(T)&&S.setParent(b,T)});let N=new Set;e.edges().forEach(b=>{let w=mi(e,b.v,I),T=mi(e,b.w,I);if(w===b.v&&T===b.w)S.setEdge(b,{...e.edge(b)});else if(w&&T&&w!==T){let j=`${w}\0${T}`;N.has(j)||(N.add(j),S.setEdge(w,T,{...e.edge(b)}))}}),bc(S,t,n);let R=Si(S);yi(R,t,n,null),bi(S,R);let A=1/0,k=1/0,P=-1/0,_=-1/0;S.nodes().forEach(b=>{if(b===I)return;let w=S.node(b);w&&typeof w.x=="number"&&typeof w.y=="number"&&typeof w.width=="number"&&typeof w.height=="number"&&(A=Math.min(A,w.x-w.width/2),P=Math.max(P,w.x+w.width/2),k=Math.min(k,w.y-w.height/2),_=Math.max(_,w.y+w.height/2))}),(!isFinite(A)||!isFinite(k)||!isFinite(P)||!isFinite(_))&&(A=k=0,P=_=0);let M=P-A,O=_-k;o[I]={minX:A,minY:k,maxX:P,maxY:_,width:M,height:O,offsetX:A,offsetY:k},m._dagreClusterSubgraph=S}});let i=[],a=I=>{let m=[],S=(e.children(I)||[]).filter(E=>E!==I);for(;S.length>0;){let E=S.shift();m.push(E),(e.children(E)||[]).filter(N=>N!==E).forEach(N=>S.push(N))}return m},l=new Map;s.forEach(I=>{let m=e.node(I);m&&m.rankdir&&o[I]&&l.set(I,(e.children(I)||[]).filter(S=>S!==I))});let c=new Set([...l.values()].flat()),u=new Map;l.forEach((I,m)=>{c.has(m)||u.set(m,a(m))});let d=new Set([...u.values()].flat()),f=I=>{for(let[m,S]of u)if(S.includes(I))return m;return I},g=[];e.edges().forEach(I=>{(d.has(I.v)||d.has(I.w))&&g.push({edge:I,label:e.edge(I)})});let p=new Map;d.forEach(I=>{let m=e.parent(I);p.set(I,typeof m=="string"?m:void 0)}),u.forEach((I,m)=>{let S=e.node(m),E=[];I.forEach(A=>{let k=e.node(A);k&&(E.push({id:A,node:k,parent:p.get(A)}),e.removeNode(A))});let N=g.filter(({edge:A})=>I.includes(A.v)||I.includes(A.w)),R=o[m];S&&(i.push({clusterId:m,subgraph:S._dagreClusterSubgraph,bounds:R,children:I,removedNodes:E,removedEdges:N}),S.width=R.width,S.height=R.height)});let y=new Set;g.forEach(({edge:I,label:m})=>{let S=f(I.v),E=f(I.w);if(S!==E&&e.hasNode(S)&&e.hasNode(E)){let N=`${S}\0${E}`;y.has(N)||(y.add(N),e.setEdge(S,E,{...m,width:0,height:0}))}});let x=Si(e),v=yi(x,t,n,(r=gi.get(e))!=null?r:null);gi.set(e,v),bi(e,x),y.forEach(I=>{let m=I.indexOf("\0"),S=I.slice(0,m),E=I.slice(m+1);e.hasEdge(S,E)&&e.removeEdge(S,E)}),i.forEach(({clusterId:I,subgraph:m,bounds:S,removedNodes:E,removedEdges:N})=>{var R,A;let k=e.node(I),P=(R=k?.x)!=null?R:0,_=(A=k?.y)!=null?A:0,M=(S.minX+S.maxX)/2,O=(S.minY+S.maxY)/2;E.forEach(({id:b,node:w,parent:T})=>{e.setNode(b,w),T!==void 0&&e.setParent(b,T)}),N.forEach(({edge:b,label:w})=>{e.setEdge(b,w)}),m.nodes().forEach(b=>{if(b===I)return;let w=m.node(b),T=e.node(b);T&&w&&typeof w.x=="number"&&typeof w.y=="number"&&(T.x=P+(w.x-M),T.y=_+(w.y-O))}),vi(e,m,P-M,_-O),delete k._dagreClusterSubgraph}),s.forEach(I=>{var m,S;let E=e.node(I),N=o[I];if(E&&E.rankdir&&E._dagreClusterSubgraph&&N){let R=E._dagreClusterSubgraph,A=(m=E.x)!=null?m:0,k=(S=E.y)!=null?S:0,P=(N.minX+N.maxX)/2,_=(N.minY+N.maxY)/2;R.nodes().forEach(M=>{if(M===I)return;let O=R.node(M),b=e.node(M);if(b&&O&&typeof O.x=="number"&&typeof O.y=="number"){let w=O.x-P,T=O.y-_;b.x=A+w,b.y=k+T}}),vi(e,R,A-P,k-_),delete E._dagreClusterSubgraph}})}function vi(e,t,n,r){t.edges().forEach(s=>{if(!e.hasEdge(s))return;let o=t.edge(s),i=e.edge(s);i.points=o.points.map(a=>({x:a.x+n,y:a.y+r})),Object.hasOwn(o,"x")&&(i.x=o.x+n,i.y=o.y+r)})}function yi(e,t,n,r=null){var s,o;let i=n?.useDynamic!==!1,a=i&&(s=r?.graph)!=null?s:null,l=i&&(o=r?.rawNodes)!=null?o:null;t(" makeSpaceForEdgeLabels",()=>D0(e)),t(" removeSelfEdges",()=>V0(e)),t(" acyclic",()=>ym(e,a)),t(" nestingGraph.run",()=>Gm(e)),t(" rank",()=>Pm(sc(e))),t(" injectEdgeLabelProxies",()=>$0(e)),t(" removeEmptyRanks",()=>sm(e)),t(" nestingGraph.cleanup",()=>Vm(e)),t(" normalizeRanks",()=>rm(e)),t(" assignRankMinMax",()=>F0(e)),t(" removeEdgeLabelProxies",()=>z0(e)),t(" normalize.run",()=>Im(e)),t(" parentDummyChains",()=>Fm(e)),t(" addBorderSegments",()=>Km(e)),t(" order",()=>vc(e,n,l)),t(" insertSelfEdges",()=>K0(e)),t(" adjustCoordinateSystem",()=>Wm(e)),t(" position",()=>R0(e,n.corePath)),t(" positionSelfEdges",()=>Y0(e));let c=JSON.parse(JSON.stringify(e._nodes));return t(" removeBorderNodes",()=>q0(e)),t(" normalize.undo",()=>Em(e)),t(" fixupEdgeLabelCoords",()=>G0(e)),t(" undoCoordinateSystem",()=>Xm(e)),t(" translateGraph",()=>H0(e)),t(" assignNodeIntersects",()=>B0(e)),t(" reversePoints",()=>U0(e)),t(" acyclic.undo",()=>xm(e)),{graph:e,rawNodes:c}}function bi(e,t){e.nodes().forEach(n=>{let r=e.node(n),s=t.node(n);r&&(r.x=s.x,r.y=s.y,r.order=s.order,r.rank=s.rank,t.children(n).length&&(r.width=s.width,r.height=s.height))}),e.edges().forEach(n=>{let r=e.edge(n),s=t.edge(n);r.points=s.points,Object.hasOwn(s,"x")&&(r.x=s.x,r.y=s.y)}),e.graph().width=t.graph().width,e.graph().height=t.graph().height}var A0=["nodesep","edgesep","ranksep","marginx","marginy"],M0={ranksep:50,edgesep:20,nodesep:50,rankdir:"TB",rankalign:"center"},k0=["acyclicer","ranker","rankdir","align","rankalign"],O0=["width","height","rank"],xi={width:0,height:0},j0=["minlen","weight","width","height","labeloffset"],P0={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},L0=["labelpos"];function Si(e){let t=new Ve({multigraph:!0,compound:!0}),n=rs(e.graph());return t.setGraph(Object.assign({},M0,ns(n,A0),or(n,k0))),e.nodes().forEach(r=>{let s=ns(rs(e.node(r)),O0);Object.keys(xi).forEach(i=>{s[i]===void 0&&(s[i]=xi[i])}),t.setNode(r,s);let o=e.parent(r);o!==void 0&&t.setParent(r,o)}),e.edges().forEach(r=>{let s=rs(e.edge(r));t.setEdge(r,Object.assign({},P0,ns(s,j0),or(s,L0)))}),t}function D0(e){let t=e.graph();t.ranksep/=2,e.edges().forEach(n=>{var r;let s=e.edge(n);s.minlen*=2,((r=s.labelpos)!=null?r:"r").toLowerCase()!=="c"&&(t.rankdir==="TB"||t.rankdir==="BT"?s.width+=s.labeloffset:s.height+=s.labeloffset)})}function $0(e){e.edges().forEach(t=>{let n=e.edge(t);if(n.width&&n.height){let r=e.node(t.v);tn(e,"edge-proxy",{rank:(e.node(t.w).rank-r.rank)/2+r.rank,e:t},"_ep")}})}function F0(e){let t=0;e.nodes().forEach(n=>{let r=e.node(n);r.borderTop&&(r.minRank=e.node(r.borderTop).rank,r.maxRank=e.node(r.borderBottom).rank,t=Math.max(t,r.maxRank))}),e.graph().maxRank=t}function z0(e){e.nodes().forEach(t=>{let n=e.node(t);if(n.dummy==="edge-proxy"){let r=n;e.edge(r.e).labelRank=n.rank,e.removeNode(t)}})}function H0(e){let t=Number.POSITIVE_INFINITY,n=0,r=Number.POSITIVE_INFINITY,s=0,o=e.graph(),i=o.marginx||0,a=o.marginy||0;function l(c){let u=c.x,d=c.y,f=c.width,g=c.height;t=Math.min(t,u-f/2),n=Math.max(n,u+f/2),r=Math.min(r,d-g/2),s=Math.max(s,d+g/2)}e.nodes().forEach(c=>l(e.node(c))),e.edges().forEach(c=>{let u=e.edge(c);Object.hasOwn(u,"x")&&l(u)}),t-=i,r-=a,e.nodes().forEach(c=>{let u=e.node(c);u.x-=t,u.y-=r}),e.edges().forEach(c=>{let u=e.edge(c);u.points.forEach(d=>{d.x-=t,d.y-=r}),Object.hasOwn(u,"x")&&(u.x-=t),Object.hasOwn(u,"y")&&(u.y-=r)}),o.width=n-t+i,o.height=s-r+a}function B0(e){e.edges().forEach(t=>{if(t.v===t.w)return;let n=e.edge(t),r=e.node(t.v),s=e.node(t.w),o,i;n.points?(o=n.points[0],i=n.points[n.points.length-1]):(n.points=[],o=s,i=r),n.points.unshift(si(r,o)),n.points.push(si(s,i))})}function G0(e){e.edges().forEach(t=>{let n=e.edge(t);if(Object.hasOwn(n,"x"))switch((n.labelpos==="l"||n.labelpos==="r")&&(n.width-=n.labeloffset),n.labelpos){case"l":n.x-=n.width/2+n.labeloffset;break;case"r":n.x+=n.width/2+n.labeloffset}})}function U0(e){e.edges().forEach(t=>{let n=e.edge(t);n.reversed&&n.points.reverse()})}function q0(e){e.nodes().forEach(t=>{if(e.children(t).length){let n=e.node(t),r=e.node(n.borderTop),s=e.node(n.borderBottom),o=e.node(n.borderLeft[n.borderLeft.length-1]),i=e.node(n.borderRight[n.borderRight.length-1]);n.width=Math.abs(i.x-o.x),n.height=Math.abs(s.y-r.y),n.x=o.x+n.width/2,n.y=r.y+n.height/2}}),e.nodes().forEach(t=>{e.node(t).dummy==="border"&&e.removeNode(t)})}function V0(e){e.edges().forEach(t=>{if(t.v===t.w){let n=e.node(t.v);n.selfEdges||(n.selfEdges=[]),n.selfEdges.push({e:t,label:e.edge(t)}),e.removeEdge(t)}})}function K0(e){Rr(e).forEach(t=>{let n=0;t.forEach((r,s)=>{let o=e.node(r);typeof o.rank!="number"&&(o.rank=0),o.order=s+n,(o.selfEdges||[]).forEach(i=>{tn(e,"selfedge",{width:i.label.width,height:i.label.height,rank:o.rank,order:s+ ++n,e:i.e,edgeLabel:i.label},"_se"),(!Array.isArray(i.label.points)||i.label.points.length!==7)&&(i.label.points=[{x:0,y:-10},{x:0,y:-10},{x:0,y:0},{x:0,y:10},{x:0,y:10},{x:0,y:0},{x:0,y:0}])}),delete o.selfEdges})})}function Y0(e){e.nodes().forEach(t=>{let n=e.node(t),r=s=>typeof s=="number"&&isFinite(s);if(n.dummy==="selfedge"){let s=n,o=e.node(s.e.v),i=r(o?.x)?o.x:0,a=r(o?.y)?o.y:0,l=r(o?.width)?o.width:0,c=r(o?.height)?o.height:0,u=r(n.x)?n.x:i,d=r(n.y)?n.y:a,f=l/2,g=c/2;s.edgeLabel.points=[{x:u+f,y:d-g},{x:u+f,y:d-g},{x:u,y:d},{x:u-f,y:d+g},{x:u-f,y:d+g},{x:u,y:d},{x:u,y:d}],s.edgeLabel.x=u,s.edgeLabel.y=d,e.setEdge(s.e,s.edgeLabel),e.removeNode(t)}else n&&Array.isArray(n.selfEdges)&&n.selfEdges.forEach(s=>{if(!Array.isArray(s.label.points)||s.label.points.length!==7){let o=r(n.x)?n.x:0,i=r(n.y)?n.y:0,a=r(n.width)?n.width:0,l=r(n.height)?n.height:0,c=a/2,u=l/2;s.label.points=[{x:o+c,y:i-u},{x:o+c,y:i-u},{x:o,y:i},{x:o-c,y:i+u},{x:o-c,y:i+u},{x:o,y:i},{x:o,y:i}]}})})}function ns(e,t){return _r(or(e,t),Number)}function rs(e){let t={};return e&&Object.entries(e).forEach(([n,r])=>{typeof n=="string"&&(n=n.toLowerCase()),t[n]=r}),t}var un=({schemaName:e,tableName:t})=>e?`${e}.${t}`:t,W0=(e,t)=>{const n=(t==="all"?e:e.filter(r=>r.schemaName===t)).map(r=>({...r,id:un(r)}));return{tables:n,edges:n.flatMap(r=>r.columns.flatMap(s=>{const{referencedTable:o,referencedSchema:i,referencedColumn:a}=s;if(!o||!a)return[];const l=n.find(c=>c.tableName===o&&c.schemaName===i);return l?{id:`${r.id}.${s.columnName}->${l.id}`,source:r.id,sourceColumn:s.columnName,target:l.id,targetColumn:a}:[]}))}},X0=(e,t)=>{const n=new Xl.Graph;n.setDefaultEdgeLabel(()=>({})),n.setGraph({rankdir:"LR",ranksep:160,nodesep:60});for(const r of e)n.setNode(r.id,{width:r.width,height:r.height});for(const r of t)n.setEdge(r.target,r.source);return T0(n),new Map(e.map(r=>{const{x:s,y:o}=n.node(r.id);return[r.id,{x:s-r.width/2,y:o-r.height/2}]}))},Q0=(e,t)=>{const n=new Set([t]),r=new Set,s=new Set;for(const o of e)o.source!==t&&o.target!==t||(n.add(o.source).add(o.target),r.add(`${o.source}.${o.sourceColumn}`).add(`${o.target}.${o.targetColumn}`),s.add(o.id));return{tables:n,columns:r,edgeIds:s}},J0=e=>{const t=Math.max(e.tableName.length,...e.columns.map(n=>n.columnName.length+n.dataTypeLabel.length+4));return Math.min(Math.max(t*7.5+72,220),420)};function ue(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=ue(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var Z0={value:()=>{}};function Ar(){for(var e=0,t=arguments.length,n={},r;e<t;++e){if(!(r=arguments[e]+"")||r in n||/[\s.]/.test(r))throw new Error("illegal type: "+r);n[r]=[]}return new Jn(n)}function Jn(e){this._=e}function ev(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",s=n.indexOf(".");if(s>=0&&(r=n.slice(s+1),n=n.slice(0,s)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}Jn.prototype=Ar.prototype={constructor:Jn,on:function(e,t){var n=this._,r=ev(e+"",n),s,o=-1,i=r.length;if(arguments.length<2){for(;++o<i;)if((s=(e=r[o]).type)&&(s=tv(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++o<i;)if(s=(e=r[o]).type)n[s]=Ii(n[s],e.name,t);else if(t==null)for(s in n)n[s]=Ii(n[s],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new Jn(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,o;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(o=this._[e],r=0,s=o.length;r<s;++r)o[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],s=0,o=r.length;s<o;++s)r[s].value.apply(t,n)}};function tv(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function Ii(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=Z0,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var nv="http://www.w3.org/1999/xhtml",wi={svg:"http://www.w3.org/2000/svg",xhtml:nv,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Mr(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),wi.hasOwnProperty(t)?{space:wi[t],local:e}:e}function rv(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n==="http://www.w3.org/1999/xhtml"&&t.documentElement.namespaceURI==="http://www.w3.org/1999/xhtml"?t.createElement(e):t.createElementNS(n,e)}}function sv(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function xc(e){var t=Mr(e);return(t.local?sv:rv)(t)}function ov(){}function ho(e){return e==null?ov:function(){return this.querySelector(e)}}function iv(e){typeof e!="function"&&(e=ho(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var o=t[s],i=o.length,a=r[s]=new Array(i),l,c,u=0;u<i;++u)(l=o[u])&&(c=e.call(l,l.__data__,u,o))&&("__data__"in l&&(c.__data__=l.__data__),a[u]=c);return new Ie(r,this._parents)}function av(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function lv(){return[]}function Sc(e){return e==null?lv:function(){return this.querySelectorAll(e)}}function cv(e){return function(){return av(e.apply(this,arguments))}}function uv(e){typeof e=="function"?e=cv(e):e=Sc(e);for(var t=this._groups,n=t.length,r=[],s=[],o=0;o<n;++o)for(var i=t[o],a=i.length,l,c=0;c<a;++c)(l=i[c])&&(r.push(e.call(l,l.__data__,c,i)),s.push(l));return new Ie(r,s)}function Ic(e){return function(){return this.matches(e)}}function wc(e){return function(t){return t.matches(e)}}var dv=Array.prototype.find;function hv(e){return function(){return dv.call(this.children,e)}}function fv(){return this.firstElementChild}function pv(e){return this.select(e==null?fv:hv(typeof e=="function"?e:wc(e)))}var gv=Array.prototype.filter;function mv(){return Array.from(this.children)}function vv(e){return function(){return gv.call(this.children,e)}}function yv(e){return this.selectAll(e==null?mv:vv(typeof e=="function"?e:wc(e)))}function bv(e){typeof e!="function"&&(e=Ic(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var o=t[s],i=o.length,a=r[s]=[],l,c=0;c<i;++c)(l=o[c])&&e.call(l,l.__data__,c,o)&&a.push(l);return new Ie(r,this._parents)}function Ec(e){return new Array(e.length)}function xv(){return new Ie(this._enter||this._groups.map(Ec),this._parents)}function ir(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}ir.prototype={constructor:ir,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};function Sv(e){return function(){return e}}function Iv(e,t,n,r,s,o){for(var i=0,a,l=t.length,c=o.length;i<c;++i)(a=t[i])?(a.__data__=o[i],r[i]=a):n[i]=new ir(e,o[i]);for(;i<l;++i)(a=t[i])&&(s[i]=a)}function wv(e,t,n,r,s,o,i){var a,l,c=new Map,u=t.length,d=o.length,f=new Array(u),g;for(a=0;a<u;++a)(l=t[a])&&(f[a]=g=i.call(l,l.__data__,a,t)+"",c.has(g)?s[a]=l:c.set(g,l));for(a=0;a<d;++a)g=i.call(e,o[a],a,o)+"",(l=c.get(g))?(r[a]=l,l.__data__=o[a],c.delete(g)):n[a]=new ir(e,o[a]);for(a=0;a<u;++a)(l=t[a])&&c.get(f[a])===l&&(s[a]=l)}function Ev(e){return e.__data__}function Cv(e,t){if(!arguments.length)return Array.from(this,Ev);var n=t?wv:Iv,r=this._parents,s=this._groups;typeof e!="function"&&(e=Sv(e));for(var o=s.length,i=new Array(o),a=new Array(o),l=new Array(o),c=0;c<o;++c){var u=r[c],d=s[c],f=d.length,g=Nv(e.call(u,u&&u.__data__,c,r)),p=g.length,y=a[c]=new Array(p),x=i[c]=new Array(p);n(u,d,y,x,l[c]=new Array(f),g,t);for(var v=0,I=0,m,S;v<p;++v)if(m=y[v]){for(v>=I&&(I=v+1);!(S=x[I])&&++I<p;);m._next=S||null}}return i=new Ie(i,r),i._enter=a,i._exit=l,i}function Nv(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function Rv(){return new Ie(this._exit||this._groups.map(Ec),this._parents)}function _v(e,t,n){var r=this.enter(),s=this,o=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(s=t(s),s&&(s=s.selection())),n==null?o.remove():n(o),r&&s?r.merge(s).order():s}function Tv(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,o=r.length,i=Math.min(s,o),a=new Array(s),l=0;l<i;++l)for(var c=n[l],u=r[l],d=c.length,f=a[l]=new Array(d),g,p=0;p<d;++p)(g=c[p]||u[p])&&(f[p]=g);for(;l<s;++l)a[l]=n[l];return new Ie(a,this._parents)}function Av(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,o=r[s],i;--s>=0;)(i=r[s])&&(o&&i.compareDocumentPosition(o)^4&&o.parentNode.insertBefore(i,o),o=i);return this}function Mv(e){e||(e=kv);function t(d,f){return d&&f?e(d.__data__,f.__data__):!d-!f}for(var n=this._groups,r=n.length,s=new Array(r),o=0;o<r;++o){for(var i=n[o],a=i.length,l=s[o]=new Array(a),c,u=0;u<a;++u)(c=i[u])&&(l[u]=c);l.sort(t)}return new Ie(s,this._parents).order()}function kv(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function Ov(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function jv(){return Array.from(this)}function Pv(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,o=r.length;s<o;++s){var i=r[s];if(i)return i}return null}function Lv(){let e=0;for(const t of this)++e;return e}function Dv(){return!this.node()}function $v(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var s=t[n],o=0,i=s.length,a;o<i;++o)(a=s[o])&&e.call(a,a.__data__,o,s);return this}function Fv(e){return function(){this.removeAttribute(e)}}function zv(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Hv(e,t){return function(){this.setAttribute(e,t)}}function Bv(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function Gv(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function Uv(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function qv(e,t){var n=Mr(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((t==null?n.local?zv:Fv:typeof t=="function"?n.local?Uv:Gv:n.local?Bv:Hv)(n,t))}function Cc(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function Vv(e){return function(){this.style.removeProperty(e)}}function Kv(e,t,n){return function(){this.style.setProperty(e,t,n)}}function Yv(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function Wv(e,t,n){return arguments.length>1?this.each((t==null?Vv:typeof t=="function"?Yv:Kv)(e,t,n??"")):Kt(this.node(),e)}function Kt(e,t){return e.style.getPropertyValue(t)||Cc(e).getComputedStyle(e,null).getPropertyValue(t)}function Xv(e){return function(){delete this[e]}}function Qv(e,t){return function(){this[e]=t}}function Jv(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function Zv(e,t){return arguments.length>1?this.each((t==null?Xv:typeof t=="function"?Jv:Qv)(e,t)):this.node()[e]}function Nc(e){return e.trim().split(/^|\s+/)}function fo(e){return e.classList||new Rc(e)}function Rc(e){this._node=e,this._names=Nc(e.getAttribute("class")||"")}Rc.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};function _c(e,t){for(var n=fo(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function Tc(e,t){for(var n=fo(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function ey(e){return function(){_c(this,e)}}function ty(e){return function(){Tc(this,e)}}function ny(e,t){return function(){(t.apply(this,arguments)?_c:Tc)(this,e)}}function ry(e,t){var n=Nc(e+"");if(arguments.length<2){for(var r=fo(this.node()),s=-1,o=n.length;++s<o;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?ny:t?ey:ty)(n,t))}function sy(){this.textContent=""}function oy(e){return function(){this.textContent=e}}function iy(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function ay(e){return arguments.length?this.each(e==null?sy:(typeof e=="function"?iy:oy)(e)):this.node().textContent}function ly(){this.innerHTML=""}function cy(e){return function(){this.innerHTML=e}}function uy(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function dy(e){return arguments.length?this.each(e==null?ly:(typeof e=="function"?uy:cy)(e)):this.node().innerHTML}function hy(){this.nextSibling&&this.parentNode.appendChild(this)}function fy(){return this.each(hy)}function py(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function gy(){return this.each(py)}function my(e){var t=typeof e=="function"?e:xc(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function vy(){return null}function yy(e,t){var n=typeof e=="function"?e:xc(e),r=t==null?vy:typeof t=="function"?t:ho(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function by(){var e=this.parentNode;e&&e.removeChild(this)}function xy(){return this.each(by)}function Sy(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function Iy(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function wy(e){return this.select(e?Iy:Sy)}function Ey(e){return arguments.length?this.property("__data__",e):this.node().__data__}function Cy(e){return function(t){e.call(this,t,this.__data__)}}function Ny(e){return e.trim().split(/^|\s+/).map(function(t){var n="",r=t.indexOf(".");return r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),{type:t,name:n}})}function Ry(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,o;n<s;++n)o=t[n],(!e.type||o.type===e.type)&&o.name===e.name?this.removeEventListener(o.type,o.listener,o.options):t[++r]=o;++r?t.length=r:delete this.__on}}}function _y(e,t,n){return function(){var r=this.__on,s,o=Cy(t);if(r){for(var i=0,a=r.length;i<a;++i)if((s=r[i]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=o,s.options=n),s.value=t;return}}this.addEventListener(e.type,o,n),s={type:e.type,name:e.name,value:t,listener:o,options:n},r?r.push(s):this.__on=[s]}}function Ty(e,t,n){var r=Ny(e+""),s,o=r.length,i;if(arguments.length<2){var a=this.node().__on;if(a){for(var l=0,c=a.length,u;l<c;++l)for(s=0,u=a[l];s<o;++s)if((i=r[s]).type===u.type&&i.name===u.name)return u.value}return}for(a=t?_y:Ry,s=0;s<o;++s)this.each(a(r[s],t,n));return this}function Ac(e,t,n){var r=Cc(e),s=r.CustomEvent;typeof s=="function"?s=new s(t,n):(s=r.document.createEvent("Event"),n?(s.initEvent(t,n.bubbles,n.cancelable),s.detail=n.detail):s.initEvent(t,!1,!1)),e.dispatchEvent(s)}function Ay(e,t){return function(){return Ac(this,e,t)}}function My(e,t){return function(){return Ac(this,e,t.apply(this,arguments))}}function ky(e,t){return this.each((typeof t=="function"?My:Ay)(e,t))}function*Oy(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,o=r.length,i;s<o;++s)(i=r[s])&&(yield i)}var Mc=[null];function Ie(e,t){this._groups=e,this._parents=t}function nn(){return new Ie([[document.documentElement]],Mc)}function jy(){return this}Ie.prototype=nn.prototype={constructor:Ie,select:iv,selectAll:uv,selectChild:pv,selectChildren:yv,filter:bv,data:Cv,enter:xv,exit:Rv,join:_v,merge:Tv,selection:jy,order:Av,sort:Mv,call:Ov,nodes:jv,node:Pv,size:Lv,empty:Dv,each:$v,attr:qv,style:Wv,property:Zv,classed:ry,text:ay,html:dy,raise:fy,lower:gy,append:my,insert:yy,remove:xy,clone:wy,datum:Ey,on:Ty,dispatch:ky,[Symbol.iterator]:Oy};function Se(e){return typeof e=="string"?new Ie([[document.querySelector(e)]],[document.documentElement]):new Ie([[e]],Mc)}function Py(e){let t;for(;t=e.sourceEvent;)e=t;return e}function Oe(e,t){if(e=Py(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,r=r.matrixTransform(t.getScreenCTM().inverse()),[r.x,r.y]}if(t.getBoundingClientRect){var s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}}return[e.pageX,e.pageY]}var Ly={passive:!1},Sn={capture:!0,passive:!1};function ss(e){e.stopImmediatePropagation()}function Lt(e){e.preventDefault(),e.stopImmediatePropagation()}function kc(e){var t=e.document.documentElement,n=Se(e).on("dragstart.drag",Lt,Sn);"onselectstart"in t?n.on("selectstart.drag",Lt,Sn):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function Oc(e,t){var n=e.document.documentElement,r=Se(e).on("dragstart.drag",null);t&&(r.on("click.drag",Lt,Sn),setTimeout(function(){r.on("click.drag",null)},0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}var Dn=e=>()=>e;function Ts(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:o,x:i,y:a,dx:l,dy:c,dispatch:u}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:s,enumerable:!0,configurable:!0},active:{value:o,enumerable:!0,configurable:!0},x:{value:i,enumerable:!0,configurable:!0},y:{value:a,enumerable:!0,configurable:!0},dx:{value:l,enumerable:!0,configurable:!0},dy:{value:c,enumerable:!0,configurable:!0},_:{value:u}})}Ts.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function Dy(e){return!e.ctrlKey&&!e.button}function $y(){return this.parentNode}function Fy(e,t){return t??{x:e.x,y:e.y}}function zy(){return navigator.maxTouchPoints||"ontouchstart"in this}function jc(){var e=Dy,t=$y,n=Fy,r=zy,s={},o=Ar("start","drag","end"),i=0,a,l,c,u,d=0;function f(S){S.on("mousedown.drag",g).filter(r).on("touchstart.drag",x).on("touchmove.drag",v,Ly).on("touchend.drag touchcancel.drag",I).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function g(S,E){if(!(u||!e.call(this,S,E))){var N=m(this,t.call(this,S,E),S,E,"mouse");N&&(Se(S.view).on("mousemove.drag",p,Sn).on("mouseup.drag",y,Sn),kc(S.view),ss(S),c=!1,a=S.clientX,l=S.clientY,N("start",S))}}function p(S){if(Lt(S),!c){var E=S.clientX-a,N=S.clientY-l;c=E*E+N*N>d}s.mouse("drag",S)}function y(S){Se(S.view).on("mousemove.drag mouseup.drag",null),Oc(S.view,c),Lt(S),s.mouse("end",S)}function x(S,E){if(e.call(this,S,E))for(var N=S.changedTouches,R=t.call(this,S,E),A=N.length,k=0,P;k<A;++k)(P=m(this,R,S,E,N[k].identifier,N[k]))&&(ss(S),P("start",S,N[k]))}function v(S){for(var E=S.changedTouches,N=E.length,R=0,A;R<N;++R)(A=s[E[R].identifier])&&(Lt(S),A("drag",S,E[R]))}function I(S){var E=S.changedTouches,N=E.length,R,A;for(u&&clearTimeout(u),u=setTimeout(function(){u=null},500),R=0;R<N;++R)(A=s[E[R].identifier])&&(ss(S),A("end",S,E[R]))}function m(S,E,N,R,A,k){var P=o.copy(),_=Oe(k||N,E),M,O,b;if((b=n.call(S,new Ts("beforestart",{sourceEvent:N,target:f,identifier:A,active:i,x:_[0],y:_[1],dx:0,dy:0,dispatch:P}),R))!=null)return M=b.x-_[0]||0,O=b.y-_[1]||0,function w(T,j,D){var L=_,F;switch(T){case"start":s[A]=w,F=i++;break;case"end":delete s[A],--i;case"drag":_=Oe(D||j,E),F=i}P.call(T,S,new Ts(T,{sourceEvent:j,subject:b,target:f,identifier:A,active:F,x:_[0]+M,y:_[1]+O,dx:_[0]-L[0],dy:_[1]-L[1],dispatch:P}),R)}}return f.filter=function(S){return arguments.length?(e=typeof S=="function"?S:Dn(!!S),f):e},f.container=function(S){return arguments.length?(t=typeof S=="function"?S:Dn(S),f):t},f.subject=function(S){return arguments.length?(n=typeof S=="function"?S:Dn(S),f):n},f.touchable=function(S){return arguments.length?(r=typeof S=="function"?S:Dn(!!S),f):r},f.on=function(){var S=o.on.apply(o,arguments);return S===o?f:S},f.clickDistance=function(S){return arguments.length?(d=(S=+S)*S,f):Math.sqrt(d)},f}function po(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function Pc(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function Mn(){}var In=.7,ar=1/In,Dt="\\s*([+-]?\\d+)\\s*",wn="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Ue="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",Hy=/^#([0-9a-f]{3,8})$/,By=new RegExp(`^rgb\\(${Dt},${Dt},${Dt}\\)$`),Gy=new RegExp(`^rgb\\(${Ue},${Ue},${Ue}\\)$`),Uy=new RegExp(`^rgba\\(${Dt},${Dt},${Dt},${wn}\\)$`),qy=new RegExp(`^rgba\\(${Ue},${Ue},${Ue},${wn}\\)$`),Vy=new RegExp(`^hsl\\(${wn},${Ue},${Ue}\\)$`),Ky=new RegExp(`^hsla\\(${wn},${Ue},${Ue},${wn}\\)$`),Ei={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};po(Mn,Ct,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Ci,formatHex:Ci,formatHex8:Yy,formatHsl:Wy,formatRgb:Ni,toString:Ni});function Ci(){return this.rgb().formatHex()}function Yy(){return this.rgb().formatHex8()}function Wy(){return Lc(this).formatHsl()}function Ni(){return this.rgb().formatRgb()}function Ct(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=Hy.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?Ri(t):n===3?new be(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?$n(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?$n(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=By.exec(e))?new be(t[1],t[2],t[3],1):(t=Gy.exec(e))?new be(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Uy.exec(e))?$n(t[1],t[2],t[3],t[4]):(t=qy.exec(e))?$n(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Vy.exec(e))?Ai(t[1],t[2]/100,t[3]/100,1):(t=Ky.exec(e))?Ai(t[1],t[2]/100,t[3]/100,t[4]):Ei.hasOwnProperty(e)?Ri(Ei[e]):e==="transparent"?new be(NaN,NaN,NaN,0):null}function Ri(e){return new be(e>>16&255,e>>8&255,e&255,1)}function $n(e,t,n,r){return r<=0&&(e=t=n=NaN),new be(e,t,n,r)}function Xy(e){return e instanceof Mn||(e=Ct(e)),e?(e=e.rgb(),new be(e.r,e.g,e.b,e.opacity)):new be}function lr(e,t,n,r){return arguments.length===1?Xy(e):new be(e,t,n,r??1)}function be(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}po(be,lr,Pc(Mn,{brighter(e){return e=e==null?ar:Math.pow(ar,e),new be(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?In:Math.pow(In,e),new be(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new be(It(this.r),It(this.g),It(this.b),cr(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:_i,formatHex:_i,formatHex8:Qy,formatRgb:Ti,toString:Ti}));function _i(){return`#${xt(this.r)}${xt(this.g)}${xt(this.b)}`}function Qy(){return`#${xt(this.r)}${xt(this.g)}${xt(this.b)}${xt((isNaN(this.opacity)?1:this.opacity)*255)}`}function Ti(){const e=cr(this.opacity);return`${e===1?"rgb(":"rgba("}${It(this.r)}, ${It(this.g)}, ${It(this.b)}${e===1?")":`, ${e})`}`}function cr(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function It(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function xt(e){return e=It(e),(e<16?"0":"")+e.toString(16)}function Ai(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new je(e,t,n,r)}function Lc(e){if(e instanceof je)return new je(e.h,e.s,e.l,e.opacity);if(e instanceof Mn||(e=Ct(e)),!e)return new je;if(e instanceof je)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,s=Math.min(t,n,r),o=Math.max(t,n,r),i=NaN,a=o-s,l=(o+s)/2;return a?(t===o?i=(n-r)/a+(n<r)*6:n===o?i=(r-t)/a+2:i=(t-n)/a+4,a/=l<.5?o+s:2-o-s,i*=60):a=l>0&&l<1?0:i,new je(i,a,l,e.opacity)}function Jy(e,t,n,r){return arguments.length===1?Lc(e):new je(e,t,n,r??1)}function je(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}po(je,Jy,Pc(Mn,{brighter(e){return e=e==null?ar:Math.pow(ar,e),new je(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?In:Math.pow(In,e),new je(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,s=2*n-r;return new be(os(e>=240?e-240:e+120,s,r),os(e,s,r),os(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new je(Mi(this.h),Fn(this.s),Fn(this.l),cr(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=cr(this.opacity);return`${e===1?"hsl(":"hsla("}${Mi(this.h)}, ${Fn(this.s)*100}%, ${Fn(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Mi(e){return e=(e||0)%360,e<0?e+360:e}function Fn(e){return Math.max(0,Math.min(1,e||0))}function os(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}function Dc(e,t,n,r,s){var o=e*e,i=o*e;return((1-3*e+3*o-i)*t+(4-6*o+3*i)*n+(1+3*e+3*o-3*i)*r+i*s)/6}function Zy(e){var t=e.length-1;return function(n){var r=n<=0?n=0:n>=1?(n=1,t-1):Math.floor(n*t),s=e[r],o=e[r+1],i=r>0?e[r-1]:2*s-o,a=r<t-1?e[r+2]:2*o-s;return Dc((n-r/t)*t,i,s,o,a)}}function eb(e){var t=e.length;return function(n){var r=Math.floor(((n%=1)<0?++n:n)*t),s=e[(r+t-1)%t],o=e[r%t],i=e[(r+1)%t],a=e[(r+2)%t];return Dc((n-r/t)*t,s,o,i,a)}}var go=e=>()=>e;function tb(e,t){return function(n){return e+n*t}}function nb(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function rb(e){return(e=+e)==1?$c:function(t,n){return n-t?nb(t,n,e):go(isNaN(t)?n:t)}}function $c(e,t){var n=t-e;return n?tb(e,n):go(isNaN(e)?t:e)}var ur=(function e(t){var n=rb(t);function r(s,o){var i=n((s=lr(s)).r,(o=lr(o)).r),a=n(s.g,o.g),l=n(s.b,o.b),c=$c(s.opacity,o.opacity);return function(u){return s.r=i(u),s.g=a(u),s.b=l(u),s.opacity=c(u),s+""}}return r.gamma=e,r})(1);function Fc(e){return function(t){for(var n=t.length,r=new Array(n),s=new Array(n),o=new Array(n),i=0,a;i<n;++i)a=lr(t[i]),r[i]=a.r||0,s[i]=a.g||0,o[i]=a.b||0;return r=e(r),s=e(s),o=e(o),a.opacity=1,function(l){return a.r=r(l),a.g=s(l),a.b=o(l),a+""}}}var z_=Fc(Zy),H_=Fc(eb);function sb(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),s;return function(o){for(s=0;s<n;++s)r[s]=e[s]*(1-o)+t[s]*o;return r}}function ob(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function ib(e,t){for(var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),o=new Array(n),i=0;i<r;++i)s[i]=vn(e[i],t[i]);for(;i<n;++i)o[i]=t[i];return function(a){for(i=0;i<r;++i)o[i]=s[i](a);return o}}function ab(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function Be(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function lb(e,t){var n={},r={},s;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(s in t)s in e?n[s]=vn(e[s],t[s]):r[s]=t[s];return function(o){for(s in n)r[s]=n[s](o);return r}}var As=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,is=new RegExp(As.source,"g");function cb(e){return function(){return e}}function ub(e){return function(t){return e(t)+""}}function zc(e,t){var n=As.lastIndex=is.lastIndex=0,r,s,o,i=-1,a=[],l=[];for(e=e+"",t=t+"";(r=As.exec(e))&&(s=is.exec(t));)(o=s.index)>n&&(o=t.slice(n,o),a[i]?a[i]+=o:a[++i]=o),(r=r[0])===(s=s[0])?a[i]?a[i]+=s:a[++i]=s:(a[++i]=null,l.push({i,x:Be(r,s)})),n=is.lastIndex;return n<t.length&&(o=t.slice(n),a[i]?a[i]+=o:a[++i]=o),a.length<2?l[0]?ub(l[0].x):cb(t):(t=l.length,function(c){for(var u=0,d;u<t;++u)a[(d=l[u]).i]=d.x(c);return a.join("")})}function vn(e,t){var n=typeof t,r;return t==null||n==="boolean"?go(t):(n==="number"?Be:n==="string"?(r=Ct(t))?(t=r,ur):zc:t instanceof Ct?ur:t instanceof Date?ab:ob(t)?sb:Array.isArray(t)?ib:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?lb:Be)(e,t)}var ki=180/Math.PI,Ms={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Hc(e,t,n,r,s,o){var i,a,l;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(l=e*n+t*r)&&(n-=e*l,r-=t*l),(a=Math.sqrt(n*n+r*r))&&(n/=a,r/=a,l/=a),e*r<t*n&&(e=-e,t=-t,l=-l,i=-i),{translateX:s,translateY:o,rotate:Math.atan2(t,e)*ki,skewX:Math.atan(l)*ki,scaleX:i,scaleY:a}}var zn;function db(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Ms:Hc(t.a,t.b,t.c,t.d,t.e,t.f)}function hb(e){return e==null||(zn||(zn=document.createElementNS("http://www.w3.org/2000/svg","g")),zn.setAttribute("transform",e),!(e=zn.transform.baseVal.consolidate()))?Ms:(e=e.matrix,Hc(e.a,e.b,e.c,e.d,e.e,e.f))}function Bc(e,t,n,r){function s(c){return c.length?c.pop()+" ":""}function o(c,u,d,f,g,p){if(c!==d||u!==f){var y=g.push("translate(",null,t,null,n);p.push({i:y-4,x:Be(c,d)},{i:y-2,x:Be(u,f)})}else(d||f)&&g.push("translate("+d+t+f+n)}function i(c,u,d,f){c!==u?(c-u>180?u+=360:u-c>180&&(c+=360),f.push({i:d.push(s(d)+"rotate(",null,r)-2,x:Be(c,u)})):u&&d.push(s(d)+"rotate("+u+r)}function a(c,u,d,f){c!==u?f.push({i:d.push(s(d)+"skewX(",null,r)-2,x:Be(c,u)}):u&&d.push(s(d)+"skewX("+u+r)}function l(c,u,d,f,g,p){if(c!==d||u!==f){var y=g.push(s(g)+"scale(",null,",",null,")");p.push({i:y-4,x:Be(c,d)},{i:y-2,x:Be(u,f)})}else(d!==1||f!==1)&&g.push(s(g)+"scale("+d+","+f+")")}return function(c,u){var d=[],f=[];return c=e(c),u=e(u),o(c.translateX,c.translateY,u.translateX,u.translateY,d,f),i(c.rotate,u.rotate,d,f),a(c.skewX,u.skewX,d,f),l(c.scaleX,c.scaleY,u.scaleX,u.scaleY,d,f),c=u=null,function(g){for(var p=-1,y=f.length,x;++p<y;)d[(x=f[p]).i]=x.x(g);return d.join("")}}}var fb=Bc(db,"px, ","px)","deg)"),pb=Bc(hb,", ",")",")"),gb=1e-12;function Oi(e){return((e=Math.exp(e))+1/e)/2}function mb(e){return((e=Math.exp(e))-1/e)/2}function vb(e){return((e=Math.exp(2*e))-1)/(e+1)}var Zn=(function e(t,n,r){function s(o,i){var a=o[0],l=o[1],c=o[2],u=i[0],d=i[1],f=i[2],g=u-a,p=d-l,y=g*g+p*p,x,v;if(y<gb)v=Math.log(f/c)/t,x=function(N){return[a+N*g,l+N*p,c*Math.exp(t*N*v)]};else{var I=Math.sqrt(y),m=(f*f-c*c+r*y)/(2*c*n*I),S=(f*f-c*c-r*y)/(2*f*n*I),E=Math.log(Math.sqrt(m*m+1)-m);v=(Math.log(Math.sqrt(S*S+1)-S)-E)/t,x=function(N){var R=N*v,A=Oi(E),k=c/(n*I)*(A*vb(t*R+E)-mb(E));return[a+k*g,l+k*p,c*A/Oi(t*R+E)]}}return x.duration=v*1e3*t/Math.SQRT2,x}return s.rho=function(o){var i=Math.max(.001,+o),a=i*i;return e(i,a,a*a)},s})(Math.SQRT2,2,4),Yt=0,dn=0,on=0,Gc=1e3,dr,hn,hr=0,Nt=0,kr=0,En=typeof performance=="object"&&performance.now?performance:Date,Uc=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function mo(){return Nt||(Uc(yb),Nt=En.now()+kr)}function yb(){Nt=0}function fr(){this._call=this._time=this._next=null}fr.prototype=qc.prototype={constructor:fr,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?mo():+n)+(t==null?0:+t),!this._next&&hn!==this&&(hn?hn._next=this:dr=this,hn=this),this._call=e,this._time=n,ks()},stop:function(){this._call&&(this._call=null,this._time=1/0,ks())}};function qc(e,t,n){var r=new fr;return r.restart(e,t,n),r}function bb(){mo(),++Yt;for(var e=dr,t;e;)(t=Nt-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Yt}function ji(){Nt=(hr=En.now())+kr,Yt=dn=0;try{bb()}finally{Yt=0,Sb(),Nt=0}}function xb(){var e=En.now(),t=e-hr;t>Gc&&(kr-=t,hr=e)}function Sb(){for(var e,t=dr,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:dr=n);hn=e,ks(r)}function ks(e){Yt||(dn&&(dn=clearTimeout(dn)),e-Nt>24?(e<1/0&&(dn=setTimeout(ji,e-En.now()-kr)),on&&(on=clearInterval(on))):(on||(hr=En.now(),on=setInterval(xb,Gc)),Yt=1,Uc(ji)))}function Pi(e,t,n){var r=new fr;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var Ib=Ar("start","end","cancel","interrupt"),wb=[];function Or(e,t,n,r,s,o){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;Eb(e,n,{name:t,index:r,group:s,on:Ib,tween:wb,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:0})}function vo(e,t){var n=$e(e,t);if(n.state>0)throw new Error("too late; already scheduled");return n}function Ke(e,t){var n=$e(e,t);if(n.state>3)throw new Error("too late; already running");return n}function $e(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function Eb(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=qc(o,0,n.time);function o(c){n.state=1,n.timer.restart(i,n.delay,n.time),n.delay<=c&&i(c-n.delay)}function i(c){var u,d,f,g;if(n.state!==1)return l();for(u in r)if(g=r[u],g.name===n.name){if(g.state===3)return Pi(i);g.state===4?(g.state=6,g.timer.stop(),g.on.call("interrupt",e,e.__data__,g.index,g.group),delete r[u]):+u<t&&(g.state=6,g.timer.stop(),g.on.call("cancel",e,e.__data__,g.index,g.group),delete r[u])}if(Pi(function(){n.state===3&&(n.state=4,n.timer.restart(a,n.delay,n.time),a(c))}),n.state=2,n.on.call("start",e,e.__data__,n.index,n.group),n.state===2){for(n.state=3,s=new Array(f=n.tween.length),u=0,d=-1;u<f;++u)(g=n.tween[u].value.call(e,e.__data__,n.index,n.group))&&(s[++d]=g);s.length=d+1}}function a(c){for(var u=c<n.duration?n.ease.call(null,c/n.duration):(n.timer.restart(l),n.state=5,1),d=-1,f=s.length;++d<f;)s[d].call(e,u);n.state===5&&(n.on.call("end",e,e.__data__,n.index,n.group),l())}function l(){n.state=6,n.timer.stop(),delete r[t];for(var c in r)return;delete e.__transition}}function er(e,t){var n=e.__transition,r,s,o=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){o=!1;continue}s=r.state>2&&r.state<5,r.state=6,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}o&&delete e.__transition}}function Cb(e){return this.each(function(){er(this,e)})}function Nb(e,t){var n,r;return function(){var s=Ke(this,e),o=s.tween;if(o!==n){r=n=o;for(var i=0,a=r.length;i<a;++i)if(r[i].name===t){r=r.slice(),r.splice(i,1);break}}s.tween=r}}function Rb(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var o=Ke(this,e),i=o.tween;if(i!==r){s=(r=i).slice();for(var a={name:t,value:n},l=0,c=s.length;l<c;++l)if(s[l].name===t){s[l]=a;break}l===c&&s.push(a)}o.tween=s}}function _b(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=$e(this.node(),n).tween,s=0,o=r.length,i;s<o;++s)if((i=r[s]).name===e)return i.value;return null}return this.each((t==null?Nb:Rb)(n,e,t))}function yo(e,t,n){var r=e._id;return e.each(function(){var s=Ke(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return $e(s,r).value[t]}}function Vc(e,t){var n;return(typeof t=="number"?Be:t instanceof Ct?ur:(n=Ct(t))?(t=n,ur):zc)(e,t)}function Tb(e){return function(){this.removeAttribute(e)}}function Ab(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Mb(e,t,n){var r,s=n+"",o;return function(){var i=this.getAttribute(e);return i===s?null:i===r?o:o=t(r=i,n)}}function kb(e,t,n){var r,s=n+"",o;return function(){var i=this.getAttributeNS(e.space,e.local);return i===s?null:i===r?o:o=t(r=i,n)}}function Ob(e,t,n){var r,s,o;return function(){var i,a=n(this),l;return a==null?void this.removeAttribute(e):(i=this.getAttribute(e),l=a+"",i===l?null:i===r&&l===s?o:(s=l,o=t(r=i,a)))}}function jb(e,t,n){var r,s,o;return function(){var i,a=n(this),l;return a==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),l=a+"",i===l?null:i===r&&l===s?o:(s=l,o=t(r=i,a)))}}function Pb(e,t){var n=Mr(e),r=n==="transform"?pb:Vc;return this.attrTween(e,typeof t=="function"?(n.local?jb:Ob)(n,r,yo(this,"attr."+e,t)):t==null?(n.local?Ab:Tb)(n):(n.local?kb:Mb)(n,r,t))}function Lb(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function Db(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function $b(e,t){var n,r;function s(){var o=t.apply(this,arguments);return o!==r&&(n=(r=o)&&Db(e,o)),n}return s._value=t,s}function Fb(e,t){var n,r;function s(){var o=t.apply(this,arguments);return o!==r&&(n=(r=o)&&Lb(e,o)),n}return s._value=t,s}function zb(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var r=Mr(e);return this.tween(n,(r.local?$b:Fb)(r,t))}function Hb(e,t){return function(){vo(this,e).delay=+t.apply(this,arguments)}}function Bb(e,t){return t=+t,function(){vo(this,e).delay=t}}function Gb(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?Hb:Bb)(t,e)):$e(this.node(),t).delay}function Ub(e,t){return function(){Ke(this,e).duration=+t.apply(this,arguments)}}function qb(e,t){return t=+t,function(){Ke(this,e).duration=t}}function Vb(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?Ub:qb)(t,e)):$e(this.node(),t).duration}function Kb(e,t){if(typeof t!="function")throw new Error;return function(){Ke(this,e).ease=t}}function Yb(e){var t=this._id;return arguments.length?this.each(Kb(t,e)):$e(this.node(),t).ease}function Wb(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Ke(this,e).ease=n}}function Xb(e){if(typeof e!="function")throw new Error;return this.each(Wb(this._id,e))}function Qb(e){typeof e!="function"&&(e=Ic(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var o=t[s],i=o.length,a=r[s]=[],l,c=0;c<i;++c)(l=o[c])&&e.call(l,l.__data__,c,o)&&a.push(l);return new nt(r,this._parents,this._name,this._id)}function Jb(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,o=Math.min(r,s),i=new Array(r),a=0;a<o;++a)for(var l=t[a],c=n[a],u=l.length,d=i[a]=new Array(u),f,g=0;g<u;++g)(f=l[g]||c[g])&&(d[g]=f);for(;a<r;++a)i[a]=t[a];return new nt(i,this._parents,this._name,this._id)}function Zb(e){return(e+"").trim().split(/^|\s+/).every(function(t){var n=t.indexOf(".");return n>=0&&(t=t.slice(0,n)),!t||t==="start"})}function ex(e,t,n){var r,s,o=Zb(t)?vo:Ke;return function(){var i=o(this,e),a=i.on;a!==r&&(s=(r=a).copy()).on(t,n),i.on=s}}function tx(e,t){var n=this._id;return arguments.length<2?$e(this.node(),n).on.on(e):this.each(ex(n,e,t))}function nx(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function rx(){return this.on("end.remove",nx(this._id))}function sx(e){var t=this._name,n=this._id;typeof e!="function"&&(e=ho(e));for(var r=this._groups,s=r.length,o=new Array(s),i=0;i<s;++i)for(var a=r[i],l=a.length,c=o[i]=new Array(l),u,d,f=0;f<l;++f)(u=a[f])&&(d=e.call(u,u.__data__,f,a))&&("__data__"in u&&(d.__data__=u.__data__),c[f]=d,Or(c[f],t,n,f,c,$e(u,n)));return new nt(o,this._parents,t,n)}function ox(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Sc(e));for(var r=this._groups,s=r.length,o=[],i=[],a=0;a<s;++a)for(var l=r[a],c=l.length,u,d=0;d<c;++d)if(u=l[d]){for(var f=e.call(u,u.__data__,d,l),g,p=$e(u,n),y=0,x=f.length;y<x;++y)(g=f[y])&&Or(g,t,n,y,f,p);o.push(f),i.push(u)}return new nt(o,i,t,n)}var ix=nn.prototype.constructor;function ax(){return new ix(this._groups,this._parents)}function lx(e,t){var n,r,s;return function(){var o=Kt(this,e),i=(this.style.removeProperty(e),Kt(this,e));return o===i?null:o===n&&i===r?s:s=t(n=o,r=i)}}function Kc(e){return function(){this.style.removeProperty(e)}}function cx(e,t,n){var r,s=n+"",o;return function(){var i=Kt(this,e);return i===s?null:i===r?o:o=t(r=i,n)}}function ux(e,t,n){var r,s,o;return function(){var i=Kt(this,e),a=n(this),l=a+"";return a==null&&(l=a=(this.style.removeProperty(e),Kt(this,e))),i===l?null:i===r&&l===s?o:(s=l,o=t(r=i,a))}}function dx(e,t){var n,r,s,o="style."+t,i="end."+o,a;return function(){var l=Ke(this,e),c=l.on,u=l.value[o]==null?a||(a=Kc(t)):void 0;(c!==n||s!==u)&&(r=(n=c).copy()).on(i,s=u),l.on=r}}function hx(e,t,n){var r=(e+="")=="transform"?fb:Vc;return t==null?this.styleTween(e,lx(e,r)).on("end.style."+e,Kc(e)):typeof t=="function"?this.styleTween(e,ux(e,r,yo(this,"style."+e,t))).each(dx(this._id,e)):this.styleTween(e,cx(e,r,t),n).on("end.style."+e,null)}function fx(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function px(e,t,n){var r,s;function o(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&fx(e,i,n)),r}return o._value=t,o}function gx(e,t,n){var r="style."+(e+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(t==null)return this.tween(r,null);if(typeof t!="function")throw new Error;return this.tween(r,px(e,t,n??""))}function mx(e){return function(){this.textContent=e}}function vx(e){return function(){var t=e(this);this.textContent=t??""}}function yx(e){return this.tween("text",typeof e=="function"?vx(yo(this,"text",e)):mx(e==null?"":e+""))}function bx(e){return function(t){this.textContent=e.call(this,t)}}function xx(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&bx(s)),t}return r._value=e,r}function Sx(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(e==null)return this.tween(t,null);if(typeof e!="function")throw new Error;return this.tween(t,xx(e))}function Ix(){for(var e=this._name,t=this._id,n=Yc(),r=this._groups,s=r.length,o=0;o<s;++o)for(var i=r[o],a=i.length,l,c=0;c<a;++c)if(l=i[c]){var u=$e(l,t);Or(l,e,n,c,i,{time:u.time+u.delay+u.duration,delay:0,duration:u.duration,ease:u.ease})}return new nt(r,this._parents,e,n)}function wx(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(o,i){var a={value:i},l={value:function(){--s===0&&o()}};n.each(function(){var c=Ke(this,r),u=c.on;u!==e&&(t=(e=u).copy(),t._.cancel.push(a),t._.interrupt.push(a),t._.end.push(l)),c.on=t}),s===0&&o()})}var Ex=0;function nt(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function Cx(e){return nn().transition(e)}function Yc(){return++Ex}var Xe=nn.prototype;nt.prototype=Cx.prototype={constructor:nt,select:sx,selectAll:ox,selectChild:Xe.selectChild,selectChildren:Xe.selectChildren,filter:Qb,merge:Jb,selection:ax,transition:Ix,call:Xe.call,nodes:Xe.nodes,node:Xe.node,size:Xe.size,empty:Xe.empty,each:Xe.each,on:tx,attr:Pb,attrTween:zb,style:hx,styleTween:gx,text:yx,textTween:Sx,remove:rx,tween:_b,delay:Gb,duration:Vb,ease:Yb,easeVarying:Xb,end:wx,[Symbol.iterator]:Xe[Symbol.iterator]};function Nx(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var Rx={time:null,delay:0,duration:250,ease:Nx};function _x(e,t){for(var n;!(n=e.__transition)||!(n=n[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return n}function Tx(e){var t,n;e instanceof nt?(t=e._id,e=e._name):(t=Yc(),(n=Rx).time=mo(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,o=0;o<s;++o)for(var i=r[o],a=i.length,l,c=0;c<a;++c)(l=i[c])&&Or(l,e,t,c,i,n||_x(l,t));return new nt(r,this._parents,e,t)}nn.prototype.interrupt=Cb;nn.prototype.transition=Tx;var Hn=e=>()=>e;function Ax(e,{sourceEvent:t,target:n,transform:r,dispatch:s}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:s}})}function et(e,t,n){this.k=e,this.x=t,this.y=n}et.prototype={constructor:et,scale:function(e){return e===1?this:new et(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new et(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var jr=new et(1,0,0);Wc.prototype=et.prototype;function Wc(e){for(;!e.__zoom;)if(!(e=e.parentNode))return jr;return e.__zoom}function as(e){e.stopImmediatePropagation()}function an(e){e.preventDefault(),e.stopImmediatePropagation()}function Mx(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function kx(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e,e.hasAttribute("viewBox")?(e=e.viewBox.baseVal,[[e.x,e.y],[e.x+e.width,e.y+e.height]]):[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]):[[0,0],[e.clientWidth,e.clientHeight]]}function Li(){return this.__zoom||jr}function Ox(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function jx(){return navigator.maxTouchPoints||"ontouchstart"in this}function Px(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],o=e.invertY(t[0][1])-n[0][1],i=e.invertY(t[1][1])-n[1][1];return e.translate(s>r?(r+s)/2:Math.min(0,r)||Math.max(0,s),i>o?(o+i)/2:Math.min(0,o)||Math.max(0,i))}function Xc(){var e=Mx,t=kx,n=Px,r=Ox,s=jx,o=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],a=250,l=Zn,c=Ar("start","zoom","end"),u,d,f,g=500,p=150,y=0,x=10;function v(b){b.property("__zoom",Li).on("wheel.zoom",A,{passive:!1}).on("mousedown.zoom",k).on("dblclick.zoom",P).filter(s).on("touchstart.zoom",_).on("touchmove.zoom",M).on("touchend.zoom touchcancel.zoom",O).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}v.transform=function(b,w,T,j){var D=b.selection?b.selection():b;D.property("__zoom",Li),b!==D?E(b,w,T,j):D.interrupt().each(function(){N(this,arguments).event(j).start().zoom(null,typeof w=="function"?w.apply(this,arguments):w).end()})},v.scaleBy=function(b,w,T,j){v.scaleTo(b,function(){return this.__zoom.k*(typeof w=="function"?w.apply(this,arguments):w)},T,j)},v.scaleTo=function(b,w,T,j){v.transform(b,function(){var D=t.apply(this,arguments),L=this.__zoom,F=T==null?S(D):typeof T=="function"?T.apply(this,arguments):T,z=L.invert(F),B=typeof w=="function"?w.apply(this,arguments):w;return n(m(I(L,B),F,z),D,i)},T,j)},v.translateBy=function(b,w,T,j){v.transform(b,function(){return n(this.__zoom.translate(typeof w=="function"?w.apply(this,arguments):w,typeof T=="function"?T.apply(this,arguments):T),t.apply(this,arguments),i)},null,j)},v.translateTo=function(b,w,T,j,D){v.transform(b,function(){var L=t.apply(this,arguments),F=this.__zoom,z=j==null?S(L):typeof j=="function"?j.apply(this,arguments):j;return n(jr.translate(z[0],z[1]).scale(F.k).translate(typeof w=="function"?-w.apply(this,arguments):-w,typeof T=="function"?-T.apply(this,arguments):-T),L,i)},j,D)};function I(b,w){return w=Math.max(o[0],Math.min(o[1],w)),w===b.k?b:new et(w,b.x,b.y)}function m(b,w,T){var j=w[0]-T[0]*b.k,D=w[1]-T[1]*b.k;return j===b.x&&D===b.y?b:new et(b.k,j,D)}function S(b){return[(+b[0][0]+ +b[1][0])/2,(+b[0][1]+ +b[1][1])/2]}function E(b,w,T,j){b.on("start.zoom",function(){N(this,arguments).event(j).start()}).on("interrupt.zoom end.zoom",function(){N(this,arguments).event(j).end()}).tween("zoom",function(){var D=this,L=arguments,F=N(D,L).event(j),z=t.apply(D,L),B=T==null?S(z):typeof T=="function"?T.apply(D,L):T,K=Math.max(z[1][0]-z[0][0],z[1][1]-z[0][1]),H=D.__zoom,W=typeof w=="function"?w.apply(D,L):w,J=l(H.invert(B).concat(K/H.k),W.invert(B).concat(K/W.k));return function(X){if(X===1)X=W;else{var $=J(X),q=K/$[2];X=new et(q,B[0]-$[0]*q,B[1]-$[1]*q)}F.zoom(null,X)}})}function N(b,w,T){return!T&&b.__zooming||new R(b,w)}function R(b,w){this.that=b,this.args=w,this.active=0,this.sourceEvent=null,this.extent=t.apply(b,w),this.taps=0}R.prototype={event:function(b){return b&&(this.sourceEvent=b),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(b,w){return this.mouse&&b!=="mouse"&&(this.mouse[1]=w.invert(this.mouse[0])),this.touch0&&b!=="touch"&&(this.touch0[1]=w.invert(this.touch0[0])),this.touch1&&b!=="touch"&&(this.touch1[1]=w.invert(this.touch1[0])),this.that.__zoom=w,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(b){var w=Se(this.that).datum();c.call(b,this.that,new Ax(b,{sourceEvent:this.sourceEvent,target:v,type:b,transform:this.that.__zoom,dispatch:c}),w)}};function A(b,...w){if(!e.apply(this,arguments))return;var T=N(this,w).event(b),j=this.__zoom,D=Math.max(o[0],Math.min(o[1],j.k*Math.pow(2,r.apply(this,arguments)))),L=Oe(b);if(T.wheel)(T.mouse[0][0]!==L[0]||T.mouse[0][1]!==L[1])&&(T.mouse[1]=j.invert(T.mouse[0]=L)),clearTimeout(T.wheel);else{if(j.k===D)return;T.mouse=[L,j.invert(L)],er(this),T.start()}an(b),T.wheel=setTimeout(F,p),T.zoom("mouse",n(m(I(j,D),T.mouse[0],T.mouse[1]),T.extent,i));function F(){T.wheel=null,T.end()}}function k(b,...w){if(f||!e.apply(this,arguments))return;var T=b.currentTarget,j=N(this,w,!0).event(b),D=Se(b.view).on("mousemove.zoom",B,!0).on("mouseup.zoom",K,!0),L=Oe(b,T),F=b.clientX,z=b.clientY;kc(b.view),as(b),j.mouse=[L,this.__zoom.invert(L)],er(this),j.start();function B(H){if(an(H),!j.moved){var W=H.clientX-F,J=H.clientY-z;j.moved=W*W+J*J>y}j.event(H).zoom("mouse",n(m(j.that.__zoom,j.mouse[0]=Oe(H,T),j.mouse[1]),j.extent,i))}function K(H){D.on("mousemove.zoom mouseup.zoom",null),Oc(H.view,j.moved),an(H),j.event(H).end()}}function P(b,...w){if(e.apply(this,arguments)){var T=this.__zoom,j=Oe(b.changedTouches?b.changedTouches[0]:b,this),D=T.invert(j),L=T.k*(b.shiftKey?.5:2),F=n(m(I(T,L),j,D),t.apply(this,w),i);an(b),a>0?Se(this).transition().duration(a).call(E,F,j,b):Se(this).call(v.transform,F,j,b)}}function _(b,...w){if(e.apply(this,arguments)){var T=b.touches,j=T.length,D=N(this,w,b.changedTouches.length===j).event(b),L,F,z,B;for(as(b),F=0;F<j;++F)z=T[F],B=Oe(z,this),B=[B,this.__zoom.invert(B),z.identifier],D.touch0?!D.touch1&&D.touch0[2]!==B[2]&&(D.touch1=B,D.taps=0):(D.touch0=B,L=!0,D.taps=1+!!u);u&&(u=clearTimeout(u)),L&&(D.taps<2&&(d=B[0],u=setTimeout(function(){u=null},g)),er(this),D.start())}}function M(b,...w){if(this.__zooming){var T=N(this,w).event(b),j=b.changedTouches,D=j.length,L,F,z,B;for(an(b),L=0;L<D;++L)F=j[L],z=Oe(F,this),T.touch0&&T.touch0[2]===F.identifier?T.touch0[0]=z:T.touch1&&T.touch1[2]===F.identifier&&(T.touch1[0]=z);if(F=T.that.__zoom,T.touch1){var K=T.touch0[0],H=T.touch0[1],W=T.touch1[0],J=T.touch1[1],X=(X=W[0]-K[0])*X+(X=W[1]-K[1])*X,$=($=J[0]-H[0])*$+($=J[1]-H[1])*$;F=I(F,Math.sqrt(X/$)),z=[(K[0]+W[0])/2,(K[1]+W[1])/2],B=[(H[0]+J[0])/2,(H[1]+J[1])/2]}else if(T.touch0)z=T.touch0[0],B=T.touch0[1];else return;T.zoom("touch",n(m(F,z,B),T.extent,i))}}function O(b,...w){if(this.__zooming){var T=N(this,w).event(b),j=b.changedTouches,D=j.length,L,F;for(as(b),f&&clearTimeout(f),f=setTimeout(function(){f=null},g),L=0;L<D;++L)F=j[L],T.touch0&&T.touch0[2]===F.identifier?delete T.touch0:T.touch1&&T.touch1[2]===F.identifier&&delete T.touch1;if(T.touch1&&!T.touch0&&(T.touch0=T.touch1,delete T.touch1),T.touch0)T.touch0[1]=this.__zoom.invert(T.touch0[0]);else if(T.end(),T.taps===2&&(F=Oe(F,this),Math.hypot(d[0]-F[0],d[1]-F[1])<x)){var z=Se(this).on("dblclick.zoom");z&&z.apply(this,arguments)}}}return v.wheelDelta=function(b){return arguments.length?(r=typeof b=="function"?b:Hn(+b),v):r},v.filter=function(b){return arguments.length?(e=typeof b=="function"?b:Hn(!!b),v):e},v.touchable=function(b){return arguments.length?(s=typeof b=="function"?b:Hn(!!b),v):s},v.extent=function(b){return arguments.length?(t=typeof b=="function"?b:Hn([[+b[0][0],+b[0][1]],[+b[1][0],+b[1][1]]]),v):t},v.scaleExtent=function(b){return arguments.length?(o[0]=+b[0],o[1]=+b[1],v):[o[0],o[1]]},v.translateExtent=function(b){return arguments.length?(i[0][0]=+b[0][0],i[1][0]=+b[1][0],i[0][1]=+b[0][1],i[1][1]=+b[1][1],v):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},v.constrain=function(b){return arguments.length?(n=b,v):n},v.duration=function(b){return arguments.length?(a=+b,v):a},v.interpolate=function(b){return arguments.length?(l=b,v):l},v.on=function(){var b=c.on.apply(c,arguments);return b===c?v:b},v.clickDistance=function(b){return arguments.length?(y=(b=+b)*b,v):Math.sqrt(y)},v.tapDistance=function(b){return arguments.length?(x=+b,v):x},v}var Te={error001:(e="react")=>`Seems like you have not used ${e==="svelte"?"SvelteFlowProvider":"ReactFlowProvider"} as an ancestor. Help: https://${e}flow.dev/error#001`,error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${e==="source"?n:r}", edge id: ${t}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs.",error016:e=>`Edge with id "${e}" does not exist, it may have been removed. This can happen when an edge is deleted before the "onEdgeClick" handler is called.`},Cn=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Qc=["Enter"," ","Escape"],Jc={"node.a11yDescription.default":"Press enter or space to select a node. Press delete to remove it and escape to cancel.","node.a11yDescription.keyboardDisabled":"Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.","node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:n})=>`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.","controls.ariaLabel":"Control Panel","controls.zoomIn.ariaLabel":"Zoom In","controls.zoomOut.ariaLabel":"Zoom Out","controls.fitView.ariaLabel":"Fit View","controls.interactive.ariaLabel":"Toggle Interactivity","minimap.ariaLabel":"Mini Map","handle.ariaLabel":"Handle"},Wt;(function(e){e.Strict="strict",e.Loose="loose"})(Wt||(Wt={}));var wt;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(wt||(wt={}));var Nn;(function(e){e.Partial="partial",e.Full="full"})(Nn||(Nn={}));var Zc={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null},lt;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(lt||(lt={}));var pr;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(pr||(pr={}));var Y;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(Y||(Y={}));var Di={[Y.Left]:Y.Right,[Y.Right]:Y.Left,[Y.Top]:Y.Bottom,[Y.Bottom]:Y.Top},eu=e=>!!e&&typeof e=="object"&&"id"in e&&"source"in e&&"target"in e,Lx=e=>!!e&&typeof e=="object"&&"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),bo=e=>!!e&&typeof e=="object"&&"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),kn=(e,t=[0,0])=>{const{width:n,height:r}=Fe(e),s=e.origin??t,o=n*s[0],i=r*s[1];return{x:e.position.x-o,y:e.position.y-i}},Dx=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};let n=!1;const r=e.reduce((s,o)=>{const i=typeof o=="string";let a=!t.nodeLookup&&!i?o:void 0;return t.nodeLookup&&(a=i?t.nodeLookup.get(o):bo(o)?o:t.nodeLookup.get(o.id)),a?(n=!0,Pr(s,gr(a,t.nodeOrigin))):s},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return n?Lr(r):{x:0,y:0,width:0,height:0}},On=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(s=>{(t.filter===void 0||t.filter(s))&&(n=Pr(n,gr(s)),r=!0)}),r?Lr(n):{x:0,y:0,width:0,height:0}},xo=(e,t,[n,r,s]=[0,0,1],o=!1,i=!1)=>{const a=(t.x-n)/s,l=(t.y-r)/s,c=t.width/s,u=t.height/s,d=[];for(const f of e.values()){const{measured:g,selectable:p=!0,hidden:y=!1}=f;if(i&&!p||y)continue;const x=g.width??f.width??f.initialWidth??0,v=g.height??f.height??f.initialHeight??0,{x:I,y:m}=f.internals.positionAbsolute,S=su(a,l,c,u,I,m,x,v),E=x*v,N=o&&S>0;(!f.internals.handleBounds||N||S>=E||f.dragging)&&d.push(f)}return d},$x=(e,t)=>{const n=new Set;return e.forEach(r=>{n.add(r.id)}),t.filter(r=>n.has(r.source)||n.has(r.target))};function Fx(e,t){const n=new Map,r=t?.nodes?new Set(t.nodes.map(s=>s.id)):null;return e.forEach(s=>{let o;if(t?.includeHiddenNodes){const{width:i,height:a}=Fe(s);o=i>0&&a>0}else o=!!(s.measured.width&&s.measured.height&&!s.hidden);o&&(!r||r.has(s.id))&&n.set(s.id,s)}),n}async function zx({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:o},i){if(e.size===0)return!0;const a=Fx(e,i),l=On(a),c=Io(l,t,n,i?.minZoom??s,i?.maxZoom??o,i?.padding??.1);return await r.setViewport(c,{duration:i?.duration,ease:i?.ease,interpolate:i?.interpolate}),!0}function tu({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:o}){const i=n.get(e),a=i.parentId?n.get(i.parentId):void 0,{x:l,y:c}=a?a.internals.positionAbsolute:{x:0,y:0},u=i.origin??r;let d=i.extent||s;if(i.extent==="parent"&&!i.expandParent)if(!a)o?.("005",Te.error005());else{const{width:g,height:p}=Fe(a);g&&p&&(d=[[l,c],[l+g,c+p]])}else a&&_t(i.extent)&&(d=[[i.extent[0][0]+l,i.extent[0][1]+c],[i.extent[1][0]+l,i.extent[1][1]+c]]);const f=_t(d)?Rt(t,d,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&o?.("015",Te.error015()),{position:{x:f.x-l+(i.measured.width??0)*u[0],y:f.y-c+(i.measured.height??0)*u[1]},positionAbsolute:f}}async function Hx({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const o=new Set(e.map(d=>d.id)),i=[];for(const d of n){if(d.deletable===!1)continue;const f=o.has(d.id),g=!f&&d.parentId&&i.find(p=>p.id===d.parentId);(f||g)&&i.push(d)}const a=new Set(t.map(d=>d.id)),l=r.filter(d=>d.deletable!==!1),c=$x(i,l);for(const d of l)a.has(d.id)&&!c.find(f=>f.id===d.id)&&c.push(d);if(!s)return{edges:c,nodes:i};const u=await s({nodes:i,edges:c});return typeof u=="boolean"?u?{edges:c,nodes:i}:{edges:[],nodes:[]}:u}var Xt=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Rt=(e={x:0,y:0},t,n)=>({x:Xt(e.x,t[0][0],t[1][0]-(n?.width??0)),y:Xt(e.y,t[0][1],t[1][1]-(n?.height??0))});function nu(e,t,n){const{width:r,height:s}=Fe(n),{x:o,y:i}=n.internals.positionAbsolute;return Rt(e,[[o,i],[o+r,i+s]],t)}var $i=(e,t,n)=>e<t?Xt(Math.abs(e-t),1,t)/t:e>n?-Xt(Math.abs(e-n),1,t)/t:0,So=(e,t,n=15,r=40)=>[$i(e.x,r,t.width-r)*n,$i(e.y,r,t.height-r)*n],Pr=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),Os=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),Lr=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),Rn=(e,t=[0,0])=>{const{x:n,y:r}=bo(e)?e.internals.positionAbsolute:kn(e,t);return{x:n,y:r,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},gr=(e,t=[0,0])=>{const{x:n,y:r}=bo(e)?e.internals.positionAbsolute:kn(e,t);return{x:n,y:r,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:r+(e.measured?.height??e.height??e.initialHeight??0)}},ru=(e,t)=>Lr(Pr(Os(e),Os(t))),su=(e,t,n,r,s,o,i,a)=>{const l=Math.max(0,Math.min(e+n,s+i)-Math.max(e,s)),c=Math.max(0,Math.min(t+r,o+a)-Math.max(t,o));return Math.ceil(l*c)},mr=(e,t)=>su(e.x,e.y,e.width,e.height,t.x,t.y,t.width,t.height),Fi=e=>Pe(e.width)&&Pe(e.height)&&Pe(e.x)&&Pe(e.y),Pe=e=>!isNaN(e)&&isFinite(e),ou=(e,t)=>(n,r)=>{},jn=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),Pn=({x:e,y:t},[n,r,s],o=!1,i=[1,1])=>{const a={x:(e-n)/s,y:(t-r)/s};return o?jn(a,i):a},Qt=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function jt(e,t){if(typeof e=="number")return Math.floor((t-t/(1+e))*.5);if(typeof e=="string"&&e.endsWith("px")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(n)}if(typeof e=="string"&&e.endsWith("%")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function Bx(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=jt(e,n),s=jt(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=jt(e.top??e.y??0,n),s=jt(e.bottom??e.y??0,n),o=jt(e.left??e.x??0,t),i=jt(e.right??e.x??0,t);return{top:r,right:i,bottom:s,left:o,x:o+i,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function Gx(e,t,n,r,s,o){const{x:i,y:a}=Qt(e,[t,n,r]),{x:l,y:c}=Qt({x:e.x+e.width,y:e.y+e.height},[t,n,r]),u=s-l,d=o-c;return{left:Math.floor(i),top:Math.floor(a),right:Math.floor(u),bottom:Math.floor(d)}}var Io=(e,t,n,r,s,o)=>{const i=Bx(o,t,n),a=(t-i.x)/e.width,l=(n-i.y)/e.height,c=Xt(Math.min(a,l),r,s),u=e.x+e.width/2,d=e.y+e.height/2,f=t/2-u*c,g=n/2-d*c,p=Gx(e,f,g,c,t,n),y={left:Math.min(p.left-i.left,0),top:Math.min(p.top-i.top,0),right:Math.min(p.right-i.right,0),bottom:Math.min(p.bottom-i.bottom,0)};return{x:f-y.left+y.right,y:g-y.top+y.bottom,zoom:c}},_n=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function _t(e){return e!=null&&e!=="parent"}function Fe(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function wo(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function iu(e,t={width:0,height:0},n,r,s){const o={...e},i=r.get(n);if(i){const a=i.origin||s;o.x+=i.internals.positionAbsolute.x-(t.width??0)*a[0],o.y+=i.internals.positionAbsolute.y-(t.height??0)*a[1]}return o}function zi(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function Ux(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}function qx(e){return{...Jc,...e||{}}}function au(e){return e===null?null:e?"valid":"invalid"}function yn(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:o,y:i}=Le(e),a=Pn({x:o-(s?.left??0),y:i-(s?.top??0)},r),{x:l,y:c}=n?jn(a,t):a;return{xSnapped:l,ySnapped:c,...a}}var Eo=e=>({width:e.offsetWidth,height:e.offsetHeight}),lu=e=>e?.getRootNode?.()||window?.document,Vx=["INPUT","SELECT","TEXTAREA"];function cu(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:Vx.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}var uu=e=>"clientX"in e,Le=(e,t)=>{const n=uu(e),r=n?e.clientX:e.touches?.[0].clientX,s=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:s-(t?.top??0)}},Hi=(e,t,n,r,s)=>{const o=t.querySelectorAll(`.${e}`);return!o||!o.length?null:Array.from(o).map(i=>{const a=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:s,position:i.getAttribute("data-handlepos"),x:(a.left-n.left)/r,y:(a.top-n.top)/r,...Eo(i)}})};function du({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:o,targetControlX:i,targetControlY:a}){const l=e*.125+s*.375+i*.375+n*.125,c=t*.125+o*.375+a*.375+r*.125;return[l,c,Math.abs(l-e),Math.abs(c-t)]}function Bn(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Bi({pos:e,x1:t,y1:n,x2:r,y2:s,c:o}){switch(e){case Y.Left:return[t-Bn(t-r,o),n];case Y.Right:return[t+Bn(r-t,o),n];case Y.Top:return[t,n-Bn(n-s,o)];case Y.Bottom:return[t,n+Bn(s-n,o)]}}function hu({sourceX:e,sourceY:t,sourcePosition:n=Y.Bottom,targetX:r,targetY:s,targetPosition:o=Y.Top,curvature:i=.25}){const[a,l]=Bi({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[c,u]=Bi({pos:o,x1:r,y1:s,x2:e,y2:t,c:i}),[d,f,g,p]=du({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:a,sourceControlY:l,targetControlX:c,targetControlY:u});return[`M${e},${t} C${a},${l} ${c},${u} ${r},${s}`,d,f,g,p]}function fu({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,o=n<e?n+s:n-s,i=Math.abs(r-t)/2;return[o,r<t?r+i:r-i,s,i]}function Kx({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:o="basic"}){return o==="manual"?r:(s&&n?r+1e3:r)+Math.max(e.parentId||s&&e.selected?e.internals.z:0,t.parentId||s&&t.selected?t.internals.z:0)}function Yx({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const o=Pr(gr(e),gr(t));o.x===o.x2&&(o.x2+=1),o.y===o.y2&&(o.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return mr(i,Lr(o))>0}var Wx=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,Xx=(e,t)=>t.some(n=>n.source===e.source&&n.target===e.target&&(n.sourceHandle===e.sourceHandle||!n.sourceHandle&&!e.sourceHandle)&&(n.targetHandle===e.targetHandle||!n.targetHandle&&!e.targetHandle)),Qx=(e,t,n={})=>{if(!e.source||!e.target)return n.onError?.("006",Te.error006()),t;const r=n.getEdgeId||Wx;let s;return eu(e)?s={...e}:s={...e,id:r(e)},Xx(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function pu({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,o,i,a]=fu({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,o,i,a]}var Gi={[Y.Left]:{x:-1,y:0},[Y.Right]:{x:1,y:0},[Y.Top]:{x:0,y:-1},[Y.Bottom]:{x:0,y:1}},Jx=({source:e,sourcePosition:t=Y.Bottom,target:n})=>t===Y.Left||t===Y.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},Ui=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function Zx({source:e,sourcePosition:t=Y.Bottom,target:n,targetPosition:r=Y.Top,center:s,offset:o,stepPosition:i}){const a=Gi[t],l=Gi[r],c={x:e.x+a.x*o,y:e.y+a.y*o},u={x:n.x+l.x*o,y:n.y+l.y*o},d=Jx({source:c,sourcePosition:t,target:u}),f=d.x!==0?"x":"y",g=d[f];let p=[],y,x;const v={x:0,y:0},I={x:0,y:0},[,,m,S]=fu({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(a[f]*l[f]===-1){f==="x"?(y=s.x??c.x+(u.x-c.x)*i,x=s.y??(c.y+u.y)/2):(y=s.x??(c.x+u.x)/2,x=s.y??c.y+(u.y-c.y)*i);const R=[{x:y,y:c.y},{x:y,y:u.y}],A=[{x:c.x,y:x},{x:u.x,y:x}];a[f]===g?p=f==="x"?R:A:p=f==="x"?A:R}else{const R=[{x:c.x,y:u.y}],A=[{x:u.x,y:c.y}];if(f==="x"?p=a.x===g?A:R:p=a.y===g?R:A,t===r){const _=Math.abs(e[f]-n[f]);if(_<=o){const M=Math.min(o-1,o-_);a[f]===g?v[f]=(c[f]>e[f]?-1:1)*M:I[f]=(u[f]>n[f]?-1:1)*M}}if(t!==r){const _=f==="x"?"y":"x",M=a[f]===l[_],O=c[_]>u[_],b=c[_]<u[_];(a[f]===1&&(!M&&O||M&&b)||a[f]!==1&&(!M&&b||M&&O))&&(p=f==="x"?R:A)}const k={x:c.x+v.x,y:c.y+v.y},P={x:u.x+I.x,y:u.y+I.y};Math.max(Math.abs(k.x-p[0].x),Math.abs(P.x-p[0].x))>=Math.max(Math.abs(k.y-p[0].y),Math.abs(P.y-p[0].y))?(y=(k.x+P.x)/2,x=p[0].y):(y=p[0].x,x=(k.y+P.y)/2)}const E={x:c.x+v.x,y:c.y+v.y},N={x:u.x+I.x,y:u.y+I.y};return[[e,...E.x!==p[0].x||E.y!==p[0].y?[E]:[],...p,...N.x!==p[p.length-1].x||N.y!==p[p.length-1].y?[N]:[],n],y,x,m,S]}function eS(e,t,n,r){const s=Math.min(Ui(e,t)/2,Ui(t,n)/2,r),{x:o,y:i}=t;if(e.x===o&&o===n.x||e.y===i&&i===n.y)return`L${o} ${i}`;if(e.y===i){const l=e.x<n.x?-1:1,c=e.y<n.y?1:-1;return`L ${o+s*l},${i}Q ${o},${i} ${o},${i+s*c}`}const a=e.x<n.x?1:-1;return`L ${o},${i+s*(e.y<n.y?-1:1)}Q ${o},${i} ${o+s*a},${i}`}function js({sourceX:e,sourceY:t,sourcePosition:n=Y.Bottom,targetX:r,targetY:s,targetPosition:o=Y.Top,borderRadius:i=5,centerX:a,centerY:l,offset:c=20,stepPosition:u=.5}){const[d,f,g,p,y]=Zx({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:o,center:{x:a,y:l},offset:c,stepPosition:u});let x=`M${d[0].x} ${d[0].y}`;for(let v=1;v<d.length-1;v++)x+=eS(d[v-1],d[v],d[v+1],i);return x+=`L${d[d.length-1].x} ${d[d.length-1].y}`,[x,f,g,p,y]}function qi(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function tS(e){const{sourceNode:t,targetNode:n}=e;if(!qi(t)||!qi(n))return null;const r=t.internals.handleBounds||Vi(t.handles),s=n.internals.handleBounds||Vi(n.handles),o=Ki(r?.source??[],e.sourceHandle),i=Ki(e.connectionMode===Wt.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!o||!i)return e.onError?.("008",Te.error008(o?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const a=o?.position||Y.Bottom,l=i?.position||Y.Top,c=Tt(t,o,a),u=Tt(n,i,l);return{sourceX:c.x,sourceY:c.y,targetX:u.x,targetY:u.y,sourcePosition:a,targetPosition:l}}function Vi(e){if(!e)return null;const t=[],n=[];for(const r of e)r.width=r.width??1,r.height=r.height??1,r.type==="source"?t.push(r):r.type==="target"&&n.push(r);return{source:t,target:n}}function Tt(e,t,n=Y.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,o=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:a}=t??Fe(e);if(r)return{x:s+i/2,y:o+a/2};switch(t?.position??n){case Y.Top:return{x:s+i/2,y:o};case Y.Right:return{x:s+i,y:o+a/2};case Y.Bottom:return{x:s+i/2,y:o+a};case Y.Left:return{x:s,y:o+a/2}}}function Ki(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Ps(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(n=>`${n}=${e[n]}`).join("&")}`:""}function nS(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const o=new Set;return e.reduce((i,a)=>([a.markerStart||r,a.markerEnd||s].forEach(l=>{if(l&&typeof l=="object"){const c=Ps(l,t);o.has(c)||(i.push({id:c,color:l.color||n,...l}),o.add(c))}}),i),[]).sort((i,a)=>i.id.localeCompare(a.id))}var gu=1e3,rS=10,Co={nodeOrigin:[0,0],nodeExtent:Cn,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},sS={...Co,checkEquality:!0};function No(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function oS(e,t,n){const r=No(Co,n);for(const s of e.values())if(s.parentId)_o(s,e,t,r);else{const o=kn(s,r.nodeOrigin),i=_t(s.extent)?s.extent:r.nodeExtent,a=Rt(o,i,Fe(s));s.internals.positionAbsolute=a}}function iS(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const o={id:s.id,width:s.width??1,height:s.height??1,nodeId:e.id,x:s.x,y:s.y,position:s.position,type:s.type};s.type==="source"?n.push(o):s.type==="target"&&r.push(o)}return{source:n,target:r}}function Ro(e){return e==="manual"}function Ls(e,t,n,r={}){const s=No(sS,r),o={i:0},i=new Map(t),a=s?.elevateNodesOnSelect&&!Ro(s.zIndexMode)?gu:0;let l=e.length>0,c=!1;t.clear(),n.clear();for(const u of e){let d=i.get(u.id);if(s.checkEquality&&u===d?.internals.userNode)t.set(u.id,d);else{const f=kn(u,s.nodeOrigin),g=_t(u.extent)?u.extent:s.nodeExtent,p=Rt(f,g,Fe(u));d={...s.defaults,...u,measured:{width:u.measured?.width,height:u.measured?.height},internals:{positionAbsolute:p,handleBounds:iS(u,d),z:mu(u,a,s.zIndexMode),userNode:u}},t.set(u.id,d)}(d.measured===void 0||d.measured.width===void 0||d.measured.height===void 0)&&!d.hidden&&(l=!1),u.parentId&&_o(d,t,n,r,o),c||=u.selected??!1}return{nodesInitialized:l,hasSelectedNodes:c}}function aS(e,t){if(!e.parentId)return;const n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}function _o(e,t,n,r,s){const{elevateNodesOnSelect:o,nodeOrigin:i,nodeExtent:a,zIndexMode:l}=No(Co,r),c=e.parentId,u=t.get(c);if(!u){console.warn(`Parent node ${c} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}aS(e,n),s&&!u.parentId&&u.internals.rootParentIndex===void 0&&l==="auto"&&(u.internals.rootParentIndex=++s.i,u.internals.z=u.internals.z+s.i*rS),s&&u.internals.rootParentIndex!==void 0&&(s.i=u.internals.rootParentIndex);const{x:d,y:f,z:g}=lS(e,u,i,a,o&&!Ro(l)?gu:0,l),{positionAbsolute:p}=e.internals,y=d!==p.x||f!==p.y;(y||g!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:d,y:f}:p,z:g}})}function mu(e,t,n){const r=Pe(e.zIndex)?e.zIndex:0;return Ro(n)?r:r+(e.selected?t:0)}function lS(e,t,n,r,s,o){const{x:i,y:a}=t.internals.positionAbsolute,l=Fe(e),c=kn(e,n),u=_t(e.extent)?Rt(c,e.extent,l):c;let d=Rt({x:i+u.x,y:a+u.y},r,l);e.extent==="parent"&&(d=nu(d,l,t));const f=mu(e,s,o),g=t.internals.z??0;return{x:d.x,y:d.y,z:g>=f?g+1:f}}function To(e,t,n,r=[0,0]){const s=[],o=new Map;for(const i of e){const a=t.get(i.parentId);if(!a)continue;const l=o.get(i.parentId)?.expandedRect??Rn(a),c=ru(l,i.rect);o.set(i.parentId,{expandedRect:c,parent:a})}return o.size>0&&o.forEach(({expandedRect:i,parent:a},l)=>{const c=a.internals.positionAbsolute,u=Fe(a),d=a.origin??r,f=i.x<c.x?Math.round(Math.abs(c.x-i.x)):0,g=i.y<c.y?Math.round(Math.abs(c.y-i.y)):0,p=Math.max(u.width,Math.round(i.width)),y=Math.max(u.height,Math.round(i.height)),x=(p-u.width)*d[0],v=(y-u.height)*d[1];(f>0||g>0||x||v)&&(s.push({id:l,type:"position",position:{x:a.position.x-f+x,y:a.position.y-g+v}}),n.get(l)?.forEach(I=>{e.some(m=>m.id===I.id)||s.push({id:I.id,type:"position",position:{x:I.position.x+f,y:I.position.y+g}})})),(u.width<i.width||u.height<i.height||f||g)&&s.push({id:l,type:"dimensions",setAttributes:!0,dimensions:{width:p+(f?d[0]*f-x:0),height:y+(g?d[1]*g-v:0)}})}),s}function cS(e,t,n,r,s,o,i){const a=r?.querySelector(".xyflow__viewport");let l=!1;if(!a)return{changes:[],updatedInternals:l};const c=[],u=window.getComputedStyle(a),{m22:d}=new window.DOMMatrixReadOnly(u.transform),f=[];for(const g of e.values()){const p=t.get(g.id);if(!p)continue;if(p.hidden){t.set(p.id,{...p,internals:{...p.internals,handleBounds:void 0}}),l=!0;continue}const y=Eo(g.nodeElement),x=p.measured.width!==y.width||p.measured.height!==y.height;if(y.width&&y.height&&(x||!p.internals.handleBounds||g.force)){const v=g.nodeElement.getBoundingClientRect(),I=_t(p.extent)?p.extent:o;let{positionAbsolute:m}=p.internals;if(p.parentId&&p.extent==="parent"){const E=t.get(p.parentId);E&&(m=nu(m,y,E))}else I&&(m=Rt(m,I,y));const S={...p,measured:y,internals:{...p.internals,positionAbsolute:m,handleBounds:{source:Hi("source",g.nodeElement,v,d,p.id),target:Hi("target",g.nodeElement,v,d,p.id)}}};t.set(p.id,S),p.parentId&&_o(S,t,n,{nodeOrigin:s,zIndexMode:i}),l=!0,x&&(c.push({id:p.id,type:"dimensions",dimensions:y}),p.expandParent&&p.parentId&&f.push({id:p.id,parentId:p.parentId,rect:Rn(S,s)}))}}if(f.length>0){const g=To(f,t,n,s);c.push(...g)}return{changes:c,updatedInternals:l}}async function uS({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:o}){if(!t||!e.x&&!e.y)return!1;const i=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,o]],r);return!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2])}function Yi(e,t,n,r,s,o){let i=s;const a=r.get(i)||new Map;r.set(i,a.set(n,t)),i=`${s}-${e}`;const l=r.get(i)||new Map;if(r.set(i,l.set(n,t)),o){i=`${s}-${e}-${o}`;const c=r.get(i)||new Map;r.set(i,c.set(n,t))}}function vu(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:o,sourceHandle:i=null,targetHandle:a=null}=r,l={edgeId:r.id,source:s,target:o,sourceHandle:i,targetHandle:a},c=`${s}-${i}--${o}-${a}`;Yi("source",l,`${o}-${a}--${s}-${i}`,e,s,i),Yi("target",l,c,e,o,a),t.set(r.id,r)}}function yu(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:yu(n,t):!1}function Wi(e,t,n){let r=e;do{if(r?.matches?.(t))return!0;if(r===n)return!1;r=r?.parentElement}while(r);return!1}function dS(e,t,n,r){const s=new Map;for(const[o,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!yu(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const a=e.get(o);a&&s.set(o,{id:o,position:a.position||{x:0,y:0},distance:{x:n.x-a.internals.positionAbsolute.x,y:n.y-a.internals.positionAbsolute.y},extent:a.extent,parentId:a.parentId,origin:a.origin,expandParent:a.expandParent,internals:{positionAbsolute:a.internals.positionAbsolute||{x:0,y:0}},measured:{width:a.measured.width??0,height:a.measured.height??0}})}return s}function ls({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const s=[];for(const[i,a]of t){const l=n.get(i)?.internals.userNode;l&&s.push({...l,position:a.position,dragging:r})}if(!e)return[s[0],s];const o=n.get(e)?.internals.userNode;return[o?{...o,position:t.get(e)?.position||o.position,dragging:r}:s[0],s]}function hS({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const o={x:n-s.distance.x,y:r-s.distance.y},i=jn(o,t);return{x:i.x-o.x,y:i.y-o.y}}function fS({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let o={x:null,y:null},i=0,a=new Map,l=!1,c={x:0,y:0},u=null,d=!1,f=null,g=!1,p=!1,y=null;function x({noDragClassName:I,handleSelector:m,domNode:S,isSelectable:E,nodeId:N,nodeClickDistance:R=0}){f=Se(S);function A({x:M,y:O}){const{nodeLookup:b,nodeExtent:w,snapGrid:T,snapToGrid:j,nodeOrigin:D,onNodeDrag:L,onSelectionDrag:F,onError:z,updateNodePositions:B}=t();o={x:M,y:O};let K=!1;const H=a.size>1,W=H&&w?Os(On(a)):null,J=H&&j?hS({dragItems:a,snapGrid:T,x:M,y:O}):null;for(const[X,$]of a){if(!b.has(X))continue;let q={x:M-$.distance.x,y:O-$.distance.y};j&&(q=J?{x:Math.round(q.x+J.x),y:Math.round(q.y+J.y)}:jn(q,T));let Q=null;if(H&&w&&!$.extent&&W){const{positionAbsolute:ne}=$.internals,Z=ne.x-W.x+w[0][0],U=ne.x+$.measured.width-W.x2+w[1][0],V=ne.y-W.y+w[0][1],pe=ne.y+$.measured.height-W.y2+w[1][1];Q=[[Z,V],[U,pe]]}const{position:te,positionAbsolute:G}=tu({nodeId:X,nextPosition:q,nodeLookup:b,nodeExtent:Q||w,nodeOrigin:D,onError:z});K=K||$.position.x!==te.x||$.position.y!==te.y,$.position=te,$.internals.positionAbsolute=G}if(p=p||K,!!K&&(B(a,!0),y&&(r||L||!N&&F))){const[X,$]=ls({nodeId:N,dragItems:a,nodeLookup:b});r?.(y,a,X,$),L?.(y,X,$),N||F?.(y,$)}}async function k(){if(!u)return;const{transform:M,panBy:O,autoPanSpeed:b,autoPanOnNodeDrag:w}=t();if(!w){l=!1,cancelAnimationFrame(i);return}const[T,j]=So(c,u,b);(T!==0||j!==0)&&(o.x=(o.x??0)-T/M[2],o.y=(o.y??0)-j/M[2],await O({x:T,y:j})&&A(o)),i=requestAnimationFrame(k)}function P(M){const{nodeLookup:O,multiSelectionActive:b,nodesDraggable:w,transform:T,snapGrid:j,snapToGrid:D,selectNodesOnDrag:L,onNodeDragStart:F,onSelectionDragStart:z,unselectNodesAndEdges:B}=t();d=!0,(!L||!E)&&!b&&N&&(O.get(N)?.selected||B()),E&&L&&N&&e?.(N);const K=yn(M.sourceEvent,{transform:T,snapGrid:j,snapToGrid:D,containerBounds:u});if(o=K,a=dS(O,w,K,N),a.size>0&&(n||F||!N&&z)){const[H,W]=ls({nodeId:N,dragItems:a,nodeLookup:O});n?.(M.sourceEvent,a,H,W),F?.(M.sourceEvent,H,W),N||z?.(M.sourceEvent,W)}}const _=jc().clickDistance(R).on("start",M=>{const{domNode:O,nodeDragThreshold:b,transform:w,snapGrid:T,snapToGrid:j}=t();u=O?.getBoundingClientRect()||null,g=!1,p=!1,y=M.sourceEvent,b===0&&P(M),o=yn(M.sourceEvent,{transform:w,snapGrid:T,snapToGrid:j,containerBounds:u}),c=Le(M.sourceEvent,u)}).on("drag",M=>{const{autoPanOnNodeDrag:O,transform:b,snapGrid:w,snapToGrid:T,nodeDragThreshold:j,nodeLookup:D}=t(),L=yn(M.sourceEvent,{transform:b,snapGrid:w,snapToGrid:T,containerBounds:u});if(y=M.sourceEvent,(M.sourceEvent.type==="touchmove"&&M.sourceEvent.touches.length>1||N&&!D.has(N))&&(g=!0),!g){if(!l&&O&&d&&(l=!0,k()),!d){const F=Le(M.sourceEvent,u),z=F.x-c.x,B=F.y-c.y;Math.sqrt(z*z+B*B)>j&&P(M)}(o.x!==L.xSnapped||o.y!==L.ySnapped)&&a&&d&&(c=Le(M.sourceEvent,u),A(L))}}).on("end",M=>{if(!d||g){g&&a.size>0&&t().updateNodePositions(a,!1);return}if(l=!1,d=!1,cancelAnimationFrame(i),a.size>0){const{nodeLookup:O,updateNodePositions:b,onNodeDragStop:w,onSelectionDragStop:T}=t();if(p&&(b(a,!1),p=!1),s||w||!N&&T){const[j,D]=ls({nodeId:N,dragItems:a,nodeLookup:O,dragging:!1});s?.(M.sourceEvent,a,j,D),w?.(M.sourceEvent,j,D),N||T?.(M.sourceEvent,D)}}}).filter(M=>{const O=M.target;return!M.button&&(!I||!Wi(O,`.${I}`,S))&&(!m||Wi(O,m,S))});f.call(_)}function v(){f?.on(".drag",null)}return{update:x,destroy:v}}function pS(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const o of t.values())mr(s,Rn(o))>0&&r.push(o);return r}var gS=250;function mS(e,t,n,r){let s=[],o=1/0;const i=pS(e,n,t+gS);for(const a of i){const l=[...a.internals.handleBounds?.source??[],...a.internals.handleBounds?.target??[]];for(const c of l){if(r.nodeId===c.nodeId&&r.type===c.type&&r.id===c.id)continue;const{x:u,y:d}=Tt(a,c,c.position,!0),f=Math.sqrt(Math.pow(u-e.x,2)+Math.pow(d-e.y,2));f>t||(f<o?(s=[{...c,x:u,y:d}],o=f):f===o&&s.push({...c,x:u,y:d}))}}if(!s.length)return null;if(s.length>1){const a=r.type==="source"?"target":"source";return s.find(l=>l.type===a)??s[0]}return s[0]}function bu(e,t,n,r,s,o=!1){const i=r.get(e);if(!i)return null;const a=s==="strict"?i.internals.handleBounds?.[t]:[...i.internals.handleBounds?.source??[],...i.internals.handleBounds?.target??[]],l=(n?a?.find(c=>c.id===n):a?.[0])??null;return l&&o?{...l,...Tt(i,l,l.position,!0)}:l}function xu(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function vS(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}var Su=()=>!0;function yS(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:o,isTarget:i,domNode:a,nodeLookup:l,lib:c,autoPanOnConnect:u,flowId:d,panBy:f,cancelConnection:g,onConnectStart:p,onConnect:y,onConnectEnd:x,isValidConnection:v=Su,onReconnectEnd:I,updateConnection:m,getTransform:S,getFromHandle:E,autoPanSpeed:N,dragThreshold:R=1,handleDomNode:A}){const k=lu(e.target);let P=0,_;const{x:M,y:O}=Le(e),b=xu(o,A),w=a?.getBoundingClientRect();let T=!1;if(!w||!b)return;const j=bu(s,b,r,l,t);if(!j)return;let D=Le(e,w),L=!1,F=null,z=!1,B=null;function K(){if(!u||!w)return;const[Q,te]=So(D,w,N);f({x:Q,y:te}),P=requestAnimationFrame(K)}const H={...j,nodeId:s,type:b,position:j.position},W=l.get(s);let J={inProgress:!0,isValid:null,from:Tt(W,H,Y.Left,!0),fromHandle:H,fromPosition:H.position,fromNode:W,to:D,toHandle:null,toPosition:Di[H.position],toNode:null,pointer:D};function X(){T=!0,m(J),p?.(e,{nodeId:s,handleId:r,handleType:b})}R===0&&X();function $(Q){if(!T){const{x:V,y:pe}=Le(Q),ge=V-M,ve=pe-O;if(!(ge*ge+ve*ve>R*R))return;X()}if(!E()||!H){q(Q);return}const te=S();D=Le(Q,w),_=mS(Pn(D,te,!1,[1,1]),n,l,H),L||(K(),L=!0);const G=Iu(Q,{handle:_,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:v,doc:k,lib:c,flowId:d,nodeLookup:l});B=G.handleDomNode,F=G.connection,z=vS(!!_,G.isValid);const ne=l.get(s),Z=ne?Tt(ne,H,Y.Left,!0):J.from,U={...J,from:Z,isValid:z,to:G.toHandle&&z?Qt({x:G.toHandle.x,y:G.toHandle.y},te):D,toHandle:G.toHandle,toPosition:z&&G.toHandle?G.toHandle.position:Di[H.position],toNode:G.toHandle?l.get(G.toHandle.nodeId):null,pointer:D};m(U),J=U}function q(Q){if(!("touches"in Q&&Q.touches.length>0)){if(T){(_||B)&&F&&z&&y?.(F);const{inProgress:te,...G}=J,ne={...G,toPosition:J.toHandle?J.toPosition:null};x?.(Q,ne),o&&I?.(Q,ne)}g(),cancelAnimationFrame(P),L=!1,z=!1,F=null,B=null,k.removeEventListener("mousemove",$),k.removeEventListener("mouseup",q),k.removeEventListener("touchmove",$),k.removeEventListener("touchend",q)}}k.addEventListener("mousemove",$),k.addEventListener("mouseup",q),k.addEventListener("touchmove",$),k.addEventListener("touchend",q)}function Iu(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:o,doc:i,lib:a,flowId:l,isValidConnection:c=Su,nodeLookup:u}){const d=o==="target",f=t?i.querySelector(`.${a}-flow__handle[data-id="${l}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:g,y:p}=Le(e),y=i.elementFromPoint(g,p),x=y?.classList.contains(`${a}-flow__handle`)?y:f,v={handleDomNode:x,isValid:!1,connection:null,toHandle:null};if(x){const I=xu(void 0,x),m=x.getAttribute("data-nodeid"),S=x.getAttribute("data-handleid"),E=x.classList.contains("connectable"),N=x.classList.contains("connectableend");if(!m||!I)return v;const R={source:d?m:r,sourceHandle:d?S:s,target:d?r:m,targetHandle:d?s:S};v.connection=R,v.isValid=E&&N&&(n===Wt.Strict?d&&I==="source"||!d&&I==="target":m!==r||S!==s)&&c(R),v.toHandle=bu(m,I,S,u,n,!0)}return v}var Ds={onPointerDown:yS,isValid:Iu};function bS({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Se(e);function o({translateExtent:a,width:l,height:c,zoomStep:u=1,pannable:d=!0,zoomable:f=!0,inversePan:g=!1}){const p=m=>{if(m.sourceEvent.type!=="wheel"||!t)return;const S=n(),E=m.sourceEvent.ctrlKey&&_n()?10:1,N=-m.sourceEvent.deltaY*(m.sourceEvent.deltaMode===1?.05:m.sourceEvent.deltaMode?1:.002)*u,R=S[2]*Math.pow(2,N*E);t.scaleTo(R)};let y=[0,0];const x=m=>{(m.sourceEvent.type==="mousedown"||m.sourceEvent.type==="touchstart")&&(y=[m.sourceEvent.clientX??m.sourceEvent.touches[0].clientX,m.sourceEvent.clientY??m.sourceEvent.touches[0].clientY])},v=m=>{const S=n();if(m.sourceEvent.type!=="mousemove"&&m.sourceEvent.type!=="touchmove"||!t)return;const E=[m.sourceEvent.clientX??m.sourceEvent.touches[0].clientX,m.sourceEvent.clientY??m.sourceEvent.touches[0].clientY],N=[E[0]-y[0],E[1]-y[1]];y=E;const R=r()*Math.max(S[2],Math.log(S[2]))*(g?-1:1),A={x:S[0]-N[0]*R,y:S[1]-N[1]*R},k=[[0,0],[l,c]];t.setViewportConstrained({x:A.x,y:A.y,zoom:S[2]},k,a)},I=Xc().on("start",x).on("zoom",d?v:null).on("zoom.wheel",f?p:null);s.call(I,{})}function i(){s.on("zoom",null)}return{update:o,destroy:i,pointer:Oe}}var Dr=e=>({x:e.x,y:e.y,zoom:e.k}),cs=({x:e,y:t,zoom:n})=>jr.translate(e,t).scale(n),at=(e,t)=>e.target.closest(`.${t}`),wu=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),xS=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,us=(e,t=0,n=xS,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},Eu=e=>{const t=e.ctrlKey&&_n()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function SS({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:o,zoomOnPinch:i,onPanZoomStart:a,onPanZoom:l,onPanZoomEnd:c}){return u=>{if(at(u,t))return u.ctrlKey&&u.preventDefault(),!1;u.preventDefault(),u.stopImmediatePropagation();const d=n.property("__zoom").k||1;if(u.ctrlKey&&i){const x=Oe(u),v=Eu(u),I=d*Math.pow(2,v);r.scaleTo(n,I,x,u);return}const f=u.deltaMode===1?20:1;let g=s===wt.Vertical?0:u.deltaX*f,p=s===wt.Horizontal?0:u.deltaY*f;!_n()&&u.shiftKey&&s!==wt.Vertical&&(g=u.deltaY*f,p=0),r.translateBy(n,-(g/d)*o,-(p/d)*o,{internal:!0});const y=Dr(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?l?.(u,y):(e.isPanScrolling=!0,a?.(u,y)),e.panScrollTimeout=setTimeout(()=>{c?.(u,y),e.isPanScrolling=!1},150)}}function IS({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const o=r.type==="wheel",i=!t&&o&&!r.ctrlKey,a=at(r,e);if(r.ctrlKey&&o&&a&&r.preventDefault(),i||a)return null;r.preventDefault(),n.call(this,r,s)}}function wS({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=Dr(r.transform);e.mouseButton=r.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=s,r.sourceEvent?.type==="mousedown"&&t(!0),n&&n?.(r.sourceEvent,s)}}function ES({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return o=>{e.usedRightMouseButton=!!(n&&wu(t,e.mouseButton??0)),o.sourceEvent?.sync||r([o.transform.x,o.transform.y,o.transform.k]),s&&!o.sourceEvent?.internal&&s?.(o.sourceEvent,Dr(o.transform))}}function CS({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:o}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,o&&wu(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&o(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const a=Dr(i.transform);e.prevViewport=a,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,a)},n?150:0)}}}function NS({panActivationKeyPressed:e,zoomActivationKeyPressed:t,zoomOnScroll:n,zoomOnPinch:r,panOnDrag:s,panOnScroll:o,zoomOnDoubleClick:i,userSelectionActive:a,noWheelClassName:l,noPanClassName:c,lib:u,connectionInProgress:d}){return f=>{const g=t||n,p=r&&f.ctrlKey,y=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(at(f,`${u}-flow__node`)||at(f,`${u}-flow__edge`)||at(f,`${u}-flow__selection`)||at(f,`${u}-flow__nodesselection`)))return!0;if(!s&&!g&&!o&&!i&&!r||a||d&&!y||at(f,l)&&y||at(f,c)&&(!y||o&&y&&!t)||!r&&f.ctrlKey&&y)return!1;if(!r&&f.type==="touchstart"&&f.touches?.length>1)return f.preventDefault(),!1;if(!g&&!o&&!p&&y||!s&&(f.type==="mousedown"||f.type==="touchstart")||Array.isArray(s)&&!s.includes(f.button)&&f.type==="mousedown")return!1;const x=Array.isArray(s)&&s.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||y||e)&&x}}function RS({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:o,onPanZoomStart:i,onPanZoomEnd:a,onDraggingChange:l}){const c={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},u=e.getBoundingClientRect();let d=[[0,0],[u.width,u.height]];(typeof ResizeObserver<"u"?new ResizeObserver(M=>{const O=M[0];O&&(d=[[0,0],[O.contentRect.width,O.contentRect.height]])}):null)?.observe(e);const f=Xc().extent(()=>d).scaleExtent([t,n]).translateExtent(r),g=Se(e).call(f);m({x:s.x,y:s.y,zoom:Xt(s.zoom,t,n)},[[0,0],[u.width,u.height]],r);const p=g.on("wheel.zoom"),y=g.on("dblclick.zoom");f.wheelDelta(Eu);async function x(M,O){return g?new Promise(b=>{f?.interpolate(O?.interpolate==="linear"?vn:Zn).transform(us(g,O?.duration,O?.ease,()=>b(!0)),M)}):!1}function v({noWheelClassName:M,noPanClassName:O,onPaneContextMenu:b,userSelectionActive:w,panOnScroll:T,panOnDrag:j,panOnScrollMode:D,panOnScrollSpeed:L,preventScrolling:F,zoomOnPinch:z,zoomOnScroll:B,zoomOnDoubleClick:K,panActivationKeyPressed:H=!1,zoomActivationKeyPressed:W,lib:J,onTransformChange:X,connectionInProgress:$,paneClickDistance:q,selectionOnDrag:Q}){w&&!c.isZoomingOrPanning&&I();const te=T&&!W&&!w;f.clickDistance(Q?1/0:!Pe(q)||q<0?0:q);const G=te?SS({zoomPanValues:c,noWheelClassName:M,d3Selection:g,d3Zoom:f,panOnScrollMode:D,panOnScrollSpeed:L,zoomOnPinch:z,onPanZoomStart:i,onPanZoom:o,onPanZoomEnd:a}):IS({noWheelClassName:M,preventScrolling:F,d3ZoomHandler:p});g.on("wheel.zoom",G,{passive:!1});const ne=wS({zoomPanValues:c,onDraggingChange:l,onPanZoomStart:i});f.on("start",ne);const Z=ES({zoomPanValues:c,panOnDrag:j,onPaneContextMenu:!!b,onPanZoom:o,onTransformChange:X});f.on("zoom",Z);const U=CS({zoomPanValues:c,panOnDrag:j,panOnScroll:T,onPaneContextMenu:b,onPanZoomEnd:a,onDraggingChange:l});f.on("end",U);const V=NS({panActivationKeyPressed:H,zoomActivationKeyPressed:W,panOnDrag:j,zoomOnScroll:B,panOnScroll:T,zoomOnDoubleClick:K,zoomOnPinch:z,userSelectionActive:w,noPanClassName:O,noWheelClassName:M,lib:J,connectionInProgress:$});f.filter(V),K?g.on("dblclick.zoom",y):g.on("dblclick.zoom",null)}function I(){f.on("zoom",null)}async function m(M,O,b){const w=cs(M),T=f?.constrain()(w,O,b);return T&&await x(T),T}async function S(M,O){const b=cs(M);return await x(b,O),b}function E(M){if(g){const O=cs(M),b=g.property("__zoom");(b.k!==M.zoom||b.x!==M.x||b.y!==M.y)&&f?.transform(g,O,null,{sync:!0})}}function N(){const M=g?Wc(g.node()):{x:0,y:0,k:1};return{x:M.x,y:M.y,zoom:M.k}}async function R(M,O){return g?new Promise(b=>{f?.interpolate(O?.interpolate==="linear"?vn:Zn).scaleTo(us(g,O?.duration,O?.ease,()=>b(!0)),M)}):!1}async function A(M,O){return g?new Promise(b=>{f?.interpolate(O?.interpolate==="linear"?vn:Zn).scaleBy(us(g,O?.duration,O?.ease,()=>b(!0)),M)}):!1}function k(M){f?.scaleExtent(M)}function P(M){f?.translateExtent(M)}function _(M){const O=!Pe(M)||M<0?0:M;f?.clickDistance(O)}return{update:v,destroy:I,setViewport:S,setViewportConstrained:m,getViewport:N,scaleTo:R,scaleBy:A,setScaleExtent:k,setTranslateExtent:P,syncViewport:E,setClickDistance:_}}var Jt;(function(e){e.Line="line",e.Handle="handle"})(Jt||(Jt={}));function _S({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:o}){const i=e-t,a=n-r,l=[i>0?1:i<0?-1:0,a>0?1:a<0?-1:0];return i&&s&&(l[0]=l[0]*-1),a&&o&&(l[1]=l[1]*-1),l}function Xi(e){return{isHorizontal:e.includes("right")||e.includes("left"),isVertical:e.includes("bottom")||e.includes("top"),affectsX:e.includes("left"),affectsY:e.includes("top")}}function st(e,t){return Math.max(0,t-e)}function ot(e,t){return Math.max(0,e-t)}function Gn(e,t,n){return Math.max(0,t-e,e-n)}function Qi(e,t){return e?!t:t}function TS(e,t,n,r,s,o,i,a){let{affectsX:l,affectsY:c}=t;const{isHorizontal:u,isVertical:d}=t,f=u&&d,{xSnapped:g,ySnapped:p}=n,{minWidth:y,maxWidth:x,minHeight:v,maxHeight:I}=r,{x:m,y:S,width:E,height:N,aspectRatio:R}=e;let A=Math.floor(u?g-e.pointerX:0),k=Math.floor(d?p-e.pointerY:0);const P=E+(l?-A:A),_=N+(c?-k:k),M=-o[0]*E,O=-o[1]*N;let b=Gn(P,y,x),w=Gn(_,v,I);if(i){let D=0,L=0;l&&A<0?D=st(m+A+M,i[0][0]):!l&&A>0&&(D=ot(m+P+M,i[1][0])),c&&k<0?L=st(S+k+O,i[0][1]):!c&&k>0&&(L=ot(S+_+O,i[1][1])),b=Math.max(b,D),w=Math.max(w,L)}if(a){let D=0,L=0;l&&A>0?D=ot(m+A,a[0][0]):!l&&A<0&&(D=st(m+P,a[1][0])),c&&k>0?L=ot(S+k,a[0][1]):!c&&k<0&&(L=st(S+_,a[1][1])),b=Math.max(b,D),w=Math.max(w,L)}if(s){if(u){const D=Gn(P/R,v,I)*R;if(b=Math.max(b,D),i){let L=0;!l&&!c||l&&!c&&f?L=ot(S+O+P/R,i[1][1])*R:L=st(S+O+(l?A:-A)/R,i[0][1])*R,b=Math.max(b,L)}if(a){let L=0;!l&&!c||l&&!c&&f?L=st(S+P/R,a[1][1])*R:L=ot(S+(l?A:-A)/R,a[0][1])*R,b=Math.max(b,L)}}if(d){const D=Gn(_*R,y,x)/R;if(w=Math.max(w,D),i){let L=0;!l&&!c||c&&!l&&f?L=ot(m+_*R+M,i[1][0])/R:L=st(m+(c?k:-k)*R+M,i[0][0])/R,w=Math.max(w,L)}if(a){let L=0;!l&&!c||c&&!l&&f?L=st(m+_*R,a[1][0])/R:L=ot(m+(c?k:-k)*R,a[0][0])/R,w=Math.max(w,L)}}}k=k+(k<0?w:-w),A=A+(A<0?b:-b),s&&(f?P>_*R?k=(Qi(l,c)?-A:A)/R:A=(Qi(l,c)?-k:k)*R:u?(k=A/R,c=l):(A=k*R,l=c));const T=l?m+A:m,j=c?S+k:S;return{width:E+(l?-A:A),height:N+(c?-k:k),x:o[0]*A*(l?-1:1)+T,y:o[1]*k*(c?-1:1)+j}}var Cu={width:0,height:0,x:0,y:0},AS={...Cu,pointerX:0,pointerY:0,aspectRatio:1};function MS(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,o=e.measured.width??0,i=e.measured.height??0,a=n[0]*o,l=n[1]*i;return[[r-a,s-l],[r+o-a,s+i-l]]}function kS({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const o=Se(e);let i={controlDirection:Xi("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function a({controlPosition:c,boundaries:u,keepAspectRatio:d,resizeDirection:f,onResizeStart:g,onResize:p,onResizeEnd:y,shouldResize:x}){let v={...Cu},I={...AS};i={boundaries:u,resizeDirection:f,keepAspectRatio:d,controlDirection:Xi(c)};let m,S=null,E=[],N,R,A;const k=jc().on("start",P=>{const{nodeLookup:_,transform:M,snapGrid:O,snapToGrid:b,nodeOrigin:w,paneDomNode:T}=n();if(m=_.get(t),!m)return;S=T?.getBoundingClientRect()??null;const{xSnapped:j,ySnapped:D}=yn(P.sourceEvent,{transform:M,snapGrid:O,snapToGrid:b,containerBounds:S});v={width:m.measured.width??0,height:m.measured.height??0,x:m.position.x??0,y:m.position.y??0},I={...v,pointerX:j,pointerY:D,aspectRatio:v.width/v.height},N=void 0,R=_t(m.extent)?m.extent:void 0,m.parentId&&(m.extent==="parent"||m.expandParent)&&(N=_.get(m.parentId)),N&&m.extent==="parent"&&(R=[[0,0],[N.measured.width,N.measured.height]]),E=[],A=void 0;for(const[L,F]of _)if(F.parentId===t&&(E.push({id:L,position:{...F.position},extent:F.extent}),F.extent==="parent"||F.expandParent)){const z=MS(F,m,F.origin??w);A?A=[[Math.min(z[0][0],A[0][0]),Math.min(z[0][1],A[0][1])],[Math.max(z[1][0],A[1][0]),Math.max(z[1][1],A[1][1])]]:A=z}g?.(P,{...v})}).on("drag",P=>{const{transform:_,snapGrid:M,snapToGrid:O,nodeOrigin:b}=n(),w=yn(P.sourceEvent,{transform:_,snapGrid:M,snapToGrid:O,containerBounds:S}),T=[];if(!m)return;const{x:j,y:D,width:L,height:F}=v,z={},B=m.origin??b,{width:K,height:H,x:W,y:J}=TS(I,i.controlDirection,w,i.boundaries,i.keepAspectRatio,B,R,A),X=K!==L,$=H!==F,q=W!==j&&X,Q=J!==D&&$;if(!q&&!Q&&!X&&!$)return;const te={prevValues:{...v},startX:I.x,startY:I.y,childNodes:E.map(Z=>({...Z,position:{...Z.position}}))};if((q||Q||B[0]===1||B[1]===1)&&(z.x=q?W:v.x,z.y=Q?J:v.y,v.x=z.x,v.y=z.y,E.length>0)){const Z=W-j,U=J-D;for(const V of E)V.position={x:V.position.x-Z+B[0]*(K-L),y:V.position.y-U+B[1]*(H-F)},T.push(V)}if((X||$)&&(z.width=X&&(!i.resizeDirection||i.resizeDirection==="horizontal")?K:v.width,z.height=$&&(!i.resizeDirection||i.resizeDirection==="vertical")?H:v.height,v.width=z.width,v.height=z.height),N&&m.expandParent){const Z=B[0]*(z.width??0);z.x&&z.x<Z&&(v.x=Z,I.x=I.x-(z.x-Z));const U=B[1]*(z.height??0);z.y&&z.y<U&&(v.y=U,I.y=I.y-(z.y-U))}const G=_S({width:v.width,prevWidth:L,height:v.height,prevHeight:F,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),ne={...v,direction:G};if(x?.(P,ne)===!1){v=te.prevValues,I.x=te.startX,I.y=te.startY,E.forEach((Z,U)=>{Z.position=te.childNodes[U].position});return}p?.(P,ne),r(z,T)}).on("end",P=>{y?.(P,{...v}),s?.({...v})});o.call(k)}function l(){o.on(".drag",null)}return{update:a,destroy:l}}var OS=wr(of(),1),Ji=e=>{let t;const n=new Set,r=(u,d)=>{const f=typeof u=="function"?u(t):u;if(!Object.is(f,t)){const g=t;t=d??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(p=>p(t,g))}},s=()=>t,l={setState:r,getState:s,getInitialState:()=>c,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{n.clear()}},c=t=e(r,s,l);return l},jS=e=>e?Ji(e):Ji,{useDebugValue:PS}=C.default,{useSyncExternalStoreWithSelector:LS}=OS.default,DS=e=>e;function Nu(e,t=DS,n){const r=LS(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return PS(r),r}var Zi=(e,t)=>{const n=jS(e),r=(s,o=t)=>Nu(n,s,o);return Object.assign(r,n),r},$S=(e,t)=>e?Zi(e,t):Zi;function le(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,s]of e)if(!Object.is(s,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}var B_=wr(Bf()),$r=(0,C.createContext)(null),FS=$r.Provider,Ru=Te.error001("react");function re(e,t){const n=(0,C.useContext)($r);if(n===null)throw new Error(Ru);return Nu(n,e,t)}function oe(){const e=(0,C.useContext)($r);if(e===null)throw new Error(Ru);return(0,C.useMemo)(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}var ea={display:"none"},zS={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},_u="react-flow__node-desc",Tu="react-flow__edge-desc",HS="react-flow__aria-live",BS=e=>e.ariaLiveMessage,GS=e=>e.ariaLabelConfig;function US({rfId:e}){const t=re(BS);return(0,h.jsx)("div",{id:`${HS}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:zS,children:t})}function qS({rfId:e,disableKeyboardA11y:t}){const n=re(GS);return(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{id:`${_u}-${e}`,style:ea,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),(0,h.jsx)("div",{id:`${Tu}-${e}`,style:ea,children:n["edge.a11yDescription.default"]}),!t&&(0,h.jsx)(US,{rfId:e})]})}var Fr=(0,C.forwardRef)(({position:e="top-left",children:t,className:n,style:r,...s},o)=>{const i=`${e}`.split("-");return(0,h.jsx)("div",{className:ue(["react-flow__panel",n,...i]),style:r,ref:o,...s,children:t})});Fr.displayName="Panel";var ta="https://reactflow.dev?utm_source=attribution";function VS({proOptions:e,position:t="bottom-right"}){return(0,C.useEffect)(()=>{},[]),e?.hideAttribution?null:(0,h.jsx)(Fr,{position:t,className:"react-flow__attribution","data-message":`Please only hide this attribution when you are subscribed to React Flow Pro: ${ta}`,children:(0,h.jsx)("a",{href:ta,target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}var KS=e=>{const t=[],n=[];for(const[,r]of e.nodeLookup)r.selected&&t.push(r.internals.userNode);for(const[,r]of e.edgeLookup)r.selected&&n.push(r);return{selectedNodes:t,selectedEdges:n}},Un=e=>e.id;function YS(e,t){return le(e.selectedNodes.map(Un),t.selectedNodes.map(Un))&&le(e.selectedEdges.map(Un),t.selectedEdges.map(Un))}function WS({onSelectionChange:e}){const t=oe(),{selectedNodes:n,selectedEdges:r}=re(KS,YS);return(0,C.useEffect)(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(o=>o(s))},[n,r,e]),null}var XS=e=>!!e.onSelectionChangeHandlers;function QS({onSelectionChange:e}){const t=re(XS);return e||t?(0,h.jsx)(WS,{onSelectionChange:e}):null}var Au=[0,0],JS={x:0,y:0,zoom:1},na=["nodes","edges","defaultNodes","defaultEdges","onConnect","onConnectStart","onConnectEnd","onClickConnectStart","onClickConnectEnd","nodesDraggable","autoPanOnNodeFocus","nodesConnectable","nodesFocusable","edgesFocusable","edgesReconnectable","elevateNodesOnSelect","elevateEdgesOnSelect","minZoom","maxZoom","nodeExtent","onNodesChange","onEdgesChange","elementsSelectable","connectionMode","snapGrid","snapToGrid","translateExtent","connectOnClick","defaultEdgeOptions","fitView","fitViewOptions","onNodesDelete","onEdgesDelete","onDelete","onNodeDrag","onNodeDragStart","onNodeDragStop","onSelectionDrag","onSelectionDragStart","onSelectionDragStop","onMoveStart","onMove","onMoveEnd","noPanClassName","nodeOrigin","autoPanOnConnect","autoPanOnNodeDrag","onError","connectionRadius","isValidConnection","selectNodesOnDrag","nodeDragThreshold","connectionDragThreshold","onBeforeDelete","debug","autoPanSpeed","ariaLabelConfig","zIndexMode","rfId"],ZS=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges}),ra={translateExtent:Cn,nodeOrigin:Au,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function eI(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:o,setNodeExtent:i,reset:a,setDefaultNodesAndEdges:l}=re(ZS,le),c=oe();(0,C.useEffect)(()=>(l(e.defaultNodes,e.defaultEdges),()=>{u.current=ra,a()}),[]);const u=(0,C.useRef)(ra);return(0,C.useEffect)(()=>{for(const d of na){const f=e[d];f!==u.current[d]&&(typeof e[d]>"u"||(d==="nodes"?t(f):d==="edges"?n(f):d==="minZoom"?r(f):d==="maxZoom"?s(f):d==="translateExtent"?o(f):d==="nodeExtent"?i(f):d==="ariaLabelConfig"?c.setState({ariaLabelConfig:qx(f)}):d==="fitView"?c.setState({fitViewQueued:f}):d==="fitViewOptions"?c.setState({fitViewOptions:f}):c.setState({[d]:f})))}u.current=e},na.map(d=>e[d])),null}function sa(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function tI(e){const[t,n]=(0,C.useState)(e==="system"?null:e);return(0,C.useEffect)(()=>{if(e!=="system"){n(e);return}const r=sa(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:sa()?.matches?"dark":"light"}var oa=typeof document<"u"?document:null;function Tn(e=null,t={target:oa,actInsideInputWithModifier:!0}){const[n,r]=(0,C.useState)(!1),s=(0,C.useRef)(!1),o=(0,C.useRef)(new Set([])),[i,a]=(0,C.useMemo)(()=>{if(e!==null){const l=(Array.isArray(e)?e:[e]).filter(c=>typeof c=="string").map(c=>c.replace(/\+/g,`
|
|
3
|
+
`).replace(`
|
|
4
|
+
|
|
5
|
+
`,`
|
|
6
|
+
+`).split(`
|
|
7
|
+
`));return[l,l.reduce((c,u)=>c.concat(...u),[])]}return[[],[]]},[e]);return(0,C.useEffect)(()=>{const l=t?.target??oa,c=t?.actInsideInputWithModifier??!0;if(e!==null){const u=g=>{if(s.current=g.ctrlKey||g.metaKey||g.shiftKey||g.altKey,(!s.current||s.current&&!c)&&cu(g))return!1;const p=aa(g.code,a);if(o.current.add(g[p]),ia(i,o.current,!1)){const y=g.composedPath?.()?.[0]||g.target,x=y?.nodeName==="BUTTON"||y?.nodeName==="A";t.preventDefault!==!1&&(s.current||!x)&&g.preventDefault(),r(!0)}},d=g=>{const p=aa(g.code,a);ia(i,o.current,!0)?(r(!1),o.current.clear()):o.current.delete(g[p]),g.key==="Meta"&&o.current.clear(),s.current=!1},f=()=>{o.current.clear(),r(!1)};return l?.addEventListener("keydown",u),l?.addEventListener("keyup",d),window.addEventListener("blur",f),window.addEventListener("contextmenu",f),()=>{l?.removeEventListener("keydown",u),l?.removeEventListener("keyup",d),window.removeEventListener("blur",f),window.removeEventListener("contextmenu",f)}}},[e,r]),n}function ia(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(s=>t.has(s)))}function aa(e,t){return t.includes(e)?"code":"key"}var nI=()=>{const e=oe();return(0,C.useMemo)(()=>({zoomIn:async t=>{const{panZoom:n}=e.getState();return n?n.scaleBy(1.2,t):!1},zoomOut:async t=>{const{panZoom:n}=e.getState();return n?n.scaleBy(1/1.2,t):!1},zoomTo:async(t,n)=>{const{panZoom:r}=e.getState();return r?r.scaleTo(t,n):!1},getZoom:()=>e.getState().transform[2],setViewport:async(t,n)=>{const{transform:[r,s,o],panZoom:i}=e.getState();return i?(await i.setViewport({x:t.x??r,y:t.y??s,zoom:t.zoom??o},n),!0):!1},getViewport:()=>{const[t,n,r]=e.getState().transform;return{x:t,y:n,zoom:r}},setCenter:async(t,n,r)=>e.getState().setCenter(t,n,r),fitBounds:async(t,n)=>{const{width:r,height:s,minZoom:o,maxZoom:i,panZoom:a}=e.getState(),l=Io(t,r,s,o,i,n?.padding??.1);return a?(await a.setViewport(l,{duration:n?.duration,ease:n?.ease,interpolate:n?.interpolate}),!0):!1},screenToFlowPosition:(t,n={})=>{const{transform:r,snapGrid:s,snapToGrid:o,domNode:i}=e.getState();if(!i)return t;const{x:a,y:l}=i.getBoundingClientRect(),c={x:t.x-a,y:t.y-l},u=n.snapGrid??s,d=n.snapToGrid??o;return Pn(c,r,d,u)},flowToScreenPosition:t=>{const{transform:n,domNode:r}=e.getState();if(!r)return t;const{x:s,y:o}=r.getBoundingClientRect(),i=Qt(t,n);return{x:i.x+s,y:i.y+o}}}),[])};function Mu(e,t){const n=[],r=new Map,s=[];for(const o of e)if(o.type==="add"){s.push(o);continue}else if(o.type==="remove"||o.type==="replace")r.set(o.id,[o]);else{const i=r.get(o.id);i?i.push(o):r.set(o.id,[o])}for(const o of t){const i=r.get(o.id);if(!i){n.push(o);continue}if(i[0].type==="remove")continue;if(i[0].type==="replace"){n.push({...i[0].item});continue}const a={...o};for(const l of i)rI(l,a);n.push(a)}return s.length&&s.forEach(o=>{o.index!==void 0?n.splice(o.index,0,{...o.item}):n.push({...o.item})}),n}function rI(e,t){switch(e.type){case"select":t.selected=e.selected;break;case"position":typeof e.position<"u"&&(t.position=e.position),typeof e.dragging<"u"&&(t.dragging=e.dragging);break;case"dimensions":typeof e.dimensions<"u"&&(t.measured={...e.dimensions},e.setAttributes&&((e.setAttributes===!0||e.setAttributes==="width")&&(t.width=e.dimensions.width),(e.setAttributes===!0||e.setAttributes==="height")&&(t.height=e.dimensions.height))),typeof e.resizing=="boolean"&&(t.resizing=e.resizing)}}function ku(e,t){return Mu(e,t)}function sI(e,t){return Mu(e,t)}function vt(e,t){return{id:e,type:"select",selected:t}}function Pt(e,t=new Set,n=!1){const r=[];for(const[s,o]of e){const i=t.has(s);!(o.selected===void 0&&!i)&&o.selected!==i&&(n&&(o.selected=i),r.push(vt(o.id,i)))}return r}function la({items:e=[],lookup:t}){const n=[],r=new Map(e.map(s=>[s.id,s]));for(const[s,o]of e.entries()){const i=t.get(o.id),a=i?.internals?.userNode??i;a!==void 0&&a!==o&&n.push({id:o.id,item:o,type:"replace"}),a===void 0&&n.push({item:o,type:"add",index:s})}for(const[s]of t)r.get(s)===void 0&&n.push({id:s,type:"remove"});return n}function ca(e){return{id:e.id,type:"remove"}}var oI=ou("React Flow","https://reactflow.dev/");function iI(e,t,n={}){return Qx(e,t,{...n,onError:n.onError??oI})}var ua=e=>Lx(e),aI=e=>eu(e);function Ou(e){return(0,C.forwardRef)(e)}var ju=typeof window<"u"?C.useLayoutEffect:C.useEffect;function da(e){const[t,n]=(0,C.useState)(BigInt(0)),[r]=(0,C.useState)(()=>lI(()=>n(s=>s+BigInt(1))));return ju(()=>{const s=r.get();s.length&&(e(s),r.reset())},[t]),r}function lI(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}var Pu=(0,C.createContext)(null);function cI({children:e}){const t=oe(),n=da((0,C.useCallback)(o=>{const{nodes:i=[],setNodes:a,hasDefaultNodes:l,onNodesChange:c,nodeLookup:u,fitViewQueued:d,onNodesChangeMiddlewareMap:f}=t.getState();let g=i;for(const y of o)g=typeof y=="function"?y(g):y;let p=la({items:g,lookup:u});for(const y of f.values())p=y(p);l&&a(g),p.length>0?c?.(p):d&&window.requestAnimationFrame(()=>{const{fitViewQueued:y,nodes:x,setNodes:v}=t.getState();y&&v(x)})},[])),r=da((0,C.useCallback)(o=>{const{edges:i=[],setEdges:a,hasDefaultEdges:l,onEdgesChange:c,edgeLookup:u}=t.getState();let d=i;for(const f of o)d=typeof f=="function"?f(d):f;l?a(d):c&&c(la({items:d,lookup:u}))},[])),s=(0,C.useMemo)(()=>({nodeQueue:n,edgeQueue:r}),[]);return(0,h.jsx)(Pu.Provider,{value:s,children:e})}function uI(){const e=(0,C.useContext)(Pu);if(!e)throw new Error("useBatchContext must be used within a BatchProvider");return e}var dI=e=>!!e.panZoom;function zr(){const e=nI(),t=oe(),n=uI(),r=re(dI),s=(0,C.useMemo)(()=>{const o=d=>t.getState().nodeLookup.get(d),i=d=>{n.nodeQueue.push(d)},a=d=>{n.edgeQueue.push(d)},l=d=>{const{nodeLookup:f,nodeOrigin:g}=t.getState(),p=ua(d)?d:f.get(d.id),y=p.parentId?iu(p.position,p.measured,p.parentId,f,g):p.position,x={...p,position:y,width:p.measured?.width??p.width,height:p.measured?.height??p.height};return Rn(x)},c=(d,f,g={replace:!1})=>{i(p=>p.map(y=>{if(y.id===d){const x=typeof f=="function"?f(y):f;return g.replace&&ua(x)?x:{...y,...x}}return y}))},u=(d,f,g={replace:!1})=>{a(p=>p.map(y=>{if(y.id===d){const x=typeof f=="function"?f(y):f;return g.replace&&aI(x)?x:{...y,...x}}return y}))};return{getNodes:()=>t.getState().nodes.map(d=>({...d})),getNode:d=>o(d)?.internals.userNode,getInternalNode:o,getEdges:()=>{const{edges:d=[]}=t.getState();return d.map(f=>({...f}))},getEdge:d=>t.getState().edgeLookup.get(d),setNodes:i,setEdges:a,addNodes:d=>{const f=Array.isArray(d)?d:[d];n.nodeQueue.push(g=>[...g,...f])},addEdges:d=>{const f=Array.isArray(d)?d:[d];n.edgeQueue.push(g=>[...g,...f])},toObject:()=>{const{nodes:d=[],edges:f=[],transform:g}=t.getState(),[p,y,x]=g;return{nodes:d.map(v=>({...v})),edges:f.map(v=>({...v})),viewport:{x:p,y,zoom:x}}},deleteElements:async({nodes:d=[],edges:f=[]})=>{const{nodes:g,edges:p,onNodesDelete:y,onEdgesDelete:x,triggerNodeChanges:v,triggerEdgeChanges:I,onDelete:m,onBeforeDelete:S}=t.getState(),{nodes:E,edges:N}=await Hx({nodesToRemove:d,edgesToRemove:f,nodes:g,edges:p,onBeforeDelete:S}),R=N.length>0,A=E.length>0;if(R){const k=N.map(ca);x?.(N),I(k)}if(A){const k=E.map(ca);y?.(E),v(k)}return(A||R)&&m?.({nodes:E,edges:N}),{deletedNodes:E,deletedEdges:N}},getIntersectingNodes:(d,f=!0,g)=>{const p=Fi(d),y=p?d:l(d),x=g!==void 0;return y?(g||t.getState().nodes).filter(v=>{const I=t.getState().nodeLookup.get(v.id);if(I&&!p&&(v.id===d.id||!I.internals.positionAbsolute))return!1;const m=Rn(x?v:I),S=mr(m,y);return f&&S>0||S>=m.width*m.height||S>=y.width*y.height}):[]},isNodeIntersecting:(d,f,g=!0)=>{const p=Fi(d)?d:l(d);if(!p)return!1;const y=mr(p,f);return g&&y>0||y>=f.width*f.height||y>=p.width*p.height},updateNode:c,updateNodeData:(d,f,g={replace:!1})=>{c(d,p=>{const y=typeof f=="function"?f(p):f;return g.replace?{...p,data:y}:{...p,data:{...p.data,...y}}},g)},updateEdge:u,updateEdgeData:(d,f,g={replace:!1})=>{u(d,p=>{const y=typeof f=="function"?f(p):f;return g.replace?{...p,data:y}:{...p,data:{...p.data,...y}}},g)},getNodesBounds:d=>{const{nodeLookup:f,nodeOrigin:g}=t.getState();return Dx(d,{nodeLookup:f,nodeOrigin:g})},getHandleConnections:({type:d,id:f,nodeId:g})=>Array.from(t.getState().connectionLookup.get(`${g}-${d}${f?`-${f}`:""}`)?.values()??[]),getNodeConnections:({type:d,handleId:f,nodeId:g})=>Array.from(t.getState().connectionLookup.get(`${g}${d?f?`-${d}-${f}`:`-${d}`:""}`)?.values()??[]),fitView:async d=>{const f=t.getState().fitViewResolver??Ux();return t.setState({fitViewQueued:!0,fitViewOptions:d,fitViewResolver:f}),n.nodeQueue.push(g=>[...g]),f.promise}}},[]);return(0,C.useMemo)(()=>({...s,...e,viewportInitialized:r}),[r])}var ha=e=>e.selected,hI=typeof window<"u"?window:void 0;function fI({deleteKeyCode:e,multiSelectionKeyCode:t}){const n=oe(),{deleteElements:r}=zr(),s=Tn(e,{actInsideInputWithModifier:!1}),o=Tn(t,{target:hI});(0,C.useEffect)(()=>{if(s){const{edges:i,nodes:a}=n.getState();r({nodes:a.filter(ha),edges:i.filter(ha)}),n.setState({nodesSelectionActive:!1})}},[s]),(0,C.useEffect)(()=>{n.setState({multiSelectionActive:o})},[o])}function pI(e){const t=oe();(0,C.useEffect)(()=>{const n=()=>{if(!e.current||!(e.current.checkVisibility?.()??!0))return!1;const r=Eo(e.current);(r.height===0||r.width===0)&&t.getState().onError?.("004",Te.error004()),t.setState({width:r.width||500,height:r.height||500})};if(e.current){n(),window.addEventListener("resize",n);const r=new ResizeObserver(()=>n());return r.observe(e.current),()=>{window.removeEventListener("resize",n),r&&e.current&&r.unobserve(e.current)}}},[])}var Hr={position:"absolute",width:"100%",height:"100%",top:0,left:0},gI=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function mI({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:r=!1,panActivationKeyPressed:s,panOnScrollSpeed:o=.5,panOnScrollMode:i=wt.Free,zoomOnDoubleClick:a=!0,panOnDrag:l=!0,defaultViewport:c,translateExtent:u,minZoom:d,maxZoom:f,zoomActivationKeyCode:g,preventScrolling:p=!0,children:y,noWheelClassName:x,noPanClassName:v,onViewportChange:I,isControlledViewport:m,paneClickDistance:S,selectionOnDrag:E}){const N=oe(),R=(0,C.useRef)(null),{userSelectionActive:A,lib:k,connectionInProgress:P}=re(gI,le),_=Tn(g),M=(0,C.useRef)();pI(R);const O=(0,C.useCallback)(b=>{I?.({x:b[0],y:b[1],zoom:b[2]}),m||N.setState({transform:b})},[I,m]);return(0,C.useEffect)(()=>{if(R.current){M.current=RS({domNode:R.current,minZoom:d,maxZoom:f,translateExtent:u,viewport:c,onDraggingChange:j=>N.setState(D=>D.paneDragging===j?D:{paneDragging:j}),onPanZoomStart:(j,D)=>{const{onViewportChangeStart:L,onMoveStart:F}=N.getState();F?.(j,D),L?.(D)},onPanZoom:(j,D)=>{const{onViewportChange:L,onMove:F}=N.getState();F?.(j,D),L?.(D)},onPanZoomEnd:(j,D)=>{const{onViewportChangeEnd:L,onMoveEnd:F}=N.getState();F?.(j,D),L?.(D)}});const{x:b,y:w,zoom:T}=M.current.getViewport();return N.setState({panZoom:M.current,transform:[b,w,T],domNode:R.current.closest(".react-flow")}),()=>{M.current?.destroy()}}},[]),(0,C.useEffect)(()=>{M.current?.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:r,panActivationKeyPressed:s,panOnScrollSpeed:o,panOnScrollMode:i,zoomOnDoubleClick:a,panOnDrag:l,zoomActivationKeyPressed:_,preventScrolling:p,noPanClassName:v,userSelectionActive:A,noWheelClassName:x,lib:k,onTransformChange:O,connectionInProgress:P,selectionOnDrag:E,paneClickDistance:S})},[e,t,n,r,s,o,i,a,l,_,p,v,A,x,k,O,P,E,S]),(0,h.jsx)("div",{className:"react-flow__renderer",ref:R,style:Hr,children:y})}var vI=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function yI(){const{userSelectionActive:e,userSelectionRect:t}=re(vI,le);return e&&t?(0,h.jsx)("div",{className:"react-flow__selection react-flow__container",style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}var ds=(e,t)=>n=>{n.target===t.current&&e?.(n)},bI=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging,panBy:e.panBy,autoPanSpeed:e.autoPanSpeed});function xI({isSelecting:e,selectionKeyPressed:t,selectionMode:n=Nn.Full,panOnDrag:r,autoPanOnSelection:s,paneClickDistance:o,selectionOnDrag:i,onSelectionStart:a,onSelectionEnd:l,onPaneClick:c,onPaneContextMenu:u,onPaneScroll:d,onPaneMouseEnter:f,onPaneMouseMove:g,onPaneMouseLeave:p,children:y}){const x=(0,C.useRef)(0),v=oe(),{userSelectionActive:I,elementsSelectable:m,dragging:S,panBy:E,autoPanSpeed:N}=re(bI,le),R=m&&(e||I),A=(0,C.useRef)(null),k=(0,C.useRef)(),P=(0,C.useRef)(new Set),_=(0,C.useRef)(new Set),M=(0,C.useRef)(!1),O=(0,C.useRef)(!1),b=(0,C.useRef)({x:0,y:0}),w=(0,C.useRef)(!1),T=$=>{if(O.current||M.current||v.getState().connection.inProgress){O.current=!1,M.current=!1;return}c?.($),v.getState().resetSelectedElements(),v.setState({nodesSelectionActive:!1})},j=$=>{if(Array.isArray(r)&&r?.includes(2)){$.preventDefault();return}u?.($)},D=d?$=>d($):void 0,L=$=>{O.current&&($.stopPropagation(),O.current=!1)},F=$=>{if($.pointerType==="touch"&&r!==!1&&!t)return;const{domNode:q,transform:Q}=v.getState();if(k.current=q?.getBoundingClientRect(),!k.current)return;const te=$.target===A.current;if(!te&&$.target.closest(".nokey")||!e||!(i&&te||t)||$.button!==0||!$.isPrimary)return;$.target?.setPointerCapture?.($.pointerId),O.current=!1;const{x:G,y:ne}=Le($.nativeEvent,k.current),Z=Pn({x:G,y:ne},Q);v.setState({userSelectionRect:{width:0,height:0,startX:Z.x,startY:Z.y,x:G,y:ne}}),te||($.stopPropagation(),$.preventDefault())};function z($,q){const{userSelectionRect:Q}=v.getState();if(!Q)return;const{transform:te,nodeLookup:G,edgeLookup:ne,connectionLookup:Z,triggerNodeChanges:U,triggerEdgeChanges:V,defaultEdgeOptions:pe}=v.getState(),ge={x:Q.startX,y:Q.startY},{x:ve,y:Me}=Qt(ge,te),ie={startX:ge.x,startY:ge.y,x:$<ve?$:ve,y:q<Me?q:Me,width:Math.abs($-ve),height:Math.abs(q-Me)},rt=P.current,ee=_.current;P.current=new Set(xo(G,ie,te,n===Nn.Partial,!0).map(ke=>ke.id)),_.current=new Set;const ce=pe?.selectable??!0;for(const ke of P.current){const Ye=Z.get(ke);if(Ye)for(const{edgeId:We}of Ye.values()){const pt=ne.get(We);pt&&(pt.selectable??ce)&&_.current.add(We)}}zi(rt,P.current)||U(Pt(G,P.current,!0)),zi(ee,_.current)||V(Pt(ne,_.current)),v.setState({userSelectionRect:ie,userSelectionActive:!0,nodesSelectionActive:!1})}function B(){if(!s||!k.current)return;const[$,q]=So(b.current,k.current,N);E({x:$,y:q}).then(Q=>{if(!O.current||!Q){x.current=requestAnimationFrame(B);return}const{x:te,y:G}=b.current;z(te,G),x.current=requestAnimationFrame(B)})}const K=()=>{cancelAnimationFrame(x.current),x.current=0,w.current=!1};(0,C.useEffect)(()=>()=>K(),[]);const H=$=>{const{userSelectionRect:q,transform:Q,resetSelectedElements:te}=v.getState();if(!k.current||!q)return;const{x:G,y:ne}=Le($.nativeEvent,k.current);b.current={x:G,y:ne};const Z=Qt({x:q.startX,y:q.startY},Q);if(!O.current){const U=t?0:o;if(Math.hypot(G-Z.x,ne-Z.y)<=U)return;te(),a?.($)}O.current=!0,w.current||(B(),w.current=!0),z(G,ne)},W=$=>{if(!R){$.target===A.current&&v.getState().connection.inProgress&&(M.current=!0);return}$.button===0&&($.target?.releasePointerCapture?.($.pointerId),!I&&$.target===A.current&&v.getState().userSelectionRect&&T?.($),v.setState({userSelectionActive:!1,userSelectionRect:null}),O.current&&(l?.($),v.setState({nodesSelectionActive:P.current.size>0})),K())},J=$=>{$.target?.releasePointerCapture?.($.pointerId),K()},X=r===!0||Array.isArray(r)&&r.includes(0);return(0,h.jsxs)("div",{className:ue(["react-flow__pane",{draggable:X,dragging:S,selection:e}]),onClick:R?void 0:ds(T,A),onContextMenu:ds(j,A),onWheel:ds(D,A),onPointerEnter:R?void 0:f,onPointerMove:R?H:g,onPointerUp:W,onPointerCancel:R?J:void 0,onPointerDownCapture:R?F:void 0,onClickCapture:R?L:void 0,onPointerLeave:p,ref:A,style:Hr,children:[y,(0,h.jsx)(yI,{})]})}function $s({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:s,unselectNodesAndEdges:o,multiSelectionActive:i,nodeLookup:a,onError:l}=t.getState(),c=a.get(e);if(!c){l?.("012",Te.error012(e));return}t.setState({nodesSelectionActive:!1}),c.selected?(n||c.selected&&i)&&(o({nodes:[c],edges:[]}),requestAnimationFrame(()=>r?.current?.blur())):s([e])}function Lu({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:s,isSelectable:o,nodeClickDistance:i}){const a=oe(),[l,c]=(0,C.useState)(!1),u=(0,C.useRef)();return(0,C.useEffect)(()=>{if(!t)return u.current=fS({getStoreItems:()=>a.getState(),onNodeMouseDown:d=>{$s({id:d,store:a,nodeRef:e})},onDragStart:()=>{c(!0)},onDragStop:()=>{c(!1)}}),()=>{u.current?.destroy(),u.current=void 0}},[t,a,e]),(0,C.useEffect)(()=>{t||!e.current||!u.current||u.current.update({noDragClassName:n,handleSelector:r,domNode:e.current,isSelectable:o,nodeId:s,nodeClickDistance:i})},[n,r,t,o,e,s,i]),l}var SI=e=>t=>t.selected&&(t.draggable||e&&typeof t.draggable>"u");function Du(){const e=oe();return(0,C.useCallback)(t=>{const{nodeExtent:n,snapToGrid:r,snapGrid:s,nodesDraggable:o,onError:i,updateNodePositions:a,nodeLookup:l,nodeOrigin:c}=e.getState(),u=new Map,d=SI(o),f=r?s[0]:5,g=r?s[1]:5,p=t.direction.x*f*t.factor,y=t.direction.y*g*t.factor;for(const[,x]of l){if(!d(x))continue;let v={x:x.internals.positionAbsolute.x+p,y:x.internals.positionAbsolute.y+y};r&&(v=jn(v,s));const{position:I,positionAbsolute:m}=tu({nodeId:x.id,nextPosition:v,nodeLookup:l,nodeExtent:n,nodeOrigin:c,onError:i});x.position=I,x.internals.positionAbsolute=m,u.set(x.id,x)}a(u)},[])}var Ao=(0,C.createContext)(null),II=Ao.Provider;Ao.Consumer;var $u=()=>(0,C.useContext)(Ao),wI=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),Fu=(0,C.createContext)(null);function EI({children:e}){const t=re(wI,le);return(0,h.jsx)(Fu.Provider,{value:t,children:e})}function CI(){const e=(0,C.useContext)(Fu);if(!e)throw new Error("useHandleConfig must be used within a HandleConfigProvider");return e}var NI={connectingFrom:!1,connectingTo:!1,clickConnecting:!1,isPossibleEndHandle:!0,connectionInProcess:!1,clickConnectionInProcess:!1,valid:!1},RI=(e,t,n)=>r=>{const{connectionClickStartHandle:s,connectionMode:o,connection:i}=r,{fromHandle:a,toHandle:l,isValid:c}=i;if(!a&&!s)return NI;const u=l?.nodeId===e&&l?.id===t&&l?.type===n;return{connectingFrom:a?.nodeId===e&&a?.id===t&&a?.type===n,connectingTo:u,clickConnecting:s?.nodeId===e&&s?.id===t&&s?.type===n,isPossibleEndHandle:o===Wt.Strict?a?.type!==n:e!==a?.nodeId||t!==a?.id,connectionInProcess:!!a,clickConnectionInProcess:!!s,valid:u&&c}};function _I({type:e="source",position:t=Y.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:s=!0,isConnectableEnd:o=!0,id:i,onConnect:a,children:l,className:c,onMouseDown:u,onTouchStart:d,...f},g){const p=i||null,y=e==="target",x=oe(),v=$u(),{connectOnClick:I,noPanClassName:m,rfId:S}=CI(),{connectingFrom:E,connectingTo:N,clickConnecting:R,isPossibleEndHandle:A,connectionInProcess:k,clickConnectionInProcess:P,valid:_}=re(RI(v,p,e),le);v||x.getState().onError?.("010",Te.error010());const M=w=>{const{defaultEdgeOptions:T,onConnect:j,hasDefaultEdges:D}=x.getState(),L={...T,...w};if(D){const{edges:F,setEdges:z,onError:B}=x.getState();z(iI(L,F,{onError:B}))}j?.(L),a?.(L)},O=w=>{if(!v)return;const T=uu(w.nativeEvent);if(s&&(T&&w.button===0||!T)){const j=x.getState();Ds.onPointerDown(w.nativeEvent,{handleDomNode:w.currentTarget,autoPanOnConnect:j.autoPanOnConnect,connectionMode:j.connectionMode,connectionRadius:j.connectionRadius,domNode:j.domNode,nodeLookup:j.nodeLookup,lib:j.lib,isTarget:y,handleId:p,nodeId:v,flowId:j.rfId,panBy:j.panBy,cancelConnection:j.cancelConnection,onConnectStart:j.onConnectStart,onConnectEnd:(...D)=>x.getState().onConnectEnd?.(...D),updateConnection:j.updateConnection,onConnect:M,isValidConnection:n||((...D)=>x.getState().isValidConnection?.(...D)??!0),getTransform:()=>x.getState().transform,getFromHandle:()=>x.getState().connection.fromHandle,autoPanSpeed:j.autoPanSpeed,dragThreshold:j.connectionDragThreshold})}T?u?.(w):d?.(w)},b=w=>{const{onClickConnectStart:T,onClickConnectEnd:j,connectionClickStartHandle:D,connectionMode:L,isValidConnection:F,lib:z,rfId:B,nodeLookup:K,connection:H}=x.getState();if(!v||!D&&!s)return;if(!D){T?.(w.nativeEvent,{nodeId:v,handleId:p,handleType:e}),x.setState({connectionClickStartHandle:{nodeId:v,type:e,id:p}});return}const W=lu(w.target),J=n||F,{connection:X,isValid:$}=Ds.isValid(w.nativeEvent,{handle:{nodeId:v,id:p,type:e},connectionMode:L,fromNodeId:D.nodeId,fromHandleId:D.id||null,fromType:D.type,isValidConnection:J,flowId:B,doc:W,lib:z,nodeLookup:K});$&&X&&M(X);const q=structuredClone(H);delete q.inProgress,q.toPosition=q.toHandle?q.toHandle.position:null,j?.(w,q),x.setState({connectionClickStartHandle:null})};return(0,h.jsx)("div",{"data-handleid":p,"data-nodeid":v,"data-handlepos":t,"data-id":`${S}-${v}-${p}-${e}`,className:ue(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",m,c,{source:!y,target:y,connectable:r,connectablestart:s,connectableend:o,clickconnecting:R,connectingfrom:E,connectingto:N,valid:_,connectionindicator:r&&(!k||A)&&(k||P?o:s)}]),onMouseDown:O,onTouchStart:O,onClick:I?b:void 0,ref:g,...f,children:l})}var Zt=(0,C.memo)(Ou(_I));function TI({data:e,isConnectable:t,sourcePosition:n=Y.Bottom}){return(0,h.jsxs)(h.Fragment,{children:[e?.label,(0,h.jsx)(Zt,{type:"source",position:n,isConnectable:t})]})}function AI({data:e,isConnectable:t,targetPosition:n=Y.Top,sourcePosition:r=Y.Bottom}){return(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(Zt,{type:"target",position:n,isConnectable:t}),e?.label,(0,h.jsx)(Zt,{type:"source",position:r,isConnectable:t})]})}function MI(){return null}function kI({data:e,isConnectable:t,targetPosition:n=Y.Top}){return(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(Zt,{type:"target",position:n,isConnectable:t}),e?.label]})}var vr={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},fa={input:TI,default:AI,output:kI,group:MI};function OI(e){return e.internals.handleBounds===void 0?{width:e.width??e.initialWidth??e.style?.width,height:e.height??e.initialHeight??e.style?.height}:{width:e.width??e.style?.width,height:e.height??e.style?.height}}var jI=e=>{const{width:t,height:n,x:r,y:s}=On(e.nodeLookup,{filter:o=>!!o.selected});return{width:Pe(t)?t:null,height:Pe(n)?n:null,userSelectionActive:e.userSelectionActive,transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]}) translate(${r}px,${s}px)`}};function PI({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=oe(),{width:s,height:o,transformString:i,userSelectionActive:a}=re(jI,le),l=Du(),c=(0,C.useRef)(null);(0,C.useEffect)(()=>{n||c.current?.focus({preventScroll:!0})},[n]);const u=!a&&s!==null&&o!==null;if(Lu({nodeRef:c,disabled:!u}),!u)return null;const d=e?g=>{e(g,r.getState().nodes.filter(p=>p.selected))}:void 0,f=g=>{Object.prototype.hasOwnProperty.call(vr,g.key)&&(g.preventDefault(),l({direction:vr[g.key],factor:g.shiftKey?4:1}))};return(0,h.jsx)("div",{className:ue(["react-flow__nodesselection","react-flow__container",t]),style:{transform:i},children:(0,h.jsx)("div",{ref:c,className:"react-flow__nodesselection-rect",onContextMenu:d,tabIndex:n?void 0:-1,onKeyDown:n?void 0:f,style:{width:s,height:o}})})}var pa=typeof window<"u"?window:void 0,LI=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function zu({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:s,onPaneContextMenu:o,onPaneScroll:i,paneClickDistance:a,deleteKeyCode:l,selectionKeyCode:c,selectionOnDrag:u,selectionMode:d,onSelectionStart:f,onSelectionEnd:g,multiSelectionKeyCode:p,panActivationKeyCode:y,zoomActivationKeyCode:x,elementsSelectable:v,zoomOnScroll:I,zoomOnPinch:m,panOnScroll:S,panOnScrollSpeed:E,panOnScrollMode:N,zoomOnDoubleClick:R,panOnDrag:A,autoPanOnSelection:k,defaultViewport:P,translateExtent:_,minZoom:M,maxZoom:O,preventScrolling:b,onSelectionContextMenu:w,noWheelClassName:T,noPanClassName:j,disableKeyboardA11y:D,onViewportChange:L,isControlledViewport:F}){const{nodesSelectionActive:z,userSelectionActive:B}=re(LI,le),K=Tn(c,{target:pa}),H=Tn(y,{target:pa}),W=H||A,J=H||S,X=u&&W!==!0,$=K||B||X;return fI({deleteKeyCode:l,multiSelectionKeyCode:p}),(0,h.jsx)(mI,{onPaneContextMenu:o,elementsSelectable:v,zoomOnScroll:I,zoomOnPinch:m,panOnScroll:J,panActivationKeyPressed:H,panOnScrollSpeed:E,panOnScrollMode:N,zoomOnDoubleClick:R,panOnDrag:!K&&W,defaultViewport:P,translateExtent:_,minZoom:M,maxZoom:O,zoomActivationKeyCode:x,preventScrolling:b,noWheelClassName:T,noPanClassName:j,onViewportChange:L,isControlledViewport:F,paneClickDistance:a,selectionOnDrag:X,children:(0,h.jsxs)(xI,{onSelectionStart:f,onSelectionEnd:g,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:s,onPaneContextMenu:o,onPaneScroll:i,panOnDrag:W,autoPanOnSelection:k,isSelecting:!!$,selectionMode:d,selectionKeyPressed:K,paneClickDistance:a,selectionOnDrag:X,children:[e,z&&(0,h.jsx)(PI,{onSelectionContextMenu:w,noPanClassName:j,disableKeyboardA11y:D})]})})}zu.displayName="FlowRenderer";var DI=(0,C.memo)(zu),$I=e=>t=>e?xo(t.nodeLookup,{x:0,y:0,width:t.width,height:t.height},t.transform,!0).map(n=>n.id):Array.from(t.nodeLookup.keys());function FI(e){return re((0,C.useCallback)($I(e),[e]),le)}var zI=e=>e.updateNodeInternals;function HI(){const e=re(zI),[t]=(0,C.useState)(()=>typeof ResizeObserver>"u"?null:new ResizeObserver(n=>{const r=new Map;n.forEach(s=>{const o=s.target.getAttribute("data-id");r.set(o,{id:o,nodeElement:s.target,force:!0})}),e(r)}));return(0,C.useEffect)(()=>()=>{t?.disconnect()},[t]),t}function BI({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){const s=oe(),o=(0,C.useRef)(null),i=(0,C.useRef)(null),a=(0,C.useRef)(e.sourcePosition),l=(0,C.useRef)(e.targetPosition),c=(0,C.useRef)(t),u=n&&!!e.internals.handleBounds;return(0,C.useEffect)(()=>{o.current&&!e.hidden&&(!u||i.current!==o.current)&&(i.current&&r?.unobserve(i.current),r?.observe(o.current),i.current=o.current)},[u,e.hidden]),(0,C.useEffect)(()=>()=>{i.current&&(r?.unobserve(i.current),i.current=null)},[]),(0,C.useEffect)(()=>{if(o.current){const d=c.current!==t,f=a.current!==e.sourcePosition,g=l.current!==e.targetPosition;(d||f||g)&&(c.current=t,a.current=e.sourcePosition,l.current=e.targetPosition,s.getState().updateNodeInternals(new Map([[e.id,{id:e.id,nodeElement:o.current,force:!0}]])))}},[e.id,t,e.sourcePosition,e.targetPosition]),o}function GI({id:e,onClick:t,onMouseEnter:n,onMouseMove:r,onMouseLeave:s,onContextMenu:o,onDoubleClick:i,nodesDraggable:a,elementsSelectable:l,nodesConnectable:c,nodesFocusable:u,resizeObserver:d,noDragClassName:f,noPanClassName:g,disableKeyboardA11y:p,rfId:y,nodeTypes:x,nodeClickDistance:v,onError:I}){const{node:m,internals:S,isParent:E}=re($=>{const q=$.nodeLookup.get(e),Q=$.parentLookup.has(e);return{node:q,internals:q.internals,isParent:Q}},le);let N=m.type||"default",R=x?.[N]||fa[N];R===void 0&&(I?.("003",Te.error003(N)),N="default",R=x?.default||fa.default);const A=!!(m.draggable||a&&typeof m.draggable>"u"),k=!!(m.selectable||l&&typeof m.selectable>"u"),P=!!(m.connectable||c&&typeof m.connectable>"u"),_=!!(m.focusable||u&&typeof m.focusable>"u"),M=oe(),O=wo(m),b=BI({node:m,nodeType:N,hasDimensions:O,resizeObserver:d}),w=Lu({nodeRef:b,disabled:m.hidden||!A,noDragClassName:f,handleSelector:m.dragHandle,nodeId:e,isSelectable:k,nodeClickDistance:v}),T=Du();if(m.hidden)return null;const j=Fe(m),D=OI(m),L=k||A||t||n||r||s,F=n?$=>n($,{...S.userNode}):void 0,z=r?$=>r($,{...S.userNode}):void 0,B=s?$=>s($,{...S.userNode}):void 0,K=o?$=>o($,{...S.userNode}):void 0,H=i?$=>i($,{...S.userNode}):void 0,W=$=>{const{selectNodesOnDrag:q,nodeDragThreshold:Q}=M.getState();k&&(!q||!A||Q>0)&&$s({id:e,store:M,nodeRef:b}),t&&t($,{...S.userNode})},J=$=>{if(!(cu($.nativeEvent)||p)){if(Qc.includes($.key)&&k){const q=$.key==="Escape";$s({id:e,store:M,unselect:q,nodeRef:b})}else if(A&&m.selected&&Object.prototype.hasOwnProperty.call(vr,$.key)){$.preventDefault();const{ariaLabelConfig:q}=M.getState();M.setState({ariaLiveMessage:q["node.a11yDescription.ariaLiveMessage"]({direction:$.key.replace("Arrow","").toLowerCase(),x:~~S.positionAbsolute.x,y:~~S.positionAbsolute.y})}),T({direction:vr[$.key],factor:$.shiftKey?4:1})}}},X=()=>{if(p||!b.current?.matches(":focus-visible"))return;const{transform:$,width:q,height:Q,autoPanOnNodeFocus:te,setCenter:G}=M.getState();te&&(xo(new Map([[e,m]]),{x:0,y:0,width:q,height:Q},$,!0).length>0||G(m.position.x+j.width/2,m.position.y+j.height/2,{zoom:$[2]}))};return(0,h.jsx)("div",{className:ue(["react-flow__node",`react-flow__node-${N}`,{[g]:A},m.className,{selected:m.selected,selectable:k,parent:E,draggable:A,dragging:w}]),ref:b,style:{zIndex:S.z,transform:`translate(${S.positionAbsolute.x}px,${S.positionAbsolute.y}px)`,pointerEvents:L?"all":"none",visibility:O?"visible":"hidden",...m.style,...D},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:F,onMouseMove:z,onMouseLeave:B,onContextMenu:K,onClick:W,onDoubleClick:H,onKeyDown:_?J:void 0,tabIndex:_?0:void 0,onFocus:_?X:void 0,role:m.ariaRole??(_?"group":void 0),"aria-roledescription":"node","aria-describedby":p?void 0:`${_u}-${y}`,"aria-label":m.ariaLabel,...m.domAttributes,children:(0,h.jsx)(II,{value:e,children:(0,h.jsx)(R,{id:e,data:m.data,type:N,positionAbsoluteX:S.positionAbsolute.x,positionAbsoluteY:S.positionAbsolute.y,selected:m.selected??!1,selectable:k,draggable:A,deletable:m.deletable??!0,isConnectable:P,sourcePosition:m.sourcePosition,targetPosition:m.targetPosition,dragging:w,dragHandle:m.dragHandle,zIndex:S.z,parentId:m.parentId,...j})})})}var UI=(0,C.memo)(GI),qI=e=>({nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function Hu(e){const{nodesConnectable:t,nodesFocusable:n,elementsSelectable:r,onError:s}=re(qI,le),o=FI(e.onlyRenderVisibleElements),i=HI();return(0,h.jsx)("div",{className:"react-flow__nodes",style:Hr,children:o.map(a=>(0,h.jsx)(UI,{id:a,nodeTypes:e.nodeTypes,nodeExtent:e.nodeExtent,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,resizeObserver:i,nodesDraggable:e.nodesDraggable??!0,nodesConnectable:t,nodesFocusable:n,elementsSelectable:r,nodeClickDistance:e.nodeClickDistance,onError:s},a))})}Hu.displayName="NodeRenderer";var VI=(0,C.memo)(Hu);function KI(e){return re((0,C.useCallback)(t=>{if(!e)return t.edges.map(r=>r.id);const n=[];if(t.width&&t.height)for(const r of t.edges){const s=t.nodeLookup.get(r.source),o=t.nodeLookup.get(r.target);s&&o&&Yx({sourceNode:s,targetNode:o,width:t.width,height:t.height,transform:t.transform})&&n.push(r.id)}return n},[e]),le)}var YI=({color:e="none",strokeWidth:t=1})=>{const n={strokeWidth:t,...e&&{stroke:e}};return(0,h.jsx)("polyline",{className:"arrow",style:n,strokeLinecap:"round",fill:"none",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4"})},WI=({color:e="none",strokeWidth:t=1})=>{const n={strokeWidth:t,...e&&{stroke:e,fill:e}};return(0,h.jsx)("polyline",{className:"arrowclosed",style:n,strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"})},ga={[pr.Arrow]:YI,[pr.ArrowClosed]:WI};function XI(e){const t=oe();return(0,C.useMemo)(()=>Object.prototype.hasOwnProperty.call(ga,e)?ga[e]:(t.getState().onError?.("009",Te.error009(e)),null),[e])}var QI=({id:e,type:t,color:n,width:r=12.5,height:s=12.5,markerUnits:o="strokeWidth",strokeWidth:i,orient:a="auto-start-reverse"})=>{const l=XI(t);return l?(0,h.jsx)("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${r}`,markerHeight:`${s}`,viewBox:"-10 -10 20 20",markerUnits:o,orient:a,refX:"0",refY:"0",children:(0,h.jsx)(l,{color:n,strokeWidth:i})}):null},Bu=({defaultColor:e,rfId:t})=>{const n=re(o=>o.edges),r=re(o=>o.defaultEdgeOptions),s=(0,C.useMemo)(()=>nS(n,{id:t,defaultColor:e,defaultMarkerStart:r?.markerStart,defaultMarkerEnd:r?.markerEnd}),[n,r,t,e]);return s.length?(0,h.jsx)("svg",{className:"react-flow__marker","aria-hidden":"true",children:(0,h.jsx)("defs",{children:s.map(o=>(0,h.jsx)(QI,{id:o.id,type:o.type,color:o.color,width:o.width,height:o.height,markerUnits:o.markerUnits,strokeWidth:o.strokeWidth,orient:o.orient},o.id))})}):null};Bu.displayName="MarkerDefinitions";var JI=(0,C.memo)(Bu);function Gu({x:e,y:t,label:n,labelStyle:r,labelShowBg:s=!0,labelBgStyle:o,labelBgPadding:i=[2,4],labelBgBorderRadius:a=2,children:l,className:c,...u}){const[d,f]=(0,C.useState)({x:1,y:0,width:0,height:0}),g=ue(["react-flow__edge-textwrapper",c]),p=(0,C.useRef)(null);return(0,C.useEffect)(()=>{if(p.current){const y=p.current.getBBox();f({x:y.x,y:y.y,width:y.width,height:y.height})}},[n]),n?(0,h.jsxs)("g",{transform:`translate(${e-d.width/2} ${t-d.height/2})`,className:g,visibility:d.width?"visible":"hidden",...u,children:[s&&(0,h.jsx)("rect",{width:d.width+2*i[0],x:-i[0],y:-i[1],height:d.height+2*i[1],className:"react-flow__edge-textbg",style:o,rx:a,ry:a}),(0,h.jsx)("text",{className:"react-flow__edge-text",y:d.height/2,dy:"0.3em",ref:p,style:r,children:n}),l]}):null}Gu.displayName="EdgeText";var ZI=(0,C.memo)(Gu);function Br({path:e,labelX:t,labelY:n,label:r,labelStyle:s,labelShowBg:o,labelBgStyle:i,labelBgPadding:a,labelBgBorderRadius:l,interactionWidth:c=20,...u}){return(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("path",{...u,d:e,fill:"none",className:ue(["react-flow__edge-path",u.className])}),c?(0,h.jsx)("path",{d:e,fill:"none",strokeOpacity:0,strokeWidth:c,className:"react-flow__edge-interaction"}):null,r&&Pe(t)&&Pe(n)?(0,h.jsx)(ZI,{x:t,y:n,label:r,labelStyle:s,labelShowBg:o,labelBgStyle:i,labelBgPadding:a,labelBgBorderRadius:l}):null]})}function ma({pos:e,x1:t,y1:n,x2:r,y2:s}){return e===Y.Left||e===Y.Right?[.5*(t+r),n]:[t,.5*(n+s)]}function Uu({sourceX:e,sourceY:t,sourcePosition:n=Y.Bottom,targetX:r,targetY:s,targetPosition:o=Y.Top}){const[i,a]=ma({pos:n,x1:e,y1:t,x2:r,y2:s}),[l,c]=ma({pos:o,x1:r,y1:s,x2:e,y2:t}),[u,d,f,g]=du({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:i,sourceControlY:a,targetControlX:l,targetControlY:c});return[`M${e},${t} C${i},${a} ${l},${c} ${r},${s}`,u,d,f,g]}function qu(e){return(0,C.memo)(({id:t,sourceX:n,sourceY:r,targetX:s,targetY:o,sourcePosition:i,targetPosition:a,label:l,labelStyle:c,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:g,style:p,markerEnd:y,markerStart:x,interactionWidth:v})=>{const[I,m,S]=Uu({sourceX:n,sourceY:r,sourcePosition:i,targetX:s,targetY:o,targetPosition:a}),E=e.isInternal?void 0:t;return(0,h.jsx)(Br,{id:E,path:I,labelX:m,labelY:S,label:l,labelStyle:c,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:g,style:p,markerEnd:y,markerStart:x,interactionWidth:v})})}var ew=qu({isInternal:!1}),Vu=qu({isInternal:!0});ew.displayName="SimpleBezierEdge";Vu.displayName="SimpleBezierEdgeInternal";function Ku(e){return(0,C.memo)(({id:t,sourceX:n,sourceY:r,targetX:s,targetY:o,label:i,labelStyle:a,labelShowBg:l,labelBgStyle:c,labelBgPadding:u,labelBgBorderRadius:d,style:f,sourcePosition:g=Y.Bottom,targetPosition:p=Y.Top,markerEnd:y,markerStart:x,pathOptions:v,interactionWidth:I})=>{const[m,S,E]=js({sourceX:n,sourceY:r,sourcePosition:g,targetX:s,targetY:o,targetPosition:p,borderRadius:v?.borderRadius,offset:v?.offset,stepPosition:v?.stepPosition}),N=e.isInternal?void 0:t;return(0,h.jsx)(Br,{id:N,path:m,labelX:S,labelY:E,label:i,labelStyle:a,labelShowBg:l,labelBgStyle:c,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:y,markerStart:x,interactionWidth:I})})}var Yu=Ku({isInternal:!1}),Wu=Ku({isInternal:!0});Yu.displayName="SmoothStepEdge";Wu.displayName="SmoothStepEdgeInternal";function Xu(e){return(0,C.memo)(({id:t,...n})=>{const r=e.isInternal?void 0:t;return(0,h.jsx)(Yu,{...n,id:r,pathOptions:(0,C.useMemo)(()=>({borderRadius:0,offset:n.pathOptions?.offset}),[n.pathOptions?.offset])})})}var tw=Xu({isInternal:!1}),Qu=Xu({isInternal:!0});tw.displayName="StepEdge";Qu.displayName="StepEdgeInternal";function Ju(e){return(0,C.memo)(({id:t,sourceX:n,sourceY:r,targetX:s,targetY:o,label:i,labelStyle:a,labelShowBg:l,labelBgStyle:c,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:g,markerStart:p,interactionWidth:y})=>{const[x,v,I]=pu({sourceX:n,sourceY:r,targetX:s,targetY:o}),m=e.isInternal?void 0:t;return(0,h.jsx)(Br,{id:m,path:x,labelX:v,labelY:I,label:i,labelStyle:a,labelShowBg:l,labelBgStyle:c,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:g,markerStart:p,interactionWidth:y})})}var nw=Ju({isInternal:!1}),Zu=Ju({isInternal:!0});nw.displayName="StraightEdge";Zu.displayName="StraightEdgeInternal";function ed(e){return(0,C.memo)(({id:t,sourceX:n,sourceY:r,targetX:s,targetY:o,sourcePosition:i=Y.Bottom,targetPosition:a=Y.Top,label:l,labelStyle:c,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:g,style:p,markerEnd:y,markerStart:x,pathOptions:v,interactionWidth:I})=>{const[m,S,E]=hu({sourceX:n,sourceY:r,sourcePosition:i,targetX:s,targetY:o,targetPosition:a,curvature:v?.curvature}),N=e.isInternal?void 0:t;return(0,h.jsx)(Br,{id:N,path:m,labelX:S,labelY:E,label:l,labelStyle:c,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:g,style:p,markerEnd:y,markerStart:x,interactionWidth:I})})}var rw=ed({isInternal:!1}),td=ed({isInternal:!0});rw.displayName="BezierEdge";td.displayName="BezierEdgeInternal";var va={default:td,straight:Zu,step:Qu,smoothstep:Wu,simplebezier:Vu},ya={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null,zIndex:void 0},sw=(e,t,n)=>n===Y.Left?e-t:n===Y.Right?e+t:e,ow=(e,t,n)=>n===Y.Top?e-t:n===Y.Bottom?e+t:e,ba="react-flow__edgeupdater";function xa({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:s,onMouseEnter:o,onMouseOut:i,type:a}){return(0,h.jsx)("circle",{onMouseDown:s,onMouseEnter:o,onMouseOut:i,className:ue([ba,`${ba}-${a}`]),cx:sw(t,r,e),cy:ow(n,r,e),r,stroke:"transparent",fill:"transparent"})}function iw({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:r,sourceY:s,targetX:o,targetY:i,sourcePosition:a,targetPosition:l,onReconnect:c,onReconnectStart:u,onReconnectEnd:d,setReconnecting:f,setUpdateHover:g}){const p=oe(),y=(S,E)=>{if(S.button!==0)return;const{autoPanOnConnect:N,domNode:R,connectionMode:A,connectionRadius:k,lib:P,onConnectStart:_,cancelConnection:M,nodeLookup:O,rfId:b,panBy:w,updateConnection:T}=p.getState(),j=E.type==="target",D=(z,B)=>{f(!1),d?.(z,n,E.type,B)},L=z=>c?.(n,z),F=(z,B)=>{f(!0),u?.(S,n,E.type),_?.(z,B)};Ds.onPointerDown(S.nativeEvent,{autoPanOnConnect:N,connectionMode:A,connectionRadius:k,domNode:R,handleId:E.id,nodeId:E.nodeId,nodeLookup:O,isTarget:j,edgeUpdaterType:E.type,lib:P,flowId:b,cancelConnection:M,panBy:w,isValidConnection:(...z)=>p.getState().isValidConnection?.(...z)??!0,onConnect:L,onConnectStart:F,onConnectEnd:(...z)=>p.getState().onConnectEnd?.(...z),onReconnectEnd:D,updateConnection:T,getTransform:()=>p.getState().transform,getFromHandle:()=>p.getState().connection.fromHandle,dragThreshold:p.getState().connectionDragThreshold,handleDomNode:S.currentTarget})},x=S=>y(S,{nodeId:n.target,id:n.targetHandle??null,type:"target"}),v=S=>y(S,{nodeId:n.source,id:n.sourceHandle??null,type:"source"}),I=()=>g(!0),m=()=>g(!1);return(0,h.jsxs)(h.Fragment,{children:[(e===!0||e==="source")&&(0,h.jsx)(xa,{position:a,centerX:r,centerY:s,radius:t,onMouseDown:x,onMouseEnter:I,onMouseOut:m,type:"source"}),(e===!0||e==="target")&&(0,h.jsx)(xa,{position:l,centerX:o,centerY:i,radius:t,onMouseDown:v,onMouseEnter:I,onMouseOut:m,type:"target"})]})}function aw({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:r,onClick:s,onDoubleClick:o,onContextMenu:i,onMouseEnter:a,onMouseMove:l,onMouseLeave:c,reconnectRadius:u,onReconnect:d,onReconnectStart:f,onReconnectEnd:g,rfId:p,edgeTypes:y,noPanClassName:x,onError:v,disableKeyboardA11y:I}){let m=re(G=>G.edgeLookup.get(e));const S=re(G=>G.defaultEdgeOptions);m=S?{...S,...m}:m;let E=m.type||"default",N=y?.[E]||va[E];N===void 0&&(v?.("011",Te.error011(E)),E="default",N=y?.default||va.default);const R=!!(m.focusable||t&&typeof m.focusable>"u"),A=typeof d<"u"&&(m.reconnectable||n&&typeof m.reconnectable>"u"),k=!!(m.selectable||r&&typeof m.selectable>"u"),P=(0,C.useRef)(null),[_,M]=(0,C.useState)(!1),[O,b]=(0,C.useState)(!1),w=oe(),{zIndex:T=m.zIndex,sourceX:j,sourceY:D,targetX:L,targetY:F,sourcePosition:z,targetPosition:B}=re((0,C.useCallback)(G=>{const ne=G.nodeLookup.get(m.source),Z=G.nodeLookup.get(m.target);if(!ne||!Z)return ya;const U=tS({id:e,sourceNode:ne,targetNode:Z,sourceHandle:m.sourceHandle||null,targetHandle:m.targetHandle||null,connectionMode:G.connectionMode,onError:v}),V=Kx({selected:m.selected,zIndex:m.zIndex,sourceNode:ne,targetNode:Z,elevateOnSelect:G.elevateEdgesOnSelect,zIndexMode:G.zIndexMode});return{...U||ya,zIndex:V}},[m.source,m.target,m.sourceHandle,m.targetHandle,m.selected,m.zIndex,v]),le),K=(0,C.useMemo)(()=>m.markerStart?`url('#${Ps(m.markerStart,p)}')`:void 0,[m.markerStart,p]),H=(0,C.useMemo)(()=>m.markerEnd?`url('#${Ps(m.markerEnd,p)}')`:void 0,[m.markerEnd,p]);if(m.hidden||j===null||D===null||L===null||F===null)return null;const W=G=>{const{addSelectedEdges:ne,unselectNodesAndEdges:Z,multiSelectionActive:U}=w.getState();k&&(w.setState({nodesSelectionActive:!1}),m.selected&&U?(Z({nodes:[],edges:[m]}),P.current?.blur()):ne([e])),s&&s(G,m)},J=o?G=>{o(G,{...m})}:void 0,X=i?G=>{i(G,{...m})}:void 0,$=a?G=>{a(G,{...m})}:void 0,q=l?G=>{l(G,{...m})}:void 0,Q=c?G=>{c(G,{...m})}:void 0,te=G=>{if(!I&&Qc.includes(G.key)&&k){const{unselectNodesAndEdges:ne,addSelectedEdges:Z}=w.getState();G.key==="Escape"?(P.current?.blur(),ne({edges:[m]})):Z([e])}};return(0,h.jsx)("svg",{style:{zIndex:T},children:(0,h.jsxs)("g",{className:ue(["react-flow__edge",`react-flow__edge-${E}`,m.className,x,{selected:m.selected,animated:m.animated,inactive:!k&&!s,updating:_,selectable:k}]),onClick:W,onDoubleClick:J,onContextMenu:X,onMouseEnter:$,onMouseMove:q,onMouseLeave:Q,onKeyDown:R?te:void 0,tabIndex:R?0:void 0,role:m.ariaRole??(R?"group":"img"),"aria-roledescription":"edge","data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":m.ariaLabel===null?void 0:m.ariaLabel||`Edge from ${m.source} to ${m.target}`,"aria-describedby":R?`${Tu}-${p}`:void 0,ref:P,...m.domAttributes,children:[!O&&(0,h.jsx)(N,{id:e,source:m.source,target:m.target,type:m.type,selected:m.selected,animated:m.animated,selectable:k,deletable:m.deletable??!0,label:m.label,labelStyle:m.labelStyle,labelShowBg:m.labelShowBg,labelBgStyle:m.labelBgStyle,labelBgPadding:m.labelBgPadding,labelBgBorderRadius:m.labelBgBorderRadius,sourceX:j,sourceY:D,targetX:L,targetY:F,sourcePosition:z,targetPosition:B,data:m.data,style:m.style,sourceHandleId:m.sourceHandle,targetHandleId:m.targetHandle,markerStart:K,markerEnd:H,pathOptions:"pathOptions"in m?m.pathOptions:void 0,interactionWidth:m.interactionWidth}),A&&(0,h.jsx)(iw,{edge:m,isReconnectable:A,reconnectRadius:u,onReconnect:d,onReconnectStart:f,onReconnectEnd:g,sourceX:j,sourceY:D,targetX:L,targetY:F,sourcePosition:z,targetPosition:B,setUpdateHover:M,setReconnecting:b})]})})}var lw=(0,C.memo)(aw),cw=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function nd({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:r,noPanClassName:s,onReconnect:o,onEdgeContextMenu:i,onEdgeMouseEnter:a,onEdgeMouseMove:l,onEdgeMouseLeave:c,onEdgeClick:u,reconnectRadius:d,onEdgeDoubleClick:f,onReconnectStart:g,onReconnectEnd:p,disableKeyboardA11y:y}){const{edgesFocusable:x,edgesReconnectable:v,elementsSelectable:I,onError:m}=re(cw,le),S=KI(t);return(0,h.jsxs)("div",{className:"react-flow__edges",children:[(0,h.jsx)(JI,{defaultColor:e,rfId:n}),S.map(E=>(0,h.jsx)(lw,{id:E,edgesFocusable:x,edgesReconnectable:v,elementsSelectable:I,noPanClassName:s,onReconnect:o,onContextMenu:i,onMouseEnter:a,onMouseMove:l,onMouseLeave:c,onClick:u,reconnectRadius:d,onDoubleClick:f,onReconnectStart:g,onReconnectEnd:p,rfId:n,onError:m,edgeTypes:r,disableKeyboardA11y:y},E))]})}nd.displayName="EdgeRenderer";var uw=(0,C.memo)(nd),Sa=e=>`translate(${e[0]}px,${e[1]}px) scale(${e[2]})`;function dw({children:e}){const t=oe(),n=(0,C.useRef)(null),[r]=(0,C.useState)(()=>t.getState().transform);return ju(()=>{let s=null;const o=()=>{const i=t.getState().transform;s&&i[0]===s[0]&&i[1]===s[1]&&i[2]===s[2]||(s=i,n.current&&(n.current.style.transform=Sa(i)))};return o(),t.subscribe(o)},[t]),(0,h.jsx)("div",{ref:n,className:"react-flow__viewport xyflow__viewport react-flow__container",style:{transform:Sa(r)},children:e})}function hw(e){const t=zr(),n=(0,C.useRef)(!1);(0,C.useEffect)(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}var fw=e=>e.panZoom?.syncViewport;function pw(e){const t=re(fw),n=oe();return(0,C.useEffect)(()=>{e&&(t?.(e),n.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function Ia(e){return e.connection.inProgress?{...e.connection,to:Pn(e.connection.to,e.transform)}:{...e.connection}}function gw(e){return e?n=>e(Ia(n)):Ia}function mw(e){return re(gw(e),le)}var vw=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function yw({containerStyle:e,style:t,type:n,component:r}){const{nodesConnectable:s,width:o,height:i,isValid:a,inProgress:l}=re(vw,le);return o&&s&&l?(0,h.jsx)("svg",{style:e,width:o,height:i,className:"react-flow__connectionline react-flow__container",children:(0,h.jsx)("g",{className:ue(["react-flow__connection",au(a)]),children:(0,h.jsx)(rd,{style:t,type:n,CustomComponent:r,isValid:a})})}):null}var rd=({style:e,type:t=lt.Bezier,CustomComponent:n,isValid:r})=>{const{inProgress:s,from:o,fromNode:i,fromHandle:a,fromPosition:l,to:c,toNode:u,toHandle:d,toPosition:f,pointer:g}=mw();if(!s)return;if(n)return(0,h.jsx)(n,{connectionLineType:t,connectionLineStyle:e,fromNode:i,fromHandle:a,fromX:o.x,fromY:o.y,toX:c.x,toY:c.y,fromPosition:l,toPosition:f,connectionStatus:au(r),toNode:u,toHandle:d,pointer:g});let p="";const y={sourceX:o.x,sourceY:o.y,sourcePosition:l,targetX:c.x,targetY:c.y,targetPosition:f};switch(t){case lt.Bezier:[p]=hu(y);break;case lt.SimpleBezier:[p]=Uu(y);break;case lt.Step:[p]=js({...y,borderRadius:0});break;case lt.SmoothStep:[p]=js(y);break;default:[p]=pu(y)}return(0,h.jsx)("path",{d:p,fill:"none",className:"react-flow__connection-path",style:e})};rd.displayName="ConnectionLine";var bw={};function wa(e=bw){(0,C.useRef)(e),oe(),(0,C.useEffect)(()=>{},[e])}function xw(){oe(),(0,C.useRef)(!1),(0,C.useEffect)(()=>{},[])}function sd({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:r,onEdgeClick:s,onNodeDoubleClick:o,onEdgeDoubleClick:i,onNodeMouseEnter:a,onNodeMouseMove:l,onNodeMouseLeave:c,onNodeContextMenu:u,onSelectionContextMenu:d,onSelectionStart:f,onSelectionEnd:g,connectionLineType:p,connectionLineStyle:y,connectionLineComponent:x,connectionLineContainerStyle:v,selectionKeyCode:I,selectionOnDrag:m,selectionMode:S,multiSelectionKeyCode:E,panActivationKeyCode:N,zoomActivationKeyCode:R,deleteKeyCode:A,onlyRenderVisibleElements:k,elementsSelectable:P,defaultViewport:_,translateExtent:M,minZoom:O,maxZoom:b,preventScrolling:w,defaultMarkerColor:T,zoomOnScroll:j,zoomOnPinch:D,panOnScroll:L,panOnScrollSpeed:F,panOnScrollMode:z,zoomOnDoubleClick:B,panOnDrag:K,autoPanOnSelection:H,onPaneClick:W,onPaneMouseEnter:J,onPaneMouseMove:X,onPaneMouseLeave:$,onPaneScroll:q,onPaneContextMenu:Q,paneClickDistance:te,nodeClickDistance:G,onEdgeContextMenu:ne,onEdgeMouseEnter:Z,onEdgeMouseMove:U,onEdgeMouseLeave:V,reconnectRadius:pe,onReconnect:ge,onReconnectStart:ve,onReconnectEnd:Me,noDragClassName:ie,noWheelClassName:rt,noPanClassName:ee,disableKeyboardA11y:ce,nodeExtent:ke,rfId:Ye,viewport:We,onViewportChange:pt,nodesDraggable:Kr}){return wa(e),wa(t),xw(),hw(n),pw(We),(0,h.jsx)(DI,{onPaneClick:W,onPaneMouseEnter:J,onPaneMouseMove:X,onPaneMouseLeave:$,onPaneContextMenu:Q,onPaneScroll:q,paneClickDistance:te,deleteKeyCode:A,selectionKeyCode:I,selectionOnDrag:m,selectionMode:S,onSelectionStart:f,onSelectionEnd:g,multiSelectionKeyCode:E,panActivationKeyCode:N,zoomActivationKeyCode:R,elementsSelectable:P,zoomOnScroll:j,zoomOnPinch:D,zoomOnDoubleClick:B,panOnScroll:L,panOnScrollSpeed:F,panOnScrollMode:z,panOnDrag:K,autoPanOnSelection:H,defaultViewport:_,translateExtent:M,minZoom:O,maxZoom:b,onSelectionContextMenu:d,preventScrolling:w,noDragClassName:ie,noWheelClassName:rt,noPanClassName:ee,disableKeyboardA11y:ce,onViewportChange:pt,isControlledViewport:!!We,children:(0,h.jsxs)(dw,{children:[(0,h.jsx)(uw,{edgeTypes:t,onEdgeClick:s,onEdgeDoubleClick:i,onReconnect:ge,onReconnectStart:ve,onReconnectEnd:Me,onlyRenderVisibleElements:k,onEdgeContextMenu:ne,onEdgeMouseEnter:Z,onEdgeMouseMove:U,onEdgeMouseLeave:V,reconnectRadius:pe,defaultMarkerColor:T,noPanClassName:ee,disableKeyboardA11y:ce,rfId:Ye}),(0,h.jsx)(yw,{style:y,type:p,component:x,containerStyle:v}),(0,h.jsx)("div",{className:"react-flow__edgelabel-renderer"}),(0,h.jsx)(VI,{nodeTypes:e,onNodeClick:r,onNodeDoubleClick:o,onNodeMouseEnter:a,onNodeMouseMove:l,onNodeMouseLeave:c,onNodeContextMenu:u,nodeClickDistance:G,onlyRenderVisibleElements:k,noPanClassName:ee,noDragClassName:ie,disableKeyboardA11y:ce,nodeExtent:ke,rfId:Ye,nodesDraggable:Kr}),(0,h.jsx)("div",{className:"react-flow__viewport-portal"})]})})}sd.displayName="GraphView";var Sw=(0,C.memo)(sd),Iw=ou("React Flow","https://reactflow.dev/"),Ea=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:s,height:o,fitView:i,fitViewOptions:a,minZoom:l=.5,maxZoom:c=2,nodeOrigin:u,nodeExtent:d,zIndexMode:f="basic"}={})=>{const g=new Map,p=new Map,y=new Map,x=new Map,v=r??t??[],I=n??e??[],m=u??[0,0],S=d??Cn;vu(y,x,v);const{nodesInitialized:E}=Ls(I,g,p,{nodeOrigin:m,nodeExtent:S,zIndexMode:f});let N=[0,0,1];if(i&&s&&o){const R=On(g,{filter:_=>!!((_.width||_.initialWidth)&&(_.height||_.initialHeight))}),{x:A,y:k,zoom:P}=Io(R,s,o,l,c,a?.padding??.1);N=[A,k,P]}return{rfId:"1",width:s??0,height:o??0,transform:N,nodes:I,nodesInitialized:E,nodeLookup:g,parentLookup:p,edges:v,edgeLookup:x,connectionLookup:y,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:n!==void 0,hasDefaultEdges:r!==void 0,panZoom:null,minZoom:l,maxZoom:c,translateExtent:Cn,nodeExtent:S,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:Wt.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:m,nodeDragThreshold:1,connectionDragThreshold:1,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesReconnectable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,elevateEdgesOnSelect:!0,selectNodesOnDrag:!0,multiSelectionActive:!1,fitViewQueued:i??!1,fitViewOptions:a,fitViewResolver:null,connection:{...Zc},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:Iw,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:"react",debug:!1,ariaLabelConfig:Jc,zIndexMode:f,defaultEdgeOptions:void 0,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map,onNodesDelete:void 0,onEdgesDelete:void 0,onDelete:void 0,onBeforeDelete:void 0,onViewportChangeStart:void 0,onViewportChange:void 0,onViewportChangeEnd:void 0,onNodeDragStart:void 0,onNodeDrag:void 0,onNodeDragStop:void 0,onSelectionDragStart:void 0,onSelectionDrag:void 0,onSelectionDragStop:void 0,onMoveStart:void 0,onMove:void 0,onMoveEnd:void 0,onConnect:void 0,onConnectStart:void 0,onConnectEnd:void 0,onClickConnectStart:void 0,onClickConnectEnd:void 0}},ww=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:s,height:o,fitView:i,fitViewOptions:a,minZoom:l,maxZoom:c,nodeOrigin:u,nodeExtent:d,zIndexMode:f})=>$S((g,p)=>{async function y(){const{nodeLookup:x,panZoom:v,fitViewOptions:I,fitViewResolver:m,width:S,height:E,minZoom:N,maxZoom:R}=p();v&&(await zx({nodes:x,width:S,height:E,panZoom:v,minZoom:N,maxZoom:R},I),m?.resolve(!0),g({fitViewResolver:null}))}return{...Ea({nodes:e,edges:t,width:s,height:o,fitView:i,fitViewOptions:a,minZoom:l,maxZoom:c,nodeOrigin:u,nodeExtent:d,defaultNodes:n,defaultEdges:r,zIndexMode:f}),setNodes:x=>{const{nodeLookup:v,parentLookup:I,nodeOrigin:m,nodeExtent:S,elevateNodesOnSelect:E,fitViewQueued:N,zIndexMode:R,nodesSelectionActive:A}=p(),{nodesInitialized:k,hasSelectedNodes:P}=Ls(x,v,I,{nodeOrigin:m,nodeExtent:S,elevateNodesOnSelect:E,checkEquality:!0,zIndexMode:R}),_=A&&P;N&&k?(y(),g({nodes:x,nodesInitialized:k,fitViewQueued:!1,fitViewOptions:void 0,nodesSelectionActive:_})):g({nodes:x,nodesInitialized:k,nodesSelectionActive:_})},setEdges:x=>{const{connectionLookup:v,edgeLookup:I}=p();vu(v,I,x),g({edges:x})},setDefaultNodesAndEdges:(x,v)=>{if(x){const{setNodes:I}=p();I(x),g({hasDefaultNodes:!0})}if(v){const{setEdges:I}=p();I(v),g({hasDefaultEdges:!0})}},updateNodeInternals:x=>{const{triggerNodeChanges:v,nodeLookup:I,parentLookup:m,domNode:S,nodeOrigin:E,nodeExtent:N,debug:R,fitViewQueued:A,zIndexMode:k}=p(),{changes:P,updatedInternals:_}=cS(x,I,m,S,E,N,k);_&&(oS(I,m,{nodeOrigin:E,nodeExtent:N,zIndexMode:k}),A?(y(),g({fitViewQueued:!1,fitViewOptions:void 0})):g({}),P?.length>0&&(R&&console.log("React Flow: trigger node changes",P),v?.(P)))},updateNodePositions:(x,v=!1)=>{const I=[];let m=[];const{nodeLookup:S,triggerNodeChanges:E,connection:N,updateConnection:R,onNodesChangeMiddlewareMap:A}=p();for(const[k,P]of x){const _=S.get(k),M=!!(_?.expandParent&&_?.parentId&&P?.position),O={id:k,type:"position",position:M?{x:Math.max(0,P.position.x),y:Math.max(0,P.position.y)}:P.position,dragging:v};if(_&&N.inProgress&&N.fromNode.id===_.id){const b=Tt(_,N.fromHandle,Y.Left,!0);R({...N,from:b})}M&&_.parentId&&I.push({id:k,parentId:_.parentId,rect:{...P.internals.positionAbsolute,width:P.measured.width??0,height:P.measured.height??0}}),m.push(O)}if(I.length>0){const{parentLookup:k,nodeOrigin:P}=p(),_=To(I,S,k,P);m.push(..._)}for(const k of A.values())m=k(m);E(m)},triggerNodeChanges:x=>{const{onNodesChange:v,setNodes:I,nodes:m,hasDefaultNodes:S,debug:E}=p();x?.length&&(S&&I(ku(x,m)),E&&console.log("React Flow: trigger node changes",x),v?.(x))},triggerEdgeChanges:x=>{const{onEdgesChange:v,setEdges:I,edges:m,hasDefaultEdges:S,debug:E}=p();x?.length&&(S&&I(sI(x,m)),E&&console.log("React Flow: trigger edge changes",x),v?.(x))},addSelectedNodes:x=>{const{multiSelectionActive:v,edgeLookup:I,nodeLookup:m,triggerNodeChanges:S,triggerEdgeChanges:E}=p();if(v){S(x.map(N=>vt(N,!0)));return}S(Pt(m,new Set([...x]),!0)),E(Pt(I))},addSelectedEdges:x=>{const{multiSelectionActive:v,edgeLookup:I,nodeLookup:m,triggerNodeChanges:S,triggerEdgeChanges:E}=p();if(v){E(x.map(N=>vt(N,!0)));return}E(Pt(I,new Set([...x]))),S(Pt(m,new Set,!0))},unselectNodesAndEdges:({nodes:x,edges:v}={})=>{const{edges:I,nodes:m,nodeLookup:S,triggerNodeChanges:E,triggerEdgeChanges:N}=p(),R=x||m,A=v||I,k=[];for(const _ of R){if(!_.selected)continue;const M=S.get(_.id);M&&(M.selected=!1),k.push(vt(_.id,!1))}const P=[];for(const _ of A)_.selected&&P.push(vt(_.id,!1));E(k),N(P)},setMinZoom:x=>{const{panZoom:v,maxZoom:I}=p();v?.setScaleExtent([x,I]),g({minZoom:x})},setMaxZoom:x=>{const{panZoom:v,minZoom:I}=p();v?.setScaleExtent([I,x]),g({maxZoom:x})},setTranslateExtent:x=>{p().panZoom?.setTranslateExtent(x),g({translateExtent:x})},resetSelectedElements:()=>{const{edges:x,nodes:v,triggerNodeChanges:I,triggerEdgeChanges:m,elementsSelectable:S}=p();if(!S)return;const E=v.reduce((R,A)=>A.selected?[...R,vt(A.id,!1)]:R,[]),N=x.reduce((R,A)=>A.selected?[...R,vt(A.id,!1)]:R,[]);I(E),m(N)},setNodeExtent:x=>{const{nodes:v,nodeLookup:I,parentLookup:m,nodeOrigin:S,elevateNodesOnSelect:E,nodeExtent:N,zIndexMode:R}=p();x[0][0]===N[0][0]&&x[0][1]===N[0][1]&&x[1][0]===N[1][0]&&x[1][1]===N[1][1]||(Ls(v,I,m,{nodeOrigin:S,nodeExtent:x,elevateNodesOnSelect:E,checkEquality:!1,zIndexMode:R}),g({nodeExtent:x}))},panBy:x=>{const{transform:v,width:I,height:m,panZoom:S,translateExtent:E}=p();return uS({delta:x,panZoom:S,transform:v,translateExtent:E,width:I,height:m})},setCenter:async(x,v,I)=>{const{width:m,height:S,maxZoom:E,panZoom:N}=p();if(!N)return!1;const R=typeof I?.zoom<"u"?I.zoom:E;return await N.setViewport({x:m/2-x*R,y:S/2-v*R,zoom:R},{duration:I?.duration,ease:I?.ease,interpolate:I?.interpolate}),!0},cancelConnection:()=>{g({connection:{...Zc}})},updateConnection:x=>{g({connection:x})},reset:()=>g({...Ea()})}},Object.is);function od({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:r,initialWidth:s,initialHeight:o,initialMinZoom:i,initialMaxZoom:a,initialFitViewOptions:l,fitView:c,nodeOrigin:u,nodeExtent:d,zIndexMode:f,children:g}){const[p]=(0,C.useState)(()=>ww({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:s,height:o,fitView:c,minZoom:i,maxZoom:a,fitViewOptions:l,nodeOrigin:u,nodeExtent:d,zIndexMode:f}));return(0,h.jsx)(FS,{value:p,children:(0,h.jsx)(cI,{children:(0,h.jsx)(EI,{children:g})})})}function Ew({children:e,nodes:t,edges:n,defaultNodes:r,defaultEdges:s,width:o,height:i,fitView:a,fitViewOptions:l,minZoom:c,maxZoom:u,nodeOrigin:d,nodeExtent:f,zIndexMode:g}){return(0,C.useContext)($r)?(0,h.jsx)(h.Fragment,{children:e}):(0,h.jsx)(od,{initialNodes:t,initialEdges:n,defaultNodes:r,defaultEdges:s,initialWidth:o,initialHeight:i,fitView:a,initialFitViewOptions:l,initialMinZoom:c,initialMaxZoom:u,nodeOrigin:d,nodeExtent:f,zIndexMode:g,children:e})}var Cw={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0};function Nw({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:s,nodeTypes:o,edgeTypes:i,onNodeClick:a,onEdgeClick:l,onInit:c,onMove:u,onMoveStart:d,onMoveEnd:f,onConnect:g,onConnectStart:p,onConnectEnd:y,onClickConnectStart:x,onClickConnectEnd:v,onNodeMouseEnter:I,onNodeMouseMove:m,onNodeMouseLeave:S,onNodeContextMenu:E,onNodeDoubleClick:N,onNodeDragStart:R,onNodeDrag:A,onNodeDragStop:k,onNodesDelete:P,onEdgesDelete:_,onDelete:M,onSelectionChange:O,onSelectionDragStart:b,onSelectionDrag:w,onSelectionDragStop:T,onSelectionContextMenu:j,onSelectionStart:D,onSelectionEnd:L,onBeforeDelete:F,connectionMode:z,connectionLineType:B=lt.Bezier,connectionLineStyle:K,connectionLineComponent:H,connectionLineContainerStyle:W,deleteKeyCode:J="Backspace",selectionKeyCode:X="Shift",selectionOnDrag:$=!1,selectionMode:q=Nn.Full,panActivationKeyCode:Q="Space",multiSelectionKeyCode:te=_n()?"Meta":"Control",zoomActivationKeyCode:G=_n()?"Meta":"Control",snapToGrid:ne,snapGrid:Z,onlyRenderVisibleElements:U=!1,selectNodesOnDrag:V,nodesDraggable:pe,autoPanOnNodeFocus:ge,nodesConnectable:ve,nodesFocusable:Me,nodeOrigin:ie=Au,edgesFocusable:rt,edgesReconnectable:ee,elementsSelectable:ce=!0,defaultViewport:ke=JS,minZoom:Ye=.5,maxZoom:We=2,translateExtent:pt=Cn,preventScrolling:Kr=!0,nodeExtent:Yr,defaultMarkerColor:Vd="#b1b1b7",zoomOnScroll:Kd=!0,zoomOnPinch:Yd=!0,panOnScroll:Wd=!1,panOnScrollSpeed:Xd=.5,panOnScrollMode:Qd=wt.Free,zoomOnDoubleClick:Jd=!0,panOnDrag:Zd=!0,onPaneClick:eh,onPaneMouseEnter:th,onPaneMouseMove:nh,onPaneMouseLeave:rh,onPaneScroll:sh,onPaneContextMenu:oh,paneClickDistance:ih=1,nodeClickDistance:ah=0,children:lh,onReconnect:ch,onReconnectStart:uh,onReconnectEnd:dh,onEdgeContextMenu:hh,onEdgeDoubleClick:fh,onEdgeMouseEnter:ph,onEdgeMouseMove:gh,onEdgeMouseLeave:mh,reconnectRadius:vh=10,onNodesChange:yh,onEdgesChange:bh,noDragClassName:xh="nodrag",noWheelClassName:Sh="nowheel",noPanClassName:Do="nopan",fitView:$o,fitViewOptions:Fo,connectOnClick:Ih,attributionPosition:wh,proOptions:Eh,defaultEdgeOptions:Ch,elevateNodesOnSelect:Nh=!0,elevateEdgesOnSelect:Rh=!1,disableKeyboardA11y:zo=!1,autoPanOnConnect:_h,autoPanOnNodeDrag:Th,autoPanOnSelection:Ah=!0,autoPanSpeed:Mh,connectionRadius:kh,isValidConnection:Oh,onError:jh,style:Ph,id:Ho,nodeDragThreshold:Lh,connectionDragThreshold:Dh,viewport:$h,onViewportChange:Fh,width:zh,height:Hh,colorMode:Bh="light",debug:Gh,onScroll:Bo,ariaLabelConfig:Uh,zIndexMode:Go="basic",...qh},Vh){const Wr=Ho||"1",Kh=tI(Bh),Yh=(0,C.useCallback)(Uo=>{Uo.currentTarget.scrollTo({top:0,left:0,behavior:"instant"}),Bo?.(Uo)},[Bo]);return(0,h.jsx)("div",{"data-testid":"rf__wrapper",...qh,onScroll:Yh,style:{...Ph,...Cw},ref:Vh,className:ue(["react-flow",s,Kh]),id:Ho,role:"application",children:(0,h.jsxs)(Ew,{nodes:e,edges:t,width:zh,height:Hh,fitView:$o,fitViewOptions:Fo,minZoom:Ye,maxZoom:We,nodeOrigin:ie,nodeExtent:Yr,zIndexMode:Go,children:[(0,h.jsx)(eI,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:g,onConnectStart:p,onConnectEnd:y,onClickConnectStart:x,onClickConnectEnd:v,nodesDraggable:pe,autoPanOnNodeFocus:ge,nodesConnectable:ve,nodesFocusable:Me,edgesFocusable:rt,edgesReconnectable:ee,elementsSelectable:ce,elevateNodesOnSelect:Nh,elevateEdgesOnSelect:Rh,minZoom:Ye,maxZoom:We,nodeExtent:Yr,onNodesChange:yh,onEdgesChange:bh,snapToGrid:ne,snapGrid:Z,connectionMode:z,translateExtent:pt,connectOnClick:Ih,defaultEdgeOptions:Ch,fitView:$o,fitViewOptions:Fo,onNodesDelete:P,onEdgesDelete:_,onDelete:M,onNodeDragStart:R,onNodeDrag:A,onNodeDragStop:k,onSelectionDrag:w,onSelectionDragStart:b,onSelectionDragStop:T,onMove:u,onMoveStart:d,onMoveEnd:f,noPanClassName:Do,nodeOrigin:ie,rfId:Wr,autoPanOnConnect:_h,autoPanOnNodeDrag:Th,autoPanSpeed:Mh,onError:jh,connectionRadius:kh,isValidConnection:Oh,selectNodesOnDrag:V,nodeDragThreshold:Lh,connectionDragThreshold:Dh,onBeforeDelete:F,debug:Gh,ariaLabelConfig:Uh,zIndexMode:Go}),(0,h.jsx)(Sw,{onInit:c,onNodeClick:a,onEdgeClick:l,onNodeMouseEnter:I,onNodeMouseMove:m,onNodeMouseLeave:S,onNodeContextMenu:E,onNodeDoubleClick:N,nodeTypes:o,edgeTypes:i,connectionLineType:B,connectionLineStyle:K,connectionLineComponent:H,connectionLineContainerStyle:W,selectionKeyCode:X,selectionOnDrag:$,selectionMode:q,deleteKeyCode:J,multiSelectionKeyCode:te,panActivationKeyCode:Q,zoomActivationKeyCode:G,onlyRenderVisibleElements:U,defaultViewport:ke,translateExtent:pt,minZoom:Ye,maxZoom:We,preventScrolling:Kr,zoomOnScroll:Kd,zoomOnPinch:Yd,zoomOnDoubleClick:Jd,panOnScroll:Wd,panOnScrollSpeed:Xd,panOnScrollMode:Qd,panOnDrag:Zd,autoPanOnSelection:Ah,onPaneClick:eh,onPaneMouseEnter:th,onPaneMouseMove:nh,onPaneMouseLeave:rh,onPaneScroll:sh,onPaneContextMenu:oh,paneClickDistance:ih,nodeClickDistance:ah,onSelectionContextMenu:j,onSelectionStart:D,onSelectionEnd:L,onReconnect:ch,onReconnectStart:uh,onReconnectEnd:dh,onEdgeContextMenu:hh,onEdgeDoubleClick:fh,onEdgeMouseEnter:ph,onEdgeMouseMove:gh,onEdgeMouseLeave:mh,reconnectRadius:vh,defaultMarkerColor:Vd,noDragClassName:xh,noWheelClassName:Sh,noPanClassName:Do,rfId:Wr,disableKeyboardA11y:zo,nodeExtent:Yr,viewport:$h,onViewportChange:Fh,nodesDraggable:pe}),(0,h.jsx)(QS,{onSelectionChange:O}),lh,(0,h.jsx)(VS,{proOptions:Eh,position:wh}),(0,h.jsx)(qS,{rfId:Wr,disableKeyboardA11y:zo})]})})}var Rw=Ou(Nw);function _w(e){const[t,n]=(0,C.useState)(e);return[t,n,(0,C.useCallback)(r=>n(s=>ku(r,s)),[])]}var Tw=e=>t=>{if(!e.includeHiddenNodes)return t.nodesInitialized;if(t.nodeLookup.size===0)return!1;for(const[,{internals:n}]of t.nodeLookup)if(n.handleBounds===void 0||!wo(n.userNode))return!1;return!0};function Aw(e={includeHiddenNodes:!1}){return re(Tw(e))}var G_=Te.error014();function Mw({dimensions:e,lineWidth:t,variant:n,className:r}){return(0,h.jsx)("path",{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:ue(["react-flow__background-pattern",n,r])})}function kw({radius:e,className:t}){return(0,h.jsx)("circle",{cx:e,cy:e,r:e,className:ue(["react-flow__background-pattern","dots",t])})}var tt;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(tt||(tt={}));var Ow={[tt.Dots]:1,[tt.Lines]:1,[tt.Cross]:6},jw=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function id({id:e,variant:t=tt.Dots,gap:n=20,size:r,lineWidth:s=1,offset:o=0,color:i,bgColor:a,style:l,className:c,patternClassName:u}){const d=(0,C.useRef)(null),{transform:f,patternId:g}=re(jw,le),p=r||Ow[t],y=t===tt.Dots,x=t===tt.Cross,v=Array.isArray(n)?n:[n,n],I=[v[0]*f[2]||1,v[1]*f[2]||1],m=p*f[2],S=Array.isArray(o)?o:[o,o],E=x?[m,m]:I,N=[S[0]*f[2]+E[0]/2,S[1]*f[2]+E[1]/2],R=`${g}${e||""}`;return(0,h.jsxs)("svg",{className:ue(["react-flow__background",c]),style:{...l,...Hr,"--xy-background-color-props":a,"--xy-background-pattern-color-props":i},ref:d,"data-testid":"rf__background",children:[(0,h.jsx)("pattern",{id:R,x:f[0]%I[0],y:f[1]%I[1],width:I[0],height:I[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${N[0]},-${N[1]})`,children:y?(0,h.jsx)(kw,{radius:m/2,className:u}):(0,h.jsx)(Mw,{dimensions:E,lineWidth:s,variant:t,className:u})}),(0,h.jsx)("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${R})`})]})}id.displayName="Background";var Pw=(0,C.memo)(id);function Lw(){return(0,h.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",children:(0,h.jsx)("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"})})}function Dw(){return(0,h.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5",children:(0,h.jsx)("path",{d:"M0 0h32v4.2H0z"})})}function $w(){return(0,h.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30",children:(0,h.jsx)("path",{d:"M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z"})})}function Fw(){return(0,h.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:(0,h.jsx)("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z"})})}function zw(){return(0,h.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:(0,h.jsx)("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z"})})}function fn({children:e,className:t,...n}){return(0,h.jsx)("button",{type:"button",className:ue(["react-flow__controls-button",t]),...n,children:e})}var Hw=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function ad({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:s,onZoomIn:o,onZoomOut:i,onFitView:a,onInteractiveChange:l,className:c,children:u,position:d="bottom-left",orientation:f="vertical","aria-label":g}){const p=oe(),{isInteractive:y,minZoomReached:x,maxZoomReached:v,ariaLabelConfig:I}=re(Hw,le),{zoomIn:m,zoomOut:S,fitView:E}=zr(),N=()=>{m(),o?.()},R=()=>{S(),i?.()},A=()=>{E(s),a?.()},k=()=>{p.setState({nodesDraggable:!y,nodesConnectable:!y,elementsSelectable:!y}),l?.(!y)};return(0,h.jsxs)(Fr,{className:ue(["react-flow__controls",f==="horizontal"?"horizontal":"vertical",c]),position:d,style:e,"data-testid":"rf__controls","aria-label":g??I["controls.ariaLabel"],children:[t&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(fn,{onClick:N,className:"react-flow__controls-zoomin",title:I["controls.zoomIn.ariaLabel"],"aria-label":I["controls.zoomIn.ariaLabel"],disabled:v,children:(0,h.jsx)(Lw,{})}),(0,h.jsx)(fn,{onClick:R,className:"react-flow__controls-zoomout",title:I["controls.zoomOut.ariaLabel"],"aria-label":I["controls.zoomOut.ariaLabel"],disabled:x,children:(0,h.jsx)(Dw,{})})]}),n&&(0,h.jsx)(fn,{className:"react-flow__controls-fitview",onClick:A,title:I["controls.fitView.ariaLabel"],"aria-label":I["controls.fitView.ariaLabel"],children:(0,h.jsx)($w,{})}),r&&(0,h.jsx)(fn,{className:"react-flow__controls-interactive",onClick:k,title:I["controls.interactive.ariaLabel"],"aria-label":I["controls.interactive.ariaLabel"],children:y?(0,h.jsx)(zw,{}):(0,h.jsx)(Fw,{})}),u]})}ad.displayName="Controls";var Bw=(0,C.memo)(ad);function Gw({id:e,x:t,y:n,width:r,height:s,style:o,color:i,strokeColor:a,strokeWidth:l,className:c,borderRadius:u,shapeRendering:d,selected:f,onClick:g}){const{background:p,backgroundColor:y}=o||{},x=i||p||y;return(0,h.jsx)("rect",{className:ue(["react-flow__minimap-node",{selected:f},c]),x:t,y:n,rx:u,ry:u,width:r,height:s,style:{fill:x,stroke:a,strokeWidth:l},shapeRendering:d,onClick:g?v=>g(v,e):void 0})}var Uw=(0,C.memo)(Gw),qw=e=>e.nodes.map(t=>t.id),hs=e=>e instanceof Function?e:()=>e;function Vw({nodeStrokeColor:e,nodeColor:t,nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:s,nodeComponent:o=Uw,onClick:i}){const a=re(qw,le),l=hs(t),c=hs(e),u=hs(n),d=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return(0,h.jsx)(h.Fragment,{children:a.map(f=>(0,h.jsx)(Yw,{id:f,nodeColorFunc:l,nodeStrokeColorFunc:c,nodeClassNameFunc:u,nodeBorderRadius:r,nodeStrokeWidth:s,NodeComponent:o,onClick:i,shapeRendering:d},f))})}function Kw({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:r,nodeBorderRadius:s,nodeStrokeWidth:o,shapeRendering:i,NodeComponent:a,onClick:l}){const{node:c,x:u,y:d,width:f,height:g}=re(p=>{const y=p.nodeLookup.get(e);if(!y)return{node:void 0,x:0,y:0,width:0,height:0};const x=y.internals.userNode,{x:v,y:I}=y.internals.positionAbsolute,{width:m,height:S}=Fe(x);return{node:x,x:v,y:I,width:m,height:S}},le);return!c||c.hidden||!wo(c)?null:(0,h.jsx)(a,{x:u,y:d,width:f,height:g,style:c.style,selected:!!c.selected,className:r(c),color:t(c),borderRadius:s,strokeColor:n(c),strokeWidth:o,shapeRendering:i,onClick:l,id:c.id})}var Yw=(0,C.memo)(Kw),Ww=(0,C.memo)(Vw),Xw=200,Qw=150,Jw=e=>!e.hidden,Zw=e=>{const t={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]};let n=!1;for(const r of e.nodeLookup.values())if(!r.hidden){n=!0;break}return{viewBB:t,boundingRect:n?ru(On(e.nodeLookup,{filter:Jw}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}},Ca=(e,t)=>e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height,eE=(e,t)=>Ca(e.viewBB,t.viewBB)&&Ca(e.boundingRect,t.boundingRect)&&e.rfId===t.rfId&&e.panZoom===t.panZoom&&e.translateExtent===t.translateExtent&&e.flowWidth===t.flowWidth&&e.flowHeight===t.flowHeight&&e.ariaLabelConfig===t.ariaLabelConfig,tE="react-flow__minimap-desc";function ld({style:e,className:t,nodeStrokeColor:n,nodeColor:r,nodeClassName:s="",nodeBorderRadius:o=5,nodeStrokeWidth:i,nodeComponent:a,bgColor:l,maskColor:c,maskStrokeColor:u,maskStrokeWidth:d,position:f="bottom-right",onClick:g,onNodeClick:p,pannable:y=!1,zoomable:x=!1,ariaLabel:v,inversePan:I,zoomStep:m=1,offsetScale:S=5}){const E=oe(),N=(0,C.useRef)(null),{boundingRect:R,panZoom:A,viewBB:k,rfId:P,translateExtent:_,flowWidth:M,flowHeight:O,ariaLabelConfig:b}=re(Zw,eE),w=e?.width??Xw,T=e?.height??Qw,j=R.width/w,D=R.height/T,L=Math.max(j,D),F=L*w,z=L*T,B=S*L,K=R.x-(F-R.width)/2-B,H=R.y-(z-R.height)/2-B,W=F+B*2,J=z+B*2,X=`${tE}-${P}`,$=(0,C.useRef)(0),q=(0,C.useRef)();$.current=L,(0,C.useEffect)(()=>{const Z=E.getState().panZoom;if(N.current&&Z)return q.current=bS({domNode:N.current,panZoom:Z,getTransform:()=>E.getState().transform,getViewScale:()=>$.current}),()=>{q.current?.destroy()}},[A]),(0,C.useEffect)(()=>{q.current?.update({translateExtent:_,width:M,height:O,inversePan:I,pannable:y,zoomStep:m,zoomable:x})},[y,x,I,m,_,M,O]);const Q=g?Z=>{const[U,V]=q.current?.pointer(Z)||[0,0];g(Z,{x:U,y:V})}:void 0,te=(0,C.useCallback)((Z,U)=>{const V=E.getState().nodeLookup.get(U).internals.userNode;p?.(Z,V)},[p]),G=p?te:void 0,ne=v??b["minimap.ariaLabel"];return(0,h.jsx)(Fr,{position:f,style:{...e,"--xy-minimap-background-color-props":typeof l=="string"?l:void 0,"--xy-minimap-mask-background-color-props":typeof c=="string"?c:void 0,"--xy-minimap-mask-stroke-color-props":typeof u=="string"?u:void 0,"--xy-minimap-mask-stroke-width-props":typeof d=="number"?d*L:void 0,"--xy-minimap-node-background-color-props":typeof r=="string"?r:void 0,"--xy-minimap-node-stroke-color-props":typeof n=="string"?n:void 0,"--xy-minimap-node-stroke-width-props":typeof i=="number"?i:void 0},className:ue(["react-flow__minimap",t]),"data-testid":"rf__minimap",children:(0,h.jsxs)("svg",{width:w,height:T,viewBox:`${K} ${H} ${W} ${J}`,className:"react-flow__minimap-svg",role:"img","aria-labelledby":X,ref:N,onClick:Q,children:[ne&&(0,h.jsx)("title",{id:X,children:ne}),(0,h.jsx)(Ww,{onClick:G,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:o,nodeClassName:s,nodeStrokeWidth:i,nodeComponent:a}),(0,h.jsx)("path",{className:"react-flow__minimap-mask",d:`M${K-B},${H-B}h${W+B*2}v${J+B*2}h${-W-B*2}z
|
|
8
|
+
M${k.x},${k.y}h${k.width}v${k.height}h${-k.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}ld.displayName="MiniMap";var nE=(0,C.memo)(ld),rE=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,sE={[Jt.Line]:"right",[Jt.Handle]:"bottom-right"};function oE({nodeId:e,position:t,variant:n=Jt.Handle,className:r,style:s=void 0,children:o,color:i,minWidth:a=10,minHeight:l=10,maxWidth:c=Number.MAX_VALUE,maxHeight:u=Number.MAX_VALUE,keepAspectRatio:d=!1,resizeDirection:f,autoScale:g=!0,shouldResize:p,onResizeStart:y,onResize:x,onResizeEnd:v}){const I=$u(),m=typeof e=="string"?e:I,S=oe(),E=(0,C.useRef)(null),N=n===Jt.Handle,R=re((0,C.useCallback)(rE(N&&g),[N,g]),le),A=(0,C.useRef)(null),k=t??sE[n];(0,C.useEffect)(()=>{if(!(!E.current||!m))return A.current||(A.current=kS({domNode:E.current,nodeId:m,getStoreItems:()=>{const{nodeLookup:_,transform:M,snapGrid:O,snapToGrid:b,nodeOrigin:w,domNode:T}=S.getState();return{nodeLookup:_,transform:M,snapGrid:O,snapToGrid:b,nodeOrigin:w,paneDomNode:T}},onChange:(_,M)=>{const{triggerNodeChanges:O,nodeLookup:b,parentLookup:w,nodeOrigin:T}=S.getState(),j=[],D={x:_.x,y:_.y},L=b.get(m);if(L&&L.expandParent&&L.parentId){const F=L.origin??T,z=_.width??L.measured.width??0,B=_.height??L.measured.height??0,K={id:L.id,parentId:L.parentId,rect:{width:z,height:B,...iu({x:_.x??L.position.x,y:_.y??L.position.y},{width:z,height:B},L.parentId,b,F)}},H=To([K],b,w,T);j.push(...H),D.x=_.x?Math.max(F[0]*z,_.x):void 0,D.y=_.y?Math.max(F[1]*B,_.y):void 0}if(D.x!==void 0&&D.y!==void 0){const F={id:m,type:"position",position:{...D}};j.push(F)}if(_.width!==void 0&&_.height!==void 0){const F={id:m,type:"dimensions",resizing:!0,setAttributes:f?f==="horizontal"?"width":"height":!0,dimensions:{width:_.width,height:_.height}};j.push(F)}for(const F of M){const z={...F,type:"position"};j.push(z)}O(j)},onEnd:({width:_,height:M})=>{const O={id:m,type:"dimensions",resizing:!1,dimensions:{width:_,height:M}};S.getState().triggerNodeChanges([O])}})),A.current.update({controlPosition:k,boundaries:{minWidth:a,minHeight:l,maxWidth:c,maxHeight:u},keepAspectRatio:d,resizeDirection:f,onResizeStart:y,onResize:x,onResizeEnd:v,shouldResize:p}),()=>{A.current?.destroy()}},[k,a,l,c,u,d,y,x,v,p]);const P=k.split("-");return(0,h.jsx)("div",{className:ue(["react-flow__resize-control","nodrag",...P,n,r]),ref:E,style:{...s,scale:R,...i&&{[N?"backgroundColor":"borderColor"]:i}},children:o})}var U_=(0,C.memo)(oE),iE=()=>(0,h.jsxs)("div",{className:"absolute bottom-3 left-3 z-10 flex items-center gap-3 rounded-md border bg-card/95 px-3 py-2 text-xs text-muted-foreground shadow-sm",children:[(0,h.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,h.jsx)(Zs,{className:"size-3.5 text-amber-500"})," Primary key"]}),(0,h.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,h.jsx)(El,{className:"size-3.5 text-sky-500"})," Foreign key"]}),(0,h.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,h.jsx)(ws,{className:"size-3 fill-current"})," Required"]}),(0,h.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,h.jsx)(ws,{className:"size-3"})," Nullable"]})]});var aE=({column:e})=>(0,h.jsxs)("span",{className:"flex w-8 shrink-0 items-center gap-1",children:[e.isPrimaryKey?(0,h.jsx)(Zs,{"aria-label":"Primary key",className:"size-3.5 text-amber-500"}):e.isForeignKey?(0,h.jsx)(El,{"aria-label":"Foreign key",className:"size-3.5 text-sky-500"}):(0,h.jsx)("span",{className:"size-3.5"}),(0,h.jsx)(ws,{"aria-label":e.isNullable?"Nullable":"Required",className:me("size-3 text-muted-foreground",!e.isNullable&&"fill-current")})]}),Na="size-1! min-h-0! min-w-0! border-0! bg-transparent!",lE=({data:e})=>{const{table:t,active:n,dimmed:r,highlightedColumns:s}=e;return(0,h.jsxs)("div",{"data-active":n||void 0,"data-dimmed":r||void 0,className:me("group overflow-hidden rounded-md border bg-card text-card-foreground shadow-sm transition-opacity",n&&"border-primary ring-2 ring-primary/30",r&&"opacity-25"),children:[(0,h.jsxs)("div",{className:"flex items-center gap-2 border-b bg-muted/60 px-3 text-sm font-medium",style:{height:36},children:[(0,h.jsx)(Es,{className:"size-4 shrink-0 text-muted-foreground"}),(0,h.jsxs)("span",{className:"flex-1 truncate",children:[t.schemaName&&t.schemaName!=="public"&&(0,h.jsxs)("span",{className:"text-muted-foreground",children:[t.schemaName,"."]}),t.tableName]}),(0,h.jsx)(Er,{to:"/table/$table",params:{table:t.tableName},"aria-label":`Open ${t.tableName}`,title:"Open table",className:"nodrag rounded p-0.5 text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100",onClick:o=>o.stopPropagation(),children:(0,h.jsx)(gf,{className:"size-4"})})]}),t.columns.map(o=>(0,h.jsxs)("div",{className:me("relative flex items-center gap-2 px-3 text-xs",s.has(`${t.id}.${o.columnName}`)&&"bg-primary/10"),style:{height:28},children:[(0,h.jsx)(Zt,{type:"target",position:Y.Left,id:`${o.columnName}-l`,isConnectable:!1,className:Na}),(0,h.jsx)(aE,{column:o}),(0,h.jsx)("span",{className:"truncate font-mono",children:o.columnName}),(0,h.jsx)("span",{className:"ml-auto shrink-0 font-mono text-muted-foreground",children:o.dataTypeLabel}),(0,h.jsx)(Zt,{type:"source",position:Y.Right,id:`${o.columnName}-r`,isConnectable:!1,className:Na})]},o.columnName))]})},cE={table:lE},uE=({tables:e,edges:t})=>{const n=e.map(s=>({id:s.id,width:J0(s),height:36+s.columns.length*28+2})),r=X0(n,t);return e.map((s,o)=>({id:s.id,type:"table",position:r.get(s.id)??{x:0,y:0},width:n[o].width,data:{table:s,active:!1,dimmed:!1,highlightedColumns:new Set}}))},dE=(e,t,n)=>({id:e.id,source:e.target,sourceHandle:`${e.targetColumn}-r`,target:e.source,targetHandle:`${e.sourceColumn}-l`,type:"smoothstep",animated:t,zIndex:t?1:0,style:{stroke:t?"var(--primary)":"var(--muted-foreground)",strokeWidth:t?2:1.25,opacity:n?.15:t?1:.55}}),hE=({tables:e,edges:t})=>{const{isDark:n}=so(),r=Js(),{fitView:s}=zr(),o=Aw(),[i,a]=_l(bt.ACTIVE_TABLE,{defaultValue:""}),[l,c]=(0,C.useState)(null),u=(0,C.useMemo)(()=>uE({tables:e,edges:t}),[e,t]),[d,f,g]=_w(u),p=(0,C.useRef)(!1);(0,C.useEffect)(()=>{f(u),p.current=!1},[u,f]);const y=(0,C.useRef)(!1);(0,C.useEffect)(()=>{o&&(i&&!y.current?s({nodes:[{id:i}],duration:400,maxZoom:1.1}):p.current||s(),p.current=!0,y.current=!1)},[i,o,s]);const x=E=>{y.current=!0,a(E||null)},v=l??(i||null),I=v?Q0(t,v):null,m=d.map(E=>({...E,data:{...E.data,active:E.id===i,dimmed:I!==null&&!I.tables.has(E.id),highlightedColumns:I?.columns??new Set}})),S=t.map(E=>{const N=I?.edgeIds.has(E.id)??!1;return dE(E,N,I!==null&&!N)});return(0,h.jsxs)(Rw,{nodes:m,edges:S,nodeTypes:cE,onNodesChange:g,onNodeMouseEnter:(E,N)=>c(N.id),onNodeMouseLeave:()=>c(null),onNodeClick:(E,N)=>x(N.id===i?"":N.id),onNodeDoubleClick:(E,N)=>{r({to:"/table/$table",params:{table:N.data.table.tableName},search:{[bt.TABLE_SCHEMA]:N.data.table.schemaName}})},onPaneClick:()=>x(""),nodesConnectable:!1,colorMode:n?"dark":"light",minZoom:.1,maxZoom:2,proOptions:{hideAttribution:!0},className:"bg-background!",children:[(0,h.jsx)(Pw,{variant:tt.Dots,gap:18,size:1.5}),(0,h.jsx)(Bw,{position:"top-right",showInteractive:!1,children:(0,h.jsx)(fn,{title:"Reset layout","aria-label":"Reset layout",onClick:()=>{f(u),s({duration:300})},children:(0,h.jsx)(yf,{})})}),(0,h.jsx)(nE,{pannable:!0,zoomable:!0}),(0,h.jsx)(iE,{})]})},fE=e=>(0,h.jsx)(od,{children:(0,h.jsx)(hE,{...e})}),pE=()=>{const{selectedDatabase:e}=ht(),[t]=_l(bt.ACTIVE_SCHEMA,{defaultValue:"all"}),{data:n,isLoading:r,error:s}=zt({queryKey:Ns.graph(e),queryFn:()=>_p(e),select:o=>o.data.data,enabled:!!e});return{...(0,C.useMemo)(()=>W0(n??[],t),[n,t]),isLoading:r,error:s}},q_=()=>{const{tables:e,edges:t,isLoading:n,error:r}=pE();return n?(0,h.jsx)("div",{className:"flex h-full items-center justify-center",children:(0,h.jsx)(to,{size:"size-6"})}):r?(0,h.jsxs)("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:["Couldn't load the schema: ",r.message]}):e.length===0?(0,h.jsx)("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"This database has no tables yet."}):(0,h.jsxs)("div",{className:"relative h-full w-full",children:[(0,h.jsx)(fE,{tables:e,edges:t}),t.length===0&&(0,h.jsx)("p",{className:"pointer-events-none absolute top-3 left-1/2 z-10 -translate-x-1/2 rounded-md border bg-card px-3 py-1.5 text-xs text-muted-foreground shadow-sm",children:"This database has no foreign keys."})]})},Ra="Select a table first",gE="Not available for schemaless databases",mE=()=>{const{pathname:e}=Il(),t=Zh({strict:!1}).table??null,{dbType:n}=ht(),r=Vp(),s=dp(),o=e.startsWith("/table/"),i=e.startsWith("/schema/");return{pathname:e,activeTable:t,dbType:n,isKeyValue:r?.dataModel==="key-value",isSchemaless:s,canCreateTable:!s,canEditRecords:!!t&&o,recordsHint:t?"Open the table data screen first":Ra,hasIndexes:!!r?.indexes,canEditSchema:!!t&&i&&!s,schemaHint:s?gE:t?"Open the table schema screen first":Ra}},vE=()=>{const{openOverlay:e,closeOverlay:t,isOverlayOpen:n}=ut(),[r,s]=(0,C.useState)("all"),[o,i]=(0,C.useState)(""),a=(0,C.useRef)(null),l=n("command-palette.root"),c=(0,C.useCallback)(y=>{if(y){e("command-palette.root");return}t("command-palette.root"),s("all"),i("")},[e,t]),u=(0,C.useCallback)(y=>{c(!1),y()},[c]),d=(0,C.useCallback)(()=>{s("tables"),i(""),setTimeout(()=>a.current?.focus(),0)},[]),f=(0,C.useCallback)(()=>{s("all"),i(""),setTimeout(()=>a.current?.focus(),0)},[]),g=(0,C.useCallback)(y=>{if(r==="all"&&y.startsWith(">")){d(),i(y.slice(1));return}if(r==="all"&&(y.toLowerCase()==="table "||y.toLowerCase()==="tables ")){d();return}i(y)},[r,d]),p=(0,C.useCallback)(y=>{y.key==="Backspace"&&o===""&&r==="tables"&&(y.preventDefault(),f())},[o,r,f]);return $l("ctrl+k, meta+k",y=>{y.target?.closest?.(".monaco-editor")||(y.preventDefault(),c(!ut.getState().isOverlayOpen("command-palette.root")))},{enableOnFormTags:!0,enableOnContentEditable:!0}),{open:l,mode:r,inputValue:o,inputRef:a,handleOpenChange:c,handleAction:u,handleInputChange:g,handleKeyDown:p,switchToAllMode:f,switchToTablesMode:d}};function yE(){const e=Js(),t=gp(),{openOverlay:n}=ut(),{toggleSidebarOpen:r,toggleSidebarPinned:s,sidebar:o}=ql(),{toggleTheme:i,isDark:a}=so(),{tablesList:l,isLoadingTablesList:c,errorTablesList:u}=Fl(),{exportFile:d,isExportingFile:f}=yp(),{copyTableSchema:g,isCopyingSchema:p}=dg(),{requestAssistant:y}=ug(),{open:x,mode:v,inputValue:I,inputRef:m,handleOpenChange:S,handleAction:E,handleInputChange:N,handleKeyDown:R,switchToAllMode:A,switchToTablesMode:k}=vE(),{pathname:P,activeTable:_,dbType:M,isKeyValue:O,isSchemaless:b,canCreateTable:w,canEditRecords:T,recordsHint:j,canEditSchema:D,schemaHint:L,hasIndexes:F}=mE(),z=typeof navigator<"u"&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),B=(H,W)=>{E(()=>{M&&Nr.capture("table_viewed",{db_type:M}),e({to:"/table/$table",params:{table:H},search:{[bt.TABLE_SCHEMA]:W}})})},K=H=>{E(()=>{y(H),n("chat.assistant")})};return(0,h.jsxs)(tp,{open:x,onOpenChange:S,className:"sm:max-w-lg",children:[(0,h.jsxs)("div",{className:"flex items-center border-b border-input px-2 gap-2 w-full",children:[v==="tables"&&(0,h.jsxs)("button",{type:"button",onClick:A,"aria-label":"Back to all commands",className:"flex items-center gap-1.5 h-8! rounded-md bg-primary/10 px-2.5 py-1 text-xs font-medium text-primary transition-colors hover:bg-primary/20 shrink-0",children:[(0,h.jsx)(Es,{className:"size-3.5"}),(0,h.jsx)("span",{children:"Tables"}),(0,h.jsx)(Lf,{className:"size-3 opacity-60"})]}),(0,h.jsx)(Dl,{ref:m,placeholder:v==="all"?"Search commands... (type > for tables)":"Search tables...",value:I,onValueChange:N,onKeyDown:R,className:"border-0 px-0"})]}),(0,h.jsxs)(kl,{children:[(0,h.jsx)(Ml,{children:v==="tables"?"No tables found.":"No results found."}),v==="tables"&&!c&&!u&&l&&(0,h.jsx)(it,{heading:"Tables",children:l.length===0?(0,h.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No tables in database"}):l.map(H=>(0,h.jsxs)(se,{value:un(H),onSelect:()=>B(H.tableName,H.schemaName),children:[(0,h.jsx)(Xr,{className:"mr-2 size-4 text-primary"}),(0,h.jsxs)("div",{className:"flex flex-1 items-center justify-between",children:[(0,h.jsx)("span",{className:"font-medium",children:H.tableName}),(0,h.jsxs)("span",{className:"text-xs text-muted-foreground",children:[H.rowCountEstimated&&"~",H.rowCount," ",H.rowCount===1?"row":"rows"]})]})]},un(H)))}),v==="tables"&&c&&(0,h.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Loading tables..."}),v==="tables"&&u&&(0,h.jsx)("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Failed to load tables."}),v==="all"&&(0,h.jsxs)(h.Fragment,{children:[!O&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(it,{heading:"Quick Access",children:(0,h.jsxs)(se,{onSelect:k,keywords:["tables",">","go to table"],className:"group",children:[(0,h.jsx)(Cl,{className:"mr-2 size-4 text-primary"}),(0,h.jsxs)("div",{className:"flex flex-1 items-center justify-between",children:[(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Search Tables"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:"Navigate to any table quickly"})]}),(0,h.jsx)(op,{children:">"})]})]})}),(0,h.jsx)(rn,{})]}),(0,h.jsxs)(it,{heading:"Go to",children:[!O&&(0,h.jsxs)(se,{onSelect:()=>E(()=>e({to:"/"})),keywords:["go","navigate","home","tables"],children:[(0,h.jsx)(Es,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Go to Tables"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:"Open the tables overview"})]})]}),(0,h.jsxs)(se,{onSelect:()=>E(()=>e({to:"/runner"})),keywords:["go","navigate","sql","query","runner","editor"],children:[(0,h.jsx)(wf,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Go to Query Runner"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:"Write and execute queries"})]})]}),!O&&(0,h.jsxs)(se,{disabled:!_||b,onSelect:()=>{if(!_||b)return;const H=_;E(()=>e({to:"/schema/$table",params:{table:H},search:{[bt.TABLE_SCHEMA]:t}}))},keywords:["go","navigate","schema","columns"],children:[(0,h.jsx)(xf,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Go to Schema"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:b?"Not available for schemaless databases":_?`View the schema of ${_}`:"Select a table first"})]})]}),F&&(0,h.jsxs)(se,{disabled:!_,onSelect:()=>{if(!_)return;const H=_;E(()=>e({to:"/indexes/$table",params:{table:H},search:{[bt.TABLE_SCHEMA]:t}}))},keywords:["go","navigate","indexes","index"],children:[(0,h.jsx)(qo,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Go to Indexes"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:_?`View the indexes of ${_}`:"Select a table first"})]})]}),O&&(0,h.jsxs)(se,{onSelect:()=>E(()=>e({to:"/browser"})),keywords:["go","navigate","redis","browser","keys"],children:[(0,h.jsx)(Xr,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Go to Redis Browser"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:"Browse keys across logical databases"})]})]})]}),(0,h.jsx)(rn,{}),(0,h.jsxs)(it,{heading:"AI Assistant",children:[(0,h.jsxs)(se,{onSelect:()=>E(()=>n("chat.assistant")),keywords:["ai","assistant","chat","help"],children:[(0,h.jsx)(uf,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Chat with AI Assistant"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:"Ask questions about your database"})]})]}),(0,h.jsxs)(se,{onSelect:()=>K("Generate a query for this database. Ask me for the goal if it is unclear."),keywords:["ai","generate","sql","query","write"],children:[(0,h.jsx)(Of,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Generate SQL with AI"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:"Create queries using natural language"})]})]}),(0,h.jsxs)(se,{disabled:!_||b,onSelect:()=>{!_||b||K(`Explain the schema of table "${_}": what each column stores and how it relates to other tables.`)},keywords:["ai","explain","schema","table","understand"],children:[(0,h.jsx)(lf,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Explain Table Schema"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:b?"Not available for schemaless databases":_?`Understand the structure of ${_} with AI`:"Select a table first"})]})]})]}),(0,h.jsx)(rn,{}),(0,h.jsxs)(it,{heading:"Database Actions",children:[w&&(0,h.jsxs)(se,{onSelect:()=>E(()=>n("table-builder.create-table")),keywords:["create","new","table"],children:[(0,h.jsx)(Vo,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Create New Table"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:"Design and create a new database table"})]})]}),O&&(0,h.jsxs)(se,{onSelect:()=>E(()=>{P.startsWith("/browser")||e({to:"/browser"}),n("redis-browser.create-key")}),keywords:["create","new","redis","key"],children:[(0,h.jsx)(Zs,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Create Redis Key"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:"Add a new key to the selected database"})]})]}),!O&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)(se,{disabled:!T,onSelect:()=>E(()=>n("records.add-record")),keywords:["add","new","row","record","insert"],children:[(0,h.jsx)(Vo,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Add New Row"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:T?`Insert a new record into ${_}`:j})]})]}),(0,h.jsxs)(se,{disabled:!T,onSelect:()=>E(()=>n("records.bulk-insert")),keywords:["bulk","insert","import","csv","excel","json"],children:[(0,h.jsx)(Ef,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Bulk Insert Records"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:T?`Import many records into ${_}`:j})]})]}),(0,h.jsxs)(se,{disabled:!D,onSelect:()=>E(()=>n("schema.add-column")),keywords:["add","new","column","schema"],children:[(0,h.jsx)(_f,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Add Column"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:D?`Add a column to ${_}`:L})]})]}),F&&(0,h.jsxs)(se,{disabled:!_,onSelect:()=>{if(!_)return;const H=_;E(()=>{P.startsWith("/indexes/")||e({to:"/indexes/$table",params:{table:H},search:{[bt.TABLE_SCHEMA]:t}}),n("indexes.create-index")})},keywords:["create","add","new","index","indexes"],children:[(0,h.jsx)(qo,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Create Index"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:_?`Create an index on ${_}`:"Select a table first"})]})]}),(0,h.jsxs)(se,{disabled:!_||f,onSelect:()=>{if(!_)return;const H=_;E(()=>{d({tableName:H,schemaName:t,format:"csv"}).catch(()=>{})})},keywords:["export","download","csv"],children:[(0,h.jsx)(Ko,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Export Table as CSV"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:_?`Download ${_} as a CSV file`:"Select a table first"})]})]}),(0,h.jsxs)(se,{disabled:!_||f,onSelect:()=>{if(!_)return;const H=_;E(()=>{d({tableName:H,schemaName:t,format:"json"}).catch(()=>{})})},keywords:["export","download","json"],children:[(0,h.jsx)(Ko,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Export Table as JSON"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:_?`Download ${_} as a JSON file`:"Select a table first"})]})]}),(0,h.jsxs)(se,{disabled:!_||p||b,onSelect:()=>{if(!_||b)return;const H=_;E(()=>{g(H,t).catch(()=>{})})},keywords:["copy","schema","ddl","clipboard"],children:[(0,h.jsx)(kf,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Copy Table Schema"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:b?"Not available for schemaless databases":_?`Copy the schema of ${_} to the clipboard`:"Select a table first"})]})]})]}),(0,h.jsxs)(se,{onSelect:()=>E(()=>{window.location.reload()}),keywords:["refresh","reload","restart"],children:[(0,h.jsx)(Pf,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Reload Application"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:"Reload all tables and data"})]})]})]}),(0,h.jsx)(rn,{}),(0,h.jsxs)(it,{heading:"View & Settings",children:[(0,h.jsxs)(se,{onSelect:()=>E(r),keywords:["sidebar","show","hide","toggle","view"],children:[(0,h.jsx)(Cf,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsxs)("span",{children:[o.isOpen?"Hide":"Show"," Sidebar"]}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:"Toggle sidebar visibility"})]})]}),(0,h.jsxs)(se,{onSelect:()=>E(s),keywords:["sidebar","pin","unpin"],children:[o.isPinned?(0,h.jsx)(Nf,{className:"mr-2 size-4"}):(0,h.jsx)(mf,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsxs)("span",{children:[o.isPinned?"Unpin":"Pin"," Sidebar"]}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:"Keep sidebar always visible"})]})]}),(0,h.jsxs)(se,{onSelect:()=>E(i),keywords:["theme","dark","light","mode","appearance"],children:[a?(0,h.jsx)(Rf,{className:"mr-2 size-4"}):(0,h.jsx)(vf,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsxs)("span",{children:["Switch to ",a?"Light":"Dark"," Mode"]}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:"Toggle the application theme"})]})]}),(0,h.jsxs)(se,{onSelect:()=>E(()=>n("settings.app")),keywords:["settings","preferences","configure","options"],children:[(0,h.jsx)(Df,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:"Settings & Preferences"}),(0,h.jsx)("span",{className:"text-xs text-muted-foreground",children:"Configure application settings"})]})]})]}),!O&&!c&&!u&&l&&l.length>0&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(rn,{}),(0,h.jsxs)(it,{heading:"Recent Tables",children:[l.slice(0,5).map(H=>(0,h.jsxs)(se,{value:un(H),keywords:["table","recent",H.tableName],onSelect:()=>B(H.tableName,H.schemaName),children:[(0,h.jsx)(Xr,{className:"mr-2 size-4"}),(0,h.jsxs)("div",{className:"flex flex-col",children:[(0,h.jsx)("span",{children:H.tableName}),(0,h.jsxs)("span",{className:"text-xs text-muted-foreground",children:[H.rowCountEstimated&&"~",H.rowCount," ",H.rowCount===1?"row":"rows"]})]})]},un(H))),l.length>5&&(0,h.jsx)(se,{onSelect:k,className:"text-muted-foreground",children:(0,h.jsxs)("span",{className:"text-xs",children:["+",l.length-5," more tables — press"," ",(0,h.jsx)(Je,{className:"rounded border bg-muted px-1 py-0.5 font-mono text-[10px]",children:">"})," ","to see all"]})})]})]})]})]}),(0,h.jsxs)("div",{"aria-hidden":"true",className:"flex items-center gap-3 border-t border-border px-3 py-2 text-[11px] text-muted-foreground",children:[(0,h.jsxs)("span",{className:"flex items-center gap-1",children:[(0,h.jsx)(Je,{children:"↑"}),(0,h.jsx)(Je,{children:"↓"})," to navigate"]}),(0,h.jsxs)("span",{className:"flex items-center gap-1",children:[(0,h.jsx)(Je,{children:"↵"})," to select"]}),(0,h.jsxs)("span",{className:"flex items-center gap-1",children:[(0,h.jsx)(Je,{children:"esc"})," to close"]}),(0,h.jsxs)("span",{className:"ml-auto flex items-center gap-1",children:[(0,h.jsx)(Je,{children:z?"⌘":"Ctrl"}),(0,h.jsx)(Je,{children:"K"})," to toggle"]})]})]})}var V_=()=>{const{setDbType:e,selectedDatabase:t,setSelectedDatabase:n}=ht(),{data:r,isLoading:s,error:o,refetch:i,isRefetching:a}=zt({queryKey:nr.list(),queryFn:Bl,select:l=>l.data.data,staleTime:3e5});return(0,C.useEffect)(()=>{r?.dbType&&(e(r.dbType),Hl(r.dbType)),!t&&r?.databases?.length&&n(r.databases[0]?.name??null)},[r?.dbType,r?.databases,t,e,n]),{databases:r?.databases,dbType:r?.dbType,isLoadingDatabases:s,databasesError:o,refetchDatabases:i,isRefetchingDatabases:a}},bE=()=>{const{selectedDatabase:e,setSelectedDatabase:t,setDbType:n}=ht(),r=(0,C.useRef)(!1),{data:s,isLoading:o,error:i}=zt({queryKey:nr.list(),queryFn:Bl,select:f=>f.data.data,staleTime:3e5}),{data:a,isLoading:l,error:c}=zt({queryKey:nr.current(),queryFn:async()=>{const f=await Cp();return n(f.data.data.dbType),Hl(f.data.data.dbType),!e&&f.data.data.db&&t(f.data.data.db),f.data.data},staleTime:3e5});(0,C.useEffect)(()=>{if(r.current||o||l)return;r.current=!0;const f=a?.db||s?.databases?.[0]?.name;f&&t(f)},[o,l,a?.db,s?.databases,t]);const u=o||l,d=r.current;return{currentDatabase:a,databases:s?.databases,isLoading:u,isInitialized:d,error:i||c}},xE=()=>{const{data:e,isLoading:t,error:n}=zt({queryKey:nr.connectionInfo(),queryFn:Np,select:r=>r.data.data,staleTime:3e5});return{connectionInfo:e,isLoadingConnectionInfo:t,connectionInfoError:n}},Ze=e=>typeof e.details=="string"&&e.details||e.message,$t,Ot=()=>{const{data:e,isLoading:t,error:n}=zt({queryKey:mn.state(),queryFn:async()=>{const r=(await Rp()).data.data;return $t===void 0&&($t=r.active?.connectionId??null,Gl($t)),r},refetchOnWindowFocus:!0,staleTime:0});return{connections:e?.connections??[],active:e?.active??null,isLoading:t,error:n}},cd=()=>{const e=Qs(),t=Js();return async n=>{$t=n.active?.connectionId??null,Gl($t),await e.cancelQueries({queryKey:mn.state()}),e.removeQueries({predicate:r=>r.queryKey[0]!==mn.state()[0]}),e.setQueryData(mn.state(),n),ht.setState({selectedDatabase:null,dbType:null}),vp.getState().clearUpdates(),xp.getState().clearRowDetails(),ut.getState().closeAllOverlays(),t({to:"/",search:{}})}},Gr=()=>{const e=cd(),{active:t}=Ot(),n=Ft({mutationFn:async i=>(await Ip(i)).data.data,onSuccess:e}),r=Ft({mutationFn:async({id:i})=>(await Sp(i)).data.data,onSuccess:e}),s=i=>he.promise(n.mutateAsync(i),{loading:"Connecting…",success:"Connected",error:a=>t?`${Ze(a)}. Still on the previous connection.`:Ze(a)}),o=i=>he.promise(r.mutateAsync(i),{loading:`Connecting to ${i.name}…`,success:`Connected to ${i.name}`,error:a=>t?`${Ze(a)}. Still on the previous connection.`:Ze(a)});return{connectUrl:s,isConnectingUrl:n.isPending,urlError:n.error?Ze(n.error):null,clearUrlError:n.reset,connectSaved:o}},SE=()=>{const{active:e,connections:t,isLoading:n}=Ot(),r=cd(),s=(0,C.useRef)(void 0),o=e?.connectionId??null;(0,C.useEffect)(()=>{if(n)return;const i=s.current;if(s.current=o,i===void 0||i===o||o===$t)return;r({connections:t,active:e});const a=t.find(l=>l.id===e?.id)?.name;he.info(a?`Connection changed to ${a}`:e?"The connection changed":"The connection was closed")},[n,o,t,e,r])},IE=6e4,ud=(e,t=Date.now())=>{const n=Math.round((t-e)/IE);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.round(n/60);return r<24?`${r}h ago`:`${Math.round(r/24)}d ago`},wE={red:"bg-red-500",orange:"bg-orange-500",amber:"bg-amber-400",green:"bg-emerald-500",teal:"bg-teal-500",blue:"bg-blue-500",violet:"bg-violet-500",pink:"bg-pink-500"},yr=({color:e,className:t})=>(0,h.jsx)("span",{"aria-hidden":!0,className:me("inline-block size-2.5 shrink-0 rounded-full",e?wE[e]:"border border-muted-foreground/50",t)}),EE=5,K_=({databasesCount:e})=>{const{connections:t,active:n}=Ot(),{connectSaved:r}=Gr(),{connectionInfo:s}=xE(),o=t.find(a=>a.id===n?.id),i=o?.name??(n?Ht[n.dbType].label:"Not connected");return(0,h.jsxs)(Ll,{children:[(0,h.jsx)(Pl,{asChild:!0,children:(0,h.jsxs)("button",{type:"button",title:n?Ht[n.dbType].label:void 0,className:"flex min-w-0 max-w-[55%] items-center gap-2 rounded-sm px-2 py-1.5 transition-colors hover:bg-muted/60 aria-expanded:bg-muted/60",children:[(0,h.jsx)(yr,{color:o?.color??null}),(0,h.jsx)("span",{className:"truncate text-xs font-medium",children:i}),o?.readOnly&&(0,h.jsx)(eo,{"aria-label":"Read-only",className:"size-3 shrink-0 text-muted-foreground"})]})}),(0,h.jsxs)(Ol,{align:"start",side:"top",sideOffset:6,className:"w-72 p-0",children:[s&&(0,h.jsx)("dl",{className:"space-y-1 border-b px-3 py-2.5 text-xs",children:[["Host",s.host?`${s.host}${s.port?`:${s.port}`:""}`:"Local file"],["User",s.user||"—"],["Databases",e]].map(([a,l])=>(0,h.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,h.jsx)("dt",{className:"text-muted-foreground",children:a}),(0,h.jsx)("dd",{className:"truncate font-mono",children:l})]},a))}),(0,h.jsxs)("div",{className:"p-1",children:[(0,h.jsx)("p",{className:"px-2 pb-1 pt-1.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground",children:"Switch connection"}),t.slice(0,EE).map(a=>{const l=a.id===n?.id;return(0,h.jsxs)(tr,{onSelect:()=>{l||r(a)},children:[(0,h.jsx)(yr,{color:a.color}),(0,h.jsx)("span",{className:"flex-1 truncate",children:a.name}),l?(0,h.jsx)(wl,{className:"size-3.5 text-emerald-500"}):(0,h.jsx)("span",{className:"text-[10px] text-muted-foreground",children:ud(a.lastUsedAt)})]},a.id)})]}),(0,h.jsx)(jl,{className:"my-0"}),(0,h.jsx)("div",{className:"p-1",children:(0,h.jsx)(tr,{asChild:!0,children:(0,h.jsxs)(Er,{to:"/connect",children:[(0,h.jsx)(Sf,{})," All connections…"]})})})]})]})},CE=()=>{const[e,t]=(0,C.useState)(""),{connectUrl:n,isConnectingUrl:r,urlError:s,clearUrlError:o}=Gr(),i=kp(e.trim().split("://")[0]?.toLowerCase()??"");return(0,h.jsxs)("form",{className:"space-y-1.5",onSubmit:a=>{a.preventDefault(),e.trim()&&n(e.trim())},children:[(0,h.jsxs)("div",{className:"flex h-8",children:[(0,h.jsxs)("div",{className:"relative h-full min-w-0 flex-1",children:[(0,h.jsx)(ro,{autoFocus:!0,variant:"outline",value:e,onChange:a=>{t(a.target.value),o()},placeholder:"postgres://user:password@localhost:5432/mydb",spellCheck:!1,autoComplete:"off","aria-label":"Connection URL","aria-invalid":!!s,"aria-describedby":"connect-url-hint",className:"h-full rounded-r-none pr-36 font-mono focus-visible:ring-inset"}),i&&(0,h.jsx)("span",{className:"pointer-events-none absolute right-2 top-1/2 -translate-y-1/2 text-[10px] uppercase text-muted-foreground",children:Ht[i].label})]}),(0,h.jsx)(ct,{type:"submit",disabled:!e.trim()||r,className:"h-full w-28 rounded-l-none bg-clip-border",children:r?(0,h.jsx)(to,{size:"size-3.5",color:"bg-primary-foreground"}):(0,h.jsxs)(h.Fragment,{children:["Connect",(0,h.jsx)(Je,{className:"border-0 bg-primary-foreground/15 text-primary-foreground",children:"↵"})]})})]}),(0,h.jsx)("p",{id:"connect-url-hint",role:s?"alert":void 0,className:me("text-xs",s?"text-destructive":"text-muted-foreground"),children:s??"The connection is tested first. Nothing changes if it fails."})]})},dd=e=>{const t=Qs(),{active:n}=Ot(),{connectSaved:r}=Gr(),s=d=>t.setQueryData(mn.state(),f=>f&&d(f)),o=Ft({mutationFn:async d=>(await Mp(e.id,d)).data.data,onSuccess:d=>s(f=>({...f,connections:f.connections.map(g=>g.id===d.id?d:g)}))}),i=Ft({mutationFn:async()=>(await Ep(e.id)).data.data,onSuccess:()=>s(d=>({connections:d.connections.filter(f=>f.id!==e.id),active:d.active?.id===e.id?{...d.active,id:null}:d.active}))});return{rename:d=>he.promise(o.mutateAsync({name:d}),{loading:"Renaming connection…",success:"Connection renamed",error:f=>Ze(f)||"Failed to rename connection"}),setColor:d=>he.promise(o.mutateAsync({color:d}),{error:f=>Ze(f)||"Failed to change the color"}),setReadOnly:d=>he.promise(o.mutateAsync({readOnly:d}).then(f=>{n?.id===f.id&&r(f)}),{error:f=>Ze(f)||"Failed to change read-only mode"}),remove:()=>he.promise(i.mutateAsync(),{loading:"Removing connection…",success:"Connection removed",error:d=>Ze(d)||"Failed to remove connection"})}},NE=({connection:e,onRename:t})=>{const{setColor:n,setReadOnly:r,remove:s}=dd(e),o=[null,...Op],i=(0,C.useRef)(!1);return(0,h.jsxs)(Ll,{children:[(0,h.jsx)(Pl,{asChild:!0,children:(0,h.jsx)(ct,{variant:"ghost",size:"icon-sm","aria-label":`Actions for ${e.name}`,onClick:a=>a.stopPropagation(),onKeyDown:a=>a.stopPropagation(),children:(0,h.jsx)(Af,{})})}),(0,h.jsxs)(Ol,{align:"end",onClick:a=>a.stopPropagation(),onCloseAutoFocus:a=>{i.current&&(i.current=!1,a.preventDefault(),t())},children:[(0,h.jsxs)(tr,{onSelect:()=>{i.current=!0},children:[(0,h.jsx)(af,{})," Rename"]}),(0,h.jsxs)(ap,{children:[(0,h.jsxs)(up,{children:[(0,h.jsx)(ff,{})," Color"]}),(0,h.jsx)(fp,{className:"flex items-center gap-1.5 p-2",children:o.map(a=>(0,h.jsx)("button",{type:"button","aria-label":a??"No color","aria-pressed":e.color===a,onClick:()=>n(a),className:me("grid size-5 place-items-center rounded-full",e.color===a&&"ring-2 ring-ring ring-offset-1 ring-offset-popover"),children:(0,h.jsx)(yr,{color:a,className:"size-3.5"})},a??"none"))})]}),Ht[e.dbType].readOnly&&(0,h.jsxs)(lp,{checked:e.readOnly,onCheckedChange:r,className:"whitespace-nowrap",children:[(0,h.jsx)(eo,{})," Read-only"]}),(0,h.jsx)(jl,{}),(0,h.jsxs)(tr,{variant:"destructive",onSelect:s,children:[(0,h.jsx)(If,{})," Delete"]})]})]})},RE=({connection:e,onDone:t})=>{const{rename:n}=dd(e),[r,s]=(0,C.useState)(e.name),o=(0,C.useRef)(!1),i=a=>{if(o.current)return;o.current=!0;const l=r.trim();a&&l&&l!==e.name&&n(l),t()};return(0,h.jsx)("input",{autoFocus:!0,"aria-label":"Connection name",value:r,maxLength:100,onChange:a=>s(a.target.value),onBlur:()=>i(!0),onClick:a=>a.stopPropagation(),onKeyDown:a=>{a.stopPropagation(),a.key==="Enter"&&i(!0),a.key==="Escape"&&i(!1)},className:"h-6 min-w-0 flex-1 rounded-sm border border-input bg-background px-1.5 text-sm outline-none focus:ring-2 focus:ring-ring/30"})},hd="grid grid-cols-[minmax(0,1.1fr)_minmax(0,2fr)_6.5rem_4.5rem_1.75rem] gap-3",_E=({connection:e,isActive:t})=>{const{connectSaved:n}=Gr(),[r,s]=(0,C.useState)(!1),o=()=>{r||n(e)};return(0,h.jsxs)("div",{role:"button",tabIndex:0,"aria-label":`Connect to ${e.name}`,onClick:o,onKeyDown:i=>{i.key==="Enter"&&i.target===i.currentTarget&&o()},className:me(hd,"group relative cursor-pointer items-center border-b px-3 py-1.5 text-sm outline-none last:border-b-0 hover:bg-muted/60 focus-visible:bg-muted/60",t&&"bg-muted/40"),children:[t&&(0,h.jsx)("span",{className:"absolute inset-y-0 left-0 w-1 bg-primary"}),(0,h.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,h.jsx)(yr,{color:e.color}),r?(0,h.jsx)(RE,{connection:e,onDone:()=>s(!1)}):(0,h.jsx)("span",{className:"truncate",children:e.name}),e.readOnly&&(0,h.jsx)(eo,{"aria-label":"Read-only",className:"size-3 shrink-0 text-muted-foreground"})]}),(0,h.jsx)("span",{className:"truncate font-mono text-xs text-muted-foreground",children:e.maskedUrl}),(0,h.jsx)("span",{title:Ht[e.dbType].label,className:"truncate text-xs text-muted-foreground",children:Ht[e.dbType].label}),(0,h.jsx)("span",{className:"text-right text-xs tabular-nums text-muted-foreground",children:t?"current":ud(e.lastUsedAt)}),(0,h.jsx)("div",{className:"flex justify-end opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100 has-[[data-state=open]]:opacity-100",children:(0,h.jsx)(NE,{connection:e,onRename:()=>s(!0)})})]})},TE=()=>{const{connections:e,active:t}=Ot(),n=(0,C.useRef)(null),[r,s]=(0,C.useState)("");$l("/",()=>n.current?.focus(),{preventDefault:!0});const o=r.trim().toLowerCase(),i=o?e.filter(a=>`${a.name} ${a.maskedUrl}`.toLowerCase().includes(o)):e;return e.length===0?(0,h.jsx)("p",{className:"rounded-sm border border-dashed px-3 py-6 text-center text-xs text-muted-foreground",children:"Connections you open are saved here."}):(0,h.jsxs)("div",{className:"overflow-hidden rounded-sm border",children:[(0,h.jsxs)("div",{className:"flex h-8 items-center border-b",children:[(0,h.jsxs)("div",{className:"relative h-full flex-1",children:[(0,h.jsx)(Cl,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"}),(0,h.jsx)("input",{ref:n,value:r,onChange:a=>s(a.target.value),placeholder:"Filter saved connections","aria-label":"Filter saved connections",className:"h-full w-full bg-transparent pl-8 pr-8 text-xs outline-none placeholder:text-muted-foreground"}),(0,h.jsx)(Je,{className:"absolute right-2 top-1/2 -translate-y-1/2",children:"/"})]}),(0,h.jsxs)("span",{className:"flex h-full items-center border-l px-3 text-xs text-muted-foreground",children:[e.length," saved"]})]}),(0,h.jsxs)("div",{className:me(hd,"h-8 items-center border-b bg-muted/40 px-3 text-xs text-muted-foreground"),children:[(0,h.jsx)("span",{children:"Name"}),(0,h.jsx)("span",{children:"URL"}),(0,h.jsx)("span",{children:"Engine"}),(0,h.jsx)("span",{className:"text-right",children:"Last used"}),(0,h.jsx)("span",{})]}),i.map(a=>(0,h.jsx)(_E,{connection:a,isActive:a.id===t?.id},a.id)),i.length===0&&(0,h.jsxs)("p",{className:"px-3 py-6 text-center text-xs text-muted-foreground",children:['No saved connection matches "',r,'".']})]})},Y_=()=>{const{active:e,connections:t}=Ot(),n=t.find(r=>r.id===e?.id)?.name;return(0,h.jsxs)("div",{className:"flex h-dvh flex-col bg-background text-foreground",children:[(0,h.jsxs)("header",{className:"flex h-8 shrink-0 items-center gap-2 border-b px-3 text-xs",children:[(0,h.jsx)("img",{src:"/favicon.png",alt:"",className:"size-4"}),(0,h.jsx)("span",{className:"font-medium",children:"DB Studio"}),(0,h.jsxs)("span",{className:"text-muted-foreground",children:["v","2.2.1"]}),e&&(0,h.jsxs)(Er,{to:"/",className:"ml-auto flex items-center gap-1.5 text-muted-foreground hover:text-foreground",children:[(0,h.jsx)(df,{className:"size-3.5"}),"Back to ",n??"the open connection"]})]}),(0,h.jsx)("main",{className:"flex-1 overflow-auto",children:(0,h.jsxs)("div",{className:"mx-auto w-full max-w-3xl space-y-8 px-6 pb-16 pt-[10vh]",children:[(0,h.jsxs)("div",{className:"space-y-3",children:[(0,h.jsxs)("div",{className:"space-y-1",children:[(0,h.jsx)("h1",{className:"text-sm font-semibold",children:"Connect a database"}),(0,h.jsx)("p",{className:"text-xs text-muted-foreground",children:"Paste a connection URL, or pick one you used before."})]}),(0,h.jsx)(CE,{})]}),(0,h.jsx)(TE,{})]})})]})};function fd(){return{id:"memory",label:"Session only (not saved)",persistent:!1,warning:"Keys stay in memory for this tab only. They are not saved across reloads.",load:()=>({}),save:()=>{},clear:()=>{}}}var AE=/^[a-z][a-z0-9-]{0,63}$/,ME="x-byok-";function _e(e){return typeof e=="string"&&AE.test(e)}function _a(e){if(!_e(e))throw new Error(`Invalid BYOK provider id: ${e}`);return`${ME}${e}`}function kE(e){if(typeof e!="object"||e===null||!("error"in e))return!1;const t=e.error;return!(typeof t!="object"||t===null||!("type"in t)||t.type!=="byok_missing"||!("provider"in t)||typeof t.provider!="string"||!_e(t.provider)||!("message"in t)||typeof t.message!="string")}var Fs=class extends Error{provider;constructor(e){super(`Missing ${e} API key`),this.name="ByokMissingError",this.provider=e}},br=class extends Error{provider;reason;constructor(e,t){super(t==="locked"?`${e} key is locked`:`Missing ${e} API key`),this.name="ByokBlockedError",this.provider=e,this.reason=t}},pd=class extends Error{constructor(){super("BYOK is enabled but no provider slug was resolved. Pass byokProvider or forwardedProps.provider."),this.name="ByokUnresolvedProviderError"}};function qn(e){return e.length<=4?"••":e.slice(-4)}var OE={status:{},locked:!1,prompt:null,storageError:null},gd=new WeakMap;function jE(e){const t=Object.entries(e.keys()).filter(r=>!!r[1]).map(r=>r[0]).filter(_e);if(t.length===1)return t[0];const n=gd.get(e)??[];if(n.length===1)return n[0]}function gt(e){if(!_e(e))throw new Error(`Invalid BYOK provider id: ${e}`);return e}function Vn(e,t){return e instanceof Error&&e.message.length>0?e.message:t}function PE(e){if(typeof DOMException<"u"&&e instanceof DOMException&&e.name==="NotAllowedError")return!0;if(e instanceof Error){if(e.name==="NotAllowedError")return!0;const t=e.message.toLowerCase();return t.includes("cancelled")||t.includes("not allowed")}return!1}function Ta(e){if(typeof e!="object"||e===null)return{};const t={};for(const[n,r]of Object.entries(e))_e(n)&&typeof r=="string"&&r.length>0&&(t[n]=r);return t}var LE=class{storage;#e={};#t={};#n;#r=null;#l=!1;#a={};#d={};#c=new Set;#u;#o=null;#i;constructor(e={}){this.storage=e.storage??fd();const t=[];for(const n of e.providers??[]){const r=gt(n.id);t.push(r),n.with?.length&&(this.#d[r]=n.with.map(s=>gt(s.id)))}gd.set(this,t),this.#n=!!this.storage.unlockable,this.#u=this.#h(),this.#i=this.#m()}ready=()=>this.#i;subscribe=e=>(this.#c.add(e),()=>{this.#c.delete(e)});getSnapshot=()=>this.#u;#h(){return{status:{...this.#t},locked:this.#n,prompt:this.#r,storageError:this.#o}}keys(){return{...this.#e}}request(e,t){this.#r={provider:gt(e),reason:t},this.#s()}setServerCoverage(e){if(typeof e=="boolean"){this.#l=e,this.#a={};return}this.#l=!1,this.#a={...this.#a,...e}}#p(e){return this.#l||this.#a[e]===!0}#f(e){return[e,...this.#d[e]??[]]}headers(e){const t={};if(e){gt(e);for(const n of this.#f(e)){const r=this.#e[n];r&&(t[_a(n)]=r)}return t}for(const[n,r]of Object.entries(this.#e))r&&(t[_a(n)]=r);return t}async prepare(e){if(await this.#i,this.storage.unlockable&&this.#n&&await this.unlock(),!!e){gt(e);for(const t of this.#f(e))if(!(this.#e[t]||this.#p(t)))throw this.request(t,"missing"),new br(t,"missing")}}async update(e,t){await this.#i;let n,r;if(t===void 0){if(!this.#r)throw new Error("byok.update(key) cannot run when prompt is null");n=this.#r.provider,r=e}else n=gt(e),r=t;if(r=r.trim(),r.length===0)throw new Error("BYOK key must be non-empty");this.storage.unlockable&&this.#n&&await this.unlock();const s=this.#e,o={...this.#t},i=this.#n,a=this.#r,l=this.#o,c={...this.#e,[n]:r};try{await this.storage.save(c)}catch(u){throw this.#e=s,this.#t=o,this.#n=i,this.#r=a,this.#o=l,this.#t[n]={state:"error",masked:qn(r),message:Vn(u,`Failed to persist ${n} key`)},this.#s(),u}this.#e=c,this.#t[n]={state:"set",masked:qn(r)},this.#n=!1,this.#r=null,this.#o=null,this.#s()}async clear(e){if(await this.#i,e){gt(e),this.storage.unlockable&&this.#n&&await this.unlock();const o=this.#e,i={...this.#t},a={...this.#e};delete a[e];try{await this.storage.save(a)}catch(l){throw this.#e=o,this.#t=i,this.#s(),l}this.#e=a,delete this.#t[e],this.#s();return}const t=this.#e,n=this.#t,r=this.#n,s=this.#r;try{await this.storage.clear()}catch(o){throw this.#e=t,this.#t=n,this.#n=r,this.#r=s,this.#s(),o}this.#e={},this.#t={},this.#n=!1,this.#r=null,this.#o=null,this.#s()}async unlock(){if(await this.#i,!!this.storage.unlockable)try{const e=Ta(await this.storage.load());this.#e={...e,...this.#e};for(const[t,n]of Object.entries(e)){if(!_e(t)||!n)continue;const r=this.#t[t];(!r||r.state==="locked")&&(this.#t[t]={state:"set",masked:qn(n)})}this.#n=!1,this.#o=null,this.#s()}catch(e){if(PE(e)){const t=this.#g();if(t)throw this.request(t,"locked"),new br(t,"locked")}throw this.#o=Vn(e,"Failed to unlock keyring"),this.#s(),e instanceof Error?e:new Error(String(e))}}#g(){if(this.#r&&_e(this.#r.provider))return this.#r.provider;for(const[e,t]of Object.entries(this.#t))if(t?.state==="locked"&&_e(e))return e}async#m(){if(this.storage.unlockable){if(!this.storage.peek)return;try{const e=await this.storage.peek();for(const[t,n]of Object.entries(e))!_e(t)||this.#t[t]||(this.#t[t]={state:"locked",masked:n||"••"});this.#n=Object.keys(e).length>0,this.#o=null,this.#s()}catch(e){this.#o=Vn(e,"Failed to read keyring"),this.#s()}return}try{const e=Ta(await this.storage.load());this.#e={...e,...this.#e};for(const[t,n]of Object.entries(e))!_e(t)||!n||(this.#t[t]={state:"set",masked:qn(n)});this.#o=null,this.#s()}catch(e){this.#o=Vn(e,"Failed to read keyring"),this.#s()}}#s(){this.#u=this.#h();for(const e of this.#c)e()}};function DE(e={}){return new LE(e)}var bn=DE({storage:fd()});bn.setServerCoverage({gemini:!0});var zs=class extends Error{missingFeature;constructor(e){super($E(e)),this.name="UnsupportedResponseStreamError",this.missingFeature=e}};function $E(e){return`Streaming fetch responses are not supported in this runtime because ${e} is unavailable. React Native users need a compatible fetch/stream/TextDecoder polyfill, or should use a fetch, XHR, or custom transport that can deliver streaming chunks.`}function FE(e){if(!e.body)throw new zs("Response.body");if(typeof e.body.getReader!="function")throw new zs("Response.body.getReader");return e.body.getReader()}function zE(){if(typeof globalThis.TextDecoder!="function")throw new zs("TextDecoder");return new globalThis.TextDecoder}function HE(e){if(!e.startsWith("data:"))return e;const t=e.slice(5);return t.startsWith(" ")?t.slice(1):t}function Aa(e){if(e instanceof Date)return Number.isNaN(e.getTime())?void 0:e;if(typeof e!="string")return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}function BE(e){const t=Aa(e.createdAt),n=e.parts.map(o=>{if(o.type!=="tool-result")return o;const i=Aa(o.createdAt),{createdAt:a,...l}=o;return i?{...l,createdAt:i}:l}),{createdAt:r,...s}=e;return t?{...s,parts:n,createdAt:t}:{...s,parts:n}}function Hs(e){return e.map(BE)}function Ma(e){return Object.keys(e).length>0?e:void 0}function md(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)&&"promptTokens"in e}function GE(e,t){return md(e)?e:Array.isArray(e)?ka(e,t):ka(void 0,t)}function ka(e,t){const n=e?.[0];if(n==null&&t==null)return;const{promptTokensDetails:r,completionTokensDetails:s,...o}=t??{},i=Ma({...n?.cachedInputTokens!==void 0?{cachedTokens:n.cachedInputTokens}:{},...r}),a=Ma({...n?.reasoningTokens!==void 0?{reasoningTokens:n.reasoningTokens}:{},...s});return{promptTokens:n?.inputTokens??0,completionTokens:n?.outputTokens??0,totalTokens:n?.totalTokens??0,...o,...i!==void 0?{promptTokensDetails:i}:{},...a!==void 0?{completionTokensDetails:a}:{}}}function Oa(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function vd(e,t){if(t==null)return e;if(e==null)return{...t};const n={...e,...t};return Oa(e.tanstack)&&Oa(t.tanstack)&&(n.tanstack={...e.tanstack,...t.tanstack}),n}function ae(e){if(e==null)return;const t="metadata"in e?e.metadata:void 0,n=(t!=null&&typeof t=="object"&&!Array.isArray(t)?t:e).tanstack;if(!(n==null||typeof n!="object"||Array.isArray(n)))return n}function yd(e,t){const n=e.metadata,r=ae(e)??{};return{...e,metadata:{...n??{},tanstack:{...r,...t}}}}var Kn=(function(e){return e.TEXT_MESSAGE_START="TEXT_MESSAGE_START",e.TEXT_MESSAGE_CONTENT="TEXT_MESSAGE_CONTENT",e.TEXT_MESSAGE_END="TEXT_MESSAGE_END",e.TEXT_MESSAGE_CHUNK="TEXT_MESSAGE_CHUNK",e.TOOL_CALL_START="TOOL_CALL_START",e.TOOL_CALL_ARGS="TOOL_CALL_ARGS",e.TOOL_CALL_END="TOOL_CALL_END",e.TOOL_CALL_CHUNK="TOOL_CALL_CHUNK",e.TOOL_CALL_RESULT="TOOL_CALL_RESULT",e.THINKING_START="THINKING_START",e.THINKING_END="THINKING_END",e.THINKING_TEXT_MESSAGE_START="THINKING_TEXT_MESSAGE_START",e.THINKING_TEXT_MESSAGE_CONTENT="THINKING_TEXT_MESSAGE_CONTENT",e.THINKING_TEXT_MESSAGE_END="THINKING_TEXT_MESSAGE_END",e.STATE_SNAPSHOT="STATE_SNAPSHOT",e.STATE_DELTA="STATE_DELTA",e.MESSAGES_SNAPSHOT="MESSAGES_SNAPSHOT",e.ACTIVITY_SNAPSHOT="ACTIVITY_SNAPSHOT",e.ACTIVITY_DELTA="ACTIVITY_DELTA",e.RAW="RAW",e.CUSTOM="CUSTOM",e.RUN_STARTED="RUN_STARTED",e.RUN_FINISHED="RUN_FINISHED",e.RUN_ERROR="RUN_ERROR",e.STEP_STARTED="STEP_STARTED",e.STEP_FINISHED="STEP_FINISHED",e.REASONING_START="REASONING_START",e.REASONING_MESSAGE_START="REASONING_MESSAGE_START",e.REASONING_MESSAGE_CONTENT="REASONING_MESSAGE_CONTENT",e.REASONING_MESSAGE_END="REASONING_MESSAGE_END",e.REASONING_MESSAGE_CHUNK="REASONING_MESSAGE_CHUNK",e.REASONING_END="REASONING_END",e.REASONING_ENCRYPTED_VALUE="REASONING_ENCRYPTED_VALUE",e})({}),UE=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function ze(e,t){return e>>>t|e<<32-t}function qE(e){const t=new TextEncoder().encode(e),n=t.length*8,r=t.length+1,s=r+(56-r%64+64)%64+8,o=new Uint8Array(s);o.set(t),o[t.length]=128;const i=new DataView(o.buffer);i.setUint32(s-8,Math.floor(n/4294967296)),i.setUint32(s-4,n>>>0);let a=1779033703,l=3144134277,c=1013904242,u=2773480762,d=1359893119,f=2600822924,g=528734635,p=1541459225;const y=new Uint32Array(64);for(let v=0;v<s;v+=64){for(let P=0;P<16;P++)y[P]=i.getUint32(v+P*4);for(let P=16;P<64;P++){const _=y[P-15]??0,M=y[P-2]??0,O=ze(_,7)^ze(_,18)^_>>>3,b=ze(M,17)^ze(M,19)^M>>>10;y[P]=(y[P-16]??0)+O+(y[P-7]??0)+b>>>0}let I=a,m=l,S=c,E=u,N=d,R=f,A=g,k=p;for(let P=0;P<64;P++){const _=ze(N,6)^ze(N,11)^ze(N,25),M=N&R^~N&A,O=k+_+M+(UE[P]??0)+(y[P]??0)>>>0,b=(ze(I,2)^ze(I,13)^ze(I,22))+(I&m^I&S^m&S)>>>0;k=A,A=R,R=N,N=E+O>>>0,E=S,S=m,m=I,I=O+b>>>0}a=a+I>>>0,l=l+m>>>0,c=c+S>>>0,u=u+E>>>0,d=d+N>>>0,f=f+R>>>0,g=g+A>>>0,p=p+k>>>0}const x=v=>(v>>>0).toString(16).padStart(8,"0");return x(a)+x(l)+x(c)+x(u)+x(d)+x(f)+x(g)+x(p)}function VE(e){return`sha256:${qE(e)}`}function Bs(e,t){if(e===null)return"null";if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return JSON.stringify(e);if(typeof e!="object")throw new TypeError("Interrupt values must be JSON-compatible.");if(t.has(e))throw new TypeError("Interrupt values must not cycle.");if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new TypeError("Interrupt values must use plain JSON objects.");t.add(e);let n;if(Array.isArray(e)){const r=[];for(let s=0;s<e.length;s++)r.push(Bs(e[s],t));n=`[${r.join(",")}]`}else{const r=e;n=`{${Object.keys(r).sort().map(s=>`${JSON.stringify(s)}:${Bs(r[s],t)}`).join(",")}}`}return t.delete(e),n}function At(e){return Bs(e,new WeakSet)}function Mt(e,t=VE){if(typeof e!="string")throw new TypeError("Interrupt digests require canonical JSON text.");return t(e)}function bd(e){e===null||typeof e!="object"||Object.isFrozen(e)||(Object.values(e).forEach(bd),Object.freeze(e))}function de(e){const t=JSON.parse(At(e));return bd(t),t}function KE(e){const t=[...e].sort((s,o)=>s.interruptId.localeCompare(o.interruptId)),n=de(t),r=At(n);return Object.freeze({resolutions:n,canonicalResolutions:r,fingerprint:Mt(r)})}function ja(e){const t={};for(const[n,r]of Object.entries(e))n!=="$schema"&&(t[n]=r);return t}function xd(e){return(typeof e=="object"||typeof e=="function")&&e!==null}function Ln(e){if(!xd(e)||!("~standard"in e))return!1;const t=e["~standard"];return typeof t!="object"||t===null||!("version"in t)||t.version!==1||!("jsonSchema"in t)||typeof t.jsonSchema!="object"||t.jsonSchema===null||!("input"in t.jsonSchema)?!1:typeof t.jsonSchema.input=="function"}function ft(e){return xd(e)&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"version"in e["~standard"]&&e["~standard"].version===1&&"validate"in e["~standard"]&&typeof e["~standard"].validate=="function"}function YE(e){return Object.keys(e).length>0?e:void 0}function Pa(e){if(Array.isArray(e)){const n=e.map(s=>xr(s,s.required||[])),r=n.map(s=>s.nullWidening??{});return{schema:n.map(s=>s.schema),itemMap:r.some(s=>Object.keys(s).length>0)?r:void 0}}const t=xr(e,e.required||[]);return{schema:t.schema,itemMap:t.nullWidening}}function xr(e,t=[]){const n={...e},r={};if(n.type==="object"&&n.properties){const s={...n.properties},o=Object.keys(s),i={};for(const a of o){const l=s[a];if(!l)continue;const c=!t.includes(a);let u=!1,d;if(l.type==="object"&&l.properties){const f=xr(l,l.required||[]);s[a]=c?{...f.schema,type:["object","null"]}:f.schema,u=c,d=f.nullWidening}else if(l.type==="array"&&l.items){const f=Pa(l.items);s[a]={...l,items:f.schema,...c?{type:["array","null"]}:{}},u=c,d=f.itemMap?{items:f.itemMap}:void 0}else c&&(l.type&&!Array.isArray(l.type)?(s[a]={...l,type:[l.type,"null"]},u=!0):Array.isArray(l.type)&&!l.type.includes("null")&&(s[a]={...l,type:[...l.type,"null"]},u=!0));(u||d)&&(i[a]={...d??{},...u?{widened:!0}:{}})}n.properties=s,n.required=o,n.additionalProperties=!1,Object.keys(i).length>0&&(r.properties=i)}if(n.type==="array"&&n.items){const s=Pa(n.items);n.items=s.schema,s.itemMap&&(r.items=s.itemMap)}return{schema:n,nullWidening:YE(r)}}function WE(e){if(Ln(e)){const t=ja(e["~standard"].jsonSchema.input({target:"draft-07"}));return"properties"in t&&!t.type&&(t.type="object"),t.type==="object"&&!("properties"in t)&&(t.properties={}),t.type==="object"&&!("required"in t)&&(t.required=[]),t}if(ft(e))throw new Error("Schema is a Standard Schema validator but does not expose a JSON Schema converter on `~standard.jsonSchema`. Use Zod v4.2+, ArkType v2.1.28+, or wrap a Valibot schema with `toStandardJsonSchema()` from `@valibot/to-json-schema` before passing it as `outputSchema`.");return typeof e!="object"?e:ja(e)}function Gs(e,t={}){if(!e)return;const{forStructuredOutput:n=!1}=t;if(!n&&!Ln(e)&&!ft(e))return e;const r=WE(e);return!r||typeof r!="object"||!n?r:xr(r,r.required||[]).schema}var XE=class extends Error{name="StandardSchemaValidationError";issues;constructor(e){super(`Validation failed: ${e.map(t=>t.message||"Validation failed").join(", ")}`),this.issues=e}};function QE(e,t){if(!ft(e))return t;const n=e["~standard"].validate(t);if(n instanceof Promise)throw new Error("Schema validation returned a Promise. Use validateWithStandardSchema for async validation.");if(!n.issues)return n.value;throw new XE(n.issues)}var JE=new Set(["$schema","$id","$ref","$defs","type","properties","required","additionalProperties","items","oneOf","anyOf","allOf","enum","const","format","minimum","maximum","minLength","maxLength","pattern"]);function Sd(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function Mo(e){return Sd(e)&&Object.keys(e).some(t=>JE.has(t))}function ZE(e){return ft(e)||Ln(e)||Mo(e)}function eC(e){if(!Sd(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>n==="approve"||n==="reject")&&t.every(n=>ZE(e[n]))}function tC(e){const t={};for(const[n,r]of Object.entries(e))t[n]=r;return t}function pn(e){if(ft(e)){const t=Ln(e)?tC(e["~standard"].jsonSchema.input({target:"draft-2020-12"})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(Mo(e))return{source:e,jsonSchema:e};throw new TypeError("Expected a supported SchemaInput.")}function La(e){const t={approved:{const:e.approved}},n=["approved"];return e.approved&&e.inputSchema&&(t.editedArgs=e.inputSchema.jsonSchema??{}),e.payload&&(t.payload=e.payload.jsonSchema??{},n.push("payload")),{type:"object",properties:t,required:n,additionalProperties:!1}}function nC(e,t){const n=t===void 0?null:pn(t);let r=null,s=null;if(e!==void 0)if(ft(e)||Mo(e))r=pn(e),s=r;else if(eC(e))r=e.approve===void 0?null:pn(e.approve),s=e.reject===void 0?null:pn(e.reject);else throw new TypeError("approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.");const o={oneOf:[La({approved:!0,payload:r,inputSchema:n}),La({approved:!1,payload:s,inputSchema:null})]},i=At(o),a=At({approve:r?.jsonSchema??null,reject:s?.jsonSchema??null});return{branches:{approve:r,reject:s},responseSchema:o,responseSchemaHash:Mt(i),approvalSchemaHash:Mt(a)}}function Da(e){if(e===void 0)return Mt("undefined");const t=pn(e).jsonSchema??{standardValidator:"unserialized"};return Mt(At(t))}var Ur="tanstack:interruptBinding",Id=Ur;function Sr(e){return e&&typeof e=="object"?e:null}function ye(e,t){return typeof e[t]=="string"?e[t]:void 0}function rC(e){const t=e.v;return t===void 0?!0:t===1}function wd(e){const t=Sr(e.metadata),n=t?Sr(t[Id]):null;if(!n||ye(n,"interruptId")!==e.id||!rC(n))return;const r=ye(n,"kind"),s=ye(n,"interruptId"),o=ye(n,"responseSchemaHash"),i=ye(n,"expiresAt");if(!s||o===""||i!==void 0&&!Number.isFinite(Date.parse(i)))return;const a=1;if(r==="generic"){const u=ye(n,"definitionId"),d=ye(n,"key"),f=n.batchIndex,g=ye(n,"payloadSchemaHash");return(u!==void 0||d!==void 0||f!==void 0||g!==void 0)&&(!u||!d||typeof f!="number"||!Number.isInteger(f)||f<0)?void 0:{v:a,kind:r,interruptId:s,...o?{responseSchemaHash:o}:{},...i?{expiresAt:i}:{},...u?{definitionId:u}:{},...d?{key:d}:{},...typeof f=="number"?{batchIndex:f}:{},...g?{payloadSchemaHash:g}:{}}}if(!o)return;const l=ye(n,"toolName"),c=ye(n,"toolCallId");if(!(!l||!c)){if(r==="client-tool-execution"){const u=ye(n,"outputSchemaHash");return u?{v:a,kind:r,interruptId:s,toolName:l,toolCallId:c,outputSchemaHash:u,responseSchemaHash:o,...i?{expiresAt:i}:{}}:void 0}if(r==="tool-approval"){const u=ye(n,"inputSchemaHash"),d=ye(n,"approvalSchemaHash");return!u||!d?void 0:{v:a,kind:r,interruptId:s,toolName:l,toolCallId:c,originalArgs:n.originalArgs,inputSchemaHash:u,approvalSchemaHash:d,responseSchemaHash:o,...i?{expiresAt:i}:{}}}}}function sC(e){const t=wd(e);if(!t)return;const n=Sr(e.metadata),r=n?Sr(n[Id]):null;if(!r)return;const s=ye(r,"interruptedRunId"),o=r.generation;if(!(!s||typeof o!="number"||!Number.isInteger(o)||o<0))return{...t,interruptedRunId:s,generation:o}}var oC="tanstack:interruptPayload";function iC(e,t){if(!Ln(e))throw new TypeError(`${t} must be a Standard Schema with a JSON Schema converter.`);try{const n=e["~standard"].jsonSchema.input({target:"draft-07"});if(n===void 0)throw new TypeError("The exported schema is undefined.");if(typeof n=="function")throw new TypeError("The exported schema must not be a function.");if(Array.isArray(n))throw new TypeError("The exported schema must be a plain JSON object.");if(!n||typeof n!="object"||![Object.prototype,null].includes(Object.getPrototypeOf(n)))throw new TypeError("The exported schema must be a plain JSON object.");const r={};for(const[s,o]of Object.entries(n))s!=="$schema"&&(r[s]=o);return{json:r,canonicalJson:At(r)}}catch(n){throw new TypeError(`${t} could not export compatible JSON Schema: ${n instanceof Error?n.message:String(n)}`)}}function aC(e){return Mt(iC(e,"Interrupt schema").canonicalJson)}var lC="tanstack:interruptContinuation";function cC(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function uC(e){return{[lC]:e}}function dC(e){const t=wd(e);if(t?.kind!=="generic"||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;const n=cC(e.metadata)?e.metadata:void 0,r=n!==void 0&&Object.prototype.hasOwnProperty.call(n,"tanstack:interruptPayload");return{v:1,definitionId:t.definitionId,key:t.key,batchIndex:t.batchIndex,reason:e.reason,message:e.message??"",...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{},...t.responseSchemaHash!==void 0?{responseSchemaHash:t.responseSchemaHash}:{},...t.payloadSchemaHash!==void 0?{payloadSchemaHash:t.payloadSchemaHash}:{},...r?{payload:n[oC]}:{}}}var hC=new Set(["text","image","audio","video","document"]);function fC(e){if(typeof e!="object"||e===null)return!1;const t=e;if(typeof t.type!="string"||!hC.has(t.type))return!1;if(t.type==="text")return typeof t.content=="string";const n=t.source;if(typeof n!="object"||n===null)return!1;const r=n;return typeof r.value!="string"?!1:r.type==="data"?typeof r.mimeType=="string":r.type==="url"}function Us(e){return Array.isArray(e)&&e.length>0&&e.every(fC)}function ko(e){return typeof e=="string"||Us(e)?e:JSON.stringify(e)}function pC(e){const t=e?.metadata;return typeof t=="object"&&t!==null&&t.providerExecuted===!0?t:null}function Ed(e){return pC(e)!==null}function fs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gC(e){return e.type==="text"||e.type==="image"||e.type==="audio"||e.type==="video"||e.type==="document"}function mC(e){try{return JSON.stringify(e)??""}catch{return""}}function $a(e){return typeof e=="string"&&e!==""?e:void 0}function vC(e){if("encryptedValue"in e){const t=$a(e.encryptedValue);if(t!==void 0)return t}return $a(ae(e)?.signature)}function Cd(e){return e.length===0?null:e.every(t=>t.type==="text")?e.map(t=>t.content).join("")||null:e}function Nd(e){return e==null?"":typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.content).join("")}function yC(e){return Array.isArray(e)?e:Nd(e)}function bC(e){if(!("role"in e)||e.role!=="tool")return e;const t=e,n=ae(t)?.toolResult;if(!fs(n)||"content"in n&&!Us(n.content))return e;const r={...e};if("id"in n||Reflect.deleteProperty(r,"id"),"createdAt"in n||Reflect.deleteProperty(r,"createdAt"),typeof n.id=="string"&&Reflect.set(r,"id",n.id),typeof n.createdAt=="string"){const o=Ae(n.createdAt);o&&Reflect.set(r,"createdAt",o)}Us(n.content)&&Reflect.set(r,"content",n.content);const s=Reflect.get(t,"metadata");if(fs(s)){const o=s.tanstack;if(fs(o)){const{toolResult:i,...a}=o,l={...s};Object.keys(a).length?l.tanstack=a:delete l.tanstack,Object.keys(l).length?Reflect.set(r,"metadata",l):Reflect.deleteProperty(r,"metadata")}}return r}function Ae(e){if(e instanceof Date)return Number.isNaN(e.getTime())?void 0:e;if(typeof e!="string")return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}function Rd(e){if(e.type!=="tool-result")return e;const t=Ae(e.createdAt),{createdAt:n,...r}=e;return t===void 0?r:{...r,createdAt:t}}function _d(e){return Ae(ae(e)?.createdAt)}function qs(e){const t=Ae(e.createdAt);return t!==void 0?{createdAt:t}:{}}function qr(e){return e.name!==void 0?{name:e.name}:{}}function Vr(e){if(e==null||typeof e!="object"||Array.isArray(e)||!("type"in e)||e.type!=="ui-resource"||!("toolCallId"in e)||typeof e.toolCallId!="string"||!("toolName"in e)||typeof e.toolName!="string"||!("resource"in e)||e.resource==null||typeof e.resource!="object"||Array.isArray(e.resource))return!1;const t=e.resource;return"uri"in t&&typeof t.uri=="string"&&"mimeType"in t&&typeof t.mimeType=="string"}function Fa(e){return`${e.toolCallId}\0${e.toolName}\0${e.resource.uri}`}function Td(e,t){if(t.length===0)return e;const n=new Set(e.parts.filter(Vr).map(s=>Fa(s))),r=t.filter(s=>!n.has(Fa(s)));return r.length===0?e:{...e,parts:[...e.parts,...r]}}function xC(e){const t=e.parts.filter(Vr),n=e.metadata??{},r=ae(e),s={};r?.model!==void 0&&(s.model=r.model),r?.signature!==void 0&&(s.signature=r.signature),t.length>0&&(s.uiResources=t);const o={...n};return Object.keys(s).length>0?o.tanstack=s:delete o.tanstack,Object.keys(o).length>0?o:void 0}function SC(e){return e.role==="system"?[]:e.role!=="assistant"?[IC(e)]:EC(e)}function IC(e){const t=[];for(const n of e.parts)gC(n)&&t.push(n);return{id:e.id,role:e.role,content:Cd(t),...qr(e),...qs(e),...e.metadata!==void 0&&{metadata:e.metadata}}}function za(){return{contentParts:[],toolCalls:[]}}function wC(e){return e.state==="input-complete"||e.state==="complete"||e.state==="approval-requested"||e.state==="approval-responded"||e.state==="error"||e.output!==void 0}function EC(e){const t=[];let n=za(),r=[];const s=new Set,o={id:e.id,...qr(e),...qs(e)},i=xC(e),a={...o,...i!==void 0&&{metadata:i}};function l(c=!1){const u=Cd(n.contentParts),d=u!==null,f=n.toolCalls.length>0,g=r.length>0;(c||d||f||g)&&(t.push({...a,role:"assistant",content:u,...f&&{toolCalls:n.toolCalls},...g&&{thinking:r},...n.structuredOutput&&{structuredOutput:n.structuredOutput}}),r=[]),n=za()}for(const c of e.parts)switch(c.type){case"text":case"image":case"audio":case"video":case"document":n.contentParts.push(c);break;case"tool-call":wC(c)&&n.toolCalls.push({id:c.id,type:"function",function:{name:c.name,arguments:c.arguments},...c.metadata!==void 0&&{metadata:c.metadata}});break;case"tool-result":l(t.length===0),(c.state==="complete"||c.state==="error")&&!s.has(c.toolCallId)&&(t.push({...c.id!==void 0&&{id:c.id},...qs(c),role:"tool",content:c.content,toolCallId:c.toolCallId,...c.name!==void 0&&{name:c.name},...c.metadata!==void 0&&{metadata:c.metadata},...c.error!==void 0&&{error:c.error}}),s.add(c.toolCallId));break;case"thinking":(c.content||c.signature)&&(n.toolCalls.some(Ed)&&l(),r.push({content:c.content,...c.signature&&{signature:c.signature}}));break;case"structured-output":if(c.status==="complete"){const u=c.raw!==""?c.raw:c.data!==void 0?mC(c.data):"";u!==""&&(n.contentParts.push({type:"text",content:u}),n.structuredOutput=c)}}l();for(const c of e.parts)if(c.type==="tool-call"&&(c.output!==void 0&&!s.has(c.id)&&(t.push({role:"tool",content:ko(c.output),toolCallId:c.id}),s.add(c.id)),c.output===void 0&&c.state==="approval-responded"&&c.approval?.approved!==void 0&&!s.has(c.id))){const u=c.approval.approved;t.push({role:"tool",content:JSON.stringify({approved:u,...u&&{pendingExecution:!0},message:u?"User approved this action":"User denied this action"}),toolCallId:c.id}),s.add(c.id)}return t.length===0&&t.push({...a,role:"assistant",content:null}),t}function Ir(e,t){const n=[],r=Ae(e.createdAt);if(e.role==="assistant"&&e.thinking?.length)for(const a of e.thinking)!a.content&&!a.signature||n.push({type:"thinking",content:a.content,...a.signature&&{signature:a.signature}});const s=e.structuredOutput??Ad(ae(e)?.structuredOutput);if(e.role==="assistant"&&s){if(typeof e.content=="string"&&e.content&&e.content!==s.raw){const a=s.raw,l=a!==""&&e.content.endsWith(a)?e.content.slice(0,-a.length):e.content;l&&n.push({type:"text",content:l})}n.push(s)}else if(e.role==="tool"&&e.toolCallId)n.push({type:"tool-result",toolCallId:e.toolCallId,content:yC(e.content),state:e.error===void 0?"complete":"error",...e.id!==void 0&&{id:e.id},...e.name!==void 0&&{name:e.name},...e.metadata!==void 0&&{metadata:e.metadata},...r!==void 0&&{createdAt:r},...e.error!==void 0&&{error:e.error}});else if(Array.isArray(e.content))for(const a of e.content)n.push(a);else{const a=Nd(e.content);a&&n.push({type:"text",content:a})}if(e.toolCalls&&e.toolCalls.length>0)for(const a of e.toolCalls){let l;try{l=JSON.parse(a.function.arguments)}catch{l=void 0}n.push({type:"tool-call",id:a.id,name:a.function.name,arguments:a.function.arguments,state:"input-complete",...l!==void 0&&{input:l},...a.metadata!==void 0&&{metadata:a.metadata}})}const o={id:t||Et(),role:e.role==="tool"?"assistant":e.role,parts:n,...qr(e),...r!==void 0&&{createdAt:r},...e.metadata!==void 0&&{metadata:e.metadata}},i=ae(e)?.uiResources;return Td(o,Array.isArray(i)?i.filter(Vr):[])}function CC(e){if("parts"in e)return mt(e,{...e,id:e.id||Et()});const t=e.id||Et();switch(e.role){case"user":return mt(e,{id:t,role:"user",parts:NC(e.content)});case"assistant":{const n=ae(e),r=n?.toolCallMetadata,s=Ad(n?.structuredOutput),o=e.toolCalls?.map(i=>{const a=r!=null&&typeof r=="object"?r[i.id]:void 0;return a!==void 0?{...i,metadata:a}:i});return mt(e,Ir({role:"assistant",content:e.content??null,...qr(e),...o&&{toolCalls:o},...s&&{structuredOutput:s}},t))}case"tool":{e=bC(e);const n=Ae("createdAt"in e?e.createdAt:void 0)??_d(e);return mt(e,Ir({role:"tool",content:e.content,toolCallId:e.toolCallId,..."name"in e&&typeof e.name=="string"?{name:e.name}:{},..."id"in e&&typeof e.id=="string"?{id:e.id}:{},..."metadata"in e&&e.metadata!=null?{metadata:e.metadata}:{},...n!==void 0?{createdAt:n}:{},...e.error!==void 0&&{error:e.error}},t))}case"system":case"developer":return mt(e,{id:t,role:"system",parts:e.content?[{type:"text",content:e.content}]:[]});case"reasoning":{const n=vC(e),r=typeof e.content=="string"?e.content:"";return mt(e,{id:t,role:"assistant",parts:r||n!==void 0?[{type:"thinking",content:r,...n!==void 0?{signature:n}:{}}]:[]})}default:return mt(e,{id:t,role:"assistant",parts:[]})}}function mt(e,t){const n=t.parts.map(c=>Rd(c));n!==t.parts&&(t={...t,parts:n});const r="name"in e&&typeof e.name=="string"?e.name:void 0;let s=r!==void 0?{...t,name:r}:t,o;if("metadata"in e){const c=e.metadata;c!=null&&typeof c=="object"&&!Array.isArray(c)&&(o=c,s={...s,metadata:o})}const i=Ae(s.createdAt)??(o!==void 0?_d(o):void 0);if(i!==void 0&&!Object.is(i,s.createdAt))s={...s,createdAt:i};else if(i===void 0&&s.createdAt!==void 0){const{createdAt:c,...u}=s;s=u}const a=ae(o)?.uiResources,l=Array.isArray(a)?a.filter(Vr):[];return Td(s,l)}function Ad(e){if(!(e==null||e.status!=="streaming"&&e.status!=="complete"&&e.status!=="error"||typeof e.raw!="string"))return{type:"structured-output",status:e.status,raw:e.raw,...e.partial!==void 0?{partial:e.partial}:{},...e.data!==void 0?{data:e.data}:{},...e.reasoning?{reasoning:e.reasoning}:{},...e.errorMessage!==void 0?{errorMessage:e.errorMessage}:{}}}function NC(e){if(typeof e=="string")return e?[{type:"text",content:e}]:[];const t=[];for(const n of e)n.type==="text"?t.push({type:"text",content:n.text}):n.type!=="binary"&&t.push(n);return t}function RC(e,t){if("parts"in e){const n=e.parts.map(r=>Rd(r));return{...e,parts:n,id:e.id||t(),createdAt:Ae(e.createdAt)??new Date}}else return{...Ir(e,t()),createdAt:Ae(e.createdAt)??new Date}}function Et(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function Ha(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ps(e,t,n,r,s=!1){const o=Ha(e)?e:{},i=Ha(o.tanstack)?{...o.tanstack}:{};s&&delete i.uiResources;const a=Ae(t),l={...n!==void 0?{id:n}:{},...a&&{createdAt:a.toISOString()},...Array.isArray(r)&&{content:r}},c={...o,tanstack:{...i,toolResult:l}};return Object.keys(c).length?c:void 0}function _C(e,t){const n=[],r=new Set(e.flatMap(i=>"id"in i&&i.id&&i.role!=="tool"?[i.id]:[])),s=t?.includeSnapshotStructuredOutput??!1,o=new Set;for(const i of e)i.role==="assistant"&&i.id!==void 0&&o.add(i.id);for(const i of e){if(!("parts"in i)&&i.role==="tool"&&i.toolCallId){const f=ms(LC(i.id,i.toolCallId,o),r),g=ps(i.metadata,i.createdAt,i.id,i.content);n.push({role:"tool",id:f,...i.name!==void 0&&{name:i.name},toolCallId:i.toolCallId,content:typeof i.content=="string"?i.content:JSON.stringify(i.content),...i.error!==void 0&&{error:i.error},...g!==void 0&&{metadata:g}});continue}const a="parts"in i?i:Ir(i,i.id),l=a.parts;if(r.add(a.id),i.role==="system"){n.push(gs(a,"system",{content:l.length>0?Vs(l):i.content??""},l,s));continue}if(i.role==="user"){n.push(gs(a,"user",{content:l.length>0?kC(l):i.content??""},l,s));continue}for(const f of l)if(f.type==="thinking"){const g={role:"reasoning",id:Md(PC(a.id,f),r),content:f.content};f.signature&&(g.encryptedValue=f.signature),n.push(g)}const c=Vs(l),u=jC(l);n.push(gs(a,"assistant",{...c!==""&&{content:c},...u&&{toolCalls:u}},l,s));const d=new Set(l.flatMap(f=>f.type==="tool-result"?[f.toolCallId]:[]));for(const f of l)if(f.type==="tool-result"){const g=ms(f.id??Ks(f.toolCallId),r),p=ps(f.metadata,f.createdAt,f.id,f.content,!0);n.push({role:"tool",id:g,toolCallId:f.toolCallId,...f.name!==void 0&&{name:f.name},content:typeof f.content=="string"?f.content:JSON.stringify(f.content),...f.error!==void 0&&{error:f.error},...p!==void 0&&{metadata:p}})}else if(f.type==="tool-call"){const g=f.approval?.approved;if(d.has(f.id)||f.output===void 0&&(f.state!=="approval-responded"||g===void 0))continue;const p=f.output!==void 0?ko(f.output):JSON.stringify({approved:g,...g&&{pendingExecution:!0},message:g?"User approved this action":"User denied this action"}),y=typeof p=="string"?p:JSON.stringify(p);n.push({role:"tool",id:ms(Ks(f.id),r),toolCallId:f.id,content:y,metadata:ps(void 0,void 0,void 0,p)})}}return n}function gs(e,t,n,r,s){const o=TC(e,r,s),i={id:e.id,...e.name!==void 0&&{name:e.name},...o!==void 0&&{metadata:o}};return t==="system"?{...i,role:t,content:String(n.content??"")}:t==="user"?{...i,role:t,content:n.content??""}:{...i,role:t,...typeof n.content=="string"&&{content:n.content},...n.toolCalls!==void 0&&{toolCalls:n.toolCalls}}}function TC(e,t,n){const r={...e.metadata??{}},s=ae(e),o={};s?.model!==void 0&&(o.model=s.model),s?.signature!==void 0&&(o.signature=s.signature);const i=Ae(e.createdAt);i!==void 0&&(o.createdAt=i.toISOString());const a=AC(t,n);a&&(o.structuredOutput=a);const l={};for(const u of t)u.type==="tool-call"&&u.metadata!==void 0&&(l[u.id]=u.metadata);Object.keys(l).length>0&&(o.toolCallMetadata=l);const c=t.filter(u=>u.type==="ui-resource");return c.length>0&&(o.uiResources=c),Object.keys(o).length>0?r.tanstack=o:delete r.tanstack,Object.keys(r).length>0?r:void 0}function AC(e,t){for(const n of e)if(n.type==="structured-output"&&(t||n.status!=="complete"))return MC(n,t)}function MC(e,t){return{status:e.status,raw:e.raw,...t&&e.partial!==void 0?{partial:e.partial}:{},...t&&e.data!==void 0?{data:e.data}:{},...t&&e.reasoning?{reasoning:e.reasoning}:{},...e.errorMessage!==void 0&&{errorMessage:e.errorMessage}}}function Vs(e){const t=[];for(const n of e)n.type==="text"?t.push(n.content):n.type==="structured-output"&&n.status==="complete"&&n.raw!==""&&t.push(n.raw);return t.join("")}function kC(e){if(!e.some(n=>n.type==="image"||n.type==="audio"||n.type==="video"||n.type==="document"))return Vs(e);const t=[];for(const n of e)n.type==="text"?t.push({type:"text",text:n.content}):(n.type==="image"||n.type==="audio"||n.type==="video"||n.type==="document")&&t.push(n);return t}function OC(e){if(e==null||typeof e!="object"||Array.isArray(e)||!("thoughtSignature"in e))return;const t=e.thoughtSignature;return typeof t=="string"&&t!==""?t:void 0}function jC(e){const t=[];for(const n of e)if(n.type==="tool-call"){const r=OC(n.metadata);t.push({id:n.id,type:"function",function:{name:n.name,arguments:n.arguments},...r!==void 0?{encryptedValue:r}:{}})}return t.length>0?t:void 0}function PC(e,t){return`${e}-reasoning-${t.id??DC(t.content)}`}function Ks(e){return`tool-${e}`}function ms(e,t){return Md(e,t)}function Md(e,t){if(!t.has(e))return t.add(e),e;let n=2;for(;t.has(`${e}-${n}`);)n++;const r=`${e}-${n}`;return t.add(r),r}function LC(e,t,n){const r=Ks(t);return e===void 0||n.has(e)?r:e}function DC(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return Math.abs(t).toString(36)}function $C(e){if((e.type===Kn.RUN_FINISHED||e.type===Kn.RUN_ERROR)&&(Array.isArray(e.usage)||md(e.usage))){const t=GE(e.usage,ae(e)?.usage);t!==void 0&&(e.usage=t)}if(e.type===Kn.TOOL_CALL_START&&e.toolName===void 0&&e.toolCallName&&(e.toolName=e.toolCallName),e.type===Kn.TOOL_CALL_END&&e.input===void 0){const t=ae(e)?.input;t!==void 0&&(e.input=t)}return e}function kd(e){$C(e);const t=ae(e),n=e;if(t==null)return n;for(const[r,s]of Object.entries(t))r==="usage"||r==="interruptErrors"||n[r]===void 0&&s!==void 0&&(n[r]=s);return t.interruptErrors!==void 0&&(n["tanstack:interruptErrors"]=t.interruptErrors),n}function Ba(e){return typeof e=="string"&&e!==""?e:void 0}function Od(e){if("runId"in e){const t=Ba(e.runId);if(t!==void 0)return t}return Ba(ae(e)?.runId)}var Ga=xl((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow})),FC=xl(((e,t,n)=>{var r=n&&n.__createBinding||(Object.create?(function(d,f,g,p){p===void 0&&(p=g);var y=Object.getOwnPropertyDescriptor(f,g);(!y||("get"in y?!f.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return f[g]}}),Object.defineProperty(d,p,y)}):(function(d,f,g,p){p===void 0&&(p=g),d[p]=f[g]})),s=n&&n.__exportStar||function(d,f){for(var g in d)g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g)&&r(f,d,g)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;var o=Ga();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return o.Allow}}),s(Ga(),e);var i=class extends Error{};e.PartialJSON=i;var a=class extends Error{};e.MalformedJSON=a;function l(d,f=o.Allow.ALL){if(typeof d!="string")throw new TypeError(`expecting str, got ${typeof d}`);if(!d.trim())throw new Error(`${d} is empty`);return c(d.trim(),f)}e.parseJSON=l;var c=(d,f)=>{const g=d.length;let p=0;const y=R=>{throw new i(`${R} at position ${p}`)},x=R=>{throw new a(`${R} at position ${p}`)},v=()=>(N(),p>=g&&y("Unexpected end of input"),d[p]==='"'?I():d[p]==="{"?m():d[p]==="["?S():d.substring(p,p+4)==="null"||o.Allow.NULL&f&&g-p<4&&"null".startsWith(d.substring(p))?(p+=4,null):d.substring(p,p+4)==="true"||o.Allow.BOOL&f&&g-p<4&&"true".startsWith(d.substring(p))?(p+=4,!0):d.substring(p,p+5)==="false"||o.Allow.BOOL&f&&g-p<5&&"false".startsWith(d.substring(p))?(p+=5,!1):d.substring(p,p+8)==="Infinity"||o.Allow.INFINITY&f&&g-p<8&&"Infinity".startsWith(d.substring(p))?(p+=8,1/0):d.substring(p,p+9)==="-Infinity"||o.Allow._INFINITY&f&&1<g-p&&g-p<9&&"-Infinity".startsWith(d.substring(p))?(p+=9,-1/0):d.substring(p,p+3)==="NaN"||o.Allow.NAN&f&&g-p<3&&"NaN".startsWith(d.substring(p))?(p+=3,NaN):E()),I=()=>{const R=p;let A=!1;for(p++;p<g&&(d[p]!=='"'||A&&d[p-1]==="\\");)A=d[p]==="\\"?!A:!1,p++;if(d.charAt(p)=='"')try{return JSON.parse(d.substring(R,++p-Number(A)))}catch(k){x(String(k))}else if(o.Allow.STR&f)try{return JSON.parse(d.substring(R,p-Number(A))+'"')}catch{return JSON.parse(d.substring(R,d.lastIndexOf("\\"))+'"')}y("Unterminated string literal")},m=()=>{p++,N();const R={};try{for(;d[p]!=="}";){if(N(),p>=g&&o.Allow.OBJ&f)return R;const A=I();N(),p++;try{R[A]=v()}catch(k){if(o.Allow.OBJ&f)return R;throw k}N(),d[p]===","&&p++}}catch{if(o.Allow.OBJ&f)return R;y("Expected '}' at end of object")}return p++,R},S=()=>{p++;const R=[];try{for(;d[p]!=="]";)R.push(v()),N(),d[p]===","&&p++}catch{if(o.Allow.ARR&f)return R;y("Expected ']' at end of array")}return p++,R},E=()=>{if(p===0){d==="-"&&x("Not sure what '-' is");try{return JSON.parse(d)}catch(A){if(o.Allow.NUM&f)try{return JSON.parse(d.substring(0,d.lastIndexOf("e")))}catch{}x(String(A))}}const R=p;for(d[p]==="-"&&p++;d[p]&&",]}".indexOf(d[p])===-1;)p++;p==g&&!(o.Allow.NUM&f)&&y("Unterminated number literal");try{return JSON.parse(d.substring(R,p))}catch{d.substring(R,p)==="-"&&y("Not sure what '-' is");try{return JSON.parse(d.substring(R,d.lastIndexOf("e")))}catch(k){x(String(k))}}},N=()=>{for(;p<g&&`
|
|
9
|
+
\r `.includes(d[p]);)p++};return v()},u=l;e.parse=u})),zC=FC(),HC=class{parse(e){if(!(!e||e.trim()===""))try{return(0,zC.parse)(e)}catch{return}}},jd=new HC;function BC(e){return jd.parse(e)}var GC=class{shouldEmit(e,t){return!0}};function UC(e){const t=new Error(e.message||e.error?.message||"An error occurred"),n=e.code??e.error?.code;return n!==void 0&&Object.assign(t,{code:n}),e.rawEvent!==void 0&&Object.assign(t,{rawEvent:e.rawEvent}),t}function qC(e,t,n){return e.map(r=>{if(r.id!==t)return r;const s=[...r.parts],o=s.length>0?s[s.length-1]:null;return o&&o.type==="text"?s[s.length-1]={type:"text",content:n}:s.push({type:"text",content:n}),{...r,parts:s}})}function Yn(e,t,n){return e.map(r=>{if(r.id!==t)return r;const s=[...r.parts],o=s.find(c=>c.type==="tool-call"&&c.id===n.id),i=n.metadata??o?.metadata,a=n.input??o?.input,l={type:"tool-call",id:n.id,name:n.name,arguments:n.arguments,state:n.state,...o?.approval&&{approval:{...o.approval}},...o?.output!==void 0&&{output:o.output},...a!==void 0&&{input:a},...i!==void 0&&{metadata:i}};return o?s[s.indexOf(o)]=l:s.push(l),{...r,parts:s}})}function Ua(e,t,n,r,s,o){return e.map(i=>{if(i.id!==t)return i;const a=[...i.parts],l=a.findIndex(u=>u.type==="tool-result"&&u.toolCallId===n),c={type:"tool-result",toolCallId:n,content:r,state:s,...o&&{error:o}};return l>=0?a[l]=c:a.push(c),{...i,parts:a}})}function qa(e,t,n,r){return e.map(s=>{if(s.id!==t)return s;const o=[...s.parts],i=o.find(a=>a.type==="tool-call"&&a.id===n);if(i){const a=o.indexOf(i);o[a]={...i,state:"approval-requested",approval:{id:r,needsApproval:!0}}}return{...s,parts:o}})}function Va(e,t,n,r,s){return e.map(o=>{const i=[...o.parts],a=i.find(l=>l.type==="tool-call"&&l.id===t);if(a){const l=i.indexOf(a);i[l]={...a,output:s?{error:s}:n,state:r??(s?"error":"complete")}}return{...o,parts:i}})}function VC(e,t,n){return e.map(r=>{const s=[...r.parts],o=s.find(i=>i.type==="tool-call"&&i.approval?.id===t);if(o&&o.approval){const i=s.indexOf(o);s[i]={...o,approval:{...o.approval,approved:n},state:"approval-responded"}}return{...r,parts:s}})}function KC(e,t,n){return e.map(r=>{if(r.id!==t)return r;const s=[...r.parts],o=s.findIndex(d=>d.type==="structured-output"),i=o>=0?s[o]:null,a=(i?.raw??"")+n,l=BC(a),c=l??i?.partial,u={type:"structured-output",status:"streaming",raw:a,...c!==void 0?{partial:c}:{},...i?.reasoning!==void 0?{reasoning:i.reasoning}:{}};return o>=0?s[o]=u:s.push(u),{...r,parts:s}})}function YC(e,t,n,r,s){return e.map(o=>{if(o.id!==t)return o;const i=[...o.parts],a=i.findIndex(d=>d.type==="structured-output"),l=a>=0?i[a].raw:"";let c=r||l;if(c===""&&n!==void 0)try{c=JSON.stringify(n)}catch{}const u={type:"structured-output",status:"complete",data:n,partial:n,raw:c,...s!==void 0?{reasoning:s}:{}};return a>=0?i[a]=u:i.push(u),{...o,parts:i}})}function Ka(e,t,n){return e.map(r=>{if(r.id!==t)return r;const s=[...r.parts],o=s.findIndex(a=>a.type==="structured-output");if(o<0)return s.push({type:"structured-output",status:"error",raw:"",errorMessage:n}),{...r,parts:s};const i=s[o];return i.status==="complete"?r:(s[o]={...i,status:"error",errorMessage:n},{...r,parts:s})})}function vs(e,t,n,r,s){return e.map(o=>{if(o.id!==t)return o;const i=[...o.parts],a=i.findIndex(c=>c.type==="thinking"&&c.stepId===n),l={type:"thinking",content:r,stepId:n,...s&&{signature:s}};return a>=0?i[a]=l:i.push(l),{...o,parts:i}})}var WC=12;function XC(e){return e.some(t=>{const n=t.metadata;if(!n||typeof n!="object"||Array.isArray(n))return!1;const r=n[Ur];return r!==null&&typeof r=="object"&&!Array.isArray(r)&&r.kind==="generic"})}var QC=class Pd{chunkStrategy;events;jsonParser;recordingEnabled;messages=[];messageStates=new Map;activeMessageIds=new Set;toolCallToMessage=new Map;pendingManualMessageId=null;pendingThinkingStepId=null;structuredMessageIds=new Set;structuredOutputUpdateBatches=new Map;activeRuns=new Set;finishReason=null;hasError=!1;isDone=!1;streamEndEmitted=!1;recording=null;recordingStartTime=0;constructor(t={}){this.chunkStrategy=t.chunkStrategy||new GC,this.events=t.events||{},this.jsonParser=t.jsonParser||jd,this.recordingEnabled=t.recording??!1,t.initialMessages&&(this.messages=[...t.initialMessages])}setMessages(t){this.messages=[...t],this.emitMessagesChange()}prependMessages(t){const n=new Set(this.messages.map(s=>s.id)),r=[];for(const s of t)n.has(s.id)||(n.add(s.id),r.push(s));this.messages=[...r,...this.messages],this.emitMessagesChange()}addUserMessage(t,n,r){const s=typeof t=="string"?[{type:"text",content:t}]:t.map(i=>i),o={id:n??Et(),role:"user",parts:s,createdAt:new Date,...r!=null?{metadata:r}:{}};return this.messages=[...this.messages,o],this.emitMessagesChange(),o}prepareAssistantMessage(){this.resetStreamState()}startAssistantMessage(t){this.prepareAssistantMessage();const{messageId:n}=this.ensureAssistantMessage(t);return this.pendingManualMessageId=n,n}getCurrentAssistantMessageId(){let t=null;for(const[n,r]of this.messageStates)r.role==="assistant"&&(t=n);return t}addToolResult(t,n,r){const s=this.messages.find(l=>l.parts.some(c=>c.type==="tool-call"&&c.id===t));if(!s){console.warn(`[StreamProcessor] Could not find message with tool call ${t}`);return}let o=Va(this.messages,t,n,r?"error":void 0,r);const i=ko(n),a=r?"error":"complete";o=Ua(o,s.id,t,i,a,r),this.messages=o,this.emitMessagesChange()}addToolApprovalResponse(t,n){this.messages=VC(this.messages,t,n),this.emitMessagesChange()}toModelMessages(){const t=[];for(const n of this.messages)t.push(...SC(n));return t}getMessages(){return this.messages}areAllToolsComplete(){const t=this.messages.findLast(s=>s.role==="assistant");if(!t)return!0;const n=t.parts.filter(s=>s.type==="tool-call");if(n.length===0)return!0;const r=new Set(t.parts.filter(s=>s.type==="tool-result").map(s=>s.toolCallId));return n.every(s=>s.state==="complete"||s.state==="approval-responded"||s.output!==void 0&&!s.approval||r.has(s.id)||Ed(s))}removeMessagesAfter(t){const n=new Set(this.messages.slice(0,t+1).map(r=>r.id));for(const r of this.structuredMessageIds)n.has(r)||this.structuredMessageIds.delete(r);for(const r of this.structuredOutputUpdateBatches.keys())n.has(r)||this.structuredOutputUpdateBatches.delete(r);for(const r of this.messageStates.keys())n.has(r)||this.messageStates.delete(r);for(const[r,s]of this.toolCallToMessage)n.has(s)||this.toolCallToMessage.delete(r);for(const r of this.activeMessageIds)n.has(r)||this.activeMessageIds.delete(r);this.messages=this.messages.slice(0,t+1),this.emitMessagesChange()}clearMessages(){this.messages=[],this.messageStates.clear(),this.activeMessageIds.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.emitMessagesChange()}async process(t){this.resetStreamState(),this.recordingEnabled&&this.startRecording();for await(const n of t)this.processChunk(n);return this.finalizeStream(),this.recording&&(this.recording.result=this.getResult()),this.getResult()}processChunk(t){switch(this.recording&&this.recording.chunks.push({chunk:t,timestamp:Date.now(),index:this.recording.chunks.length}),t.type){case"TEXT_MESSAGE_START":this.handleTextMessageStartEvent(t);break;case"TEXT_MESSAGE_CONTENT":this.handleTextMessageContentEvent(t);break;case"TEXT_MESSAGE_END":this.handleTextMessageEndEvent(t);break;case"TOOL_CALL_START":this.handleToolCallStartEvent(t);break;case"TOOL_CALL_ARGS":this.handleToolCallArgsEvent(t);break;case"TOOL_CALL_END":this.handleToolCallEndEvent(t);break;case"RUN_FINISHED":this.handleRunFinishedEvent(t);break;case"RUN_ERROR":this.handleRunErrorEvent(t);break;case"STEP_FINISHED":this.handleStepFinishedEvent(t);break;case"MESSAGES_SNAPSHOT":this.handleMessagesSnapshotEvent(t);break;case"CUSTOM":this.handleCustomEvent(t);break;case"RUN_STARTED":this.handleRunStartedEvent(t);break;case"REASONING_START":case"REASONING_MESSAGE_START":case"REASONING_MESSAGE_END":case"REASONING_END":break;case"REASONING_MESSAGE_CONTENT":this.handleReasoningMessageContentEvent(t);break;case"REASONING_ENCRYPTED_VALUE":this.handleReasoningEncryptedValueEvent(t);break;case"TOOL_CALL_RESULT":this.handleToolCallResultEvent(t);break;case"STEP_STARTED":this.handleStepStartedEvent(t)}}createMessageState(t,n){const r={id:t,role:n,totalTextContent:"",currentSegmentText:"",lastEmittedText:"",hasSeenReasoningEvents:!1,thinkingSteps:new Map,thinkingStepSignatures:new Map,thinkingStepOrder:[],currentThinkingStepId:null,toolCalls:new Map,toolCallOrder:[],hasToolCallsSinceTextStart:!1,isComplete:!1};return this.messageStates.set(t,r),r}getMessageState(t){return this.messageStates.get(t)}consumePendingThinkingStep(t){if(!this.pendingThinkingStepId)return;const n=this.pendingThinkingStepId;t.currentThinkingStepId=n,t.thinkingSteps.has(n)||(t.thinkingSteps.set(n,""),t.thinkingStepOrder.push(n)),this.pendingThinkingStepId=null}getActiveAssistantMessageId(){const t=Array.from(this.activeMessageIds).reverse();for(const n of t){const r=this.messageStates.get(n);if(r&&r.role==="assistant")return n}for(const[n,r]of[...this.messageStates].reverse())if(r.role==="assistant")return n;return null}resumeAssistantState(t,n){this.activeMessageIds.add(t),(n.isComplete||this.isDone)&&(n.isComplete=!1,this.isDone=!1)}ensureAssistantMessage(t){if(t){const i=this.getMessageState(t);if(i)return this.resumeAssistantState(t,i),{messageId:t,state:i}}const n=this.getActiveAssistantMessageId();if(n){const i=this.getMessageState(n);if(i)return this.resumeAssistantState(n,i),{messageId:n,state:i}}if(t){const i=this.messages.find(a=>a.id===t);if(i){const a=this.createMessageState(t,i.role);this.activeMessageIds.add(t);const l=i.parts.length>0?i.parts[i.parts.length-1]:null;return l&&l.type==="text"&&(a.currentSegmentText=l.content,a.lastEmittedText=l.content,a.totalTextContent=l.content),{messageId:t,state:a}}}const r=t||Et(),s={id:r,role:"assistant",parts:[],createdAt:new Date};this.messages=[...this.messages,s];const o=this.createMessageState(r,"assistant");return this.activeMessageIds.add(r),this.pendingManualMessageId=r,this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:r,state:o}}mergeMessageMetadata(t,n){if(n==null||typeof n!="object"||Array.isArray(n))return;const r=this.messages.find(u=>u.id===t);if(!r)return;const s=n,o=ae(s),i=o!=null&&("content"in o||"args"in o)?{...s,tanstack:Object.fromEntries(Object.entries(o).filter(([u])=>u!=="content"&&u!=="args"))}:s,a=vd(r.metadata,i),l=Ae(ae(s)?.createdAt),c=l!==void 0;this.messages=this.messages.map(u=>u.id===t?{...u,...a!==void 0?{metadata:a}:{},...c?{createdAt:l}:{}}:u),this.emitMessagesChange()}handleTextMessageStartEvent(t){const{messageId:n,role:r}=t,s=r==="user"||r==="system"?r:"assistant";if(this.pendingManualMessageId){const i=this.pendingManualMessageId;if(this.pendingManualMessageId=null,i!==n){this.messages=this.messages.map(c=>c.id===i?{...c,id:n}:c);const l=this.messageStates.get(i);l&&(l.id=n,this.messageStates.delete(i),this.messageStates.set(n,l)),this.activeMessageIds.delete(i),this.activeMessageIds.add(n);for(const[c,u]of this.toolCallToMessage)u===i&&this.toolCallToMessage.set(c,n)}let a=this.messageStates.get(n);a?a.hasToolCallsSinceTextStart&&(a.currentSegmentText!==a.lastEmittedText&&this.emitTextUpdateForMessage(n),a.currentSegmentText="",a.lastEmittedText="",a.hasToolCallsSinceTextStart=!1):(a=this.createMessageState(n,s),this.activeMessageIds.add(n)),this.mergeMessageMetadata(n,t.metadata),this.emitMessagesChange();return}if(this.messages.find(i=>i.id===n)){this.activeMessageIds.add(n);const i=this.messageStates.get(n);i?i.hasToolCallsSinceTextStart&&(i.currentSegmentText!==i.lastEmittedText&&this.emitTextUpdateForMessage(n),i.currentSegmentText="",i.lastEmittedText="",i.hasToolCallsSinceTextStart=!1):this.createMessageState(n,s),this.mergeMessageMetadata(n,t.metadata);return}const o={id:n,role:s,parts:[],createdAt:new Date};this.messages=[...this.messages,o],this.createMessageState(n,s),this.activeMessageIds.add(n),this.mergeMessageMetadata(n,t.metadata),this.events.onStreamStart?.(),this.emitMessagesChange()}handleTextMessageEndEvent(t){const{messageId:n}=t;this.mergeMessageMetadata(n,t.metadata);const r=this.getMessageState(n);r&&(r.isComplete||r.currentSegmentText!==r.lastEmittedText&&this.emitTextUpdateForMessage(n))}handleMessagesSnapshotEvent(t){this.resetStreamState();const n=this.messages,r=new Map(n.map(o=>[o.id,o])),s=this.mergeReasoningFanOut(t.messages.map(CC));this.messages=this.reconcileSnapshotToolCalls(s,n).map(o=>{if(o.metadata!=null)return o;const i=r.get(o.id);return i?.metadata==null?o:{...o,metadata:i.metadata}}),this.emitMessagesChange()}mergeReasoningFanOut(t){const n=[];let r=[];const s=l=>l.parts.filter(c=>c.type==="thinking"),o=l=>l.role==="assistant"&&l.parts.length>0&&l.parts.every(c=>c.type==="thinking"),i=l=>l.role==="assistant"&&l.parts.some(c=>c.type==="tool-result")&&l.parts.every(c=>c.type==="tool-result"||c.type==="ui-resource"),a=()=>{n.push(...r),r=[]};for(const l of t){if(o(l)){r.push(l);continue}if(l.role==="assistant"&&r.length>0&&!i(l)){n.push({...l,parts:[...r.flatMap(s),...l.parts]}),r=[];continue}a(),n.push(l)}return a(),n}reconcileSnapshotToolCalls(t,n){const r=new Map;for(const i of n)for(const a of i.parts)a.type==="tool-call"&&r.set(a.id,a);const s=new Set;for(const i of t)for(const a of i.parts)a.type==="tool-call"&&s.add(a.id);const o=[];for(const i of t){const a=i.parts.filter(d=>d.type==="tool-result"),l=i.role==="assistant"&&a.length===1&&i.parts.every(d=>d.type==="tool-result"||d.type==="ui-resource")?a[0]:void 0;if(!l){o.push(i);continue}const c=o.findLast(d=>d.parts.some(f=>f.type==="tool-call"&&f.id===l.toolCallId))??o.findLast(d=>d.role==="assistant"&&!(d.parts.length===1&&d.parts[0]?.type==="tool-result"));if(!c){s.has(l.toolCallId)||console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${l.toolCallId}" but no matching tool-call exists in the snapshot, and there is no assistant message to anchor into; addToolResult("${l.toolCallId}") will not be able to locate this call`),o.push(i);continue}const u=[...c.parts];if(!s.has(l.toolCallId)&&!u.some(d=>d.type==="tool-call"&&d.id===l.toolCallId)){const d=r.get(l.toolCallId);d?(u.push({...d}),s.add(d.id)):console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${l.toolCallId}" but no matching tool-call exists in the snapshot or the pre-snapshot state; addToolResult("${l.toolCallId}") will not be able to locate this call`)}u.push(...i.parts),c.parts=u}return this.enrichSnapshotToolCallsFromResults(o,r)}enrichSnapshotToolCallsFromResults(t,n){const r=new Map;for(const s of t)for(const o of s.parts)o.type==="tool-result"&&r.set(o.toolCallId,o);return t.map(s=>{const o=s.parts.map(i=>{if(i.type!=="tool-call")return i;const a=n.get(i.id),l=r.get(i.id);let c=i;if(a&&(a.output!==void 0||a.state==="complete"||a.state==="error")&&(i.output===void 0||i.state==="input-complete"||i.state==="input-streaming"||i.state==="awaiting-input")&&(c={...i,...a.output!==void 0?{output:a.output}:{},state:a.state,...a.approval!==void 0?{approval:a.approval}:{},...a.metadata!==void 0?{metadata:a.metadata}:{}}),l&&c.output===void 0){let u;if(Array.isArray(l.content))u=l.content;else try{u=JSON.parse(l.content)}catch{u=l.content}const d=l.state==="error"?this.extractToolResultError(u):void 0;c={...c,output:d?{error:d}:u,state:l.state==="error"?"error":"complete"}}return c});return o.some((i,a)=>i!==s.parts[a])?{...s,parts:o}:s})}handleTextMessageContentEvent(t){const{messageId:n,state:r}=this.ensureAssistantMessage(t.messageId);if(this.mergeMessageMetadata(n,t.metadata),this.structuredMessageIds.has(n)){const u=t.delta||"";u!==""&&(this.messages=KC(this.messages,n,u),r.totalTextContent+=u,this.queueStructuredOutputUpdate(n,u),this.emitMessagesChange());return}const s=r.currentSegmentText;r.hasToolCallsSinceTextStart&&s.length>0&&this.isNewTextSegment(t,s)&&(s!==r.lastEmittedText&&this.emitTextUpdateForMessage(n),r.currentSegmentText="",r.lastEmittedText="",r.hasToolCallsSinceTextStart=!1),r.hasToolCallsSinceTextStart=!1;const o=r.currentSegmentText,i=t.delta||"",a=i!==""?o+i:o,l=a.slice(o.length);r.currentSegmentText=a,r.totalTextContent+=l;const c=t.delta||"";this.chunkStrategy.shouldEmit(c,r.currentSegmentText)&&r.currentSegmentText!==r.lastEmittedText&&this.emitTextUpdateForMessage(n)}handleToolCallStartEvent(t){const n=t.parentMessageId??this.getActiveAssistantMessageId(),{messageId:r,state:s}=this.ensureAssistantMessage(n??void 0);s.hasToolCallsSinceTextStart=!0;const o=t.toolCallId;if(!s.toolCalls.get(o)){const i="awaiting-input",a=t.toolCallName,l=t.metadata,c={id:t.toolCallId,name:a,arguments:"",state:i,parsedArguments:void 0,index:s.toolCalls.size,...l!==void 0&&{metadata:l}};s.toolCalls.set(o,c),s.toolCallOrder.push(o),this.toolCallToMessage.set(o,r),this.messages=Yn(this.messages,r,{id:t.toolCallId,name:a,arguments:"",state:i,...l!==void 0&&{metadata:l}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(r,t.toolCallId,i,"")}}handleToolCallArgsEvent(t){const n=t.toolCallId,r=this.toolCallToMessage.get(n);if(!r)return;const s=this.getMessageState(r);if(!s)return;const o=s.toolCalls.get(n);if(!o)return;const i=o.state==="awaiting-input";o.arguments+=t.delta||"",i&&t.delta&&(o.state="input-streaming"),o.parsedArguments=this.jsonParser.parse(o.arguments),this.messages=Yn(this.messages,r,{id:o.id,name:o.name,arguments:o.arguments,state:o.state}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(r,o.id,o.state,o.arguments)}handleToolCallEndEvent(t){const n=this.toolCallToMessage.get(t.toolCallId);if(!n)return;const r=this.getMessageState(n);if(!r)return;const s=t.input!==void 0?t.input:ae(t)?.input,o=r.toolCalls.get(t.toolCallId);if(o&&o.state!=="input-complete"){if(s!==void 0&&!o.arguments)try{o.arguments=JSON.stringify(s)}catch{}const i=r.toolCallOrder.indexOf(t.toolCallId);this.completeToolCall(n,i,o),s!==void 0&&(o.parsedArguments=s,this.messages=Yn(this.messages,n,{id:o.id,name:o.name,arguments:o.arguments,state:"input-complete",input:s,...o.metadata!==void 0&&{metadata:o.metadata}}),this.emitMessagesChange())}}extractToolResultError(t){return t&&typeof t=="object"&&"error"in t&&typeof t.error=="string"?t.error:typeof t=="string"?t:"Tool execution failed"}handleToolCallResultEvent(t){const n=this.toolCallToMessage.get(t.toolCallId)??this.messages.find(i=>i.parts.some(a=>a.type==="tool-call"&&a.id===t.toolCallId))?.id;if(!n)return;const r=t.state==="output-error"||ae(t)?.state==="output-error";let s;try{s=JSON.parse(t.content)}catch{s=t.content}this.messages=Va(this.messages,t.toolCallId,s,r?"error":void 0);const o=r?"error":"complete";this.messages=Ua(this.messages,n,t.toolCallId,t.content,o,o==="error"?this.extractToolResultError(s):void 0),this.emitMessagesChange()}handleRunStartedEvent(t){this.activeRuns.add(t.runId)}handleRunFinishedEvent(t){const n=t;if(this.finishReason=n.finishReason!==void 0?n.finishReason:ae(t)?.finishReason??null,this.activeRuns.delete(t.runId),t.outcome?.type==="interrupt"&&this.handleInterrupts(t.outcome.interrupts),this.activeRuns.size===0){if(this.completeAllToolCalls(),this.finishReason==="tool_calls"&&t.outcome?.type!=="interrupt")return;this.isDone=!0,this.finalizeStream()}}handleInterrupts(t){const n=XC(t);for(const r of t){const s=r.metadata&&typeof r.metadata=="object"?r.metadata:{},o=typeof s.kind=="string"?s.kind:void 0,i=r.toolCallId;if(!i)continue;const a=typeof s.toolName=="string"?s.toolName:this.findToolCallName(i),l=Object.hasOwn(s,"input")?s.input:{};if(o==="approval"||r.reason==="approval_required"){const c=this.getActiveAssistantMessageId()??this.toolCallToMessage.get(i)??this.messages.find(u=>u.role==="assistant"&&u.parts.some(d=>d.type==="tool-call"&&d.id===i))?.id;c&&(this.messages=qa(this.messages,c,i,r.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:i,toolName:a,input:l,approvalId:r.id});continue}if(o==="client_tool"||r.reason==="client_tool_input"){if(n)continue;this.events.onToolCall?.({toolCallId:i,toolName:a,input:l})}}}findToolCallName(t){for(const n of this.messageStates.values()){const r=n.toolCalls.get(t);if(r)return r.name}return""}handleRunErrorEvent(t){this.hasError=!0;const n=Od(t);n?this.activeRuns.delete(n):this.activeRuns.clear();const{messageId:r}=this.ensureAssistantMessage(),s=t.message||"An error occurred";t.message||console.error("[StreamProcessor] RUN_ERROR with no message; original chunk:",t),this.structuredMessageIds.has(r)&&(this.flushStructuredOutputUpdate(r),this.messages=Ka(this.messages,r,s),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,"error"),this.emitMessagesChange()),this.events.onError?.(UC(t))}handleStepStartedEvent(t){const n=t.stepName||Et(),r=this.getActiveAssistantMessageId();if(r){const s=this.getMessageState(r);if(s){s.currentThinkingStepId=n,s.thinkingSteps.has(n)||(s.thinkingSteps.set(n,""),s.thinkingStepOrder.push(n)),this.pendingThinkingStepId=null;return}}this.pendingThinkingStepId=n}handleStepFinishedEvent(t){const n=t,r=n.signature;if(!r)return;const{messageId:s,state:o}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),i=o.currentThinkingStepId??n.stepId;if(!i)return;const a=o.thinkingSteps.get(i);a!==void 0&&(o.thinkingStepSignatures.set(i,r),this.messages=vs(this.messages,s,i,a,r),this.emitMessagesChange())}handleReasoningMessageContentEvent(t){const{messageId:n,state:r}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);r.hasSeenReasoningEvents=!0;const s=t.delta||"";this.consumePendingThinkingStep(r);const o=r.currentThinkingStepId??t.messageId;r.thinkingSteps.has(o)||(r.thinkingSteps.set(o,""),r.thinkingStepOrder.push(o),r.currentThinkingStepId=o);const i=(r.thinkingSteps.get(o)??"")+s;r.thinkingSteps.set(o,i),this.messages=vs(this.messages,n,o,i,r.thinkingStepSignatures.get(o)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(n,o,i)}handleReasoningEncryptedValueEvent(t){const n=t.encryptedValue;if(typeof n!="string"||n==="")return;if(t.subtype==="tool-call"){this.attachToolCallSignature(t.entityId,n);return}const{messageId:r,state:s}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),o=s.currentThinkingStepId??t.entityId;s.thinkingStepSignatures.set(o,n);const i=s.thinkingSteps.get(o)??"";s.thinkingSteps.has(o)||(s.thinkingSteps.set(o,i),s.thinkingStepOrder.push(o)),this.messages=vs(this.messages,r,o,i,n),this.emitMessagesChange()}attachToolCallSignature(t,n){this.messages=this.messages.map(r=>{let s=!1;const o=r.parts.map(i=>i.type!=="tool-call"||i.id!==t?i:(s=!0,{...i,metadata:{...i.metadata!=null&&typeof i.metadata=="object"?i.metadata:{},thoughtSignature:n}}));return s?{...r,parts:o}:r});for(const r of this.messageStates.values()){const s=r.toolCalls.get(t);s&&(s.metadata={...s.metadata??{},thoughtSignature:n})}this.emitMessagesChange()}handleCustomEvent(t){const n=this.getActiveAssistantMessageId();if(t.name==="structured-output.start"&&t.value){const r=t.value,{messageId:s}=this.ensureAssistantMessage(r.messageId??n??void 0);s&&(this.structuredMessageIds.add(s),this.structuredOutputUpdateBatches.delete(s),this.events.onStructuredOutputChange?.({phase:"start",messageId:s,status:"streaming",raw:""}));return}if(t.name==="structured-output.complete"&&t.value){const r=t.value,{messageId:s}=this.ensureAssistantMessage(r.messageId??n??void 0);s&&(this.flushStructuredOutputUpdate(s),this.messages=YC(this.messages,s,r.object,r.raw??"",r.reasoning),this.structuredMessageIds.delete(s),this.emitStructuredOutputChange(s,"complete"),this.emitMessagesChange())}if(t.name==="tool-input-available"&&t.value){const{toolCallId:r,toolName:s,input:o}=t.value;this.events.onToolCall?.({toolCallId:r,toolName:s,input:o});return}if(t.name==="approval-requested"&&t.value){const{toolCallId:r,toolName:s,input:o,approval:i}=t.value,a=n??this.toolCallToMessage.get(r);a&&(this.messages=qa(this.messages,a,r,i.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:r,toolName:s,input:o,approvalId:i.id});return}if(t.name==="ui-resource"&&t.value){const r=t.value,s=this.toolCallToMessage.get(r.toolCallId)??n;if(s){const o={type:"ui-resource",resource:r.resource,toolCallId:r.toolCallId,toolName:r.toolName,...r.serverId!==void 0&&{serverId:r.serverId},...r.meta!==void 0&&{meta:r.meta}};this.messages=this.messages.map(i=>i.id===s?{...i,parts:[...i.parts,o]}:i),this.emitMessagesChange()}else console.warn(`[mcp-apps] dropped ui-resource: no target message for toolCallId "${r.toolCallId}" (toolName "${r.toolName}")`);return}if(this.events.onCustomEvent){const r=t.value&&typeof t.value=="object"?t.value.toolCallId:void 0;this.events.onCustomEvent(t.name,t.value,{toolCallId:r})}}isNewTextSegment(t,n){return!0}completeAllToolCalls(){for(const t of this.activeMessageIds)this.completeAllToolCallsForMessage(t)}completeAllToolCallsForMessage(t){const n=this.getMessageState(t);n&&n.toolCalls.forEach((r,s)=>{if(r.state!=="input-complete"){const o=n.toolCallOrder.indexOf(s);this.completeToolCall(t,o,r)}})}completeToolCall(t,n,r){r.state="input-complete";let s=!1;try{r.parsedArguments=JSON.parse(r.arguments),s=!0}catch{r.parsedArguments=void 0}this.isToolCallPartErrored(r.id)||this.isToolCallPartAwaitingUserAction(r.id)||(this.messages=Yn(this.messages,t,{id:r.id,name:r.name,arguments:r.arguments,state:"input-complete",...s&&{input:r.parsedArguments},...r.metadata!==void 0&&{metadata:r.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(t,r.id,"input-complete",r.arguments))}isToolCallPartAwaitingUserAction(t){return this.messages.some(n=>n.parts?.some(r=>r.type==="tool-call"&&r.id===t&&(r.state==="approval-requested"||r.state==="approval-responded")))}isToolCallPartErrored(t){return this.messages.some(n=>n.parts?.some(r=>r.type==="tool-call"&&r.id===t&&r.state==="error"))}emitTextUpdateForMessage(t){const n=this.getMessageState(t);n&&(n.lastEmittedText=n.currentSegmentText,this.messages=qC(this.messages,t,n.currentSegmentText),this.emitMessagesChange(),this.events.onTextUpdate?.(t,n.currentSegmentText))}queueStructuredOutputUpdate(t,n){const r=this.structuredOutputUpdateBatches.get(t),s={delta:`${r?.delta??""}${n}`,chunkCount:(r?.chunkCount??0)+1};this.structuredOutputUpdateBatches.set(t,s),s.chunkCount>=WC&&this.flushStructuredOutputUpdate(t)}flushStructuredOutputUpdate(t){const n=this.structuredOutputUpdateBatches.get(t);!n||n.chunkCount===0||(this.structuredOutputUpdateBatches.delete(t),this.emitStructuredOutputChange(t,"update",n.delta))}emitStructuredOutputChange(t,n,r){const s=this.messages.find(o=>o.id===t)?.parts.find(o=>o.type==="structured-output");s&&this.events.onStructuredOutputChange?.({phase:n,messageId:t,status:s.status,raw:s.raw,...s.partial!==void 0?{partial:s.partial}:{},...s.data!==void 0?{data:s.data}:{},...s.reasoning!==void 0?{reasoning:s.reasoning}:{},...s.errorMessage!==void 0?{errorMessage:s.errorMessage}:{},...r!==void 0?{delta:r}:{}})}emitMessagesChange(){this.events.onMessagesChange?.([...this.messages])}finalizeStream(){this.isDone=!0;let t;for(const n of this.activeMessageIds){const r=this.getMessageState(n);if(!r)continue;this.completeAllToolCallsForMessage(n),r.currentSegmentText!==r.lastEmittedText&&this.emitTextUpdateForMessage(n),r.isComplete=!0;const s=this.messages.find(o=>o.id===n);s&&s.role==="assistant"&&(t=s)}for(const n of this.structuredMessageIds)this.flushStructuredOutputUpdate(n),this.messages=Ka(this.messages,n,"Stream ended without structured-output.complete"),this.emitStructuredOutputChange(n,"error");if(this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.activeMessageIds.clear(),t&&!this.hasError&&this.isWhitespaceOnlyMessage(t)){this.messages=this.messages.filter(n=>n.id!==t.id),this.emitMessagesChange();return}t&&!this.streamEndEmitted&&(this.streamEndEmitted=!0,this.events.onStreamEnd?.(t))}getCompletedToolCalls(){const t=[];for(const n of this.messageStates.values())for(const r of n.toolCalls.values())r.state==="input-complete"&&t.push({id:r.id,type:"function",function:{name:r.name,arguments:r.arguments},...r.metadata!==void 0&&{metadata:r.metadata}});return t}getResult(){const t=this.getCompletedToolCalls();let n="",r="";for(const s of this.messageStates.values()){n+=s.totalTextContent;for(const o of s.thinkingStepOrder)r+=s.thinkingSteps.get(o)??""}return{content:n,thinking:r||void 0,toolCalls:t.length>0?t:void 0,finishReason:this.finishReason}}getState(){let t="",n="";const r=new Map,s=[];for(const o of this.messageStates.values()){t+=o.totalTextContent;for(const i of o.thinkingStepOrder)n+=o.thinkingSteps.get(i)??"";for(const[i,a]of o.toolCalls)r.set(i,a);s.push(...o.toolCallOrder)}return{content:t,thinking:n,toolCalls:r,toolCallOrder:s,finishReason:this.finishReason,done:this.isDone}}startRecording(){this.recordingEnabled=!0,this.recordingStartTime=Date.now(),this.recording={version:"1.0",timestamp:this.recordingStartTime,chunks:[]}}getRecording(){return this.recording}resetStreamState(){this.messageStates.clear(),this.activeMessageIds.clear(),this.activeRuns.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.pendingThinkingStepId=null,this.finishReason=null,this.hasError=!1,this.isDone=!1,this.streamEndEmitted=!1,this.chunkStrategy.reset?.()}reset(){this.resetStreamState(),this.messages=[]}isWhitespaceOnlyMessage(t){return t.parts.length===0?!1:t.parts.every(n=>n.type==="text"&&n.content.trim()==="")}static async replay(t,n){return new Pd(n).process(JC(t))}};function JC(e){return{async*[Symbol.asyncIterator](){for(const{chunk:t}of e.chunks)yield t}}}var Ys=(function(e){return e.TEXT_MESSAGE_START="TEXT_MESSAGE_START",e.TEXT_MESSAGE_CONTENT="TEXT_MESSAGE_CONTENT",e.TEXT_MESSAGE_END="TEXT_MESSAGE_END",e.TEXT_MESSAGE_CHUNK="TEXT_MESSAGE_CHUNK",e.TOOL_CALL_START="TOOL_CALL_START",e.TOOL_CALL_ARGS="TOOL_CALL_ARGS",e.TOOL_CALL_END="TOOL_CALL_END",e.TOOL_CALL_CHUNK="TOOL_CALL_CHUNK",e.TOOL_CALL_RESULT="TOOL_CALL_RESULT",e.THINKING_START="THINKING_START",e.THINKING_END="THINKING_END",e.THINKING_TEXT_MESSAGE_START="THINKING_TEXT_MESSAGE_START",e.THINKING_TEXT_MESSAGE_CONTENT="THINKING_TEXT_MESSAGE_CONTENT",e.THINKING_TEXT_MESSAGE_END="THINKING_TEXT_MESSAGE_END",e.STATE_SNAPSHOT="STATE_SNAPSHOT",e.STATE_DELTA="STATE_DELTA",e.MESSAGES_SNAPSHOT="MESSAGES_SNAPSHOT",e.ACTIVITY_SNAPSHOT="ACTIVITY_SNAPSHOT",e.ACTIVITY_DELTA="ACTIVITY_DELTA",e.RAW="RAW",e.CUSTOM="CUSTOM",e.RUN_STARTED="RUN_STARTED",e.RUN_FINISHED="RUN_FINISHED",e.RUN_ERROR="RUN_ERROR",e.STEP_STARTED="STEP_STARTED",e.STEP_FINISHED="STEP_FINISHED",e.REASONING_START="REASONING_START",e.REASONING_MESSAGE_START="REASONING_MESSAGE_START",e.REASONING_MESSAGE_CONTENT="REASONING_MESSAGE_CONTENT",e.REASONING_MESSAGE_END="REASONING_MESSAGE_END",e.REASONING_MESSAGE_CHUNK="REASONING_MESSAGE_CHUNK",e.REASONING_END="REASONING_END",e.REASONING_ENCRYPTED_VALUE="REASONING_ENCRYPTED_VALUE",e})({}),Ld=new WeakMap;function Re(e){return Ld.get(e)??Od(e)}var Dd=class extends Error{constructor(){super("Stream ended with unterminated trailing data — connection was likely cut short."),this.name="StreamTruncatedError"}},Oo=class extends Error{constructor(e){super("Stream response body read failed",{cause:e}),this.name="StreamReadError"}},ZC=class extends Error{constructor(){super("Durable run ended without a terminal event and could not resume — the run did not complete."),this.name="DurableStreamIncompleteError"}},eN=class extends Error{constructor(e){super(`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`),this.name="StreamReconnectLimitError"}};function tN(e){const t=e?.maxAttempts??5,n=e?.delayMs??250;if(!Number.isInteger(t)||t<0)throw new Error(`Invalid reconnect.maxAttempts: ${t}. Must be a non-negative integer.`);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid reconnect.delayMs: ${n}. Must be a non-negative finite number.`);return{maxAttempts:t,delayMs:n}}function nN(e){const t=tN(e),n=new Set;let r,s=0;return{get lastEventId(){return r},note(o){return o===void 0?"new":o===""?(r=void 0,n.clear(),"reset"):n.has(o)?"duplicate":(n.add(o),r=o,"new")},async waitBeforeReconnect(o,i){if(o)s=0;else if(s+=1,s>t.maxAttempts)throw new eN(t.maxAttempts);await rN(t.delayMs,i)}}}function rN(e,t){return e<=0||t?.aborted?Promise.resolve():new Promise(n=>{const r=()=>{clearTimeout(s),n()},s=setTimeout(()=>{t?.removeEventListener("abort",r),n()},e);t?.addEventListener("abort",r,{once:!0})})}function Ya(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Wn(e,t){if(!e)throw new Error(`Cannot synthesize terminal event: ${t} not supplied via runContext and not observed in the upstream stream.`);return e}function ln(e){if(!e)return{};if(e instanceof Headers){const t={};return e.forEach((n,r)=>{t[r]=n}),t}return e}var sN="X-Run-Id";function oN(e){return e===void 0?{}:{[sN]:e}}function jo(e,t){const n=e.indexOf("#"),r=n===-1?"":e.slice(n),s=n===-1?e:e.slice(0,n),o=s.indexOf("?"),i=o===-1?s:s.slice(0,o),a=new URLSearchParams(o===-1?"":s.slice(o+1));for(const[c,u]of Object.entries(t))a.set(c,u);const l=a.toString();return`${i}${l.length===0?"":`?${l}`}${r}`}async function*iN(e,t){try{const n=zE();let r="";for(;!t?.aborted;){let s;try{s=await e.read()}catch(l){if(t?.aborted)return;throw new Oo(l)}const{done:o,value:i}=s;if(o)break;r+=n.decode(i,{stream:!0});const a=r.split(`
|
|
10
|
+
`);r=a.pop()||"";for(const l of a){const c=l.endsWith("\r")?l.slice(0,-1):l;c.trim()&&(yield c)}}if(r+=n.decode(),r.trim()&&!t?.aborted)throw new Dd}finally{e.releaseLock()}}function aN(e){return kd(e)}function lN(e){const t=ae(e)?.model;if(typeof t=="string")return t;const n="usage"in e?e.usage:void 0;if(Array.isArray(n)){const r=n[0]?.model;if(typeof r=="string")return r}}async function*cN(e,t){let n,r,s,o;for await(const i of e){if(i==="id"||i.startsWith("id:")){const d=i==="id"?"":i.slice(3);o=d.startsWith(" ")?d.slice(1):d;continue}if(i.startsWith(":")||i.startsWith("event:")||i.startsWith("retry:"))continue;const a=HE(i);if(a==="[DONE]"){yield{chunk:yd({type:Ys.RUN_FINISHED,threadId:n??t?.threadId??"",runId:r??t?.runId??"",timestamp:Date.now()},{finishReason:"stop",...s!==void 0?{model:s}:{}})};return}const l=aN(JSON.parse(a));"threadId"in l&&typeof l.threadId=="string"&&(n=l.threadId),"runId"in l&&typeof l.runId=="string"&&(r=l.runId);const c=lN(l);c!==void 0&&(s=c);const u=o;o=void 0,yield{chunk:l,...u!==void 0?{id:u}:{}}}}async function Po(e){if(!e.ok){if(e.status===401){const t=await e.clone().json().catch(()=>null);if(kE(t))throw new Fs(t.error.provider)}throw new Error(`HTTP error! status: ${e.status} ${e.statusText}`)}}function uN(e,t){const n={threadId:e};return t?.limit!==void 0&&(n.limit=String(t.limit)),t?.before!==void 0&&(n.before=t.before),n}function dN(e){return e===null||typeof e!="object"?{truncated:!1}:!("truncated"in e)||e.truncated!==!0?{truncated:!1}:!("cursor"in e)||typeof e.cursor!="string"||e.cursor===""?{truncated:!1}:{truncated:!0,cursor:e.cursor}}async function hN(e,t,n,r,s,o){const i=await e(jo(t,uN(s,o)),{method:"GET",headers:{Accept:"application/json",...n},credentials:r});await Po(i);const a=await i.json(),l=a.activeRun&&typeof a.activeRun.runId=="string"?{runId:a.activeRun.runId}:null,c=a.interrupts&&typeof a.interrupts.runId=="string"&&Array.isArray(a.interrupts.pending)&&a.interrupts.pending.length>0?{runId:a.interrupts.runId,pending:a.interrupts.pending}:null;return{messages:Array.isArray(a.messages)?Hs(a.messages):[],activeRun:l,interrupts:c,page:dN(a.page)}}async function fN(e,t,n,r,s){const o=await e(jo(t,{threadId:s}),{method:"GET",headers:{Accept:"application/json",...n},credentials:r});await Po(o);const i=await o.json();if(i===null)return{resumeSnapshot:null,activeRun:null};if(typeof i!="object"||Array.isArray(i))throw new Error(`Generation hydration expected a JSON object from ${t}, received ${Array.isArray(i)?"an array":typeof i}.`);const a=i,l=a.activeRun&&typeof a.activeRun.runId=="string"?{runId:a.activeRun.runId}:null;return{resumeSnapshot:a.resumeSnapshot??null,activeRun:l}}async function*Ws(e,t,n){await Po(e),yield*cN(iN(FE(e),t),n)}async function*pN(e,t){for await(const{chunk:n}of Ws(e,t))yield n}function Wa(e,t,n,r){return async function*(s,o){let i;try{i=await e(t,{...n,headers:{...n.headers,...s},...o?{signal:o}:{}})}catch(a){throw new Oo(a)}yield*r(i,o)}}async function*Xa(e,t,n){const r=nN(n);for(;;){if(t?.aborted)return;const s=r.lastEventId!==void 0?{"Last-Event-ID":r.lastEventId}:{};let o=!1,i=!1;try{for await(const{chunk:a,id:l}of e(s,t))r.note(l)!=="duplicate"&&(i=!0,(a.type==="RUN_FINISHED"||a.type==="RUN_ERROR")&&(o=!0),yield a)}catch(a){if(t?.aborted)return;if((a instanceof Dd||a instanceof Oo)&&r.lastEventId!==void 0){await r.waitBeforeReconnect(i,t);continue}throw a}if(t?.aborted||o)return;if(r.lastEventId!==void 0){if(i){await r.waitBeforeReconnect(!0,t);continue}throw new ZC}return}}function Qa(e){if(!e)throw new Error("Connection adapter is required");const t="connect"in e,n="subscribe"in e,r="send"in e;if(t&&(n||r))throw new Error("Connection adapter must provide either connect or both subscribe and send, not both modes");if(n&&r){const c=e.joinRun?.bind(e),u=e.hydrate?.bind(e);return{subscribe:e.subscribe.bind(e),send:e.send.bind(e),...c?{joinRun:c}:{},...u?{hydrate:u}:{}}}if(!t)throw new Error("Connection adapter must provide either connect or both subscribe and send");let s=[],o=[],i;function a(c,u){u&&Ld.set(c,u);const d=o.shift();d?d(c):s.push(c)}async function l(c){const u=()=>i!==o||s.length===0&&(o.length>0||c?.aborted);for(let d=0;d<16&&!c?.aborted;d++){if(u())return;await Promise.resolve()}for(;!c?.aborted;){if(u())return;await new Promise(d=>setTimeout(d,0))}}return{subscribe(c){const u=s.splice(0),d=[];return s=u,o=d,(async function*(){i=d;try{for(;!c?.aborted;){let f;const g=u.shift();g!==void 0?f=g:f=await new Promise(p=>{const y=()=>p(null);d.push(x=>{c?.removeEventListener("abort",y),p(x)}),c?.addEventListener("abort",y,{once:!0})}),f!==null&&(yield f)}}finally{i===d&&(i=void 0)}})()},async send(c,u,d,f){let g=!1,p,y;try{const x=e.connect(c,u,d,f);for await(const v of x)"threadId"in v&&typeof v.threadId=="string"&&(p=v.threadId),"runId"in v&&typeof v.runId=="string"&&(y=v.runId),(v.type==="RUN_FINISHED"||v.type==="RUN_ERROR")&&(g=!0),a(v,f?.runId);!d?.aborted&&!g&&a(yd({type:Ys.RUN_FINISHED,threadId:Wn(p??f?.threadId,"threadId"),runId:Wn(y??f?.runId,"runId"),timestamp:Date.now()},{finishReason:"stop",model:"connect-wrapper"}),f?.runId)}catch(x){if(!d?.aborted&&!g)try{const v=x instanceof Error?x.message:"Unknown error in connect()";a({type:Ys.RUN_ERROR,threadId:Wn(p??f?.threadId,"threadId"),runId:Wn(y??f?.runId,"runId"),timestamp:Date.now(),message:v},f?.runId)}catch{}throw x}await l(d)},...typeof e.joinRun=="function"?{joinRun:(c,u)=>e.joinRun(c,u)}:{},...(()=>{const c=e.hydrate;return typeof c=="function"?{hydrate:(u,d)=>c(u,d)}:{}})()}}function gN(e,t,n,r){const s=_C(e),o={...r.body,...n?.forwardedProps??{},...t};return{threadId:n?.threadId??Ya("thread"),runId:n?.runId??Ya("run"),...n?.parentRunId!==void 0&&{parentRunId:n.parentRunId},...n?.resume!==void 0&&{resume:n.resume},state:{},messages:s,tools:n?.clientTools??[],context:[],forwardedProps:o,data:{...o}}}function W_(e,t={}){return{async*connect(n,r,s,o){const i=typeof e=="function"?e():e,a=typeof t=="function"?await t():t,l={"Content-Type":"application/json",...ln(a.headers),...ln(o?.headers),...oN(o?.runId)},c=gN(n,r,o,a),u=a.fetchClient??fetch,d=s||a.signal;yield*Xa(Wa(u,i,{method:"POST",headers:l,body:JSON.stringify(c),credentials:a.credentials||"same-origin"},(f,g)=>Ws(f,g,{...o?.threadId!==void 0?{threadId:o.threadId}:{},...o?.runId!==void 0?{runId:o.runId}:{}})),d,a.reconnect)},async*joinRun(n,r){const s=typeof e=="function"?e():e,o=typeof t=="function"?await t():t,i=jo(s,{offset:"-1",runId:n}),a={...ln(o.headers)},l=o.fetchClient??fetch,c=r||o.signal;yield*Xa(Wa(l,i,{method:"GET",headers:a,credentials:o.credentials||"same-origin"},(u,d)=>Ws(u,d,{runId:n})),c,o.reconnect)},async hydrate(n,r){const s=typeof e=="function"?e():e,o=typeof t=="function"?await t():t;return hN(o.fetchClient??fetch,s,ln(o.headers),o.credentials||"same-origin",n,r)},async hydrateGeneration(n){const r=typeof e=="function"?e():e,s=typeof t=="function"?await t():t;return fN(s.fetchClient??fetch,r,ln(s.headers),s.credentials||"same-origin",n)}}}function mN(e){return{async*connect(t,n,r,s){if(!r)throw new Error("fetcherToConnectionAdapter requires an AbortSignal — the chat client always supplies one.");if(!s)throw new Error("fetcherToConnectionAdapter requires a RunAgentInputContext — the chat client always supplies one.");const o=await e({messages:t,data:n,threadId:s.threadId,runId:s.runId,...s.parentRunId!==void 0?{parentRunId:s.parentRunId}:{},...s.resume!==void 0?{resume:s.resume}:{}},{signal:r,headers:s.headers});o instanceof Response?yield*pN(o,r):yield*vN(o,r)}}}async function*vN(e,t){if(t.aborted)return;const n=e[Symbol.asyncIterator](),r=new Promise(s=>{t.addEventListener("abort",()=>s({done:!0,value:void 0}),{once:!0})});try{for(;;){const s=await Promise.race([n.next(),r]);if(s.done)return;yield s.value}}finally{await n.return?.()}}function Qe(e){return e.resumable}function ys(e,t){const n=dC(e.descriptor);return n?{...t,metadata:uC(n)}:t}function yN(e){return"cancel"in e&&"clearResolution"in e}var bN=new Set(["invalid-payload","invalid-edited-args","invalid-tool-output","invalid-response-schema","unknown-interrupt","expired","stale","conflict","legacy-unsupported"]),xN=new Set(["incomplete-batch","item-validation-failed","unsupported-bulk-operation","async-resolver","inactive-transaction","mixed-provenance","transport","server","protocol","invalid-response-schema","expired","stale","conflict","legacy-submit-failed"]);function De(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function $d(e){return De(e)&&e.kind==="approval"&&typeof e.toolName=="string"&&"input"in e}function Fd(e){return De(e)&&e.kind==="client_tool"&&typeof e.toolName=="string"&&"input"in e}function SN(e){return $d(e.metadata)||Fd(e.metadata)}function Ja(e){return sC(e)}function IN(e){if(!De(e.metadata))return!1;const t=e.metadata[Ur];return!De(t)||t.v!==void 0&&t.v!==1?!1:t.kind==="generic"||t.kind==="tool-approval"||t.kind==="client-tool-execution"||"definitionId"in t||"key"in t||"batchIndex"in t||"payloadSchemaHash"in t}function wN(e){if(!De(e.metadata))return!1;const t=e.metadata[Ur];return!De(t)||t.kind!=="generic"?!1:"definitionId"in t||"key"in t||"batchIndex"in t||"payloadSchemaHash"in t}function EN(e){return e.metadata?.["tanstack:interruptPayload"]}function CN(e){return e==="tanstack:client_tool_execution"||e==="client_tool_input"}function gn(e){if(e.responseSchema!==void 0)try{return Mt(At(e.responseSchema))}catch{return}}function Za(e){if(e!==void 0)try{return aC(e)}catch{return}}function yt(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&"then"in e&&typeof e.then=="function"}function Xn(e,t,n){if(e===void 0)return{valid:!0,payload:t};if(ft(e)){const r=e["~standard"].validate(t),s=o=>o.issues?{code:n,message:o.issues[0]?.message??"Schema validation failed."}:{valid:!0,payload:o.value};return yt(r)?Promise.resolve(r).then(s):s(r)}return{valid:!0,payload:t}}function NN(e){for(const t of bN)if(t===e)return!0;return!1}function RN(e){for(const t of xN)if(t===e)return!0;return!1}function el(e){if(!De(e))return!1;const t=e.scope,n=e.code;return typeof n=="string"&&typeof e.message=="string"&&typeof e.retryable=="boolean"&&typeof e.threadId=="string"&&typeof e.interruptedRunId=="string"&&typeof e.generation=="number"?t==="item"?NN(n)&&typeof e.interruptId=="string"&&(e.source==="client"||e.source==="server"):t==="batch"&&RN(n)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(r=>typeof r=="string")&&(e.source==="client"||e.source==="server"||e.source==="transport"):!1}function _N(e){return el(e)?[e]:!De(e)||!Array.isArray(e.errors)?[]:e.errors.every(el)?e.errors:[]}function zd(e,t){if(e.length!==t.length)return!1;const n=[...e].sort(),r=[...t].sort();return n.every((s,o)=>s===r[o])}function tl(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&zd(e.interruptIds,t.interruptIds)}function TN(e,t,n){const r=n.filter(a=>a.source!=="transport"),s=a=>t.includes(a)&&r.some(l=>tl(a,l)),o=e.filter(a=>!s(a)),i=t.filter(a=>!r.some(l=>tl(a,l)));return Object.freeze({rootErrors:Object.freeze([...o,...n]),submissionRootErrors:Object.freeze([...i,...r])})}function AN(e,t){if(e.threadId!==t.threadId||e.interruptedRunId!==t.interruptedRunId||e.generation!==t.generation)return!1;const n=t.resolutions.map(r=>r.interruptId);return e.scope==="item"?n.includes(e.interruptId):zd(e.interruptIds,n)}function bs(e,t,n){const r=gn(e)??n?.responseSchemaHash;return de({v:1,kind:"generic",interruptId:e.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...r!==void 0?{responseSchemaHash:r}:{},...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{}})}function MN(e,t){const n=de(e.descriptor),r=e.error===void 0?Object.freeze([]):Object.freeze([de(e.error)]),s=r[0];return{id:n.id,interruptId:n.id,reason:n.reason,...n.message!==void 0?{message:n.message}:{},...n.responseSchema!==void 0?{responseSchema:n.responseSchema}:{},...n.expiresAt!==void 0?{expiresAt:n.expiresAt}:{},...n.metadata!==void 0?{metadata:n.metadata}:{},threadId:t.threadId,interruptedRunId:t.interruptedRunId,generation:t.generation,status:e.status,errors:r,...s!==void 0?{error:s}:{},canResolve:e.canResolve}}var kN=class{options;hydration;items=[];snapshot=Object.freeze([]);rootErrors=Object.freeze([]);submissionRootErrors=Object.freeze([]);state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1});activeTransaction;activeSubmissionOperation;retrySubmission;resuming=!1;tools;interruptDefinitions;constructor(e){this.options=e,this.tools=e.tools;const t=new Map;for(const n of e.interrupts??[]){if(t.has(n.id))throw new Error(`Duplicate interrupt definition id: ${n.id}`);t.set(n.id,n)}this.interruptDefinitions=t}updateTools(e){this.tools=e}hydrate(e,t="live"){this.activeSubmissionOperation=void 0,this.hydration={threadId:e.threadId,interruptedRunId:e.interruptedRunId,generation:e.generation,interrupts:de(e.interrupts)};const n=new Map;for(const r of e.interrupts){const s=Ja(r);s?.kind==="generic"&&s.definitionId!==void 0&&s.key!==void 0&&s.batchIndex!==void 0&&n.set(s.batchIndex,(n.get(s.batchIndex)??0)+1)}this.items=e.interrupts.map(r=>this.hydrateInterrupt(r,e,n)),this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([]),this.retrySubmission=void 0,this.resuming=!1,this.publish(t)}getInterrupts(){return this.snapshot}getState(){return this.state}getDescriptors(){return this.hydration?.interrupts??Object.freeze([])}hasValidatedFirstPartyGenericBatch(){return this.items.some(e=>e.kind==="generic"&&e.definition!==void 0)}reset(e){this.activeSubmissionOperation=void 0,this.hydration=void 0,this.items=[],this.snapshot=Object.freeze([]),e?.preserveRootErrors!==!0&&(this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([])),this.retrySubmission=void 0,this.resuming=!1,this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1}),this.options.onChange?.(e?.source??"live")}getInterruptErrors(){return this.rootErrors}getResuming(){return this.resuming}resolve(e){if(this.assertRootMutable(),typeof e=="boolean"){this.resolveBooleanBulk(e);return}this.resolveTransaction(e)}cancel(){this.assertRootMutable(),this.invalidateRetry();for(const e of this.items)Qe(e)&&(e.validationGeneration++,e.resolution=Object.freeze(ys(e,{interruptId:e.descriptor.id,status:"cancelled"})),e.status="staged",e.error=void 0);this.publish(),this.maybeSubmit()}retry(){if(this.resuming)throw new Error("Interrupt submission is already active.");const e=this.retrySubmission;if(!e){this.addRootError("transport","There is no retryable interrupt submission.",!1);return}this.submitBatch(e)}resolveClientToolOutput(e,t){const n=this.items.find(r=>r.kind==="client-tool-execution"&&r.binding?.kind==="client-tool-execution"&&r.binding.toolCallId===e||r.kind==="generic"&&CN(r.descriptor.reason)&&r.descriptor.toolCallId===e&&Fd(r.descriptor.metadata));return n?(this.resolveItem(n.descriptor.id,t),!0):!1}resolveToolApprovalDecision(e,t){const n=this.items.find(r=>r.descriptor.id===e&&(r.kind==="tool-approval"||r.kind==="generic"&&r.descriptor.reason==="approval_required"&&$d(r.descriptor.metadata)));return n?(this.resolveItem(n.descriptor.id,{approved:t}),!0):!1}hydrateInterrupt(e,t,n){const r=de(e),s=Ja(r),o=s===void 0&&SN(r);if(s===void 0&&!o)return IN(r)?{descriptor:r,binding:bs(r,t,void 0),kind:"generic",status:"error",canResolve:!1,resumable:!1,error:this.itemError(r.id,"stale","The interrupt binding is invalid or incomplete."),validationGeneration:0}:{descriptor:r,binding:void 0,kind:"unbound",status:"pending",canResolve:!1,resumable:!1,validationGeneration:0};const i=s!==void 0&&s.interruptId===r.id&&s.interruptedRunId===t.interruptedRunId&&s.generation===t.generation&&gn(r)===s.responseSchemaHash,a=s!==void 0&&s.interruptId===r.id&&s.interruptedRunId===t.interruptedRunId&&s.generation===t.generation&&s.responseSchemaHash===(gn(r)??s.responseSchemaHash);if(s!==void 0&&wN(r)&&(!a||s.kind!=="generic"||s.definitionId===void 0||s.key===void 0||s.batchIndex===void 0))return{descriptor:r,binding:bs(r,t,s),kind:"generic",status:"error",canResolve:!1,resumable:!1,error:this.itemError(r.id,"stale","The interrupt binding does not match this interrupted run."),validationGeneration:0};if(a&&s.kind==="tool-approval"){const c=this.tools?.find(u=>u.name===s.toolName);if(c?.needsApproval===!0&&r.toolCallId===s.toolCallId)try{const u=nC(c.approvalSchema,c.inputSchema);if(Da(c.inputSchema)===s.inputSchemaHash&&u.approvalSchemaHash===s.approvalSchemaHash&&u.responseSchemaHash===s.responseSchemaHash)return{descriptor:r,binding:de(s),kind:"tool-approval",status:"pending",canResolve:!0,resumable:!0,tool:c,validationGeneration:0}}catch{}}if(a&&s.kind==="client-tool-execution"){const c=this.tools?.find(u=>u.name===s.toolName);if(c!==void 0&&r.toolCallId===s.toolCallId&&Da(c.outputSchema)===s.outputSchemaHash)return{descriptor:r,binding:de(s),kind:"client-tool-execution",status:"pending",canResolve:!0,resumable:!0,tool:c,validationGeneration:0}}if(s!==void 0&&s.kind==="generic"&&s.definitionId!==void 0&&s.key!==void 0&&s.batchIndex!==void 0&&s.key.length>0&&n.get(s.batchIndex)!==1)return{descriptor:r,binding:de(s),kind:"generic",status:"error",canResolve:!1,resumable:!1,error:this.itemError(r.id,"stale","Generic interrupt batch contains a duplicate batchIndex."),validationGeneration:0};if(i&&s.kind==="generic"&&s.definitionId!==void 0&&s.key!==void 0&&s.batchIndex!==void 0&&s.key.length>0&&n.get(s.batchIndex)===1){const c=this.interruptDefinitions.get(s.definitionId);if(c!==void 0&&Za(c.responseSchema)===s.responseSchemaHash&&(c.payloadSchema===void 0?s.payloadSchemaHash===void 0:s.payloadSchemaHash===Za(c.payloadSchema))){const u=EN(r);return{descriptor:r,binding:de(s),definition:c,kind:"generic",status:"pending",canResolve:!0,resumable:!0,...u===void 0?{}:{payload:de(u)},validationGeneration:0}}}const l=o||s!==void 0&&s.interruptId===r.id&&s.interruptedRunId===t.interruptedRunId&&s.generation===t.generation&&(s.kind!=="generic"||gn(r)===void 0||s.responseSchemaHash===gn(r));return{descriptor:r,binding:bs(r,t,s),kind:"generic",status:"pending",canResolve:l,resumable:l,validationGeneration:0}}buildSnapshot(e){const t=this.requireHydration(),n=this.items.filter(r=>r.kind!=="client-tool-execution"&&r.status!=="submitting").map(r=>{const s=MN(r,t);if(r.kind==="unbound"||r.binding===void 0){const a={...s,kind:"unbound",canResolve:!1};return Object.freeze(a)}if(r.kind==="tool-approval"&&r.binding.kind==="tool-approval"){const a=de(r.binding),l={...s,kind:"tool-approval",binding:a,toolName:r.binding.toolName,toolCallId:r.binding.toolCallId,originalArgs:de(r.binding.originalArgs),cancel:()=>this.cancelItem(r.descriptor.id,e),clearResolution:()=>this.clearItem(r.descriptor.id,e),resolveInterrupt:(c,u)=>{const d=De(u)?u:void 0;this.resolveItem(r.descriptor.id,{approved:c,...c&&d?.editedArgs!==void 0?{editedArgs:d.editedArgs}:{},...d?.payload!==void 0?{payload:d.payload}:{}},e)}};return Object.freeze(l)}const o=r.binding.kind==="generic"?de(r.binding):de({v:1,kind:"generic",interruptId:r.descriptor.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...typeof r.binding.responseSchemaHash=="string"?{responseSchemaHash:r.binding.responseSchemaHash}:{}});if(r.definition!==void 0&&r.binding.kind==="generic"){const a={...s,kind:"generic",definitionId:r.definition.id,key:r.binding.key??"",payload:r.payload,binding:o,cancel:()=>this.cancelItem(r.descriptor.id,e),clearResolution:()=>this.clearItem(r.descriptor.id,e),resolveInterrupt:l=>this.resolveItem(r.descriptor.id,l,e)};return Object.freeze(a)}const i={...s,kind:"generic",binding:o,cancel:()=>this.cancelItem(r.descriptor.id,e),clearResolution:()=>this.clearItem(r.descriptor.id,e),resolveInterrupt:a=>this.resolveItem(r.descriptor.id,a,e)};return Object.freeze(i)});return Object.freeze(n)}publish(e="live"){if(!this.hydration){this.snapshot=Object.freeze([]),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e);return}this.snapshot=this.buildSnapshot(),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e)}resolveItem(e,t,n){this.assertItemMutable(n);const r=this.findItem(e);if(this.invalidateRetry(),!r.canResolve){r.status="error",r.error=this.itemError(e,"invalid-response-schema","The interrupt response schema is invalid and cannot be resolved."),n||this.publish();return}const s=++r.validationGeneration,o=this.validateCandidate(r,t);if(yt(o)){r.status="validating",r.error=void 0,n||this.publish(),Promise.resolve(o).then(i=>{s===r.validationGeneration&&this.applyValidation(r,i,n)}).catch(i=>{s===r.validationGeneration&&this.applyValidation(r,{code:this.validationCode(r),message:i instanceof Error?i.message:String(i)},n)});return}this.applyValidation(r,o,n)}cancelItem(e,t){this.assertItemMutable(t);const n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=Object.freeze(ys(n,{interruptId:e,status:"cancelled"})),n.status="staged",n.error=void 0,t||(this.publish(),this.maybeSubmit())}clearItem(e,t){this.assertItemMutable(t);const n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=void 0,n.error=void 0,n.status="pending",t||this.publish()}maybeSubmit(){const e=this.items.some(o=>o.kind==="generic"),t=this.items.filter(o=>Qe(o)&&!(e&&o.kind==="client-tool-execution"));if(t.length===0||t.some(o=>o.resolution===void 0||o.status!=="staged"))return;const n=this.requireHydration(),r=KE(t.map(o=>o.resolution).filter(o=>o!==void 0)),s=Object.freeze({threadId:n.threadId,interruptedRunId:n.interruptedRunId,generation:n.generation,resolutions:r.resolutions,canonicalResolutions:r.canonicalResolutions,fingerprint:r.fingerprint});this.submitBatch(s)}applyValidation(e,t,n){if(!("valid"in t)){e.status="error";const r=this.itemError(e.descriptor.id,t.code,t.message,t.path);e.error=r,e.kind==="client-tool-execution"&&(this.rootErrors=Object.freeze([...this.rootErrors.filter(s=>!(s.code==="item-validation-failed"&&s.interruptIds.includes(e.descriptor.id))),Object.freeze({scope:"batch",code:"item-validation-failed",message:r.message,source:"client",retryable:!1,interruptIds:Object.freeze([e.descriptor.id]),threadId:r.threadId,interruptedRunId:r.interruptedRunId,generation:r.generation})])),n||this.publish();return}e.resolution=de(ys(e,{interruptId:e.descriptor.id,status:"resolved",payload:t.payload})),e.status="staged",e.error=void 0,n||(this.publish(),this.maybeSubmit())}validateCandidate(e,t){if(e.kind==="generic"){const n=Xn(e.definition?.responseSchema??e.descriptor.responseSchema,t,"invalid-payload");if(e.definition===void 0)return n;const r=s=>"valid"in s?{valid:!0,payload:t}:s;return yt(n)?Promise.resolve(n).then(r):r(n)}return e.kind==="client-tool-execution"?Xn(e.tool?.outputSchema,t,"invalid-tool-output"):this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!De(t)||typeof t.approved!="boolean")return{code:"invalid-payload",message:"Tool approval resolutions require an approved boolean."};const n=t.approved,r=t.editedArgs;if(!n&&r!==void 0)return{code:"invalid-edited-args",message:"Rejected tool approvals cannot edit tool arguments."};if(n&&r!==void 0){const s=Xn(e.tool?.inputSchema,r,"invalid-edited-args");return yt(s)?Promise.resolve(s).then(o=>"valid"in o?this.validateApprovalPayload(e,t,o.payload):o):"valid"in s?this.validateApprovalPayload(e,t,s.payload):s}return this.validateApprovalPayload(e,t,void 0)}validateApprovalPayload(e,t,n){const r=t.approved===!0,s=this.approvalBranchSchema(e.tool,r),o=t.payload;if(s===void 0&&o!==void 0)return{code:"invalid-payload",message:"This approval branch does not accept a payload."};if(s!==void 0&&o===void 0)return{code:"invalid-payload",message:"This approval branch requires a payload."};const i=Xn(s,o,"invalid-payload"),a=l=>"valid"in l?{valid:!0,payload:{approved:r,...n!==void 0?{editedArgs:n}:{},...s!==void 0?{payload:l.payload}:{}}}:l;return yt(i)?Promise.resolve(i).then(a):a(i)}approvalBranchSchema(e,t){const n=e?.approvalSchema;return!De(n)||!("approve"in n||"reject"in n)?n:t?n.approve:n.reject}validationCode(e){return e.kind==="client-tool-execution"?"invalid-tool-output":"invalid-payload"}resolveBooleanBulk(e){const t=this.items.filter(n=>Qe(n)&&n.kind!=="client-tool-execution");if(!t.every(n=>n.kind==="tool-approval"&&this.approvalBranchSchema(n.tool,e)===void 0)||t.length===0){this.addRootError("unsupported-bulk-operation","Boolean bulk resolution requires payloadless tool approvals.",!1);return}this.invalidateRetry();for(const n of t)n.validationGeneration++,n.resolution=de({interruptId:n.descriptor.id,status:"resolved",payload:{approved:e}}),n.status="staged",n.error=void 0;this.publish(),this.maybeSubmit()}resolveTransaction(e){const t=this.items.map(o=>({status:o.status,...o.resolution!==void 0?{resolution:o.resolution}:{},...o.error!==void 0?{error:o.error}:{},validationGeneration:o.validationGeneration})),n={active:!0};this.activeTransaction=n;const r=this.buildSnapshot(n).filter(yN);let s;try{for(const o of r){const i=e(o);if(i!==void 0){s={code:yt(i)?"async-resolver":"inactive-transaction",message:yt(i)?"Interrupt transaction resolvers must be synchronous.":"Interrupt transaction resolvers must return literal undefined."};break}}s===void 0&&this.items.some(o=>Qe(o)&&o.kind!=="client-tool-execution"&&(o.resolution===void 0||o.status!=="staged"))&&(s={code:"incomplete-batch",message:"Interrupt transaction did not resolve every item."})}catch(o){s={code:"item-validation-failed",message:o instanceof Error?o.message:String(o)}}finally{n.active=!1,this.activeTransaction=void 0}if(s){this.restoreCheckpoints(t),this.addRootError(s.code,s.message,!1);return}this.publish(),this.maybeSubmit()}restoreCheckpoints(e){this.items.forEach((t,n)=>{const r=e[n];r&&(t.status=r.status,t.resolution=r.resolution,t.error=r.error,t.validationGeneration=r.validationGeneration+1)}),this.publish()}assertItemMutable(e){if(e&&!e.active)throw new Error("Interrupt transaction is inactive.");if(this.activeTransaction&&e!==this.activeTransaction)throw new Error("Interrupt transaction is inactive.");if(this.resuming)throw new Error("Interrupts cannot be mutated while submitting.")}assertRootMutable(){if(this.activeTransaction)throw new Error("Interrupt transaction is already active.");if(this.resuming)throw new Error("Interrupts cannot be mutated while submitting.")}invalidateRetry(){this.retrySubmission=void 0}submitBatch(e){const t={submission:e};this.activeSubmissionOperation=t,this.resuming=!0,this.retrySubmission=void 0;for(const n of this.items)Qe(n)&&(n.status="submitting");this.publish(),this.performSubmission(t)}async performSubmission(e){try{await this.options.submit(e.submission)}catch(t){if(this.activeSubmissionOperation!==e)return;this.handleSubmissionFailure(t,e.submission)}finally{this.activeSubmissionOperation===e&&(this.activeSubmissionOperation=void 0,this.resuming=!1,this.publish())}}handleSubmissionFailure(e,t){const n=_N(e);if(n.length===0){const l=e instanceof Error?e.message:String(e);this.addRootError("transport",l,!0,"transport"),this.retrySubmission=t;for(const c of this.items)Qe(c)&&(c.status="error");return}const r=n.filter(l=>AN(l,t));r.length!==n.length&&this.addRootError("protocol","Interrupt submission errors did not match the active batch.",!1);let s=!1,o=!1;const i=[];for(const l of r)if((l.code==="stale"||l.code==="expired"||l.code==="conflict")&&(s=!0),o||=l.retryable,l.scope==="item"){const c=this.items.find(u=>Qe(u)&&u.descriptor.id===l.interruptId);c&&(c.status="error",c.error=de(l))}else i.push(de(l));const a=TN(this.rootErrors,this.submissionRootErrors,i);this.rootErrors=a.rootErrors,this.submissionRootErrors=a.submissionRootErrors;for(const l of this.items)Qe(l)&&l.status==="submitting"&&(l.status="error");this.retrySubmission=o&&!s?t:void 0}addRootError(e,t,n,r="client"){const s=this.requireHydration();this.rootErrors=Object.freeze([...this.rootErrors,Object.freeze({scope:"batch",code:e,message:t,source:r,retryable:n,interruptIds:Object.freeze(this.items.filter(Qe).map(o=>o.descriptor.id)),threadId:s.threadId,interruptedRunId:s.interruptedRunId,generation:s.generation})]),this.publish()}findItem(e){const t=this.items.find(n=>n.descriptor.id===e);if(!t)throw new Error(`Unknown interrupt: ${e}`);return t}requireHydration(){if(!this.hydration)throw new Error("InterruptManager is not hydrated.");return this.hydration}itemError(e,t,n,r){const s=this.requireHydration();return Object.freeze({scope:"item",interruptId:e,code:t,message:n,...r!==void 0?{path:Object.freeze([...r])}:{},source:"client",retryable:!1,threadId:s.threadId,interruptedRunId:s.interruptedRunId,generation:s.generation})}};function ON(e,...t){const n=e?.();if(_e(n))return n;for(const r of t)if(_e(r))return r}async function jN(e,t){if(!t)throw new pd;return await e.prepare(t),e.headers(t)}function PN(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():Math.random().toString(36).slice(2)}var Qn;function nl(){return Qn!==void 0||(globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__||(globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__=PN()),Qn=globalThis.__TANSTACK_AI_DEVTOOLS_RUNTIME_ID__),Qn}var LN=0;function He(e){return e==null||e===""?"missing":`value-${encodeURIComponent(String(e))}`}function Xs(e){const t=e.runtimeId??nl(),n=e.eventId&&e.eventId.length>0?e.eventId:[e.source,e.eventType,He(t),He(e.clientId),He(e.requestId),He(e.streamId),He(e.hookId),He(e.threadId),He(e.runId),He(e.messageId),He(e.toolCallId),He(e.sequence),e.timestamp,nl(),LN++].join(":");return{...e,runtimeId:t,eventId:n}}var DN=class extends rf{constructor(){super({pluginId:"tanstack-ai-devtools"})}},rl=Symbol.for("tanstack.ai.devtools.eventClient");function $N(){const e=globalThis,t=e[rl];if(t)return t;const n=new DN;return e[rl]=n,n}var An=$N();function xe(e,t){An.emit(e,t)}var Hd=class{clientId;constructor(e){this.clientId=e}clientCreated(e){this.emitEvent("client:created",{initialMessageCount:e})}loadingChanged(e){this.emitEvent("client:loading:changed",{isLoading:e})}errorChanged(e){this.emitEvent("client:error:changed",{error:e})}textUpdated(e,t,n,r){this.emitEvent("text:chunk:content",{streamId:e,messageId:t,content:n,...r})}toolCallStateChanged(e,t,n,r,s,o,i){this.emitEvent("tools:call:updated",{streamId:e,messageId:t,toolCallId:n,toolName:r,state:s,arguments:o,...i})}thinkingUpdated(e,t,n,r,s){this.emitEvent("text:chunk:thinking",{streamId:e,messageId:t,content:n,delta:r,...s})}structuredOutputChanged(e,t,n,r,s){this.emitEvent(e,{streamId:t,messageId:n,...r,...s})}approvalRequested(e,t,n,r,s,o,i){this.emitEvent("tools:approval:requested",{streamId:e,messageId:t,toolCallId:n,toolName:r,input:s,approvalId:o,...i})}messageAppended(e,t,n){const r=e.parts.filter(s=>s.type==="text").map(s=>s.content).join(" ");this.emitEvent("text:message:created",{streamId:t,messageId:e.id,role:e.role,content:r,parts:e.parts,...n})}messageSent(e,t){const n=typeof t=="string"?t:t.filter(r=>r.type==="text").map(r=>r.content).join("");this.emitEvent("text:message:created",{messageId:e,role:"user",content:n,...Array.isArray(t)&&{parts:t}}),this.emitEvent("text:message:user",{messageId:e,role:"user",content:n,...Array.isArray(t)&&{parts:t}})}reloaded(e){this.emitEvent("client:reloaded",{fromMessageIndex:e})}stopped(){this.emitEvent("client:stopped")}messagesCleared(){this.emitEvent("client:messages:cleared")}toolResultAdded(e,t,n,r,s){this.emitEvent("tools:result:added",{toolCallId:e,toolName:t,output:n,state:r,...s})}toolApprovalResponded(e,t,n,r){this.emitEvent("tools:approval:responded",{approvalId:e,toolCallId:t,approved:n,...r})}toolFixtureApplied(e){this.emitEvent("devtools:tool-fixture:applied",{...e})}},FN=class extends Hd{emitEvent(e,t){const n=Date.now(),r=e.startsWith("text:")||e.startsWith("tools:")||e.startsWith("structured-output:")||e==="devtools:tool-fixture:applied",s=e.startsWith("client:")||e.startsWith("tools:")||e.startsWith("text:")||e.startsWith("structured-output:")||e==="devtools:tool-fixture:applied",o=r?"user-visible":"client-state",i={hookId:this.clientId,...typeof t?.threadId=="string"?{threadId:t.threadId}:{},...typeof t?.runId=="string"?{runId:t.runId}:{},...typeof t?.streamId=="string"?{streamId:t.streamId}:{},...typeof t?.messageId=="string"?{messageId:t.messageId}:{},...typeof t?.toolCallId=="string"?{toolCallId:t.toolCallId}:{}};if(s){const a=Xs({eventType:e,clientId:this.clientId,...i,source:"client",visibility:o,timestamp:n});An.emit(e,{...t,...a})}else{const a=Xs({eventType:e,source:"client",visibility:"client-state",timestamp:n});An.emit(e,{...t,...a})}}},zN=class extends Hd{emitEvent(){}},HN=class{events;constructor(e){this.events=new zN(e.clientId)}emitRegistered(){}emitUpdated(){}emitSnapshot(){}emitToolsRegistered(){}emitRunLifecycle(e,t,n,r){}deactivate(){}supersede(){}dispose(){}mountWithTools(e){}notifyToolsChanged(){}setCurrentStreamId(e){}recordStreamId(e){}getCurrentStreamId(){return null}getLastStreamId(){return null}resolveStreamId(){return""}observeChunk(e){}recordMemoryState(e){}recordCompactionEvent(e,t){}recordCompactionState(e){}recordSkillsState(e){}beginRun(e,t){}getCurrentRunEventContext(){}getCurrentOrLastRunEventContext(){}findToolCallContext(e){return{toolCallId:e}}async applyFixture(e){}},BN=e=>new HN(e);function sl(e){if(Array.isArray(e))return{messages:e};if(e&&Array.isArray(e.messages))return e}function ol(e){return"toolCallId"in e&&typeof e.toolCallId=="string"?e.toolCallId:void 0}function il(e){return"messageId"in e&&typeof e.messageId=="string"?e.messageId:void 0}function GN(e){return"parentMessageId"in e&&typeof e.parentMessageId=="string"?e.parentMessageId:void 0}var UN=class{adapter;id;applyMessages;applyResume;skipNextPersist=!1;generation=0;queue=Promise.resolve();queuePending=!1;messagesGeneration=0;lastMessages=[];lastResume=null;clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;constructor(e,t,n,r){this.adapter=e,this.id=t,this.applyMessages=n,this.applyResume=r}writeState(){const e=[...this.lastMessages];if(e.length===0&&!this.lastResume){const r=this.generation;this.runOperation(()=>{if(r===this.generation)return this.adapter.removeItem(this.id)});return}const t=this.generation,n={messages:e,...this.lastResume?{resume:this.lastResume}:{}};this.runOperation(()=>{if(t===this.generation)return this.adapter.setItem(this.id,n)})}readInitial(){try{const e=this.adapter.getItem(this.id);if(e instanceof Promise)return e.then(sl).catch(()=>{});const t=sl(e);return t&&(this.lastMessages=t.messages,this.lastResume=t.resume??null),t}catch{return}}hydrateAsync(e){if(!(e instanceof Promise))return;const t=this.messagesGeneration;e.then(n=>{!n||this.messagesGeneration!==t||(this.lastResume=n.resume??null,this.lastMessages=n.messages,this.applyMessages(n.messages),n.resume&&this.applyResume&&this.applyResume(n.resume))}).catch(()=>{})}notifyMessagesChanged(e){if(this.messagesGeneration++,this.lastMessages=[...e],this.skipNextPersist){this.skipNextPersist=!1;return}this.writeState()}persistResumeSnapshot(e){this.lastResume=e,!this.skipNextPersist&&this.writeState()}remove(){this.lastMessages=[],this.lastResume=null;const e=++this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)})}runOperation(e){if(this.queuePending){const t=this.queue.then(e).catch(()=>{});this.queue=t,t.finally(()=>{this.queue===t&&(this.queuePending=!1)});return}try{const t=e();if(t instanceof Promise){this.queuePending=!0;const n=t.catch(()=>{});this.queue=n,n.finally(()=>{this.queue===n&&(this.queuePending=!1)})}}catch{}}snapshotClear(e){for(const t of e.messages)this.clearedMessageIds.add(t.id);for(const t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}beginClear(){this.skipNextPersist=!0}shouldIgnoreChunk(e){const t=Re(e);if(t&&this.clearedRunIds.has(t))return e.type==="RUN_STARTED"&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t))return this.markIgnoredChunkIds(e),!0;if(this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;const n=ol(e);if(n&&this.clearedToolCallIds.has(n))return!0;const r=GN(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;const s=il(e);return s?!!this.clearedMessageIds.has(s):!1}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetIgnored(){this.ignoredActiveRunIds.clear()}takeRunlessRunId(){const e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){const t=il(e);t&&this.clearedMessageIds.add(t);const n=ol(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return Re(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type==="TEXT_MESSAGE_START"||e.type==="TEXT_MESSAGE_CONTENT"||e.type==="TOOL_CALL_START"||e.type==="TOOL_CALL_ARGS"||e.type==="TOOL_CALL_END"||e.type==="TOOL_CALL_RESULT"||e.type==="MESSAGES_SNAPSHOT"||e.type==="RUN_ERROR"}};function al(e){return"toolCallId"in e&&typeof e.toolCallId=="string"?e.toolCallId:void 0}function ll(e){return"messageId"in e&&typeof e.messageId=="string"?e.messageId:void 0}function qN(e){return"parentMessageId"in e&&typeof e.parentMessageId=="string"?e.parentMessageId:void 0}var VN=class{clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;snapshotClear(e){for(const t of e.messages)this.clearedMessageIds.add(t.id);for(const t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}shouldIgnoreChunk(e){const t=Re(e);if(t&&this.clearedRunIds.has(t))return e.type==="RUN_STARTED"&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t))return this.markIgnoredChunkIds(e),!0;if(this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;const n=al(e);if(n&&this.clearedToolCallIds.has(n))return!0;const r=qN(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;const s=ll(e);return!!(s&&this.clearedMessageIds.has(s))}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetActiveRuns(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}takeRunlessRunId(){const e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){const t=ll(e);t&&this.clearedMessageIds.add(t);const n=al(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return Re(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type==="TEXT_MESSAGE_START"||e.type==="TEXT_MESSAGE_CONTENT"||e.type==="TOOL_CALL_START"||e.type==="TOOL_CALL_ARGS"||e.type==="TOOL_CALL_END"||e.type==="TOOL_CALL_RESULT"||e.type==="MESSAGES_SNAPSHOT"||e.type==="RUN_ERROR"}};function KN(e){const t=new Set;for(const n of e??[]){if(t.has(n.id))throw new Error(`Duplicate interrupt definition id: ${n.id}`);t.add(n.id)}}function cl(e){const{connection:t,fetcher:n}=e;if(t&&n)throw new Error("ChatClient: pass either `connection` or `fetcher`, not both.");if(t)return t;if(n)return mN(n);throw new Error("ChatClient: either `connection` or `fetcher` is required.")}function ul(e){return"connect"in e}function dl(e){if(e.type!=="RUN_FINISHED"||e.outcome?.type==="interrupt")return!1;const t=e;return t.finishReason!==void 0?t.finishReason==="tool_calls":ae(e)?.finishReason==="tool_calls"}function hl(e){const t={whenBusy:"queue",drain:"fifo",onOverflow:"reject"};if(!e)return t;if(typeof e=="string")return{...t,whenBusy:e};if(typeof e=="function")return{...t,strategy:e};const n=e.maxSize;if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new Error("ChatClient: queue.maxSize must be a non-negative integer");return{whenBusy:e.whenBusy??"queue",drain:e.drain??"fifo",onOverflow:e.onOverflow??"reject",...n!==void 0?{maxSize:n}:{}}}function YN(e){const t=e.at(-1)?.body,n=[];for(const o of e){if(typeof o.content!="string")break;n.push(o.content)}if(n.length===e.length)return{content:n.join(`
|
|
11
|
+
`),...t!==void 0?{body:t}:{}};const r=[];let s;for(const o of e){if(typeof o.content=="string"){r.push({type:"text",content:o.content});continue}typeof o.content.content=="string"?r.push({type:"text",content:o.content.content}):r.push(...o.content.content),s=vd(s,o.content.metadata)}return{content:{content:r,...s!==void 0?{metadata:s}:{}},...t!==void 0?{body:t}:{}}}function WN(e){if(!(e===null||typeof e!="object"||Array.isArray(e))&&!(!("approved"in e)||typeof e.approved!="boolean"))return e.approved}function XN(e){const t=e;if(t===null||typeof t!="object"||!("resumeState"in t))return;const n=t.resumeState;if(!(n===null||typeof n!="object"||!("threadId"in n)||typeof n.threadId!="string"||n.threadId.length===0||!("runId"in n)||typeof n.runId!="string"||n.runId.length===0))return{threadId:n.threadId,runId:n.runId}}var QN=2e3,JN=new Set(["TEXT_MESSAGE_START","TEXT_MESSAGE_CONTENT","TOOL_CALL_START","MESSAGES_SNAPSHOT"]),ZN=64,eR=class{processor;connection;uniqueId;threadId;persistor;clearedStreamTracker=new VN;currentRunId=null;lastResume=null;runParents=new Map;supersededInterruptRunIds=new Set;rejoinedRunId=null;interruptManager;activeInterruptSubmission;interruptSubmissionFailure;joinedRunWaiters=new Map;pendingResumeParentRunId=null;pendingResumeThreadId=null;pendingResumeItems=null;activeResumeThreadId=null;activeResumeRunId=null;bodyOption={};forwardedPropsOption={};byok;byokProvider;context=void 0;pendingMessageBody=void 0;queueConfig;messageQueue=[];sendInFlight=!1;messageQueueDraining=!1;stopMessageQueueDrain=!1;deliverClaim=!1;isLoading=!1;isSubscribed=!1;error=void 0;status="ready";connectionStatus="disconnected";abortController=null;clientToolsRef;devtoolsBridge;events;currentStreamId=null;currentMessageId=null;postStreamActions=[];pendingToolExecutions=new Map;activeClientTools=null;activeContext=void 0;continuationPending=!1;subscriptionAbortController=null;processingResolve=null;connectionDrainsOnSend=!1;errorReportedGeneration=null;streamGeneration=0;continuationGeneration=0;streamContinuationGeneration=0;continuationSkipped=!1;draining=!1;sessionGenerating=!1;activeRunIds=new Set;disposed=!1;tailing=!1;rejoinRunId;cachesMessages;historyPageSize;hasOlderMessages=!1;olderMessagesCursor;knownServerMessageIds=new Set;loadOlderMessagesInFlight=!1;historyGeneration=0;devtoolsMounted=!1;callbacksRef;constructor(e){KN(e.interrupts),this.threadId=e.threadId||"",this.uniqueId=this.threadId;let t=!0;if(e.persistence===!0){if(!e.threadId)throw new Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");t=!1,this.historyPageSize=e.history?.pageSize}else if(e.persistence){if(!e.threadId)throw new Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");this.persistor=new UN(e.persistence,e.threadId,a=>this.processor.setMessages(a),a=>this.applyPersistedResume(a)),this.historyPageSize=void 0}else this.historyPageSize=void 0;this.bodyOption=e.body||{},this.forwardedPropsOption=e.forwardedProps||{},this.byok=e.byok,this.byokProvider=e.byokProvider,this.context=e.context,this.queueConfig=hl(e.queue);const n=cl(e);if(this.connectionDrainsOnSend=ul(n),this.connection=Qa(n),this.clientToolsRef={current:new Map},e.tools)for(const a of e.tools)this.clientToolsRef.current.set(a.name,a);this.devtoolsBridge=(e.devtoolsBridgeFactory??BN)(this.buildDevtoolsBridgeOptions(e.devtools)),this.events=this.devtoolsBridge.events,this.callbacksRef={current:{onResponse:e.onResponse||(()=>{}),onChunk:e.onChunk||(()=>{}),onFinish:e.onFinish||(()=>{}),onError:e.onError||(()=>{}),onMessagesChange:e.onMessagesChange||(()=>{}),onLoadingChange:e.onLoadingChange||(()=>{}),onErrorChange:e.onErrorChange||(()=>{}),onStatusChange:e.onStatusChange||(()=>{}),onSubscriptionChange:e.onSubscriptionChange||(()=>{}),onConnectionStatusChange:e.onConnectionStatusChange||(()=>{}),onSessionGeneratingChange:e.onSessionGeneratingChange||(()=>{}),onQueueChange:e.onQueueChange||(()=>{}),onResumeStateChange:e.onResumeStateChange||(()=>{}),onRunIdChange:e.onRunIdChange||(()=>{}),onInterruptStateChange:e.onInterruptStateChange||(()=>{}),onCustomEvent:e.onCustomEvent||(()=>{})}},this.interruptManager=new kN({...e.tools!==void 0?{tools:e.tools}:{},...e.interrupts!==void 0?{interrupts:e.interrupts}:{},submit:a=>this.submitInterruptBatch(a),onChange:a=>this.notifyResumeStateChange(a)}),e.initialResumeSnapshot&&this.applyResumeSnapshot(e.initialResumeSnapshot);const r=this.persistor?.readInitial(),s=r instanceof Promise?void 0:r,o=s?s.messages:e.initialMessages;let i=null;if(s?.resume){const a=s.resume;Array.isArray(a.pendingInterrupts)&&a.pendingInterrupts.length>0?this.applyResumeSnapshot(a):a.resumeState.runId&&(i=a.resumeState.runId)}if(!i&&e.initialResumeSnapshot){const a=e.initialResumeSnapshot;!(Array.isArray(a.pendingInterrupts)&&a.pendingInterrupts.length>0)&&a.resumeState.runId&&(i=a.resumeState.runId)}this.processor=new QC({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...o?{initialMessages:o}:{},events:{onMessagesChange:a=>{this.persistor?.notifyMessagesChanged(a),this.callbacksRef.current.onMessagesChange(a)},onStreamStart:()=>{this.setStatus("streaming");const a=this.processor.getCurrentAssistantMessageId();if(!a)return;const l=this.processor.getMessages().find(c=>c.id===a);l&&(this.currentMessageId=l.id,this.events.messageAppended(l,this.currentStreamId||void 0))},onStreamEnd:a=>{this.callbacksRef.current.onFinish(a),this.setStatus("ready"),this.resolveProcessing()},onError:a=>{this.reportStreamError(a)},onTextUpdate:(a,l)=>{this.currentStreamId&&this.events.textUpdated(this.currentStreamId,a,l)},onThinkingUpdate:(a,l)=>{this.currentStreamId&&this.events.thinkingUpdated(this.currentStreamId,a,l,void 0)},onStructuredOutputChange:a=>{const l=this.devtoolsBridge.resolveStreamId(),c=a.phase==="start"?"structured-output:started":a.phase==="complete"?"structured-output:completed":a.phase==="error"?"structured-output:errored":"structured-output:updated";this.currentMessageId=a.messageId,this.events.structuredOutputChanged(c,l,a.messageId,{status:a.status,raw:a.raw,...a.partial!==void 0?{partial:a.partial}:{},...a.data!==void 0?{data:a.data}:{},...a.reasoning!==void 0?{reasoning:a.reasoning}:{},...a.errorMessage!==void 0?{errorMessage:a.errorMessage}:{},...a.delta!==void 0?{delta:a.delta}:{}})},onToolCallStateChange:(a,l,c,u)=>{const d=this.processor.getMessages().find(f=>f.id===a)?.parts.find(f=>f.type==="tool-call"&&f.id===l)?.name||"unknown";this.currentStreamId&&this.events.toolCallStateChanged(this.currentStreamId,a,l,d,c,u)},onToolCall:a=>{const l=(this.activeClientTools??this.clientToolsRef.current).get(a.toolName),c=l?.execute;if(c){const u=this.continuationGeneration,d=this.devtoolsBridge.getCurrentRunEventContext(),f=(async()=>{try{const g=this.activeClientTools===null?this.context:this.activeContext,p=await c(a.input,{toolCallId:a.toolCallId,context:g,emitCustomEvent:()=>{}});await this.addToolResultForClientTool({toolCallId:a.toolCallId,tool:a.toolName,output:p,state:"output-available"},l,u,d)}catch(g){await this.addToolResultForClientTool({toolCallId:a.toolCallId,tool:a.toolName,output:null,state:"output-error",errorText:g.message},l,u,d)}finally{this.pendingToolExecutions.delete(a.toolCallId)}})();this.pendingToolExecutions.set(a.toolCallId,f)}},onApprovalRequest:a=>{const l=this.devtoolsBridge.resolveStreamId(),c=this.findMessageIdForToolCall(a.toolCallId)??this.currentMessageId??"";this.events.approvalRequested(l,c,a.toolCallId,a.toolName,a.input,a.approvalId)},onCustomEvent:(a,l,c)=>{a==="memory:state"&&this.devtoolsBridge.recordMemoryState(l),(a==="compaction:started"||a==="compaction:state"||a==="compaction:ended")&&this.devtoolsBridge.recordCompactionEvent(a,l),a==="skills:state"&&this.devtoolsBridge.recordSkillsState(l),this.callbacksRef.current.onCustomEvent(a,l,c)}}}),this.persistor?.hydrateAsync(r),this.rejoinRunId=i,this.cachesMessages=t}attach(){this.disposed||this.tailing||(this.ensureThreadId(),this.tailing=!0,this.rejoinRunId&&this.maybeRejoinInFlight(this.rejoinRunId),!this.cachesMessages&&this.connection.hydrate&&this.hydrateFromServer())}detach(){this.tailing&&(this.tailing=!1,this.cancelInFlightStream({setReadyStatus:!0}),this.rejoinedRunId=null)}applyResumeSnapshot(e){const t=XN(e);if(t===void 0){this.interruptManager.reset({source:"hydrate"});return}this.lastResume=t;const n=Array.isArray(e.pendingInterrupts)?e.pendingInterrupts:[];if(n.length===0){this.interruptManager.reset({source:"hydrate"});return}const r=this.interruptGeneration(n);this.interruptManager.hydrate({threadId:t.threadId,interruptedRunId:t.runId,generation:r,interrupts:n},"hydrate")}applyPersistedResume(e){this.applyResumeSnapshot(e);const t=Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0,n=e.resumeState?.runId;!t&&n&&this.maybeRejoinInFlight(n)}maybeRejoinInFlight(e){this.connection.joinRun&&(this.disposed||!this.tailing||this.rejoinedRunId!==e&&(this.isLoading||this.abortController||(this.rejoinedRunId=e,this.resumeInFlightRun(e))))}hydrateFromServer(){const e=this.connection.hydrate;if(!e||this.isLoading||this.abortController||this.disposed)return;const t=this.historyPageSize,n=t===void 0?void 0:{limit:t};(async()=>{let r;const s=this.historyGeneration;try{r=await e(this.threadId,n)}catch{return}if(s===this.historyGeneration&&!(this.disposed||!this.tailing)&&!(this.isLoading||this.abortController)){if(this.applyHydrationPage(r.page),r.messages.length>0){const o=Hs(r.messages);this.processor.setMessages(o),this.rememberServerMessageIds(o)}r.interrupts&&r.interrupts.pending.length>0?this.applyResumeSnapshot({resumeState:{threadId:this.threadId,runId:r.interrupts.runId},pendingInterrupts:r.interrupts.pending}):r.activeRun?.runId&&this.maybeRejoinInFlight(r.activeRun.runId)}})()}mountDevtools(){this.ensureThreadId(),!this.devtoolsMounted&&(this.devtoolsMounted=!0,this.devtoolsBridge.mountWithTools(this.processor.getMessages().length))}ensureThreadId(){return this.threadId||(this.threadId=this.generateUniqueId("thread")),this.uniqueId=this.threadId,this.threadId}drainIgnoredRunlessChunk(e){if(e.type!=="RUN_ERROR")return;const t=this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),this.resolveProcessing())}retireIgnoredClearedTerminalChunk(e){if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const t=Re(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),Re(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type==="RUN_STARTED"){const s=Re(e)??e.runId,o="parentRunId"in e&&typeof e.parentRunId=="string"?e.parentRunId:void 0;o&&(this.runParents.set(s,o),this.supersededInterruptRunIds.has(s)&&this.markLineageAnswered(o)),this.activeResumeThreadId="threadId"in e&&typeof e.threadId=="string"?e.threadId:this.activeResumeThreadId,this.activeResumeRunId=s;const i=this.supersededInterruptRunIds.has(s)&&!this.isLoading;i||(this.activeRunIds.add(s),this.clearedStreamTracker.onRunStarted(s),this.setSessionGenerating(!0)),this.persistor&&this.connection.joinRun&&!this.lastResume&&!i&&this.persistResumeSnapshot({threadId:this.activeResumeThreadId??this.threadId,runId:s}),this.lastResume&&this.supersededInterruptRunIds.has(this.lastResume.runId)&&(this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset());return}if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const n=Re(e);n?(this.activeRunIds.delete(n),this.clearedStreamTracker.onRunSettled(n)):e.type==="RUN_ERROR"&&(this.activeRunIds.clear(),this.clearedStreamTracker.onSessionRunError()),this.setSessionGenerating(this.activeRunIds.size>0);const r=e.type==="RUN_FINISHED"&&dl(e);t?.resolveProcessing!==!1&&!r&&this.resolveProcessing()}observeInterruptState(e){if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR"||this.activeInterruptSubmission&&e.type==="RUN_ERROR")return;const t=Re(e),n="threadId"in e&&typeof e.threadId=="string"?e.threadId:this.activeResumeThreadId;if(t&&!dl(e)&&(e.type==="RUN_ERROR"||e.type==="RUN_FINISHED"&&e.outcome?.type!=="interrupt")&&this.markLineageAnswered(t),e.type==="RUN_FINISHED"&&e.outcome?.type==="interrupt"){const u=this.currentRunId??t??this.activeResumeRunId??"";if(u&&this.supersededInterruptRunIds.has(u))return;this.lastResume={threadId:n??this.threadId,runId:u},this.interruptManager.hydrate({threadId:this.lastResume.threadId,interruptedRunId:u,generation:this.interruptGeneration(e.outcome.interrupts),interrupts:e.outcome.interrupts},"live");return}const r=e.type==="RUN_ERROR"&&!t,s=!!(t&&this.lastResume?.runId===t),o=!!(t&&this.currentRunId===t||this.currentRunId&&this.lastResume?.runId===this.currentRunId),i=!!(this.isLoading&&t&&(t===this.activeResumeRunId||t===this.currentRunId)),a=this.isLoading&&e.type==="RUN_FINISHED"&&!t,l=!!(this.activeInterruptSubmission&&this.isLoading&&e.type==="RUN_FINISHED"&&e.outcome?.type!=="interrupt"),c=!!(this.lastResume&&this.supersededInterruptRunIds.has(this.lastResume.runId));if(r||s||o||i||a||l||c){this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset();return}this.notifyResumeStateChange("live")}markLineageAnswered(e){let t=e,n=0;for(;t!==void 0&&n<ZN;){if(this.supersededInterruptRunIds.has(t))return;this.supersededInterruptRunIds.add(t),t=this.runParents.get(t),n++}}getResumeState(){return this.lastResume?{...this.lastResume}:null}getCurrentRunId(){return this.currentRunId}setCurrentRunId(e){this.currentRunId!==e&&(this.currentRunId=e,this.callbacksRef.current.onRunIdChange(e))}getInterruptState(){return this.interruptManager.getState()}getInterrupts(){return this.interruptManager.getInterrupts()}getPendingInterrupts(){return this.interruptManager.getInterrupts()}resolveInterrupts(e){if(typeof e=="boolean"){this.interruptManager.resolve(e);return}this.interruptManager.resolve(e)}cancelInterrupts(){this.interruptManager.cancel()}retryInterrupts(){this.interruptManager.retry()}resumeInterruptsUnsafe(e,t){const n=t??this.lastResume;return n?this.resumeInterruptsUnsafeForGeneration(e,n,this.continuationGeneration):Promise.resolve(!1)}resumeInterruptsUnsafeForGeneration(e,t,n){return n!==this.continuationGeneration?Promise.resolve(!1):this.isLoading?new Promise((r,s)=>{this.queuePostStreamAction(async()=>{try{r(await this.resumeInterruptsUnsafeForGeneration(e,t,n))}catch(o){s(o)}})}):(this.pendingResumeThreadId=t.threadId,this.pendingResumeParentRunId=t.runId,this.pendingResumeItems=[...e],this.streamResponse())}resumeInterrupts(e,t){return this.resumeInterruptsUnsafe(e,t)}async submitInterruptBatch(e){const t=this.continuationGeneration;this.activeInterruptSubmission=e,this.interruptSubmissionFailure=void 0;for(const s of e.resolutions){const o=WN(s.payload);if(o===void 0)continue;const i=s.interruptId;this.processor.addToolApprovalResponse(i,o)}const n=await this.resumeInterruptsUnsafeForGeneration([...e.resolutions],{threadId:e.threadId,runId:e.interruptedRunId},t).finally(()=>{this.activeInterruptSubmission===e&&(this.activeInterruptSubmission=void 0)});if(t!==this.continuationGeneration)return;const r=this.takeInterruptSubmissionFailure();if(r!==void 0)throw{errors:r.errors};if(!n)throw new Error("Interrupt continuation could not be started.");this.lastResume?.runId===e.interruptedRunId&&(this.lastResume=null,this.interruptManager.reset())}takeInterruptSubmissionFailure(){const e=this.interruptSubmissionFailure;return this.interruptSubmissionFailure=void 0,e}interruptGeneration(e){let t;for(const n of e){const r=n.metadata?.["tanstack:interruptBinding"];if(r===null||typeof r!="object"||!("generation"in r)||typeof r.generation!="number"||!Number.isInteger(r.generation)||r.generation<0||t!==void 0&&t!==r.generation)return 0;t=r.generation}return t??0}generateUniqueId(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(7)}`}setIsLoading(e){this.isLoading=e,this.callbacksRef.current.onLoadingChange(e),this.events.loadingChanged(e)}setStatus(e){this.status=e,this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){this.isSubscribed=e,this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){this.connectionStatus=e,this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}setSessionGenerating(e){this.sessionGenerating!==e&&(this.sessionGenerating=e,this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(e){const t=this.getResumeState(),n=this.interruptManager.getState();this.persistResumeSnapshot(t),this.callbacksRef.current.onResumeStateChange(t,n.interrupts),this.callbacksRef.current.onInterruptStateChange(n,{source:e})}persistResumeSnapshot(e){if(!this.persistor)return;if(!e){this.persistor.persistResumeSnapshot(null);return}const t=this.interruptManager.getDescriptors();this.persistor.persistResumeSnapshot({resumeState:e,...t.length>0?{pendingInterrupts:[...t]}:{}})}resetSessionGenerating(e){this.activeRunIds.clear(),e?.preserveClearedStreamTracking||this.clearedStreamTracker.resetActiveRuns(),this.setSessionGenerating(!1)}setError(e){this.error=e,this.callbacksRef.current.onErrorChange(e),this.events.errorChanged(e?.message||null)}buildDevtoolsBridgeOptions(e){const t=this;return{get hookId(){return t.uniqueId},get clientId(){return t.uniqueId},get threadId(){return t.threadId},metadata:{hookName:e?.hookName??"useChat",outputKind:e?.outputKind??"chat",...e?.framework?{framework:e.framework}:{},...e?.name?{name:e.name}:{}},getSnapshot:()=>this.getDevtoolsSnapshot(),getTools:()=>this.clientToolsRef.current.values(),getMessages:()=>this.processor.getMessages(),setMessages:n=>{this.processor.setMessages(n)},addToolResult:(n,r,s)=>{this.processor.addToolResult(n,r,s)},generateId:n=>this.generateUniqueId(n)}}getDevtoolsSnapshot(){return{messages:this.processor.getMessages(),status:this.status,isLoading:this.isLoading,isSubscribed:this.isSubscribed,connectionStatus:this.connectionStatus,sessionGenerating:this.sessionGenerating,activeRunIds:Array.from(this.activeRunIds),queue:this.getQueue(),...this.error?{error:this.error.message}:{}}}findMessageIdForToolCall(e){const t=this.processor.getMessages();for(const n of t)if(n.parts.find(r=>r.type==="tool-call"&&r.id===e))return n.id}abortSubscriptionLoop(){this.subscriptionAbortController?.abort(),this.subscriptionAbortController=null}resolveProcessing(){this.processingResolve?.(),this.processingResolve=null}cancelInFlightStream(e){this.abortController?.abort(),this.abortController=null,e?.abortSubscription&&this.abortSubscriptionLoop(),this.resolveProcessing(),this.setIsLoading(!1),this.deliverClaim=!1,e?.setReadyStatus&&this.setStatus("ready")}reportStreamError(e){const t=this.errorReportedGeneration===this.streamGeneration;this.setError(e),(this.isLoading||this.status==="submitted"||this.status==="streaming")&&this.setStatus("error"),t||(this.errorReportedGeneration=this.streamGeneration,this.callbacksRef.current.onError(e))}startSubscription(){this.subscriptionAbortController=new AbortController;const e=this.subscriptionAbortController.signal;this.consumeSubscription(e).catch(t=>{t instanceof Error&&t.name!=="AbortError"&&(this.setConnectionStatus("error"),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.reportStreamError(t)),this.resolveProcessing()}).finally(()=>{this.subscriptionAbortController?.signal===e&&(this.subscriptionAbortController=null,!e.aborted&&this.isSubscribed&&(this.setIsSubscribed(!1),this.connectionStatus!=="error"&&this.setConnectionStatus("disconnected")))})}async consumeSubscription(e){const t=this.connection.subscribe(e);for await(const n of t){if(e.aborted)break;await this.processIncomingChunk(n)}}resumeInFlightRun(e){const t=this.connection.joinRun;if(!t)return;const n=new AbortController;this.abortController=n,this.setCurrentRunId(e),this.lastResume={threadId:this.threadId,runId:e},this.streamContinuationGeneration=this.continuationGeneration,this.setIsLoading(!0),this.setStatus("streaming"),(async()=>{let r=!1,s=!1,o=!1;const i=setTimeout(()=>{s||n.abort()},QN);try{for await(const a of t(e,n.signal)){if(n.signal.aborted)break;s||(s=!0,clearTimeout(i)),!r&&JN.has(a.type)&&(r=!0,this.dropTrailingInFlightAssistant()),await this.processIncomingChunk(a,{defer:!1})}this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values())}catch(a){const l=a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError");!s&&!l&&(o=!0),s&&!l&&this.reportStreamError(a instanceof Error?a:new Error(String(a)))}finally{clearTimeout(i),!s&&o&&this.tailing&&!this.disposed&&(this.lastResume=null,this.persistor?.persistResumeSnapshot(null)),this.abortController===n&&(this.abortController=null,this.setIsLoading(!1),this.status==="streaming"&&this.setStatus("ready"),await this.drainPostStreamActions())}})()}dropTrailingInFlightAssistant(){const e=this.processor.getMessages(),t=e[e.length-1];t&&t.role==="assistant"&&this.processor.setMessages(e.slice(0,-1))}async processIncomingChunk(e,t){if(e=kd(e),e.type==="RUN_ERROR"&&this.isActiveInterruptSubmissionFailure(e)){const n=ae(e)?.interruptErrors;this.interruptSubmissionFailure={errors:Array.isArray(n)?n:[]}}if(this.connectionStatus==="connecting"&&this.setConnectionStatus("connected"),this.clearedStreamTracker.shouldIgnoreChunk(e)){(e.type==="RUN_FINISHED"||e.type==="RUN_ERROR")&&(Re(e)?this.updateRunLifecycle(e,{resolveProcessing:!1}):this.drainIgnoredRunlessChunk(e),this.retireIgnoredClearedTerminalChunk(e),this.resolveJoinedRun(e));return}this.callbacksRef.current.onChunk(e),this.devtoolsBridge.observeChunk(e),this.processor.processChunk(e),this.updateRunLifecycle(e),this.observeInterruptState(e),t?.defer!==!1&&(typeof document>"u"||!document.hidden)&&await new Promise(n=>setTimeout(n,0)),this.resolveJoinedRun(e)}isActiveInterruptSubmissionFailure(e){const t=this.activeInterruptSubmission,n=ae(e)?.interruptErrors;if(!t||!Array.isArray(n)||n.length===0)return!1;const r=Re(e);return r!==void 0&&r!==this.currentRunId||typeof e.threadId=="string"&&e.threadId!==t.threadId?!1:n.every(s=>s==null||typeof s!="object"||typeof s.threadId!="string"||typeof s.interruptedRunId!="string"||typeof s.generation!="number"?!1:s.threadId===t.threadId&&s.interruptedRunId===t.interruptedRunId&&s.generation===t.generation)}resolveJoinedRun(e){if(e.type!=="RUN_FINISHED"&&e.type!=="RUN_ERROR")return;const t=Re(e);if(t===void 0)return;const n=this.joinedRunWaiters.get(t);n!==void 0&&(this.joinedRunWaiters.delete(t),n())}ensureSubscription(){if(!this.isSubscribed){this.subscribe();return}(!this.subscriptionAbortController||this.subscriptionAbortController.signal.aborted)&&this.subscribe({restart:!0})}waitForProcessing(){return this.resolveProcessing(),new Promise(e=>{this.processingResolve=e})}async sendMessage(e,t,n){if(this.mountDevtools(),typeof e=="string"&&!e.trim())return;if(this.hasPendingInterrupts())throw new Error("ChatClient: cannot send normal input while pending interrupts exist. Use resumeInterrupts() instead.");const r={...t,...n?.body};if(this.isSendBusy()){const{action:s,id:o}=this.decideWhenBusy(e,n);if(s==="drop")return;if(s==="queue"){this.enqueueMessage(e,r,o);return}this.stopMessageQueueDrain=!0,this.sendInFlight=!0,this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating()}else this.sendInFlight=!0;try{await this.deliverMessage(e,r)}finally{this.sendInFlight=!1}}hasPendingInterrupts(){return this.interruptManager.getDescriptors().length>0}isSendBusy(){return this.isLoading||this.sendInFlight||this.messageQueueDraining}resolveBusyReason(){return this.isLoading?"streaming":this.messageQueueDraining?"draining":"sendInFlight"}async deliverMessage(e,t){if(this.isLoading||this.deliverClaim)return!1;this.deliverClaim=!0;try{const n=this.normalizeMessageInput(e);this.pendingMessageBody=t;const r=this.processor.addUserMessage(n.content,n.id,n.metadata);return this.events.messageSent(r.id,n.content),await this.streamResponse()}finally{this.deliverClaim=!1}}decideWhenBusy(e,t){const n=this.generateUniqueId("queued");if(t?.whenBusy)return{action:t.whenBusy,id:n};const{strategy:r,whenBusy:s}=this.queueConfig;if(r){const{action:o}=r({pending:{id:n,content:e,createdAt:Date.now()},busyReason:this.resolveBusyReason(),queued:this.getQueue()});return{action:o,id:n}}return{action:s,id:n}}enqueueMessage(e,t,n){const{maxSize:r,onOverflow:s}=this.queueConfig;if(r!==void 0&&this.messageQueue.length>=r){if(s==="reject"||r===0)return;this.messageQueue.shift()}this.messageQueue.push({id:n??this.generateUniqueId("queued"),content:e,createdAt:Date.now(),...t!==void 0?{body:t}:{}}),this.emitQueueChange()}normalizeMessageInput(e){return typeof e=="string"?{content:e.trim()}:{content:e.content,id:e.id,...e.metadata!==void 0?{metadata:e.metadata}:{}}}async append(e){if(this.mountDevtools(),this.hasPendingInterrupts())throw new Error("ChatClient: cannot append normal input while pending interrupts exist. Use resumeInterrupts() instead.");const t=RC(e,Et);if(t.role==="system")return;const n=t;this.events.messageAppended(n);const r=this.processor.getMessages();if(this.processor.setMessages([...r,n]),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(async()=>{await this.streamResponse()});return}await this.streamResponse()}async streamResponse(){if(this.isLoading)return!1;const e=++this.streamGeneration;this.streamContinuationGeneration=this.continuationGeneration;const t=this.pendingResumeThreadId,n=this.pendingResumeParentRunId,r=this.pendingResumeItems;this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null;const s=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.setCurrentRunId(s),this.activeResumeThreadId=t??this.threadId,this.activeResumeRunId=s,this.setIsLoading(!0),this.deliverClaim=!1,this.setStatus("submitted"),this.setError(void 0),this.errorReportedGeneration=null,this.abortController=new AbortController;const o=this.abortController.signal;this.pendingToolExecutions.clear();let i=!1,a=null,l=!1;try{const c=this.messagesForSend(this.processor.getMessages()),u=new Map(this.clientToolsRef.current),d=this.context;if(await this.callbacksRef.current.onResponse(),o.aborted)return!1;const f={...this.bodyOption,...this.forwardedPropsOption,...this.pendingMessageBody};this.pendingMessageBody=void 0,this.currentStreamId=this.generateUniqueId("stream"),this.devtoolsBridge.setCurrentStreamId(this.currentStreamId),this.currentMessageId=null,this.activeClientTools=u,this.activeContext=d,this.processor.prepareAssistantMessage(),this.ensureSubscription();const g=this.waitForProcessing();let p;if(this.byok){const x=ON(this.byokProvider,f.provider,jE(this.byok));p=await jN(this.byok,x)}const y={threadId:t??this.threadId,runId:s,...n!==null?{parentRunId:n}:{},clientTools:Array.from(u.values()).map(x=>({name:x.name,description:x.description,parameters:x.inputSchema?Gs(x.inputSchema):{type:"object"}})),forwardedProps:{...f},...r?{resume:r}:{},...p?{headers:p}:{}};if(this.devtoolsBridge.beginRun(y.runId,y.threadId),a=y.runId,this.devtoolsBridge.emitRunLifecycle("run:created",y.runId,"created"),this.devtoolsBridge.emitRunLifecycle("run:started",y.runId,"started"),this.devtoolsBridge.emitSnapshot(),await this.connection.send(c,f,o,y),e!==this.streamGeneration||o.aborted||(this.connectionDrainsOnSend&&this.resolveProcessing(),await g,e!==this.streamGeneration))return!1;if(this.status==="error")return a&&(this.devtoolsBridge.emitRunLifecycle("run:errored",a,"errored",this.error?{error:this.error.message}:{}),l=!0),!1;this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values()),this.processor.finalizeStream(),i=!0}catch(c){const u=c instanceof Error?c:new Error(String(c));if(u.name==="AbortError")return a&&(this.devtoolsBridge.emitRunLifecycle("run:cancelled",a,"cancelled"),l=!0),!1;if(u instanceof Fs&&this.byok?.request(u.provider,"missing"),u instanceof br&&u.reason==="locked"&&this.byok?.request(u.provider,"locked"),e===this.streamGeneration&&(this.reportStreamError(u),a&&(this.devtoolsBridge.emitRunLifecycle("run:errored",a,"errored",{error:u.message}),l=!0)),e===this.streamGeneration&&(u instanceof Fs||u instanceof br||u instanceof pd))throw u}finally{e===this.streamGeneration&&(this.currentStreamId=null,this.devtoolsBridge.setCurrentStreamId(null),this.currentMessageId=null,this.setCurrentRunId(null),this.activeClientTools=null,this.activeContext=void 0,this.abortController=null,this.setIsLoading(!1),this.pendingMessageBody=void 0,a&&!l&&(i?this.devtoolsBridge.emitRunLifecycle("run:completed",a,"completed"):o.aborted&&this.devtoolsBridge.emitRunLifecycle("run:cancelled",a,"cancelled")),await this.drainPostStreamActions(),i?(this.rememberProcessorMessageIds(),this.status!=="ready"&&this.setStatus("ready"),this.messageQueueDraining||await this.drainQueue()):this.flushQueue())}return i}subscribe(e){const t=e?.restart===!0;this.isSubscribed&&!t||(this.isSubscribed&&t&&this.abortSubscriptionLoop(),this.setIsSubscribed(!0),this.setConnectionStatus("connecting"),this.startSubscription())}unsubscribe(){this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}),this.discardPendingSends(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus("disconnected")}async reload(){const e=this.processor.getMessages();if(e.length===0)return;const t=e.findLastIndex(n=>n.role==="user");t!==-1&&(this.isLoading&&this.cancelInFlightStream(),this.discardPendingSends(),this.events.reloaded(t),this.processor.removeMessagesAfter(t),this.devtoolsBridge.emitSnapshot(),await this.streamResponse())}stop(){this.continuationGeneration++;const e=this.abortController!==null;this.cancelInFlightStream({setReadyStatus:!0}),this.discardPendingSends(),this.lastResume=null,this.activeInterruptSubmission=void 0,this.interruptManager.reset(),e&&this.resetSessionGenerating(),this.events.stopped()}clear(){const e=this.abortController!==null;this.clearedStreamTracker.snapshotClear({messages:this.processor.getMessages(),activeRunIds:this.activeRunIds,currentRunId:this.currentRunId}),this.isLoading||e?(this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating({preserveClearedStreamTracking:!0})):this.activeRunIds.size>0&&this.resetSessionGenerating({preserveClearedStreamTracking:!0}),this.persistor?.beginClear(),this.processor.clearMessages(),this.resetHistoryPaging(),this.discardPendingSends(),this.persistor?.remove(),this.lastResume=null,this.interruptManager.reset(),this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null,this.setError(void 0),this.events.messagesCleared()}async addToolResult(e){const t=this.clientToolsRef.current.get(e.tool);await this.addToolResultForClientTool(e,t,this.streamContinuationGeneration)}async addToolResultForClientTool(e,t,n,r){if(t&&e.state!=="output-error")try{e={...e,output:this.validateClientToolOutput(t,e.output)}}catch(s){e={...e,output:null,state:"output-error",errorText:s.message}}if(this.events.toolResultAdded(e.toolCallId,e.tool,e.output,e.state||"output-available",r),n===this.continuationGeneration&&(this.processor.addToolResult(e.toolCallId,e.output,e.state==="output-error"?e.errorText||"Tool execution failed":void 0),this.devtoolsBridge.emitSnapshot(),!this.interruptManager.resolveClientToolOutput(e.toolCallId,e.state==="output-error"?{error:e.errorText||"Tool execution failed"}:e.output))){if(this.isLoading){this.queuePostStreamAction(()=>n===this.continuationGeneration?this.checkForContinuation():Promise.resolve());return}await this.checkForContinuation()}}validateClientToolOutput(e,t){return e.outputSchema&&ft(e.outputSchema)?QE(e.outputSchema,t):t}async addToolApprovalResponse(e){if(this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.interruptManager.resolveToolApprovalDecision(e.id,e.approved))return;const t=this.processor.getMessages();let n;for(const r of t){const s=r.parts.find(o=>o.type==="tool-call"&&o.approval?.id===e.id);if(s){n=s.id;break}}if(n&&this.events.toolApprovalResponded(e.id,n,e.approved),this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}queuePostStreamAction(e){const t=this.continuationGeneration;this.postStreamActions.push(async()=>{t===this.continuationGeneration&&await e()})}async drainPostStreamActions(){if(!this.draining){this.draining=!0;try{let e;for(;(e=this.postStreamActions.shift())!==void 0;)await e()}finally{this.draining=!1}}}async checkForContinuation(){if(this.streamContinuationGeneration===this.continuationGeneration&&!this.hasPendingInterrupts()){if(this.continuationPending||this.isLoading){this.continuationSkipped=!0;return}if(this.shouldAutoSend()){this.continuationPending=!0,this.continuationSkipped=!1;let e=!1;try{e=await this.streamResponse()}finally{this.continuationPending=!1}this.continuationSkipped&&e&&(this.continuationSkipped=!1,await this.checkForContinuation())}}}shouldAutoSend(){if(this.lastResume||this.activeInterruptSubmission&&this.hasPendingInterrupts()||this.interruptManager.getInterrupts().length>0)return!1;const e=this.processor.getMessages().findLast(t=>t.role==="assistant");return!e||!e.parts.some(t=>t.type==="tool-call")?!1:this.processor.areAllToolsComplete()}getMessages(){return this.processor.getMessages()}getHasOlderMessages(){return this.hasOlderMessages}async loadOlderMessages(){const e=this.connection.hydrate;if(e===void 0||this.disposed||!this.hasOlderMessages)return;const t=this.olderMessagesCursor;if(t===void 0||this.loadOlderMessagesInFlight)return;const n={before:t};this.historyPageSize!==void 0&&(n.limit=this.historyPageSize),this.loadOlderMessagesInFlight=!0;const r=this.historyGeneration;try{const s=await e(this.threadId,n);if(this.disposed||r!==this.historyGeneration)return;const o=Hs(s.messages);if(o.length===0)throw new Error("Older page was empty");this.applyHydrationPage(s.page),this.processor.prependMessages(o),this.rememberServerMessageIds(o)}finally{this.loadOlderMessagesInFlight=!1}}resetHistoryPaging(){this.hasOlderMessages=!1,this.olderMessagesCursor=void 0,this.knownServerMessageIds.clear(),this.historyGeneration++}applyHydrationPage(e){if(e?.truncated===!0){this.hasOlderMessages=!0,this.olderMessagesCursor=e.cursor;return}this.hasOlderMessages=!1,this.olderMessagesCursor=void 0}rememberServerMessageIds(e){const t=e.map(n=>n.id);for(const n of t)this.knownServerMessageIds.add(n)}rememberProcessorMessageIds(){this.historyPageSize!==void 0&&this.rememberServerMessageIds(this.processor.getMessages())}messagesForSend(e){if(this.historyPageSize===void 0)return e;const t=[];for(const r of e)this.knownServerMessageIds.has(r.id)||t.push(r);if(t.length>0)return t;const n=e.findLastIndex(r=>r.role==="user");return n===-1?[]:e.slice(n)}shouldAbortMessageQueueDrain(){return this.isLoading||this.stopMessageQueueDrain}async drainQueue(){if(!(this.messageQueueDraining||this.isLoading||this.messageQueue.length===0)){this.messageQueueDraining=!0,this.stopMessageQueueDrain=!1;try{if(this.queueConfig.drain==="batch"){for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;const e=this.messageQueue.splice(0);this.emitQueueChange();const t=YN(e);if(!await this.deliverMessage(t.content,t.body)||this.shouldAbortMessageQueueDrain())return}return}for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;const e=this.messageQueue.shift();if(e===void 0||(this.emitQueueChange(),!await this.deliverMessage(e.content,e.body)||this.shouldAbortMessageQueueDrain()))return}}finally{this.messageQueueDraining=!1,this.stopMessageQueueDrain=!1}}}discardPendingSends(){this.sendInFlight=!1,this.flushQueue()}getQueue(){return this.messageQueue.map(({id:e,content:t,createdAt:n})=>({id:e,content:t,createdAt:n}))}emitQueueChange(){this.callbacksRef.current.onQueueChange(this.getQueue()),this.devtoolsBridge.emitSnapshot()}cancelQueued(e){const t=this.messageQueue.findIndex(n=>n.id===e);t!==-1&&(this.messageQueue.splice(t,1),this.emitQueueChange())}flushQueue(){this.messageQueue.length!==0&&(this.messageQueue=[],this.emitQueueChange())}getIsLoading(){return this.isLoading}getStatus(){return this.status}getIsSubscribed(){return this.isSubscribed}getConnectionStatus(){return this.connectionStatus}getSessionGenerating(){return this.sessionGenerating}getError(){return this.error}setMessagesManually(e){this.processor.setMessages(e),this.devtoolsBridge.emitSnapshot()}updateOptions(e){if(e.connection!==void 0||e.fetcher!==void 0){const t=this.isSubscribed;this.isLoading?this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}):t&&this.abortSubscriptionLoop(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus("disconnected");const n=cl({connection:e.connection,fetcher:e.fetcher});this.connectionDrainsOnSend=ul(n),this.connection=Qa(n),t&&this.subscribe()}if(e.body!==void 0&&(this.bodyOption=e.body),e.forwardedProps!==void 0&&(this.forwardedPropsOption=e.forwardedProps),e.byok!==void 0&&(this.byok=e.byok),e.byokProvider!==void 0&&(this.byokProvider=e.byokProvider),"context"in e&&(this.context=e.context),e.tools!==void 0){this.interruptManager.updateTools(e.tools),this.clientToolsRef.current=new Map;for(const t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge.notifyToolsChanged()}e.queue!==void 0&&(this.queueConfig=hl(e.queue)),e.onResponse!==void 0&&(this.callbacksRef.current.onResponse=e.onResponse),e.onChunk!==void 0&&(this.callbacksRef.current.onChunk=e.onChunk),e.onFinish!==void 0&&(this.callbacksRef.current.onFinish=e.onFinish),e.onError!==void 0&&(this.callbacksRef.current.onError=e.onError),e.onSubscriptionChange!==void 0&&(this.callbacksRef.current.onSubscriptionChange=e.onSubscriptionChange),e.onConnectionStatusChange!==void 0&&(this.callbacksRef.current.onConnectionStatusChange=e.onConnectionStatusChange),e.onSessionGeneratingChange!==void 0&&(this.callbacksRef.current.onSessionGeneratingChange=e.onSessionGeneratingChange),e.onQueueChange!==void 0&&(this.callbacksRef.current.onQueueChange=e.onQueueChange),e.onResumeStateChange!==void 0&&(this.callbacksRef.current.onResumeStateChange=e.onResumeStateChange),e.onRunIdChange!==void 0&&(this.callbacksRef.current.onRunIdChange=e.onRunIdChange),e.onInterruptStateChange!==void 0&&(this.callbacksRef.current.onInterruptStateChange=e.onInterruptStateChange),e.onCustomEvent!==void 0&&(this.callbacksRef.current.onCustomEvent=e.onCustomEvent)}dispose(){this.disposed=!0,this.unsubscribe(),this.devtoolsBridge.dispose(),this.devtoolsMounted=!1}};function fl(e){return!e||typeof e!="object"?{}:{..."before"in e&&typeof e.before=="number"?{before:e.before}:{},..."after"in e&&typeof e.after=="number"?{after:e.after}:{},..."messagesBefore"in e&&typeof e.messagesBefore=="number"?{messagesBefore:e.messagesBefore}:{},..."messagesAfter"in e&&typeof e.messagesAfter=="number"?{messagesAfter:e.messagesAfter}:{},..."reusedCheckpoint"in e&&typeof e.reusedCheckpoint=="boolean"?{reusedCheckpoint:e.reusedCheckpoint}:{},..."maxTokens"in e&&typeof e.maxTokens=="number"?{maxTokens:e.maxTokens}:{},..."strategyKey"in e&&typeof e.strategyKey=="string"?{strategyKey:e.strategyKey}:{},..."durationMs"in e&&typeof e.durationMs=="number"?{durationMs:e.durationMs}:{}}}function pl(e){if(!Array.isArray(e))return;const t=[];for(const n of e)!n||typeof n!="object"||!("role"in n)||!("tokens"in n)||!("text"in n)||typeof n.role!="string"||typeof n.tokens!="number"||typeof n.text!="string"||t.push({role:n.role,tokens:n.tokens,text:n.text});return t}function tR(e){if(!e||typeof e!="object"||!("before"in e)||!("after"in e)||!("messagesBefore"in e)||!("messagesAfter"in e)||typeof e.before!="number"||typeof e.after!="number"||typeof e.messagesBefore!="number"||typeof e.messagesAfter!="number")return null;const t="reusedCheckpoint"in e&&e.reusedCheckpoint===!0,n="maxTokens"in e&&typeof e.maxTokens=="number"?e.maxTokens:void 0,r="strategyKey"in e&&typeof e.strategyKey=="string"?e.strategyKey:void 0,s="dropped"in e?pl(e.dropped):void 0,o="result"in e?pl(e.result):void 0;return{before:e.before,after:e.after,messagesBefore:e.messagesBefore,messagesAfter:e.messagesAfter,reusedCheckpoint:t,...n!==void 0?{maxTokens:n}:{},...r?{strategyKey:r}:{},...s?{dropped:s}:{},...o?{result:o}:{}}}var gl=Symbol.for("tanstack.ai.devtools.activeBridgeByHookId");function xs(){const e=globalThis,t=e[gl];if(t)return t;const n=new Map;return e[gl]=n,n}function nR(e,t){return{get hookId(){return e.hookId},get clientId(){return e.clientId},get threadId(){return e.threadId},metadata:e.metadata,getSnapshot:t.getSnapshot,...t.getTools||e.getTools?{getTools:t.getTools??e.getTools}:{},...t.applyToolFixture||e.applyToolFixture?{applyToolFixture:t.applyToolFixture??e.applyToolFixture}:{}}}var rR=class{options;unsubscribers=[];disposed=!1;superseded=!1;registered=!1;constructor(e){this.options=e}emitRegistered(){this.prepareForMountEmit()&&(this.registered=!0,xe("hook:registered",{...this.createEnvelope("hook:registered"),...this.createMetadataPayload(),lifecycle:"mounted"}))}emitUpdated(){this.prepareForEmit()&&xe("hook:updated",{...this.createEnvelope("hook:updated"),...this.createMetadataPayload(),lifecycle:"active"})}emitSnapshot(){this.prepareForEmit()&&xe("hook:state-snapshot",{...this.createEnvelope("hook:state-snapshot"),...this.createMetadataPayload(),state:this.options.getSnapshot()})}emitToolsRegistered(){if(!this.prepareForEmit())return;const e=this.options.getTools?Array.from(this.options.getTools()).map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema?Gs(t.inputSchema):{type:"object"},outputSchema:t.outputSchema?Gs(t.outputSchema):void 0,needsApproval:t.needsApproval,metadata:t.metadata})):[];xe("tools:registered",{...this.createEnvelope("tools:registered"),...this.createMetadataPayload(),tools:e})}emitRunLifecycle(e,t,n,r={}){this.prepareForEmit()&&xe(e,{...this.createEnvelope(e,"client-state",{runId:t}),runId:t,status:n,...r.error?{error:r.error}:{}})}deactivate(){const e=xs();e.get(this.options.hookId)===this&&e.delete(this.options.hookId);for(const t of this.unsubscribers.splice(0))t()}supersede(){this.disposed||(this.superseded=!0,this.disposed=!0,this.deactivate())}dispose(){if(this.disposed)return;if(this.disposed=!0,!this.registered){this.deactivate();return}if(xs().get(this.options.hookId)!==this){this.deactivate();return}const e={...this.createEnvelope("hook:unregistered"),...this.createMetadataPayload(),reason:"disposed"};xe("hook:unregistered",e),this.deactivate()}prepareForEmit(){return this.disposed||this.superseded?!1:(this.activate(),!0)}prepareForMountEmit(){return this.superseded?!1:(this.disposed&&(this.disposed=!1,this.registered=!1),this.activate(),!0)}activate(){if(this.disposed)return;const e=xs(),t=e.get(this.options.hookId);t&&t!==this&&(typeof t.supersede=="function"?t.supersede():t.deactivate()),e.set(this.options.hookId,this),!(this.unsubscribers.length>0)&&(this.unsubscribers.push(An.on("devtools:request-state",n=>{this.handleRequestState(n)})),this.options.applyToolFixture&&this.unsubscribers.push(An.on("devtools:tool-fixture:apply",n=>{this.handleToolFixtureApply(n)})))}handleRequestState(e){if(this.disposed||this.superseded)return;const t=e.payload.targetHookId;t&&t!==this.options.hookId||(this.emitRegistered(),this.emitToolsRegistered(),this.emitSnapshot(),this.onReplayState())}onReplayState(){}async handleToolFixtureApply(e){const t=e.payload;this.matchesFixtureTarget(t)&&await this.options.applyToolFixture?.(t)}matchesFixtureTarget(e){return!e.hookId&&!e.threadId?!1:e.hookId?e.hookId===this.options.hookId:!(e.threadId&&(!this.options.threadId||e.threadId!==this.options.threadId))}createEnvelope(e,t="client-state",n={}){return Xs({eventType:e,source:"client",visibility:t,clientId:this.options.clientId,hookId:this.options.hookId,...this.options.threadId?{threadId:this.options.threadId}:{},...n.runId?{runId:n.runId}:{},timestamp:Date.now()})}createMetadataPayload(){return{hookId:this.options.hookId,hookName:this.options.metadata.hookName,...this.options.metadata.name?{displayName:this.options.metadata.name}:{},...this.options.metadata.outputKind?{outputKind:this.options.metadata.outputKind}:{},...this.options.metadata.framework?{framework:this.options.metadata.framework}:{}}}},sR=class extends rR{events;chatOptions;currentRunId=null;currentRunThreadId=null;currentStreamId=null;lastStreamId=null;lastRunEventContext;lastMemoryStateValue=null;lastCompactionEvents=[];lastSkillsStateValue=null;constructor(e){super(nR(e,{getSnapshot:e.getSnapshot,applyToolFixture:t=>this.applyFixture(t)})),this.chatOptions=e,this.events=new uR(()=>e.clientId,this)}setCurrentStreamId(e){this.currentStreamId=e,e&&(this.lastStreamId=e)}recordStreamId(e){e&&(this.lastStreamId=e)}mountWithTools(e){this.events.clientCreated(e),this.emitRegistered(),this.emitToolsRegistered(),this.emitSnapshot()}notifyToolsChanged(){this.emitToolsRegistered(),this.emitSnapshot()}getCurrentStreamId(){return this.currentStreamId}getLastStreamId(){return this.lastStreamId}resolveStreamId(){return this.currentStreamId??this.lastStreamId??this.chatOptions.generateId("stream")}beginRun(e,t){this.currentRunId=e,this.currentRunThreadId=t,this.lastRunEventContext={runId:e,threadId:t}}observeChunk(e){if(e.type==="RUN_STARTED"){this.beginRun(e.runId,e.threadId);return}if(e.type==="RUN_FINISHED"||e.type==="RUN_ERROR"){const t=(e.type==="RUN_FINISHED",e.runId);if(!t||t===this.currentRunId){const n=this.getCurrentRunEventContext();n&&(this.lastRunEventContext=n),this.currentRunId=null,this.currentRunThreadId=null}}}recordMemoryState(e){this.lastMemoryStateValue=e,this.emitMemoryState(e)}recordSkillsState(e){this.lastSkillsStateValue=e,this.emitSkillsState(e)}emitMemoryState(e){if(!e||typeof e!="object")return;const t=e,n=t.scope,r=t.adapter;if(!n||typeof r!="string")return;const s=this.currentRunId?{runId:this.currentRunId}:{};xe("memory:retrieve:started",{...this.createEnvelope("memory:retrieve:started","client-state",s),scope:n,adapter:r,query:t.query??""}),t.recall&&xe("memory:retrieve:completed",{...this.createEnvelope("memory:retrieve:completed","client-state",s),scope:n,adapter:r,fragmentCount:t.recall.fragmentCount??0,hasTools:!!t.recall.hasTools,systemPromptChars:t.recall.systemPromptChars??0,durationMs:t.recall.durationMs??0}),t.snapshot&&xe("memory:snapshot",{...this.createEnvelope("memory:snapshot","client-state",s),scope:n,adapter:r,takenAt:t.snapshot.takenAt,data:t.snapshot.data,facts:t.snapshot.facts??[]})}recordCompactionEvent(e,t){this.lastCompactionEvents.push({eventType:e,value:t}),this.lastCompactionEvents.length>60&&this.lastCompactionEvents.splice(0,this.lastCompactionEvents.length-60),this.emitCompactionEvent(e,t)}recordCompactionState(e){this.recordCompactionEvent("compaction:state",e)}emitCompactionEvent(e,t){const n=this.currentRunId?{runId:this.currentRunId}:{};if(e==="compaction:started"){const r=fl(t);xe("compaction:started",{...this.createEnvelope("compaction:started","client-state",n),...r});return}if(e==="compaction:ended"){const r=fl(t);xe("compaction:ended",{...this.createEnvelope("compaction:ended","client-state",n),...r});return}if(e==="compaction:state"){const r=tR(t);if(!r)return;xe("compaction:state",{...this.createEnvelope("compaction:state","client-state",n),...r})}}emitSkillsState(e){if(!e||typeof e!="object")return;const t=e,n=Array.isArray(t.catalog)?t.catalog:[],r=Array.isArray(t.activated)?t.activated:[],s=this.currentRunId?{runId:this.currentRunId}:{};xe("skills:snapshot",{...this.createEnvelope("skills:snapshot","client-state",s),catalog:n,activated:r})}onReplayState(){this.lastMemoryStateValue!=null&&this.emitMemoryState(this.lastMemoryStateValue);for(const e of this.lastCompactionEvents)this.emitCompactionEvent(e.eventType,e.value);this.lastSkillsStateValue!=null&&this.emitSkillsState(this.lastSkillsStateValue)}getCurrentRunEventContext(){if(this.currentRunId)return{threadId:this.currentRunThreadId??this.chatOptions.threadId??"",runId:this.currentRunId}}getCurrentOrLastRunEventContext(){return this.getCurrentRunEventContext()??this.lastRunEventContext}findToolCallContext(e){const t={toolCallId:e},n=this.getCurrentRunEventContext();return n?{threadId:n.threadId,runId:n.runId,toolCallId:e}:this.chatOptions.threadId?{threadId:this.chatOptions.threadId,toolCallId:e}:t}async applyFixture(e){const t=this.chatOptions.getMessages(),n=e.threadId??this.chatOptions.threadId??"";if(e.execute){await this.executeFixture(e,t,n);return}const{message:r,toolCallId:s}=this.createReplayMessageFromFixture(e,t),o=r.id;this.events.messageAppended(r,void 0,{threadId:n,toolCallId:s,...e.runId?{runId:e.runId}:{}}),this.chatOptions.setMessages([...t,r]),this.events.toolFixtureApplied({hookId:this.chatOptions.hookId,threadId:n,...e.runId?{runId:e.runId}:{},toolName:e.toolName,input:e.input,output:e.output,messageId:o,toolCallId:s,...e.execute!==void 0?{execute:e.execute}:{},...e.message?{message:e.message}:{},...e.errorText?{errorText:e.errorText}:{}}),this.emitSnapshot()}async executeFixture(e,t,n){const r=this.resolveFixtureToolCallId(e.toolCallId,t),s=this.resolveFixtureMessageId(e.messageId,t),o={id:s,role:"assistant",parts:[{type:"tool-call",id:r,name:e.toolName,arguments:Ss(e.input),input:e.input,state:"input-complete"}],createdAt:new Date};this.events.messageAppended(o,void 0,{threadId:n,toolCallId:r,...e.runId?{runId:e.runId}:{}}),this.chatOptions.setMessages([...t,o]),this.emitSnapshot();const i=this.findClientTool(e.toolName)?.execute;if(!i){console.warn(`[ai-devtools] tool fixture "${e.toolName}" requested execute=true but no client tool implementation is registered; replaying saved output instead.`),this.addToolResultForFixture({fixture:e,messageId:s,toolCallId:r,threadId:n,output:e.output,errorText:e.errorText});return}let a;try{a=await i(e.input)}catch(l){console.error(`[ai-devtools] tool fixture "${e.toolName}" execute threw`,l),this.addToolResultForFixture({fixture:e,messageId:s,toolCallId:r,threadId:n,output:null,errorText:l instanceof Error?`${l.name}: ${l.message}`:`Tool execution failed: ${String(l)}`});return}this.addToolResultForFixture({fixture:e,messageId:s,toolCallId:r,threadId:n,output:a})}addToolResultForFixture(e){const t=e.errorText?"output-error":"output-available";this.events.toolResultAdded(e.toolCallId,e.fixture.toolName,e.output,t,{threadId:e.threadId,...e.fixture.runId?{runId:e.fixture.runId}:{},toolCallId:e.toolCallId}),this.chatOptions.addToolResult(e.toolCallId,e.output,e.errorText),this.events.toolFixtureApplied({hookId:this.chatOptions.hookId,threadId:e.threadId,...e.fixture.runId?{runId:e.fixture.runId}:{},toolName:e.fixture.toolName,input:e.fixture.input,output:e.output,execute:!0,messageId:e.messageId,toolCallId:e.toolCallId,...e.errorText?{errorText:e.errorText}:{}}),this.emitSnapshot()}createReplayMessageFromFixture(e,t){const n=this.cloneFixtureSourceMessage(e,t);if(n)return n;const r=this.resolveFixtureToolCallId(e.toolCallId,t),s=this.resolveFixtureMessageId(e.messageId,t),o=e.errorText?"error":"complete";return{toolCallId:r,message:{id:s,role:"assistant",parts:[{type:"tool-call",id:r,name:e.toolName,arguments:Ss(e.input),input:e.input,state:"input-complete",output:e.output},{type:"tool-result",toolCallId:r,content:Ss(e.output),state:o,...e.errorText?{error:e.errorText}:{}}],createdAt:new Date}}}cloneFixtureSourceMessage(e,t){const n=e.message;if(!n||!Array.isArray(n.parts))return;const r=this.createFixtureToolCallIdMap(n.parts,t),s=n.parts.map(a=>iR(a,r)).filter(a=>!!a),o=e.toolCallId?r.get(e.toolCallId):void 0;if(lR(s,{...o?{mappedToolCallId:o}:{},output:e.output}),s.length===0)return;const i=(e.toolCallId?r.get(e.toolCallId):void 0)??aR(s);if(i)return{toolCallId:i,message:{id:this.resolveFixtureMessageId(n.id,t),role:n.role,parts:s,createdAt:new Date}}}createFixtureToolCallIdMap(e,t){const n=new Map;for(const r of e)!Bd(r)||r.type!=="tool-call"||typeof r.id=="string"&&n.set(r.id,this.resolveFixtureToolCallId(r.id,t));return n}resolveFixtureMessageId(e,t){return e&&!t.some(n=>n.id===e)?e:this.chatOptions.generateId("fixture-msg")}resolveFixtureToolCallId(e,t){return e&&!cR(t,e)?e:this.chatOptions.generateId("fixture-tool-call")}findClientTool(e){const t=this.chatOptions.getTools?.();if(t){for(const n of t)if(n.name===e)return n}}};function Bd(e){return typeof e=="object"&&e!==null}function Ss(e){if(typeof e=="string")return e;if(e===void 0||typeof e=="function"||typeof e=="symbol")return String(e);try{return JSON.stringify(e)}catch(t){return console.error("[ai-devtools] failed to JSON.stringify fixture value; falling back to String(). Tool call arguments may be malformed.",{error:t,value:e}),String(e)}}function oR(e){try{return JSON.parse(e)}catch(t){return console.error("[ai-devtools] failed to JSON.parse fixture result content; replaying as raw string. Fixture payload may be corrupted.",{error:t,content:e}),e}}function iR(e,t){if(!Bd(e)||typeof e.type!="string")return;const n={...e};return e.type==="tool-call"&&typeof e.id=="string"&&(n.id=t.get(e.id)??e.id),e.type==="tool-result"&&typeof e.toolCallId=="string"&&(n.toolCallId=t.get(e.toolCallId)??e.toolCallId),n}function aR(e){const t=e.find(n=>n.type==="tool-call");return t?.type==="tool-call"?t.id:void 0}function lR(e,t){for(const n of e){if(n.type!=="tool-result")continue;const r=e.find(s=>s.type==="tool-call"&&s.id===n.toolCallId&&s.output===void 0);r&&(r.output=Array.isArray(n.content)?n.content:oR(n.content))}if(t.mappedToolCallId&&t.output!==void 0){const n=e.find(r=>r.type==="tool-call"&&r.id===t.mappedToolCallId&&r.output===void 0);n&&(n.output=t.output)}}function cR(e,t){return e.some(n=>n.parts.some(r=>r.type==="tool-call"?r.id===t:r.type==="tool-result"?r.toolCallId===t:!1))}var uR=class extends FN{getClientId;helper;constructor(e,t){super(e()),this.getClientId=e,this.helper=t}emitEvent(e,t){this.clientId=this.getClientId(),super.emitEvent(e,t)}afterEmit(e){e&&this.helper.recordStreamId(e),this.helper.emitSnapshot()}textUpdated(e,t,n,r){super.textUpdated(e,t,n,r??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}thinkingUpdated(e,t,n,r,s){super.thinkingUpdated(e,t,n,r,s??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}messageAppended(e,t,n){super.messageAppended(e,t,n??this.helper.getCurrentRunEventContext()),this.afterEmit(t)}toolCallStateChanged(e,t,n,r,s,o,i){super.toolCallStateChanged(e,t,n,r,s,o,i??this.helper.getCurrentRunEventContext()),this.afterEmit(e)}structuredOutputChanged(e,t,n,r,s){super.structuredOutputChanged(e,t,n,r,s??this.helper.getCurrentOrLastRunEventContext()),this.afterEmit(t)}approvalRequested(e,t,n,r,s,o,i){super.approvalRequested(e,t,n,r,s,o,i??this.helper.getCurrentOrLastRunEventContext()),this.afterEmit(e)}toolResultAdded(e,t,n,r,s){super.toolResultAdded(e,t,n,r,s??this.helper.getCurrentRunEventContext()),this.afterEmit()}toolApprovalResponded(e,t,n,r){super.toolApprovalResponded(e,t,n,r??this.helper.getCurrentRunEventContext()),this.afterEmit()}clientCreated(e){super.clientCreated(e),this.afterEmit()}loadingChanged(e){super.loadingChanged(e),this.afterEmit()}errorChanged(e){super.errorChanged(e),this.afterEmit()}reloaded(e){super.reloaded(e),this.afterEmit()}stopped(){super.stopped(),this.afterEmit()}messagesCleared(){super.messagesCleared(),this.afterEmit()}messageSent(e,t){super.messageSent(e,t),this.afterEmit()}toolFixtureApplied(e){super.toolFixtureApplied(e),this.afterEmit()}};function dR(e){return new sR(e)}var ml=Object.freeze([]),hR=Object.freeze([]);function X_(e){const t=(0,C.useId)(),n=e.threadId??t,[r,s]=(0,C.useState)(e.initialMessages||[]),[o,i]=(0,C.useState)(!1),[a,l]=(0,C.useState)(void 0),[c,u]=(0,C.useState)("ready"),[d,f]=(0,C.useState)(!1),[g,p]=(0,C.useState)("disconnected"),[y,x]=(0,C.useState)(!1),[v,I]=(0,C.useState)([]),[m,S]=(0,C.useState)(null),[E,N]=(0,C.useState)(()=>({interrupts:ml,pendingInterrupts:ml,interruptErrors:hR,resuming:!1})),R=(0,C.useRef)(e.initialMessages||[]),A=(0,C.useRef)(!0),k=(0,C.useRef)(!1),P=(0,C.useRef)(null),_=(0,C.useRef)(null),M=(0,C.useRef)(null);R.current=r;const O=(0,C.useRef)(e);O.current=e;const b=(0,C.useCallback)(U=>{U&&(S(U.getCurrentRunId()),N(U.getInterruptState()))},[]),{client:w,initialization:T}=(0,C.useMemo)(()=>{const U=e.initialMessages||[];A.current=!1;const V=O.current,pe=V.connection?{connection:V.connection}:{fetcher:V.fetcher},ge={current:void 0},ve=()=>{const ee=ge.current;if(!(!ee||P.current!==ee))return ee},Me={ready:!1,callbacks:[]},ie=ee=>{if(!Me.ready){Me.callbacks.push(ee);return}const ce=ge.current;!ce||P.current!==ce||ee()},rt=new eR({devtoolsBridgeFactory:dR,...pe,initialMessages:U,...typeof V.threadId=="string"&&V.persistence?{persistence:V.persistence,threadId:V.threadId}:{...V.threadId!==void 0&&{threadId:V.threadId}},...V.body!==void 0&&{body:V.body},...V.forwardedProps!==void 0&&{forwardedProps:V.forwardedProps},...V.byok!==void 0&&{byok:V.byok},byokProvider:()=>O.current.byokProvider?.(),...V.initialResumeSnapshot!==void 0&&{initialResumeSnapshot:V.initialResumeSnapshot},...V.context!==void 0&&{context:V.context},devtools:{...V.devtools,framework:"react",hookName:"useChat",outputKind:V.outputSchema?"structured":"chat"},onResponse:ee=>{if(ve())return O.current.onResponse?.(ee)},onChunk:ee=>{ie(()=>{O.current.onChunk?.(ee)})},onFinish:ee=>{ie(()=>{O.current.onFinish?.(ee)})},onError:ee=>{ie(()=>{O.current.onError?.(ee)})},...V.tools!==void 0&&{tools:V.tools},...V.interrupts!==void 0&&{interrupts:V.interrupts},onCustomEvent:(ee,ce,ke)=>{ie(()=>{O.current.onCustomEvent?.(ee,ce,ke)})},...e.streamProcessor!==void 0&&{streamProcessor:e.streamProcessor},onMessagesChange:ee=>{ie(()=>{s(ee)})},onLoadingChange:ee=>{ie(()=>{const ce=ve();ce&&(i(ee),b(ce))})},onErrorChange:ee=>{ie(()=>{l(ee)})},onStatusChange:ee=>{ie(()=>{u(ee)})},onSubscriptionChange:ee=>{ie(()=>{f(ee)})},onConnectionStatusChange:ee=>{ie(()=>{p(ee)})},onSessionGeneratingChange:ee=>{ie(()=>{x(ee)})},...O.current.queue!==void 0&&{queue:O.current.queue},onQueueChange:ee=>{ie(()=>{I(ee)})},onRunIdChange:ee=>{ie(()=>{S(ee)})},onResumeStateChange:(ee,ce)=>{ie(()=>{N(ke=>({...ke,interrupts:ce,pendingInterrupts:ce}))})},onInterruptStateChange:(ee,ce)=>{ie(()=>{N(ee),O.current.onInterruptStateChange?.(ee,ce)})}});return ge.current=rt,{client:rt,initialization:Me}},[n,b]);(0,C.useEffect)(()=>{P.current=w;try{for(;T.callbacks.length>0;){if(P.current!==w){T.callbacks.length=0;break}T.callbacks.shift()?.()}}finally{T.ready=!0}},[w,T]),(0,C.useEffect)(()=>{const U=w.getMessages();U!==R.current&&s(U)},[w]),(0,C.useEffect)(()=>{w.updateOptions({body:e.body})},[w,e.body]),(0,C.useEffect)(()=>{e.forwardedProps!==void 0&&w.updateOptions({forwardedProps:e.forwardedProps})},[w,e.forwardedProps]),(0,C.useEffect)(()=>{e.tools!==void 0&&w.updateOptions({tools:e.tools})},[w,e.tools]),(0,C.useEffect)(()=>{w.updateOptions({context:e.context})},[w,e.context]),(0,C.useEffect)(()=>{e.queue!==void 0&&w.updateOptions({queue:e.queue})},[w,e.queue]),(0,C.useEffect)(()=>{e.live?(w.subscribe(),k.current=!0):k.current&&(w.unsubscribe(),k.current=!1)},[w,e.live]),(0,C.useEffect)(()=>(w.attach(),()=>{w.detach()}),[w]),(0,C.useEffect)(()=>(M.current?.client===w&&(clearTimeout(M.current.timeout),M.current=null),_.current&&(clearTimeout(_.current),_.current=null),w.mountDevtools(),b(w),()=>{_.current=setTimeout(()=>{P.current===w&&(P.current=null),_.current=null},0);const U={client:w,timeout:setTimeout(()=>{O.current.live?w.unsubscribe():w.stop(),w.dispose(),M.current===U&&(M.current=null)},0)};M.current=U}),[w,b]);const j=(0,C.useCallback)(async(U,V)=>{try{await w.sendMessage(U,void 0,V)}finally{b(w)}},[w,b]),D=(0,C.useCallback)(U=>{w.cancelQueued(U)},[w,b]),L=(0,C.useCallback)(async U=>{try{await w.append(U)}finally{b(w)}},[w,b]),F=(0,C.useCallback)(async()=>{try{await w.reload()}finally{b(w)}},[w,b]),z=(0,C.useCallback)(()=>{w.stop()},[w]),B=(0,C.useCallback)(()=>{w.clear(),b(w)},[w,b]),K=(0,C.useCallback)(U=>{w.setMessagesManually(U)},[w]),H=(0,C.useCallback)(async U=>{await w.addToolResult(U)},[w]),W=(0,C.useCallback)(async U=>{await w.addToolApprovalResponse(U),b(w)},[w,b]),J=(0,C.useCallback)(async(U,V)=>{const pe=await w.resumeInterrupts(U,V??void 0);return b(w),pe},[w,b]),X=(0,C.useCallback)(U=>{w.resolveInterrupts(U)},[w]),$=(0,C.useCallback)(()=>{w.cancelInterrupts()},[w]),q=(0,C.useCallback)(()=>{w.retryInterrupts()},[w]),Q=(0,C.useCallback)((U,V)=>w.resumeInterruptsUnsafe(U,V),[w]),te=w.getMessages(),G=(0,C.useMemo)(()=>{let U=-1;for(let V=te.length-1;V>=0;V--)if(te[V]?.role==="user"){U=V;break}if(U===-1)return null;for(let V=te.length-1;V>U;V--){const pe=te[V];if(pe?.role!=="assistant")continue;const ge=pe.parts.find(ve=>ve.type==="structured-output");if(ge)return ge}return null},[te]),ne=(0,C.useMemo)(()=>G?G.partial??G.data??{}:{},[G]),Z=(0,C.useMemo)(()=>!G||G.status!=="complete"?null:G.data,[G]);return{messages:te,sendMessage:j,append:L,reload:F,stop:z,isLoading:o,error:a,status:c,isSubscribed:d,connectionStatus:g,sessionGenerating:y,setMessages:K,clear:B,addToolResult:H,addToolApprovalResponse:W,queue:v,cancelQueued:D,runId:m,interrupts:E.interrupts,pendingInterrupts:E.pendingInterrupts,interruptErrors:E.interruptErrors,resuming:E.resuming,resolveInterrupts:X,cancelInterrupts:$,retryInterrupts:q,resumeInterruptsUnsafe:Q,resumeInterrupts:J,partial:ne,final:Z}}function fR(e){return(0,C.useSyncExternalStore)(e.subscribe,e.getSnapshot,()=>OE)}var Q_=new Uint8Array(128).fill(128),pR=zl()(Yp(e=>({provider:"gemini",model:Xo("gemini"),includeSchemaInAiContext:!0,setProvider:t=>e({provider:t,model:Xo(t)}),setModel:t=>e({model:t}),setIncludeSchemaInAiContext:t=>e({includeSchemaInAiContext:t})}),{name:"db-studio-ai-settings"})),gR=()=>{const[e,t]=(0,C.useState)(""),n=fR(bn),r=pR(),s=Wo.find(u=>u.id===r.provider),o=n.status[r.provider],i=o&&"masked"in o?o.masked:null,a=r.provider==="gemini",l=async()=>{const u=e.trim();u&&(await he.promise(bn.update(r.provider,u),{loading:`Saving ${s?.label} key...`,success:`${s?.label} key ready for this tab`,error:d=>d.message||`Could not save ${s?.label} key`}),t(""))},c=async()=>{await he.promise(bn.clear(r.provider),{loading:`Removing ${s?.label} key...`,success:a?"Using the hosted Gemini key":"API key removed",error:u=>u.message||`Could not remove ${s?.label} key`})};return(0,h.jsxs)("section",{className:"space-y-3",children:[(0,h.jsxs)("div",{className:"space-y-2 rounded-lg border p-3",children:[(0,h.jsx)(fe,{htmlFor:"ai-provider",children:"Provider"}),(0,h.jsxs)(qt,{value:r.provider,onValueChange:u=>{t(""),r.setProvider(u)},children:[(0,h.jsx)(Gt,{id:"ai-provider",children:(0,h.jsx)(Bt,{})}),(0,h.jsx)(Ut,{children:Wo.map(u=>(0,h.jsx)(dt,{value:u.id,children:u.label},u.id))})]}),(0,h.jsx)(fe,{htmlFor:"ai-model",children:"Model"}),(0,h.jsxs)(qt,{value:r.model,onValueChange:r.setModel,children:[(0,h.jsx)(Gt,{id:"ai-model",children:(0,h.jsx)(Bt,{})}),(0,h.jsx)(Ut,{children:s?.models.map(u=>(0,h.jsx)(dt,{value:u.id,children:u.label},u.id))})]})]}),(0,h.jsxs)("div",{className:"space-y-2 rounded-lg border p-3",children:[(0,h.jsxs)(fe,{htmlFor:"ai-api-key",children:[s?.label," API key"]}),(0,h.jsx)(ro,{id:"ai-api-key",type:"password",autoComplete:"off",value:e,onChange:u=>t(u.target.value),placeholder:i?`Saved ${i}`:"Paste an API key"}),(0,h.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Kept in memory for this tab only and cleared when the page reloads.",a&&" Leave empty to use the hosted Gemini key."]}),n.storageError&&(0,h.jsx)("p",{className:"text-xs text-destructive",children:n.storageError}),(0,h.jsxs)("div",{className:"flex gap-2",children:[(0,h.jsx)(ct,{type:"button",disabled:!e.trim(),onClick:l,children:"Save key"}),o&&o.state!=="empty"&&(0,h.jsx)(ct,{type:"button",variant:"outline",onClick:c,children:a?"Use hosted key":"Remove key"})]})]}),(0,h.jsxs)("div",{className:"flex items-center justify-between gap-4 rounded-lg border p-3",children:[(0,h.jsxs)("div",{className:"space-y-1",children:[(0,h.jsx)(fe,{htmlFor:"include-schema",children:"Include database schema"}),(0,h.jsx)("p",{className:"text-xs text-muted-foreground",children:"Share table and column metadata for context-aware answers."})]}),(0,h.jsx)(Vl,{id:"include-schema",checked:r.includeSchemaInAiContext,onCheckedChange:r.setIncludeSchemaInAiContext})]})]})},Gd=Nl("hover:text-foreground aria-pressed:bg-muted focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[state=on]:bg-accent data-[state=on]:text-accent-foreground gap-1 rounded-sm text-xs font-medium transition-colors [&_svg:not([class*='size-'])]:size-3.5 group/toggle hover:bg-muted inline-flex items-center justify-center whitespace-nowrap outline-none focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",{variants:{variant:{default:"bg-transparent",ghost:"bg-transparent hover:bg-muted",outline:"border-input hover:bg-muted border bg-transparent"},size:{default:"h-7 min-w-7 px-2",sm:"h-6 min-w-6 px-1.5 text-[0.625rem] [&_svg:not([class*='size-'])]:size-3",lg:"h-8 min-w-8 px-2"}},defaultVariants:{variant:"default",size:"default"}});function J_({className:e,variant:t="default",size:n="default",...r}){return(0,h.jsx)(Vf,{"data-slot":"toggle",className:me(Gd({variant:t,size:n,className:e})),...r})}var Ud=C.createContext({size:"default",variant:"default",spacing:0,orientation:"horizontal"});function vl({className:e,variant:t,size:n,spacing:r=0,orientation:s="horizontal",children:o,...i}){return(0,h.jsx)(Uf,{"data-slot":"toggle-group","data-variant":t,"data-size":n,"data-spacing":r,"data-orientation":s,style:{"--gap":r},className:me("rounded-sm group/toggle-group flex w-fit flex-row items-center gap-[--spacing(var(--gap))] data-[orientation=vertical]:flex-col data-[orientation=vertical]:items-stretch",e),...i,children:(0,h.jsx)(Ud.Provider,{value:{variant:t,size:n,spacing:r,orientation:s},children:o})})}function yl({className:e,children:t,variant:n="default",size:r="default",...s}){const o=(0,C.use)(Ud);return(0,h.jsx)(Gf,{"data-slot":"toggle-group-item","data-variant":o.variant||n,"data-size":o.size||r,"data-spacing":o.spacing,className:me("group-data-[spacing=0]/toggle-group:rounded-none group-data-[spacing=0]/toggle-group:px-2 group-data-horizontal/toggle-group:data-[spacing=0]:first:rounded-l-sm group-data-vertical/toggle-group:data-[spacing=0]:first:rounded-t-sm group-data-horizontal/toggle-group:data-[spacing=0]:last:rounded-r-sm group-data-vertical/toggle-group:data-[spacing=0]:last:rounded-b-sm shrink-0 focus:z-10 focus-visible:z-10 group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:border-l-0 group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:border-t-0 group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-l group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-t",Gd({variant:o.variant||n,size:o.size||r}),e),...s,children:t})}var mR=()=>{const{editor:e,setTabSize:t,setEditorFontSize:n,setEditorWordWrap:r}=ql();return(0,h.jsxs)("section",{className:"space-y-3",children:[(0,h.jsxs)("div",{className:"space-y-2 rounded-lg border p-3",children:[(0,h.jsx)(fe,{children:"Tab size"}),(0,h.jsx)("p",{className:"text-xs text-muted-foreground",children:"Indentation used by the query editor and JSON cells."}),(0,h.jsx)(vl,{type:"single",variant:"outline",className:"w-full",value:String(e.tabSize),onValueChange:s=>{s&&t(Number(s))},"aria-label":"Tab size",children:Up.map(s=>(0,h.jsxs)(yl,{value:String(s),className:"flex-1",children:[s," spaces"]},s))})]}),(0,h.jsxs)("div",{className:"space-y-2 rounded-lg border p-3",children:[(0,h.jsx)(fe,{children:"Font size"}),(0,h.jsx)("p",{className:"text-xs text-muted-foreground",children:"Text size in the query editor."}),(0,h.jsx)(vl,{type:"single",variant:"outline",className:"w-full",value:String(e.fontSize),onValueChange:s=>{s&&n(Number(s))},"aria-label":"Editor font size",children:qp.map(s=>(0,h.jsxs)(yl,{value:String(s),className:"flex-1",children:[s," px"]},s))})]}),(0,h.jsxs)("div",{className:"flex items-center justify-between gap-4 rounded-lg border p-3",children:[(0,h.jsxs)("div",{className:"space-y-1",children:[(0,h.jsx)(fe,{htmlFor:"editor-word-wrap",children:"Word wrap"}),(0,h.jsx)("p",{className:"text-xs text-muted-foreground",children:"Wrap long lines in the query editor instead of scrolling."})]}),(0,h.jsx)(Vl,{id:"editor-word-wrap",checked:e.wordWrap,onCheckedChange:r})]})]})},bl=({title:e,description:t,children:n})=>(0,h.jsxs)("div",{className:"space-y-3",children:[(0,h.jsxs)("div",{className:"space-y-1",children:[(0,h.jsx)("h3",{className:"text-sm font-semibold",children:e}),(0,h.jsx)("p",{className:"text-xs text-muted-foreground",children:t})]}),n]}),vR=()=>{const{closeOverlay:e,isOverlayOpen:t}=ut();return(0,h.jsxs)(Ul,{title:"Settings",description:"Changes apply immediately and are saved on this device.",open:t("settings.app"),size:"sm:max-w-md!",onOpenChange:n=>{n||e("settings.app")},children:[(0,h.jsx)(bl,{title:"Editor",description:"Query editor and JSON cell behavior.",children:(0,h.jsx)(mR,{})}),(0,h.jsx)(Kp,{}),(0,h.jsx)(bl,{title:"AI",description:"Provider, model, and API key for the assistant.",children:(0,h.jsx)(gR,{})})]})},Z_=()=>{const[e,t]=(0,C.useState)(!1);return(0,C.useEffect)(()=>{let n=!0;return bn.ready().then(()=>{n&&t(!0)}),()=>{n=!1}},[]),e},yR=`
|
|
12
|
+
try {
|
|
13
|
+
const stored = localStorage.getItem('db-studio-personal-preferences');
|
|
14
|
+
const theme = stored ? JSON.parse(stored)?.state?.theme : 'dark';
|
|
15
|
+
const isDark = theme === 'dark' || (theme === 'system' ? window.matchMedia('(prefers-color-scheme: dark)').matches : false);
|
|
16
|
+
if (isDark) {
|
|
17
|
+
document.documentElement.classList.add('dark');
|
|
18
|
+
document.documentElement.classList.remove('light');
|
|
19
|
+
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', '#09090b');
|
|
20
|
+
} else {
|
|
21
|
+
document.documentElement.classList.remove('dark');
|
|
22
|
+
document.documentElement.classList.add('light');
|
|
23
|
+
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', '#ffffff');
|
|
24
|
+
}
|
|
25
|
+
} catch (_) {
|
|
26
|
+
document.documentElement.classList.add('dark');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
try {
|
|
30
|
+
if (/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform)) {
|
|
31
|
+
document.documentElement.classList.add('os-macos');
|
|
32
|
+
}
|
|
33
|
+
} catch (_) {}
|
|
34
|
+
`,qd=()=>(0,h.jsx)("div",{className:"flex items-center justify-center h-screen",children:(0,h.jsx)(to,{size:"size-8",color:"bg-primary"})}),bR=()=>{const{dbType:e}=ht(),{isLoading:t,isInitialized:n,error:r}=bE();return(0,C.useEffect)(()=>{if(r&&e){const s=r?.status;Nr.capture("connection_error",{db_type:e,status_bucket:s?s>=500?"5xx":"4xx":"network"})}},[r,e]),(t||!n)&&!r?(0,h.jsx)(qd,{}):r?(0,h.jsxs)("div",{className:"flex flex-col items-center justify-center h-screen gap-3 text-center",children:[(0,h.jsx)("p",{className:"text-destructive font-medium",children:"Failed to connect to the database"}),(0,h.jsx)("p",{className:"text-muted-foreground text-sm max-w-sm",children:r?.message??"An unexpected error occurred"}),(0,h.jsx)(Er,{to:"/connect",className:"text-sm underline underline-offset-4",children:"Choose another connection"})]}):(0,h.jsx)(Sl,{})},Lo=nf({component:function(){so();const t=Il({select:l=>l.pathname}),{active:n,isLoading:r,error:s}=Ot();SE();const o=ef({select:l=>l.matches.some(c=>c.routeId==="/connect")});(0,C.useEffect)(()=>{const l="db-studio-telemetry-notice-shown";jp().then(c=>{c?.enabled&&(wp(),localStorage.getItem(l)||(localStorage.setItem(l,"1"),he.info("Anonymous usage and reliability data helps improve DB Studio.",{description:"Queries, schemas, names, and values are never collected.",duration:8e3})))})},[]),(0,C.useEffect)(()=>{const l=t.split("/").filter(Boolean)[0],c=["connect","browser","table","schema","runner","visualizer","logs","indexes"].find(u=>u===l)??"home";Nr.capture("page_viewed",{page:c})},[t]);const i=!!n&&!o,a=o?(0,h.jsx)(Sl,{}):r?(0,h.jsx)(qd,{}):s?(0,h.jsxs)("div",{className:"flex flex-col items-center justify-center h-screen gap-3 text-center",children:[(0,h.jsx)("p",{className:"text-destructive font-medium",children:"Cannot reach the DB Studio server"}),(0,h.jsx)("p",{className:"text-muted-foreground text-sm max-w-sm",children:s.message})]}):n?(0,h.jsx)(bR,{},n.connectionId):(0,h.jsx)(Jh,{to:"/connect"});return(0,h.jsxs)(Kf,{children:[(0,h.jsx)("script",{defer:!0,src:`data:text/javascript;base64,${btoa(yR)}`}),(0,h.jsxs)(cg,{fullPageNavigationOnShallowFalseUpdates:!0,defaultOptions:{shallow:!0,clearOnDefault:!0},children:[a,i&&(0,h.jsx)(yE,{})]}),(0,h.jsx)(eg,{position:"top-right"}),i&&(0,h.jsx)(Tg,{}),(0,h.jsx)(vR,{})]})}}),xR=()=>Ce(()=>import("./_pathlessLayout-D4dS7_ZZ.js").then(e=>e.t),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30])),SR=we("/_pathlessLayout")({component:Ee(xR,"component")}),IR=()=>Ce(()=>import("./connect-CCHOGwiQ.js"),[]),wR=we("/connect")({component:Ee(IR,"component")}),ER=()=>Ce(()=>import("./_pathlessLayout-1KXlcJn5.js"),__vite__mapDeps([31,2,1,3,4,16,6,7,8])),CR=we("/_pathlessLayout/")({component:Ee(ER,"component")}),NR=()=>Ce(()=>import("./browser-BXjW1U6_.js"),__vite__mapDeps([32,1,10,3,4,11,12,13,7,14,19,2,25,17,5,6,8,29,23,30,27,18])),RR=we("/_pathlessLayout/browser")({component:Ee(NR,"component")}),_R=()=>Ce(()=>import("./logs-C2iyjCnP.js"),__vite__mapDeps([33,1,13,4,3,12,11,7,19,26,9,10,14,15,16,6,8,2,17,5,18,20,24,27,25,22,23,28,21])),TR=we("/_pathlessLayout/logs")({component:Ee(_R,"component")}),AR=()=>Ce(()=>import("./visualizer-Bd-PB2Fm.js"),__vite__mapDeps([34,4,1,3])),MR=we("/_pathlessLayout/visualizer")({component:Ee(AR,"component")}),kR=()=>Ce(()=>import("./indexes-DUzB2YOr.js"),__vite__mapDeps([35,4,1,3])),OR=we("/_pathlessLayout/indexes/")({component:Ee(kR,"component")}),jR=()=>Ce(()=>import("./_table-DQvTfc38.js"),__vite__mapDeps([36,1,10,3,4,11,12,13,7,14,9,15,16,6,8,2,17,5,18,19,20,26,24,27,25,22,23,28,21])),PR=we("/_pathlessLayout/indexes/$table")({component:Ee(jR,"component")}),LR=()=>Ce(()=>import("./runner-DIQss6Kz.js"),__vite__mapDeps([37,38,1,2,3,4,17,16,6,7,8,29,23,13,12,11,19,28,25,5,20])),DR=we("/_pathlessLayout/runner/")({validateSearch:e=>typeof e.cmd=="string"?{cmd:e.cmd}:{},component:Ee(LR,"component")}),$R=()=>Ce(()=>import("./_queryId-DfjPCkx7.js"),__vite__mapDeps([39,38,1,2,3,4,17,16,6,7,8,29,23,13,12,11,19,28,25,5,20])),FR=we("/_pathlessLayout/runner/$queryId")({component:Ee($R,"component")}),zR=()=>Ce(()=>import("./schema-BqwkN_6u.js"),__vite__mapDeps([40,4,1,3])),HR=we("/_pathlessLayout/schema/")({component:Ee(zR,"component")}),BR=()=>Ce(()=>import("./_table-M7xRcFSl.js"),__vite__mapDeps([41,9,1,10,3,4,11,12,13,7,14,15,16,6,8,2,17,5,18,19,20])),GR=we("/_pathlessLayout/schema/$table")({component:Ee(BR,"component")}),UR=()=>Ce(()=>import("./table-BWy367NZ.js"),__vite__mapDeps([42,4,1,3])),qR=we("/_pathlessLayout/table/")({component:Ee(UR,"component")}),Ne=SR.update({id:"/_pathlessLayout",getParentRoute:()=>Lo}),VR=wR.update({id:"/connect",path:"/connect",getParentRoute:()=>Lo}),KR=CR.update({id:"/",path:"/",getParentRoute:()=>Ne}),YR=RR.update({id:"/browser",path:"/browser",getParentRoute:()=>Ne}),WR=TR.update({id:"/logs",path:"/logs",getParentRoute:()=>Ne}),XR=MR.update({id:"/visualizer",path:"/visualizer",getParentRoute:()=>Ne}),QR=OR.update({id:"/indexes/",path:"/indexes/",getParentRoute:()=>Ne}),JR=PR.update({id:"/indexes/$table",path:"/indexes/$table",getParentRoute:()=>Ne}),ZR=DR.update({id:"/runner/",path:"/runner/",getParentRoute:()=>Ne}),e_=FR.update({id:"/runner/$queryId",path:"/runner/$queryId",getParentRoute:()=>Ne}),t_=HR.update({id:"/schema/",path:"/schema/",getParentRoute:()=>Ne}),n_=GR.update({id:"/schema/$table",path:"/schema/$table",getParentRoute:()=>Ne}),r_=qR.update({id:"/table/",path:"/table/",getParentRoute:()=>Ne}),s_={PathlessLayoutBrowserRoute:YR,PathlessLayoutLogsRoute:WR,PathlessLayoutVisualizerRoute:XR,PathlessLayoutIndexRoute:KR,PathlessLayoutIndexesTableRoute:JR,PathlessLayoutRunnerQueryIdRoute:e_,PathlessLayoutSchemaTableRoute:n_,PathlessLayoutTableTableRoute:bp.update({id:"/table/$table",path:"/table/$table",getParentRoute:()=>Ne}),PathlessLayoutIndexesIndexRoute:QR,PathlessLayoutRunnerIndexRoute:ZR,PathlessLayoutSchemaIndexRoute:t_,PathlessLayoutTableIndexRoute:r_},o_={PathlessLayoutRoute:Ne._addFileChildren(s_),ConnectRoute:VR},i_=Lo._addFileChildren(o_)._addFileTypes(),a_=tf({routeTree:i_,context:{queryClient:Kl()},defaultPreload:"intent",scrollRestoration:!0,defaultStructuralSharing:!0}),Is=document.getElementById("root");if(Is&&!Is.innerHTML){const e=Wp.createRoot(Is),t=Kl();e.render((0,h.jsx)(C.StrictMode,{children:(0,h.jsx)(Wh,{client:t,children:(0,h.jsx)(sf,{router:a_})})}))}export{ug as C,dg as S,q_ as _,Z_ as a,L_ as b,J_ as c,X_ as d,W_ as f,V_ as g,K_ as h,PR as i,pR as l,Y_ as m,FR as n,vl as o,bn as p,DR as r,yl as s,GR as t,fR as u,D_ as v,$_ as x,F_ as y};
|