@augmentd-labs/canvas-web 0.0.0-stage → 2.14.8
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/LICENSE +661 -0
- package/NOTICE +78 -0
- package/README.md +139 -2
- package/dist/assets/Assistant-Bold-gm-uSS1B.woff2 +0 -0
- package/dist/assets/Assistant-Medium-DrcxCXg3.woff2 +0 -0
- package/dist/assets/Assistant-Regular-DVxZuzxb.woff2 +0 -0
- package/dist/assets/Assistant-SemiBold-SCI4bEL9.woff2 +0 -0
- package/dist/assets/EditorOverlay-CftUh9OI.js +1 -0
- package/dist/assets/LocationTab-ARqmeXmv.js +1 -0
- package/dist/assets/MarkdownEditor-BHRHw39q.js +93 -0
- package/dist/assets/MarkdownEditor-ByK7DHQ0.css +1 -0
- package/dist/assets/NextShell-B4NeoNB5.css +1 -0
- package/dist/assets/NextShell-CIyIaK3b.js +1 -0
- package/dist/assets/SketchEditor-DtRVLazd.css +1 -0
- package/dist/assets/SketchEditor-vg1HMZ0V.js +109 -0
- package/dist/assets/TextDocumentEditor-B6bUq9US.js +1 -0
- package/dist/assets/abnfDiagram-VCTEODGH-Cy_5vShZ.js +1 -0
- package/dist/assets/ar-SA-G6X2FPQ2-BJ7kJfgn.js +10 -0
- package/dist/assets/arc-SXJSVd7o.js +1 -0
- package/dist/assets/architecture-7GRP2DOG-BMOPAkUC.js +1 -0
- package/dist/assets/architectureDiagram-5GKGNRK7-2gVOlDi3.js +36 -0
- package/dist/assets/array-BifhSqXX.js +1 -0
- package/dist/assets/az-AZ-76LH7QW2-8v0TczD5.js +1 -0
- package/dist/assets/bg-BG-XCXSNQG7-DFFjBv03.js +5 -0
- package/dist/assets/blobs-DsQ7VyoY.js +1 -0
- package/dist/assets/blockDiagram-I7D4REHJ-DJlTH4XU.js +129 -0
- package/dist/assets/bn-BD-2XOGV67Q-KCzfC93t.js +5 -0
- package/dist/assets/c4Diagram-7LVT6UL2-aDTW23RC.js +38 -0
- package/dist/assets/ca-ES-6MX7JW3Y-QAg3jm2p.js +8 -0
- package/dist/assets/channel-DbE-WRyM.js +1 -0
- package/dist/assets/chunk-2E4U76K2-BX8JWCIb.js +2 -0
- package/dist/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
- package/dist/assets/chunk-2ZTRR5NV-C2qZJila.js +2 -0
- package/dist/assets/chunk-3Z5EZCMW-DMniOlPd.js +1 -0
- package/dist/assets/chunk-4HAMMTFA-DwG4o-7o.js +62 -0
- package/dist/assets/chunk-5V3GS4D5-i-ZDOEnP.js +1 -0
- package/dist/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
- package/dist/assets/chunk-6AZGARVD-BB6FqMl-.js +1 -0
- package/dist/assets/chunk-6EIED4P4-DdUJkP0f.js +1 -0
- package/dist/assets/chunk-6K3QC6MW-CqVsVn-y.js +1 -0
- package/dist/assets/chunk-6TQVIW2G-DKlLbNIP.js +1 -0
- package/dist/assets/chunk-6U3AYISY-C6-Mtja1.js +12 -0
- package/dist/assets/chunk-747NJXEK-BFkZPlab.js +2 -0
- package/dist/assets/chunk-75Z2AOVW-CzSd0Veu.js +2 -0
- package/dist/assets/chunk-CLGD4ZFX-BzBIdJij.js +1 -0
- package/dist/assets/chunk-DU6HZSFF-BlZbyIL6.js +125 -0
- package/dist/assets/chunk-EIO257PC-CAhBf1ig.js +22 -0
- package/dist/assets/chunk-F27PBJKO-B8_NVNfE.js +1 -0
- package/dist/assets/chunk-FOHPRMQF-DHwB1DNv.js +161 -0
- package/dist/assets/chunk-GMAD6QVW-tEmtNh72.js +72 -0
- package/dist/assets/chunk-GVQU2GXP-BMi2Lqv6.js +1 -0
- package/dist/assets/chunk-I5DQTOEV-Hm2LfiYI.js +1 -0
- package/dist/assets/chunk-ICYGCRZG-749o-pGJ.js +1 -0
- package/dist/assets/chunk-IH6LHLGP-CC6I9F3i.js +1 -0
- package/dist/assets/chunk-IMKFNOWR-BuKGugNz.js +231 -0
- package/dist/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
- package/dist/assets/chunk-K2UTITRG-D0fgw4vC.js +41 -0
- package/dist/assets/chunk-KI3K4JFJ-Rma-0k_M.js +1 -0
- package/dist/assets/chunk-L3NEJ4N5-Cl0-d4Gu.js +1 -0
- package/dist/assets/chunk-LNGE3PJU-DWpGwHrW.js +34 -0
- package/dist/assets/chunk-OSK3NFVY-fNjfug78.js +10 -0
- package/dist/assets/chunk-OUJLGHUK-D0j2JRSg.js +2 -0
- package/dist/assets/chunk-P2QGCYS3-DsGP3wH9.js +1 -0
- package/dist/assets/chunk-POPQ4Y6H-B7yAy58S.js +1 -0
- package/dist/assets/chunk-PWAF6VOD-DPI_wv9p.js +1 -0
- package/dist/assets/chunk-SHT3W25Y-75CQ5pWa.js +168 -0
- package/dist/assets/chunk-SRAX5OIU-Dhm3gOdh.js +1 -0
- package/dist/assets/chunk-SVP7TREG-CoPu3EjZ.js +88 -0
- package/dist/assets/chunk-TICWLB2K-jXepk-qW.js +206 -0
- package/dist/assets/chunk-TLUHSLCS-C47Epi2D.js +2 -0
- package/dist/assets/chunk-UY3FDG6J-CnmaAkG5.js +1 -0
- package/dist/assets/chunk-XHIXRSVI-BFQ6B8BE.js +1 -0
- package/dist/assets/chunk-XXDRQBXY-CazVBYiP.js +1 -0
- package/dist/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
- package/dist/assets/chunk-Z3N5DIM6-D9TMVU7m.js +1 -0
- package/dist/assets/classDiagram-ZZMXUADV-DLpT76o5.js +1 -0
- package/dist/assets/classDiagram-v2-VYDZK3BY-DLpT76o5.js +1 -0
- package/dist/assets/cose-bilkent-JH36ORCC-DIeJt_L_.js +1 -0
- package/dist/assets/cs-CZ-2BRQDIVT-Bz62EbC5.js +11 -0
- package/dist/assets/cynefin-OW5HDTMX-7tP7QfM3.js +1 -0
- package/dist/assets/cynefinDiagram-5FMLGOSQ-Bwsug0X5.js +62 -0
- package/dist/assets/cytoscape.esm-CGd-uY3x.js +321 -0
- package/dist/assets/da-DK-5WZEPLOC-D55fbhpB.js +5 -0
- package/dist/assets/dagre-GXQ25YYZ-DAaeOVEp.js +4 -0
- package/dist/assets/dagre-PrKaheQc.js +1 -0
- package/dist/assets/de-DE-XR44H4JA-DNaOwkE9.js +8 -0
- package/dist/assets/defaultLocale-BFoDCU3G.js +1 -0
- package/dist/assets/diagram-S7CK7UJ4-BCYFjoge.js +30 -0
- package/dist/assets/diagram-UQ7AKVKN-CC4synlk.js +41 -0
- package/dist/assets/diagram-VSXAHHWV-BR6t4bem.js +3 -0
- package/dist/assets/diagram-VX7I27RA-D-UFFc5T.js +24 -0
- package/dist/assets/diagram-Z3DM3KII-aAOMR4aJ.js +24 -0
- package/dist/assets/directory-open-01563666-D4xXyWb_.js +1 -0
- package/dist/assets/directory-open-4ed118d0-1i309Asm.js +1 -0
- package/dist/assets/dist-Cz2MTljl.js +1 -0
- package/dist/assets/dist-zgyESmtJ.js +29 -0
- package/dist/assets/ebnfDiagram-PWID7BFC-B9wGidHs.js +1 -0
- package/dist/assets/el-GR-BZB4AONW-Chellj6d.js +10 -0
- package/dist/assets/en-B4ZKOASM-BClIFgbE.js +1 -0
- package/dist/assets/erDiagram-RLTQ6QDP-CL7FBspC.js +99 -0
- package/dist/assets/es-ES-U4NZUMDT-D_KzWrdW.js +9 -0
- package/dist/assets/eu-ES-A7QVB2H4-CAoFumRj.js +11 -0
- package/dist/assets/eventmodeling-NTZA5JFV-BR2FzK4R.js +1 -0
- package/dist/assets/fa-IR-HGAKTJCU-ddIdgP13.js +8 -0
- package/dist/assets/fi-FI-Z5N7JZ37-DC3Y34Y8.js +6 -0
- package/dist/assets/file-open-002ab408-BHUWm0Sh.js +1 -0
- package/dist/assets/file-open-7c801643-DZtJT5zp.js +1 -0
- package/dist/assets/file-save-3189631c-CO9S4HFW.js +1 -0
- package/dist/assets/file-save-745eba88-Bwdfz6OZ.js +1 -0
- package/dist/assets/flowDiagram-HODETNUW-BrKzgeF8.js +1 -0
- package/dist/assets/fr-FR-RHASNOE6-BH99frB1.js +9 -0
- package/dist/assets/ganttDiagram-EL5Y4UJY-BKBiwfwb.js +292 -0
- package/dist/assets/gitGraph-4MIJSDKK-DYlXv_yJ.js +1 -0
- package/dist/assets/gitGraphDiagram-WWUBYQGX-D6Gfp0nt.js +106 -0
- package/dist/assets/gl-ES-HMX3MZ6V-4bQs8jWL.js +10 -0
- package/dist/assets/graphlib-DS17s2tU.js +1 -0
- package/dist/assets/he-IL-6SHJWFNN-9Ylp6ncb.js +10 -0
- package/dist/assets/hi-IN-IWLTKZ5I-Dzr4DvnL.js +4 -0
- package/dist/assets/hu-HU-A5ZG7DT2-BBrlHtCw.js +7 -0
- package/dist/assets/icons-DTuc_pxj.js +1 -0
- package/dist/assets/id-ID-SAP4L64H-ZZuXM5fX.js +10 -0
- package/dist/assets/image-GAAHSSAO-CLJY35GR.js +1 -0
- package/dist/assets/image-blob-reduce.esm-Dj7YBvMv.js +2 -0
- package/dist/assets/index-C6iLJpya.js +91 -0
- package/dist/assets/index-DD41XjkN.css +2 -0
- package/dist/assets/info-A6RAGUB7-BlU-8_xu.js +1 -0
- package/dist/assets/infoDiagram-27XIBGKW-BuJx_j6a.js +2 -0
- package/dist/assets/init-C-OQMol4.js +1 -0
- package/dist/assets/ishikawaDiagram-5VMMS53U-Hs60L6ow.js +70 -0
- package/dist/assets/it-IT-JPQ66NNP-D6FUHYuZ.js +11 -0
- package/dist/assets/ja-JP-DBVTYXUO-DSHejo8t.js +8 -0
- package/dist/assets/journeyDiagram-3NMN7TZE-CL9Lqe59.js +139 -0
- package/dist/assets/kaa-6HZHGXH3-0hNa4m6s.js +1 -0
- package/dist/assets/kab-KAB-ZGHBKWFO-BXYUMKRc.js +8 -0
- package/dist/assets/kanban-definition-UXKFOSKX-BqkLgv78.js +89 -0
- package/dist/assets/katex-CXMH3UgJ.js +257 -0
- package/dist/assets/kk-KZ-P5N5QNE5-D52-yIxL.js +1 -0
- package/dist/assets/km-KH-HSX4SM5Z-CaYVKl3D.js +11 -0
- package/dist/assets/ko-KR-MTYHY66A-BdMJRRpv.js +9 -0
- package/dist/assets/ku-TR-6OUDTVRD-Ky7FAdew.js +9 -0
- package/dist/assets/line-DXCbHsGS.js +1 -0
- package/dist/assets/linear-aVQWq3ZZ.js +1 -0
- package/dist/assets/lt-LT-XHIRWOB4-B6H0gZ-C.js +3 -0
- package/dist/assets/lv-LV-5QDEKY6T-BTnV-PCT.js +7 -0
- package/dist/assets/map-BcsP_QXj.css +1 -0
- package/dist/assets/map-BxCwdK0d.js +1 -0
- package/dist/assets/markdown-html-T86c6cqD.css +1 -0
- package/dist/assets/markdown-html-bKd2bDZi.js +12 -0
- package/dist/assets/mermaid-parser.core-CN1hT9Tn.js +4 -0
- package/dist/assets/mindmap-definition-YA3MSWOX-aAz9cEjj.js +96 -0
- package/dist/assets/mr-IN-CRQNXWMA-9iKXC6Ya.js +13 -0
- package/dist/assets/my-MM-5M5IBNSE-BXTnMvRC.js +1 -0
- package/dist/assets/nb-NO-T6EIAALU-BQeWbEx1.js +10 -0
- package/dist/assets/nl-NL-IS3SIHDZ-C4-Hez0V.js +8 -0
- package/dist/assets/nn-NO-6E72VCQL-Dfy734xI.js +8 -0
- package/dist/assets/oc-FR-POXYY2M6-Cn1eE_Zu.js +8 -0
- package/dist/assets/ordinal-BDEzSJ7C.js +1 -0
- package/dist/assets/pa-IN-N4M65BXN-wsiZwueU.js +4 -0
- package/dist/assets/packet-AYTQ26CC-BSJEH9Lb.js +1 -0
- package/dist/assets/path-fybaL0A-.js +1 -0
- package/dist/assets/pdf-Ciz5_WNq.js +54 -0
- package/dist/assets/pdf.worker.min-C8Ts8bNu.js +1 -0
- package/dist/assets/pdf.worker.min-CHFwMXne.mjs +29 -0
- package/dist/assets/pegDiagram-XKGWAZYB-DqjEkpXQ.js +1 -0
- package/dist/assets/percentages-BXMCSKIN-BPGA3zHb.js +1 -0
- package/dist/assets/pica-XznpCgP2.js +2 -0
- package/dist/assets/pie-WAS4IAKB-qxv01Y8W.js +1 -0
- package/dist/assets/pieDiagram-E7YTZNPT-Cs2lygkh.js +39 -0
- package/dist/assets/pl-PL-T2D74RX3-DgfcfsGT.js +9 -0
- package/dist/assets/preload-helper-Czpn1I53.js +1 -0
- package/dist/assets/pt-BR-5N22H2LF-CeODeunU.js +9 -0
- package/dist/assets/pt-PT-UZXXM6DQ-DXzHR8rJ.js +9 -0
- package/dist/assets/punycode.es6-ZbLrB_Dn.js +2 -0
- package/dist/assets/quadrantDiagram-AXDQQJYC-CAXFELe7.js +7 -0
- package/dist/assets/radar-RG4KPBEZ-B6h6pWOs.js +1 -0
- package/dist/assets/railroad-74A4TZTK-CGtTWdGc.js +1 -0
- package/dist/assets/railroad-abnf-HS5TGJTU-Cq7y22IA.js +1 -0
- package/dist/assets/railroad-ebnf-LZEXJU2U-V0aQVv9m.js +1 -0
- package/dist/assets/railroad-peg-WCYAUIDC-BQiIsX_p.js +1 -0
- package/dist/assets/railroadDiagram-O6MQD6OU-Cjw_zMBC.js +1 -0
- package/dist/assets/react-DQazvoR7.js +164 -0
- package/dist/assets/requirementDiagram-BXWQKSXE-S99ev3k7.js +84 -0
- package/dist/assets/ro-RO-JPDTUUEW-BqxNXAVP.js +11 -0
- package/dist/assets/rolldown-runtime-C0FnF6B9.js +1 -0
- package/dist/assets/rough.esm-Dy-Kn_BL.js +1 -0
- package/dist/assets/roundRect-D01gJrlt.js +1 -0
- package/dist/assets/ru-RU-B4JR7IUQ-n637KE87.js +9 -0
- package/dist/assets/sanitize-DrVcFY1Q.js +3 -0
- package/dist/assets/sankeyDiagram-P5KCCOFB-CBdZpflq.js +40 -0
- package/dist/assets/search-COMZIxA7.js +1 -0
- package/dist/assets/sequenceDiagram-WJ2MYXX4-Dyn971wT.js +162 -0
- package/dist/assets/sha256-BoNzwjzt.js +1 -0
- package/dist/assets/si-LK-N5RQ5JYF-ROLYABqx.js +1 -0
- package/dist/assets/sizeCapture-INFHLROL-B0uUizjq.js +1 -0
- package/dist/assets/sk-SK-C5VTKIMK-NlHjiedH.js +6 -0
- package/dist/assets/sl-SI-NN7IZMDC-DFJxhRNE.js +6 -0
- package/dist/assets/socket-hM4c-ZSl.js +1 -0
- package/dist/assets/src-CllyRBe0.js +1 -0
- package/dist/assets/stateDiagram-D77RDMKH-Dsv4fQ8Y.js +1 -0
- package/dist/assets/stateDiagram-v2-MP3YSRHH-UMuzQhZ7.js +1 -0
- package/dist/assets/subset-shared.chunk-CzQ5JF2O.js +1 -0
- package/dist/assets/subset-worker.chunk-D4w07nYk.js +1 -0
- package/dist/assets/sv-SE-XGPEYMSR-CWEjOHYD.js +10 -0
- package/dist/assets/swimlanes-42K2YHIH-f0gJOzIY.js +1 -0
- package/dist/assets/swimlanesDiagram-VR7AAH4N-DACbRCkF.js +8 -0
- package/dist/assets/ta-IN-2NMHFXQM-D1gPGRIR.js +9 -0
- package/dist/assets/text-documents-CcT6N3vu.js +3 -0
- package/dist/assets/th-TH-HPSO5L25-swaKUA2N.js +2 -0
- package/dist/assets/timeline-definition-24CTP7MA-HQ5YMAQc.js +120 -0
- package/dist/assets/tr-TR-DEFEU3FU-Q633YFo2.js +7 -0
- package/dist/assets/treeView-Q6P3EWNA-BTTYcvrF.js +1 -0
- package/dist/assets/treemap-WGGIJYW6-Cg7tyfH8.js +1 -0
- package/dist/assets/ui-CSX-zKZm.js +41 -0
- package/dist/assets/uk-UA-QMV73CPH-BfWne7LV.js +6 -0
- package/dist/assets/use-theme-pnVLU4Kg.js +1 -0
- package/dist/assets/utils-2pl1SbIp.js +1 -0
- package/dist/assets/utils-BxVxyehK.js +1 -0
- package/dist/assets/vennDiagram-4TSXK5OY-P6FI4YvP.js +34 -0
- package/dist/assets/vi-VN-M7AON7JQ-BFEVKFOA.js +5 -0
- package/dist/assets/wardley-WFR3VGLG-C6N1rULY.js +1 -0
- package/dist/assets/wardleyDiagram-VM6X3IG4-XOnMkSi-.js +78 -0
- package/dist/assets/workbox-window.prod.es5-Bd17z0YL.js +2 -0
- package/dist/assets/workspace-Dg_GXg8P.js +1 -0
- package/dist/assets/xychartDiagram-S5SC5T6Z-Cg27DCiq.js +7 -0
- package/dist/assets/zh-CN-LNUGB5OW-N0-P-YPg.js +10 -0
- package/dist/assets/zh-HK-E62DVLB3-dcRoFFJT.js +1 -0
- package/dist/assets/zh-TW-RAJ6MFWO-BTknr43S.js +9 -0
- package/dist/excalidraw/fonts/Assistant/Assistant-Bold.woff2 +0 -0
- package/dist/excalidraw/fonts/Assistant/Assistant-Medium.woff2 +0 -0
- package/dist/excalidraw/fonts/Assistant/Assistant-Regular.woff2 +0 -0
- package/dist/excalidraw/fonts/Assistant/Assistant-SemiBold.woff2 +0 -0
- package/dist/excalidraw/fonts/Cascadia/CascadiaCode-Regular.woff2 +0 -0
- package/dist/excalidraw/fonts/ComicShanns/ComicShanns-Regular-279a7b317d12eb88de06167bd672b4b4.woff2 +0 -0
- package/dist/excalidraw/fonts/ComicShanns/ComicShanns-Regular-6e066e8de2ac57ea9283adb9c24d7f0c.woff2 +0 -0
- package/dist/excalidraw/fonts/ComicShanns/ComicShanns-Regular-dc6a8806fa96795d7b3be5026f989a17.woff2 +0 -0
- package/dist/excalidraw/fonts/ComicShanns/ComicShanns-Regular-fcb0fc02dcbee4c9846b3e2508668039.woff2 +0 -0
- package/dist/excalidraw/fonts/Excalifont/Excalifont-Regular-349fac6ca4700ffec595a7150a0d1e1d.woff2 +0 -0
- package/dist/excalidraw/fonts/Excalifont/Excalifont-Regular-3f2c5db56cc93c5a6873b1361d730c16.woff2 +0 -0
- package/dist/excalidraw/fonts/Excalifont/Excalifont-Regular-41b173a47b57366892116a575a43e2b6.woff2 +0 -0
- package/dist/excalidraw/fonts/Excalifont/Excalifont-Regular-623ccf21b21ef6b3a0d87738f77eb071.woff2 +0 -0
- package/dist/excalidraw/fonts/Excalifont/Excalifont-Regular-a88b72a24fb54c9f94e3b5fdaa7481c9.woff2 +0 -0
- package/dist/excalidraw/fonts/Excalifont/Excalifont-Regular-b9dcf9d2e50a1eaf42fc664b50a3fd0d.woff2 +0 -0
- package/dist/excalidraw/fonts/Excalifont/Excalifont-Regular-be310b9bcd4f1a43f571c46df7809174.woff2 +0 -0
- package/dist/excalidraw/fonts/Liberation/LiberationSans-Regular.woff2 +0 -0
- package/dist/excalidraw/fonts/Lilita/Lilita-Regular-i7dPIFZ9Zz-WBtRtedDbYE98RXi4EwSsbg.woff2 +0 -0
- package/dist/excalidraw/fonts/Lilita/Lilita-Regular-i7dPIFZ9Zz-WBtRtedDbYEF8RXi4EwQ.woff2 +0 -0
- package/dist/excalidraw/fonts/Nunito/Nunito-Regular-XRXI3I6Li01BKofiOc5wtlZ2di8HDIkhdTA3j6zbXWjgevT5.woff2 +0 -0
- package/dist/excalidraw/fonts/Nunito/Nunito-Regular-XRXI3I6Li01BKofiOc5wtlZ2di8HDIkhdTQ3j6zbXWjgeg.woff2 +0 -0
- package/dist/excalidraw/fonts/Nunito/Nunito-Regular-XRXI3I6Li01BKofiOc5wtlZ2di8HDIkhdTk3j6zbXWjgevT5.woff2 +0 -0
- package/dist/excalidraw/fonts/Nunito/Nunito-Regular-XRXI3I6Li01BKofiOc5wtlZ2di8HDIkhdTo3j6zbXWjgevT5.woff2 +0 -0
- package/dist/excalidraw/fonts/Nunito/Nunito-Regular-XRXI3I6Li01BKofiOc5wtlZ2di8HDIkhdTs3j6zbXWjgevT5.woff2 +0 -0
- package/dist/excalidraw/fonts/Virgil/Virgil-Regular.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-019d66dcad46dc156b162d267f981c20.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-04b718e5623574919c8b0dea5f301444.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-069e77aac84590e2e991d0a0176d34f2.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-06c77b8c66e51ed6c63ccb502dd8b8af.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-08e0dc436ad0ad61ba5558db0674d762.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-093b9ef39a46ceae95a1df18a0a3a326.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-095c169f3314805276f603a362766abd.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-09850c4077f3fffe707905872e0e2460.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-0986d134c05864f5025962eef9f994a0.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-0b5d723fdc4e249c140f0909e87d03b4.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-0f626226ba1272e832aea87bafd9720e.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-0f7fb1e0d5015bb1371343153ecf7ce3.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-0fa55a080fcd0f9dc2e0b0058b793df8.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-0facdf1ea213ba40261022f5d5ed4493.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-10a7ae9a371830a80c3d844acf1c02d7.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-112c051027b2d766c19a519f6ee1f4f7.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-11c345711937f0ba4b8f7b6b919c8440.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-12b52b58eb3df36804b9a654ec9ee194.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-13ae07ed2e272d26d59bc0691cd7117a.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-13d2887ec8ee73c43acdabc52a05af7b.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-145aa02cdd91946e67dc934e1acffe75.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-15dc6d811c9cd078f9086a740d5a1038.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-173945821411c09f70c95f98d590e697.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-1b611157cd46bb184d4fa4dae2d6a2b8.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-1e6fd68f1f3902ce48ce8c69df385622.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-1ee544f0f1dac422545c505baa788992.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-1fdc0c67ed57263a80fd108c1f6ccf24.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-203b0e569e3b14aac86a003dc3fa523e.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-20cc1bbf50e7efb442756cb605672c1f.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-20e7bf72fa05de9adf7dbcc7bf51dde6.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-21430ee05a1248901da8d0de08744d47.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-23686f7f29da6e8008c36dd3a80c83d6.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-23ad2d71b280f00b1363b95b7bea94eb.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-23f228f3999c01983860012330e4be08.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-24476a126f129212beb33f66853ea151.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-24a21c1e4449222e8d1898d69ff3a404.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-25b7f38e18f035f96cb5e547bd2bd08c.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-29cec36cd205b211da97acabaa62f055.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-2a26d20a23b00898ce82f09d2ee47c3f.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-2adbc89c11e65905393d3dfc468b9d5b.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-2b7441d46298788ac94e610ffcc709b6.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-2b77e8ebfb2367ab2662396a60e7d320.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-2cf96d082d35ea3d8106851223ad0d16.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-2d43040e86ff03ba677f6f9c04cd0805.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-2e33e8dc771ef5e1d9127d60a6b73679.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-33432927cd87d40cfe393c7482bf221f.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-353f33792a8f60dc69323ddf635a269e.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-36925dfe329a45086cbb7fc5c20d45ac.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-3717077e38f98d89eae729b6c14e56dc.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-3756e81d3e149cf6099163ee79944fec.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-395c35dd584b56b0789f58a0559beaf1.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-3c9de2ae0ea4bc91a510942dfa4be8d2.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-3cc70dbb64df5b21f1326cc24dee2195.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-3e1f8f654357353bf0e04ba5c34b5f7f.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-3e63ed8162808a9e425ed80a8bc79114.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-3eaa538115d76932653c21d8dc28f207.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-4095eb84ef3874e2600247bee0b04026.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-41521fade99856108931b4768b1b2648.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-450da755d5bcb70906e1295e559b9602.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-452225341522a7942f0f6aab1a5c91a3.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-4535823663ad81405188a528d8f2b1a2.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-4806e761d750087c2d734fc64596eaff.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-4a0fdb40036e87b40aa08dd30584cb85.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-4a38cc3e9cf104e69ba246d37f8cf135.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-4aca6a43e59aceee2166b0c7e4e85ef1.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-4bfaa8ffa64c5ee560aa2daba7c9cbd3.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-4dc6d5f188d5c96d44815cd1e81aa885.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-4ddc14ed3eb0c3e46364317dfc0144a3.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-4ee10ae43505e2e0bc62656ced49c0fa.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-4f50e5136e136527280bc902c5817561.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-51502f1206be09c565f1547c406e9558.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-51a0e808bbc8361236ac521a119758a3.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-52a84a22fd1369bffeaf21da2d6158dc.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-5330a2119a716e4e7224ed108b085dac.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-543fa46ace099a7099dad69123399400.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-544fc28abe2c5c30e62383fd4dac255f.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-54acdfc2166ad7fcbd074f75fd4a56ba.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-5572b3513ba8df57a3d5d7303ee6b11b.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-56467a5c8840c4d23a60b2f935114848.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-56a32a7689abd0326e57c10c6c069bb4.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-57862b464a55b18c7bf234ce22907d73.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-583d166e56ba0de4b77eabb47ef67839.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-5882ffa04f32584d26109137e2da4352.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-58fd02350d0bc52cf1ca3bb32ce9766e.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-5935a5775af3d5c6307ac667bd9ae74e.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-59e9ff77b0efaf684bc09274fb6908c9.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-5a1ce3117cfe90c48e8fb4a9a00f694d.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-5a45d991244d4c7140217e1e5f5ca4f4.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-5a7fac4b8b23a6e4e5ba0c9bf1756c91.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-5b0ed6971aaab9c8ad563230bd5471a7.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-5d2898fbc097a7e24c6f38d80587621e.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-603aefd23e350ba7eb124273e3c9bcf1.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-60a3089806700d379f11827ee9843b6b.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-60a41c7e1c68f22424e6d22df544bc82.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-642b26e2e5f5fb780b51b593dbc8c851.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-66493ba5a8367f2928812f446f47b56a.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-670ba603758d94268e8606f240a42e12.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-671a2c20b1eb9e4ef8a192833940e319.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-684d65f1793cac449dde5d59cb3c47fb.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-69c09cc5fa3e55c74fc4821f76909cc3.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-6ae5b42180ad70b971c91e7eefb8eba2.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-6e092f71c1e634059ada0e52abadce67.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-6f3256af8454371776bc46670d33cc65.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-6fe5c5973cc06f74b2387a631ea36b88.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-70c2eb8d64e71a42a834eb857ea9df51.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-70e811fd7994e61f408c923de6ddd078.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-7197d6fda6cba7c3874c53d6381ca239.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-72252d73220fa3cd856677888cee1635.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-72536a3d71b694a0d53dd90ddceae41e.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-726303e0774b4e678bff8c2deb6ca603.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-733171b4ffcd17ea1fe1c0ba627173bf.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-739bc1a567439c7cffcd1614644593d2.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-73e309718fd16cea44b4d54a33581811.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-7494dc504ae00ee9cd0505f990f88c5d.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-74e2263a91439c25b91d5132ce9f4d62.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-761d05e3cd968cf574166867998ef06a.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-7718fe60986d8b42b1be9c5ace5ccf25.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-774d4f764a1299da5d28ec2f2ffe0d69.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-79d494361ae093b69e74ee9dbe65bfd4.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-79f007c1c6d07557120982951ea67998.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-7a07ddc0f0c0f5f4a9bad6ee3dda66b5.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-7ab2bed91166a9dca83a5ebfbe2a7f38.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-7ccce86603f80a099ddb0cb21d4ae3e3.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-7e4bde7e9c7f84cd34d8a845e384c746.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-7e929f262f30c8ee78bf398150b1a7cd.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-7eb9fffd1aa890d07d0f88cc82e6cfe4.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-7f855356ab893b0d2b9c1c83b8116f0e.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-829615148e6357d826b9242eb7fbbd1e.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-866fa7613df6b3fd272bcfd4530c0bb9.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-87599f94b6cc129d505b375798d0d751.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-8c2f33cee3993174f7e87c28e4bf42ee.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-8d3bcabb847b56243b16afe62adaaf21.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-8de5b863cb50dfefdd07cb11c774d579.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-8e9f97f01034820170065b2921b4fb5e.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-8f476c4c99813d57cbe6eca4727388ad.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-903bb6865f3452e2fda42e3a25547bc5.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-91ddb2969bf2d31ba02ad82998d1314c.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-938d90c10ff8c20386af7f242c05d6b0.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-93fc8f28a33234bcadf1527cafabd502.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-95429962233afd82db1c27df1500a28c.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-9544732d2e62d1a429674f8ee41b5d3a.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-9592bfc861f07bcb8d75c196b370e548.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-95bfd249da4902577b4b7d76ebdd0b44.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-968cffdc8ee679da094e77ebf50f58ef.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-97f7f48ce90c9429bf32ae51469db74d.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-982b630266d87db93d2539affb1275c6.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-98f2ad84457de7f3740d9920b8fa8667.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-99a16ef6a64934d5781933dbd9c46b2e.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-9cfb2a77a4e45025105ad29a1748b90d.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-9d81066dd2b337c938df6e90380a00dc.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-9eb5a99df4e76ac3363453ac9ca288b1.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-a004ddfcb26e67bd6e678c8ed19e25ce.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-a0ca5df4258213d7fc9fce80f65ce760.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-a1f916d6039285c4ffb900cd654e418f.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-a203b91dad570bf05a58c3c3ddb529bf.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-a365e82ed54697a52f27adcea1315fe8.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-a4c34be6d42152e64b0df90bc4607f64.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-a7accba310e821da5505f71c03b76bdb.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-aa0d470430e6391eca720c7cfa44446f.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-aa5c9ca6cf4fba00433b7aa3fa10671a.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-ac9ceb44437becc3e9c4dbfebab7fc2d.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-b1220a3c61f85cc0408deedb4c5f57a2.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-b358f7a51ece39a3247942b1feabdb29.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-b57aaedfd8ebdf3931f25119dc6a5eb2.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-b5c1596551c256e0e9cf02028595b092.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-b6d128682ee29e471486354d486a1b90.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-b6fd38ca30869792244804b04bc058da.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-b7d203b051eff504ff59ddca7576b6a9.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-b96d9226ce77ec94ceca043d712182e6.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-ba3de316d63c7e339987b16f41a0b879.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-bafff7a14c27403dcc6cf1432e8ea836.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-bd77e3c7f9e0b072d96af37f73d1aa32.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-be549ab72f0719d606a5c01e2c0219b6.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-c16ed9740b85badf16e86ea782a3062f.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-c1f94158256bb1f3bf665b053d895af9.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-c40533fdf4cc57177b12803598af7e59.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-c4a687ac4f0c2766eefc9f77ed99cddf.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-c69f61a4ab18d0488c8d1fc12e7028e8.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-c8b71798409ccc126ee264a00aadcf21.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-c99eda15fc26a2941579560f76c3a5cf.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-cb17fc3db95f6d139afc9d31a8e93293.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-cbaaefaaf326668277aa24dfa93c4d28.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-cd145ce4a0ea18469358df53c207bc1b.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-cdbce89e82cc1ab53a2decbf5819278f.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-ce4884f96f11589608b76b726a755803.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-cf2cc71752631e579e35b0e423bf2638.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-cf6ff4e0f491ca0cf3038187a997b9b4.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-cfb211578629b7e8153b37240de6a9d5.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-d0cf73942fea1c74edbdf0b3011f4656.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-d2666cbed13462c5dc36fa2f15c202ca.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-d3716376641d615e2995605b29bca7b6.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-dac48066b5883d8b4551fc584f0c2a3e.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-dbea1af6dcd9860be40c3d18254338f5.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-e11567fd2accf9957cd0d3c2be937d87.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-e2ead7ea7da0437f085f42ffc05f8d13.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-e3fcf5180fd466c8915c4e8069491054.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-e480d9c614742d05f0e78f274f1e69e6.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-e4bca6cfa53e499cae0a6be4894a90e9.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-e51ef413167c6e14e0c0fdcc585f2fc9.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-e5f453bb04da18eed01675eeebd88bf8.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-e656f091b9dc4709722c9f4b84d3c797.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-ec181b795ac1fb5a50d700b6e996d745.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-ee8bae97908d5147b423f77ad0d3c1bb.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-f0f13b5c60e0af5553bd359f5513be1b.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-f2b54d4e7be0eaefe1c2c56836fa5368.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-f56414bf9bced67990def8660e306759.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-f5d079153c99a25b9be5b8583c4cc8a7.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-f6032fc06eb20480f096199713f70885.woff2 +0 -0
- package/dist/excalidraw/fonts/Xiaolai/Xiaolai-Regular-f8ee5d36068a42b51d0e4a1116cfcec1.woff2 +0 -0
- package/dist/favicon.png +0 -0
- package/dist/favicon_wl.png +0 -0
- package/dist/images/android-chrome-512x512.png +0 -0
- package/dist/images/apple-touch-icon.png +0 -0
- package/dist/images/avatars/default.png +0 -0
- package/dist/images/favicon.png +0 -0
- package/dist/images/logo-bl_1024x1024.png +0 -0
- package/dist/images/logo-bl_128x128.png +0 -0
- package/dist/images/logo-bl_256x256.png +0 -0
- package/dist/images/logo-bl_512x512.png +0 -0
- package/dist/images/logo-bl_64x64.png +0 -0
- package/dist/images/logo-bl_orig.png +0 -0
- package/dist/images/logo-br_1024x1024.png +0 -0
- package/dist/images/logo-br_128x128.png +0 -0
- package/dist/images/logo-br_256x256.png +0 -0
- package/dist/images/logo-br_512x512.png +0 -0
- package/dist/images/logo-br_64x64.png +0 -0
- package/dist/images/logo-br_orig.png +0 -0
- package/dist/images/logo-wr_1024x1024.png +0 -0
- package/dist/images/logo-wr_128x128.png +0 -0
- package/dist/images/logo-wr_256x256.png +0 -0
- package/dist/images/logo-wr_512x512.png +0 -0
- package/dist/images/logo-wr_64x64.png +0 -0
- package/dist/images/logo-wr_orig.png +0 -0
- package/dist/images/logo_1024x1024.png +0 -0
- package/dist/images/logo_128x128.png +0 -0
- package/dist/images/logo_256x256.png +0 -0
- package/dist/images/logo_512x512.png +0 -0
- package/dist/images/logo_64x64.png +0 -0
- package/dist/images/logo_orig.png +0 -0
- package/dist/index.html +71 -0
- package/dist/js/particles.config.json +110 -0
- package/dist/js/particles.min.js +8 -0
- package/dist/manifest.webmanifest +1 -0
- package/dist/screenshots/s1.png +0 -0
- package/dist/screenshots/s2.png +0 -0
- package/dist/screenshots/s3.png +0 -0
- package/dist/sw.js +1 -0
- package/dist/wallpapers/files/canvas_1.avif +0 -0
- package/dist/wallpapers/files/canvas_1.svg +33 -0
- package/dist/wallpapers/files/canvas_1.webp +0 -0
- package/dist/wallpapers/files/canvas_3.avif +0 -0
- package/dist/wallpapers/files/canvas_3.svg +29 -0
- package/dist/wallpapers/files/canvas_3.webp +0 -0
- package/dist/wallpapers/files/w1.avif +0 -0
- package/dist/wallpapers/files/w1.jpg +0 -0
- package/dist/wallpapers/files/w1.webp +0 -0
- package/dist/wallpapers/thumbs/canvas_1.webp +0 -0
- package/dist/wallpapers/thumbs/canvas_3.webp +0 -0
- package/dist/wallpapers/thumbs/w1.webp +0 -0
- package/package.json +14 -4
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pdf-Ciz5_WNq.js","assets/preload-helper-Czpn1I53.js","assets/markdown-html-bKd2bDZi.js","assets/rolldown-runtime-C0FnF6B9.js","assets/react-DQazvoR7.js","assets/sanitize-DrVcFY1Q.js","assets/punycode.es6-ZbLrB_Dn.js","assets/markdown-html-T86c6cqD.css","assets/SketchEditor-vg1HMZ0V.js","assets/ui-CSX-zKZm.js","assets/utils-BxVxyehK.js","assets/workspace-Dg_GXg8P.js","assets/utils-2pl1SbIp.js","assets/blobs-DsQ7VyoY.js","assets/sha256-BoNzwjzt.js","assets/chunk-K2UTITRG-D0fgw4vC.js","assets/chunk-SRAX5OIU-Dhm3gOdh.js","assets/chunk-6U3AYISY-C6-Mtja1.js","assets/chunk-Z3N5DIM6-D9TMVU7m.js","assets/EditorOverlay-CftUh9OI.js","assets/SketchEditor-DtRVLazd.css","assets/TextDocumentEditor-B6bUq9US.js","assets/text-documents-CcT6N3vu.js","assets/LocationTab-ARqmeXmv.js","assets/map-BxCwdK0d.js","assets/map-BcsP_QXj.css","assets/NextShell-CIyIaK3b.js","assets/NextShell-B4NeoNB5.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{a as e,n as t,o as n,r,t as i}from"./rolldown-runtime-C0FnF6B9.js";import{Ct as a,St as o,_t as s,bt as c,st as l,vt as u,wt as d,xt as f,yt as p}from"./react-DQazvoR7.js";import{t as m}from"./preload-helper-Czpn1I53.js";import{$ as h,$n as g,$r as _,$t as v,An as y,Ar as b,At as x,B as S,Bn as C,Br as w,Bt as T,C as E,Cn as D,Cr as O,Ct as k,Dn as A,Dr as j,Dt as M,En as N,Er as P,Et as ee,F,Fr as I,Ft as te,G as ne,Gn as L,Gr as re,Gt as R,H as ie,Hn as ae,Hr as oe,Ht as z,I as se,In as ce,Ir as B,It as V,J as le,Jn as ue,Jr as de,Jt as fe,K as pe,Kn as me,Kr as H,Kt as he,L as ge,Ln as _e,Lr as ve,Lt as ye,Mn as U,Mr as be,Mt as xe,Nn as Se,Nr as Ce,Nt as W,On as G,Or as we,Ot as Te,Pr as Ee,Pt as De,Q as Oe,Qn as ke,Qt as Ae,R as je,Rn as Me,Rr as Ne,Rt as Pe,S as Fe,Sn as Ie,Sr as Le,St as Re,T as ze,Tn as Be,Tr as Ve,Tt as He,U as Ue,Un as We,Ur as Ge,Ut as Ke,V as qe,Vn as Je,Vr as Ye,Vt as Xe,W as Ze,Wn as Qe,Wr as $e,Wt as et,X as tt,Xn as nt,Xr as rt,Xt as it,Y as at,Yn as ot,Yr as st,Yt as ct,Z as lt,Zn as ut,Zr as dt,Zt as ft,_ as pt,_n as mt,_r as ht,_t as gt,ai as _t,an as vt,ar as yt,at as bt,b as xt,bn as St,br as Ct,bt as wt,ci as Tt,cn as Et,cr as Dt,ct as Ot,d as kt,di as At,dr as jt,dt as Mt,ei as Nt,en as Pt,er as Ft,et as It,f as Lt,fi as Rt,fn as zt,fr as Bt,ft as Vt,g as Ht,gn as Ut,gr as Wt,gt as Gt,h as Kt,hn as qt,hr as Jt,ht as Yt,ii as Xt,in as Zt,ir as Qt,it as $t,jn as en,jr as tn,jt as nn,kn as rn,kr as an,kt as on,li as sn,ln as cn,lr as ln,lt as un,m as dn,mn as fn,mr as pn,mt as mn,ni as hn,nn as gn,nr as _n,nt as vn,oi as yn,on as bn,or as xn,ot as Sn,p as Cn,pr as wn,pt as Tn,q as En,qn as Dn,qr as On,qt as kn,ri as An,rn as jn,rr as Mn,rt as Nn,si as Pn,sn as Fn,sr as In,st as Ln,ti as Rn,tn as zn,tr as Bn,tt as Vn,u as Hn,ui as Un,un as Wn,ur as Gn,ut as Kn,v as qn,vn as Jn,vr as Yn,vt as Xn,w as Zn,wr as Qn,wt as $n,x as er,xn as tr,xr as nr,xt as rr,y as ir,yn as ar,yr as or,yt as sr,z as cr,zn as lr,zr as ur,zt as dr}from"./ui-CSX-zKZm.js";import{i as fr,n as pr,r as mr}from"./utils-BxVxyehK.js";import{n as hr,t as K}from"./utils-2pl1SbIp.js";import{$ as gr,$t as _r,A as vr,An as yr,At as br,B as xr,Bt as Sr,C as Cr,Cn as wr,Ct as Tr,D as Er,Dn as Dr,Dt as Or,E as kr,En as Ar,Et as jr,F as Mr,Fn as q,Ft as Nr,G as Pr,H as Fr,Ht as Ir,I as Lr,In as J,It as Rr,J as zr,Jt as Br,K as Vr,Kt as Hr,L as Ur,Lt as Wr,M as Gr,Mn as Kr,Mt as qr,N as Jr,Nn as Yr,Nt as Xr,O as Zr,On as Qr,Ot as $r,P as ei,Pn as ti,Pt as ni,Q as ri,Qt as ii,R as ai,Rt as oi,S as si,Sn as ci,St as li,T as ui,Tn as Y,Tt as di,U as fi,Ut as pi,V as mi,Vt as hi,W as gi,Wt as _i,X as vi,Xt as yi,Y as bi,Yt as xi,Z as Si,Zt as Ci,_ as wi,_n as Ti,_t as Ei,a as Di,an as Oi,at as ki,b as Ai,bn as ji,bt as Mi,c as Ni,cn as Pi,ct as Fi,d as Ii,dn as Li,dt as Ri,en as zi,et as Bi,f as Vi,fn as Hi,ft as Ui,g as Wi,gn as Gi,gt as Ki,h as qi,hn as Ji,ht as Yi,i as Xi,in as Zi,it as Qi,jn as $i,jt as ea,k as ta,kn as na,kt as ra,l as ia,ln as aa,lt as oa,m as sa,mn as ca,mt as la,n as ua,nn as da,nt as fa,o as pa,on as ma,ot as ha,p as ga,pn as _a,pt as va,q as ya,qt as ba,r as xa,rn as Sa,rt as Ca,s as wa,sn as Ta,st as Ea,t as Da,tn as Oa,tt as ka,u as Aa,un as ja,ut as Ma,v as Na,vn as Pa,vt as Fa,w as Ia,wn as La,wt as Ra,x as za,xn as Ba,xt as Va,y as Ha,yn as Ua,yt as Wa,z as Ga,zt as Ka}from"./workspace-Dg_GXg8P.js";import{t as qa}from"./socket-hM4c-ZSl.js";import{_ as Ja,a as Ya,d as Xa,g as Za,h as Qa,i as $a,l as eo,m as to,n as no,o as ro,p as io,t as ao,v as oo}from"./blobs-DsQ7VyoY.js";import{_ as so,a as co,c as lo,d as uo,f as fo,g as po,h as mo,i as ho,l as go,m as _o,n as vo,o as yo,p as bo,r as xo,s as So,t as Co,u as wo,v as To}from"./text-documents-CcT6N3vu.js";import{n as Eo,t as Do}from"./map-BxCwdK0d.js";import{t as Oo}from"./search-COMZIxA7.js";import{A as ko,B as Ao,C as jo,D as Mo,E as No,F as Po,H as Fo,I as Io,L as Lo,M as Ro,N as zo,O as Bo,P as Vo,R as Ho,S as Uo,T as Wo,V as Go,_ as Ko,a as qo,b as Jo,c as Yo,d as Xo,f as Zo,g as Qo,h as $o,i as es,j as ts,k as ns,l as rs,m as is,o as as,p as os,r as ss,s as cs,t as ls,u as us,v as ds,w as fs,x as ps,y as ms,z as hs}from"./sha256-BoNzwjzt.js";import{t as gs}from"./sanitize-DrVcFY1Q.js";import{n as _s,t as vs}from"./use-theme-pnVLU4Kg.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var X=n(d(),1),ys=o(),bs=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,xs=/^[\\/]{2}/;function Ss(e,t){return t+e.replace(/\\/g,`/`)}var Cs=(e=>(e.Pop=`POP`,e.Push=`PUSH`,e.Replace=`REPLACE`,e))(Cs||{}),ws=`popstate`;function Ts(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function Es(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return js(``,{pathname:r,search:i,hash:a},t.state&&t.state.usr||null,t.state&&t.state.key||`default`,n?{pathname:e.location.pathname,search:e.location.search,hash:e.location.hash}:void 0)}function n(e,t){return typeof t==`string`?t:Ms(t)}return Ps(t,n,null,e)}function Ds(e,t){if(e===!1||e==null)throw Error(t)}function Os(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function ks(){return Math.random().toString(36).substring(2,10)}function As(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function js(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?Ns(t):t,state:n,key:t&&t.key||r||ks(),mask:i}}function Ms({pathname:e=`/`,search:t=``,hash:n=``}){return t&&t!==`?`&&(e+=t.charAt(0)===`?`?t:`?`+t),n&&n!==`#`&&(e+=n.charAt(0)===`#`?n:`#`+n),e}function Ns(e){let t={};if(e){let n=e.indexOf(`#`);n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf(`?`);r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function Ps(e,t,n,r={}){let{window:i=document.defaultView,v5Compat:a=!1}=r,o=i.history,s=`POP`,c=null,l=u();l??(l=0,o.replaceState({...o.state,idx:l},``));function u(){return(o.state||{idx:null}).idx}function d(){s=`POP`;let e=u(),t=e==null?null:e-l;l=e,c&&c({action:s,location:h.location,delta:t})}function f(e,t){s=`PUSH`;let r=Ts(e)?e:js(h.location,e,t);n&&n(r,e),l=u()+1;let d=As(r,l),f=h.createHref(r.mask||r);try{o.pushState(d,``,f)}catch(e){if(e instanceof DOMException&&e.name===`DataCloneError`)throw e;i.location.assign(f)}a&&c&&c({action:s,location:h.location,delta:1})}function p(e,t){s=`REPLACE`;let r=Ts(e)?e:js(h.location,e,t);n&&n(r,e),l=u();let i=As(r,l),d=h.createHref(r.mask||r);o.replaceState(i,``,d),a&&c&&c({action:s,location:h.location,delta:0})}function m(e){return Fs(i,e)}let h={get action(){return s},get location(){return e(i,o)},listen(e){if(c)throw Error(`A history only accepts one active listener`);return i.addEventListener(ws,d),c=e,()=>{i.removeEventListener(ws,d),c=null}},createHref(e){return t(i,e)},createURL:m,encodeLocation(e){let t=m(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:f,replace:p,go(e){return o.go(e)}};return h}function Fs(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),Ds(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:Ms(t);return i=i.replace(/ $/,`%20`),!n&&xs.test(i)&&(i=r+i),new URL(i,r)}function Is(e,t,n=`/`){return Ls(e,t,n,!1)}function Ls(e,t,n,r,i){let a=nc((typeof t==`string`?Ns(t):t).pathname||`/`,n);if(a==null)return null;let o=i??Rs(e),s=null,c=tc(a);for(let e=0;s==null&&e<o.length;++e)s=Zs(o[e],c,r);return s}function Rs(e){let t=zs(e);return Vs(t),t}function zs(e,t=[],n=[],r=``,i=!1){let a=(e,a,o=i,s)=>{let c={relativePath:s===void 0?e.path||``:s,caseSensitive:e.caseSensitive===!0,childrenIndex:a,route:e};if(c.relativePath.startsWith(`/`)){if(!c.relativePath.startsWith(r)&&o)return;Ds(c.relativePath.startsWith(r),`Absolute route path "${c.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),c.relativePath=c.relativePath.slice(r.length)}let l=uc([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(Ds(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),zs(e.children,t,u,l,o)),!(e.path==null&&!e.index)&&t.push({path:l,score:Ys(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=ec(e.relativePath,e.caseSensitive,t===u.length-1);return{...e,matcher:n,compiledParams:r}})})};return e.forEach((e,t)=>{if(e.path===``||!e.path?.includes(`?`))a(e,t);else for(let n of Bs(e.path))a(e,t,!0,n)}),t}function Bs(e){let t=e.split(`/`);if(t.length===0)return[];let[n,...r]=t,i=n.endsWith(`?`),a=n.replace(/\?$/,``);if(r.length===0)return i?[a,``]:[a];let o=Bs(r.join(`/`)),s=[];return s.push(...o.map(e=>e===``?a:[a,e].join(`/`))),i&&s.push(...o),s.map(t=>e.startsWith(`/`)&&t===``?`/`:t)}function Vs(e){e.sort((e,t)=>e.score===t.score?Xs(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var Hs=/^:[\w-]+$/,Us=3,Ws=2,Gs=1,Ks=10,qs=-2,Js=e=>e===`*`;function Ys(e,t){let n=e.split(`/`),r=n.length;return n.some(Js)&&(r+=qs),t&&(r+=Ws),n.filter(e=>!Js(e)).reduce((e,t)=>e+(Hs.test(t)?Us:t===``?Gs:Ks),r)}function Xs(e,t){return e.length===t.length&&e.slice(0,-1).every((e,n)=>e===t[n])?e[e.length-1]-t[t.length-1]:0}function Zs(e,t,n=!1){let{routesMeta:r}=e,i={},a=`/`,o=[];for(let e=0;e<r.length;++e){let s=r[e],c=e===r.length-1,l=a===`/`?t:t.slice(a.length)||`/`,u={path:s.relativePath,caseSensitive:s.caseSensitive,end:c},d=s.matcher&&s.compiledParams?$s(u,l,s.matcher,s.compiledParams):Qs(u,l),f=s.route;if(!d&&c&&n&&!r[r.length-1].route.index&&(d=Qs({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},l)),!d)return null;Object.assign(i,d.params),o.push({params:i,pathname:uc([a,d.pathname]),pathnameBase:fc(uc([a,d.pathnameBase])),route:f}),d.pathnameBase!==`/`&&(a=uc([a,d.pathnameBase]))}return o}function Qs(e,t){typeof e==`string`&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=ec(e.path,e.caseSensitive,e.end);return $s(e,t,n,r)}function $s(e,t,n,r){let i=t.match(n);if(!i)return null;let a=i[0],o=a.replace(/(.)\/+$/,`$1`),s=i.slice(1);return{params:r.reduce((e,{paramName:t,isOptional:n},r)=>{if(t===`*`){let e=s[r]||``;o=a.slice(0,a.length-e.length).replace(/(.)\/+$/,`$1`)}let i=s[r];return e[t]=n&&!i?void 0:(i||``).replace(/%2F/g,`/`),e},{}),pathname:a,pathnameBase:o,pattern:e}}function ec(e,t=!1,n=!0){Os(e===`*`||!e.endsWith(`*`)||e.endsWith(`/*`),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,`/*`)}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,`/*`)}".`);let r=[],i=`^`+e.replace(/\/*\*?$/,``).replace(/^\/*/,`/`).replace(/[\\.*+^${}|()[\]]/g,`\\$&`).replace(/\/:([\w-]+)(\?)?/g,(e,t,n,i,a)=>{if(r.push({paramName:t,isOptional:n!=null}),n){let t=a.charAt(i+e.length);return t&&t!==`/`?`/([^\\/]*)`:`(?:/([^\\/]*))?`}return`/([^\\/]+)`}).replace(/\/([\w-]+)\?(\/|$)/g,`(/$1)?$2`);return e.endsWith(`*`)?(r.push({paramName:`*`}),i+=e===`*`||e===`/*`?`(.*)$`:`(?:\\/(.+)|\\/*)$`):n?i+=`\\/*$`:e!==``&&e!==`/`&&(i+=`(?:(?=\\/|$))`),[new RegExp(i,t?void 0:`i`),r]}function tc(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return Os(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function nc(e,t){if(t===`/`)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith(`/`)?t.length-1:t.length,r=e.charAt(n);return r&&r!==`/`?null:e.slice(n)||`/`}function rc(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?Ns(e):e,a;return n?(n=lc(n),a=n.startsWith(`/`)?ic(n.substring(1),`/`):ic(n,t)):a=t,{pathname:a,search:pc(r),hash:mc(i)}}function ic(e,t){let n=dc(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function ac(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function oc(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function sc(e){let t=oc(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function cc(e,t,n,r=!1){let i;typeof e==`string`?i=Ns(e):(i={...e},Ds(!i.pathname||!i.pathname.includes(`?`),ac(`?`,`pathname`,`search`,i)),Ds(!i.pathname||!i.pathname.includes(`#`),ac(`#`,`pathname`,`hash`,i)),Ds(!i.search||!i.search.includes(`#`),ac(`#`,`search`,`hash`,i)));let a=e===``||i.pathname===``,o=a?`/`:i.pathname,s;if(o==null)s=n;else{let e=t.length-1;if(!r&&o.startsWith(`..`)){let t=o.split(`/`);for(;t[0]===`..`;)t.shift(),--e;i.pathname=t.join(`/`)}s=e>=0?t[e]:`/`}let c=rc(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var lc=e=>e.replace(/[\\/]{2,}/g,`/`),uc=e=>lc(e.join(`/`)),dc=e=>e.replace(/\/+$/,``),fc=e=>dc(e).replace(/^\/*/,`/`),pc=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,mc=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,hc=class{constructor(e,t,n,r=!1){this.status=e,this.statusText=t||``,this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function gc(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function _c(e){return uc(e.map(e=>e.route.path).filter(Boolean))||`/`}var vc=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function yc(e,t){let n=e;if(typeof n!=`string`||!bs.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(vc)try{let e=new URL(window.location.href),r=xs.test(n)?new URL(Ss(n,e.protocol)):new URL(n),a=nc(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{Os(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:i,to:n}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);var bc=[`POST`,`PUT`,`PATCH`,`DELETE`];new Set(bc);var xc=[`GET`,...bc];new Set(xc);var Sc=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function Cc(e){try{return Sc.includes(new URL(e).protocol)}catch{return!1}}var wc=X.createContext(null);wc.displayName=`DataRouter`;var Tc=X.createContext(null);Tc.displayName=`DataRouterState`;var Ec=X.createContext(!1);function Dc(){return X.useContext(Ec)}var Oc=X.createContext({isTransitioning:!1});Oc.displayName=`ViewTransition`;var kc=X.createContext(new Map);kc.displayName=`Fetchers`;var Ac=X.createContext(null);Ac.displayName=`Await`;var jc=X.createContext(null);jc.displayName=`Navigation`;var Mc=X.createContext(null);Mc.displayName=`Location`;var Nc=X.createContext({outlet:null,matches:[],isDataRoute:!1});Nc.displayName=`Route`;var Pc=X.createContext(null);Pc.displayName=`RouteError`;var Fc=`REACT_ROUTER_ERROR`,Ic=`REDIRECT`,Lc=`ROUTE_ERROR_RESPONSE`;function Rc(e){if(e.startsWith(`${Fc}:${Ic}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`&&typeof t.location==`string`&&typeof t.reloadDocument==`boolean`&&typeof t.replace==`boolean`)return t}catch{}}function zc(e){if(e.startsWith(`${Fc}:${Lc}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new hc(t.status,t.statusText,t.data)}catch{}}function Bc(e,{relative:t}={}){Ds(Vc(),`useHref() may be used only in the context of a <Router> component.`);let{basename:n,navigator:r}=X.useContext(jc),{hash:i,pathname:a,search:o}=Xc(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:uc([n,a])),r.createHref({pathname:s,search:o,hash:i})}function Vc(){return X.useContext(Mc)!=null}function Hc(){return Ds(Vc(),`useLocation() may be used only in the context of a <Router> component.`),X.useContext(Mc).location}var Uc=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function Wc(e){X.useContext(jc).static||X.useLayoutEffect(e)}function Gc(){let{isDataRoute:e}=X.useContext(Nc);return e?pl():Kc()}function Kc(){Ds(Vc(),`useNavigate() may be used only in the context of a <Router> component.`);let e=X.useContext(wc),{basename:t,navigator:n}=X.useContext(jc),{matches:r}=X.useContext(Nc),{pathname:i}=Hc(),a=JSON.stringify(sc(r)),o=X.useRef(!1);return Wc(()=>{o.current=!0}),X.useCallback((r,s={})=>{if(Os(o.current,Uc),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=cc(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:uc([t,c.pathname])),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}var qc=X.createContext(null);function Jc(e){let t=X.useContext(Nc).outlet;return X.useMemo(()=>t&&X.createElement(qc.Provider,{value:e},t),[t,e])}function Yc(){let{matches:e}=X.useContext(Nc);return e[e.length-1]?.params??{}}function Xc(e,{relative:t}={}){let{matches:n}=X.useContext(Nc),{pathname:r}=Hc(),i=JSON.stringify(sc(n));return X.useMemo(()=>cc(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function Zc(e,t){return Qc(e,t)}function Qc(e,t,n){Ds(Vc(),`useRoutes() may be used only in the context of a <Router> component.`);let{navigator:r}=X.useContext(jc),{matches:i}=X.useContext(Nc),a=i[i.length-1],o=a?a.params:{},s=a?a.pathname:`/`,c=a?a.pathnameBase:`/`,l=a&&a.route;{let e=l&&l.path||``;hl(s,!l||e.endsWith(`*`)||e.endsWith(`*?`),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${s}" (under <Route path="${e}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
|
|
3
|
+
|
|
4
|
+
Please change the parent <Route path="${e}"> to <Route path="${e===`/`?`*`:`${e}/*`}">.`)}let u=Hc(),d;if(t){let e=typeof t==`string`?Ns(t):t;Ds(c===`/`||e.pathname?.startsWith(c),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${c}" but pathname "${e.pathname}" was given in the \`location\` prop.`),d=e}else d=u;let f=d.pathname||`/`,p=f;if(c!==`/`){let e=c.replace(/^\//,``).split(`/`);p=`/`+f.replace(/^\//,``).split(`/`).slice(e.length).join(`/`)}let m=n&&n.state.matches.length?n.state.matches.map(e=>Object.assign(e,{route:n.manifest[e.route.id]||e.route})):Is(e,{pathname:p});Os(l||m!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),Os(m==null||m[m.length-1].route.element!==void 0||m[m.length-1].route.Component!==void 0||m[m.length-1].route.lazy!==void 0,`Matched leaf route at location "${d.pathname}${d.search}${d.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let h=al(m&&m.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:uc([c,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?c:uc([c,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&h?X.createElement(Mc.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...d},navigationType:`POP`}},h):h}function $c(){let e=fl(),t=gc(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r=`rgba(200,200,200, 0.5)`,i={padding:`0.5rem`,backgroundColor:r},a={padding:`2px 4px`,backgroundColor:r},o=null;return console.error(`Error handled by React Router default ErrorBoundary:`,e),o=X.createElement(X.Fragment,null,X.createElement(`p`,null,`💿 Hey developer 👋`),X.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,X.createElement(`code`,{style:a},`ErrorBoundary`),` or`,` `,X.createElement(`code`,{style:a},`errorElement`),` prop on your route.`)),X.createElement(X.Fragment,null,X.createElement(`h2`,null,`Unexpected Application Error!`),X.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?X.createElement(`pre`,{style:i},n):null,o)}var el=X.createElement($c,null),tl=class extends X.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=zc(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:X.createElement(Nc.Provider,{value:this.props.routeContext},X.createElement(Pc.Provider,{value:e,children:this.props.component}));return this.context?X.createElement(rl,{error:e},t):t}};tl.contextType=Ec;var nl=new WeakMap;function rl({children:e,error:t}){let{basename:n}=X.useContext(jc);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=Rc(t.digest);if(e){let r=nl.get(t);if(r)throw r;let i=yc(e.location,n),a=i.absoluteURL||i.to;if(Cc(a))throw Error(`Invalid redirect location`);if(vc&&!nl.get(t)){if(i.isExternal||e.reloadDocument)window.location.href=a;else{let n=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(i.to,{replace:e.replace}));throw nl.set(t,n),n}}return X.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${a}`})}}return e}function il({routeContext:e,match:t,children:n}){let r=X.useContext(wc);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),X.createElement(Nc.Provider,{value:e},n)}function al(e,t=[],n){let r=n?.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let i=e,a=r?.errors;if(a!=null){let e=i.findIndex(e=>e.route.id&&a?.[e.route.id]!==void 0);Ds(e>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(`,`)}`),i=i.slice(0,Math.min(i.length,e+1))}let o=!1,s=-1;if(n&&r){o=r.renderFallback;for(let e=0;e<i.length;e++){let t=i[e];if((t.route.HydrateFallback||t.route.hydrateFallbackElement)&&(s=e),t.route.id){let{loaderData:e,errors:a}=r,c=t.route.loader&&!e.hasOwnProperty(t.route.id)&&(!a||a[t.route.id]===void 0);if(t.route.lazy||c){n.isStatic&&(o=!0),i=s>=0?i.slice(0,s+1):[i[0]];break}}}}let c=n?.onError,l=r&&c?(e,t)=>{c(e,{location:r.location,params:r.matches?.[0]?.params??{},pattern:_c(r.matches),errorInfo:t})}:void 0;return i.reduceRight((e,n,c)=>{let u,d=!1,f=null,p=null;r&&(u=a&&n.route.id?a[n.route.id]:void 0,f=n.route.errorElement||el,o&&(s<0&&c===0?(hl(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?X.createElement(n.route.Component,null):n.route.element?n.route.element:e,X.createElement(il,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?X.createElement(tl,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function ol(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function sl(e){let t=X.useContext(wc);return Ds(t,ol(e)),t}function cl(e){let t=X.useContext(Tc);return Ds(t,ol(e)),t}function ll(e){let t=X.useContext(Nc);return Ds(t,ol(e)),t}function ul(e){let t=ll(e),n=t.matches[t.matches.length-1];return Ds(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function dl(){return ul(`useRouteId`)}function fl(){let e=X.useContext(Pc),t=cl(`useRouteError`),n=ul(`useRouteError`);return e===void 0?t.errors?.[n]:e}function pl(){let{router:e}=sl(`useNavigate`),t=ul(`useNavigate`),n=X.useRef(!1);return Wc(()=>{n.current=!0}),X.useCallback(async(r,i={})=>{Os(n.current,Uc),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var ml={};function hl(e,t,n){!t&&!ml[e]&&(ml[e]=!0,Os(!1,n))}X.memo(gl);function gl({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return Qc(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function _l({to:e,replace:t,state:n,relative:r}){Ds(Vc(),`<Navigate> may be used only in the context of a <Router> component.`);let{static:i}=X.useContext(jc);Os(!i,`<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`);let{matches:a}=X.useContext(Nc),{pathname:o}=Hc(),s=Gc(),c=cc(e,sc(a),o,r===`path`),l=JSON.stringify(c);return X.useEffect(()=>{s(JSON.parse(l),{replace:t,state:n,relative:r})},[s,l,r,t,n]),null}function vl(e){return Jc(e.context)}function yl(e){Ds(!1,`A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.`)}function bl({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){Ds(!Vc(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=X.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=Ns(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=X.useMemo(()=>{let e=nc(l,s);return e==null?null:{location:{pathname:e,search:u,hash:d,state:f,key:p,mask:m},navigationType:r}},[s,l,u,d,f,p,r,m]);return Os(h!=null,`<Router basename="${s}"> is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the <Router> won't render anything.`),h==null?null:X.createElement(jc.Provider,{value:c},X.createElement(Mc.Provider,{children:t,value:h}))}function xl({children:e,location:t}){return Zc(Sl(e),t)}X.Component;function Sl(e,t=[]){let n=[];return X.Children.forEach(e,(e,r)=>{if(!X.isValidElement(e))return;let i=[...t,r];if(e.type===X.Fragment){n.push.apply(n,Sl(e.props.children,i));return}Ds(e.type===yl,`[${typeof e.type==`string`?e.type:e.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),Ds(!e.props.index||!e.props.children,`An index route cannot have child routes.`);let a={id:e.props.id||i.join(`-`),caseSensitive:e.props.caseSensitive,element:e.props.element,Component:e.props.Component,index:e.props.index,path:e.props.path,middleware:e.props.middleware,loader:e.props.loader,action:e.props.action,hydrateFallbackElement:e.props.hydrateFallbackElement,HydrateFallback:e.props.HydrateFallback,errorElement:e.props.errorElement,ErrorBoundary:e.props.ErrorBoundary,hasErrorBoundary:e.props.hasErrorBoundary===!0||e.props.ErrorBoundary!=null||e.props.errorElement!=null,shouldRevalidate:e.props.shouldRevalidate,handle:e.props.handle,lazy:e.props.lazy};e.props.children&&(a.children=Sl(e.props.children,i)),n.push(a)}),n}var Cl=`get`,wl=`application/x-www-form-urlencoded`;function Tl(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function El(e){return Tl(e)&&e.tagName.toLowerCase()===`button`}function Dl(e){return Tl(e)&&e.tagName.toLowerCase()===`form`}function Ol(e){return Tl(e)&&e.tagName.toLowerCase()===`input`}function kl(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Al(e,t){return e.button===0&&(!t||t===`_self`)&&!kl(e)}function jl(e=``){return new URLSearchParams(typeof e==`string`||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}function Ml(e,t){let n=jl(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var Nl=null;function Pl(){if(Nl===null)try{new FormData(document.createElement(`form`),0),Nl=!1}catch{Nl=!0}return Nl}var Fl=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function Il(e){return e!=null&&!Fl.has(e)?(Os(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${wl}"`),null):e}function Ll(e,t){let n,r,i,a,o;if(Dl(e)){let o=e.getAttribute(`action`);r=o?nc(o,t):null,n=e.getAttribute(`method`)||Cl,i=Il(e.getAttribute(`enctype`))||wl,a=new FormData(e)}else if(El(e)||Ol(e)&&(e.type===`submit`||e.type===`image`)){let o=e.form;if(o==null)throw Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);let s=e.getAttribute(`formaction`)||o.getAttribute(`action`);if(r=s?nc(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||Cl,i=Il(e.getAttribute(`formenctype`))||Il(o.getAttribute(`enctype`))||wl,a=new FormData(o,e),!Pl()){let{name:t,type:n,value:r}=e;if(n===`image`){let e=t?`${t}.`:``;a.append(`${e}x`,`0`),a.append(`${e}y`,`0`)}else t&&a.append(t,r)}}else if(Tl(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=Cl,r=null,i=wl,o=e;return a&&i===`text/plain`&&(o=a,a=void 0),{action:r,method:n.toLowerCase(),encType:i,formData:a,body:o}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);function Rl(e,t){if(e===!1||e==null)throw Error(t)}function zl(e,t,n,r){let i=typeof e==`string`?new URL(e,typeof window>`u`?`server://singlefetch/`:window.location.origin):e;return i.pathname=n?i.pathname.endsWith(`/`)?`${i.pathname}_.${r}`:`${i.pathname}.${r}`:i.pathname===`/`?`_root.${r}`:t&&nc(i.pathname,t)===`/`?`${dc(t)}/_root.${r}`:`${dc(i.pathname)}.${r}`,i}async function Bl(e,t){if(e.id in t)return t[e.id];try{let n=await m(()=>import(e.module),[]);return t[e.id]=n,n}catch(t){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function Vl(e){return e!=null&&typeof e.page==`string`}function Hl(e){return e==null?!1:e.href==null?e.rel===`preload`&&typeof e.imageSrcSet==`string`&&typeof e.imageSizes==`string`:typeof e.rel==`string`&&typeof e.href==`string`}async function Ul(e,t,n){return Jl((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await Bl(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(Hl).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function Wl(e,t,n,r,i,a){let o=(e,t)=>!n[t]||e.route.id!==n[t].route.id,s=(e,t)=>n[t].pathname!==e.pathname||n[t].route.path?.endsWith(`*`)&&n[t].params[`*`]!==e.params[`*`];return a===`assets`?t.filter((e,t)=>o(e,t)||s(e,t)):a===`data`?t.filter((t,a)=>{let c=r.routes[t.route.id];if(!c||!c.hasLoader)return!1;if(o(t,a)||s(t,a))return!0;if(t.route.shouldRevalidate){let r=t.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(e,window.origin),nextParams:t.params,defaultShouldRevalidate:!0});if(typeof r==`boolean`)return r}return!0}):[]}function Gl(e,t,{includeHydrateFallback:n}={}){return Kl(e.map(e=>{let r=t.routes[e.route.id];if(!r)return[];let i=[r.module];return r.clientActionModule&&(i=i.concat(r.clientActionModule)),r.clientLoaderModule&&(i=i.concat(r.clientLoaderModule)),n&&r.hydrateFallbackModule&&(i=i.concat(r.hydrateFallbackModule)),r.imports&&(i=i.concat(r.imports)),i}).flat(1))}function Kl(e){return[...new Set(e)]}function ql(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function Jl(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!Vl(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(ql(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function Yl(){let e=X.useContext(wc);return Rl(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function Xl(){let e=X.useContext(Tc);return Rl(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var Zl=X.createContext(void 0);Zl.displayName=`FrameworkContext`;function Ql(){let e=X.useContext(Zl);return Rl(e,`You must render this element inside a <HydratedRouter> element`),e}function $l(e,t){let n=X.useContext(Zl),[r,i]=X.useState(!1),[a,o]=X.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=X.useRef(null);X.useEffect(()=>{if(e===`render`&&o(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{o(e.isIntersecting)})},{threshold:.5});return f.current&&e.observe(f.current),()=>{e.disconnect()}}},[e]),X.useEffect(()=>{if(r){let e=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(e)}}},[r]);let p=()=>{i(!0)},m=()=>{i(!1),o(!1)};return n?e===`intent`?[a,f,{onFocus:eu(s,p),onBlur:eu(c,m),onMouseEnter:eu(l,p),onMouseLeave:eu(u,m),onTouchStart:eu(d,p)}]:[a,f,{}]:[!1,f,{}]}function eu(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function tu({page:e,...t}){let n=Dc(),{nonce:r}=Ql(),{router:i}=Yl(),a=X.useMemo(()=>Is(i.routes,e,i.basename),[i.routes,e,i.basename]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?X.createElement(ru,{page:e,matches:a,...t}):X.createElement(iu,{page:e,matches:a,...t})):null}function nu(e){let{manifest:t,routeModules:n}=Ql(),[r,i]=X.useState([]);return X.useEffect(()=>{let r=!1;return Ul(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function ru({page:e,matches:t,...n}){let r=Hc(),{future:i}=Ql(),{basename:a}=Yl(),o=X.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=zl(e,a,i.v8_trailingSlashAwareDataRequests,`rsc`),o=!1,s=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?o=!0:s.push(e.route.id);return o&&s.length>0&&n.searchParams.set(`_routes`,s.join(`,`)),[n.pathname+n.search]},[a,i.v8_trailingSlashAwareDataRequests,e,r,t]);return X.createElement(X.Fragment,null,o.map(e=>X.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function iu({page:e,matches:t,...n}){let r=Hc(),{future:i,manifest:a,routeModules:o}=Ql(),{basename:s}=Yl(),{loaderData:c,matches:l}=Xl(),u=X.useMemo(()=>Wl(e,t,l,a,r,`data`),[e,t,l,a,r]),d=X.useMemo(()=>Wl(e,t,l,a,r,`assets`),[e,t,l,a,r]),f=X.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=new Set,l=!1;if(t.forEach(e=>{let t=a.routes[e.route.id];!t||!t.hasLoader||(!u.some(t=>t.route.id===e.route.id)&&e.route.id in c&&o[e.route.id]?.shouldRevalidate||t.hasClientLoader?l=!0:n.add(e.route.id))}),n.size===0)return[];let d=zl(e,s,i.v8_trailingSlashAwareDataRequests,`data`);return l&&n.size>0&&d.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[d.pathname+d.search]},[s,i.v8_trailingSlashAwareDataRequests,c,r,a,u,t,e,o]),p=X.useMemo(()=>Gl(d,a),[d,a]),m=nu(d);return X.createElement(X.Fragment,null,f.map(e=>X.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),p.map(e=>X.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),m.map(({key:e,link:t})=>X.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function au(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}X.Component;var ou=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{ou&&(window.__reactRouterVersion=`7.18.2`)}catch{}function su({basename:e,children:t,useTransitions:n,window:r}){let i=X.useRef();i.current??=Es({window:r,v5Compat:!0});let a=i.current,[o,s]=X.useState({action:a.action,location:a.location}),c=X.useCallback(e=>{n===!1?s(e):X.startTransition(()=>s(e))},[n]);return X.useLayoutEffect(()=>a.listen(c),[a,c]),X.createElement(bl,{basename:e,children:t,location:o.location,navigationType:o.action,navigator:a,useTransitions:n})}var cu=X.forwardRef(function({onClick:e,discover:t=`render`,prefetch:n=`none`,relative:r,reloadDocument:i,replace:a,mask:o,state:s,target:c,to:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m){let{basename:h,navigator:g,useTransitions:_}=X.useContext(jc),v=typeof l==`string`&&bs.test(l),y=yc(l,h);l=y.to;let b=Bc(l,{relative:r}),x=Hc(),S=null;if(o){let e=cc(o,[],x.mask?x.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:uc([h,e.pathname])),S=g.createHref(e)}let[C,w,T]=$l(n,p),E=pu(l,{replace:a,mask:o,state:s,target:c,preventScrollReset:u,relative:r,viewTransition:d,defaultShouldRevalidate:f,useTransitions:_});function D(t){e&&e(t),t.defaultPrevented||E(t)}let O=!(y.isExternal||i),k=X.createElement(`a`,{...p,...T,href:(O?S:void 0)||y.absoluteURL||b,onClick:O?D:e,ref:au(m,w),target:c,"data-discover":!v&&t===`render`?`true`:void 0});return C&&!v?X.createElement(X.Fragment,null,k,X.createElement(tu,{page:b})):k});cu.displayName=`Link`;var lu=X.forwardRef(function({"aria-current":e=`page`,caseSensitive:t=!1,className:n=``,end:r=!1,style:i,to:a,viewTransition:o,children:s,...c},l){let u=Xc(a,{relative:c.relative}),d=Hc(),f=X.useContext(Tc),{navigator:p,basename:m}=X.useContext(jc),h=f!=null&&yu(u)&&o===!0,g=p.encodeLocation?p.encodeLocation(u).pathname:u.pathname,_=d.pathname,v=f&&f.navigation&&f.navigation.location?f.navigation.location.pathname:null;t||(_=_.toLowerCase(),v=v?v.toLowerCase():null,g=g.toLowerCase()),v&&m&&(v=nc(v,m)||v);let y=g!==`/`&&g.endsWith(`/`)?g.length-1:g.length,b=_===g||!r&&_.startsWith(g)&&_.charAt(y)===`/`,x=v!=null&&(v===g||!r&&v.startsWith(g)&&v.charAt(g.length)===`/`),S={isActive:b,isPending:x,isTransitioning:h},C=b?e:void 0,w;w=typeof n==`function`?n(S):[n,b?`active`:null,x?`pending`:null,h?`transitioning`:null].filter(Boolean).join(` `);let T=typeof i==`function`?i(S):i;return X.createElement(cu,{...c,"aria-current":C,className:w,ref:l,style:T,to:a,viewTransition:o},typeof s==`function`?s(S):s)});lu.displayName=`NavLink`;var uu=X.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=Cl,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=X.useContext(jc),g=_u(),_=vu(s,{relative:l}),v=o.toLowerCase()===`get`?`get`:`post`,y=typeof s==`string`&&bs.test(s);return X.createElement(`form`,{ref:m,method:v,action:_,onSubmit:r?c:e=>{if(c&&c(e),e.defaultPrevented)return;e.preventDefault();let r=e.nativeEvent.submitter,s=r?.getAttribute(`formmethod`)||o,p=()=>g(r||e.currentTarget,{fetcherKey:t,method:s,navigate:n,replace:i,state:a,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f});h&&n!==!1?X.startTransition(()=>p()):p()},...p,"data-discover":!y&&e===`render`?`true`:void 0})});uu.displayName=`Form`;function du(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function fu(e){let t=X.useContext(wc);return Ds(t,du(e)),t}function pu(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=Gc(),d=Hc(),f=Xc(e,{relative:o});return X.useCallback(p=>{if(Al(p,t)){p.preventDefault();let t=n===void 0?Ms(d)===Ms(f):n,m=()=>u(e,{replace:t,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c});l?X.startTransition(()=>m()):m()}},[d,u,f,n,r,i,t,e,a,o,s,c,l])}function mu(e){Os(typeof URLSearchParams<`u`,"You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=X.useRef(jl(e)),n=X.useRef(!1),r=Hc(),i=X.useMemo(()=>Ml(r.search,n.current?null:t.current),[r.search]),a=Gc();return[i,X.useCallback((e,t)=>{let r=jl(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var hu=0,gu=()=>`__${String(++hu)}__`;function _u(){let{router:e}=fu(`useSubmit`),{basename:t}=X.useContext(jc),n=dl(),r=e.fetch,i=e.navigate;return X.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=Ll(e,t);if(a.navigate===!1){let e=a.fetcherKey||gu();await r(e,n,a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,flushSync:a.flushSync})}else await i(a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,replace:a.replace,state:a.state,fromRouteId:n,flushSync:a.flushSync,viewTransition:a.viewTransition})},[r,i,t,n])}function vu(e,{relative:t}={}){let{basename:n}=X.useContext(jc),r=X.useContext(Nc);Ds(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...Xc(e||`.`,{relative:t})},o=Hc();if(e==null){a.search=o.search;let e=new URLSearchParams(a.search),t=e.getAll(`index`);if(t.some(e=>e===``)){e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();a.search=n?`?${n}`:``}}return(!e||e===`.`)&&i.route.index&&(a.search=a.search?a.search.replace(/^\?/,`?index&`):`?index`),n!==`/`&&(a.pathname=a.pathname===`/`?n:uc([n,a.pathname])),Ms(a)}function yu(e,{relative:t}={}){let n=X.useContext(Oc);Ds(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=fu(`useViewTransitionState`),i=Xc(e,{relative:t});if(!n.isTransitioning)return!1;let a=nc(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=nc(n.nextLocation.pathname,r)||n.nextLocation.pathname;return Qs(i.pathname,o)!=null||Qs(i.pathname,a)!=null}var Z=f(),bu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Rt,{ref:n,className:K(`text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70`,e),...t}));bu.displayName=Rt.displayName;var xu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`rounded-lg border bg-card text-card-foreground shadow-elevation-1`,e),...t}));xu.displayName=`Card`;var Su=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`flex flex-col space-y-1.5 p-6`,e),...t}));Su.displayName=`CardHeader`;var Cu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`h3`,{ref:n,className:K(`text-2xl font-semibold leading-none tracking-tight`,e),...t}));Cu.displayName=`CardTitle`;var wu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`p`,{ref:n,className:K(`text-sm text-muted-foreground`,e),...t}));wu.displayName=`CardDescription`;var Tu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`p-6 pt-0`,e),...t}));Tu.displayName=`CardContent`;var Eu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`flex items-center p-6 pt-0`,e),...t}));Eu.displayName=`CardFooter`;var Du=`2.14.8`,Ou=e=>{window.particlesJS.load(e,`/js/particles.config.json`,()=>{console.log(`particles.js config loaded for`,e)})};function ku(e){(0,X.useEffect)(()=>{if(window.particlesJS!==void 0)Ou(e);else{if(document.getElementById(`particles-js-script`))return;let t=document.createElement(`script`);t.id=`particles-js-script`,t.src=`/js/particles.min.js`,t.onload=()=>{console.log(`particles.js loaded`),Ou(e)},document.head.appendChild(t)}return()=>{window.pJS&&window.pJS[e]?.destroy&&window.pJS[e].destroy()}},[e])}var Au=`session.open`,ju=`session.set`,Mu=`session.ids`,Nu=`session.materialize`,Pu=`session.close`,Fu=`session.delta`;function Iu(){let[e,t]=(0,X.useState)(null),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=!0;async function n(){try{r(!0),a(null);let n=await Y.get(`/ping`,{skipAuth:!0});e&&(n?.version?t(n.version):a(`Invalid server response`))}catch(t){e&&(console.error(`Failed to fetch server version:`,t),a(`Unable to connect to server`))}finally{e&&r(!1)}}n();let i=setInterval(n,3e4);return()=>{e=!1,clearInterval(i)}},[]),{serverVersion:e,isLoading:n,error:i}}var Lu=`https://github.com/canvas-ui/canvas-server`,Ru=null;function zu(){return Ru||=Y.get(`/ping`,{skipAuth:!0}).then(e=>{let t=e??{};return{sourceUrl:t.sourceUrl||Lu,version:t.version??null,commit:t.commit??null,license:t.license??null}}).catch(e=>(console.error(`Failed to fetch server source info:`,e),Ru=null,{sourceUrl:Lu,version:null,commit:null,license:null})),Ru}function Bu(){let[e,t]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=!0;return zu().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function Vu({className:e=``}){let t=Bu();if(!t)return null;let n=[t.version?`v${t.version}`:null,t.commit?.slice(0,7)].filter(Boolean).join(` `);return(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground ${e}`,children:[`Powered by`,` `,(0,Z.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Canvas`}),n?` ${n}`:``,t.license?`, ${t.license}`:``,`.`,` `,(0,Z.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})}function Hu({children:e}){ku(`particle-js`);let{serverVersion:t,isLoading:n,error:r}=Iu();return(0,Z.jsx)(`div`,{className:`flex min-h-viewport w-full items-center justify-center p-4 flex-col`,children:(0,Z.jsxs)(xu,{className:`flex w-[95vw] h-viewport-modal overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`hidden md:block w-1/2 relative bg-background`,"data-scheme":`dark`,id:`particle-js`,children:[(0,Z.jsxs)(cu,{className:`absolute top-8 left-8 font-bold text-foreground flex items-center z-raised`,to:`/`,children:[(0,Z.jsx)(`img`,{src:`/images/logo-wr_128x128.png`,alt:`Canvas Logo`,className:`mr-2 h-6 w-6 touch-target`}),(0,Z.jsx)(`span`,{className:`text-2xl font-bold text-foreground`,children:`Canvas`})]}),(0,Z.jsxs)(`div`,{className:`absolute bottom-8 left-8 text-sm text-foreground max-w-[80%] z-raised`,children:[`Web UI: v`,Du,`, Server: `,n?`Loading...`:r?`Unavailable`:t?`v${t}`:`Unknown`]})]}),(0,Z.jsx)(`div`,{className:`flex w-full md:w-1/2 flex-col justify-center px-4 py-12 sm:px-6 lg:px-8`,children:(0,Z.jsxs)(`div`,{className:`mx-auto w-full max-w-sm`,children:[e,(0,Z.jsxs)(`div`,{className:`mt-8 border-t pt-6`,children:[(0,Z.jsxs)(`a`,{href:`https://github.com/canvas-ui`,target:`_blank`,className:`text-muted-foreground hover:text-foreground justify-center flex items-center space-x-2`,rel:`noopener noreferrer`,children:[(0,Z.jsx)(`svg`,{viewBox:`0 0 24 24`,width:`24`,height:`24`,stroke:`currentColor`,fill:`none`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`w-6 h-6`,children:(0,Z.jsx)(`path`,{d:`M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22`})}),(0,Z.jsx)(`span`,{children:`View on GitHub`})]}),(0,Z.jsx)(Vu,{className:`mt-4 text-center`})]})]})})]})})}function Uu(){let e=localStorage.getItem(`authToken`);return!e||e===`canvas-server-token`?null:e}var Wu=new class{socket=null;connected=!1;authToken=null;handlers=new Map;socketWrappers=new Map;desiredSubscriptions=new Set;baseUrl;connectionId=``;constructor(){this.baseUrl=ti,this.connectionId=`socket-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}connect(e){let t=e||Uu();!t||t===`canvas-server-token`||this.socket&&this.authToken===t||(this.cleanupSocket(),this.authToken=t,this.socket=qa(this.baseUrl,{transports:[`websocket`],autoConnect:!1,reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,randomizationFactor:.5,timeout:1e4,forceNew:!0,extraHeaders:{Authorization:`Bearer ${t}`,"X-Connection-ID":this.connectionId},auth:{token:t}}),this.setupDefaultHandlers(),this.registerHandlers(),this.socket.connect())}cleanupSocket(){this.socket?.removeAllListeners(),this.socket?.disconnect(),this.socket=null,this.connected=!1,this.socketWrappers.clear()}setupDefaultHandlers(){this.socket&&(this.socket.on(`connect`,()=>{this.connected=!0;for(let e of this.desiredSubscriptions)this.socket?.emit(`subscribe`,{channel:e})}),this.socket.on(`disconnect`,()=>{this.connected=!1}),this.socket.on(`connect_error`,()=>{this.connected=!1}))}registerHandlers(){this.socket&&this.handlers.forEach((e,t)=>{e.forEach(e=>{this.attach(t,e)})})}attach(e,t){if(!this.socket)return;let n=this.socketWrappers.get(e);if(n||(n=new Map,this.socketWrappers.set(e,n)),n.has(t))return;let r=(...e)=>t(...e);n.set(t,r),this.socket.on(e,r)}detach(e,t){if(!this.socket)return;let n=this.socketWrappers.get(e),r=n?.get(t);r&&(this.socket.off(e,r),n?.delete(t),n&&n.size===0&&this.socketWrappers.delete(e))}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set);let n=this.handlers.get(e);return n.has(t)?()=>this.off(e,t):(n.add(t),this.socket&&this.attach(e,t),()=>this.off(e,t))}off(e,t){let n=this.handlers.get(e);n&&n.has(t)&&(n.delete(t),n.size===0&&this.handlers.delete(e),this.detach(e,t))}request(e,t,n=1e4){return new Promise((r,i)=>{if(!this.socket||!this.connected){i(Error(`Socket not connected`));return}let a=!1,o=setTimeout(()=>{a||(a=!0,i(Error(`Socket request timed out: ${e}`)))},n);try{this.socket.emit(e,t??{},t=>{a||(a=!0,clearTimeout(o),t?.status===`error`?i(Error(t.message||`${e} failed`)):r(t?.payload??t))})}catch(e){a=!0,clearTimeout(o),i(e instanceof Error?e:Error(String(e)))}})}emit(e,...t){if(e===`subscribe`){let e=t?.[0]?.channel;typeof e==`string`&&e&&this.desiredSubscriptions.add(e)}else if(e===`unsubscribe`){let e=t?.[0]?.channel;typeof e==`string`&&e&&this.desiredSubscriptions.delete(e)}if(this.socket&&this.connected)try{this.socket.emit(e,...t)}catch(t){console.error(`Error emitting event ${e}:`,t),this.reconnect()}else this.connect()}disconnect(){this.cleanupSocket(),this.authToken=null,this.desiredSubscriptions.clear()}isConnected(){return this.connected}retryNow(){this.connected||(this.cleanupSocket(),this.connect())}reconnect(){this.connect()}};async function Gu(e,t,n=`auto`){try{let r=await Y.post(Kr.login,{email:e,password:t,strategy:n},{skipAuth:!0});console.log(`Login response:`,r);let i=r;if(`token`in i)return console.log(`Setting auth token (direct):`,i.token.substring(0,10)+`...`),Y.setAuthToken(i.token),Wu.connect(i.token),r;if(i&&`payload`in i&&i.payload&&i.payload.token)return console.log(`Setting auth token (nested):`,i.payload.token.substring(0,10)+`...`),Y.setAuthToken(i.payload.token),Wu.connect(i.payload.token),r;throw console.error(`Invalid login response structure:`,r),Error(`Invalid login response: missing token`)}catch(e){throw console.error(`Login error:`,e),Y.clearAuthToken(),e}}async function Ku(e,t,n){try{return await Y.post(Kr.register,{name:e,email:t,password:n},{skipAuth:!0})}catch(e){throw console.error(`Registration failed:`,e),e}}function qu(e){return e instanceof Error&&/^Network error/i.test(e.message)}function Ju(){let e=localStorage.getItem(`authToken`);if(!e)return!1;if(e.startsWith(`canvas-`))return!0;try{return mr(e).exp*1e3>Date.now()}catch{return!1}}function Yu(){let e=localStorage.getItem(`authToken`);if(!e||e.startsWith(`canvas-`))return null;try{let t=mr(e);return t.exp*1e3<Date.now()?(Y.clearAuthToken(),null):{id:t.sub,email:t.email,userType:t.userType||`user`}}catch(e){return console.error(`Failed to decode token:`,e),Y.clearAuthToken(),null}}async function Xu(){try{if(!Y.isAuthenticated())return console.log(`Not authenticated, skipping getCurrentUser request`),null;let e=await Y.get(Kr.me);return console.log(`Current user response:`,e),e&&e?(Wu.isConnected()||Wu.reconnect(),e):(console.warn(`Invalid user profile response structure:`,e),null)}catch(e){if(console.error(`Failed to get current user:`,e),qu(e))throw e;return e instanceof Error&&(e.message.includes(`USER_NOT_FOUND_IN_DATABASE`)||e.message.includes(`Your session is invalid`)||e.message.includes(`Authentication required`)||e.message.includes(`user account no longer exists`))?(console.warn(`Authentication error detected, clearing token:`,e.message),Y.clearAuthToken(),Wu.disconnect(),null):null}}function Zu(){return Y.isAuthenticated()}async function Qu(){try{let e=await Y.get(Kr.authConfig,{skipAuth:!0});return e||e}catch(e){return console.error(`Failed to get auth config:`,e),{strategies:{local:{enabled:!0},imap:{enabled:!1,domains:[]}}}}}async function $u(e){try{await Y.post(Kr.verifyEmailRequest,{email:e},{skipAuth:!0})}catch(e){throw console.error(`Failed to request email verification:`,e),e}}var ed=e=>e?.strategies?.local?.enabled!==!1,td=e=>e?.allowUserRegistrations!==!1;function nd(){let e=Gc(),[t,n]=X.useState(!1),[r,i]=X.useState({}),[a,o]=X.useState(null),[s,c]=X.useState({email:``,password:``,strategy:`auto`});X.useEffect(()=>{Zu()&&e(`/workspaces`),Qu().then(e=>{o(e)}).catch(e=>{console.error(`Failed to load auth config:`,e)})},[e]);let l=()=>{let e={};return s.email?/\S+@\S+\.\S+/.test(s.email)||(e.email=`Email is invalid`):e.email=`Email is required`,s.password||(e.password=`Password is required`),i(e),Object.keys(e).length===0},u=e=>{let{name:t,value:n}=e.target;c(e=>({...e,[t]:n}))};async function d(t){if(t.preventDefault(),l()){n(!0);try{console.log(`Attempting login with:`,s.email,`strategy:`,s.strategy);let t=await Gu(s.email,s.password,s.strategy);console.log(`Login successful, received token:`,`token`in t?!!t.token:!!t.payload?.token),i({}),e(`/home`)}catch(e){console.error(`Login error:`,e);let t=`Login failed`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;n.message?t=n.message:n.error?t=n.error:n.payload?.message&&(t=n.payload.message)}i({password:t})}finally{n(!1)}}}return(0,Z.jsx)(Hu,{children:(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Welcome back`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your credentials to access your account`})]}),(0,Z.jsx)(`form`,{onSubmit:d,children:(0,Z.jsxs)(`div`,{className:`grid gap-4`,children:[a?.strategies?.imap?.enabled&&a.strategies.imap.domains.length>0&&(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(bu,{htmlFor:`strategy`,children:`Authentication Method`}),(0,Z.jsxs)(`select`,{id:`strategy`,name:`strategy`,value:s.strategy,onChange:u,disabled:t,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`,children:[(0,Z.jsx)(`option`,{value:`auto`,children:`Auto-detect`}),(0,Z.jsx)(`option`,{value:`local`,children:`Local Account`}),(0,Z.jsx)(`option`,{value:`imap`,children:`Email Server (IMAP)`})]})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(bu,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,name:`email`,placeholder:`name@example.com`,type:`email`,autoCapitalize:`none`,autoComplete:`email`,autoCorrect:`off`,disabled:t,value:s.email,onChange:u}),r.email&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:r.email})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(bu,{htmlFor:`password`,children:`Password`}),(0,Z.jsx)(q,{id:`password`,name:`password`,type:`password`,disabled:t,value:s.password,onChange:u}),r.password&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:r.password})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Z.jsx)(J,{type:`submit`,disabled:t,children:t?`Signing in...`:`Sign In`}),ed(a)&&td(a)&&(0,Z.jsx)(J,{variant:`outline`,type:`button`,disabled:t,onClick:()=>e(`/register`),children:`Don't have an account? Sign up`})]})]})})]})})}function rd(){let e=Gc(),{showToast:t}=oo(),[n,r]=X.useState(!1),[i,a]=X.useState({}),[o,s]=X.useState({name:``,email:``,password:``}),[c,l]=X.useState(!1),[u,d]=X.useState(!1),[f,p]=X.useState(null);X.useEffect(()=>{(async()=>{let t=await Qu(),n=t?.strategies?.local;if(t?.allowUserRegistrations===!1||n?.enabled===!1){e(`/login`,{replace:!0});return}n?.passwordPolicy&&p(n.passwordPolicy),d(!!n?.requireEmailVerification)})()},[e]);let m=X.useMemo(()=>{if(!f)return null;let e=o.password||``;return{minLength:!f.minLength||e.length>=f.minLength,maxLength:!f.maxLength||e.length<=f.maxLength,uppercase:!f.requireUppercase||/[A-Z]/.test(e),lowercase:!f.requireLowercase||/[a-z]/.test(e),number:!f.requireNumbers||/[0-9]/.test(e),special:!f.requireSpecialChars||/[^A-Za-z0-9]/.test(e)}},[f,o.password]),h=()=>{let e={};if(!o.name)e.name=`Username is required`;else if(o.name.trim().length===0)e.name=`Username cannot be empty`;else{let t=o.name.toLowerCase().trim();t.length<3?e.name=`Username must be at least 3 characters long`:t.length>39?e.name=`Username cannot be longer than 39 characters`:/^[a-z0-9_-]+$/.test(t)?[`admin`,`administrator`,`root`,`system`,`support`,`help`,`api`,`www`,`mail`,`ftp`,`localhost`,`test`,`demo`,`canvas`,`universe`,`workspace`,`context`,`user`,`users`].includes(t)&&(e.name=`Username '${t}' is reserved and cannot be used`):e.name=`Username can only contain lowercase letters, numbers, underscores, and hyphens`}if(o.email?/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o.email)||(e.email=`Please enter a valid email address`):e.email=`Email is required`,!o.password)e.password=`Password is required`;else if(f){let t=o.password,n=[];f.minLength&&t.length<f.minLength&&n.push(`at least ${f.minLength} characters`),f.maxLength&&t.length>f.maxLength&&n.push(`no more than ${f.maxLength} characters`),f.requireUppercase&&!/[A-Z]/.test(t)&&n.push(`an uppercase letter`),f.requireLowercase&&!/[a-z]/.test(t)&&n.push(`a lowercase letter`),f.requireNumbers&&!/[0-9]/.test(t)&&n.push(`a number`),f.requireSpecialChars&&!/[^A-Za-z0-9]/.test(t)&&n.push(`a special character`),n.length&&(e.password=`Password must contain ${n.join(`, `).replace(/, ([^,]*)$/,` and $1`)}.`)}else o.password.length<8&&(e.password=`Password must be at least 8 characters long`);return a(e),Object.keys(e).length===0},g=e=>{let t={...o,[e.target.id]:e.target.value};s(t),(e.target.id===`name`||e.target.id===`email`||e.target.id===`password`)&&h()};return c?(0,Z.jsxs)(Hu,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Registration Successful!`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:u?`Check your email for a verification link to activate your account.`:`Your account has been created.`})]}),(0,Z.jsx)(`div`,{className:`space-y-6 text-center pt-6`,children:!u&&(0,Z.jsx)(J,{asChild:!0,className:`w-full`,children:(0,Z.jsx)(cu,{to:`/login`,children:`Go to Login`})})})]}):(0,Z.jsxs)(Hu,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Create an account`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your email below to create your account`})]}),(0,Z.jsxs)(`form`,{onSubmit:async e=>{if(e.preventDefault(),h()){r(!0);try{let e=await Ku(o.name,o.email,o.password);console.log(`Registration successful:`,e),t({title:`Registration Successful`,description:u?`Check your email for a verification link before logging in.`:`You can now log in with your credentials.`,variant:`default`}),l(!0),s({name:``,email:``,password:``}),a({})}catch(e){console.error(`Registration failed:`,e);let n=e?.message||`Registration failed`;n.toLowerCase().includes(`password`)?a({...i,password:n}):a({...i,email:n}),t({title:`Registration Failed`,description:n,variant:`destructive`})}finally{r(!1)}}},className:`space-y-4 pt-6`,children:[(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(bu,{htmlFor:`name`,children:`Username`}),(0,Z.jsx)(q,{id:`name`,type:`text`,placeholder:`Enter your username (e.g., john_doe)`,value:o.name,onChange:g,disabled:n,className:i.name?`border-destructive`:``}),i.name&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.name}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(bu,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,type:`email`,placeholder:`name@example.com`,value:o.email,onChange:g,disabled:n,className:i.email?`border-destructive`:``}),i.email&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.email})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(bu,{htmlFor:`password`,children:`Password`}),(0,Z.jsx)(q,{id:`password`,type:`password`,placeholder:`Enter your password`,value:o.password,onChange:g,disabled:n,className:i.password?`border-destructive`:``}),i.password&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.password}),f&&m&&(0,Z.jsxs)(`ul`,{className:`text-xs list-disc pl-4 space-y-1`,children:[(0,Z.jsxs)(`li`,{className:m.minLength?`text-success`:`text-muted-foreground`,children:[`At least `,f.minLength,` characters`]}),f.requireUppercase&&(0,Z.jsx)(`li`,{className:m.uppercase?`text-success`:`text-muted-foreground`,children:`At least one uppercase letter`}),f.requireLowercase&&(0,Z.jsx)(`li`,{className:m.lowercase?`text-success`:`text-muted-foreground`,children:`At least one lowercase letter`}),f.requireNumbers&&(0,Z.jsx)(`li`,{className:m.number?`text-success`:`text-muted-foreground`,children:`At least one number`}),f.requireSpecialChars&&(0,Z.jsx)(`li`,{className:m.special?`text-success`:`text-muted-foreground`,children:`At least one special character`}),f.maxLength&&(0,Z.jsxs)(`li`,{className:m.maxLength?`text-success`:`text-muted-foreground`,children:[`No more than `,f.maxLength,` characters`]})]})]}),(0,Z.jsx)(J,{type:`submit`,className:`w-full`,disabled:n,children:n?`Creating Account...`:`Create Account`})]}),(0,Z.jsxs)(`div`,{className:`mt-4 text-center text-sm`,children:[`Already have an account?`,` `,(0,Z.jsx)(cu,{to:`/login`,className:`underline`,children:`Sign in`})]}),(0,Z.jsxs)(`div`,{className:`px-8 py-4 text-center text-sm text-muted-foreground border-t mt-6`,children:[`By clicking continue, you agree to our`,` `,(0,Z.jsx)(cu,{to:`/terms`,className:`underline underline-offset-4 hover:text-primary`,children:`Terms of Service`}),` `,`and`,` `,(0,Z.jsx)(cu,{to:`/privacy`,className:`underline underline-offset-4 hover:text-primary`,children:`Privacy Policy`}),`.`]})]})}function id({className:e=`h-5 w-5`,...t}){return(0,Z.jsxs)(`svg`,{className:`animate-spin ${e}`,xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 24 24`,...t,children:[(0,Z.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,Z.jsx)(`path`,{className:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z`})]})}function ad({children:e}){let[t,n]=(0,X.useState)(`loading`);return(0,X.useEffect)(()=>{(async()=>{try{if(!Zu()){console.log(`No authentication token found, redirecting to login`),n(`unauthenticated`);return}let e=await Xu();e?(console.log(`User authenticated:`,e.email),n(`authenticated`)):(console.log(`User not authenticated or token expired`),n(`unauthenticated`))}catch(e){if(console.error(`Authentication check failed:`,e),qu(e)){n(Ju()?`authenticated`:`unauthenticated`);return}e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from ProtectedRoute`),Y.clearAuthToken()),n(`unauthenticated`)}})()},[]),t===`loading`?(0,Z.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,Z.jsx)(id,{className:`h-8 w-8`})}):t===`unauthenticated`?(0,Z.jsx)(_l,{to:`/login`,replace:!0}):(0,Z.jsx)(Z.Fragment,{children:e})}function od({children:e}){let[t,n]=(0,X.useState)(null);return(0,X.useEffect)(()=>{(async()=>{try{await Y.get(`/auth/me`),n(!0)}catch(e){e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from PublicRoute`),Y.clearAuthToken()),n(!1)}})()},[]),t===null?null:t?(0,Z.jsx)(_l,{to:`/workspaces`,replace:!0}):(0,Z.jsx)(Z.Fragment,{children:e})}var sd=i(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?r(e):typeof define==`function`&&define.amd?define([`exports`],r):(n=typeof globalThis<`u`?globalThis:n||self,r(n[`fast-equals`]={}))})(e,(function(e){function t(e){return function(t,n,r,i,a,o,s){return e(t,n,s)}}function n(e){return function(t,n,r,i){if(!t||!n||typeof t!=`object`||typeof n!=`object`)return e(t,n,r,i);var a=i.get(t),o=i.get(n);if(a&&o)return a===n&&o===t;i.set(t,n),i.set(n,t);var s=e(t,n,r,i);return i.delete(t),i.delete(n),s}}function r(e,t){var n={};for(var r in e)n[r]=e[r];for(var r in t)n[r]=t[r];return n}function i(e){return e.constructor===Object||e.constructor==null}function a(e){return typeof e.then==`function`}function o(e,t){return e===t||e!==e&&t!==t}var s=Object.prototype.toString;function c(e){var t=e.areArraysEqual,n=e.areDatesEqual,r=e.areMapsEqual,c=e.areObjectsEqual,l=e.areRegExpsEqual,u=e.areSetsEqual,d=e.createIsNestedEqual,f=d(p);function p(e,d,p){if(e===d)return!0;if(!e||!d||typeof e!=`object`||typeof d!=`object`)return e!==e&&d!==d;if(i(e)&&i(d))return c(e,d,f,p);var m=Array.isArray(e),h=Array.isArray(d);if(m||h)return m===h&&t(e,d,f,p);var g=s.call(e);return g===s.call(d)?g===`[object Date]`?n(e,d,f,p):g===`[object RegExp]`?l(e,d,f,p):g===`[object Map]`?r(e,d,f,p):g===`[object Set]`?u(e,d,f,p):g===`[object Object]`||g===`[object Arguments]`?a(e)||a(d)?!1:c(e,d,f,p):g===`[object Boolean]`||g===`[object Number]`||g===`[object String]`?o(e.valueOf(),d.valueOf()):!1:!1}return p}function l(e,t,n,r){var i=e.length;if(t.length!==i)return!1;for(;i-->0;)if(!n(e[i],t[i],i,i,e,t,r))return!1;return!0}var u=n(l);function d(e,t){return o(e.valueOf(),t.valueOf())}function f(e,t,n,r){var i=e.size===t.size;if(!i)return!1;if(!e.size)return!0;var a={},o=0;return e.forEach(function(s,c){if(i){var l=!1,u=0;t.forEach(function(i,d){!l&&!a[u]&&(l=n(c,d,o,u,e,t,r)&&n(s,i,c,d,e,t,r))&&(a[u]=!0),u++}),o++,i=l}}),i}var p=n(f),m=`_owner`,h=Object.prototype.hasOwnProperty;function g(e,t,n,r){var i=Object.keys(e),a=i.length;if(Object.keys(t).length!==a)return!1;for(var o;a-->0;){if(o=i[a],o===m){var s=!!e.$$typeof,c=!!t.$$typeof;if((s||c)&&s!==c)return!1}if(!h.call(t,o)||!n(e[o],t[o],o,o,e,t,r))return!1}return!0}var _=n(g);function v(e,t){return e.source===t.source&&e.flags===t.flags}function y(e,t,n,r){var i=e.size===t.size;if(!i)return!1;if(!e.size)return!0;var a={};return e.forEach(function(o,s){if(i){var c=!1,l=0;t.forEach(function(i,u){!c&&!a[l]&&(c=n(o,i,s,u,e,t,r))&&(a[l]=!0),l++}),i=c}}),i}var b=n(y),x=Object.freeze({areArraysEqual:l,areDatesEqual:d,areMapsEqual:f,areObjectsEqual:g,areRegExpsEqual:v,areSetsEqual:y,createIsNestedEqual:t}),S=Object.freeze({areArraysEqual:u,areDatesEqual:d,areMapsEqual:p,areObjectsEqual:_,areRegExpsEqual:v,areSetsEqual:b,createIsNestedEqual:t}),C=c(x);function w(e,t){return C(e,t,void 0)}var T=c(r(x,{createIsNestedEqual:function(){return o}}));function E(e,t){return T(e,t,void 0)}var D=c(S);function O(e,t){return D(e,t,new WeakMap)}var k=c(r(S,{createIsNestedEqual:function(){return o}}));function A(e,t){return k(e,t,new WeakMap)}function j(e){return c(r(x,e(x)))}function M(e){var t=c(r(S,e(S)));return(function(e,n,r){return r===void 0&&(r=new WeakMap),t(e,n,r)})}e.circularDeepEqual=O,e.circularShallowEqual=A,e.createCustomCircularEqual=M,e.createCustomEqual=j,e.deepEqual=w,e.sameValueZeroEqual=o,e.shallowEqual=E,Object.defineProperty(e,"__esModule",{value:!0})}))})),cd=i(((e,t)=>{t.exports=function(e,t,n){return e===t||e.className===t.className&&n(e.style,t.style)&&e.width===t.width&&e.autoSize===t.autoSize&&e.cols===t.cols&&e.draggableCancel===t.draggableCancel&&e.draggableHandle===t.draggableHandle&&n(e.verticalCompact,t.verticalCompact)&&n(e.compactType,t.compactType)&&n(e.layout,t.layout)&&n(e.margin,t.margin)&&n(e.containerPadding,t.containerPadding)&&e.rowHeight===t.rowHeight&&e.maxRows===t.maxRows&&e.isBounded===t.isBounded&&e.isDraggable===t.isDraggable&&e.isResizable===t.isResizable&&e.allowOverlap===t.allowOverlap&&e.preventCollision===t.preventCollision&&e.useCSSTransforms===t.useCSSTransforms&&e.transformScale===t.transformScale&&e.isDroppable===t.isDroppable&&n(e.resizeHandles,t.resizeHandles)&&n(e.resizeHandle,t.resizeHandle)&&e.onLayoutChange===t.onLayoutChange&&e.onDragStart===t.onDragStart&&e.onDrag===t.onDrag&&e.onDragStop===t.onDragStop&&e.onResizeStart===t.onResizeStart&&e.onResize===t.onResize&&e.onResizeStop===t.onResizeStop&&e.onDrop===t.onDrop&&n(e.droppingItem,t.droppingItem)&&n(e.innerRef,t.innerRef)}})),ld=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.bottom=l,e.childrenEqual=h,e.cloneLayout=u,e.cloneLayoutItem=m,e.collides=_,e.compact=v,e.compactItem=x,e.compactType=se,e.correctBounds=S,e.fastPositionEqual=g,e.fastRGLPropsEqual=void 0,e.getAllCollisions=T,e.getFirstCollision=w,e.getLayoutItem=C,e.getStatics=E,e.modifyLayout=f,e.moveElement=D,e.moveElementAwayFromCollision=O,e.noop=void 0,e.perc=k,e.resizeItemInDirection=ne,e.setTopLeft=re,e.setTransform=L,e.sortLayoutItems=R,e.sortLayoutItemsByColRow=ae,e.sortLayoutItemsByRowCol=ie,e.synchronizeLayoutWithChildren=oe,e.validateLayout=z,e.withLayoutItem=p;var t=sd(),n=r(d());function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?i(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function o(e,t,n){return(t=s(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e){var t=c(e,`string`);return typeof t==`symbol`?t:t+``}function c(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function l(e){let t=0,n;for(let r=0,i=e.length;r<i;r++)n=e[r].y+e[r].h,n>t&&(t=n);return t}function u(e){let t=Array(e.length);for(let n=0,r=e.length;n<r;n++)t[n]=m(e[n]);return t}function f(e,t){let n=Array(e.length);for(let r=0,i=e.length;r<i;r++)t.i===e[r].i?n[r]=t:n[r]=e[r];return n}function p(e,t,n){let r=C(e,t);return r?(r=n(m(r)),e=f(e,r),[e,r]):[e,null]}function m(e){return{w:e.w,h:e.h,x:e.x,y:e.y,i:e.i,minW:e.minW,maxW:e.maxW,minH:e.minH,maxH:e.maxH,moved:!!e.moved,static:!!e.static,isDraggable:e.isDraggable,isResizable:e.isResizable,resizeHandles:e.resizeHandles,isBounded:e.isBounded}}function h(e,r){return(0,t.deepEqual)(n.default.Children.map(e,e=>e?.key),n.default.Children.map(r,e=>e?.key))&&(0,t.deepEqual)(n.default.Children.map(e,e=>e?.props[`data-grid`]),n.default.Children.map(r,e=>e?.props[`data-grid`]))}e.fastRGLPropsEqual=cd();function g(e,t){return e.left===t.left&&e.top===t.top&&e.width===t.width&&e.height===t.height}function _(e,t){return!(e.i===t.i||e.x+e.w<=t.x||e.x>=t.x+t.w||e.y+e.h<=t.y||e.y>=t.y+t.h)}function v(e,t,n,r){let i=E(e),a=l(i),o=R(e,t),s=Array(e.length);for(let c=0,l=o.length;c<l;c++){let l=m(o[c]);l.static||(l=x(i,l,t,n,o,r,a),a=Math.max(a,l.y+l.h),i.push(l)),s[e.indexOf(o[c])]=l,l.moved=!1}return s}var y={x:`w`,y:`h`};function b(e,t,n,r){let i=y[r];t[r]+=1;let a=e.map(e=>e.i).indexOf(t.i);for(let o=a+1;o<e.length;o++){let a=e[o];if(!a.static){if(a.y>t.y+t.h)break;_(t,a)&&b(e,a,n+t[i],r)}}t[r]=n}function x(e,t,n,r,i,a,o){let s=n===`vertical`,c=n===`horizontal`;if(s)for(t.y=Math.min(typeof o==`number`?o:l(e),t.y);t.y>0&&!w(e,t);)t.y--;else if(c)for(;t.x>0&&!w(e,t);)t.x--;let u;for(;(u=w(e,t))&&!(n===null&&a);)if(c?b(i,t,u.x+u.w,`x`):b(i,t,u.y+u.h,`y`),c&&t.x+t.w>r)for(t.x=r-t.w,t.y++;t.x>0&&!w(e,t);)t.x--;return t.y=Math.max(t.y,0),t.x=Math.max(t.x,0),t}function S(e,t){let n=E(e);for(let r=0,i=e.length;r<i;r++){let i=e[r];if(i.x+i.w>t.cols&&(i.x=t.cols-i.w),i.x<0&&(i.x=0,i.w=t.cols),!i.static)n.push(i);else for(;w(n,i);)i.y++}return e}function C(e,t){for(let n=0,r=e.length;n<r;n++)if(e[n].i===t)return e[n]}function w(e,t){for(let n=0,r=e.length;n<r;n++)if(_(e[n],t))return e[n]}function T(e,t){return e.filter(e=>_(e,t))}function E(e){return e.filter(e=>e.static)}function D(e,t,n,r,i,a,o,s,c){if(t.static&&t.isDraggable!==!0||t.y===r&&t.x===n)return e;`${t.i}${String(n)}${String(r)}${t.x}${t.y}`;let l=t.x,d=t.y;typeof n==`number`&&(t.x=n),typeof r==`number`&&(t.y=r),t.moved=!0;let f=R(e,o);(o===`vertical`&&typeof r==`number`?d>=r:o===`horizontal`&&typeof n==`number`&&l>=n)&&(f=f.reverse());let p=T(f,t),m=p.length>0;if(m&&c)return u(e);if(m&&a)return`${t.i}`,t.x=l,t.y=d,t.moved=!1,e;for(let n=0,r=p.length;n<r;n++){let r=p[n];`${t.i}${t.x}${t.y}${r.i}${r.x}${r.y}`,!r.moved&&(e=r.static?O(e,r,t,i,o,s):O(e,t,r,i,o,s))}return e}function O(e,t,n,r,i,a){let o=i===`horizontal`,s=i===`vertical`,c=t.static;if(r){r=!1;let l={x:o?Math.max(t.x-n.w,0):n.x,y:s?Math.max(t.y-n.h,0):n.y,w:n.w,h:n.h,i:`-1`},u=w(e,l),d=u&&u.y+u.h>t.y,f=u&&t.x+t.w>u.x;if(!u)return`${n.i}${l.x}${l.y}`,D(e,n,o?l.x:void 0,s?l.y:void 0,r,c,i,a);if(d&&s)return D(e,n,void 0,n.y+1,r,c,i,a);if(d&&i==null)return t.y=n.y,n.y+=n.h,e;if(f&&o)return D(e,t,n.x,void 0,r,c,i,a)}let l=o?n.x+1:void 0,u=s?n.y+1:void 0;return l==null&&u==null?e:D(e,n,o?n.x+1:void 0,s?n.y+1:void 0,r,c,i,a)}function k(e){return e*100+`%`}var A=(e,t,n,r)=>e+n>r?t:n,j=(e,t,n)=>e<0?t:n,M=e=>Math.max(0,e),N=e=>Math.max(0,e),P=(e,t,n)=>{let{left:r,height:i,width:a}=t,o=e.top-(i-e.height);return{left:r,width:a,height:j(o,e.height,i),top:N(o)}},ee=(e,t,n)=>{let{top:r,left:i,height:a,width:o}=t;return{top:r,height:a,width:A(e.left,e.width,o,n),left:M(i)}},F=(e,t,n)=>{let{top:r,height:i,width:a}=t,o=e.left-(a-e.width);return{height:i,width:o<0?e.width:A(e.left,e.width,a,n),top:N(r),left:M(o)}},I=(e,t,n)=>{let{top:r,left:i,height:a,width:o}=t;return{width:o,left:i,height:j(r,e.height,a),top:N(r)}},te={n:P,ne:function(){return P(arguments.length<=0?void 0:arguments[0],ee(...arguments),arguments.length<=2?void 0:arguments[2])},e:ee,se:function(){return I(arguments.length<=0?void 0:arguments[0],ee(...arguments),arguments.length<=2?void 0:arguments[2])},s:I,sw:function(){return I(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])},w:F,nw:function(){return P(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])}};function ne(e,t,n,r){let i=te[e];return i?i(t,a(a({},t),n),r):n}function L(e){let{top:t,left:n,width:r,height:i}=e,a=`translate(${n}px,${t}px)`;return{transform:a,WebkitTransform:a,MozTransform:a,msTransform:a,OTransform:a,width:`${r}px`,height:`${i}px`,position:`absolute`}}function re(e){let{top:t,left:n,width:r,height:i}=e;return{top:`${t}px`,left:`${n}px`,width:`${r}px`,height:`${i}px`,position:`absolute`}}function R(e,t){return t===`horizontal`?ae(e):t===`vertical`?ie(e):e}function ie(e){return e.slice(0).sort(function(e,t){return e.y>t.y||e.y===t.y&&e.x>t.x?1:e.y===t.y&&e.x===t.x?0:-1})}function ae(e){return e.slice(0).sort(function(e,t){return e.x>t.x||e.x===t.x&&e.y>t.y?1:-1})}function oe(e,t,r,i,o){e||=[];let s=[];n.default.Children.forEach(t,t=>{if(t?.key==null)return;let n=C(e,String(t.key)),r=t.props[`data-grid`];n&&r==null?s.push(m(n)):r?s.push(m(a(a({},r),{},{i:t.key}))):s.push(m({w:1,h:1,x:0,y:l(s),i:String(t.key)}))});let c=S(s,{cols:r});return o?c:v(c,i,r)}function z(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Layout`,n=[`x`,`y`,`w`,`h`];if(!Array.isArray(e))throw Error(t+` must be an array!`);for(let r=0,i=e.length;r<i;r++){let i=e[r];for(let e=0;e<n.length;e++){let a=n[e],o=i[a];if(typeof o!=`number`||Number.isNaN(o))throw Error(`ReactGridLayout: ${t}[${r}].${a} must be a number! Received: ${o} (${typeof o})`)}if(i.i!==void 0&&typeof i.i!=`string`)throw Error(`ReactGridLayout: ${t}[${r}].i must be a string! Received: ${i.i} (${typeof i.i})`)}}function se(e){let{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}e.noop=()=>{}})),ud=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.calcGridColWidth=t,e.calcGridItemPosition=r,e.calcGridItemWHPx=n,e.calcWH=a,e.calcXY=i,e.clamp=o;function t(e){let{margin:t,containerPadding:n,containerWidth:r,cols:i}=e;return(r-t[0]*(i-1)-n[0]*2)/i}function n(e,t,n){return Number.isFinite(e)?Math.round(t*e+Math.max(0,e-1)*n):e}function r(e,r,i,a,o,s){let{margin:c,containerPadding:l,rowHeight:u}=e,d=t(e),f={};return s&&s.resizing?(f.width=Math.round(s.resizing.width),f.height=Math.round(s.resizing.height)):(f.width=n(a,d,c[0]),f.height=n(o,u,c[1])),s&&s.dragging?(f.top=Math.round(s.dragging.top),f.left=Math.round(s.dragging.left)):s&&s.resizing&&typeof s.resizing.top==`number`&&typeof s.resizing.left==`number`?(f.top=Math.round(s.resizing.top),f.left=Math.round(s.resizing.left)):(f.top=Math.round((u+c[1])*i+l[1]),f.left=Math.round((d+c[0])*r+l[0])),f}function i(e,n,r,i,a){let{margin:s,containerPadding:c,cols:l,rowHeight:u,maxRows:d}=e,f=t(e),p=Math.round((r-c[0])/(f+s[0])),m=Math.round((n-c[1])/(u+s[1]));return p=o(p,0,l-i),m=o(m,0,d-a),{x:p,y:m}}function a(e,n,r,i,a,s){let{margin:c,maxRows:l,cols:u,rowHeight:d}=e,f=t(e),p=Math.round((n+c[0])/(f+c[0])),m=Math.round((r+c[1])/(d+c[1])),h=o(p,0,u-i),g=o(m,0,l-a);return[`sw`,`w`,`nw`].indexOf(s)!==-1&&(h=o(p,0,u)),[`nw`,`n`,`ne`].indexOf(s)!==-1&&(g=o(m,0,l)),{w:h,h:g}}function o(e,t,n){return Math.max(Math.min(e,n),t)}})),dd=i(((e,t)=>{t.exports=`SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED`})),fd=i(((e,t)=>{var n=dd();function r(){}function i(){}i.resetWarningCache=r,t.exports=function(){function e(e,t,r,i,a,o){if(o!==n){var s=Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw s.name=`Invariant Violation`,s}}e.isRequired=e;function t(){return e}var a={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:i,resetWarningCache:r};return a.PropTypes=a,a}})),pd=i(((e,t)=>{t.exports=fd()()})),md=i(((e,t)=>{var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},u=(e,t,n,a)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let s of o(t))!c.call(e,s)&&s!==n&&r(e,s,{get:()=>t[s],enumerable:!(a=i(t,s))||a.enumerable});return e},f=(e,t,i)=>(i=e==null?{}:n(s(e)),u(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)),p=e=>u(r({},`__esModule`,{value:!0}),e),m={};l(m,{DraggableCore:()=>xe,default:()=>Se}),t.exports=p(m);var h=f(d()),g=f(pd()),_=f(a()),v=pr();function y(e,t){for(let n=0,r=e.length;n<r;n++)if(t.apply(t,[e[n],n,e]))return e[n]}function b(e){return typeof e==`function`||Object.prototype.toString.call(e)===`[object Function]`}function x(e){return typeof e==`number`&&!isNaN(e)}function S(e){return parseInt(e,10)}function C(e,t,n){if(e[t])return Error(`Invalid prop ${t} passed to ${n} - do not set this, set it on the child.`)}var w=[`Moz`,`Webkit`,`O`,`ms`];function T(e=`transform`){if(typeof window>`u`)return``;let t=window.document?.documentElement?.style;if(!t||e in t)return``;for(let n=0;n<w.length;n++)if(E(e,w[n])in t)return w[n];return``}function E(e,t){return t?`${t}${D(e)}`:e}function D(e){let t=``,n=!0;for(let r=0;r<e.length;r++)n?(t+=e[r].toUpperCase(),n=!1):e[r]===`-`?n=!0:t+=e[r];return t}var O=T(),k=``;function A(e,t){k||=y([`matches`,`webkitMatchesSelector`,`mozMatchesSelector`,`msMatchesSelector`,`oMatchesSelector`],function(t){return b(e[t])})??``;let n=e[k];return b(n)?!!n.call(e,t):!1}function j(e,t,n){let r=e;do{if(A(r,t))return!0;if(r===n)return!1;r=r.parentNode}while(r);return!1}function M(e,t,n,r){if(!e)return;let i={capture:!0,...r},a=n;e.addEventListener?e.addEventListener(t,a,i):e.attachEvent?e.attachEvent(`on`+t,a):e[`on`+t]=a}function N(e,t,n,r){if(!e)return;let i={capture:!0,...r},a=n;e.removeEventListener?e.removeEventListener(t,a,i):e.detachEvent?e.detachEvent(`on`+t,a):e[`on`+t]=null}function P(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderTopWidth),t+=S(n.borderBottomWidth),t}function ee(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderLeftWidth),t+=S(n.borderRightWidth),t}function F(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingTop),t-=S(n.paddingBottom),t}function I(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingLeft),t-=S(n.paddingRight),t}function te(e,t,n){let r=t===t.ownerDocument.body?{left:0,top:0}:t.getBoundingClientRect();return{x:(e.clientX+t.scrollLeft-r.left)/n,y:(e.clientY+t.scrollTop-r.top)/n}}function ne(e,t){let n=re(e,t,`px`);return{[E(`transform`,O)]:n}}function L(e,t){return re(e,t,``)}function re({x:e,y:t},n,r){let i=`translate(${e}${r},${t}${r})`;return n&&(i=`translate(${`${typeof n.x==`string`?n.x:n.x+r}`}, ${`${typeof n.y==`string`?n.y:n.y+r}`})`+i),i}function R(e,t){return e.targetTouches&&y(e.targetTouches,e=>t===e.identifier)||e.changedTouches&&y(e.changedTouches,e=>t===e.identifier)}function ie(e){if(e.targetTouches&&e.targetTouches[0])return e.targetTouches[0].identifier;if(e.changedTouches&&e.changedTouches[0])return e.changedTouches[0].identifier}function ae(){return typeof __webpack_nonce__<`u`?__webpack_nonce__:void 0}function oe(e,t){if(!e)return;let n=e.getElementById(`react-draggable-style-el`);if(!n){n=e.createElement(`style`),n.type=`text/css`,n.id=`react-draggable-style-el`;let r=t??ae();r&&n.setAttribute(`nonce`,r),n.innerHTML=`.react-draggable-transparent-selection *::-moz-selection {all: inherit;}
|
|
5
|
+
`,n.innerHTML+=`.react-draggable-transparent-selection *::selection {all: inherit;}
|
|
6
|
+
`,e.getElementsByTagName(`head`)[0].appendChild(n)}e.body&&ce(e.body,`react-draggable-transparent-selection`)}function z(e){window.requestAnimationFrame?window.requestAnimationFrame(()=>{se(e)}):se(e)}function se(e){if(e)try{e.body&&B(e.body,`react-draggable-transparent-selection`);let t=e.selection;if(t)t.empty();else{let t=(e.defaultView||window).getSelection();t&&t.type!==`Caret`&&t.removeAllRanges()}}catch{}}function ce(e,t){e.classList?e.classList.add(t):e.className.match(RegExp(`(?:^|\\s)${t}(?!\\S)`))||(e.className+=` ${t}`)}function B(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(RegExp(`(?:^|\\s)${t}(?!\\S)`,`g`),``)}function V(e,t,n){if(!e.props.bounds)return[t,n];let{bounds:r}=e.props;r=typeof r==`string`?r:H(r);let i=he(e);if(typeof r==`string`){let{ownerDocument:e}=i,t=e.defaultView;if(!t)throw Error(`Cannot resolve the owner window of the draggable node.`);let n;if(n=r===`parent`?i.parentNode:i.getRootNode().querySelector(r),!(n instanceof t.HTMLElement))throw Error(`Bounds selector "`+r+`" could not find an element.`);let a=n,o=t.getComputedStyle(i),s=t.getComputedStyle(a);r={left:-i.offsetLeft+S(s.paddingLeft)+S(o.marginLeft),top:-i.offsetTop+S(s.paddingTop)+S(o.marginTop),right:I(a)-ee(i)-i.offsetLeft+S(s.paddingRight)-S(o.marginRight),bottom:F(a)-P(i)-i.offsetTop+S(s.paddingBottom)-S(o.marginBottom)}}return x(r.right)&&(t=Math.min(t,r.right)),x(r.bottom)&&(n=Math.min(n,r.bottom)),x(r.left)&&(t=Math.max(t,r.left)),x(r.top)&&(n=Math.max(n,r.top)),[t,n]}function le(e,t,n){return[Math.round(t/e[0])*e[0],Math.round(n/e[1])*e[1]]}function ue(e){return e.props.axis===`both`||e.props.axis===`x`}function de(e){return e.props.axis===`both`||e.props.axis===`y`}function fe(e,t,n){let r=typeof t==`number`?R(e,t):null;if(typeof t==`number`&&!r)return null;let i=he(n),a=n.props.offsetParent||i.offsetParent||i.ownerDocument.body;return te(r||e,a,n.props.scale)}function pe(e,t,n){let r=!x(e.lastX),i=he(e);return r?{node:i,deltaX:0,deltaY:0,lastX:t,lastY:n,x:t,y:n}:{node:i,deltaX:t-e.lastX,deltaY:n-e.lastY,lastX:e.lastX,lastY:e.lastY,x:t,y:n}}function me(e,t){let n=e.props.scale;return{node:t.node,x:e.state.x+t.deltaX/n,y:e.state.y+t.deltaY/n,deltaX:t.deltaX/n,deltaY:t.deltaY/n,lastX:e.state.x,lastY:e.state.y}}function H(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom}}function he(e){let t=e.findDOMNode();if(!t)throw Error(`<DraggableCore>: Unmounted during event!`);return t}var ge=f(d()),_e=f(pd()),ve=f(a()),ye=typeof process<`u`&&{}.DRAGGABLE_DEBUG?console.log.bind(console):function(){},U={touch:{start:`touchstart`,move:`touchmove`,stop:`touchend`},mouse:{start:`mousedown`,move:`mousemove`,stop:`mouseup`}},be=U.mouse,xe=class extends ge.Component{constructor(){super(...arguments),this.dragging=!1,this.lastX=NaN,this.lastY=NaN,this.touchIdentifier=null,this.mounted=!1,this.handleDragStart=e=>{if(this.props.onMouseDown(e),!this.props.allowAnyClick&&(typeof e.button==`number`&&e.button!==0||e.ctrlKey))return!1;let t=this.findDOMNode();if(!t||!t.ownerDocument||!t.ownerDocument.body)throw Error(`<DraggableCore> not mounted on DragStart!`);let{ownerDocument:n}=t;if(this.props.disabled||!(e.target instanceof n.defaultView.Node)||this.props.handle&&!j(e.target,this.props.handle,t)||this.props.cancel&&j(e.target,this.props.cancel,t))return;e.type===`touchstart`&&!this.props.allowMobileScroll&&e.preventDefault();let r=ie(e);this.touchIdentifier=r;let i=fe(e,r,this);if(i==null)return;let{x:a,y:o}=i,s=pe(this,a,o);ye(`DraggableCore: handleDragStart: %j`,s),ye(`calling`,this.props.onStart),this.props.onStart(e,s)!==!1&&this.mounted!==!1&&(this.props.enableUserSelectHack&&oe(n,this.props.nonce),this.dragging=!0,this.lastX=a,this.lastY=o,M(n,be.move,this.handleDrag),M(n,be.stop,this.handleDragStop))},this.handleDrag=e=>{let t=fe(e,this.touchIdentifier,this);if(t==null)return;let{x:n,y:r}=t;if(Array.isArray(this.props.grid)){let e=n-this.lastX,t=r-this.lastY;if([e,t]=le(this.props.grid,e,t),!e&&!t)return;n=this.lastX+e,r=this.lastY+t}let i=pe(this,n,r);if(ye(`DraggableCore: handleDrag: %j`,i),this.props.onDrag(e,i)===!1||this.mounted===!1){try{this.handleDragStop(new MouseEvent(`mouseup`))}catch{let e=document.createEvent(`MouseEvents`);e.initMouseEvent(`mouseup`,!0,!0,window,0,0,0,0,0,!1,!1,!1,!1,0,null),this.handleDragStop(e)}return}this.lastX=n,this.lastY=r},this.handleDragStop=e=>{if(!this.dragging)return;let t=fe(e,this.touchIdentifier,this);if(t==null)return;let{x:n,y:r}=t;if(Array.isArray(this.props.grid)){let e=n-this.lastX||0,t=r-this.lastY||0;[e,t]=le(this.props.grid,e,t),n=this.lastX+e,r=this.lastY+t}let i=pe(this,n,r);if(this.props.onStop(e,i)===!1||this.mounted===!1)return!1;let a=this.findDOMNode();a&&this.props.enableUserSelectHack&&z(a.ownerDocument),ye(`DraggableCore: handleDragStop: %j`,i),this.dragging=!1,this.lastX=NaN,this.lastY=NaN,a&&(ye(`DraggableCore: Removing handlers`),N(a.ownerDocument,be.move,this.handleDrag),N(a.ownerDocument,be.stop,this.handleDragStop))},this.onMouseDown=e=>(be=U.mouse,this.handleDragStart(e)),this.onMouseUp=e=>(be=U.mouse,this.handleDragStop(e)),this.onTouchStart=e=>(be=U.touch,this.handleDragStart(e)),this.onTouchEnd=e=>(be=U.touch,this.handleDragStop(e))}componentDidMount(){this.mounted=!0;let e=this.findDOMNode();e&&M(e,U.touch.start,this.onTouchStart,{passive:!1})}componentWillUnmount(){this.mounted=!1;let e=this.findDOMNode();if(e){let{ownerDocument:t}=e;N(t,U.mouse.move,this.handleDrag),N(t,U.touch.move,this.handleDrag),N(t,U.mouse.stop,this.handleDragStop),N(t,U.touch.stop,this.handleDragStop),N(e,U.touch.start,this.onTouchStart,{passive:!1}),this.props.enableUserSelectHack&&z(t)}}findDOMNode(){if(this.props?.nodeRef)return this.props.nodeRef.current;let e=ve.default;return typeof e.findDOMNode==`function`?e.findDOMNode(this):(ye(`react-draggable: ReactDOM.findDOMNode is not available in React 19+. You must provide a nodeRef prop. See: https://github.com/react-grid-layout/react-draggable#noderef`),null)}render(){return ge.cloneElement(ge.Children.only(this.props.children),{onMouseDown:this.onMouseDown,onMouseUp:this.onMouseUp,onTouchEnd:this.onTouchEnd})}};xe.displayName=`DraggableCore`,xe.propTypes={allowAnyClick:_e.default.bool,allowMobileScroll:_e.default.bool,children:_e.default.node.isRequired,disabled:_e.default.bool,enableUserSelectHack:_e.default.bool,offsetParent:function(e,t){if(e[t]&&e[t].nodeType!==1)throw Error(`Draggable's offsetParent must be a DOM Node.`)},grid:_e.default.arrayOf(_e.default.number),handle:_e.default.string,cancel:_e.default.string,nodeRef:_e.default.object,nonce:_e.default.string,onStart:_e.default.func,onDrag:_e.default.func,onStop:_e.default.func,onMouseDown:_e.default.func,scale:_e.default.number,className:C,style:C,transform:C},xe.defaultProps={allowAnyClick:!1,allowMobileScroll:!1,disabled:!1,enableUserSelectHack:!0,onStart:function(){},onDrag:function(){},onStop:function(){},onMouseDown:function(){},scale:1};var Se=class extends h.Component{constructor(e){super(e),this.onDragStart=(e,t)=>{if(ye(`Draggable: onDragStart: %j`,t),this.props.onStart(e,me(this,t))===!1)return!1;this.setState({dragging:!0,dragged:!0})},this.onDrag=(e,t)=>{if(!this.state.dragging)return!1;ye(`Draggable: onDrag: %j`,t);let n=me(this,t),r={x:n.x,y:n.y,slackX:0,slackY:0};if(this.props.bounds){let{x:e,y:t}=r;r.x+=this.state.slackX,r.y+=this.state.slackY;let[i,a]=V(this,r.x,r.y);r.x=i,r.y=a,r.slackX=this.state.slackX+(e-r.x),r.slackY=this.state.slackY+(t-r.y),n.x=r.x,n.y=r.y,n.deltaX=r.x-this.state.x,n.deltaY=r.y-this.state.y}if(this.props.onDrag(e,n)===!1)return!1;this.setState(r)},this.onDragStop=(e,t)=>{if(!this.state.dragging||this.props.onStop(e,me(this,t))===!1)return!1;ye(`Draggable: onDragStop: %j`,t);let n={dragging:!1,slackX:0,slackY:0};if(this.props.position){let{x:e,y:t}=this.props.position;n.x=e,n.y=t}this.setState(n)},this.state={dragging:!1,dragged:!1,x:e.position?e.position.x:e.defaultPosition.x,y:e.position?e.position.y:e.defaultPosition.y,prevPropsPosition:{...e.position},slackX:0,slackY:0,isElementSVG:!1},e.position&&!(e.onDrag||e.onStop)&&console.warn("A `position` was applied to this <Draggable>, without drag handlers. This will make this component effectively undraggable. Please attach `onDrag` or `onStop` handlers so you can adjust the `position` of this element.")}static getDerivedStateFromProps({position:e},{prevPropsPosition:t}){return e&&(!t||e.x!==t.x||e.y!==t.y)?(ye(`Draggable: getDerivedStateFromProps %j`,{position:e,prevPropsPosition:t}),{x:e.x,y:e.y,prevPropsPosition:{...e}}):null}componentDidMount(){window.SVGElement!==void 0&&this.findDOMNode()instanceof window.SVGElement&&this.setState({isElementSVG:!0})}componentWillUnmount(){this.state.dragging&&this.setState({dragging:!1})}findDOMNode(){if(this.props?.nodeRef)return this.props.nodeRef.current;let e=_.default;return typeof e.findDOMNode==`function`?e.findDOMNode(this):null}render(){let{axis:e,bounds:t,children:n,defaultPosition:r,defaultClassName:i,defaultClassNameDragging:a,defaultClassNameDragged:o,position:s,positionOffset:c,scale:l,...u}=this.props,d={},f=null,p=!s||this.state.dragging,m=s||r,g={x:ue(this)&&p?this.state.x:m.x,y:de(this)&&p?this.state.y:m.y};this.state.isElementSVG?f=L(g,c):d=ne(g,c);let _=h.Children.only(n),y=(0,v.clsx)(_.props.className||``,i,{[a]:this.state.dragging,[o]:this.state.dragged});return h.createElement(xe,{...u,onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop},h.cloneElement(_,{className:y,style:{..._.props.style,...d},transform:f}))}};Se.displayName=`Draggable`,Se.propTypes={...xe.propTypes,axis:g.default.oneOf([`both`,`x`,`y`,`none`]),bounds:g.default.oneOfType([g.default.shape({left:g.default.number,right:g.default.number,top:g.default.number,bottom:g.default.number}),g.default.string,g.default.oneOf([!1])]),defaultClassName:g.default.string,defaultClassNameDragging:g.default.string,defaultClassNameDragged:g.default.string,defaultPosition:g.default.shape({x:g.default.number,y:g.default.number}),positionOffset:g.default.shape({x:g.default.oneOfType([g.default.number,g.default.string]),y:g.default.oneOfType([g.default.number,g.default.string])}),position:g.default.shape({x:g.default.number,y:g.default.number}),className:C,style:C,transform:C},Se.defaultProps={...xe.defaultProps,axis:`both`,bounds:!1,defaultClassName:`react-draggable`,defaultClassNameDragging:`react-draggable-dragging`,defaultClassNameDragged:`react-draggable-dragged`,defaultPosition:{x:0,y:0},scale:1},0&&(t.exports={DraggableCore:xe})})),hd=i(((e,t)=>{var n=md(),r=n.DraggableCore,i=n.default||n;t.exports=i,t.exports.default=i,t.exports.DraggableCore=r})),gd=i((e=>{e.__esModule=!0,e.cloneElement=c;var t=n(d());function n(e){return e&&e.__esModule?e:{default:e}}function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function i(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?r(Object(n),!0).forEach(function(t){a(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function a(e,t,n){return(t=o(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e){var t=s(e,`string`);return typeof t==`symbol`?t:t+``}function s(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function c(e,n){return n.style&&e.props.style&&(n.style=i(i({},e.props.style),n.style)),n.className&&e.props.className&&(n.className=e.props.className+` `+n.className),t.default.cloneElement(e,n)}})),_d=i((e=>{e.__esModule=!0,e.resizableProps=void 0;var t=n(pd());hd();function n(e){return e&&e.__esModule?e:{default:e}}e.resizableProps={axis:t.default.oneOf([`both`,`x`,`y`,`none`]),className:t.default.string,children:t.default.element.isRequired,draggableOpts:t.default.shape({allowAnyClick:t.default.bool,cancel:t.default.string,children:t.default.node,disabled:t.default.bool,enableUserSelectHack:t.default.bool,offsetParent:typeof Element<`u`?t.default.instanceOf(Element):t.default.any,grid:t.default.arrayOf(t.default.number),handle:t.default.string,nodeRef:t.default.object,onStart:t.default.func,onDrag:t.default.func,onStop:t.default.func,onMouseDown:t.default.func,scale:t.default.number}),height:function(){var e=[...arguments];let n=e[0];return n.axis===`both`||n.axis===`y`?t.default.number.isRequired(...e):t.default.number(...e)},handle:t.default.oneOfType([t.default.node,t.default.func]),handleSize:t.default.arrayOf(t.default.number),lockAspectRatio:t.default.bool,maxConstraints:t.default.arrayOf(t.default.number),minConstraints:t.default.arrayOf(t.default.number),onResizeStop:t.default.func,onResizeStart:t.default.func,onResize:t.default.func,resizeHandles:t.default.arrayOf(t.default.oneOf([`s`,`w`,`e`,`n`,`sw`,`nw`,`se`,`ne`])),transformScale:t.default.number,width:function(){var e=[...arguments];let n=e[0];return n.axis===`both`||n.axis===`x`?t.default.number.isRequired(...e):t.default.number(...e)}}})),vd=i((e=>{e.__esModule=!0,e.default=void 0;var t=o(d()),n=hd(),r=gd(),i=_d(),a=[`children`,`className`,`draggableOpts`,`width`,`height`,`handle`,`handleSize`,`lockAspectRatio`,`axis`,`minConstraints`,`maxConstraints`,`onResize`,`onResizeStop`,`onResizeStart`,`resizeHandles`,`transformScale`];function o(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(o=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function s(){return s=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s.apply(null,arguments)}function c(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function l(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function u(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?l(Object(n),!0).forEach(function(t){f(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):l(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function f(e,t,n){return(t=p(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function p(e){var t=m(e,`string`);return typeof t==`symbol`?t:t+``}function m(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var h=class extends t.Component{constructor(){super(...arguments),this.handleRefs={},this.lastHandleRect=null,this.slack=null,this.lastSize=null}componentWillUnmount(){this.resetData()}resetData(){this.lastHandleRect=this.slack=this.lastSize=null}runConstraints(e,t){let n=this.props,r=n.minConstraints,i=n.maxConstraints,a=n.lockAspectRatio;if(!r&&!i&&!a)return[e,t];if(a){let n=this.props.width/this.props.height,r=e-this.props.width,i=t-this.props.height;Math.abs(r)>Math.abs(i*n)?t=e/n:e=t*n}let o=e,s=t,c=this.slack||[0,0],l=c[0],u=c[1];return e+=l,t+=u,r&&(e=Math.max(r[0],e),t=Math.max(r[1],t)),i&&(e=Math.min(i[0],e),t=Math.min(i[1],t)),this.slack=[l+(o-e),u+(s-t)],[e,t]}resizeHandler(e,t){return(n,r)=>{let i=r.node,a=r.deltaX,o=r.deltaY;e===`onResizeStart`&&this.resetData();let s=(this.props.axis===`both`||this.props.axis===`x`)&&t!==`n`&&t!==`s`,c=(this.props.axis===`both`||this.props.axis===`y`)&&t!==`e`&&t!==`w`;if(!s&&!c)return;let l=t[0],u=t[t.length-1],d=i.getBoundingClientRect();if(this.lastHandleRect!=null){if(u===`w`){let e=d.left-this.lastHandleRect.left;a+=e}if(l===`n`){let e=d.top-this.lastHandleRect.top;o+=e}}this.lastHandleRect=d,u===`w`&&(a=-a),l===`n`&&(o=-o);let f=this.lastSize?.width??this.props.width,p=this.lastSize?.height??this.props.height,m=f+(s?a/this.props.transformScale:0),h=p+(c?o/this.props.transformScale:0);var g=this.runConstraints(m,h);if(m=g[0],h=g[1],e===`onResizeStop`&&this.lastSize){var _=this.lastSize;m=_.width,h=_.height}let v=m!==f||h!==p;e!==`onResizeStop`&&(this.lastSize={width:m,height:h});let y=typeof this.props[e]==`function`?this.props[e]:null;y&&!(e===`onResize`&&!v)&&(n.persist==null||n.persist(),y(n,{node:i,size:{width:m,height:h},handle:t})),e===`onResizeStop`&&this.resetData()}}renderResizeHandle(e,n){let r=this.props.handle;if(!r)return t.createElement(`span`,{className:`react-resizable-handle react-resizable-handle-`+e,ref:n});if(typeof r==`function`)return r(e,n);let i=typeof r.type==`string`,a=u({ref:n},i?{}:{handleAxis:e});return t.cloneElement(r,a)}render(){let e=this.props,i=e.children,o=e.className,l=e.draggableOpts;e.width,e.height,e.handle,e.handleSize,e.lockAspectRatio,e.axis,e.minConstraints,e.maxConstraints,e.onResize,e.onResizeStop,e.onResizeStart;let d=e.resizeHandles;e.transformScale;let f=c(e,a);return(0,r.cloneElement)(i,u(u({},f),{},{className:(o?o+` `:``)+`react-resizable`,children:[...t.Children.toArray(i.props.children),...d.map(e=>{let r=this.handleRefs[e]??(this.handleRefs[e]=t.createRef());return t.createElement(n.DraggableCore,s({},l,{nodeRef:r,key:`resizableHandle-`+e,onStop:this.resizeHandler(`onResizeStop`,e),onStart:this.resizeHandler(`onResizeStart`,e),onDrag:this.resizeHandler(`onResize`,e)}),this.renderResizeHandle(e,r))})]}))}};e.default=h,h.propTypes=i.resizableProps,h.defaultProps={axis:`both`,handleSize:[20,20],lockAspectRatio:!1,minConstraints:[20,20],maxConstraints:[1/0,1/0],resizeHandles:[`se`],transformScale:1}})),yd=i((e=>{e.__esModule=!0,e.default=void 0;var t=s(d()),n=o(pd()),r=o(vd()),i=_d(),a=[`handle`,`handleSize`,`onResize`,`onResizeStart`,`onResizeStop`,`draggableOpts`,`minConstraints`,`maxConstraints`,`lockAspectRatio`,`axis`,`width`,`height`,`resizeHandles`,`style`,`transformScale`];function o(e){return e&&e.__esModule?e:{default:e}}function s(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(s=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function c(){return c=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c.apply(null,arguments)}function l(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function u(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?l(Object(n),!0).forEach(function(t){f(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):l(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function f(e,t,n){return(t=p(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function p(e){var t=m(e,`string`);return typeof t==`symbol`?t:t+``}function m(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function h(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var g=class extends t.Component{constructor(){super(...arguments),this.state={width:this.props.width,height:this.props.height,propsWidth:this.props.width,propsHeight:this.props.height},this.onResize=(e,t)=>{let n=t.size;this.props.onResize?(e.persist==null||e.persist(),this.setState(n,()=>this.props.onResize&&this.props.onResize(e,t))):this.setState(n)}}static getDerivedStateFromProps(e,t){return t.propsWidth!==e.width||t.propsHeight!==e.height?{width:e.width,height:e.height,propsWidth:e.width,propsHeight:e.height}:null}render(){let e=this.props,n=e.handle,i=e.handleSize;e.onResize;let o=e.onResizeStart,s=e.onResizeStop,l=e.draggableOpts,d=e.minConstraints,f=e.maxConstraints,p=e.lockAspectRatio,m=e.axis;e.width,e.height;let g=e.resizeHandles,_=e.style,v=e.transformScale,y=h(e,a);return t.createElement(r.default,{axis:m,draggableOpts:l,handle:n,handleSize:i,height:this.state.height,lockAspectRatio:p,maxConstraints:f,minConstraints:d,onResizeStart:o,onResize:this.onResize,onResizeStop:s,resizeHandles:g,transformScale:v,width:this.state.width},t.createElement(`div`,c({},y,{style:u(u({},_),{},{width:this.state.width+`px`,height:this.state.height+`px`})})))}};e.default=g,g.propTypes=u(u({},i.resizableProps),{},{children:n.default.element})})),bd=i(((e,t)=>{t.exports=function(){throw Error(`Don't instantiate Resizable directly! Use require('react-resizable').Resizable`)},t.exports.Resizable=vd().default,t.exports.ResizableBox=yd().default})),xd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resizeHandleType=e.resizeHandleAxesType=e.default=void 0;var t=r(pd()),n=r(d());function r(e){return e&&e.__esModule?e:{default:e}}var i=e.resizeHandleAxesType=t.default.arrayOf(t.default.oneOf([`s`,`w`,`e`,`n`,`sw`,`nw`,`se`,`ne`])),a=e.resizeHandleType=t.default.oneOfType([t.default.node,t.default.func]);e.default={className:t.default.string,style:t.default.object,width:t.default.number,autoSize:t.default.bool,cols:t.default.number,draggableCancel:t.default.string,draggableHandle:t.default.string,verticalCompact:function(e){e.verticalCompact},compactType:t.default.oneOf([`vertical`,`horizontal`]),layout:function(e){var t=e.layout;t!==void 0&&ld().validateLayout(t,`layout`)},margin:t.default.arrayOf(t.default.number),containerPadding:t.default.arrayOf(t.default.number),rowHeight:t.default.number,maxRows:t.default.number,isBounded:t.default.bool,isDraggable:t.default.bool,isResizable:t.default.bool,allowOverlap:t.default.bool,preventCollision:t.default.bool,useCSSTransforms:t.default.bool,transformScale:t.default.number,isDroppable:t.default.bool,resizeHandles:i,resizeHandle:a,onLayoutChange:t.default.func,onDragStart:t.default.func,onDrag:t.default.func,onDragStop:t.default.func,onResizeStart:t.default.func,onResize:t.default.func,onResizeStop:t.default.func,onDrop:t.default.func,droppingItem:t.default.shape({i:t.default.string.isRequired,w:t.default.number.isRequired,h:t.default.number.isRequired}),children:function(e,t){let r=e[t],i={};n.default.Children.forEach(r,function(e){if(e?.key!=null){if(i[e.key])throw Error(`Duplicate child key "`+e.key+`" found! This will cause problems in ReactGridLayout.`);i[e.key]=!0}})},innerRef:t.default.any}})),Sd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=f(d()),n=a(),r=f(pd()),i=hd(),o=bd(),s=ld(),c=ud(),l=xd(),u=f(pr());function f(e){return e&&e.__esModule?e:{default:e}}function p(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function m(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?p(Object(n),!0).forEach(function(t){h(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):p(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function h(e,t,n){return(t=g(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function g(e){var t=_(e,`string`);return typeof t==`symbol`?t:t+``}function _(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var v=class extends t.default.Component{constructor(){super(...arguments),h(this,`state`,{resizing:null,dragging:null,className:``}),h(this,`elementRef`,t.default.createRef()),h(this,`onDragStart`,(e,t)=>{let{node:n}=t,{onDragStart:r,transformScale:i}=this.props;if(!r)return;let a={top:0,left:0},{offsetParent:o}=n;if(!o)return;let s=o.getBoundingClientRect(),l=n.getBoundingClientRect(),u=l.left/i,d=s.left/i,f=l.top/i,p=s.top/i;a.left=u-d+o.scrollLeft,a.top=f-p+o.scrollTop,this.setState({dragging:a});let{x:m,y:h}=(0,c.calcXY)(this.getPositionParams(),a.top,a.left,this.props.w,this.props.h);return r.call(this,this.props.i,m,h,{e,node:n,newPosition:a})}),h(this,`onDrag`,(e,t,r)=>{let{node:i,deltaX:a,deltaY:o}=t,{onDrag:s}=this.props;if(!s)return;if(!this.state.dragging)throw Error(`onDrag called before onDragStart.`);let l=this.state.dragging.top+o,u=this.state.dragging.left+a,{isBounded:d,i:f,w:p,h:m,containerWidth:h}=this.props,g=this.getPositionParams();if(d){let{offsetParent:e}=i;if(e){let{margin:t,rowHeight:n}=this.props,r=e.clientHeight-(0,c.calcGridItemWHPx)(m,n,t[1]);l=(0,c.clamp)(l,0,r);let i=(0,c.calcGridColWidth)(g),a=h-(0,c.calcGridItemWHPx)(p,i,t[0]);u=(0,c.clamp)(u,0,a)}}let _={top:l,left:u};r?this.setState({dragging:_}):(0,n.flushSync)(()=>{this.setState({dragging:_})});let{x:v,y}=(0,c.calcXY)(g,l,u,p,m);return s.call(this,f,v,y,{e,node:i,newPosition:_})}),h(this,`onDragStop`,(e,t)=>{let{node:n}=t,{onDragStop:r}=this.props;if(!r)return;if(!this.state.dragging)throw Error(`onDragEnd called before onDragStart.`);let{w:i,h:a,i:o}=this.props,{left:s,top:l}=this.state.dragging,u={top:l,left:s};this.setState({dragging:null});let{x:d,y:f}=(0,c.calcXY)(this.getPositionParams(),l,s,i,a);return r.call(this,o,d,f,{e,node:n,newPosition:u})}),h(this,`onResizeStop`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResizeStop`)),h(this,`onResizeStart`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResizeStart`)),h(this,`onResize`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResize`))}shouldComponentUpdate(e,t){if(this.props.children!==e.children||this.props.droppingPosition!==e.droppingPosition)return!0;let n=(0,c.calcGridItemPosition)(this.getPositionParams(this.props),this.props.x,this.props.y,this.props.w,this.props.h,this.state),r=(0,c.calcGridItemPosition)(this.getPositionParams(e),e.x,e.y,e.w,e.h,t);return!(0,s.fastPositionEqual)(n,r)||this.props.useCSSTransforms!==e.useCSSTransforms}componentDidMount(){this.moveDroppingItem({})}componentDidUpdate(e){this.moveDroppingItem(e)}moveDroppingItem(e){let{droppingPosition:t}=this.props;if(!t)return;let n=this.elementRef.current;if(!n)return;let r=e.droppingPosition||{left:0,top:0},{dragging:i}=this.state,a=i&&t.left!==r.left||t.top!==r.top;if(!i)this.onDragStart(t.e,{node:n,deltaX:t.left,deltaY:t.top});else if(a){let e=t.left-i.left,r=t.top-i.top;this.onDrag(t.e,{node:n,deltaX:e,deltaY:r},!0)}}getPositionParams(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.props;return{cols:e.cols,containerPadding:e.containerPadding,containerWidth:e.containerWidth,margin:e.margin,maxRows:e.maxRows,rowHeight:e.rowHeight}}createStyle(e){let{usePercentages:t,containerWidth:n,useCSSTransforms:r}=this.props,i;return r?i=(0,s.setTransform)(e):(i=(0,s.setTopLeft)(e),t&&(i.left=(0,s.perc)(e.left/n),i.width=(0,s.perc)(e.width/n))),i}mixinDraggable(e,n){return t.default.createElement(i.DraggableCore,{disabled:!n,onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop,handle:this.props.handle,cancel:`.react-resizable-handle`+(this.props.cancel?`,`+this.props.cancel:``),scale:this.props.transformScale,nodeRef:this.elementRef},e)}curryResizeHandler(e,t){return(n,r)=>t(n,r,e)}mixinResizable(e,n,r){let{cols:i,minW:a,minH:s,maxW:l,maxH:u,transformScale:d,resizeHandles:f,resizeHandle:p}=this.props,m=this.getPositionParams(),h=(0,c.calcGridItemPosition)(m,0,0,i,0).width,g=(0,c.calcGridItemPosition)(m,0,0,a,s),_=(0,c.calcGridItemPosition)(m,0,0,l,u),v=[g.width,g.height],y=[Math.min(_.width,h),Math.min(_.height,1/0)];return t.default.createElement(o.Resizable,{draggableOpts:{disabled:!r},className:r?void 0:`react-resizable-hide`,width:n.width,height:n.height,minConstraints:v,maxConstraints:y,onResizeStop:this.curryResizeHandler(n,this.onResizeStop),onResizeStart:this.curryResizeHandler(n,this.onResizeStart),onResize:this.curryResizeHandler(n,this.onResize),transformScale:d,resizeHandles:f,handle:p},e)}onResizeHandler(e,t,r,i){let{node:a,size:o,handle:l}=t,u=this.props[i];if(!u)return;let{x:d,y:f,i:p,maxH:m,minH:h,containerWidth:g}=this.props,{minW:_,maxW:v}=this.props,y=o;a&&(y=(0,s.resizeItemInDirection)(l,r,o,g),(0,n.flushSync)(()=>{this.setState({resizing:i===`onResizeStop`?null:y})}));let{w:b,h:x}=(0,c.calcWH)(this.getPositionParams(),y.width,y.height,d,f,l);b=(0,c.clamp)(b,Math.max(_,1),v),x=(0,c.clamp)(x,h,m),u.call(this,p,b,x,{e,node:a,size:y,handle:l})}render(){let{x:e,y:n,w:r,h:i,isDraggable:a,isResizable:o,droppingPosition:s,useCSSTransforms:l}=this.props,d=(0,c.calcGridItemPosition)(this.getPositionParams(),e,n,r,i,this.state),f=t.default.Children.only(this.props.children),p=t.default.cloneElement(f,{ref:this.elementRef,className:(0,u.default)(`react-grid-item`,f.props.className,this.props.className,{static:this.props.static,resizing:!!this.state.resizing,"react-draggable":a,"react-draggable-dragging":!!this.state.dragging,dropping:!!s,cssTransforms:l}),style:m(m(m({},this.props.style),f.props.style),this.createStyle(d))});return p=this.mixinResizable(p,d,o),p=this.mixinDraggable(p,a),p}};e.default=v,h(v,`propTypes`,{children:r.default.element,cols:r.default.number.isRequired,containerWidth:r.default.number.isRequired,rowHeight:r.default.number.isRequired,margin:r.default.array.isRequired,maxRows:r.default.number.isRequired,containerPadding:r.default.array.isRequired,x:r.default.number.isRequired,y:r.default.number.isRequired,w:r.default.number.isRequired,h:r.default.number.isRequired,minW:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`minWidth not Number`);if(n>e.w||n>e.maxW)return Error(`minWidth larger than item width/maxWidth`)},maxW:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`maxWidth not Number`);if(n<e.w||n<e.minW)return Error(`maxWidth smaller than item width/minWidth`)},minH:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`minHeight not Number`);if(n>e.h||n>e.maxH)return Error(`minHeight larger than item height/maxHeight`)},maxH:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`maxHeight not Number`);if(n<e.h||n<e.minH)return Error(`maxHeight smaller than item height/minHeight`)},i:r.default.string.isRequired,resizeHandles:l.resizeHandleAxesType,resizeHandle:l.resizeHandleType,onDragStop:r.default.func,onDragStart:r.default.func,onDrag:r.default.func,onResizeStop:r.default.func,onResizeStart:r.default.func,onResize:r.default.func,isDraggable:r.default.bool.isRequired,isResizable:r.default.bool.isRequired,isBounded:r.default.bool.isRequired,static:r.default.bool,useCSSTransforms:r.default.bool.isRequired,transformScale:r.default.number,className:r.default.string,handle:r.default.string,cancel:r.default.string,droppingPosition:r.default.shape({e:r.default.object.isRequired,left:r.default.number.isRequired,top:r.default.number.isRequired})}),h(v,`defaultProps`,{className:``,cancel:``,handle:``,minH:1,minW:1,maxH:1/0,maxW:1/0,transformScale:1})})),Cd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=l(d()),n=sd(),r=c(pr()),i=ld(),a=ud(),o=c(Sd()),s=c(xd());function c(e){return e&&e.__esModule?e:{default:e}}function l(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(l=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function u(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function f(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?u(Object(n),!0).forEach(function(t){p(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):u(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function p(e,t,n){return(t=m(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function m(e){var t=h(e,`string`);return typeof t==`symbol`?t:t+``}function h(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var g=`react-grid-layout`,_=!1;try{_=/firefox/i.test(navigator.userAgent)}catch{}var v=class extends t.Component{constructor(){super(...arguments),p(this,`state`,{activeDrag:null,layout:(0,i.synchronizeLayoutWithChildren)(this.props.layout,this.props.children,this.props.cols,(0,i.compactType)(this.props),this.props.allowOverlap),mounted:!1,oldDragItem:null,oldLayout:null,oldResizeItem:null,resizing:!1,droppingDOMNode:null,children:[]}),p(this,`dragEnterCounter`,0),p(this,`onDragStart`,(e,t,n,r)=>{let{e:a,node:o}=r,{layout:s}=this.state,c=(0,i.getLayoutItem)(s,e);if(!c)return;let l={w:c.w,h:c.h,x:c.x,y:c.y,placeholder:!0,i:e};return this.setState({oldDragItem:(0,i.cloneLayoutItem)(c),oldLayout:s,activeDrag:l}),this.props.onDragStart(s,c,c,null,a,o)}),p(this,`onDrag`,(e,t,n,r)=>{let{e:a,node:o}=r,{oldDragItem:s}=this.state,{layout:c}=this.state,{cols:l,allowOverlap:u,preventCollision:d}=this.props,f=(0,i.getLayoutItem)(c,e);if(!f)return;let p={w:f.w,h:f.h,x:f.x,y:f.y,placeholder:!0,i:e};c=(0,i.moveElement)(c,f,t,n,!0,d,(0,i.compactType)(this.props),l,u),this.props.onDrag(c,s,f,p,a,o),this.setState({layout:u?c:(0,i.compact)(c,(0,i.compactType)(this.props),l),activeDrag:p})}),p(this,`onDragStop`,(e,t,n,r)=>{let{e:a,node:o}=r;if(!this.state.activeDrag)return;let{oldDragItem:s}=this.state,{layout:c}=this.state,{cols:l,preventCollision:u,allowOverlap:d}=this.props,f=(0,i.getLayoutItem)(c,e);if(!f)return;c=(0,i.moveElement)(c,f,t,n,!0,u,(0,i.compactType)(this.props),l,d);let p=d?c:(0,i.compact)(c,(0,i.compactType)(this.props),l);this.props.onDragStop(p,s,f,null,a,o);let{oldLayout:m}=this.state;this.setState({activeDrag:null,layout:p,oldDragItem:null,oldLayout:null}),this.onLayoutMaybeChanged(p,m)}),p(this,`onResizeStart`,(e,t,n,r)=>{let{e:a,node:o}=r,{layout:s}=this.state,c=(0,i.getLayoutItem)(s,e);c&&(this.setState({oldResizeItem:(0,i.cloneLayoutItem)(c),oldLayout:this.state.layout,resizing:!0}),this.props.onResizeStart(s,c,c,null,a,o))}),p(this,`onResize`,(e,t,n,r)=>{let{e:a,node:o,size:s,handle:c}=r,{oldResizeItem:l}=this.state,{layout:u}=this.state,{cols:d,preventCollision:p,allowOverlap:m}=this.props,h=!1,g,_,v,[y,b]=(0,i.withLayoutItem)(u,e,e=>{let r;return _=e.x,v=e.y,[`sw`,`w`,`nw`,`n`,`ne`].indexOf(c)!==-1&&([`sw`,`nw`,`w`].indexOf(c)!==-1&&(_=e.x+(e.w-t),t=e.x!==_&&_<0?e.w:t,_=_<0?0:_),[`ne`,`n`,`nw`].indexOf(c)!==-1&&(v=e.y+(e.h-n),n=e.y!==v&&v<0?e.h:n,v=v<0?0:v),h=!0),p&&!m&&(r=(0,i.getAllCollisions)(u,f(f({},e),{},{w:t,h:n,x:_,y:v})).filter(t=>t.i!==e.i).length>0,r&&(v=e.y,n=e.h,_=e.x,t=e.w,h=!1)),e.w=t,e.h=n,e});if(!b)return;g=y,h&&(g=(0,i.moveElement)(y,b,_,v,!0,this.props.preventCollision,(0,i.compactType)(this.props),d,m));let x={w:b.w,h:b.h,x:b.x,y:b.y,static:!0,i:e};this.props.onResize(g,l,b,x,a,o),this.setState({layout:m?g:(0,i.compact)(g,(0,i.compactType)(this.props),d),activeDrag:x})}),p(this,`onResizeStop`,(e,t,n,r)=>{let{e:a,node:o}=r,{layout:s,oldResizeItem:c}=this.state,{cols:l,allowOverlap:u}=this.props,d=(0,i.getLayoutItem)(s,e),f=u?s:(0,i.compact)(s,(0,i.compactType)(this.props),l);this.props.onResizeStop(f,c,d,null,a,o);let{oldLayout:p}=this.state;this.setState({activeDrag:null,layout:f,oldResizeItem:null,oldLayout:null,resizing:!1}),this.onLayoutMaybeChanged(f,p)}),p(this,`onDragOver`,e=>{var n;if(e.preventDefault(),e.stopPropagation(),_&&!((n=e.nativeEvent.target)!=null&&n.classList.contains(g)))return!1;let{droppingItem:r,onDropDragOver:i,margin:o,cols:s,rowHeight:c,maxRows:l,width:u,containerPadding:d,transformScale:p}=this.props,m=i?.(e);if(m===!1)return this.state.droppingDOMNode&&this.removeDroppingPlaceholder(),!1;let h=f(f({},r),m),{layout:v}=this.state,y=e.currentTarget.getBoundingClientRect(),b=e.clientX-y.left,x=e.clientY-y.top,S={left:b/p,top:x/p,e};if(!this.state.droppingDOMNode){let e={cols:s,margin:o,maxRows:l,rowHeight:c,containerWidth:u,containerPadding:d||o},n=(0,a.calcXY)(e,x,b,h.w,h.h);this.setState({droppingDOMNode:t.createElement(`div`,{key:h.i}),droppingPosition:S,layout:[...v,f(f({},h),{},{x:n.x,y:n.y,static:!1,isDraggable:!0})]})}else if(this.state.droppingPosition){let{left:e,top:t}=this.state.droppingPosition;(e!=b||t!=x)&&this.setState({droppingPosition:S})}}),p(this,`removeDroppingPlaceholder`,()=>{let{droppingItem:e,cols:t}=this.props,{layout:n}=this.state,r=(0,i.compact)(n.filter(t=>t.i!==e.i),(0,i.compactType)(this.props),t,this.props.allowOverlap);this.setState({layout:r,droppingDOMNode:null,activeDrag:null,droppingPosition:void 0})}),p(this,`onDragLeave`,e=>{e.preventDefault(),e.stopPropagation(),this.dragEnterCounter--,this.dragEnterCounter===0&&this.removeDroppingPlaceholder()}),p(this,`onDragEnter`,e=>{e.preventDefault(),e.stopPropagation(),this.dragEnterCounter++}),p(this,`onDrop`,e=>{e.preventDefault(),e.stopPropagation();let{droppingItem:t}=this.props,{layout:n}=this.state,r=n.find(e=>e.i===t.i);this.dragEnterCounter=0,this.removeDroppingPlaceholder(),this.props.onDrop(n,r,e)})}componentDidMount(){this.setState({mounted:!0}),this.onLayoutMaybeChanged(this.state.layout,this.props.layout)}static getDerivedStateFromProps(e,t){let r;return t.activeDrag?null:(!(0,n.deepEqual)(e.layout,t.propsLayout)||e.compactType!==t.compactType?r=e.layout:(0,i.childrenEqual)(e.children,t.children)||(r=t.layout),r?{layout:(0,i.synchronizeLayoutWithChildren)(r,e.children,e.cols,(0,i.compactType)(e),e.allowOverlap),compactType:e.compactType,children:e.children,propsLayout:e.layout}:null)}shouldComponentUpdate(e,t){return this.props.children!==e.children||!(0,i.fastRGLPropsEqual)(this.props,e,n.deepEqual)||this.state.activeDrag!==t.activeDrag||this.state.mounted!==t.mounted||this.state.droppingPosition!==t.droppingPosition}componentDidUpdate(e,t){if(!this.state.activeDrag){let e=this.state.layout,n=t.layout;this.onLayoutMaybeChanged(e,n)}}containerHeight(){if(!this.props.autoSize)return;let e=(0,i.bottom)(this.state.layout),t=this.props.containerPadding?this.props.containerPadding[1]:this.props.margin[1];return e*this.props.rowHeight+(e-1)*this.props.margin[1]+t*2+`px`}onLayoutMaybeChanged(e,t){t||=this.state.layout,(0,n.deepEqual)(t,e)||this.props.onLayoutChange(e)}placeholder(){let{activeDrag:e}=this.state;if(!e)return null;let{width:n,cols:r,margin:i,containerPadding:a,rowHeight:s,maxRows:c,useCSSTransforms:l,transformScale:u}=this.props;return t.createElement(o.default,{w:e.w,h:e.h,x:e.x,y:e.y,i:e.i,className:`react-grid-placeholder ${this.state.resizing?`placeholder-resizing`:``}`,containerWidth:n,cols:r,margin:i,containerPadding:a||i,maxRows:c,rowHeight:s,isDraggable:!1,isResizable:!1,isBounded:!1,useCSSTransforms:l,transformScale:u},t.createElement(`div`,null))}processGridItem(e,n){if(!e||!e.key)return;let r=(0,i.getLayoutItem)(this.state.layout,String(e.key));if(!r)return null;let{width:a,cols:s,margin:c,containerPadding:l,rowHeight:u,maxRows:d,isDraggable:f,isResizable:p,isBounded:m,useCSSTransforms:h,transformScale:g,draggableCancel:_,draggableHandle:v,resizeHandles:y,resizeHandle:b}=this.props,{mounted:x,droppingPosition:S}=this.state,C=typeof r.isDraggable==`boolean`?r.isDraggable:!r.static&&f,w=typeof r.isResizable==`boolean`?r.isResizable:!r.static&&p,T=r.resizeHandles||y,E=C&&m&&r.isBounded!==!1;return t.createElement(o.default,{containerWidth:a,cols:s,margin:c,containerPadding:l||c,maxRows:d,rowHeight:u,cancel:_,handle:v,onDragStop:this.onDragStop,onDragStart:this.onDragStart,onDrag:this.onDrag,onResizeStart:this.onResizeStart,onResize:this.onResize,onResizeStop:this.onResizeStop,isDraggable:C,isResizable:w,isBounded:E,useCSSTransforms:h&&x,usePercentages:!x,transformScale:g,w:r.w,h:r.h,x:r.x,y:r.y,i:r.i,minH:r.minH,minW:r.minW,maxH:r.maxH,maxW:r.maxW,static:r.static,droppingPosition:n?S:void 0,resizeHandles:T,resizeHandle:b},e)}render(){let{className:e,style:n,isDroppable:a,innerRef:o}=this.props,s=(0,r.default)(g,e),c=f({height:this.containerHeight()},n);return t.createElement(`div`,{ref:o,className:s,style:c,onDrop:a?this.onDrop:i.noop,onDragLeave:a?this.onDragLeave:i.noop,onDragEnter:a?this.onDragEnter:i.noop,onDragOver:a?this.onDragOver:i.noop},t.Children.map(this.props.children,e=>this.processGridItem(e)),a&&this.state.droppingDOMNode&&this.processGridItem(this.state.droppingDOMNode,!0),this.placeholder())}};e.default=v,p(v,`displayName`,`ReactGridLayout`),p(v,`propTypes`,s.default),p(v,`defaultProps`,{autoSize:!0,cols:12,className:``,style:{},draggableHandle:``,draggableCancel:``,containerPadding:null,rowHeight:150,maxRows:1/0,layout:[],margin:[10,10],isBounded:!1,isDraggable:!0,isResizable:!0,allowOverlap:!1,isDroppable:!1,useCSSTransforms:!0,transformScale:1,verticalCompact:!0,compactType:`vertical`,preventCollision:!1,droppingItem:{i:`__dropping-elem__`,h:1,w:1},resizeHandles:[`se`],onLayoutChange:i.noop,onDragStart:i.noop,onDrag:i.noop,onDragStop:i.noop,onResizeStart:i.noop,onResize:i.noop,onResizeStop:i.noop,onDrop:i.noop,onDropDragOver:i.noop})})),wd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.findOrGenerateResponsiveLayout=i,e.getBreakpointFromWidth=n,e.getColsFromBreakpoint=r,e.sortBreakpoints=a;var t=ld();function n(e,t){let n=a(e),r=n[0];for(let i=1,a=n.length;i<a;i++){let a=n[i];t>e[a]&&(r=a)}return r}function r(e,t){if(!t[e])throw Error("ResponsiveReactGridLayout: `cols` entry for breakpoint "+e+` is missing!`);return t[e]}function i(e,n,r,i,o,s){if(e[r])return(0,t.cloneLayout)(e[r]);let c=e[i],l=a(n),u=l.slice(l.indexOf(r));for(let t=0,n=u.length;t<n;t++){let n=u[t];if(e[n]){c=e[n];break}}return c=(0,t.cloneLayout)(c||[]),(0,t.compact)((0,t.correctBounds)(c,{cols:o}),s,o)}function a(e){return Object.keys(e).sort(function(t,n){return e[t]-e[n]})}})),Td=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=l(d()),n=c(pd()),r=sd(),i=ld(),a=wd(),o=c(Cd()),s=[`breakpoint`,`breakpoints`,`cols`,`layouts`,`margin`,`containerPadding`,`onBreakpointChange`,`onLayoutChange`,`onWidthChange`];function c(e){return e&&e.__esModule?e:{default:e}}function l(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(l=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function u(){return u=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u.apply(null,arguments)}function f(e,t){if(e==null)return{};var n,r,i=p(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function p(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function m(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function h(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?m(Object(n),!0).forEach(function(t){g(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):m(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function g(e,t,n){return(t=_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _(e){var t=v(e,`string`);return typeof t==`symbol`?t:t+``}function v(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var y=e=>Object.prototype.toString.call(e);function b(e,t){return e==null?null:Array.isArray(e)?e:e[t]}var x=class extends t.Component{constructor(){super(...arguments),g(this,`state`,this.generateInitialState()),g(this,`onLayoutChange`,e=>{this.props.onLayoutChange(e,h(h({},this.props.layouts),{},{[this.state.breakpoint]:e}))})}generateInitialState(){let{width:e,breakpoints:t,layouts:n,cols:r}=this.props,i=(0,a.getBreakpointFromWidth)(t,e),o=(0,a.getColsFromBreakpoint)(i,r),s=this.props.verticalCompact===!1?null:this.props.compactType;return{layout:(0,a.findOrGenerateResponsiveLayout)(n,t,i,i,o,s),breakpoint:i,cols:o}}static getDerivedStateFromProps(e,t){if(!(0,r.deepEqual)(e.layouts,t.layouts)){let{breakpoint:n,cols:r}=t;return{layout:(0,a.findOrGenerateResponsiveLayout)(e.layouts,e.breakpoints,n,n,r,e.compactType),layouts:e.layouts}}return null}componentDidUpdate(e){(this.props.width!=e.width||this.props.breakpoint!==e.breakpoint||!(0,r.deepEqual)(this.props.breakpoints,e.breakpoints)||!(0,r.deepEqual)(this.props.cols,e.cols))&&this.onWidthChange(e)}onWidthChange(e){let{breakpoints:t,cols:n,layouts:r,compactType:o}=this.props,s=this.props.breakpoint||(0,a.getBreakpointFromWidth)(this.props.breakpoints,this.props.width),c=this.state.breakpoint,l=(0,a.getColsFromBreakpoint)(s,n),u=h({},r);if(c!==s||e.breakpoints!==t||e.cols!==n){c in u||(u[c]=(0,i.cloneLayout)(this.state.layout));let e=(0,a.findOrGenerateResponsiveLayout)(u,t,s,c,l,o);e=(0,i.synchronizeLayoutWithChildren)(e,this.props.children,l,o,this.props.allowOverlap),u[s]=e,this.props.onBreakpointChange(s,l),this.props.onLayoutChange(e,u),this.setState({breakpoint:s,layout:e,cols:l})}let d=b(this.props.margin,s),f=b(this.props.containerPadding,s);this.props.onWidthChange(this.props.width,d,l,f)}render(){let e=this.props,{breakpoint:n,breakpoints:r,cols:i,layouts:a,margin:c,containerPadding:l,onBreakpointChange:d,onLayoutChange:p,onWidthChange:m}=e,h=f(e,s);return t.createElement(o.default,u({},h,{margin:b(c,this.state.breakpoint),containerPadding:b(l,this.state.breakpoint),onLayoutChange:this.onLayoutChange,layout:this.state.layout,cols:this.state.cols}))}};e.default=x,g(x,`propTypes`,{breakpoint:n.default.string,breakpoints:n.default.object,allowOverlap:n.default.bool,cols:n.default.object,margin:n.default.oneOfType([n.default.array,n.default.object]),containerPadding:n.default.oneOfType([n.default.array,n.default.object]),layouts(e,t){if(y(e[t])!==`[object Object]`)throw Error(`Layout property must be an object. Received: `+y(e[t]));Object.keys(e[t]).forEach(t=>{if(!(t in e.breakpoints))throw Error(`Each key in layouts must align with a key in breakpoints.`);(0,i.validateLayout)(e.layouts[t],`layouts.`+t)})},width:n.default.number.isRequired,onBreakpointChange:n.default.func,onLayoutChange:n.default.func,onWidthChange:n.default.func}),g(x,`defaultProps`,{breakpoints:{lg:1200,md:996,sm:768,xs:480,xxs:0},cols:{lg:12,md:10,sm:6,xs:4,xxs:2},containerPadding:{lg:null,md:null,sm:null,xs:null,xxs:null},layouts:{},margin:[10,10],allowOverlap:!1,onBreakpointChange:i.noop,onLayoutChange:i.noop,onWidthChange:i.noop})})),Ed=r({default:()=>tf});function Dd(e,t){var n=!1,r=!1,i=0;function a(){n&&(n=!1,e()),r&&s()}function o(){Bd(a)}function s(){var e=Date.now();if(n){if(e-i<Vd)return;r=!0}else n=!0,r=!1,setTimeout(o,t);i=e}return s}function Od(e){return parseFloat(e)||0}function kd(e){return[...arguments].slice(1).reduce(function(t,n){var r=e[`border-`+n+`-width`];return t+Od(r)},0)}function Ad(e){for(var t=[`top`,`right`,`bottom`,`left`],n={},r=0,i=t;r<i.length;r++){var a=i[r],o=e[`padding-`+a];n[a]=Od(o)}return n}function jd(e){var t=e.getBBox();return Id(0,0,t.width,t.height)}function Md(e){var t=e.clientWidth,n=e.clientHeight;if(!t&&!n)return Jd;var r=qd(e).getComputedStyle(e),i=Ad(r),a=i.left+i.right,o=i.top+i.bottom,s=Od(r.width),c=Od(r.height);if(r.boxSizing===`border-box`&&(Math.round(s+a)!==t&&(s-=kd(r,`left`,`right`)+a),Math.round(c+o)!==n&&(c-=kd(r,`top`,`bottom`)+o)),!Nd(e)){var l=Math.round(s+a)-t,u=Math.round(c+o)-n;Math.abs(l)!==1&&(s-=l),Math.abs(u)!==1&&(c-=u)}return Id(i.left,i.top,s,c)}function Nd(e){return e===qd(e).document.documentElement}function Pd(e){return Rd?Yd(e)?jd(e):Md(e):Jd}function Fd(e){var t=e.x,n=e.y,r=e.width,i=e.height,a=Object.create((typeof DOMRectReadOnly<`u`?DOMRectReadOnly:Object).prototype);return Kd(a,{x:t,y:n,width:r,height:i,top:n,right:t+r,bottom:i+n,left:t}),a}function Id(e,t,n,r){return{x:e,y:t,width:n,height:r}}var Ld,Rd,zd,Bd,Vd,Hd,Ud,Wd,Gd,Kd,qd,Jd,Yd,Xd,Zd,Qd,$d,ef,tf,nf=t((()=>{Ld=(function(){if(typeof Map<`u`)return Map;function e(e,t){var n=-1;return e.some(function(e,r){return e[0]===t&&(n=r,!0)}),n}return function(){function t(){this.__entries__=[]}return Object.defineProperty(t.prototype,"size",{get:function(){return this.__entries__.length},enumerable:!0,configurable:!0}),t.prototype.get=function(t){var n=e(this.__entries__,t),r=this.__entries__[n];return r&&r[1]},t.prototype.set=function(t,n){var r=e(this.__entries__,t);~r?this.__entries__[r][1]=n:this.__entries__.push([t,n])},t.prototype.delete=function(t){var n=this.__entries__,r=e(n,t);~r&&n.splice(r,1)},t.prototype.has=function(t){return!!~e(this.__entries__,t)},t.prototype.clear=function(){this.__entries__.splice(0)},t.prototype.forEach=function(e,t){t===void 0&&(t=null);for(var n=0,r=this.__entries__;n<r.length;n++){var i=r[n];e.call(t,i[1],i[0])}},t}()})(),Rd=typeof window<`u`&&typeof document<`u`&&window.document===document,zd=(function(){return typeof global<`u`&&global.Math===Math?global:typeof self<`u`&&self.Math===Math?self:typeof window<`u`&&window.Math===Math?window:Function(`return this`)()})(),Bd=(function(){return typeof requestAnimationFrame==`function`?requestAnimationFrame.bind(zd):function(e){return setTimeout(function(){return e(Date.now())},1e3/60)}})(),Vd=2,Hd=20,Ud=[`top`,`right`,`bottom`,`left`,`width`,`height`,`size`,`weight`],Wd=typeof MutationObserver<`u`,Gd=function(){function e(){this.connected_=!1,this.mutationEventsAdded_=!1,this.mutationsObserver_=null,this.observers_=[],this.onTransitionEnd_=this.onTransitionEnd_.bind(this),this.refresh=Dd(this.refresh.bind(this),Hd)}return e.prototype.addObserver=function(e){~this.observers_.indexOf(e)||this.observers_.push(e),this.connected_||this.connect_()},e.prototype.removeObserver=function(e){var t=this.observers_,n=t.indexOf(e);~n&&t.splice(n,1),!t.length&&this.connected_&&this.disconnect_()},e.prototype.refresh=function(){this.updateObservers_()&&this.refresh()},e.prototype.updateObservers_=function(){var e=this.observers_.filter(function(e){return e.gatherActive(),e.hasActive()});return e.forEach(function(e){return e.broadcastActive()}),e.length>0},e.prototype.connect_=function(){!Rd||this.connected_||(document.addEventListener(`transitionend`,this.onTransitionEnd_),window.addEventListener(`resize`,this.refresh),Wd?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener(`DOMSubtreeModified`,this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},e.prototype.disconnect_=function(){!Rd||!this.connected_||(document.removeEventListener(`transitionend`,this.onTransitionEnd_),window.removeEventListener(`resize`,this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener(`DOMSubtreeModified`,this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},e.prototype.onTransitionEnd_=function(e){var t=e.propertyName,n=t===void 0?``:t;Ud.some(function(e){return!!~n.indexOf(e)})&&this.refresh()},e.getInstance=function(){return this.instance_||=new e,this.instance_},e.instance_=null,e}(),Kd=(function(e,t){for(var n=0,r=Object.keys(t);n<r.length;n++){var i=r[n];Object.defineProperty(e,i,{value:t[i],enumerable:!1,writable:!1,configurable:!0})}return e}),qd=(function(e){return e&&e.ownerDocument&&e.ownerDocument.defaultView||zd}),Jd=Id(0,0,0,0),Yd=(function(){return typeof SVGGraphicsElement<`u`?function(e){return e instanceof qd(e).SVGGraphicsElement}:function(e){return e instanceof qd(e).SVGElement&&typeof e.getBBox==`function`}})(),Xd=function(){function e(e){this.broadcastWidth=0,this.broadcastHeight=0,this.contentRect_=Id(0,0,0,0),this.target=e}return e.prototype.isActive=function(){var e=Pd(this.target);return this.contentRect_=e,e.width!==this.broadcastWidth||e.height!==this.broadcastHeight},e.prototype.broadcastRect=function(){var e=this.contentRect_;return this.broadcastWidth=e.width,this.broadcastHeight=e.height,e},e}(),Zd=function(){function e(e,t){var n=Fd(t);Kd(this,{target:e,contentRect:n})}return e}(),Qd=function(){function e(e,t,n){if(this.activeObservations_=[],this.observations_=new Ld,typeof e!=`function`)throw TypeError(`The callback provided as parameter 1 is not a function.`);this.callback_=e,this.controller_=t,this.callbackCtx_=n}return e.prototype.observe=function(e){if(!arguments.length)throw TypeError(`1 argument required, but only 0 present.`);if(!(typeof Element>`u`||!(Element instanceof Object))){if(!(e instanceof qd(e).Element))throw TypeError(`parameter 1 is not of type "Element".`);var t=this.observations_;t.has(e)||(t.set(e,new Xd(e)),this.controller_.addObserver(this),this.controller_.refresh())}},e.prototype.unobserve=function(e){if(!arguments.length)throw TypeError(`1 argument required, but only 0 present.`);if(!(typeof Element>`u`||!(Element instanceof Object))){if(!(e instanceof qd(e).Element))throw TypeError(`parameter 1 is not of type "Element".`);var t=this.observations_;t.has(e)&&(t.delete(e),t.size||this.controller_.removeObserver(this))}},e.prototype.disconnect=function(){this.clearActive(),this.observations_.clear(),this.controller_.removeObserver(this)},e.prototype.gatherActive=function(){var e=this;this.clearActive(),this.observations_.forEach(function(t){t.isActive()&&e.activeObservations_.push(t)})},e.prototype.broadcastActive=function(){if(this.hasActive()){var e=this.callbackCtx_,t=this.activeObservations_.map(function(e){return new Zd(e.target,e.broadcastRect())});this.callback_.call(e,t,e),this.clearActive()}},e.prototype.clearActive=function(){this.activeObservations_.splice(0)},e.prototype.hasActive=function(){return this.activeObservations_.length>0},e}(),$d=typeof WeakMap<`u`?new WeakMap:new Ld,ef=function(){function e(t){if(!(this instanceof e))throw TypeError(`Cannot call a class as a function.`);if(!arguments.length)throw TypeError(`1 argument required, but only 0 present.`);var n=new Qd(t,Gd.getInstance(),this);$d.set(this,n)}return e}(),[`observe`,`unobserve`,`disconnect`].forEach(function(e){ef.prototype[e]=function(){var t;return(t=$d.get(this))[e].apply(t,arguments)}}),tf=(function(){return zd.ResizeObserver===void 0?ef:zd.ResizeObserver})()})),rf=i((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=_;var n=c(d()),r=s(pd()),i=s((nf(),e(Ed))),a=s(pr()),o=[`measureBeforeMount`];function s(e){return e&&e.__esModule?e:{default:e}}function c(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(c=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function l(){return l=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l.apply(null,arguments)}function u(e,t){if(e==null)return{};var n,r,i=f(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function f(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function p(e,t,n){return(t=m(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function m(e){var t=h(e,`string`);return typeof t==`symbol`?t:t+``}function h(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var g=`react-grid-layout`;function _(e){var t;return t=class extends n.Component{constructor(){super(...arguments),p(this,`state`,{width:1280}),p(this,`elementRef`,n.createRef()),p(this,`mounted`,!1),p(this,`resizeObserver`,void 0)}componentDidMount(){this.mounted=!0,this.resizeObserver=new i.default(e=>{if(this.elementRef.current instanceof HTMLElement){let t=e[0].contentRect.width;this.setState({width:t})}});let e=this.elementRef.current;e instanceof HTMLElement&&this.resizeObserver.observe(e)}componentWillUnmount(){this.mounted=!1;let e=this.elementRef.current;e instanceof HTMLElement&&this.resizeObserver.unobserve(e),this.resizeObserver.disconnect()}render(){let t=this.props,{measureBeforeMount:r}=t,i=u(t,o);return r&&!this.mounted?n.createElement(`div`,{className:(0,a.default)(this.props.className,g),style:this.props.style,ref:this.elementRef}):n.createElement(e,l({innerRef:this.elementRef},i,this.state))}},p(t,`defaultProps`,{measureBeforeMount:!1}),p(t,`propTypes`,{measureBeforeMount:r.default.bool}),t}})),af=n(i(((e,t)=>{t.exports=Cd().default,t.exports.utils=ld(),t.exports.calculateUtils=ud(),t.exports.Responsive=Td().default,t.exports.Responsive.utils=wd(),t.exports.WidthProvider=rf().default}))(),1),of=new Map;function sf(e){of.set(e.type,e)}function cf(e){return of.get(e)}function lf(){return[...of.values()]}function uf(){let e,t,n=!1,r=()=>{clearTimeout(e),e=void 0,t=void 0};return{cancel:r,start(i,a,o){r(),n=!1,t={x:i,y:a},e=setTimeout(()=>{e=void 0,n=!0,o()},500)},move(e,n){t&&Math.hypot(e-t.x,n-t.y)>10&&r()},consumeClick(){let e=n;return n=!1,e},contextMenu(){let e=n;return t&&(n=!0),r(),e},reset(){r(),n=!1}}}function df(){let[e]=(0,X.useState)(uf);return(0,X.useEffect)(()=>e.cancel,[e]),{onPointerDown:t=>{if(e.reset(),t.pointerType!==`touch`||!t.isPrimary)return;let n=t.target;if(!t.currentTarget.contains(n)||n.closest(`button, input, textarea, select, a, [contenteditable="true"], [role="dialog"]`))return;let{clientX:r,clientY:i}=t;e.start(r,i,()=>{n.dispatchEvent(new window.MouseEvent(`contextmenu`,{bubbles:!0,cancelable:!0,clientX:r,clientY:i}))})},onPointerMove:t=>e.move(t.clientX,t.clientY),onPointerUp:e.cancel,onPointerCancel:e.cancel,onPointerLeave:e.cancel,onDragStartCapture:t=>{e.cancel(),e.consumeClick()&&t.preventDefault()},onContextMenuCapture:t=>{t.isTrusted&&e.contextMenu()&&(t.preventDefault(),t.stopPropagation())},onClickCapture:t=>{e.consumeClick()&&(t.preventDefault(),t.stopPropagation())}}}function ff(e,t,n,r,i=!1){let a=e.indexOf(n);if(a<0)return new Set(r);let o=t===null?-1:e.indexOf(t),s=o<0?a:o,c=i?new Set(r):new Set;for(let t of e.slice(Math.min(s,a),Math.max(s,a)+1))c.add(t);return c}var pf=n(a(),1),mf=[];function hf(e){if(e.key!==`Escape`||e.isComposing||e.defaultPrevented)return;let t=mf[mf.length-1];t&&(e.preventDefault(),t())}function gf(e,t=!0){let n=(0,X.useRef)(e);(0,X.useEffect)(()=>{n.current=e});let r=t&&!!e;(0,X.useEffect)(()=>{if(!r)return;let e=()=>n.current?.();return mf.push(e),mf.length===1&&window.addEventListener(`keydown`,hf),()=>{let t=mf.indexOf(e);t>=0&&mf.splice(t,1),mf.length===0&&window.removeEventListener(`keydown`,hf)}},[r])}function _f({x:e,y:t,onClose:n,className:r,children:i}){let a=(0,X.useRef)(null),[o,s]=(0,X.useState)({x:e,y:t});return gf(n),(0,X.useLayoutEffect)(()=>{let n=a.current;if(!n)return;let{width:r,height:i}=n.getBoundingClientRect();s({x:Math.max(8,Math.min(e,window.innerWidth-r-8)),y:Math.max(8,Math.min(t,window.innerHeight-i-8))})},[e,t]),(0,pf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-menu-scrim`,onClick:n,onContextMenu:e=>{e.preventDefault(),n()}}),(0,Z.jsx)(`div`,{ref:a,style:{left:o.x,top:o.y},className:K(`fixed z-menu max-h-viewport-modal overflow-y-auto`,r),children:i})]}),document.body)}var vf=null;function yf(){return vf||=fetch(`https://api.iconify.design/collection?prefix=ph`).then(e=>e.json()).then(e=>[...e.uncategorized??[],...Object.values(e.categories??{}).flat()].filter(e=>e.endsWith(`-fill`)).map(e=>`ph:${e}`)).catch(()=>(vf=null,[])),vf}async function bf(e,t=120){let n=e.trim();if(!n)return[];try{let e=await(await fetch(`https://api.iconify.design/search?query=${encodeURIComponent(n)}&limit=${t}`)).json();return Array.isArray(e.icons)?e.icons:[]}catch{return[]}}var xf=[`#ef4444`,`#f97316`,`#f59e0b`,`#eab308`,`#84cc16`,`#22c55e`,`#14b8a6`,`#06b6d4`,`#3b82f6`,`#6366f1`,`#8b5cf6`,`#a855f7`,`#ec4899`,`#f43f5e`,`#64748b`,`#78716c`],Sf={home:{icon:`ph:house-fill`,color:`#3b82f6`},travel:{icon:`ph:airplane-tilt-fill`,color:`#06b6d4`},work:{icon:`ph:briefcase-fill`,color:`#64748b`},books:{icon:`ph:books-fill`,color:`#a855f7`},workouts:{icon:`ph:barbell-fill`,color:`#22c55e`},sport:{icon:`ph:barbell-fill`,color:`#22c55e`},sports:{icon:`ph:barbell-fill`,color:`#22c55e`},fitness:{icon:`ph:barbell-fill`,color:`#22c55e`},beauty:{icon:`ph:flower-lotus-fill`,color:`#ec4899`},recipes:{icon:`ph:cooking-pot-fill`,color:`#f97316`},"to watch":{icon:`ph:monitor-play-fill`,color:`#f43f5e`},"to read":{icon:`ph:book-open-text-fill`,color:`#8b5cf6`},learning:{icon:`ph:graduation-cap-fill`,color:`#6366f1`},tech:{icon:`ph:cpu-fill`,color:`#14b8a6`},music:{icon:`ph:music-notes-fill`,color:`#eab308`},finance:{icon:`ph:piggy-bank-fill`,color:`#84cc16`},shopping:{icon:`ph:shopping-cart-fill`,color:`#f59e0b`},ideas:{icon:`ph:lightbulb-filament-fill`,color:`#facc15`},data:{icon:`ph:database-fill`,color:`#14b8a6`}},Cf={"workspace:home":{icon:`ph:house-fill`,color:`#3b82f6`},"workspace:data":{icon:`ph:database-fill`,color:`#14b8a6`}},wf={file:{icon:`ph:folder-fill`,color:`#64748b`},cacache:{icon:`ph:database-fill`,color:`#14b8a6`},s3:{icon:`ph:cloud-fill`,color:`#0ea5e9`},gdrive:{icon:`mdi:google-drive`,color:`#fbbc04`},http:{icon:`ph:globe-fill`,color:`#0ea5e9`},imap:{icon:`ph:envelope-fill`,color:`#a855f7`}},Tf={icon:`ph:hard-drive-fill`,color:`#64748b`};function Ef(e){let t=e.config?.ui??{},n=e.address&&Cf[e.address]||e.driver&&wf[e.driver]||Tf;return{icon:typeof t.icon==`string`?t.icon:n.icon??Tf.icon,color:typeof t.color==`string`?t.color:n.color??Tf.color}}function Df(e){let t=e.metadata?.ui??{},n=Sf[String(e.label??e.name??``).trim().toLowerCase()];return{icon:typeof t.icon==`string`?t.icon:n?.icon,color:typeof t.color==`string`?t.color:e.color??n?.color}}function Of(e){let t=Sf[(e.split(`/`).filter(Boolean).pop()??``).trim().toLowerCase()];return t?{metadata:kf(void 0,t)}:null}function kf(e,t){let n={...e??{}},r={...n.ui??{}};return`icon`in t&&(t.icon?r.icon=t.icon:delete r.icon),`color`in t&&(t.color?r.color=t.color:delete r.color),n.ui=r,n}var Af=(e,t)=>Math.floor(Math.random()*(t-e+1))+e,jf=()=>({h:Af(0,360),s:Af(42,98),l:Af(40,90)}),Mf=(e,t,n)=>{t/=100,n/=100;let r=(1-Math.abs(2*n-1))*t,i=r*(1-Math.abs(e/60%2-1)),a=n-r/2,o=0,s=0,c=0;0<=e&&e<60?(o=r,s=i):60<=e&&e<120?(o=i,s=r):120<=e&&e<180?(s=r,c=i):180<=e&&e<240?(s=i,c=r):240<=e&&e<300?(o=i,c=r):300<=e&&e<360&&(o=r,c=i),o=Math.round((o+a)*255),s=Math.round((s+a)*255),c=Math.round((c+a)*255);let l=e=>e.toString(16).padStart(2,`0`);return`#${l(o)}${l(s)}${l(c)}`},Nf=()=>{let{h:e,s:t,l:n}=jf();return Mf(e,t,n)},Pf=e=>{let t=e.trim().match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);if(!t)return null;let n=t[1];n.length===3&&(n=n.split(``).map(e=>e+e).join(``));let r=e=>{let t=parseInt(n.slice(e*2,e*2+2),16)/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4};return .2126*r(0)+.7152*r(1)+.0722*r(2)},Ff=(e,t=.82)=>{let n=Pf(e);return n===null||n>t},If=e=>e&&!Ff(e)?e:void 0,Lf=e=>{if(!e)return`text-muted-foreground/70`;let t=Pf(e);return t!==null&&t>.5?`text-black/45`:`text-white/80`},Rf=e=>{let t=Pf(e);return t!==null&&t>.45?`text-black`:`text-white`},zf=[{color:`text-data-1`,chip:`bg-data-1/15`},{color:`text-data-2`,chip:`bg-data-2/15`},{color:`text-data-3`,chip:`bg-data-3/15`},{color:`text-data-4`,chip:`bg-data-4/15`},{color:`text-data-5`,chip:`bg-data-5/15`},{color:`text-data-6`,chip:`bg-data-6/15`},{color:`text-data-7`,chip:`bg-data-7/15`},{color:`text-data-8`,chip:`bg-data-8/15`},{color:`text-data-9`,chip:`bg-data-9/15`},{color:`text-data-10`,chip:`bg-data-10/15`},{color:`text-data-11`,chip:`bg-data-11/15`},{color:`text-data-12`,chip:`bg-data-12/15`}];function Bf(e,t){return{Icon:e,...zf[t-1]}}var Vf={tab:Bf(C,7),link:Bf(C,7),email:Bf(vt,3),note:Bf(vn,3),task:Bf(Sn,5),message:Bf(ft,6),identity:Bf(Ze,2),contact:Bf(Ze,2),device:Bf(kn,10),application:Bf(Ke,11),dotfile:Bf(Yt,4),document:Bf(_n,9)},Hf=[{test:/^image\//,spec:Bf(rn,5)},{test:/^video\//,spec:Bf(Ft,11)},{test:/^audio\//,spec:Bf(et,10)},{test:/pdf$/,spec:Bf(_n,1)},{test:/zip|tar|gzip|7z|rar|compressed/,spec:Bf(In,12)},{test:/json|javascript|typescript|xml|html|css|x-sh|python/,spec:Bf(xn,6)},{test:/^text\//,spec:Bf(_n,12)}],Uf=Bf(Bn,6),Wf=Bf(Bn,9);function Gf(e){let t=(e.schema||``).split(`/`).pop()||``;if(t===`file`){let t=String(e.metadata?.contentType||``).toLowerCase();return Hf.find(({test:e})=>e.test(t))?.spec||Uf}return Vf[t]||Wf}var Kf={3.5:`h-3.5 w-3.5`,4:`h-4 w-4`,5:`h-5 w-5`,10:`h-10 w-10`};function qf(e){let t=[],n=typeof e?.favIconUrl==`string`?e.favIconUrl:``;/^https?:\/\//i.test(n)&&t.push(n);let r=typeof e?.url==`string`?e.url:``;try{let e=new URL(r).origin;if(/^https?:/i.test(e)){let n=`${e}/favicon.ico`;t.includes(n)||t.push(n)}}catch{}return t}function Jf({document:e,size:t=4,chip:n=!1,className:r}){let i=Gf(e),a=e.schema===`data/schema/tab`?qf(e.data):[],[o,s]=(0,X.useState)(0),c=a[o]??null,l=c?(0,Z.jsx)(`img`,{src:c,alt:``,loading:`lazy`,onError:()=>s(e=>e+1),className:K(Kf[t],`rounded-xs object-contain`,!n&&`shrink-0`,!n&&r)}):(0,Z.jsx)(i.Icon,{className:K(Kf[t],i.color,!n&&`shrink-0`,!n&&r)});return n?(0,Z.jsx)(`span`,{className:K(`inline-flex shrink-0 items-center justify-center rounded-md`,t>=10?`p-3`:`p-1`,i.chip,r),children:l}):l}var Yf={context:(0,Z.jsx)(Je,{className:`h-3.5 w-3.5`}),directory:(0,Z.jsx)(L,{className:`h-3.5 w-3.5`}),backends:(0,Z.jsx)(_e,{className:`h-3.5 w-3.5`}),relations:(0,Z.jsx)(Tn,{className:`h-3.5 w-3.5`})},Xf={context:`Context tree`,directory:`Directory tree`,backends:`Backends tree`,relations:`Relations`};function Zf(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function Qf(e,t){let n=(0,X.useRef)(null),r=(0,X.useRef)(!1),i=()=>{n.current&&=(clearTimeout(n.current),null)},a=e=>()=>{if(r.current){r.current=!1;return}e()};return t?{guardClick:a,handlers:{onContextMenu:n=>{n.preventDefault(),n.stopPropagation(),t({clientX:n.clientX,clientY:n.clientY,path:e})},onPointerDown:a=>{if(a.pointerType!==`touch`)return;let{clientX:o,clientY:s}=a;i(),n.current=setTimeout(()=>{r.current=!0,t({clientX:o,clientY:s,path:e})},500)},onPointerUp:i,onPointerLeave:i,onPointerMove:i}}:{handlers:{},guardClick:a}}function $f(e,t,n){let r=Zf(t,e.name);return r.toLowerCase().includes(n)||(e.label||``).toLowerCase().includes(n)?!0:e.children?.some(e=>$f(e,r,n))??!1}var ep=200;function tp({onConfirm:e,onCancel:t,busy:n}){let[r,i]=(0,X.useState)(``);return(0,Z.jsxs)(`div`,{className:`flex min-h-11 items-center gap-2 rounded-md bg-card px-3 py-2.5 text-sm shadow-elevation-1`,children:[(0,Z.jsx)(or,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`input`,{type:`text`,value:r,onChange:e=>i(e.target.value),onKeyDown:n=>{n.key===`Enter`&&r.trim()&&e(r.trim()),n.key===`Escape`&&t()},onBlur:()=>{n||t()},placeholder:`New folder name…`,autoFocus:!0,disabled:n,className:`w-full flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground`}),n&&(0,Z.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:`Creating…`})]})}function np({node:e,parentPath:t,query:n,selected:r,onToggle:i,onActivate:a,onRowMenu:o,createParent:s,onCreateConfirm:l,onCreateCancel:u,creating:d}){let f=Zf(t,e.name),p=!!e.children?.length,[m,h]=(0,X.useState)(!1),{handlers:g,guardClick:_}=Qf(f,o);if(n&&!$f(e,t,n))return null;let v=s===f,y=m||n.length>0||v,b=r.has(f),x=e.type===`canvas`,S=Df(e);return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:K(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none text-sm shadow-elevation-1 hover:shadow`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,b?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:_(()=>i(f)),onDoubleClick:a?()=>a(f):void 0,title:f,...g,children:[(0,Z.jsx)(`button`,{type:`button`,className:K(`shrink-0 text-muted-foreground hover:text-foreground`,!p&&`invisible`),onClick:e=>{e.stopPropagation(),h(e=>!e)},children:y?(0,Z.jsx)(Ne,{className:`w-4 h-4`}):(0,Z.jsx)(B,{className:`w-4 h-4`})}),(0,Z.jsx)(c,{icon:S.icon||(x?`ph:squares-four-fill`:`ph:folder-fill`),width:16,height:16,color:If(S.color),className:K(`shrink-0`,!If(S.color)&&(x?`text-primary`:`text-muted-foreground`))}),(0,Z.jsx)(`span`,{className:`flex-1 truncate font-medium`,title:e.description||void 0,children:e.label||e.name})]}),y&&p||v?(0,Z.jsxs)(`div`,{className:`ml-[22px] mt-1.5 space-y-1.5`,children:[v&&l&&u&&(0,Z.jsx)(tp,{busy:d,onConfirm:e=>{h(!0),l(f,e)},onCancel:u}),y&&e.children?.map(e=>(0,Z.jsx)(np,{node:e,parentPath:f,query:n,selected:r,onToggle:i,onActivate:a,onRowMenu:o,createParent:s,onCreateConfirm:l,onCreateCancel:u,creating:d},e.id||e.name))]}):null]})}function rp({workspaces:e,loading:t,onPick:n}){return t&&e.length===0?(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):e.length===0?(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`No workspaces found`}):(0,Z.jsx)(`div`,{className:`space-y-1.5`,children:e.map(e=>{let t=If(e.color);return(0,Z.jsxs)(`div`,{onClick:()=>n(e.name),className:`group relative flex cursor-pointer items-center gap-2 rounded-md bg-card px-3 py-2.5 shadow-elevation-1 transition-all hover:bg-accent/50 hover:shadow`,style:{borderRight:`6px solid ${t||`transparent`}`,borderRadius:t?`6px 0 0 6px`:void 0},children:[(0,Z.jsx)(c,{icon:e.icon||`ph:stack-fill`,width:18,height:18,color:t,className:K(`shrink-0`,!t&&`text-muted-foreground`)}),(0,Z.jsx)(`span`,{className:`flex-1 truncate text-sm font-medium`,children:e.label||e.name}),(0,Z.jsx)(B,{className:`h-4 w-4 shrink-0 text-muted-foreground`})]},e.id||e.name)})})}function ip({workspaceName:e,treeTab:t,onTreeTabChange:n,selectedDocIds:r,onToggleDoc:i,onNavigate:a,excludeDocumentIds:o}){let[s,c]=(0,X.useState)(`folder`),[l,u]=(0,X.useState)(``),d=l.trim().toLowerCase(),[f,p]=(0,X.useState)(`/`),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)([]),[b,x]=(0,X.useState)(!1),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(``),[E,D]=(0,X.useState)(t),O=n?t:E,k=e=>{p(`/`),c(`folder`),C(``),T(``),a?.(`/`),n?n(e):D(e)},[A,j]=(0,X.useState)(O);O!==A&&(j(O),p(`/`),c(`folder`)),(0,X.useEffect)(()=>{let e=setTimeout(()=>T(S.trim()),300);return()=>clearTimeout(e)},[S]),(0,X.useEffect)(()=>{let t=!1;async function n(){_(!0);try{let n=await fi(e,O);t||h(n)}catch{t||h(null)}finally{t||_(!1)}}return n(),()=>{t=!0}},[e,O]),(0,X.useEffect)(()=>{if(s!==`documents`)return;let t=!1,n=O===`directory`?`directory`:Da,r=O===`context`?`context`:`directory`;async function i(){x(!0);try{let i=w?await Bi(e,f,[],{treeName:n,treeType:r,q:w,limit:ep}):await gi(e,f,n,{limit:ep});t||y(i.payload||[])}catch{t||y([])}finally{t||x(!1)}}return i(),()=>{t=!0}},[e,O,f,s,w]);let M=e=>`${O===`directory`?`dir`:`ctx`}://${e.replace(/^\/+/,``)}`,N=e=>{p(e),a?.(e)},P=o?.size?v.filter(e=>!o.has(e.id)):v;return s===`folder`?(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-muted/30 px-3 py-2`,children:[!n&&(0,Z.jsx)(`div`,{className:`flex items-center gap-1 rounded-md border border-input p-0.5`,children:[`context`,`directory`].map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>k(e),className:K(`flex flex-1 items-center justify-center gap-1.5 rounded px-2 py-1 text-xs transition-colors`,O===e?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Browse the ${Xf[e].toLowerCase()}`,children:[Yf[e],(0,Z.jsx)(`span`,{className:`font-mono`,children:e===`directory`?`dir://`:`ctx://`})]},e))}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Step 1 of 2 · Pick a folder`}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>c(`documents`),className:`inline-flex items-center gap-1 rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground transition-opacity hover:opacity-90`,children:[`Next `,(0,Z.jsx)(B,{className:`h-3.5 w-3.5`})]})]}),(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(Xn,{className:`pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{type:`text`,placeholder:`Filter folders…`,value:l,onChange:e=>u(e.target.value),className:`w-full rounded-md border border-input bg-background py-1.5 pl-8 pr-3 text-xs placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`})]})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,children:g?(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:K(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none text-sm shadow-elevation-1 hover:shadow`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,f===`/`?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:()=>N(`/`),onDoubleClick:()=>{N(`/`),c(`documents`)},title:`/`,children:[(0,Z.jsx)(Ne,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:`/`})]}),(0,Z.jsx)(`div`,{className:`ml-[22px] space-y-1.5`,children:m?.children?.length?m.children.map(e=>(0,Z.jsx)(np,{node:e,parentPath:`/`,query:d,selected:new Set([f]),onToggle:N,onActivate:e=>{N(e),c(`documents`)}},e.id||e.name)):(0,Z.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})})]})})]}):(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-muted/30 px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>c(`folder`),className:`inline-flex min-w-0 items-center gap-1 rounded-md px-1.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:`Back to folders`,children:[(0,Z.jsx)(B,{className:`h-3.5 w-3.5 shrink-0 rotate-180`}),(0,Z.jsx)(`span`,{className:`truncate font-mono`,children:M(f)})]}),(0,Z.jsx)(`span`,{className:`ml-auto shrink-0 text-xs text-muted-foreground`,children:`Step 2 of 2 · Pick a document`})]}),(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(Xn,{className:`pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{type:`text`,placeholder:`Search documents in this folder…`,value:S,onChange:e=>C(e.target.value),className:`w-full rounded-md border border-input bg-background py-1.5 pl-8 pr-7 text-xs placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`}),S&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>C(``),className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,"aria-label":`Clear document search`,children:(0,Z.jsx)(je,{className:`h-3.5 w-3.5`})})]})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1 overflow-y-auto p-3`,children:b?(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading documents…`}):P.length===0?(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:w?`No documents match “${w}” here.`:`No documents in this folder.`}):P.map(e=>{let t=mo(e),n=r.has(e.id);return(0,Z.jsxs)(`div`,{onClick:()=>i(e.id),className:K(`flex min-h-9 items-center gap-2 rounded-md px-3 py-1.5 cursor-pointer transition-all select-none text-sm`,n?`bg-primary/[0.08] hover:bg-primary/[0.12]`:`hover:bg-primary/[0.04]`),children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>i(e.id),className:`shrink-0`,onClick:e=>e.stopPropagation()}),(0,Z.jsx)(Jf,{document:e,size:3.5}),(0,Z.jsx)(`span`,{className:`flex-1 truncate`,children:t.title})]},e.id)})})]})}function ap({onClose:e,onConfirm:t,documentCount:n,fixedWorkspaceName:r,excludeWorkspace:i,multiple:a=!0,saving:o=!1,savingContent:s,sizeClassName:c,tabs:l=[`context`,`directory`],title:u,confirmLabel:d,onConfirmRelation:f,relationWorkspaceName:p,relationPredicates:m,relationExcludeIds:h}){let[g,_]=(0,X.useState)(r?`tree`:`workspace`);gf(e,!o);let[v,y]=(0,X.useState)([]),[b,x]=(0,X.useState)(!r),[S,C]=(0,X.useState)(r??null),[w,T]=(0,X.useState)(l.includes(`context`)||l.includes(`directory`)?`pins`:l[0]??`context`),E=m?.length?m:[...xa],[D,O]=(0,X.useState)(E[0]??`references`),[k,A]=(0,X.useState)(`out`),[j,M]=(0,X.useState)(new Set),[N,P]=(0,X.useState)(null),[ee,F]=(0,X.useState)(`context`),[I,te]=(0,X.useState)(!1),ne=w===`pins`?ee:w;(0,X.useEffect)(()=>{if(!S)return;let e=!1;return Va(S).then(t=>{e||P(t)}).catch(()=>{e||te(!0)}),()=>{e=!0}},[S]);let L=w===`relations`,[re,R]=(0,X.useState)(null),[ie,ae]=(0,X.useState)(!1),[oe,z]=(0,X.useState)(new Set),[se,ce]=(0,X.useState)(``),V=se.trim().toLowerCase(),{showErrorToast:le}=Ya(),[ue,de]=(0,X.useState)(null),[fe,pe]=(0,X.useState)(null),[me,H]=(0,X.useState)(!1),he=Qf(`/`,e=>de(e)),ge=w!==`pins`&&w!==`backends`&&w!==`relations`,_e=async(e,t)=>{let n=t.trim().replace(/^\/+|\/+$/g,``);if(!(!n||!S||me||!ge)){H(!0);try{let t=`${e===`/`?``:e}/${n}`;await Fi(S,t,!0,w===`directory`?`directory`:Da),oa(S);let r=await fi(S,w);R(r),z(e=>a?new Set([...e,t]):new Set([t])),pe(null)}catch(e){le(e instanceof Error?e.message:`Failed to create folder`)}finally{H(!1)}}},[ve,ye]=(0,X.useState)(r);r!==ve&&(ye(r),r||x(!0)),(0,X.useEffect)(()=>{r||Or().then(e=>y(e.filter(e=>e.id!==i&&e.name!==i))).catch(()=>y([])).finally(()=>x(!1))},[r,i]),(0,X.useEffect)(()=>{if(!S||w===`relations`||w===`pins`)return;let e=!1;async function t(){ae(!0);try{let t=await fi(S,w);e||R(t)}catch{e||R(null)}finally{e||ae(!1)}}return t(),()=>{e=!0}},[S,w]);let U=e=>{e!==S&&(P(null),te(!1)),T(l.includes(`context`)||l.includes(`directory`)?`pins`:l[0]??`context`),C(e),z(new Set),M(new Set),_(`tree`)},be=e=>{M(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},xe=e=>{if(!a){z(new Set([e]));return}z(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},Se=L?j.size>0&&!!f:oe.size>0,Ce=async()=>{if(!(!S||o||!Se)){if(L){await f?.({predicate:D,direction:k,targetIds:Array.from(j)},{workspaceName:p??S});return}await t(Array.from(oe),{workspaceName:S,treeName:ne===`context`?Da:ne,treeType:ne===`context`?`context`:`directory`})}},W=n??1;return o&&s?(0,Z.jsx)(`div`,{className:K(`flex flex-col overflow-hidden rounded-2xl border bg-card shadow-elevation-4`,c||`h-viewport-card max-h-full w-[min(380px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:s}):(0,Z.jsxs)(`div`,{className:K(`flex flex-col overflow-hidden rounded-2xl border bg-card shadow-elevation-4`,c||`h-viewport-card max-h-full w-[min(380px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:[(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(qt,{className:`h-4 w-4`}),u??(g===`workspace`?`Link to…`:L?`Relate ${W} document${W===1?``:`s`} to…`:`Link ${W} document${W===1?``:`s`} to…`)]}),(0,Z.jsx)(`button`,{type:`button`,onClick:e,disabled:o,className:`text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40`,"aria-label":`Close`,children:(0,Z.jsx)(je,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,Z.jsxs)(`div`,{className:`grid h-full w-[200%] grid-cols-2 transition-transform duration-200`,style:{transform:g===`workspace`?`translateX(0)`:`translateX(-50%)`},children:[(0,Z.jsx)(`div`,{className:`flex min-w-0 flex-col overflow-y-auto p-2`,children:(0,Z.jsx)(rp,{workspaces:v,loading:b,onPick:U})}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 overflow-x-auto border-b px-2 pt-2`,children:[!r&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>_(`workspace`),className:`mr-1 rounded p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground touch-target`,"aria-label":`Back to workspaces`,children:(0,Z.jsx)(B,{className:`h-4 w-4 rotate-180`})}),(l.includes(`context`)||l.includes(`directory`))&&(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>{T(`pins`),z(new Set),pe(null)},className:K(`flex shrink-0 items-center gap-1.5 border-b-2 px-3 py-2 text-xs`,w===`pins`?`border-primary`:`border-transparent text-muted-foreground`),children:[(0,Z.jsx)(De,{className:`h-3.5 w-3.5`}),`Pins`]}),l.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>{T(e),z(new Set),pe(null)},className:K(`flex shrink-0 items-center gap-1.5 rounded-t-md border-b-2 px-3 py-2 text-xs font-medium transition-colors`,w===e?`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground`),children:[Yf[e],Xf[e]]},e))]}),!L&&(0,Z.jsx)(`div`,{className:`shrink-0 border-b p-2`,children:(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(Xn,{className:`pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{type:`text`,placeholder:`Search paths…`,value:se,onChange:e=>ce(e.target.value),className:`w-full rounded-md border border-input bg-background py-2 pl-9 pr-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`})]})}),L&&(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-primary/[0.04] px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{htmlFor:`relation-predicate`,className:`shrink-0 text-xs text-muted-foreground`,children:`Predicate`}),(0,Z.jsx)(`select`,{id:`relation-predicate`,value:D,onChange:e=>O(e.target.value),className:`min-w-0 flex-1 rounded-md border border-input bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-2 focus:ring-ring`,children:E.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))})]}),(0,Z.jsx)(`div`,{className:`flex items-center gap-1`,children:[{dir:`out`,label:`This → picked`,hint:`the ${W===1?`document`:`documents`} you started from ${D} the picked one(s)`},{dir:`in`,label:`Picked → this`,hint:`the picked document(s) ${D} the ${W===1?`one`:`ones`} you started from`}].map(({dir:e,label:t,hint:n})=>(0,Z.jsx)(`button`,{type:`button`,title:n,onClick:()=>A(e),className:K(`flex-1 rounded-md border px-2 py-1.5 text-xs transition-colors`,k===e?`border-primary bg-primary text-primary-foreground`:`border-input hover:bg-accent`),children:t},e))})]}),!L&&a&&oe.size>0&&(0,Z.jsx)(`div`,{className:`flex shrink-0 flex-wrap gap-1.5 border-b bg-primary/[0.04] px-3 py-2`,children:Array.from(oe).map(e=>(0,Z.jsxs)(`span`,{className:`inline-flex max-w-full items-center gap-1 rounded-full bg-primary px-2 py-0.5 text-xs text-primary-foreground`,children:[(0,Z.jsx)(`span`,{className:`truncate`,title:e,children:e}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>xe(e),className:`shrink-0 rounded-full hover:bg-primary-foreground/20`,"aria-label":`Remove ${e}`,children:(0,Z.jsx)(je,{className:`h-3 w-3`})})]},e))}),L&&(p??S)&&(0,Z.jsx)(ip,{workspaceName:p??S,treeTab:`context`,selectedDocIds:j,onToggleDoc:be,excludeDocumentIds:h}),w===`pins`&&(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3 space-y-2`,children:[!N&&!I&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading pins…`}),I&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Could not load pins. You can still browse the trees.`}),!I&&N?.length===0&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No pinned paths yet. Choose a path from a tree.`}),N?.filter(e=>e.resolvable!==!1&&l.includes(e.tree===`context`?`context`:e.tree)&&`${e.label??e.name??``} ${e.path}`.toLowerCase().includes(V)).map(e=>{let t=e.tree===`context`?`context`:e.tree;return(0,Z.jsxs)(`button`,{type:`button`,"aria-pressed":ee===t&&oe.has(e.path),className:K(`w-full rounded-md border p-3 text-left text-sm hover:bg-muted`,ee===t&&oe.has(e.path)&&`border-primary bg-primary/10`),onClick:()=>{ee===t?xe(e.path):(F(t),z(new Set([e.path])))},children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(De,{className:`h-3.5 w-3.5`}),e.label||e.name||e.path]}),(0,Z.jsxs)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:[t,` · `,e.path]})]},e.id)})]}),(0,Z.jsx)(`div`,{className:K(`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,(L||w===`pins`)&&`hidden`),children:ie?(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:K(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none text-sm shadow-elevation-1 hover:shadow`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,oe.has(`/`)?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:he.guardClick(()=>xe(`/`)),title:`/`,...ge?he.handlers:{},children:[(0,Z.jsx)(Ne,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:`/`})]}),(0,Z.jsxs)(`div`,{className:`ml-[22px] space-y-1.5`,children:[fe===`/`&&(0,Z.jsx)(tp,{busy:me,onConfirm:e=>_e(`/`,e),onCancel:()=>pe(null)}),re?.children?.length?re.children.map(e=>(0,Z.jsx)(np,{node:e,parentPath:`/`,query:V,selected:oe,onToggle:xe,onRowMenu:ge?de:void 0,createParent:fe,onCreateConfirm:_e,onCreateCancel:()=>pe(null),creating:me},e.id||e.name)):fe===`/`?null:(0,Z.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})]})]})})]})]})}),g===`tree`&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between border-t px-4 py-3`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:L?`${j.size} document${j.size===1?``:`s`} selected`:`${oe.size} path${oe.size===1?``:`s`} selected`}),(0,Z.jsx)(J,{size:`sm`,onClick:Ce,disabled:!Se||o,children:o?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(id,{className:`mr-1.5 h-3.5 w-3.5`}),L?`Relating…`:`Linking…`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(qt,{className:`mr-1 h-3.5 w-3.5`}),L?`Relate`:d??`Link`]})})]}),ue&&(0,Z.jsx)(_f,{x:ue.clientX,y:ue.clientY,onClose:()=>de(null),className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:(0,Z.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 rounded-sm px-3 py-1.5 text-left text-xs hover:bg-accent`,onClick:()=>{pe(ue.path),de(null)},children:[(0,Z.jsx)(ot,{className:`h-3 w-3`}),`New folder in `,ue.path]})})]})}var op=`h-full w-[380px] max-w-[90vw] max-md:w-full`;function sp({onClose:e,children:t}){return(0,pf.createPortal)((0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-stretch justify-end bg-scrim animate-fade-in`,onClick:e,children:(0,Z.jsx)(`div`,{className:`h-full p-2 max-md:w-full max-md:p-1`,onClick:e=>e.stopPropagation(),children:t})}),window.document.body)}function cp(e){let t=2166136261;for(let e of localStorage.getItem(`authToken`)||``)t=Math.imul(t^e.charCodeAt(0),16777619);return`canvas:workspace-copy:${t>>>0}:${e}`}function lp({workspaceId:e,ids:t,onClose:n}){let[r]=(0,X.useState)(()=>{try{return cp(e)}catch{return``}}),[i,a]=(0,X.useState)(()=>{try{let e=JSON.parse(localStorage.getItem(r)||`null`);return e&&Array.isArray(e.ids)&&e.target&&e.index<e.ids.length?e:null}catch{return null}}),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(``),u=(0,X.useRef)(!1),d=(0,X.useRef)(!1);(0,X.useEffect)(()=>(u.current=!1,()=>{u.current=!0}),[]);let f=e=>{try{e.index>=e.ids.length?localStorage.removeItem(r):localStorage.setItem(r,JSON.stringify(e))}catch{}u.current||a(e)},p=async t=>{if(d.current)return;d.current=!0,s(!0),l(``);let n=t;f(n);try{for(;n.index<n.ids.length&&!u.current;){if(!navigator.onLine)throw Error(`Offline. Your copy is saved; resume when connected.`);await ga(e,n.ids[n.index],{destination:n.target.workspaceName,context:n.paths,treeType:n.target.treeType,treeNameOrTreeId:n.target.treeName,operationId:`${n.id}:${n.index}`}),n={...n,index:n.index+1},f(n)}window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`))}catch(e){u.current||l(`Document ${n.ids[n.index]}: ${e instanceof Error?e.message:`Copy failed`}. Resume to retry.`)}finally{d.current=!1,u.current||s(!1)}},m=()=>{u.current=!0,n()},h=i!=null&&i.index>=i.ids.length;return(0,Z.jsx)(sp,{onClose:m,children:i?(0,Z.jsxs)(`section`,{role:`dialog`,"aria-label":`Copy to workspace`,className:`${op} flex flex-col rounded-2xl border bg-card p-4 shadow-elevation-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Copy to workspace`}),(0,Z.jsxs)(`p`,{className:`mt-3 break-words text-sm`,children:[i.target.workspaceName,`: `,i.paths.join(`, `)]}),(0,Z.jsxs)(`p`,{role:`status`,className:`mt-3 text-sm`,children:[i.index,` of `,i.ids.length,` copied`,h?`.`:o?`…`:` — paused.`]}),c&&(0,Z.jsx)(`p`,{role:`alert`,className:`mt-3 text-sm text-destructive`,children:c}),(0,Z.jsx)(`p`,{className:`mt-3 text-xs text-muted-foreground`,children:`Files go to workspace:data. Destination rules handle storage placement. Relationships and sharing permissions are not copied. Source documents stay unchanged.`}),!h&&(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`Closing lets the current item finish and pauses the rest. Reopen Copy to workspace to resume, including after reconnecting.`}),(0,Z.jsxs)(`div`,{className:`mt-auto flex flex-wrap justify-end gap-2 pt-4`,children:[!h&&!o&&(0,Z.jsx)(J,{variant:`ghost`,onClick:()=>{try{localStorage.removeItem(r)}catch{}a(null),l(``)},children:`Discard remaining`}),!h&&!o&&(0,Z.jsx)(J,{onClick:()=>void p(i),children:`Resume copy`}),(0,Z.jsx)(J,{variant:h?`default`:`outline`,onClick:m,children:h?`Done`:o?`Pause & close`:`Close`})]})]}):(0,Z.jsx)(ap,{title:`Copy to workspace…`,confirmLabel:`Copy documents`,excludeWorkspace:e,documentCount:t.length,sizeClassName:op,onClose:m,onConfirm:(e,n)=>p({ids:t,target:n,paths:e,index:0,id:crypto.randomUUID()})})})}function up({tags:e,onChange:t,placeholder:n=`Add tag, press Enter`,suggestions:r=[]}){let[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(!1),c=i.trim().toLowerCase(),l=(c?r.filter(t=>t.toLowerCase().includes(c)&&!e.includes(t)):o?r.filter(t=>!e.includes(t)):[]).slice(0,8),u=()=>{let n=i.trim();n&&!e.includes(n)&&t([...e,n]),a(``)};return(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 rounded-md border border-input bg-transparent px-2 py-1.5 focus-within:ring-1 focus-within:ring-ring`,children:[e.map(n=>(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded bg-muted px-1.5 py-0.5 text-xs`,children:[n,(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(e.filter(e=>e!==n)),className:`text-muted-foreground hover:text-foreground`,"aria-label":`Remove ${n}`,children:(0,Z.jsx)(je,{className:`h-3 w-3`})})]},n)),(0,Z.jsxs)(`div`,{className:`relative flex-1 min-w-[8ch]`,children:[(0,Z.jsx)(`input`,{value:i,onChange:e=>a(e.target.value),onKeyDown:n=>{n.key===`Enter`||n.key===`,`?(n.preventDefault(),u()):n.key===`Backspace`&&!i&&e.length&&t(e.slice(0,-1))},onFocus:()=>s(!0),onBlur:()=>{setTimeout(u,150),s(!1)},placeholder:e.length?``:n,className:`w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground`}),l.length>0&&(0,Z.jsx)(`div`,{className:`absolute left-0 top-full z-50 mt-1 max-h-48 w-56 overflow-auto rounded-md border bg-popover p-1 text-sm shadow-elevation-2`,children:l.map(n=>(0,Z.jsx)(`button`,{type:`button`,onMouseDown:r=>{r.preventDefault(),e.includes(n)||t([...e,n]),a(``)},className:`block w-full rounded px-2 py-1 text-left hover:bg-accent`,children:n},n))})]})]})}function dp(e){let t=new Set;for(let n of e){let e=n.trim();e&&t.add(`tag/${e}`)}return Array.from(t)}function fp(e){return(e||[]).filter(e=>e.startsWith(`tag/`)).map(e=>e.slice(4))}function pp(e,t,n){return{...t.length?{features:[...new Set([...e.features??e.metadata?.features??[],...dp(e.data?.tags??[]),...dp(t)])]}:{},...n?{geo:n}:{}}}function mp(e,t,n,r){return{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,metadata:pp(e,t,n),...r===void 0?{}:{comment:r.trim()}}}var hp=n(Eo(),1),gp=`#8b5cf6`,_p=`https://nominatim.openstreetmap.org`,vp=700,yp=e=>Math.round(e*1e6)/1e6;function bp(){let e=`<div style="display:flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:9999px 9999px 9999px 2px;transform:rotate(-45deg);background:${gp};border:2px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.45)"><div style="width:8px;height:8px;border-radius:9999px;background:#fff"></div></div>`;return hp.default.divIcon({html:e,className:`canvas-map-pick`,iconSize:[28,28],iconAnchor:[14,28]})}function xp({initial:e,onPick:t,onClose:n}){let r=(0,X.useRef)(null),i=(0,X.useRef)(null),a=(0,X.useRef)(null),o=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>o.current?.abort(),[]);let[s,c]=(0,X.useState)(e?{lat:e.lat,lon:e.lon}:null),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)([]),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(!1),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(!1);(0,X.useEffect)(()=>{let e=requestAnimationFrame(()=>S(!0));return()=>cancelAnimationFrame(e)},[]),gf(n);let C=(0,X.useCallback)((e,t,n)=>{let r=i.current;if(!r)return;let o=hp.default.latLng(e,t);a.current?a.current.setLatLng(o):(a.current=hp.default.marker(o,{icon:bp(),draggable:!0,autoPan:!0}).addTo(r),a.current.on(`dragend`,()=>{let e=a.current.getLatLng();c({lat:yp(e.lat),lon:yp(e.lng)})})),c({lat:yp(e),lon:yp(t),...n?{label:n}:{}})},[]);(0,X.useEffect)(()=>{let t=r.current;if(!t||i.current)return;let n=hp.default.map(t,{center:e?[e.lat,e.lon]:[20,0],zoom:e?13:2,worldCopyJump:!0,zoomControl:!0});hp.default.tileLayer(`https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`,{attribution:`© OpenStreetMap contributors`,maxZoom:19}).addTo(n),i.current=n,e&&C(e.lat,e.lon),n.on(`click`,e=>C(e.latlng.lat,e.latlng.lng));let o=new ResizeObserver(()=>n.invalidateSize());o.observe(t);let s=setTimeout(()=>n.invalidateSize(),260);return()=>{clearTimeout(s),o.disconnect(),n.remove(),i.current=null,a.current=null}},[]),(0,X.useEffect)(()=>{if(!s||s.label)return;let{lat:e,lon:t}=s,n=new AbortController,r=setTimeout(()=>{v(!0),fetch(`${_p}/reverse?format=jsonv2&zoom=16&lat=${e}&lon=${t}`,{signal:n.signal,headers:{Accept:`application/json`}}).then(e=>e.ok?e.json():null).then(n=>{let r=n?.display_name;typeof r==`string`&&r&&c(n=>n&&n.lat===e&&n.lon===t?{...n,label:r}:n)}).catch(()=>{}).finally(()=>v(!1))},vp);return()=>{clearTimeout(r),n.abort()}},[s]);let w=(0,X.useCallback)(async()=>{let e=l.trim();if(e.length<2)return;o.current?.abort();let t=new AbortController;o.current=t;let n=!1,r=window.setTimeout(()=>{n=!0,t.abort()},12e3);m(!0),f([]),g(null);try{let n=await fetch(`${_p}/search?format=jsonv2&limit=6&q=${encodeURIComponent(e)}`,{signal:t.signal,headers:{Accept:`application/json`}});if(n.status===429)throw Error(`Place search is busy. Wait a moment and try again, or click the map`);if(!n.ok)throw Error(`Place search is unavailable (${n.status}). Try again, or click the map`);let r=await n.json();if(!Array.isArray(r))throw Error(`Place search returned an invalid response. Try again, or click the map`);if(t.signal.aborted||o.current!==t)return;f(r),r.length||g(`No match. Try a different spelling, or just click the map`)}catch(e){if(o.current!==t||t.signal.aborted&&!n)return;g(n?`Place search timed out. Try again, or click the map`:e instanceof TypeError?`Could not reach place search. Check your connection, or click the map`:e instanceof Error?e.message:`Search is unavailable right now. Click the map to place a pin`)}finally{window.clearTimeout(r),o.current===t&&(!t.signal.aborted||n)&&m(!1)}},[l]),T=(0,X.useCallback)(()=>{if(!navigator.geolocation){g(`This browser has no geolocation`);return}b(!0),g(null),navigator.geolocation.getCurrentPosition(e=>{b(!1),i.current?.setView([e.coords.latitude,e.coords.longitude],16),C(e.coords.latitude,e.coords.longitude)},()=>{b(!1),g(`Could not read your location. Search or click the map instead`)},{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})},[C]),E=(0,X.useCallback)(e=>{let t=i.current,n=Number(e.lat),r=Number(e.lon);if(!t||!Number.isFinite(n)||!Number.isFinite(r))return;let a=e.boundingbox?.map(Number);a&&a.length===4&&a.every(Number.isFinite)?t.fitBounds(hp.default.latLngBounds([a[0],a[2]],[a[1],a[3]]),{maxZoom:16}):t.setView([n,r],15),C(n,r,e.display_name),f([])},[C]);return(0,pf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:K(`fixed inset-0 z-[60] bg-black/40 transition-opacity duration-200`,x?`opacity-100`:`opacity-0`),onClick:n}),(0,Z.jsxs)(`div`,{role:`dialog`,"aria-label":`Pick a location on the map`,className:K(`fixed inset-y-0 right-0 z-[61] flex w-[min(560px,100vw)] flex-col bg-background shadow-elevation-4 transition-transform duration-200 ease-out`,x?`translate-x-0`:`translate-x-full`),children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(Zt,{className:`h-4 w-4 text-info`}),`Custom geotag`]}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,"aria-label":`Close map`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(je,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`div`,{className:`relative z-10 shrink-0 border-b px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsxs)(`div`,{className:`relative flex-1`,children:[(0,Z.jsx)(Xn,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{value:l,autoFocus:!0,onChange:e=>{o.current?.abort(),o.current=null,m(!1),f([]),u(e.target.value),g(null)},"aria-label":`Search for a place or address`,onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),w())},placeholder:`Search a place, e.g. Slavkovský štít`,spellCheck:!1,className:`h-8 w-full rounded-md border border-input bg-transparent pl-7 pr-2 text-sm outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring`})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:T,disabled:y,title:`Use my current location`,"aria-label":`Use my current location`,className:`inline-flex h-8 w-8 items-center justify-center rounded-md border border-border text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50`,children:y?(0,Z.jsx)(Wn,{className:`h-3.5 w-3.5 animate-spin`}):(0,Z.jsx)(cn,{className:`h-3.5 w-3.5`})}),(0,Z.jsxs)(`button`,{type:`button`,onClick:w,disabled:p||l.trim().length<2,className:`inline-flex h-8 items-center gap-1.5 rounded-md bg-primary px-3 text-xs text-primary-foreground disabled:opacity-50`,children:[p?(0,Z.jsx)(Wn,{className:`h-3.5 w-3.5 animate-spin`}):(0,Z.jsx)(Xn,{className:`h-3.5 w-3.5`}),`Search`]})]}),h&&(0,Z.jsx)(`p`,{role:`status`,className:`mt-1 text-xs text-warning`,children:h}),d.length>0&&(0,Z.jsx)(`div`,{className:`absolute inset-x-3 top-full z-10 mt-1 max-h-64 overflow-y-auto rounded-md border bg-popover shadow-elevation-4`,children:d.map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>E(e),className:`block w-full border-b border-border/60 px-3 py-2 text-left text-xs last:border-0 hover:bg-muted`,children:e.display_name},`${e.lat},${e.lon},${e.display_name}`))})]}),(0,Z.jsxs)(`div`,{className:`relative isolate z-0 min-h-0 flex-1`,children:[(0,Z.jsx)(`div`,{ref:r,className:`h-full w-full`}),!s&&(0,Z.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-3 z-[1000] flex justify-center`,children:(0,Z.jsx)(`span`,{className:`rounded-full bg-background/90 px-3 py-1 text-xs text-muted-foreground shadow-elevation-2`,children:`Click the map to drop a pin, or drag it to fine-tune`})})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-3 border-t px-3 py-2`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 text-xs`,children:s?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5 tabular-nums text-foreground`,children:[(0,Z.jsx)(Wt,{className:`h-3 w-3 shrink-0 text-muted-foreground`}),s.lat.toFixed(5),`, `,s.lon.toFixed(5),_&&(0,Z.jsx)(Wn,{className:`h-3 w-3 animate-spin text-muted-foreground`})]}),s.label&&(0,Z.jsx)(`div`,{className:`truncate text-muted-foreground`,children:s.label})]}):(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`No point selected`})}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground hover:bg-muted hover:text-foreground`,children:`Cancel`}),(0,Z.jsxs)(`button`,{type:`button`,disabled:!s,onClick:()=>{s&&(t(s),n())},className:`inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground disabled:opacity-50`,children:[(0,Z.jsx)(ur,{className:`h-3.5 w-3.5`}),`Use this point`]})]})]})]})]}),document.body)}var Sp={exif:`from the photo's EXIF`,device:`from the device at capture`,manual:`placed by hand`};function Cp(e){let t=`${e.lat.toFixed(5)}, ${e.lon.toFixed(5)}`,n=e.source?Sp[e.source]:null;return[t,e.accuracy==null?null:`±${e.accuracy} m`,n].filter(Boolean).join(` · `)}function wp({value:e,onChange:t,idPrefix:n=`edit-geo`}){let[r,i]=(0,X.useState)(!1);return(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`${n}-action`,children:`Location`}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Z.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2 text-xs`,children:[(0,Z.jsx)(Zt,{className:e?`h-4 w-4 shrink-0 text-info`:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:e?`truncate tabular-nums`:`truncate text-muted-foreground`,children:e?Cp(e):`No location on this document`})]}),(0,Z.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1`,children:[(0,Z.jsxs)(`button`,{id:`${n}-action`,type:`button`,onClick:()=>i(!0),className:`inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,Z.jsx)(jn,{className:`h-3.5 w-3.5`}),e?`Move pin`:`Set on map`]}),e&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(null),"aria-label":`Remove location`,title:`Remove location`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})]}),r&&(0,Z.jsx)(xp,{initial:e,onPick:e=>t({lat:e.lat,lon:e.lon,source:`manual`}),onClose:()=>i(!1)})]})}function Tp({workspaceId:e,documentIds:t,onClose:n}){let[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(`keep`),[l,u]=(0,X.useState)(``),d=(r.length>0||!!a||s!==`keep`)&&(s!==`replace`||l.trim().length>0),[f,p]=(0,X.useState)(t),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(``);return gf(n,!m),(0,pf.createPortal)((0,Z.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-scrim p-4`,children:(0,Z.jsxs)(`section`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`bulk-edit-title`,className:`max-h-viewport-modal overflow-y-auto w-full max-w-md space-y-4 rounded-xl border bg-background p-5 shadow-elevation-4`,children:[(0,Z.jsxs)(`h2`,{id:`bulk-edit-title`,className:`font-semibold`,children:[`Bulk Edit · `,f.length,` documents`]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Add tags to all selected documents. Choosing a location replaces their existing geotags; leaving it unset keeps them.`}),(0,Z.jsxs)(`fieldset`,{disabled:m,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:`Add tags`}),(0,Z.jsx)(up,{tags:r,onChange:i,suggestions:[]})]}),(0,Z.jsx)(wp,{value:a,onChange:o,idPrefix:`bulk-geo`}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`label`,{htmlFor:`bulk-comment-mode`,className:`text-sm font-medium`,children:`Comment`}),(0,Z.jsxs)(`select`,{id:`bulk-comment-mode`,value:s,onChange:e=>c(e.target.value),className:`w-full rounded-md border border-input bg-background px-3 py-2 text-sm`,children:[(0,Z.jsx)(`option`,{value:`keep`,children:`Keep existing comments`}),(0,Z.jsx)(`option`,{value:`replace`,children:`Replace comments`}),(0,Z.jsx)(`option`,{value:`clear`,children:`Clear comments`})]}),s===`replace`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`label`,{htmlFor:`bulk-comment`,className:`sr-only`,children:`New comment for all selected documents`}),(0,Z.jsx)(`textarea`,{id:`bulk-comment`,rows:3,value:l,onChange:e=>u(e.target.value),placeholder:`Comment for all selected documents…`,className:`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This replaces the comment on every selected document.`})]}),s===`clear`&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This removes the comment from every selected document.`})]})]}),g&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:g}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(J,{variant:`outline`,onClick:n,disabled:m,children:`Cancel`}),(0,Z.jsx)(J,{onClick:async()=>{if(m||!d)return;h(!0),_(``);let t=[];for(let n of f)try{let t=await gr(e,n);await Li(e,mp(t,r,a,s===`keep`?void 0:s===`clear`?``:l))}catch{t.push(n)}window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),h(!1),t.length?(p(t),_(`${f.length-t.length} saved; ${t.length} could not be updated. Retry applies only to those documents.`)):n()},disabled:m||!d,children:m?`Saving…`:g?`Retry failed`:`Apply to all`})]})]})}),window.document.body)}var Ep=[{mode:`copy`,label:`Copy to`,icon:(0,Z.jsx)(Ct,{className:`h-3.5 w-3.5`})},{mode:`move`,label:`Move to`,icon:(0,Z.jsx)(_t,{className:`h-3.5 w-3.5`})},{mode:`delete`,label:`Delete from`,icon:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})}],Dp=[{value:`rename`,label:`Rename mine (file-1.ext)`},{value:`overwrite`,label:`Overwrite the existing file`},{value:`error`,label:`Skip the document`}],Op=`h-9 w-full rounded-md border bg-background px-2 text-xs outline-none focus:ring-2 focus:ring-ring disabled:opacity-50`;function kp(e){return e.driver===`cacache`?Jt:e.config?.remote===!0?O:_e}function Ap({workspaceId:e,documentCount:t,initialMode:n=`copy`,defaultFilename:r=``,onConfirm:i,onClose:a,saving:o=!1,sizeClassName:s}){let{showErrorToast:c}=Ya(),[l,u]=(0,X.useState)(!1);gf(a,!o&&!l);let[d,f]=(0,X.useState)(n),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(new Set),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(``),[C,w]=(0,X.useState)(r),[T,E]=(0,X.useState)(`rename`);(0,X.useEffect)(()=>{let t=!1;return va(e).then(e=>{t||m(e.filter(e=>e.kind===`storage`))}).catch(e=>{t||g(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e]);let D=d===`move`,O=e=>d===`delete`?null:e.enabled===!1?`disabled`:e.config?.readOnly===!0?`read-only`:e.config?.supported===!1?`unsupported`:null,k=(0,X.useMemo)(()=>(p||[]).filter(e=>!O(e)).map(e=>e.address),[p,d]),A=e=>{f(e),v(t=>{let n=(p||[]).filter(t=>e===`delete`||t.enabled!==!1&&t.config?.readOnly!==!0&&t.config?.supported!==!1).map(e=>e.address),r=[...t].filter(e=>n.includes(e));return new Set(e===`move`?r.slice(0,1):r)})},j=e=>{v(t=>{if(D)return t.has(e)?new Set:new Set([e]);let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},M=(0,X.useMemo)(()=>(p||[]).filter(e=>_.has(e.address)&&ia(e)),[p,_]),N=d!==`delete`&&M.length>0,P=e=>{u(!1);let t=Aa(e[0]||``,p||[]),n=t?(p||[]).find(e=>e.address===t.address):null;if(!t||!n){c(`Pick a folder inside a storage backend`);return}if(O(n)){c(`${n.address} is ${O(n)}`);return}if(!ia(n)){c(`${n.address} does not keep folders — objects are stored by content`);return}S(t.key),v(e=>D?new Set([t.address]):new Set([...e,t.address]))},ee=async()=>{_.size===0||o||await i([..._],d,{keepDocument:y,folder:N?x.trim():``,filename:N&&t===1?C.trim():``,onConflict:T})},F=t,I=F===1?``:`s`,te=d===`delete`?`Delete ${F} document${I} from…`:`${d===`move`?`Move`:`Copy`} ${F} document${I} to…`,ne=d===`delete`?`Delete from`:d===`move`?`Move to`:`Copy to`,re=_.size===0?ne.split(` `)[0]:`${ne} ${_.size} backend${_.size===1?``:`s`}`;return(0,Z.jsxs)(`div`,{className:K(`flex flex-col overflow-hidden rounded-2xl border bg-card shadow-elevation-4`,s||`max-h-viewport-card w-[min(420px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:[(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(_e,{className:`h-4 w-4`}),te]}),(0,Z.jsx)(`button`,{type:`button`,onClick:a,disabled:o,className:`text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40`,"aria-label":`Close`,children:(0,Z.jsx)(je,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{className:`flex shrink-0 items-center gap-1 border-b px-2 pt-2`,children:Ep.map(({mode:e,label:t,icon:n})=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>A(e),disabled:o,className:K(`flex items-center gap-1.5 rounded-t-md border-b-2 px-3 py-2 text-xs font-medium transition-colors disabled:opacity-50`,d===e?e===`delete`?`border-destructive text-destructive`:`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground`),children:[n,t]},e))}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,children:[h&&(0,Z.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-destructive`,children:h}),!p&&!h&&(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading backends…`}),p?.length===0&&(0,Z.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`No storage backends configured.`}),p?.map(e=>{let t=kp(e),n=O(e),r=_.has(e.address),i=e.config?.remote===!0;return(0,Z.jsxs)(`div`,{onClick:()=>!n&&!o&&j(e.address),className:K(`group relative flex min-h-10 items-center gap-2 rounded-md px-3 py-2 text-sm shadow-elevation-1 transition-all select-none`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,n?`cursor-not-allowed bg-muted/40 opacity-60 before:bg-transparent`:`cursor-pointer hover:shadow`,!n&&r?d===`delete`?`bg-destructive/[0.08] hover:bg-destructive/[0.12] before:bg-destructive`:`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:n?``:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),title:e.address,children:[(0,Z.jsx)(`input`,{type:D?`radio`:`checkbox`,checked:r,disabled:!!n||o,onChange:()=>j(e.address),onClick:e=>e.stopPropagation(),className:`h-4 w-4 shrink-0 accent-primary`,"aria-label":e.address}),(0,Z.jsx)(t,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block truncate font-medium`,children:e.config?.label||e.address}),(0,Z.jsxs)(`span`,{className:`block truncate font-mono text-[10px] text-muted-foreground`,children:[e.driver,` · `,e.address]})]}),i&&(0,Z.jsx)(`span`,{className:`shrink-0 rounded bg-info-subtle px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,title:`Network mount${e.config?.transport?` (${e.config.transport})`:``} — transfers cross the network`,children:e.config?.transport||`remote`}),n&&(0,Z.jsx)(`span`,{className:`shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:n})]},`${e.driver}/${e.address}`)}),d===`delete`&&(0,Z.jsxs)(`label`,{className:`mt-3 flex cursor-pointer items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:y,onChange:e=>b(e.target.checked),className:`mt-0.5 h-3.5 w-3.5 accent-destructive`}),(0,Z.jsxs)(`span`,{children:[`Keep the index entry when its `,(0,Z.jsx)(`strong`,{children:`last`}),` copy is deleted.`,(0,Z.jsx)(`span`,{className:`block text-muted-foreground`,children:`Otherwise the document is removed from the index once no locations remain.`})]})]}),N&&(0,Z.jsxs)(`div`,{className:`mt-3 space-y-2 rounded-md border px-3 py-2`,children:[(0,Z.jsxs)(`p`,{className:`text-xs font-medium`,children:[`Destination on `,M.map(e=>e.config?.label||e.address).join(`, `)]}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{htmlFor:`backend-transfer-folder`,className:`text-[11px] text-muted-foreground`,children:`Folder (relative to the backend root)`}),(0,Z.jsxs)(`div`,{className:`flex gap-1.5`,children:[(0,Z.jsx)(q,{id:`backend-transfer-folder`,value:x,onChange:e=>S(e.target.value),placeholder:`/`,disabled:o,className:`h-9 font-mono text-xs`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`icon`,className:`h-9 w-9 shrink-0`,onClick:()=>u(!0),disabled:o,"aria-label":`Browse backend folders`,title:`Browse…`,children:(0,Z.jsx)(L,{className:`h-4 w-4`})})]})]}),t===1?(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{htmlFor:`backend-transfer-filename`,className:`text-[11px] text-muted-foreground`,children:`File name`}),(0,Z.jsx)(q,{id:`backend-transfer-filename`,value:C,onChange:e=>w(e.target.value),placeholder:r||`keeps the document's own name`,disabled:o,className:`h-9 font-mono text-xs`})]}):(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Each document keeps its own file name and extension.`}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{htmlFor:`backend-transfer-conflict`,className:`text-[11px] text-muted-foreground`,children:`If a different file already has that name`}),(0,Z.jsx)(`select`,{id:`backend-transfer-conflict`,className:Op,value:T,onChange:e=>E(e.target.value),disabled:o,children:Dp.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))})]})]}),d===`move`&&k.length>0&&(0,Z.jsx)(`p`,{className:`px-1 pt-2 text-[11px] text-muted-foreground`,children:`The source copy is released only once the destination write is durable.`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-t px-4 py-3`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[_.size,` backend`,_.size===1?``:`s`,` selected`]}),(0,Z.jsx)(J,{size:`sm`,variant:d===`delete`?`destructive`:`default`,onClick:ee,disabled:_.size===0||o,children:o?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(id,{className:`mr-1.5 h-3.5 w-3.5`}),`Working…`]}):(0,Z.jsxs)(Z.Fragment,{children:[d===`delete`?(0,Z.jsx)(lt,{className:`mr-1 h-3.5 w-3.5`}):d===`move`?(0,Z.jsx)(_t,{className:`mr-1 h-3.5 w-3.5`}):(0,Z.jsx)(Ct,{className:`mr-1 h-3.5 w-3.5`}),re]})})]}),d===`delete`&&(0,Z.jsxs)(`div`,{className:`flex items-start gap-2 border-t bg-destructive/5 px-4 py-2 text-[11px] text-muted-foreground`,children:[(0,Z.jsx)(at,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-destructive`}),(0,Z.jsx)(`span`,{children:`Deletes the file data from the selected backends. Copies on other backends are untouched.`})]}),l&&(0,Z.jsx)(sp,{onClose:()=>u(!1),children:(0,Z.jsx)(ap,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,multiple:!1,tabs:[`backends`],fixedWorkspaceName:e,title:`Pick a destination folder…`,confirmLabel:`Use folder`,onConfirm:P,onClose:()=>u(!1)})})]})}function jp({onClose:e,onConfirm:t,fixedWorkspaceName:n,saving:r=!1,sizeClassName:i}){let[a,o]=(0,X.useState)(n?`browse`:`workspace`),[s,c]=(0,X.useState)([]),[l,u]=(0,X.useState)(!n),[d,f]=(0,X.useState)(n??null),[p,m]=(0,X.useState)(`context`),[h,g]=(0,X.useState)(new Set),[_,v]=(0,X.useState)(n);return n!==_&&(v(n),n||u(!0)),(0,X.useEffect)(()=>{n||Or().then(c).catch(()=>c([])).finally(()=>u(!1))},[n]),(0,Z.jsxs)(`div`,{className:K(`flex flex-col overflow-hidden rounded-2xl border bg-card shadow-elevation-4`,i||`h-viewport-card max-h-full w-[min(420px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:[(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(Qt,{className:`h-4 w-4`}),a===`workspace`?`Add existing documents…`:`Pick documents…`]}),(0,Z.jsx)(`button`,{type:`button`,onClick:e,disabled:r,className:`text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40`,"aria-label":`Close`,children:(0,Z.jsx)(je,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,Z.jsxs)(`div`,{className:`grid h-full w-[200%] grid-cols-2 transition-transform duration-200`,style:{transform:a===`workspace`?`translateX(0)`:`translateX(-50%)`},children:[(0,Z.jsx)(`div`,{className:`flex min-w-0 flex-col overflow-y-auto p-2`,children:(0,Z.jsx)(rp,{workspaces:s,loading:l,onPick:e=>{f(e),g(new Set),o(`browse`)}})}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 border-b px-2 pt-2`,children:[!n&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>o(`workspace`),className:`mr-1 rounded p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground touch-target`,"aria-label":`Back to workspaces`,children:(0,Z.jsx)(B,{className:`h-4 w-4 rotate-180`})}),[`context`,`directory`].map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>{m(e),g(new Set)},className:K(`flex items-center gap-1.5 rounded-t-md border-b-2 px-3 py-2 text-xs font-medium transition-colors`,p===e?`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground`),children:[Yf[e],Xf[e]]},e))]}),d&&(0,Z.jsx)(ip,{workspaceName:d,treeTab:p,onTreeTabChange:m,selectedDocIds:h,onToggleDoc:e=>{g(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},onNavigate:()=>g(new Set)})]})]})}),a===`browse`&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between border-t px-4 py-3`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[h.size,` document`,h.size===1?``:`s`,` selected`]}),(0,Z.jsx)(J,{size:`sm`,onClick:async()=>{!d||h.size===0||r||await t(Array.from(h),{workspaceName:d,treeName:p===`directory`?`directory`:Da,treeType:p})},disabled:h.size===0||r,children:r?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(id,{className:`mr-1.5 h-3.5 w-3.5`}),`Adding…`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Qt,{className:`mr-1 h-3.5 w-3.5`}),`Add`]})})]})]})}var Mp=(0,X.createContext)(null),Np={entry:null,open:()=>{},close:()=>{}};function Pp(){return(0,X.useContext)(Mp)??Np}var Fp=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{className:`relative w-full overflow-auto`,children:(0,Z.jsx)(`table`,{ref:n,className:K(`w-full caption-bottom text-sm`,e),...t})}));Fp.displayName=`Table`;var Ip=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`thead`,{ref:n,className:K(`[&_tr]:border-b`,e),...t}));Ip.displayName=`TableHeader`;var Lp=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`tbody`,{ref:n,className:K(`[&_tr:last-child]:border-0`,e),...t}));Lp.displayName=`TableBody`;var Rp=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`tfoot`,{ref:n,className:K(`border-t bg-muted/50 font-medium [&>tr]:last:border-b-0`,e),...t}));Rp.displayName=`TableFooter`;var zp=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`tr`,{ref:n,className:K(`border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted`,e),...t}));zp.displayName=`TableRow`;var Bp=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`th`,{ref:n,className:K(`h-12 px-2 md:px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0`,e),...t}));Bp.displayName=`TableHead`;var Vp=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`td`,{ref:n,className:K(`p-2 md:p-4 align-middle [&:has([role=checkbox])]:pr-0`,e),...t}));Vp.displayName=`TableCell`;var Hp=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`caption`,{ref:n,className:K(`mt-4 text-sm text-muted-foreground`,e),...t}));Hp.displayName=`TableCaption`;var Up=({label:e,sortKey:t,sort:n,onSort:r,className:i})=>{let a=n.key===t;return(0,Z.jsx)(Bp,{"aria-sort":a?n.dir===`asc`?`ascending`:`descending`:`none`,className:K(`cursor-pointer select-none hover:text-foreground transition-colors`,i),onClick:()=>r(t),children:(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[e,a?n.dir===`asc`?(0,Z.jsx)(Rn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Tt,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Ce,{className:`h-3.5 w-3.5 opacity-40`})]})})};Up.displayName=`SortableTableHead`;function Wp(e,t,n={key:null,dir:`asc`}){let[r,i]=X.useState(n);return{sorted:X.useMemo(()=>{let n=r.key?t[r.key]:null;if(!n)return e;let i=r.dir===`asc`?1:-1;return[...e].sort((e,t)=>{let r=n(e)??``,a=n(t)??``;return typeof r==`number`&&typeof a==`number`?(r-a)*i:String(r).localeCompare(String(a),void 0,{numeric:!0})*i})},[e,r,t]),sort:r,toggleSort:X.useCallback(e=>{i(t=>t.key===e?{key:e,dir:t.dir===`asc`?`desc`:`asc`}:{key:e,dir:`asc`})},[])}}var Gp=`workspace:relations:refresh`;function Kp(){window.dispatchEvent(new CustomEvent(Gp))}var qp=(0,X.createContext)(null),Jp=`canvas:documentOpenMode`;function Yp(){try{return localStorage.getItem(Jp)===`modal`?`modal`:`side`}catch{return`side`}}var Xp=Yp(),Zp=new Set;function Qp(){return Xp}function $p(e){try{localStorage.setItem(Jp,e)}catch{}Xp=e;for(let e of Zp)e()}function em(e){Zp.add(e);let t=t=>{(t.key===Jp||t.key===null)&&(Xp=Yp(),e())};return window.addEventListener(`storage`,t),()=>{Zp.delete(e),window.removeEventListener(`storage`,t)}}function tm(){return(0,X.useSyncExternalStore)(em,Qp,()=>`side`)}function nm({tabs:e,active:t,onChange:n,className:r=``,iconOnly:i=!1}){return(0,Z.jsx)(`div`,{className:`flex gap-1 border-b overflow-x-auto ${r}`,children:e.map(e=>{let r=e.icon;return(0,Z.jsxs)(`button`,{onClick:()=>n(e.id),title:e.label,className:`${i&&r?`px-3`:`px-4`} py-2 text-sm font-medium border-b-2 transition-colors whitespace-nowrap inline-flex items-center gap-1.5 ${t===e.id?`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground`}`,children:[r&&(0,Z.jsx)(r,{className:`h-3.5 w-3.5`}),(!i||!r)&&e.label]},e.id)})})}var rm=e=>`${Kr.workspaces}/${encodeURIComponent(e)}/messages`,im=e=>Y.get(`${rm(e)}/accounts`),am=(e,t)=>Y.get(`${rm(e)}/reply-target/${t}`),om=(e,t)=>Y.post(`${rm(e)}/send`,t),sm=(e,t)=>Y.get(`${rm(e)}/whatsapp/${encodeURIComponent(t)}/connection`),cm=(e,t)=>Y.get(`${rm(e)}/outbox/${encodeURIComponent(t)}`),lm=(e,t)=>Y.delete(`${rm(e)}/whatsapp/${encodeURIComponent(t)}/connection`);function um(e,t,n=!1){let r=2166136261;try{for(let e of localStorage.getItem(`authToken`)||``)r=Math.imul(r^e.charCodeAt(0),16777619)}catch{}return`canvas:message-draft:${r>>>0}:${e}:${t||`new`}${n?`:fwd`:``}`}var dm={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`};function fm({workspaceId:e,replyToDocumentId:t,mode:n=`reply`,originalSubject:r,onClose:i}){let a=!!t&&n===`forward`,o=um(e,t,a),s=()=>({requestId:crypto.randomUUID(),text:``,replyToDocumentId:t,...a?{forward:!0}:t?{replyAll:n===`replyAll`,quote:!0}:{}}),[c,l]=(0,X.useState)(()=>{try{let e=localStorage.getItem(o);if(e){let r=JSON.parse(e),i=r.draft||r;return a||!t?i:{...i,replyAll:n===`replyAll`}}}catch{}return s()}),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(navigator.onLine);(0,X.useEffect)(()=>{let e=()=>h(navigator.onLine);return window.addEventListener(`online`,e),window.addEventListener(`offline`,e),()=>{window.removeEventListener(`online`,e),window.removeEventListener(`offline`,e)}},[]);let[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(()=>{try{return JSON.parse(localStorage.getItem(o)||`{}`).attempted===!0}catch{return!1}}),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(null);(0,X.useEffect)(()=>{let n=!0;return Promise.all([im(e),t?am(e,t):Promise.resolve(null)]).then(([e,r])=>{n&&(d(r),p(e.filter(e=>e.canSend&&(!r||e.driver===r.driver&&e.address===r.address))),t&&!r&&x(`This message has no supported reply account.`),r&&l(e=>({...e,driver:r.driver,address:r.address})))}).catch(e=>{n&&x(e.message)}),()=>{n=!1}},[e,t]),(0,X.useEffect)(()=>{try{S?.status===`accepted`?localStorage.removeItem(o):localStorage.setItem(o,JSON.stringify({draft:c,attempted:v}))}catch{}},[o,c,v,S]);let w=f.find(e=>e.driver===c.driver&&e.address===c.address),T=w?.driver===`imap`,E=!!c.text.trim(),D=e=>l(t=>({...t,...e})),O=async()=>{_(!0),x(``),y(!0);let t=T?E?c:{...c,html:void 0}:{...c,html:void 0,quote:void 0,forward:void 0};try{let n=v?await cm(e,c.requestId).catch(n=>{if(n.statusCode===404)return om(e,t);throw n}):await om(e,t);if(C(n),n.status===`accepted`){try{localStorage.removeItem(o)}catch{}window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e}}))}}catch(e){let t=e;x(t.message),!v&&t.statusCode&&t.statusCode>=400&&t.statusCode<500&&t.statusCode!==409&&y(!1)}finally{_(!1)}},k=c.replyAll?u?.allRecipients:u?.recipients,A=g||v,j=t?a?dm.forward:dm[c.replyAll?`replyAll`:`reply`]:`New message`,M=t&&r?`${a?`Fwd`:`Re`}: ${r.replace(a?/^(fwd?|fw):\s*/i:/^re:\s*/i,``)}`:``;return(0,Z.jsxs)(`section`,{className:`max-h-[70dvh] overflow-y-auto rounded-md border bg-card p-3 space-y-3`,"aria-label":t?`${j} to message`:`New message`,children:[(0,Z.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,Z.jsx)(`strong`,{className:`text-sm`,children:j}),(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,onClick:i,children:`Close`})]}),(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[`Send from`,(0,Z.jsxs)(`select`,{"aria-label":`Sending account`,className:`w-full rounded border bg-background p-2`,value:w?`${w.driver}:${w.address}`:``,disabled:A||!!t,onChange:e=>{let t=f.find(t=>`${t.driver}:${t.address}`===e.target.value);t&&D({driver:t.driver,address:t.address,to:[],cc:[],bcc:[],subject:void 0,target:void 0,replyAll:!1})},children:[(0,Z.jsx)(`option`,{value:``,children:`Select an enabled sending account`}),f.map(e=>(0,Z.jsxs)(`option`,{value:`${e.driver}:${e.address}`,children:[e.driver,` · `,e.from||e.address]},`${e.driver}:${e.address}`))]})]}),!f.length&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Enable sending in the account’s workspace settings. Your draft stays on this device.`}),T?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[`To `,t&&!a?`(leave blank to reply to the sender)`:``,(0,Z.jsx)(q,{"aria-label":`To`,disabled:A,value:c.to?.join(`, `)||``,onChange:e=>D({to:[e.target.value]})})]}),t&&!a&&!c.to?.some(e=>e.trim())&&k&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Reply to: `,k.to.join(`, `),k.cc.length?` · Cc: ${k.cc.join(`, `)}`:``]}),[`cc`,`bcc`].map(e=>(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[e===`cc`?`Cc`:`Bcc`,(0,Z.jsx)(q,{"aria-label":e===`cc`?`Cc`:`Bcc`,disabled:A,value:c[e]?.join(`, `)||``,onChange:t=>D({[e]:[t.target.value]})})]},e)),(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[`Subject`,(0,Z.jsx)(q,{"aria-label":`Subject`,disabled:A,value:c.subject||``,placeholder:M,onChange:e=>D({subject:e.target.value||void 0})})]}),t&&!a&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-4 text-xs`,children:[(0,Z.jsxs)(`label`,{className:`flex gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:A,checked:c.replyAll||!1,onChange:e=>D({replyAll:e.target.checked})}),`Reply all`]}),(0,Z.jsxs)(`label`,{className:`flex gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:A,checked:c.quote||!1,onChange:e=>D({quote:e.target.checked})}),`Quote original message`]})]}),a&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The original message and its attachments are included below your note.`}),(0,Z.jsx)(go,{format:`html`,editable:!A,value:c.html||``,placeholder:a?`Add a note (optional)…`:`Write a message…`,onChange:(e,t)=>D({html:e,text:t.slice(0,32e3)})})]}):(0,Z.jsxs)(Z.Fragment,{children:[!t&&(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[`Conversation (configured channel name or ID)`,(0,Z.jsx)(q,{"aria-label":`Conversation`,disabled:A,value:c.target||``,onChange:e=>D({target:e.target.value})})]}),(0,Z.jsx)(`textarea`,{"aria-label":`Message text`,className:`w-full rounded border bg-background p-2 text-sm`,rows:5,maxLength:32e3,disabled:A,value:c.text,onChange:e=>D({text:e.target.value}),placeholder:`Write a message…`})]}),b&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:b}),S&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[S.status===`accepted`?`Accepted by the provider.`:S.message,` `,S.warnings?.join(` `),` `,S.rejected?.length?`Not accepted for: ${S.rejected.join(`, `)}`:``]}),S?.status!==`accepted`&&(0,Z.jsx)(J,{size:`sm`,disabled:g||!v&&(!w||!E&&!(T&&a)||a&&!c.to?.some(e=>e.trim()))||!m,onClick:()=>void O(),children:g?`Sending…`:v?`Check send status`:`Send`}),(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,disabled:g,onClick:()=>{window.confirm(v?`This message may already have been sent. Discard this draft only after checking the conversation.`:`Discard this draft?`)&&(l({...s(),driver:c.driver,address:c.address}),y(!1),C(null),x(``))},children:`Discard draft`}),v&&S?.status!==`accepted`&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Do not start another send until you have checked the conversation. The same request will not be delivered twice by Canvas.`})]})}var pm=1,mm=8,hm=320,gm=28,_m=2.5,vm={scale:1,x:0,y:0};function ym({src:e,alt:t,className:n=``,onZoomChange:r}){let i=(0,X.useRef)(null),a=(0,X.useRef)(null),[o,s]=(0,X.useState)(vm),c=(0,X.useRef)(new Map),l=(0,X.useRef)(null),u=(0,X.useRef)(null),d=(0,X.useRef)(!1),f=(0,X.useRef)(null),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(e);h!==e&&(g(e),s(vm)),(0,X.useEffect)(()=>{r?.(o.scale>1.001)},[o.scale,r]);let _=(0,X.useCallback)(e=>{let t=i.current,n=a.current;if(!t||!n)return e;let r=Math.min(mm,Math.max(pm,e.scale)),o=Math.max(0,(n.offsetWidth*r-t.clientWidth)/2),s=Math.max(0,(n.offsetHeight*r-t.clientHeight)/2);return{scale:r,x:Math.min(o,Math.max(-o,e.x)),y:Math.min(s,Math.max(-s,e.y))}},[]),v=(0,X.useCallback)((e,t,n)=>{let r=i.current;if(!r)return;let a=r.getBoundingClientRect(),o=t-a.left-a.width/2,c=n-a.top-a.height/2;s(t=>{let n=e/t.scale;return _({scale:e,x:o-(o-t.x)*n,y:c-(c-t.y)*n})})},[_]),y=(0,X.useCallback)(()=>{let e=i.current,t=a.current;if(!e||!t||!t.offsetWidth||!t.offsetHeight)return _m;let n=Math.max(e.clientWidth/t.offsetWidth,e.clientHeight/t.offsetHeight),r=Math.max(t.naturalWidth/t.offsetWidth,t.naturalHeight/t.offsetHeight)||mm;return Math.min(mm,Math.max(_m,Math.min(Math.max(n,_m),r)))},[]),b=(0,X.useCallback)((e,t)=>{o.scale>1.001?s(vm):v(y(),e,t)},[o.scale,v,y]),x=e=>{if(c.current.set(e.pointerId,{x:e.clientX,y:e.clientY}),d.current=!1,c.current.size===2){let[e,t]=[...c.current.values()];l.current={dist:Math.hypot(e.x-t.x,e.y-t.y),scale:o.scale,cx:(e.x+t.x)/2,cy:(e.y+t.y)/2}}e.currentTarget.setPointerCapture(e.pointerId)},S=e=>{let t=c.current.get(e.pointerId);if(!t)return;if(c.current.set(e.pointerId,{x:e.clientX,y:e.clientY}),c.current.size>=2&&l.current){let[e,t]=[...c.current.values()],n=Math.hypot(e.x-t.x,e.y-t.y);l.current.dist>0&&(d.current=!0,m(!0),v(l.current.scale*(n/l.current.dist),l.current.cx,l.current.cy));return}if(o.scale<=1.001)return;let n=e.clientX-t.x,r=e.clientY-t.y;(Math.abs(n)>1||Math.abs(r)>1)&&(d.current=!0,m(!0)),s(e=>_({...e,x:e.x+n,y:e.y+r}))},C=e=>{if(c.current.delete(e.pointerId),c.current.size<2&&(l.current=null),c.current.size===0&&m(!1),d.current){u.current=null;return}let t=e.timeStamp,n=u.current;if(n&&t-n.t<hm&&Math.hypot(e.clientX-n.x,e.clientY-n.y)<gm){u.current=null,f.current=t,b(e.clientX,e.clientY);return}u.current={t,x:e.clientX,y:e.clientY}},w=e=>{e.preventDefault();let t=o.scale*(e.deltaY<0?1.15:1/1.15);t<=pm?s(vm):v(Math.min(mm,t),e.clientX,e.clientY)},T=o.scale>1.001;return(0,Z.jsx)(`div`,{ref:i,className:`relative flex h-full w-full items-center justify-center overflow-hidden`,style:{touchAction:`none`,cursor:T?`grab`:`zoom-in`},onPointerDown:x,onPointerMove:S,onPointerUp:C,onPointerCancel:e=>{c.current.delete(e.pointerId),l.current=null,u.current=null,d.current=!0,c.current.size===0&&m(!1)},onWheel:w,onDoubleClick:e=>{e.preventDefault(),e.stopPropagation(),!(f.current!==null&&e.timeStamp-f.current<hm)&&b(e.clientX,e.clientY)},children:(0,Z.jsx)(`img`,{ref:a,src:e,alt:t,draggable:!1,className:n,style:{transform:`translate3d(${o.x}px, ${o.y}px, 0) scale(${o.scale})`,transformOrigin:`center center`,transition:p?`none`:`transform 160ms ease-out`,willChange:`transform`}})})}var bm=`(max-width: 767px)`,xm=new Map;function Sm(e){let t=xm.get(e);if(!t){let n=()=>typeof window<`u`&&typeof window.matchMedia==`function`;t={subscribe:t=>{if(!n())return()=>{};let r=window.matchMedia(e);return r.addEventListener(`change`,t),()=>r.removeEventListener(`change`,t)},getSnapshot:()=>n()?window.matchMedia(e).matches:!1},xm.set(e,t)}return t}function Cm(){let e=Sm(bm);return(0,X.useSyncExternalStore)(e.subscribe,e.getSnapshot,()=>!1)}function wm(){return Tm(`(max-width: 1023px)`)}function Tm(e){let t=Sm(e);return(0,X.useSyncExternalStore)(t.subscribe,t.getSnapshot,()=>!1)}function Em(){return!/android|iphone|ipad|mobile/i.test(navigator.userAgent)&&navigator.pdfViewerEnabled!==!1}var Dm=40,Om=1600;function km({blob:e,filename:t}){let n=(0,X.useRef)(null),[r,i]=(0,X.useState)({error:null,pages:0,truncated:!1});return(0,X.useEffect)(()=>{let r=n.current;if(!r)return;let a=!1,o=null;return(async()=>{let n=await m(()=>import(`./pdf-Ciz5_WNq.js`),__vite__mapDeps([0,1])),s=(await m(async()=>{let{default:e}=await import(`./pdf.worker.min-C8Ts8bNu.js`);return{default:e}},[])).default;n.GlobalWorkerOptions.workerSrc=s;let c=await e.arrayBuffer();if(a)return;let l=n.getDocument({data:c});o=()=>{l.destroy()};let u=await l.promise;if(a)return;let d=Math.min(u.numPages,Dm),f=r.clientWidth||600,p=window.devicePixelRatio||1;for(let e=1;e<=d;e++){if(a)return;let n=await u.getPage(e),o=n.getViewport({scale:1}),s=Math.min(f*p,Om*p)/o.width,c=n.getViewport({scale:s}),l=document.createElement(`canvas`);if(l.width=c.width,l.height=c.height,l.style.width=`100%`,l.style.height=`auto`,l.className=`rounded border bg-white`,l.setAttribute(`aria-label`,`${t}, page ${e}`),await n.render({canvas:l,viewport:c}).promise,n.cleanup(),a)return;r.appendChild(l),i({error:null,pages:e,truncated:u.numPages>Dm})}})().catch(e=>{a||i(t=>({...t,error:e instanceof Error?e.message:String(e)}))}),()=>{a=!0,o?.(),r.replaceChildren()}},[e,t]),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[r.error&&(0,Z.jsxs)(`p`,{className:`text-sm text-destructive`,children:[`Could not render PDF: `,r.error]}),!r.error&&r.pages===0&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Rendering PDF…`}),(0,Z.jsx)(`div`,{ref:n,className:`space-y-2`}),r.truncated&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Showing the first `,Dm,` pages. Download the file for the full document.`]})]})}function Am({blob:e,blobUrl:t,filename:n,className:r=``}){let i=(0,X.useMemo)(()=>e&&e.type!==`application/pdf`?URL.createObjectURL(e.slice(0,e.size,`application/pdf`)):null,[e]);return(0,X.useEffect)(()=>()=>{i&&URL.revokeObjectURL(i)},[i]),Em()||!e?(0,Z.jsx)(`div`,{className:`min-h-[300px] ${r}`,children:(0,Z.jsx)(`iframe`,{src:i??t,className:`h-full min-h-[300px] w-full rounded border`,title:n})}):(0,Z.jsx)(`div`,{className:`max-h-viewport-pane overflow-y-auto ${r}`,children:(0,Z.jsx)(km,{blob:e,filename:n})})}function jm(e,t,n=256,{enabled:r=!0,blobFallback:i=!0,version:a=null}={}){let{isPublic:o,fetchBlob:s,fetchThumbnail:c}=fo(e),l=`${o?`pub`:`ws`}:${e}:${t}:${n}:${r}:${a??``}`,[u,d]=(0,X.useState)({blobUrl:null,error:null,loading:r}),[f,p]=(0,X.useState)(l);return l!==f&&(p(l),d({blobUrl:null,error:null,loading:r})),(0,X.useEffect)(()=>{if(!r)return;let e=!1,o=null;return c(t,n,a).catch(e=>{if(!i)throw e;return s(t)}).then(({blob:t})=>{e||(o=URL.createObjectURL(t),d({blobUrl:o,error:null,loading:!1}))}).catch(t=>{e||d({blobUrl:null,error:String(t instanceof Error?t.message:t),loading:!1})}),()=>{e=!0,o&&URL.revokeObjectURL(o)}},[l]),u}function Mm({workspaceId:e,document:t}){let{download:n}=fo(e),[r,i]=(0,X.useState)(!1),a=so(t)||`document-${t.id}`;return(0,Z.jsxs)(`button`,{type:`button`,onClick:async()=>{i(!0);try{await n(t.id,a)}finally{i(!1)}},disabled:r,className:`inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50`,children:[(0,Z.jsx)(wn,{className:`h-3.5 w-3.5`}),r?`Preparing…`:`Download`]})}var Nm=1600;function Pm({error:e,loading:t,children:n}){return e?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:e}):t?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading preview...`}):(0,Z.jsx)(Z.Fragment,{children:n})}function Fm({workspaceId:e,document:t,className:n=``}){let r=(0,X.useContext)(qp),i=Cm(),a=Tm(`(pointer: coarse)`),{blobUrl:o,error:s,loading:c}=jm(e,t.id,Nm,{version:t.checksumArray?.[0]??null}),{fetchBlob:l}=fo(e),u=so(t)||`document-${t.id}`,[d,f]=(0,X.useState)(!1);return(0,Z.jsx)(Pm,{error:s,loading:c,children:o&&(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2 ${n}`,children:[i||a?(0,Z.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,Z.jsx)(ym,{src:o,alt:u,className:`max-h-full max-w-full object-contain`})}):(0,Z.jsx)(`img`,{src:o,alt:u,draggable:!1,onDoubleClick:r?e=>{e.preventDefault(),e.stopPropagation(),r()}:void 0,title:r?`Double-click to maximize or restore`:void 0,className:`min-h-0 w-full flex-1 object-contain ${r?`cursor-zoom-in`:``}`}),(0,Z.jsxs)(`button`,{type:`button`,onClick:async()=>{f(!0);try{let{blob:e}=await l(t.id),n=URL.createObjectURL(e),r=window.document.createElement(`a`);r.href=n,r.download=u,window.document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(n),3e4)}finally{f(!1)}},disabled:d,className:`inline-flex shrink-0 self-start items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50`,children:[(0,Z.jsx)(wn,{className:`h-3.5 w-3.5`}),d?`Preparing…`:`Download original`]})]})})}function Im({workspaceId:e,document:t,className:n=``}){let{src:r,error:i,loading:a}=lo(e,t.id);return(0,Z.jsx)(Pm,{error:i,loading:a,children:r&&(0,Z.jsxs)(`div`,{className:`space-y-2 ${n}`,children:[(0,Z.jsx)(`audio`,{src:r,controls:!0,preload:`metadata`,className:`w-full`}),(0,Z.jsx)(Mm,{workspaceId:e,document:t})]})})}function Lm({workspaceId:e,document:t,className:n=``}){let{src:r,error:i,loading:a}=lo(e,t.id),[o,s]=(0,X.useState)(!1);return(0,Z.jsx)(Pm,{error:i,loading:a,children:r&&(0,Z.jsxs)(`div`,{className:`space-y-2 ${n}`,children:[(0,Z.jsx)(`video`,{src:r,controls:!0,playsInline:!0,preload:`metadata`,onError:()=>s(!0),className:`max-h-viewport-pane w-full rounded border`}),o&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This video can’t be played inline in your browser. Download it to view.`}),(0,Z.jsx)(Mm,{workspaceId:e,document:t})]})})}function Rm({workspaceId:e,document:t,className:n=``}){let{blobUrl:r,blob:i,error:a,loading:o}=So(e,t.id,{typeHint:`application/pdf`}),s=so(t)||`document-${t.id}`;return(0,Z.jsx)(Pm,{error:a,loading:o,children:r&&(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2 ${n}`,children:[(0,Z.jsx)(Am,{blob:i,blobUrl:r,filename:s,className:`min-h-0 flex-1`}),(0,Z.jsx)(`div`,{children:(0,Z.jsx)(Mm,{workspaceId:e,document:t})})]})})}var zm=(0,X.lazy)(()=>m(()=>import(`./markdown-html-bKd2bDZi.js`),__vite__mapDeps([2,3,4,5,6,7])));function Bm({content:e,className:t=``,preview:n=!1}){return(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`div`,{className:`whitespace-pre-wrap break-words ${t}`,children:e}),children:(0,Z.jsx)(zm,{content:e,className:t,preview:n})})}function Vm({workspaceId:e,document:t,className:n=``}){let{text:r,error:i,loading:a}=So(e,t.id,{mode:`text`});return i?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i}):a||r==null?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading...`}):(0,Z.jsx)(`pre`,{className:`bg-muted p-3 rounded text-xs overflow-auto max-h-viewport-pane whitespace-pre-wrap ${n}`,children:r})}function Hm({workspaceId:e,document:t,className:n=``}){let r=t.schema===Xa,{text:i,error:a,loading:o}=So(e,t.id,{mode:`text`,enabled:!r});return r?(0,Z.jsxs)(`div`,{className:`space-y-3 ${n}`,children:[t.data?.title?(0,Z.jsx)(`h3`,{className:`text-lg font-semibold`,children:String(t.data.title)}):null,(0,Z.jsx)(`div`,{className:`rounded-md border border-input bg-transparent`,children:(0,Z.jsx)(Bm,{content:String(t.data?.content??``),className:`markdown-doc px-4 py-3`})})]}):a?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:a}):o||i==null?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading...`}):(0,Z.jsx)(`div`,{className:`rounded-md border border-input bg-transparent overflow-auto max-h-viewport-pane ${n}`,children:(0,Z.jsx)(Bm,{content:i,className:`markdown-doc px-4 py-3`})})}function Um({document:e,className:t=``}){let n=String(e.data?.url??e.data?.uri??``),r=Za(n);return r?(0,Z.jsx)(`div`,{className:`aspect-video w-full ${t}`,children:(0,Z.jsx)(`iframe`,{src:`https://www.youtube-nocookie.com/embed/${encodeURIComponent(r)}`,title:String(e.data?.title??e.data?.label??`YouTube video`),className:`h-full w-full rounded border`,allow:`accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture`,allowFullScreen:!0})}):null}function Wm({document:e,className:t=``}){let n=String(e.data?.url??e.data?.uri??``),[r,i]=(0,X.useState)({blobUrl:null,blob:null,failed:!1,loading:!0}),[a,o]=(0,X.useState)(n);n!==a&&(o(n),i({blobUrl:null,blob:null,failed:!1,loading:!0})),(0,X.useEffect)(()=>{let e=!1,t=null,r=async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.blob();return new Blob([t],{type:`application/pdf`})},a=()=>{let e=localStorage.getItem(`authToken`);return fetch(`${Yr}/proxy/pdf?url=${encodeURIComponent(n)}`,{headers:e?{Authorization:`Bearer ${e}`}:{}})};return fetch(n).then(r).catch(()=>a().then(r)).then(n=>{e||(t=URL.createObjectURL(n),i({blobUrl:t,blob:n,failed:!1,loading:!1}))}).catch(()=>{e||i({blobUrl:null,blob:null,failed:!0,loading:!1})}),()=>{e=!0,t&&URL.revokeObjectURL(t)}},[n]);let{blobUrl:s,blob:c,failed:l,loading:u}=r,d=(()=>{try{let e=decodeURIComponent(new URL(n).pathname.split(`/`).filter(Boolean).pop()??``)||`document`;return/\.pdf$/i.test(e)?e:`${e}.pdf`}catch{return`document.pdf`}})();return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2 ${t}`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-3`,children:[(0,Z.jsxs)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:`inline-flex items-center gap-1 text-xs text-primary hover:underline`,children:[(0,Z.jsx)(Gn,{className:`h-3 w-3`}),` `,n]}),c&&(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>{if(!c)return;let e=URL.createObjectURL(c),t=window.document.createElement(`a`);t.href=e,t.download=d,window.document.body.appendChild(t),t.click(),t.remove(),setTimeout(()=>URL.revokeObjectURL(e),3e4)},className:`inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:[(0,Z.jsx)(wn,{className:`h-3.5 w-3.5`}),` Download`]})]}),u&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading PDF…`}),l&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Inline preview unavailable (direct fetch and server proxy both failed). Use the link above.`}),s&&(0,Z.jsx)(Am,{blob:c,blobUrl:s,filename:d,className:`min-h-[300px] flex-1`})]})}function Gm(e){if(!e)return!1;try{let t=new URL(e);return!!(/\.pdf$/i.test(t.pathname)||t.hostname.endsWith(`arxiv.org`)&&t.pathname.startsWith(`/pdf/`))}catch{return!1}}function Km(e){try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}}function qm({document:e,className:t=``}){let n=e.data||{},r=String(n.url??n.uri??``),i=String(n.title??n.label??``)||Km(r),a=typeof n.favIconUrl==`string`?n.favIconUrl:``,o=n.pinned===!0,s=typeof n.timestamp==`string`?n.timestamp:null,[c,l]=(0,X.useState)(!1);return(0,Z.jsxs)(`div`,{className:`space-y-3 ${t}`,children:[(0,Z.jsxs)(`a`,{href:r,target:`_blank`,rel:`noopener noreferrer`,className:`group flex items-start gap-3 rounded-lg border bg-card p-3 transition-colors hover:bg-accent/40`,children:[(0,Z.jsx)(`div`,{className:`mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded bg-muted`,children:a&&!c?(0,Z.jsx)(`img`,{src:a,alt:``,className:`h-5 w-5`,onError:()=>l(!0)}):(0,Z.jsx)(C,{className:`h-4 w-4 text-muted-foreground`})}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(`span`,{className:`truncate font-medium leading-tight`,children:i}),o&&(0,Z.jsx)(De,{className:`h-3 w-3 shrink-0 fill-warning text-warning`})]}),(0,Z.jsx)(`div`,{className:`mt-0.5 truncate text-xs text-muted-foreground`,children:Km(r)}),(0,Z.jsx)(`div`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground/70`,children:r})]}),(0,Z.jsx)(Gn,{className:`mt-1 h-4 w-4 shrink-0 text-muted-foreground reveal-on-hover`})]}),s&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Saved `,new Date(s).toLocaleString()]})]})}var Jm={enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4};function Ym(e){let t=e.coords,n={lat:t.latitude,lon:t.longitude,source:`device`};return t.altitude!=null&&Number.isFinite(t.altitude)&&(n.alt=t.altitude),Number.isFinite(t.accuracy)&&(n.accuracy=Math.round(t.accuracy)),n}function Xm(){return new Promise((e,t)=>navigator.geolocation.getCurrentPosition(e,t,Jm))}function Zm(e){let t=e?.code;return t===1?`Location permission denied`:t===2?`Location unavailable; no fix right now`:t===3?`Timed out waiting for a location fix`:`Could not read your location`}function Qm(){let e=typeof navigator<`u`&&`geolocation`in navigator&&typeof window<`u`&&window.isSecureContext,[t,n]=(0,X.useState)(e?`prompt`:`unsupported`),[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(null),h=(0,X.useRef)(!1),g=(0,X.useRef)(null),_=(0,X.useRef)(null);(0,X.useEffect)(()=>{if(!e||!navigator.permissions?.query)return;let t=!1,r=null;return navigator.permissions.query({name:`geolocation`}).then(e=>{t||(r=e,n(e.state),e.onchange=()=>n(e.state))}).catch(()=>{}),()=>{t=!0,r&&(r.onchange=null)}},[e]);let v=(0,X.useCallback)(e=>{if(c(null),!e){_.current=null,f(null),m(null),h.current||i(!1);return}let t={lat:e.lat,lon:e.lon,source:`manual`};_.current=t,f(t),m(e.label??null),i(!0)},[]);return{supported:e,permission:t,enabled:r,busy:a,error:s,fix:l,setEnabled:(0,X.useCallback)(t=>{if(c(null),!t){h.current=!1,_.current=null,f(null),m(null),i(!1);return}_.current||e&&(h.current=!0,i(!0),o(!0),Xm().then(e=>{let t=Ym(e);g.current=t,u(t),n(`granted`)}).catch(e=>{c(Zm(e)),e?.code===1&&(n(`denied`),h.current=!1,i(!1))}).finally(()=>o(!1)))},[e]),manual:d,manualLabel:p,setManual:v,capture:(0,X.useCallback)(async()=>{if(_.current)return _.current;if(!h.current||!e)return null;try{return Ym(await Xm())}catch{return g.current}},[e])}}var $m=`2.1`,eh=[`pending`,`in-progress`,`completed`,`cancelled`],th={pending:`Pending`,"in-progress":`In progress`,completed:`Completed`,cancelled:`Cancelled`};function nh(e){return String(e).padStart(2,`0`)}function rh(e){return`${e.getFullYear()}-${nh(e.getMonth()+1)}-${nh(e.getDate())}T${nh(e.getHours())}:${nh(e.getMinutes())}`}function ih(e){if(!e)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:rh(t)}function ah(e){if(!e)return;let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t.toISOString()}function oh(){let e=new Date;return e.setHours(23,59,0,0),rh(e)}function sh(e){let t=ah(e.due);return{title:e.title.trim(),...e.description.trim()?{description:e.description.trim()}:{},status:e.status,completed:e.status===`completed`,...t?{dueDate:t}:{},...e.priority===``?{}:{priority:Number(e.priority)}}}function ch(){let[e,t]=(0,X.useState)(``),[n,r]=(0,X.useState)(``),[i,a]=(0,X.useState)(`pending`),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(oh()),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)(``),[m,h]=(0,X.useState)(!1),g=Qm(),_=e.trim().length>0&&!m;async function v(t){h(!0);try{let r=await g.capture(),a=f.trim(),s={schema:io,schemaVersion:$m,data:sh({title:e,description:n,status:i,priority:o,due:c}),...a?{comment:a}:{},metadata:{features:dp(u),...r?{geo:r}:{}}};return await Yo(t,[s])}finally{h(!1)}}return{title:e,setTitle:t,description:n,setDescription:r,status:i,setStatus:a,priority:o,setPriority:s,due:c,setDue:l,tags:u,setTags:d,comment:f,setComment:p,saving:m,canSave:_,save:v,geotag:g}}function lh(e){return e.data||{}}var uh={pending:`bg-muted text-muted-foreground`,"in-progress":`bg-info/15 text-info dark:text-info`,completed:`bg-success/15 text-success dark:text-success`,cancelled:`bg-muted text-muted-foreground line-through`};function dh(e){if(!e.dueDate||e.status===`completed`||e.status===`cancelled`)return!1;let t=new Date(e.dueDate).getTime();return Number.isFinite(t)&&t<Date.now()}function fh(e){if(!e)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:t.toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`})}async function ph(e,t,n){let r=n===`completed`,i={...t.data||{},status:n,completed:r};r?i.completedAt=new Date().toISOString():delete i.completedAt,await Li(e,{id:t.id,schema:t.schema,schemaVersion:t.schemaVersion,data:i}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`))}function mh({document:e,workspaceId:t,className:n=``}){let r=lh(e),i=bo()!=null,[a,o]=(0,X.useState)(!1),{replicating:s,label:c}=Ji(e),l=r.status===`completed`,u=r.status??`pending`,d=dh(r);return(0,Z.jsx)(`div`,{className:`space-y-3 ${n}`,children:(0,Z.jsxs)(`div`,{className:`relative flex items-start gap-3 rounded-lg border bg-card p-3 transition-opacity ${s?`opacity-60`:``}`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:async()=>{if(!(i||a)){o(!0);try{await ph(t,e,l?`pending`:`completed`)}catch{}finally{o(!1)}}},disabled:i||a||s,"aria-pressed":l,title:l?`Mark not done`:`Mark done`,className:`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border transition-colors ${l?`border-success bg-success text-success-foreground`:`border-input hover:border-success`} ${i?`cursor-default opacity-70`:``}`,children:a?(0,Z.jsx)(Wn,{className:`h-3 w-3 animate-spin`}):l&&(0,Z.jsx)(ur,{className:`h-3.5 w-3.5`})}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`font-medium leading-tight ${l?`text-muted-foreground line-through`:``}`,children:r.title||`Todo ${e.id}`}),(0,Z.jsxs)(`div`,{className:`mt-1.5 flex flex-wrap items-center gap-2 text-xs`,children:[(0,Z.jsx)(`span`,{className:`rounded-full px-2 py-0.5 ${uh[u]}`,children:th[u]}),r.dueDate&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 ${d?`font-medium text-destructive`:`text-muted-foreground`}`,children:[(0,Z.jsx)(Ge,{className:`h-3 w-3`}),fh(r.dueDate),d?` · overdue`:``]}),typeof r.priority==`number`&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-muted-foreground`,children:[(0,Z.jsx)(ke,{className:`h-3 w-3`}),`P`,r.priority]})]}),r.description&&(0,Z.jsx)(Bm,{content:String(r.description),className:`mt-2 text-sm text-muted-foreground`}),s&&(0,Z.jsxs)(`div`,{className:`mt-2 inline-flex items-center gap-1.5 text-xs text-muted-foreground`,role:`status`,children:[(0,Z.jsx)(Wn,{className:`h-3 w-3 animate-spin`}),c]})]})]})})}function hh(e){return e?typeof e==`string`?e:e.name&&e.address?`${e.name} <${e.address}>`:e.address||e.name||``:``}function gh(e){return e?(Array.isArray(e)?e:[e]).map(e=>hh(e)).filter(Boolean).join(`, `):``}function _h(e){if(!Number.isFinite(e))return``;let t=Number(e);return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}function vh(e,t,n){let r=0;gs.addHook(`afterSanitizeAttributes`,e=>{if(e.tagName===`IMG`){let i=e.getAttribute(`src`)||``,a=i.toLowerCase();if(a.startsWith(`cid:`)){let n=i.slice(4).replace(/^<|>$/g,``),r=t.get(n)||t.get(`<${n}>`);r?e.setAttribute(`src`,r):e.removeAttribute(`src`)}else(a.startsWith(`http:`)||a.startsWith(`https:`)||a.startsWith(`//`))&&(r++,n?e.setAttribute(`src`,i.replace(/^http:/i,`https:`).replace(/^\/\//,`https://`)):e.removeAttribute(`src`))}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noopener noreferrer`))});try{let t=gs.sanitize(e,{FORBID_TAGS:[`script`,`iframe`,`object`,`embed`,`form`,`base`,`link`,`meta`],FORBID_ATTR:[`srcset`]}),i=`<!doctype html><html><head>
|
|
7
|
+
<meta charset="utf-8">
|
|
8
|
+
<meta http-equiv="Content-Security-Policy" content="${`default-src 'none'; img-src data:${n?` https:`:``}; style-src 'unsafe-inline'`}">
|
|
9
|
+
<style>body{margin:12px;font:14px/1.5 system-ui,sans-serif;color:#1a1a1a;background:#fff;word-break:break-word}img{max-width:100%}</style>
|
|
10
|
+
</head><body>${t}</body></html>`;return{url:URL.createObjectURL(new Blob([i],{type:`text/html;charset=utf-8`})),remoteCount:r}}finally{gs.removeHook(`afterSanitizeAttributes`)}}function yh(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result)),r.onerror=()=>n(r.error),r.readAsDataURL(e)})}function bh({workspaceId:e,document:t,className:n=``}){let{fetchBlob:r,download:i}=fo(e),a=t.data||{},o=Array.isArray(a.attachments)?a.attachments:[],s=typeof a.bodyHtml==`string`&&a.bodyHtml.trim()?a.bodyHtml:null,c=typeof a.body==`string`?a.body:``,[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(!s),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(0),[_,v]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!s||d)return;let e=!1,n=[],i=o.filter(e=>e.contentId&&e.url);return Promise.all(i.slice(0,20).map(async e=>{try{let{blob:n}=await r(t.id,{url:e.url}),i=await yh(n);return[String(e.contentId).replace(/^<|>$/g,``),i]}catch{return null}})).then(t=>{if(e)return;let r=new Map(t.filter(Boolean)),{url:i,remoteCount:a}=vh(s,r,p);n.push(i),u(i),g(a)}).catch(t=>{e||v(String(t instanceof Error?t.message:t))}),()=>{e=!0,n.forEach(e=>URL.revokeObjectURL(e)),u(null)}},[e,t.id,s,d,p]);let b=typeof a.date==`string`?new Date(a.date).toLocaleString():null,x=o.filter(e=>!e.isInline||!e.contentId),S=async e=>{if(e.url)try{await i(t.id,e.filename||`attachment`,{url:e.url})}catch(e){v(e instanceof Error?e.message:String(e))}};return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3 ${n}`,children:[(0,Z.jsx)(`div`,{className:`shrink-0 rounded-md border bg-muted/30 p-3 text-sm`,children:(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 space-y-1`,children:[(0,Z.jsx)(`div`,{className:`text-base font-semibold`,children:String(a.subject??`(no subject)`)}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`From:`}),` `,hh(a.from)]}),gh(a.to)&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`To:`}),` `,gh(a.to)]}),gh(a.cc)&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Cc:`}),` `,gh(a.cc)]}),b&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:b})]}),s&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 flex-wrap justify-end gap-2`,children:[(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,onClick:()=>f(!d),children:[d?(0,Z.jsx)(Le,{className:`mr-1.5 h-3.5 w-3.5`}):(0,Z.jsx)(_n,{className:`mr-1.5 h-3.5 w-3.5`}),d?`HTML`:`Plain text`]}),!d&&h>0&&(0,Z.jsxs)(J,{size:`sm`,variant:p?`secondary`:`outline`,onClick:()=>m(!p),title:`Remote images can reveal your IP/read status to the sender`,children:[p?(0,Z.jsx)(y,{className:`mr-1.5 h-3.5 w-3.5`}):(0,Z.jsx)(rn,{className:`mr-1.5 h-3.5 w-3.5`}),p?`Hide remote images`:`Show remote images (${h})`]})]})]})}),_&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:_}),!d&&s?l?(0,Z.jsx)(`iframe`,{src:l,sandbox:``,title:String(a.subject??`email`),className:`min-h-[12rem] w-full flex-1 rounded border bg-white`}):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Rendering...`}):(0,Z.jsx)(`pre`,{className:`min-h-[12rem] flex-1 overflow-auto whitespace-pre-wrap rounded bg-muted p-3 text-sm`,children:c||`(empty body)`}),x.length>0&&(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`text-xs font-medium text-muted-foreground`,children:[`Attachments (`,x.length,`)`]}),x.map((e,t)=>(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-2 py-1.5 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(_n,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`truncate`,children:e.filename||`attachment`}),(0,Z.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:_h(e.size)})]}),e.url&&(0,Z.jsxs)(`button`,{onClick:()=>S(e),className:`inline-flex shrink-0 items-center gap-1 text-xs text-primary hover:underline`,children:[(0,Z.jsx)(wn,{className:`h-3 w-3`}),` Download`]})]},e.url||t))]})]})}var xh={email:vt,phone:V,sms:ft,chat:ft,slack:ft,matrix:ft,web:C,url:C},Sh={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},Ch=e=>Array.isArray(e)?e:[];function wh(e,t){return t?e===`email`?`mailto:${t}`:e===`phone`||e===`sms`?`tel:${t.replace(/[^\d+]/g,``)}`:/^https?:\/\//i.test(t)?t:null:null}function Th({title:e,count:t,children:n}){return t===0?null:(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground`,children:e}),(0,Z.jsx)(`div`,{className:`space-y-1`,children:n})]})}function Eh({icon:e,primary:t,children:n,title:r}){return(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 rounded-md border bg-card px-2.5 py-1.5 text-sm`,title:r,children:[(0,Z.jsx)(e,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`div`,{className:`min-w-0 flex-1 truncate`,children:n}),t&&(0,Z.jsx)(Nn,{className:`h-3 w-3 shrink-0 fill-current text-data-5`,"aria-label":`Primary`})]})}function Dh({document:e,className:t}){let n=e.data??{},r=Ch(n.identifiers),i=Ch(n.channels),a=Ch(n.organizations),o=Ch(n.links),s=Ch(n.tags),c=String(n.displayName||``).trim(),l=Qa(e.schema,eo),u=String(n.primaryEmail||``).trim(),d=n.name&&typeof n.name==`object`?n.name:{},f=[d.prefix,d.given,d.middle,d.family,d.suffix].map(e=>String(e||``).trim()).filter(Boolean).join(` `),p=i.some(e=>e.kind===`email`&&e.value===u);return(0,Z.jsxs)(`div`,{className:K(`space-y-4`,t),children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:c||`Identity ${e.id}`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-muted-foreground`,children:[l&&(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5`,children:Sh[l]||l}),f&&f!==c&&(0,Z.jsx)(`span`,{children:f}),String(n.timezone||``)&&(0,Z.jsx)(`span`,{children:String(n.timezone)}),String(n.locale||``)&&(0,Z.jsx)(`span`,{children:String(n.locale)})]})]}),u&&!p&&(0,Z.jsx)(Th,{title:`Primary email`,count:1,children:(0,Z.jsx)(Eh,{icon:vt,primary:!0,children:(0,Z.jsx)(`a`,{href:`mailto:${u}`,className:`hover:underline`,children:u})})}),(0,Z.jsx)(Th,{title:`Channels`,count:i.length,children:i.map((e,t)=>{let n=String(e.kind||``).toLowerCase(),r=String(e.value||``),i=wh(n,r),a=xh[n]||ft;return(0,Z.jsxs)(Eh,{icon:a,primary:e.primary,title:e.platform||n,children:[i?(0,Z.jsx)(`a`,{href:i,className:`hover:underline`,target:i.startsWith(`http`)?`_blank`:void 0,rel:`noopener noreferrer`,children:r}):r,e.label&&(0,Z.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.label})]},`${n}:${r}:${t}`)})}),(0,Z.jsx)(Th,{title:`Identifiers`,count:r.length,children:r.map((e,t)=>(0,Z.jsxs)(Eh,{icon:g,primary:e.primary,children:[(0,Z.jsx)(`span`,{className:`font-mono text-xs`,children:e.identifier}),(0,Z.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:[e.type,e.provider].filter(Boolean).join(` · `)})]},`${e.type}:${e.identifier}:${t}`))}),(0,Z.jsx)(Th,{title:`Organizations`,count:a.length,children:a.map((e,t)=>(0,Z.jsxs)(Eh,{icon:$e,children:[e.name,e.role&&(0,Z.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.role})]},`${e.name}:${t}`))}),(0,Z.jsx)(Th,{title:`Links`,count:o.length,children:o.map((e,t)=>(0,Z.jsxs)(Eh,{icon:fn,children:[(0,Z.jsx)(`span`,{className:`font-mono text-xs`,children:e.target}),e.type&&(0,Z.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.type})]},`${e.type}:${e.target}:${t}`))}),s.length>0&&(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:s.map(e=>(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:e},e))})]})}function Oh({document:e}){let t=String(e.metadata?.contentType||`application/octet-stream`);return(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`No inline preview available for `,(0,Z.jsx)(`span`,{className:`font-mono`,children:t}),`. Use Download.`]})}function kh(e){let t=e.schema;if(t===`data/schema/note`)return Hm;if(t===`data/schema/drawing`)return Fm;if(t===`data/schema/task`)return mh;if(t===`data/schema/message/email`)return bh;if(t===`data/schema/identity`||t.startsWith(`data/schema/identity/`))return Dh;if(t===`data/schema/tab`||t===`data/schema/link`){let t=String(e.data?.url??e.data?.uri??``);return Za(t)?Um:Gm(t)?Wm:qm}if(t!==`data/schema/file`)return null;let n=String(e.metadata?.contentType||``);switch(to(n,so(e))){case`image`:return Fm;case`audio`:return Im;case`video`:return Lm;case`pdf`:return Rm;case`markdown`:return Hm;case`text`:return Vm;default:return Oh}}function Ah({workspaceId:e,document:t,className:n}){let r=kh(t);return r?(0,Z.jsx)(r,{workspaceId:e,document:t,className:n}):(0,Z.jsx)(`pre`,{className:`overflow-auto p-2 text-xs`,children:JSON.stringify(t.data,null,2)})}var jh=15,Mh=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function Nh(e){return String(e).padStart(2,`0`)}function Ph(e){let t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(e||``);return t?{date:`${t[1]}-${t[2]}-${t[3]}`,time:`${t[4]}:${t[5]}`}:null}function Fh(e){return`${e.getFullYear()}-${Nh(e.getMonth()+1)}-${Nh(e.getDate())}`}function Ih(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(t,n-1,r)}function Lh(){let e=new Date;return e.setSeconds(0,0),e.setMinutes(Math.ceil(e.getMinutes()/jh)*jh),`${Nh(e.getHours())}:${Nh(e.getMinutes())}`}function Rh(){let e=[];for(let t=0;t<1440;t+=jh)e.push(`${Nh(Math.floor(t/60))}:${Nh(t%60)}`);return e}var zh=Rh();function Bh(e){let t=new Date(e.getFullYear(),e.getMonth(),1),n=(t.getDay()+6)%7,r=new Date(t);return r.setDate(t.getDate()-n),Array.from({length:42},(e,t)=>{let n=new Date(r);return n.setDate(r.getDate()+t),n})}function Vh(e){let[t,n]=e.split(`:`).map(Number);return new Date(2e3,0,1,t,n).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`})}function Hh(e){let t=Ph(e);if(!t)return``;let[n,r,i]=t.date.split(`-`).map(Number),[a,o]=t.time.split(`:`).map(Number);return new Date(n,r-1,i,a,o).toLocaleString(void 0,{weekday:`short`,day:`numeric`,month:`short`,year:`numeric`,hour:`2-digit`,minute:`2-digit`})}function Uh({value:e,onChange:t,id:n,placeholder:r=`Pick a date & time`,clearable:i=!0,disabled:a=!1,compact:o=!1,className:s=``}){let[c,l]=(0,X.useState)(!1),u=(0,X.useRef)(null),d=Ph(e),f=d?Hh(e):``;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{ref:u,id:n,type:`button`,disabled:a,onClick:()=>l(e=>!e),"aria-haspopup":`dialog`,"aria-expanded":c,className:K(`inline-flex w-full items-center gap-2 rounded-md border border-input bg-transparent text-left shadow-elevation-1 transition-colors`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`,o?`h-6 px-1.5 text-[11px]`:`h-9 px-3 py-1 text-sm`,!d&&`text-muted-foreground`,s),children:[(0,Z.jsx)(Ge,{className:K(`shrink-0 text-muted-foreground`,o?`h-3 w-3`:`h-4 w-4`)}),(0,Z.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:f||r}),i&&d&&(0,Z.jsx)(`span`,{role:`button`,tabIndex:-1,"aria-label":`Clear date`,title:`Clear`,onClick:e=>{e.stopPropagation(),t(``)},className:`shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(je,{className:o?`h-2.5 w-2.5`:`h-3.5 w-3.5`})})]}),c&&(0,Z.jsx)(Wh,{anchorRef:u,value:e,onChange:t,onClose:()=>l(!1)})]})}function Wh({anchorRef:e,value:t,onChange:n,onClose:r}){let i=Ph(t),a=i?.date??Fh(new Date),o=i?.time??null,[s,c]=(0,X.useState)(()=>{let e=Ih(a);return new Date(e.getFullYear(),e.getMonth(),1)}),l=(0,X.useRef)(null),u=(0,X.useRef)(null),[d,f]=(0,X.useState)(null);(0,X.useLayoutEffect)(()=>{let t=l.current,n=e.current;if(!t||!n)return;let r=()=>{let e=n.getBoundingClientRect(),{width:r,height:i}=t.getBoundingClientRect(),a=e.bottom+4,o=a+i+8>window.innerHeight?Math.max(8,e.top-i-4):a,s=Math.max(8,Math.min(e.left,window.innerWidth-r-8));f({x:s,y:o})};r();let i=new ResizeObserver(r);return i.observe(t),window.addEventListener(`resize`,r),window.addEventListener(`scroll`,r,!0),()=>{i.disconnect(),window.removeEventListener(`resize`,r),window.removeEventListener(`scroll`,r,!0)}},[e]),(0,X.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),r())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[r]);let p=(0,X.useMemo)(()=>!o||zh.includes(o)?zh:[...zh,o].sort(),[o]);(0,X.useEffect)(()=>{let e=u.current,t=e?.querySelector(`[data-selected="true"]`);e&&t&&(e.scrollTop=t.offsetTop-e.clientHeight/2+t.clientHeight/2)},[]);let m=(e,t)=>n(`${e}T${t}`),h=e=>{let t=o??Lh();m(Fh(e),t),e.getMonth()!==s.getMonth()&&c(new Date(e.getFullYear(),e.getMonth(),1))},g=e=>{m(a,e),r()},_=e=>{let t=new Date;t.setDate(t.getDate()+e);let n=o??Lh();m(Fh(t),n),c(new Date(t.getFullYear(),t.getMonth(),1))},v=Fh(new Date),y=Bh(s);return(0,pf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:r}),(0,Z.jsxs)(`div`,{ref:l,role:`dialog`,"aria-label":`Choose date and time`,className:`fixed z-50 flex max-w-[95vw] gap-2 rounded-md border bg-popover p-2 text-popover-foreground shadow-elevation-4`,style:{left:d?.x??-9999,top:d?.y??-9999,visibility:d?`visible`:`hidden`},children:[(0,Z.jsxs)(`div`,{className:`w-[236px]`,children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-center justify-between`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(new Date(s.getFullYear(),s.getMonth()-1,1)),"aria-label":`Previous month`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(ve,{className:`h-4 w-4`})}),(0,Z.jsx)(`span`,{className:`text-xs font-medium`,children:s.toLocaleDateString(void 0,{month:`long`,year:`numeric`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(new Date(s.getFullYear(),s.getMonth()+1,1)),"aria-label":`Next month`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(B,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5 px-0.5 pb-1 text-center text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:Mh.map(e=>(0,Z.jsx)(`span`,{children:e},e))}),(0,Z.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5`,children:y.map(e=>{let t=Fh(e),n=e.getMonth()!==s.getMonth(),r=t===a&&!!i;return(0,Z.jsx)(`button`,{type:`button`,onClick:()=>h(e),"aria-pressed":r,className:K(`h-7 rounded text-xs tabular-nums transition-colors`,n?`text-muted-foreground/40`:`text-foreground`,r?`bg-primary text-primary-foreground`:`hover:bg-muted`,!r&&t===v&&`font-semibold ring-1 ring-inset ring-border`),children:e.getDate()},t)})}),(0,Z.jsx)(`div`,{className:`mt-1.5 flex gap-1`,children:[[`Today`,0],[`Tomorrow`,1],[`Next week`,7]].map(([e,t])=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>_(t),className:`flex-1 rounded border border-border px-1.5 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:e},e))})]}),(0,Z.jsxs)(`div`,{className:`flex w-[104px] flex-col`,children:[(0,Z.jsx)(`input`,{type:`time`,step:900,value:o??``,onChange:e=>{e.target.value&&m(a,e.target.value.slice(0,5))},"aria-label":`Time`,className:`mb-1 h-7 w-full rounded border border-input bg-transparent px-1.5 text-xs tabular-nums focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`}),(0,Z.jsx)(`div`,{ref:u,className:`max-h-[236px] flex-1 overflow-y-auto pr-0.5`,children:p.map(e=>{let t=e===o;return(0,Z.jsx)(`button`,{type:`button`,"data-selected":t,onClick:()=>g(e),"aria-pressed":t,className:K(`block w-full rounded px-2 py-1 text-left text-xs tabular-nums transition-colors`,t?`bg-primary text-primary-foreground`:`hover:bg-muted`),children:Vh(e)},e)})})]})]})]}),document.body)}var Gh={1:`1: Highest`,2:`2`,3:`3: High`,4:`4`,5:`5: Medium`,6:`6`,7:`7: Low`,8:`8`,9:`9: Lowest`},Kh=`flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-elevation-1 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`,qh=`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`;function Jh({title:e,setTitle:t,description:n,setDescription:r,status:i,setStatus:a,priority:o,setPriority:s,due:c,setDue:l,idPrefix:u=`todo`}){return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`${u}-title`,children:`Title`}),(0,Z.jsx)(q,{id:`${u}-title`,value:e,onChange:e=>t(e.target.value),placeholder:`What needs doing?`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`${u}-desc`,children:`Description`}),(0,Z.jsx)(`textarea`,{id:`${u}-desc`,value:n,onChange:e=>r(e.target.value),rows:3,placeholder:`Optional details…`,className:qh})]}),(0,Z.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`${u}-due`,children:`Due`}),(0,Z.jsx)(Uh,{id:`${u}-due`,value:c,onChange:l,placeholder:`No due date`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`${u}-priority`,children:`Priority`}),(0,Z.jsxs)(`select`,{id:`${u}-priority`,value:o===``?``:String(o),onChange:e=>s(e.target.value===``?``:Number(e.target.value)),className:Kh,children:[(0,Z.jsx)(`option`,{value:``,children:`None`}),[1,2,3,4,5,6,7,8,9].map(e=>(0,Z.jsx)(`option`,{value:e,children:Gh[e]},e))]})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`${u}-status`,children:`Status`}),(0,Z.jsx)(`select`,{id:`${u}-status`,value:i,onChange:e=>a(e.target.value),className:Kh,children:eh.map(e=>(0,Z.jsx)(`option`,{value:e,children:th[e]},e))})]})]})}var Yh=`3.0`,Xh=[`person`,`organization`,`service`,`bot`],Zh={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},Qh=[`email`,`phone`,`sms`,`chat`,`web`],$h=[`email`,`github`,`slack`,`matrix`,`gpg`,`url`];function eg(e){let t=e.primaryEmail.trim().toLowerCase(),n=e.channels.map(e=>({...e,kind:e.kind.trim(),value:e.value.trim(),label:e.label?.trim()||void 0})).filter(e=>e.kind&&e.value);if(t&&!n.some(e=>e.kind===`email`&&e.value===t)){for(let e of n)e.kind===`email`&&(e.primary=!1);n.push({kind:`email`,value:t,label:void 0,primary:!0})}let r=e.given.trim(),i=e.family.trim();return{displayName:e.displayName.trim(),...t?{primaryEmail:t}:{},...r||i?{name:{...r?{given:r}:{},...i?{family:i}:{}}}:{},channels:n,identifiers:e.identifiers.map(e=>({...e,type:e.type.trim(),identifier:e.identifier.trim(),provider:e.provider?.trim()||void 0})).filter(e=>e.type&&e.identifier),organizations:e.organizations.map(({identityId:e,...t})=>({...t,name:t.name.trim(),role:t.role?.trim()||void 0,...e?{metadata:{identityId:e}}:{}})).filter(e=>e.name)}}function tg(e){let t=e?.data??{},n=t.name&&typeof t.name==`object`?t.name:{},r=e=>Array.isArray(e)?e:[],i=Qa(String(e?.schema||``),eo);return{displayName:String(t.displayName||``),type:Xh.includes(i)?i:`person`,primaryEmail:String(t.primaryEmail||``),given:String(n.given||``),family:String(n.family||``),channels:r(t.channels),identifiers:r(t.identifiers),organizations:r(t.organizations).map(e=>({name:String(e.name||``),role:e.role?String(e.role):void 0,identityId:Number(e.metadata?.identityId)||void 0}))}}async function ng(e,t,n){if(!t||!e||e.mode!==`workspace`)return;let r=n.filter(e=>e.identityId);for(let n of r)try{await Wi(e.workspaceName,t,`member-of`,[n.identityId])}catch(e){console.error(`Failed to link organization`,n.name,e)}}function rg(e){let[t,n]=(0,X.useState)(e?.displayName??``),[r,i]=(0,X.useState)(e?.type??`person`),[a,o]=(0,X.useState)(e?.primaryEmail??``),[s,c]=(0,X.useState)(e?.given??``),[l,u]=(0,X.useState)(e?.family??``),[d,f]=(0,X.useState)(e?.channels??[]),[p,m]=(0,X.useState)(e?.identifiers??[]),[h,g]=(0,X.useState)(e?.organizations??[]),[_,v]=(0,X.useState)([]),[y,b]=(0,X.useState)(``),[x,S]=(0,X.useState)(!1),C={displayName:t,type:r,primaryEmail:a,given:s,family:l,channels:d,identifiers:p,organizations:h},w=!a.trim()||/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(a.trim()),T=t.trim().length>0&&w&&!x;async function E(e){S(!0);try{let t=y.trim(),n={schema:`${eo}/${C.type}`,schemaVersion:Yh,data:eg(C),...t?{comment:t}:{},metadata:{features:dp(_)}},r=await Yo(e,[n]);return await ng(e,r[0],h),r}finally{S(!1)}}return{displayName:t,setDisplayName:n,type:r,setType:i,primaryEmail:a,setPrimaryEmail:o,given:s,setGiven:c,family:l,setFamily:u,channels:d,setChannels:f,identifiers:p,setIdentifiers:m,organizations:h,setOrganizations:g,tags:_,setTags:v,comment:y,setComment:b,values:C,saving:x,canSave:T,emailValid:w,save:E}}var ig=`h-9 shrink-0 rounded-md border border-input bg-transparent px-2 text-sm shadow-elevation-1 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`;function ag({label:e,rows:t,onChange:n,blank:r,addLabel:i,children:a}){return(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsx)(bu,{children:e}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>n([...t,r()]),className:`inline-flex items-center gap-1 rounded-md px-1.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,Z.jsx)(nn,{className:`h-3 w-3`}),` `,i]})]}),t.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None yet.`}):(0,Z.jsx)(`div`,{className:`space-y-1.5`,children:t.map((r,i)=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[a(r,e=>n(t.map((t,n)=>n===i?{...t,...e}:t))),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>n(t.filter((e,t)=>t!==i)),className:`shrink-0 rounded p-1.5 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive`,"aria-label":`Remove ${e.toLowerCase()} row`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]},i))})]})}function og(e,t){let n=e[t].kind,r=e[t].primary;return e.map((e,i)=>e.kind===n?{...e,primary:!r&&i===t}:e)}function sg(e){let[t,n]=(0,X.useState)([]);return(0,X.useEffect)(()=>{if(!e)return;let t=!1;async function r(){try{let r=await Fa(e,`organization`);t||n(r.map(e=>({id:e.id,name:mo(e).title})))}catch{t||n([])}}return r(),()=>{t=!0}},[e]),t}function cg({idPrefix:e,workspaceName:t,displayName:n,setDisplayName:r,type:i,setType:a,primaryEmail:o,setPrimaryEmail:s,given:c,setGiven:l,family:u,setFamily:d,channels:f,setChannels:p,identifiers:m,setIdentifiers:h,organizations:g,setOrganizations:_,emailValid:v=!0}){let y=sg(t);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`${e}-display-name`,children:`Display name`}),(0,Z.jsx)(q,{id:`${e}-display-name`,value:n,onChange:e=>r(e.target.value),placeholder:`Jane Doe, Acme Ltd, build-bot…`,autoFocus:!0})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsxs)(`div`,{className:`w-40 space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`${e}-type`,children:`Type`}),(0,Z.jsx)(`select`,{id:`${e}-type`,value:i,onChange:e=>a(e.target.value),className:K(ig,`w-full`),children:Xh.map(e=>(0,Z.jsx)(`option`,{value:e,children:Zh[e]},e))})]}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`${e}-email`,children:`Primary email`}),(0,Z.jsx)(q,{id:`${e}-email`,type:`email`,value:o,onChange:e=>s(e.target.value),placeholder:`jane@example.com`}),!v&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid email address.`})]})]}),i===`person`&&(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`${e}-given`,children:`Given name`}),(0,Z.jsx)(q,{id:`${e}-given`,value:c,onChange:e=>l(e.target.value),placeholder:`Jane`})]}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`${e}-family`,children:`Family name`}),(0,Z.jsx)(q,{id:`${e}-family`,value:u,onChange:e=>d(e.target.value),placeholder:`Doe`})]})]}),(0,Z.jsx)(ag,{label:`Channels`,rows:f,onChange:p,blank:()=>({kind:`email`,value:``}),addLabel:`Add channel`,children:(e,t)=>(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`select`,{value:e.kind,onChange:e=>t({kind:e.target.value}),className:K(ig,`w-24`),children:[Qh.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e)),!Qh.includes(e.kind)&&(0,Z.jsx)(`option`,{value:e.kind,children:e.kind})]}),(0,Z.jsx)(q,{value:e.value,onChange:e=>t({value:e.target.value}),placeholder:e.kind===`phone`?`+421…`:`address or handle`,className:`min-w-0 flex-1`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(og(f,f.indexOf(e))),className:K(`shrink-0 rounded p-1.5 transition-colors hover:bg-muted`,e.primary?`text-data-5`:`text-muted-foreground`),title:e.primary?`Primary for this kind`:`Make primary for this kind`,"aria-pressed":!!e.primary,children:(0,Z.jsx)(Nn,{className:K(`h-3.5 w-3.5`,e.primary&&`fill-current`)})})]})}),(0,Z.jsx)(ag,{label:`Identifiers`,rows:m,onChange:h,blank:()=>({type:`github`,identifier:``}),addLabel:`Add identifier`,children:(e,t)=>(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`select`,{value:e.type,onChange:e=>t({type:e.target.value}),className:K(ig,`w-24`),children:[$h.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e)),!$h.includes(e.type)&&(0,Z.jsx)(`option`,{value:e.type,children:e.type})]}),(0,Z.jsx)(q,{value:e.identifier,onChange:e=>t({identifier:e.target.value}),placeholder:`octocat, U024BE7LH, 0xABCD…`,className:`min-w-0 flex-1 font-mono text-xs`})]})}),(0,Z.jsx)(ag,{label:`Organizations`,rows:g,onChange:_,blank:()=>({name:``}),addLabel:`Add organization`,children:(e,t)=>(0,Z.jsxs)(Z.Fragment,{children:[y.length>0?(0,Z.jsxs)(`select`,{value:e.identityId?String(e.identityId):``,onChange:e=>{let n=y.find(t=>String(t.id)===e.target.value);t(n?{identityId:n.id,name:n.name}:{identityId:void 0})},className:K(ig,`min-w-0 flex-1`),children:[(0,Z.jsx)(`option`,{value:``,children:`Other… (type a name)`}),y.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.name},e.id))]}):null,!e.identityId&&(0,Z.jsx)(q,{value:e.name,onChange:e=>t({name:e.target.value}),placeholder:`Acme Ltd`,className:`min-w-0 flex-1`}),e.identityId&&(0,Z.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,title:`Linked — saving relates this identity to that organization`,children:(0,Z.jsx)(qt,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(q,{value:e.role??``,onChange:e=>t({role:e.target.value}),placeholder:`Role`,className:`w-28 shrink-0`})]})})]})}function lg(e){return e===`data/schema/note`||e===`data/schema/link`||e===`data/schema/tab`||e===`data/schema/task`||e===`data/schema/drawing`||e===`data/schema/identity`||e.startsWith(`data/schema/identity/`)}function ug(e){return lg(e.schema)||ho(e)}function dg(e){return e===`data/schema/link`?{urlKey:`uri`,titleKey:`label`}:e===`data/schema/tab`?{urlKey:`url`,titleKey:`title`}:{urlKey:null,titleKey:`title`}}async function fg(e,t,n){try{let r=new Set(n.map(e=>e.identityId).filter(Boolean)),i=await ya(e,t,{resolve:!1}),a=new Set(i.outgoing.filter(e=>e.p===`member-of`).map(e=>e.to));for(let n of r)a.has(n)||await Wi(e,t,`member-of`,[n]);for(let n of a)r.has(n)||await Wr(e,t,`member-of`,n)}catch(e){console.error(`Failed to sync organization relations`,e)}}function pg({document:e,workspaceId:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=Ya(),a=lg(e.schema),o=e.schema===Xa,s=ho(e),c=xo(e)??`markdown`,l=s&&co(e),u=e.schema===io,d=e.schema===`data/schema/identity`||e.schema.startsWith(`data/schema/identity/`),{urlKey:f,titleKey:p}=dg(e.schema),[m,h]=(0,X.useState)(f?String(e.data?.[f]??``):``),[g,_]=(0,X.useState)(String(e.data?.[p]??``)),[v,y]=(0,X.useState)(String(e.data?.content??``)),[b,x]=(0,X.useState)(String(e.data?.description??``)),[S,C]=(0,X.useState)(e.data?.status??`pending`),[w,T]=(0,X.useState)(typeof e.data?.priority==`number`?e.data.priority:``),[E,D]=(0,X.useState)(e.data?.dueDate?ih(String(e.data.dueDate)):oh()),O=rg(tg(e)),[k,A]=(0,X.useState)(String(e.comment??``)),j=e.metadata?.geo??null,[M,N]=(0,X.useState)(j),P=JSON.stringify(M??null)!==JSON.stringify(j??null),ee=e.features??e.metadata?.features,[F,I]=(0,X.useState)(fp(ee).length?fp(ee):e.data?.tags??[]),te=So(t,e.id,{mode:`text`,enabled:s&&!l,maxTextLength:vo,version:e.checksumArray?.[0]??null}),[ne,L]=(0,X.useState)(null),re=`${e.id}:${e.checksumArray?.[0]??``}`;s&&te.text!=null&&ne!==re&&(L(re),y(te.text));let[R,ie]=(0,X.useState)([]),[ae,oe]=(0,X.useState)(!1),{replicating:z,mirror:se}=Ji(e);(0,X.useEffect)(()=>{let e=!1;return Tr(t).then(t=>{e||ie(t)}).catch(()=>{}),()=>{e=!0}},[t]);let ce=!f||(()=>{try{return new URL(m.trim()),!0}catch{return!1}})(),B=!ae&&(s?!l&&te.text!=null&&!te.loading:a?d?O.displayName.trim().length>0&&O.emailValid:u?g.trim().length>0:o?v.trim().length>0:ce:!0),V=async()=>{oe(!0);try{if(s){await Co(t,e,v,{comment:k.trim(),...P?{metadata:{geo:M}}:{}}),r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n();return}let i={id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,comment:k.trim()};if(d){let{type:t,...n}=e.data??{};i.schema=`${eo}/${O.values.type}`,i.data={...n,...eg(O.values)},i.metadata={features:dp(F)}}else if(u)i.data={...e.data,...sh({title:g,description:b,status:S,priority:w,due:E})},i.metadata={features:dp(F)};else if(a){let t=F.map(e=>e.trim()).filter(Boolean),n;o?n={...g.trim()?{title:g.trim()}:{},content:v}:(n={...e.data},f&&(n[f]=m.trim()),g.trim()?n[p]=g.trim():delete n[p],n.tags=t),i.data=n,i.metadata={features:dp(F)}}P&&(i.metadata={...i.metadata??{},geo:M}),await Li(t,i),d&&await fg(t,e.id,O.values.organizations),r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n()}catch(e){i(e instanceof Error?e.message:`Failed to update document`)}finally{oe(!1)}};return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[a&&f&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`edit-url`,children:`URL`}),(0,Z.jsx)(q,{id:`edit-url`,value:m,onChange:e=>h(e.target.value),placeholder:`https://example.com`,className:`font-mono text-xs`}),m.trim()&&!ce&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),a&&d&&(0,Z.jsx)(cg,{idPrefix:`edit-identity`,workspaceName:t,...O,emailValid:O.emailValid}),a&&u&&(0,Z.jsx)(Jh,{idPrefix:`edit-todo`,title:g,setTitle:_,description:b,setDescription:x,status:S,setStatus:C,priority:w,setPriority:T,due:E,setDue:D}),a&&!u&&!d&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`edit-title`,children:`Title`}),(0,Z.jsx)(q,{id:`edit-title`,value:g,onChange:e=>_(e.target.value),placeholder:o?`Optional; defaults to today's date`:`Optional display title`})]}),(o||s)&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{children:`Body`}),l?(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`This file is too large to edit here (`,`>`,1e3,` kB) — download it instead.`]}):s&&te.error?(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:te.error}):s&&te.text==null?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading content…`}):(0,Z.jsx)(yo,{kind:o?`markdown`:c,value:v,onChange:y,placeholder:o?`Write your note…`:void 0})]}),a&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{children:`Tags`}),(0,Z.jsx)(up,{tags:F,onChange:I,suggestions:R})]}),(0,Z.jsx)(wp,{value:M,onChange:N}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`edit-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`edit-comment`,value:k,onChange:e=>A(e.target.value),rows:3,placeholder:`Add context you can't infer from the content, e.g. “sofa from the cozmo bar in Košice”`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2 pt-2`,children:[(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:n,disabled:ae,children:`Cancel`}),(0,Z.jsx)(J,{size:`sm`,onClick:V,disabled:!B,children:ae?z?`Replicating to ${se.label}…`:`Saving…`:`Save changes`})]})]})}var mg=(0,X.createContext)(null),hg={open:()=>{},close:()=>{}};function gg(){return(0,X.useContext)(mg)??hg}var _g=`main`,vg=(0,X.createContext)(null);function yg(){return(0,X.useContext)(vg)}function bg({relation:e,workspaceId:t,direction:n,onRemove:r,removing:i}){let{open:a}=gg(),o=Pp(),s=yg(),c=n===`out`?e.to:e.from,l=e.document??null,u=!e.meta||e.meta.src===`doc`;return(0,Z.jsxs)(`div`,{className:`group flex items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted/60`,children:[n===`out`?(0,Z.jsx)(_t,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}):(0,Z.jsx)(Pn,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),l?(0,Z.jsx)(Jf,{document:l,size:3.5}):null,l?(0,Z.jsx)(`button`,{type:`button`,onClick:()=>s?o.open(l,t):a(l,t),className:`min-w-0 flex-1 truncate text-left hover:underline`,title:`Open document ${c}`,children:mo(l).title}):(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1 truncate italic text-muted-foreground`,children:[`Document `,c,` (not available)`]}),(0,Z.jsxs)(`span`,{className:`shrink-0 font-mono text-[10px] text-muted-foreground`,children:[`#`,c]}),!u&&(0,Z.jsx)(`span`,{className:`shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,title:`Derived by ${e.meta?.src}`,children:e.meta?.src}),u&&(0,Z.jsx)(`button`,{type:`button`,onClick:r,disabled:i,className:`shrink-0 rounded p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-destructive/10 hover:text-destructive group-hover:opacity-100 disabled:opacity-40`,title:`Remove relation`,"aria-label":`Remove relation`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})}function xg({document:e,workspaceId:t}){let{showSuccessToast:n,showErrorToast:r}=Ya(),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),m=(0,X.useCallback)(async()=>{try{let n=await ya(t,e.id);a(n),s(null)}catch(e){s(e instanceof Error?e.message:String(e))}},[t,e.id]),h=`${t}:${e.id}`,[g,_]=(0,X.useState)(h);h!==g&&(_(h),a(null),s(null)),(0,X.useEffect)(()=>{async function e(){await m()}return e(),window.addEventListener(Gp,e),()=>window.removeEventListener(Gp,e)},[m]);let v=async(i,a)=>{let o=a===`out`?i.to:i.from;if(o==null)return;let s=`${a}:${i.p}:${o}`;p(s);try{await Wr(t,e.id,i.p,o,a),n(`Relation removed`),Kp()}catch(e){r(e instanceof Error?e.message:`Failed to remove relation`)}finally{p(null)}},y=[{dir:`out`,title:`Points at`,hint:`this document as the subject`,entries:i?.outgoing??[]},{dir:`in`,title:`Pointed at by`,hint:`this document as the object`,entries:i?.incoming??[]}];return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold`,children:`Documents`}),(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>l(!0),children:[(0,Z.jsx)(nn,{className:`mr-1 h-3 w-3`}),` Add relation`]})]}),o?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:o}):i?y.every(e=>e.entries.length===0)?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No related documents.`}):(0,Z.jsx)(`div`,{className:`space-y-4`,children:y.filter(e=>e.entries.length>0).map(({dir:e,title:n,hint:r,entries:i})=>(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`mb-1 text-xs font-medium text-muted-foreground`,title:r,children:n}),Array.from(new Set(i.map(e=>e.p))).map(n=>(0,Z.jsxs)(`div`,{className:`mb-2`,children:[(0,Z.jsx)(`p`,{className:`px-2 font-mono text-[11px] text-muted-foreground`,children:n}),i.filter(e=>e.p===n).map(n=>{let r=e===`out`?n.to:n.from,i=`${e}:${n.p}:${r}`;return(0,Z.jsx)(bg,{relation:n,workspaceId:t,direction:e,removing:f===i,onRemove:()=>void v(n,e)},i)})]},n))]},e))}):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading relations…`}),c&&(0,Z.jsx)(sp,{onClose:()=>{u||l(!1)},children:(0,Z.jsx)(ap,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,title:`Relate to…`,tabs:[`relations`],fixedWorkspaceName:t,documentCount:1,saving:u,relationPredicates:i?.predicates,relationExcludeIds:new Set([e.id]),onClose:()=>l(!1),onConfirm:()=>{},onConfirmRelation:async({predicate:i,direction:a,targetIds:o})=>{d(!0);try{await Wi(t,e.id,i,o,a),n(`Related to ${o.length} document${o.length===1?``:`s`}`),l(!1),Kp()}catch(e){r(e instanceof Error?e.message:`Failed to create relation`)}finally{d(!1)}}})})]})}window.EXCALIDRAW_ASSET_PATH=`/excalidraw/`;var Sg=(0,X.lazy)(()=>m(()=>import(`./SketchEditor-vg1HMZ0V.js`),__vite__mapDeps([8,3,4,1,9,10,11,12,13,14,15,16,17,18,19,20]))),Cg=(0,X.lazy)(()=>m(()=>import(`./TextDocumentEditor-B6bUq9US.js`),__vite__mapDeps([21,3,4,9,11,10,12,13,22,1,19]))),wg={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`},Tg={reply:He,replyAll:ee,forward:We};function Eg({document:e,workspaceId:t,initialEdit:n=!1,onChanged:r}){let i=bo()!=null,{showErrorToast:a}=Ya(),[o,s]=(0,X.useState)(null),c=e.schema===`data/schema/message/email`,l=!i&&(c||[`slack`,`whatsapp`].includes(String(e.data?.platform))),u=c?[`reply`,`replyAll`,`forward`]:[`reply`],d=e=>s(t=>t===e?null:e),f=!i,[p,m]=(0,X.useState)(n&&ug(e)),h=e.schema===ro,[g,_]=(0,X.useState)(!1),v=e.schema===`data/schema/note`||ho(e),[y,b]=(0,X.useState)(!1),x=`${e.id}:${n}`,[S,C]=(0,X.useState)(x);return x!==S&&(C(x),m(n&&ug(e))),p&&f?(0,Z.jsx)(pg,{document:e,workspaceId:t,onClose:()=>{m(!1),r?.()}}):(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3`,children:[f&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[l&&u.map(e=>{let t=Tg[e];return(0,Z.jsxs)(J,{size:`sm`,variant:o===e?`secondary`:`outline`,onClick:()=>d(e),children:[(0,Z.jsx)(t,{className:`mr-1.5 h-3.5 w-3.5`}),wg[e]]},e)}),e.schema===`data/schema/file`&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>Gr(t,e.id,so(e)||`document-${e.id}`).catch(e=>a(e instanceof Error?e.message:String(e))),children:[(0,Z.jsx)(wn,{className:`mr-1 h-3 w-3`}),` Download`]}),h&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>_(!0),children:[(0,Z.jsx)(re,{className:`mr-1 h-3 w-3`}),` Edit sketch`]}),v&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>b(!0),children:[(0,Z.jsx)(dr,{className:`mr-1 h-3 w-3`}),` Open editor`]}),(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>m(!0),children:[(0,Z.jsx)(ye,{className:`mr-1 h-3 w-3`}),` Edit`]})]}),g&&(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,Z.jsx)(Sg,{doc:e,workspaceName:t,onSaved:()=>{_(!1),r?.()},onClose:()=>_(!1),onDetails:()=>{_(!1),m(!0)}})}),y&&(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading editor…`})}),children:(0,Z.jsx)(Cg,{doc:e,workspaceName:t,onSaved:()=>{b(!1),r?.()},onClose:()=>b(!1),onDetails:()=>{b(!1),m(!0)}})}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:[(0,Z.jsx)(Ah,{workspaceId:t,document:e}),o&&l&&(0,Z.jsx)(fm,{workspaceId:t,replyToDocumentId:Number(e.id),mode:o,originalSubject:c&&typeof e.data?.subject==`string`?e.data.subject:void 0,onClose:()=>s(null)},`${e.id}:${o}`)]}),e.comment?.trim()&&(0,Z.jsxs)(`div`,{className:`shrink-0 rounded-md border border-border bg-muted/40 px-3 py-2`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground mb-0.5`,children:`Comment`}),(0,Z.jsx)(`p`,{className:`text-sm whitespace-pre-wrap`,children:e.comment})]})]})}var Dg=e=>e?new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`long`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`}):`—`,Og=e=>!Number.isFinite(e)||!e?null:e>=1?`${e}s`:`1/${Math.round(1/e)}s`;function kg({meta:e}){let{geo:t,exif:n,dimensions:r}=e;if(!t&&!n&&!r)return null;let i=(e,t)=>t==null||t===``?null:(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`span`,{className:`font-medium`,children:[e,`:`]}),(0,Z.jsx)(`span`,{className:`ml-2`,children:t})]});return(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Photo`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[r&&i(`Dimensions`,r.width&&r.height?`${r.width} × ${r.height}`:null),n&&i(`Camera`,[n.make,n.model].filter(Boolean).join(` `)),n&&i(`Lens`,n.lensModel),n&&i(`Aperture`,Number.isFinite(n.fNumber)?`ƒ/${n.fNumber}`:null),n&&i(`Shutter`,Og(n.exposureTime)),n&&i(`ISO`,Number.isFinite(n.iso)?n.iso:null),n&&i(`Focal length`,Number.isFinite(n.focalLength)?`${n.focalLength} mm`:null),n&&i(`Captured`,Dg(n.capturedAt)),t&&Number.isFinite(t.lat)&&Number.isFinite(t.lon)&&i(`Location`,(0,Z.jsxs)(`a`,{href:`https://www.openstreetmap.org/?mlat=${t.lat}&mlon=${t.lon}#map=15/${t.lat}/${t.lon}`,target:`_blank`,rel:`noopener noreferrer`,className:`text-primary underline underline-offset-2`,children:[t.lat.toFixed(5),`, `,t.lon.toFixed(5),Number.isFinite(t.alt)?` · ${Math.round(t.alt)} m`:``]}))]})]})}function Ag({document:e}){let t=e.metadata;return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Basic Information`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,Z.jsx)(`span`,{className:`ml-2 font-mono`,children:e.id})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Schema:`}),(0,Z.jsx)(`span`,{className:`ml-2 font-mono`,children:e.schema})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Schema Version:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:e.schemaVersion})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Created:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:Dg(e.createdAt)})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Updated:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:Dg(e.updatedAt)})]})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Metadata`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Content Type:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentType??`—`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Content Encoding:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentEncoding??`—`})]}),Number.isFinite(e.metadata?.size)&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Size:`}),(0,Z.jsxs)(`span`,{className:`ml-2`,children:[e.metadata?.size,` bytes`]})]})]})]}),(0,Z.jsx)(kg,{meta:t}),Array.isArray(e.locations)&&e.locations.length>0&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Locations`}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.locations.map((e,t)=>{let{backend:n,key:r}=Pg(e.url);return(0,Z.jsxs)(`div`,{className:`flex items-baseline gap-2 text-sm font-mono`,children:[(0,Z.jsx)(`span`,{className:`font-medium shrink-0`,children:n}),r&&(0,Z.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),Array.isArray(e.checksumArray)&&e.checksumArray.length>0&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Checksums`}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.checksumArray.map((e,t)=>{let[n,r]=e.split(`/`);return(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-mono`,children:[(0,Z.jsxs)(`span`,{className:`font-medium`,children:[n,`:`]}),(0,Z.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),e.indexOptions&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Index Options`}),(0,Z.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`FTS Search Fields:`}),(0,Z.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.ftsSearchFields??[]).map((e,t)=>(0,Z.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Vector Embedding Fields:`}),(0,Z.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.vectorEmbeddingFields??[]).map((e,t)=>(0,Z.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]})]})]})]})}function jg({document:e}){let{showSuccessToast:t,showErrorToast:n}=Ya(),r=JSON.stringify(e,null,2);return(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`div`,{className:`flex justify-end`,children:(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:async()=>{try{await navigator.clipboard.writeText(r),t(`Copied to clipboard`)}catch{n(`Copy failed`)}},children:[(0,Z.jsx)(Ct,{className:`mr-1 h-3 w-3`}),` Copy to clipboard`]})}),(0,Z.jsx)(`pre`,{className:`overflow-x-auto rounded-lg bg-muted p-4 text-xs`,children:r})]})}function Mg({document:e,workspaceId:t}){let[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null),o=`${t}:${e.id}`,[s,c]=(0,X.useState)(o);return o!==s&&(c(o),r(null),a(null)),(0,X.useEffect)(()=>{let n=!1;return Vr(t,e.id).then(e=>{n||r(e)}).catch(e=>{n||a(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[o]),i?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i}):n?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[[{title:`Context tree`,type:`context`},{title:`Directory tree`,type:`directory`}].map(({title:e,type:t})=>{let r=n.filter(e=>e.type===t),i=r.flatMap(e=>e.paths.map(t=>({tree:e.tree,path:t})));return(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`mb-3 font-semibold`,children:e}),i.length===0?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No placements.`}):(0,Z.jsx)(`div`,{className:`space-y-1`,children:i.map(({tree:e,path:t},n)=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm`,children:[(0,Z.jsx)(`span`,{className:`break-all font-mono text-xs`,children:t}),r.length>1&&(0,Z.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:[`(`,e,`)`]})]},`${e}:${t}:${n}`))})]},t)}),(0,Z.jsx)(xg,{document:e,workspaceId:t})]}):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading memberships...`})}function Ng(e){return e===`stored`?Jt:e===`workspace-file`?_e:e===`imap`?vt:e===`readonly`?C:yt}function Pg(e){let t=e.match(/^([a-z][a-z0-9+.-]*):\/\/([^/]*)\/?(.*)$/i);return t?{backend:`${t[1]}://${t[2]}`,key:t[3]}:{backend:e,key:``}}function Fg({document:e,workspaceId:t,onChanged:n}){let{showSuccessToast:r,showErrorToast:i}=Ya(),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(!1),_=`${t}:${e.id}`,[v,y]=(0,X.useState)(_);_!==v&&(y(_),o(null),c(null),f(null));let b=()=>{Pr(t,e.id).then(o).catch(e=>c(e instanceof Error?e.message:String(e)))};(0,X.useEffect)(()=>{let n=!1;return Pr(t,e.id).then(e=>{n||o(e)}).catch(e=>{n||c(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[_]);let x=async(a,o)=>{u(a),f(null);try{let i=await Er(t,[e.id],{urls:[a],...o===void 0?{}:{keepDocument:o}}),s=i.successful[0];if(!s)throw Error(i.failed[0]?.reason||`Destroy failed`);s.docDeleted?r(`Removed from backend; document removed from index`):s.deleted.includes(a)?r(`Removed from backend`):r(`Reference dropped (backend is read-only)`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n?.(),b()}catch(e){i(e instanceof Error?e.message:String(e))}finally{u(null)}},S=async(a,o,s)=>{g(!0);try{let i=await Oi(t,[e.id],{to:a,mode:o,keepDocument:s.keepDocument,folder:s.folder,filename:s.filename,onConflict:s.onConflict}),c=i.successful[0];if(!c)throw Error(i.failed[0]?.reason||`Transfer failed`);let l=c.transfers?.flatMap(e=>e.state===`unchanged`?[]:[e.backend])??[],u=a.join(`, `);o===`delete`?r(`Deleted from ${u}`):l.length===0?r(`Nothing to do — already on ${u}`):r(`${o===`move`?`Moved to`:`Copied to`} ${l.join(`, `)}${c.transfers?.some(e=>e.state===`pending`)?` (pending sync)`:``}`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),m(null),n?.(),b()}catch(e){i(e instanceof Error?e.message:String(e))}finally{g(!1)}},C=e=>{if((a?.length??0)<=1){f(e.url);return}window.confirm(`Remove this copy from the backend?\n\n${e.url}`)&&x(e.url)};if(s)return(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:s});if(!a)return(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading locations...`});let w=a.length===0,T=so(e);return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-3 py-2 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(Jt,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`font-mono text-xs`,children:`workspace:db`}),(0,Z.jsxs)(`span`,{className:`truncate text-xs text-muted-foreground`,children:[`index entry (id `,e.id,`)`]})]}),(0,Z.jsx)(`span`,{className:`shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:`json`})]}),w?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No byte locations; this object lives only in the workspace database, so there is no file data to copy or move.`}):(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>m(`copy`),title:`Copy the file data to another storage backend (keeps the existing copies)`,children:[(0,Z.jsx)(Ct,{className:`mr-1 h-3.5 w-3.5`}),` Copy to…`]}),(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>m(`move`),title:`Move the file data to another storage backend (source released once the copy is durable)`,children:[(0,Z.jsx)(_t,{className:`mr-1 h-3.5 w-3.5`}),` Move to…`]})]}),a.map(n=>{let r=Ng(n.kind),{backend:a,key:o}=Pg(n.url),s=l===n.url;return(0,Z.jsxs)(`div`,{className:`space-y-2 rounded border px-3 py-2 text-sm`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(r,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`shrink-0 font-mono text-xs`,children:n.backend||a}),(0,Z.jsx)(`span`,{className:`truncate font-mono text-xs text-muted-foreground`,title:n.url,children:o||n.url})]}),(0,Z.jsxs)(`span`,{className:`flex shrink-0 items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`rounded px-1.5 py-0.5 text-[10px] uppercase ${n.deletable?`bg-muted text-muted-foreground`:`bg-warning/15 text-warning`}`,children:n.deletable?n.kind:`read-only`}),(0,Z.jsx)(`button`,{onClick:()=>Gr(t,e.id,T||`document-${e.id}`,{url:n.url}).catch(e=>i(e instanceof Error?e.message:String(e))),className:`text-muted-foreground hover:text-foreground`,title:`Download this copy`,children:(0,Z.jsx)(wn,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`button`,{onClick:()=>C(n),disabled:s,className:`text-muted-foreground hover:text-destructive disabled:opacity-50`,title:n.deletable?`Remove from backend`:`Drop reference (bytes stay; backend is read-only)`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})]}),d===n.url&&(0,Z.jsxs)(`div`,{className:`space-y-2 rounded border border-destructive/40 bg-destructive/5 p-2`,children:[(0,Z.jsxs)(`p`,{className:`text-xs`,children:[`This is the object's `,(0,Z.jsx)(`strong`,{children:`last`}),` location. Remove the bytes from the backend and…`]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsx)(J,{variant:`destructive`,size:`sm`,disabled:s,onClick:()=>void x(n.url,!1),children:`Also remove index entry`}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,disabled:s,onClick:()=>void x(n.url,!0),children:`Keep index entry (no bytes)`}),(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:()=>f(null),children:`Cancel`})]})]})]},n.url)}),p&&(0,pf.createPortal)((0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,Z.jsx)(Ap,{workspaceId:t,documentCount:1,initialMode:p,defaultFilename:T,saving:h,onConfirm:S,onClose:()=>{h||m(null)}})}),window.document.body)]})}function Ig(e){let t=e.metadata?.geo,n=t?.lat,r=t?.lon;if(n==null||r==null||n===``||r===``)return null;let i=Number(n),a=Number(r);return!Number.isFinite(i)||!Number.isFinite(a)||i===0&&a===0?null:{lat:i,lon:a}}function Lg(e,t,n){let r=!1;for(let i=0,a=n.length-1;i<n.length;a=i++){let o=n[i].lat,s=n[i].lon,c=n[a].lat,l=n[a].lon;o>e!=c>e&&t<(l-s)*(e-o)/(c-o)+s&&(r=!r)}return r}function Rg(e,t,n){if(n.kind===`rect`){let r=n.bbox;return e>=r.minLat&&e<=r.maxLat&&t>=r.minLon&&t<=r.maxLon}return n.points.length>=3&&Lg(e,t,n.points)}function zg(e,t,n=!1){let r=Ig(e);return r?Rg(r.lat,r.lon,t):n}var Bg=(0,X.lazy)(()=>m(()=>import(`./LocationTab-ARqmeXmv.js`),__vite__mapDeps([23,3,4,24,25]))),Vg=[{id:`view`,label:`View`,icon:Dt},{id:`location`,label:`Location`,icon:Zt},{id:`metadata`,label:`Metadata`,icon:N},{id:`json`,label:`JSON`,icon:On},{id:`synapses`,label:`Synapses`,icon:Tn},{id:`backends`,label:`Backends`,icon:Jt}];function Hg({document:e,workspaceId:t,initialTab:n=`view`,initialEdit:r=!1,onChanged:i,className:a=``,compact:o=!1}){let s=bo()!=null,c=Ig(e),l=Vg.filter(e=>(e.id!==`location`||c!==null)&&(!s||![`synapses`,`backends`].includes(e.id))),[u,d]=(0,X.useState)(n),f=`${e.id}:${n}`,[p,m]=(0,X.useState)(f);f!==p&&(m(f),d(n));let h=l.some(e=>e.id===u)?u:`view`;return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col ${a}`,children:[(0,Z.jsx)(nm,{tabs:l,active:h,onChange:d,className:`shrink-0 px-2`,iconOnly:o}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-4`,children:[h===`view`&&(0,Z.jsx)(Eg,{document:e,workspaceId:t,initialEdit:r&&!s,onChanged:i}),h===`location`&&c&&(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading map…`}),children:(0,Z.jsx)(Bg,{lat:c.lat,lon:c.lon})}),h===`metadata`&&(0,Z.jsx)(Ag,{document:e,workspaceId:t}),h===`json`&&(0,Z.jsx)(jg,{document:e,workspaceId:t}),h===`synapses`&&!s&&(0,Z.jsx)(Mg,{document:e,workspaceId:t}),h===`backends`&&!s&&(0,Z.jsx)(Fg,{document:e,workspaceId:t,onChanged:i})]})]})}function Ug(e,t){let[n,r]=(0,X.useState)(null),i=t?.id??null,[a,o]=(0,X.useState)(i);i!==a&&(o(i),r(null));let s=(0,X.useRef)(i);(0,X.useEffect)(()=>{s.current=i},[i]);let c=(0,X.useCallback)(()=>{!e||i==null||gr(e,i).then(e=>{s.current===i&&e&&r(e)}).catch(()=>{})},[e,i]);return{document:n??t,refresh:c}}function Wg(e){let t=tm(),n=(0,X.useContext)(Mp),{document:r,workspaceId:i,isOpen:a,onClose:o,initialEdit:s,initialTab:c}=e,l=t===`side`&&!!n&&!!i&&!s&&!c;return(0,X.useLayoutEffect)(()=>{!l||!a||!r||!i||!n||((n.preview??n.open)(r,i),o())},[l,a,r,i,n,o]),l?null:(0,Z.jsx)(Gg,{...e})}function Gg({document:e,isOpen:t,onClose:n,workspaceId:r,initialTab:i,initialEdit:a}){let[o,s]=(0,X.useState)(!1),c=Ao(),{document:l,refresh:u}=Ug(r,e);if(gf(()=>o?s(!1):n(),t&&!!l),!t||!l)return null;let d=!!(c?.state.t1Open||c?.state.t2Open);return(0,pf.createPortal)((0,Z.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:K(`fixed inset-0 z-50 flex items-center justify-center bg-scrim`,o?`p-0`:`p-4 max-md:p-2`,o&&d&&`md:right-[min(436px,90vw)]`),onClick:n,children:(0,Z.jsxs)(`div`,{className:K(`flex w-full flex-col border bg-background max-md:h-full max-md:max-w-none`,o?`h-full max-w-none rounded-none md:rounded-lg md:m-2 md:h-[calc(var(--viewport-h)-1rem)]`:`h-viewport-card max-w-3xl rounded-lg`),onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between p-4 pb-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h2`,{className:`truncate text-lg font-bold`,children:mo(l).title}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`ID: `,l.id,` · `,l.schema]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[(()=>{let e=po(l);return e?(0,Z.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`rounded-sm p-2 text-muted-foreground hover:bg-muted hover:text-foreground`,title:`Open original: ${e}`,"aria-label":`Open original`,children:(0,Z.jsx)(Gn,{className:`h-4 w-4`})}):null})(),(0,Z.jsx)(`button`,{onClick:()=>s(!o),className:`hidden rounded-sm p-2 hover:bg-muted md:block`,title:o?`Restore`:`Fullscreen`,"aria-label":o?`Restore`:`Fullscreen`,children:o?(0,Z.jsx)(ct,{className:`h-4 w-4`}):(0,Z.jsx)(gn,{className:`h-4 w-4`})}),(0,Z.jsx)(`button`,{onClick:n,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,children:`✕`})]})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,Z.jsx)(qp.Provider,{value:()=>s(e=>!e),children:(0,Z.jsx)(Hg,{document:l,workspaceId:r??``,initialTab:i,initialEdit:a,onChanged:u})})})]})}),window.document.body)}var Kg={sortBy:`crud:created`,order:`desc`},qg={"crud:created":`Created`,"crud:updated":`Updated`,content:`Content`};function Jg(e){return qg[e]??e}function Yg(e){let[t,n]=(0,X.useState)([]);return(0,X.useEffect)(()=>{let t=!1;return Ra(e).then(e=>{t||n(e)}).catch(()=>{t||n([])}),()=>{t=!0}},[e]),(0,X.useMemo)(()=>[...new Set([`crud:created`,`crud:updated`,...t])].map(e=>({value:e,label:Jg(e)})),[t])}function Xg({workspaceId:e,value:t,onChange:n}){let r=Yg(e);return(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-1`,children:[(0,Z.jsxs)(`select`,{value:t.sortBy,onChange:e=>n({...t,sortBy:e.target.value}),className:`h-7 rounded-md border bg-background px-1.5 text-xs`,title:`Sort by timeline`,children:[!r.some(e=>e.value===t.sortBy)&&(0,Z.jsx)(`option`,{value:t.sortBy,children:Jg(t.sortBy)}),r.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>n({...t,order:t.order===`asc`?`desc`:`asc`}),title:t.order===`asc`?`Ascending (oldest first)`:`Descending (newest first)`,className:`flex h-7 w-7 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent hover:text-foreground touch-target`,children:t.order===`asc`?(0,Z.jsx)(hn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(sn,{className:`h-3.5 w-3.5`})})]})}var Zg={today:8,yesterday:7,thisWeek:6,lastWeek:5,thisMonth:4,lastMonth:3,thisYear:2,year:1,unknown:0},Qg=e=>e*1e6;function $g(){try{let e=new Intl.Locale(navigator.language),t=(typeof e.getWeekInfo==`function`?e.getWeekInfo():e.weekInfo)?.firstDay;if(typeof t==`number`&&t>=1&&t<=7)return t}catch{}return 1}function e_(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function t_(e,t){let n=((e.getDay()===0?7:e.getDay())-t+7)%7,r=e_(e);return r.setDate(r.getDate()-n),r}var n_=864e5;function r_(e){let t=$g(),n=e_(e),r=t_(e,t);return{today:n.getTime(),yesterday:n.getTime()-n_,weekStart:r.getTime(),lastWeekStart:r.getTime()-7*n_,year:e.getFullYear(),month:e.getFullYear()*12+e.getMonth()}}function i_(e,t){if(e===null||!Number.isFinite(e))return{key:`unknown`,label:`Unknown date`,rank:Qg(Zg.unknown)};if(e>=t.today)return{key:`today`,label:`Today`,rank:Qg(Zg.today)};if(e>=t.yesterday)return{key:`yesterday`,label:`Yesterday`,rank:Qg(Zg.yesterday)};if(e>=t.weekStart)return{key:`this-week`,label:`Earlier this week`,rank:Qg(Zg.thisWeek)};if(e>=t.lastWeekStart)return{key:`last-week`,label:`Last week`,rank:Qg(Zg.lastWeek)};let n=new Date(e),r=n.getFullYear()*12+n.getMonth();if(r===t.month)return{key:`this-month`,label:`Earlier this month`,rank:Qg(Zg.thisMonth)};if(r===t.month-1)return{key:`last-month`,label:`Last month`,rank:Qg(Zg.lastMonth)};if(n.getFullYear()===t.year)return{key:`this-year`,label:`Earlier this year`,rank:Qg(Zg.thisYear)};let i=n.getFullYear();return{key:`year-${i}`,label:String(i),rank:Qg(Zg.year)+i}}function a_(e,t,n=`desc`,r=new Date){let i=r_(r),a=new Map;for(let n of e){let e=i_(t(n),i),r=a.get(e.key);r?r.items.push(n):a.set(e.key,{...e,items:[n]})}let o=[...a.values()].sort((e,t)=>n===`asc`?e.rank-t.rank:t.rank-e.rank),s=o.filter(e=>e.key===`unknown`);return s.length?[...o.filter(e=>e.key!==`unknown`),...s]:o}function o_({isOpen:e,onClose:t,documents:n,selectedDocuments:r}){let[i,a]=(0,X.useState)(`idle`);if(!e)return null;let o=()=>{a(`idle`),t()},s=r.size>0?n.filter(e=>r.has(e.id)):n,c=s.map(e=>({schema:e.schema,schemaVersion:e.schemaVersion,data:e.data,metadata:e.metadata})),l=JSON.stringify(c,null,2),u=async()=>{try{await navigator.clipboard.writeText(l),a(`copied`),setTimeout(()=>a(`idle`),2e3)}catch(e){console.error(`Failed to copy to clipboard:`,e),a(`error`),setTimeout(()=>a(`idle`),2e3)}};return(0,pf.createPortal)((0,Z.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 bg-scrim flex items-center justify-center z-50 p-4 max-md:p-2`,children:(0,Z.jsx)(`div`,{className:`bg-background border rounded-lg max-w-3xl w-full max-h-viewport-card overflow-y-auto max-md:h-full max-md:max-h-none max-md:max-w-none`,children:(0,Z.jsxs)(`div`,{className:`p-6`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Export Documents`}),(0,Z.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Exporting `,s.length,` document`,s.length===1?``:`s`,i===`copied`&&(0,Z.jsx)(`span`,{className:`text-success ml-2`,children:`✓ Copied to clipboard!`}),i===`error`&&(0,Z.jsx)(`span`,{className:`text-destructive ml-2`,children:`✗ Failed to copy`})]})]}),(0,Z.jsx)(`button`,{onClick:o,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,Z.jsx)(`div`,{className:`space-y-4`,children:(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold`,children:`JSON Data (Press Ctrl+A to select all, Ctrl+C to copy)`}),(0,Z.jsxs)(J,{onClick:u,size:`sm`,className:`flex items-center gap-2`,children:[(0,Z.jsx)(Ct,{className:`h-4 w-4`}),`Copy to Clipboard`]})]}),(0,Z.jsx)(`textarea`,{className:`w-full h-96 p-4 bg-muted border rounded-lg text-sm font-mono resize-none focus:outline-none focus:ring-2 focus:ring-primary`,value:l,readOnly:!0,autoFocus:!0,onKeyDown:e=>{if(e.ctrlKey||e.metaKey){if(e.key===`a`){e.preventDefault();let t=window.getSelection(),n=document.createRange();n.selectNodeContents(e.currentTarget),t?.removeAllRanges(),t?.addRange(n)}else e.key===`c`&&u()}},onFocus:e=>e.target.select()})]})}),(0,Z.jsx)(`div`,{className:`mt-8 pt-4 border-t flex justify-end`,children:(0,Z.jsx)(J,{onClick:o,children:`Close`})})]})})}),window.document.body)}function s_({isOpen:e,onClose:t,onImport:n}){let[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null);if(!e)return null;let l=async()=>{if(c(null),!r.trim()){c(`Please enter JSON data`);return}try{let e=JSON.parse(r),a=Array.isArray(e)?e:[e];for(let e of a)if(!e.schema||!e.data){c(`Each document must have "schema" and "data" fields`);return}o(!0),await n(a)?(i(``),t()):c(`Failed to import documents`)}catch{c(`Invalid JSON format`)}finally{o(!1)}},u=()=>{i(``),c(null),t()};return(0,pf.createPortal)((0,Z.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 bg-scrim flex items-center justify-center z-50 p-4 max-md:p-2`,children:(0,Z.jsx)(`div`,{className:`bg-background border rounded-lg max-w-3xl w-full max-h-viewport-card overflow-y-auto max-md:h-full max-md:max-h-none max-md:max-w-none`,children:(0,Z.jsxs)(`div`,{className:`p-6`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Import Documents`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:`Paste JSON data containing documents to import`})]}),(0,Z.jsx)(`button`,{onClick:u,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`block text-sm font-medium mb-2`,children:`JSON Data (single document or array of documents)`}),(0,Z.jsx)(`textarea`,{value:r,onChange:e=>i(e.target.value),className:`w-full h-64 p-3 border rounded-lg font-mono text-sm`,placeholder:`[{"schema": "data/schema/tab", "schemaVersion": "2.0", "data": {...}, "metadata": {...}}]`,disabled:a,autoFocus:!0})]}),s&&(0,Z.jsx)(`div`,{className:`text-sm text-destructive bg-destructive/10 p-3 rounded-lg border`,children:s}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[(0,Z.jsxs)(`p`,{children:[(0,Z.jsx)(`strong`,{children:`Format:`}),` Each document must have "schema", "schemaVersion", "data", and "metadata" fields.`]}),(0,Z.jsxs)(`p`,{children:[(0,Z.jsx)(`strong`,{children:`Example schemas:`}),` "data/schema/tab", "data/schema/file", etc.`]})]})]}),(0,Z.jsxs)(`div`,{className:`mt-8 pt-4 border-t flex justify-between`,children:[(0,Z.jsx)(J,{variant:`outline`,onClick:u,disabled:a,children:`Cancel`}),(0,Z.jsx)(J,{onClick:l,disabled:a||!r.trim(),children:a?`Importing...`:`Import Documents`})]})]})})}),window.document.body)}function c_({document:e,open:t,onClose:n,onViewDetails:r,onEdit:i,onLink:a,onOpenToSide:o,onRemove:s,onDelete:c}){if(gf(n,t),!t)return null;let l=mo(e),u=e=>()=>{n(),e()},d=`flex w-full items-center gap-3 rounded-xl border bg-card px-4 py-4 text-base font-medium transition-transform active:scale-[.98]`;return(0,pf.createPortal)((0,Z.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 z-fullscreen flex flex-col bg-background animate-in slide-in-from-bottom-10 fade-in duration-200`,onClick:n,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-start gap-3 border-b p-4`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsx)(Jf,{document:e,chip:!0}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`truncate text-base font-semibold`,children:l.title}),(0,Z.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[`ID: `,e.id,` · `,e.schema]})]}),(0,Z.jsx)(`button`,{onClick:n,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,"aria-label":`Close`,children:(0,Z.jsx)(je,{className:`h-5 w-5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1`}),(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-2 px-4 pt-2`,style:{paddingBottom:`calc(var(--safe-bottom) + 1.25rem)`},onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`button`,{onClick:u(r),className:d,children:[(0,Z.jsx)(Dt,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),` View details`]}),i&&(0,Z.jsxs)(`button`,{onClick:u(i),className:d,children:[(0,Z.jsx)(ye,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),` Edit`]}),a&&(0,Z.jsxs)(`button`,{onClick:u(a),className:d,children:[(0,Z.jsx)(qt,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),` Link to…`]}),o&&(0,Z.jsxs)(`button`,{onClick:u(o),className:d,children:[(0,Z.jsx)(Xe,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),` Open to the side`]}),s&&(0,Z.jsxs)(`button`,{onClick:u(s),className:d,children:[(0,Z.jsx)(je,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),` Remove from context`]}),c&&(0,Z.jsxs)(`button`,{onClick:u(c),className:`${d} border-destructive/30 text-destructive`,children:[(0,Z.jsx)(lt,{className:`h-5 w-5 shrink-0`}),` Delete permanently`]}),(0,Z.jsx)(`button`,{onClick:n,className:`${d} justify-center bg-muted`,children:`Cancel`})]})]}),window.document.body)}function l_({document:e}){let{replicating:t,label:n}=Ji(e);return t?(0,Z.jsxs)(`span`,{role:`status`,className:`inline-flex shrink-0 items-center gap-1 rounded-full border bg-muted/60 px-2 py-0.5 text-[11px] font-normal text-muted-foreground`,children:[(0,Z.jsx)(Wn,{className:`h-3 w-3 animate-spin`}),n]}):null}function u_({document:e,isSelected:t,workspaceId:n,onSelect:r,onRemoveDocument:i,onDeleteDocument:a,onLinkDocument:o,onOpenToSide:s,onRightClick:c,onDragStart:l}){let u=df(),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(!1),_=bo()!=null,v=ug(e),{replicating:y}=Ji(e),b=e.schema===`data/schema/tab`,x=b?e.data.url:null,S=mo(e),C=f_(e),w=C||m_(e),{blobUrl:T}=jm(n??``,e.id,128,{enabled:w,blobFallback:C,version:e.checksumArray?.[0]??null}),E=t=>{l?.(t,e.id)},D=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),O=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),k=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&(i?r(e.id,!t,i):r(e.id,!0,i)),i||(b&&x?window.open(x,`_blank`,`noopener,noreferrer`):(m(!1),f(!0)))},A=e=>{e.shiftKey&&e.preventDefault()},j=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),c?.(n,e.id)},M=e=>{e.stopPropagation(),m(!1),f(!0)},N=e=>{e.stopPropagation(),m(!0),f(!0)},P=t=>{t.stopPropagation(),i?.(e.id)},ee=t=>{t.stopPropagation(),a?.(e.id)};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(zp,{className:`cursor-pointer transition-opacity ${y?`opacity-60`:``} ${t?`bg-info-subtle hover:bg-info-subtle`:`hover:bg-muted/50`}`,onClick:k,onMouseDown:A,...u,onContextMenu:j,draggable:!0,onDragStart:E,children:[(0,Z.jsx)(Vp,{className:`w-10`,onClick:e=>e.stopPropagation(),children:(0,Z.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 cursor-pointer accent-primary align-middle`,checked:!!t,onClick:t=>{t.stopPropagation(),r?.(e.id,t.currentTarget.checked,!0,t.shiftKey)},onChange:()=>{}})}),(0,Z.jsx)(Vp,{className:`w-12`,children:T?(0,Z.jsx)(`img`,{src:T,alt:``,className:`h-8 w-8 rounded-md border object-cover`}):(0,Z.jsx)(Jf,{document:e,chip:!0})}),(0,Z.jsx)(Vp,{className:`font-medium w-full max-w-0 md:w-auto md:max-w-xs`,children:(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`truncate`,title:S.title,children:S.title}),S.isExternal&&(0,Z.jsx)(Gn,{className:`h-3 w-3 text-muted-foreground flex-shrink-0`}),(0,Z.jsx)(l_,{document:e})]}),S.subtitle&&(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,title:S.subtitle,children:S.subtitle})]})}),(0,Z.jsx)(Vp,{className:`hidden md:table-cell`,children:(0,Z.jsx)(`span`,{className:`px-2 py-1 text-xs bg-muted rounded border`,children:S.schemaLabel})}),(0,Z.jsx)(Vp,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:e.id}),(0,Z.jsx)(Vp,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:O&&(0,Z.jsx)(`span`,{className:`font-mono`,title:`${O.algo} checksum`,children:O.hash})}),(0,Z.jsx)(Vp,{className:`hidden text-xs text-muted-foreground sm:table-cell`,children:D(e.createdAt)}),(0,Z.jsxs)(Vp,{children:[(0,Z.jsxs)(`div`,{className:`hidden items-center gap-1 md:flex`,children:[(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:M,title:`View document details`,children:(0,Z.jsx)(Dt,{className:`h-4 w-4`})}),v&&!_&&(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:N,title:`Edit document`,children:(0,Z.jsx)(ye,{className:`h-4 w-4`})}),o&&(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:t=>{t.stopPropagation(),o(e.id)},title:`Link document to other paths`,children:(0,Z.jsx)(qt,{className:`h-4 w-4`})}),s&&(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:t=>{t.stopPropagation(),s(e)},title:`Open to the side`,children:(0,Z.jsx)(Xe,{className:`h-4 w-4`})}),i&&(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:P,title:`Remove document from context`,children:(0,Z.jsx)(je,{className:`h-4 w-4`})}),a&&(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:ee,title:`Delete document permanently`,className:`text-destructive hover:text-destructive`,children:(0,Z.jsx)(lt,{className:`h-4 w-4`})})]}),(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,className:`md:hidden`,onClick:e=>{e.stopPropagation(),g(!0)},title:`Actions`,"aria-label":`Document actions`,children:(0,Z.jsx)(Bt,{className:`h-4 w-4`})})]})]}),(0,Z.jsx)(c_,{document:e,open:h,onClose:()=>g(!1),onViewDetails:()=>{m(!1),f(!0)},onEdit:v&&!_?()=>{m(!0),f(!0)}:void 0,onLink:o?()=>o(e.id):void 0,onOpenToSide:s?()=>s(e):void 0,onRemove:i?()=>i(e.id):void 0,onDelete:a?()=>a(e.id):void 0}),(0,Z.jsx)(Wg,{document:e,isOpen:d,onClose:()=>f(!1),workspaceId:n,initialEdit:p})]})}function d_({document:e,isSelected:t,workspaceId:n,onSelect:r,onRemoveDocument:i,onDeleteDocument:a,onLinkDocument:o,onOpenToSide:s,onRightClick:c,onDragStart:l}){let u=df(),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(!1),_=bo()!=null,v=e.schema===`data/schema/tab`,y=ug(e),{replicating:b}=Ji(e),x=v?e.data.url:null,S=mo(e),C=f_(e),w=C||m_(e),{blobUrl:T,loading:E}=jm(n??``,e.id,128,{enabled:w,blobFallback:C,version:e.checksumArray?.[0]??null}),D=t=>{l?.(t,e.id)},O=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),k=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),A=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&(i?r(e.id,!t,i):r(e.id,!0,i)),i||(v&&x?window.open(x,`_blank`,`noopener,noreferrer`):(m(!1),f(!0)))},j=e=>{e.shiftKey&&e.preventDefault()},M=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),c?.(n,e.id)},N=e=>{e.stopPropagation(),m(!1),f(!0)},P=e=>{e.stopPropagation(),m(!0),f(!0)},ee=t=>{t.stopPropagation(),i?.(e.id)},F=t=>{t.stopPropagation(),a?.(e.id)};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`border rounded-lg p-4 transition cursor-pointer ${b?`opacity-60`:``} ${t?`bg-info-subtle border-info ring-1 ring-info`:``} ${v&&!t?`hover:bg-info-subtle hover:border-info`:t?``:`hover:bg-accent/50`}`,onClick:A,onMouseDown:j,...u,onContextMenu:M,draggable:!0,onDragStart:D,children:(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[w&&(0,Z.jsx)(`div`,{className:`h-14 w-14 shrink-0 overflow-hidden rounded-md border bg-muted/40`,children:T?(0,Z.jsx)(`img`,{src:T,alt:S.title,loading:`lazy`,className:`h-full w-full object-cover`}):E?(0,Z.jsx)(`div`,{className:`h-full w-full animate-pulse bg-muted/60`}):(0,Z.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,Z.jsx)(Jf,{document:e})})}),(0,Z.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 mb-2 overflow-hidden`,children:[(0,Z.jsx)(Jf,{document:e,chip:!0}),(0,Z.jsx)(`h4`,{className:`font-medium truncate min-w-0 flex-1 max-w-[640px]`,title:S.title,children:S.title}),S.isExternal&&(0,Z.jsx)(Gn,{className:`h-3 w-3 text-muted-foreground flex-shrink-0`}),(0,Z.jsx)(`span`,{className:`px-2 py-0.5 text-xs bg-muted text-muted-foreground rounded border flex-shrink-0`,children:S.schemaLabel}),(0,Z.jsx)(l_,{document:e})]}),S.subtitle&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2 truncate`,title:S.subtitle,children:S.subtitle}),S.preview&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mb-3 line-clamp-2 break-all overflow-hidden`,children:S.preview}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-4 text-xs text-muted-foreground overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,Z.jsx)(`span`,{className:`font-mono truncate max-w-[60px]`,title:`ID: ${e.id}`,children:e.id})]}),k&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Z.jsx)(ce,{className:`h-3 w-3`}),(0,Z.jsx)(`span`,{className:`font-mono`,title:`${k.algo} checksum`,children:k.hash})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Z.jsx)(Ye,{className:`h-3 w-3`}),(0,Z.jsx)(`span`,{title:`Created: ${O(e.createdAt)}`,children:O(e.createdAt)})]})]})]}),(0,Z.jsxs)(`div`,{className:`hidden items-center gap-2 md:flex`,children:[(0,Z.jsx)(`button`,{onClick:N,className:`p-1 hover:bg-muted rounded-sm`,title:`View document details`,children:(0,Z.jsx)(Dt,{className:`h-4 w-4`})}),y&&!_&&(0,Z.jsx)(`button`,{onClick:P,className:`p-1 hover:bg-muted rounded-sm`,title:`Edit document`,children:(0,Z.jsx)(ye,{className:`h-4 w-4`})}),o&&(0,Z.jsx)(`button`,{onClick:t=>{t.stopPropagation(),o(e.id)},className:`p-1 hover:bg-muted rounded-sm`,title:`Link document to other paths`,children:(0,Z.jsx)(qt,{className:`h-4 w-4`})}),s&&(0,Z.jsx)(`button`,{onClick:t=>{t.stopPropagation(),s(e)},className:`p-1 hover:bg-muted rounded-sm`,title:`Open to the side`,children:(0,Z.jsx)(Xe,{className:`h-4 w-4`})}),i&&(0,Z.jsx)(`button`,{onClick:ee,className:`p-1 hover:bg-muted rounded-sm`,title:`Remove document from context (keep in database)`,children:(0,Z.jsx)(je,{className:`h-4 w-4`})}),a&&(0,Z.jsx)(`button`,{onClick:F,className:`p-1 hover:bg-destructive hover:text-destructive-foreground rounded-sm text-destructive`,title:`Delete document permanently from database`,children:(0,Z.jsx)(lt,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`button`,{onClick:e=>{e.stopPropagation(),g(!0)},className:`p-2 hover:bg-muted rounded-sm md:hidden`,title:`Actions`,"aria-label":`Document actions`,children:(0,Z.jsx)(Bt,{className:`h-4 w-4`})})]})}),(0,Z.jsx)(c_,{document:e,open:h,onClose:()=>g(!1),onViewDetails:()=>{m(!1),f(!0)},onEdit:y&&!_?()=>{m(!0),f(!0)}:void 0,onLink:o?()=>o(e.id):void 0,onOpenToSide:s?()=>s(e):void 0,onRemove:i?()=>i(e.id):void 0,onDelete:a?()=>a(e.id):void 0}),(0,Z.jsx)(Wg,{document:e,isOpen:d,onClose:()=>f(!1),workspaceId:n,initialEdit:p})]})}function f_(e){return(e.schema===`data/schema/file`||e.schema===`data/schema/drawing`)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function p_(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``).startsWith(`video/`)}function m_(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``)===`application/pdf`}function h_({workspaceId:e,documentId:t,fallback:n}){let{src:r,error:i}=lo(e,t),[a,o]=(0,X.useState)(!1);return i||a?(0,Z.jsx)(Z.Fragment,{children:n}):r?(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(`video`,{src:r,preload:`metadata`,muted:!0,playsInline:!0,onError:()=>o(!0),className:`block h-auto w-full`}),(0,Z.jsx)(`span`,{className:`pointer-events-none absolute bottom-2 right-2 rounded-sm bg-scrim p-1 text-scrim-foreground`,children:(0,Z.jsx)(W,{className:`h-3.5 w-3.5`})})]}):(0,Z.jsx)(`div`,{className:`aspect-video w-full animate-pulse bg-muted/60`})}function g_({document:e,workspaceId:t,markdown:n}){let r=(0,X.useRef)(null),[i,a]=(0,X.useState)(()=>typeof IntersectionObserver>`u`);(0,X.useEffect)(()=>{let e=r.current;if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&(a(!0),t.disconnect())});return t.observe(e),()=>t.disconnect()},[]);let{text:o,loading:s,error:c}=So(t,e.id,{mode:`text`,enabled:i,maxTextLength:8e3});return(0,Z.jsx)(`div`,{ref:r,className:`relative h-48 w-full overflow-hidden bg-card text-card-foreground`,children:o!=null&&!c?(0,Z.jsxs)(`div`,{className:`pointer-events-none p-3 pt-7 text-xs leading-relaxed`,"aria-hidden":`true`,children:[o.length===0?(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Empty file`}):n?(0,Z.jsx)(Bm,{content:o,preview:!0,className:`text-xs [&_pre]:whitespace-pre-wrap [&_pre]:break-words [&_table]:table-fixed [&_table]:w-full`}):(0,Z.jsx)(`pre`,{className:`whitespace-pre-wrap break-words font-mono`,children:o}),(0,Z.jsx)(`div`,{className:`absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-card to-transparent`})]}):(0,Z.jsxs)(`div`,{className:`flex h-full items-center justify-center`,children:[(0,Z.jsx)(Jf,{document:e,size:10,chip:!0}),i&&s&&(0,Z.jsx)(`span`,{className:`sr-only`,children:`Loading text preview`})]})})}function __({document:e,isSelected:t,workspaceId:n,onSelect:r,onOpenToSide:i,onRightClick:a,onDragStart:o}){let s=df(),[c,l]=(0,X.useState)(!1),u=e.schema===`data/schema/tab`,d=u?e.data.url:null,f=f_(e),p=p_(e),m=f||m_(e),h=mo(e),g=to(String(e.metadata?.contentType||``).split(`;`)[0].trim().toLowerCase(),e.metadata?.filename||so(e)),_=e.schema===`data/schema/file`&&(g===`markdown`||g===`text`)&&(e.metadata?.size??e.data?.size??0)<=1048576,v=!m&&e.schema!==`data/schema/file`&&!!(h.preview||h.subtitle),{replicating:y}=Ji(e),{blobUrl:b,loading:x}=jm(n??``,e.id,768,{enabled:m,blobFallback:f,version:e.checksumArray?.[0]??null}),S=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&r(e.id,!i||!t,i),i||(u&&d?window.open(d,`_blank`,`noopener,noreferrer`):l(!0))},C=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),a?.(n,e.id)};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`group relative mb-3 flex break-inside-avoid flex-col overflow-hidden rounded-lg border transition cursor-pointer hover:shadow-elevation-2 ${y?`opacity-60`:``} ${t?`ring-2 ring-info border-info`:``}`,onClick:S,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},...s,onContextMenu:C,draggable:!0,onDragStart:t=>o?.(t,e.id),title:h.title,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`absolute left-2 top-2 z-10 h-4 w-4 cursor-pointer accent-primary ${t?``:`reveal-on-hover`}`,checked:t,onClick:t=>{t.stopPropagation(),r?.(e.id,t.currentTarget.checked,!0,t.shiftKey)},onChange:()=>{}}),(0,Z.jsxs)(`div`,{className:`relative w-full bg-muted/40 ${m&&b||v||_&&n||p&&n?``:`aspect-square`}`,children:[m&&x&&(0,Z.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),m&&b?(0,Z.jsx)(`img`,{src:b,alt:h.title,loading:`lazy`,className:`block h-auto w-full`}):p&&n?(0,Z.jsx)(h_,{workspaceId:n,documentId:e.id,fallback:(0,Z.jsx)(`div`,{className:`flex aspect-square w-full items-center justify-center`,children:(0,Z.jsx)(Jf,{document:e,size:10,chip:!0})})}):_&&n?(0,Z.jsx)(g_,{document:e,workspaceId:n,markdown:g===`markdown`},`${n}:${e.id}:${e.checksumArray?.[0]??``}`):v?(0,Z.jsxs)(`div`,{className:`flex min-h-28 w-full flex-col gap-1.5 overflow-hidden bg-card p-3 pt-7 text-left`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(Jf,{document:e}),(0,Z.jsx)(`span`,{className:`min-w-0 truncate text-[10px] uppercase tracking-wide text-muted-foreground`,children:h.schemaLabel})]}),(0,Z.jsx)(`div`,{className:`line-clamp-2 text-sm font-semibold leading-snug`,children:h.title}),h.subtitle&&(0,Z.jsx)(`div`,{className:`truncate text-[11px] text-info`,children:h.subtitle}),(0,Z.jsx)(`p`,{className:`line-clamp-[8] text-xs leading-relaxed text-muted-foreground`,children:h.preview})]}):(0,Z.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,Z.jsx)(Jf,{document:e,size:10,chip:!0})}),i&&(0,Z.jsx)(`button`,{onClick:t=>{t.stopPropagation(),i(e)},className:`absolute right-2 top-2 rounded-sm bg-scrim p-1 text-scrim-foreground reveal-on-hover`,title:`Open to the side`,children:(0,Z.jsx)(Xe,{className:`h-3.5 w-3.5`})})]}),!v&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t bg-card px-2 py-1.5`,children:[(0,Z.jsx)(`span`,{className:`truncate text-xs font-medium`,title:h.title,children:h.title}),h.isExternal&&(0,Z.jsx)(Gn,{className:`h-3 w-3 shrink-0 text-muted-foreground`})]})]}),(0,Z.jsx)(Wg,{document:e,isOpen:c,onClose:()=>l(!1),workspaceId:n})]})}function v_(e,t,n,r){let[i,a]=(0,X.useState)(!1),o=e=>Array.from(e.dataTransfer.types).includes(`application/json`);return{over:i,onDragOver:e=>{!t||!o(e)||(e.preventDefault(),e.dataTransfer.dropEffect=`link`,i||a(!0))},onDragLeave:()=>a(!1),onDrop:async i=>{if(a(!1),!t||!o(i))return;i.preventDefault(),i.stopPropagation();let s=null;try{s=JSON.parse(i.dataTransfer.getData(`application/json`))}catch{s=null}if(!(s?.type!==`document`||!Array.isArray(s.documentIds)||s.documentIds.length===0))try{await t(e.path,s.documentIds,{move:!1,sourcePath:s.sourcePath??n,sourceTreeName:s.sourceTreeName??r})}catch{}}}}function y_({folder:e,className:t=`h-4 w-4`}){if(e.isParent)return(0,Z.jsx)(Yn,{className:`${t} text-muted-foreground`});let n=e.color?{color:e.color}:void 0;return(0,Z.jsx)(Qe,{className:`${t} ${e.color?``:`text-warning`}`,style:n})}var b_=e=>e.isParent?`Parent folder`:e.label&&e.label!==e.name?`${e.label} (${e.name})`:e.name;function x_({folder:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i}){let a=v_(e,n,r,i);return(0,Z.jsxs)(`button`,{type:`button`,title:b_(e),onClick:()=>t?.(e.path),onDragOver:a.onDragOver,onDragLeave:a.onDragLeave,onDrop:a.onDrop,className:`folder-surface group flex min-w-0 max-w-full items-center gap-2 rounded-md border px-2.5 py-1.5 text-sm transition-colors hover:bg-accent ${a.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,Z.jsxs)(`span`,{className:`relative shrink-0`,children:[(0,Z.jsx)(y_,{folder:e,className:`h-4 w-4 group-hover:hidden`}),e.isParent?(0,Z.jsx)(Yn,{className:`hidden h-4 w-4 group-hover:block`}):(0,Z.jsx)(nt,{className:`hidden h-4 w-4 group-hover:block`,style:e.color?{color:e.color}:void 0})]}),(0,Z.jsx)(`span`,{className:`truncate`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,Z.jsx)(`span`,{className:`shrink-0 text-[11px] tabular-nums text-muted-foreground`,children:e.childCount})]})}function S_({folder:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i}){let a=v_(e,n,r,i),o=e.color?{color:e.color}:void 0;return(0,Z.jsxs)(`button`,{type:`button`,title:b_(e),onClick:()=>t?.(e.path),onDragOver:a.onDragOver,onDragLeave:a.onDragLeave,onDrop:a.onDrop,className:`folder-surface group flex min-w-0 flex-col items-center gap-1.5 rounded-lg border px-2 py-3 text-sm transition hover:bg-accent hover:shadow-elevation-2 ${a.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,Z.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center`,children:e.isParent?(0,Z.jsx)(Yn,{className:`h-10 w-10`,strokeWidth:1.5}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Qe,{className:`h-14 w-14 group-hover:hidden ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:o}),(0,Z.jsx)(nt,{className:`hidden h-14 w-14 group-hover:block ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:o})]})}),(0,Z.jsx)(`span`,{className:`w-full truncate text-center font-medium`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,Z.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[e.childCount,` subfolder`,e.childCount===1?``:`s`]})]})}function C_({folders:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i}){return e.length===0?null:(0,Z.jsx)(`div`,{className:`mb-4 grid grid-cols-[repeat(auto-fill,minmax(120px,1fr))] gap-3 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,Z.jsx)(S_,{folder:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i},e.path))})}function w_({folders:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i}){return e.length===0?null:(0,Z.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-2 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,Z.jsx)(x_,{folder:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i},e.path))})}function T_({folder:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i}){let a=v_(e,n,r,i);return(0,Z.jsxs)(zp,{className:`cursor-pointer ${a.over?`bg-accent ring-1 ring-inset ring-info`:``} ${e.isParent?`text-muted-foreground`:``}`,onClick:()=>t?.(e.path),onContextMenu:e=>e.stopPropagation(),onDragOver:a.onDragOver,onDragLeave:a.onDragLeave,onDrop:a.onDrop,title:b_(e),children:[(0,Z.jsx)(Vp,{className:`w-10`}),(0,Z.jsx)(Vp,{className:`w-12`,children:(0,Z.jsx)(y_,{folder:e})}),(0,Z.jsx)(Vp,{className:`w-full max-w-0 md:w-auto md:max-w-none`,children:(0,Z.jsx)(`span`,{className:`block truncate font-medium`,children:e.isParent?`..`:e.label||e.name})}),(0,Z.jsx)(Vp,{className:`hidden md:table-cell text-xs text-muted-foreground`,children:e.isParent?``:`Folder`}),(0,Z.jsx)(Vp,{className:`hidden lg:table-cell`}),(0,Z.jsx)(Vp,{className:`hidden lg:table-cell`}),(0,Z.jsx)(Vp,{className:`hidden sm:table-cell text-xs text-muted-foreground`,children:!e.isParent&&e.childCount?`${e.childCount} subfolder${e.childCount===1?``:`s`}`:``}),(0,Z.jsx)(Vp,{className:`w-12 md:w-auto`})]})}function E_({label:e,count:t,collapsed:n,allSelected:r,someSelected:i,onToggle:a,onSelectAll:o}){return(0,Z.jsxs)(`div`,{className:`sticky top-0 z-10 -mx-1 mb-2 flex items-center gap-2 bg-background/95 px-1 py-1.5 backdrop-blur-sm`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`h-3.5 w-3.5 cursor-pointer accent-primary ${r||i?``:`reveal-on-hover`}`,checked:r,ref:e=>{e&&(e.indeterminate=i&&!r)},onChange:e=>o(e.target.checked),title:`Select everything in "${e}"`,onClick:e=>e.stopPropagation()}),(0,Z.jsxs)(`button`,{type:`button`,onClick:a,"aria-expanded":!n,className:`flex min-w-0 items-center gap-1.5 text-left text-muted-foreground transition-colors hover:text-foreground`,children:[(0,Z.jsx)(B,{className:`h-3.5 w-3.5 shrink-0 transition-transform ${n?``:`rotate-90`}`}),(0,Z.jsx)(`span`,{className:`truncate text-xs font-semibold uppercase tracking-wide`,children:e}),(0,Z.jsx)(`span`,{className:`shrink-0 text-xs font-normal tabular-nums opacity-70`,children:t})]}),(0,Z.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function D_({documents:e,isLoading:t,contextPath:n,treeName:r,workspaceId:i,totalCount:a,onRemoveDocument:o,onDeleteDocument:s,onDestroyDocument:c,onRemoveDocuments:l,onDeleteDocuments:u,onDestroyDocuments:d,onCopyDocuments:f,onCutDocuments:p,onPasteDocuments:m,onImportDocuments:h,onSelectionChange:g,pastedDocumentIds:_,viewMode:v=`card`,allowViewToggle:y=!1,activeContextUrl:b,currentContextUrl:x,currentPage:S=1,pageSize:w=50,onPageChange:T,onPageSizeChange:E,onPurgeDocuments:D,disablePurgeDocuments:O=!1,backendSearchQueries:k=[],onBackendSearch:A,onRemoveBackendQuery:j,serverSort:M,onServerSortChange:N,scope:P=`path`,onScopeChange:ee,canSaveChanges:F=!1,isSavingChanges:te=!1,onSaveChanges:L,linkTree:re,folders:ie,onOpenFolder:ae}){let[z,se]=(0,X.useState)(()=>{if(!y)return v;try{let e=localStorage.getItem(`doclist:view`);if(e===`card`||e===`table`||e===`tile`)return e}catch{}return v}),ce=y?z:v,V=(0,X.useCallback)(e=>{se(e);try{localStorage.setItem(`doclist:view`,e)}catch{}},[]),[le,ue]=(0,X.useState)(()=>{try{return localStorage.getItem(`doclist:groupdates`)!==`off`}catch{return!0}}),de=(0,X.useCallback)(()=>{ue(e=>{let t=!e;try{localStorage.setItem(`doclist:groupdates`,t?`on`:`off`)}catch{}return t})},[]),[fe,pe]=(0,X.useState)(new Set),me=(0,X.useCallback)(e=>{pe(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),[H,he]=(0,X.useState)(new Set),[ge,U]=(0,X.useState)(null),[be,xe]=(0,X.useState)(null),Se=Ao(),Ce=!!(Se&&i),W=(0,X.useCallback)(t=>{if(!Se||!i)return;let n=t.map(t=>e.find(e=>e.id===t)).filter(e=>!!e);n.length!==0&&Se.openAddRelated({workspaceName:i,documents:n})},[Se,i,e]),[G,we]=(0,X.useState)(!1),[Te,De]=(0,X.useState)(null),[Oe,ke]=(0,X.useState)(!1),[Ae,Me]=(0,X.useState)(!1),[Pe,Fe]=(0,X.useState)(null),[Ie,Le]=(0,X.useState)(null),ze=bo()==null&&!!i,[Be,He]=(0,X.useState)(null),Ue=!!(re&&m),We=!!i,{showSuccessToast:Ge,showErrorToast:Ke}=Ya(),qe=Pp(),Je=i?e=>qe.open(e,i):void 0,Ye=P===`workspace`,Xe=Ye?void 0:o,Ze=Ye?void 0:l,[Qe,$e]=(0,X.useState)(null),[et,tt]=(0,X.useState)(!1),[nt,rt]=(0,X.useState)(!1),[it,at]=(0,X.useState)(!1),[ot,st]=(0,X.useState)(``),[ct,ut]=(0,X.useState)(!1),dt=k.length>0,ft=(0,X.useRef)(null),pt=(0,X.useCallback)(()=>{st(``),ft.current&&(ft.current.value=``)},[]);(0,X.useEffect)(()=>{if(!y||window.matchMedia(`(max-width: 767px)`).matches)return;let e=ft.current;if(!e)return;let t=setTimeout(()=>e.focus(),60);return()=>clearTimeout(t)},[y]);let[mt,ht]=(0,X.useState)(n);n!==mt&&(ht(n),he(new Set)),(0,X.useEffect)(()=>{let e=()=>{Ue&&H.size>0&&xe(Array.from(H))};return window.addEventListener(`workspace:documents:link-selection`,e),()=>window.removeEventListener(`workspace:documents:link-selection`,e)},[Ue,H]),(0,X.useEffect)(()=>{g?.(Array.from(H))},[H,g]);let gt=(0,X.useCallback)(()=>{if(!A)return;let e=ot.trim();e&&(A(e),pt())},[A,ot,pt]),_t=(0,X.useCallback)(()=>{pt(),j&&k.length>0&&j(-1)},[j,k.length,pt]),vt=(0,X.useCallback)((e,t)=>{let i;H.has(t)&&H.size>1?i=Array.from(H):(i=[t],he(new Set([t])));let a={type:`document`,documentIds:i,sourcePath:n,sourceTreeName:r};e.dataTransfer.setData(`application/json`,JSON.stringify(a)),e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setDragImage(e.currentTarget,0,0)},[H,n,r]),yt=(0,X.useCallback)(async e=>{if(!m)return;let t=e.dataTransfer.getData(`application/json`);if(!t)return;let r=null;try{r=JSON.parse(t)}catch{return}r?.type!==`document`||!Array.isArray(r.documentIds)||r.documentIds.length===0||(e.preventDefault(),e.stopPropagation(),ut(!1),await m(n,r.documentIds,{move:e.shiftKey,sourcePath:r.sourcePath,sourceTreeName:r.sourceTreeName}),he(new Set))},[n,m]),bt=(0,X.useCallback)(e=>{m&&Array.from(e.dataTransfer.types).includes(`application/json`)&&(e.preventDefault(),e.dataTransfer.dropEffect=e.shiftKey?`move`:`copy`,ut(!0))},[m]),xt=(0,X.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||ut(!1)},[]),St=(0,X.useMemo)(()=>({keys:[{name:`data.title`,weight:.4},{name:`data.name`,weight:.4},{name:`locations.url`,weight:.4},{name:`data.url`,weight:.3},{name:`data.content`,weight:.2},{name:`data.description`,weight:.2},{name:`schema`,weight:.1}],threshold:.4,location:0,distance:100,minMatchCharLength:1,includeScore:!0,includeMatches:!0,ignoreLocation:!0}),[]),Tt=(0,X.useMemo)(()=>e.length===0?null:new Oo(e,St),[e,St]),Et=(0,X.useDeferredValue)(ot),kt=(0,X.useMemo)(()=>!Et.trim()||!Tt?e:Tt.search(Et).map(e=>e.item),[e,Et,Tt]),At=(0,X.useMemo)(()=>!ie||ie.length===0||Et.trim()?[]:ie,[ie,Et]),jt=At.length>0,Mt={folders:At,onOpen:ae,onPasteDocuments:m,contextPath:n,treeName:r},{sorted:Nt,sort:Pt,toggleSort:Ft}=Wp(kt,(0,X.useMemo)(()=>({title:e=>mo(e).title?.toLowerCase()??``,schema:e=>mo(e).schemaLabel??``,type:e=>(e.metadata?.contentType||e.schema||``).toLowerCase(),id:e=>e.id,created:e=>Date.parse(e.createdAt)||0}),[])),Lt=(0,X.useCallback)(e=>{let t=M?.sortBy===`crud:updated`?e.updatedAt:e.createdAt,n=Date.parse(t??``);return Number.isNaN(n)?null:n},[M?.sortBy]),Rt=(0,X.useMemo)(()=>a_(kt,Lt,M?.order===`asc`?`asc`:`desc`),[kt,Lt,M?.order]),zt=le&&Rt.length>1,Bt=(0,X.useCallback)((e,t)=>{he(n=>{let r=new Set(n);for(let n of e)t?r.add(n):r.delete(n);return r})},[]),Vt=(0,X.useMemo)(()=>(ce===`table`?Nt:zt?Rt.filter(e=>!fe.has(e.key)).flatMap(e=>e.items):kt).map(e=>e.id),[ce,Nt,zt,Rt,fe,kt]),Ht=(0,X.useRef)(null),Wt=JSON.stringify([i,n,r,S]),Gt=(0,X.useCallback)((e,t,n,r=!1)=>{let i=Ht.current,a=i?.scope===Wt&&Vt.includes(i.id)?i.id:null;(!r||a===null)&&(Ht.current={scope:Wt,id:e}),he(i=>{if(r)return ff(Vt,a,e,i,n);let o=n?new Set(i):new Set;return t?o.add(e):o.delete(e),o})},[Wt,Vt]),Kt=(0,X.useCallback)((e,t)=>{if(e.target.closest?.(`[role="dialog"]`))return;e.preventDefault(),e.stopPropagation();let n;H.has(t)?n=Array.from(H):(n=[t],he(new Set([t]))),U({x:e.clientX,y:e.clientY,documentIds:n})},[H]),Jt=(0,X.useCallback)(async(e,t)=>{if(t.length!==0&&e.targetIds.length!==0){we(!0);try{for(let n of t)await Wi(i,n,e.predicate,e.targetIds,e.direction);let n=t.length*e.targetIds.length;Ge(`Created ${n} relation${n===1?``:`s`}`),Kp(),xe(null)}catch(e){Ke(e instanceof Error?e.message:`Failed to create relations`)}finally{we(!1)}}},[i,Ge,Ke]),Yt=(0,X.useCallback)(async(e,t,n)=>{if(m){for(let r of e)await m(r,t,{move:!1,targetTreeName:n?.treeName,targetTreeType:n?.treeType});he(new Set)}},[m]),Xt=(0,X.useCallback)(async(e,t,n)=>{if(!(!i||!Te)){ke(!0);try{let r=await Oi(i,Te.ids,{to:e,mode:t,keepDocument:n.keepDocument,folder:n.folder,filename:n.filename,onConflict:n.onConflict}),a=r.successful.filter(e=>e.transfers?.every(e=>e.state===`unchanged`)).length,o=r.successful.length-a,s=r.failed.length,c=t===`delete`?`Deleted from`:t===`move`?`Moved to`:`Copied to`,l=e.join(`, `),u=[a?`${a} already there`:null,s?`${s} skipped`:null].filter(Boolean).join(` · `);o>0?Ge(`${c} ${l}: ${o} document${o===1?``:`s`}${u?` · ${u}`:``}`):a>0?Ge(`Nothing to do — already on ${l}`):s>0&&Ke(r.failed[0]?.reason||`Transfer failed`),s>0&&console.warn(`Backend transfer skipped documents:`,r.failed),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),De(null),he(new Set)}catch(e){Ke(e instanceof Error?e.message:String(e))}finally{ke(!1)}}},[i,Te,Ge,Ke]),Zt=(0,X.useCallback)(async(t,n)=>{switch(t){case`edit`:if(n.length===1){let t=e.find(e=>e.id===n[0]);if(t){He({document:t,edit:!0}),U(null);return}}break;case`copy`:f?.(n);break;case`cut`:p?.(n);break;case`link-to`:xe(n),U(null);return;case`add-related`:W(n),U(null);return;case`remove`:n.length===1?o?.(n[0]):l?.(n);break;case`delete`:n.length===1?s?.(n[0]):u?.(n);break;case`destroy`:n.length===1?c?.(n[0]):d?.(n);break;case`view-details`:if(n.length===1){let t=e.find(e=>e.id===n[0]);if(t){He({document:t}),U(null);return}}break;case`open-url`:if(n.length===1){let t=e.find(e=>e.id===n[0]);t&&t.schema===`data/schema/tab`&&t.data.url&&window.open(t.data.url,`_blank`,`noopener,noreferrer`)}break;case`copy-id`:if(n.length===1)try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(n[0].toString());else{let e=document.createElement(`textarea`);e.value=n[0].toString(),document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e)}}catch(e){console.error(`Failed to copy ID to clipboard:`,e);let t=document.createElement(`textarea`);t.value=n[0].toString(),document.body.appendChild(t),t.select(),document.execCommand(`copy`),document.body.removeChild(t)}}U(null),he(new Set)},[f,p,o,l,s,u,c,d,e,W]),en=(0,X.useCallback)(e=>{e.target.closest?.(`[role="dialog"]`)||!(_&&_.length>0&&m)&&!h||(e.preventDefault(),e.stopPropagation(),$e({x:e.clientX,y:e.clientY}))},[_,m,h]),tn=(0,X.useCallback)(async()=>{if(!(!m||!_||_.length===0))try{await m(n,_)}catch(e){console.error(`Failed to paste documents:`,e)}finally{$e(null)}},[m,_,n]),rn=(0,X.useCallback)(()=>{H.size===kt.length?he(new Set):he(new Set(kt.map(e=>e.id)))},[H.size,kt]),an=(0,X.useCallback)(async e=>{if(!h)return!1;try{return await h(e,n)}catch(e){return console.error(`Failed to import documents:`,e),!1}},[h,n]),on=e=>zt?Rt.map(t=>{let n=fe.has(t.key),r=t.items.map(e=>e.id),i=r.reduce((e,t)=>e+ +!!H.has(t),0);return(0,Z.jsxs)(`section`,{className:`group mb-4`,children:[(0,Z.jsx)(E_,{label:t.label,count:t.items.length,collapsed:n,allSelected:i===r.length,someSelected:i>0,onToggle:()=>me(t.key),onSelectAll:e=>Bt(r,e)}),!n&&e(t.items)]},t.key)}):e(kt);return t?(0,Z.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,children:(0,Z.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Z.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading documents...`})]})}):(0,Z.jsxs)(`div`,{className:`flex-1 flex flex-col min-h-0 p-4 rounded-lg transition-colors ${ct?`ring-2 ring-inset ring-primary bg-primary/5`:``}`,onDragOver:bt,onDragLeave:xt,onDrop:yt,children:[(0,Z.jsxs)(`div`,{className:`border-b pb-3 mb-4 flex-shrink-0`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 space-y-0.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold text-sm text-muted-foreground`,children:`Documents`}),(0,Z.jsx)(`p`,{className:`shrink-0 text-sm font-medium`,children:ot?`${kt.length} of ${e.length}`:`${a.toLocaleString()} document${a===1?``:`s`}`})]}),(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsxs)(`p`,{className:`min-w-0 truncate`,children:[`Context: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:n}),b&&x&&b!==x&&(0,Z.jsx)(`span`,{className:`text-warning ml-2`,children:`(not yet active)`})]}),(0,Z.jsxs)(`p`,{className:`shrink-0`,children:[H.size>0&&(0,Z.jsxs)(`span`,{className:`text-info`,children:[H.size,` selected`]}),H.size>0&&(ot||a>w)&&(0,Z.jsx)(`span`,{className:`mx-1`,children:`·`}),ot?`on this page`:a>w?`Showing ${Math.min((S-1)*w+1,a)}–${Math.min(S*w,a)}`:null]})]})]}),(0,Z.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`relative flex flex-wrap items-center gap-2`,children:[ee&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 rounded-md border border-input overflow-hidden text-xs font-medium`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>ee(`path`),className:`px-2.5 py-2 transition-colors ${P===`path`?`bg-primary text-primary-foreground`:`bg-background text-muted-foreground hover:text-foreground hover:bg-muted`}`,title:`List documents in the selected path`,children:`This path`}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>ee(`workspace`),className:`px-2.5 py-2 border-l border-input transition-colors flex items-center gap-1 ${P===`workspace`?`bg-primary text-primary-foreground`:`bg-background text-muted-foreground hover:text-foreground hover:bg-muted`}`,title:`List every document in the workspace (staging excluded)`,children:[(0,Z.jsx)(C,{className:`h-3.5 w-3.5`}),`Whole workspace`]})]}),y&&(0,Z.jsx)(`div`,{className:`flex shrink-0 items-center rounded-md border p-0.5 touch-target`,children:[[`table`,It,`Table view`],[`tile`,Jn,`Tile view`],[`card`,Ut,`Card view`]].map(([e,t,n])=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>V(e),title:n,"aria-pressed":ce===e,className:`rounded-sm p-1.5 transition-colors ${ce===e?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,Z.jsx)(t,{className:`h-4 w-4`})},e))}),y&&ce!==`table`&&(0,Z.jsx)(`button`,{type:`button`,onClick:de,title:le?`Grouping by date — click for a flat list`:`Group by date (Today, Yesterday, …)`,"aria-pressed":le,className:`touch-target shrink-0 rounded-md border p-1.5 transition-colors ${le?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,Z.jsx)(oe,{className:`h-4 w-4`})}),(0,Z.jsxs)(`div`,{className:`relative flex-1 min-w-[12rem]`,children:[(0,Z.jsx)(Xn,{className:`absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none`}),(0,Z.jsx)(`input`,{ref:ft,type:`text`,placeholder:A?dt?`Refine: add another query (Enter)…`:`Search documents (Enter for server search)…`:`Search documents...`,defaultValue:``,onChange:e=>st(e.target.value),onFocus:e=>{let t=e.currentTarget;window.matchMedia(`(max-width: 767px)`).matches&&setTimeout(()=>t.scrollIntoView({block:`center`,behavior:`smooth`}),250)},onKeyDown:e=>{e.key===`Enter`&&A&&(e.preventDefault(),gt())},className:`w-full pl-10 pr-9 py-2 border border-input rounded-md bg-background text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent`}),(ot||dt)&&(0,Z.jsx)(`button`,{onClick:_t,className:`absolute right-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground hover:text-foreground`,title:`Clear search`,children:(0,Z.jsx)(je,{className:`h-4 w-4`})})]}),A&&ot.trim()&&!k.includes(ot.trim())&&(0,Z.jsxs)(J,{size:`sm`,variant:`default`,onClick:gt,className:`shrink-0`,title:dt?`Refine: narrow the current results by this query`:`Run full-text search on the server`,children:[(0,Z.jsx)(Xn,{className:`h-3.5 w-3.5 mr-1`}),dt?`Refine`:`Search server`]}),F&&L&&(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,onClick:L,disabled:te,className:`shrink-0`,title:`Save current query and filters`,children:[(0,Z.jsx)(Re,{className:`h-3.5 w-3.5 mr-1`}),te?`Saving...`:`Save filters`]})]}),dt&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 text-xs`,children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Server search:`}),k.map((e,t)=>(0,Z.jsxs)(`span`,{className:`flex items-center gap-1`,children:[t>0&&(0,Z.jsx)(`span`,{className:`text-muted-foreground/70 font-medium uppercase text-[10px]`,children:`then`}),(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 px-2 py-0.5 rounded bg-muted text-foreground border`,children:[(0,Z.jsxs)(`span`,{className:`font-mono`,children:[`"`,e,`"`]}),j&&(0,Z.jsx)(`button`,{onClick:()=>j(t),className:`text-muted-foreground hover:text-foreground`,title:`Remove this query`,children:(0,Z.jsx)(je,{className:`h-3 w-3`})})]})]},`${e}-${t}`)),j&&k.length>1&&(0,Z.jsx)(`button`,{onClick:()=>j(-1),className:`ml-1 text-muted-foreground hover:text-foreground underline`,title:`Clear all queries`,children:`clear all`})]})]}),T&&a>0&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 mt-3 pt-3 border-t max-sm:flex-nowrap max-sm:gap-1`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1.5 text-sm text-muted-foreground`,children:[(0,Z.jsx)(`span`,{className:`max-sm:sr-only`,children:`Show:`}),(0,Z.jsxs)(`select`,{value:w,onChange:e=>E?.(Number(e.target.value)),className:`h-control-sm rounded-(--input-radius) border-(length:--input-border-width) border-input bg-background px-2 text-sm focus-ring`,children:[(0,Z.jsx)(`option`,{value:25,children:`25`}),(0,Z.jsx)(`option`,{value:50,children:`50`}),(0,Z.jsx)(`option`,{value:100,children:`100`}),(0,Z.jsx)(`option`,{value:200,children:`200`})]}),(0,Z.jsx)(`span`,{className:`max-sm:sr-only`,children:`per page`})]}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 max-sm:gap-0.5`,children:[(0,Z.jsxs)(`span`,{className:`text-sm text-muted-foreground max-md:hidden`,children:[`Showing `,Math.min((S-1)*w+1,a),` - `,Math.min(S*w,a),` of `,a]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 max-sm:gap-0.5`,children:[(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>T(1),disabled:S===1,className:`p-1 touch-target`,children:(0,Z.jsx)(I,{className:`h-4 w-4`})}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>T(S-1),disabled:S===1,className:`p-1 touch-target`,children:(0,Z.jsx)(ve,{className:`h-4 w-4`})}),(0,Z.jsxs)(`span`,{className:`whitespace-nowrap px-3 py-1 text-sm font-medium max-sm:px-1 max-sm:text-xs`,children:[(0,Z.jsx)(`span`,{className:`max-sm:sr-only`,children:`Page `}),S,(0,Z.jsx)(`span`,{className:`max-sm:hidden`,children:` of `}),(0,Z.jsx)(`span`,{className:`sm:hidden`,children:`/`}),Math.ceil(a/w)]}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>T(S+1),disabled:S>=Math.ceil(a/w),className:`p-1 touch-target`,children:(0,Z.jsx)(B,{className:`h-4 w-4`})}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>T(Math.ceil(a/w)),disabled:S>=Math.ceil(a/w),className:`p-1 touch-target`,children:(0,Z.jsx)(Ee,{className:`h-4 w-4`})})]})]})]}),e.length>0&&(0,Z.jsxs)(`div`,{className:`mt-3 pt-3 border-t`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>tt(e=>!e),"aria-expanded":et,className:`flex w-full items-center justify-between gap-2 rounded-md border px-2.5 py-1.5 text-xs text-muted-foreground hover:bg-accent/50 sm:hidden`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(Ot,{className:`h-3.5 w-3.5`}),`Actions`,H.size>0?` (${H.size} selected)`:``]}),(0,Z.jsx)(Ne,{className:`h-3.5 w-3.5 transition-transform ${et?`rotate-180`:``}`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap ${et?`max-sm:mt-2`:`max-sm:hidden`}`,children:[N&&M&&i&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Sort`}),(0,Z.jsx)(Xg,{workspaceId:i,value:M,onChange:N})]}),ce!==`table`&&(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:rn,className:`flex items-center gap-2`,disabled:kt.length===0,children:H.size===kt.length?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Sn,{className:`h-4 w-4`}),`Deselect Page`,ot&&` (${kt.length})`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)($t,{className:`h-4 w-4`}),`Select Page`,ot&&` (${kt.length})`]})}),D&&a>0&&H.size===0&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:D,disabled:O||!!ot,className:`flex items-center gap-2 text-destructive hover:text-destructive-foreground hover:bg-destructive`,title:O||ot?`Purge is disabled while local search is active`:`Delete all documents matching the current server-side filters across all pages`,children:[(0,Z.jsx)(lt,{className:`h-4 w-4`}),`Purge All (`,a,`)`]}),H.size>0&&(0,Z.jsxs)(Z.Fragment,{children:[ze&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>Le(Array.from(H)),children:[(0,Z.jsx)(ye,{className:`mr-2 h-4 w-4`}),`Bulk Edit… (`,H.size,`)`]}),(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>{let e=Array.from(H);f?.(e)},className:`flex items-center gap-2`,title:`Copy selected documents`,children:[(0,Z.jsx)(Ct,{className:`h-4 w-4`}),`Copy (`,H.size,`)`]}),Ue&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>xe(Array.from(H)),className:`flex items-center gap-2`,title:`Link selected documents to another path`,children:[(0,Z.jsx)(qt,{className:`h-4 w-4`}),`Link to… (`,H.size,`)`]}),ze&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>Fe(Array.from(H)),children:[(0,Z.jsx)(Ct,{className:`mr-1 h-4 w-4`}),`Copy to workspace…`]}),Ce&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>W(Array.from(H)),className:`flex items-center gap-2`,title:`Create a new document related to the selected ones`,children:[(0,Z.jsx)(nn,{className:`h-4 w-4`}),`Add related… (`,H.size,`)`]}),We&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>De({ids:Array.from(H),mode:`copy`}),className:`flex items-center gap-2`,title:`Copy, move, or delete the file data on storage backends`,children:[(0,Z.jsx)(_e,{className:`h-4 w-4`}),`Backends… (`,H.size,`)`]}),p&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>{p(Array.from(H))},className:`flex items-center gap-2`,title:`Cut selected documents`,children:[(0,Z.jsx)(wt,{className:`h-4 w-4`}),`Cut (`,H.size,`)`]}),(o||l)&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,disabled:Ye,onClick:()=>{let e=Array.from(H);e.length===1?Xe?.(e[0]):Ze?.(e),he(new Set)},className:`flex items-center gap-2`,title:Ye?`Switch to “This path” to remove documents from a folder`:`Remove selected documents from this folder (kept in index)`,children:[(0,Z.jsx)(je,{className:`h-4 w-4`}),`Remove (unlink) from folder (`,H.size,`)`]}),(s||u)&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>{let e=Array.from(H);e.length===1?s?.(e[0]):u?.(e),he(new Set)},className:`flex items-center gap-2 text-destructive hover:text-destructive-foreground hover:bg-destructive`,title:`Delete from index (data stays on backends)`,children:[(0,Z.jsx)(lt,{className:`h-4 w-4`}),`Delete from index (`,H.size,`)`]}),(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>rt(!0),className:`flex items-center gap-2`,title:`Export selected documents`,children:[(0,Z.jsx)(wn,{className:`h-4 w-4`}),`Export (`,H.size,`)`]})]}),_&&_.length>0&&m&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>m(n,_),className:`flex items-center gap-2`,title:`Paste documents to current context`,children:[(0,Z.jsx)(Ve,{className:`h-4 w-4`}),`Paste (`,_.length,`)`]}),H.size===0&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>rt(!0),className:`flex items-center gap-2`,title:`Export all documents`,children:[(0,Z.jsx)(wn,{className:`h-4 w-4`}),`Export All`]}),h&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>at(!0),className:`flex items-center gap-2`,title:`Import documents`,children:[(0,Z.jsx)(ne,{className:`h-4 w-4`}),`Import`]}),m&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>Me(!0),className:`flex items-center gap-2`,title:`Browse and add existing documents to this folder`,children:[(0,Z.jsx)(Qt,{className:`h-4 w-4`}),`Add existing…`]})]})]})]}),kt.length===0&&!jt?(0,Z.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,onContextMenu:en,children:(0,Z.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Z.jsx)(Bn,{className:`h-12 w-12 text-muted-foreground/50 mx-auto`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:ot?`No documents match your search`:`No documents found in this context`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:ot?(0,Z.jsxs)(Z.Fragment,{children:[`Search: `,(0,Z.jsxs)(`span`,{className:`font-mono`,children:[`"`,ot,`"`]})]}):(0,Z.jsxs)(Z.Fragment,{children:[`Path: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:n})]})}),ot&&(0,Z.jsx)(`button`,{onClick:pt,className:`text-xs text-primary hover:text-primary/80 underline mt-1`,children:`Clear search`}),!ot&&_&&_.length>0&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Right-click to paste `,_.length,` document(s)`]})]})}):ce===`tile`?(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,onContextMenu:en,children:[(0,Z.jsx)(C_,{...Mt}),kt.length===0&&(0,Z.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),on(e=>(0,Z.jsx)(`div`,{className:`columns-[300px] gap-3 pr-2`,children:e.map(e=>(0,Z.jsx)(__,{document:e,isSelected:H.has(e.id),workspaceId:i,onSelect:Gt,onRemoveDocument:Xe,onDeleteDocument:s,onLinkDocument:Ue?e=>xe([e]):void 0,onOpenToSide:Je,onRightClick:Kt,onDragStart:vt},e.id))}))]}):ce===`table`?(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto`,onContextMenu:en,children:(0,Z.jsxs)(Fp,{children:[(0,Z.jsx)(Ip,{children:(0,Z.jsxs)(zp,{children:[(0,Z.jsx)(Bp,{className:`w-10`,children:(0,Z.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 cursor-pointer accent-primary align-middle`,checked:kt.length>0&&H.size===kt.length,ref:e=>{e&&(e.indeterminate=H.size>0&&H.size<kt.length)},onChange:rn,title:`Select all on this page`})}),(0,Z.jsx)(Up,{label:(0,Z.jsx)(`span`,{className:`max-md:sr-only`,children:`Type`}),sortKey:`type`,sort:Pt,onSort:Ft,className:`w-12`}),(0,Z.jsx)(Up,{label:`Title`,sortKey:`title`,sort:Pt,onSort:Ft,className:`w-full max-w-0 md:w-auto md:max-w-none`}),(0,Z.jsx)(Up,{label:`Schema`,sortKey:`schema`,sort:Pt,onSort:Ft,className:`hidden md:table-cell`}),(0,Z.jsx)(Up,{label:`ID`,sortKey:`id`,sort:Pt,onSort:Ft,className:`hidden lg:table-cell`}),(0,Z.jsx)(Bp,{className:`hidden lg:table-cell`,children:`Checksum`}),(0,Z.jsx)(Up,{label:`Created`,sortKey:`created`,sort:Pt,onSort:Ft,className:`hidden sm:table-cell`}),(0,Z.jsx)(Bp,{className:`w-12 md:w-auto`,children:(0,Z.jsx)(`span`,{className:`max-md:sr-only`,children:`Actions`})})]})}),(0,Z.jsxs)(Lp,{children:[At.map(e=>(0,Z.jsx)(T_,{folder:e,onOpen:ae,onPasteDocuments:m,contextPath:n,treeName:r},e.path)),Nt.map(e=>(0,Z.jsx)(u_,{document:e,isSelected:H.has(e.id),workspaceId:i,onSelect:Gt,onRemoveDocument:Xe,onDeleteDocument:s,onLinkDocument:Ue?e=>xe([e]):void 0,onOpenToSide:Je,onRightClick:Kt,onDragStart:vt},e.id))]})]})}):(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,onContextMenu:en,children:[(0,Z.jsx)(w_,{...Mt}),kt.length===0&&(0,Z.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),on(e=>(0,Z.jsx)(`div`,{className:`space-y-3 pr-2`,children:e.map(e=>(0,Z.jsx)(`div`,{onContextMenu:t=>{t.stopPropagation(),Kt(t,e.id)},children:(0,Z.jsx)(d_,{document:e,isSelected:H.has(e.id),workspaceId:i,onSelect:Gt,onRemoveDocument:Xe,onDeleteDocument:s,onLinkDocument:Ue?e=>xe([e]):void 0,onOpenToSide:Je,onRightClick:Kt,onDragStart:vt})},e.id))}))]}),ge&&(0,Z.jsxs)(_f,{x:ge.x,y:ge.y,onClose:()=>U(null),className:`bg-background border rounded-lg shadow-elevation-3 py-1 min-w-[120px]`,children:[(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Zt(`copy`,ge.documentIds),children:[(0,Z.jsx)(Ct,{className:`h-3 w-3`}),`Copy `,ge.documentIds.length>1?`(${ge.documentIds.length})`:``]}),ze&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>{Fe(ge.documentIds),U(null)},children:[(0,Z.jsx)(Ct,{className:`h-3 w-3`}),`Copy to workspace…`]}),p&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Zt(`cut`,ge.documentIds),children:[(0,Z.jsx)(wt,{className:`h-3 w-3`}),`Cut `,ge.documentIds.length>1?`(${ge.documentIds.length})`:``]}),Ue&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Zt(`link-to`,ge.documentIds),children:[(0,Z.jsx)(qt,{className:`h-3 w-3`}),`Link to… `,ge.documentIds.length>1?`(${ge.documentIds.length})`:``]}),ze&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>{Le(ge.documentIds),U(null)},children:[(0,Z.jsx)(ye,{className:`h-3 w-3`}),`Bulk Edit… (`,ge.documentIds.length,`)`]}),Ce&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Zt(`add-related`,ge.documentIds),children:[(0,Z.jsx)(nn,{className:`h-3 w-3`}),`Add related document… `,ge.documentIds.length>1?`(${ge.documentIds.length})`:``]}),ge.documentIds.length===1&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Zt(`view-details`,ge.documentIds),children:[(0,Z.jsx)(Dt,{className:`h-3 w-3`}),`View Details`]}),(()=>{let t=e.find(e=>e.id===ge.documentIds[0]);return t?.schema===`data/schema/note`||t?.schema===`data/schema/link`?(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Zt(`edit`,ge.documentIds),children:[(0,Z.jsx)(ye,{className:`h-3 w-3`}),`Edit`]}):null})(),(()=>{let t=e.find(e=>e.id===ge.documentIds[0]);return t?.schema===`data/schema/tab`&&t?.data.url?(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Zt(`open-url`,ge.documentIds),children:[(0,Z.jsx)(Gn,{className:`h-3 w-3`}),`Open URL`]}):null})(),(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Zt(`copy-id`,ge.documentIds),children:[(0,Z.jsx)(fn,{className:`h-3 w-3`}),`Copy ID`]})]}),(Xe||Ze)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,title:`Unlinks from this folder; the document stays in the index`,onClick:()=>Zt(`remove`,ge.documentIds),children:[(0,Z.jsx)(R,{className:`h-3 w-3`}),`Remove (unlink) from folder `,ge.documentIds.length>1?`(${ge.documentIds.length})`:``]})]}),(s||u)&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2 text-destructive`,title:`Removes the document from the index entirely; file data stays on its backend(s)`,onClick:()=>Zt(`delete`,ge.documentIds),children:[(0,Z.jsx)(lt,{className:`h-3 w-3`}),`Delete from index `,ge.documentIds.length>1?`(${ge.documentIds.length})`:``]}),We&&ge.documentIds.some(t=>(e.find(e=>e.id===t)?.locations?.length??0)>0)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),(0,Z.jsx)(`div`,{className:`px-3 py-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground`,children:`Backends`}),(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,title:`Copy the file data to another storage backend (keeps the existing copies)`,onClick:()=>{De({ids:ge.documentIds,mode:`copy`}),U(null)},children:[(0,Z.jsx)(_e,{className:`h-3 w-3`}),`Copy to backend… `,ge.documentIds.length>1?`(${ge.documentIds.length})`:``]}),(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,title:`Move the file data to another storage backend (source released once the copy is durable)`,onClick:()=>{De({ids:ge.documentIds,mode:`move`}),U(null)},children:[(0,Z.jsx)(yn,{className:`h-3 w-3`}),`Move to backend… `,ge.documentIds.length>1?`(${ge.documentIds.length})`:``]}),(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-destructive hover:text-destructive-foreground text-sm flex items-center gap-2 text-destructive font-medium`,title:`Delete the file data from selected backends (copies elsewhere are kept)`,onClick:()=>{De({ids:ge.documentIds,mode:`delete`}),U(null)},children:[(0,Z.jsx)(lt,{className:`h-3 w-3`}),`Delete from backend… `,ge.documentIds.length>1?`(${ge.documentIds.length})`:``]})]}),!We&&(c||d)&&ge.documentIds.some(t=>(e.find(e=>e.id===t)?.locations?.length??0)>0)&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-destructive hover:text-destructive-foreground text-sm flex items-center gap-2 text-destructive font-medium`,title:`Deletes the document and its file data from the storage backend(s)`,onClick:()=>Zt(`destroy`,ge.documentIds),children:[(0,Z.jsx)(lt,{className:`h-3 w-3`}),`Delete from backend(s) `,ge.documentIds.length>1?`(${ge.documentIds.length})`:``]})]}),Qe&&(0,Z.jsxs)(_f,{x:Qe.x,y:Qe.y,onClose:()=>$e(null),className:`bg-background border rounded-lg shadow-elevation-3 py-1 min-w-[120px]`,children:[_&&_.length>0&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:tn,children:[(0,Z.jsx)(Ve,{className:`h-3 w-3`}),`Paste Documents (`,_.length,`)`]}),h&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>{$e(null),at(!0)},children:[(0,Z.jsx)(ne,{className:`h-3 w-3`}),`Import Documents`]})]}),(0,Z.jsx)(o_,{isOpen:nt,onClose:()=>rt(!1),documents:e,selectedDocuments:H}),(0,Z.jsx)(s_,{isOpen:it,onClose:()=>at(!1),onImport:an}),Pe&&i&&(0,Z.jsx)(lp,{workspaceId:i,ids:Pe,onClose:()=>Fe(null)}),be&&re&&(0,Z.jsx)(sp,{onClose:()=>xe(null),children:(0,Z.jsx)(ap,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,documentCount:be.length,fixedWorkspaceName:i,tabs:[`context`,`directory`,`relations`],saving:G,relationExcludeIds:new Set(be),onConfirm:(e,t)=>Yt(e,be,t),onConfirmRelation:e=>Jt(e,be),onClose:()=>xe(null)})}),Te&&i&&(0,pf.createPortal)((0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,Z.jsx)(Ap,{workspaceId:i,documentCount:Te.ids.length,initialMode:Te.mode,defaultFilename:Te.ids.length===1?so(e.find(e=>e.id===Te.ids[0])??{}):``,saving:Oe,onConfirm:Xt,onClose:()=>{Oe||De(null)}})}),window.document.body),Ae&&m&&(0,pf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:()=>Me(!1),"aria-hidden":!0}),(0,Z.jsx)(`div`,{className:`fixed inset-y-0 right-0 z-picker flex items-stretch py-2 pr-2 max-md:bottom-2 max-md:left-2 max-md:top-2 max-md:py-0 max-md:pr-0 max-md:animate-fade-in`,children:(0,Z.jsx)(jp,{sizeClassName:`h-full w-[420px] max-w-full max-md:w-full max-md:shadow-elevation-5`,fixedWorkspaceName:i,onConfirm:async e=>{await m(n,e),Me(!1)},onClose:()=>Me(!1)})})]}),window.document.body),Ie&&i&&(0,Z.jsx)(Tp,{workspaceId:i,documentIds:Ie,onClose:()=>Le(null)}),(0,Z.jsx)(Wg,{document:Be?.document??null,isOpen:!!Be,onClose:()=>He(null),workspaceId:i,initialEdit:Be?.edit})]})}function O_(e,t){let n=typeof e.setCanvasQueries==`function`,[r,i]=(0,X.useState)(e.canvasQueries??[]),a=(0,X.useMemo)(()=>n?e.canvasQueries??[]:r,[n,e.canvasQueries,r]),o=(0,X.useCallback)(r=>{n?e.setCanvasQueries(r):i(r),t?.()},[n,e,t]);return{queries:a,runSearch:(0,X.useCallback)(e=>{let t=e.trim();!t||a.includes(t)||o([...a,t])},[a,o]),removeQuery:(0,X.useCallback)(e=>{o(e<0?[]:a.filter((t,n)=>n!==e))},[a,o]),clearSearch:(0,X.useCallback)(()=>o([]),[o])}}function k_({config:e,canvas:t}){let n=typeof e.pageSize==`number`?e.pageSize:50,r=e.viewMode===`card`||e.viewMode===`tile`||e.viewMode===`table`?e.viewMode:`table`,[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(0),[c,l]=(0,X.useState)(1),[u,d]=(0,X.useState)(!0),f=t.canvasSort??Kg,{queries:p,runSearch:m,removeQuery:h}=O_(t,()=>l(1));(0,X.useEffect)(()=>{let e=!1;return(async()=>{d(!0);try{let r=await t.fetchDocuments({limit:n,page:c,sortBy:f.sortBy,order:f.order,queries:p.length?p:void 0});if(e)return;a(r.payload||[]),s(r.totalCount||r.count||0)}catch{e||(a([]),s(0))}finally{e||d(!1)}})(),()=>{e=!0}},[t,n,c,f.sortBy,f.order,p]);let g=(0,X.useCallback)(e=>{t.setCanvasSort?.(e),l(1)},[t]),_=t.readOnly===!0;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!_&&(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-2 border-b px-1 pb-2`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Sort`}),(0,Z.jsx)(Xg,{workspaceId:t.workspaceId,value:f,onChange:g})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:(0,Z.jsx)(D_,{documents:i,isLoading:u,contextPath:t.path,treeName:t.treeName,workspaceId:t.workspaceId,totalCount:o,viewMode:r,allowViewToggle:!0,currentPage:c,pageSize:n,onPageChange:l,backendSearchQueries:p,onBackendSearch:_?void 0:m,onRemoveBackendQuery:_?void 0:h})})]})}sf({type:`documents-table`,name:`Documents`,icon:It,defaultSize:{w:8,h:6,minW:4,minH:3},mobileHeight:.9,defaultConfig:{pageSize:50,viewMode:`table`},component:k_});function A_({config:e,setConfig:t,canvas:n}){let[r,i]=(0,X.useState)(()=>new Date),a=e.format!==`24`;return(0,X.useEffect)(()=>{let e=setInterval(()=>i(new Date),1e3);return()=>clearInterval(e)},[]),(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-1`,children:[(0,Z.jsx)(`div`,{className:`text-3xl font-semibold tabular-nums`,children:r.toLocaleTimeString(void 0,{hour12:a,hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:r.toLocaleDateString(void 0,{weekday:`short`,month:`short`,day:`numeric`})}),!n.readOnly&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t({...e,format:a?`24`:`12`}),className:`mt-1 px-2 py-0.5 text-[10px] border rounded-md text-muted-foreground hover:bg-accent`,children:a?`12h`:`24h`})]})}sf({type:`clock`,name:`Clock`,icon:Qn,defaultSize:{w:3,h:2,minW:2,minH:2},defaultConfig:{format:`24`},component:A_});var j_=450,M_=10;function N_(e,t){let{open:n}=gg(),r=(0,X.useRef)(null),i=(0,X.useRef)(null),a=(0,X.useRef)(!1),o=()=>{e&&n(e,t)},s=()=>{r.current&&=(clearTimeout(r.current),null)};return{activationProps:{role:`button`,tabIndex:0,onClick:()=>{if(a.current){a.current=!1;return}o()},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())},onContextMenu:e=>{e.preventDefault(),o()},onPointerDown:e=>{e.pointerType===`touch`&&(i.current={x:e.clientX,y:e.clientY},a.current=!1,s(),r.current=setTimeout(()=>{a.current=!0,o()},j_))},onPointerMove:e=>{i.current&&Math.hypot(e.clientX-i.current.x,e.clientY-i.current.y)>M_&&s()},onPointerUp:s,onPointerCancel:s,onPointerLeave:s},stopRowActivation:e=>e.stopPropagation()}}function P_({doc:e,workspaceId:t}){let n=mo(e),{activationProps:r}=N_(e,t);return(0,Z.jsxs)(`li`,{...r,title:`Open details`,className:`canvas-no-drag cursor-pointer py-1.5 min-w-0 rounded px-1 transition-colors hover:bg-accent/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,Z.jsx)(`div`,{className:`truncate font-medium`,children:n.title}),n.preview&&(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:n.preview})]})}function F_({config:e,canvas:t}){let n=typeof e.limit==`number`?e.limit:10,[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(!0),[s,c]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=!1;return(async()=>{o(!0);try{let r=await t.fetchDocuments({limit:n});if(e)return;i(r.payload||[]),c(null)}catch(t){if(e)return;c(t instanceof Error?t.message:`Failed to load documents`),i([])}finally{e||o(!1)}})(),()=>{e=!0}},[t,n]),a?(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground p-1`,children:`Loading…`}):s?(0,Z.jsx)(`div`,{className:`text-xs text-destructive p-1`,children:s}):r.length===0?(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground p-1`,children:`No documents on this canvas.`}):(0,Z.jsx)(`ul`,{className:`divide-y text-sm`,children:r.map(e=>(0,Z.jsx)(P_,{doc:e,workspaceId:t.workspaceId},e.id))})}sf({type:`recent-documents`,name:`Recent documents`,icon:Mn,defaultSize:{w:4,h:4,minW:3,minH:2},mobileHeight:.5,defaultConfig:{limit:10},component:F_});function I_({config:e,setConfig:t,canvas:n}){let r=typeof e.text==`string`?e.text:``;return(0,Z.jsx)(`textarea`,{value:r,readOnly:n.readOnly,onChange:n=>t({...e,text:n.target.value}),placeholder:n.readOnly?``:`Jot something down…`,className:`canvas-no-drag w-full h-full resize-none bg-transparent text-sm leading-6 outline-none`})}sf({type:`note`,name:`Note`,icon:vn,defaultSize:{w:3,h:3,minW:2,minH:2},defaultConfig:{text:``},component:I_});var L_=`data/schema/file`,R_=`data/schema/drawing`;function z_(e){return(e.schema===L_||e.schema===R_)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function B_(e){return e.schema===L_&&String(e.metadata?.contentType||``).startsWith(`video/`)}var V_=`data/mime/image`;function H_(e,t,n=!1){let[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(0),[s,c]=(0,X.useState)(1),[l,u]=(0,X.useState)(!0),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(``),{queries:h,runSearch:g,removeQuery:_,clearSearch:v}=O_(e,()=>c(1)),y=e.canvasSort??Kg;(0,X.useEffect)(()=>{let r=!1,a=async()=>{u(!0),f(null);try{let a=await e.fetchDocuments({limit:t,page:s,queries:h.length?h:void 0,sortBy:y.sortBy,order:y.order,...n?{anyOf:[V_,`data/mime/video`]}:{allOf:[V_]}});if(r)return;i((a.payload||[]).filter(e=>z_(e)||n&&B_(e))),o(a.totalCount||a.count||0)}catch(e){if(r)return;i([]),o(0),f(e instanceof Error?e.message:`Failed to load images`)}finally{r||u(!1)}};return a(),window.addEventListener(`workspace:documents:refresh`,a),()=>{r=!0,window.removeEventListener(`workspace:documents:refresh`,a)}},[e,t,s,h,y.sortBy,y.order,n]);let b=(0,X.useCallback)(()=>{let e=p.trim();m(``),g(e)},[p,g]),x=(0,X.useCallback)(()=>{m(``),v()},[v]),S=(0,X.useCallback)(e=>{_(e)},[_]),C=(0,X.useCallback)(t=>{e.setCanvasSort?.(t),c(1)},[e]);return{images:r,isLoading:l,error:d,page:s,setPage:c,totalCount:a,totalPages:(0,X.useMemo)(()=>Math.max(1,Math.ceil(a/t)),[a,t]),input:p,setInput:m,submit:b,clearSearch:x,removeQuery:S,activeQueries:h,sort:y,setSort:C}}function U_({workspaceId:e,doc:t,onClick:n,className:r=`aspect-square`,comments:i=`off`}){let{blobUrl:a,error:o,loading:s}=jm(e,t.id,512,{blobFallback:!B_(t),version:t.checksumArray?.[0]??null}),c=so(t)||`image-${t.id}`,l=_o(t),u=l!==``&&i!==`off`;return(0,Z.jsxs)(`button`,{type:`button`,onClick:n,title:l||c,className:`canvas-no-drag group relative block w-full overflow-hidden rounded-lg border bg-muted/40 shadow-elevation-1 transition-shadow hover:shadow-elevation-2 hover:ring-2 hover:ring-primary/30 ${r}`,children:[s&&(0,Z.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),o&&!B_(t)&&(0,Z.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center p-1 text-[10px] text-destructive`,children:o}),a&&(0,Z.jsx)(`img`,{src:a,alt:c,loading:`lazy`,className:`h-full w-full object-cover transition-transform duration-200 group-hover:scale-105`}),B_(t)&&(0,Z.jsxs)(`span`,{className:`absolute inset-0 flex items-center justify-center`,children:[(0,Z.jsx)(W,{className:`h-10 w-10 rounded-full bg-black/60 p-2 text-white`}),(0,Z.jsx)(`span`,{className:`sr-only`,children:`Play video`})]}),u&&(0,Z.jsx)(`span`,{className:`pointer-events-none absolute inset-x-0 bottom-0 px-1.5 pb-1 pt-4 text-left text-[11px] leading-snug text-white bg-gradient-to-t from-black/75 via-black/45 to-transparent ${i===`reveal`?`caption-reveal`:``}`,children:(0,Z.jsx)(`span`,{className:`line-clamp-2`,children:l})}),l!==``&&i!==`caption`&&(0,Z.jsx)(`span`,{className:`pointer-events-none absolute right-1 top-1 rounded-full bg-black/55 p-1 text-white transition-opacity ${i===`reveal`?`hidden [@media(hover:hover)]:block [@media(hover:hover)]:group-hover:opacity-0`:``}`,title:`Has a comment`,children:(0,Z.jsx)(Ae,{className:`h-3 w-3`})})]})}function W_({workspaceId:e,docs:t,index:n,onClose:r,onNavigate:i}){let a=t[n],{blobUrl:o,error:s,loading:c}=So(e,a.id,{version:a.checksumArray?.[0]??null,enabled:!B_(a)}),l=so(a)||`image-${a.id}`,u=_o(a),[d,f]=(0,X.useState)(!1);return gf(r),(0,X.useEffect)(()=>{let e=e=>{e.target?.closest(`video`)||(e.key===`ArrowLeft`&&n>0&&i(n-1),e.key===`ArrowRight`&&n<t.length-1&&i(n+1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,t.length,i]),(0,pf.createPortal)((0,Z.jsxs)(`div`,{"data-scheme":`dark`,className:`fixed inset-0 z-fullscreen flex flex-col bg-scrim p-0 sm:p-4`,onClick:r,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:r,className:`canvas-no-drag absolute right-2 top-2 z-10 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20 touch-target sm:right-4 sm:top-4`,title:`Close`,children:(0,Z.jsx)(je,{className:`h-5 w-5`})}),n>0&&!d&&(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),i(n-1)},className:`canvas-no-drag absolute left-3 top-1/2 -translate-y-1/2 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20`,title:`Previous`,children:(0,Z.jsx)(ve,{className:`h-6 w-6 touch-target`})}),n<t.length-1&&!d&&(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),i(n+1)},className:`canvas-no-drag absolute right-3 top-1/2 -translate-y-1/2 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20`,title:`Next`,children:(0,Z.jsx)(B,{className:`h-6 w-6 touch-target`})}),(0,Z.jsxs)(`figure`,{className:`flex min-h-0 flex-1 flex-col`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center`,children:[c&&(0,Z.jsx)(`div`,{className:`text-sm text-foreground/70`,children:`Loading…`}),s&&(0,Z.jsx)(`div`,{className:`text-sm text-destructive`,children:s}),B_(a)&&(0,Z.jsx)(K_,{workspaceId:e,doc:a},a.id),o&&(0,Z.jsx)(ym,{src:o,alt:l,onZoomChange:f,className:`max-h-full max-w-full rounded object-contain`})]}),(0,Z.jsxs)(`figcaption`,{className:`shrink-0 px-4 py-2 text-center text-xs text-foreground/70`,children:[u&&(0,Z.jsx)(`span`,{className:`mx-auto mb-1 block max-w-2xl whitespace-pre-wrap text-sm text-foreground`,children:u}),l,` · `,n+1,`/`,t.length,!d&&!B_(a)&&(0,Z.jsx)(`span`,{className:`ml-2 opacity-70`,children:`· double-tap to zoom`})]})]})]}),document.body)}function G_({workspaceId:e,state:t,comments:n,onToggleComments:r}){let{input:i,setInput:a,submit:o,clearSearch:s,removeQuery:c,activeQueries:l,sort:u,setSort:d,page:f,setPage:p,totalPages:m,totalCount:h,isLoading:g}=t,_=l.length>0;return(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex flex-wrap items-center gap-x-2 gap-y-1.5 border-b px-1 pb-1.5`,children:[(0,Z.jsxs)(`div`,{className:`relative min-w-[9rem] flex-1 basis-full sm:basis-auto`,children:[(0,Z.jsx)(Xn,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&o()},placeholder:_?`Refine: add another query (Enter)…`:`Search media (Enter)…`,className:`h-7 w-full rounded-md border bg-background pl-7 pr-7 text-xs`}),_&&(0,Z.jsx)(`button`,{type:`button`,onClick:s,title:`Clear search`,className:`absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-0.5 text-muted-foreground hover:text-foreground touch-target`,children:(0,Z.jsx)(je,{className:`h-3.5 w-3.5`})})]}),_&&(0,Z.jsx)(`div`,{className:`flex w-full flex-wrap items-center gap-1 order-last`,children:l.map((e,t)=>(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[t>0&&(0,Z.jsx)(`span`,{className:`text-[10px] uppercase text-muted-foreground`,children:`then`}),(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-full border bg-accent/50 px-2 py-0.5 text-xs`,children:[(0,Z.jsx)(`span`,{className:`max-w-[10rem] truncate`,children:e}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(t),title:`Remove "${e}"`,className:`rounded p-0.5 text-muted-foreground hover:text-foreground touch-target`,children:(0,Z.jsx)(je,{className:`h-3 w-3`})})]})]},`${e}-${t}`))}),(0,Z.jsxs)(`div`,{className:`flex flex-1 basis-full items-center justify-between gap-2 sm:basis-auto sm:justify-end`,children:[r&&(0,Z.jsx)(`button`,{type:`button`,onClick:r,"aria-pressed":n!==`off`,title:n===`off`?`Show comments on tiles`:`Hide comments on tiles`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border touch-target ${n===`off`?`text-muted-foreground hover:bg-accent`:`border-primary/30 bg-primary/15 text-primary hover:bg-primary/25`}`,children:(0,Z.jsx)(Ae,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(Xg,{workspaceId:e,value:u,onChange:d}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1`,children:[g&&(0,Z.jsx)(id,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`shrink-0 whitespace-nowrap tabular-nums text-xs text-muted-foreground`,children:[h.toLocaleString(),(0,Z.jsxs)(`span`,{className:`hidden sm:inline`,children:[` item`,h===1?``:`s`]})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(Math.max(1,f-1)),disabled:f<=1,title:`Previous page`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent disabled:opacity-40 touch-target`,children:(0,Z.jsx)(ve,{className:`h-3.5 w-3.5`})}),(0,Z.jsxs)(`span`,{className:`shrink-0 tabular-nums text-xs text-muted-foreground`,children:[f,`/`,m]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(Math.min(m,f+1)),disabled:f>=m,title:`Next page`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent disabled:opacity-40 touch-target`,children:(0,Z.jsx)(B,{className:`h-3.5 w-3.5`})})]})]})]})}function K_({workspaceId:e,doc:t}){let{src:n,loading:r,error:i}=lo(e,t.id);return(0,Z.jsxs)(Z.Fragment,{children:[r&&(0,Z.jsx)(`span`,{children:`Loading video…`}),i&&(0,Z.jsx)(`span`,{role:`alert`,children:i}),n&&(0,Z.jsx)(`video`,{src:n,controls:!0,playsInline:!0,preload:`metadata`,className:`max-h-full max-w-full`})]})}function q_({config:e,setConfig:t,canvas:n}){let r=H_(n,typeof e.pageSize==`number`?e.pageSize:60,!0),i=bo()==null&&(n.interactive??!n.readOnly),[a,o]=(0,X.useState)(new Set),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),p=e=>o(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),[m,h]=(0,X.useState)(null),{images:g,isLoading:_,error:v,activeQueries:y}=r,b=e.showComments===!1?`off`:`caption`;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!n.readOnly&&(0,Z.jsx)(G_,{workspaceId:n.workspaceId,state:r,comments:b,onToggleComments:()=>t({...e,showComments:b===`off`})}),i&&(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-2 py-1`,children:[(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,onClick:()=>{c(!s),o(new Set)},children:s?`Done selecting`:`Select`}),s&&(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,onClick:()=>o(new Set(g.map(e=>e.id))),children:`Select page`}),a.size>0&&(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,onClick:()=>u([...a]),children:[`Bulk Edit… (`,a.size,`)`]})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1`,children:v?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-destructive`,children:v}):g.length===0?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-muted-foreground`,children:_?`Loading media…`:y.length?`No images or videos match your search.`:`No images or videos in this canvas' context.`}):(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(min(120px,100%),1fr))] gap-2 sm:grid-cols-[repeat(auto-fill,minmax(min(200px,100%),1fr))] sm:gap-3`,children:g.map((e,t)=>(0,Z.jsxs)(`div`,{className:`relative`,onContextMenu:t=>{i&&(t.preventDefault(),t.stopPropagation(),f({x:t.clientX,y:t.clientY,ids:a.has(e.id)?[...a]:[e.id]}))},children:[(0,Z.jsx)(U_,{workspaceId:n.workspaceId,doc:e,onClick:()=>s?p(e.id):h(t),comments:b}),s&&(0,Z.jsx)(`input`,{type:`checkbox`,"aria-label":`Select document ${e.id}`,checked:a.has(e.id),onChange:()=>p(e.id),className:`canvas-no-drag absolute left-2 top-2 h-4 w-4 accent-primary`})]},e.id))})}),d&&(0,Z.jsx)(_f,{x:d.x,y:d.y,onClose:()=>f(null),className:`rounded-lg border bg-popover p-1 shadow-elevation-3`,children:(0,Z.jsxs)(`button`,{className:`px-3 py-2 text-sm hover:bg-muted`,onClick:()=>{u(d.ids),f(null)},children:[`Bulk Edit… (`,d.ids.length,`)`]})}),l&&(0,Z.jsx)(Tp,{workspaceId:n.workspaceId,documentIds:l,onClose:()=>u(null)}),m!=null&&g[m]&&(0,Z.jsx)(W_,{workspaceId:n.workspaceId,docs:g,index:m,onClose:()=>h(null),onNavigate:h})]})}sf({type:`gallery`,name:`Gallery`,icon:G,defaultSize:{w:8,h:6,minW:3,minH:3},mobileHeight:.9,defaultConfig:{pageSize:60,showComments:!0},component:q_});var J_=150;function Y_(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)&&t>0?t:0}function X_(e){let t=e.metadata??{},n=e.data??{};return{w:Y_(t.width)||Y_(t.imageWidth)||Y_(n.width)||Y_(n.imageWidth),h:Y_(t.height)||Y_(t.imageHeight)||Y_(n.height)||Y_(n.imageHeight)}}function Z_(e,t){if(t%9==0)return{cols:2,rows:2};let{w:n,h:r}=X_(e),i=n&&r?n/r:0;return i>=1.5?{cols:2,rows:1}:i>0&&i<=.66?{cols:1,rows:2}:!i&&t%7==3?{cols:2,rows:1}:{cols:1,rows:1}}function Q_({config:e,setConfig:t,canvas:n}){let r=H_(n,typeof e.pageSize==`number`?e.pageSize:60),[i,a]=(0,X.useState)(null),{images:o,isLoading:s,error:c,activeQueries:l}=r,u=e.showComments===!1?`off`:`reveal`;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!n.readOnly&&(0,Z.jsx)(G_,{workspaceId:n.workspaceId,state:r,comments:u,onToggleComments:()=>t({...e,showComments:u===`off`})}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1`,children:c?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-destructive`,children:c}):o.length===0?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-muted-foreground`,children:s?`Loading images…`:l.length?`No images match your search.`:`No images in this canvas' context.`}):(0,Z.jsx)(`div`,{className:`grid gap-2`,style:{gridTemplateColumns:`repeat(auto-fill, minmax(${J_}px, 1fr))`,gridAutoRows:`${J_}px`,gridAutoFlow:`dense`},children:o.map((e,t)=>{let{cols:r,rows:i}=Z_(e,t);return(0,Z.jsx)(`div`,{style:{gridColumn:`span ${r}`,gridRow:`span ${i}`},children:(0,Z.jsx)(U_,{workspaceId:n.workspaceId,doc:e,onClick:()=>a(t),className:`h-full`,comments:u})},e.id)})})}),i!=null&&o[i]&&(0,Z.jsx)(W_,{workspaceId:n.workspaceId,docs:o,index:i,onClose:()=>a(null),onNavigate:a})]})}sf({type:`mosaic`,name:`Mosaic`,icon:mt,defaultSize:{w:8,h:7,minW:4,minH:4},mobileHeight:.9,defaultConfig:{pageSize:60,showComments:!0},component:Q_});var $_=`data/schema/task`;function ev({doc:e,workspaceId:t,readOnly:n,onChanged:r}){let i=lh(e),[a,o]=(0,X.useState)(!1),{replicating:s,label:c}=Ji(e),l=i.status===`completed`,u=i.status??`pending`,d=dh(i),{activationProps:f,stopRowActivation:p}=N_(e,t),m=async()=>{if(!(n||a)){o(!0);try{await ph(t,e,l?`pending`:`completed`),r()}catch{}finally{o(!1)}}};return(0,Z.jsxs)(`div`,{...f,title:`Open details`,className:`canvas-no-drag flex cursor-pointer items-start gap-2.5 rounded-md border bg-card px-2.5 py-2 transition-colors hover:bg-accent/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring ${s?`opacity-60`:``}`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{p(e),m()},disabled:n||a||s,"aria-pressed":l,title:l?`Mark not done`:`Mark done`,className:`canvas-no-drag mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border transition-colors ${l?`border-success bg-success text-success-foreground`:`border-input hover:border-success`} ${n?`cursor-default opacity-70`:``}`,children:a?(0,Z.jsx)(Wn,{className:`h-2.5 w-2.5 animate-spin`}):l&&(0,Z.jsx)(ur,{className:`h-3 w-3`})}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm ${l?`text-muted-foreground line-through`:``}`,children:i.title||`Todo ${e.id}`}),(0,Z.jsxs)(`div`,{className:`mt-0.5 flex flex-wrap items-center gap-1.5 text-[11px]`,children:[(0,Z.jsx)(`span`,{className:`rounded-full px-1.5 py-0.5 ${uh[u]}`,children:th[u]}),i.dueDate&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 ${d?`font-medium text-destructive`:`text-muted-foreground`}`,children:[(0,Z.jsx)(Ge,{className:`h-3 w-3`}),fh(i.dueDate)]}),typeof i.priority==`number`&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 text-muted-foreground`,children:[(0,Z.jsx)(ke,{className:`h-3 w-3`}),`P`,i.priority]}),s&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-muted-foreground`,role:`status`,children:[(0,Z.jsx)(Wn,{className:`h-3 w-3 animate-spin`}),c]})]})]})]})}function tv({config:e,setConfig:t,canvas:n}){let r=typeof e.pageSize==`number`?e.pageSize:50,[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(!0),[c,l]=(0,X.useState)(0),u=n.interactive===!1,d=n.readOnly!==!0,[f,p]=(0,X.useState)(e.hideDone===!0),m=d?e.hideDone===!0:f,h=n=>{d?t({...e,hideDone:n}):p(n)};(0,X.useEffect)(()=>{let e=!1;return(async()=>{s(!0);try{let t=await n.fetchDocuments({limit:r,allOf:[$_],sortBy:`tasks`,order:`asc`});if(e)return;a((t.payload||[]).filter(e=>e.schema===io))}catch{e||a([])}finally{e||s(!1)}})(),()=>{e=!0}},[n,r,c]),(0,X.useEffect)(()=>{let e=()=>l(e=>e+1);return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[]);let g=(0,X.useCallback)(()=>l(e=>e+1),[]),_=m?i.filter(e=>lh(e).status!==`completed`):i,v=i.filter(e=>{let t=lh(e).status;return t!==`completed`&&t!==`cancelled`}).length;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center justify-between gap-2 border-b px-1 pb-2`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[v,` open`]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>h(e.target.checked),className:`h-3 w-3`}),`Hide done`]})]}),(0,Z.jsx)(`div`,{className:`flex-1 space-y-1.5 overflow-y-auto p-1`,children:o&&i.length===0?(0,Z.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:`Loading todos…`}):_.length===0?(0,Z.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:`No todos in this canvas' context.`}):_.map(e=>(0,Z.jsx)(ev,{doc:e,workspaceId:n.workspaceId,readOnly:u,onChanged:g},e.id))})]})}sf({type:`todos`,name:`Todos`,icon:zt,defaultSize:{w:4,h:6,minW:3,minH:3},mobileHeight:.6,defaultConfig:{pageSize:50,hideDone:!1},component:tv});function nv(e){if(!e)return`/`;let t=e.replace(/\/+/g,`/`);return t.startsWith(`/`)?t:`/${t}`}var rv=`context`;function iv(e){let t=e=>{try{return decodeURIComponent(e)}catch{return e}},n=e.split(`/`).filter(Boolean);if(n[0]!==`workspaces`)return{treeName:rv,path:`/`};if(n[2]===`trees`&&n[3]){let e=t(n[3]);if(n[4]!==`path`)return{treeName:e,path:`/`};let r=n.slice(5).map(t).join(`/`);return{treeName:e,path:r?`/${r}`:`/`}}if(n[2]===`path`){let e=n.slice(3).map(t).join(`/`);return{treeName:rv,path:e?`/${e}`:`/`}}return{treeName:rv,path:`/`}}function av(e,t,n){let r=n&&n!==rv?`/trees/${encodeURIComponent(n)}`:``,i=nv(t);return`/workspaces/${e}${r}${i===`/`?``:`/path/${i.split(`/`).filter(Boolean).map(encodeURIComponent).join(`/`)}`}`}function ov({canvas:e}){return bo()!=null||!Zu()?(0,Z.jsx)(`p`,{className:`p-3 text-sm text-muted-foreground`,children:`Workspace pins are available in the signed-in workspace view.`}):(0,Z.jsx)(sv,{workspaceId:e.workspaceId},e.workspaceId)}function sv({workspaceId:e}){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(`Workspace`),[a,o]=(0,X.useState)(!0),[s,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(0);return(0,X.useEffect)(()=>{let t=!1,r=0,a=async()=>{let a=++r;o(!0);try{let[o,s]=await Promise.all([vi(e),Va(e)]);if(t||a!==r)return;i(o.label||o.name||`Workspace`),n(s),l(null)}catch{if(t||a!==r)return;n([]),l(`Workspace pins are unavailable. Check your workspace access or try again.`)}finally{!t&&a===r&&o(!1)}},s=()=>{document.visibilityState===`visible`&&a()};a(),window.addEventListener(`focus`,s),document.addEventListener(`visibilitychange`,s);let c=Wu.on(`pins.changed`,s),u=window.setInterval(s,6e4);return()=>{t=!0,window.removeEventListener(`focus`,s),document.removeEventListener(`visibilitychange`,s),c?.(),window.clearInterval(u)}},[e,u]),(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex h-full min-h-0 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-b px-2 pb-2`,children:[(0,Z.jsx)(`span`,{className:`truncate text-sm font-medium`,children:r}),(0,Z.jsx)(`button`,{type:`button`,title:`Refresh pins`,"aria-label":`Refresh pins`,disabled:a,onClick:()=>d(e=>e+1),className:`rounded p-1.5 text-muted-foreground hover:bg-accent disabled:opacity-40`,children:(0,Z.jsx)(M,{className:`h-3.5 w-3.5 ${a?`animate-spin`:``}`})})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-1`,children:s?(0,Z.jsx)(`p`,{role:`alert`,className:`p-2 text-sm text-muted-foreground`,children:s}):t.length?(0,Z.jsx)(`ul`,{className:`space-y-2`,children:t.map(t=>{let n=t.resolvable===!1,r=If(t.color),i=(0,Z.jsxs)(Z.Fragment,{children:[n?(0,Z.jsx)(at,{className:`h-5 w-5 shrink-0 text-warning`}):(0,Z.jsx)(c,{icon:t.icon||(t.type===`canvas`?`ph:squares-four-fill`:`ph:folder-fill`),width:22,height:22,color:r,className:`shrink-0`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`p`,{className:`truncate text-sm font-medium`,children:t.label||t.name||t.path}),(0,Z.jsxs)(`p`,{className:`truncate text-xs text-muted-foreground`,children:[t.tree,`:`,t.path]}),t.description&&(0,Z.jsx)(`p`,{className:`line-clamp-2 text-xs text-muted-foreground`,children:t.description}),n&&(0,Z.jsx)(`p`,{className:`text-xs text-warning`,children:`Folder no longer exists`})]})]}),a=`flex items-center gap-3 rounded-lg border border-l-4 bg-card p-3`,o={borderLeftColor:r||`transparent`};return(0,Z.jsx)(`li`,{children:n?(0,Z.jsx)(`div`,{className:`${a} opacity-60`,style:o,children:i}):(0,Z.jsx)(cu,{to:av(e,t.path,t.tree),title:`Open ${t.tree}:${t.path}`,className:`${a} transition-colors hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,style:o,children:i})},t.id)})}):(0,Z.jsx)(`p`,{className:`p-2 text-sm text-muted-foreground`,children:a?`Loading pins…`:`No workspace pins yet. Pin a folder from the workspace tree menu.`})})]})}sf({type:`workspace-pins`,name:`Workspace pins`,icon:De,defaultSize:{w:4,h:6,minW:3,minH:2},mobileHeight:.6,defaultConfig:{},component:ov});function cv({title:e,icon:t,onRemove:n,fill:r,onToggleFill:i,readOnly:a=!1,stacked:o=!1,children:s}){let[c,l]=(0,X.useState)(!1),u=c?document.getElementById(`content-area`):null,d=(0,Z.jsxs)(`div`,{className:c?u?`absolute inset-0 z-40 flex flex-col bg-background`:`fixed inset-0 z-50 flex flex-col bg-background`:`flex flex-col h-full rounded-lg border bg-background overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`canvas-drag-handle flex items-center gap-2 px-2 py-1 border-b bg-muted/30 select-none ${o?``:`cursor-move`}`,children:[t&&(0,Z.jsx)(t,{className:`w-3.5 h-3.5 text-muted-foreground shrink-0`}),(0,Z.jsx)(`span`,{className:`text-xs font-medium truncate flex-1`,children:e}),!a&&i&&!c&&!o&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(lv,{on:r?.w===!0,onClick:()=>i(`w`),label:`Fill width`,icon:le}),(0,Z.jsx)(lv,{on:r?.h===!0,onClick:()=>i(`h`),label:`Fill height`,icon:En})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>l(e=>!e),className:`canvas-no-drag shrink-0 p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-accent touch-target`,title:c?`Restore`:`Full screen`,children:c?(0,Z.jsx)(ct,{className:`w-3.5 h-3.5`}):(0,Z.jsx)(gn,{className:`w-3.5 h-3.5`})}),!a&&n&&(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`canvas-no-drag shrink-0 p-0.5 rounded text-muted-foreground hover:text-destructive hover:bg-destructive/10 touch-target`,title:`Remove widget`,children:(0,Z.jsx)(je,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 min-h-0 overflow-auto p-2`,children:s})]});return c?(0,pf.createPortal)(d,u??document.body):d}function lv({on:e,onClick:t,label:n,icon:r}){return(0,Z.jsx)(`button`,{type:`button`,onClick:t,"aria-pressed":e,title:e?`${n} (on)`:n,className:`canvas-no-drag shrink-0 p-0.5 rounded touch-target ${e?`bg-primary/15 text-primary hover:bg-primary/25`:`text-muted-foreground hover:text-foreground hover:bg-accent`}`,children:(0,Z.jsx)(r,{className:`w-3.5 h-3.5`})})}var uv=(0,af.WidthProvider)(af.default),dv=12,fv=80,pv=40,mv=[12,12],hv=[8,8],gv={w:!1,h:!1};function _v(e){return Math.max(1,...e.map(e=>e.y+e.h).filter(Number.isFinite))}function vv(e){return Math.max(0,...e.map(e=>e.y+e.h).filter(Number.isFinite))}function yv(e){let t=(e,t)=>typeof e==`number`&&Number.isFinite(e)?e:t;return{...e,x:t(e.x,0),y:t(e.y,0),w:t(e.w,1),h:t(e.h,1)}}function bv(e,t,n=0){let r=n>0?n:_v(e);return e.map(e=>{let n=t[e.i]??gv;return!n.w&&!n.h?e:{...e,x:n.w?0:e.x,w:n.w?dv:e.w,y:n.h?0:e.y,h:n.h?Math.max(e.minH??1,r):e.h}})}var xv=4;function Sv(e,t,n=mv[1]){return Math.max(1,Math.ceil((e-n-xv)/(t+n)))}var Cv=45,wv=640;function Tv(e,t,n=0,r){let i=[...bv(e,t,n)].sort((e,t)=>e.y-t.y||e.x-t.x),a=0;return i.map(e=>{let t=r?.(e.i)??0,n=Math.max(e.h,e.minH??1,t),i={...e,x:0,w:dv,y:a,h:n};return a+=n,i})}var Ev=e=>e&&e.trim()?[e]:[];function Dv(e){let t=e?.ui??{},n=Array.isArray(t.layout)?t.layout.map(yv):[],r={};for(let e of n)r[e.i]={w:e.fillW??e.w>=dv,h:e.fillH===!0};return{layout:n,fills:r,widgets:t.widgets&&typeof t.widgets==`object`?t.widgets:{}}}function Ov({workspaceId:e,treeName:t,path:n,layerId:r,querySpec:i,metadata:a,isLocked:o=!1,readOnly:s=!1,interactive:c=!0,fetchDocuments:l,onSaved:u}){let d=!s,f=(0,X.useMemo)(()=>Dv(a),[a]),[p,m]=(0,X.useState)(f.layout),[h,g]=(0,X.useState)(f.widgets),[_,v]=(0,X.useState)(f.fills),y=(0,X.useRef)(f.fills),[b,x]=(0,X.useState)(!1),[S,C]=(0,X.useState)(!1),[w,T]=(0,X.useState)(!1),[E,D]=(0,X.useState)(null),[O,k]=(0,X.useState)(!1),[A,j]=(0,X.useState)(0),M=(0,X.useRef)(0),N=(0,X.useCallback)(e=>{y.current=e,v(e)},[]),[P,ee]=(0,X.useState)(()=>i?.sort??Kg),F=(0,X.useRef)(!1),[I,te]=(0,X.useState)(()=>Ev(i?.query)),ne=(0,X.useRef)(!1),L=(0,X.useRef)(null),re=(0,X.useRef)(f),R=(0,X.useCallback)(e=>{let t=cf(h[e]?.type??``)?.mobileHeight;if(!(!t||A<=0))return Math.max(1,Math.round(A*t))},[h,A]),ie=(0,X.useMemo)(()=>O?Tv(p,_,A,R):bv(p,_,A),[p,_,O,A,R]),ae=O?pv:fv,oe=(0,X.useMemo)(()=>JSON.stringify(a?.ui??null),[a?.ui]);(0,X.useEffect)(()=>{let e=Dv(a);m(e.layout),g(e.widgets),N(e.fills),re.current=e,ee(i?.sort??Kg),F.current=!1,te(Ev(i?.query)),ne.current=!1,C(!1)},[n,r]),(0,X.useEffect)(()=>{if(!s)return;let e=Dv(a);m(e.layout),g(e.widgets),N(e.fills),re.current=e},[s,oe,a,N]),(0,X.useEffect)(()=>{let e=L.current;if(!e)return;let t=()=>{let t=e.clientHeight,n=e.clientWidth>0&&e.clientWidth<wv;k(n),M.current=t,e.style.setProperty(`--canvas-host-h`,`${t}px`);let r=n?hv:mv;e.style.setProperty(`--canvas-grid-gutter`,`${r[1]}px`),t>0&&j(Sv(t,n?pv:fv,r[1]))};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[p]);let z=(0,X.useCallback)(e=>{ee(e),F.current=!0,C(!0)},[]),se=(0,X.useCallback)(e=>{te(e),ne.current=!0,C(!0)},[]),ce=(0,X.useMemo)(()=>({workspaceId:e,treeName:t,path:n,layerId:r,querySpec:i,readOnly:!d,interactive:c,canvasSort:P,setCanvasSort:d?z:void 0,canvasQueries:I,setCanvasQueries:d?se:void 0,fetchDocuments:l??(async r=>{let i;if(r?.anyOf?.length&&(i=((await gi(e,n,t,{anyOf:r.anyOf,limit:0,applyCanvasSpec:!1})).payload||[]).map(e=>e.id),!i.length))return{payload:[],count:0,totalCount:0};let a=await gi(e,n,t,{...r,anyOf:void 0,ids:i});return{payload:a.payload||[],count:a.count??void 0,totalCount:a.totalCount??void 0}})}),[e,t,n,r,i,d,c,l,P,z,I,se]),B=(0,X.useCallback)((e,t,n)=>{re.current={layout:e,widgets:t,fills:n??y.current},C(!0)},[]),V=(0,X.useCallback)(async()=>{if(!(!d||w)){T(!0),D(null);try{let r={widgets:re.current.widgets,layout:re.current.layout.map(e=>({...e,fillW:y.current[e.i]?.w===!0,fillH:y.current[e.i]?.h===!0}))};re.current={...r,fills:y.current};let o=F.current||ne.current?{...i||{},...F.current?{sort:P.sortBy?P:null}:{},...ne.current?{query:I.join(` `).trim()||null}:{}}:void 0;await xi(e,n,t,{...a||{},ui:r},o),F.current=!1,ne.current=!1,C(!1),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:t}})),u?.()}catch(e){let t=e instanceof Error?e.message:`Save failed`;D(t),console.error(`Failed to save canvas layout:`,e)}finally{T(!1)}}},[d,w,e,n,t,a,u,i,P,I]),le=(0,X.useCallback)(e=>{!d||O||m(t=>{let n=e.map(e=>{let n=t.find(t=>t.i===e.i),r=y.current[e.i];return n?{...e,x:r?.w?n.x:e.x,w:r?.w?n.w:e.w,y:r?.h?n.y:e.y,h:r?.h?n.h:e.h}:e});return B(n,h),n})},[d,O,B,h]),ue=(0,X.useCallback)((e,t,n)=>{if(!d)return;let r=y.current[n.i]??gv,i=mv[1]+(n.y+n.h)*(fv+mv[1]),a={w:n.x+n.w>=dv,h:M.current>0&&i>=M.current-Cv};if(a.w||=r.w&&n.w===t.w,a.h||=r.h&&n.h===t.h,a.w===r.w&&a.h===r.h)return;let o={...y.current,[n.i]:a};N(o),B(re.current.layout,h,o)},[d,N,B,h]),de=(0,X.useCallback)((e,t)=>{if(!d)return;let n=y.current[e]??gv,r={...y.current,[e]:{...n,[t]:!n[t]}};N(r),B(p,h,r)},[d,N,B,p,h]),fe=(0,X.useCallback)(e=>{let t=cf(e);if(!t)return;let n=crypto.randomUUID(),{w:r,h:i,minW:a,minH:o,maxW:s,maxH:c}=t.defaultSize,l=[...p,{i:n,x:0,y:vv(ie),w:r,h:i,minW:a,minH:o,maxW:s,maxH:c}],u={...h,[n]:{type:e,config:{...t.defaultConfig||{}}}},d={...y.current,[n]:{w:r>=dv,h:!1}};m(l),g(u),N(d),x(!1),B(l,u,d)},[p,ie,h,N,B]),pe=(0,X.useCallback)(e=>{let t=p.filter(t=>t.i!==e),n={...h};delete n[e];let r={...y.current};delete r[e],m(t),g(n),N(r),B(t,n,r)},[p,h,N,B]),me=(0,X.useCallback)((e,t)=>{g(n=>{let r={...n,[e]:{...n[e],config:t}};return B(p,r),r})},[p,B]),H=Object.keys(h);return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full min-h-0`,children:[d&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-2 py-1.5 border-b shrink-0 sm:px-3`,children:[(0,Z.jsxs)(`div`,{className:`relative shrink-0`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>x(e=>!e),className:`flex items-center gap-1.5 whitespace-nowrap px-2.5 py-1 text-xs border rounded-md hover:bg-accent`,children:[(0,Z.jsx)(nn,{className:`w-3.5 h-3.5`}),`Add`,(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:` widget`})]}),b&&(0,Z.jsx)(`div`,{className:`absolute left-0 top-full mt-1 z-20 w-48 rounded-md border bg-popover shadow-elevation-2 py-1`,children:lf().map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>fe(e.type),className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs text-left hover:bg-accent`,children:[(0,Z.jsx)(e.icon,{className:`w-3.5 h-3.5 text-muted-foreground`}),e.name]},e.type))})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:V,disabled:!S||w,className:K(`flex shrink-0 items-center gap-1.5 whitespace-nowrap px-2.5 py-1 text-xs rounded-md transition-colors disabled:opacity-50`,S?`bg-primary text-primary-foreground hover:bg-primary`:`border hover:bg-accent`),children:[(0,Z.jsx)(Re,{className:`w-3.5 h-3.5`}),w?`Saving…`:`Save`]}),(0,Z.jsxs)(`span`,{className:`min-w-0 truncate text-xs text-muted-foreground`,children:[H.length,` widget`,H.length===1?``:`s`,S?` · unsaved`:``,E?` · ${E}`:``]})]}),(0,Z.jsx)(`div`,{ref:L,className:`canvas-grid-host flex-1 min-h-0 bg-muted/10 overflow-y-auto overflow-x-hidden`,children:H.length===0?(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(`p`,{children:`No widgets yet.`}),d&&(0,Z.jsx)(`p`,{className:`text-xs`,children:`Use “Add widget” to place one on the canvas.`})]}):(0,Z.jsx)(uv,{className:`layout`,layout:ie,cols:dv,rowHeight:ae,margin:O?hv:mv,isDraggable:d&&!O,isResizable:d&&!O,resizeHandles:[`s`,`e`,`se`],draggableHandle:`.canvas-drag-handle`,draggableCancel:`.canvas-no-drag`,onLayoutChange:le,onResizeStop:ue,compactType:`vertical`,children:H.map(e=>{let t=h[e],n=cf(t.type),r=_[e]??gv,i=[r.w?`w`:``,r.h?`h`:``].filter(Boolean).join(` `);return(0,Z.jsx)(`div`,{"data-fill":i||void 0,children:n?(0,Z.jsx)(cv,{title:n.name,icon:n.icon,readOnly:!d,stacked:O,onRemove:()=>pe(e),fill:_[e]??gv,onToggleFill:d?t=>de(e,t):void 0,children:(0,Z.jsx)(n.component,{config:t.config??{...n.defaultConfig||{}},setConfig:t=>me(e,t),canvas:ce})}):(0,Z.jsx)(cv,{title:`Unknown: ${t.type}`,readOnly:!d,stacked:O,onRemove:()=>pe(e),children:(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`This widget type is not available.`})})},e)})})})]})}var kv=`data/schema/file`;function Av(e){return String(e.locations?.[0]?.url||``).trim()}function jv(e){let t=Av(e);if(!t)return``;let n=t.split(/[?#]/)[0].split(`/`).filter(Boolean).pop()||``;try{return decodeURIComponent(n)}catch{return n}}function Mv(e){return e.schema===kv&&String(e.metadata?.contentType||``).startsWith(`image/`)}function Nv(e){let t=Number(e);return!Number.isFinite(t)||t<0?``:t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}function Pv(e){if(e.schema!==kv)return mo(e);let t=jv(e),n=String(e.metadata?.contentType||``).trim(),r=Nv(e.metadata?.size);return{...mo(e),title:t||`File ${e.id}`,preview:[n,r].filter(Boolean).join(` · `),subtitle:Av(e),schemaLabel:`file`}}function Fv(e){return/^https?:\/\/[^\s]+$/i.test(e)}function Iv(e,t){if(e.schema===`data/schema/tab`){let t=String(e.data?.url||``).trim();return Fv(t)?t:null}return t.isExternal&&Fv(t.subtitle)?t.subtitle:Fv(t.title)?t.title:null}function Lv(e,t,n=!1){return uo(e,t,{download:n})}function Rv(e){return e.split(/(https?:\/\/[^\s]+)/gi).map((e,t)=>Fv(e)?(0,Z.jsx)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`underline decoration-muted-foreground underline-offset-2 hover:text-primary`,children:e},`${e}-${t}`):e)}function zv(e){return e?new Date(e).toLocaleString():``}function Bv(){let{code:e=``}=Yc(),[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(``),d=(0,X.useMemo)(()=>t?.documents?Array.isArray(t.documents)?t.documents:t.documents.data||[]:[],[t]),f=(0,X.useMemo)(()=>{let e=l.trim().toLowerCase();return e?d.filter(t=>{let n=Pv(t);return[t.schema,n.title,n.preview,n.subtitle,jv(t),t.metadata?.contentType].join(` `).toLowerCase().includes(e)}):d},[d,l]),p=(0,X.useCallback)(async()=>{if(e){i(!0);try{let t=await Y.get(`${Yr}/pub/c/${encodeURIComponent(e)}`,{skipAuth:!0});n(t),o(null)}catch(e){n(null),o(e instanceof Error?e.message:`Failed to load public canvas`)}finally{i(!1)}}},[e]);(0,X.useEffect)(()=>{p()},[p]),(0,X.useEffect)(()=>{if(!e)return;let t=qa(`${ti}/pub`,{transports:[`websocket`],auth:{code:e},reconnection:!0,reconnectionAttempts:10,reconnectionDelay:1500});return t.on(`connect`,()=>c(!0)),t.on(`disconnect`,()=>c(!1)),t.on(`connect_error`,()=>c(!1)),t.on(`canvas:changed`,()=>p()),()=>{t?.disconnect(),t=null}},[e,p]);let m=(0,X.useCallback)(e=>{e?.preventDefault(),u(l.trim())},[l]),h=(0,X.useCallback)(()=>{u(``)},[]),g=(0,X.useCallback)(async()=>({payload:d,totalCount:t?.stats.documentCount??d.length}),[d,t]);if(r&&!t)return(0,Z.jsx)(`main`,{className:`min-h-screen bg-muted flex items-center justify-center p-6`,children:(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Loading canvas...`})});if(a||!t)return(0,Z.jsxs)(`main`,{className:`min-h-screen bg-muted flex flex-col items-center justify-center p-6`,children:[(0,Z.jsxs)(xu,{className:`max-w-md bg-card`,children:[(0,Z.jsx)(Su,{children:(0,Z.jsx)(Cu,{children:`Canvas unavailable`})}),(0,Z.jsx)(Tu,{className:`text-sm text-muted-foreground`,children:a||`This public canvas does not exist.`})]}),(0,Z.jsx)(Vu,{className:`mt-6 text-center`})]});let _=t.canvas.metadata?.ui??{},v=!!_.widgets&&Object.keys(_.widgets).length>0;return(0,Z.jsx)(wo.Provider,{value:e,children:(0,Z.jsx)(`main`,{className:`min-h-screen bg-muted p-2 text-foreground sm:p-4 md:p-10`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-6xl`,children:[(0,Z.jsxs)(xu,{className:`bg-card shadow-elevation-3`,children:[(0,Z.jsx)(Su,{className:`border-b p-3 sm:p-6`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 md:flex-row md:items-start md:justify-between md:gap-4`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 gap-3 sm:gap-4`,children:[(0,Z.jsx)(`div`,{className:`mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-accent text-primary sm:mt-1 sm:h-12 sm:w-12 sm:rounded-2xl`,style:t.canvas.color?{borderLeft:`4px solid ${t.canvas.color}`}:void 0,children:(0,Z.jsx)(mt,{className:`h-5 w-5 sm:h-6 sm:w-6`})}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`truncate text-xs uppercase tracking-wide text-muted-foreground`,children:t.workspace.label||t.workspace.name}),(0,Z.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] text-muted-foreground md:hidden`,children:[s?(0,Z.jsx)(S,{className:`h-3 w-3 text-success`}):(0,Z.jsx)(qe,{className:`h-3 w-3 text-muted-foreground`}),s?`Live`:`Offline`]})]}),(0,Z.jsx)(Cu,{className:`mt-0.5 truncate text-2xl sm:mt-1 sm:text-3xl md:text-5xl`,children:t.canvas.label||t.canvas.name||`Canvas`}),t.canvas.description&&(0,Z.jsx)(`p`,{className:`mt-1.5 max-w-3xl text-sm text-muted-foreground sm:mt-3 sm:text-base`,children:t.canvas.description})]})]}),(0,Z.jsxs)(`div`,{className:`hidden shrink-0 items-center gap-2 rounded-full border px-3 py-1 text-xs text-muted-foreground md:flex`,children:[s?(0,Z.jsx)(S,{className:`h-3.5 w-3.5 text-success`}):(0,Z.jsx)(qe,{className:`h-3.5 w-3.5 text-muted-foreground`}),s?`Live`:`Offline`]})]})}),(0,Z.jsxs)(Tu,{className:`space-y-4 p-3 sm:space-y-6 sm:p-6 md:p-8`,children:[(0,Z.jsxs)(`section`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-xs text-muted-foreground md:hidden`,children:[(0,Z.jsx)(`span`,{className:`w-full truncate font-mono text-foreground`,children:t.share.path}),(0,Z.jsxs)(`span`,{className:`tabular-nums`,children:[t.stats.documentCount,` docs`]}),f.length!==t.stats.documentCount&&(0,Z.jsxs)(`span`,{className:`tabular-nums`,children:[`· `,f.length,` shown`]}),(0,Z.jsxs)(`span`,{className:`truncate`,children:[`· `,zv(t.stats.refreshedAt)]})]}),(0,Z.jsxs)(`section`,{className:`hidden gap-3 md:grid md:grid-cols-4`,children:[(0,Z.jsx)(Vv,{label:`Path`,value:t.share.path,mono:!0}),(0,Z.jsx)(Vv,{label:`Documents`,value:String(t.stats.documentCount)}),(0,Z.jsx)(Vv,{label:`Shown`,value:String(f.length)}),(0,Z.jsx)(Vv,{label:`Refreshed`,value:zv(t.stats.refreshedAt)})]}),v&&(0,Z.jsx)(`section`,{id:`content-area`,className:`flex w-full flex-col overflow-hidden rounded-2xl border h-viewport-card min-h-[420px] md:h-viewport-pane`,children:(0,Z.jsx)(Ov,{workspaceId:t.workspace.name,treeName:t.share.treeName,path:t.share.path,layerId:t.canvas.id,querySpec:t.canvas.querySpec,metadata:t.canvas.metadata,readOnly:!0,interactive:!1,fetchDocuments:g},JSON.stringify(_))}),!v&&(0,Z.jsxs)(`section`,{className:`rounded-2xl border`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 border-b px-4 py-3 md:flex-row md:items-center md:justify-between`,children:[(0,Z.jsx)(`h2`,{className:`font-semibold`,children:`Content`}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 md:flex-row md:items-center`,children:[(0,Z.jsxs)(`form`,{onSubmit:m,className:`flex min-w-0 items-center gap-2`,children:[(0,Z.jsxs)(`div`,{className:`relative min-w-0`,children:[(0,Z.jsx)(Xn,{className:`pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{type:`search`,value:l,onChange:e=>u(e.target.value),placeholder:`Search loaded documents...`,className:`w-full rounded-md border py-1.5 pl-9 pr-8 text-sm md:w-72`}),l&&(0,Z.jsx)(`button`,{type:`button`,onClick:h,className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,"aria-label":`Clear search`,children:(0,Z.jsx)(je,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`button`,{type:`submit`,className:`rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:`Search`})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:p,className:`inline-flex items-center justify-center gap-2 rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:[(0,Z.jsx)(M,{className:`h-3.5 w-3.5 ${r?`animate-spin`:``}`}),`Refresh`]})]})]}),l.trim()&&(0,Z.jsxs)(`div`,{className:`border-b bg-muted px-4 py-2 text-xs text-muted-foreground`,children:[`Local search: `,(0,Z.jsxs)(`span`,{className:`font-mono`,children:[`"`,l.trim(),`"`]})]}),(0,Z.jsx)(`div`,{className:`divide-y`,children:f.length===0?(0,Z.jsx)(`div`,{className:`p-8 text-center text-sm text-muted-foreground`,children:l.trim()?`No loaded documents match your search.`:`No documents yet.`}):f.map(t=>{let n=Pv(t),r=Iv(t,n),i=t.schema===kv,a=i?Lv(e,t.id):null,o=a||r;return(0,Z.jsxs)(`article`,{className:`p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1 md:flex-row md:items-start md:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h3`,{className:`truncate font-medium`,children:o?(0,Z.jsx)(`a`,{href:o,target:`_blank`,rel:`noreferrer`,className:`hover:text-primary hover:underline`,children:n.title}):n.title}),(0,Z.jsx)(`div`,{className:`mt-1 font-mono text-xs text-muted-foreground`,children:n.schemaLabel})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3`,children:[i&&(0,Z.jsxs)(`a`,{href:Lv(e,t.id,!0),download:n.title,className:`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground`,children:[(0,Z.jsx)(wn,{className:`h-3.5 w-3.5`}),`Download`]}),(0,Z.jsx)(`time`,{className:`text-xs text-muted-foreground`,children:zv(t.updatedAt||t.createdAt)})]})]}),n.preview&&(0,Z.jsx)(`p`,{className:`mt-3 line-clamp-3 text-sm leading-6 text-foreground`,children:Rv(n.preview)}),Mv(t)&&(0,Z.jsx)(`a`,{href:a||void 0,target:`_blank`,rel:`noreferrer`,className:`mt-3 block w-fit`,children:(0,Z.jsx)(`img`,{src:a||void 0,alt:n.title,loading:`lazy`,className:`max-h-64 max-w-full rounded border bg-muted object-contain transition-opacity hover:opacity-90`})})]},t.id)})})]})]})]}),(0,Z.jsx)(Vu,{className:`mt-6 text-center`})]})})})}function Vv({label:e,value:t,mono:n=!1}){return(0,Z.jsxs)(`div`,{className:`min-w-0 rounded-xl border bg-muted p-4`,children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:e}),(0,Z.jsx)(`div`,{className:`mt-2 truncate text-lg font-semibold ${n?`font-mono text-sm`:``}`,children:t||`-`})]})}var Hv=(0,X.createContext)(void 0);function Uv(){let e=(0,X.useContext)(Hv),t=Ao()?.state,n=!!t,r=t?.activeContextType,i=t?.activeContextId,a=t?.activeWorkspaceName,o=t?.activeContextPath,s=t?.activeTreeName;return(0,X.useMemo)(()=>e===void 0?n?r===`context`&&i?{mode:`context`,contextId:i}:a&&o?{mode:`workspace`,workspaceName:a,path:o,treeName:s||`context`,treeType:s===`directory`||s===`backends`?`directory`:`context`}:null:null:e,[e,n,r,i,a,o,s])}function Wv({value:e,onChange:t,onBlur:n,placeholder:r,innerRef:i}){let a=(0,X.useRef)(null),o=(0,X.useCallback)(()=>{let e=a.current;e&&(e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)},[]);return(0,X.useEffect)(()=>{o()},[e,o]),(0,Z.jsx)(`textarea`,{ref:e=>{a.current=e,i?.(e)},value:e,onChange:e=>t(e.target.value),onBlur:n,placeholder:r,rows:1,spellCheck:!1,className:`w-full resize-none overflow-hidden border-0 bg-transparent p-0 text-sm leading-relaxed text-foreground outline-none placeholder:text-muted-foreground/60`})}function Gv({onLinkTo:e,onDelete:t}){return(0,Z.jsxs)(`span`,{className:`reveal-on-hover flex items-center gap-0.5`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:e,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Link to…`,title:`Link to…`,children:(0,Z.jsx)(qt,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:t,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-destructive`,"aria-label":`Delete`,title:`Delete (moves to trash)`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})}function Kv({documentId:e,workspaceName:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=Ya(),[a,o]=(0,X.useState)(!1);return(0,Z.jsx)(sp,{onClose:n,children:(0,Z.jsx)(ap,{onClose:n,onConfirm:async(t,a)=>{if(t.length){o(!0);try{for(let n of t)await qr(a.workspaceName,n,[e],a.treeName,a.treeType);r(`Linked to ${t.length} path${t.length>1?`s`:``}`),n()}catch(e){i(e instanceof Error?e.message:`Failed to link document`),o(!1)}}},documentCount:1,saving:a,sizeClassName:op,tabs:t?[`context`,`directory`,`relations`]:[`context`,`directory`],relationWorkspaceName:t,relationExcludeIds:new Set([e]),onConfirmRelation:async({predicate:a,direction:s,targetIds:c})=>{if(!(!t||!c.length)){o(!0);try{await Wi(t,e,a,c,s),r(`Related to ${c.length} document${c.length===1?``:`s`}`),Kp(),n()}catch(e){i(e instanceof Error?e.message:`Failed to create relation`),o(!1)}}}})})}var qv=1200;function Jv(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleDateString(void 0,{year:`numeric`,month:`short`,day:`numeric`})+` `+t.toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`})}function Yv(e,t){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(!1),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(null),u=(0,X.useCallback)(()=>{if(!e)return Promise.resolve();if(e.mode===`context`){let{contextId:n}=e;return Promise.all([Qo(n,[t]),$o(n)]).then(([e,t])=>{r(Array.isArray(e)?e:[]);let n=t.workspaceName||t.workspaceId;l(n?{workspaceName:n,path:t.path||`/`,treeName:t.treeId||`context`,treeType:`context`}:null)}).catch(e=>s(e instanceof Error?e.message:`Failed to load documents`)).finally(()=>a(!1))}let{workspaceName:n,path:i,treeName:o,treeType:c}=e;return Bi(n,i,[t],{treeName:o,treeType:c,limit:50}).then(e=>{r(e.payload||[]),l({workspaceName:n,path:i,treeName:o,treeType:c})}).catch(e=>s(e instanceof Error?e.message:`Failed to load documents`)).finally(()=>a(!1))},[e,t]),d=(0,X.useCallback)(async()=>{if(!e){r([]),l(null);return}a(!0),s(null),await u()},[e,u]),[f,p]=(0,X.useState)(null);return(!f||f.target!==e||f.schema!==t)&&(p({target:e,schema:t}),e?(a(!0),s(null)):(r([]),l(null))),(0,X.useEffect)(()=>{u()},[u]),(0,X.useEffect)(()=>{let e=()=>d();return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[d]),{docs:n,setDocs:r,loading:i,error:o,scope:c,reload:d,removeDoc:(0,X.useCallback)(async e=>{if(!c)throw Error(`No workspace scope resolved`);await Ia(c.workspaceName,[e],c.path,[],c.treeName,c.treeType),r(t=>t.filter(t=>t.id!==e))},[c])}}var Xv=`2.0`;function Zv({doc:e,updateWorkspace:t,registerEl:n,registerBody:r,highlighted:i,onLinkTo:a,onDelete:o}){let[s,c]=(0,X.useState)(String(e.data?.title??``)),[l,u]=(0,X.useState)(String(e.data?.content??``)),[d,f]=(0,X.useState)(`idle`),p=(0,X.useRef)({title:String(e.data?.title??``),content:String(e.data?.content??``)}),m=(0,X.useRef)(null),h=(0,X.useRef)(0),g=(0,X.useCallback)(async(n,r)=>{if(!t||n===p.current.title&&r===p.current.content||!r.trim())return;let i=++h.current;f(`saving`);try{if(await Li(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:{...e.data||{},...n.trim()?{title:n.trim()}:{title:void 0},content:r},metadata:e.metadata}),i!==h.current)return;p.current={title:n,content:r},f(`saved`),setTimeout(()=>f(e=>e===`saved`?`idle`:e),1500)}catch{i===h.current&&f(`error`)}},[e.id,e.schema,e.schemaVersion,e.data,e.metadata,t]),_=(0,X.useCallback)((e,t)=>{f(`dirty`),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>g(e,t),qv)},[g]),v=(0,X.useCallback)(()=>{m.current&&=(clearTimeout(m.current),null),g(s,l)},[g,s,l]);return(0,X.useEffect)(()=>()=>{m.current&&clearTimeout(m.current)},[]),(0,Z.jsxs)(`div`,{ref:t=>n(e.id,t),className:K(`group border-t border-border/60 px-4 py-3 transition-colors`,i&&`bg-primary/5`),children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:[Jv(e.createdAt),` · #`,e.id]}),(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground/70`,children:[d===`saving`&&(0,Z.jsx)(Wn,{className:`inline h-3 w-3 animate-spin`}),d===`saved`&&(0,Z.jsx)(ur,{className:`inline h-3 w-3 text-success`}),d===`dirty`&&`·`,d===`error`&&(0,Z.jsx)(`span`,{className:`text-destructive`,children:`save failed`}),(0,Z.jsx)(Gv,{onLinkTo:a,onDelete:o})]})]}),(0,Z.jsx)(`input`,{value:s,onChange:e=>{c(e.target.value),_(e.target.value,l)},onBlur:v,placeholder:`Untitled`,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,Z.jsx)(Wv,{value:l,onChange:e=>{u(e),_(s,e)},onBlur:v,innerRef:t=>r(e.id,t)})]})}function Qv({target:e,onCreated:t,onCancel:n}){let[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null);return(0,Z.jsxs)(`div`,{className:`border-t border-border/60 bg-muted/30 px-4 py-3`,children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between`,children:[(0,Z.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:`New note`}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground hover:text-foreground`,"aria-label":`Discard draft`,children:(0,Z.jsx)(je,{className:`h-3 w-3`})})]}),(0,Z.jsx)(`input`,{value:r,onChange:e=>i(e.target.value),placeholder:`Untitled`,autoFocus:!0,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,Z.jsx)(Wv,{value:a,onChange:o,placeholder:`Write your note…`}),l&&(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-destructive`,children:l}),(0,Z.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,Z.jsx)(`button`,{type:`button`,onClick:async()=>{if(!(!a.trim()||!e||s)){c(!0),u(null);try{await Yo(e,[{schema:Xa,schemaVersion:Xv,data:{...r.trim()?{title:r.trim()}:{},content:a},metadata:{features:[]}}]),t()}catch(e){u(e instanceof Error?e.message:`Failed to create note`),c(!1)}}},disabled:!a.trim()||s,className:`rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground disabled:opacity-50`,children:s?`Saving…`:`Save note`})})]})}function $v({autoAdd:e=!1}){let t=Uv(),{docs:n,loading:r,error:i,scope:a,reload:o,removeDoc:s}=Yv(t,Xa),[c,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(0),[f,p]=(0,X.useState)(`desc`),[m,h]=(0,X.useState)(e),[g,_]=(0,X.useState)(null),v=(0,X.useRef)(new Map),y=(0,X.useRef)(new Map),b=(0,X.useCallback)((e,t)=>{t?v.current.set(e,t):v.current.delete(e)},[]),x=(0,X.useCallback)((e,t)=>{t?y.current.set(e,t):y.current.delete(e)},[]),S=(0,X.useCallback)(async e=>{let t=e.data?.title?`"${e.data.title}"`:`#${e.id}`;if(window.confirm(`Delete note ${t}?\n\nIt is removed from this path and moves to the workspace trash if nothing else links it.`))try{await s(e.id)}catch{}},[s]),C=(0,X.useMemo)(()=>{let e=[...n];return e.sort((e,t)=>{let n=new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime();return f===`asc`?n:-n}),e},[n,f]),w=(0,X.useMemo)(()=>{let e=c.trim().toLowerCase();if(!e)return[];let t=[];for(let n of C){let r=String(n.data?.content??``),i=String(n.data?.title??``),a=r.toLowerCase().indexOf(e);a>=0?t.push({docId:n.id,offset:a}):i.toLowerCase().includes(e)&&t.push({docId:n.id,offset:-1})}return t},[c,C]),T=w.length?w[Math.min(u,w.length-1)]:null;(0,X.useEffect)(()=>{T&&v.current.get(T.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[T]);let E=(0,X.useCallback)(e=>{if(!w.length)return;let t=e?(u+1)%w.length:u;e&&d(t);let n=w[t],r=y.current.get(n.docId);r&&n.offset>=0&&(r.focus(),r.setSelectionRange(n.offset,n.offset+c.trim().length)),v.current.get(n.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[w,u,c]);return t?(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`relative flex-1`,children:[(0,Z.jsx)(Xn,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{value:c,onChange:e=>{l(e.target.value),d(0)},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),E(!0))},placeholder:`Search notes…`,spellCheck:!1,className:`w-full rounded-md border border-input bg-transparent py-1 pl-7 pr-14 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring`}),c.trim()&&(0,Z.jsx)(`span`,{className:`absolute right-2 top-1/2 -translate-y-1/2 text-[10px] tabular-nums text-muted-foreground`,children:w.length?`${Math.min(u+1,w.length)}/${w.length}`:`0/0`})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(e=>e===`desc`?`asc`:`desc`),className:`rounded-md border border-border p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:f===`desc`?`Newest first (click for oldest first)`:`Oldest first (click for newest first)`,"aria-label":`Toggle sort order`,children:f===`desc`?(0,Z.jsx)(sn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(An,{className:`h-3.5 w-3.5`})}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>h(!0),className:`flex items-center gap-1 rounded-md bg-primary px-2 py-1.5 text-xs text-primary-foreground`,title:`Add a note`,children:[(0,Z.jsx)(nn,{className:`h-3.5 w-3.5`}),`Note`]})]}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:[m&&(0,Z.jsx)(Qv,{target:t,onCreated:()=>{h(!1),o()},onCancel:()=>h(!1)}),r&&!n.length&&(0,Z.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,Z.jsx)(Wn,{className:`h-5 w-5 animate-spin text-muted-foreground`})}),i&&(0,Z.jsx)(`p`,{className:`px-4 py-6 text-center text-sm text-destructive`,children:i}),!r&&!i&&!C.length&&!m&&(0,Z.jsx)(`p`,{className:`px-4 py-10 text-center text-sm text-muted-foreground`,children:`No notes here yet - add the first one.`}),C.map(e=>(0,Z.jsx)(Zv,{doc:e,updateWorkspace:a?.workspaceName??null,registerEl:b,registerBody:x,highlighted:T?.docId===e.id,onLinkTo:()=>_(e.id),onDelete:()=>S(e)},e.id))]}),g!==null&&(0,Z.jsx)(Kv,{documentId:g,workspaceName:a?.workspaceName,onClose:()=>_(null)})]}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:ss(t)})}var ey=`2.1`,ty=new Set([`completed`,`cancelled`]);function ny({doc:e,updateWorkspace:t,registerEl:n,registerBody:r,highlighted:i,onLinkTo:a,onDelete:o,onStatusSaved:s}){let[c,l]=(0,X.useState)(String(e.data?.title??``)),[u,d]=(0,X.useState)(String(e.data?.description??``)),[f,p]=(0,X.useState)(e.data?.status||`pending`),[m,h]=(0,X.useState)(ih(e.data?.dueDate)),[g,_]=(0,X.useState)(`idle`),{replicating:v,label:y}=Ji(e),x=(0,X.useRef)({title:String(e.data?.title??``),description:String(e.data?.description??``)}),S=(0,X.useRef)(null),C=(0,X.useRef)(0),w=(0,X.useCallback)(async n=>{if(!t||!n.title.trim())return!1;let r=++C.current;_(`saving`);try{let i=ah(n.due),a={...e.data||{},title:n.title.trim(),...n.description.trim()?{description:n.description.trim()}:{description:void 0},status:n.status,completed:n.status===`completed`};return i?a.dueDate=i:delete a.dueDate,await Li(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:a,metadata:e.metadata}),r!==C.current||(x.current={title:n.title,description:n.description},_(`saved`),setTimeout(()=>_(e=>e===`saved`?`idle`:e),1500),!0)}catch{return r===C.current&&_(`error`),!1}},[e.id,e.schema,e.schemaVersion,e.data,e.metadata,t]),T=(0,X.useCallback)((e,t)=>{(e!==x.current.title||t!==x.current.description)&&(_(`dirty`),S.current&&clearTimeout(S.current),S.current=setTimeout(()=>w({title:e,description:t,status:f,due:m}),qv))},[w,f,m]),E=(0,X.useCallback)(()=>{S.current&&=(clearTimeout(S.current),null),w({title:c,description:u,status:f,due:m})},[w,c,u,f,m]);(0,X.useEffect)(()=>()=>{S.current&&clearTimeout(S.current)},[]);let D=(0,X.useCallback)(async()=>{let t=f,n=f===`completed`?`pending`:`completed`;p(n),await w({title:c,description:u,status:n,due:m})?s(e.id,n):p(t)},[f,w,c,u,m,e.id,s]),O=(0,X.useCallback)(e=>{h(e),S.current&&=(clearTimeout(S.current),null),w({title:c,description:u,status:f,due:e})},[w,c,u,f]),k=ty.has(f);return(0,Z.jsxs)(`div`,{ref:t=>n(e.id,t),className:K(`group border-t border-border/60 px-4 py-3 transition-colors`,i&&`bg-primary/5`),children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5 text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:[(0,Z.jsxs)(`span`,{className:`shrink-0`,children:[Jv(e.createdAt),` · #`,e.id,f!==`pending`&&(0,Z.jsxs)(`span`,{children:[` · `,th[f]??f]})]}),(0,Z.jsx)(Uh,{value:m,onChange:O,compact:!0,placeholder:`No due date`,className:`w-[168px] shrink-0 normal-case tracking-normal`})]}),(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground/70`,children:[g===`saving`&&(0,Z.jsx)(Wn,{className:`inline h-3 w-3 animate-spin`}),v&&(0,Z.jsx)(`span`,{className:`whitespace-nowrap`,children:y}),g===`saved`&&(0,Z.jsx)(ur,{className:`inline h-3 w-3 text-success`}),g===`dirty`&&`·`,g===`error`&&(0,Z.jsx)(`span`,{className:`text-destructive`,children:`save failed`}),(0,Z.jsx)(Gv,{onLinkTo:a,onDelete:o})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:D,className:`mt-0.5 shrink-0 text-muted-foreground transition-colors hover:text-foreground`,"aria-label":k?`Mark as pending`:`Mark as completed`,title:k?`Mark as pending`:`Mark as completed`,children:k?(0,Z.jsx)(b,{className:`h-4 w-4 text-success`}):(0,Z.jsx)(P,{className:`h-4 w-4`})}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`input`,{value:c,onChange:e=>{l(e.target.value),T(e.target.value,u)},onBlur:E,placeholder:`Untitled`,spellCheck:!1,className:K(`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold outline-none placeholder:text-muted-foreground/50`,k?`text-muted-foreground line-through`:`text-foreground`)}),(0,Z.jsx)(Wv,{value:u,onChange:e=>{d(e),T(c,e)},onBlur:E,placeholder:`Description…`,innerRef:t=>r(e.id,t)})]})]})]})}function ry({target:e,onCreated:t,onCancel:n}){let[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(oh()),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(null);return(0,Z.jsxs)(`div`,{className:`border-t border-border/60 bg-muted/30 px-4 py-3`,children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between`,children:[(0,Z.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:`New todo`}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground hover:text-foreground`,"aria-label":`Discard draft`,children:(0,Z.jsx)(je,{className:`h-3 w-3`})})]}),(0,Z.jsx)(`input`,{value:r,onChange:e=>i(e.target.value),placeholder:`What needs doing?`,autoFocus:!0,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,Z.jsx)(Wv,{value:a,onChange:o,placeholder:`Description (optional)…`}),(0,Z.jsx)(`div`,{className:`mt-2`,children:(0,Z.jsx)(Uh,{value:s,onChange:c,compact:!0,placeholder:`No due date`,className:`w-[188px]`})}),d&&(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-destructive`,children:d}),(0,Z.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,Z.jsx)(`button`,{type:`button`,onClick:async()=>{if(!(!r.trim()||!e||l)){u(!0),f(null);try{await Yo(e,[{schema:io,schemaVersion:ey,data:sh({title:r,description:a,status:`pending`,priority:``,due:s}),metadata:{features:[]}}]),t()}catch(e){f(e instanceof Error?e.message:`Failed to create todo`),u(!1)}}},disabled:!r.trim()||l,className:`rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground disabled:opacity-50`,children:l?`Saving…`:`Save todo`})})]})}function iy({autoAdd:e=!1}){let t=Uv(),{docs:n,setDocs:r,loading:i,error:a,scope:o,reload:s,removeDoc:c}=Yv(t,io),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(0),[p,m]=(0,X.useState)(`desc`),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(e),[y,b]=(0,X.useState)(null),x=(0,X.useRef)(new Map),S=(0,X.useRef)(new Map),C=(0,X.useCallback)((e,t)=>{t?x.current.set(e,t):x.current.delete(e)},[]),w=(0,X.useCallback)((e,t)=>{t?S.current.set(e,t):S.current.delete(e)},[]),T=(0,X.useCallback)(async e=>{let t=e.data?.title?`"${e.data.title}"`:`#${e.id}`;if(window.confirm(`Delete todo ${t}?\n\nIt is removed from this path and moves to the workspace trash if nothing else links it.`))try{await c(e.id)}catch{}},[c]),E=(0,X.useCallback)((e,t)=>{r(n=>n.map(n=>n.id===e?{...n,data:{...n.data||{},status:t,completed:t===`completed`}}:n))},[r]),D=(0,X.useMemo)(()=>{let e=h?[...n]:n.filter(e=>!ty.has(String(e.data?.status??`pending`)));return e.sort((e,t)=>{let n=new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime();return p===`asc`?n:-n}),e},[n,p,h]),O=(0,X.useMemo)(()=>n.filter(e=>ty.has(String(e.data?.status??`pending`))).length,[n]),k=(0,X.useMemo)(()=>{let e=l.trim().toLowerCase();if(!e)return[];let t=[];for(let n of D){let r=String(n.data?.description??``),i=String(n.data?.title??``),a=r.toLowerCase().indexOf(e);a>=0?t.push({docId:n.id,offset:a}):i.toLowerCase().includes(e)&&t.push({docId:n.id,offset:-1})}return t},[l,D]),A=k.length?k[Math.min(d,k.length-1)]:null;(0,X.useEffect)(()=>{A&&x.current.get(A.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[A]);let j=(0,X.useCallback)(e=>{if(!k.length)return;let t=e?(d+1)%k.length:d;e&&f(t);let n=k[t],r=S.current.get(n.docId);r&&n.offset>=0&&(r.focus(),r.setSelectionRange(n.offset,n.offset+l.trim().length)),x.current.get(n.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[k,d,l]);return t?(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`relative flex-1`,children:[(0,Z.jsx)(Xn,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{value:l,onChange:e=>{u(e.target.value),f(0)},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),j(!0))},placeholder:`Search todos…`,spellCheck:!1,className:`w-full rounded-md border border-input bg-transparent py-1 pl-7 pr-14 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring`}),l.trim()&&(0,Z.jsx)(`span`,{className:`absolute right-2 top-1/2 -translate-y-1/2 text-[10px] tabular-nums text-muted-foreground`,children:k.length?`${Math.min(d+1,k.length)}/${k.length}`:`0/0`})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>g(e=>!e),className:K(`rounded-md border p-1.5 transition-colors`,h?`border-foreground text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:h?`Hide done items`:`Show done items${O?` (${O})`:``}`,"aria-label":h?`Hide done items`:`Show done items`,children:h?(0,Z.jsx)(Dt,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(ln,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>m(e=>e===`desc`?`asc`:`desc`),className:`rounded-md border border-border p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:p===`desc`?`Newest first (click for oldest first)`:`Oldest first (click for newest first)`,"aria-label":`Toggle sort order`,children:p===`desc`?(0,Z.jsx)(sn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(An,{className:`h-3.5 w-3.5`})}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>v(!0),className:`flex items-center gap-1 rounded-md bg-primary px-2 py-1.5 text-xs text-primary-foreground`,title:`Add a todo`,children:[(0,Z.jsx)(nn,{className:`h-3.5 w-3.5`}),`Todo`]})]}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:[_&&(0,Z.jsx)(ry,{target:t,onCreated:()=>{v(!1),s()},onCancel:()=>v(!1)}),i&&!n.length&&(0,Z.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,Z.jsx)(Wn,{className:`h-5 w-5 animate-spin text-muted-foreground`})}),a&&(0,Z.jsx)(`p`,{className:`px-4 py-6 text-center text-sm text-destructive`,children:a}),!i&&!a&&!D.length&&!_&&(0,Z.jsx)(`p`,{className:`px-4 py-10 text-center text-sm text-muted-foreground`,children:O?`Nothing pending - ${O} done item${O>1?`s`:``} hidden.`:`No todos here yet - add the first one.`}),D.map(e=>(0,Z.jsx)(ny,{doc:e,updateWorkspace:o?.workspaceName??null,registerEl:C,registerBody:w,highlighted:A?.docId===e.id,onLinkTo:()=>b(e.id),onDelete:()=>T(e),onStatusSaved:E},e.id))]}),y!==null&&(0,Z.jsx)(Kv,{documentId:y,workspaceName:o?.workspaceName,onClose:()=>b(null)})]}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:ss(t)})}var ay=(0,X.createContext)(null);function oy(){let e=(0,X.useContext)(ay);if(!e)throw Error(`useLensFeed must be used within a LensFeedProvider`);return e}function sy(e=!0){let{registerViewer:t}=oy();(0,X.useEffect)(()=>{if(e)return t()},[e,t])}function cy(e={}){let t=(0,X.useRef)(null),n=(0,X.useRef)(e.onEnded);(0,X.useEffect)(()=>{n.current=e.onEnded});let r=(0,X.useRef)(null),i=(0,X.useRef)(null),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),d=(0,X.useCallback)(()=>{r.current?.getTracks().forEach(e=>e.stop()),r.current=null,t.current&&(t.current.srcObject=null),c(null),o(!1)},[]),f=(0,X.useCallback)(async e=>{r.current=e,e.getVideoTracks().forEach(e=>{e.onended=()=>{d(),n.current?.()}}),t.current&&(t.current.srcObject=e,await t.current.play().catch(()=>{})),c(e),o(!0)},[d]),p=(0,X.useCallback)(async()=>{if(u(null),!window.isSecureContext)return u(`Camera needs a secure context (https or localhost).`),!1;if(!navigator.mediaDevices?.getUserMedia)return u(`Camera API not available in this browser.`),!1;try{let e=await navigator.mediaDevices.getUserMedia({video:{facingMode:`environment`,width:{ideal:1280},height:{ideal:720}},audio:!1});return await f(e),!0}catch(e){let t=e?.name;return u(t===`NotAllowedError`?`Camera permission denied.`:t===`NotFoundError`?`No camera found.`:`Camera failed: ${e?.message||t||`unknown error`}`),o(!1),!1}},[f]),m=(0,X.useCallback)(async()=>{if(u(null),!window.isSecureContext)return u(`Screen capture needs a secure context (https or localhost).`),!1;if(!navigator.mediaDevices?.getDisplayMedia)return u(`Screen capture API not available in this browser.`),!1;try{let e=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1280},height:{ideal:720}},audio:!1});return await f(e),!0}catch(e){let t=e?.name;return u(t===`NotAllowedError`?`Screen capture cancelled.`:`Screen capture failed: ${e?.message||t||`unknown error`}`),o(!1),!1}},[f]),h=(0,X.useCallback)((e=640,n=.72)=>{let r=t.current;if(!r||r.readyState<2||!r.videoWidth)return null;let a=Math.min(1,e/Math.max(r.videoWidth,r.videoHeight)),o=Math.round(r.videoWidth*a),s=Math.round(r.videoHeight*a);i.current||=document.createElement(`canvas`);let c=i.current;c.width=o,c.height=s;let l=c.getContext(`2d`);return l?(l.drawImage(r,0,0,o,s),c.toDataURL(`image/jpeg`,n)):null},[]);return(0,X.useEffect)(()=>d,[d]),{videoRef:t,stream:s,active:a,error:l,start:p,startScreen:m,stop:d,captureFrame:h}}async function ly(e,t,n={}){let r={limit:n.limit??12,scope:n.contextPath?`path`:`workspace`};t&&(r.image=t),n.similarTo&&(r.similarTo=n.similarTo);let i=n.q?.trim();i&&(r.q=i),n.maxDistance!=null&&Number.isFinite(n.maxDistance)&&(r.maxDistance=n.maxDistance),n.minDistance!=null&&Number.isFinite(n.minDistance)&&(r.minDistance=n.minDistance),n.debug&&(r.debug=!0),n.idsOnly&&(r.idsOnly=!0),n.contextPath&&(r.context=n.contextPath);let a=await Y.postEnvelope(`${Kr.workspaces}/${encodeURIComponent(e)}/documents/search/image`,r,n.signal?{signal:n.signal}:void 0),o=a.payload??[],s=n.idsOnly===!0;return{documents:s?[]:o,ids:s?o:o.map(e=>e.id),count:a.count??o.length,totalCount:a.totalCount??o.length,distances:a.debug?.distances??a.debug?.imageDistances??null}}var uy=[{label:`0.5 fps`,ms:2e3},{label:`1 fps`,ms:1e3},{label:`2 fps`,ms:500},{label:`5 fps`,ms:200},{label:`10 fps`,ms:100},{label:`15 fps`,ms:67},{label:`30 fps`,ms:33}],dy=1e3,fy=32,py=12;function my({className:e}){let{stream:t}=oy(),n=(0,X.useRef)(null);return(0,X.useEffect)(()=>{let e=n.current;if(e)return e.srcObject=t,t&&e.play().catch(()=>{}),()=>{e.srcObject=null}},[t]),(0,Z.jsx)(`video`,{ref:n,muted:!0,playsInline:!0,className:e})}function hy({children:e}){let t=Ao(),n=(0,X.useRef)(t);(0,X.useEffect)(()=>{n.current=t});let r=t?.state.activeWorkspaceName??null,i=t!==null,a=(0,X.useRef)(()=>{}),{videoRef:o,stream:s,error:c,start:l,startScreen:u,stop:d,captureFrame:f}=cy({onEnded:()=>a.current()}),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(!1),[y,b]=(0,X.useState)(dy),[x,S]=(0,X.useState)(``),[C,w]=(0,X.useState)(``),[T,E]=(0,X.useState)(null),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(null),[j,M]=(0,X.useState)([]),[N,P]=(0,X.useState)(0),[ee,F]=(0,X.useState)(``),I=(0,X.useRef)({running:!1,paused:!1,consumer:null,workspaceRef:``,contextPath:null,text:``,maxDistance:NaN,rateMs:dy}),te=(0,X.useRef)([]),ne=(0,X.useRef)(new Map),L=(0,X.useRef)(null),re=(0,X.useRef)(null),R=(0,X.useRef)(null),ie=(0,X.useRef)(0),ae=(0,X.useRef)(!1),oe=(0,X.useRef)(async()=>{});(0,X.useEffect)(()=>{I.current.text=C,I.current.maxDistance=x===``?NaN:Number(x),I.current.rateMs=y,I.current.paused=_},[C,x,y,_]);let z=(0,X.useCallback)(()=>(P(e=>e+1),()=>P(e=>Math.max(0,e-1))),[]),se=(0,X.useCallback)(e=>{te.current=[...te.current.slice(-2),e];let t=te.current,r=[...new Set(t.flat())],i=t.length<2?e:r.filter(e=>t.filter(t=>t.includes(e)).length>=2);A(i.length);let a=L.current;(!a||a.length!==i.length||a.some((e,t)=>e!==i[t]))&&(L.current=i,n.current?.setLensIds(i))},[]),ce=(0,X.useCallback)((e,t)=>{for(let n of e)ne.current.set(n.id,{doc:n,distance:t.get(n.id)});let n=e.map(e=>e.id);te.current=[...te.current.slice(-2),n];let r=te.current,i=r[r.length-1]??[],a=r.length<2?i:i.filter(e=>r.filter(t=>t.includes(e)).length>=2),o=[...ne.current.keys()].filter(e=>!i.includes(e)&&r.filter(t=>t.includes(e)).length>=2),s=[...a,...o].map(e=>ne.current.get(e)).filter(e=>!!e);A(s.length),M(s)},[]),B=(0,X.useCallback)(async()=>{let e=I.current;if(!e.running)return;let t=performance.now();if(!e.paused){let n=f();if(n&&e.workspaceRef){let r=e.consumer===`applet`,i=new AbortController;R.current=i;try{let a=await ly(e.workspaceRef,n,{q:r&&e.text||void 0,maxDistance:Number.isFinite(e.maxDistance)?e.maxDistance:void 0,contextPath:r?e.contextPath:null,limit:r?py:fy,idsOnly:!r,debug:r,signal:i.signal});if(i.signal.aborted||I.current!==e||!e.running)return;ie.current=0,O(Math.round(performance.now()-t)),E(null),r?ce(a.documents,new Map((a.distances??[]).map(e=>[e.id,e.distance]))):se(a.ids)}catch(t){if(i.signal.aborted||I.current!==e||!e.running)return;ie.current++,t?.name!==`AbortError`&&E(t?.message||`search failed`)}}}if(I.current.running){let e=Math.max(ie.current?Math.min(3e4,1e3*2**Math.min(ie.current-1,5)):0,I.current.rateMs-(performance.now()-t));re.current=window.setTimeout(()=>void oe.current(),e)}},[f,ce,se]);(0,X.useEffect)(()=>{oe.current=B},[B]);let V=(0,X.useCallback)(()=>{let e=I.current.consumer===`filter`;I.current.running=!1,ie.current=0,I.current.consumer=null,re.current&&window.clearTimeout(re.current),R.current?.abort(),d(),te.current=[],ne.current.clear(),L.current=null,m(null),g(null),v(!1),F(``),M([]),A(null),O(null),E(null),e&&n.current?.setLensIds(null)},[d]);(0,X.useEffect)(()=>{a.current=V},[V]);let le=(0,X.useCallback)(async(e,t,n)=>{if(!n.workspaceRef||ae.current)return!1;I.current.running&&V(),ae.current=!0;let r=e===`camera`?await l():await u();return ae.current=!1,r?(te.current=[],ne.current.clear(),L.current=null,M([]),A(null),E(null),F(n.workspaceRef),I.current={...I.current,running:!0,paused:!1,consumer:t,workspaceRef:n.workspaceRef,contextPath:n.contextPath??null},m(e),g(t),v(!1),B(),!0):!1},[l,u,V,B]),ue=(0,X.useCallback)(e=>{I.current.contextPath=e},[]),de=(0,X.useCallback)(e=>{I.current.paused=e,v(e)},[]);(0,X.useEffect)(()=>{!i||!I.current.running||r&&r===I.current.workspaceRef||V()},[i,r,V]);let fe=(0,X.useCallback)(()=>{let e=n.current;if(e){if(I.current.consumer===`applet`){e.setView(`apps`),e.openApplet(`lens`);return}e.setView(`tools`),e.setToolsTab(`lens`)}},[]);(0,X.useEffect)(()=>V,[V]);let pe=(0,X.useMemo)(()=>({source:p,running:p!==null,paused:_,consumer:h,stream:s,workspaceRef:ee,rateMs:y,setRateMs:b,maxDistance:x,setMaxDistance:S,text:C,setText:w,error:c||T,latencyMs:D,lastCount:k,hits:j,start:le,setContextPath:ue,stop:V,setPaused:de,reopen:fe,hasViewer:N>0,registerViewer:z}),[p,_,h,s,ee,y,x,C,c,T,D,k,j,le,ue,V,de,fe,N,z]);return(0,Z.jsxs)(ay.Provider,{value:pe,children:[e,(0,Z.jsx)(`video`,{ref:o,muted:!0,playsInline:!0,"aria-hidden":!0,className:`pointer-events-none fixed bottom-0 left-0 h-px w-px opacity-0`})]})}var gy=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring`,_y=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`;function vy({workspaceRef:e,doc:t,distance:n,onOpen:r}){let i=To(t),{blobUrl:a}=jm(e,t.id,256,{enabled:i}),o=mo(t);return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r(t),title:`Open ${o.title}`,className:`rounded-lg border border-border bg-card overflow-hidden flex flex-col text-left cursor-pointer transition-colors hover:border-foreground/30 hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,Z.jsx)(`div`,{className:`aspect-square bg-muted/40 flex items-center justify-center overflow-hidden`,children:i&&a?(0,Z.jsx)(`img`,{src:a,alt:o.title,className:`h-full w-full object-cover`}):(0,Z.jsx)(Jf,{document:t,size:10})}),(0,Z.jsxs)(`div`,{className:`p-2 min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-xs font-medium truncate`,title:o.title,children:o.title}),(0,Z.jsxs)(`div`,{className:`text-[10px] text-muted-foreground truncate`,children:[o.schemaLabel,n==null?``:` · d=${n.toFixed(3)}`]})]})]})}function yy(){let e=Uv(),t=gg(),n=oy(),{rateMs:r,setRateMs:i,text:a,setText:o,maxDistance:s,setMaxDistance:c,latencyMs:l,error:u}=n,d=e?.mode===`workspace`?e.workspaceName:``,f=e?.mode===`workspace`&&e.path!==`/`?e.path:null,p=n.running&&n.consumer===`applet`,m=n.running&&n.consumer!==`applet`,h=p?n.hits:[];sy(p);let g=e=>{d&&n.start(e,`applet`,{workspaceRef:d,contextPath:f})},{setContextPath:_}=n;return(0,X.useEffect)(()=>{p&&_(f)},[p,f,_]),e?.mode===`workspace`?(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`select`,{className:gy,value:r,onChange:e=>i(Number(e.target.value)),title:`Frame rate. High rates (10–30 fps) are experimental; the loop never overlaps requests, so the effective rate is capped by search latency.`,children:uy.map(e=>(0,Z.jsx)(`option`,{value:e.ms,children:e.label},e.ms))}),(0,Z.jsx)(`input`,{className:K(_y,`w-44`),placeholder:`Optional text (fused mode)`,value:a,onChange:e=>o(e.target.value)}),(0,Z.jsx)(`input`,{className:K(_y,`w-28`),placeholder:`max distance`,inputMode:`decimal`,value:s,onChange:e=>c(e.target.value),title:`Cosine-distance floor (0 = identical). Empty = top-K.`}),p?(0,Z.jsxs)(`button`,{type:`button`,onClick:n.stop,className:`flex h-8 items-center gap-1 rounded-md bg-destructive px-3 text-xs font-medium text-destructive-foreground transition-colors hover:bg-destructive/90`,children:[(0,Z.jsx)(we,{className:`h-3.5 w-3.5`}),` Stop`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>g(`camera`),disabled:m,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`,children:[(0,Z.jsx)(w,{className:`h-3.5 w-3.5`}),` Camera`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>g(`screen`),disabled:m,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`,children:[(0,Z.jsx)(kn,{className:`h-3.5 w-3.5`}),` Desktop`]})]})]}),(0,Z.jsxs)(`div`,{className:`relative shrink-0 overflow-hidden rounded-xl border border-border bg-black/80 aspect-video max-h-64`,children:[p&&(0,Z.jsx)(my,{className:`h-full w-full object-cover`}),!p&&(0,Z.jsxs)(`div`,{className:`absolute inset-0 flex items-center justify-center text-sm text-muted-foreground`,children:[(0,Z.jsx)(ut,{className:`mr-2 h-4 w-4`}),` camera off`]})]}),(0,Z.jsx)(`div`,{className:`shrink-0 text-xs text-muted-foreground`,children:u?(0,Z.jsx)(`span`,{className:`text-destructive`,children:u}):p?(0,Z.jsxs)(Z.Fragment,{children:[`live · `,l==null?`searching…`:`${l} ms/frame`,` · `,h.length,` match`,h.length===1?``:`es`,f?` · scoped to ${f}`:``]}):m?`The Lens filter is using the camera. Stop it there first.`:`Frames are ephemeral: embedded for the query, never stored or indexed.`}),h.length===0?(0,Z.jsx)(`div`,{className:`flex min-h-24 flex-1 items-center justify-center rounded-xl border border-dashed border-border text-sm text-muted-foreground`,children:p?`Nothing matching in view`:`Matches appear here`}):(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4`,children:h.map(e=>(0,Z.jsx)(vy,{workspaceRef:d,doc:e.doc,distance:e.distance,onOpen:e=>t.open(e,d)},e.doc.id))})]}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:`Lens searches a workspace. Bind it to a workspace path to start.`})}function by({doc:e,scope:t,onOpen:n,onRemove:r}){let{blobUrl:i,loading:a}=jm(t.workspaceName,e.id,256,{version:e.checksumArray?.[0]??null}),o=String(e.data?.title??`Sketch`);return(0,Z.jsxs)(`div`,{className:`group relative overflow-hidden rounded-lg border bg-card shadow-elevation-2 transition-shadow hover:shadow-elevation-3`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:n,className:`block w-full text-left`,children:[(0,Z.jsx)(`div`,{className:`flex aspect-[4/3] items-center justify-center overflow-hidden bg-muted/30`,children:i?(0,Z.jsx)(`img`,{src:i,alt:o,className:`h-full w-full object-contain`}):(0,Z.jsx)(re,{className:`h-6 w-6 text-muted-foreground ${a?`animate-pulse`:``}`})}),(0,Z.jsxs)(`div`,{className:`px-2 py-1.5`,children:[(0,Z.jsx)(`div`,{className:`truncate text-xs font-medium`,children:o}),(0,Z.jsx)(`div`,{className:`text-[10px] text-muted-foreground`,children:Jv(e.updatedAt||e.createdAt)})]})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Delete ${o}`,className:`absolute right-1.5 top-1.5 rounded-md bg-background/80 p-1 opacity-0 transition-opacity hover:text-destructive group-hover:opacity-100`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})}function xy({autoAdd:e}){let t=Uv(),{docs:n,loading:r,error:i,scope:a,reload:o,removeDoc:s}=Yv(t,ro),[c,l]=(0,X.useState)(e?`new`:null),{showErrorToast:u}=Ya();return t?(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 p-3`,children:[(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,className:`self-start`,onClick:()=>l(`new`),children:[(0,Z.jsx)(nn,{className:`mr-1.5 h-4 w-4`}),`New sketch`]}),i&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i}),r&&!n.length&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketches…`}),!r&&!n.length&&!i&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No sketches here yet.`}),a&&n.length>0&&(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4`,children:n.map(e=>(0,Z.jsx)(by,{doc:e,scope:a,onOpen:()=>l(e),onRemove:()=>{confirm(`Delete "${String(e.data?.title??`Sketch`)}"?`)&&s(e.id).catch(e=>u(e instanceof Error?e.message:`Failed to delete sketch`))}},`${e.id}:${e.checksumArray?.[0]??``}`))}),c&&a&&(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,Z.jsx)(Sg,{doc:c===`new`?null:c,workspaceName:a.workspaceName,target:t,onSaved:()=>{l(null),o()},onClose:()=>l(null)})}),c&&!a&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Resolving destination…`})})]}):(0,Z.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`Select a context or workspace path first.`})}var Sy=[{id:`notes`,label:`Notes`,icon:vn,modes:[`context`],description:`All notes in the current context, editable in place`,Component:$v},{id:`todo`,label:`Todos`,icon:zt,modes:[`context`],description:`Todos in the current context, done items hidden by default`,Component:iy},{id:`sketch`,label:`Sketch`,icon:re,modes:[`context`],description:`Quick-sketch into the current context; tap a sketch to keep editing`,Component:xy},{id:`lens`,label:`Lens`,icon:rr,modes:[`context`],description:`Point a camera at things; matching documents surface live`,Component:yy}];function Cy(e){return Sy.filter(t=>t.modes.includes(e))}function wy({target:e,children:t}){return(0,Z.jsx)(Hv.Provider,{value:e,children:t})}function Ty({children:e}){let[t,n]=(0,X.useState)(null),r=(0,X.useCallback)((e,t)=>n({document:e,workspaceId:t}),[]),i=(0,X.useCallback)(()=>n(null),[]),a=(0,X.useMemo)(()=>({open:r,close:i}),[r,i]);return(0,Z.jsxs)(mg.Provider,{value:a,children:[e,(0,Z.jsx)(Wg,{document:t?.document??null,isOpen:!!t,onClose:i,workspaceId:t?.workspaceId})]})}var Ey=`universe`;function Dy(){let{appletId:e}=Yc(),[t,n]=mu(),r=Sy.find(t=>t.id===e),i=t.get(`context`),a=t.get(`workspace`)||Ey,o=t.get(`path`)||`/`,s=t.get(`tree`)||`context`,c=t.get(`add`)===`1`,l=(0,X.useMemo)(()=>i?{mode:`context`,contextId:i}:{mode:`workspace`,workspaceName:a,path:o,treeName:s,treeType:s===`directory`?`directory`:`context`},[i,a,o,s]),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)([]);(0,X.useEffect)(()=>{Or().then(d).catch(()=>d([])),Uo().then(p).catch(()=>p([]))},[]);let[m,h]=(0,X.useState)(o),[g,_]=(0,X.useState)(o);g!==o&&(_(o),h(o));let v=e=>{let r=new URLSearchParams(t);r.delete(`add`);for(let[t,n]of Object.entries(e))n===null?r.delete(t):r.set(t,n);n(r,{replace:!0})};if(!r)return(0,Z.jsxs)(`div`,{className:`flex h-viewport flex-col items-center justify-center gap-3 surface-desk`,children:[(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Unknown app`,e?` "${e}"`:``,`.`]}),(0,Z.jsx)(`div`,{className:`flex gap-2`,children:Sy.map(e=>(0,Z.jsx)(cu,{to:`/apps/${e.id}`,className:`rounded-md border border-border px-3 py-1.5 text-sm hover:bg-muted`,children:e.label},e.id))})]});let y=i?`context`:`path`;return(0,Z.jsx)(Ty,{children:(0,Z.jsx)(hy,{children:(0,Z.jsxs)(`div`,{className:`flex h-viewport flex-col surface-desk p-shell gap-shell`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2 rounded-xl border bg-card px-3 py-2 shadow-elevation-2`,children:[(0,Z.jsx)(r.icon,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:r.label}),(0,Z.jsx)(`div`,{className:`ml-2 flex overflow-hidden rounded-md border border-border`,children:[`path`,`context`].map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{e!==y&&v(e===`path`?{context:null}:{context:f[0]?.id??``,workspace:null,path:null,tree:null})},className:K(`px-2.5 py-1 text-xs capitalize transition-colors`,y===e?`bg-foreground text-background`:`text-muted-foreground hover:bg-muted hover:text-foreground`),children:e},e))}),y===`path`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`select`,{value:a,onChange:e=>v({workspace:e.target.value,path:`/`}),className:`h-7 rounded-md border border-input bg-transparent px-1.5 text-xs`,"aria-label":`Workspace`,children:[!u.some(e=>e.name===a)&&(0,Z.jsx)(`option`,{value:a,children:a}),u.map(e=>(0,Z.jsx)(`option`,{value:e.name,children:e.label||e.name},e.id))]}),(0,Z.jsx)(`input`,{value:m,onChange:e=>h(e.target.value),onBlur:()=>{let e=m.trim()||`/`;e!==o&&v({path:e})},onKeyDown:e=>{e.key===`Enter`&&e.target.blur()},spellCheck:!1,placeholder:`/`,className:`h-7 w-40 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,"aria-label":`Path`})]}):(0,Z.jsxs)(`select`,{value:i??``,onChange:e=>v({context:e.target.value}),className:`h-7 max-w-56 rounded-md border border-input bg-transparent px-1.5 text-xs`,"aria-label":`Context`,children:[!i&&(0,Z.jsx)(`option`,{value:``,children:`Pick a context…`}),f.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.id,e.url?` (${e.url})`:``]},e.id))]}),(0,Z.jsx)(`div`,{className:`grow`}),(0,Z.jsx)(cu,{to:`/home`,className:`flex items-center gap-1 rounded-md p-1.5 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:`Open the full Canvas app`,children:(0,Z.jsx)(en,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border bg-card shadow-elevation-2`,children:y===`context`&&!i?(0,Z.jsxs)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:[`Pick a context above to bind `,r.label,` to it.`]}):(0,Z.jsx)(wy,{target:l,children:(0,Z.jsx)(r.Component,{autoAdd:c},JSON.stringify(l))})})]})})})}var Oy=`false`,ky=`false`,Ay=Oy===`true`,jy=ky===`true`;function My(e={}){let{immediate:t=!1,onNeedReload:n,onNeedRefresh:r,onOfflineReady:i,onRegistered:a,onRegisteredSW:o,onRegisterError:s}=e,c,l,u,d=async(e=!0)=>{await l,Ay||u?.()};async function f(){if(`serviceWorker`in navigator){if(c=await m(async()=>{let{Workbox:e}=await import(`./workbox-window.prod.es5-Bd17z0YL.js`);return{Workbox:e}},[]).then(({Workbox:e})=>new e(`/sw.js`,{scope:`/`,type:`classic`})).catch(e=>{s?.(e)}),!c)return;if(u=()=>{c?.messageSkipWaiting()},!jy){if(Ay)c.addEventListener(`activated`,e=>{(e.isUpdate||e.isExternal)&&(n?n():window.location.reload())}),c.addEventListener(`installed`,e=>{e.isUpdate||i?.()});else{let e=!1,t=()=>{e=!0,c?.addEventListener(`controlling`,e=>{e.isUpdate&&(n?n():window.location.reload())}),r?.()};c.addEventListener(`installed`,n=>{n.isUpdate===void 0?n.isExternal===void 0?!e&&i?.():n.isExternal?t():!e&&i?.():n.isUpdate||i?.()}),c.addEventListener(`waiting`,t)}}c.register({immediate:t}).then(e=>{o?o(`/sw.js`,e):a?.(e)}).catch(e=>{s?.(e)})}}return l=f(),d}var Ny=new Set,Py=!1,Fy=My({immediate:!0,onRegisteredSW(e,t){t&&setInterval(()=>{t.update()},36e5)},onNeedRefresh(){Py=!0,Ny.forEach(e=>e())}});function Iy(e){return Ny.add(e),Py&&e(),()=>{Ny.delete(e)}}function Ly(){Fy(!0)}function Ry(){let[e,t]=(0,X.useState)(!1),[n,r]=(0,X.useState)(!1);return(0,X.useEffect)(()=>Iy(()=>t(!0)),[]),!e||n?null:(0,Z.jsx)(`div`,{className:`fixed bottom-4 left-1/2 z-50 -translate-x-1/2`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 rounded-full border border-border bg-card px-4 py-2 shadow-elevation-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm`,children:`A new version of Canvas is ready`}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>Ly(),className:`flex items-center gap-1 rounded-full bg-foreground px-3 py-1 text-xs font-medium text-background hover:bg-foreground/90`,children:[(0,Z.jsx)(M,{className:`h-3 w-3`}),` Reload`]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(!0),"aria-label":`Not now`,className:`rounded-full p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(je,{className:`h-3.5 w-3.5`})})]})})}function zy(e){return e.isShared||e.type===`shared`?e.id:e.name}function By({title:e,description:t,actions:n,backTo:r,onBack:i,className:a,compact:o}){let s=Gc();return(0,Z.jsxs)(`div`,{className:K(`flex flex-wrap items-start gap-x-3 gap-y-2`,!o&&`border-b pb-4`,a),children:[(0,Z.jsxs)(`div`,{className:`flex min-w-[14rem] flex-1 items-start gap-3`,children:[(i||r)&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>i?i():s(r),"aria-label":`Back`,title:`Back`,className:`mt-1 shrink-0 text-muted-foreground transition-colors hover:text-foreground touch-target`,children:(0,Z.jsx)(Pn,{className:`h-5 w-5`})}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h1`,{className:K(`truncate font-bold tracking-tight`,o?`text-xl`:`text-3xl`),children:e}),t&&(0,Z.jsx)(`p`,{className:K(`break-words text-muted-foreground`,o?`mt-1 text-xs`:`mt-2`),children:t})]})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>s(`/`),"aria-label":`Close`,title:`Close`,className:`order-2 flex h-9 w-9 shrink-0 items-center justify-center rounded-md border text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,children:(0,Z.jsx)(je,{className:`h-4 w-4`})}),n&&(0,Z.jsx)(`div`,{className:`order-3 flex w-full items-center gap-2 max-sm:flex-wrap sm:order-1 sm:w-auto`,children:n})]})}function Vy({className:e}){let t=Gc();return(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(`/`),"aria-label":`Close`,title:`Close`,className:K(`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground transition-colors hover:bg-accent hover:text-foreground touch-target`,e),children:(0,Z.jsx)(je,{className:`h-3.5 w-3.5`})})}function Hy({onBack:e,title:t=`Back`,className:n}){return(0,Z.jsx)(`button`,{type:`button`,onClick:e,"aria-label":t,title:t,className:K(`flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground touch-target`,n),children:(0,Z.jsx)(Pn,{className:`h-4 w-4`})})}var Uy=180;function Wy({x:e,y:t,current:n,onChange:r,onClose:i}){gf(i);let[a,o]=(0,X.useState)(``),[s,l]=(0,X.useState)([]),[u,d]=(0,X.useState)({q:``,list:[]}),[f,p]=(0,X.useState)(!0),m=(0,X.useRef)(null),h=(0,X.useRef)({name:``,t:0}),g=(e,t)=>{r({icon:e}),h.current.name===e&&t-h.current.t<350&&i(),h.current={name:e,t}};(0,X.useEffect)(()=>{m.current?.focus()},[]),(0,X.useEffect)(()=>{let e=!0;return yf().then(t=>{e&&(l(t),p(!1))}),()=>{e=!1}},[]),(0,X.useEffect)(()=>{let e=a.trim();if(!e)return;let t=setTimeout(()=>{bf(e).then(t=>{d({q:e,list:t})})},250);return()=>clearTimeout(t)},[a]);let _=a.trim(),v=u.q===_,y=_!==``&&!v,b=(0,X.useMemo)(()=>(_?v?u.list:[]:s).slice(0,Uy),[_,v,u.list,s]),x=(0,X.useRef)(null),[S,C]=(0,X.useState)({x:e,y:t});return(0,X.useLayoutEffect)(()=>{let n=x.current;if(!n)return;let r=()=>{let{width:r,height:i}=n.getBoundingClientRect();C({x:Math.max(8,Math.min(e,window.innerWidth-r-8)),y:Math.max(8,Math.min(t,window.innerHeight-i-8))})};r();let i=new ResizeObserver(r);return i.observe(n),window.addEventListener(`resize`,r),()=>{i.disconnect(),window.removeEventListener(`resize`,r)}},[e,t]),(0,pf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:i}),(0,Z.jsxs)(`div`,{ref:x,className:`fixed z-50 w-[270px] max-w-[90vw] rounded-md border bg-popover p-2 shadow-elevation-4`,style:{left:S.x,top:S.y},children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between px-1 pb-1.5`,children:[(0,Z.jsx)(`span`,{className:`text-xs font-medium`,children:`Icon & color`}),(0,Z.jsx)(`button`,{type:`button`,onClick:i,className:`text-muted-foreground hover:text-foreground`,children:(0,Z.jsx)(je,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-1.5 px-1 pb-2`,children:[xf.map(e=>(0,Z.jsx)(`button`,{type:`button`,title:e,onClick:()=>r({color:e}),className:K(`w-5 h-5 rounded-full border transition-transform hover:scale-110`,n.color===e?`ring-2 ring-offset-1 ring-foreground`:`border-border`),style:{backgroundColor:e}},e)),(0,Z.jsx)(`button`,{type:`button`,title:`No color`,onClick:()=>r({color:void 0}),className:K(`w-5 h-5 rounded-full border flex items-center justify-center text-muted-foreground hover:scale-110 transition-transform`,!n.color&&`ring-2 ring-offset-1 ring-foreground`),children:(0,Z.jsx)(je,{className:`w-3 h-3`})}),(0,Z.jsx)(`label`,{title:`Custom color`,className:K(`relative w-5 h-5 rounded-full border border-border cursor-pointer hover:scale-110 transition-transform overflow-hidden`,n.color&&!xf.includes(n.color)&&`ring-2 ring-offset-1 ring-foreground`),style:{background:n.color&&!xf.includes(n.color)?n.color:`conic-gradient(from 0deg, #ef4444, #eab308, #22c55e, #06b6d4, #6366f1, #ec4899, #ef4444)`},children:(0,Z.jsx)(`input`,{type:`color`,value:n.color??`#3b82f6`,onChange:e=>r({color:e.target.value}),className:`absolute inset-0 opacity-0 cursor-pointer`})})]}),(0,Z.jsx)(`input`,{ref:m,value:a,onChange:e=>o(e.target.value),placeholder:`Search icons…`,className:`w-full mb-2 rounded-sm border bg-background px-2 py-1 text-xs outline-none focus:ring-1 focus:ring-primary`}),f||y?(0,Z.jsxs)(`div`,{className:`flex items-center justify-center gap-2 py-8 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Wn,{className:`w-4 h-4 animate-spin`}),` `,y?`Searching…`:`Loading icons…`]}):(0,Z.jsxs)(`div`,{className:`grid grid-cols-7 gap-0.5 max-h-[200px] overflow-y-auto`,children:[(0,Z.jsx)(`button`,{type:`button`,title:`No icon`,onClick:()=>r({icon:void 0}),className:K(`aspect-square flex items-center justify-center rounded-sm hover:bg-accent text-muted-foreground`,!n.icon&&`bg-accent ring-1 ring-primary`),children:(0,Z.jsx)(je,{className:`w-4 h-4`})}),b.map(e=>(0,Z.jsx)(`button`,{type:`button`,title:e.replace(/^[^:]+:/,``).replace(`-fill`,``),onClick:t=>g(e,t.timeStamp),className:K(`aspect-square flex items-center justify-center rounded-sm hover:bg-accent`,n.icon===e&&`bg-accent ring-1 ring-primary`),children:(0,Z.jsx)(c,{icon:e,width:18,height:18,color:n.color})},e))]}),!f&&!y&&b.length===0&&(0,Z.jsxs)(`div`,{className:`px-1 py-3 text-center text-[11px] text-muted-foreground`,children:[`No icons match “`,a,`”`]})]})]}),document.body)}function Gy(e,t,n){let r=(0,X.useRef)(n);(0,X.useEffect)(()=>{r.current=n}),(0,X.useEffect)(()=>{if(!e)return;e.emit(`subscribe`,{channel:t});let n=Object.keys(r.current).map(t=>{let n=(...e)=>{r.current[t]?.(...e)};return e.on(t,n),[t,n]});return()=>{e.emit(`unsubscribe`,{channel:t});for(let[t,r]of n)e.off(t,r)}},[e,t])}function Ky({title:e,onClose:t,children:n}){return(0,Z.jsxs)(`div`,{className:`space-y-4 rounded-lg border bg-card p-4 shadow-elevation-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:e}),(0,Z.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close`,className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,children:(0,Z.jsx)(je,{className:`h-4 w-4`})})]}),n]})}function qy({workspace:e,onStart:t,onStop:n,onEnter:r,onEdit:i,onSettings:a,onDestroy:o}){let[s,c]=(0,X.useState)(!1),l=e.status===`active`,u=e.type===`universe`||e.name===`universe`,d=e.status===`error`,f=e.status===`not_found`,p=e.isShared===!0||e.type===`shared`,m=e.ownerEmail||e.owner,h=typeof e.sharedVia==`object`&&e.sharedVia?e.sharedVia:null,g=h?.permissions||[],_=g.includes(`admin`)?`admin`:g.includes(`write`)?`read/write`:`read-only`,v=h?.type===`group`?`via group ${h.principal}`:h?.type===`user`?`shared with you`:``,y=e.origin===`remote`,b=e.status===`offline`,x=If(e.color),S=x?``:`border-border`,C=x?{borderLeftColor:x,borderLeftWidth:`4px`}:{borderLeftWidth:`4px`};return(0,Z.jsx)(Z.Fragment,{children:(0,Z.jsxs)(xu,{className:`relative ${S}`,style:C,children:[(0,Z.jsx)(Su,{children:(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 basis-40`,children:[(0,Z.jsx)(Cu,{className:`truncate`,children:e.label||e.name}),(0,Z.jsx)(wu,{children:p?`Shared from ${m}`:e.description||``})]}),(0,Z.jsxs)(`div`,{className:`flex w-full shrink-0 flex-wrap items-center gap-2 sm:w-auto`,children:[l?(0,Z.jsx)(J,{variant:`outline`,size:`icon`,onClick:()=>n(zy(e)),title:`Stop Workspace`,disabled:d||f,children:(0,Z.jsx)($t,{className:`h-4 w-4`})}):(0,Z.jsx)(J,{variant:`outline`,size:`icon`,onClick:()=>t(zy(e)),title:b?`Remote unreachable${e.statusMessage?`: ${e.statusMessage}`:``}`:`Start Workspace`,disabled:d||f||b,children:(0,Z.jsx)(W,{className:`h-4 w-4`})}),l&&(0,Z.jsx)(J,{variant:`outline`,size:`icon`,onClick:()=>r(zy(e)),title:`Enter Workspace`,disabled:d||f,children:(0,Z.jsx)(pn,{className:`h-4 w-4`})}),a&&(0,Z.jsx)(J,{variant:`outline`,size:`icon`,onClick:()=>a(e),title:`Workspace settings`,"aria-label":`Workspace settings`,disabled:f,children:(0,Z.jsx)(mn,{className:`h-4 w-4`})}),i&&!u&&!p&&(0,Z.jsx)(J,{variant:`outline`,size:`icon`,onClick:()=>i(e),title:`Edit Workspace`,disabled:d||f,children:(0,Z.jsx)(bt,{className:`h-4 w-4`})}),o&&!u&&!p&&(0,Z.jsxs)(Gi,{open:s,onOpenChange:c,children:[(0,Z.jsx)(La,{asChild:!0,children:(0,Z.jsx)(J,{variant:`outline`,size:`icon`,title:y?`Remove remote workspace reference`:`Delete Workspace`,disabled:l&&!y,className:`text-destructive hover:text-destructive hover:bg-destructive/10`,children:(0,Z.jsx)(lt,{className:`h-4 w-4`})})}),(0,Z.jsxs)(Ua,{children:[(0,Z.jsxs)(ci,{children:[(0,Z.jsx)(wr,{children:y?`Remove remote workspace`:`Delete Workspace`}),(0,Z.jsx)(ji,{children:y?(0,Z.jsxs)(Z.Fragment,{children:[`Remove the reference to "`,e.label||e.name,`" from this server?`,(0,Z.jsx)(`br`,{}),(0,Z.jsx)(`br`,{}),`The workspace itself stays untouched on `,e.remote?.url||e.host,`; only the stored share token and the local cache entry are dropped.`]}):(0,Z.jsxs)(Z.Fragment,{children:[`Are you sure you want to delete the workspace "`,e.label||e.name,`"?`,(0,Z.jsx)(`br`,{}),(0,Z.jsx)(`br`,{}),(0,Z.jsx)(`strong`,{children:`This action cannot be undone.`}),` All data associated with this workspace, including documents, contexts, and configurations will be permanently removed.`]})})]}),(0,Z.jsxs)(Ba,{children:[(0,Z.jsx)(Pa,{children:`Cancel`}),(0,Z.jsx)(Ti,{onClick:()=>{o(e),c(!1)},className:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,children:y?`Remove reference`:`Delete Workspace`})]})]})]})]})]})}),(0,Z.jsx)(Tu,{children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`div`,{className:`h-3 w-3 rounded-full ${(()=>{switch(e.status){case`active`:return`bg-success`;case`inactive`:case`available`:return`bg-muted-foreground`;case`error`:case`offline`:return`bg-destructive`;case`not_found`:return`bg-muted-foreground`;default:return`bg-accent`}})()}`}),(0,Z.jsx)(`span`,{className:`text-sm text-muted-foreground`,children:(()=>{switch(e.status){case`active`:return`Active`;case`inactive`:return`Inactive`;case`error`:return`Error`;case`not_found`:return`Not Found`;case`available`:return`Available`;case`removed`:return`Removed`;case`destroyed`:return`Destroyed`;case`offline`:return`Offline`;default:return e.status}})()}),u&&(0,Z.jsx)(`span`,{className:`ml-2 rounded-full bg-primary/10 px-2 py-1 text-xs text-primary`,children:`Universe`}),y&&(0,Z.jsxs)(`span`,{className:`ml-2 rounded-full bg-info/10 px-2 py-1 text-xs text-info`,title:e.remote?.url?`${e.remote.url} (${(e.remote.permissions||[]).join(`, `)||`no permissions`})`:void 0,children:[`Remote · `,e.host]}),p&&(0,Z.jsxs)(`span`,{className:`ml-2 rounded-full bg-info/10 px-2 py-1 text-xs text-info`,title:[v,`${_} access`].filter(Boolean).join(` · `),children:[`Shared · `,_]})]})})]})})}function Jy(){let[e,t]=mu(),n=e.get(`create`)===`1`,[r,i]=(0,X.useState)(n),[a,o]=(0,X.useState)(n);return n!==a&&(o(n),n&&i(!0)),[r,(0,X.useCallback)(r=>{if(i(r),!r&&n){let n=new URLSearchParams(e);n.delete(`create`),t(n,{replace:!0})}},[e,n,t])]}var Yy=`canvas:lastPath`,Xy=200;function Zy(){try{let e=localStorage.getItem(Yy);if(!e)return{};let t=JSON.parse(e);return t&&typeof t==`object`?t:{}}catch{return{}}}function Qy(e){try{localStorage.setItem(Yy,JSON.stringify(e))}catch{}}function $y(e,t,n){if(!e)return;let r=Zy(),i=r[e];if(i&&i.tree===t&&i.path===n)return;delete r[e],r[e]={tree:t,path:n};let a=Object.keys(r);if(a.length>Xy)for(let e of a.slice(0,a.length-Xy))delete r[e];Qy(r)}function eb(e){let t=Zy()[e];return!t||typeof t.path!=`string`||typeof t.tree!=`string`?null:t}function tb(e){let t=eb(e);return t?av(e,t.path,t.tree):`/workspaces/${e}`}var nb=[{id:`device`,label:`This device`,description:`Personalize this browser and manage content available offline.`,items:[{path:`/appearance`,icon:z,label:`Appearance`,description:`Choose the theme, layout, colours, display density and document reading pane.`},{path:`/key-bindings`,icon:tr,label:`Keyboard shortcuts`,description:`View and customize shortcuts for navigation and actions.`},{path:`/offline`,icon:Me,label:`Offline & cache`,description:`Manage cached content and storage on this device.`}]},{id:`account`,label:`Your account`,description:`Manage your access and the defaults your workspaces inherit.`,items:[{path:`/api-tokens`,icon:Ie,label:`API access tokens`,description:`Create and revoke credentials for apps and integrations.`},{path:`/devices`,icon:kn,label:`Registered devices`,description:`Manage devices connected to your account.`},{path:`/embedding`,icon:Ln,label:`Search & AI defaults`,description:`Choose default embedding providers and models for your workspaces.`},{path:`/shared`,icon:Tn,label:`Shared with you`,description:`Find content other people have shared with your account.`}]},{id:`server`,label:`Server administration`,description:`Administrator controls for everyone using this Canvas server.`,items:[{path:`/admin/users`,icon:Ue,label:`Users`,description:`Manage accounts and server access.`},{path:`/admin/roles`,icon:un,label:`Roles & permissions`,description:`Manage reusable permissions across the server.`},{path:`/admin/embedding`,icon:Ln,label:`Server search & AI defaults`,description:`Set the embedding providers and models accounts inherit.`},{path:`/admin/logs`,icon:sr,label:`Server logs`,description:`Inspect server activity and troubleshoot failures.`},{path:`/admin/contexts`,icon:ar,label:`All contexts`,description:`Inspect and manage contexts across the server.`},{path:`/admin/workspaces`,icon:nt,label:`All workspaces`,description:`Inspect and manage workspaces across the server.`},{path:`/admin/agents`,icon:H,label:`All agents`,description:`Inspect and manage agents across the server.`}]},{id:`information`,label:`Information`,description:`Information about your Canvas installation.`,items:[{path:`/about`,icon:N,label:`About Canvas`,description:`View versions and information about this installation.`}]}],rb=[`/settings`,...nb.filter(e=>e.id!==`server`).flatMap(e=>e.items.map(e=>e.path))];function ib(e,...t){let n=t.join(` `).toLocaleLowerCase();return e.toLocaleLowerCase().trim().split(/\s+/).every(e=>n.includes(e))}var ab=[{id:`classic`,name:`Classic`,description:`Menu panel on the left, one content sheet.`},{id:`strip`,name:`Canvas strip (beta)`,description:`Experimental. Menus and canvases side by side in a strip you walk with the arrow keys or a swipe. Shift+click opens a second canvas to the right; pins open their own row.`}],ob=`canvas:layout`;function sb(){try{return localStorage.getItem(ob)===`strip`?`strip`:`classic`}catch{return`classic`}}var cb=sb(),lb=new Set;function ub(){for(let e of lb)e()}function db(){return cb}function fb(e){try{e===`strip`?localStorage.setItem(ob,e):localStorage.removeItem(ob)}catch{}cb=e,ub()}function pb(e){lb.add(e);let t=t=>{(t.key===ob||t.key===null)&&(cb=sb(),e())};return window.addEventListener(`storage`,t),()=>{lb.delete(e),window.removeEventListener(`storage`,t)}}function mb(){return(0,X.useSyncExternalStore)(pb,db,()=>`classic`)}var hb=[{id:`shift`,name:`Shift + arrows`,description:`Shift with an arrow key moves between columns and rows.`},{id:`alt`,name:`Alt + arrows`,description:`Alt with an arrow key. Some browsers use Alt+Left/Right for history.`},{id:`ctrl`,name:`Ctrl + arrows`,description:`Ctrl (Cmd on macOS) with an arrow key.`},{id:`none`,name:`Bare arrows`,description:`Plain arrow keys, except while typing in a field.`}],gb=`canvas:layout-nav`;function _b(){try{let e=localStorage.getItem(gb);return e===`alt`||e===`ctrl`||e===`none`?e:`shift`}catch{return`shift`}}var vb=_b(),yb=new Set;function bb(){return vb}function xb(e){try{e===`shift`?localStorage.removeItem(gb):localStorage.setItem(gb,e)}catch{}vb=e;for(let e of yb)e()}function Sb(e){yb.add(e);let t=t=>{(t.key===gb||t.key===null)&&(vb=_b(),e())};return window.addEventListener(`storage`,t),()=>{yb.delete(e),window.removeEventListener(`storage`,t)}}function Cb(){return(0,X.useSyncExternalStore)(Sb,bb,()=>`shift`)}function wb(e,t){let n=e.ctrlKey||e.metaKey;switch(t){case`shift`:return e.shiftKey&&!e.altKey&&!n;case`alt`:return e.altKey&&!e.shiftKey&&!n;case`ctrl`:return n&&!e.shiftKey&&!e.altKey;case`none`:return!e.shiftKey&&!e.altKey&&!n}}var Tb=(0,X.createContext)(null);function Eb(){let e=(0,X.useContext)(Tb);if(!e)throw Error(`useMenu must be used within a MenuProvider`);return e}function Db(e){let t=e.split(`/`).filter(Boolean),n=t[0]||``,r=t[1]||null,i=t[2]||null;return n===`contexts`?{section:`contexts`,entityId:r,m2View:i===`settings`?`settings`:r?`detail`:null}:n===`workspaces`?{section:`workspaces`,entityId:r,m2View:i===`settings`?`settings`:r?`detail`:null}:n===`agents`?{section:`agents`,entityId:r,m2View:i===`settings`?`settings`:r?`detail`:null}:n===`admin`||rb.includes(`/${n}`)?{section:`settings`,entityId:null,m2View:null}:{section:null,entityId:null,m2View:null}}function Ob(e,t){let n=Hc(),r=Gc(),i=(0,X.useRef)(!1),a=(0,X.useRef)(e);return(0,X.useEffect)(()=>{a.current=e},[e]),(0,X.useEffect)(()=>{if(i.current){i.current=!1;return}let{section:e,entityId:r,m2View:o}=Db(n.pathname);if(e===null&&n.pathname!==`/`&&db()===`strip`){let t=a.current;e=t.activeSection,r=t.selectedEntityId,o=t.m2View}let s=window.matchMedia(`(max-width: 767px)`).matches&&db()!==`strip`;t({type:`SYNC_FROM_URL`,section:e,entityId:r,m2View:o,mobile:s})},[n.key,n.pathname,t]),{navigateToEntity:(0,X.useCallback)(e=>{i.current=!0,r(e)},[r])}}function kb(){let[e,t]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=localStorage.getItem(`authToken`);if(!e)return;let n=qa(Kr.ws,{auth:{token:e},transports:[`websocket`],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3});return n.on(`connect`,()=>{console.log(`WebSocket connected`)}),n.on(`connect_error`,e=>{console.error(`WebSocket connection error:`,e)}),n.on(`error`,e=>{console.error(`WebSocket error:`,e)}),t(n),()=>{n.close()}},[]),e}var Ab=[`Home`,`Travel`,`Work`,`Books`,`Workouts`,`Beauty`,`Recipes`,`To Watch`,`To Read`,`Learning`,`Tech`,`Music`,`Finance`,`Shopping`,`Ideas`];async function jb(e,t,n){let r=0,i=0,a=n===`directory`?`directory`:`context`;for(let n of t)try{await Fi(e,`/${n}`,!0,a);let t=Of(`/${n}`);t&&await _a(e,`/${n}`,t,a).catch(()=>{}),r+=1}catch{i+=1}return oa(e),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n}})),{ok:r,failed:i}}function Mb(){let[e,t]=(0,X.useState)(new Set),[n,r]=(0,X.useState)(`context`);return{selected:e,setSelected:t,tree:n,setTree:r,toggle:e=>{t(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}}}function Nb({selected:e,onToggle:t,tree:n,onTreeChange:r,disabled:i=!1,idPrefix:a=`default-folders`,stacked:o=!1}){return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 text-xs`,children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Create in:`}),[`context`,`directory`].map(e=>(0,Z.jsxs)(`label`,{className:`flex items-center gap-1`,children:[(0,Z.jsx)(`input`,{type:`radio`,name:`${a}-tree`,checked:n===e,onChange:()=>r(e),disabled:i}),e,` tree`]},e))]}),(0,Z.jsx)(`div`,{className:`mt-3 grid gap-1.5 ${o?`grid-cols-1`:`grid-cols-2 sm:grid-cols-3 md:grid-cols-4`}`,children:Ab.map(n=>{let r=Sf[n.toLowerCase()];return(0,Z.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded border px-2 py-1.5 text-sm hover:bg-accent/50`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:e.has(n),onChange:()=>t(n),disabled:i}),r?.icon&&(0,Z.jsx)(c,{icon:r.icon,width:16,height:16,color:r.color}),(0,Z.jsx)(`span`,{className:`truncate`,children:n})]},n)})})]})}var Pb=[{value:`full`,icon:L,title:`Standard`,blurb:`Everything in one folder: your files in home/, alongside db/, data/, git/.`,tree:[`workspace.json`,`home/ ← your files`,`db/ data/ cache/ git/`]},{value:`home`,icon:_e,title:`Roaming home`,blurb:`The workspace folder IS your drive. Mount it over WebDAV and it looks like a plain home directory. Canvas keeps its files in a hidden .workspace/.`,tree:[`your files, at the top level`,`.workspace/ ← hidden, ignored`]}];function Fb({value:e,onChange:t,disabled:n=!1,idPrefix:r=`workspace-layout`,compact:i=!1}){return(0,Z.jsx)(`div`,{className:i?`space-y-1.5`:`grid gap-2 sm:grid-cols-2`,children:Pb.map(i=>{let a=e===i.value,o=i.icon;return(0,Z.jsxs)(`button`,{id:`${r}-${i.value}`,type:`button`,role:`radio`,"aria-checked":a,disabled:n,onClick:()=>t(i.value),className:`flex w-full gap-2 rounded-md border p-2.5 text-left transition-colors disabled:opacity-50 ${a?`border-primary bg-accent/40`:`hover:bg-accent/20`}`,children:[(0,Z.jsx)(o,{className:`mt-0.5 h-4 w-4 shrink-0 ${a?`text-primary`:`text-muted-foreground`}`}),(0,Z.jsxs)(`span`,{className:`min-w-0`,children:[(0,Z.jsx)(`span`,{className:`block text-xs font-medium`,children:i.title}),(0,Z.jsx)(`span`,{className:`mt-0.5 block text-[11px] leading-snug text-muted-foreground`,children:i.blurb}),(0,Z.jsx)(`span`,{className:`mt-1 block font-mono text-[10px] leading-relaxed text-muted-foreground/80`,children:i.tree.map(e=>(0,Z.jsx)(`span`,{className:`block truncate`,children:e},e))})]})]},i.value)})})}function Ib(){let[e,t]=(0,X.useState)(`full`),[n,r]=(0,X.useState)(!1);return(0,X.useEffect)(()=>{let e=!0;return Y.get(`/ping`,{skipAuth:!0}).then(r=>{let i=r?.defaults?.workspaceLayout;e&&!n&&(i===`home`||i===`full`)&&t(i)}).catch(()=>{}),()=>{e=!1}},[]),[e,e=>{r(!0),t(e)}]}function Lb(e){return[...e].sort((e,t)=>{let n=typeof e.order==`number`&&Number.isFinite(e.order)?e.order:2**53-1,r=typeof t.order==`number`&&Number.isFinite(t.order)?t.order:2**53-1;if(n!==r)return n-r;let i=e.createdAt??``,a=t.createdAt??``;return i===a?(e.name??``).localeCompare(t.name??``):i<a?-1:1})}function Rb(e,t,n){let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r}async function zb(e,t){return{failed:(await Promise.allSettled(e.map((e,n)=>e.order===n?Promise.resolve():t(e,n)))).filter(e=>e.status===`rejected`).length}}function Bb(e){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(null);return{rowProps:e=>({"data-reorder-index":e}),handleProps:t=>({onPointerDown:r=>{if(r.pointerType===`mouse`&&r.button!==0)return;r.preventDefault(),r.stopPropagation();let a=r.currentTarget.closest(`[data-reorder-index]`);if(!a)return;let o=a.parentElement,s=(o?[...o.querySelectorAll(`:scope > [data-reorder-index]`)]:[a]).map(e=>({index:Number(e.dataset.reorderIndex),rect:e.getBoundingClientRect()})).filter(e=>Number.isFinite(e.index)).sort((e,t)=>e.index-t.index).map(e=>e.rect.top+e.rect.height/2),c=a.getBoundingClientRect(),l=a.cloneNode(!0);Object.assign(l.style,{position:`fixed`,left:`${c.left}px`,top:`${c.top}px`,width:`${c.width}px`,height:`${c.height}px`,margin:`0`,pointerEvents:`none`,zIndex:`100`,opacity:`0.92`,boxShadow:`0 12px 32px rgba(0,0,0,.28)`,willChange:`transform`}),document.body.appendChild(l);let u={x:r.clientX,y:r.clientY},d=t;n(t),i(t);let f={x:r.clientX,y:r.clientY},p=0,m=()=>{p=0,l.style.transform=`translate(${f.x-u.x}px, ${f.y-u.y}px) scale(1.02)`;let e=s.length;for(let t=0;t<s.length;t++)if(f.y<s[t]){e=t;break}e!==d&&(d=e,i(e))},h=e=>{f={x:e.clientX,y:e.clientY},p||=requestAnimationFrame(m)},g=()=>{window.removeEventListener(`pointermove`,h),window.removeEventListener(`pointerup`,g),window.removeEventListener(`pointercancel`,g),p&&cancelAnimationFrame(p),l.remove(),n(null),i(null),d!==t&&d!==t+1&&e(t,d>t?d-1:d)};window.addEventListener(`pointermove`,h),window.addEventListener(`pointerup`,g),window.addEventListener(`pointercancel`,g)},onClick:e=>{e.preventDefault(),e.stopPropagation()},style:{touchAction:`none`}}),insertIndex:r,draggingIndex:t,insertLineClass:(e,n)=>r===null||t===null?!1:r===e?`shadow-[0_-3px_0_0_var(--color-primary)]`:r===n&&e===n-1&&`shadow-[0_3px_0_0_var(--color-primary)]`}}function Vb(){let[e,t]=(0,X.useState)([]),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(``),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(Nf()),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(``),[_,v]=Ib(),[y,b]=(0,X.useState)(null),[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(!1),[T,E]=Jy(),D=Mb(),[O,k]=(0,X.useState)(!1),[A,j]=(0,X.useState)(!1),[M,N]=(0,X.useState)(!1),[P,ee]=(0,X.useState)(null),{showToast:F}=oo(),I=Gc(),te=Cm(),{openM2Drawer:ne}=Eb(),L=kb();Gy(L,`workspace`,{"workspace:status:changed":e=>t(t=>t.map(t=>t.id===e.workspaceId?{...t,status:e.status}:t)),"workspace:created":e=>t(t=>[...t,e.workspace]),"workspace:deleted":e=>t(t=>t.filter(t=>t.id!==e.workspaceId))}),(0,X.useEffect)(()=>{(async()=>{try{r(!0);let e=await Or();t(Lb(e)),a(null)}catch(e){console.error(`Workspace fetch error:`,e);let t=`Failed to fetch workspaces`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to fetch workspaces`}a(t),F({title:`Error`,description:t,variant:`destructive`})}finally{r(!1)}})()},[L,F]);let re=async e=>{if(e.preventDefault(),o.trim()){w(!0);try{let e=await Na({name:o,description:l||void 0,color:d,icon:p,label:h||o,layout:_});if(t(t=>[...t,e]),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),D.selected.size>0){try{await ii(e.name);let{ok:t,failed:n}=await jb(e.name,Array.from(D.selected),D.tree);n&&F({title:`Folders`,description:`${t} folder(s) created, ${n} failed`,variant:`destructive`})}catch(e){console.error(`Default folder creation failed:`,e),F({title:`Folders`,description:`Workspace created, but default folders failed`,variant:`destructive`})}D.setSelected(new Set)}s(``),u(``),f(Nf()),m(null),g(``),F({title:`Success`,description:`Workspace '${e.label||e.name}' created.`}),E(!1)}catch(e){console.error(`Workspace creation error:`,e);let t=`Failed to create workspace`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to create workspace`}F({title:`Error`,description:t,variant:`destructive`})}finally{w(!1)}}},R=async e=>{if(e.preventDefault(),P)try{let e={label:P.label,description:P.description,color:P.color,icon:P.icon??null};await ja(P.name,e),t(t=>t.map(t=>t.id===P.id?{...t,...e}:t)),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),F({title:`Success`,description:`Workspace '${P.label}' details updated.`}),ee(null)}catch(e){let t=e instanceof Error?e.message:`Failed to update workspace`;F({title:`Error`,description:t,variant:`destructive`})}},ie=e=>{ee(e)},ae=async e=>{try{await Ka(e.name),t(t=>t.filter(t=>t.id!==e.id)),F({title:`Success`,description:`Workspace '${e.label||e.name}' has been destroyed.`})}catch(e){let t=e instanceof Error?e.message:`Failed to destroy workspace`;F({title:`Error`,description:t,variant:`destructive`})}},oe=async e=>{try{let n=await ii(e);t(e=>e.map(e=>e.id===n.id?{...e,...n}:e)),F({title:`Success`,description:`Workspace '${n.label||n.name}' started.`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){console.error(`Workspace start error:`,e);let t=`Failed to start workspace`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to start workspace`}F({title:`Error`,description:t,variant:`destructive`})}},z=async e=>{try{let n=await _r(e);t(e=>e.map(e=>e.id===n.id?{...e,...n}:e)),F({title:`Success`,description:`Workspace '${n.label||n.name}' stopped.`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){console.error(`Workspace stop error:`,e);let t=`Failed to stop workspace`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to stop workspace`}F({title:`Error`,description:t,variant:`destructive`})}},se=e=>{I(tb(e))},{rowProps:ce,handleProps:B,draggingIndex:V,insertLineClass:le}=Bb((n,r)=>{let i=Rb(e,n,r);t(i),zb(i,(e,t)=>ja(zy(e),{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e&&F({title:`Partial reorder`,description:`${e} workspace(s) could not be reordered`,variant:`destructive`})})});return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(By,{title:`Workspaces`,description:`Divide your Universe into self-contained workspaces`,actions:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(J,{variant:`outline`,onClick:()=>k(e=>!e),className:`max-sm:hidden`,children:`Open shared Workspace (local)…`}),(0,Z.jsx)(J,{variant:`outline`,onClick:()=>j(e=>!e),className:`max-sm:hidden`,children:`Import remote…`}),(0,Z.jsx)(J,{variant:`outline`,onClick:()=>N(e=>!e),className:`max-sm:hidden`,children:`Open remote…`}),!T&&(0,Z.jsxs)(J,{onClick:()=>E(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create workspace`,title:`Create workspace`,children:[(0,Z.jsx)(nn,{className:`h-4 w-4 sm:mr-2`}),(0,Z.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Workspace`})]})]})}),T&&(0,Z.jsx)(Ky,{title:`Create New Workspace`,onClose:()=>E(!1),children:(0,Z.jsxs)(`form`,{onSubmit:re,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`Workspace Name (e.g., 'my-project')`,disabled:C}),(0,Z.jsx)(q,{value:h,onChange:e=>g(e.target.value),placeholder:`Workspace Label (display name, optional)`,disabled:C})]}),(0,Z.jsx)(q,{value:l,onChange:e=>u(e.target.value),placeholder:`Description (optional)`,disabled:C}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{htmlFor:`workspace-color`,className:`text-sm font-medium`,children:`Icon & Color`}),(0,Z.jsx)(`button`,{type:`button`,title:`Pick icon & color`,disabled:C,onClick:e=>b({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360)}),className:`flex h-10 w-10 items-center justify-center rounded-md border hover:bg-accent`,children:(0,Z.jsx)(c,{icon:p||`ph:stack-fill`,width:22,height:22,color:If(d)})}),(0,Z.jsx)(q,{id:`workspace-color`,type:`color`,value:d,onChange:e=>f(e.target.value),className:`h-10 w-16 p-1`,disabled:C}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>f(Nf()),disabled:C,children:`Randomize`})]}),y&&(0,Z.jsx)(Wy,{x:y.x,y:y.y,current:{icon:p??void 0,color:d},onChange:e=>{`icon`in e&&m(e.icon??null),`color`in e&&e.color&&f(e.color)},onClose:()=>b(null)}),(0,Z.jsxs)(`div`,{className:`rounded-lg border p-3`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:`Folder structure`}),(0,Z.jsx)(`p`,{className:`mb-3 mt-0.5 text-xs text-muted-foreground`,children:`How the workspace directory is laid out on disk. Fixed once created.`}),(0,Z.jsx)(Fb,{value:_,onChange:v,disabled:C,idPrefix:`create-workspace-layout`})]}),(0,Z.jsxs)(`div`,{className:`rounded-lg border p-3`,children:[(0,Z.jsxs)(`p`,{className:`text-sm font-medium`,children:[`Default folders `,(0,Z.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional)`})]}),(0,Z.jsx)(`p`,{className:`mb-3 mt-0.5 text-xs text-muted-foreground`,children:`Ticked folders are created right after the workspace, with matching icons and colors.`}),(0,Z.jsx)(Nb,{selected:D.selected,onToggle:D.toggle,tree:D.tree,onTreeChange:D.setTree,disabled:C,idPrefix:`create-default-folders`})]}),(0,Z.jsxs)(J,{type:`submit`,disabled:C||!o.trim(),children:[(0,Z.jsx)(nn,{className:`mr-2 h-4 w-4`}),`Create Workspace`]})]})}),O&&(0,Z.jsx)(Ub,{}),M&&(0,Z.jsx)(Wb,{onClose:()=>N(!1),onChanged:async()=>{try{t(Lb(await Or()))}catch{}window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}}),A&&(0,Z.jsx)(Hb,{onImported:e=>{t(t=>t.some(t=>t.id===e.id)?t:[...t,e]),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),j(!1)},onClose:()=>j(!1)}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Workspaces`}),n&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading workspaces...`}),i&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:i})}),!n&&!i&&e.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No workspaces found`}),e.length>0&&(0,Z.jsx)(`div`,{className:`grid gap-4`,children:e.map((t,n)=>{let r={...t,createdAt:t.createdAt,updatedAt:t.updatedAt,color:t.color===null?void 0:t.color},i=If(t.color);return(0,Z.jsxs)(`div`,{...ce(n),className:`flex items-stretch rounded-lg ${le(n,e.length)||``} ${V===n?`opacity-60`:``}`,children:[(0,Z.jsx)(`button`,{type:`button`,...B(n),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:`hidden w-5 shrink-0 cursor-grab items-center justify-center rounded-l-lg active:cursor-grabbing md:flex ${i?``:`bg-muted`}`,style:i?{backgroundColor:i}:void 0,children:(0,Z.jsx)(lr,{className:`h-4 w-4 ${Lf(i)}`})}),(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,Z.jsx)(qy,{workspace:r,onStart:oe,onStop:z,onEnter:se,onEdit:ie,onSettings:e=>{te?ne(`workspaces`,`settings`,zy(e)):I(`/workspaces/${zy(e)}/settings/general`)},onDestroy:ae})})]},t.id)})})]}),P&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`h2`,{className:`text-xl font-semibold`,children:[`Edit Workspace: `,P.label]}),(0,Z.jsxs)(`form`,{onSubmit:R,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-label`,className:`text-sm font-medium`,children:`Label`}),(0,Z.jsx)(q,{id:`edit-label`,value:P.label,onChange:e=>ee(t=>t?{...t,label:e.target.value}:null),placeholder:`Workspace Label`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-description`,className:`text-sm font-medium`,children:`Description`}),(0,Z.jsx)(q,{id:`edit-description`,value:P.description||``,onChange:e=>ee(t=>t?{...t,description:e.target.value}:null),placeholder:`Description (optional)`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-color`,className:`text-sm font-medium`,children:`Icon & Color`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`button`,{type:`button`,title:`Pick icon & color`,onClick:e=>S({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360)}),className:`flex h-10 w-10 items-center justify-center rounded-md border hover:bg-accent`,children:(0,Z.jsx)(c,{icon:P.icon||`ph:stack-fill`,width:22,height:22,color:If(P.color)})}),(0,Z.jsx)(q,{id:`edit-workspace-color`,type:`color`,value:P.color||`#FFFFFF`,onChange:e=>ee(t=>t?{...t,color:e.target.value}:null),className:`h-10 w-16 p-1`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>ee(e=>e?{...e,color:Nf()}:null),children:`Randomize Color`})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(J,{type:`submit`,disabled:!P.label?.trim(),children:`Save Changes`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>ee(null),children:`Cancel`})]})]}),x&&(0,Z.jsx)(Wy,{x:x.x,y:x.y,current:{icon:P.icon??void 0,color:P.color??void 0},onChange:e=>{ee(t=>{if(!t)return null;let n={...t};return`icon`in e&&(n.icon=e.icon??null),`color`in e&&e.color&&(n.color=e.color),n})},onClose:()=>S(null)})]})]})}function Hb({onImported:e,onClose:t}){let{showToast:n}=oo(),[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(``);return(0,Z.jsx)(Ky,{title:`Import (pull) a remote Workspace`,onClose:t,children:(0,Z.jsxs)(`form`,{onSubmit:async t=>{t.preventDefault();let i;try{i=new URL(r.trim()).origin}catch{n({title:`Error`,description:`Invalid server URL`,variant:`destructive`});return}if(!a.trim().startsWith(`canvas-`)){n({title:`Error`,description:`Invalid access token (expected canvas-...)`,variant:`destructive`});return}c(!0),u(`Starting…`);try{let t=await Ea(i,a.trim(),e=>{u(ua[e.phase]||e.phase)});n({title:`Success`,description:`Workspace '${t.label||t.name}' imported from ${i}.`}),e(t)}catch(e){let t=e,r=t?.message||t?.payload?.message||`Failed to import remote workspace`;n({title:`Error`,description:r,variant:`destructive`})}finally{c(!1),u(``)}},className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{placeholder:`Server URL (e.g., https://my.canvas-server.tld)`,value:r,onChange:e=>i(e.target.value),disabled:s}),(0,Z.jsx)(q,{placeholder:`Workspace share token (canvas-...)`,value:a,onChange:e=>o(e.target.value),disabled:s}),(0,Z.jsx)(J,{type:`submit`,disabled:s||!r.trim()||!a.trim(),children:s?`Importing…`:`Import Workspace`})]}),s&&l&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:l}),(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Pulls a full `,(0,Z.jsx)(`strong`,{children:`copy`}),` of the workspace from the remote canvas-server into this one, where it then lives independently. The remote workspace is stopped while it is packed, and large workspaces can take several minutes — progress is shown above.`]})]})})}function Ub(){let{showToast:e}=oo(),[t,n]=(0,X.useState)(``),[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(!1),s=e=>{try{return new URL(e)}catch{return null}};return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Open shared Workspace (local)`}),(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{placeholder:`Shared URL (e.g., https://host/rest/v2/pub/workspaces/ID)`,value:t,onChange:e=>n(e.target.value)}),(0,Z.jsx)(q,{placeholder:`Access token (canvas-...)`,value:r,onChange:e=>i(e.target.value)}),(0,Z.jsx)(J,{onClick:async()=>{if(!s(t.trim())){e({title:`Error`,description:`Invalid URL`,variant:`destructive`});return}if(!r.trim().startsWith(`canvas-`)){e({title:`Error`,description:`Invalid access token`,variant:`destructive`});return}o(!0);try{sessionStorage.setItem(`sharedToken:last`,r.trim());let e=new URLSearchParams({url:t.trim()}).toString();window.location.href=`/shared?${e}`}catch(t){e({title:`Error`,description:t instanceof Error?t.message:`Failed to open shared resource`,variant:`destructive`})}finally{o(!1)}},disabled:a||!t.trim()||!r.trim(),children:`Open`})]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`We use your provided URL and token to fetch via the remote's public API.`})]})}function Wb({onClose:e,onChanged:t}){let{showToast:n}=oo(),r=Gc(),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)([]),f=(0,X.useCallback)(async()=>{try{d(await la())}catch{d([])}},[]);(0,X.useEffect)(()=>{f()},[f]);let p=async e=>{e.preventDefault();let r;try{r=new URL(i.trim()).origin}catch{n({title:`Error`,description:`Invalid server URL`,variant:`destructive`});return}l(!0);try{let e=await pa(r,o.trim());n({title:`Remote workspace added`,description:`'${e.label}' is available as ${e.address}.`}),a(``),s(``),await f(),t?.()}catch(e){let t=e;n({title:`Error`,description:t?.message||t?.payload?.message||`Failed to add remote workspace`,variant:`destructive`})}finally{l(!1)}},m=async e=>{try{await oi(e.id),await f(),t?.()}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to remove remote workspace`,variant:`destructive`})}};return(0,Z.jsxs)(Ky,{title:`Open a remote Workspace`,onClose:e,children:[(0,Z.jsxs)(`form`,{onSubmit:p,className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{placeholder:`Server URL (e.g., https://my.canvas-server.tld)`,value:i,onChange:e=>a(e.target.value),disabled:c}),(0,Z.jsx)(q,{placeholder:`Workspace share token (canvas-...)`,value:o,onChange:e=>s(e.target.value),disabled:c}),(0,Z.jsx)(J,{type:`submit`,disabled:c||!i.trim()||!o.trim(),children:c?`Checking…`:`Add Remote`})]}),(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Keeps the workspace on its own server and registers it here as`,` `,(0,Z.jsx)(`code`,{className:`font-mono text-xs`,children:`name@host`}),` — nothing is copied. Every call you make to it is forwarded to the remote with the share token (its permissions apply); document content and thumbnails are cached locally so they stay readable when the remote is offline. Use “Import remote…” if you want an independent local copy instead.`]})]}),u.length>0&&(0,Z.jsx)(`ul`,{className:`mt-4 space-y-2 border-t pt-3`,children:u.map(e=>(0,Z.jsxs)(`li`,{className:`flex flex-col gap-2 rounded-md border p-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`truncate text-sm font-medium`,children:[e.label,(0,Z.jsx)(`span`,{className:`ml-2 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`remote`})]}),(0,Z.jsxs)(`div`,{className:`mt-0.5 truncate font-mono text-[11px] text-muted-foreground`,children:[e.address,` · `,e.remote.url]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>r(`/workspaces/${e.address}`),children:`Open`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>m(e),className:`text-destructive hover:text-destructive`,children:`Remove`})]})]},e.id))})]})}function Gb({workspaceName:e,children:t}){let n=e,[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(0);return(0,X.useEffect)(()=>{let t=!1,r=0,a,s=async()=>{let s=++r;try{let c=await vi(e);!t&&s===r&&(a=c.id,i({identity:n,active:c.status===`active`}),o(``))}catch(e){!t&&s===r&&(i({identity:n,active:!1}),o(e instanceof Error?e.message:`Unable to check workspace status`))}},c=t=>{let o=t.detail?.refs;!o?.includes(e)&&!(a&&o?.includes(a))||(r++,i({identity:n,active:!1}))};s(),window.addEventListener(`workspaces:refresh`,s),window.addEventListener(`workspace:stopped`,c),window.addEventListener(`focus`,s);let l=window.setInterval(s,5e3);return()=>{t=!0,window.clearInterval(l),window.removeEventListener(`workspaces:refresh`,s),window.removeEventListener(`workspace:stopped`,c),window.removeEventListener(`focus`,s)}},[e,n,l]),r?.identity===n?r.active?t:(0,Z.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,Z.jsx)(`p`,{className:`font-medium`,children:`Workspace stopped`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Start this workspace to view its content.`}),a&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,Z.jsx)(J,{disabled:s,onClick:async()=>{c(!0),o(``);try{await ii(e),u(e=>e+1)}catch(e){o(e instanceof Error?e.message:`Unable to start workspace`)}finally{c(!1)}},children:s?`Starting…`:`Start workspace`}),(0,Z.jsx)(cu,{className:`text-sm underline`,to:`/workspaces/${encodeURIComponent(e)}/settings`,children:`Workspace settings`})]}):(0,Z.jsx)(`p`,{className:`p-6 text-sm text-muted-foreground`,children:`Checking workspace…`})}function Kb({workspaceId:e,workspaceName:t}){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(new Set),o=t=>`${e}:${t.address}:${t.resyncStartedAt||``}`;(0,X.useEffect)(()=>{let t=!1,n=!1,i=!1,a=async()=>{if(n){i=!0;return}n=!0;try{let n=await va(e);t||r(n.filter(e=>e.resyncing))}catch{}finally{n=!1,i&&!t&&(i=!1,a())}},o=t=>{t.workspaceId===e&&a()};a();let s=setInterval(()=>{a()},3e3);return Wu.on(`backend.resync.changed`,o),()=>{t=!0,clearInterval(s),Wu.off(`backend.resync.changed`,o)}},[e]);let s=n.filter(e=>!i.has(o(e)));return s.length?(0,Z.jsxs)(`aside`,{"aria-label":`Storage scans for ${t}`,className:`absolute bottom-5 right-5 z-50 w-72 max-w-[calc(100vw-2.5rem)] rounded-lg border bg-popover/95 p-3 text-popover-foreground shadow-lg backdrop-blur`,children:[(0,Z.jsxs)(`div`,{role:`status`,className:`mb-2 flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(Wn,{"aria-hidden":`true`,className:`h-4 w-4 animate-spin`}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block`,children:`Scanning storage`}),(0,Z.jsx)(`span`,{className:`block truncate text-xs font-normal text-muted-foreground`,title:t,children:t})]}),(0,Z.jsx)(`button`,{type:`button`,"aria-label":`Hide scan progress for ${t}`,title:`Hide progress; scanning continues`,className:`rounded p-1 hover:bg-muted focus-visible:outline focus-visible:outline-2`,onClick:()=>a(e=>new Set([...e,...s.map(o)])),children:(0,Z.jsx)(je,{"aria-hidden":`true`,className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{className:`max-h-48 space-y-3 overflow-y-auto`,children:s.map(e=>{let{scanned:t=0,total:n=null}=e.progress||{},r=n&&n>0?Math.min(100,Math.round(t/n*100)):null,i=typeof e.config?.label==`string`?e.config.label:e.address;return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-xs`,children:[(0,Z.jsx)(`span`,{className:`truncate`,children:i}),(0,Z.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:n===null?`${t} files`:`${t} / ${n}`})]}),(0,Z.jsx)(`div`,{role:`progressbar`,"aria-label":`Scanning ${i}`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":r??void 0,className:`mt-1.5 h-1 overflow-hidden rounded-full bg-muted`,children:(0,Z.jsx)(`div`,{className:`h-full rounded-full bg-primary ${r===null?`animate-pulse`:`transition-all`}`,style:{width:r===null?`35%`:`${r}%`}})})]},e.address)})})]}):null}function qb(){let{openAddPicker:e}=hs();return(0,Z.jsx)(`button`,{type:`button`,onClick:e,title:`Add here`,"aria-label":`Add`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-full bg-foreground text-background hover:opacity-90 transition-opacity`,children:(0,Z.jsx)(nn,{className:`w-4 h-4`})})}function Jb({count:e}){return e<=0?null:(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>window.dispatchEvent(new CustomEvent(`workspace:documents:link-selection`)),title:`Link ${e} selected document(s) to…`,"aria-label":`Link selection`,className:`shrink-0 flex items-center justify-center gap-1 h-7 min-w-7 rounded-full bg-info px-1.5 text-info-foreground hover:bg-info transition-colors touch-target`,children:[(0,Z.jsx)(qt,{className:`w-3.5 h-3.5`}),(0,Z.jsx)(`span`,{className:`text-[11px] font-semibold leading-none`,children:e})]})}function Yb({urlType:e,urlDisplay:t,onUrlClick:n,onUrlSubmit:r}){let i=t.match(/^(.*?:\/\/)(.*)$/),a=i?.[1]??``,o=i?.[2]??t,s=(0,X.useRef)(null);(0,X.useEffect)(()=>{s.current&&(s.current.value=o)},[o]);let c=(0,Z.jsxs)(`span`,{className:`font-mono text-xs px-1.5 py-0.5 rounded bg-muted border text-muted-foreground shrink-0`,children:[`[`,e.replace(`-`,`:`),`]`]}),l=n?(0,Z.jsxs)(`button`,{type:`button`,onClick:n,title:`Browse tree`,"aria-label":`Browse tree`,className:`shrink-0 flex items-center gap-1 rounded hover:opacity-80 transition-opacity`,children:[(0,Z.jsx)(L,{className:`w-3.5 h-3.5 text-muted-foreground`}),c]}):c;return r?(0,Z.jsxs)(`div`,{className:`flex h-9 min-w-0 flex-1 items-center gap-2 rounded-full border border-transparent bg-muted/60 px-3 transition-colors hover:bg-muted focus-within:border-border focus-within:bg-background focus-within:shadow-elevation-1`,children:[l,(0,Z.jsxs)(`form`,{className:`flex flex-1 min-w-0 items-center`,onSubmit:e=>{e.preventDefault(),r(s.current?.value??o)},children:[a&&(0,Z.jsx)(`span`,{className:`shrink-0 font-mono text-sm text-muted-foreground select-none`,children:a}),(0,Z.jsx)(`input`,{ref:s,type:`text`,defaultValue:o,onKeyDown:e=>{e.key===`Escape`&&s.current&&(s.current.value=o)},spellCheck:!1,autoComplete:`off`,title:`Edit path; press Enter to go`,className:`w-full min-w-0 flex-1 truncate bg-transparent px-1 py-1 font-mono text-sm text-foreground focus:outline-none`})]})]}):(0,Z.jsxs)(`div`,{className:`flex h-9 min-w-0 flex-1 items-center gap-2 rounded-full bg-muted/60 px-3`,children:[l,n?(0,Z.jsx)(`button`,{type:`button`,onClick:n,title:`Browse tree`,className:`flex-1 truncate rounded px-1 -mx-1 text-left text-sm text-foreground transition-colors hover:bg-accent active:bg-accent`,children:t}):(0,Z.jsx)(`span`,{className:`text-sm text-foreground truncate flex-1`,children:t})]})}function Xb({urlType:e,urlDisplay:t,contextPath:n,treeName:r,workspaceId:i,documents:a,isLoading:o,totalCount:s,currentPage:c,pageSize:l,onPageChange:u,onPageSizeChange:d,onRemoveDocument:f,onDeleteDocument:p,onDestroyDocument:m,onRemoveDocuments:h,onDeleteDocuments:g,onDestroyDocuments:_,onCopyDocuments:v,onCutDocuments:y,onPasteDocuments:b,onImportDocuments:x,onSelectionChange:S,pastedDocumentIds:C,onPurgeDocuments:w,disablePurgeDocuments:T,canvasInfo:E,isCanvasPinned:D,onTogglePinCanvas:O,onSaveAsCanvas:k,onShareCanvas:A,onUnshareCanvas:j,onDeleteCanvas:M,isSharingCanvas:N,isDeletingCanvas:P,isCanvasShared:ee,isCanvasLocked:F,backendSearchQueries:I,onBackendSearch:ne,onRemoveBackendQuery:L,serverSort:re,onServerSortChange:R,scope:ie,onScopeChange:ae,canSaveChanges:oe,isSavingChanges:z,onSaveChanges:se,onUrlClick:ce,onUrlSubmit:B,linkTree:V,selectedCount:le=0,children:ue,contentBanner:de,folders:fe,onOpenFolder:me}){let H=e===`canvas`;return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full min-h-0 bg-background`,children:[H&&E?(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 px-4 py-2.5 border-b bg-muted/20 shrink-0 min-w-0`,children:[E.color&&(0,Z.jsx)(`div`,{className:`w-1 h-6 rounded-full shrink-0`,style:{backgroundColor:E.color}}),(0,Z.jsx)(mt,{className:`w-4 h-4 shrink-0 text-primary`}),(0,Z.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`text-lg font-semibold leading-tight truncate`,children:E.label||t.split(`://`)[1]||`Canvas`}),E.description&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground truncate leading-tight`,children:E.description})]}),oe&&se&&(0,Z.jsxs)(`button`,{type:`button`,onClick:se,disabled:z,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground disabled:opacity-50`,title:`Save filters`,children:[(0,Z.jsx)(Re,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:z?`Saving...`:`Save filters`})]}),O&&(0,Z.jsxs)(`button`,{type:`button`,onClick:O,"aria-pressed":!!D,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground`,title:D?`Unpin from home`:`Pin to home`,children:[D?(0,Z.jsx)(te,{className:`w-3 h-3`}):(0,Z.jsx)(De,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:D?`Unpin`:`Pin`})]}),A&&(0,Z.jsxs)(`button`,{type:`button`,onClick:A,disabled:N||P,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground disabled:opacity-50`,title:ee?`Copy public link`:`Share canvas`,children:[(0,Z.jsx)(Tn,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:N?`Sharing...`:ee?`Copy link`:`Share`})]}),ee&&j&&(0,Z.jsxs)(`button`,{type:`button`,onClick:j,disabled:N||P,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-destructive/10 transition-colors text-muted-foreground hover:text-destructive disabled:opacity-50`,children:[(0,Z.jsx)(pe,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:`Unshare`})]}),M&&(0,Z.jsxs)(`button`,{type:`button`,onClick:M,disabled:P||F&&!ee,title:F&&!ee?`Unlock this canvas before deleting it`:`Delete canvas`,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-destructive/10 transition-colors text-muted-foreground hover:text-destructive disabled:opacity-50`,children:[(0,Z.jsx)(lt,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:P?`Deleting…`:`Delete`})]}),(0,Z.jsx)(Jb,{count:le}),(0,Z.jsx)(qb,{})]}):(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-4 py-2.5 border-b bg-muted/20 shrink-0`,children:[(0,Z.jsx)(Yb,{urlType:e,urlDisplay:t,onUrlClick:ce,onUrlSubmit:B}),k&&(0,Z.jsxs)(`button`,{type:`button`,onClick:k,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground`,title:`Save as canvas`,children:[(0,Z.jsx)(dt,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:`Save as canvas`})]}),(0,Z.jsx)(Jb,{count:le}),(0,Z.jsx)(qb,{})]}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:[de,ue||(0,Z.jsx)(D_,{documents:a,isLoading:o,folders:fe,onOpenFolder:me,contextPath:n,treeName:r,workspaceId:i,totalCount:s,viewMode:`table`,allowViewToggle:!0,currentPage:c,pageSize:l,onPageChange:u,onPageSizeChange:d,onRemoveDocument:f,onDeleteDocument:p,onDestroyDocument:m,onRemoveDocuments:h,onDeleteDocuments:g,onDestroyDocuments:_,onCopyDocuments:v,onCutDocuments:y,onPasteDocuments:b,onImportDocuments:x,onSelectionChange:S,pastedDocumentIds:C,onPurgeDocuments:w,disablePurgeDocuments:T,backendSearchQueries:I,onBackendSearch:ne,serverSort:re,onServerSortChange:R,onRemoveBackendQuery:L,scope:ie,onScopeChange:ae,canSaveChanges:!H&&oe,isSavingChanges:z,onSaveChanges:se,linkTree:V})]})]})}var Zb=[{id:`todos`,label:`Todos`},{id:`notes`,label:`Notes`}],Qb={id:`default`,name:`All`,kind:`documents`};function $b(){return[{id:`emails`,label:`Emails`,schemas:[`data/schema/message`]},{id:`todos`,label:`Todos`,schemas:[`data/schema/task`]},{id:`notes`,label:`Notes`,schemas:[`data/schema/note`]},{id:`links`,label:`Links`,schemas:[`data/schema/tab`,`data/schema/link`]},{id:`files`,label:`Files`,schemas:[`data/schema/file`]}]}function ex(e){let t=e?.views;if(!Array.isArray(t))return[Qb];let n=t.filter(e=>{let t=e;return!t||typeof t.id!=`string`||typeof t.name!=`string`?!1:t.kind===`documents`||t.kind===`columns`||t.kind===`app`&&Zb.some(e=>e.id===t.app)});return n.length>0?n:[Qb]}function tx({views:e,activeId:t,onSelect:n,onSave:r,readOnly:i=!1,className:a,accentColor:o,onOpenToSide:s}){let c=o?(Pf(o)??0)>.5?`text-black`:`text-white`:``,[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(null),y=()=>{g(null),v(null)},b=()=>{if(h&&_&&h!==_.id){let t=e.find(e=>e.id===h),n=e.filter(e=>e.id!==h),i=n.findIndex(e=>e.id===_.id);t&&i>=0&&(n.splice(_.before?i:i+1,0,t),n.some((t,n)=>t.id!==e[n].id)&&r(n))}y()},x=()=>{if(!l)return;let t=d.trim();t&&r(e.map(e=>e.id===l?{...e,name:t}:e)),u(null)},S=(t,n)=>{m(!1);let i=`view-${Date.now().toString(36)}`,a=t===`columns`?`Board`:t===`app`?Zb.find(e=>e.id===n)?.label??`App`:`View ${e.length+1}`,o=t===`columns`?{id:i,name:a,kind:t,columns:$b()}:t===`app`?{id:i,name:a,kind:t,app:n}:{id:i,name:a,kind:t};r([...e,o],i),u(i),f(a)},C=n=>{let i=e.filter(e=>e.id!==n);r(i.length>0?i:[Qb],n===t?i[0]?.id??Qb.id:void 0)};return(0,Z.jsxs)(`div`,{className:K(`flex min-w-0 items-end`,a),children:[(0,Z.jsx)(`div`,{className:`flex min-w-0 items-end gap-0.5 overflow-x-auto pt-1`,children:e.map(r=>{let a=r.id===t;return l===r.id?(0,Z.jsx)(`input`,{autoFocus:!0,value:d,onChange:e=>f(e.target.value),onBlur:x,onKeyDown:e=>{e.key===`Enter`&&x(),e.key===`Escape`&&u(null)},className:`relative z-[1] h-8 w-28 rounded-t-md border border-b-0 border-input bg-background px-2 text-xs focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`},r.id):(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>n(r.id),onDoubleClick:()=>{i||(u(r.id),f(r.name))},title:i?r.name:`${r.name}: double-click to rename, drag to reorder`,draggable:!i,onDragStart:e=>{e.dataTransfer.setData(`text/plain`,r.name),e.dataTransfer.effectAllowed=`move`,g(r.id)},onDragOver:e=>{if(!h||h===r.id)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let t=e.currentTarget.getBoundingClientRect(),n=e.clientX<t.left+t.width/2;v(e=>e?.id===r.id&&e.before===n?e:{id:r.id,before:n})},onDrop:e=>{e.preventDefault(),b()},onDragEnd:y,className:K(`group flex h-8 shrink-0 items-center gap-1.5 rounded-t-md px-3 text-xs transition-colors`,a?K(`relative z-[1] border border-b-0 font-medium`,o?c:`border-border bg-background text-foreground`):`mb-[3px] border border-b-0 border-transparent bg-muted/40 text-muted-foreground hover:bg-accent/60 hover:text-foreground`,h===r.id&&`opacity-50`,_?.id===r.id&&(_.before?`border-l-2 border-l-primary`:`border-r-2 border-r-primary`)),style:a&&o?{backgroundColor:o,..._?.id===r.id?{}:{borderColor:o}}:void 0,children:[r.kind===`columns`?(0,Z.jsx)(nr,{className:`h-3 w-3 shrink-0`}):r.kind===`app`?r.app===`todos`?(0,Z.jsx)(zt,{className:`h-3 w-3 shrink-0`}):(0,Z.jsx)(vn,{className:`h-3 w-3 shrink-0`}):(0,Z.jsx)(Ut,{className:`h-3 w-3 shrink-0`}),(0,Z.jsx)(`span`,{className:`max-w-32 truncate`,children:r.name}),s&&(0,Z.jsx)(Xe,{className:`h-3 w-3 shrink-0 opacity-0 transition-opacity hover:opacity-100 group-hover:opacity-60`,"aria-label":`Open to the side`,onClick:e=>{e.stopPropagation(),s(r.id)}}),!i&&e.length>1&&(0,Z.jsx)(je,{className:K(`h-3 w-3 shrink-0 transition-opacity hover:text-destructive`,a?`opacity-60 hover:opacity-100`:`opacity-0 group-hover:opacity-100`),onClick:e=>{e.stopPropagation(),C(r.id)}})]},r.id)})}),!i&&(p?(0,Z.jsxs)(`span`,{className:`relative z-[1] mb-1.5 ml-1 flex shrink-0 items-center gap-1`,children:[!e.some(e=>e.id===Qb.id)&&(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>{m(!1),r([{...Qb},...e],Qb.id)},className:`flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,Z.jsx)(Ut,{className:`h-3 w-3`}),` All`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>S(`documents`),className:`flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,Z.jsx)(Ut,{className:`h-3 w-3`}),` List`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>S(`columns`),className:`flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,Z.jsx)(nr,{className:`h-3 w-3`}),` Board`]}),Zb.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>S(`app`,e.id),className:`flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[e.id===`todos`?(0,Z.jsx)(zt,{className:`h-3 w-3`}):(0,Z.jsx)(vn,{className:`h-3 w-3`}),` `,e.label]},e.id)),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>m(!1),className:`p-1 text-muted-foreground hover:text-foreground`,"aria-label":`Cancel`,children:(0,Z.jsx)(je,{className:`h-3 w-3`})})]}):(0,Z.jsx)(`button`,{type:`button`,onClick:()=>m(!0),title:`Add view`,"aria-label":`Add view`,className:`relative z-[1] mb-1.5 ml-1 flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:(0,Z.jsx)(nn,{className:`h-3.5 w-3.5`})}))]})}var nx=`data/schema/note`;function rx(e,t,n,r,i){let a=`${e}\0${t}\0${n}\0${r}\0${i??``}`,[o,s]=(0,X.useState)(0),[c,l]=(0,X.useState)(null);(0,X.useEffect)(()=>{let o=!1;return gi(e,n,t,{limit:200,allOf:[r],...i?{sortBy:i,order:`asc`}:{}}).then(e=>{o||l({key:a,docs:e.payload||[]})}).catch(()=>{o||l({key:a,docs:[]})}),()=>{o=!0}},[a,o]);let u=c?.key===a?c.docs:[],d=c?.key!==a;return(0,X.useEffect)(()=>{let e=()=>s(e=>e+1);return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[]),{docs:u,isLoading:d,refresh:(0,X.useCallback)(()=>s(e=>e+1),[])}}function ix({workspaceId:e,treeName:t,path:n}){let{docs:r,isLoading:i,refresh:a}=rx(e,t,n,io,`tasks`),[o,s]=(0,X.useState)(!1),c=o?r.filter(e=>e.data?.status!==`completed`):r,l=r.filter(e=>{let t=e.data?.status;return t!==`completed`&&t!==`cancelled`}).length;return(0,Z.jsxs)(`div`,{className:`mx-auto flex h-full w-full max-w-3xl flex-col p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-2 flex shrink-0 items-center justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[l,` open`]}),(0,Z.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:o,onChange:e=>s(e.target.checked)}),`hide done`]})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1 overflow-y-auto`,children:i?(0,Z.jsx)(`p`,{className:`py-4 text-sm text-muted-foreground`,children:`Loading…`}):c.length===0?(0,Z.jsx)(`p`,{className:`py-4 text-sm text-muted-foreground`,children:`No todos here.`}):c.map(t=>(0,Z.jsx)(ev,{doc:t,workspaceId:e,readOnly:!1,onChanged:a},t.id))})]})}function ax({workspaceId:e,treeName:t,path:n}){let{docs:r,isLoading:i}=rx(e,t,n,nx);return(0,Z.jsx)(`div`,{className:`h-full overflow-y-auto p-4`,children:(0,Z.jsx)(D_,{documents:r,isLoading:i,contextPath:n,treeName:t,workspaceId:e,totalCount:r.length,viewMode:`card`})})}function ox({app:e,...t}){return e===`todos`?(0,Z.jsx)(ix,{...t}):(0,Z.jsx)(ax,{...t})}var sx=[{id:`emails`,label:`Emails`,schemas:[`data/schema/message`]},{id:`todos`,label:`Todos`,schemas:[`data/schema/task`]},{id:`notes`,label:`Notes`,schemas:[`data/schema/note`]},{id:`links`,label:`Links`,schemas:[`data/schema/tab`,`data/schema/link`]},{id:`files`,label:`Files`,schemas:[`data/schema/file`]}];function cx(e,t){return t.some(t=>e.schema===t||e.schema.startsWith(`${t}/`))}function lx({documents:e,workspaceId:t,columns:n,onColumnsChange:r,readOnly:i=!1}){let[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)({}),[d,f]=(0,X.useState)({}),p=(0,X.useRef)(null),[m,h]=(0,X.useState)(!1),g=(0,X.useCallback)(()=>{let e=p.current;e&&h(e.scrollWidth-e.clientWidth-e.scrollLeft>8)},[]);(0,X.useEffect)(()=>{let e=p.current;if(!e)return;let t=new ResizeObserver(()=>g());return t.observe(e),()=>t.disconnect()},[g]);let _=(e,t)=>{e.preventDefault();let i=e.currentTarget.parentElement;if(!i)return;let a=e.clientX,o=i.getBoundingClientRect().width,s=o,c=e=>{s=Math.min(900,Math.max(220,o+e.clientX-a)),f(e=>({...e,[t]:s}))},l=()=>{window.removeEventListener(`pointermove`,c),window.removeEventListener(`pointerup`,l),r(n.map(e=>e.id===t?{...e,width:Math.round(s)}:e))};window.addEventListener(`pointermove`,c),window.addEventListener(`pointerup`,l)},v=e=>{f(t=>{let n={...t};return delete n[e],n}),r(n.map(t=>t.id===e?{...t,width:void 0}:t))},y=e=>{let t=l[e];if(t===void 0)return;let i=n.find(t=>t.id===e);i&&(i.filter||``)!==t&&r(n.map(n=>n.id===e?{...n,filter:t||void 0}:n))},b=sx.filter(e=>!n.some(t=>t.id===e.id));return(0,Z.jsxs)(`div`,{className:`relative h-full`,children:[(0,Z.jsx)(`div`,{ref:p,onScroll:g,className:`flex h-full snap-x snap-mandatory gap-3 overflow-x-auto overscroll-x-contain p-2`,"data-testid":`schema-columns-board`,children:n.map(t=>{let a=(l[t.id]??t.filter??``).toLowerCase(),s=e.filter(e=>cx(e,t.schemas)).filter(e=>{if(!a)return!0;let t=mo(e);return`${t.title}\n${t.preview}\n${t.subtitle}`.toLowerCase().includes(a)}),c=d[t.id]??t.width;return(0,Z.jsxs)(`div`,{className:`relative flex h-full min-h-0 min-w-0 shrink-0 grow-0 basis-full snap-start flex-col rounded-lg border bg-muted/20 ${c?`sm:basis-[var(--col-w)]`:`sm:basis-[48%] lg:basis-[32%] xl:basis-[24%]`}`,style:c?{"--col-w":`${c}px`}:void 0,children:[!i&&(0,Z.jsx)(`div`,{onPointerDown:e=>_(e,t.id),onDoubleClick:()=>v(t.id),title:`Drag to resize; double-click to reset`,className:`absolute right-0 inset-y-0 z-10 w-2 cursor-col-resize touch-none rounded-r-lg transition-colors hover:bg-primary/25 active:bg-primary/40 max-sm:hidden`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-3 pb-1 pt-2.5 max-sm:pr-10`,children:[(0,Z.jsx)(`span`,{className:`truncate text-sm font-medium`,children:t.label}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:s.length}),(0,Z.jsx)(`span`,{className:`flex-1`}),!i&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(n.filter(e=>e.id!==t.id)),title:`Remove column`,className:`rounded-sm p-0.5 text-muted-foreground hover:text-destructive`,children:(0,Z.jsx)(je,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsx)(`div`,{className:`px-3 pb-2`,children:(0,Z.jsx)(`input`,{value:l[t.id]??t.filter??``,onChange:e=>u(n=>({...n,[t.id]:e.target.value})),onBlur:()=>y(t.id),onKeyDown:e=>{e.key===`Enter`&&y(t.id)},placeholder:`Filter…`,readOnly:i,className:`h-7 w-full rounded-md border border-input bg-background px-2 text-xs placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})}),(0,Z.jsxs)(`div`,{className:`flex-1 space-y-1.5 overflow-y-auto px-2 pb-2`,children:[s.map(e=>{let t=mo(e);return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>o(e),className:`w-full min-w-0 rounded-md border bg-card px-2.5 py-2 text-left transition-colors hover:bg-accent/50`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(Jf,{document:e,size:3.5}),(0,Z.jsx)(`span`,{className:`truncate text-xs font-medium`,title:t.title,children:t.title})]}),t.preview&&(0,Z.jsx)(`p`,{className:`mt-1 line-clamp-2 break-words text-[11px] leading-snug text-muted-foreground`,children:t.preview}),(0,Z.jsx)(`p`,{className:`mt-1 text-[10px] text-muted-foreground/70`,children:new Date(e.updatedAt||e.createdAt).toLocaleDateString()})]},e.id)}),s.length===0&&(0,Z.jsx)(`p`,{className:`px-2 py-3 text-center text-xs text-muted-foreground/60`,children:`Empty`})]})]},t.id)})}),(!i&&b.length>0||m)&&(0,Z.jsxs)(`div`,{className:`pointer-events-none absolute inset-y-0 right-0 z-20 flex w-7 flex-col items-end bg-gradient-to-l from-background via-background/60 to-transparent py-2`,children:[!i&&b.length>0&&(0,Z.jsxs)(`div`,{className:`pointer-events-auto relative`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(e=>!e),title:`Add column`,"aria-label":`Add column`,className:`flex h-7 w-6 items-center justify-center rounded-l-md border border-r-0 bg-background text-muted-foreground shadow-elevation-1 hover:bg-accent hover:text-foreground`,children:(0,Z.jsx)(nn,{className:`h-3.5 w-3.5`})}),s&&(0,Z.jsxs)(`div`,{className:`absolute right-0 top-8 w-44 rounded-lg border bg-background p-2 shadow-elevation-2`,children:[(0,Z.jsx)(`p`,{className:`px-2 pb-1 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`Add column`}),b.map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{c(!1),r([...n,{...e}])},className:`w-full rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:e.label},e.id)),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(!1),className:`mt-1 w-full rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground/60 hover:bg-accent/50`,children:`Cancel`})]})]}),m&&(0,Z.jsx)(B,{className:`my-auto h-4 w-4 self-center text-muted-foreground/70`,"aria-label":`More columns`})]}),(0,Z.jsx)(Wg,{document:a,isOpen:a!==null,onClose:()=>o(null),workspaceId:t})]})}var ux=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:null;function dx(e){return`/${e}`.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`}function fx(e,t,n){if(e==null)return[];if(Array.isArray(e))return e.flatMap(e=>fx(e,t,n));if(typeof e==`string`)return[{tree:null,kind:t,path:dx(e)}];let r=ux(e);if(!r)return[];let i=r.tree??r.treeId,a=typeof i==`string`?n.get(i)??null:null;return[].concat(r.paths??r.path??`/`).filter(e=>typeof e==`string`).map(e=>({tree:a,kind:t,path:dx(e)}))}function px(e){let t=[],n=e=>{let n=Number(e);Number.isSafeInteger(n)&&n>0&&t.push(n)};return Array.isArray(e.ids)&&e.ids.forEach(n),Array.isArray(e.documentIds)&&e.documentIds.forEach(n),e.id!=null&&n(e.id),e.documentId!=null&&n(e.documentId),t}function mx(e){let t=new Map;for(let n of e)t.set(n.id,n.name),t.set(n.name,n.name);return t}function hx(e,t,n=new Map){let r=ux(t);if(!r)return{targets:[],ids:[],unknown:!0};if(e.startsWith(`tree.`)){let e=typeof r.treeName==`string`?r.treeName:null,t=r.treeType===`directory`||r.treeType===`context`?r.treeType:null,n=r.contextSpec??r.path;return typeof n==`string`?{targets:[{tree:e,kind:t,path:dx(n)}],ids:px(r),unknown:!1}:{targets:[],ids:[],unknown:!0}}let i=[...fx(r.context,`context`,n),...fx(r.directory,`directory`,n)],a=ux(r.changed);a&&i.push(...fx(a.context,`context`,n),...fx(a.directory,`directory`,n));let o=px(r);if(i.length)return{targets:i,ids:o,unknown:!1};let s=r.reason===`content`||r.reason===`relations`;return e.startsWith(`document.updated`)&&s&&o.length?{targets:[],ids:o,unknown:!1}:{targets:[],ids:o,unknown:!0}}function gx(e,t){return e===t||e===`/`||t===`/`||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}function _x(e,t){return e.kind&&e.kind!==t.kind||e.tree&&e.tree!==t.tree?!1:gx(e.path,t.path)}function vx(e,t,n){if(e.unknown||e.targets.length&&(t.wholeWorkspace||e.targets.some(e=>_x(e,t))))return!0;if(e.ids.length&&n){let t=n instanceof Set?n:new Set(n);if(e.ids.some(e=>t.has(e)))return!0}return!1}var yx={sortBy:`crud:created`,order:`desc`},bx={features:{allOf:[],anyOf:[],noneOf:[]},timeline:{quickFilter:null,customRanges:[],indexCreated:!0,indexUpdated:!0,indexDeleted:!1,contentEvents:!1,selectedTimelines:[]},geo:{bbox:null},lens:{gps:null,ids:null},sort:{...yx}};function xx(e){let t=e.bbox;return t?[`geo:bbox:${t.minLat},${t.minLon},${t.maxLat},${t.maxLon}`,...e.includeUnlocated?[`geo:missing`]:[]]:[]}function Sx(e,t=!1){if(!e.gps)return[];let{lat:n,lon:r,radiusM:i}=e.gps;return[`geo:near:${n},${r},${Math.max(1,Math.round(i))}m`,...t?[`geo:missing`]:[]]}function Cx(e){return e.customRanges?.length?e.customRanges:e.customRange?[e.customRange]:[]}function wx(e){let{quickFilter:t,indexCreated:n,indexUpdated:r,indexDeleted:i,contentEvents:a,selectedTimelines:o}=e,s=Cx(e),c=s.length>0?s.map(e=>`${e.start}..${e.end}`):t?[t]:[];if(c.length===0)return[];let l=[];return n&&l.push(`crud:created`),r&&l.push(`crud:updated`),i&&l.push(`crud:deleted`),a&&l.push(`content`),l.push(...o),l.flatMap(e=>c.map(t=>`t:${e}:${t}`))}var Tx=(0,X.createContext)(null);function Ex(){let e=(0,X.useContext)(Tx);if(!e)throw Error(`useCanvasPins must be used within a CanvasPinsProvider`);return e}function Dx(e,t,n={}){return Wu.request(Au,{workspace:e,specs:t,opts:n})}function Ox(e,t,n){return Wu.request(ju,{sessionId:e,label:t,spec:n})}function kx(e){return Wu.request(Mu,{sessionId:e})}function Ax(e,t={}){return Wu.request(Nu,{sessionId:e,...t})}function jx(e){return Wu.request(Pu,{sessionId:e})}function Mx(e){return Wu.on(Fu,e)}var Nx=100;function Px({workspaceRef:e,specs:t,opts:n,enabled:r=!0}){let[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(0),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(null),f=(0,X.useRef)([]),p=(0,X.useRef)(new Map),m=(0,X.useRef)(null),h=(0,X.useRef)(null),g=(0,X.useRef)(null),_=(0,X.useRef)({}),v=(0,X.useRef)(null),y=(0,X.useMemo)(()=>JSON.stringify(t),[t]),b=(0,X.useMemo)(()=>JSON.stringify(n??{}),[n]),x=(0,X.useCallback)(()=>{let e=p.current;a(f.current.map(t=>e.get(t)).filter(Boolean))},[]),S=(0,X.useCallback)(async e=>{let t=h.current;if(!t||e.length===0)return[];let n=[];for(let r=0;r<e.length;r+=Nx){let i=e.slice(r,r+Nx),a=await Bi(t,`/`,[],{ids:i,scope:`workspace`,limit:i.length});n.push(...a.payload||[])}return n},[]),C=(0,X.useCallback)(async(e,t,n)=>{if(t.length>0){let e=new Set(t);f.current=f.current.filter(t=>!e.has(t));for(let t of e)p.current.delete(t)}let r=e.filter(e=>!p.current.has(e)),i=new Set(f.current);for(let t of e)i.has(t)||(f.current.push(t),i.add(t));if(n!==null&&s(n),x(),r.length===0)return;let a=await S(r);for(let e of a)p.current.set(e.id,e);let o=new Set(a.map(e=>e.id)),c=r.filter(e=>!o.has(e));if(c.length>0){let e=new Set(c);f.current=f.current.filter(t=>!e.has(t))}x()},[S,x]),w=(0,X.useCallback)(async(e,t)=>{let n=e??[],r=new Set(n);f.current=f.current.filter(e=>r.has(e));for(let e of p.current.keys())r.has(e)||p.current.delete(e);let i=new Set(f.current),a=n.filter(e=>!i.has(e));await C(a,[],t)},[C]);(0,X.useEffect)(()=>{if(h.current=e??null,!r||!e)return;let t=!1,n=null,i=async()=>{try{let r=await Dx(e,JSON.parse(y),JSON.parse(b));if(t){jx(r.sessionId).catch(()=>{});return}n=r.sessionId,m.current=r.sessionId,l(r.sessionId),d(null),f.current=[],p.current=new Map,await w(r.ids,r.count)}catch(e){if(t)return;d(e instanceof Error?e.message:`Failed to open query session`),l(null),m.current=null}};i();let o=Wu.on(`connect`,()=>{i()});return()=>{t=!0,o?.();let e=n??m.current;e&&jx(e).catch(()=>{}),m.current=null,f.current=[],p.current=new Map,l(null),a([]),s(0)}},[e,y,b,r]),(0,X.useEffect)(()=>{if(!c)return;let e=Mx(e=>{if(e.sessionId===c){if(g.current!==null){v.current?.(g.current,_.current);return}e.ids===void 0?C(e.added??[],e.removed??[],e.count):w(e.ids,e.count)}});return()=>{e?.()}},[c,C,w]);let T=(0,X.useCallback)(async()=>{let e=m.current;if(e)try{let t=await kx(e);await w(t.ids,t.count)}catch{}},[w]),E=(0,X.useCallback)(async(e,t)=>{let n=m.current;if(!n)throw Error(`No open query session`);let r=await Ox(n,e,t);if(g.current!==null){await v.current?.(g.current,_.current);return}await w(r.ids,r.count)},[w]),D=(0,X.useCallback)(async(e,t={})=>{let n=m.current;if(!n)throw Error(`No open query session`);if(g.current=e,_.current=t,e===null){await T();return}let r=await Ax(n,{match:e,...t});for(let e of r.documents)p.current.set(e.id,e);f.current=r.ids,s(r.totalCount),x()},[x,T]);(0,X.useEffect)(()=>{v.current=D},[D]);let O=(0,X.useCallback)(async(e,t,n={})=>{let r=m.current;if(!r)throw Error(`No open query session`);let i=await Ax(r,{match:t,limit:n.limit??100,...n.mode?{mode:n.mode}:{}});for(let e of i.documents)p.current.set(e.id,e);let a=await Ox(r,e,{ids:i.ids});return await w(a.ids,a.count),i.ids},[w]);return{documents:i,count:o,ready:c!==null,error:u,setCue:E,resync:T,rank:D,rankAndPin:O}}var Fx=`canvas:query-debug`,Ix=`canvas:query-debug-changed`;function Lx(){try{return localStorage.getItem(Fx)===`1`}catch{return!1}}function Rx(e){try{e?localStorage.setItem(Fx,`1`):localStorage.removeItem(Fx)}catch{}window.dispatchEvent(new CustomEvent(Ix,{detail:e}))}function zx(){let[e,t]=(0,X.useState)(Lx);return(0,X.useEffect)(()=>{let e=()=>t(Lx());return window.addEventListener(Ix,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(Ix,e),window.removeEventListener(`storage`,e)}},[]),e}function Bx({data:e,className:t}){let[n,r]=(0,X.useState)(!0),{rows:i,gapIndex:a,span:o}=(0,X.useMemo)(()=>{let t=[...e.distances].sort((e,t)=>e.distance-t.distance),n=[];for(let e=1;e<t.length;e++)n.push(t[e].distance-t[e-1].distance);let r=n.length?[...n].sort((e,t)=>e-t)[Math.floor(n.length/2)]:0,i=-1,a=0;for(let e=0;e<n.length;e++)n[e]>a&&(a=n[e],i=e+1);let o=i>0&&a>=Math.max(r*4,1e-6),s=t[0]?.distance??0,c=t[t.length-1]?.distance??0;return{rows:t,gapIndex:o?i:-1,span:{first:s,last:c,biggest:a,median:r}}},[e.distances]);if(i.length===0)return(0,Z.jsxs)(`div`,{className:K(`rounded-md border border-dashed border-border px-3 py-2 text-xs text-muted-foreground`,t),children:[`Query debug: no image distances for “`,e.query,`”. The dense side returned nothing: either no photos are embedded in this scope, or the image space is not ready.`]});let s=a>0?i[a].distance:null;return(0,Z.jsxs)(`div`,{className:K(`rounded-md border border-border bg-muted/30 text-xs`,t),children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r(e=>!e),className:`flex w-full items-center gap-1.5 px-3 py-2 text-left font-medium`,children:[n?(0,Z.jsx)(Ne,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(B,{className:`h-3.5 w-3.5`}),`Query debug`,(0,Z.jsxs)(`span`,{className:`font-normal text-muted-foreground`,children:[`: image distances for “`,e.query,`” (`,i.length,` nearest, unfloored)`]})]}),n&&(0,Z.jsxs)(`div`,{className:`space-y-2 border-t border-border px-3 py-2`,children:[(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Best-first cosine distance (0 = identical). Scroll to where the photos stop being relevant and set the image relevance floor just above that value in Settings → Database → Search tuning.`,s===null?(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.jsx)(`span`,{className:`text-amber-600 dark:text-amber-500`,children:`No boundary in this window`}),`; the distances step evenly (typical Δ`,o.median.toFixed(4),`), so there is nothing here to set a floor from. Relevance probably ends further down the list than this window reaches, or the model is not separating this query at all.`]}):(0,Z.jsxs)(Z.Fragment,{children:[` A jump at `,(0,Z.jsx)(`span`,{className:`font-mono`,children:s.toFixed(4)}),` (Δ`,o.biggest.toFixed(4),`, vs typical Δ`,o.median.toFixed(4),`) stands out (a likely boundary).`]})]}),(0,Z.jsx)(`div`,{className:`max-h-56 overflow-y-auto`,children:(0,Z.jsx)(`table`,{className:`w-full font-mono text-[11px]`,children:(0,Z.jsx)(`tbody`,{children:i.map((e,t)=>(0,Z.jsxs)(`tr`,{className:K(`border-b border-border/40 last:border-0`,t===a&&`border-t-2 border-t-amber-500/70`),children:[(0,Z.jsx)(`td`,{className:`py-0.5 pr-3 text-muted-foreground`,children:t+1}),(0,Z.jsxs)(`td`,{className:`py-0.5 pr-3`,children:[`#`,e.id]}),(0,Z.jsx)(`td`,{className:`py-0.5 tabular-nums`,children:e.distance.toFixed(4)}),t===a&&(0,Z.jsx)(`td`,{className:`py-0.5 pl-2 font-sans text-[10px] text-amber-600 dark:text-amber-500`,children:`← biggest gap`})]},e.id))})})}),(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Range `,o.first.toFixed(4),` – `,o.last.toFixed(4),` (spread `,(o.last-o.first).toFixed(4),`) over `,i.length,` rows. Absolute values shift with the model and are not comparable across models. After a re-embed every floor has to be picked again. A spread this narrow relative to the range means ranking is doing the work, not distance.`]})]})]})}function Vx(e,t){if(!e)return[];let n=t.split(`/`).filter(Boolean),r=e;for(let e of n)if(r=r?.children?.find(t=>t.name===e)??null,!r)return[];let i=n.length?`/${n.join(`/`)}`:``,a=(r.children??[]).filter(e=>e.type!==`canvas`).map(e=>({name:e.name,path:`${i}/${e.name}`,label:e.label,color:e.color,childCount:e.children?.length??0})).sort((e,t)=>(e.label||e.name).localeCompare(t.label||t.name,void 0,{numeric:!0,sensitivity:`base`}));return n.length>0&&a.unshift({name:`..`,path:n.length>1?`/${n.slice(0,-1).join(`/`)}`:`/`,isParent:!0}),a}var Hx=new Map;function Ux(e,t,n){return`${e}\0${t}\0${n}`}function Wx(e,t,n,r,i,a,o=``,s=``,c=`path`){return`${Ux(e,t,n)}\0${r}\0${i}\0${a}\0${o}\0${s}\0${c}`}function Gx(e,t,n){let r=Ux(e,t,n);for(let e of Hx.keys())e.startsWith(r)&&Hx.delete(e)}function Kx(e,t){let n=`${e}\0`;for(let[e,r]of Hx){if(!e.startsWith(n))continue;let[,i,a,,,,,,o=`path`]=e.split(`\0`);vx(t,{tree:i,kind:ma(i),path:a,wholeWorkspace:o.startsWith(`workspace`)},r.documents.map(e=>Number(e.id)))&&Hx.delete(e)}}function qx(e,t){if(!t?.treeName)return;let n=t.workspaceName??e,r=t.path?Ux(n,t.treeName,t.path):`${n}\0${t.treeName}\0`;for(let e of Hx.keys())e.startsWith(r)&&Hx.delete(e)}function Jx(){let{workspaceName:e}=Yc();return e?(0,Z.jsx)(Gb,{workspaceName:e,children:(0,Z.jsx)(Yx,{})}):null}function Yx(){let{workspaceName:e,treeName:t}=Yc(),n=Hc(),r=Gc(),{showToast:i}=oo(),a=new URLSearchParams(n.search),o=(()=>{let e=a.getAll(`q`).map(e=>e.trim()).filter(Boolean);if(e.length>0)return e;let t=(a.get(`search`)||``).trim();return t?[t]:[]})(),[s,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(!0),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(0),v=zx(),[y,b]=(0,X.useState)(null),[x,S]=(0,X.useState)(v);x!==v&&(S(v),v||b(null));let[C,w]=(0,X.useState)(`path`),[T,E]=(0,X.useState)(!1),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(null),[j,M]=(0,X.useState)(``),[N,P]=(0,X.useState)(!1),[ee,F]=(0,X.useState)(!1),[I,te]=(0,X.useState)(!1),[ne,L]=(0,X.useState)(null),[re,R]=(0,X.useState)(1),[ie,oe]=(0,X.useState)(50),[z,se]=(0,X.useState)(o),[ce,B]=(0,X.useState)(null),{state:V,saveFilters:le,toggleView:ue,setSort:de,setAccentColor:fe,setMapDocuments:pe,hasActiveFilters:me}=hs(),H=V.filters.features.allOf,he=V.filters.features.anyOf,ge=V.filters.features.noneOf,_e=wx(V.filters.timeline),ve=xx(V.filters.geo),ye=Sx(V.filters.lens,V.filters.geo.includeUnlocated),U=V.filters.lens.ids,be=[..._e,...ve,...ye],xe=V.filters.sort??yx,Se=JSON.stringify({a:H,b:he,c:ge,d:be,i:U,s:xe}),Ce=JSON.stringify({a:H,b:he,c:ge,d:be,s:xe}),W=iv(n.pathname).path,G=t??`context`,we=G===`backends`,[Te,Ee]=(0,X.useState)([]);(0,X.useEffect)(()=>{!we||!e||va(e).then(Ee).catch(()=>Ee([]))},[we,e]);let De=we?wa(W,Te):null,[Oe,ke]=(0,X.useState)(!1),Ae=`${G}\0${W}`,[je,Me]=(0,X.useState)(Ae);je!==Ae&&(Me(Ae),ke(!1));let Ne=a.get(`layer`)===`1`,Pe=a.get(`layerId`)||null,[Fe,Ie]=(0,X.useState)(null),[Le,Re]=(0,X.useState)(null),[ze,Be]=(0,X.useState)(`left`),[Ve,He]=(0,X.useState)([]),{openM2Drawer:Ue}=Eb(),We=Cm(),[Ge,Ke]=(0,X.useState)([]),qe=(0,X.useMemo)(()=>{if(!Fe||W===`/`||Ne)return null;let e=W.split(`/`).filter(Boolean),t=Fe;for(let n of e)if(t=t?.children?.find(e=>e.name===n)??null,!t)return null;return t},[Fe,W,Ne]),Je=qe?.type===`canvas`?`canvas`:null,Ye=(0,X.useRef)(null);(0,X.useEffect)(()=>{!e||!Fe||Ne||Ye.current===`${e}/${G}`&&(W!==`/`&&!qe||$y(e,G,W))},[e,Fe,Ne,W,qe,G]);let Xe=(0,X.useMemo)(()=>Ne||C===`workspace`||z.length>0||ma(G)!==`directory`?[]:Vx(Fe,W),[Fe,W,G,Ne,C,z]),Ze=Ne?null:W===`/`?Fe:qe,Qe=`${G}\0${W}`,[$e,et]=(0,X.useState)(null),tt=$e?.key===Qe?$e.views:ex(Ze?.metadata),nt=$e?.key===Qe?$e.activeId:tt[0]?.id??Qb.id,rt=tt.find(e=>e.id===nt)??tt[0]??Qb,it=e=>et({key:Qe,views:tt,activeId:e}),at=(t,n)=>{et({key:Qe,views:t,activeId:n??nt}),_a(e,W,{metadata:{...Ze?.metadata??{},views:t}},G).catch(()=>{i({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},ot=Je===`canvas`&&typeof qe?.querySpec?.query==`string`?qe.querySpec.query:``,st=Je===`canvas`?{label:qe?.label,description:qe?.description,color:qe?.color}:null,{isPinned:ct,pin:lt,unpin:ut,pins:dt}=Ex(),ft=s?.name,pt=(0,X.useMemo)(()=>ft&&Je===`canvas`&&!Ne?{workspaceName:ft,treeName:G,path:W}:null,[ft,Je,Ne,G,W]),mt=pt?ct(pt):!1,ht=qe?.id,gt=qe?.label,_t=(0,X.useCallback)(async()=>{if(pt)try{let e=dt.find(e=>e.workspaceName===pt.workspaceName&&e.treeName===pt.treeName&&e.path===pt.path);e?await ut(e.id):await lt({...pt,layerId:ht,label:gt})}catch(e){console.error(`Failed to update home pins:`,e)}},[pt,dt,lt,ut,ht,gt]),vt=e?`${e}://${W===`/`?``:W.replace(/^\//,``)}`:``,yt=If(s?.color)||null;(0,X.useEffect)(()=>(fe(yt),()=>fe(null)),[yt,fe]);let bt=(0,X.useCallback)(async t=>{let n=U;if(t?.anyOf?.length&&he.length&&(n=((await gi(e,W,G,{limit:0,anyOf:he,ids:U,applyCanvasSpec:!1})).payload||[]).map(e=>e.id),!n.length))return{payload:[],count:0,totalCount:0};let r=await gi(e,W,G,{limit:t?.limit,offset:t?.offset,page:t?.page,sortBy:t?.sortBy,order:t?.order,allOf:[...H,...t?.allOf??[]],anyOf:t?.anyOf?.length?t.anyOf:he,noneOf:ge,filters:be,ids:n,queries:[...z,...t?.queries??[],...t?.q?[t.q]:[]],applyCanvasSpec:!1});return{payload:r.payload||[],count:r.count??void 0,totalCount:r.totalCount??void 0}},[e,W,G,Se,z]);(0,X.useEffect)(()=>{e&&(async()=>{d(!0);try{let t=await Y.get(`${Kr.workspaces}/${e}`),n;n=t&&`workspace`in t?t.workspace:t,l(n)}catch(t){let n=t instanceof Error?t.message:`Failed to fetch workspace ${e}`;i({title:`Error`,description:n,variant:`destructive`}),l(null)}finally{d(!1)}})()},[e,i]),(0,X.useEffect)(()=>{let e=e=>{let t=e.detail?.workspace;t&&l(e=>e&&(t===e.name||t===e.id)&&e.status!==`active`?{...e,status:`active`}:e)};return window.addEventListener(`workspace:autostarted`,e),()=>window.removeEventListener(`workspace:autostarted`,e)},[]);let xt=(U?.length??0)>0&&!Ne&&!(Oe&&De)&&z.length<=1,{documents:St,count:Ct,ready:wt,setCue:Tt,resync:Et,rank:Dt}=Px({workspaceRef:e,specs:(0,X.useMemo)(()=>{let e={features:{allOf:H,anyOf:he,noneOf:ge},filters:be};return C!==`workspace`&&(ma(G)===`directory`?e.directory={tree:G,path:W}:e.context=W),[{label:`scope`,spec:e}]},[Ce,W,G,C]),opts:(0,X.useMemo)(()=>({mode:`live`,debounceMs:150}),[]),enabled:xt}),Ot=xt&&wt,kt=(0,X.useRef)(!1);(0,X.useEffect)(()=>{kt.current=Ot},[Ot]);let At=z.length===1?z[0].trim():``;(0,X.useEffect)(()=>{wt&&Dt(At?{text:At}:null,{limit:ie,offset:(re-1)*ie}).catch(()=>{})},[wt,At,ie,re,Dt]);let jt=(U??[]).join(`,`);(0,X.useEffect)(()=>{wt&&Tt(`lens`,{ids:U??[]}).catch(()=>{})},[wt,jt,Tt,U]);let Mt=Ot?St:f,Nt=Ot?Ct:g,Pt=(0,X.useRef)(new Set);(0,X.useEffect)(()=>{Pt.current=new Set(Mt.map(e=>Number(e.id)))},[Mt]);let Ft=V.geoSelection;(0,X.useEffect)(()=>{pe(Mt,s?.name??null)},[Mt,s?.name,pe]),(0,X.useEffect)(()=>()=>pe([]),[pe]);let It=(0,X.useMemo)(()=>Ft?Mt.filter(e=>zg(e,Ft,V.filters.geo.includeUnlocated)):Mt,[Mt,Ft,V.filters.geo.includeUnlocated]),Lt=(0,X.useRef)(0),Rt=(0,X.useRef)(``),zt=(0,X.useCallback)(async t=>{if(!e||kt.current)return;let n=++Lt.current,r=Oe&&De?`${C}:unfiled`:C,a=(U?.length??0)>0,o=Wx(e,G,W,re,ie,z.join(`␟`),Ce,Ne&&Pe?Pe:``,r),s=a&&o===Rt.current;Rt.current=o;let c=Wx(e,G,W,re,ie,z.join(`␟`),Se,Ne&&Pe?Pe:``,r),l=a||v?void 0:Hx.get(c);if(l){p(l.documents),_(l.totalCount),h(!1);return}(t?.silent??s)||h(!0);try{let t;t=Oe&&De?await Ri(e,De.driver,De.address,{linked:!1,limit:ie,offset:(re-1)*ie}):Ne&&Pe&&C!==`workspace`?await ka(e,G,Pe,{limit:ie,page:re,queries:z,allOf:H,anyOf:he,noneOf:ge,filters:be,ids:U,sortBy:xe.sortBy||void 0,order:xe.order}):await Bi(e,W,H,{limit:ie,page:re,treeName:G,treeType:G===`directory`||G===`backends`?`directory`:`context`,queries:z,anyOf:he,noneOf:ge,filters:be,ids:U,sortBy:xe.sortBy||void 0,order:xe.order,scope:C,debug:v&&z.length>0,debugLimit:200});let r=t.payload||[],i=t.totalCount||t.count||0;if(a||Hx.set(c,{documents:r,totalCount:i}),n!==Lt.current)return;let o=t.debug,l=o?.imageDistances??o?.distances??null;b(l?{query:z[z.length-1]??``,distances:l}:null),p(s?e=>e.length===r.length&&e.every((e,t)=>e.id===r[t].id)?e:r:r),_(i)}catch(e){if(n!==Lt.current)return;let t=e instanceof Error?e.message:`Failed to fetch documents`;i({title:`Error`,description:t,variant:`destructive`}),p([]),_(0)}finally{n===Lt.current&&h(!1)}},[e,W,G,Pe,Ne,re,ie,s?.status,z,Se,C,Oe,v]);(0,X.useEffect)(()=>{zt()},[zt]),(0,X.useEffect)(()=>{let t=t=>{let n=t.detail;!n||n.workspaceName!==e||(Re({treeName:n.treeName||`context`,path:nv(n.path||`/`)}),Be(`left`))};return window.addEventListener(`workspace:open-to-side`,t),()=>window.removeEventListener(`workspace:open-to-side`,t)},[e,G,W]),(0,X.useEffect)(()=>{let t=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||(e&&qx(e,n),!(n?.treeName&&n.treeName!==G)&&(n?.path&&n.path!==W||(e&&Gx(e,G,W),zt({silent:!0}))))};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[zt,e,W,G]);let Bt=s?.name,Vt=s?.id;(0,X.useEffect)(()=>{if(!e||!Bt&&!Vt)return;let t=[Bt,Vt].filter(Boolean).map(e=>`workspace:${e}`),n=()=>t.forEach(e=>Wu.emit(`subscribe`,{channel:e}));n();let r=Wu.on(`connect`,n),i=new Map,a=!1,o=()=>{jr(e).then(e=>{a||(i=mx(e))}).catch(()=>{})};o();let s=null,c=0,l=()=>{if(s=null,c=Date.now(),kt.current){Et();return}zt({silent:!0})},u=t=>n=>{(t.startsWith(`tree.created`)||t.startsWith(`tree.renamed`))&&o();let r=hx(t,n,i);Kx(e,r),vx(r,{tree:G,kind:ma(G),path:W,wholeWorkspace:C===`workspace`},Pt.current)&&(s||=setTimeout(l,Math.max(200,c+1500-Date.now())))},d=[`document.inserted`,`document.updated`,`document.removed`,`document.deleted`,`document.removed.batch`,`document.deleted.batch`,`document.linked`,`document.unlinked`,`document.linked.batch`,`document.unlinked.batch`,`tree.document.inserted`,`tree.document.inserted.batch`,`tree.document.removed`,`tree.document.removed.batch`,`tree.document.deleted`,`tree.document.deleted.batch`,`tree.layer.merged`,`tree.layer.subtracted`,`tree.created`,`tree.renamed`].map(e=>[e,u(e)]);return d.forEach(([e,t])=>Wu.on(e,t)),()=>{a=!0,s&&clearTimeout(s),r?.(),d.forEach(([e,t])=>Wu.off(e,t))}},[e,Vt,Bt,G,W,C,zt,Et]);let Ht=`${W}\0${G}\0${Pe??``}\0${C}`,[Ut,Wt]=(0,X.useState)(Ht);Ut!==Ht&&(Wt(Ht),R(1),B(null));let Gt=`${W}\0${G}\0${Pe??``}`,[Kt,qt]=(0,X.useState)(Gt);Kt!==Gt&&(qt(Gt),w(`path`));let Jt=(e,t)=>{let n=e===`/`?`canvas`:e.split(`/`).pop()||`canvas`;M(n),A({parentPath:e,captureView:t})},Yt=a.get(`createCanvas`)===`1`,[Xt,Zt]=(0,X.useState)(!1);Xt!==Yt&&(Zt(Yt),Yt&&Jt(W,!1)),(0,X.useEffect)(()=>{if(!Yt)return;let e=new URLSearchParams(n.search);e.delete(`createCanvas`);let t=e.toString();r(`${n.pathname}${t?`?${t}`:``}`,{replace:!0})},[Yt,W]);let Qt=(0,X.useCallback)(e=>{let t=new URLSearchParams(n.search);t.delete(`q`),t.delete(`search`);for(let n of e)t.append(`q`,n);let i=t.toString();r(`${n.pathname}${i?`?${i}`:``}`)},[n.pathname,n.search,r]),$t=o.join(`␟`),[en,tn]=(0,X.useState)($t);en!==$t&&(tn($t),se(o),R(1));let nn=`${$t}\0${Je??``}\0${ot}\0${W}\0${ce??``}`,[rn,an]=(0,X.useState)(nn);rn!==nn&&(an(nn),o.length>0||Je!==`canvas`||ce===W||(se(ot?[ot]:[]),R(1)));let on=(0,X.useCallback)(e=>{let t=e.trim();t&&(B(null),se(e=>{if(e.includes(t))return e;let n=[...e,t];return Qt(n),R(1),n}))},[Qt,B,se,R]),sn=(0,X.useCallback)(e=>{se(t=>{let n=e<0?[]:t.filter((t,n)=>n!==e);return n.length===0&&B(W),Qt(n),R(1),n})},[Qt,W,B,se,R]),cn=z.join(` `).trim(),ln=!!V.activeContextType&&(V.isDirty||cn!==(Je===`canvas`?ot:V.savedSearchQuery||``));!e&&Fe!==null&&Ie(null),(0,X.useEffect)(()=>{let t=!1;if(!e)return;let n=(n=!1)=>{n&&oa(e,G),fi(e,G,{force:n}).then(n=>{t||(Ye.current=`${e}/${G}`,Ie(n))}).catch(()=>{t||Ie(null)})};n(!1);let r=t=>{let r=t.detail;r?.workspaceName&&r.workspaceName!==e||r?.treeName&&r.treeName!==G||n(!0)};window.addEventListener(`workspace:tree:refresh`,r);let i=null,a=()=>{i&&clearTimeout(i),i=setTimeout(()=>{window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}}))},200)},o=[`tree.path.inserted`,`tree.path.moved`,`tree.path.removed`,`tree.path.copied`,`tree.layer.updated`,`tree.layer.merged`,`tree.layer.subtracted`,`tree.recalculated`,`tree.created`,`tree.deleted`,`tree.renamed`];return o.forEach(e=>Wu.on(e,a)),()=>{t=!0,i&&clearTimeout(i),window.removeEventListener(`workspace:tree:refresh`,r),o.forEach(e=>Wu.off(e,a))}},[e,G]),!(e&&Je===`canvas`&&!Ne)&&ne!==null&&L(null),(0,X.useEffect)(()=>{let t=!1;if(!(!e||Je!==`canvas`||Ne))return zr(e,W,G).then(e=>{t||L(e)}).catch(()=>{t||L(null)}),()=>{t=!0}},[e,W,G,Je,Ne]);let un=async()=>{if(s){E(!0);try{let t=await ii(e||s.id);l(t),i({title:`Success`,description:`Workspace started successfully`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){let t=e instanceof Error?e.message:`Failed to start workspace`;i({title:`Error`,description:t,variant:`destructive`})}finally{E(!1)}}},dn=async t=>{if(s)try{await Sr(e||s.id,[t],W,[],G,yn,{trashIfOrphaned:!0}),Gx(e||s.id,G,W),p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),i({title:`Success`,description:`Document removed from workspace path.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to remove document`,variant:`destructive`})}},fn=async t=>{if(s)try{await Ia(e||s.id,[t],W,[],G,yn),Gx(e||s.id,G,W),p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),i({title:`Success`,description:`Document deleted.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete document`,variant:`destructive`})}},pn=async t=>{if(s)try{await Sr(e||s.id,t,W,[],G,yn,{trashIfOrphaned:!0}),Gx(e||s.id,G,W),p(e=>e.filter(e=>!t.includes(e.id))),_(e=>Math.max(0,e-t.length)),i({title:`Success`,description:`${t.length} document(s) removed.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},mn=async t=>{if(s)try{await Ia(e||s.id,t,W,[],G,yn),Gx(e||s.id,G,W),p(e=>e.filter(e=>!t.includes(e.id))),_(e=>Math.max(0,e-t.length)),i({title:`Success`,description:`${t.length} document(s) deleted.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},hn=async t=>{if(s)try{let n=await Er(e||s.id,[t]);if(n.failed?.length){i({title:`Error`,description:n.failed[0].reason,variant:`destructive`});return}p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),i({title:`Destroyed`,description:`Document removed from all backends.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy document`,variant:`destructive`})}},gn=async t=>{if(s)try{let n=await Er(e||s.id,t),r=new Set(n.successful?.filter(e=>e.docDeleted).map(e=>e.id)??[]);p(e=>e.filter(e=>!r.has(e.id))),_(e=>Math.max(0,e-r.size));let a=[n.successful?.length?`${n.successful.length} destroyed`:null,n.failed?.length?`${n.failed.length} failed`:null].filter(Boolean).join(`, `);i({title:`Done`,description:a||`No documents destroyed`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},_n=e=>{O({documentIds:e,operation:`copy`,sourcePath:W,sourceTreeName:G}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}})),i({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},vn=e=>{O({documentIds:e,operation:`cut`,sourcePath:W,sourceTreeName:G}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}})),i({title:`Cut`,description:`${e.length} document(s) cut to clipboard`})},yn=ma(G),bn=async(t,n,r={})=>{if(!e)return!1;let a=r.targetTreeName??G,o=r.targetTreeType??yn;try{let s=await qr(e,t,n,a,o);if(s){Gx(e,a,t);let o=r.sourceTreeName||D?.sourceTreeName,s=r.sourcePath||D?.sourcePath;if((r.move||D?.operation===`cut`)&&s&&o){let t=ma(o);await Sr(e,n,s,[],o,t),Gx(e,o,s),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:s,treeName:o}}))}await zt(),O(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null})),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:a}})),i({title:`Success`,description:`${n.length} document(s) ${r.move||D?.operation===`cut`?`moved`:`pasted`} to "${t}"`})}return s}catch(e){return i({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},xn=async(t,n)=>{if(!e)return!1;try{let r=(await ki(e,n,t,G,yn)).length>0;return r&&(window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:n,treeName:G}})),i({title:`Success`,description:`Imported ${t.length} document(s) to "${n}"`})),r}catch(e){return i({title:`Error`,description:e instanceof Error?e.message:`Failed to import documents`,variant:`destructive`}),!1}},Sn=async()=>{if(!(!s||g===0)&&window.prompt(`Type PURGE to permanently delete all ${g} matching documents.`)===`PURGE`)try{let t=await ni(e||s.id,W,[],[],{},G);await zt(),i({title:`Success`,description:`${t.deleted} document(s) purged.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to purge documents`,variant:`destructive`})}},Cn=()=>Jt(W,!0),wn=async()=>{if(!(!e||!k||!j.trim())){P(!0);try{let t=j.trim(),n=k.parentPath,i=n===`/`?`/${t}`:`${n}/${t}`;await Ha(e,i,G,k.captureView?{metadata:{toolbox:V.filters},querySpec:{features:V.filters.features,filters:[...wx(V.filters.timeline),...xx(V.filters.geo)],query:cn||void 0,sort:V.filters.sort?.sortBy?V.filters.sort:null}}:{}),A(null),oa(e,G);try{let t=await fi(e,G,{force:!0});Ie(t)}catch{}window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}})),r(av(e,i,G))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to create canvas`,variant:`destructive`})}finally{P(!1)}}},Tn=async()=>{if(!(!e||Je!==`canvas`)){F(!0);try{let t=ne||await wi(e,W,G);L(t);let n=`${window.location.origin}${t.url}`;await navigator.clipboard?.writeText(n),i({title:`Public canvas link copied`,description:n})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to share canvas`,variant:`destructive`})}finally{F(!1)}}},En=async()=>{if(ne){F(!0);try{await za(ne.code),L(null),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:G}})),i({title:`Canvas unshared`,description:`The public link no longer works.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to unshare canvas`,variant:`destructive`})}finally{F(!1)}}},Dn=async()=>{if(!e||Je!==`canvas`||W===`/`)return;let t=st?.label||W.split(`/`).pop()||`canvas`,n=ne?` Its public link will stop working.`:``;if(window.confirm(`Delete canvas "${t}"? This cannot be undone.${n}`)){te(!0);try{if(ne)await za(ne.code),L(null);else if(qe?.locked){i({title:`Canvas is locked`,description:`Unlock it before deleting.`,variant:`destructive`});return}await hi(e,W,!1,G);let n=W.split(`/`).filter(Boolean);n.pop();let a=n.length?`/${n.join(`/`)}`:`/`;window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:G}})),r(av(e,a,G)),i({title:`Canvas deleted`,description:`"${t}" was removed.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete canvas`,variant:`destructive`})}finally{te(!1)}}},On=(0,X.useCallback)(async t=>{if(!e||!Le)return;let n={treeName:G,path:W},r=ze===`left`?n:Le,a=ze===`left`?Le:n,o=ze===`left`?Ve:Ge;if(o.length===0){i({title:`Nothing selected`,description:`Tick documents in the focused pane first.`});return}let s=ma(a.treeName);try{if(!await qr(e,a.path,o,a.treeName,s))return;if(Gx(e,a.treeName,a.path),t){let t=ma(r.treeName);await Sr(e,o,r.path,[],r.treeName,t),Gx(e,r.treeName,r.path)}[r,a].forEach(t=>window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t.path,treeName:t.treeName}}))),i({title:t?`Moved`:`Copied`,description:`${o.length} document(s) → "${a.path}"`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Transfer failed`,variant:`destructive`})}},[e,Le,ze,G,W,Ve,Ge,i]);if((0,X.useEffect)(()=>{if(!Le)return;let e=e=>{if(e.key!==`F5`&&e.key!==`F6`)return;let t=e.target;t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`&&(e.preventDefault(),On(e.key===`F6`))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Le,On]),u)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,Z.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Z.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading workspace...`})]})});if(!s)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Workspace not found.`});let kn=Je===`canvas`&&!Ne&&!!qe,An=(0,Z.jsx)(Xb,{urlType:Ne?ma(G)===`directory`?`${G}-layer`:`context-layer`:Je===`canvas`?`canvas`:ma(G)===`directory`?G:`context`,urlDisplay:vt,contextPath:W,treeName:G,workspaceId:e||s.id,documents:It,isLoading:m,totalCount:Nt,currentPage:re,pageSize:ie,onPageChange:R,onPageSizeChange:e=>{oe(e),R(1)},onRemoveDocument:W===`/`?void 0:dn,onDeleteDocument:fn,onDestroyDocument:hn,onRemoveDocuments:W===`/`?void 0:pn,onDeleteDocuments:mn,onDestroyDocuments:gn,onCopyDocuments:_n,onCutDocuments:vn,onPasteDocuments:we?void 0:bn,onImportDocuments:we?void 0:xn,onSelectionChange:He,selectedCount:Ve.length,onUrlClick:()=>Ue(`workspaces`,`detail`,e??null),onUrlSubmit:t=>r(av(e,nv(`/`+t),G)),folders:Xe,onOpenFolder:t=>r(av(e,nv(t),G)),scope:C,onScopeChange:w,pastedDocumentIds:D?.documentIds,linkTree:Fe,onPurgeDocuments:we?void 0:Sn,disablePurgeDocuments:!1,canvasInfo:st??void 0,isCanvasPinned:mt,onTogglePinCanvas:pt?_t:void 0,onSaveAsCanvas:Fe&&Je!==`canvas`&&!Ne&&!we?Cn:void 0,onShareCanvas:Je===`canvas`&&!Ne?Tn:void 0,onUnshareCanvas:ne?En:void 0,onDeleteCanvas:Je===`canvas`&&!Ne?Dn:void 0,isSharingCanvas:ee,isDeletingCanvas:I,isCanvasShared:!!ne,isCanvasLocked:!!qe?.locked,backendSearchQueries:z,onBackendSearch:on,serverSort:V.filters.sort,onServerSortChange:de,onRemoveBackendQuery:sn,canSaveChanges:ln,isSavingChanges:V.isSaving,onSaveChanges:le,contentBanner:v&&y?(0,Z.jsx)(Bx,{data:y,className:`mb-3`}):null,children:kn&&qe?(0,Z.jsx)(Ov,{workspaceId:e||s.id,treeName:G,path:W,layerId:qe.id,querySpec:qe.querySpec,metadata:qe.metadata,isLocked:!!qe.locked,fetchDocuments:V.isDirty?bt:void 0}):!we&&rt.kind===`columns`?(0,Z.jsx)(lx,{documents:It,workspaceId:e||s.id,columns:rt.columns??[],onColumnsChange:e=>at(tt.map(t=>t.id===rt.id?{...t,columns:e}:t))}):!we&&rt.kind===`app`&&rt.app?(0,Z.jsx)(ox,{app:rt.app,workspaceId:e||s.id,treeName:G,path:W}):null});return(0,Z.jsxs)(`div`,{className:`relative flex flex-col h-full min-h-0`,children:[(0,Z.jsx)(Kb,{workspaceId:s.id,workspaceName:s.label||s.name},s.id),(0,Z.jsxs)(`div`,{className:`relative shrink-0 max-sm:border-b`,children:[(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute inset-x-0 bottom-0 h-[3px] bg-border max-sm:hidden`,style:If(s.color)?{backgroundColor:If(s.color)}:void 0}),!kn&&!we&&Ze&&(0,Z.jsxs)(`div`,{className:`relative px-2 pt-1.5 sm:hidden`,children:[(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute inset-x-0 bottom-0 h-[3px] bg-border`,style:If(s.color)?{backgroundColor:If(s.color)}:void 0}),(0,Z.jsx)(tx,{accentColor:If(s.color),views:tt,activeId:nt,onSelect:it,onSave:at,readOnly:!1})]}),(0,Z.jsxs)(`div`,{className:`flex h-12 items-center gap-3 px-4`,children:[(0,Z.jsx)(Hy,{title:We?`Back to workspace tree`:`Back to workspaces`,onBack:()=>We?Ue(`workspaces`,`detail`,e||s.id):r(`/workspaces`)}),(0,Z.jsx)(`span`,{className:`w-2 h-2 rounded-full shrink-0 ${s.status===`active`?`bg-success`:s.status===`error`?`bg-destructive`:`bg-muted-foreground`}`,title:s.status}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>Ue(`workspaces`,`detail`,e||s.id),title:`Browse workspace tree`,className:`flex min-w-0 items-center gap-1.5 truncate rounded px-1 -mx-1 text-left text-sm font-medium transition-colors hover:bg-accent`,children:[(0,Z.jsx)(c,{icon:s.icon||`ph:stack-fill`,width:16,height:16,color:If(s.color),className:K(`shrink-0`,!If(s.color)&&`text-muted-foreground`)}),(0,Z.jsx)(`span`,{className:`truncate`,children:s.label||s.name})]}),!kn&&!we&&Ze?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(tx,{className:`min-w-0 flex-1 self-stretch max-sm:hidden`,accentColor:If(s.color),views:tt,activeId:nt,onSelect:it,onSave:at,onOpenToSide:e=>{Re({treeName:G,path:W,viewId:e}),Be(`right`)},readOnly:!1}),(0,Z.jsx)(`div`,{className:`flex-1 sm:hidden`})]}):(0,Z.jsx)(`div`,{className:`flex-1`}),De&&(0,Z.jsx)(`button`,{onClick:()=>{ke(!Oe),R(1)},className:K(`flex items-center gap-1.5 px-3 py-1 text-xs border rounded-md transition-colors`,Oe?`bg-warning/15 border-warning/40 text-warning`:`hover:bg-accent text-muted-foreground hover:text-foreground`),title:`Show only documents not filed into any context/directory tree (safe to purge from the backend)`,children:`Unfiled only`}),s.status===`active`?(0,Z.jsx)(`button`,{onClick:()=>ue(`tools`),className:K(`flex h-7 w-7 items-center justify-center border rounded-md transition-colors touch-target`,me?`border-info bg-info text-info-foreground hover:bg-info/90`:V.t1Open&&V.t1View===`tools`?`bg-accent text-foreground`:`hover:bg-accent text-muted-foreground hover:text-foreground`),"aria-label":`Filters`,title:me?`Toolbox filters are active and narrow this view`:`Open the toolbox filters`,children:(0,Z.jsx)(ae,{className:`h-3.5 w-3.5`})}):(0,Z.jsx)(`button`,{onClick:un,disabled:T,className:`px-3 py-1 text-xs border rounded-md hover:bg-accent disabled:opacity-50 touch-target`,children:T?`Starting…`:`Start`}),(0,Z.jsx)(Vy,{})]})]}),k&&(0,Z.jsx)(`div`,{className:`shrink-0 px-2 pt-2`,children:(0,Z.jsx)(Ky,{title:`New canvas`,onClose:()=>A(null),children:(0,Z.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),wn()},className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`canvas-name`,className:`mb-1 block text-sm font-medium`,children:`Name`}),(0,Z.jsx)(`input`,{id:`canvas-name`,className:`w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary`,placeholder:`Canvas name…`,value:j,onChange:e=>M(e.target.value),onKeyDown:e=>{e.key===`Escape`&&A(null)},autoFocus:!0})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`mb-1 block text-sm font-medium`,children:`Parent path`}),(0,Z.jsx)(`div`,{className:`flex h-10 items-center rounded-md bg-muted px-3 font-mono text-sm text-muted-foreground`,children:k.parentPath===`/`?`/`:k.parentPath})]})]}),(0,Z.jsxs)(`label`,{className:`flex items-start gap-2 text-sm`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:k.captureView,onChange:e=>A({...k,captureView:e.target.checked})}),(0,Z.jsxs)(`span`,{children:[`Capture the current view`,(0,Z.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:`Freezes the active filters, search and sort into the canvas.`})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(J,{type:`submit`,disabled:!j.trim()||N,children:N?`Creating…`:`Create canvas`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>A(null),children:`Cancel`})]})]})})}),(0,Z.jsxs)(`div`,{"data-canvas-panes":!0,className:`flex-1 min-h-0 flex gap-2 p-2 bg-muted/20`,children:[(0,Z.jsx)(`div`,{"data-canvas-pane":!0,className:K(`flex-1 min-w-0 rounded-lg border bg-background overflow-hidden`,Le&&(ze===`left`?`ring-2 ring-primary`:`ring-1 ring-primary/20`)),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||Be(`left`)},children:An}),Le&&e&&(0,Z.jsx)(Zx,{workspaceName:e,pane:Le,isFocused:ze===`right`,clipboard:D,setClipboard:O,onFocus:()=>Be(`right`),onSelectionChange:Ke,onNavigate:e=>Re(t=>t&&{...t,path:e,viewId:void 0}),onClose:()=>{Re(null),Be(`left`),Ke([])}})]})]})}function Xx(e,t){if(!e||t===`/`)return e;let n=e;for(let e of t.split(`/`).filter(Boolean))if(n=n?.children?.find(t=>t.name===e)??null,!n)return null;return n}function Zx({workspaceName:e,pane:t,isFocused:n=!1,clipboard:r,setClipboard:i,onFocus:a,onSelectionChange:o,onNavigate:s,onClose:c}){let{showToast:l}=oo(),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(0),[v,y]=(0,X.useState)(1),[b,x]=(0,X.useState)(50),S=ma(t.treeName),C=Xx(u,t.path),w=C?.type===`canvas`,T=(0,X.useMemo)(()=>S===`directory`?Vx(u,t.path):[],[u,t.path,S]),E=t.viewId?ex(C?.metadata).find(e=>e.id===t.viewId)??null:null,D=`${e}://${t.path===`/`?``:t.path.replace(/^\//,``)}`,O=(0,X.useCallback)(async()=>{let n=Wx(e,t.treeName,t.path,v,b,``,``),r=Hx.get(n);if(r){p(r.documents),_(r.totalCount);return}h(!0);try{let r=await Bi(e,t.path,[],{limit:b,page:v,treeName:t.treeName,treeType:S}),i=r.payload||[],a=r.totalCount||r.count||0;p(i),_(a),Hx.set(n,{documents:i,totalCount:a})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Failed to fetch side pane documents`,variant:`destructive`}),p([]),_(0)}finally{h(!1)}},[e,t.path,t.treeName,S,b,v,l]);(0,X.useEffect)(()=>{let n=!1,r=(r=!1)=>{r&&oa(e,t.treeName),fi(e,t.treeName,{force:r}).then(e=>{n||d(e)}).catch(()=>{n||d(null)})};r(!1);let i=n=>{let i=n.detail;i?.workspaceName&&i.workspaceName!==e||i?.treeName&&i.treeName!==t.treeName||r(!0)};return window.addEventListener(`workspace:tree:refresh`,i),()=>{n=!0,window.removeEventListener(`workspace:tree:refresh`,i)}},[e,t.treeName]),(0,X.useEffect)(()=>{O()},[O]),(0,X.useEffect)(()=>{let n=n=>{let r=n.detail;r?.workspaceName&&r.workspaceName!==e||(qx(e,r),!(r?.treeName&&r.treeName!==t.treeName)&&(r?.path&&r.path!==t.path||(Gx(e,t.treeName,t.path),O())))};return window.addEventListener(`workspace:documents:refresh`,n),()=>window.removeEventListener(`workspace:documents:refresh`,n)},[O,e,t.treeName,t.path]);let k=(0,X.useCallback)(async(n,a,o={})=>{let s=o.targetTreeName??t.treeName,c=o.targetTreeType??S;try{let t=await qr(e,n,a,s,c);if(t){Gx(e,s,n);let t=o.sourcePath||r?.sourcePath,c=o.sourceTreeName||r?.sourceTreeName;if((o.move||r?.operation===`cut`)&&t&&c){let n=ma(c);await Sr(e,a,t,[],c,n),Gx(e,c,t),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:c}}))}i(null),await O(),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:n,treeName:s}}))}return t}catch(e){return l({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},[e,t.treeName,S,O,l,r,i]),A=(0,X.useCallback)(()=>{Gx(e,t.treeName,t.path),O()},[e,t.treeName,t.path,O]),j=(0,X.useCallback)(async n=>{try{await Sr(e,n,t.path,[],t.treeName,S),A(),l({title:`Removed`,description:`${n.length} document(s) removed from "${t.path}"`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},[e,t.path,t.treeName,S,A,l]),M=(0,X.useCallback)(async n=>{try{await Ia(e,n,t.path,[],t.treeName,S),A(),l({title:`Deleted`,description:`${n.length} document(s) deleted.`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},[e,t.path,t.treeName,S,A,l]),N=(0,X.useCallback)(async t=>{try{let n=await Er(e,t);if(n.failed?.length&&!n.successful?.length){l({title:`Error`,description:n.failed[0].reason,variant:`destructive`});return}A(),l({title:`Destroyed`,description:`${n.successful?.length??t.length} document(s) removed from all backends.`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},[e,A,l]);return(0,Z.jsxs)(`div`,{className:K(`relative flex-1 min-w-0 rounded-lg border bg-background overflow-hidden`,n?`ring-2 ring-primary`:`ring-1 ring-primary/20`),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||a()},children:[c&&(0,Z.jsx)(`button`,{type:`button`,onClick:c,className:`absolute right-2 top-2 z-10 px-2 py-1 text-xs rounded-md border bg-background/90 hover:bg-accent`,children:`Close`}),(0,Z.jsx)(Xb,{urlType:w?`canvas`:S===`directory`?t.treeName:`context`,urlDisplay:D,contextPath:t.path,treeName:t.treeName,workspaceId:e,documents:f,isLoading:m,totalCount:g,currentPage:v,pageSize:b,onPageChange:y,onPageSizeChange:e=>{x(e),y(1)},onRemoveDocument:t.path===`/`?void 0:e=>j([e]),onRemoveDocuments:t.path===`/`?void 0:j,onDeleteDocument:e=>M([e]),onDeleteDocuments:M,onDestroyDocument:e=>N([e]),onDestroyDocuments:N,onCopyDocuments:e=>{i({documentIds:e,operation:`copy`,sourcePath:t.path,sourceTreeName:t.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}}))},onCutDocuments:e=>{i({documentIds:e,operation:`cut`,sourcePath:t.path,sourceTreeName:t.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}}))},onPasteDocuments:t.treeName===`backends`?void 0:k,onSelectionChange:o,pastedDocumentIds:r?.documentIds,linkTree:u,folders:T,onOpenFolder:s,canvasInfo:w?{label:C?.label,description:C?.description,color:C?.color}:void 0,children:E?.kind===`columns`?(0,Z.jsx)(lx,{documents:f,workspaceId:e,columns:E.columns??[],onColumnsChange:()=>{},readOnly:!0}):E?.kind===`app`&&E.app?(0,Z.jsx)(ox,{app:E.app,workspaceId:e,treeName:t.treeName,path:t.path}):null})]})}function Qx(e){let t=new URLSearchParams;return e?.mode===`context`&&t.set(`context`,e.contextId),e?.mode===`workspace`&&(t.set(`workspace`,e.workspaceName),t.set(`path`,e.path),t.set(`tree`,e.treeName)),t}var $x={id:`sketch`,label:`Sketch`,icon:re,schemas:[ro],canCreate:!0,canEdit:e=>e.schema===ro,createUrl(e){let t=Qx(e);return t.set(`add`,`1`),`/apps/sketch?${t.toString()}`},editUrl(e,t){let n=Qx(t);return n.set(`doc`,String(e.id)),`/apps/sketch?${n.toString()}`}},eS=[{kind:`message`,label:`New Message`,icon:v},{kind:`note`,label:`Note`,icon:vn},{kind:`link`,label:`Link`,icon:fn},{kind:`todo`,label:`Todo`,icon:zt},{kind:`identity`,label:`Identity`,icon:Ze},{kind:`sketch`,label:`Sketch`,icon:re},{kind:`file`,label:`File`,icon:ne},{kind:`photo`,label:`Photo/Video`,icon:w},{kind:`existing`,label:`Existing document`,icon:Qt},{kind:`folder`,label:`Folder`,icon:ot}];function tS(){return typeof navigator<`u`&&navigator.mediaDevices?.getUserMedia?eS:eS.filter(e=>e.kind!==`photo`)}function nS({onSelect:e,variant:t=`list`,omit:n}){let r=tS().filter(e=>!n?.includes(e.kind));return t===`stack`?(0,Z.jsx)(Z.Fragment,{children:r.map(({kind:t,label:n,icon:r})=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:`flex items-center gap-2 rounded-full bg-card px-3 py-1.5 text-sm font-medium shadow-elevation-3 transition-transform hover:scale-105`,children:[n,(0,Z.jsx)(r,{className:`h-3.5 w-3.5`})]},t))}):(0,Z.jsx)(`div`,{className:`p-2`,children:r.map(({kind:t,label:n,icon:r})=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:`flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-foreground transition-colors hover:bg-muted`,children:[(0,Z.jsx)(r,{className:`h-4 w-4 text-muted-foreground`}),n]},t))})}var rS=`data/schema/note`,iS=`2.0`;function aS(){let[e,t]=(0,X.useState)(``),[n,r]=(0,X.useState)(``),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)([]),[c,l]=(0,X.useState)(!1),u=Qm(),d=n.trim().length>0&&!c;async function f(t){l(!0);try{let r=await u.capture(),a={schema:rS,schemaVersion:iS,...i.trim()?{comment:i.trim()}:{},data:{...e.trim()?{title:e.trim()}:{},content:n},metadata:{features:dp(o),...r?{geo:r}:{}}};return await Yo(t,[a])}finally{l(!1)}}return{title:e,setTitle:t,content:n,setContent:r,comment:i,setComment:a,tags:o,setTags:s,saving:c,canSave:d,save:f,geotag:u}}function oS(e){if(e.manual){let t=`${e.manual.lat.toFixed(5)}, ${e.manual.lon.toFixed(5)}`;return e.manualLabel?`${e.manualLabel} · ${t}`:`Custom pin · ${t}`}if(!e.supported)return`Needs a secure (https) connection, or pick a point on the map`;if(e.permission===`denied`)return`Blocked. Allow location for this site, or pick a point on the map`;if(e.error)return e.error;if(e.busy)return`Getting your location…`;if(e.enabled&&e.fix){let{lat:t,lon:n,accuracy:r}=e.fix;return`${t.toFixed(5)}, ${n.toFixed(5)}${r==null?``:` · ±${r} m`}`}return e.enabled?`Location will be attached when you save`:`Attach where you are, or pick any point on the map`}function sS({geotag:e,idPrefix:t=`geotag`}){let[n,r]=(0,X.useState)(!1),i=!e.supported||e.permission===`denied`,a=!e.manual&&(!e.supported||e.permission===`denied`||!!e.error);return(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{role:`switch`,"aria-checked":e.enabled,"aria-disabled":i,"aria-label":`Geotag this document`,"aria-describedby":`${t}-hint`,tabIndex:i?-1:0,onClick:()=>!i&&e.setEnabled(!e.enabled),onKeyDown:t=>{i||(t.key===` `||t.key===`Enter`)&&(t.preventDefault(),e.setEnabled(!e.enabled))},className:K(`flex flex-1 items-center justify-between gap-3 select-none outline-none rounded focus-visible:ring-2 focus-visible:ring-ring`,i?`cursor-not-allowed opacity-50`:`cursor-pointer`),children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm text-foreground`,children:[e.busy?(0,Z.jsx)(Wn,{className:`h-4 w-4 shrink-0 animate-spin text-muted-foreground`}):(0,Z.jsx)(Zt,{className:K(`h-4 w-4 shrink-0`,e.enabled?`text-info`:`text-muted-foreground`)}),`Geotag`]}),(0,Z.jsx)(`div`,{className:K(`relative h-5 w-10 shrink-0 rounded-full transition-colors`,e.enabled?`bg-info`:`bg-muted-foreground/30`),children:(0,Z.jsx)(`div`,{className:K(`absolute top-[2px] h-4 w-4 rounded-full bg-background shadow-elevation-1 transition-transform`,e.enabled?`translate-x-[22px]`:`translate-x-[2px]`)})})]}),(0,Z.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r(!0),title:`Pick a point on the map`,className:`inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,Z.jsx)(jn,{className:`h-3.5 w-3.5`}),e.manual?`Change pin`:`Pick on map`]}),e.manual&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>e.setManual(null),"aria-label":`Remove custom pin`,title:`Remove custom pin`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(je,{className:`h-3.5 w-3.5`})})]})]}),(0,Z.jsx)(`p`,{id:`${t}-hint`,className:K(`text-xs`,a?`text-warning`:`text-muted-foreground`),children:oS(e)}),n&&(0,Z.jsx)(xp,{initial:e.manual??e.fix??null,onPick:t=>e.setManual(t),onClose:()=>r(!1)})]})}function cS(e){let t=`/workspaces/${encodeURIComponent(e.workspaceName)}`,n=e.path.replace(/^\/+/,``).split(`/`).map(encodeURIComponent).join(`/`);return e.treeName===`context`?`${t}/path/${n}`:`${t}/trees/${encodeURIComponent(e.treeName)}/path/${n}`}function lS({title:e,icon:t,onClose:n,onSave:r,navigateAfterSave:i=!1,canSave:a=!1,saving:o=!1,saveProgress:s,successMessage:c=`Saved`,lockedWorkspaceName:l,fillParent:u=!1,fullWidthContent:d=!1,relationSubjectId:f,frame:p,children:m}){let h=Gc(),[g,_]=(0,X.useState)(`portrait`),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(!1),[S,C]=(0,X.useState)(!1),[w,T]=(0,X.useState)(!1),E=o||w;gf(()=>x(!1),b&&!E),gf(()=>y(!1),v&&!b);let D=(0,X.useRef)(null),O=Cm(),{showSuccessToast:A,showErrorToast:j}=Ya(),M=O&&!u&&!v,[N,P]=(0,X.useState)(!1),ee=!u&&!v&&!p&&!N;(0,X.useEffect)(()=>{b&&D.current?.scrollIntoView({behavior:`smooth`,inline:`end`,block:`nearest`})},[b]);let F=async(e,t)=>{if(!(!r||E)){T(!0);try{let a=await r({...t,path:e[0]}),o=e.slice(1);a.length&&o.length&&await Promise.all(o.map(e=>qr(t.workspaceName,e,a,t.treeName,t.treeType))),A(c),n(),i&&h(cS({...t,path:e[0]}),{replace:!0})}catch(e){j(e instanceof Error?e.message:`Failed to save`)}finally{T(!1)}}},I=async e=>{if(!(!f||!l||e.targetIds.length===0)){C(!0);try{await Wi(l,f,e.predicate,e.targetIds,e.direction),A(`Created ${e.targetIds.length} relation${e.targetIds.length===1?``:`s`}`),Kp(),x(!1)}catch(e){j(e instanceof Error?e.message:`Failed to create relations`)}finally{C(!1)}}},te=v?b?{flex:`1 1 auto`,minWidth:0,height:`100%`}:{width:`100%`,height:`100%`}:u?{height:`100%`,flexShrink:0}:M?void 0:g===`portrait`?{aspectRatio:`0.707 / 1`,height:`calc(var(--viewport-h) * 0.85)`,width:`auto`,maxWidth:`min(90vw, 100%)`,flexShrink:0}:{aspectRatio:`1 / 0.707`,width:`min(90vw, 900px)`,maxWidth:`100%`,height:`auto`,maxHeight:`calc(var(--viewport-h) * 0.85)`,flexShrink:0},ne=!!(f&&l),L=r&&b&&(0,Z.jsx)(ap,{onClose:()=>x(!1),onConfirm:F,fixedWorkspaceName:l,saving:E||S,savingContent:s,tabs:ne?[`context`,`directory`,`relations`]:[`context`,`directory`],onConfirmRelation:ne?I:void 0,relationWorkspaceName:l,relationExcludeIds:ne?new Set([f]):void 0,sizeClassName:p?`h-full max-h-full w-full min-w-0 rounded-none border-0 shadow-none`:u?`h-full max-h-full w-[min(380px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`:void 0}),re=(0,Z.jsxs)(`div`,{style:p&&!v?{width:`100%`,height:`100%`,minWidth:0}:te,onAnimationEnd:e=>{ee&&e.target===e.currentTarget&&P(!0)},className:K(`flex flex-col overflow-hidden`,p&&!v?`strip-document-card`:`rounded-2xl border bg-card shadow-elevation-4 transition-[width,height]`,u&&!v&&!p&&`w-full md:w-[var(--document-card-width,min(560px,90vw))]`,M&&`fixed inset-2 z-40 shadow-elevation-5`,ee&&`animate-card-in`),children:[(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between gap-2 border-b px-4`,children:[(0,Z.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2 truncate text-sm font-medium`,children:[(0,Z.jsx)(t,{className:`h-4 w-4 shrink-0`}),(0,Z.jsx)(`span`,{className:`truncate`,children:e})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[!u&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>_(e=>e===`portrait`?`landscape`:`portrait`),className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground max-md:hidden touch-target`,"aria-label":`Toggle orientation`,title:`Toggle orientation`,children:(0,Z.jsx)(k,{className:`h-4 w-4`})}),r&&(0,Z.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>x(!0),disabled:!a||E,children:E?`Saving…`:`Save / Link to…`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p&&!v?p.onToggleExpanded():y(e=>!e),className:K(`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,!v&&!p&&`max-md:hidden`),"aria-label":p&&!v?p.expanded?`Card size`:`Expand to full width`:v?`Restore`:`Maximize`,title:p&&!v?p.expanded?`Card size`:`Expand to full width`:v?`Restore`:`Maximize`,children:v||p?.expanded?(0,Z.jsx)(ct,{className:`h-4 w-4`}):(0,Z.jsx)(gn,{className:`h-4 w-4`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,disabled:E,className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40 touch-target`,"aria-label":`Close`,children:(0,Z.jsx)(je,{className:`h-4 w-4`})})]})]}),(0,Z.jsx)(qp.Provider,{value:()=>y(e=>!e),children:(0,Z.jsx)(`div`,{className:K(`min-h-0 flex-1 overflow-y-auto`,v&&!d&&`mx-auto w-full max-w-3xl`),children:p&&L?L:m})})]});return v?(0,pf.createPortal)((0,Z.jsxs)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center gap-4 bg-scrim p-4 max-md:p-2`,children:[re,L&&(0,Z.jsx)(`div`,{className:`flex max-md:absolute max-md:inset-2 max-md:z-10`,children:L})]}),document.body):(0,Z.jsxs)(Z.Fragment,{children:[re,!p&&L&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-card bg-scrim animate-fade-in md:hidden`,onClick:()=>!E&&x(!1),"aria-hidden":!0}),(0,Z.jsx)(`div`,{ref:D,className:`relative shrink-0 md:z-panel md:ml-2 max-md:fixed max-md:bottom-2 max-md:left-2 max-md:right-2 max-md:top-2 max-md:z-card-overlay max-md:animate-fade-in`,children:L})]})]})}function uS({onClose:e,initialData:t}){let n=aS();return(0,X.useEffect)(()=>{t?.title&&n.setTitle(t.title),t?.content&&n.setContent(t.content)},[]),(0,Z.jsx)(lS,{title:`New Note`,icon:vn,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Note created`,children:(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`qa-note-title`,children:`Title`}),(0,Z.jsx)(q,{id:`qa-note-title`,value:n.title,onChange:e=>n.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,Z.jsxs)(`div`,{className:`flex flex-1 flex-col gap-1.5`,children:[(0,Z.jsx)(bu,{children:`Body`}),(0,Z.jsx)(`div`,{className:`flex-1`,children:(0,Z.jsx)(yo,{kind:`markdown`,value:n.content,onChange:n.setContent,placeholder:`Write your note…`})})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{children:`Tags`}),(0,Z.jsx)(up,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsx)(sS,{geotag:n.geotag,idPrefix:`qa-note-geotag`})]})})}var dS=`data/schema/tab`,fS=`2.0`;function pS(e){try{return new URL(e),!0}catch{return!1}}function mS(){let[e,t]=(0,X.useState)(``),[n,r]=(0,X.useState)(``),[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(!1),c=Qm(),l=e.trim(),u=pS(l),d=l.length>0&&!u,f=u&&!o;async function p(e){if(!u)throw Error(`Enter a valid URL`);s(!0);try{let t=await c.capture(),r=i.map(e=>e.trim()).filter(Boolean),a={schema:dS,schemaVersion:fS,data:{url:l,...n.trim()?{title:n.trim()}:{},...r.length?{tags:r}:{}},metadata:{features:dp(i),...t?{geo:t}:{}}};return await Yo(e,[a])}finally{s(!1)}}return{url:e,setUrl:t,title:n,setTitle:r,tags:i,setTags:a,saving:o,canSave:f,urlValid:u,showUrlError:d,save:p,geotag:c}}function hS({onClose:e,initialData:t}){let n=mS();return(0,X.useEffect)(()=>{t?.url&&n.setUrl(t.url),t?.title&&n.setTitle(t.title)},[]),(0,Z.jsx)(lS,{title:`New Link`,icon:fn,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Link created`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`qa-link-url`,children:`URL`}),(0,Z.jsx)(q,{id:`qa-link-url`,value:n.url,onChange:e=>n.setUrl(e.target.value),placeholder:`https://example.com`,autoFocus:!0}),n.showUrlError&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`qa-link-title`,children:`Title`}),(0,Z.jsx)(q,{id:`qa-link-title`,value:n.title,onChange:e=>n.setTitle(e.target.value),placeholder:`Optional display title`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{children:`Tags`}),(0,Z.jsx)(up,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsx)(sS,{geotag:n.geotag,idPrefix:`qa-link-geotag`})]})})}function gS({onClose:e,initialData:t}){let n=ch();return(0,X.useEffect)(()=>{t?.title&&n.setTitle(t.title),t?.content&&n.setDescription(t.content)},[]),(0,Z.jsx)(lS,{title:`New Todo`,icon:zt,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Todo created`,children:(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsx)(Jh,{...n,idPrefix:`qa-todo`}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{children:`Tags`}),(0,Z.jsx)(up,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`qa-todo-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`qa-todo-comment`,value:n.comment,onChange:e=>n.setComment(e.target.value),rows:3,placeholder:`Optional context`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]}),(0,Z.jsx)(sS,{geotag:n.geotag,idPrefix:`qa-todo-geotag`})]})})}function _S({onClose:e,initialData:t}){let n=rg();return(0,X.useEffect)(()=>{t?.title&&n.setDisplayName(t.title)},[]),(0,Z.jsx)(lS,{title:`New Identity`,icon:Ze,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Identity created`,children:(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsx)(cg,{idPrefix:`qa-identity`,...n,emailValid:n.emailValid}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{children:`Tags`}),(0,Z.jsx)(up,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`qa-identity-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`qa-identity-comment`,value:n.comment,onChange:e=>n.setComment(e.target.value),rows:3,placeholder:`How you know them, where they came from…`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]})]})})}var vS=3;function yS(e){return`${e.name}:${e.size}:${e.lastModified}`}function bS(e=[]){let[t,n]=(0,X.useState)(()=>e.map(e=>({id:yS(e),file:e,status:`queued`,progress:0}))),[r,i]=(0,X.useState)(!1),a=(0,X.useRef)(t),o=(0,X.useRef)(null),s=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>s.current?.abort(),[]);let c=(0,X.useCallback)(e=>{a.current=e,n(e)},[]),l=(0,X.useCallback)((e,t)=>{let r=a.current.map(n=>n.id===e?{...n,...t}:n);a.current=r,n(r)},[]),u=(0,X.useCallback)(e=>{let t=new Set(a.current.map(e=>e.id)),n=e.filter(e=>!t.has(yS(e))).map(e=>({id:yS(e),file:e,status:`queued`,progress:0}));n.length&&c([...a.current,...n])},[c]),d=(0,X.useCallback)(e=>{c(a.current.filter(t=>t.id!==e))},[c]),f=(0,X.useCallback)(()=>{s.current?.abort(),s.current=null,c([]),i(!1)},[c]),p=(0,X.useCallback)(()=>{s.current?.abort()},[]);return{items:t,running:r,addFiles:u,removeItem:d,reset:f,start:(0,X.useCallback)(async(e,t)=>{if(!e)throw Error(`No active workspace or context to add to`);let{workspaceName:n,treeName:r,path:u}=await cs(e),d=r===`backends`?await as(n,u):null,f=JSON.stringify([n,r,u]);o.current!==null&&o.current!==f&&c(a.current.map(({id:e,file:t})=>({id:e,file:t,status:`queued`,progress:0}))),o.current=f;let p=new AbortController;s.current=p,i(!0);let m=a.current.filter(e=>e.status!==`done`);for(let e of m)l(e.id,{status:`queued`,progress:0,error:void 0});try{if(d){let e=0;await Promise.all(Array.from({length:Math.min(vS,m.length)},async()=>{for(;e<m.length&&!p.signal.aborted;){let t=m[e++];try{l(t.id,{status:`uploading`,progress:0,resumed:!1});let e=await no(n,{...d,key:Go(d.key,t.file.name)},t.file,{signal:p.signal,onProgress:(e,n)=>l(t.id,{progress:n?e/n:0})});l(t.id,{status:`done`,progress:1,docId:e.docId??void 0})}catch(e){l(t.id,{status:`error`,error:e instanceof Error?e.message:`Upload failed`})}}}))}else{let r=new Map;for(let e of m){if(p.signal.aborted)throw new DOMException(`cancelled`,`AbortError`);l(e.id,{status:`hashing`});try{let t=await ls(e.file,t=>l(e.id,{progress:t}));r.set(e.id,t),l(e.id,{status:`checking`,progress:0})}catch(t){l(e.id,{status:`error`,error:t instanceof Error?t.message:`Failed to read file`})}}let i={};if(r.size)try{i=await ao(n,[...new Set(r.values())])}catch{i={}}let a=m.filter(e=>r.has(e.id)),o=0;await Promise.all(Array.from({length:Math.min(vS,a.length)},async()=>{for(;o<a.length;){if(p.signal.aborted)return;let s=a[o++],c=r.get(s.id);try{let r=i[c]??null;r?l(s.id,{status:`linking`,progress:1,resumed:!0}):(l(s.id,{status:`uploading`,progress:0}),r=await $a(n,s.file,{signal:p.signal,onProgress:(e,t)=>l(s.id,{progress:t?e/t:0})}),l(s.id,{status:`linking`,progress:1}));let a=await Yo(e,[t(r,s.file)],{refresh:!1});l(s.id,{status:`done`,docId:a[0]})}catch(e){let t=e instanceof DOMException&&e.name===`AbortError`;l(s.id,{status:`error`,error:t?`Cancelled`:e instanceof Error?e.message:`Upload failed`})}}}))}}finally{if(p.signal.aborted)for(let e of a.current)e.status!==`done`&&e.status!==`error`&&l(e.id,{status:`error`,error:`Cancelled`});i(!1),s.current===p&&(s.current=null),a.current.some(e=>e.status===`done`)&&qo(e)}let h=a.current;return{done:h.filter(e=>e.status===`done`).length,resumed:h.filter(e=>e.status===`done`&&e.resumed).length,failed:h.filter(e=>e.status===`error`).length,total:h.length,docIds:h.flatMap(e=>e.status===`done`&&e.docId!=null?[e.docId]:[])}},[l,c]),cancel:p}}function xS(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function SS(e){switch(e.status){case`hashing`:return`hashing`;case`checking`:return`checking`;case`uploading`:return`${Math.round(e.progress*100)}%`;case`linking`:return`saving`;case`done`:return e.resumed?`already uploaded`:`done`;case`error`:return e.error||`failed`;default:return xS(e.file.size)}}function CS({item:e}){switch(e.status){case`done`:return(0,Z.jsx)(ur,{className:`h-3.5 w-3.5 shrink-0 text-green-600 dark:text-green-500`});case`error`:return(0,Z.jsx)(be,{className:`h-3.5 w-3.5 shrink-0 text-destructive`});case`queued`:return(0,Z.jsx)(Bn,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`});default:return(0,Z.jsx)(Wn,{className:`h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground`})}}function wS({item:e}){if(e.status===`queued`)return null;let t=e.status===`done`||e.status===`error`||e.status===`linking`?1:e.status===`checking`?0:e.progress;return(0,Z.jsx)(`div`,{className:`h-1 w-full overflow-hidden rounded-full bg-muted`,children:(0,Z.jsx)(`div`,{className:K(`h-full rounded-full transition-[width] duration-200`,e.status===`error`?`bg-destructive`:e.status===`done`?`bg-green-600 dark:bg-green-500`:`bg-primary`),style:{width:`${Math.round(t*100)}%`}})})}function TS({items:e,running:t,onRemove:n}){let r=e.filter(e=>e.status===`done`).length,i=e.filter(e=>e.status===`error`).length;return(0,Z.jsx)(Z.Fragment,{children:e.length>0&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(bu,{children:[e.length,` file(s)`,r>0&&(0,Z.jsxs)(`span`,{className:`ml-1 text-muted-foreground`,children:[`— `,r,` done`,i>0?`, ${i} failed`:``]})]}),(0,Z.jsx)(`ul`,{className:`max-h-48 space-y-1 overflow-y-auto`,children:e.map(e=>(0,Z.jsxs)(`li`,{className:`flex flex-col gap-1 rounded border border-input px-2 py-1 text-sm`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(CS,{item:e}),(0,Z.jsx)(`span`,{className:`flex-1 truncate`,title:e.file.name,children:e.file.name}),(0,Z.jsx)(`span`,{className:K(`shrink-0 text-xs`,e.status===`error`?`text-destructive`:`text-muted-foreground`),title:e.status===`error`?e.error:void 0,children:SS(e)}),!t&&e.status!==`done`&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>n(e.id),className:`text-muted-foreground hover:text-foreground`,"aria-label":`Remove ${e.file.name}`,children:(0,Z.jsx)(je,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsx)(wS,{item:e})]},e.id))})]})})}function ES({items:e,running:t,onCancel:n}){return(0,Z.jsxs)(`div`,{className:`space-y-4 overflow-y-auto p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-medium`,children:`Uploading files`}),!t&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:`Preparing / finishing upload…`}),(0,Z.jsx)(TS,{items:e,running:!0,onRemove:()=>{}}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,disabled:!t,onClick:n,children:`Cancel upload`})]})}function DS(e){let[t,n]=(0,X.useState)(null);return(0,X.useEffect)(()=>{if(!e)return;let t=!1;return Tr(e).then(r=>{t||n({workspace:e,tags:r})}).catch(()=>{}),()=>{t=!0}},[e]),t&&t.workspace===e?t.tags:[]}var OS=`data/schema/file`,kS=`3.0`;function AS(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(``);return{tags:t,setTags:n,comment:r,setComment:i,suggestions:DS(e),geotag:Qm()}}function jS(e,t,n={}){let r=dp(n.tags??[]),i=n.comment?.trim();return{schema:OS,schemaVersion:kS,data:{},checksumArray:[`sha256/${e.checksum}`],locations:[{url:e.url,metadata:{filename:t.name}}],...i?{comment:i}:{},metadata:{contentType:t.type,size:e.size,...r.length?{features:r}:{},...n.geo?{geo:n.geo}:{}}}}var MS=`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`;function NS({fields:e,idPrefix:t=`file`,multiple:n=!1}){return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{children:`Tags`}),(0,Z.jsx)(up,{tags:e.tags,onChange:e.setTags,suggestions:e.suggestions})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`${t}-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`${t}-comment`,value:e.comment,onChange:t=>e.setComment(t.target.value),rows:3,placeholder:`Optional; searchable, and the only text a photo has`,className:MS}),n&&e.tags.length+e.comment.trim().length>0&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Applied to every file in this upload`})]}),(0,Z.jsx)(sS,{geotag:e.geotag,idPrefix:`${t}-geotag`})]})}var PS={jpg:`image/jpeg`,jpeg:`image/jpeg`,png:`image/png`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,heic:`image/heic`,heif:`image/heif`,bmp:`image/bmp`,tif:`image/tiff`,tiff:`image/tiff`,svg:`image/svg+xml`,mp4:`video/mp4`,mov:`video/quicktime`,webm:`video/webm`,"3gp":`video/3gpp`};function FS(e){return/^(image|video)\//.test(e.type)}async function IS(e){let t=await Promise.all(e.map(async e=>{let t=new Uint8Array(await e.slice(0,64).arrayBuffer()),n=(e,n)=>String.fromCharCode(...t.slice(e,e+n)),r=``;if(t[0]===255&&t[1]===216&&t[2]===255)r=`image/jpeg`;else if(n(0,8)===`PNG\r
|
|
11
|
+
|
|
12
|
+
`)r=`image/png`;else if([`GIF87a`,`GIF89a`].includes(n(0,6)))r=`image/gif`;else if(n(0,4)===`RIFF`&&n(8,4)===`WEBP`)r=`image/webp`;else if(n(0,5)===`%PDF-`)r=`application/pdf`;else if(n(0,4)===`PK`)r=`application/zip`;else if(n(4,4)===`ftyp`){let e=[n(8,4)],i=new DataView(t.buffer).getUint32(0);for(let r=16;r+4<=Math.min(t.length,i);r+=4)e.push(n(r,4));e.some(e=>[`avif`,`avis`].includes(e))?r=`image/avif`:e.some(e=>[`heic`,`heix`,`hevc`,`hevx`].includes(e))?r=`image/heic`:e.some(e=>[`mif1`,`msf1`].includes(e))?r=`image/heif`:e.includes(`qt `)?r=`video/quicktime`:e.some(e=>[`isom`,`iso2`,`mp41`,`mp42`,`avc1`,`M4V `].includes(e))&&(r=`video/mp4`)}let i=e.type.toLowerCase().split(`;`)[0].trim(),a=!i||[`application/octet-stream`,`binary/octet-stream`,`*/*`].includes(i),o=e.name.split(`.`).pop()?.toLowerCase()??``,s=r||a&&PS[o]||i;return s===e.type?e:new File([e],e.name,{type:s,lastModified:e.lastModified})}));return{kind:t.length>0&&t.every(FS)?`photo`:`file`,files:t}}function LS({file:e}){let t=(0,X.useRef)(null),[n,r]=(0,X.useState)(!1);return(0,X.useEffect)(()=>{let n=t.current;if(!n)return;let r=URL.createObjectURL(e);return n.src=r,()=>{n.removeAttribute(`src`),URL.revokeObjectURL(r)}},[e]),(0,Z.jsx)(`div`,{className:`flex min-h-24 items-center justify-center overflow-hidden rounded-md border border-input bg-muted/30`,children:n?(0,Z.jsxs)(`p`,{className:`p-4 text-center text-sm text-muted-foreground`,children:[`Preview unavailable for `,e.name,`. You can still save the original.`]}):e.type.startsWith(`video/`)?(0,Z.jsx)(`video`,{ref:t,controls:!0,preload:`metadata`,"aria-label":e.name,onError:()=>r(!0),className:`max-h-64 max-w-full`}):(0,Z.jsx)(`img`,{ref:t,alt:e.name,onError:()=>r(!0),className:`max-h-64 max-w-full object-contain`})})}function RS({onClose:e,initialData:t}){let n=(0,X.useRef)(null),r=bS(t?.files),i=r.items.map(e=>e.file),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(!1),{state:l}=hs(),u=AS(l.activeWorkspaceName),d=e=>{e&&(s||r.addFiles(Array.from(e)))},f=e=>{e.preventDefault(),o(!1),d(e.dataTransfer.files)},p=i.length>0;return(0,Z.jsx)(lS,{title:`Upload File`,icon:ne,onClose:e,onSave:async e=>{c(!0);try{let t={mode:`workspace`,...e},n=await u.geotag.capture(),i=await r.start(t,(e,t)=>jS(e,t,{tags:u.tags,comment:u.comment,geo:n}));if(i.failed)throw Error(`${i.failed} file(s) failed or cancelled. Retry keeps completed uploads.`);return i.docIds}finally{c(!1)}},navigateAfterSave:!0,canSave:p,saving:s,saveProgress:(0,Z.jsx)(ES,{items:r.items,running:r.running,onCancel:r.cancel}),successMessage:`File(s) uploaded`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),o(!0)},onDragLeave:()=>o(!1),onDrop:f,onClick:()=>n.current?.click(),className:K(`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-md border border-dashed px-4 py-8 text-center transition-colors`,a?`border-primary bg-primary/5`:`border-input hover:bg-muted/40`),children:[(0,Z.jsx)(ne,{className:`h-6 w-6 text-muted-foreground touch-target`}),(0,Z.jsx)(`p`,{className:`text-sm`,children:`Drag & drop files here`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`or click to browse`}),(0,Z.jsx)(`input`,{ref:n,type:`file`,multiple:!0,disabled:s,className:`hidden`,onChange:e=>{d(e.target.files),e.target.value=``}})]}),r.items.filter(e=>FS(e.file)).map(e=>(0,Z.jsx)(LS,{file:e.file},e.id)),(0,Z.jsx)(TS,{items:r.items,running:s,onRemove:r.removeItem}),(0,Z.jsx)(NS,{fields:u,idPrefix:`qa-file`,multiple:i.length>1})]})})}function zS({onClose:e,initialData:t}){let n=bS(t?.files),r=(0,X.useRef)(null),i=n.items.length>0,[a,o]=(0,X.useState)(!1),{state:s}=hs(),c=AS(s.activeWorkspaceName),l=e=>{!a&&e&&n.addFiles([e])};return(0,Z.jsx)(lS,{title:`Photo/Video`,icon:w,onClose:e,onSave:async e=>{if(!i)return[];o(!0);try{let t=await c.geotag.capture(),r={mode:`workspace`,...e},i=await n.start(r,(e,n)=>jS(e,n,{tags:c.tags,comment:c.comment,geo:t}));if(i.failed)throw Error(`Upload failed or cancelled. You can retry.`);return i.docIds}finally{o(!1)}},navigateAfterSave:!0,canSave:i,saving:a,saveProgress:(0,Z.jsx)(ES,{items:n.items,running:n.running,onCancel:n.cancel}),successMessage:`Upload saved`,children:(0,Z.jsxs)(`div`,{className:K(`flex h-full flex-col gap-4 p-4`,!i&&`items-center justify-center`),children:[i?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`flex min-h-0 w-full flex-1 flex-col gap-3 overflow-y-auto`,children:n.items.map(({id:e,file:t,status:r})=>(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(LS,{file:t}),(0,Z.jsxs)(`div`,{className:`flex w-full items-center gap-2 rounded border border-input px-3 py-2 text-sm`,children:[(0,Z.jsx)(Bn,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`flex-1 truncate`,children:t.name}),(0,Z.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:[(t.size/1024/1024).toFixed(1),` MB`]}),(0,Z.jsx)(`button`,{type:`button`,disabled:a||r===`done`,onClick:()=>n.removeItem(e),"aria-label":`Remove ${t.name}`,className:`text-muted-foreground hover:text-foreground disabled:opacity-40`,children:(0,Z.jsx)(je,{className:`h-3.5 w-3.5`})})]})]},e))}),(0,Z.jsx)(`div`,{className:`w-full shrink-0 space-y-4`,children:(0,Z.jsx)(NS,{fields:c,idPrefix:`qa-photo`,multiple:n.items.length>1})})]}):(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r.current?.click(),className:`flex flex-col items-center gap-2 rounded-md border border-dashed border-input px-6 py-10 text-center transition-colors hover:bg-muted/40`,children:[(0,Z.jsx)(w,{className:`h-8 w-8 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-sm`,children:`Open camera`})]}),(0,Z.jsx)(`input`,{ref:r,type:`file`,accept:`image/*,video/*`,capture:`environment`,className:`hidden`,disabled:a,onChange:e=>{l(e.target.files?.[0]??null),e.target.value=``}})]})})}var BS=`shrink-0 h-viewport-card w-[min(380px,90vw)] max-md:fixed max-md:inset-2 max-md:z-40 max-md:h-auto max-md:w-auto max-md:shadow-elevation-5`;function VS({onClose:e}){let{showSuccessToast:t,showErrorToast:n}=Ya(),[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)(!1);return r?(0,Z.jsx)(ap,{sizeClassName:BS,documentCount:r.length,saving:a,onClose:e,onConfirm:async(i,a)=>{o(!0);try{await Promise.all(i.map(e=>qr(a.workspaceName,e,r,a.treeName,a.treeType))),t(`${r.length} document${r.length===1?``:`s`} linked`),e()}catch(e){n(e instanceof Error?e.message:`Failed to link documents`)}finally{o(!1)}}}):(0,Z.jsx)(jp,{sizeClassName:BS,onConfirm:e=>{e.length&&i(e)},onClose:e})}var HS=0;function US(){return HS+=1,`card-${HS}`}function WS({initialKind:e,initialData:t,onInitialCardClose:n,onCardsOpenChange:r}){let[i,a]=(0,X.useState)(!1),o=Cm(),s=Ao(),c=!!(s?.state.t1Open||s?.state.addOpen),[l,u]=(0,X.useState)(()=>e?[{id:`initial`,kind:e,initialData:t}]:[]),d=l.length>0,f=(0,X.useRef)(r);(0,X.useEffect)(()=>{f.current=r},[r]),(0,X.useEffect)(()=>{f.current?.(d)},[d]),c&&i&&a(!1);let p=Gc(),m=e=>{if(e===`sketch`){a(!1),p($x.createUrl(null));return}u(t=>[...t,{id:US(),kind:e}]),a(!1)},h=e=>{u(t=>t.filter(t=>t.id!==e)),e===`initial`&&n?.()},g=(0,Z.jsxs)(`div`,{className:K(`pointer-events-none fixed right-6 z-40 flex flex-col items-end gap-2`,`bottom-fab-inset md:bottom-[calc(var(--spacing-fab-inset)+5rem)]`,l.length>0&&`max-md:hidden`,c&&`hidden`),children:[(0,Z.jsx)(`div`,{className:K(`flex flex-col items-end gap-2 transition-all duration-150`,i?`pointer-events-auto opacity-100`:`pointer-events-none translate-y-2 opacity-0`),children:(0,Z.jsx)(nS,{variant:`stack`,omit:[`folder`,`message`],onSelect:m})}),(0,Z.jsx)(`div`,{className:`pointer-events-none flex w-16 justify-center`,children:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>a(e=>!e),"aria-label":i?`Close quick add`:`Quick add`,className:`pointer-events-auto flex h-11 w-11 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-elevation-3 transition-transform hover:scale-105`,children:i?(0,Z.jsx)(je,{className:`h-5 w-5`}):(0,Z.jsx)(nn,{className:`h-5 w-5`})})})]});return(0,Z.jsxs)(`div`,{className:`relative flex h-full w-full flex-col`,children:[l.length>0&&(0,Z.jsx)(`div`,{className:`pointer-events-auto flex flex-1 items-center gap-4 overflow-x-auto p-6 md:pr-28`,children:l.map(e=>{let t=()=>h(e.id);switch(e.kind){case`note`:return(0,Z.jsx)(uS,{onClose:t,initialData:e.initialData},e.id);case`link`:return(0,Z.jsx)(hS,{onClose:t,initialData:e.initialData},e.id);case`todo`:return(0,Z.jsx)(gS,{onClose:t,initialData:e.initialData},e.id);case`identity`:return(0,Z.jsx)(_S,{onClose:t,initialData:e.initialData},e.id);case`file`:return(0,Z.jsx)(RS,{onClose:t,initialData:e.initialData},e.id);case`photo`:return(0,Z.jsx)(zS,{onClose:t,initialData:e.initialData},e.id);case`existing`:return(0,Z.jsx)(VS,{onClose:t},e.id);case`sketch`:return null;case`folder`:case`message`:return null}})}),o?(0,pf.createPortal)(g,document.body):g]})}function GS(e){let t=`${e.workspaceName}\0${e.treeName}\0${e.path}`,[n,r]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let n=!1;return Ca(e.workspaceName,e.treeName).then(i=>{n||r({key:t,node:xr(i,e.path)})}).catch(()=>{n||r({key:t,node:null})}),()=>{n=!0}},[t,e.workspaceName,e.treeName,e.path]),!n||n.key!==t?{state:`loading`}:n.node?{state:`ready`,node:n.node}:{state:`missing`}}function KS(e){let t=`/workspaces/${encodeURIComponent(e.workspaceName)}`,n=e.path.replace(/^\//,``);return e.treeName===`context`?`${t}/path/${n}`:`${t}/trees/${encodeURIComponent(e.treeName)}/path/${n}`}var qS=`application/x-canvas-pin`;function JS({pin:e,onUnpin:t,onMinimize:n,onDropPin:r}){let i=GS(e),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),l=!!r&&!a,u=e=>{let t=e.currentTarget.getBoundingClientRect();return e.clientX>t.left+t.width/2?`after`:`before`},d=l?{onDragOver:e=>{e.dataTransfer.types.includes(`application/x-canvas-pin`)&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,c(u(e)))},onDragLeave:()=>c(null),onDrop:t=>{let n=t.dataTransfer.getData(qS);c(null),!(!n||n===e.id)&&(t.preventDefault(),r?.(n,u(t)===`after`))}}:{},f=i.state===`ready`?i.node:null,p=f?.label||e.label||e.path.split(`/`).filter(Boolean).pop()||`Canvas`,m=f?.color;return(0,X.useEffect)(()=>{if(!a)return;let e=e=>{e.key===`Escape`&&o(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[a]),(0,Z.jsxs)(`section`,{...d,className:a?`fixed inset-0 z-picker flex flex-col bg-background`:`flex flex-col rounded-lg border bg-background overflow-hidden min-h-0 min-w-0 ${s?`ring-2 ring-primary/60`:``}`,children:[(0,Z.jsxs)(`header`,{draggable:l,onDragStart:l?t=>{t.dataTransfer.setData(qS,e.id),t.dataTransfer.effectAllowed=`move`}:void 0,className:`flex items-center gap-2 px-3 py-2 border-b bg-muted/20 shrink-0 min-w-0 ${l?`cursor-grab active:cursor-grabbing`:``}`,children:[l&&(0,Z.jsx)(lr,{className:`w-3.5 h-3.5 shrink-0 text-muted-foreground/60`,"aria-hidden":!0}),m&&(0,Z.jsx)(`div`,{className:`w-1 h-5 rounded-full shrink-0`,style:{backgroundColor:m}}),(0,Z.jsx)(mt,{className:`w-4 h-4 shrink-0 text-primary`}),(0,Z.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-semibold leading-tight truncate`,children:p}),(0,Z.jsxs)(`span`,{className:`text-[11px] text-muted-foreground truncate leading-tight font-mono`,children:[e.workspaceName,`://`,e.path.replace(/^\//,``)]})]}),n&&(0,Z.jsx)(`button`,{type:`button`,onClick:n,title:`Minimize to tab bar`,"aria-label":`Minimize to tab bar`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-md text-muted-foreground hover:bg-accent hover:text-foreground transition-colors`,children:(0,Z.jsx)(fe,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>o(e=>!e),"aria-pressed":a,title:a?`Restore tile (Esc)`:`Fill view area`,"aria-label":a?`Restore tile`:`Fill view area`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-md text-muted-foreground hover:bg-accent hover:text-foreground transition-colors`,children:a?(0,Z.jsx)(ct,{className:`w-3.5 h-3.5`}):(0,Z.jsx)(gn,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(cu,{to:KS(e),title:`Open in workspace`,"aria-label":`Open in workspace`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-md text-muted-foreground hover:bg-accent hover:text-foreground transition-colors`,children:(0,Z.jsx)(Gn,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:t,title:`Unpin from home`,"aria-label":`Unpin from home`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-md text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors`,children:(0,Z.jsx)(te,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0`,children:[i.state===`loading`&&(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full text-xs text-muted-foreground`,children:`Loading…`}),i.state===`missing`&&(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-2 px-4 text-center`,children:[(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`This canvas is no longer available.`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`It may have been renamed, moved or deleted.`}),(0,Z.jsx)(`button`,{type:`button`,onClick:t,className:`mt-1 px-2.5 py-1 text-xs border rounded-md hover:bg-accent`,children:`Remove pin`})]}),i.state===`ready`&&(0,Z.jsx)(Ov,{workspaceId:e.workspaceName,treeName:e.treeName,path:e.path,layerId:i.node.id,querySpec:i.node.querySpec,metadata:i.node.metadata,readOnly:!0})]})]})}function YS(e,t,n){let r=Promise.resolve();return i=>{let a=r.then(async()=>{let r=await e(),a=i(r.home?.pinnedCanvases??[]);n(await t({...r,home:{...r.home,pinnedCanvases:a}}))});return r=a.catch(()=>{}),a}}function XS(e,t){return e.minimized===!0||t.has(e.id)}function ZS(e){return e.label||e.path.split(`/`).filter(Boolean).pop()||`Canvas`}function QS({pins:e,onRestore:t}){let[n,r]=(0,X.useState)(!1),[i,a]=(0,X.useState)(e.length);return i!==e.length&&(a(e.length),e.length===0&&r(!1)),e.length===0?null:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`pointer-events-none absolute bottom-0 left-0 right-0 z-40 max-md:hidden`,children:(0,Z.jsx)(`div`,{className:`pointer-events-auto flex items-end gap-1 overflow-x-auto px-3 pr-28 pb-safe-bottom`,children:e.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>t(e.id),title:`Restore ${ZS(e)}`,className:`flex max-w-[180px] shrink-0 items-center gap-1.5 rounded-t-lg border border-b-0 bg-background px-3 py-1.5 text-xs shadow-elevation-1 hover:bg-accent`,children:[(0,Z.jsx)(mt,{className:`h-3.5 w-3.5 shrink-0 text-primary`}),(0,Z.jsx)(`span`,{className:`truncate`,children:ZS(e)})]},e.id))})}),n&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-drawer md:hidden`,onClick:()=>r(!1),"aria-hidden":!0}),(0,Z.jsx)(`div`,{className:`fixed bottom-rail-stack left-2 z-rail w-60 max-w-[calc(100vw-1rem)] rounded-xl border bg-card p-1.5 shadow-elevation-5 animate-fade-in md:hidden touch-target`,children:e.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>t(e.id),className:`flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-sm hover:bg-accent`,children:[(0,Z.jsx)(mt,{className:`h-4 w-4 shrink-0 text-primary`}),(0,Z.jsx)(`span`,{className:`truncate`,children:ZS(e)})]},e.id))})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r(e=>!e),"aria-label":n?`Close minimized canvases`:`Minimized canvases (${e.length})`,className:`fixed bottom-rail-inset left-16 z-nav flex h-12 w-12 items-center justify-center rounded-full bg-foreground text-background shadow-elevation-4 md:hidden`,children:[(0,Z.jsx)(mt,{className:`h-5 w-5`}),(0,Z.jsx)(`span`,{className:`absolute -top-1 -right-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-semibold`,children:e.length})]})]})}function $S(){let{pins:e,unpin:t,movePin:n,setMinimized:r,isLoading:i}=Ex(),{showErrorToast:a}=Ya(),[o,s]=(0,X.useState)(new Set),c=(0,X.useRef)(e);(0,X.useEffect)(()=>{c.current=e},[e]);let l=e=>{r(e,!0).catch(()=>a(`Could not save minimized state`))},u=t=>{s(e=>{let n=new Set(e);return n.delete(t),n}),e.find(e=>e.id===t)?.minimized&&r(t,!1).catch(()=>a(`Could not save restored state`))},d=(0,X.useCallback)(e=>{s(e?new Set(c.current.filter(e=>!e.minimized).map(e=>e.id)):new Set)},[]),f=e.filter(e=>!XS(e,o)),p=e.filter(e=>XS(e,o)),m=(t,r,i)=>{let a=e.findIndex(e=>e.id===r.id);if(a===-1)return;let o=i?e[a+1]?.id??null:r.id;n(t,o)};return(0,Z.jsxs)(`div`,{className:`relative h-full`,children:[(0,Z.jsx)(`div`,{className:`h-full overflow-y-auto`,children:i?(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full text-xs text-muted-foreground`,children:`Loading…`}):(0,Z.jsx)(`div`,{className:`grid gap-4 p-4 h-full grid-cols-[repeat(auto-fit,minmax(min(640px,100%),1fr))] auto-rows-fr ${p.length>0?`md:pb-12`:``}`,children:f.map(e=>(0,Z.jsx)(JS,{pin:e,onUnpin:()=>{t(e.id)},onMinimize:()=>l(e.id),onDropPin:(t,n)=>m(t,e,n)},e.id))})}),(0,Z.jsx)(`div`,{className:`pointer-events-none absolute inset-0`,children:(0,Z.jsx)(WS,{onCardsOpenChange:d})}),(0,Z.jsx)(QS,{pins:p,onRestore:u})]})}function eC(){return(0,Z.jsx)(`div`,{className:`h-full w-full`,"aria-hidden":!0})}var tC=`share-target-inbox`,nC={"too-large":`Android shares are limited to 100 MiB in total for temporary device storage. Nothing was uploaded. Use Add File to upload larger files directly.`,"stash-failed":`Canvas couldn't hold on to the shared file — device storage may be full. Try again, or upload it from the app.`,"empty-share":`Canvas received no files or text from the sharing app. Try again, or use Add File to select the photo directly.`,"empty-file":`The sharing app delivered an empty file. Try again, or use Add File to select the original directly.`,expired:`Nothing shared, or the share expired.`};async function rC(e){let t=await caches.open(tC),n=null,r=Date.now()+3e5;for(;Date.now()<r;){let r=await t.match(`/share-target-inbox/${e}/meta`);if(!r)return null;if(n=await r.json(),n?.status===`error`)throw Error(n.error||`stash-failed`);if(n?.status!==`receiving`)break;await new Promise(e=>setTimeout(e,300))}if(!n||n.status===`receiving`)throw Error(`stash-failed`);let i=[];for(let r=0;r<n.fileNames.length;r++){let a=await t.match(`/share-target-inbox/${e}/file-${r}`);if(!a)throw Error(`stash-failed`);let o=await a.blob();i.push(new File([o],n.fileNames[r],{type:o.type}))}let a=i.length?await IS(i):null;if(await Promise.all(n.fileNames.map((n,r)=>t.delete(`/share-target-inbox/${e}/file-${r}`))),await t.delete(`/share-target-inbox/${e}/meta`),a)return{kind:a.kind,data:{files:a.files}};if(![n.title,n.text,n.url].some(e=>e.trim()))throw Error(`empty-share`);let o=n.text.trim(),s=n.url||(oC(o)?o:``);return s?{kind:`link`,data:{url:s,title:n.title}}:{kind:`note`,data:{title:n.title,content:n.text}}}var iC=new Map;function aC(e){let t=iC.get(e);return t||(t=rC(e),iC.set(e,t),t.finally(()=>setTimeout(()=>iC.delete(e),6e4)).catch(()=>{})),t}function oC(e){if(!e||/\s/.test(e))return!1;try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}}function sC(){let[e]=mu(),t=Gc(),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null);(0,X.useEffect)(()=>{let t=!1;async function n(){let n=e.get(`error`);if(n){a(n);return}let i=e.get(`token`),o=i?await aC(i):null;t||(o?r(o):a(`expired`))}return n().catch(e=>{t||a(e instanceof Error?e.message:`stash-failed`)}),()=>{t=!0}},[e]);let o=()=>t(`/home`,{replace:!0});return i?(0,Z.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 px-6 text-center`,children:[(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:nC[i]??nC.expired}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(`/apps/add/file`,{replace:!0}),className:`text-sm font-medium text-primary underline underline-offset-4`,children:`Add File`}),(0,Z.jsx)(`button`,{type:`button`,onClick:o,className:`text-sm font-medium text-primary underline underline-offset-4`,children:`Go to Canvas`})]}):n?(0,Z.jsx)(WS,{initialKind:n.kind,initialData:n.data,onInitialCardClose:o}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center text-sm text-muted-foreground`,children:`Receiving shared content on this device… No upload has started.`})}function cC(e,t=`An error occurred`){if(e instanceof Error)return e.message;if(typeof e==`object`&&e){let n=e;return n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||t}return t}function lC(e,t,n=`An error occurred`){return console.error(t,e),cC(e,n)}function uC({value:e,onChange:t,onPickTarget:n,fixedWorkspaceName:r,format:i=`url`,tabs:a=[`context`,`directory`],pickerTitle:o=`Pick a path…`,placeholder:s,id:c,disabled:l,className:u,inputClassName:d}){let[f,p]=(0,X.useState)(!1);return(0,Z.jsxs)(`div`,{className:K(`flex gap-2`,u),children:[(0,Z.jsx)(q,{id:c,value:e,onChange:e=>t(e.target.value),placeholder:s,disabled:l,className:K(`font-mono`,d)}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`icon`,onClick:()=>p(!0),disabled:l,"aria-label":`Browse tree paths`,title:`Browse…`,className:`shrink-0`,children:(0,Z.jsx)(L,{className:`h-4 w-4`})}),f&&(0,Z.jsx)(sp,{onClose:()=>p(!1),children:(0,Z.jsx)(ap,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,multiple:!1,tabs:a,fixedWorkspaceName:r,title:o,confirmLabel:`Use path`,onConfirm:(e,r)=>{p(!1);let a=e[0];if(a){if(n){n(a,r);return}t(i===`url`?`${r.workspaceName}://${a.replace(/^\/+/,``)}`:a)}},onClose:()=>p(!1)})})]})}function dC(){let e=Gc(),[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(!0),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)(`context`),[h,g]=(0,X.useState)(`/`),[_,v]=(0,X.useState)(``),[y,b]=(0,X.useState)(`/`),[x,S]=(0,X.useState)(``),[C,w]=(0,X.useState)(!1),[T,E]=Jy(),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(null),{showToast:j}=oo();(0,X.useEffect)(()=>{Wu.isConnected()||(console.log(`Socket not connected, attempting to connect...`),Wu.reconnect())},[]);let M=(0,X.useCallback)(async()=>{try{o(!0);let[e,t]=await Promise.all([Uo(),Or()]),r=e?.filter(e=>e&&typeof e==`object`&&e.id&&e.userId)||[];n(r);let a=t||[];if(i(a),a.length>0){let e=a.some(e=>e.id===x);(!x||!e)&&S(a[0].id)}else S(``);c(null)}catch(e){console.error(`Data fetch error:`,e),n([]),i([]);let t=`Failed to fetch data`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to fetch data`}c(t),j({title:`Error`,description:t,variant:`destructive`})}finally{o(!1)}},[x,j]);(0,X.useEffect)(()=>{M()},[M]),(0,X.useEffect)(()=>{let e=()=>Wu.emit(`subscribe`,{channel:`context`}),t=()=>Wu.emit(`unsubscribe`,{channel:`context`}),r=Wu.on(`connect`,e);console.log(`Subscribing to context events`),e();let i=e=>{let t=e;if(console.log(`Received context created:`,t),!t||!t.id||!t.userId){console.error(`Invalid context data received in context:created event:`,t);return}n(e=>e.some(e=>e&&e.id===t.id&&e.userId===t.userId)?(console.log(`Context ${t.id} already exists, skipping duplicate add`),e):[...e,t])},a=e=>{let t=e;if(console.log(`Received context update:`,t),!t||!t.id||!t.userId){console.error(`Invalid context data received in context:updated event:`,t);return}n(e=>e.map(e=>e&&e.id===t.id&&e.userId===t.userId?{...e,...t}:e))},o=e=>{let t=e;console.log(`Received context deletion:`,t);let r=t?.contextId??t?.id;if(!r){console.error(`Invalid context deletion data received:`,t);return}n(e=>e.filter(e=>e&&e.id!==r))},s=e=>{let t=e;if(console.log(`Received context URL change:`,t),!t||!t.id||!t.userId){console.error(`Invalid context data received in context:url:changed event:`,t);return}n(e=>e.map(e=>e&&e.id===t.id&&e.userId===t.userId?{...e,...t}:e))},c=[[`context:created`,i],[`context.created`,i],[`context:updated`,a],[`context.updated`,a],[`context:deleted`,o],[`context.deleted`,o],[`context:url:changed`,s],[`context.url.set`,s],[`context:url:set`,s]];return c.forEach(([e,t])=>Wu.on(e,t)),()=>{console.log(`Unsubscribing from context events`),t(),r?.(),c.forEach(([e,t])=>Wu.off(e,t))}},[]);let N=async t=>{if(t.preventDefault(),!h.trim()||!x||!l.trim()){j({title:`Missing Fields`,description:`Context ID, Context URL and Workspace are required.`,variant:`destructive`});return}w(!0);try{let t={id:l,name:d.trim()||void 0,url:h,description:_||void 0,workspaceId:x,baseUrl:y||void 0,treeType:p},n=await Zo(t);u(``),f(``),g(`/`),v(``),b(`/`),await M(),j({title:`Success`,description:`Context created successfully`}),E(!1),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),e(`/contexts/${n.id}`)}catch(e){let t=lC(e,`Context creation error:`,`Failed to create context`);j({title:`Error`,description:t,variant:`destructive`})}finally{w(!1)}},P=async e=>{let n=t.find(t=>t.id===e);if(n&&n.url&&(n.url.endsWith(`/default`)||n.url.includes(`://default`))){j({title:`Error`,description:`Cannot delete the default context`,variant:`destructive`});return}A(e)},ee=async()=>{if(k)try{await os(k),n(e=>e.filter(e=>!Lo(e,{id:k}))),j({title:`Success`,description:`Context deleted successfully`})}catch(e){console.error(`Context deletion error:`,e);let t=`Failed to delete context`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to delete context`}j({title:`Error`,description:t,variant:`destructive`})}finally{A(null)}},F=t=>{let n=t.isShared||t.type===`shared`;e(n?`/contexts/${t.id}?ownerId=${encodeURIComponent(t.userId)}`:`/contexts/${t.id}`)},I=e=>{O(e)},te=async e=>{if(e.preventDefault(),D)try{n(e=>e.map(e=>e.id===D.id&&e.userId===D.userId?D:e)),j({title:`Success`,description:`Context updated successfully (mock update)`}),O(null)}catch(e){let t=e instanceof Error?e.message:`Failed to update context`;j({title:`Error`,description:t,variant:`destructive`})}},ne=(0,X.useMemo)(()=>({type:e=>e.isShared||e.type===`shared`?`shared`:`owned`,id:e=>e.id??``,owner:e=>e.isShared||e.type===`shared`?e.ownerEmail||e.userId||``:`you`,url:e=>e.url??``,workspaceId:e=>e.workspaceId??``,baseUrl:e=>e.baseUrl??``,path:e=>e.path??``,locked:e=>+!!e.locked,created:e=>Date.parse(e.createdAt)||0,updated:e=>Date.parse(e.updatedAt)||0}),[]),{sorted:L,sort:re,toggleSort:R}=Wp(t.filter(e=>e!=null),ne);return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(By,{title:`Contexts`,description:`Create and manage contexts in your workspaces. View contexts shared with you.`,actions:!T&&(0,Z.jsxs)(J,{onClick:()=>E(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create context`,title:`Create context`,children:[(0,Z.jsx)(nn,{className:`h-4 w-4 sm:mr-2`}),(0,Z.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Context`})]})}),T&&(0,Z.jsx)(Ky,{title:`Create New Context`,onClose:()=>E(!1),children:(0,Z.jsxs)(`form`,{onSubmit:N,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`workspace`,className:`block text-sm font-medium mb-1`,children:`Workspace`}),(0,Z.jsxs)(`select`,{id:`workspace`,className:`w-full px-3 py-2 border border-border rounded-md shadow-elevation-1 focus:outline-none focus:ring-primary focus:border-primary`,value:x,onChange:e=>S(e.target.value),disabled:C||r.length===0,children:[r.length===0&&(0,Z.jsx)(`option`,{value:``,children:`No workspaces available. Create one first.`}),r.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.label||e.name},`${e.owner}-${e.id}`))]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`newContextId`,className:`block text-sm font-medium mb-1`,children:`Context ID`}),(0,Z.jsx)(q,{id:`newContextId`,value:l,onChange:e=>u(e.target.value),placeholder:`e.g., my-new-context`,disabled:C})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`url`,className:`block text-sm font-medium mb-1`,children:`Context URL`}),(0,Z.jsx)(uC,{id:`url`,value:h,onChange:g,placeholder:`e.g., /project/path/resource`,disabled:C,pickerTitle:`Context URL path…`,onPickTarget:(e,t)=>{g(e),m(t.treeType);let n=r.find(e=>e.name===t.workspaceName||e.id===t.workspaceName);n&&S(n.id)}})]}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`baseUrl`,className:`block text-sm font-medium mb-1`,children:`Base URL (Optional)`}),(0,Z.jsx)(uC,{id:`baseUrl`,value:y,onChange:b,format:`path`,placeholder:`e.g., /base/path`,disabled:C,pickerTitle:`Base path…`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`description`,className:`block text-sm font-medium mb-1`,children:`Description (Optional)`}),(0,Z.jsx)(q,{id:`description`,value:_,onChange:e=>v(e.target.value),placeholder:`Description`,disabled:C})]})]}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`contextName`,className:`block text-sm font-medium mb-1`,children:`Name (Optional)`}),(0,Z.jsx)(q,{id:`contextName`,value:d,onChange:e=>f(e.target.value),placeholder:`My Context`,disabled:C})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`treeType`,className:`block text-sm font-medium mb-1`,children:`Tree`}),(0,Z.jsxs)(`select`,{id:`treeType`,className:`w-full px-3 py-2 border border-border rounded-md shadow-elevation-1 focus:outline-none focus:ring-primary focus:border-primary`,value:p,onChange:e=>m(e.target.value),disabled:C,children:[(0,Z.jsx)(`option`,{value:`context`,children:`Context tree`}),(0,Z.jsx)(`option`,{value:`directory`,children:`Directory tree`})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Which workspace tree this context navigates.`})]})]}),(0,Z.jsxs)(J,{type:`submit`,disabled:C||!h.trim()||!x||!l.trim(),children:[(0,Z.jsx)(nn,{className:`mr-2 h-4 w-4`}),`Create Context`]})]})}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Contexts & Shared Contexts`}),a&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading contexts...`}),s&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:s})}),!a&&!s&&t.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No contexts found. Create one above.`}),t.length>0&&(0,Z.jsx)(`div`,{className:`border rounded-lg overflow-hidden`,children:(0,Z.jsxs)(Fp,{children:[(0,Z.jsx)(Ip,{children:(0,Z.jsxs)(zp,{children:[(0,Z.jsx)(Up,{label:`Type`,sortKey:`type`,sort:re,onSort:R}),(0,Z.jsx)(Up,{label:`ID`,sortKey:`id`,sort:re,onSort:R}),(0,Z.jsx)(Up,{label:`Owner`,sortKey:`owner`,sort:re,onSort:R}),(0,Z.jsx)(Up,{label:`Context URL`,sortKey:`url`,sort:re,onSort:R}),(0,Z.jsx)(Up,{label:`Workspace ID`,sortKey:`workspaceId`,sort:re,onSort:R}),(0,Z.jsx)(Up,{label:`Base URL`,sortKey:`baseUrl`,sort:re,onSort:R}),(0,Z.jsx)(Up,{label:`Path`,sortKey:`path`,sort:re,onSort:R}),(0,Z.jsx)(Up,{label:`Locked`,sortKey:`locked`,sort:re,onSort:R}),(0,Z.jsx)(Up,{label:`Created`,sortKey:`created`,sort:re,onSort:R}),(0,Z.jsx)(Up,{label:`Updated`,sortKey:`updated`,sort:re,onSort:R}),(0,Z.jsx)(Bp,{className:`text-right`,children:`Actions`})]})}),(0,Z.jsx)(Lp,{children:L.map(e=>{if(!e)return console.warn(`Found null/undefined context in contexts array, skipping`),null;let t=e.createdAt?new Date(e.createdAt).toLocaleDateString():`-`,n=e.updatedAt?new Date(e.updatedAt).toLocaleDateString():`-`,r=e.isShared||e.type===`shared`,i=r?e.ownerEmail||e.userId||`-`:`You`,a=r&&e.sharedVia?typeof e.sharedVia==`string`?e.sharedVia:e.sharedVia.accessLevel||`-`:`-`;return(0,Z.jsxs)(zp,{children:[(0,Z.jsx)(Vp,{children:r?(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 text-info`,title:`Shared with you (${a})`,children:[(0,Z.jsx)(Tn,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{className:`text-xs`,children:`Shared`})]}):(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Owned`})}),(0,Z.jsx)(Vp,{className:`font-mono text-sm`,children:e.id||`-`}),(0,Z.jsx)(Vp,{className:`font-mono text-sm`,title:r?`Owned by: ${i}`:`You are the owner`,children:i}),(0,Z.jsx)(Vp,{className:`font-mono text-sm max-w-xs truncate`,title:e.url||`-`,children:e.url||`-`}),(0,Z.jsx)(Vp,{className:`font-mono text-sm`,children:e.workspaceId||`-`}),(0,Z.jsx)(Vp,{className:`font-mono text-sm`,children:e.baseUrl||`-`}),(0,Z.jsx)(Vp,{className:`font-mono text-sm`,children:e.path||`-`}),(0,Z.jsx)(Vp,{children:e.locked?`Yes`:`No`}),(0,Z.jsx)(Vp,{children:t}),(0,Z.jsx)(Vp,{children:n}),(0,Z.jsx)(Vp,{className:`text-right`,children:(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[!r&&(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>I(e),title:`Edit Context`,children:(0,Z.jsx)(bt,{className:`h-4 w-4`})}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>F(e),title:r?`Open Shared Context`:`Open Context Details`,children:(0,Z.jsx)(pn,{className:`h-4 w-4`})}),!r&&(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>P(e.id),disabled:!!(e.url&&(e.url.endsWith(`/default`)||e.url.includes(`://default`))),className:`text-destructive hover:bg-destructive/10 hover:text-destructive disabled:opacity-50 disabled:cursor-not-allowed`,title:e.url&&(e.url.endsWith(`/default`)||e.url.includes(`://default`))?`Cannot delete default context`:`Delete Context`,children:(0,Z.jsx)(tt,{className:`h-4 w-4`})})]})})]},`${e.userId}-${e.id}`)})})]})})]}),D&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Edit Context`}),(0,Z.jsxs)(`form`,{onSubmit:te,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-context-id`,className:`block text-sm font-medium mb-1`,children:`Context ID (read-only)`}),(0,Z.jsx)(q,{id:`edit-context-id`,value:D.id,disabled:!0,className:`bg-muted`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-context-url`,className:`block text-sm font-medium mb-1`,children:`Context URL`}),(0,Z.jsx)(uC,{id:`edit-context-url`,value:D.url,onChange:e=>O(t=>t?{...t,url:e}:null),placeholder:`workspace://path or /path`,pickerTitle:`Context URL path…`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:`Use format: workspace://path or /path for current workspace`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-base-url`,className:`block text-sm font-medium mb-1`,children:`Base URL (optional)`}),(0,Z.jsx)(uC,{id:`edit-base-url`,value:D.baseUrl||``,onChange:e=>O(t=>t?{...t,baseUrl:e||null}:null),format:`path`,placeholder:`/base/path`,pickerTitle:`Base path…`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:`Restricts context navigation to this base path`})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(J,{type:`submit`,children:`Save Changes`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>O(null),children:`Cancel`})]})]})]}),(0,Z.jsx)(Gi,{open:k!==null,onOpenChange:e=>!e&&A(null),children:(0,Z.jsxs)(Ua,{children:[(0,Z.jsxs)(ci,{children:[(0,Z.jsx)(wr,{children:`Delete Context`}),(0,Z.jsx)(ji,{children:`Are you sure you want to delete this context? This action cannot be undone.`})]}),(0,Z.jsxs)(Ba,{children:[(0,Z.jsx)(Pa,{children:`Cancel`}),(0,Z.jsx)(Ti,{onClick:ee,className:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,children:`Delete`})]})]})})]})}function fC(e,t){if(!e||!t)return`/`;let n=`${t}://`;if(!e.startsWith(n))return`/`;let r=e.slice(n.length).replace(/^\/+/,``).replace(/\/+$/,``);return r?`/${r}`:`/`}function pC(){let{contextId:e}=Yc(),t=Hc(),n=Gc(),r=new URLSearchParams(t.search).get(`ownerId`)||void 0,i=(0,X.useMemo)(()=>{let e=new URLSearchParams(t.search),n=e.getAll(`q`).map(e=>e.trim()).filter(Boolean),r=(e.get(`search`)||``).trim();return n.length?n:r?[r]:[]},[t.search]),{showToast:a}=oo(),{state:o,saveFilters:s,setSort:l,setAccentColor:u,setMapDocuments:d,toggleView:f,hasActiveFilters:p}=hs(),{openM2Drawer:m}=Eb(),h=Cm(),g=o.filters.features.allOf,_=o.filters.features.anyOf,v=o.filters.features.noneOf,y=[...wx(o.filters.timeline),...xx(o.filters.geo),...Sx(o.filters.lens,o.filters.geo.includeUnlocated)],b=JSON.stringify({a:g,b:_,c:v,d:y,ids:o.filters.lens.ids,sort:o.filters.sort}),x=(0,X.useMemo)(()=>JSON.parse(b),[b]),[S,C]=(0,X.useState)(null),[w,T]=(0,X.useState)(!0),[E,D]=(0,X.useState)(null),[O,k]=(0,X.useState)([]),[A,j]=(0,X.useState)(!1),[M,N]=(0,X.useState)(0),[P,ee]=(0,X.useState)([]),[F,I]=(0,X.useState)(1),[te,ne]=(0,X.useState)(50),[L,re]=(0,X.useState)(i),[R,ie]=(0,X.useState)(!1),oe=new URLSearchParams(t.search).get(`layer`),z=!!r,se=S?fC(S.url,S.workspaceName):`/`,ce=oe?`context-layer`:`context`,B=typeof S?.metadata?.toolboxSearchQuery==`string`?S.metadata.toolboxSearchQuery:``,V=z?null:S?.workspaceName??null,[le,ue]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!V)return;let e=!1;return fi(V,Da).then(t=>{e||ue({key:V,tree:t})}).catch(()=>{e||ue({key:V,tree:null})}),()=>{e=!0}},[V]);let de=V&&le?.key===V?le.tree:null,fe=!oe&&!z&&de?se===`/`?de:xr(de,se):null,pe=`${S?.workspaceName??``}\0${se}`,[me,H]=(0,X.useState)(null),he=me?.key===pe?me.views:ex(fe?.metadata),ge=me?.key===pe?me.activeId:he[0]?.id??Qb.id,_e=he.find(e=>e.id===ge)??he[0]??Qb,ve=e=>H({key:pe,views:he,activeId:e}),ye=(e,t)=>{H({key:pe,views:e,activeId:t??ge}),S?.workspaceName&&_a(S.workspaceName,se,{metadata:{...fe?.metadata??{},views:e}},Da).catch(()=>{a({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},U=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>U.current?.abort(),[]);let be=(0,X.useCallback)(async()=>{if(!e)return;U.current?.abort();let t=new AbortController;U.current=t,j(!0);try{let n=await Qo(e,x.a,x.d,{...x.sort,ids:x.ids,signal:t.signal,limit:te,page:F,queries:L.length?L:void 0,anyOf:x.b,noneOf:x.c,applyContextSpec:!1},r);if(t.signal.aborted)return;k(n),N(n.totalCount||n.count||n.length)}catch(e){if(t.signal.aborted)return;a({title:`Error`,description:e instanceof Error?e.message:`Failed to fetch documents`,variant:`destructive`}),k([]),N(0)}finally{t.signal.aborted||j(!1)}},[e,F,te,r,L,x,a]),xe=(0,X.useCallback)(async()=>{if(e){T(!0);try{let t=z?await $o(e,r):await $o(e);if(!t)throw Error(`No context data received.`);let n=t.workspace,i=t.workspaceId||(typeof n==`string`?n:n?.id)||``,a=t.workspaceName||(typeof n==`string`?n:n?.name)||``;C({id:t.id,userId:t.userId,url:t.url,baseUrl:t.baseUrl||null,path:t.path||null,pathArray:t.pathArray||[],workspaceId:i,workspaceName:a,acl:t.acl||{},createdAt:t.createdAt,updatedAt:t.updatedAt,locked:t.locked||!1,serverContextArray:t.serverContextArray||[],clientContextArray:t.clientContextArray||[],contextBitmapArray:t.contextBitmapArray||[],featureBitmapArray:t.featureBitmapArray||[],filterArray:t.filterArray||[],pendingUrl:t.pendingUrl||null,description:t.description||null,metadata:t.metadata||{},name:t.name??null,color:t.color??null,icon:t.icon??null}),D(null)}catch(t){let n=t instanceof Error?t.message:`Failed to fetch context ${e}`;D(n),C(null),a({title:`Error`,description:n,variant:`destructive`})}T(!1)}},[e,r,z,a]);(0,X.useEffect)(()=>{xe()},[xe]);let Se=If(S?.color)||null;(0,X.useEffect)(()=>(u(Se),()=>u(null)),[Se,u]);let Ce=o.geoSelection,W=S?.workspaceName||S?.workspaceId||null;(0,X.useEffect)(()=>{d(O,W)},[O,W,d]),(0,X.useEffect)(()=>()=>d([]),[d]);let G=(0,X.useMemo)(()=>Ce?O.filter(e=>zg(e,Ce,o.filters.geo.includeUnlocated)):O,[O,Ce,o.filters.geo.includeUnlocated]),we=S?.id;(0,X.useEffect)(()=>{we&&be()},[we,be]),(0,X.useEffect)(()=>{let e=()=>be();return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[be]);let[Te,Ee]=(0,X.useState)(b);Te!==b&&(Ee(b),I(1));let[De,Oe]=(0,X.useState)(e);De!==e&&(Oe(e),I(1),ie(!1));let[ke,Ae]=(0,X.useState)(i);ke!==i&&(Ae(i),re(i),I(1));let[je,Me]=(0,X.useState)({urlSearchQueries:i,ignoreSavedSearch:R,savedContextSearchQuery:B});(je.urlSearchQueries!==i||je.ignoreSavedSearch!==R||je.savedContextSearchQuery!==B)&&(Me({urlSearchQueries:i,ignoreSavedSearch:R,savedContextSearchQuery:B}),!i.length&&!R&&(re(B?[B]:[]),I(1)));let Ne=(0,X.useCallback)(e=>{let r=new URLSearchParams(t.search);r.delete(`q`),r.delete(`search`);for(let t of e)r.append(`q`,t);let i=r.toString();n(`${t.pathname}${i?`?${i}`:``}`)},[t.pathname,t.search,n]),Pe=(0,X.useCallback)(e=>{let t=e.trim();if(!t)return;ie(!1);let n=L.includes(t)?L:[...L,t];re(n),Ne(n)},[L,Ne]),Fe=(0,X.useCallback)(e=>{let t=e<0?[]:L.filter((t,n)=>n!==e);t.length===0&&ie(!0),re(t),Ne(t)},[L,Ne]),Ie=(L[0]||``).trim(),Le=!!o.activeContextType&&(o.isDirty||Ie!==(o.savedSearchQuery||B||``));(0,X.useEffect)(()=>{if(!e)return;let t=()=>Wu.emit(`subscribe`,{channel:`context:${e}`}),n=()=>Wu.emit(`unsubscribe`,{channel:`context:${e}`}),r=Wu.on(`connect`,t);t();let i=new Map,a=(t,n)=>{let r=Date.now(),a=`${t}:${n?.id||n?.contextId||e}`;return(i.get(a)||0)+1e3>r?!1:(i.set(a,r),!0)},o=t=>{let n=t,r=n?.context||n;(r?.id===e||r?.contextId===e)&&a(`ctx:updated`,r)&&(C(e=>e?{...e,...r}:null),r.url&&be())},s=t=>{let n=t,r=n?.id||n?.contextId||n?.context?.id,i=n?.url||n?.context?.url;r===e&&typeof i==`string`&&a(`ctx:url`,n)&&(C(e=>e?{...e,url:i}:null),be())},c=t=>{let n=t;(n?.contextId||n?.id||n?.context?.id)===e&&a(`doc:changed`,n)&&be()},l=[[`context.updated`,o],[`context:updated`,o],[`context.url.set`,s],[`context:url:set`,s],[`document.inserted`,c],[`document.updated`,c],[`document.removed`,c],[`document.removed.batch`,c],[`document.linked`,c],[`document.unlinked`,c],[`document.linked.batch`,c],[`document.unlinked.batch`,c],[`document.deleted`,c],[`document.deleted.batch`,c]];return l.forEach(([e,t])=>Wu.on(e,t)),()=>{r(),n(),l.forEach(([e,t])=>Wu.off(e,t))}},[e,be]);let Re=async e=>{if(S)try{await ns(S.id,[e],r,se),k(t=>t.filter(t=>t.id!==e)),N(e=>Math.max(0,e-1)),a({title:`Success`,description:`Document removed from context.`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to remove document`,variant:`destructive`})}},ze=async e=>{if(S)try{await is(S.id,[e],r,se),k(t=>t.filter(t=>t.id!==e)),N(e=>Math.max(0,e-1)),a({title:`Success`,description:`Document deleted.`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to delete document`,variant:`destructive`})}},Be=async e=>{if(S)try{await ns(S.id,e,r,se),k(t=>t.filter(t=>!e.includes(t.id))),N(t=>Math.max(0,t-e.length)),a({title:`Success`,description:`${e.length} document(s) removed.`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},Ve=async e=>{if(S)try{await is(S.id,e,r,se),k(t=>t.filter(t=>!e.includes(t.id))),N(t=>Math.max(0,t-e.length)),a({title:`Success`,description:`${e.length} document(s) deleted.`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},He=e=>{ee(e),a({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},Ue=async(e,t)=>{if(!S)return!1;try{let n=await No(S.id,e,t,r);return n&&(await be(),ee([]),a({title:`Success`,description:`${t.length} document(s) pasted to "${e}"`})),n}catch(e){return a({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},We=async(e,t)=>{if(!S)return!1;try{let n=await ms(S.workspaceId,t,e);return n&&(await be(),a({title:`Success`,description:`Imported ${e.length} document(s) to "${t}"`})),n}catch(e){return a({title:`Error`,description:e instanceof Error?e.message:`Failed to import documents`,variant:`destructive`}),!1}};if(w)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,Z.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Z.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading context...`})]})});if(E&&!S)return(0,Z.jsxs)(`div`,{className:`flex items-center justify-center h-full text-destructive`,children:[`Error: `,E]});if(!S)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Context not found.`});let Ge=If(S.color);return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full min-h-0`,children:[(0,Z.jsxs)(`div`,{className:`relative shrink-0 max-sm:border-b`,children:[(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute inset-x-0 bottom-0 h-[3px] bg-border max-sm:hidden`,style:Ge?{backgroundColor:Ge}:void 0}),fe&&(0,Z.jsxs)(`div`,{className:`relative px-2 pt-1.5 sm:hidden`,children:[(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute inset-x-0 bottom-0 h-[3px] bg-border`,style:Ge?{backgroundColor:Ge}:void 0}),(0,Z.jsx)(tx,{accentColor:Ge,views:he,activeId:ge,onSelect:ve,onSave:ye,readOnly:!1})]}),(0,Z.jsxs)(`div`,{className:`flex h-12 items-center gap-2 px-4`,children:[(0,Z.jsx)(Hy,{title:h?`Back to context menu`:`Back to contexts`,onBack:()=>h?m(`contexts`,`detail`,S.id):n(`/contexts`)}),(0,Z.jsx)(c,{icon:S.icon||`ph:stack-fill`,width:16,height:16,color:Ge,className:K(`shrink-0`,!Ge&&`text-muted-foreground`)}),(0,Z.jsx)(`span`,{className:`min-w-0 truncate text-sm font-medium`,children:S.name||S.id}),(0,Z.jsxs)(`span`,{className:`min-w-0 truncate text-xs text-muted-foreground`,children:[`@ `,S.workspaceName||S.workspaceId]}),fe?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(tx,{className:`min-w-0 flex-1 self-stretch max-sm:hidden`,accentColor:Ge,views:he,activeId:ge,onSelect:ve,onSave:ye,readOnly:!1}),(0,Z.jsx)(`div`,{className:`flex-1 sm:hidden`})]}):(0,Z.jsx)(`div`,{className:`flex-1`}),(0,Z.jsxs)(`button`,{onClick:()=>f(`tools`),className:K(`flex shrink-0 items-center gap-1.5 px-3 py-1 text-xs border rounded-md transition-colors`,p?`border-info bg-info text-info-foreground hover:bg-info/90`:o.t1Open&&o.t1View===`tools`?`bg-accent text-foreground`:`hover:bg-accent text-muted-foreground hover:text-foreground`),title:p?`Toolbox filters are active and narrow this view`:`Open the toolbox filters`,children:[(0,Z.jsx)(ae,{className:`w-3 h-3`}),`Filter`,p?` on`:``]}),(0,Z.jsx)(Vy,{})]})]}),(0,Z.jsx)(Xb,{urlType:ce,urlDisplay:S.url,contextPath:se,workspaceId:S.workspaceName||S.workspaceId,documents:G,isLoading:A,totalCount:M,currentPage:F,pageSize:te,onPageChange:I,onPageSizeChange:e=>{ne(e),I(1)},onRemoveDocument:se===`/`?void 0:Re,onDeleteDocument:ze,onRemoveDocuments:se===`/`?void 0:Be,onDeleteDocuments:Ve,onCopyDocuments:He,onPasteDocuments:Ue,onImportDocuments:z?void 0:We,pastedDocumentIds:P,backendSearchQueries:L,onBackendSearch:Pe,serverSort:o.filters.sort,onServerSortChange:l,onRemoveBackendQuery:Fe,canSaveChanges:Le,isSavingChanges:o.isSaving,onSaveChanges:s,onUrlClick:h&&e?()=>m(`contexts`,`detail`,e):void 0,children:_e.kind===`columns`?(0,Z.jsx)(lx,{documents:G,workspaceId:S.workspaceName||S.workspaceId,columns:_e.columns??[],onColumnsChange:e=>ye(he.map(t=>t.id===_e.id?{...t,columns:e}:t))}):_e.kind===`app`&&_e.app?(0,Z.jsx)(ox,{app:_e.app,workspaceId:S.workspaceName||S.workspaceId,treeName:Da,path:se}):null})]})}function mC(){let{openM1Drawer:e}=Eb();return()=>e(`settings`)}function hC(){let[e,t]=(0,X.useState)([]),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(!1),{showToast:m}=oo(),h=(0,X.useRef)(null),g=(0,X.useCallback)(async()=>{try{r(!0);let e=await Y.get(Kr.tokens),n=Array.isArray(e)?e:e.tokens||[];t(n),a(null)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch tokens`;a(t),m({title:`Error`,description:t,variant:`destructive`})}finally{r(!1)}},[m]);(0,X.useEffect)(()=>{g()},[g]);let _=async()=>{if(!(!o.trim()||c)){l(!0);try{let e=await Y.post(Kr.tokens,{name:o});s(``),await g(),e&&e.token&&(d(e.token),setTimeout(()=>{if(h.current){h.current.focus();let e=document.createRange();e.selectNodeContents(h.current);let t=window.getSelection();t&&(t.removeAllRanges(),t.addRange(e))}},100)),m({title:`Success`,description:`Token generated successfully`,variant:`default`})}catch(e){let t=e instanceof Error?e.message:`Failed to generate token`;a(t),m({title:`Error`,description:t,variant:`destructive`})}finally{l(!1)}}},v=async e=>{if(confirm(`Are you sure you want to revoke this API token? This action cannot be undone.`))try{await Y.delete(`${Kr.tokens}/${e}`),await g(),m({title:`Success`,description:`API token revoked successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to revoke API token`;m({title:`Error`,description:t,variant:`destructive`})}},y=async e=>{try{await navigator.clipboard.writeText(e),p(!0),m({title:`Success`,description:`Token copied to clipboard`}),setTimeout(()=>p(!1),2e3)}catch{m({title:`Error`,description:`Failed to copy token to clipboard`,variant:`destructive`})}};return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(By,{title:`API Tokens`,onBack:mC(),description:`Create and manage API tokens for programmatic access`}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Generate New API Token`}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`Token Name (e.g., 'CLI Access', 'Automation')`,disabled:c,className:`flex-1`}),(0,Z.jsxs)(J,{type:`button`,disabled:c||!o.trim(),onClick:_,children:[(0,Z.jsx)(nn,{className:`mr-2 h-4 w-4`}),c?`Generating...`:`Generate`]})]}),u&&(0,Z.jsxs)(`div`,{className:`p-4 border rounded-md bg-muted/50`,children:[(0,Z.jsxs)(`div`,{className:`flex justify-between items-center mb-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold`,children:`Your New API Token`}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>y(u),children:f?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(ur,{className:`mr-2 h-4 w-4`}),`Copied`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Ct,{className:`mr-2 h-4 w-4`}),`Copy`]})})]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mb-2`,children:`Make sure to copy your API token now. You won't be able to see it again!`}),(0,Z.jsx)(`div`,{ref:h,tabIndex:0,className:`p-2 bg-background border rounded font-mono text-sm break-all outline-none focus:ring-2 focus:ring-ring`,children:u})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your API Tokens`}),n&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading API tokens...`}),i&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:i})}),!n&&!i&&e.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No API tokens found`}),e.length>0&&(0,Z.jsx)(`div`,{className:`border rounded-md`,children:(0,Z.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Z.jsxs)(`table`,{className:`w-full`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{className:`bg-muted/50`,children:[(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Name`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Created`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Last Used`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Expires`}),(0,Z.jsx)(`th`,{className:`text-right p-3 font-medium`,children:`Actions`})]})}),(0,Z.jsx)(`tbody`,{children:e.map(e=>(0,Z.jsxs)(`tr`,{className:`border-t`,children:[(0,Z.jsx)(`td`,{className:`p-3 font-medium`,children:e.name}),(0,Z.jsx)(`td`,{className:`p-3`,children:new Date(e.createdAt).toLocaleDateString()}),(0,Z.jsx)(`td`,{className:`p-3`,children:e.lastUsedAt?new Date(e.lastUsedAt).toLocaleDateString():`Never`}),(0,Z.jsx)(`td`,{className:`p-3`,children:e.expiresAt?new Date(e.expiresAt).toLocaleDateString():`Never`}),(0,Z.jsx)(`td`,{className:`p-3 text-right`,children:(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>v(e.id),className:`text-destructive hover:bg-destructive/10 hover:text-destructive`,children:(0,Z.jsx)(tt,{className:`h-4 w-4`})})})]},e.id))})]})})})]})]})}async function gC(){return await Y.get(Kr.devices)||[]}async function _C(e,t){return await Y.patch(`${Kr.devices}/${encodeURIComponent(e)}`,t)}async function vC(e){await Y.delete(`${Kr.devices}/${encodeURIComponent(e)}`)}async function yC(e){return await Y.get(`${Kr.workspaces}/${e}/devices`)||[]}async function bC(e,t){let n=await Y.post(`${Kr.workspaces}/${e}/devices`,{deviceId:t});return Array.isArray(n)?n:[n]}async function xC(e,t){await Y.delete(`${Kr.workspaces}/${e}/devices/${encodeURIComponent(t)}`)}function SC({device:e,onUpdated:t,onRemoved:n}){let[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(e.name),[s,c]=(0,X.useState)(e.description??``),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),{showToast:h}=oo(),g=Object.values(e.mirrors??{}),_=async()=>{m(!0);try{await vC(e.deviceId),n(e.deviceId),h({title:`Revoked`,description:`${e.name} can no longer sign in; a running mirror stops on its next request.`})}catch(e){h({title:`Error`,description:e instanceof Error?e.message:`Failed to revoke device`,variant:`destructive`}),f(!1)}finally{m(!1)}},v=async()=>{let n=a.trim();if(n){if(n===e.name&&s.trim()===(e.description??``)){i(!1);return}u(!0);try{let r=await _C(e.deviceId,{name:n,description:s.trim()||void 0});t({...e,...r}),i(!1),h({title:`Saved`,description:`Device updated`})}catch(e){h({title:`Error`,description:e instanceof Error?e.message:`Failed to update device`,variant:`destructive`})}finally{u(!1)}}},y=()=>{o(e.name),c(e.description??``),i(!1)},b=e=>e?new Date(e).toLocaleString(void 0,{dateStyle:`medium`,timeStyle:`short`}):`—`;return(0,Z.jsx)(`div`,{className:`rounded-lg border p-4`,children:(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start gap-3 min-w-0`,children:[(0,Z.jsx)(kn,{className:`h-4 w-4 text-muted-foreground mt-0.5 shrink-0`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[r?(0,Z.jsxs)(`div`,{className:`space-y-2 mb-2`,children:[(0,Z.jsx)(q,{value:a,onChange:e=>o(e.target.value),className:`h-7 text-sm`,placeholder:`Device name`,autoFocus:!0,disabled:l,onKeyDown:e=>{e.key===`Enter`&&v(),e.key===`Escape`&&y()}}),(0,Z.jsx)(q,{value:s,onChange:e=>c(e.target.value),className:`h-7 text-xs`,placeholder:`Description (optional)`,disabled:l,onKeyDown:e=>{e.key===`Enter`&&v(),e.key===`Escape`&&y()}})]}):(0,Z.jsxs)(`div`,{className:`mb-1`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:e.name}),e.description&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mt-0.5`,children:e.description})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] font-mono text-muted-foreground`,children:[(0,Z.jsx)(`span`,{title:`Device ID`,children:e.deviceId}),e.platform&&(0,Z.jsx)(`span`,{children:e.platform}),e.arch&&(0,Z.jsx)(`span`,{children:e.arch}),e.type&&(0,Z.jsx)(`span`,{className:`capitalize`,children:e.type})]}),(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-x-4 text-[11px] text-muted-foreground`,children:[e.createdAt&&(0,Z.jsxs)(`span`,{children:[`registered `,b(e.createdAt)]}),e.updatedAt&&e.updatedAt!==e.createdAt&&(0,Z.jsxs)(`span`,{children:[`updated `,b(e.updatedAt)]}),e.lastSeen&&(0,Z.jsxs)(`span`,{children:[`seen `,b(e.lastSeen)]})]}),g.length>0&&(0,Z.jsx)(`div`,{className:`mt-3 space-y-1.5`,children:g.map(e=>(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-0.5 rounded-md bg-muted/50 px-2 py-1.5 text-[11px]`,children:[(0,Z.jsx)(me,{className:`h-3.5 w-3.5 text-muted-foreground shrink-0`}),(0,Z.jsx)(`span`,{className:`font-medium`,children:e.workspaceName||e.workspaceId}),e.client&&(0,Z.jsx)(`span`,{className:`font-mono uppercase text-muted-foreground`,children:e.client}),e.path&&(0,Z.jsx)(`span`,{className:`font-mono text-muted-foreground truncate max-w-[24rem]`,title:e.path,children:e.path}),(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:e.state||`idle`}),(e.pending??0)>0&&(0,Z.jsxs)(`span`,{className:`text-muted-foreground`,children:[`pending `,e.pending]}),(e.conflicts??0)>0&&(0,Z.jsxs)(`span`,{className:`text-amber-600 dark:text-amber-400`,children:[`conflicts `,e.conflicts]}),(0,Z.jsxs)(`span`,{className:`text-muted-foreground`,children:[`synced `,b(e.lastSync)]})]},e.workspaceId))})]})]}),(0,Z.jsx)(`div`,{className:`flex shrink-0 items-center gap-2`,children:d?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(J,{type:`button`,variant:`destructive`,size:`sm`,onClick:_,disabled:p,children:p?`Revoking…`:`Confirm revoke`}),(0,Z.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>f(!1),disabled:p,children:(0,Z.jsx)(je,{className:`h-3.5 w-3.5`})})]}):r?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:v,disabled:l||!a.trim(),children:(0,Z.jsx)(ur,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:y,disabled:l,children:(0,Z.jsx)(je,{className:`h-3.5 w-3.5`})})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>i(!0),title:`Edit name / description`,children:(0,Z.jsx)(ye,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>f(!0),title:`Revoke this device: its tokens stop working and its mirrors stop syncing`,children:(0,Z.jsx)(Kn,{className:`h-3.5 w-3.5`})})]})})]})})}function CC(){let[e,t]=(0,X.useState)([]),[n,r]=(0,X.useState)(!0),{showToast:i}=oo(),a=async()=>{r(!0);try{t(await gC())}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to load devices`,variant:`destructive`})}finally{r(!1)}};(0,X.useEffect)(()=>{(async()=>{try{t(await gC())}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to load devices`,variant:`destructive`})}finally{r(!1)}})()},[i]);let o=e=>t(t=>t.map(t=>t.deviceId===e.deviceId?e:t)),s=e=>t(t=>t.filter(t=>t.deviceId!==e));return(0,Z.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-3xl p-6 pb-12 space-y-6`,children:[(0,Z.jsx)(By,{compact:!0,title:`Devices`,onBack:mC(),description:`All devices registered to your account. Link them to individual workspaces in Workspace › Settings › Devices.`,actions:(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:a,disabled:n,children:[(0,Z.jsx)(M,{className:`mr-2 h-3.5 w-3.5 ${n?`animate-spin`:``}`}),`Refresh`]})}),n?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(M,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):e.length===0?(0,Z.jsxs)(`div`,{className:`rounded-lg border p-6 text-center text-sm text-muted-foreground space-y-2`,children:[(0,Z.jsx)(kn,{className:`h-8 w-8 mx-auto text-muted-foreground/40`}),(0,Z.jsx)(`p`,{children:`No devices registered yet.`}),(0,Z.jsxs)(`p`,{className:`text-xs`,children:[`Devices register themselves automatically on first connection via`,` `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`POST /auth/devices/register`}),`.`]})]}):(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.map(e=>(0,Z.jsx)(SC,{device:e,onUpdated:o,onRemoved:s},e.deviceId))}),e.length>0&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 rounded-md border border-dashed p-3 text-xs text-muted-foreground`,children:[(0,Z.jsx)(qt,{className:`h-3.5 w-3.5 shrink-0`}),`To link a device to a workspace, go to Workspace › Settings › Devices.`]})]})})}var wC=[{id:`general`,label:`Workspace details`,description:`Rename, change appearance or remove this workspace`,icon:Yt},{id:`data`,label:`Files & storage`,description:`Connect folders and data sources, check disk usage or restore trash`,icon:_e},{id:`db`,label:`Search & indexing`,description:`Rebuild indexes, tune search and choose embedding models`,icon:Jt},{id:`devices`,label:`Devices`,description:`Link devices to this workspace`,icon:kn},{id:`sync`,label:`Synchronization`,description:`Manage device copies and resolve sync conflicts`,icon:M},{id:`services`,label:`Connected services`,description:`Configure Git, WebDAV, IMAP and other connectors`,icon:Gt},{id:`shares`,label:`Sharing & permissions`,description:`Create public links and manage workspace access`,icon:qt},{id:`hooks`,label:`Automation`,description:`Run hooks in response to workspace events`,icon:ie}],TC={embedding:`db`,trash:`data`};function EC(e){return e?TC[e]?TC[e]:wC.some(t=>t.id===e)?e:`general`:`general`}var DC=[{id:`general`,label:`Context details`,description:`Change the name, description or color, or remove this context`,icon:Yt},{id:`location`,label:`Tree & path`,description:`Choose the workspace, tree and path this context opens`,icon:qt},{id:`shares`,label:`Sharing & permissions`,description:`Choose who can access this context`,icon:Ue}];function OC(e){return e&&DC.some(t=>t.id===e)?e:`general`}var kC=[{id:`identity`,label:`Identity & instructions`,description:`Set the agent’s name, role and instructions`,icon:Yt},{id:`provider`,label:`AI connection`,description:`Connect a chat model provider and manage its credentials`,icon:xe},{id:`models`,label:`Chat model`,description:`Choose the model and tune how it responds`,icon:ht},{id:`tools`,label:`Tools & skills`,description:`Choose the skills and MCP tools the agent can use`,icon:cr},{id:`access`,label:`Access & permissions`,description:`Choose which Canvas content the agent can access`,icon:D},{id:`memory`,label:`Memory`,description:`Configure how the agent remembers information`,icon:H},{id:`integrations`,label:`Integrations`,description:`Connect mail, chat, databases and external APIs`,icon:de}];function AC(e){return e&&kC.some(t=>t.id===e)?e:`identity`}var jC=class{static async handleStreamingResponse(e,t={}){let{onChunk:n,onError:r,onComplete:i,signal:a}=t;try{if(!e.body)throw Error(`Response body is null - streaming not supported`);if(typeof e.body.getReader!=`function`){console.warn(`ReadableStream.getReader not available, falling back to text response`);let t=await e.text();n&&n(t),i&&i();return}let t=e.body.getReader(),r=new TextDecoder;try{for(;;){if(a?.aborted)throw t.cancel(),Error(`Stream aborted`);let{done:e,value:o}=await t.read();if(e){i&&i();break}let s=r.decode(o,{stream:!0});s&&n&&n(s)}}finally{t.releaseLock()}}catch(e){console.error(`Streaming error:`,e),r&&r(e instanceof Error?e:Error(String(e)))}}static processSSEChunk(e){let t=[],n=e.split(`
|
|
13
|
+
`),r={};for(let e of n){let n=e.trim();if(n.startsWith(`data: `))try{let e=JSON.parse(n.slice(6));r={...r,...e}}catch{console.warn(`Failed to parse SSE data:`,n)}else n===``&&(r.agentId&&r.messageId&&t.push(r),r={})}return t}},MC=class{baseUrl;constructor(e,t=`/rest/v2/agents/anthropic`){this.baseUrl=t}async chatStream(e,t){let{agentId:n,messageId:r,onMessage:i,onError:a,onComplete:o,signal:s}=t;try{let t=await fetch(`${this.baseUrl}/chat/stream`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/plain, text/event-stream`,"Cache-Control":`no-cache`},body:JSON.stringify({message:e,agentId:n,messageId:r}),signal:s});if(!t.ok)throw Error(`HTTP ${t.status}: ${t.statusText}`);await jC.handleStreamingResponse(t,{onChunk:e=>{try{jC.processSSEChunk(e).forEach(e=>{i&&i(e)})}catch(e){console.warn(`Failed to process streaming chunk:`,e)}},onError:e=>{let t=Error(`Chat stream failed: AnthropicConnector chatStream failed: ${e.message}`);console.error(`Chat stream error:`,{agentId:n,messageId:r,error:t.message}),a&&a(t)},onComplete:o,signal:s})}catch(e){let t=Error(`Chat stream failed: AnthropicConnector chatStream failed: ${e instanceof Error?e.message:String(e)}`);console.error(`Chat stream error:`,{agentId:n,messageId:r,error:t.message}),a&&a(t)}}},NC=class{wsUrl;socket=null;messageHandlers=new Map;constructor(e){this.wsUrl=e}connect(){return new Promise((e,t)=>{try{this.socket=new WebSocket(this.wsUrl),this.socket.onopen=()=>{console.log(`WebSocket connected for streaming`),e()},this.socket.onerror=e=>{console.error(`WebSocket error:`,e),t(Error(`WebSocket connection failed`))},this.socket.onmessage=e=>{try{let t=JSON.parse(e.data),n=`${t.agentId}-${t.messageId}`,r=this.messageHandlers.get(n);r&&r(t)}catch(e){console.error(`Failed to parse WebSocket message:`,e)}},this.socket.onclose=()=>{console.log(`WebSocket disconnected`),this.socket=null}}catch(e){t(e)}})}startChatStream(e,t,n,r,i){if(!this.socket||this.socket.readyState!==WebSocket.OPEN){i&&i(Error(`WebSocket not connected`));return}let a=`${e}-${t}`;this.messageHandlers.set(a,r);try{this.socket.send(JSON.stringify({type:`chat_stream`,agentId:e,messageId:t,message:n}))}catch(e){i&&i(e instanceof Error?e:Error(String(e)))}}stopChatStream(e,t){let n=`${e}-${t}`;this.messageHandlers.delete(n)}disconnect(){this.socket&&=(this.socket.close(),null),this.messageHandlers.clear()}};function PC(e){if(!e)return``;if(typeof e.errorMessage==`string`&&e.errorMessage.trim())return e.errorMessage.trim();let t=e.content;return typeof t==`string`?t:Array.isArray(t)&&t.filter(e=>e?.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(`
|
|
14
|
+
`)||``}function FC(e){return e?typeof e?.metadata?.reasoning==`string`&&e.metadata.reasoning.trim()?e.metadata.reasoning.trim():Array.isArray(e.content)?e.content.filter(e=>e?.type===`thinking`||e?.type===`reasoning`).map(e=>typeof e?.thinking==`string`?e.thinking:typeof e?.reasoning==`string`?e.reasoning:typeof e?.text==`string`?e.text:``).filter(Boolean).join(`
|
|
15
|
+
`).trim():``:``}function IC(e){if(!e)return;let t=FC(e),n={...e.api?{api:e.api}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.stopReason?{stopReason:e.stopReason}:{},...e.timestamp===void 0?{}:{timestamp:e.timestamp},...e.responseId?{responseId:e.responseId}:{},...e.usage?{usage:e.usage}:{},...e.metadata?.toolCalls?{toolCalls:e.metadata.toolCalls}:{},...t?{reasoning:t}:{}};return Object.keys(n).length>0?n:void 0}function LC(e){if(typeof e==`number`)return new Date(e).toISOString();if(typeof e==`string`){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toISOString()}return new Date().toISOString()}function RC(e=[]){return e.filter(e=>e?.role===`user`||e?.role===`assistant`).map(e=>({role:e.role,content:PC(e),timestamp:LC(e.timestamp),...e.role===`assistant`?{metadata:IC(e)}:{}})).filter(e=>e.content||e.metadata?.reasoning)}function zC(e){return{mode:e?.mode,sessionId:e?.sessionId,sessionFile:e?.sessionFile,thinkingLevel:e?.thinkingLevel,model:e?.model,messages:RC(e?.messages||[])}}function BC(e){return{current:zC(e?.current),sessions:e?.sessions}}new class{connectors=new Map;wsService=null;messageCallbacks=new Map;constructor(){this.initializeWebSocketFallback()}async initializeWebSocketFallback(){try{let e=`${window.location.protocol===`https:`?`wss:`:`ws:`}//${window.location.host}/ws`;this.wsService=new NC(e)}catch(e){console.warn(`WebSocket fallback not available:`,e)}}registerAgent(e){if(e.type===`anthropic`){let t=new MC(e.apiKey||``,e.endpoint||`${Yr}/agents/${e.id}`);this.connectors.set(e.id,t)}}async sendMessage(e,t,n={}){let{onMessage:r,onError:i,onComplete:a,useWebSocketFallback:o=!1}=n,s=`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;r&&this.messageCallbacks.set(s,r);try{if(o&&this.wsService){await this.sendMessageViaWebSocket(e,s,t,r,i),a&&a();return}let n=this.connectors.get(e);n?await n.chatStream(t,{agentId:e,messageId:s,onMessage:e=>{let t={id:e.messageId,agentId:e.agentId,content:e.content||``,timestamp:new Date,type:`agent`,streaming:!e.done,error:e.error};r&&r(t)},onError:n=>{if(console.error(`Agent connector error:`,n),n.message.includes(`getReader is not a function`)&&this.wsService){console.log(`Falling back to WebSocket streaming...`),this.sendMessageViaWebSocket(e,s,t,r,i);return}i&&i(n)},onComplete:a}):await this.sendMessageViaAPI(e,s,t,r,i,a)}catch(e){console.error(`Agent communication error:`,e),i&&i(e instanceof Error?e:Error(String(e)))}finally{this.messageCallbacks.delete(s)}}async sendMessageViaAPI(e,t,n,r,i,a){try{await Y.stream(`${Yr}/agents/${e}/chat/stream`,{message:n,messageId:t},{onChunk:n=>{try{let i=JSON.parse(n),a={id:t,agentId:e,content:i.content||n,timestamp:new Date,type:`agent`,streaming:!i.done,error:i.error};r&&r(a)}catch{r&&r({id:t,agentId:e,content:n,timestamp:new Date,type:`agent`,streaming:!0})}},onError:e=>{console.error(`API streaming error:`,e),i&&i(e)},onComplete:a})}catch(e){i&&i(e instanceof Error?e:Error(String(e)))}}async sendMessageViaWebSocket(e,t,n,r,i){if(!this.wsService){i&&i(Error(`WebSocket service not available`));return}try{this.wsService.socket?.readyState!==WebSocket.OPEN&&await this.wsService.connect(),this.wsService.startChatStream(e,t,n,e=>{let t={id:e.messageId,agentId:e.agentId,content:e.content||``,timestamp:new Date,type:`agent`,streaming:!e.done,error:e.error};r&&r(t)},i)}catch(e){i&&i(e instanceof Error?e:Error(String(e)))}}async getAvailableAgents(){try{return(await Y.get(`${Yr}/agents`)).agents||[]}catch(e){return console.error(`Failed to fetch available agents:`,e),[]}}async createAgent(e){let t=await Y.post(`${Yr}/agents`,e);return this.registerAgent(t),t}dispose(){this.connectors.clear(),this.messageCallbacks.clear(),this.wsService&&this.wsService.disconnect()}};async function VC(e){return await Y.get(`${Yr}/agents/${e}/access`)||null}async function HC(e,t){return await Y.put(`${Yr}/agents/${e}/access`,t)}async function UC(e){return await Y.post(`${Yr}/agents/${e}/access/token`)}async function WC(e){await Y.delete(`${Yr}/agents/${e}/access`)}async function GC(e){return await Y.get(`${Yr}/agents/${e}/tools`)||{tools:[],config:{}}}async function KC(){try{return await Y.get(`${Yr}/agents`)||[]}catch(e){return console.error(`Failed to list agents:`,e),[]}}async function qC(e){return await Y.get(`${Yr}/agents/${e}`)}async function JC(e){return zC(await Y.get(`${Yr}/agents/${e}/session`))}async function YC(e){return await Y.get(`${Yr}/agents/${e}/sessions`)}async function XC(e,t){return BC(await Y.post(`${Yr}/agents/${e}/sessions`,t))}async function ZC(e,t){return BC(await Y.put(`${Yr}/agents/${e}/session`,t))}async function QC(e,t,n){return BC(await Y.patch(`${Yr}/agents/${e}/sessions/${t}`,n))}async function $C(e,t){return BC(await Y.delete(`${Yr}/agents/${e}/sessions/${t}`))}async function ew(e){return await Y.get(`${Yr}/agents/${e}/skills`)||[]}async function tw(e,t){return await Y.post(`${Yr}/agents/${e}/skills`,t)||[]}async function nw(e,t){return await Y.delete(`${Yr}/agents/${e}/skills/${encodeURIComponent(t)}`)||[]}async function rw(e){return await Y.post(`${Yr}/agents`,e)}async function iw(e,t){return await Y.put(`${Yr}/agents/${e}`,t)}async function aw(e){await Y.delete(`${Yr}/agents/${e}`)}async function ow(e){return await Y.post(`${Yr}/agents/${e}/start`)}async function sw(e){return await Y.post(`${Yr}/agents/${e}/stop`)}async function cw(e){return await Y.get(`${Yr}/agents/${e}/status`)}async function lw(e,t,n={}){let{onStart:r,onMessage:i,onError:a,onComplete:o,context:s,mcpContext:c,maxTokens:l,temperature:u,images:d}=n,f=``;await Y.stream(`${Yr}/agents/${e}/prompt/stream`,{message:t,images:d,context:s,mcpContext:c,maxTokens:l,temperature:u},{onOpen:()=>{r?.()},onChunk:e=>{f+=e;let t=f.split(`
|
|
16
|
+
|
|
17
|
+
`);f=t.pop()||``;for(let e of t){let t=e.split(`
|
|
18
|
+
`).map(e=>e.trim()).filter(Boolean);for(let e of t){if(!e.startsWith(`data: `))continue;let t=e.slice(6).trim();if(t!==`[DONE]`)try{let e=JSON.parse(t);if(!i)continue;if(e.type===`chunk`)i(e.delta||``,!1,e.metadata||{});else if(e.type===`thinking`)i(``,!1,{...e.metadata||{},reasoningDelta:e.delta||``});else if(e.type===`complete`){let t=Array.isArray(e.messages)?[...e.messages].reverse().find(e=>e?.role===`assistant`):null;i(``,!0,{...e.metadata||{},...IC(t)||{}})}else e.type===`error`&&a&&a(Error(e.error||`Prompt stream failed`))}catch{}}}},onError:a,onComplete:o})}async function uw(e,t){let{message:n,onMessage:r,onError:i,onComplete:a,context:o,mcpContext:s,maxTokens:c,temperature:l,images:u}=t;try{let t=await Y.post(`${Yr}/agents/${e}/prompt`,{message:n,images:u,context:o,mcpContext:s,maxTokens:c,temperature:l}),i=Array.isArray(t.messages)?[...t.messages].reverse().find(e=>e?.role===`assistant`):null,d={content:PC(i),metadata:IC(i)};return r&&r(d.content,!0,d.metadata),a&&a(),d}catch(e){throw i&&i(e),e}}function dw(e){return e.map(e=>({...e,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString()}))}async function fw(){return await Y.get(`${Yr}/voice/status`)}async function pw(e,t,n={}){let r=new FormData,i=(t.type.split(`/`)[1]||`webm`).split(`;`)[0];r.append(`file`,t,`voice.${i}`);let a=new URLSearchParams;n.tts===!1&&a.set(`tts`,`false`),n.voice&&a.set(`voice`,n.voice);let o=a.toString()?`?${a.toString()}`:``;return await Y.post(`${Yr}/agents/${e}/voice${o}`,r)}var mw=[{id:`workspace`,label:`Workspace`,path:`workspaces`,description:`Files, search, devices and sharing for one workspace. These settings override account defaults.`,sections:wC,load:async()=>(await Or()).map(e=>({id:e.name,label:e.label||e.name}))},{id:`context`,label:`Context`,path:`contexts`,description:`Choose the tree and path a context opens, and who can access that view. File storage belongs to its workspace.`,sections:DC,load:async()=>(await Uo()).map(e=>({id:e.id,label:e.name||e.id}))},{id:`agent`,label:`Agent`,path:`agents`,description:`Configure one assistant: its instructions, chat model, tools and access to Canvas.`,sections:kC,load:async()=>(await KC()).map(e=>({id:e.id,label:e.label||e.name}))}];function hw({to:e,label:t,description:n,icon:r}){return(0,Z.jsxs)(cu,{to:e,className:`group flex items-start gap-3 rounded-lg border bg-card p-4 transition-colors hover:border-primary/50 hover:bg-accent/30 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary`,children:[(0,Z.jsx)(r,{className:`mt-0.5 h-5 w-5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-semibold`,children:t}),(0,Z.jsx)(`span`,{className:`mt-1 block text-sm leading-relaxed text-muted-foreground`,children:n})]}),(0,Z.jsx)(_t,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground group-hover:text-primary`})]})}function gw({group:e,query:t}){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(`loading`),[c,l]=(0,X.useState)(0);(0,X.useEffect)(()=>{let t=!1;return e.load().then(e=>{t||(r(e),s(`ready`))}).catch(()=>{t||s(`error`)}),()=>{t=!0}},[e,c]);let u=e.sections.filter(n=>ib(t,e.label,n.label,n.description));return u.length?(0,Z.jsxs)(`section`,{id:e.id,className:`scroll-mt-6 space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsxs)(`label`,{className:`block max-w-md text-sm font-medium`,children:[`Choose a `,e.label.toLowerCase(),(0,Z.jsxs)(`select`,{className:`mt-2 h-10 w-full rounded-md border bg-background px-3 text-sm`,value:i,disabled:o!==`ready`||!n.length,onChange:e=>a(e.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:o===`loading`?`Loading…`:o===`error`?`Unable to load list`:n.length?`Select ${e.label.toLowerCase()}…`:`No ${e.path} available`}),n.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),o===`error`&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`The list could not be loaded. `,(0,Z.jsx)(`button`,{type:`button`,className:`underline`,onClick:()=>{s(`loading`),l(e=>e+1)},children:`Retry`})]}),(0,Z.jsxs)(`details`,{open:!!(i||t.trim()),children:[(0,Z.jsx)(`summary`,{className:`cursor-pointer py-2 text-sm text-muted-foreground`,children:i?`Settings for ${n.find(e=>e.id===i)?.label||i}`:`What you can configure (${u.length})`}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:u.map(t=>i?(0,Z.jsx)(hw,{to:`/${e.path}/${encodeURIComponent(i)}/settings/${t.id}`,...t},t.id):(0,Z.jsxs)(`div`,{className:`rounded-lg border border-dashed p-4`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:t.label}),(0,Z.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:t.description})]},t.id))})]})]}):null}function _w(){let{state:e}=Eb(),[t,n]=(0,X.useState)(``),r=nb.filter(t=>t.id!==`server`||e.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(n=>ib(t,e.label,n.label,n.description))})).filter(e=>e.items.length),i=mw.some(e=>e.sections.some(n=>ib(t,e.label,n.label,n.description)));return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-6xl space-y-8 pb-8 max-md:pb-rail-stack`,children:[(0,Z.jsx)(By,{title:`Settings`,description:`Start with what you want to change. Each section explains where your changes apply.`}),(0,Z.jsx)(q,{type:`search`,className:`max-w-xl`,"aria-label":`Search all settings`,placeholder:`Find a setting: offline, folders, models, sharing…`,value:t,onChange:e=>n(e.target.value)}),r.filter(e=>e.id===`device`||e.id===`account`).map(e=>(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,Z.jsx)(hw,{to:e.path,...e},e.path))})]},e.id)),mw.map(e=>(0,Z.jsx)(gw,{group:e,query:t},e.id)),r.filter(e=>e.id===`server`||e.id===`information`).map(e=>(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,Z.jsx)(hw,{to:e.path,...e},e.path))})]},e.id)),!r.length&&!i&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`No settings match “`,t,`”. Try a shorter phrase or clear the search.`]})]})}var vw=[{id:`canvas_1`,title:`Canvas Deep`,scheme:`dark`,background:`#032940`,accent:`#f2f2f2`,sources:[{type:`image/svg+xml`,src:`files/canvas_1.svg`},{type:`image/avif`,src:`files/canvas_1.avif`},{type:`image/webp`,src:`files/canvas_1.webp`}],thumb:`thumbs/canvas_1.webp`,author:`Canvas`,license:`LicenseRef-Canvas-Brand`},{id:`canvas_3`,title:`Canvas Mono Dark`,scheme:`dark`,background:`#000000`,accent:`#ffffff`,sources:[{type:`image/svg+xml`,src:`files/canvas_3.svg`},{type:`image/avif`,src:`files/canvas_3.avif`},{type:`image/webp`,src:`files/canvas_3.webp`}],thumb:`thumbs/canvas_3.webp`,author:`Canvas`,license:`LicenseRef-Canvas-Brand`},{id:`w1`,title:`Frost`,scheme:`dark`,background:`#164a6f`,accent:`#9ad9f0`,sources:[{type:`image/avif`,src:`files/w1.avif`},{type:`image/webp`,src:`files/w1.webp`},{type:`image/jpeg`,src:`files/w1.jpg`}],thumb:`thumbs/w1.webp`,author:`Peter Cui Bide`,source:`https://petercui.deviantart.com`,license:`LicenseRef-Attribution-Only`}],yw=`/wallpapers`;function bw(e){return vw.find(t=>t.id===e)}function xw(e,t={}){let n=typeof e==`string`?bw(e):e;if(!n)return null;let{base:r=yw,types:i}=t,a=(i?n.sources.find(e=>i.includes(e.type)):n.sources[0])??n.sources[n.sources.length-1];return`${r.replace(/\/$/,``)}/${a.src}`}function Sw(e,t=yw){let n=typeof e==`string`?bw(e):e;return n?`${t.replace(/\/$/,``)}/${n.thumb}`:null}var Cw=[{id:`cover`,label:`Scale and Crop`,description:`Fills the screen, cropping edges as needed`},{id:`fill`,label:`Fill`,description:`Stretches to the exact screen size`},{id:`center`,label:`Centered`,description:`Original size, centered on the desk`}],ww=`canvas:wallpaper`,Tw=`builtin:`,Ew=vw;function Dw(e){return Sw(e)??``}function Ow(e){return`${Tw}${e}`}function kw(e){return e?.startsWith(Tw)?e.slice(8):null}function Aw(){try{let e=localStorage.getItem(ww);if(e){let t=JSON.parse(e);if(typeof t.image==`string`||t.image===null){let e=t.fit===`fill`||t.fit===`center`?t.fit:`cover`;return{image:t.image??null,fit:e}}}}catch{}return{image:null,fit:`cover`}}function jw(e){localStorage.setItem(ww,JSON.stringify(e)),Fw(e)}var Mw=typeof CSS<`u`&&CSS.supports(`background-image`,`image-set(url("a.avif") type("image/avif"))`);function Nw(e){if(!e)return null;let t=kw(e);if(t===null)return`url("${e}")`;let n=bw(t);if(!n)return null;let r=`url("${xw(n,{types:[n.sources[n.sources.length-1].type]})}")`;return!Mw||n.sources.length===1?r:`image-set(${n.sources.map(e=>`url("${xw(n,{types:[e.type]})}") type("${e.type}")`).join(`, `)})`}function Pw(e){return e===`fill`?`100% 100%`:e===`center`?`auto`:`cover`}function Fw(e=Aw()){let t=document.documentElement.style,n=Nw(e.image);if(!n){t.removeProperty(`--wallpaper-image`),t.removeProperty(`--wallpaper-size`);return}t.setProperty(`--wallpaper-image`,n),t.setProperty(`--wallpaper-size`,Pw(e.fit))}var Iw=[{id:`cards`,name:`Cards`,description:`Nested cards with connector lines. Each level indents.`},{id:`accordion-mobile`,name:`Accordion on phones (beta)`,description:`Experimental. Full-width accordion rows on a phone, cards on wider screens.`},{id:`accordion`,name:`Accordion (beta)`,description:`Experimental. Full-width rows at every depth; a depth rail, tint and colour swatch replace the indent, and open parents stick to the top while you scroll.`}],Lw=`canvas:treeStyle`;function Rw(){try{let e=localStorage.getItem(Lw);return e===`accordion`||e===`accordion-mobile`?e:`cards`}catch{return`cards`}}var zw=Rw(),Bw=new Set;function Vw(){return zw}function Hw(e){try{e===`cards`?localStorage.removeItem(Lw):localStorage.setItem(Lw,e)}catch{}zw=e;for(let e of Bw)e()}function Uw(e){Bw.add(e);let t=t=>{(t.key===Lw||t.key===null)&&(zw=Rw(),e())};return window.addEventListener(`storage`,t),()=>{Bw.delete(e),window.removeEventListener(`storage`,t)}}function Ww(){return(0,X.useSyncExternalStore)(Uw,Vw,()=>`cards`)}function Gw(){let e=Ww(),t=Cm();return e===`accordion`||e===`accordion-mobile`&&t}var Kw=[{id:`canvas`,name:`Canvas`,description:`Black and white with a teal accent. Sheets of paper on a grey desk.`,swatches:[`oklch(1 0 0)`,`oklch(0 0 0)`,`oklch(0.704 0.135 183)`]},{id:`nord`,name:`Nord`,description:`Cool arctic blues, lower contrast, softer corners.`,swatches:[`oklch(0.976 0.006 251)`,`oklch(0.588 0.056 244)`,`oklch(0.686 0.062 213)`]},{id:`contrast`,name:`High Contrast`,description:`WCAG AAA text contrast, square corners, hard borders, no shadows.`,swatches:[`oklch(1 0 0)`,`oklch(0 0 0)`,`oklch(0.32 0.16 258)`]},{id:`frost`,name:`Frosted Glass`,description:`Translucent, blurred surfaces over a soft backdrop. Best with a wallpaper.`,swatches:[`oklch(0.92 0.008 250)`,`oklch(0.31 0.025 255)`,`oklch(0.55 0.05 250)`]},{id:`terminal`,name:`Terminal`,description:`Monospaced and dense. Tighter rows and chrome for large displays.`,swatches:[`oklch(0.17 0.006 152)`,`oklch(0.8 0.19 148)`,`oklch(0.75 0.12 220)`]},{id:`halflife`,name:`Half-Life`,description:`Lambda orange on black steel. Square corners; the left rail is orange.`,swatches:[`oklch(0.724 0.181 52)`,`oklch(0 0 0)`,`oklch(1 0 0)`]}],qw=Kw.map(e=>e.id),Jw=[{id:`system`,name:`System`},{id:`light`,name:`Light`},{id:`dark`,name:`Dark`}],Yw=[{id:`auto`,name:`Auto`,description:`Match the pointer: touch on phones, mouse on desktop`},{id:`compact`,name:`Compact`,description:`Maximum rows per screen`},{id:`comfortable`,name:`Comfortable`,description:`Balanced for mouse use`},{id:`touch`,name:`Touch`,description:`Large targets for finger input`}],Xw={theme:`canvas`,scheme:`light`,density:`auto`},Zw=`canvas.ui.theme`;function Qw(e){return typeof e==`string`&&qw.includes(e)}function $w(e){return e===`light`||e===`dark`||e===`system`}function eT(e){return e===`auto`||e===`compact`||e===`comfortable`||e===`touch`}function tT(e){let t=typeof e==`object`&&e?e:{};return{theme:Qw(t.theme)?t.theme:Xw.theme,scheme:$w(t.scheme)?t.scheme:Xw.scheme,density:eT(t.density)?t.density:Xw.density}}var nT=`(prefers-color-scheme: dark)`;function rT(){return typeof document<`u`}function iT(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(nT).matches}function aT(e){return e===`system`?iT()?`dark`:`light`:e}function oT(e){if(typeof window>`u`||typeof window.matchMedia!=`function`)return()=>{};let t=window.matchMedia(nT),n=t=>e(t.matches?`dark`:`light`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)}function sT(e){return oT(e)}function cT(){return iT()?`dark`:`light`}function lT(){return`light`}function uT(e){let t=getComputedStyle(e).getPropertyValue(`--background`).trim();if(!t)return;let n=document.querySelector(`meta[name="theme-color"]`);n||(n=document.createElement(`meta`),n.name=`theme-color`,document.head.appendChild(n)),n.content=t}function dT(e,t=rT()?document.documentElement:void 0){let n=aT(e.scheme);return t?(t.dataset.theme=e.theme,t.dataset.scheme=n,t.dataset.density=e.density,uT(t),n):n}function fT(e,t=rT()?document.documentElement:void 0){if(!t||typeof window>`u`)return dT(e,t);let n=document.createElement(`style`);n.appendChild(document.createTextNode(`*,*::before,*::after{transition:none!important;animation:none!important}`)),document.head.appendChild(n);let r=dT(e,t);return window.getComputedStyle(n).opacity,document.head.removeChild(n),r}function pT(e){let t=e??gT();if(!t)return Xw;try{let e=t.getItem(Zw);return e?tT(JSON.parse(e)):Xw}catch{return Xw}}function mT(e,t){let n=t??gT();if(n)try{n.setItem(Zw,JSON.stringify(e))}catch{}}function hT(e){let t=e??gT();if(t)try{t.removeItem(Zw)}catch{}}function gT(){try{return typeof localStorage<`u`?localStorage:void 0}catch{return}}function _T({children:e,initial:t,storage:n,persist:r=!0}){let[i,a]=(0,X.useState)(()=>({...pT(n),...t})),o=(0,X.useSyncExternalStore)(sT,cT,lT),s=i.scheme===`system`?o:i.scheme;(0,X.useEffect)(()=>{fT({...i,scheme:s})},[i,s]),(0,X.useEffect)(()=>{r&&mT(i,n)},[i,r,n]);let c=(0,X.useCallback)(e=>{a(t=>t.theme===e?t:{...t,theme:e})},[]),l=(0,X.useCallback)(e=>{a(t=>t.scheme===e?t:{...t,scheme:e})},[]),u=(0,X.useCallback)(e=>{a(t=>t.density===e?t:{...t,density:e})},[]),d=(0,X.useCallback)(()=>{a(e=>({...e,scheme:(e.scheme===`system`?cT():e.scheme)===`dark`?`light`:`dark`}))},[]),f=(0,X.useCallback)(()=>{hT(n),a(Xw)},[n]),p=(0,X.useMemo)(()=>({...i,resolvedScheme:s,setTheme:c,setScheme:l,setDensity:u,toggleScheme:d,reset:f}),[i,s,c,l,u,d,f]);return(0,Z.jsx)(_s.Provider,{value:p,children:e})}var vT={system:kn,light:Vn,dark:he};function yT(){let{theme:e,scheme:t,density:n,resolvedScheme:r,setTheme:i,setScheme:a,setDensity:o,reset:s}=vs(),c=tm(),l=mb(),u=Ww(),d=Cb();return(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(CT,{title:`Theme`,description:`Palette, shape and typography. Each theme defines its own light and dark variants.`}),(0,Z.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`,children:Kw.map(t=>{let n=t.id===e;return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>i(t.id),"aria-pressed":n,className:K(`focus-ring group flex flex-col gap-3 rounded-lg border p-4 text-left transition-colors`,n?`border-primary bg-accent`:`border-border hover:border-muted-foreground/40 hover:bg-accent/50`),children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:t.name}),n&&(0,Z.jsx)(ur,{className:`size-4 shrink-0 text-primary`})]}),(0,Z.jsx)(`div`,{className:`flex gap-1.5`,"aria-hidden":!0,children:t.swatches.map(e=>(0,Z.jsx)(`span`,{className:`size-6 rounded-full border border-border`,style:{backgroundColor:e}},e))}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t.description})]},t.id)})})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(CT,{title:`Colour scheme`,description:t===`system`?`Following your system setting, currently ${r}.`:`Overrides your system setting.`}),(0,Z.jsx)(wT,{options:Jw.map(e=>{let t=vT[e.id];return{id:e.id,label:e.name,icon:(0,Z.jsx)(t,{className:`size-4 shrink-0`})}}),value:t,onChange:a})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(CT,{title:`Density`,description:`Controls row height, hit-target size and shell spacing across the whole app.`}),(0,Z.jsx)(wT,{options:Yw.map(e=>({id:e.id,label:e.name,title:e.description})),value:n,onChange:o}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:Yw.find(e=>e.id===n)?.description})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(CT,{title:`Layout`,description:`How menus and content share the screen. Device-local, like the wallpaper.`}),(0,Z.jsx)(wT,{options:ab.map(e=>({id:e.id,label:e.name,title:e.description})),value:l,onChange:fb}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:ab.find(e=>e.id===l)?.description}),l===`strip`&&(0,Z.jsxs)(`div`,{className:`mt-4`,children:[(0,Z.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Navigation keys`}),(0,Z.jsx)(wT,{options:hb.map(e=>({id:e.id,label:e.name,title:e.description})),value:d,onChange:xb}),(0,Z.jsxs)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:[hb.find(e=>e.id===d)?.description,` `,`Left and right walk the columns, up and down switch pin rows.`]})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(CT,{title:`Tree style`,description:`How workspace and context trees are drawn in the menu. Device-local.`}),(0,Z.jsx)(wT,{options:Iw.map(e=>({id:e.id,label:e.name,title:e.description})),value:u,onChange:Hw}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:Iw.find(e=>e.id===u)?.description})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(CT,{title:`Open documents`,description:`Choose how documents open from lists, tiles and boards. Saved on this device.`}),(0,Z.jsx)(wT,{options:[{id:`modal`,label:`Modal`},{id:`side`,label:`Side reading pane`}],value:c,onChange:$p}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`The reading pane opens beside the content and updates as you select another document. On small screens it opens as a drawer.`})]}),(0,Z.jsx)(bT,{}),(0,Z.jsx)(`section`,{children:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{s(),$p(`modal`)},className:`focus-ring rounded-md text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline`,children:`Reset to defaults`})})]})}function bT(){let[e,t]=(0,X.useState)(Aw),[n,r]=(0,X.useState)(null),i=e=>{try{jw(e),t(e),r(null)}catch{r(`Could not store the wallpaper (browser storage full?). Try a smaller image.`)}},a=t=>{if(!t)return;if(!t.type.startsWith(`image/`)){r(`Pick an image file.`);return}let n=new FileReader;n.onload=()=>{let t=String(n.result||``);if(t.length>3670016){r(`Image too large for browser storage. Use one under ~2.5 MB.`);return}i({...e,image:t})},n.readAsDataURL(t)},o=e.image!==null&&kw(e.image)===null,s=Nw(e.image);return(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(CT,{title:`Wallpaper`,description:`Background image for the desk behind all panels. Without one, the theme's desk color shows (the default).`}),(0,Z.jsxs)(`div`,{role:`radiogroup`,"aria-label":`Wallpaper`,className:`grid grid-cols-3 gap-3 sm:grid-cols-4 lg:grid-cols-6`,children:[(0,Z.jsx)(ST,{label:`None`,isActive:e.image===null,onSelect:()=>i({...e,image:null}),children:(0,Z.jsx)(`span`,{className:`flex size-full items-center justify-center surface-desk text-xs text-muted-foreground`,style:{backgroundImage:`none`},children:`None`})}),Ew.map(t=>(0,Z.jsx)(ST,{label:t.title,title:`${t.title} — suits the ${t.scheme} scheme`,isActive:kw(e.image)===t.id,onSelect:()=>i({...e,image:Ow(t.id)}),children:(0,Z.jsx)(`img`,{src:Dw(t),alt:``,loading:`lazy`,className:`size-full object-cover`,style:{backgroundColor:t.background}})},t.id)),o&&(0,Z.jsx)(ST,{label:`Your image`,isActive:!0,onSelect:()=>{},children:(0,Z.jsx)(`img`,{src:e.image??void 0,alt:``,className:`size-full object-cover`})})]}),(0,Z.jsx)(xT,{}),(0,Z.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(`div`,{className:`h-20 w-32 shrink-0 rounded-md border surface-desk`,style:s?{backgroundImage:s,backgroundSize:Pw(e.fit),backgroundPosition:`center`,backgroundRepeat:`no-repeat`}:void 0,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsxs)(`label`,{className:`focus-ring inline-flex cursor-pointer items-center rounded-md border px-3 py-1.5 text-sm hover:bg-accent/50`,children:[o?`Change image…`:`Use your own image…`,(0,Z.jsx)(`input`,{type:`file`,accept:`image/*`,className:`hidden`,onChange:e=>{a(e.target.files?.[0]),e.target.value=``}})]}),e.image&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>i({...e,image:null}),className:`focus-ring rounded-md border px-3 py-1.5 text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:`Remove`})]}),(0,Z.jsx)(wT,{options:Cw.map(e=>({id:e.id,label:e.label,title:e.description})),value:e.fit,onChange:t=>i({...e,fit:t})}),n&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:n})]})]})]})}function xT(){let e=Ew.filter(e=>e.author!==`Canvas`);return e.length===0?null:(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:e.map((e,t)=>(0,Z.jsxs)(`span`,{children:[t>0&&` · `,e.title,` © `,e.author,e.source&&(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.jsx)(`a`,{href:e.source,target:`_blank`,rel:`noreferrer noopener`,className:`focus-ring underline underline-offset-2 hover:text-foreground`,children:new URL(e.source).hostname})]})]},e.id))})}function ST({label:e,title:t,isActive:n,onSelect:r,children:i}){return(0,Z.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":n,"aria-label":e,title:t??e,onClick:r,className:K(`focus-ring group relative aspect-video overflow-hidden rounded-md border transition-colors`,n?`border-primary ring-1 ring-primary`:`border-border hover:border-muted-foreground/40`),children:[i,n&&(0,Z.jsx)(`span`,{className:`absolute right-1 top-1 rounded-full bg-primary p-0.5 text-primary-foreground`,children:(0,Z.jsx)(ur,{className:`size-3`})})]})}function CT({title:e,description:t}){return(0,Z.jsxs)(`div`,{className:`mb-3`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function wT({options:e,value:t,onChange:n}){return(0,Z.jsx)(`div`,{role:`radiogroup`,className:`inline-flex flex-wrap gap-1 rounded-lg bg-muted p-1`,children:e.map(e=>{let r=e.id===t;return(0,Z.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":r,title:e.title,onClick:()=>n(e.id),className:K(`focus-ring flex h-control items-center gap-2 rounded-md px-3 text-sm transition-colors`,r?`bg-card text-foreground shadow-elevation-1`:`text-muted-foreground hover:text-foreground`),children:[e.icon,e.label]},e.id)})})}function TT(){return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(By,{className:`mb-6`,title:`Appearance`,onBack:mC(),description:`Theme, colour scheme and density. Changes apply immediately and are remembered on this device.`}),(0,Z.jsx)(yT,{})]})}var ET={previousTree:`Alt+Q`,nextTree:`Alt+W`},DT=`canvas:key-bindings`,OT=/^(Alt|Alt\+Shift|Ctrl\+Shift|Meta\+Shift)\+[A-Z]$/;function kT(){try{let e=JSON.parse(localStorage.getItem(DT)||`{}`),t={...ET};for(let n of Object.keys(t))(e[n]===``||OT.test(e[n]))&&(t[n]=e[n]);return t.previousTree&&t.previousTree===t.nextTree?{...ET}:t}catch{return{...ET}}}function AT(e){localStorage.setItem(DT,JSON.stringify(e))}function jT(e){return/^Key[A-Z]$/.test(e.code)?[e.ctrlKey&&`Ctrl`,e.altKey&&`Alt`,e.metaKey&&`Meta`,e.shiftKey&&`Shift`,e.code.slice(3)].filter(Boolean).join(`+`):``}function MT(e,t,n){return e[(Math.max(0,e.indexOf(t))+n+e.length)%e.length]}function NT(e,t){return Math.abs(e)>=48&&Math.abs(e)>Math.abs(t)*1.5?e<0?1:-1:0}function PT(){let[e,t]=(0,X.useState)(kT),[n,r]=(0,X.useState)(``),i=e=>{if(e.previousTree&&e.previousTree===e.nextTree){r(`Choose a different shortcut: that combination is already assigned.`);return}try{AT(e),t(e),r(`Saved on this device.`)}catch{r(`Could not save shortcuts in this browser.`)}};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(By,{className:`mb-6`,title:`Key bindings`,onBack:mC(),description:`Web UI shortcuts, saved on this device and available offline.`}),(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`font-medium`,children:`Tree navigation`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Cycle the open workspace menu’s tabs in their displayed order, including Pins and Layers. Swipe left for next or right for previous over the tab bar. Shortcuts pause while typing or using a dialog.`}),[`previousTree`,`nextTree`].map(t=>(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(`label`,{htmlFor:t,className:`min-w-32 text-sm`,children:t===`previousTree`?`Previous tree`:`Next tree`}),(0,Z.jsxs)(`select`,{id:t,className:`rounded-md border bg-background p-2 text-sm`,value:e[t].split(`+`).slice(0,-1).join(`+`),onChange:n=>i({...e,[t]:n.target.value?`${n.target.value}+${e[t].slice(-1)||ET[t].slice(-1)}`:``}),children:[(0,Z.jsx)(`option`,{value:``,children:`Disabled`}),[`Alt`,`Alt+Shift`,`Ctrl+Shift`,`Meta+Shift`].map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]}),(0,Z.jsx)(`select`,{"aria-label":`${t===`previousTree`?`Previous`:`Next`} tree key`,disabled:!e[t],className:`rounded-md border bg-background p-2 text-sm disabled:opacity-50`,value:e[t].slice(-1)||ET[t].slice(-1),onChange:n=>i({...e,[t]:`${e[t].split(`+`).slice(0,-1).join(`+`)}+${n.target.value}`}),children:`ABCDEFGHIJKLMNOPQRSTUVWXYZ`.split(``).map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))})]},t)),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Browsers and operating systems may reserve combinations. Choose another if a shortcut does not reach Canvas. Letters refer to physical keyboard positions (Q/W on a US keyboard); Meta is Command on Mac.`}),(0,Z.jsx)(`button`,{type:`button`,className:`rounded-md border px-3 py-2 text-sm hover:bg-accent`,onClick:()=>i({...ET}),children:`Restore defaults`}),(0,Z.jsx)(`p`,{role:`status`,className:`text-sm`,children:n})]})]})}var FT=`offline-content-v1`,IT=`offline-api-v1`,LT=1073741824,RT={enabled:!1,budgetBytes:4*LT,excludedWorkspaces:[]},zT=1e3;function BT(e){return(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}function VT(e,t,n){return`${e}:${t}:${BT(n)}`}var HT=`canvas-offline`,UT=2,WT=null;function GT(){return WT||(WT=new Promise((e,t)=>{let n=indexedDB.open(HT,UT);n.onupgradeneeded=e=>{let t=n.result;if(t.objectStoreNames.contains(`config`)||t.createObjectStore(`config`),t.objectStoreNames.contains(`entries`)||t.createObjectStore(`entries`,{keyPath:`url`}),e.oldVersion>=1&&t.objectStoreNames.contains(`pins`)){t.deleteObjectStore(`pins`);let e=n.transaction.objectStore(`entries`).openCursor();e.onsuccess=()=>{let t=e.result;if(!t)return;let n=t.value;n.pinned&&t.update({...n,pinned:!1}),t.continue()}}t.objectStoreNames.contains(`scopes`)||t.createObjectStore(`scopes`,{keyPath:`id`})},n.onsuccess=()=>{n.result.onversionchange=()=>{n.result.close(),WT=null},e(n.result)},n.onerror=()=>{WT=null,t(n.error)}}),WT)}function KT(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function qT(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}async function JT(e,t){return qT((await GT()).transaction(e).objectStore(e).get(t))}async function YT(e){return qT((await GT()).transaction(e).objectStore(e).getAll())}async function XT(e,t,n){let r=(await GT()).transaction(e,`readwrite`);return r.objectStore(e).put(t,n),KT(r)}async function ZT(e,t){let n=(await GT()).transaction(e,`readwrite`);return n.objectStore(e).delete(t),KT(n)}async function QT(e){let t=(await GT()).transaction(e,`readwrite`);return t.objectStore(e).clear(),KT(t)}async function $T(){try{let e=await JT(`config`,`settings`);return e?{...RT,...e}:RT}catch{return RT}}async function eE(e){await XT(`config`,e,`settings`)}async function tE(e,t){let n=(await GT()).transaction(`entries`,`readwrite`),r=n.objectStore(`entries`);for(let n of e){let e=r.get(n);e.onsuccess=()=>{let i=e.result;i?r.put({...i,pinned:t}):t&&r.put({url:n,kind:`content`,size:0,lastAccess:Date.now(),pinned:t})}}return KT(n)}async function nE(e){let t=await YT(`entries`),n=t.filter(e=>e.kind===`api`).sort((e,t)=>e.lastAccess-t.lastAccess),r=n.slice(0,Math.max(0,n.length-zT)),i=t.filter(e=>e.kind===`content`),a=i.reduce((e,t)=>e+t.size,0),o=i.filter(e=>!e.pinned).sort((e,t)=>e.lastAccess-t.lastAccess),s=[];for(let t of o){if(a<=e)break;s.push(t),a-=t.size}if(!r.length&&!s.length)return;let[c,l]=await Promise.all([caches.open(IT),caches.open(FT)]);await Promise.all([...r.map(async e=>{await c.delete(e.url),await ZT(`entries`,e.url)}),...s.map(async e=>{await l.delete(e.url),await ZT(`entries`,e.url)})])}async function rE(){let e=await YT(`entries`),t=e.filter(e=>e.kind===`content`);return{contentBytes:t.reduce((e,t)=>e+t.size,0),contentCount:t.length,pinnedBytes:t.filter(e=>e.pinned).reduce((e,t)=>e+t.size,0),apiCount:e.length-t.length}}async function iE(){await Promise.all([caches.delete(FT),caches.delete(IT)]),await QT(`entries`),await QT(`scopes`)}async function aE(){return YT(`scopes`)}async function oE(e){return JT(`scopes`,e)}async function sE(e){await XT(`scopes`,e)}async function cE(e){let t=await JT(`scopes`,e);await ZT(`scopes`,e),t?.urls.length&&await lE(t.urls)}async function lE(e){let t=await YT(`scopes`),n=new Set(t.flatMap(e=>e.urls)),r=e.filter(e=>!n.has(e));r.length&&await tE(r,!1)}var uE=3,dE=`data/schema/file`,fE=128;async function pE({workspaceRef:e,path:t,treeName:n,treeType:r},i){let a=await $T();if(!a.enabled)throw Error(`Enable the offline cache first`);if(a.excludedWorkspaces.includes(e))throw Error(`Workspace "${e}" is excluded from offline caching`);let o=VT(e,n,t),s=BT(t),c=await oE(o),l=((await Bi(e,s,[],{limit:1e4,treeName:n,treeType:r})).payload??[]).filter(e=>e.schema===dE),u=[],d=0,f=0,p=!1,m=l.length;i?.({done:f,total:m,bytes:d});let h=0;await Promise.all(Array.from({length:Math.min(uE,l.length)},async()=>{for(;h<l.length;){let t=l[h++];if(d>=a.budgetBytes*.9){p=!0;return}try{let{blob:n}=await Ur(e,t.id);d+=n.size,u.push(`${Kr.workspaces}/${e}/documents/${t.id}/content`);try{await ai(e,t.id,fE),u.push(`${Kr.workspaces}/${e}/documents/${t.id}/thumbnail?size=${fE}`)}catch{}}catch{}f+=1,i?.({done:f,total:m,bytes:d})}})),await tE(u,!0);let g={id:o,workspaceRef:e,treeName:n,treeType:r,path:s,urls:u,bytes:d,warmedAt:Date.now(),...p?{truncated:!0}:{}};if(await sE(g),c){let e=new Set(u),t=c.urls.filter(t=>!e.has(t));t.length&&await lE(t)}return g}var mE=[{label:`1 GB`,bytes:1*LT},{label:`2 GB`,bytes:2*LT},{label:`4 GB`,bytes:4*LT},{label:`8 GB`,bytes:8*LT}];function hE(e){return e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/LT).toFixed(2)} GB`}function gE(){navigator.serviceWorker?.controller?.postMessage({type:`OFFLINE_SETTINGS_CHANGED`})}function _E(){let{showSuccessToast:e,showErrorToast:t}=Ya(),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)([]),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)({}),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(!1),v=(0,X.useCallback)(()=>{$T().then(r).catch(()=>{}),rE().then(a).catch(()=>{}),aE().then(e=>d(e.sort((e,t)=>e.id.localeCompare(t.id)))).catch(()=>{}),navigator.storage?.persisted?.().then(s).catch(()=>{})},[]);(0,X.useEffect)(()=>{v(),Or().then(e=>l(e.map(e=>e.name).filter(Boolean).sort())).catch(()=>{})},[v]);let y=async e=>{r(e),await eE(e),gE(),e.enabled&&navigator.storage?.persist?.().then(s).catch(()=>{}),nE(e.budgetBytes).then(v).catch(()=>{})},b=e=>{if(!n)return;let t=n.excludedWorkspaces.includes(e)?n.excludedWorkspaces.filter(t=>t!==e):[...n.excludedWorkspaces,e];y({...n,excludedWorkspaces:t})},x=async()=>{h(!0);try{await iE(),e(`Offline cache cleared`),v()}catch(e){t(e instanceof Error?e.message:`Failed to clear cache`)}finally{h(!1)}},S=async n=>{let r=VT(n.workspaceRef,n.treeName,n.path);p(e=>({...e,[r]:{done:0,total:0,bytes:0}}));try{let t=await pE(n,e=>p(t=>({...t,[r]:e})));e(t.truncated?`Pinned ${hE(t.bytes)} — stopped at the size budget`:`Pinned ${t.workspaceRef}:/${t.path} (${hE(t.bytes)})`)}catch(e){t(e instanceof Error?e.message:`Failed to pin`)}finally{p(e=>{let{[r]:t,...n}=e;return n}),v()}},C=(e,t)=>{_(!1);for(let n of e)S({workspaceRef:t.workspaceName,path:n,treeName:t.treeName,treeType:t.treeType})},w=e=>({workspaceRef:e.workspaceRef,path:e.path,treeName:e.treeName||`context`,treeType:e.treeType||`context`}),T=async e=>{await cE(e),v()};return n?(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(vE,{title:`Offline cache`,description:`Keep documents you open (and scopes you pin) readable without a connection. Cached on this device only; least-recently-used files are evicted when the size budget fills. Video streaming is not cached.`}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>y({...n,enabled:!n.enabled}),"aria-pressed":n.enabled,className:K(`focus-ring flex items-center gap-3 rounded-lg border p-4 text-left transition-colors`,n.enabled?`border-primary bg-accent`:`border-input hover:bg-muted/40`),children:[(0,Z.jsx)(Me,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:n.enabled?`Enabled`:`Disabled`}),(0,Z.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:n.enabled?o===!1?`Storage is not persistent — the browser may still evict the cache under disk pressure`:`Documents are cached as you browse`:`Nothing is cached for offline use`})]}),n.enabled&&(0,Z.jsx)(ur,{className:`h-4 w-4 shrink-0 text-primary`})]}),n.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Size budget`}),(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:mE.map(e=>(0,Z.jsx)(J,{variant:n.budgetBytes===e.bytes?`default`:`outline`,size:`sm`,onClick:()=>y({...n,budgetBytes:e.bytes}),children:e.label},e.bytes))})]}),i&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between text-sm`,children:[(0,Z.jsxs)(`span`,{children:[hE(i.contentBytes),` of `,hE(n.budgetBytes),` used`]}),(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[i.contentCount,` file(s)`,i.pinnedBytes>0?`, ${hE(i.pinnedBytes)} pinned`:``]})]}),(0,Z.jsx)(`div`,{className:`h-2 w-full overflow-hidden rounded-full bg-muted`,children:(0,Z.jsx)(`div`,{className:`h-full rounded-full bg-primary`,style:{width:`${Math.min(100,i.contentBytes/n.budgetBytes*100)}%`}})})]}),(0,Z.jsx)(`div`,{children:(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:x,disabled:m,children:[m?(0,Z.jsx)(Wn,{className:`mr-1.5 h-3.5 w-3.5 animate-spin`}):(0,Z.jsx)(lt,{className:`mr-1.5 h-3.5 w-3.5`}),`Clear offline cache`]})})]})]})]}),n.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(vE,{title:`Pinned scopes`,description:`A pinned scope — a workspace, or one of its tree paths — is downloaded up front and never evicted. Scopes resolve fresh on every re-warm, so moved contexts and reorganized trees are picked up; documents that left a scope return to normal eviction.`}),(0,Z.jsx)(`div`,{className:`mb-3`,children:(0,Z.jsxs)(J,{size:`sm`,onClick:()=>_(!0),disabled:!!Object.keys(f).length,children:[(0,Z.jsx)(De,{className:`mr-1.5 h-3.5 w-3.5`}),`Pin a path…`]})}),(0,Z.jsxs)(`ul`,{className:`space-y-1`,children:[u.map(e=>{let t=f[e.id];return(0,Z.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`flex-1 truncate font-mono text-xs sm:text-sm`,children:[e.workspaceRef,`://`,e.path.replace(/^\//,``),e.treeName&&e.treeName!==`context`&&(0,Z.jsx)(`span`,{className:`ml-1.5 rounded bg-muted px-1 py-0.5 font-sans text-[10px] text-muted-foreground`,children:e.treeName})]}),t?(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Wn,{className:`h-3.5 w-3.5 animate-spin`}),t.total>0?`${t.done}/${t.total} · ${hE(t.bytes)}`:`listing…`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[hE(e.bytes),e.truncated?` (partial)`:``]}),(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:()=>S(w(e)),"aria-label":`Re-warm ${e.id}`,title:`Re-warm: re-resolve the scope and download anything new`,children:(0,Z.jsx)(M,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:()=>T(e.id),"aria-label":`Unpin ${e.id}`,children:(0,Z.jsx)(je,{className:`h-3.5 w-3.5`})})]})]},e.id)}),u.length===0&&(0,Z.jsx)(`li`,{className:`rounded-md border border-dashed border-input px-3 py-4 text-center text-sm text-muted-foreground`,children:`Nothing pinned — everything relies on browse-caching and LRU`})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(vE,{title:`Workspace caching`,description:`Excluded workspaces are never cached — not even as you browse — and are not served from cache.`}),(0,Z.jsx)(`ul`,{className:`space-y-1`,children:c.map(e=>{let t=n.excludedWorkspaces.includes(e);return(0,Z.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,Z.jsx)(`span`,{className:K(`flex-1 truncate`,t&&`text-muted-foreground line-through`),children:e}),t&&(0,Z.jsx)(Nt,{className:`h-3.5 w-3.5 text-muted-foreground`}),(0,Z.jsx)(J,{variant:t?`outline`:`ghost`,size:`sm`,onClick:()=>b(e),children:t?`Include`:`Exclude`})]},e)})})]})]}),g&&(0,Z.jsx)(sp,{onClose:()=>_(!1),children:(0,Z.jsx)(ap,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,multiple:!1,tabs:[`context`,`directory`],title:`Pin for offline…`,confirmLabel:`Pin path`,onConfirm:C,onClose:()=>_(!1)})})]}):null}function vE({title:e,description:t}){return(0,Z.jsxs)(`div`,{className:`mb-4`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function yE(){return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(By,{className:`mb-6`,title:`Offline`,onBack:mC(),description:`Per-device offline cache: browse notes, files, photos and saved websites without a connection.`}),(0,Z.jsx)(_E,{})]})}function bE(e){let t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60);return t>0?`${t}d ${n}h ${r}m`:n>0?`${n}h ${r}m`:`${r}m`}function xE({name:e,version:t,detail:n}){return(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-4 py-2.5`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium truncate`,children:e}),n&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate`,children:n})]}),(0,Z.jsx)(`code`,{className:`text-xs text-muted-foreground shrink-0`,children:t})]})}function SE(){let[e,t]=(0,X.useState)(null),[n,r]=(0,X.useState)(null);(0,X.useEffect)(()=>{let e=!0;return Y.get(`/ping`,{skipAuth:!0}).then(n=>{e&&t(n??{})}).catch(t=>{e&&r(t instanceof Error?t.message:`Failed to reach the server`)}),()=>{e=!1}},[]);let i=[e?.commit?`commit ${e.commit.slice(0,7)}`:null,typeof e?.uptime==`number`?`up ${bE(e.uptime)}`:null].filter(Boolean).join(` · `),a=Object.entries(e?.components??{}).sort(([e],[t])=>e.localeCompare(t));return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(By,{className:`mb-6`,title:`About`,onBack:mC(),description:`Versions of every Canvas component this installation is running.`}),(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`section`,{className:`rounded-md border border-border divide-y divide-border`,children:[(0,Z.jsx)(xE,{name:`Canvas Web`,detail:`this interface`,version:`v2.14.8`}),e?.version&&(0,Z.jsx)(xE,{name:e.productName||e.appName||`Canvas Server`,detail:i||void 0,version:`v${e.version}`})]}),a.length>0&&(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(`h2`,{className:`mb-2 px-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Server components`}),(0,Z.jsx)(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:a.map(([e,t])=>(0,Z.jsx)(xE,{name:e,version:`v${t}`},e))})]}),n&&(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Server details unavailable: `,n]}),e?.sourceUrl&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.license?`Licensed ${e.license}. `:``,(0,Z.jsx)(`a`,{href:e.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})]})]})}var CE=[`onnx`,`clip`,`blip`,`openai`],wE=[`onnx`,`clip`,`blip`,`ollama`,`vllm`],TE=[{id:`openai`,baseUrl:`https://api.openai.com/v1`,label:`OpenAI`},{id:`vllm`,baseUrl:`http://127.0.0.1:8000/v1`,label:`vLLM`},{id:`ollama`,baseUrl:`http://127.0.0.1:11434/v1`,label:`Ollama`}],EE=e=>`${Kr.workspaces}/${encodeURIComponent(e)}/inferd`;function DE(e,t){let n={};for(let[r,i]of Object.entries(e.providers||{})){let e={...i};delete e.apiKeySet,delete e.headerNames,t.has(r)&&i.apiKey?e.apiKey=i.apiKey:delete e.apiKey,n[r]=e}return{...e,providers:n}}async function OE(e){return await Y.get(`${EE(e)}/status`)}async function kE(e,t={}){let n={};return t.force!==void 0&&(n.force=t.force),await Y.post(`${EE(e)}/summarize/images`,n)}async function AE(e){return await Y.post(`${EE(e)}/summarize/images/stop`,{})}async function jE(e){return await Y.get(`${EE(e)}/config`)}async function ME(e,t){return await Y.put(`${EE(e)}/config`,t)}async function NE(e,t={}){let n={};return t.space&&(n.space=t.space),t.reindex!==void 0&&(n.reindex=t.reindex),t.scope&&(n.scope=t.scope),await Y.post(`${EE(e)}/reindex`,n)}async function PE(e){return await Y.get(`${EE(e)}/vector-tables`)}async function FE(e,t){return await Y.delete(`${EE(e)}/vector-tables/${encodeURIComponent(t)}`)}async function IE(){return await Y.get(`${Kr.inferd}/config`)}async function LE(e){return await Y.put(`${Kr.inferd}/config`,e)}async function RE(){return await Y.get(`${Kr.inferd}/defaults`)}async function zE(e){return await Y.put(`${Kr.inferd}/defaults`,e)}async function BE(e,t){let n={...e};return delete n.apiKeySet,delete n.headerNames,(await Y.post(`${Kr.inferd}/test`,{provider:n,...t?{model:t}:{},probe:!0})).cached??null}async function VE(e,t,n=`text`){let r={...e};return delete r.apiKeySet,delete r.headerNames,await Y.post(`${Kr.inferd}/test`,{provider:r,...t?{model:t}:{},modality:n})}var HE=`h-8 w-full rounded-md border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring`,UE=`font-semibold uppercase tracking-[0.08em]`,WE={openai:{url:{key:`baseUrl`,label:`Base URL`,placeholder:`http://gpu.local:8000/v1`,hint:`OpenAI-compatible embeddings endpoint — Ollama, vLLM, TEI, infinity, LM Studio and OpenAI itself all speak this. A trailing /v1 is optional; both http://host:8000 and http://host:8000/v1 work.`},apiKey:"Sent as `Authorization: Bearer …`. Leave empty for servers that do not check it.",imageInput:!0,timeoutMs:!0,headers:!0,where:e=>e.baseUrl||`no endpoint set`},ollama:{url:{key:`host`,label:`Host (legacy)`,placeholder:`http://127.0.0.1:11434`,hint:`Written by an older version. Switch the type to openai — the host becomes the base URL and the /v1 suffix is added for you.`},apiKey:"Sent as `Authorization: Bearer …`.",where:e=>e.host||`http://127.0.0.1:11434`},onnx:{cacheDir:`Where downloaded weights are cached on the server. Empty uses the server default.`,note:`Runs in-process on the server. No endpoint and no credentials.`,where:()=>`in-process`},clip:{cacheDir:`Where downloaded weights are cached on the server. Empty uses the server default.`,note:`Runs in-process on the server. No endpoint and no credentials.`,where:()=>`in-process`}},GE=[`baseUrl`,`host`,`apiKey`,`cacheDir`,`imageInput`,`timeoutMs`],KE=[{value:`data-uri`,label:`data-uri (default)`,hint:"Images ride in the ordinary `input` array as data URIs (infinity, TEI-style servers)."},{value:`messages`,label:`messages`,hint:`vLLM's multimodal shape: one request per image, wrapped in a chat message.`}],qE=12e4;function JE(e){if(typeof e!=`string`||e.trim()===``)return null;let t;try{t=new URL(e.trim())}catch{return`Must be an absolute URL including the scheme, e.g. http://127.0.0.1:11434`}return t.protocol!==`http:`&&t.protocol!==`https:`?`Unsupported scheme '${t.protocol.replace(`:`,``)}'. Use http or https.`:null}function YE({title:e,hint:t}){return(0,Z.jsxs)(`div`,{className:`mb-2`,children:[(0,Z.jsx)(`h3`,{className:K(`text-[11px] text-muted-foreground`,UE),children:e}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:t})]})}function XE({overridden:e,source:t}){return e?(0,Z.jsx)(`span`,{className:`rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`,title:`Set on this layer; it wins over anything inherited`,children:`overridden`}):(0,Z.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground`,title:t?`Inherited: ${t}`:`Inherited from a lower config layer`,children:`inherited`})}function ZE({label:e,value:t,inheritedValue:n,onChange:r,type:i=`text`,placeholder:a,disabled:o,hint:s,error:c,mono:l}){let u=t!==void 0&&t!==``;return(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:e}),(0,Z.jsx)(XE,{overridden:u,source:n===void 0?void 0:String(n)}),u&&!o&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(``),className:`text-[10px] text-muted-foreground underline hover:text-foreground`,title:`Clear the override and fall back to the inherited value`,children:`reset`})]}),(0,Z.jsx)(q,{type:i,value:t??``,disabled:o,onChange:e=>r(e.target.value),placeholder:a??(n===void 0?`—`:String(n)),className:K(`h-8 text-sm`,l&&`font-mono`,c&&`border-destructive focus-visible:ring-destructive`)}),c&&(0,Z.jsx)(`p`,{className:`text-[11px] font-medium text-destructive`,children:c}),s&&(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:s})]})}function QE({label:e,checked:t,overridden:n,disabled:r,onChange:i}){return(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:r,checked:t,onChange:e=>i(e.target.checked)}),e,(0,Z.jsx)(XE,{overridden:n})]})}function $E({storedNames:e,value:t,disabled:n,onChange:r}){let i=t!==void 0,[a,o]=(0,X.useState)([]),s=e=>{o(e),r(Object.fromEntries(e.filter(([e])=>e.trim()!==``)))};return(0,Z.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Custom headers`}),i?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will replace stored`}),!n&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{o([]),r(void 0)},className:`text-[10px] text-muted-foreground underline hover:text-foreground`,children:`cancel`})]}):(0,Z.jsx)(XE,{overridden:!1,source:e?.join(`, `)})]}),!i&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e?.length?(0,Z.jsxs)(Z.Fragment,{children:[`Stored: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:e.join(`, `)}),` (values are never sent back)`]}):`None set.`}),!n&&(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>{o([[``,``]]),r({})},children:e?.length?`Replace headers`:`Add headers`})]}),i&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Saving replaces every stored header, so re-enter the ones you want to keep.`}),a.map(([e,t],r)=>(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:e,disabled:n,placeholder:`X-Tenant`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[e.target.value,t[1]]:t))}),(0,Z.jsx)(q,{value:t,disabled:n,placeholder:`value`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[t[0],e.target.value]:t))}),(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,disabled:n,"aria-label":`Remove header ${e||r+1}`,onClick:()=>s(a.filter((e,t)=>t!==r)),children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]},r)),!n&&(0,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>s([...a,[``,``]]),children:[(0,Z.jsx)(nn,{className:`mr-1.5 h-3.5 w-3.5`}),`Add header`]})]})]})}function eD({open:e,onClick:t,label:n}){return(0,Z.jsx)(`button`,{type:`button`,onClick:t,"aria-expanded":e,title:n,"aria-label":n,className:`flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:(0,Z.jsx)(Ne,{className:K(`h-4 w-4 transition-transform motion-reduce:transition-none`,e&&`rotate-180`)})})}var tD={configured:`bg-success`,"needs-fill":`bg-warning`,unresolved:`bg-destructive`,unset:`bg-muted-foreground/30`};function nD({value:e,effective:t,inherited:n,resolvedSpaces:r,invalid:i,attention:a,onFill:o,saving:s=!1,disabled:c=!1,saveLabel:l=`Save`,onSave:u}){let{showToast:d}=oo(),[f,p]=(0,X.useState)(()=>structuredClone(e)),[m,h]=(0,X.useState)(new Set),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(null),E=(0,X.useMemo)(()=>[...new Set([...Object.keys(t.spaces||{}),...Object.keys(f.spaces||{})])].sort(),[t.spaces,f.spaces]),D=(0,X.useMemo)(()=>[...new Set([...Object.keys(t.providers||{}),...Object.keys(f.providers||{})])].sort(),[t.providers,f.providers]),O=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`dim`||t===`maxLength`||t===`dimensions`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},k=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},A=(e,t,n)=>{t===`apiKey`&&h(t=>{let r=new Set(t);return n===``?r.delete(e):r.add(e),r}),p(r=>{let i={...r.providers||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`timeoutMs`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},j=(e,t,n)=>{p(r=>{let i={...r.providers||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},M=e=>{p(t=>{let n={...t.providers||{}};return delete n[e],{...t,providers:n}}),h(t=>{let n=new Set(t);return n.delete(e),n})},N=()=>{let e=S.trim();if(e){if(E.includes(e)){d({title:`Space exists`,description:`'${e}' already has a row below.`,variant:`destructive`});return}p(t=>({...t,spaces:{...t.spaces||{},[e]:{}}})),C(``),T(`space:${e}`)}},P=(e,t)=>{if(e){if(D.includes(e)){d({title:`Backend exists`,description:`'${e}' is already declared. Open it below to edit.`,variant:`destructive`});return}p(n=>({...n,providers:{...n.providers||{},[e]:{type:`openai`,...t?{baseUrl:t}:{}}}})),x(``),T(`provider:${e}`)}},ee=e=>({...t.providers?.[e]||{},...f.providers?.[e]||{}}),F=async e=>{let n=f.spaces?.[e]?.provider??t.spaces?.[e]?.provider,r=f.spaces?.[e]?.model??t.spaces?.[e]?.model;if(!n){d({title:`No backend`,description:`Space '${e}' has no backend to test.`,variant:`destructive`});return}let i=ee(n),a=i.type?WE[i.type]?.url?.key:void 0,o=a?JE(i[a]):null;if(o){d({title:`Backend '${n}'`,description:o,variant:`destructive`});return}_(e);try{try{await BE(i,r)===!1&&(y(!0),d({title:`Downloading model`,description:`'${r??`the configured model`}' is not in the server's cache yet; downloading now. A first test can take a few minutes; the model is then cached for good.`}))}catch{}let n=await VE(i,r,e),a=f.spaces?.[e]?.dim??t.spaces?.[e]?.dim,o=n.dim>0&&a!==void 0&&n.dim!==a;(o||n.dim>0&&a===void 0)&&O(e,`dim`,String(n.dim)),d({title:o?`Backend answered; dimensions corrected`:`Backend answered`,description:o?`Returned ${n.dim}-d but '${e}' was set to ${a}-d. Dimensions updated to ${n.dim}; save to apply. (${n.latencyMs} ms)`:`${n.dim}-d in ${n.latencyMs} ms`})}catch(e){d({title:`Test failed`,description:e instanceof Error?e.message:`Backend unreachable`,variant:`destructive`})}finally{_(null),y(!1)}},I=(0,X.useMemo)(()=>{let e=[];for(let[n,r]of Object.entries(f.providers||{})){let i=r.type??t.providers?.[n]?.type,a=i?WE[i]?.url?.key:void 0;if(!a)continue;let o=JE(r[a]);o&&e.push(`${n}: ${o}`)}return e},[f.providers,t.providers]),te=(0,X.useMemo)(()=>JSON.stringify(f)!==JSON.stringify(e)||m.size>0,[f,e,m]),ne=async()=>{if(I.length>0){d({title:`Fix the endpoint first`,description:I.join(` · `),variant:`destructive`});return}await u(DE(f,m)),h(new Set)},L=e=>T(t=>t===e?null:e);return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[i&&(0,Z.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive-subtle p-3 text-xs`,children:[(0,Z.jsx)(at,{className:`mt-0.5 h-4 w-4 shrink-0 text-destructive`}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Stored config does not resolve; defaults are standing in`}),(0,Z.jsx)(`p`,{className:`mt-0.5 font-mono text-[11px] text-muted-foreground`,children:i})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(YE,{title:`Search models`,hint:`Choose a provider and model for each kind of content. After switching models, fill the new index to make existing documents searchable. Previous model indexes are preserved.`}),E.length===0?(0,Z.jsxs)(`div`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:`No spaces on this layer`}),(0,Z.jsx)(`p`,{className:`mx-auto mt-1 max-w-sm text-xs text-muted-foreground`,children:`A space needs a backend, a model and a dimension count. Add one below to start embedding.`})]}):(0,Z.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:E.map(e=>{let s=f.spaces?.[e]||{},l=t.spaces?.[e]||{},u=n.spaces?.[e]||{},d=r?.[e],p=`space:${e}`,m=w===p,h=s.model??l.model,_=s.provider??l.provider,y=s.dim??l.dim,b=s.chunk??l.chunk??!1,x=a?.includes(e)??!1;return(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(`span`,{className:K(`absolute inset-y-0 left-0 w-[3px]`,tD[i?`unresolved`:x?`needs-fill`:h?`configured`:`unset`]),"aria-hidden":!0}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 py-3 pl-4 pr-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,Z.jsx)(`span`,{className:K(`text-[11px]`,UE),children:e}),(0,Z.jsx)(`span`,{className:`truncate font-mono text-sm`,children:h||`no model set`}),_&&(0,Z.jsxs)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground`,children:[`via `,_]}),y!==void 0&&(0,Z.jsxs)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:[y,`-d`]}),b&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`chunked`})]}),r&&h&&(0,Z.jsxs)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,title:`Vector table backing this space`,children:[`└─ `,d?.table??(0,Z.jsx)(`span`,{className:`not-italic`,children:`not created yet`})]}),x&&(0,Z.jsx)(`p`,{className:`mt-1 text-[11px] text-warning`,children:`New table, nothing embedded in it yet; dense search stays thin for this space until it is filled. Reverting the model is still instant.`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[x&&o&&(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>o(e),children:`Fill`}),(0,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`ghost`,disabled:c||g!==null,onClick:()=>F(e),title:`Round-trip a real embedding call against this backend and report the dimensions it returns`,children:[(0,Z.jsx)(ge,{className:`mr-1.5 h-3.5 w-3.5`}),g===e?v?`Downloading…`:`Testing…`:`Test`]}),(0,Z.jsx)(eD,{open:m,onClick:()=>L(p),label:`Edit ${e}`})]})]}),m&&(0,Z.jsxs)(`div`,{className:`border-t bg-muted/40 py-4 pl-4 pr-3`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Backend`}),(0,Z.jsx)(XE,{overridden:s.provider!==void 0,source:u.provider})]}),(0,Z.jsxs)(`select`,{className:HE,disabled:c,value:s.provider??``,onChange:t=>O(e,`provider`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:l.provider?`inherited: ${l.provider}`:`inherited`}),D.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Z.jsx)(ZE,{label:`Model`,mono:!0,value:s.model,inheritedValue:l.model,onChange:t=>O(e,`model`,t),disabled:c}),(0,Z.jsx)(ZE,{label:`Dimensions`,type:`number`,value:s.dim,inheritedValue:l.dim,onChange:t=>O(e,`dim`,t),disabled:c,hint:`Sizes the vector table. Test asks the backend and fills in what it really returns.`}),(0,Z.jsx)(ZE,{label:`Max length`,type:`number`,value:s.maxLength,inheritedValue:l.maxLength,onChange:t=>O(e,`maxLength`,t),disabled:c})]}),(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-4`,children:[(0,Z.jsx)(QE,{label:`Chunk long inputs`,checked:b,overridden:s.chunk!==void 0,disabled:c,onChange:t=>k(e,`chunk`,t)}),(0,Z.jsx)(QE,{label:`Build ANN index`,checked:s.annIndex??l.annIndex??!0,overridden:s.annIndex!==void 0,disabled:c,onChange:t=>k(e,`annIndex`,t)})]})]})]},e)})}),!c&&(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{value:S,onChange:e=>C(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),N())},placeholder:`new space name (e.g. audio)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`ghost`,onClick:N,children:[(0,Z.jsx)(nn,{className:`mr-1.5 h-3.5 w-3.5`}),`Add space`]})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(YE,{title:`Model providers`,hint:`Connect a service here, then select it under Search models above. Built-in providers work without an extra connection. Provider changes take effect when you save.`}),(0,Z.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:D.map(e=>{let n=f.providers?.[e]||{},r=t.providers?.[e]||{},i=wE.includes(e),a=f.providers?.[e]!==void 0,o=`provider:${e}`,s=w===o,l=n.type??r.type,u=l?WE[l]:void 0,d=u?.url?JE(n[u.url.key]):null,p={...r,...n},h=GE.filter(e=>!(n[e]===void 0||e===u?.url?.key||e===`apiKey`&&u?.apiKey||e===`cacheDir`&&u?.cacheDir)),g=E.filter(n=>(f.spaces?.[n]?.provider??t.spaces?.[n]?.provider)===e);return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,Z.jsx)(`span`,{className:`font-mono text-sm font-semibold`,children:e}),(0,Z.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:l??`no type`}),i&&(0,Z.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`built-in`}),p.apiKeySet&&!m.has(e)&&(0,Z.jsx)(`span`,{className:`text-[10px] font-medium text-success`,children:`key set`}),d&&(0,Z.jsx)(`span`,{className:`text-[10px] font-medium text-destructive`,children:`check endpoint`})]}),(0,Z.jsx)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,children:u?u.where(p):`—`}),g.length>0&&(0,Z.jsxs)(`p`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`used by `,g.join(`, `)]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[a&&!i&&!c&&(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>M(e),title:`Remove this override`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(eD,{open:s,onClick:()=>L(o),label:`Edit ${e}`})]})]}),s&&(0,Z.jsxs)(`div`,{className:`border-t bg-muted/40 px-4 py-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Type`}),(0,Z.jsx)(XE,{overridden:n.type!==void 0,source:r.type})]}),(0,Z.jsxs)(`select`,{className:HE,disabled:c,value:n.type??``,onChange:t=>A(e,`type`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:r.type?`inherited: ${r.type}`:`inherited`}),CE.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e)),l&&!CE.includes(l)&&(0,Z.jsxs)(`option`,{value:l,children:[l,` (legacy)`]})]}),u?.note&&(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:u.note})]}),u?.url&&(0,Z.jsx)(ZE,{label:u.url.label,mono:!0,value:n[u.url.key],inheritedValue:r[u.url.key],onChange:t=>A(e,u.url.key,t),disabled:c,placeholder:r[u.url.key]??u.url.placeholder,hint:u.url.hint,error:d??void 0}),u?.cacheDir&&(0,Z.jsx)(ZE,{label:`Cache directory`,mono:!0,value:n.cacheDir,inheritedValue:r.cacheDir,onChange:t=>A(e,`cacheDir`,t),disabled:c,placeholder:r.cacheDir??`server default`,hint:u.cacheDir}),u?.imageInput&&(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Image input shape`}),(0,Z.jsx)(XE,{overridden:n.imageInput!==void 0,source:r.imageInput})]}),(0,Z.jsxs)(`select`,{className:HE,disabled:c,value:n.imageInput??``,onChange:t=>A(e,`imageInput`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:r.imageInput?`inherited: ${r.imageInput}`:`inherited: data-uri`}),KE.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:KE.find(e=>e.value===(n.imageInput??r.imageInput??`data-uri`))?.hint})]}),u?.timeoutMs&&(0,Z.jsx)(ZE,{label:`Request timeout (ms)`,type:`number`,value:n.timeoutMs,inheritedValue:r.timeoutMs??qE,onChange:t=>A(e,`timeoutMs`,t),disabled:c,hint:`How long to wait for a batch before giving up. Raise it for a slow or cold GPU host.`}),u?.apiKey&&(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`API key`}),m.has(e)&&(0,Z.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will be written`})]}),(0,Z.jsx)(q,{type:`password`,autoComplete:`new-password`,disabled:c,value:n.apiKey??``,onChange:t=>A(e,`apiKey`,t.target.value),placeholder:r.apiKeySet?`•••••••• (stored; leave empty to keep)`:`unset`,className:`h-8 text-sm`}),(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[u.apiKey,` Write-only: the stored key is never sent back, and leaving this empty keeps whatever is stored.`]})]})]}),u?.headers&&(0,Z.jsx)($E,{disabled:c,storedNames:r.headerNames,value:n.headers,onChange:t=>j(e,`headers`,t)}),h.length>0&&!c&&(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2 rounded-md border border-dashed p-2 text-[11px] text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{children:[`Not used by type `,(0,Z.jsx)(`span`,{className:`font-mono`,children:l}),`:`,` `,(0,Z.jsx)(`span`,{className:`font-mono`,children:h.join(`, `)})]}),(0,Z.jsx)(`button`,{type:`button`,className:`underline hover:text-foreground`,onClick:()=>h.forEach(t=>A(e,t,``)),children:`clear`})]}),r.headerNames&&r.headerNames.length>0&&(0,Z.jsxs)(`p`,{className:`mt-3 text-[11px] text-muted-foreground`,children:[`Stored custom headers: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:r.headerNames.join(`, `)}),` (values not shown)`]})]})]},e)})}),!c&&(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{value:b,onChange:e=>x(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),P(b.trim()))},placeholder:`new backend name (e.g. gpu)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>P(b.trim()),children:[(0,Z.jsx)(nn,{className:`mr-1.5 h-3.5 w-3.5`}),`Add backend`]}),TE.filter(e=>!D.includes(e.id)).map(e=>(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>P(e.id,e.baseUrl),title:`Add an openai-type backend '${e.id}' pointed at ${e.baseUrl}`,children:e.label},e.id))]})]}),!c&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-4`,children:[(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:te?`default`:`outline`,onClick:ne,disabled:s||!te||I.length>0,children:s?`Saving…`:l}),(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,disabled:s||!te,onClick:()=>{p(structuredClone(e)),h(new Set)},children:`Discard changes`}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:I.length>0?(0,Z.jsxs)(`span`,{className:`font-medium text-destructive`,children:[I.length,` endpoint `,I.length===1?`needs`:`need`,` fixing`]}):te?`Unsaved changes`:`Everything saved`})]})]})}function rD(){let{showToast:e}=oo(),[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),l=(0,X.useCallback)(()=>IE().then(e=>{n(e),c(null)}).catch(e=>c(e instanceof Error?e.message:`Failed to load embedding defaults`)).finally(()=>i(!1)),[]);(0,X.useEffect)(()=>{l()},[l]);let u=()=>{i(!0),l()};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[(0,Z.jsx)(By,{compact:!0,className:`mb-6`,title:`Search & AI defaults`,onBack:mC(),description:`Your account · Choose the embedding models used for text and image search. Workspace settings override these defaults. Running workspaces adopt new defaults when restarted.`,actions:(0,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:u,disabled:r,children:[(0,Z.jsx)(M,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})}),r?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(M,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):s||!t?(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Embedding defaults unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s||`No config returned.`})]}),(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:u,children:`Retry`})]}):(0,Z.jsx)(nD,{value:t.user||{},effective:t.effective||{},inherited:t.serverDefaults||{},invalid:t.invalid,saving:a,saveLabel:`Save defaults`,onSave:async t=>{o(!0);try{let n=await LE(t);e({title:`Defaults saved`,description:n.restartRequired?`${n.workspaces.length} running workspace(s) keep their current tables until restarted. Set the config on a workspace directly to change it live.`:`New workspaces will inherit this.`}),await l()}catch(t){e({title:`Save failed`,description:t instanceof Error?t.message:`Failed to save`,variant:`destructive`})}finally{o(!1)}}},JSON.stringify(t.user))]})}function iD(){let e=Hc(),{showToast:t}=oo(),n=new URLSearchParams(e.search),r=e=>{try{let t=new URL(e);return t.pathname.includes(`/rest/v2/workspaces/`)&&!t.pathname.includes(`/rest/v2/pub/`)?t.pathname=t.pathname.replace(`/rest/v2/workspaces/`,`/rest/v2/pub/workspaces/`):t.pathname.includes(`/rest/v2/contexts/`)&&!t.pathname.includes(`/rest/v2/pub/`)&&(t.pathname=t.pathname.replace(`/rest/v2/contexts/`,`/rest/v2/pub/contexts/`)),t.toString()}catch{return e}},i=r(n.get(`url`)||``),a=sessionStorage.getItem(`sharedToken:last`)||``,[o,s]=(0,X.useState)(i),[c,l]=(0,X.useState)(a),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(!1),g=(0,X.useMemo)(()=>{try{let e=new URL(o);return e.pathname.includes(`/pub/workspaces/`)?`workspace`:e.pathname.includes(`/pub/contexts/`)?`context`:`unknown`}catch{return`unknown`}},[o]),_=()=>({Authorization:`Bearer ${c.trim()}`}),v=async()=>{if(!(!o||!c)){h(!0);try{let e=r(o),t=await Y.get(e,{skipAuth:!0,headers:_()});d(t);let n=await Y.get(`${e}/documents`,{skipAuth:!0,headers:_()}),i=Array.isArray(n)?n:Array.isArray(n?.data)?n.data:[];p(Array.isArray(i)?i:[])}catch(e){let n=o.includes(`/rest/v2/workspaces/`)?`Ensure the URL uses /rest/v2/pub/workspaces/<workspace-id> and the token matches that workspace.`:o.includes(`/rest/v2/contexts/`)?`Ensure the URL uses /rest/v2/pub/contexts/<context-id>.`:void 0;t({title:`Error`,description:`${e instanceof Error?e.message:`Failed to load shared resource`}${n?`: ${n}`:``}`,variant:`destructive`}),d(null),p([])}finally{h(!1)}}},y=(0,X.useRef)(v);return(0,X.useEffect)(()=>{y.current()},[]),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(By,{onBack:mC(),title:`Shared Resource Viewer`,description:`Open a resource someone shared with you.`}),(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`Full pub URL`}),(0,Z.jsx)(q,{value:c,onChange:e=>l(e.target.value),placeholder:`Access token (canvas-...)`}),(0,Z.jsx)(J,{onClick:v,disabled:m||!o||!c,children:`Load`})]}),(0,Z.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`Type: `,g]}),m?(0,Z.jsx)(`div`,{className:`text-center py-8 text-muted-foreground`,children:`Loading...`}):(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,Z.jsx)(`h2`,{className:`font-semibold mb-2`,children:`Metadata`}),(0,Z.jsx)(`pre`,{className:`text-xs overflow-auto max-h-80`,children:JSON.stringify(u,null,2)})]}),(0,Z.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,Z.jsxs)(`h2`,{className:`font-semibold mb-2`,children:[`Documents (`,f.length,`)`]}),f.length===0?(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No documents`}):(0,Z.jsx)(`ul`,{className:`space-y-2 text-sm`,children:f.slice(0,100).map((e,t)=>(0,Z.jsxs)(`li`,{className:`border rounded p-2`,children:[(0,Z.jsx)(`div`,{className:`font-mono text-xs`,children:e.id}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.schema})]},t))})]})]}),(0,Z.jsx)(Vu,{className:`mt-8`})]})}function aD(e={}){let t=new URLSearchParams;e.tail&&t.set(`tail`,String(e.tail)),e.level&&t.set(`level`,e.level),e.module&&t.set(`module`,e.module);let n=t.toString();return n?`?${n}`:``}function oD(){let e=localStorage.getItem(`authToken`);if(!e)throw Error(`Authentication required`);let t=localStorage.getItem(`appName`)||window.location.hostname;return{Authorization:`Bearer ${e}`,"X-App-Name":t,Accept:`text/event-stream`}}var sD={async listUsers(e){let t=new URLSearchParams;e?.status&&t.append(`status`,e.status),e?.userType&&t.append(`userType`,e.userType);let n=t.toString(),r=n?`${Kr.admin.users}?${n}`:Kr.admin.users;return await Y.get(r)},async getUser(e){return await Y.get(`${Kr.admin.users}/${e}`)},async createUser(e){return await Y.post(Kr.admin.users,e)},async updateUser(e,t){return await Y.put(`${Kr.admin.users}/${e}`,t)},async deleteUser(e){await Y.delete(`${Kr.admin.users}/${e}`)}},cD={async listAllWorkspaces(){return await Y.get(Kr.admin.workspaces)},async createWorkspace(e){return await Y.post(Kr.admin.workspaces,e)},async deleteWorkspace(e){await Y.delete(`${Kr.admin.workspaces}/${e}`)}},lD={async getLogs(e={}){return(await Y.get(`${Kr.admin.logs}${aD(e)}`)).logs||[]},async streamLogs(e={},t={}){let{signal:n,onEntry:r,onError:i}=t;try{let t=await fetch(`${Kr.admin.logsStream}${aD(e)}`,{method:`GET`,headers:oD(),credentials:`include`,signal:n});if(!t.ok)throw Error(`Failed to open log stream (${t.status})`);if(!t.body)throw Error(`Streaming is not supported by this browser`);let i=t.body.getReader(),a=new TextDecoder,o=``,s=e=>{let t=e.split(`
|
|
19
|
+
`),n=`message`,i=[];for(let e of t)if(!(!e||e.startsWith(`:`))){if(e.startsWith(`event:`)){n=e.slice(6).trim();continue}e.startsWith(`data:`)&&i.push(e.slice(5).trim())}if(n!==`log`||i.length===0)return;let a=JSON.parse(i.join(`
|
|
20
|
+
`));r?.(a)};try{for(;;){let{done:e,value:t}=await i.read();if(e)break;o+=a.decode(t,{stream:!0});let n=o.split(`
|
|
21
|
+
|
|
22
|
+
`);o=n.pop()||``;for(let e of n)s(e)}o.trim()&&s(o)}finally{i.releaseLock()}}catch(e){if(n?.aborted)return;let t=e instanceof Error?e:Error(String(e));throw i?.(t),t}}};async function uD(e,t,n){let r=await Y.postEnvelope(`${Kr.admin.workspaces}/${encodeURIComponent(e)}/${t}`,n??{});return{message:r.message??``,payload:r.payload}}function dD(e){return uD(e,`reindex-timelines`)}function fD(e,t=!1){return uD(e,`reindex-search${t?`?rebuild=true`:``}`)}function pD(e,t){return uD(e,`optimize`,t?{space:t}:{})}function mD(e){return uD(e,`reindex-mime`)}var hD={users:sD,workspaces:cD,logs:lD},gD=()=>{let e=[`#FF6B6B`,`#4ECDC4`,`#45B7D1`,`#96CEB4`,`#FECA57`,`#FF9FF3`,`#54A0FF`,`#5F27CD`,`#00D2D3`,`#FF9F43`,`#10AC84`,`#EE5A24`,`#EA2027`,`#009432`,`#0652DD`];return e[Math.floor(Math.random()*e.length)]};function _D(){let e=Yu()?.userType===`admin`,[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(e),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(e?null:`Access denied. Admin privileges required.`),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)({search:``,owner:``,type:``,status:``}),[_,v]=(0,X.useState)({userId:``,name:``,label:``,description:``,color:gD(),type:`workspace`}),{showToast:y}=oo(),b=(0,X.useCallback)(async()=>{try{o(!0);let e=await hD.workspaces.listAllWorkspaces();n(e),u(null)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch workspaces`;u(t),y({title:`Error`,description:t,variant:`destructive`})}finally{o(!1)}},[y]);(0,X.useEffect)(()=>{e&&b()},[e,b]);let x=(0,X.useCallback)(async()=>{try{c(!0);let e=await hD.users.listUsers({status:`active`});i(e)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch users`;y({title:`Error`,description:t,variant:`destructive`})}finally{c(!1)}},[y]),S=async e=>{if(e.preventDefault(),!_.userId||!_.name.trim()){y({title:`Validation Error`,description:`User and workspace name are required`,variant:`destructive`});return}f(!0);try{let e={userId:_.userId,name:_.name.trim(),label:_.label.trim()||_.name.trim(),description:_.description.trim(),color:_.color,type:_.type};await hD.workspaces.createWorkspace(e),v({userId:``,name:``,label:``,description:``,color:gD(),type:`workspace`}),m(!1),await b(),y({title:`Success`,description:`Workspace created successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to create workspace`;y({title:`Error`,description:t,variant:`destructive`})}finally{f(!1)}},C=async(e,t)=>{if(confirm(`Are you sure you want to delete workspace "${t}"? This action cannot be undone and will delete all data in the workspace.`))try{await hD.workspaces.deleteWorkspace(e),await b(),y({title:`Success`,description:`Workspace deleted successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to delete workspace`;y({title:`Error`,description:t,variant:`destructive`})}},w=async()=>{v({userId:``,name:``,label:``,description:``,color:gD(),type:`workspace`}),m(!0),await x()},T=()=>{m(!1)};gf(T,p);let E=t.filter(e=>{let t=h.search===``||e.name.toLowerCase().includes(h.search.toLowerCase())||e.label.toLowerCase().includes(h.search.toLowerCase())||e.ownerName&&e.ownerName.toLowerCase().includes(h.search.toLowerCase())||e.ownerEmail&&e.ownerEmail.toLowerCase().includes(h.search.toLowerCase()),n=h.owner===``||e.owner===h.owner,r=h.type===``||e.type===h.type,i=h.status===``||e.status===h.status;return t&&n&&r&&i}),D=Array.from(new Set(t.map(e=>e.owner))).map(e=>{let n=t.find(t=>t.owner===e);return{id:e,name:n?.ownerName||n?.ownerEmail||e}});return e?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(By,{title:`Workspace Administration`,description:`Manage workspaces across all users`}),t.some(e=>e.status!==`active`&&e.protection?.mode&&e.protection.mode!==`none`)&&(0,Z.jsxs)(`p`,{className:`text-sm rounded border p-3`,children:[t.filter(e=>e.status!==`active`&&e.protection?.mode&&e.protection.mode!==`none`).length,` protected workspaces waiting for their owners to start them.`]}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 md:flex-row md:items-center md:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 md:flex-row md:items-center`,children:[(0,Z.jsx)(q,{placeholder:`Search workspaces...`,value:h.search,onChange:e=>g(t=>({...t,search:e.target.value})),className:`md:w-64`}),(0,Z.jsxs)(`select`,{value:h.owner,onChange:e=>g(t=>({...t,owner:e.target.value})),className:`px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:``,children:`All Owners`}),D.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),(0,Z.jsxs)(`select`,{value:h.type,onChange:e=>g(t=>({...t,type:e.target.value})),className:`px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:``,children:`All Types`}),(0,Z.jsx)(`option`,{value:`workspace`,children:`Workspace`}),(0,Z.jsx)(`option`,{value:`universe`,children:`Universe`})]}),(0,Z.jsxs)(`select`,{value:h.status,onChange:e=>g(t=>({...t,status:e.target.value})),className:`px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:``,children:`All Statuses`}),(0,Z.jsx)(`option`,{value:`active`,children:`Active`}),(0,Z.jsx)(`option`,{value:`inactive`,children:`Inactive`}),(0,Z.jsx)(`option`,{value:`error`,children:`Error`})]})]}),(0,Z.jsxs)(J,{onClick:w,children:[(0,Z.jsx)(nn,{className:`mr-2 h-4 w-4`}),`Create Workspace`]})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[a&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading workspaces...`}),l&&!t.length&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:l})}),!a&&!l&&E.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No workspaces found`}),E.length>0&&(0,Z.jsx)(`div`,{className:`border rounded-md`,children:(0,Z.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Z.jsxs)(`table`,{className:`w-full`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{className:`bg-muted/50`,children:[(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Name`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Label`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Owner`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Type`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Status`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Color`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Created`}),(0,Z.jsx)(`th`,{className:`text-right p-3 font-medium`,children:`Actions`})]})}),(0,Z.jsx)(`tbody`,{children:E.map(e=>(0,Z.jsxs)(`tr`,{className:`border-t`,children:[(0,Z.jsx)(`td`,{className:`p-3 font-medium font-mono text-sm`,children:e.name}),(0,Z.jsx)(`td`,{className:`p-3`,children:e.label}),(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(Ue,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`font-medium`,children:e.ownerName||`Unknown`}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.ownerEmail})]})]})}),(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsx)(`span`,{className:`px-2 py-1 rounded-full text-xs ${e.type===`universe`?`bg-accent text-primary`:`bg-info-subtle text-info`}`,children:e.type})}),(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsx)(`span`,{className:`px-2 py-1 rounded-full text-xs ${e.status===`active`?`bg-success-subtle text-success`:e.status===`inactive`?`bg-warning-subtle text-warning`:`bg-destructive-subtle text-destructive`}`,children:e.status})}),(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`div`,{className:`w-4 h-4 rounded border`,style:{backgroundColor:e.color}}),(0,Z.jsx)(`span`,{className:`font-mono text-xs`,children:e.color})]})}),(0,Z.jsx)(`td`,{className:`p-3`,children:new Date(e.createdAt).toLocaleDateString()}),(0,Z.jsxs)(`td`,{className:`p-3 text-right space-x-2`,children:[(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>window.open(`/workspaces/${e.name}`,`_blank`),title:`View workspace`,children:(0,Z.jsx)(Dt,{className:`h-4 w-4`})}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>C(e.id,e.name),className:`text-destructive hover:bg-destructive/10 hover:text-destructive`,title:`Delete workspace`,disabled:e.type===`universe`,children:(0,Z.jsx)(tt,{className:`h-4 w-4`})})]})]},e.id))})]})})})]}),(0,Z.jsxs)(`div`,{className:`grid grid-cols-1 md:grid-cols-4 gap-4 mt-8`,children:[(0,Z.jsxs)(`div`,{className:`bg-card p-4 rounded-lg border`,children:[(0,Z.jsx)(`div`,{className:`text-2xl font-bold`,children:t.length}),(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Total Workspaces`})]}),(0,Z.jsxs)(`div`,{className:`bg-card p-4 rounded-lg border`,children:[(0,Z.jsx)(`div`,{className:`text-2xl font-bold`,children:t.filter(e=>e.status===`active`).length}),(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Active Workspaces`})]}),(0,Z.jsxs)(`div`,{className:`bg-card p-4 rounded-lg border`,children:[(0,Z.jsx)(`div`,{className:`text-2xl font-bold`,children:t.filter(e=>e.type===`universe`).length}),(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Universe Workspaces`})]}),(0,Z.jsxs)(`div`,{className:`bg-card p-4 rounded-lg border`,children:[(0,Z.jsx)(`div`,{className:`text-2xl font-bold`,children:D.length}),(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Unique Owners`})]})]}),p&&(0,Z.jsx)(`div`,{className:`fixed inset-0 bg-scrim flex items-center justify-center z-50`,children:(0,Z.jsxs)(`div`,{className:`bg-card rounded-lg p-6 w-full max-w-md mx-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-4`,children:[(0,Z.jsx)(`h3`,{className:`text-lg font-semibold`,children:`Create New Workspace`}),(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:T,children:(0,Z.jsx)(je,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`form`,{onSubmit:S,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(bu,{htmlFor:`userId`,children:`User`}),(0,Z.jsxs)(`select`,{id:`userId`,value:_.userId,onChange:e=>v(t=>({...t,userId:e.target.value})),disabled:d||s,className:`w-full px-3 py-2 border border-border rounded-md`,required:!0,children:[(0,Z.jsx)(`option`,{value:``,children:`Select a user...`}),r.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.name,` (`,e.email,`)`]},e.id))]}),s&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:`Loading users...`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(bu,{htmlFor:`name`,children:`Workspace Name`}),(0,Z.jsx)(q,{id:`name`,type:`text`,value:_.name,onChange:e=>v(t=>({...t,name:e.target.value})),placeholder:`my-workspace`,disabled:d,required:!0}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:`Lowercase letters, numbers, and hyphens only`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(bu,{htmlFor:`label`,children:`Display Label`}),(0,Z.jsx)(q,{id:`label`,type:`text`,value:_.label,onChange:e=>v(t=>({...t,label:e.target.value})),placeholder:`My Workspace`,disabled:d})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(bu,{htmlFor:`description`,children:`Description`}),(0,Z.jsx)(q,{id:`description`,type:`text`,value:_.description,onChange:e=>v(t=>({...t,description:e.target.value})),placeholder:`Workspace description (optional)`,disabled:d})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(bu,{htmlFor:`type`,children:`Type`}),(0,Z.jsxs)(`select`,{id:`type`,value:_.type,onChange:e=>v(t=>({...t,type:e.target.value})),disabled:d,className:`w-full px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:`workspace`,children:`Workspace`}),(0,Z.jsx)(`option`,{value:`universe`,children:`Universe`})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(bu,{htmlFor:`color`,children:`Color`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(q,{id:`color`,type:`color`,value:_.color,onChange:e=>v(t=>({...t,color:e.target.value})),className:`h-10 w-16 p-1`,disabled:d}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>v(e=>({...e,color:gD()})),disabled:d,children:`Random`})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2 pt-4`,children:[(0,Z.jsx)(J,{type:`submit`,disabled:d||s,className:`flex-1`,children:d?`Creating...`:`Create Workspace`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,onClick:T,disabled:d,children:`Cancel`})]})]})]})})]}):(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:`Access denied. Admin privileges required.`})})}function vD(){let e=Yu()?.userType===`admin`;return(0,X.useEffect)(()=>{},[e]),e?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(By,{title:`All Contexts`,description:`Manage all contexts across all users`}),(0,Z.jsx)(`div`,{className:`flex flex-col items-center justify-center py-12 space-y-4`,children:(0,Z.jsxs)(`div`,{className:`text-center`,children:[(0,Z.jsx)(`h2`,{className:`text-2xl font-semibold mb-2`,children:`Coming Soon`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground max-w-md`,children:`Global context management is currently under development. Check back later for updates.`})]})})]}):(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:`Access denied. Admin privileges required.`})})}function yD(){let e=Yu()?.userType===`admin`;return(0,X.useEffect)(()=>{},[e]),e?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(By,{title:`All Agents`,description:`Manage all AI agents across all users`}),(0,Z.jsx)(`div`,{className:`flex flex-col items-center justify-center py-12 space-y-4`,children:(0,Z.jsxs)(`div`,{className:`text-center`,children:[(0,Z.jsx)(`h2`,{className:`text-2xl font-semibold mb-2`,children:`Coming Soon`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground max-w-md`,children:`Global agent management is currently under development. Check back later for updates.`})]})})]}):(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:`Access denied. Admin privileges required.`})})}var bD={tail:200,level:``,module:``};function xD(e){return e.slice(-1e3)}function SD(e){switch(e.levelLabel){case`fatal`:return`text-destructive`;case`error`:return`text-destructive`;case`warn`:return`text-warning`;case`info`:return`text-info`;case`debug`:return`text-muted-foreground`;case`trace`:return`text-muted-foreground`;default:return`text-success`}}function CD(){let e=mC(),t=Yu()?.userType===`admin`,{showToast:n}=oo(),r=(0,X.useRef)(null),[i,a]=(0,X.useState)(bD),[o,s]=(0,X.useState)(bD),[c,l]=(0,X.useState)([]),[u,d]=(0,X.useState)(t),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(t?null:`Access denied. Admin privileges required.`),v=(0,X.useCallback)(async e=>{try{d(!0);let t=await hD.logs.getLogs(e);l(xD(t)),_(null)}catch(e){let t=e instanceof Error?e.message:`Failed to load server logs`;_(t),n({title:`Error`,description:t,variant:`destructive`})}finally{d(!1)}},[n]);(0,X.useEffect)(()=>{t&&v(i)},[i,t,v]),(0,X.useEffect)(()=>{if(!t||m)return;let e=new AbortController;return p(!0),hD.logs.streamLogs(i,{signal:e.signal,onEntry:e=>{l(t=>xD([...t,e]))},onError:e=>{_(e.message)}}).catch(e=>{let t=e instanceof Error?e.message:`Log stream stopped`;_(t),n({title:`Stream error`,description:t,variant:`destructive`})}).finally(()=>{p(!1)}),()=>{e.abort()}},[i,t,m,n]),(0,X.useEffect)(()=>{!r.current||m||(r.current.scrollTop=r.current.scrollHeight)},[c,m]);let y=()=>{a({tail:Math.min(Math.max(Number(o.tail)||bD.tail,1),500),level:o.level||``,module:o.module.trim()})},b=(0,X.useMemo)(()=>[{value:``,label:`All levels`},{value:`trace`,label:`Trace`},{value:`debug`,label:`Debug`},{value:`info`,label:`Info`},{value:`warn`,label:`Warn`},{value:`error`,label:`Error`},{value:`fatal`,label:`Fatal`}],[]);return t?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(By,{onBack:e,title:`Server Logs`,description:`Live tail for the unified canvas-server logger`,actions:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm`,children:[(0,Z.jsx)(At,{className:`w-4 h-4 ${f?`text-success`:`text-muted-foreground`}`}),(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:m?`Paused`:f?`Streaming`:`Disconnected`})]})}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-[140px_180px_1fr_auto]`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(bu,{htmlFor:`tail`,children:`Tail`}),(0,Z.jsx)(q,{id:`tail`,type:`number`,min:1,max:500,value:o.tail,onChange:e=>s(t=>({...t,tail:Number(e.target.value)}))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(bu,{htmlFor:`level`,children:`Level`}),(0,Z.jsx)(`select`,{id:`level`,className:`w-full px-3 py-2 border rounded-md bg-background`,value:o.level,onChange:e=>s(t=>({...t,level:e.target.value})),children:b.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value||`all`))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(bu,{htmlFor:`module`,children:`Module filter`}),(0,Z.jsx)(q,{id:`module`,placeholder:`auth, http, workspace...`,value:o.module,onChange:e=>s(t=>({...t,module:e.target.value}))})]}),(0,Z.jsx)(`div`,{className:`flex items-end`,children:(0,Z.jsx)(J,{onClick:y,className:`w-full`,children:`Apply`})})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsxs)(J,{variant:`outline`,onClick:()=>h(e=>!e),children:[m?(0,Z.jsx)(W,{className:`w-4 h-4 mr-2`}):(0,Z.jsx)(T,{className:`w-4 h-4 mr-2`}),m?`Resume`:`Pause`]}),(0,Z.jsxs)(J,{variant:`outline`,onClick:()=>v(i),children:[(0,Z.jsx)(k,{className:`w-4 h-4 mr-2`}),`Refresh`]}),(0,Z.jsxs)(J,{variant:`outline`,onClick:()=>l([]),children:[(0,Z.jsx)(lt,{className:`w-4 h-4 mr-2`}),`Clear buffer`]}),(0,Z.jsxs)(`span`,{className:`text-sm text-muted-foreground ml-auto`,children:[`Showing `,c.length,` lines`]})]}),g&&(0,Z.jsx)(`div`,{className:`rounded-md border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive`,children:g}),(0,Z.jsx)(`div`,{className:`border rounded-lg overflow-hidden`,children:(0,Z.jsx)(`div`,{ref:r,"data-scheme":`dark`,className:`bg-background text-success font-mono text-xs h-viewport-pane overflow-auto p-4 rounded-md`,children:u?(0,Z.jsx)(`div`,{className:`text-muted-foreground`,children:`Loading logs...`}):c.length===0?(0,Z.jsx)(`div`,{className:`text-muted-foreground`,children:`No logs available`}):(0,Z.jsx)(`div`,{className:`whitespace-pre-wrap break-words`,children:c.map((e,t)=>(0,Z.jsx)(`div`,{className:SD(e),children:e.line},`${e.time||`log`}-${t}`))})})})]}):(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:`Access denied. Admin privileges required.`})})}var wD={async listRoles(e){let t=new URLSearchParams;e?.type&&t.append(`type`,e.type),e?.userId&&t.append(`userId`,e.userId),e?.workspaceId&&t.append(`workspaceId`,e.workspaceId),e?.status&&t.append(`status`,e.status);let n=t.toString(),r=n?`${Kr.roles}?${n}`:Kr.roles;return(await Y.get(r)).roles||[]},async getRole(e){return(await Y.get(`${Kr.roles}/${e}`)).role},async createRole(e){return(await Y.post(Kr.roles,e)).role},async deleteRole(e,t=!1){let n=t?`?force=true`:``;await Y.delete(`${Kr.roles}/${e}${n}`)},async startRole(e){return(await Y.post(`${Kr.roles}/${e}/start`,{})).role},async stopRole(e){await Y.post(`${Kr.roles}/${e}/stop`,{})},async restartRole(e){return(await Y.post(`${Kr.roles}/${e}/restart`,{})).role},async getRoleLogs(e,t=100){return(await Y.get(`${Kr.roles}/${e}/logs?tail=${t}`)).logs||[]},async getRoleStats(e){return(await Y.get(`${Kr.roles}/${e}/stats`)).stats},async getRoleHealth(e){return(await Y.get(`${Kr.roles}/${e}/health`)).health},async listTemplates(){return(await Y.get(`${Kr.roleTemplates}`)).templates||[]},async getTemplate(e){return(await Y.get(`${Kr.roleTemplates}/${e}`)).template}};function TD({status:e}){let t={running:{icon:tn,color:`text-success`,bg:`bg-success-subtle`,label:`Running`},stopped:{icon:j,color:`text-muted-foreground`,bg:`bg-muted`,label:`Stopped`},starting:{icon:Qn,color:`text-info`,bg:`bg-info-subtle`,label:`Starting`},stopping:{icon:Qn,color:`text-warning`,bg:`bg-warning-subtle`,label:`Stopping`},error:{icon:be,color:`text-destructive`,bg:`bg-destructive-subtle`,label:`Error`},created:{icon:At,color:`text-muted-foreground`,bg:`bg-muted`,label:`Created`},configured:{icon:At,color:`text-info`,bg:`bg-info-subtle`,label:`Configured`},removed:{icon:j,color:`text-destructive`,bg:`bg-destructive-subtle`,label:`Removed`}},n=t[e]||t.created,r=n.icon;return(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium ${n.bg} ${n.color}`,children:[(0,Z.jsx)(r,{className:`w-3 h-3`}),n.label]})}function ED({type:e}){return(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium ${e===`global`?`bg-accent text-primary`:`bg-info-subtle text-info`}`,children:[(0,Z.jsx)(Gt,{className:`w-3 h-3`}),e===`global`?`Global`:`Workspace`]})}function DD(){let e=mC(),t=Yu()?.userType===`admin`,[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(t),[c,l]=(0,X.useState)(t?null:`Access denied. Admin privileges required.`),[u,d]=(0,X.useState)(!1);gf(()=>d(!1),u);let[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(!1);gf(()=>h(!1),m);let[g,_]=(0,X.useState)([]),[v,y]=(0,X.useState)({type:``,status:``,search:``}),[b,x]=(0,X.useState)({template:``,name:``,type:`global`}),{showToast:S}=oo(),C=(0,X.useRef)(v);(0,X.useEffect)(()=>{C.current=v},[v]);let w=(0,X.useCallback)(async()=>{try{s(!0);let{type:e,status:t}=C.current,n=await wD.listRoles({type:e||void 0,status:t||void 0});r(n),l(null)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch roles`;l(t)}finally{s(!1)}},[]),T=(0,X.useCallback)(async()=>{try{let e=await wD.listTemplates();a(e)}catch(e){console.error(`Failed to fetch templates:`,e)}},[]);(0,X.useEffect)(()=>{t&&(w(),T())},[t,w,T]);let E=async()=>{if(!b.template||!b.name){S({title:`Validation Error`,description:`Template and name are required`,variant:`destructive`});return}try{await wD.createRole(b),S({title:`Success`,description:`Role "${b.name}" created successfully`}),d(!1),N(),w()}catch(e){let t=e instanceof Error?e.message:`Failed to create role`;S({title:`Error`,description:t,variant:`destructive`})}},D=async e=>{try{await wD.startRole(e.id),S({title:`Success`,description:`Role "${e.name}" started successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to start role`;S({title:`Error`,description:t,variant:`destructive`})}},O=async e=>{try{await wD.stopRole(e.id),S({title:`Success`,description:`Role "${e.name}" stopped successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to stop role`;S({title:`Error`,description:t,variant:`destructive`})}},A=async e=>{try{await wD.restartRole(e.id),S({title:`Success`,description:`Role "${e.name}" restarted successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to restart role`;S({title:`Error`,description:t,variant:`destructive`})}},j=async e=>{if(confirm(`Are you sure you want to delete role "${e.name}"?`))try{await wD.deleteRole(e.id,e.status===`running`),S({title:`Success`,description:`Role "${e.name}" deleted successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to delete role`;S({title:`Error`,description:t,variant:`destructive`})}},M=async e=>{try{let t=await wD.getRoleLogs(e.id,100);_(t),p(e),h(!0)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch logs`;S({title:`Error`,description:t,variant:`destructive`})}},N=()=>{x({template:``,name:``,type:`global`})},P=()=>{N(),d(!0)},ee=()=>{d(!1),N()},F=n.filter(e=>!v.search||e.name.toLowerCase().includes(v.search.toLowerCase())||e.template.toLowerCase().includes(v.search.toLowerCase()));return t?c&&!t?(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:c})}):(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(By,{onBack:e,title:`Role Management`,description:`Manage global and workspace roles for Canvas services`,actions:(0,Z.jsxs)(J,{onClick:P,className:`gap-2`,children:[(0,Z.jsx)(nn,{className:`w-4 h-4`}),`Create Role`]})}),(0,Z.jsxs)(`div`,{className:`flex gap-4 items-end`,children:[(0,Z.jsxs)(`div`,{className:`flex-1`,children:[(0,Z.jsx)(bu,{htmlFor:`search`,children:`Search`}),(0,Z.jsx)(q,{id:`search`,placeholder:`Search by name or template...`,value:v.search,onChange:e=>y({...v,search:e.target.value})})]}),(0,Z.jsxs)(`div`,{className:`w-48`,children:[(0,Z.jsx)(bu,{htmlFor:`type`,children:`Type`}),(0,Z.jsxs)(`select`,{id:`type`,className:`w-full px-3 py-2 border rounded-md bg-background`,value:v.type,onChange:e=>y({...v,type:e.target.value}),children:[(0,Z.jsx)(`option`,{value:``,children:`All Types`}),(0,Z.jsx)(`option`,{value:`global`,children:`Global`}),(0,Z.jsx)(`option`,{value:`workspace`,children:`Workspace`})]})]}),(0,Z.jsxs)(`div`,{className:`w-48`,children:[(0,Z.jsx)(bu,{htmlFor:`status`,children:`Status`}),(0,Z.jsxs)(`select`,{id:`status`,className:`w-full px-3 py-2 border rounded-md bg-background`,value:v.status,onChange:e=>y({...v,status:e.target.value}),children:[(0,Z.jsx)(`option`,{value:``,children:`All Statuses`}),(0,Z.jsx)(`option`,{value:`running`,children:`Running`}),(0,Z.jsx)(`option`,{value:`stopped`,children:`Stopped`}),(0,Z.jsx)(`option`,{value:`starting`,children:`Starting`}),(0,Z.jsx)(`option`,{value:`error`,children:`Error`})]})]}),(0,Z.jsxs)(J,{onClick:w,variant:`outline`,children:[(0,Z.jsx)(k,{className:`w-4 h-4 mr-2`}),`Refresh`]})]}),o?(0,Z.jsx)(`div`,{className:`text-center py-8`,children:`Loading roles...`}):F.length===0?(0,Z.jsxs)(`div`,{className:`text-center py-8 border rounded-lg`,children:[(0,Z.jsx)(Gt,{className:`w-12 h-12 mx-auto text-muted-foreground mb-4`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:v.search||v.type||v.status?`No roles match your filters`:`No roles created yet`}),!v.search&&!v.type&&!v.status&&(0,Z.jsxs)(J,{onClick:P,variant:`outline`,className:`mt-4`,children:[(0,Z.jsx)(nn,{className:`w-4 h-4 mr-2`}),`Create Your First Role`]})]}):(0,Z.jsx)(`div`,{className:`border rounded-lg`,children:(0,Z.jsxs)(`table`,{className:`w-full`,children:[(0,Z.jsx)(`thead`,{className:`bg-muted/50`,children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{className:`text-left p-4 font-medium`,children:`Name`}),(0,Z.jsx)(`th`,{className:`text-left p-4 font-medium`,children:`Template`}),(0,Z.jsx)(`th`,{className:`text-left p-4 font-medium`,children:`Type`}),(0,Z.jsx)(`th`,{className:`text-left p-4 font-medium`,children:`Status`}),(0,Z.jsx)(`th`,{className:`text-left p-4 font-medium`,children:`Container`}),(0,Z.jsx)(`th`,{className:`text-left p-4 font-medium`,children:`Created`}),(0,Z.jsx)(`th`,{className:`text-right p-4 font-medium`,children:`Actions`})]})}),(0,Z.jsx)(`tbody`,{className:`divide-y`,children:F.map(e=>(0,Z.jsxs)(`tr`,{className:`hover:bg-muted/50`,children:[(0,Z.jsx)(`td`,{className:`p-4 font-medium`,children:e.name}),(0,Z.jsx)(`td`,{className:`p-4 text-sm text-muted-foreground`,children:e.template}),(0,Z.jsx)(`td`,{className:`p-4`,children:(0,Z.jsx)(ED,{type:e.type})}),(0,Z.jsx)(`td`,{className:`p-4`,children:(0,Z.jsx)(TD,{status:e.status})}),(0,Z.jsx)(`td`,{className:`p-4 text-sm text-muted-foreground`,children:e.container?.name||`-`}),(0,Z.jsx)(`td`,{className:`p-4 text-sm text-muted-foreground`,children:new Date(e.createdAt).toLocaleDateString()}),(0,Z.jsx)(`td`,{className:`p-4`,children:(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[e.status===`stopped`||e.status===`created`?(0,Z.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>D(e),title:`Start`,children:(0,Z.jsx)(W,{className:`w-4 h-4`})}):e.status===`running`?(0,Z.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>O(e),title:`Stop`,children:(0,Z.jsx)($t,{className:`w-4 h-4`})}):null,e.status===`running`&&(0,Z.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>A(e),title:`Restart`,children:(0,Z.jsx)(k,{className:`w-4 h-4`})}),(0,Z.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>M(e),title:`View Logs`,children:(0,Z.jsx)(_n,{className:`w-4 h-4`})}),(0,Z.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>j(e),title:`Delete`,className:`text-destructive hover:text-destructive`,children:(0,Z.jsx)(tt,{className:`w-4 h-4`})})]})})]},e.id))})]})}),u&&(0,Z.jsx)(`div`,{className:`fixed inset-0 bg-scrim flex items-center justify-center z-50`,children:(0,Z.jsx)(`div`,{className:`bg-background rounded-lg shadow-elevation-3 max-w-lg w-full mx-4 max-h-viewport-modal overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`p-6 space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-bold`,children:`Create New Role`}),(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,onClick:ee,children:(0,Z.jsx)(je,{className:`w-4 h-4`})})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(bu,{htmlFor:`template`,children:`Template *`}),(0,Z.jsxs)(`select`,{id:`template`,className:`w-full px-3 py-2 border rounded-md bg-background mt-1`,value:b.template,onChange:e=>x({...b,template:e.target.value}),children:[(0,Z.jsx)(`option`,{value:``,children:`Select a template...`}),i.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.name,` - `,e.description]},e.id))]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(bu,{htmlFor:`name`,children:`Role Name *`}),(0,Z.jsx)(q,{id:`name`,placeholder:`e.g., canvas-sshd`,value:b.name,onChange:e=>x({...b,name:e.target.value})})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(bu,{htmlFor:`roleType`,children:`Type *`}),(0,Z.jsxs)(`select`,{id:`roleType`,className:`w-full px-3 py-2 border rounded-md bg-background mt-1`,value:b.type,onChange:e=>x({...b,type:e.target.value}),children:[(0,Z.jsx)(`option`,{value:`global`,children:`Global (Server-wide)`}),(0,Z.jsx)(`option`,{value:`workspace`,children:`Workspace (User-scoped)`})]})]}),b.template&&(0,Z.jsxs)(`div`,{className:`p-4 bg-muted rounded-lg`,children:[(0,Z.jsx)(`h3`,{className:`font-medium mb-2`,children:`Template Info`}),i.find(e=>e.id===b.template)&&(0,Z.jsxs)(`div`,{className:`text-sm space-y-1 text-muted-foreground`,children:[(0,Z.jsxs)(`p`,{children:[(0,Z.jsx)(`strong`,{children:`Image:`}),` `,i.find(e=>e.id===b.template)?.container.image]}),(0,Z.jsxs)(`p`,{children:[(0,Z.jsx)(`strong`,{children:`Category:`}),` `,i.find(e=>e.id===b.template)?.category]}),i.find(e=>e.id===b.template)?.documentation?.readme&&(0,Z.jsx)(`p`,{className:`mt-2`,children:i.find(e=>e.id===b.template)?.documentation?.readme})]})]})]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2 pt-4 border-t`,children:[(0,Z.jsx)(J,{variant:`outline`,onClick:ee,children:`Cancel`}),(0,Z.jsx)(J,{onClick:E,children:`Create Role`})]})]})})}),m&&f&&(0,Z.jsx)(`div`,{className:`fixed inset-0 bg-scrim flex items-center justify-center z-50`,children:(0,Z.jsxs)(`div`,{className:`bg-background rounded-lg shadow-elevation-3 max-w-4xl w-full mx-4 max-h-viewport-modal flex flex-col`,children:[(0,Z.jsxs)(`div`,{className:`p-6 border-b flex items-center justify-between`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-xl font-bold`,children:`Role Logs`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:f.name})]}),(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,onClick:()=>h(!1),children:(0,Z.jsx)(je,{className:`w-4 h-4`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-6`,children:(0,Z.jsx)(`div`,{"data-scheme":`dark`,className:`bg-background text-success p-4 rounded font-mono text-xs overflow-x-auto`,children:g.length===0?(0,Z.jsx)(`div`,{className:`text-muted-foreground`,children:`No logs available`}):(0,Z.jsx)(`pre`,{children:g.join(`
|
|
23
|
+
`)})})}),(0,Z.jsx)(`div`,{className:`p-4 border-t flex justify-end`,children:(0,Z.jsx)(J,{onClick:()=>h(!1),children:`Close`})})]})})]}):(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:`Access denied. Admin privileges required.`})})}function OD(){let e=mC(),t=Yu(),n=t?.userType===`admin`,[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(n),[s,c]=(0,X.useState)(n?null:`Access denied. Admin privileges required.`),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(null),[y,b]=(0,X.useState)({status:``,userType:``,search:``}),[x,S]=(0,X.useState)({name:``,email:``,password:``,userType:`user`,status:`active`}),{showToast:C}=oo();(0,X.useEffect)(()=>{n&&(async()=>{try{let e=await Qu(),t=!!e?.strategies?.local?.requireEmailVerification;g(t),v(e?.strategies?.local?.passwordPolicy||null)}catch{g(!1),v(null)}})()},[n]);let w=e=>{let t=e.trim().toLowerCase();return t.length<3||t.length>39?`Username must be 3-39 characters long`:/^[a-z0-9_-]+$/.test(t)?null:`Username can only contain lowercase letters, numbers, underscores, and hyphens`},T=e=>{let t=e||``,n=_||{},r=n.minLength??12,i=n.maxLength??128,a=[];return t.length<r&&a.push(`at least ${r} characters`),t.length>i&&a.push(`no more than ${i} characters`),(n.requireUppercase??!0)&&!/[A-Z]/.test(t)&&a.push(`an uppercase letter`),(n.requireLowercase??!0)&&!/[a-z]/.test(t)&&a.push(`a lowercase letter`),(n.requireNumbers??!0)&&!/[0-9]/.test(t)&&a.push(`a number`),(n.requireSpecialChars??!0)&&!/[^A-Za-z0-9]/.test(t)&&a.push(`a special character`),a.length?`Password must contain ${a.join(`, `).replace(/, ([^,]*)$/,` and $1`)}.`:null},E=()=>{let e=_||{},t=[],n=e.minLength??12;return t.push(`${n}+ chars`),(e.requireUppercase??!0)&&t.push(`uppercase`),(e.requireLowercase??!0)&&t.push(`lowercase`),(e.requireNumbers??!0)&&t.push(`number`),(e.requireSpecialChars??!0)&&t.push(`special`),t.join(`, `)},D=e=>{if(!e)return`-`;let t=new Date(e);return isNaN(t.getTime())?`-`:t.toLocaleString()},O=async e=>{try{await $u(e),C({title:`Verification email`,description:`If the account exists, a verification email was sent.`})}catch(e){let t=e instanceof Error?e.message:`Failed to send verification email`;C({title:`Error`,description:t,variant:`destructive`})}},k=(0,X.useCallback)(async()=>{try{o(!0);let{status:e,userType:t}=y,n=await hD.users.listUsers({status:e||void 0,userType:t||void 0});i(n),c(null)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch users`;c(t),C({title:`Error`,description:t,variant:`destructive`})}finally{o(!1)}},[y,C]);(0,X.useEffect)(()=>{n&&k()},[k,n]);let A=async e=>{if(e.preventDefault(),!x.name.trim()||!x.email.trim()){C({title:`Validation Error`,description:`Name and email are required`,variant:`destructive`});return}let t=w(x.name);if(t){C({title:`Validation Error`,description:t,variant:`destructive`});return}if(!x.password.trim()){C({title:`Validation Error`,description:`Password is required`,variant:`destructive`});return}let n=T(x.password);if(n){C({title:`Validation Error`,description:n,variant:`destructive`});return}u(!0);try{let e={name:x.name.trim().toLowerCase(),email:x.email.trim(),userType:x.userType,status:x.status};if(x.password.trim()&&(e.password=x.password),await hD.users.createUser(e),h&&x.status===`pending`)try{await $u(x.email.trim())}catch{}S({name:``,email:``,password:``,userType:`user`,status:h?`pending`:`active`}),m(!1),await k(),C({title:`Success`,description:`User created successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to create user`;C({title:`Error`,description:t,variant:`destructive`})}finally{u(!1)}},j=async e=>{if(e.preventDefault(),!d)return;let t=w(x.name);if(t){C({title:`Validation Error`,description:t,variant:`destructive`});return}if(x.password.trim()){let e=T(x.password);if(e){C({title:`Validation Error`,description:e,variant:`destructive`});return}}u(!0);try{let e={name:x.name.trim().toLowerCase(),email:x.email.trim(),userType:x.userType,status:x.status};x.password.trim()&&(e.password=x.password),await hD.users.updateUser(d.id,e),f(null),m(!1),await k(),C({title:`Success`,description:`User updated successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to update user`;C({title:`Error`,description:t,variant:`destructive`})}finally{u(!1)}},M=async(e,t)=>{if(confirm(`Are you sure you want to delete user "${t}"? This action cannot be undone.`))try{await hD.users.deleteUser(e),await k(),C({title:`Success`,description:`User deleted successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to delete user`;C({title:`Error`,description:t,variant:`destructive`})}},N=()=>{f(null),S({name:``,email:``,password:``,userType:`user`,status:h?`pending`:`active`}),m(!0)},P=e=>{f(e),S({name:e.name,email:e.email,password:``,userType:e.userType,status:e.status}),m(!0)},ee=()=>{m(!1),f(null)};gf(ee,p);let F=r.filter(e=>y.search===``||e.name.toLowerCase().includes(y.search.toLowerCase())||e.email.toLowerCase().includes(y.search.toLowerCase()));return n?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(By,{onBack:e,title:`User Management`,description:`Manage user accounts and permissions`}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 md:flex-row md:items-center md:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 md:flex-row md:items-center`,children:[(0,Z.jsx)(q,{placeholder:`Search users...`,value:y.search,onChange:e=>b(t=>({...t,search:e.target.value})),className:`md:w-64`}),(0,Z.jsxs)(`select`,{value:y.status,onChange:e=>b(t=>({...t,status:e.target.value})),className:`px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:``,children:`All Statuses`}),(0,Z.jsx)(`option`,{value:`active`,children:`Active`}),(0,Z.jsx)(`option`,{value:`inactive`,children:`Inactive`}),(0,Z.jsx)(`option`,{value:`pending`,children:`Pending`}),(0,Z.jsx)(`option`,{value:`deleted`,children:`Deleted`})]}),(0,Z.jsxs)(`select`,{value:y.userType,onChange:e=>b(t=>({...t,userType:e.target.value})),className:`px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:``,children:`All Types`}),(0,Z.jsx)(`option`,{value:`user`,children:`User`}),(0,Z.jsx)(`option`,{value:`admin`,children:`Admin`})]})]}),(0,Z.jsxs)(J,{onClick:N,children:[(0,Z.jsx)(nn,{className:`mr-2 h-4 w-4`}),`Create User`]})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[a&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading users...`}),s&&!r.length&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:s})}),!a&&!s&&F.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No users found`}),F.length>0&&(0,Z.jsx)(`div`,{className:`border rounded-md`,children:(0,Z.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Z.jsxs)(`table`,{className:`w-full`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{className:`bg-muted/50`,children:[(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Name`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Email`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Type`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Status`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Created`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Updated`}),(0,Z.jsx)(`th`,{className:`text-right p-3 font-medium`,children:`Actions`})]})}),(0,Z.jsx)(`tbody`,{children:F.map(e=>(0,Z.jsxs)(`tr`,{className:`border-t`,children:[(0,Z.jsx)(`td`,{className:`p-3 font-medium`,children:e.name}),(0,Z.jsx)(`td`,{className:`p-3`,children:e.email}),(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsx)(`span`,{className:`px-2 py-1 rounded-full text-xs ${e.userType===`admin`?`bg-destructive-subtle text-destructive`:`bg-info-subtle text-info`}`,children:e.userType})}),(0,Z.jsx)(`td`,{className:`p-3`,children:(0,Z.jsx)(`span`,{className:`px-2 py-1 rounded-full text-xs ${e.status===`active`?`bg-success-subtle text-success`:e.status===`inactive`?`bg-warning-subtle text-warning`:e.status===`pending`?`bg-info-subtle text-info`:`bg-destructive-subtle text-destructive`}`,children:e.status})}),(0,Z.jsx)(`td`,{className:`p-3`,children:D(e.createdAt)}),(0,Z.jsx)(`td`,{className:`p-3`,children:D(e.updatedAt)}),(0,Z.jsxs)(`td`,{className:`p-3 text-right space-x-2`,children:[(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>P(e),children:(0,Z.jsx)(Pe,{className:`h-4 w-4`})}),h&&e.status===`pending`&&(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>O(e.email),title:`Resend activation email`,children:`Resend activation`}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>M(e.id,e.name),className:`text-destructive hover:bg-destructive/10 hover:text-destructive`,disabled:e.id===t?.id,title:e.id===t?.id?`Cannot delete your own account`:`Delete user`,children:(0,Z.jsx)(tt,{className:`h-4 w-4`})})]})]},e.id))})]})})})]}),p&&(0,Z.jsx)(`div`,{className:`fixed inset-0 bg-scrim flex items-center justify-center z-50`,children:(0,Z.jsxs)(`div`,{className:`bg-card rounded-lg p-6 w-full max-w-md mx-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-4`,children:[(0,Z.jsx)(`h3`,{className:`text-lg font-semibold`,children:d?`Edit User`:`Create New User`}),(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:ee,children:(0,Z.jsx)(je,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`form`,{onSubmit:d?j:A,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(bu,{htmlFor:`name`,children:`Username`}),(0,Z.jsx)(q,{id:`name`,type:`text`,value:x.name,onChange:e=>S(t=>({...t,name:e.target.value.toLowerCase().replace(/\s+/g,``)})),placeholder:`Enter username`,disabled:l,required:!0}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(bu,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,type:`email`,value:x.email,onChange:e=>S(t=>({...t,email:e.target.value})),placeholder:`Enter email address`,disabled:l,required:!0})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(bu,{htmlFor:`password`,children:[`Password `,d&&`(leave blank to keep current)`]}),(0,Z.jsx)(q,{id:`password`,type:`password`,value:x.password,onChange:e=>S(t=>({...t,password:e.target.value})),placeholder:d?`Leave blank to keep current`:`Enter password`,disabled:l,required:!d}),!d&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:[`Must satisfy: `,E()]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(bu,{htmlFor:`userType`,children:`User Type`}),(0,Z.jsxs)(`select`,{id:`userType`,value:x.userType,onChange:e=>S(t=>({...t,userType:e.target.value})),disabled:l,className:`w-full px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:`user`,children:`User`}),(0,Z.jsx)(`option`,{value:`admin`,children:`Admin`})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(bu,{htmlFor:`status`,children:`Status`}),(0,Z.jsxs)(`select`,{id:`status`,value:x.status,onChange:e=>S(t=>({...t,status:e.target.value})),disabled:l,className:`w-full px-3 py-2 border border-border rounded-md`,children:[(0,Z.jsx)(`option`,{value:`active`,children:`Active`}),(0,Z.jsx)(`option`,{value:`inactive`,children:`Inactive`}),(0,Z.jsx)(`option`,{value:`pending`,children:`Pending`}),(0,Z.jsx)(`option`,{value:`deleted`,children:`Deleted`})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2 pt-4`,children:[(0,Z.jsx)(J,{type:`submit`,disabled:l,className:`flex-1`,children:l?`Processing...`:d?`Update User`:`Create User`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,onClick:ee,disabled:l,children:`Cancel`})]})]})]})})]}):(0,Z.jsx)(`div`,{className:`text-center space-y-4`,children:(0,Z.jsx)(`div`,{className:`text-destructive`,children:`Access denied. Admin privileges required.`})})}function kD(){let e=mC(),{showToast:t}=oo(),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(!0),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(``),f=Yu()?.userType===`admin`,p=(0,X.useCallback)(()=>RE().then(e=>{r(e),d((e.allowHosts||[]).join(`, `)),l(null)}).catch(e=>l(e instanceof Error?e.message:`Failed to load server defaults`)).finally(()=>a(!1)),[]);(0,X.useEffect)(()=>{p()},[p]);let m=()=>{a(!0),p()};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[(0,Z.jsx)(By,{onBack:e,compact:!0,className:`mb-6`,title:`Server search & AI defaults`,description:`Entire server · Set the embedding defaults accounts inherit. Account and workspace overrides take priority. Running workspaces adopt new defaults when restarted.`,actions:(0,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:m,disabled:i,children:[(0,Z.jsx)(M,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})}),!f&&(0,Z.jsxs)(`div`,{className:`mb-4 flex items-start gap-2 rounded-md border p-3 text-xs`,children:[(0,Z.jsx)(Vt,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:`Read-only. Changing server defaults requires an admin account. This is what your workspaces inherit.`})]}),i?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(M,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):c||!n?(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Server defaults unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:c||`No config returned.`})]}),(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:m,children:`Retry`})]}):(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Config file: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:n.configPath})]}),(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Endpoint allowlist`}),(0,Z.jsx)(`p`,{className:`mb-2 mt-1 text-[11px] text-muted-foreground`,children:`Provider URLs are fetched by the server, so they are an SSRF surface. Link-local and cloud-metadata targets are always refused; list additional hosts here to permit them. Comma-separated, empty = only the always-blocked ranges apply.`}),(0,Z.jsx)(q,{value:u,disabled:!f,onChange:e=>d(e.target.value),placeholder:`gpu.internal, embeddings.example.com`,className:`h-8 text-sm`})]}),(0,Z.jsx)(nD,{value:n.serverDefaults||{},effective:n.serverDefaults||{},inherited:{},saving:o,disabled:!f,saveLabel:`Save server defaults`,onSave:async e=>{s(!0);try{let n=u.split(`,`).map(e=>e.trim()).filter(Boolean),r=await zE({...e,...n.length?{allowHosts:n}:{}});t({title:`Server defaults saved`,description:`Written to ${r.configPath}. Every user inherits these, so running workspaces keep their current tables until restarted.`}),await p()}catch(e){t({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save`,variant:`destructive`})}finally{s(!1)}}},JSON.stringify(n.serverDefaults))]})]})}function AD({agent:e,onStart:t,onStop:n,onEnter:r}){let[i,a]=(0,X.useState)(!1),o=async()=>{a(!0);try{await t(e.name)}finally{a(!1)}},s=async()=>{a(!0);try{await n(e.name)}finally{a(!1)}},c=()=>{switch(e.status){case`active`:return(0,Z.jsx)(ht,{className:`h-4 w-4 text-success`});case`inactive`:return(0,Z.jsx)(ht,{className:`h-4 w-4 text-warning`});case`error`:return(0,Z.jsx)(ht,{className:`h-4 w-4 text-destructive`});default:return(0,Z.jsx)(ht,{className:`h-4 w-4 text-muted-foreground`})}},l=()=>{switch(e.llmProvider){case`anthropic`:return(0,Z.jsx)(H,{className:`h-4 w-4 text-warning`});case`openai`:return(0,Z.jsx)(H,{className:`h-4 w-4 text-success`});case`ollama`:return(0,Z.jsx)(ge,{className:`h-4 w-4 text-info`});default:return(0,Z.jsx)(H,{className:`h-4 w-4 text-muted-foreground`})}},u=()=>{switch(e.status){case`active`:return`text-success bg-success-subtle border-success`;case`inactive`:return`text-warning bg-warning-subtle border-warning`;case`error`:return`text-destructive bg-destructive-subtle border-destructive`;case`available`:return`text-info bg-info-subtle border-info`;default:return`text-foreground bg-muted border-border`}},d=e.status===`available`||e.status===`inactive`,f=e.status===`active`;return(0,Z.jsxs)(`div`,{className:`border rounded-lg p-4 space-y-4 hover:shadow-elevation-2 transition-shadow bg-card`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 mb-1`,children:[l(),(0,Z.jsx)(`h3`,{className:`text-lg font-semibold truncate`,children:e.label||e.name}),e.color&&(0,Z.jsx)(`div`,{className:`w-4 h-4 rounded border flex-shrink-0`,style:{backgroundColor:e.color},title:`Color: ${e.color}`})]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground font-mono`,children:e.name}),e.description&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1 line-clamp-2`,children:e.description})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 flex-shrink-0`,children:[c(),(0,Z.jsx)(`span`,{className:`px-2 py-1 rounded-full text-xs font-medium border ${u()}`,children:e.status})]})]}),(0,Z.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Provider:`}),(0,Z.jsx)(`div`,{className:`font-medium capitalize`,children:e.llmProvider})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Model:`}),(0,Z.jsx)(`div`,{className:`font-mono text-xs`,children:e.model})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Created:`}),(0,Z.jsx)(`div`,{children:new Date(e.createdAt).toLocaleDateString()})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Last Access:`}),(0,Z.jsx)(`div`,{children:e.lastAccessed?new Date(e.lastAccessed).toLocaleDateString():`Never`})]})]}),e.config.mcp?.servers&&e.config.mcp.servers.length>0&&(0,Z.jsxs)(`div`,{className:`text-sm`,children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`MCP Servers:`}),(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-1 mt-1`,children:e.config.mcp.servers.map((e,t)=>(0,Z.jsx)(`span`,{className:`px-2 py-1 bg-secondary text-secondary-foreground rounded text-xs`,children:e.name},t))})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2 pt-2 border-t`,children:[d&&(0,Z.jsxs)(J,{onClick:o,disabled:i,size:`sm`,variant:`outline`,className:`flex-1`,children:[(0,Z.jsx)(W,{className:`mr-2 h-4 w-4`}),`Start`]}),f&&(0,Z.jsxs)(J,{onClick:s,disabled:i,size:`sm`,variant:`outline`,className:`flex-1`,children:[(0,Z.jsx)($t,{className:`mr-2 h-4 w-4`}),`Stop`]}),(0,Z.jsxs)(J,{onClick:()=>r(e.name),size:`sm`,className:`flex-1`,children:[(0,Z.jsx)(Pt,{className:`mr-2 h-4 w-4`}),`Chat`]})]})]})}function jD(){let e={anthropic:`https://api.anthropic.com`,openai:`https://api.openai.com/v1`,ollama:`http://localhost:11434/v1`},t={anthropic:`claude-3-5-sonnet-20241022`,openai:`gpt-4o`,ollama:`qwen2.5-coder:latest`},[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(!0),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(Nf()),[m,h]=(0,X.useState)(``),[g,_]=(0,X.useState)(`anthropic`),[v,y]=(0,X.useState)(t.anthropic),[b,x]=(0,X.useState)({apiKey:``,baseUrl:e.anthropic,maxTokens:4096,temperature:.7,topP:1,frequencyPenalty:0,presencePenalty:0,numCtx:4096}),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(!1),[E,D]=Jy(),{showToast:O}=oo(),k=Gc(),A=kb();Gy(A,`agent`,{"agent:status:changed":e=>{r(t=>t.map(t=>t.id===e.agentId?{...t,status:e.status,isActive:e.isActive}:t))},"agent:created":e=>{r(t=>[...t,e.agent])},"agent:deleted":e=>{r(t=>t.filter(t=>t.id!==e.agentId))}});let j=n=>{_(n),y(t[n]),x({apiKey:``,baseUrl:e[n],maxTokens:4096,temperature:.7,topP:1,frequencyPenalty:0,presencePenalty:0,numCtx:4096})};(0,X.useEffect)(()=>((async()=>{try{a(!0);let e=await KC();r(e),s(null)}catch(e){console.error(`Agent fetch error:`,e);let t=`Failed to fetch agents`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to fetch agents`}s(t),O({title:`Error`,description:t,variant:`destructive`})}finally{a(!1)}})(),()=>{}),[A,O]);let M=async t=>{if(t.preventDefault(),c.trim()){T(!0);try{let t=await rw({name:c,label:m||c,description:u||void 0,color:f,llmProvider:g,model:v,config:{type:g,model:v,prompts:S?{system:S}:void 0,connectors:{[g]:{...b,...b.apiKey?{apiKey:b.apiKey}:{},...b.baseUrl?{baseUrl:b.baseUrl}:{},maxTokens:b.maxTokens,temperature:b.temperature,topP:b.topP,frequencyPenalty:b.frequencyPenalty,presencePenalty:b.presencePenalty,...g===`ollama`?{numCtx:b.numCtx}:{}}}},mcp:{enabled:!0,servers:[{name:`weather`,command:`node`,args:[`src/managers/agent/mcp-servers/weather.js`]}]}});r(e=>[...e,t]),l(``),d(``),p(Nf()),h(``),C(``),x({apiKey:``,baseUrl:e[g],maxTokens:4096,temperature:.7,topP:1,frequencyPenalty:0,presencePenalty:0,numCtx:4096}),O({title:`Success`,description:`Agent '${t.label||t.name}' created.`}),D(!1)}catch(e){console.error(`Agent creation error:`,e);let t=`Failed to create agent`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to create agent`}O({title:`Error`,description:t,variant:`destructive`})}finally{T(!1)}}},N=async e=>{try{let t=await ow(e);r(e=>e.map(e=>e.name===t.name?t:e)),O({title:`Success`,description:`Agent '${t.label||t.name}' started.`})}catch(e){console.error(`Agent start error:`,e);let t=`Failed to start agent`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to start agent`}O({title:`Error`,description:t,variant:`destructive`})}},P=async e=>{try{await sw(e),r(t=>t.map(t=>t.name===e?{...t,status:`inactive`,isActive:!1}:t)),O({title:`Success`,description:`Agent '${e}' stopped.`})}catch(e){console.error(`Agent stop error:`,e);let t=`Failed to stop agent`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to stop agent`}O({title:`Error`,description:t,variant:`destructive`})}},ee=e=>{k(`/agents/${e}`)};return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(By,{title:`AI Agents`,description:`Create and manage your AI agents with multiple LLM providers`,actions:!E&&(0,Z.jsxs)(J,{onClick:()=>D(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create agent`,title:`Create agent`,children:[(0,Z.jsx)(nn,{className:`h-4 w-4 sm:mr-2`}),(0,Z.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Agent`})]})}),E&&(0,Z.jsx)(Ky,{title:`Create New Agent`,onClose:()=>D(!1),children:(0,Z.jsxs)(`form`,{onSubmit:M,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsx)(q,{value:c,onChange:e=>l(e.target.value),placeholder:`Agent Name (e.g., 'my-assistant')`,disabled:w}),(0,Z.jsx)(q,{value:m,onChange:e=>h(e.target.value),placeholder:`Agent Label (display name, optional)`,disabled:w})]}),(0,Z.jsx)(q,{value:u,onChange:e=>d(e.target.value),placeholder:`Description (optional)`,disabled:w}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`agent-provider`,className:`text-sm font-medium`,children:`LLM Provider`}),(0,Z.jsxs)(`select`,{id:`agent-provider`,value:g,onChange:e=>j(e.target.value),className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring`,disabled:w,children:[(0,Z.jsx)(`option`,{value:`anthropic`,children:`Anthropic Claude`}),(0,Z.jsx)(`option`,{value:`openai`,children:`OpenAI GPT`}),(0,Z.jsx)(`option`,{value:`ollama`,children:`Ollama (Local)`})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`agent-model`,className:`text-sm font-medium`,children:`Model`}),(0,Z.jsx)(q,{id:`agent-model`,value:v,onChange:e=>y(e.target.value),placeholder:`Model name (e.g., 'gpt-4o')`,disabled:w})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`system-prompt`,className:`text-sm font-medium`,children:`System Prompt (Optional)`}),(0,Z.jsx)(`textarea`,{id:`system-prompt`,value:S,onChange:e=>C(e.target.value),placeholder:`Enter system prompt to define agent behavior...`,className:`w-full mt-1 px-3 py-2 border border-input bg-background rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring min-h-[80px] resize-y`,disabled:w})]}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`api-key`,className:`text-sm font-medium`,children:`API Key (Optional)`}),(0,Z.jsx)(q,{id:`api-key`,type:`password`,value:b.apiKey,onChange:e=>x(t=>({...t,apiKey:e.target.value})),placeholder:`Enter your API key`,disabled:w})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`baseUrl`,className:`text-sm font-medium`,children:`Base URL (Optional)`}),(0,Z.jsx)(q,{id:`baseUrl`,value:b.baseUrl,onChange:e=>x(t=>({...t,baseUrl:e.target.value})),placeholder:e[g],disabled:w})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h3`,{className:`text-lg font-medium`,children:`LLM Parameters`}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2 lg:grid-cols-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`max-tokens`,className:`text-sm font-medium`,children:`Max Tokens`}),(0,Z.jsx)(q,{id:`max-tokens`,type:`number`,min:`1`,max:`32768`,value:b.maxTokens,onChange:e=>x(t=>({...t,maxTokens:parseInt(e.target.value)||4096})),disabled:w})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`temperature`,className:`text-sm font-medium`,children:`Temperature`}),(0,Z.jsx)(q,{id:`temperature`,type:`number`,min:`0`,max:`2`,step:`0.1`,value:b.temperature,onChange:e=>x(t=>({...t,temperature:parseFloat(e.target.value)||.7})),disabled:w})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`top-p`,className:`text-sm font-medium`,children:`Top P`}),(0,Z.jsx)(q,{id:`top-p`,type:`number`,min:`0`,max:`1`,step:`0.1`,value:b.topP,onChange:e=>x(t=>({...t,topP:parseFloat(e.target.value)||1})),disabled:w})]}),g===`ollama`&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`num-ctx`,className:`text-sm font-medium`,children:`Context Length`}),(0,Z.jsx)(q,{id:`num-ctx`,type:`number`,min:`1024`,max:`32768`,value:b.numCtx,onChange:e=>x(t=>({...t,numCtx:parseInt(e.target.value)||4096})),disabled:w})]})]}),g!==`ollama`&&(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`frequency-penalty`,className:`text-sm font-medium`,children:`Frequency Penalty`}),(0,Z.jsx)(q,{id:`frequency-penalty`,type:`number`,min:`-2`,max:`2`,step:`0.1`,value:b.frequencyPenalty,onChange:e=>x(t=>({...t,frequencyPenalty:parseFloat(e.target.value)||0})),disabled:w})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`presence-penalty`,className:`text-sm font-medium`,children:`Presence Penalty`}),(0,Z.jsx)(q,{id:`presence-penalty`,type:`number`,min:`-2`,max:`2`,step:`0.1`,value:b.presencePenalty,onChange:e=>x(t=>({...t,presencePenalty:parseFloat(e.target.value)||0})),disabled:w})]})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{htmlFor:`agent-color`,className:`text-sm font-medium`,children:`Agent Color`}),(0,Z.jsx)(q,{id:`agent-color`,type:`color`,value:f,onChange:e=>p(e.target.value),className:`h-10 w-16 p-1`,disabled:w}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>p(Nf()),disabled:w,children:`Randomize`})]}),(0,Z.jsxs)(J,{type:`submit`,disabled:w||!c.trim(),children:[(0,Z.jsx)(nn,{className:`mr-2 h-4 w-4`}),`Create Agent`]})]})}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Agents`}),i&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading agents...`}),o&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:o})}),!i&&!o&&n.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No agents found`}),n.length>0&&(0,Z.jsx)(`div`,{className:`grid gap-4`,children:n.map(e=>(0,Z.jsx)(AD,{agent:e,onStart:N,onStop:P,onEnter:ee},e.id))})]})]})}function MD(e){let t=e?.usage;if(!t)return null;let n=t.totalTokens,r=t.input,i=t.output;return typeof n==`number`&&typeof r==`number`&&typeof i==`number`?`${n} tok (${r} in / ${i} out)`:typeof n==`number`?`${n} tok`:null}function ND(e){let t=e?.usage?.cost?.total;return typeof t==`number`?`$${t.toFixed(t<.01?6:4)}`:null}function PD({reasoning:e,metadata:t,isStreaming:n=!1,compact:r=!1}){let i=t?.model,a=[t?.provider,i,MD(t),ND(t)].filter(Boolean);return!e&&a.length===0?null:(0,Z.jsxs)(Z.Fragment,{children:[e&&(0,Z.jsxs)(`details`,{open:n,className:`mb-2 rounded border border-border bg-background ${r?`px-2 py-1.5`:`px-3 py-2`}`,children:[(0,Z.jsx)(`summary`,{className:`cursor-pointer font-medium text-foreground ${r?`text-[11px]`:`text-xs`}`,children:`Reasoning`}),(0,Z.jsx)(Bm,{content:e,className:`mt-1 text-foreground ${r?`text-[11px]`:`text-xs`}`})]}),a.length>0&&(0,Z.jsx)(`div`,{className:`mt-2 text-muted-foreground ${r?`text-[11px]`:`text-xs`}`,children:a.join(` • `)})]})}function FD({message:e,isStreaming:t=!1,connectionStatus:n=`disconnected`}){let[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(!0);(0,X.useEffect)(()=>{if(!t||e.isComplete)return;let n=e.content,r=0,a=setInterval(()=>{r<n.length?(i(n.substring(0,r+1)),r++):clearInterval(a)},20);return()=>clearInterval(a)},[e.content,t,e.isComplete]);let s=t&&!e.isComplete?r:e.content;return(0,X.useEffect)(()=>{if(!t||e.isComplete)return;let n=setInterval(()=>{o(e=>!e)},500);return()=>{clearInterval(n),o(!0)}},[t,e.isComplete]),(0,Z.jsx)(`div`,{className:`flex ${e.role===`user`?`justify-end`:`justify-start`}`,children:(0,Z.jsxs)(`div`,{className:`max-w-[70%] p-3 rounded-lg ${e.role===`user`?`bg-primary text-primary-foreground`:`bg-muted`} ${t&&!e.isComplete?`border-2 border-info`:``}`,children:[(0,Z.jsx)(PD,{reasoning:e.role===`assistant`?e.metadata?.reasoning?.trim():void 0,metadata:e.role===`assistant`?e.metadata:void 0,isStreaming:t&&!e.isComplete}),(0,Z.jsxs)(`div`,{className:`text-sm`,children:[e.role===`assistant`?(0,Z.jsx)(Bm,{content:s}):(0,Z.jsx)(`span`,{className:`whitespace-pre-wrap break-words`,children:s}),t&&!e.isComplete&&(0,Z.jsx)(`span`,{className:`inline-block w-2 ${a?`bg-current`:`bg-transparent`}`,children:`|`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between text-xs mt-2 opacity-70`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{children:new Date(e.timestamp).toLocaleTimeString()}),t&&!e.isComplete&&(0,Z.jsx)(`span`,{className:`text-info`,children:`• streaming...`})]}),e.role===`assistant`&&(()=>{switch(n){case`websocket`:return(0,Z.jsx)(`span`,{title:`WebSocket`,children:(0,Z.jsx)(S,{className:`h-3 w-3 text-success`})});case`sse`:return(0,Z.jsx)(`span`,{title:`Server-Sent Events`,children:(0,Z.jsx)(Te,{className:`h-3 w-3 text-info`})});case`rest`:return(0,Z.jsx)(`span`,{title:`REST API`,children:(0,Z.jsx)(ht,{className:`h-3 w-3 text-warning`})});default:return(0,Z.jsx)(`span`,{title:`Disconnected`,children:(0,Z.jsx)(qe,{className:`h-3 w-3 text-destructive`})})}})()]})]})})}var ID=(0,X.createContext)(null);function LD(e){let t=(0,X.useContext)(ID);if(!t)throw Error(`useAgentSessions must be used within an AgentSessionProvider`);let{getState:n,refresh:r,create:i,select:a,rename:o,remove:s}=t,c=n(e),l=(0,X.useCallback)(()=>r(e),[r,e]),u=(0,X.useCallback)(t=>i(e,t),[i,e]),d=(0,X.useCallback)(t=>a(e,t),[a,e]),f=(0,X.useCallback)((t,n)=>o(e,t,n),[o,e]),p=(0,X.useCallback)(t=>s(e,t),[s,e]);return(0,X.useMemo)(()=>({...c,refresh:l,create:u,select:d,rename:f,remove:p}),[c,l,u,d,f,p])}function RD(e={}){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(!1),s=(0,X.useRef)(e),c=(0,X.useRef)(null),l=(0,X.useRef)(!1);(0,X.useEffect)(()=>{s.current=e},[e]);let u=(0,X.useCallback)(()=>{if(!s.current.agentId||c.current||l.current)return;let e=localStorage.getItem(`authToken`);if(!e){console.warn(`No auth token available for WebSocket connection`);return}console.log(`[WebSocket] Using token type: ${e.startsWith(`canvas-`)?`API`:`JWT`}, length: ${e.length}`),l.current=!0,o(!0);let t=qa(Kr.ws,{auth:{token:e},transports:[`websocket`],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,timeout:1e4,forceNew:!0});t.on(`connect`,()=>{console.log(`Agent WebSocket connected successfully`),i(!0),l.current=!1,o(!1)}),t.on(`connect_error`,e=>{console.error(`Agent WebSocket connection error:`,e),i(!1),l.current=!1,o(!1),(e.message?.includes(`Auth error`)||e.message?.includes(`token`))&&console.warn(`WebSocket auth failed, will fallback to SSE for streaming`)}),t.on(`disconnect`,e=>{console.log(`Agent WebSocket disconnected:`,e),i(!1),l.current=!1,o(!1)}),t.on(`agent:chat:chunk`,e=>{console.log(`Received chat chunk:`,e),s.current.onMessage&&s.current.onMessage(e)}),t.on(`agent:chat:complete`,e=>{console.log(`Chat stream complete:`,e),s.current.onComplete&&s.current.onComplete(e.agentId,e.messageId,e.messages)}),t.on(`agent:chat:error`,e=>{console.error(`Chat stream error:`,e),s.current.onError&&s.current.onError(e)}),t.on(`agent:chat:start`,e=>{console.log(`Chat stream started:`,e)}),c.current=t,n(t)},[]),d=(0,X.useCallback)(()=>{let e=c.current;e&&(e.removeAllListeners(),e.close()),c.current=null,l.current=!1,n(null),i(!1),o(!1)},[]),f=(0,X.useCallback)(e=>{t&&r&&(console.log(`Subscribing to agent channel: ${e}`),t.emit(`agent:subscribe`,{agentId:e}))},[t,r]),p=(0,X.useCallback)(e=>{t&&r&&(console.log(`Unsubscribing from agent channel: ${e}`),t.emit(`agent:unsubscribe`,{agentId:e}))},[t,r]),m=(0,X.useCallback)((e,n)=>{if(!t||!r)throw Error(`WebSocket not connected`);let i=`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return console.log(`Starting streaming chat for agent ${e}, message ${i}`),t.emit(`agent:chat:stream`,{agentId:e,messageId:i,...n}),i},[t,r]);return(0,X.useEffect)(()=>{if(e.agentId)return u(),()=>{d()}},[e.agentId,u,d]),(0,X.useEffect)(()=>{if(r&&e.agentId)return f(e.agentId),()=>{e.agentId&&p(e.agentId)}},[r,e.agentId,f,p]),{socket:t,isConnected:r,isConnecting:a,connect:u,disconnect:d,joinAgentChannel:f,leaveAgentChannel:p,startStreamingChat:m}}function zD(e){if(!e)return``;if(typeof e.errorMessage==`string`&&e.errorMessage.trim())return e.errorMessage.trim();let t=e.content;return typeof t==`string`?t:Array.isArray(t)&&t.filter(e=>e?.type===`text`&&typeof e.text==`string`).map(e=>e.text??``).join(`
|
|
24
|
+
`)||``}function BD(e,t){return`${e||``}${t||``}`.trim()||void 0}function VD(e,t){if(!e&&!t)return;let{reasoningDelta:n,...r}=e||{};return{...r,...t?{reasoning:t}:{}}}function HD(e){let{agentId:t,initialMessages:n=[],historyKey:r,loadHistory:i=!0,onError:a,enableWebSocket:o=!0,enableSSE:s=!0,enableFallback:c=!0,llmProvider:l}=e,[u,d]=(0,X.useState)(dw(n)),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(`disconnected`),[v,y]=(0,X.useState)(null),b=(0,X.useRef)(n);(0,X.useEffect)(()=>{b.current=n});let x=`${t}${String(i)}${r??``}`,[S,C]=(0,X.useState)(x);S!==x&&(C(x),(!t||!i)&&d(dw(n))),(0,X.useEffect)(()=>{let e=!1;if(!(!t||!i))return JC(t).then(t=>{e||d(dw(t.messages))}).catch(()=>{e||d(dw(b.current))}),()=>{e=!0}},[t,i,r]);let w=(0,X.useRef)(null),T=(0,X.useRef)(null),{isConnected:E,startStreamingChat:D}=RD({agentId:o?t:void 0,onMessage:j,onComplete:M,onError:N}),O=o&&E,[k,A]=(0,X.useState)(!1);k!==O&&(A(O),_(O?`websocket`:e=>e===`websocket`?`disconnected`:e));function j(e){e.messageId===T.current&&(console.log(`Processing WebSocket chunk:`,{type:e.type,content:e.content,delta:e.delta}),e.type===`content`||e.type===`chunk`?h(t=>t?{...t,content:t.content+(e.delta||e.content||``),isComplete:!1,metadata:t.metadata}:{role:`assistant`,content:e.delta||e.content||``,timestamp:new Date().toISOString(),isComplete:!1}):e.type===`thinking`?h(t=>{let n=BD(t?.metadata?.reasoning,e.delta);return t?{...t,metadata:{...t.metadata||{},...n?{reasoning:n}:{}}}:{role:`assistant`,content:``,timestamp:new Date().toISOString(),isComplete:!1,metadata:n?{reasoning:n}:void 0}}):(e.type===`complete`||e.type===`done`)&&h(e=>{if(e){let t={...e,isComplete:!0};return d(e=>[...e,t]),p(!1),T.current=null,null}return null}))}function M(e,t,n){if(t===T.current){let e=Array.isArray(n)?[...n].reverse().find(e=>e?.role===`assistant`):null,t=zD(e),r=IC(e);h(e=>{if(e){let n={...e,content:t||e.content,isComplete:!0,metadata:{...e.metadata||{},...r||{}}};d(e=>[...e,n])}else t&&d(e=>[...e,{role:`assistant`,content:t,timestamp:new Date().toISOString(),isComplete:!0,metadata:r}]);return null}),p(!1),T.current=null}}function N(e){e.messageId===T.current&&(console.error(`WebSocket streaming error:`,e),y(e.error),p(!1),T.current=null,a&&a(Error(e.error)))}let P=(0,X.useCallback)(async(e,n={})=>{if(f)throw Error(`Cannot send message while streaming`);y(null);let r={role:`user`,content:e||(n.images?.length?`[${n.images.length} image${n.images.length===1?``:`s`} attached]`:``),timestamp:new Date().toISOString(),isComplete:!0};d(e=>[...e,r]),p(!0);let i={message:e,images:n.images,context:u.slice(-10),mcpContext:n.mcpContext??!0,maxTokens:n.maxTokens,temperature:n.temperature},m=Array.isArray(n.images)&&n.images.length>0,g=o&&E&&l!==`ollama`&&!m,v=s;if(l===`ollama`&&console.log(`🦙 Ollama detected: Using SSE streaming (WebSocket not supported by Ollama)`),g)try{console.log(`🔌 Attempting WebSocket streaming for ${l||`unknown`} provider...`);let e=D(t,i);T.current=e,_(`websocket`);return}catch(e){console.warn(`WebSocket streaming failed for ${l||`unknown`}, falling back to SSE:`,e)}if(v){let e=!1;try{console.log(`📡 ${l===`ollama`?`Using`:`Attempting`} SSE streaming for ${l||`unknown`} provider...`),_(`sse`),w.current=new AbortController;let r=``;await lw(t,i.message,{onStart:()=>{e=!0},onMessage:(e,t,n)=>{r+=e;let i=typeof n?.reasoningDelta==`string`?n.reasoningDelta:``;if(h(e=>{let a=n?.reasoning||BD(e?.metadata?.reasoning,i);return{role:`assistant`,content:r,timestamp:e?.timestamp||new Date().toISOString(),isComplete:t,metadata:VD({...e?.metadata||{},...n},a)}}),t){let e=n?.reasoning;d(t=>[...t,{role:`assistant`,content:r,timestamp:new Date().toISOString(),isComplete:!0,metadata:VD(n,e)}]),h(null),p(!1)}},onError:e=>{console.error(`SSE streaming error:`,e),y(e.message),p(!1),a&&a(e)},context:u.slice(-10).map(e=>({role:e.role,content:e.content,timestamp:e.timestamp,metadata:e.metadata})),images:n.images,mcpContext:n.mcpContext??!0,maxTokens:n.maxTokens,temperature:n.temperature});return}catch(t){if(e){console.warn(`SSE stream failed after server accepted prompt for ${l||`unknown`}; refusing REST fallback to avoid duplicate prompt.`);return}console.warn(`SSE streaming failed for ${l||`unknown`}, falling back to REST:`,t)}}if(c)try{console.log(`⚙️ Using REST API fallback for ${l||`unknown`} provider...`),_(`rest`);let r=await uw(t,{message:e,images:n.images,context:u.slice(-10).map(e=>({role:e.role,content:e.content,timestamp:e.timestamp,metadata:e.metadata})),mcpContext:n.mcpContext??!0,maxTokens:n.maxTokens,temperature:n.temperature}),i={role:`assistant`,content:r.content,timestamp:new Date().toISOString(),isComplete:!0,metadata:r.metadata};d(e=>[...e,i]),p(!1)}catch(e){console.error(`All chat methods failed:`,e);let t=e instanceof Error?e.message:`Failed to send message`;y(t),p(!1),a&&a(e instanceof Error?e:Error(t))}else y(`All streaming methods failed and fallback is disabled`),p(!1)},[t,u,f,E,D,o,s,c,l,a]),ee=(0,X.useCallback)(()=>{d([]),h(null),y(null)},[]),F=(0,X.useCallback)(()=>{w.current&&=(w.current.abort(),null),T.current=null,p(!1),h(null)},[]);return(0,X.useEffect)(()=>()=>{w.current&&w.current.abort()},[]),{messages:u,isStreaming:f,currentStreamingMessage:m,connectionStatus:g,error:v,sendMessage:P,clearMessages:ee,stopStreaming:F,allMessages:m?[...u,m]:u,isWebSocketConnected:g===`websocket`,isUsingSSE:g===`sse`,isUsingREST:g===`rest`}}function UD(e){let{sessions:t,create:n}=LD(e),r=(t?.sessions.length??0)>0;return{hasSession:r,ensureSession:async()=>r?null:n({mode:`persistent`})}}async function WD(e){let t=await new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let[,e=``]=(typeof r.result==`string`?r.result:``).split(`,`,2);t(e)},r.onerror=()=>n(r.error||Error(`Failed to read image`)),r.readAsDataURL(e)});return{id:`${e.name}-${e.size}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:`image`,data:t,mimeType:e.type||`image/png`,name:e.name}}function GD(e){return String(e||``).trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)}function KD({agentId:e,routeAgentId:t,initialMessages:n,llmProvider:r,sessionKey:i}){let{showToast:a}=oo(),{hasSession:o,ensureSession:s}=UD(e),c=Gc(),l=(0,X.useRef)(null),u=(0,X.useRef)(null),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)([]),{allMessages:h,isStreaming:g,currentStreamingMessage:_,connectionStatus:v,error:y,sendMessage:b,clearMessages:x,stopStreaming:S}=HD({agentId:e,initialMessages:n,historyKey:i,loadHistory:!1,llmProvider:r,enableWebSocket:!1,onError:e=>{a({title:`Chat Error`,description:e.message,variant:`destructive`})}});return(0,X.useEffect)(()=>{l.current?.scrollIntoView({behavior:`smooth`})},[h,_]),(0,X.useEffect)(()=>{g||u.current?.focus()},[g,i]),(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col rounded-lg border`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between border-b px-4 py-3`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Chat`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Current session conversation`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`span`,{children:v}),h.length>0&&(0,Z.jsx)(`button`,{type:`button`,onClick:x,disabled:g,className:`text-destructive hover:underline disabled:opacity-50`,children:`Clear visible chat`})]})]}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4 space-y-4`,children:[h.length===0?(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center text-center text-muted-foreground`,children:(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(Pt,{className:`mx-auto mb-4 h-10 w-10 opacity-40`}),(0,Z.jsx)(`p`,{className:`text-sm`,children:o?`No messages yet.`:`No session yet.`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs`,children:o?`Send a message to start the conversation.`:`Type a message to auto-create a session, or pick one in the Sessions panel.`})]})}):h.map((e,t)=>(0,Z.jsx)(FD,{message:e,isStreaming:g&&e===_,connectionStatus:v},`${e.timestamp}-${t}`)),y&&(0,Z.jsx)(`div`,{className:`rounded-lg bg-destructive/10 p-3 text-sm text-destructive`,children:y}),(0,Z.jsx)(`div`,{ref:l})]}),(0,Z.jsxs)(`div`,{className:`border-t p-4`,children:[p.length>0&&(0,Z.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-2`,children:p.map(e=>(0,Z.jsxs)(`div`,{className:`group relative overflow-hidden rounded-md border bg-muted/20`,children:[(0,Z.jsx)(`img`,{src:`data:${e.mimeType};base64,${e.data}`,alt:e.name||`Pasted image`,className:`h-16 w-16 object-cover`}),(0,Z.jsx)(`div`,{className:`max-w-16 truncate px-2 py-1 text-[10px] text-muted-foreground`,children:e.name||e.mimeType}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>m(t=>t.filter(t=>t.id!==e.id)),className:`absolute right-1 top-1 flex h-5 w-5 items-center justify-center rounded-full bg-background/90 text-muted-foreground hover:text-foreground`,title:`Remove image`,children:(0,Z.jsx)(je,{className:`h-3 w-3`})})]},e.id))}),(0,Z.jsxs)(`form`,{onSubmit:async e=>{e.preventDefault();let n=d.trim();if(!(!n&&p.length===0)){f(``);try{let e=await s();e?.current.sessionId&&c(`/agents/${encodeURIComponent(t)}/${encodeURIComponent(e.current.sessionId)}`,{replace:!0}),await b(n,{images:p.map(({id:e,...t})=>t)}),m([])}catch(e){a({title:`Chat Error`,description:e instanceof Error?e.message:`Failed to send message`,variant:`destructive`})}}},className:`flex gap-2`,children:[(0,Z.jsx)(`textarea`,{ref:u,value:d,onChange:e=>f(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),e.currentTarget.form?.requestSubmit())},onPaste:async e=>{let t=Array.from(e.clipboardData.items).filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).map(e=>e.getAsFile()).filter(e=>!!e);if(t.length!==0)try{let e=await Promise.all(t.map(WD));m(t=>[...t,...e])}catch(e){a({title:`Paste Error`,description:e instanceof Error?e.message:`Failed to read pasted image`,variant:`destructive`})}},placeholder:g?`Streaming in progress...`:o?`Type a message...`:`Type to start a new session…`,disabled:g,rows:2,className:`flex min-h-10 flex-1 resize-y rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50`}),g?(0,Z.jsx)(J,{type:`button`,variant:`outline`,onClick:S,children:`Stop`}):(0,Z.jsx)(J,{type:`submit`,disabled:!d.trim()&&p.length===0,children:`Send`})]}),(0,Z.jsxs)(`div`,{className:`mt-2 flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(rn,{className:`h-3.5 w-3.5`}),`Paste image files from clipboard directly into the input.`]})]})]})}function qD(){let{agentId:e,sessionId:t}=Yc(),n=Hc(),r=Gc(),{showToast:i}=oo(),{selectEntity:a,openM2Drawer:o}=Eb(),s=Cm(),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(!0),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(!1),b=(0,X.useRef)(null),{current:x,sessions:S,refresh:C,select:w}=LD(e||``),T=(0,X.useMemo)(()=>S?.sessions?S.currentSessionId?S.sessions.find(e=>e.id===S.currentSessionId)||null:S.currentSessionPath?S.sessions.find(e=>e.path===S.currentSessionPath)||null:S.sessions.find(e=>e.isCurrent)||null:null,[S]),E=[x?.mode||`persistent`,x?.sessionId||x?.sessionFile||`initial`].join(`:`);return(0,X.useEffect)(()=>{e&&(async()=>{d(!0);try{let i=await qC(e);a(i.id),l(i);let o=i.name||i.id;if(o&&decodeURIComponent(e)!==o){let e=n.pathname.endsWith(`/settings`)?`/agents/${encodeURIComponent(o)}/settings`:t?`/agents/${encodeURIComponent(o)}/${encodeURIComponent(t)}`:`/agents/${encodeURIComponent(o)}`;r(e,{replace:!0})}await C(),_(null)}catch(e){let t=e instanceof Error?e.message:`Failed to load agent`;_(t),i({title:`Error`,description:t,variant:`destructive`})}finally{d(!1)}})()},[e,t,n.pathname,r,C,a,i]),(0,X.useEffect)(()=>{if(!e||!t||!S)return;let n=decodeURIComponent(t),r=GD(n),a=S.sessions.find(e=>e.id===n||e.slug===n||GD(e.name)===r),o=!!(a&&(S.currentSessionId===a.id||S.currentSessionPath===a.path||x?.sessionId===a.id||x?.sessionFile===a.path)),s=x?.sessionId===n||S.currentSessionId===n;if(x?.mode===`persistent`&&o){b.current=null;return}if(!a){x?.mode===`persistent`&&s&&(b.current=null);return}b.current!==a.id&&(b.current=a.id,w({mode:`persistent`,sessionId:a.id}).catch(e=>{i({title:`Session Error`,description:e instanceof Error?e.message:`Failed to select session`,variant:`destructive`})}).finally(()=>{b.current===a.id&&(b.current=null)}))},[e,t,S,x?.mode,x?.sessionId,x?.sessionFile,w,i]),(0,X.useEffect)(()=>{if(!e)return;let t=async()=>{try{let t=await cw(e);l(e=>e?{...e,isActive:t.isActive,status:t.status,lastAccessed:t.lastAccessed}:null)}catch{}};t();let n=setInterval(t,5e3);return()=>clearInterval(n)},[e]),u?(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,Z.jsxs)(`div`,{className:`text-center text-muted-foreground`,children:[(0,Z.jsx)(st,{className:`mx-auto mb-3 h-8 w-8 animate-pulse`}),(0,Z.jsx)(`p`,{children:`Loading agent...`})]})}):!c||g?(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,Z.jsxs)(`div`,{className:`text-center text-destructive`,children:[(0,Z.jsx)(st,{className:`mx-auto mb-3 h-8 w-8`}),(0,Z.jsx)(`p`,{children:g||`Agent not found`})]})}):(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Z.jsx)(Hy,{title:s?`Back to agent sessions`:`Back to agents`,onBack:()=>s?o(`agents`,`detail`,c.id):r(`/agents`)}),(0,Z.jsx)(`span`,{className:`h-3 w-3 shrink-0 rounded-full`,style:{backgroundColor:c.color||`#9ca3af`}}),(0,Z.jsx)(`h1`,{className:`truncate text-xl font-semibold`,children:c.label||c.name}),(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:c.status})]}),(0,Z.jsx)(`p`,{className:`mt-1 truncate text-sm text-muted-foreground`,children:c.description||`${c.llmProvider} / ${c.model}`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[c.isActive?(0,Z.jsxs)(J,{variant:`outline`,onClick:async()=>{if(e){h(!0);try{let t=await sw(e);l(t),i({title:`Stopped`,description:`${t.label||t.name} is inactive`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to stop agent`,variant:`destructive`})}finally{h(!1)}}},disabled:m,children:[(0,Z.jsx)($t,{className:`mr-2 h-4 w-4`}),m?`Stopping...`:`Stop`]}):(0,Z.jsxs)(J,{onClick:async()=>{if(e){p(!0);try{let t=await ow(e);l(t),i({title:`Started`,description:`${t.label||t.name} is active`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to start agent`,variant:`destructive`})}finally{p(!1)}}},disabled:f,children:[(0,Z.jsx)(W,{className:`mr-2 h-4 w-4`}),f?`Starting...`:`Start`]}),(0,Z.jsxs)(J,{variant:`outline`,onClick:()=>{a(c.id),r(`/agents/${encodeURIComponent(c.name||c.id)}/settings/identity`)},children:[(0,Z.jsx)(mn,{className:`mr-2 h-4 w-4`}),`Settings`]}),(0,Z.jsx)(Vy,{className:`h-9 w-9`})]})]}),(0,Z.jsxs)(`div`,{className:`grid min-h-0 flex-1 grid-cols-1 gap-4 grid-rows-[minmax(0,1fr)_auto] xl:grid-rows-none xl:grid-cols-[minmax(0,1.2fr)_minmax(320px,0.8fr)]`,children:[(0,Z.jsx)(KD,{agentId:c.id,routeAgentId:c.name||c.id,initialMessages:x?.messages||[],llmProvider:c.llmProvider,sessionKey:E},E),(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-col rounded-lg border`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>y(e=>!e),"aria-expanded":v,className:K(`flex w-full items-center justify-between gap-2 px-4 py-3 text-left xl:pointer-events-none`,v?`border-b`:`xl:border-b`),children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Contextual Information`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Current session and runtime state.`})]}),(0,Z.jsx)(Ne,{className:K(`h-4 w-4 shrink-0 text-muted-foreground transition-transform xl:hidden`,v&&`rotate-180`)})]}),(0,Z.jsxs)(`div`,{className:K(`space-y-4 overflow-y-auto p-4 text-sm max-xl:max-h-viewport-half`,!v&&`max-xl:hidden`),children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Mode`}),(0,Z.jsx)(`div`,{className:`mt-1`,children:x?.mode||S?.mode||`persistent`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Selected Session`}),(0,Z.jsx)(`div`,{className:`mt-1 break-all`,children:T?.name||(T?.isExperimental?`Experimental`:null)||x?.sessionId||`Default session`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Known Sessions`}),(0,Z.jsx)(`div`,{className:`mt-1`,children:S?.sessions.length||0})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Thinking Level`}),(0,Z.jsx)(`div`,{className:`mt-1`,children:x?.thinkingLevel||`high`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Model`}),(0,Z.jsx)(`div`,{className:`mt-1`,children:x?.model?.modelId||c.model||`Not set`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:`Session File`}),(0,Z.jsx)(`div`,{className:`mt-1 break-all text-xs text-muted-foreground`,children:x?.sessionFile||`In-memory / not persisted yet`})]}),(0,Z.jsxs)(`div`,{className:`rounded-lg border bg-muted/20 p-4 text-sm text-muted-foreground`,children:[(0,Z.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 font-medium text-foreground`,children:[(0,Z.jsx)(ht,{className:`h-4 w-4`}),`Shape`]}),(0,Z.jsx)(`p`,{children:`Session selection lives in M2. Main content stays focused on the active conversation and its context.`})]})]})]})]})]})}var JD={anthropic:`claude-3-5-sonnet-20241022`,openai:`gpt-4o`,ollama:`qwen2.5-coder:latest`,"lm-studio":``,vllm:``,custom:``},YD={anthropic:`https://api.anthropic.com`,openai:`https://api.openai.com/v1`,ollama:`http://localhost:11434/v1`,"lm-studio":`http://localhost:1234/v1`,vllm:`http://localhost:8000/v1`,custom:``};function XD(e){return YD[e]||``}function ZD(e,t,n){return[e.trim()?`## Role\n${e.trim()}`:``,t.trim()?`## Identity\n${t.trim()}`:``,n.trim()?`## Instructions\n${n.trim()}`:``].filter(Boolean).join(`
|
|
25
|
+
|
|
26
|
+
`)}function QD({label:e,hint:t,children:n}){return(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-sm font-medium`,children:e}),t&&(0,Z.jsx)(`p`,{className:`mb-1 mt-0.5 text-xs text-muted-foreground`,children:t}),(0,Z.jsx)(`div`,{className:t?void 0:`mt-1`,children:n})]})}var $D=`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring resize-y`,eO=`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`;function tO(){let{agentId:e,tab:t}=Yc(),n=Gc(),{showToast:r}=oo(),{selectEntity:i,openM2Drawer:a}=Eb(),o=Cm(),s=AC(t);(0,X.useEffect)(()=>{t!==s&&e&&n(`/agents/${encodeURIComponent(e)}/settings/${s}`,{replace:!0})},[t,s,e,n]);let[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(!0),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(``),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(Nf()),[E,D]=(0,X.useState)(``),[O,k]=(0,X.useState)(``),[A,j]=(0,X.useState)(``),[M,N]=(0,X.useState)(``),[P,ee]=(0,X.useState)(`anthropic`),[F,I]=(0,X.useState)(``),[te,ne]=(0,X.useState)(``),[L,re]=(0,X.useState)(``),[R,ie]=(0,X.useState)(.7),[ae,oe]=(0,X.useState)(4096),[z,se]=(0,X.useState)(1),[ce,B]=(0,X.useState)([]),[V,le]=(0,X.useState)(``),[ue,de]=(0,X.useState)(``),[fe,pe]=(0,X.useState)(``),[me,H]=(0,X.useState)(``),[he,ge]=(0,X.useState)(!1),[_e,ve]=(0,X.useState)(null),[ye,U]=(0,X.useState)(null),[be,xe]=(0,X.useState)(null),[Se,Ce]=(0,X.useState)(!1),[W,G]=(0,X.useState)(null),[we,Te]=(0,X.useState)(`context`),[Ee,De]=(0,X.useState)(``),[Oe,ke]=(0,X.useState)(`/`),[Ae,je]=(0,X.useState)(``),[Me,Ne]=(0,X.useState)(!0),[Pe,Fe]=(0,X.useState)(!1),[Ie,Le]=(0,X.useState)([]),[Re,ze]=(0,X.useState)([]),[Be,Ve]=(0,X.useState)(null),[He,Ue]=(0,X.useState)(`{}`),[We,Ge]=(0,X.useState)(null),[Ke,qe]=(0,X.useState)(e);Ke!==e&&(qe(e),d(!0),l(null)),(0,X.useEffect)(()=>{if(!e)return;let t=!1;return qC(e).then(async e=>{if(t)return;let n=e.config?.identity||{};l(e),i(e.id),y(e.name||``),x(e.label||``),C(e.description||``),T(e.color||Nf()),D(n.role||``),k(n.identity||``),j(n.instructions||``),N(e.config?.prompts?.system||``),ee(e.llmProvider||`anthropic`),I(e.config?.apiKey||``),ne(e.config?.baseUrl||XD(e.llmProvider)),re(e.model||JD[e.llmProvider]||``);let r=e.config?.connectors?.[e.llmProvider];r&&(ie(r.temperature??.7),oe(r.maxTokens??4096),se(r.topP??1)),Ue(JSON.stringify(e.config?.tools??{},null,2)),Ge(null),p(null);try{B(await ew(e.id))}catch{B([])}}).catch(e=>{t||p(e instanceof Error?e.message:`Failed to load agent`)}).finally(()=>{t||d(!1)}),()=>{t=!0}},[e,i]),(0,X.useEffect)(()=>{if(s!==`access`&&s!==`tools`||!c?.id)return;let e=c.id,t=!1;return Promise.all([VC(c.id).catch(()=>null),Or().catch(()=>[]),Uo().catch(()=>[]),GC(c.id).catch(()=>null)]).then(([n,r,i,a])=>{t||(U(n),Le(r),ze(i),Ve(a?a.tools:[]),n&&(Te(n.binding.type),De(n.binding.workspace||``),ke(n.binding.path||`/`),je(n.binding.context||``),Ne(n.permissions.includes(`read`)),Fe(n.permissions.includes(`write`))),xe(e))}),()=>{t=!0}},[s,c?.id]);let Je=()=>{let e=ZD(E,O,A),t;try{let e=JSON.parse(He);e&&typeof e==`object`&&!Array.isArray(e)&&(t=e)}catch{}return{...t===void 0?{}:{tools:t},name:v.trim(),label:b.trim(),description:S.trim()||void 0,color:w,llmProvider:P,model:L,apiKey:F||void 0,baseUrl:te||void 0,config:{type:P,model:L,identity:{role:E.trim()||void 0,identity:O.trim()||void 0,instructions:A.trim()||void 0},prompts:M.trim()||e?{system:M.trim()||e}:void 0,connectors:{[P]:{temperature:R,maxTokens:ae,topP:z}}}}},Ye=async e=>{if(e.preventDefault(),c){h(!0);try{let e=await iw(c.id,Je());l(e),window.dispatchEvent(new CustomEvent(`agents:refresh`)),r({title:`Saved`,description:`Agent updated`}),e.name&&e.name!==c.name&&n(`/agents/${encodeURIComponent(e.name)}/settings/${s}`,{replace:!0})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{h(!1)}}},Xe=async()=>{if(c&&window.confirm(`Delete agent "${c.label||c.name}"? This cannot be undone.`)){_(!0);try{await aw(c.id),window.dispatchEvent(new CustomEvent(`agents:refresh`)),r({title:`Deleted`,description:`Agent removed`}),n(`/agents`)}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Delete failed`,variant:`destructive`})}finally{_(!1)}}},Ze=()=>{le(``),de(``),pe(``),H(``)},Qe=async()=>{if(!(!c||!me.trim()&&!fe.trim())){ge(!0);try{let e=await tw(c.id,me.trim()?{source:me.trim()}:{name:V,description:ue,content:fe});B(e),Ze(),window.dispatchEvent(new CustomEvent(`agents:refresh`)),r({title:`Installed`,description:`Skill saved`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Skill install failed`,variant:`destructive`})}finally{ge(!1)}}},$e=async e=>{if(c){ve(e);try{let t=await nw(c.id,e);B(t),(V===e||me===e)&&Ze(),window.dispatchEvent(new CustomEvent(`agents:refresh`)),r({title:`Removed`,description:`Skill "${e}" removed`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Skill remove failed`,variant:`destructive`})}finally{ve(null)}}},et=()=>we===`global`?{type:`global`}:we===`context`?Ae?{type:`context`,context:Ae}:null:Ee?we===`path`?{type:`path`,workspace:Ee,path:Oe.trim()||`/`}:{type:`workspace`,workspace:Ee}:null,tt=async()=>{if(!c||Se)return;let e=et(),t=[];if(Me&&t.push(`read`),Pe&&t.push(`write`),!e||t.length===0){r({title:`Invalid binding`,description:`Pick a scope target and at least one permission`,variant:`destructive`});return}if(!(e.type===`global`&&!window.confirm(`Global scope lets this agent ${Pe?`read and write`:`read`} ALL your workspaces. Continue?`))){Ce(!0);try{let n=await HC(c.id,{binding:e,permissions:t});U(n.access),G(n.token),r({title:`Bound`,description:`Access bound — copy the token now, it is not shown again`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Bind failed`,variant:`destructive`})}finally{Ce(!1)}}},nt=async()=>{if(!(!c||Se)){Ce(!0);try{let e=await UC(c.id);U(e.access),G(e.token),r({title:`Rotated`,description:`New token minted — the previous one no longer works`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Rotate failed`,variant:`destructive`})}finally{Ce(!1)}}},rt=async()=>{if(!(!c||Se)&&window.confirm(`Revoke this agent's canvas access? Its token stops working immediately.`)){Ce(!0);try{await WC(c.id),U(null),G(null),r({title:`Revoked`,description:`Agent access removed`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Revoke failed`,variant:`destructive`})}finally{Ce(!1)}}},it=e=>{if(e.type===`global`)return`Global — all workspaces`;if(e.type===`context`){let t=Re.find(t=>t.id===e.context);return`Context ${t?`${t.id} (${t.url})`:e.context} — follows the context live`}let t=e.workspaceName||e.workspace;return e.type===`path`?`Workspace ${t}, path ${e.path||`/`}`:`Workspace ${t} (whole tree)`};if(u)return(0,Z.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Loading...`});if(!c||f)return(0,Z.jsx)(`div`,{className:`p-6 text-sm text-destructive`,children:f||`Agent not found`});let at=kC.find(e=>e.id===s),ot=encodeURIComponent(c.name||c.id),st=s===`identity`||s===`provider`||s===`models`||s===`tools`;return(0,Z.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-5xl p-6 pb-12 max-md:px-4 max-md:pb-rail-stack`,children:[(0,Z.jsx)(By,{compact:!0,className:`mb-6 border-b pb-4`,title:`${at.label} - ${c.label||c.name}`,description:at.description,backTo:`/agents/${ot}`,onBack:o?()=>a(`agents`,`settings`,c.id):void 0}),(0,Z.jsxs)(`form`,{onSubmit:Ye,className:`space-y-6`,children:[s===`identity`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsx)(QD,{label:`Name`,hint:`ID: ${c.id}`,children:(0,Z.jsx)(q,{value:v,onChange:e=>y(e.target.value),placeholder:`lucy`})}),(0,Z.jsx)(QD,{label:`Label`,children:(0,Z.jsx)(q,{value:b,onChange:e=>x(e.target.value),placeholder:`Display name`})})]}),(0,Z.jsx)(QD,{label:`Description`,children:(0,Z.jsx)(q,{value:S,onChange:e=>C(e.target.value),placeholder:`Short description`})}),(0,Z.jsx)(QD,{label:`Color`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(q,{type:`color`,value:w,onChange:e=>T(e.target.value),className:`h-10 w-16 p-1`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>T(Nf()),children:`Randomize`})]})})]}),(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Persona`}),(0,Z.jsx)(QD,{label:`Role`,children:(0,Z.jsx)(q,{value:E,onChange:e=>D(e.target.value),placeholder:`e.g. Software Engineer`})}),(0,Z.jsx)(QD,{label:`Identity`,children:(0,Z.jsx)(`textarea`,{value:O,onChange:e=>k(e.target.value),placeholder:`Who this agent is…`,className:`${$D} min-h-[80px]`})}),(0,Z.jsx)(QD,{label:`Instructions`,children:(0,Z.jsx)(`textarea`,{value:A,onChange:e=>j(e.target.value),placeholder:`Behavioral instructions…`,className:`${$D} min-h-[80px]`})}),(0,Z.jsx)(QD,{label:`System Prompt`,hint:`Compiled from Role + Identity + Instructions. Override manually.`,children:(0,Z.jsx)(`textarea`,{value:M,onChange:e=>N(e.target.value),placeholder:`System prompt sent to the LLM…`,className:`${$D} min-h-[140px] font-mono text-xs`})})]}),(0,Z.jsxs)(`section`,{className:`rounded-lg border border-destructive/30 p-4`,children:[(0,Z.jsx)(`h2`,{className:`mb-3 text-sm font-semibold text-destructive`,children:`Danger Zone`}),(0,Z.jsxs)(J,{type:`button`,variant:`destructive`,disabled:g,onClick:Xe,children:[(0,Z.jsx)(lt,{className:`mr-2 h-4 w-4`}),g?`Deleting...`:`Delete Agent`]})]})]}),s===`provider`&&(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(QD,{label:`Provider`,children:(0,Z.jsxs)(`select`,{value:P,onChange:e=>{let t=e.target.value;ee(t),re(JD[t]||``),ne(XD(t))},className:`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`,children:[(0,Z.jsx)(`option`,{value:`anthropic`,children:`Anthropic Claude`}),(0,Z.jsx)(`option`,{value:`openai`,children:`OpenAI GPT`}),(0,Z.jsx)(`option`,{value:`ollama`,children:`Ollama (Local)`}),(0,Z.jsx)(`option`,{value:`lm-studio`,children:`LM Studio (Local)`}),(0,Z.jsx)(`option`,{value:`vllm`,children:`vLLM (Local)`}),(0,Z.jsx)(`option`,{value:`custom`,children:`Custom`})]})}),(0,Z.jsx)(QD,{label:`API Key`,hint:[`ollama`,`lm-studio`,`vllm`].includes(P)?`Any value works for local providers.`:void 0,children:(0,Z.jsx)(q,{type:`password`,value:F,onChange:e=>I(e.target.value),placeholder:P===`ollama`?`ollama`:P===`lm-studio`?`lm-studio`:`sk-…`})}),(0,Z.jsx)(QD,{label:`Host / Base URL`,children:(0,Z.jsx)(q,{value:te,onChange:e=>ne(e.target.value),placeholder:XD(P)||`https://api.example.com`})})]}),s===`models`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Main Model`}),(0,Z.jsx)(QD,{label:`Model`,children:(0,Z.jsx)(q,{value:L,onChange:e=>re(e.target.value),placeholder:`Model name`})}),(0,Z.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-3`,children:[(0,Z.jsx)(QD,{label:`Temperature`,children:(0,Z.jsx)(q,{type:`number`,min:0,max:2,step:.1,value:R,onChange:e=>ie(parseFloat(e.target.value)||.7)})}),(0,Z.jsx)(QD,{label:`Max Tokens`,children:(0,Z.jsx)(q,{type:`number`,min:1,max:2e5,value:ae,onChange:e=>oe(parseInt(e.target.value)||4096)})}),(0,Z.jsx)(QD,{label:`Top P`,children:(0,Z.jsx)(q,{type:`number`,min:0,max:1,step:.1,value:z,onChange:e=>se(parseFloat(e.target.value)||1)})})]})]}),[`Governance`,`Memory Management`,`Subagent / Tool Use`].map(e=>(0,Z.jsxs)(`section`,{className:`rounded-lg border border-dashed p-4`,children:[(0,Z.jsxs)(`h2`,{className:`text-sm font-semibold text-muted-foreground`,children:[e,` Model`]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Coming soon`})]},e))]}),s===`tools`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Runtime Tools`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Injected at start (pi defineTool): coding tools plus canvas tools scoped by the token binding (Access / ACL). Definitions live in the runtime — read-only here until the agent-runtime workspace lands.`})]}),Be===null?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Loading…`}):Be.length===0?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`No tools resolved.`}):(0,Z.jsx)(`div`,{className:`space-y-1.5`,children:Be.map(e=>(0,Z.jsxs)(`details`,{className:`rounded-md border px-3 py-2`,children:[(0,Z.jsxs)(`summary`,{className:`cursor-pointer text-sm`,children:[(0,Z.jsx)(`code`,{className:`font-mono text-xs font-medium`,children:e.name}),(0,Z.jsx)(`span`,{className:`ml-2 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:e.source})]}),e.description&&(0,Z.jsx)(`p`,{className:`mt-2 whitespace-pre-wrap text-xs text-muted-foreground`,children:e.description}),e.parameters!=null&&(0,Z.jsx)(`pre`,{className:`mt-2 overflow-x-auto rounded bg-muted p-2 font-mono text-[11px]`,children:JSON.stringify(e.parameters,null,2)})]},e.name))}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:ye?it(ye.binding):`Unbound — no canvas tools are injected. Bind under Access / ACL.`})]}),(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Tools Config`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`config.tools JSON, merged server-side — e.g. {"canvas": {"enabled": false}} gates the canvas tools. Saved with Save Changes.`})]}),(0,Z.jsx)(`textarea`,{value:He,onChange:e=>{Ue(e.target.value);try{JSON.parse(e.target.value),Ge(null)}catch(e){Ge(e instanceof Error?e.message:`Invalid JSON`)}},className:`${$D} min-h-[120px] font-mono text-xs`}),We&&(0,Z.jsxs)(`p`,{className:`text-xs text-destructive`,children:[`Invalid JSON (not saved): `,We]})]}),(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Skills`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Installed skills are saved immediately, independent of Save Changes.`})]}),ce.length===0?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`No skills installed.`}):ce.map(e=>(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3 rounded-md border p-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-medium`,children:e.name}),(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:e.package?e.source:e.description||`No description`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{le(e.name),de(e.description||``),pe(e.content||``),H(e.source||``)},children:`Edit`}),(0,Z.jsx)(J,{type:`button`,variant:`destructive`,size:`sm`,disabled:_e===(e.source||e.name),onClick:()=>$e(e.source||e.name),children:_e===(e.source||e.name)?`Removing…`:`Remove`})]})]},e.name)),(0,Z.jsxs)(`div`,{className:`space-y-4 rounded-md border p-4`,children:[(0,Z.jsx)(QD,{label:`Package Source`,hint:`Use this for whole pi packages. Leave empty to save inline SKILL.md content.`,children:(0,Z.jsx)(q,{value:me,onChange:e=>H(e.target.value),placeholder:`npm:@foo/pi-tools or git:github.com/badlogic/pi-doom`})}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsx)(QD,{label:`Name`,children:(0,Z.jsx)(q,{value:V,onChange:e=>le(e.target.value),placeholder:`skill-name, or read from frontmatter`,disabled:!!me.trim()})}),(0,Z.jsx)(QD,{label:`Description`,children:(0,Z.jsx)(q,{value:ue,onChange:e=>de(e.target.value),placeholder:`What this skill helps with`,disabled:!!me.trim()})})]}),(0,Z.jsx)(QD,{label:`SKILL.md Content`,children:(0,Z.jsx)(`textarea`,{value:fe,onChange:e=>pe(e.target.value),placeholder:`# Skill instructions…`,disabled:!!me.trim(),className:`${$D} min-h-[160px] font-mono text-xs`})}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(J,{type:`button`,disabled:he||!me.trim()&&!fe.trim(),onClick:Qe,children:he?`Saving…`:`Install / Update Skill`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,onClick:Ze,children:`Clear`})]})]})]}),(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`MCP Servers`}),(c.config?.mcp?.servers||[]).length===0?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`No MCP servers configured.`}):(c.config?.mcp?.servers||[]).map((e,t)=>(0,Z.jsxs)(`div`,{className:`rounded-md border p-3`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium`,children:e.name}),(0,Z.jsxs)(`div`,{className:`font-mono text-xs text-muted-foreground`,children:[e.command,` `,(e.args||[]).join(` `)]})]},t))]})]}),s===`access`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Canvas Access`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The agent talks to canvas through its own scoped token; the server clamps every request to the binding. Bind, rotate and revoke apply immediately.`})]}),be===c.id?ye?(0,Z.jsxs)(`div`,{className:`space-y-2 rounded-md border p-3`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium`,children:it(ye.binding)}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[`Permissions: `,ye.permissions.join(`, `)||`none`,ye.boundAt?` · bound ${new Date(ye.boundAt).toLocaleString()}`:``,ye.rotatedAt?` · token rotated ${new Date(ye.rotatedAt).toLocaleString()}`:``]}),(0,Z.jsxs)(`div`,{className:`flex gap-2 pt-1`,children:[(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:Se,onClick:nt,children:`Rotate Token`}),(0,Z.jsx)(J,{type:`button`,variant:`destructive`,size:`sm`,disabled:Se,onClick:rt,children:`Revoke Access`})]})]}):(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Unbound — this agent has no canvas access.`}):(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Loading…`}),W&&(0,Z.jsxs)(`div`,{className:`space-y-2 rounded-md border border-warning/50 bg-warning/10 p-3`,children:[(0,Z.jsx)(`div`,{className:`text-xs font-medium`,children:`Agent token — shown once, store it now`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`code`,{className:`flex-1 truncate rounded bg-background px-2 py-1 font-mono text-xs`,children:W}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>navigator.clipboard?.writeText(W),children:`Copy`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>G(null),children:`Dismiss`})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`In-process agents receive it automatically (canvas.env); external runtimes (agentd) take it as CANVAS_TOKEN.`})]})]}),(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:ye?`Rebind`:`Bind`}),(0,Z.jsx)(QD,{label:`Scope`,hint:`Context bindings follow the context live; global spans all workspaces.`,children:(0,Z.jsxs)(`select`,{value:we,onChange:e=>Te(e.target.value),className:eO,children:[(0,Z.jsx)(`option`,{value:`context`,children:`Context (follows live)`}),(0,Z.jsx)(`option`,{value:`workspace`,children:`Workspace`}),(0,Z.jsx)(`option`,{value:`path`,children:`Workspace path`}),(0,Z.jsx)(`option`,{value:`global`,children:`Global (all workspaces)`})]})}),we===`context`&&(0,Z.jsx)(QD,{label:`Context`,children:(0,Z.jsxs)(`select`,{value:Ae,onChange:e=>je(e.target.value),className:eO,children:[(0,Z.jsx)(`option`,{value:``,children:`Select a context…`}),Re.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.id,` — `,e.url]},e.id))]})}),(we===`workspace`||we===`path`)&&(0,Z.jsx)(QD,{label:`Workspace`,children:(0,Z.jsxs)(`select`,{value:Ee,onChange:e=>De(e.target.value),className:eO,children:[(0,Z.jsx)(`option`,{value:``,children:`Select a workspace…`}),Ie.map(e=>(0,Z.jsx)(`option`,{value:e.name||e.id,children:e.label||e.name},e.id))]})}),we===`path`&&(0,Z.jsx)(QD,{label:`Base path`,hint:`The agent is clamped to this subtree.`,children:(0,Z.jsx)(q,{value:Oe,onChange:e=>ke(e.target.value),placeholder:`/work/projects/foo`})}),(0,Z.jsx)(QD,{label:`Permissions`,children:(0,Z.jsxs)(`div`,{className:`flex gap-4 text-sm`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:Me,onChange:e=>Ne(e.target.checked)}),` read`]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:Pe,onChange:e=>Fe(e.target.checked)}),` write`]})]})}),(0,Z.jsx)(J,{type:`button`,disabled:Se,onClick:tt,children:Se?`Working…`:ye?`Rebind & Mint Token`:`Bind & Mint Token`})]})]}),s===`memory`&&(0,Z.jsxs)(`section`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold text-muted-foreground`,children:`Memory Engine`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Loop-based memory management. Settings coming soon.`})]}),s===`integrations`&&(0,Z.jsxs)(`section`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold text-muted-foreground`,children:`Integrations`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`IMAP, chat, SQL and REST API accounts. Coming soon.`})]}),st&&(0,Z.jsx)(J,{type:`submit`,disabled:m,children:m?`Saving…`:`Save Changes`})]})]})})}function nO({workspaceId:e,isActive:t,currentMode:n,onChanged:r}){let[i,a]=(0,X.useState)(n===`workspace`?`workspace`:`secrets`),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(``),[m,h]=(0,X.useState)(``),[g,_]=(0,X.useState)(!1);return(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`font-semibold text-sm`,children:`Workspace protection`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Protect service credentials with a PIN or password. Optionally require it to start the whole workspace. Files and document contents are not encrypted.`}),t&&(0,Z.jsx)(`p`,{className:`text-sm`,children:`Stop the workspace before changing protection.`}),(0,Z.jsxs)(`form`,{className:`space-y-3`,onSubmit:async t=>{if(t.preventDefault(),h(``),o!==c){h(`PIN/password confirmation does not match`);return}_(!0);try{let t=await Y.put(`${Kr.workspaces}/${e}/protection`,{mode:i,passphrase:o,currentPassphrase:u||void 0});p(t.recoveryKey),s(``),l(``),d(``)}catch(e){h(e instanceof Error?e.message:`Could not save protection`)}finally{_(!1)}},children:[(0,Z.jsxs)(`label`,{className:`block text-sm space-y-1`,children:[`Protection mode`,(0,Z.jsxs)(`select`,{className:`block rounded border bg-background p-2 w-full`,value:i,onChange:e=>a(e.target.value),disabled:t||g,children:[(0,Z.jsx)(`option`,{value:`secrets`,children:`Secrets only — allow start without integrations`}),(0,Z.jsx)(`option`,{value:`workspace`,children:`Whole workspace — require PIN/password to start`})]})]}),(0,Z.jsxs)(`label`,{className:`block text-sm space-y-1`,children:[`Current PIN/password or recovery key (if already protected)`,(0,Z.jsx)(q,{type:`password`,autoComplete:`current-password`,value:u,onChange:e=>d(e.target.value),disabled:t||g})]}),(0,Z.jsxs)(`label`,{className:`block text-sm space-y-1`,children:[`New PIN/password`,(0,Z.jsx)(q,{type:`password`,autoComplete:`new-password`,minLength:4,maxLength:1024,required:!0,value:o,onChange:e=>s(e.target.value),disabled:t||g})]}),(0,Z.jsxs)(`label`,{className:`block text-sm space-y-1`,children:[`Confirm new PIN/password`,(0,Z.jsx)(q,{type:`password`,autoComplete:`new-password`,required:!0,value:c,onChange:e=>l(e.target.value),disabled:t||g})]}),(0,Z.jsx)(J,{disabled:t||g||!!f,children:g?`Saving…`:`Save protection`})]}),m&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:m}),f&&(0,Z.jsxs)(`div`,{className:`space-y-2 rounded border p-3`,children:[(0,Z.jsx)(`p`,{className:`text-sm`,children:`Save this recovery key now. It is shown only once and replaces any previous recovery key.`}),(0,Z.jsx)(`code`,{className:`block break-all select-all`,children:f}),(0,Z.jsx)(J,{variant:`outline`,onClick:()=>{p(``),r()},children:`I saved the recovery key`})]})]})}var rO=`h-8 rounded-md border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring`;function iO({title:e,hint:t,children:n}){let[r,i]=(0,X.useState)(!1);return(0,Z.jsxs)(`section`,{className:`overflow-hidden rounded-lg border`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>i(e=>!e),"aria-expanded":r,className:`flex w-full items-center justify-between gap-4 px-4 py-3 text-left transition-colors hover:bg-muted/40`,children:[(0,Z.jsxs)(`span`,{className:`min-w-0`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:e}),(0,Z.jsx)(`span`,{className:`mt-0.5 block text-xs text-muted-foreground`,children:t})]}),(0,Z.jsx)(Ne,{className:K(`h-4 w-4 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none`,r&&`rotate-180`)})]}),r&&(0,Z.jsx)(`div`,{className:`border-t p-4`,children:n})]})}function aO({workspaceId:e,workspaceName:t,refreshKey:n,onRefresh:r}){let{showToast:i}=oo(),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),l=(0,X.useCallback)(()=>OE(e).then(e=>o(e.queue??null)).catch(()=>{}),[e]);(0,X.useEffect)(()=>{l();let e=window.setInterval(()=>{o(e=>(e&&(e.pending>0||e.draining)&&l(),e))},3e3);return()=>window.clearInterval(e)},[l,n]);let u=async()=>{if(a){c(!0);try{let e=await yi(!a.paused,t);i({title:e.paused?`Embedding paused`:`Embedding resumed`,description:e.paused?`${e.pending.toLocaleString()} job(s) held for this workspace. Resume any time; a restart also resumes.`:`${e.pending.toLocaleString()} job(s) draining.`}),await l()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to toggle the embedding queue (admin only)`,variant:`destructive`})}finally{c(!1)}}},d=!!a?.draining,f=a?a.paused?`bg-warning`:d?`bg-success`:`bg-muted-foreground/40`:`bg-muted-foreground/40`;return(0,Z.jsxs)(`section`,{className:`flex flex-wrap items-center justify-between gap-x-4 gap-y-2 rounded-lg border bg-muted/30 px-4 py-2.5`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`relative flex h-2 w-2 shrink-0`,"aria-hidden":!0,children:[d&&(0,Z.jsx)(`span`,{className:`absolute inline-flex h-full w-full animate-ping rounded-full bg-success opacity-60 motion-reduce:hidden`}),(0,Z.jsx)(`span`,{className:K(`relative inline-flex h-2 w-2 rounded-full`,f)})]}),(0,Z.jsx)(`span`,{className:`font-medium`,children:a?a.pending>0?(0,Z.jsxs)(Z.Fragment,{children:[a.pending.toLocaleString(),` `,(0,Z.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`pending`})]}):a.paused?`Paused`:`Idle`:`Queue unavailable`}),a?.paused&&a.pending>0&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`held`}),a?.ingestDisabled&&(0,Z.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,title:`CANVAS_INFERD_INGEST_DISABLED=true: nothing new is enqueued; existing vectors still serve search`,children:`ingest disabled`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1`,children:[a&&(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,disabled:s,onClick:u,title:a.paused?`Resume embedding; the held backlog drains`:`Pause after the current batch. Stops the CPU-heavy model inference; documents keep indexing and stay searchable by text.`,children:s?`…`:a.paused?`Resume`:`Pause`}),(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,onClick:r,title:`Reload config, queue and tables`,children:(0,Z.jsx)(M,{className:`h-3.5 w-3.5`})})]})]})}function oO({workspaceId:e,tables:t,error:n,onChanged:r}){let{showToast:i}=oo(),[a,o]=(0,X.useState)(null),s=t.filter(e=>!e.active),c=async t=>{if(window.confirm(`Reclaim "${t.name}"?\n\nThis permanently deletes the vectors for ${t.model||`that model`} and its "already embedded" ledger. Switching back to it afterwards would cost a full re-embed rather than being instant.\n\nThis is the only irreversible step in the whole flow.`)){o(t.name);try{let n=await FE(e,t.name);if(!n.dropped)throw Error(n.error||`Failed to drop the vector table`);i({title:`Reclaimed`,description:`Dropped '${n.name||t.name}'.`}),r()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to reclaim`,variant:`destructive`})}finally{o(null)}}};return n?(0,Z.jsxs)(`section`,{className:`rounded-lg border border-destructive/40 bg-destructive-subtle p-4`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium text-destructive`,children:`Vector tables unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:n})]}):s.length===0?null:(0,Z.jsx)(iO,{title:`Previous models (${s.length})`,hint:`Kept on disk so switching back is instant. Reclaiming deletes their vectors for good (the only irreversible step here).`,children:(0,Z.jsx)(`div`,{className:`divide-y`,children:s.map(e=>(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-4 py-2 first:pt-0 last:pb-0`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`p`,{className:`truncate font-mono text-xs`,children:[e.model||`unknown model`,e.dim?` · ${e.dim}-d`:``]}),(0,Z.jsxs)(`p`,{className:`truncate font-mono text-[11px] text-muted-foreground`,children:[`└─ `,e.name]})]}),(0,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`text-destructive hover:text-destructive`,disabled:a===e.name,onClick:()=>c(e),title:`Permanently delete this model's vectors and ledger`,children:[(0,Z.jsx)(lt,{className:`mr-1.5 h-3.5 w-3.5`}),a===e.name?`Reclaiming…`:`Reclaim`]})]},e.name))})})}function sO({workspaceId:e,workspaceName:t,spaces:n,onDone:r}){let{showToast:i}=oo(),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(``),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1);return(0,Z.jsxs)(iO,{title:`Fill a space`,hint:`Embed documents that are missing from a space. Narrow it to one subtree to try a model on a single project first.`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Space`}),(0,Z.jsxs)(`select`,{className:`${rO} w-full`,value:a,onChange:e=>o(e.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:`all spaces`}),n.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`label`,{className:`text-xs font-medium`,children:[`Limit to a path `,(0,Z.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional)`})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:s,onChange:e=>c(e.target.value),placeholder:`ctx://work/project or dir://photos`,className:`h-8 font-mono text-sm`}),(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>m(!0),title:`Pick a context or directory path from the tree`,children:(0,Z.jsx)(ue,{className:`h-3.5 w-3.5`})})]})]})]}),(0,Z.jsxs)(`label`,{className:`mt-3 flex items-start gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:l,onChange:e=>u(e.target.checked)}),(0,Z.jsxs)(`span`,{children:[`Re-embed documents that are already embedded`,l&&s.trim()&&(0,Z.jsx)(`span`,{className:`mt-1 block text-[11px] text-warning`,children:`Combined with a path limit this clears the WHOLE space, not just that subtree. A partial clear is not expressible in the ledger. Leave this off unless you mean to redo everything.`})]})]}),(0,Z.jsx)(J,{type:`button`,size:`sm`,className:`mt-3`,onClick:async()=>{f(!0);try{let t=await NE(e,{space:a||void 0,reindex:l,scope:s.trim()||void 0});t.ingestDisabled?i({title:`Ingest disabled`,description:`CANVAS_INFERD_INGEST_DISABLED=true: nothing was enqueued. Existing vectors still serve search.`,variant:`destructive`}):i({title:`Fill enqueued`,description:`${t.enqueued.toLocaleString()} document(s) queued${t.scope?` under ${t.scope}`:``}. The status line reports progress.`}),r()}catch(e){i({title:`Fill failed`,description:e instanceof Error?e.message:`Failed to enqueue`,variant:`destructive`})}finally{f(!1)}},disabled:d,children:d?`Queueing…`:`Start fill`}),p&&(0,Z.jsx)(sp,{onClose:()=>m(!1),children:(0,Z.jsx)(ap,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,fixedWorkspaceName:t,multiple:!1,onClose:()=>m(!1),onConfirm:(e,t)=>{let n=e[0];if(n){let e=t.treeType===`directory`?`dir`:`ctx`;c(`${e}://${n.replace(/^\/+/,``)}`)}m(!1)}})})]})}var cO=[{provider:`blip`,model:`HuggingFaceTB/SmolVLM-500M-Instruct`,task:`instruct`,label:`SmolVLM 500M: prompted description (recommended)`,note:`~500 MB. Follows the prompt below, so architecture/materials/setting can be asked for.`},{provider:`blip`,model:`HuggingFaceTB/SmolVLM-256M-Instruct`,task:`instruct`,label:`SmolVLM 256M: prompted, smaller`,note:`~250 MB. Same prompting, weaker; for memory-tight boxes.`},{provider:`blip`,model:`onnx-community/Florence-2-base-ft`,task:`florence2`,label:`Florence-2 base: detailed caption`,note:`Detailed multi-sentence captions, but not steerable: no prompt, fixed task token.`},{provider:`blip`,model:`Xenova/vit-gpt2-image-captioning`,task:`caption`,label:`vit-gpt2: one short sentence (weakest)`,note:`The old default. Terse and repetition-prone; kept for continuity and low memory.`}],lO=`custom`,uO=[{value:`instruct`,label:`Instruct VLM (image + prompt)`},{value:`florence2`,label:`Florence-2 (task token)`},{value:`caption`,label:`Plain captioner (image only)`}],dO=`Describe this photograph in two or three sentences. If it shows a building or interior, name the architectural style, the main materials and the setting. Describe only what is visible.`;function fO({workspaceId:e,config:t,saving:n,onSave:r}){let{showToast:i}=oo(),a=t.workspace||{},o=t.effective||{},s=cO[0],c=a.summarize?.image||o.summarize?.image||{},[l,u]=(0,X.useState)(()=>o.summarize?.image?.enabled===!0||a.summarize?.image?.enabled===!0),[d,f]=(0,X.useState)(()=>{let e=cO.find(e=>e.provider===(c.provider||s.provider)&&e.model===c.model);return e?`${e.provider}::${e.model}`:c.model?lO:`${s.provider}::${s.model}`}),[p,m]=(0,X.useState)(()=>cO.some(e=>e.model===c.model)?``:c.model||``),[h,g]=(0,X.useState)(()=>c.task||`instruct`),[_,v]=(0,X.useState)(()=>c.prompt||``),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(!1),[T,E]=(0,X.useState)(!1),[D,O]=(0,X.useState)(!1),k=cO.find(e=>`${e.provider}::${e.model}`===d),A=d===lO,j=A?{provider:s.provider,model:p.trim(),task:h,label:`Custom`,note:``}:k||s,M=j.task===`instruct`,N=(0,X.useCallback)(()=>OE(e).then(e=>S(e.summarize||null)).catch(()=>{}),[e]);(0,X.useEffect)(()=>{N();let e=window.setInterval(()=>{S(e=>(e?.running&&N(),e))},2e3);return()=>window.clearInterval(e)},[N]);let P=async()=>{await r({...a,summarize:{...a.summarize||{},image:{enabled:l,provider:j.provider,model:j.model,task:j.task,...M&&_.trim()?{prompt:_.trim()}:{}}}}),b(!1)},ee=async()=>{E(!0);try{S(await AE(e)),i({title:`Stopping image summaries`,description:`The image being captioned finishes first; the rest are left for a later run.`})}catch(e){i({title:`Could not stop`,description:e instanceof Error?e.message:`Failed to stop`,variant:`destructive`})}finally{E(!1)}},F=async(t=!1)=>{w(!0);try{let n=await kE(e,{force:t});S(n),i({title:t?`Rebuilding image summaries`:`Backfilling image summaries`,description:`${n.total.toLocaleString()} candidate image(s). First run downloads model weights.`})}catch(e){i({title:`Summaries failed to start`,description:e instanceof Error?e.message:`Failed to start`,variant:`destructive`})}finally{w(!1)}},I=o.summarize?.image?.enabled===!0,te=x?.running===!0,ne=x?.errors?.[0]?.error;return(0,Z.jsx)(iO,{title:`Summaries`,hint:`Generate descriptions for indexed images (metadata.summary); searchable via full-text and dense search`,children:(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:l,disabled:n,onChange:e=>{u(e.target.checked),b(!0)}}),`Images`]}),(0,Z.jsxs)(`select`,{className:rO,value:d,disabled:n||!l,onChange:e=>{f(e.target.value),b(!0)},children:[cO.map(e=>(0,Z.jsx)(`option`,{value:`${e.provider}::${e.model}`,children:e.label},`${e.provider}::${e.model}`)),(0,Z.jsx)(`option`,{value:lO,children:`Custom model…`})]}),!A&&(0,Z.jsx)(`span`,{className:`font-mono text-xs text-muted-foreground`,children:j.model})]}),A&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{className:`h-8 w-72 font-mono text-xs`,placeholder:`org/model-id (Transformers.js / ONNX)`,value:p,disabled:n||!l,onChange:e=>{m(e.target.value),b(!0)}}),(0,Z.jsx)(`select`,{className:rO,value:h,disabled:n||!l,onChange:e=>{g(e.target.value),b(!0)},children:uO.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))})]}),l&&j.note&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:j.note}),l&&M&&(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`textarea`,{className:`w-full rounded-md border border-input bg-transparent p-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,rows:3,placeholder:dO,value:_,disabled:n,onChange:e=>{v(e.target.value),b(!0)}}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`What to ask of every image. Empty uses the default shown above. Captions are indexed, so ask for the words you would search by.`})]}),x&&(x.running||x.total>0||x.finishedAt)&&(0,Z.jsxs)(`p`,{className:K(`text-xs`,x.aborted?`text-destructive`:`text-muted-foreground`),children:[te?`Running`:x.aborted?`Stopped`:x.cancelled?`Cancelled`:`Last run`,`: `,x.described,`/`,x.total,` described`,x.skipped?`, ${x.skipped} skipped`:``,x.failed?`, ${x.failed} failed`:``,x.aborted?`. ${x.abortedReason||`model worker died`}. Remaining images were not attempted; generate again to retry.`:x.cancelled?`. Stopped by you. The remaining images were left untouched; generate again to continue.`:ne?`. ${ne}`:``]}),(0,Z.jsxs)(`label`,{className:`flex items-start gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:D,disabled:n||te,onChange:e=>O(e.target.checked)}),(0,Z.jsxs)(`span`,{children:[`Re-caption images that already have a summary`,D&&(0,Z.jsxs)(`span`,{className:`mt-1 block text-[11px] text-warning`,children:[`Replaces every existing `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`metadata.summary`}),`, including ones written by a different model. Leave this off to fill in only what is missing.`]})]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Enable + save, then run. Only the local caption provider is wired today. Candidates come from `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`data/mime/image`}),`.`]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>void P(),disabled:n||!y,children:`Save summaries`}),(0,Z.jsx)(J,{size:`sm`,onClick:()=>void F(D),disabled:n||y||C||te||!I,title:I?y?`Save config first`:D?`Re-caption every image, replacing existing summaries`:`Caption images that have no summary yet`:`Enable image summaries and save first`,children:te||C?`Running…`:D?`Rebuild`:`Backfill`}),te&&(0,Z.jsx)(J,{size:`sm`,variant:`destructive`,onClick:()=>void ee(),disabled:T,title:`Finish the current image, then stop. The rest are left for later.`,children:T?`Stopping…`:`Stop`})]})]})]})})}function pO({workspaceId:e,workspaceName:t}){let{showToast:n}=oo(),[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)([]),[s,c]=(0,X.useState)(),[l,u]=(0,X.useState)(!0),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)([]),[_,v]=(0,X.useState)(0),y=(0,X.useCallback)(()=>jE(e).then(e=>{i(e),m(null)}).catch(e=>m(e instanceof Error?e.message:`Failed to load the embedding config`)).finally(()=>u(!1)),[e]),b=(0,X.useCallback)(()=>PE(e).then(e=>{o(e.tables||[]),c(e.error)}).catch(e=>c(e instanceof Error?e.message:`Failed to list vector tables`)),[e]);(0,X.useEffect)(()=>{y(),b()},[y,b]);let x=()=>{u(!0),y(),b(),v(e=>e+1)},S=async t=>{f(!0);try{let r=await ME(e,t);g(r.movedSpaces||[]),r.movedSpaces?.length?n({title:`Saved; fill to finish`,description:`${r.movedSpaces.join(`, `)} now targets a new model. The switch is live, but the new table is empty until you fill it.`}):r.applied===!1?n({title:`Saved; applies on next start`,description:`The workspace is not running, so the new spaces take effect when it starts.`}):n({title:`Saved`,description:`Embedding config updated.`}),await y(),await b()}catch(e){n({title:`Save failed`,description:e instanceof Error?e.message:`Failed to save`,variant:`destructive`})}finally{f(!1)}},C=async t=>{try{let r=await NE(e,{space:t});if(r.ingestDisabled){n({title:`Ingest disabled`,description:`CANVAS_INFERD_INGEST_DISABLED=true: nothing was enqueued. Existing vectors still serve search.`,variant:`destructive`});return}n({title:`Filling ${t}`,description:`${r.enqueued.toLocaleString()} document(s) queued. The status line reports progress.`}),g(e=>e.filter(e=>e!==t)),v(e=>e+1),b()}catch(e){n({title:`Fill failed`,description:e instanceof Error?e.message:`Failed to enqueue`,variant:`destructive`})}};if(l)return(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(M,{className:`h-4 w-4 animate-spin`}),`Loading the embedding config…`]});if(p||!r)return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`rounded-lg border border-destructive/40 bg-destructive-subtle p-4 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Embedding config unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:p||`No config returned.`})]}),(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:x,children:`Try again`})]});let w=Object.keys(r.effective.spaces||{}).sort();return(0,Z.jsxs)(`div`,{className:`space-y-5`,children:[(0,Z.jsx)(aO,{workspaceId:e,workspaceName:t,refreshKey:_,onRefresh:x}),(0,Z.jsx)(nD,{value:r.workspace||{},effective:r.effective||{},inherited:r.inherited||{},resolvedSpaces:r.spaces,invalid:r.invalid,attention:h,onFill:C,saving:d,saveLabel:`Save embedding config`,onSave:S},JSON.stringify(r.workspace)),(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(fO,{workspaceId:e,config:r,saving:d,onSave:S},`summarize:${JSON.stringify(r.workspace?.summarize||{})}`),(0,Z.jsx)(sO,{workspaceId:e,workspaceName:t,spaces:w,onDone:()=>{b(),v(e=>e+1)}}),(0,Z.jsx)(oO,{workspaceId:e,tables:a,error:s,onChanged:()=>{b()}})]}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Stored in this workspace's own `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`workspace.json`}),`, so it travels with the workspace. Settings resolve in layers: built-in, then server, then your defaults, then this workspace, which wins. Changes apply live, with no restart.`]})]})}function mO(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var hO=[],gO=[];(()=>{let e=`lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o`.split(`,`).map(e=>e?parseInt(e,36):1);for(let t=0,n=0;t<e.length;t++)(t%2?gO:hO).push(n+=e[t])})();function _O(e){if(e<768)return!1;for(let t=0,n=hO.length;;){let r=t+n>>1;if(e<hO[r])n=r;else if(e>=gO[r])t=r+1;else return!0;if(t==n)return!1}}function vO(e){return e>=127462&&e<=127487}var yO=8205;function bO(e,t,n=!0,r=!0){return(n?xO:SO)(e,t,r)}function xO(e,t,n){if(t==e.length)return t;t&&wO(e.charCodeAt(t))&&TO(e.charCodeAt(t-1))&&t--;let r=CO(e,t);for(t+=EO(r);t<e.length;){let i=CO(e,t);if(r==yO||i==yO||n&&_O(i))t+=EO(i),r=i;else if(vO(i)){let n=0,r=t-2;for(;r>=0&&vO(CO(e,r));)n++,r-=2;if(n%2==0)break;t+=2}else break}return t}function SO(e,t,n){for(;t>1;){let r=xO(e,t-2,n);if(r<t)return r;t--}return 0}function CO(e,t){let n=e.charCodeAt(t);if(!TO(n)||t+1==e.length)return n;let r=e.charCodeAt(t+1);return wO(r)?(n-55296<<10)+(r-56320)+65536:n}function wO(e){return e>=56320&&e<57344}function TO(e){return e>=55296&&e<56320}function EO(e){return e<65536?1:2}var DO=class e{lineAt(e){if(e<0||e>this.length)throw RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,n){[e,t]=LO(this,e,t);let r=[];return this.decompose(0,e,r,2),n.length&&n.decompose(0,n.length,r,3),this.decompose(t,this.length,r,1),kO.from(r,this.length-(t-e)+n.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=LO(this,e,t);let n=[];return this.decompose(e,t,n,0),kO.from(n,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),n=this.length-this.scanIdentical(e,-1),r=new NO(this),i=new NO(e);for(let e=t,a=t;;){if(r.next(e),i.next(e),e=0,r.lineBreak!=i.lineBreak||r.done!=i.done||r.value!=i.value)return!1;if(a+=r.value.length,r.done||a>=n)return!0}}iter(e=1){return new NO(this,e)}iterRange(e,t=this.length){return new PO(this,e,t)}iterLines(e,t){let n;if(e==null)n=this.iter();else{t??=this.lines+1;let r=this.line(e).from;n=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new FO(n)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(t){if(t.length==0)throw RangeError(`A document must have at least one line`);return t.length==1&&!t[0]?e.empty:t.length<=32?new OO(t):kO.from(OO.split(t,[]))}},OO=class e extends DO{constructor(e,t=AO(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,n,r){for(let i=0;;i++){let a=this.text[i],o=r+a.length;if((t?n:o)>=e)return new IO(r,o,n,a);r=o+1,n++}}decompose(t,n,r,i){let a=t<=0&&n>=this.length?this:new e(MO(this.text,t,n),Math.min(n,this.length)-Math.max(0,t));if(i&1){let t=r.pop(),n=jO(a.text,t.text.slice(),0,a.length);if(n.length<=32)r.push(new e(n,t.length+a.length));else{let t=n.length>>1;r.push(new e(n.slice(0,t)),new e(n.slice(t)))}}else r.push(a)}replace(t,n,r){if(!(r instanceof e))return super.replace(t,n,r);[t,n]=LO(this,t,n);let i=jO(this.text,jO(r.text,MO(this.text,0,t)),n),a=this.length+r.length-(n-t);return i.length<=32?new e(i,a):kO.from(e.split(i,[]),a)}sliceString(e,t=this.length,n=`
|
|
27
|
+
`){[e,t]=LO(this,e,t);let r=``;for(let i=0,a=0;i<=t&&a<this.text.length;a++){let o=this.text[a],s=i+o.length;i>e&&a&&(r+=n),e<s&&t>i&&(r+=o.slice(Math.max(0,e-i),t-i)),i=s+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(t,n){let r=[],i=-1;for(let a of t)r.push(a),i+=a.length+1,r.length==32&&(n.push(new e(r,i)),r=[],i=-1);return i>-1&&n.push(new e(r,i)),n}},kO=class e extends DO{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let t of e)this.lines+=t.lines}lineInner(e,t,n,r){for(let i=0;;i++){let a=this.children[i],o=r+a.length,s=n+a.lines-1;if((t?s:o)>=e)return a.lineInner(e,t,n,r);r=o+1,n=s+1}}decompose(e,t,n,r){for(let i=0,a=0;a<=t&&i<this.children.length;i++){let o=this.children[i],s=a+o.length;if(e<=s&&t>=a){let i=r&(a<=e|(s>=t?2:0));a>=e&&s<=t&&!i?n.push(o):o.decompose(e-a,t-a,n,i)}a=s+1}}replace(t,n,r){if([t,n]=LO(this,t,n),r.lines<this.lines)for(let i=0,a=0;i<this.children.length;i++){let o=this.children[i],s=a+o.length;if(t>=a&&n<=s){let c=o.replace(t-a,n-a,r),l=this.lines-o.lines+c.lines;if(c.lines<l>>4&&c.lines>l>>6){let a=this.children.slice();return a[i]=c,new e(a,this.length-(n-t)+r.length)}return super.replace(a,s,c)}a=s+1}return super.replace(t,n,r)}sliceString(e,t=this.length,n=`
|
|
28
|
+
`){[e,t]=LO(this,e,t);let r=``;for(let i=0,a=0;i<this.children.length&&a<=t;i++){let o=this.children[i],s=a+o.length;a>e&&i&&(r+=n),e<s&&t>a&&(r+=o.sliceString(e-a,t-a,n)),a=s+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(t,n){if(!(t instanceof e))return 0;let r=0,[i,a,o,s]=n>0?[0,0,this.children.length,t.children.length]:[this.children.length-1,t.children.length-1,-1,-1];for(;;i+=n,a+=n){if(i==o||a==s)return r;let e=this.children[i],c=t.children[a];if(e!=c)return r+e.scanIdentical(c,n);r+=e.length+1}}static from(t,n=t.reduce((e,t)=>e+t.length+1,-1)){let r=0;for(let e of t)r+=e.lines;if(r<32){let e=[];for(let n of t)n.flatten(e);return new OO(e,n)}let i=Math.max(32,r>>5),a=i<<1,o=i>>1,s=[],c=0,l=-1,u=[];function d(t){let n;if(t.lines>a&&t instanceof e)for(let e of t.children)d(e);else t.lines>o&&(c>o||!c)?(f(),s.push(t)):t instanceof OO&&c&&(n=u[u.length-1])instanceof OO&&t.lines+n.lines<=32?(c+=t.lines,l+=t.length+1,u[u.length-1]=new OO(n.text.concat(t.text),n.length+1+t.length)):(c+t.lines>i&&f(),c+=t.lines,l+=t.length+1,u.push(t))}function f(){c!=0&&(s.push(u.length==1?u[0]:e.from(u,l)),l=-1,c=u.length=0)}for(let e of t)d(e);return f(),s.length==1?s[0]:new e(s,n)}};DO.empty=new OO([``],0);function AO(e){let t=-1;for(let n of e)t+=n.length+1;return t}function jO(e,t,n=0,r=1e9){for(let i=0,a=0,o=!0;a<e.length&&i<=r;a++){let s=e[a],c=i+s.length;c>=n&&(c>r&&(s=s.slice(0,r-i)),i<n&&(s=s.slice(n-i)),o?(t[t.length-1]+=s,o=!1):t.push(s)),i=c+1}return t}function MO(e,t,n){return jO(e,[``],t,n)}var NO=class{constructor(e,t=1){this.dir=t,this.done=!1,this.lineBreak=!1,this.value=``,this.nodes=[e],this.offsets=[t>0?1:(e instanceof OO?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let n=this.nodes.length-1,r=this.nodes[n],i=this.offsets[n],a=i>>1,o=r instanceof OO?r.text.length:r.children.length;if(a==(t>0?o:0)){if(n==0)return this.done=!0,this.value=``,this;t>0&&this.offsets[n-1]++,this.nodes.pop(),this.offsets.pop()}else if((i&1)==(t>0?0:1)){if(this.offsets[n]+=t,e==0)return this.lineBreak=!0,this.value=`
|
|
29
|
+
`,this;e--}else if(r instanceof OO){let i=r.text[a+(t<0?-1:0)];if(this.offsets[n]+=t,i.length>Math.max(0,e))return this.value=e==0?i:t>0?i.slice(e):i.slice(0,i.length-e),this;e-=i.length}else{let i=r.children[a+(t<0?-1:0)];e>i.length?(e-=i.length,this.offsets[n]+=t):(t<0&&this.offsets[n]--,this.nodes.push(i),this.offsets.push(t>0?1:(i instanceof OO?i.text.length:i.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},PO=class{constructor(e,t,n){this.value=``,this.done=!1,this.cursor=new NO(e,t>n?-1:1),this.pos=t>n?e.length:0,this.from=Math.min(t,n),this.to=Math.max(t,n)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value=``,this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let n=t<0?this.pos-this.from:this.to-this.pos;e>n&&(e=n),n-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=n?r:t<0?r.slice(r.length-n):r.slice(0,n),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=``}},FO=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value=``,this.done=!1}next(e=0){let{done:t,lineBreak:n,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value=``,this.afterBreak=!1):t?(this.done=!0,this.value=``):n?this.afterBreak?this.value=``:(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<`u`&&(DO.prototype[Symbol.iterator]=function(){return this.iter()},NO.prototype[Symbol.iterator]=PO.prototype[Symbol.iterator]=FO.prototype[Symbol.iterator]=function(){return this});var IO=class{constructor(e,t,n,r){this.from=e,this.to=t,this.number=n,this.text=r}get length(){return this.to-this.from}};function LO(e,t,n){return t=Math.max(0,Math.min(e.length,t)),[t,Math.max(t,Math.min(e.length,n))]}function RO(e,t,n=!0,r=!0){return bO(e,t,n,r)}function zO(e){return e>=56320&&e<57344}function BO(e){return e>=55296&&e<56320}function VO(e,t){let n=e.charCodeAt(t);if(!BO(n)||t+1==e.length)return n;let r=e.charCodeAt(t+1);return zO(r)?(n-55296<<10)+(r-56320)+65536:n}function HO(e){return e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode((e>>10)+55296,(e&1023)+56320))}function UO(e){return e<65536?1:2}var WO=/\r\n?|\n/,GO=(function(e){return e[e.Simple=0]=`Simple`,e[e.TrackDel=1]=`TrackDel`,e[e.TrackBefore=2]=`TrackBefore`,e[e.TrackAfter=3]=`TrackAfter`,e})(GO||={}),KO=class e{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;t<this.sections.length;t+=2)e+=this.sections[t];return e}get newLength(){let e=0;for(let t=0;t<this.sections.length;t+=2){let n=this.sections[t+1];e+=n<0?this.sections[t]:n}return e}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(e){for(let t=0,n=0,r=0;t<this.sections.length;){let i=this.sections[t++],a=this.sections[t++];a<0?(e(n,r,i),r+=i):r+=a,n+=i}}iterChangedRanges(e,t=!1){XO(this,e,t)}get invertedDesc(){let t=[];for(let e=0;e<this.sections.length;){let n=this.sections[e++],r=this.sections[e++];r<0?t.push(n,r):t.push(r,n)}return new e(t)}composeDesc(e){return this.empty?e:e.empty?this:QO(this,e)}mapDesc(e,t=!1){return e.empty?this:ZO(this,e,t)}mapPos(e,t=-1,n=GO.Simple){let r=0,i=0;for(let a=0;a<this.sections.length;){let o=this.sections[a++],s=this.sections[a++],c=r+o;if(s<0){if(c>e)return i+(e-r);i+=o}else{if(n!=GO.Simple&&c>=e&&(n==GO.TrackDel&&r<e&&c>e||n==GO.TrackBefore&&r<e||n==GO.TrackAfter&&c>e))return null;if(c>e||c==e&&t<0&&!o)return e==r||t<0?i:i+s;i+=s}r=c}if(e>r)throw RangeError(`Position ${e} is out of range for changeset of length ${r}`);return i}touchesRange(e,t=e){for(let n=0,r=0;n<this.sections.length&&r<=t;){let i=this.sections[n++],a=this.sections[n++],o=r+i;if(a>=0&&r<=t&&o>=e)return r<e&&o>t?`cover`:!0;r=o}return!1}toString(){let e=``;for(let t=0;t<this.sections.length;){let n=this.sections[t++],r=this.sections[t++];e+=(e?` `:``)+n+(r>=0?`:`+r:``)}return e}toJSON(){return this.sections}static fromJSON(t){if(!Array.isArray(t)||t.length%2||t.some(e=>typeof e!=`number`))throw RangeError(`Invalid JSON representation of ChangeDesc`);return new e(t)}static create(t){return new e(t)}},qO=class e extends KO{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw RangeError(`Applying change set to a document with the wrong length`);return XO(this,(t,n,r,i,a)=>e=e.replace(r,r+(n-t),a),!1),e}mapDesc(e,t=!1){return ZO(this,e,t,!0)}invert(t){let n=this.sections.slice(),r=[];for(let e=0,i=0;e<n.length;e+=2){let a=n[e],o=n[e+1];if(o>=0){n[e]=o,n[e+1]=a;let s=e>>1;for(;r.length<s;)r.push(DO.empty);r.push(a?t.slice(i,i+a):DO.empty)}i+=a}return new e(n,r)}compose(e){return this.empty?e:e.empty?this:QO(this,e,!0)}map(e,t=!1){return e.empty?this:ZO(this,e,t,!0)}iterChanges(e,t=!1){XO(this,e,t)}get desc(){return KO.create(this.sections)}filter(t){let n=[],r=[],i=[],a=new $O(this);done:for(let e=0,o=0;;){let s=e==t.length?1e9:t[e++];for(;o<s||o==s&&a.len==0;){if(a.done)break done;let e=Math.min(a.len,s-o);JO(i,e,-1);let t=a.ins==-1?-1:a.off==0?a.ins:0;JO(n,e,t),t>0&&YO(r,n,a.text),a.forward(e),o+=e}let c=t[e++];for(;o<c;){if(a.done)break done;let e=Math.min(a.len,c-o);JO(n,e,-1),JO(i,e,a.ins==-1?-1:a.off==0?a.ins:0),a.forward(e),o+=e}}return{changes:new e(n,r),filtered:KO.create(i)}}toJSON(){let e=[];for(let t=0;t<this.sections.length;t+=2){let n=this.sections[t],r=this.sections[t+1];r<0?e.push(n):r==0?e.push([n]):e.push([n].concat(this.inserted[t>>1].toJSON()))}return e}static of(t,n,r){let i=[],a=[],o=0,s=null;function c(t=!1){if(!t&&!i.length)return;o<n&&JO(i,n-o,-1);let r=new e(i,a);s=s?s.compose(r.map(s)):r,i=[],a=[],o=0}function l(t){if(Array.isArray(t))for(let e of t)l(e);else if(t instanceof e){if(t.length!=n)throw RangeError(`Mismatched change set length (got ${t.length}, expected ${n})`);c(),s=s?s.compose(t.map(s)):t}else{let{from:e,to:s=e,insert:l}=t;if(e>s||e<0||s>n)throw RangeError(`Invalid change range ${e} to ${s} (in doc of length ${n})`);let u=l?typeof l==`string`?DO.of(l.split(r||WO)):l:DO.empty,d=u.length;if(e==s&&d==0)return;e<o&&c(),e>o&&JO(i,e-o,-1),JO(i,s-e,d),YO(a,i,u),o=s}}return l(t),c(!s),s}static empty(t){return new e(t?[t,-1]:[],[])}static fromJSON(t){if(!Array.isArray(t))throw RangeError(`Invalid JSON representation of ChangeSet`);let n=[],r=[];for(let e=0;e<t.length;e++){let i=t[e];if(typeof i==`number`)n.push(i,-1);else if(!Array.isArray(i)||typeof i[0]!=`number`||i.some((e,t)=>t&&typeof e!=`string`))throw RangeError(`Invalid JSON representation of ChangeSet`);else if(i.length==1)n.push(i[0],0);else{for(;r.length<e;)r.push(DO.empty);r[e]=DO.of(i.slice(1)),n.push(i[0],r[e].length)}}return new e(n,r)}static createSet(t,n){return new e(t,n)}};function JO(e,t,n,r=!1){if(t==0&&n<=0)return;let i=e.length-2;i>=0&&n<=0&&n==e[i+1]?e[i]+=t:i>=0&&t==0&&e[i]==0?e[i+1]+=n:r?(e[i]+=t,e[i+1]+=n):e.push(t,n)}function YO(e,t,n){if(n.length==0)return;let r=t.length-2>>1;if(r<e.length)e[e.length-1]=e[e.length-1].append(n);else{for(;e.length<r;)e.push(DO.empty);e.push(n)}}function XO(e,t,n){let r=e.inserted;for(let i=0,a=0,o=0;o<e.sections.length;){let s=e.sections[o++],c=e.sections[o++];if(c<0)i+=s,a+=s;else{let l=i,u=a,d=DO.empty;for(;l+=s,u+=c,c&&r&&(d=d.append(r[o-2>>1])),!(n||o==e.sections.length||e.sections[o+1]<0);)s=e.sections[o++],c=e.sections[o++];t(i,l,a,u,d),i=l,a=u}}}function ZO(e,t,n,r=!1){let i=[],a=r?[]:null,o=new $O(e),s=new $O(t);for(let e=-1;;)if(o.done&&s.len||s.done&&o.len)throw Error(`Mismatched change set lengths`);else if(o.ins==-1&&s.ins==-1){let e=Math.min(o.len,s.len);JO(i,e,-1),o.forward(e),s.forward(e)}else if(s.ins>=0&&(o.ins<0||e==o.i||o.off==0&&(s.len<o.len||s.len==o.len&&!n))){let t=s.len;for(JO(i,s.ins,-1);t;){let n=Math.min(o.len,t);o.ins>=0&&e<o.i&&o.len<=n&&(JO(i,0,o.ins),a&&YO(a,i,o.text),e=o.i),o.forward(n),t-=n}s.next()}else if(o.ins>=0){let t=0,n=o.len;for(;n;)if(s.ins==-1){let e=Math.min(n,s.len);t+=e,n-=e,s.forward(e)}else if(s.ins==0&&s.len<n)n-=s.len,s.next();else break;JO(i,t,e<o.i?o.ins:0),a&&e<o.i&&YO(a,i,o.text),e=o.i,o.forward(o.len-n)}else if(o.done&&s.done)return a?qO.createSet(i,a):KO.create(i);else throw Error(`Mismatched change set lengths`)}function QO(e,t,n=!1){let r=[],i=n?[]:null,a=new $O(e),o=new $O(t);for(let e=!1;;)if(a.done&&o.done)return i?qO.createSet(r,i):KO.create(r);else if(a.ins==0)JO(r,a.len,0,e),a.next();else if(o.len==0&&!o.done)JO(r,0,o.ins,e),i&&YO(i,r,o.text),o.next();else if(a.done||o.done)throw Error(`Mismatched change set lengths`);else{let t=Math.min(a.len2,o.len),n=r.length;if(a.ins==-1){let n=o.ins==-1?-1:o.off?0:o.ins;JO(r,t,n,e),i&&n&&YO(i,r,o.text)}else o.ins==-1?(JO(r,a.off?0:a.len,t,e),i&&YO(i,r,a.textBit(t))):(JO(r,a.off?0:a.len,o.off?0:o.ins,e),i&&!o.off&&YO(i,r,o.text));e=(a.ins>t||o.ins>=0&&o.len>t)&&(e||r.length>n),a.forward2(t),o.forward(t)}}var $O=class{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i<e.length?(this.len=e[this.i++],this.ins=e[this.i++]):(this.len=0,this.ins=-2),this.off=0}get done(){return this.ins==-2}get len2(){return this.ins<0?this.len:this.ins}get text(){let{inserted:e}=this.set,t=this.i-2>>1;return t>=e.length?DO.empty:e[t]}textBit(e){let{inserted:t}=this.set,n=this.i-2>>1;return n>=t.length&&!e?DO.empty:t[n].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}},ek=class e{constructor(e,t,n,r){this.from=e,this.to=t,this.flags=n,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(t,n=-1){let r,i;return this.empty?r=i=t.mapPos(this.from,n):(r=t.mapPos(this.from,1),i=t.mapPos(this.to,-1)),r==this.from&&i==this.to?this:new e(r,i,this.flags,this.goalColumn)}extend(e,t=e,n=0){if(e<=this.anchor&&t>=this.anchor)return Q.range(e,t,void 0,void 0,n);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return Q.range(this.anchor,r,void 0,void 0,n)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!=`number`||typeof e.head!=`number`)throw RangeError(`Invalid JSON representation for SelectionRange`);return Q.range(e.anchor,e.head)}static create(t,n,r,i){return new e(t,n,r,i)}},Q=class e{constructor(e,t){this.ranges=e,this.mainIndex=t}map(t,n=-1){return t.empty?this:e.create(this.ranges.map(e=>e.map(t,n)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let n=0;n<this.ranges.length;n++)if(!this.ranges[n].eq(e.ranges[n],t))return!1;return!0}get main(){return this.ranges[this.mainIndex]}asSingle(){return this.ranges.length==1?this:new e([this.main],0)}addRange(t,n=!0){return e.create([t].concat(this.ranges),n?0:this.mainIndex+1)}replaceRange(t,n=this.mainIndex){let r=this.ranges.slice();return r[n]=t,e.create(r,this.mainIndex)}toJSON(){return{ranges:this.ranges.map(e=>e.toJSON()),main:this.mainIndex}}static fromJSON(t){if(!t||!Array.isArray(t.ranges)||typeof t.main!=`number`||t.main>=t.ranges.length)throw RangeError(`Invalid JSON representation for EditorSelection`);return new e(t.ranges.map(e=>ek.fromJSON(e)),t.main)}static single(t,n=t){return new e([e.range(t,n)],0)}static create(t,n=0){if(t.length==0)throw RangeError(`A selection needs at least one range`);for(let r=0,i=0;i<t.length;i++){let a=t[i];if(a.empty?a.from<=r:a.from<r)return e.normalized(t.slice(),n);r=a.to}return new e(t,n)}static cursor(e,t=0,n,r){return ek.create(e,e,(t==0?0:t<0?8:16)|(n==null?7:Math.min(6,n)),r)}static range(e,t,n,r,i){let a=r==null?7:Math.min(6,r);return!i&&e!=t&&(i=t<e?1:-1),i&&(a|=i<0?8:16),t<e?ek.create(t,e,a|32,n):ek.create(e,t,a,n)}static undirectionalRange(e,t){return ek.create(e,t,64,void 0)}static normalized(t,n=0){let r=t[n];t.sort((e,t)=>e.from-t.from),n=t.indexOf(r);for(let r=1;r<t.length;r++){let i=t[r],a=t[r-1];if(i.empty?i.from<=a.to:i.from<a.to){let o=a.from,s=Math.max(i.to,a.to);r<=n&&n--,t.splice(--r,2,i.anchor>i.head?e.range(s,o):e.range(o,s))}}return new e(t,n)}};function tk(e,t){for(let n of e.ranges)if(n.to>t)throw RangeError(`Selection points outside of document`)}var nk=0,rk=class e{constructor(e,t,n,r,i){this.combine=e,this.compareInput=t,this.compare=n,this.isStatic=r,this.id=nk++,this.default=e([]),this.extensions=typeof i==`function`?i(this):i}get reader(){return this}static define(t={}){return new e(t.combine||(e=>e),t.compareInput||((e,t)=>e===t),t.compare||(t.combine?(e,t)=>e===t:ik),!!t.static,t.enables)}of(e){return new ak([],this,0,e)}compute(e,t){if(this.isStatic)throw Error(`Can't compute a static facet`);return new ak(e,this,1,t)}computeN(e,t){if(this.isStatic)throw Error(`Can't compute a static facet`);return new ak(e,this,2,t)}from(e,t){return t||=e=>e,this.compute([e],n=>t(n.field(e)))}};function ik(e,t){return e==t||e.length==t.length&&e.every((e,n)=>e===t[n])}var ak=class{constructor(e,t,n,r){this.dependencies=e,this.facet=t,this.type=n,this.value=r,this.id=nk++}dynamicSlot(e){let t=this.value,n=this.facet.compareInput,r=this.id,i=e[r]>>1,a=this.type==2,o=!1,s=!1,c=[];for(let t of this.dependencies)t==`doc`?o=!0:t==`selection`?s=!0:(e[t.id]??1)&1||c.push(e[t.id]);return{create(e){return e.values[i]=t(e),1},update(e,r){if(o&&r.docChanged||s&&(r.docChanged||r.selection)||sk(e,c)){let r=t(e);if(a?!ok(r,e.values[i],n):!n(r,e.values[i]))return e.values[i]=r,1}return 0},reconfigure:(e,o)=>{let s,c=o.config.address[r];if(c!=null){let r=bk(o,c);if(this.dependencies.every(t=>t instanceof rk?o.facet(t)===e.facet(t):t instanceof uk?o.field(t,!1)==e.field(t,!1):!0)||(a?ok(s=t(e),r,n):n(s=t(e),r)))return e.values[i]=r,0}else s=t(e);return e.values[i]=s,1}}}get extension(){return this}};function ok(e,t,n){if(e.length!=t.length)return!1;for(let r=0;r<e.length;r++)if(!n(e[r],t[r]))return!1;return!0}function sk(e,t){let n=!1;for(let r of t)yk(e,r)&1&&(n=!0);return n}function ck(e,t,n){let r=n.map(t=>e[t.id]),i=n.map(e=>e.type),a=r.filter(e=>!(e&1)),o=e[t.id]>>1;function s(e){let n=[];for(let t=0;t<r.length;t++){let a=bk(e,r[t]);if(i[t]==2)for(let e of a)n.push(e);else n.push(a)}return t.combine(n)}return{create(e){for(let t of r)yk(e,t);return e.values[o]=s(e),1},update(e,n){if(!sk(e,a))return 0;let r=s(e);return t.compare(r,e.values[o])?0:(e.values[o]=r,1)},reconfigure(e,i){let a=sk(e,r),c=i.config.facets[t.id],l=i.facet(t);if(c&&!a&&ik(n,c))return e.values[o]=l,0;let u=s(e);return t.compare(u,l)?(e.values[o]=l,0):(e.values[o]=u,1)}}}var lk=rk.define({static:!0}),uk=class e{constructor(e,t,n,r,i){this.id=e,this.createF=t,this.updateF=n,this.compareF=r,this.spec=i,this.provides=void 0}static define(t){let n=new e(nk++,t.create,t.update,t.compare||((e,t)=>e===t),t);return t.provide&&(n.provides=t.provide(n)),n}create(e){return(e.facet(lk).find(e=>e.field==this)?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:e=>(e.values[t]=this.create(e),1),update:(e,n)=>{let r=e.values[t],i=this.updateF(r,n);return this.compareF(r,i)?0:(e.values[t]=i,1)},reconfigure:(e,n)=>{let r=e.facet(lk),i=n.facet(lk),a;return(a=r.find(e=>e.field==this))&&a!=i.find(e=>e.field==this)?(e.values[t]=a.create(e),1):n.config.address[this.id]==null?(e.values[t]=this.create(e),1):(e.values[t]=n.field(this),0)}}}init(e){return[this,lk.of({field:this,create:e})]}get extension(){return this}},dk={lowest:4,low:3,default:2,high:1,highest:0};function fk(e){return t=>new mk(t,e)}var pk={highest:fk(dk.highest),high:fk(dk.high),default:fk(dk.default),low:fk(dk.low),lowest:fk(dk.lowest)},mk=class{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}},hk=class e{of(e){return new gk(this,e)}reconfigure(t){return e.reconfigure.of({compartment:this,extension:t})}get(e){return e.config.compartments.get(this)}},gk=class{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}},_k=class e{constructor(e,t,n,r,i,a){for(this.base=e,this.compartments=t,this.dynamicSlots=n,this.address=r,this.staticValues=i,this.facets=a,this.statusTemplate=[];this.statusTemplate.length<n.length;)this.statusTemplate.push(0)}staticFacet(e){let t=this.address[e.id];return t==null?e.default:this.staticValues[t>>1]}static resolve(t,n,r){let i=[],a=Object.create(null),o=new Map;for(let e of vk(t,n,o))e instanceof uk?i.push(e):(a[e.facet.id]||(a[e.facet.id]=[])).push(e);let s=Object.create(null),c=[],l=[];for(let e of i)s[e.id]=l.length<<1,l.push(t=>e.slot(t));let u=r?.config.facets;for(let e in a){let t=a[e],n=t[0].facet,i=u&&u[e]||[];if(t.every(e=>e.type==0)){if(s[n.id]=c.length<<1|1,ik(i,t))c.push(r.facet(n));else{let e=n.combine(t.map(e=>e.value));c.push(r&&n.compare(e,r.facet(n))?r.facet(n):e)}}else{for(let e of t)e.type==0?(s[e.id]=c.length<<1|1,c.push(e.value)):(s[e.id]=l.length<<1,l.push(t=>e.dynamicSlot(t)));s[n.id]=l.length<<1,l.push(e=>ck(e,n,t))}}let d=l.map(e=>e(s));return new e(t,o,d,s,c,a)}};function vk(e,t,n){let r=[[],[],[],[],[]],i=new Map;function a(e,o){let s=i.get(e);if(s!=null){if(s<=o)return;let t=r[s].indexOf(e);t>-1&&r[s].splice(t,1),e instanceof gk&&n.delete(e.compartment)}if(i.set(e,o),Array.isArray(e))for(let t of e)a(t,o);else if(e instanceof gk){if(n.has(e.compartment))throw RangeError(`Duplicate use of compartment in extensions`);let r=t.get(e.compartment)||e.inner;n.set(e.compartment,r),a(r,o)}else if(e instanceof mk)a(e.inner,e.prec);else if(e instanceof uk)r[o].push(e),e.provides&&a(e.provides,o);else if(e instanceof ak)r[o].push(e),e.facet.extensions&&a(e.facet.extensions,dk.default);else{let t=e.extension;if(!t)throw Error(`Unrecognized extension value in extension set (${e}).`);if(t==e)throw Error(`Unrecognized extension value in extension set (${e}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);a(t,o)}}return a(e,dk.default),r.reduce((e,t)=>e.concat(t))}function yk(e,t){if(t&1)return 2;let n=t>>1,r=e.status[n];if(r==4)throw Error(`Cyclic dependency between fields and/or facets`);if(r&2)return r;e.status[n]=4;let i=e.computeSlot(e,e.config.dynamicSlots[n]);return e.status[n]=2|i}function bk(e,t){return t&1?e.config.staticValues[t>>1]:e.values[t>>1]}var xk=rk.define(),Sk=rk.define({combine:e=>e.some(e=>e),static:!0}),Ck=rk.define({combine:e=>e.length?e[0]:void 0,static:!0}),wk=rk.define(),Tk=rk.define(),Ek=rk.define(),Dk=rk.define({combine:e=>e.length?e[0]:!1}),Ok=class{constructor(e,t){this.type=e,this.value=t}static define(){return new kk}},kk=class{of(e){return new Ok(this,e)}},Ak=class{constructor(e){this.map=e}of(e){return new jk(this,e)}},jk=class e{constructor(e,t){this.type=e,this.value=t}map(t){let n=this.type.map(this.value,t);return n===void 0?void 0:n==this.value?this:new e(this.type,n)}is(e){return this.type==e}static define(e={}){return new Ak(e.map||(e=>e))}static mapEffects(e,t){if(!e.length)return e;let n=[];for(let r of e){let e=r.map(t);e&&n.push(e)}return n}};jk.reconfigure=jk.define(),jk.appendConfig=jk.define();var Mk=class e{constructor(t,n,r,i,a,o){this.startState=t,this.changes=n,this.selection=r,this.effects=i,this.annotations=a,this.scrollIntoView=o,this._doc=null,this._state=null,r&&tk(r,n.newLength),a.some(t=>t.type==e.time)||(this.annotations=a.concat(e.time.of(Date.now())))}static create(t,n,r,i,a,o){return new e(t,n,r,i,a,o)}get newDoc(){return this._doc||=this.changes.apply(this.startState.doc)}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(t){let n=this.annotation(e.userEvent);return!!(n&&(n==t||n.length>t.length&&n.slice(0,t.length)==t&&n[t.length]==`.`))}};Mk.time=Ok.define(),Mk.userEvent=Ok.define(),Mk.addToHistory=Ok.define(),Mk.remote=Ok.define();function Nk(e,t){let n=[];for(let r=0,i=0;;){let a,o;if(r<e.length&&(i==t.length||t[i]>=e[r]))a=e[r++],o=e[r++];else if(i<t.length)a=t[i++],o=t[i++];else return n;!n.length||n[n.length-1]<a?n.push(a,o):n[n.length-1]<o&&(n[n.length-1]=o)}}function Pk(e,t,n){let r,i,a;return n?(r=t.changes,i=qO.empty(t.changes.length),a=e.changes.compose(t.changes)):(r=t.changes.map(e.changes),i=e.changes.mapDesc(t.changes,!0),a=e.changes.compose(r)),{changes:a,selection:t.selection?t.selection.map(i):e.selection?.map(r),effects:jk.mapEffects(e.effects,r).concat(jk.mapEffects(t.effects,i)),annotations:e.annotations.length?e.annotations.concat(t.annotations):t.annotations,scrollIntoView:e.scrollIntoView||t.scrollIntoView}}function Fk(e,t,n){let r=t.selection,i=Bk(t.annotations);return t.userEvent&&(i=i.concat(Mk.userEvent.of(t.userEvent))),{changes:t.changes instanceof qO?t.changes:qO.of(t.changes||[],n,e.facet(Ck)),selection:r&&(r instanceof Q?r:Q.single(r.anchor,r.head)),effects:Bk(t.effects),annotations:i,scrollIntoView:!!t.scrollIntoView}}function Ik(e,t,n){let r=Fk(e,t.length?t[0]:{},e.doc.length);t.length&&t[0].filter===!1&&(n=!1);for(let i=1;i<t.length;i++){t[i].filter===!1&&(n=!1);let a=!!t[i].sequential;r=Pk(r,Fk(e,t[i],a?r.changes.newLength:e.doc.length),a)}let i=Mk.create(e,r.changes,r.selection,r.effects,r.annotations,r.scrollIntoView);return Rk(n?Lk(i):i)}function Lk(e){let t=e.startState,n=!0;for(let r of t.facet(wk)){let t=r(e);if(t===!1){n=!1;break}Array.isArray(t)&&(n=n===!0?t:Nk(n,t))}if(n!==!0){let r,i;if(n===!1)i=e.changes.invertedDesc,r=qO.empty(t.doc.length);else{let t=e.changes.filter(n);r=t.changes,i=t.filtered.mapDesc(t.changes).invertedDesc}e=Mk.create(t,r,e.selection&&e.selection.map(i),jk.mapEffects(e.effects,i),e.annotations,e.scrollIntoView)}let r=t.facet(Tk);for(let n=r.length-1;n>=0;n--){let i=r[n](e);e=i instanceof Mk?i:Array.isArray(i)&&i.length==1&&i[0]instanceof Mk?i[0]:Ik(t,Bk(i),!1)}return e}function Rk(e){let t=e.startState,n=t.facet(Ek),r=e;for(let i=n.length-1;i>=0;i--){let a=n[i](e);a&&Object.keys(a).length&&(r=Pk(r,Fk(t,a,e.changes.newLength),!0))}return r==e?e:Mk.create(t,e.changes,e.selection,r.effects,r.annotations,r.scrollIntoView)}var zk=[];function Bk(e){return e==null?zk:Array.isArray(e)?e:[e]}var Vk=(function(e){return e[e.Word=0]=`Word`,e[e.Space=1]=`Space`,e[e.Other=2]=`Other`,e})(Vk||={}),Hk=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Uk;try{Uk=RegExp(`[\\p{Alphabetic}\\p{Number}_]`,`u`)}catch{}function Wk(e){if(Uk)return Uk.test(e);for(let t=0;t<e.length;t++){let n=e[t];if(/\w/.test(n)||n>``&&(n.toUpperCase()!=n.toLowerCase()||Hk.test(n)))return!0}return!1}function Gk(e){return t=>{if(!/\S/.test(t))return Vk.Space;if(Wk(t))return Vk.Word;for(let n=0;n<e.length;n++)if(t.indexOf(e[n])>-1)return Vk.Word;return Vk.Other}}var Kk=class e{constructor(e,t,n,r,i,a){this.config=e,this.doc=t,this.selection=n,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=i,a&&(a._state=this);for(let e=0;e<this.config.dynamicSlots.length;e++)yk(this,e<<1);this.computeSlot=null}field(e,t=!0){let n=this.config.address[e.id];if(n==null){if(t)throw RangeError(`Field is not present in this state`);return}return yk(this,n),bk(this,n)}update(...e){return Ik(this,e,!0)}applyTransaction(t){let n=this.config,{base:r,compartments:i}=n;for(let e of t.effects)e.is(hk.reconfigure)?(n&&=(i=new Map,n.compartments.forEach((e,t)=>i.set(t,e)),null),i.set(e.value.compartment,e.value.extension)):e.is(jk.reconfigure)?(n=null,r=e.value):e.is(jk.appendConfig)&&(n=null,r=Bk(r).concat(e.value));let a;n?a=t.startState.values.slice():(n=_k.resolve(r,i,this),a=new e(n,this.doc,this.selection,n.dynamicSlots.map(()=>null),(e,t)=>t.reconfigure(e,this),null).values);let o=t.startState.facet(Sk)?t.newSelection:t.newSelection.asSingle();new e(n,t.newDoc,o,a,(e,n)=>n.update(e,t),t)}replaceSelection(e){return typeof e==`string`&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:Q.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,n=e(t.ranges[0]),r=this.changes(n.changes),i=[n.range],a=Bk(n.effects);for(let n=1;n<t.ranges.length;n++){let o=e(t.ranges[n]),s=this.changes(o.changes),c=s.map(r);for(let e=0;e<n;e++)i[e]=i[e].map(c);let l=r.mapDesc(s,!0);i.push(o.range.map(l)),r=r.compose(c),a=jk.mapEffects(a,c).concat(jk.mapEffects(Bk(o.effects),l))}return{changes:r,selection:Q.create(i,t.mainIndex),effects:a}}changes(t=[]){return t instanceof qO?t:qO.of(t,this.doc.length,this.facet(e.lineSeparator))}toText(t){return DO.of(t.split(this.facet(e.lineSeparator)||WO))}sliceDoc(e=0,t=this.doc.length){return this.doc.sliceString(e,t,this.lineBreak)}facet(e){let t=this.config.address[e.id];return t==null?e.default:(yk(this,t),bk(this,t))}toJSON(e){let t={doc:this.sliceDoc(),selection:this.selection.toJSON()};if(e)for(let n in e){let r=e[n];r instanceof uk&&this.config.address[r.id]!=null&&(t[n]=r.spec.toJSON(this.field(e[n]),this))}return t}static fromJSON(t,n={},r){if(!t||typeof t.doc!=`string`)throw RangeError(`Invalid JSON representation for EditorState`);let i=[];if(r){for(let e in r)if(Object.prototype.hasOwnProperty.call(t,e)){let n=r[e],a=t[e];i.push(n.init(e=>n.spec.fromJSON(a,e)))}}return e.create({doc:t.doc,selection:Q.fromJSON(t.selection),extensions:n.extensions?i.concat([n.extensions]):i})}static create(t={}){let n=_k.resolve(t.extensions||[],new Map),r=t.doc instanceof DO?t.doc:DO.of((t.doc||``).split(n.staticFacet(e.lineSeparator)||WO)),i=t.selection?t.selection instanceof Q?t.selection:Q.single(t.selection.anchor,t.selection.head):Q.single(0);return tk(i,r.length),n.staticFacet(Sk)||(i=i.asSingle()),new e(n,r,i,n.dynamicSlots.map(()=>null),(e,t)=>t.create(e),null)}get tabSize(){return this.facet(e.tabSize)}get lineBreak(){return this.facet(e.lineSeparator)||`
|
|
30
|
+
`}get readOnly(){return this.facet(Dk)}phrase(t,...n){for(let n of this.facet(e.phrases))if(Object.prototype.hasOwnProperty.call(n,t)){t=n[t];break}return n.length&&(t=t.replace(/\$(\$|\d*)/g,(e,t)=>{if(t==`$`)return`$`;let r=+(t||1);return!r||r>n.length?e:n[r-1]})),t}languageDataAt(e,t,n=-1){let r=[];for(let i of this.facet(xk))for(let a of i(this,t,n))Object.prototype.hasOwnProperty.call(a,e)&&r.push(a[e]);return r}charCategorizer(e){let t=this.languageDataAt(`wordChars`,e);return Gk(t.length?t[0]:``)}wordAt(e){let{text:t,from:n,length:r}=this.doc.lineAt(e),i=this.charCategorizer(e),a=e-n,o=e-n;for(;a>0;){let e=RO(t,a,!1);if(i(t.slice(e,a))!=Vk.Word)break;a=e}for(;o<r;){let e=RO(t,o);if(i(t.slice(o,e))!=Vk.Word)break;o=e}return a==o?null:Q.range(a+n,o+n)}};Kk.allowMultipleSelections=Sk,Kk.tabSize=rk.define({combine:e=>e.length?e[0]:4}),Kk.lineSeparator=Ck,Kk.readOnly=Dk,Kk.phrases=rk.define({compare(e,t){let n=Object.keys(e),r=Object.keys(t);return n.length==r.length&&n.every(n=>e[n]==t[n])}}),Kk.languageData=xk,Kk.changeFilter=wk,Kk.transactionFilter=Tk,Kk.transactionExtender=Ek,hk.reconfigure=jk.define();function qk(e,t,n={}){let r={};for(let t of e)for(let e of Object.keys(t)){let i=t[e],a=r[e];if(a===void 0)r[e]=i;else if(a!==i&&i!==void 0){if(Object.hasOwnProperty.call(n,e))r[e]=n[e](a,i);else throw Error(`Config merge conflict for field `+e)}}for(let e in t)r[e]===void 0&&(r[e]=t[e]);return r}var Jk=class{eq(e){return this==e}range(e,t=e){return Xk.create(e,t,this)}};Jk.prototype.startSide=Jk.prototype.endSide=0,Jk.prototype.point=!1,Jk.prototype.mapMode=GO.TrackDel;function Yk(e,t){return e==t||e.constructor==t.constructor&&e.eq(t)}var Xk=class e{constructor(e,t,n){this.from=e,this.to=t,this.value=n}static create(t,n,r){return new e(t,n,r)}};function Zk(e,t){return e.from-t.from||e.value.startSide-t.value.startSide}var Qk=class e{constructor(e,t,n,r){this.from=e,this.to=t,this.value=n,this.maxPoint=r}get length(){return this.to[this.to.length-1]}findIndex(e,t,n,r=0){let i=n?this.to:this.from;for(let a=r,o=i.length;;){if(a==o)return a;let r=a+o>>1,s=i[r]-e||(n?this.value[r].endSide:this.value[r].startSide)-t;if(r==a)return s>=0?a:o;s>=0?o=r:a=r+1}}between(e,t,n,r){for(let i=this.findIndex(t,-1e9,!0),a=this.findIndex(n,1e9,!1,i);i<a;i++)if(r(this.from[i]+e,this.to[i]+e,this.value[i])===!1)return!1}map(t,n){let r=[],i=[],a=[],o=-1,s=-1;for(let e=0;e<this.value.length;e++){let c=this.value[e],l=this.from[e]+t,u=this.to[e]+t,d,f;if(l==u){let e=n.mapPos(l,c.startSide,c.mapMode);if(e==null||(d=f=e,c.startSide!=c.endSide&&(f=n.mapPos(l,c.endSide),f<d)))continue}else if(d=n.mapPos(l,c.startSide),f=n.mapPos(u,c.endSide),d>f||d==f&&c.startSide>0&&c.endSide<=0)continue;(f-d||c.endSide-c.startSide)<0||(o<0&&(o=d),c.point&&(s=Math.max(s,f-d)),r.push(c),i.push(d-o),a.push(f-o))}return{mapped:r.length?new e(i,a,r,s):null,pos:o}}},$k=class e{constructor(e,t,n,r){this.chunkPos=e,this.chunk=t,this.nextLayer=n,this.maxPoint=r}static create(t,n,r,i){return new e(t,n,r,i)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(t){let{add:n=[],sort:r=!1,filterFrom:i=0,filterTo:a=this.length}=t,o=t.filter;if(n.length==0&&!o)return this;if(r&&(n=n.slice().sort(Zk)),this.isEmpty)return n.length?e.of(n):this;let s=new rA(this,null,-1).goto(0),c=0,l=[],u=new tA;for(;s.value||c<n.length;)if(c<n.length&&(s.from-n[c].from||s.startSide-n[c].value.startSide)>=0){let e=n[c++];u.addInner(e.from,e.to,e.value)||l.push(e)}else s.rangeIndex==1&&s.chunkIndex<this.chunk.length&&(c==n.length||this.chunkEnd(s.chunkIndex)<n[c].from)&&(!o||i>this.chunkEnd(s.chunkIndex)||a<this.chunkPos[s.chunkIndex])&&u.addChunk(this.chunkPos[s.chunkIndex],this.chunk[s.chunkIndex])?s.nextChunk():((!o||i>s.to||a<s.from||o(s.from,s.to,s.value))&&(u.addInner(s.from,s.to,s.value)||l.push(Xk.create(s.from,s.to,s.value))),s.next());return u.finishInner(this.nextLayer.isEmpty&&!l.length?e.empty:this.nextLayer.update({add:l,filter:o,filterFrom:i,filterTo:a}))}map(t){if(t.empty||this.isEmpty)return this;let n=[],r=[],i=-1;for(let e=0;e<this.chunk.length;e++){let a=this.chunkPos[e],o=this.chunk[e],s=t.touchesRange(a,a+o.length);if(s===!1)i=Math.max(i,o.maxPoint),n.push(o),r.push(t.mapPos(a));else if(s===!0){let{mapped:e,pos:s}=o.map(a,t);e&&(i=Math.max(i,e.maxPoint),n.push(e),r.push(s))}}let a=this.nextLayer.map(t);return n.length==0?a:new e(r,n,a||e.empty,i)}between(e,t,n){if(!this.isEmpty){for(let r=0;r<this.chunk.length;r++){let i=this.chunkPos[r],a=this.chunk[r];if(t>=i&&e<=i+a.length&&a.between(i,e-i,t-i,n)===!1)return}this.nextLayer.between(e,t,n)}}iter(e=0){return iA.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return iA.from(e).goto(t)}static compare(e,t,n,r,i=-1){let a=e.filter(e=>e.maxPoint>0||!e.isEmpty&&e.maxPoint>=i),o=t.filter(e=>e.maxPoint>0||!e.isEmpty&&e.maxPoint>=i),s=nA(a,o,n),c=new oA(a,s,i),l=new oA(o,s,i);n.iterGaps((e,t,n)=>sA(c,e,l,t,n,r)),n.empty&&n.length==0&&sA(c,0,l,0,0,r)}static eq(e,t,n=0,r){r??=1e9-1;let i=e.filter(e=>!e.isEmpty&&t.indexOf(e)<0),a=t.filter(t=>!t.isEmpty&&e.indexOf(t)<0);if(i.length!=a.length)return!1;if(!i.length)return!0;let o=nA(i,a),s=new oA(i,o,0).goto(n),c=new oA(a,o,0).goto(n);for(;;){if(s.to!=c.to||!cA(s.active,c.active)||s.point&&(!c.point||!Yk(s.point,c.point)))return!1;if(s.to>r)return!0;s.next(),c.next()}}static spans(e,t,n,r,i=-1){let a=new oA(e,null,i).goto(t),o=t,s=a.openStart;for(;;){let e=Math.min(a.to,n);if(a.point){let n=a.activeForPoint(a.to),i=a.pointFrom<t?n.length+1:a.point.startSide<0?n.length:Math.min(n.length,s);r.point(o,e,a.point,n,i,a.pointRank),s=Math.min(a.openEnd(e),n.length)}else e>o&&(r.span(o,e,a.active,s),s=a.openEnd(e));if(a.to>n)return s+(a.point&&a.to>n?1:0);o=a.to,a.next()}}static of(e,t=!1){let n=new tA;for(let r of e instanceof Xk?[e]:t?eA(e):e)n.add(r.from,r.to,r.value);return n.finish()}static join(t){if(!t.length)return e.empty;let n=t[t.length-1];for(let r=t.length-2;r>=0;r--)for(let i=t[r];i!=e.empty;i=i.nextLayer)n=new e(i.chunkPos,i.chunk,n,Math.max(i.maxPoint,n.maxPoint));return n}};$k.empty=new $k([],[],null,-1);function eA(e){if(e.length>1)for(let t=e[0],n=1;n<e.length;n++){let r=e[n];if(Zk(t,r)>0)return e.slice().sort(Zk);t=r}return e}$k.empty.nextLayer=$k.empty;var tA=class e{finishChunk(e){this.chunks.push(new Qk(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(t,n,r){this.addInner(t,n,r)||(this.nextLayer||=new e).add(t,n,r)}addInner(e,t,n){let r=e-this.lastTo||n.startSide-this.last.endSide;if(r<=0&&(e-this.lastFrom||n.startSide-this.last.startSide)<0)throw Error("Ranges must be added sorted by `from` position and `startSide`");return r<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=n,this.lastFrom=e,this.lastTo=t,this.value.push(n),n.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let n=t.value.length-1;return this.last=t.value[n],this.lastFrom=t.from[n]+e,this.lastTo=t.to[n]+e,!0}finish(){return this.finishInner($k.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=$k.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}};function nA(e,t,n){let r=new Map;for(let t of e)for(let e=0;e<t.chunk.length;e++)t.chunk[e].maxPoint<=0&&r.set(t.chunk[e],t.chunkPos[e]);let i=new Set;for(let e of t)for(let t=0;t<e.chunk.length;t++){let a=r.get(e.chunk[t]);a!=null&&(n?n.mapPos(a):a)==e.chunkPos[t]&&!n?.touchesRange(a,a+e.chunk[t].length)&&i.add(e.chunk[t])}return i}var rA=class{constructor(e,t,n,r=0){this.layer=e,this.skip=t,this.minPoint=n,this.rank=r}get startSide(){return this.value?this.value.startSide:0}get endSide(){return this.value?this.value.endSide:0}goto(e,t=-1e9){return this.chunkIndex=this.rangeIndex=0,this.gotoInner(e,t,!1),this}gotoInner(e,t,n){for(;this.chunkIndex<this.layer.chunk.length;){let t=this.layer.chunk[this.chunkIndex];if(!(this.skip&&this.skip.has(t)||this.layer.chunkEnd(this.chunkIndex)<e||t.maxPoint<this.minPoint))break;this.chunkIndex++,n=!1}if(this.chunkIndex<this.layer.chunk.length){let r=this.layer.chunk[this.chunkIndex].findIndex(e-this.layer.chunkPos[this.chunkIndex],t,!0);(!n||this.rangeIndex<r)&&this.setRangeIndex(r)}this.next()}forward(e,t){(this.to-e||this.endSide-t)<0&&this.gotoInner(e,t,!0)}next(){for(;;)if(this.chunkIndex==this.layer.chunk.length){this.from=this.to=1e9,this.value=null;break}else{let e=this.layer.chunkPos[this.chunkIndex],t=this.layer.chunk[this.chunkIndex],n=e+t.from[this.rangeIndex];if(this.from=n,this.to=e+t.to[this.rangeIndex],this.value=t.value[this.rangeIndex],this.setRangeIndex(this.rangeIndex+1),this.minPoint<0||this.value.point&&this.to-this.from>=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex<this.layer.chunk.length&&this.skip.has(this.layer.chunk[this.chunkIndex]);)this.chunkIndex++;this.rangeIndex=0}else this.rangeIndex=e}nextChunk(){this.chunkIndex++,this.rangeIndex=0,this.next()}compare(e){return this.from-e.from||this.startSide-e.startSide||this.rank-e.rank||this.to-e.to||this.endSide-e.endSide}},iA=class e{constructor(e){this.heap=e}static from(t,n=null,r=-1){let i=[];for(let e=0;e<t.length;e++)for(let a=t[e];!a.isEmpty;a=a.nextLayer)a.maxPoint>=r&&i.push(new rA(a,n,r,e));return i.length==1?i[0]:new e(i)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let n of this.heap)n.goto(e,t);for(let e=this.heap.length>>1;e>=0;e--)aA(this.heap,e);return this.next(),this}forward(e,t){for(let n of this.heap)n.forward(e,t);for(let e=this.heap.length>>1;e>=0;e--)aA(this.heap,e);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),aA(this.heap,0)}}};function aA(e,t){for(let n=e[t];;){let r=(t<<1)+1;if(r>=e.length)break;let i=e[r];if(r+1<e.length&&i.compare(e[r+1])>=0&&(i=e[r+1],r++),n.compare(i)<0)break;e[r]=n,e[t]=i,t=r}}var oA=class{constructor(e,t,n){this.minPoint=n,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=iA.from(e,t,n)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){lA(this.active,e),lA(this.activeTo,e),lA(this.activeRank,e),this.minActive=dA(this.active,this.activeTo)}addActive(e){let t=0,{value:n,to:r,rank:i}=this.cursor;for(;t<this.activeRank.length&&(i-this.activeRank[t]||r-this.activeTo[t])>0;)t++;uA(this.active,t,n),uA(this.activeTo,t,r),uA(this.activeRank,t,i),e&&uA(e,t,this.cursor.from),this.minActive=dA(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let n=this.openStart<0?[]:null;for(;;){let r=this.minActive;if(r>-1&&(this.activeTo[r]-this.cursor.from||this.active[r].endSide-this.cursor.startSide)<0){if(this.activeTo[r]>e){this.to=this.activeTo[r],this.endSide=this.active[r].endSide;break}this.removeActive(r),n&&lA(n,r)}else if(!this.cursor.value){this.to=this.endSide=1e9;break}else if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let e=this.cursor.value;if(!e.point)this.addActive(n),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from<this.cursor.to)this.cursor.next();else{this.point=e,this.pointFrom=this.cursor.from,this.pointRank=this.cursor.rank,this.to=this.cursor.to,this.endSide=e.endSide,this.cursor.next(),this.forward(this.to,this.endSide);break}}}if(n){this.openStart=0;for(let t=n.length-1;t>=0&&n[t]<e;t--)this.openStart++}}activeForPoint(e){if(!this.active.length)return this.active;let t=[];for(let n=this.active.length-1;n>=0&&!(this.activeRank[n]<this.pointRank);n--)(this.activeTo[n]>e||this.activeTo[n]==e&&this.active[n].endSide>=this.point.endSide)&&t.push(this.active[n]);return t.reverse()}openEnd(e){let t=0;for(let n=this.activeTo.length-1;n>=0&&this.activeTo[n]>e;n--)t++;return t}};function sA(e,t,n,r,i,a){e.goto(t),n.goto(r);let o=r+i,s=r,c=r-t,l=!!a.boundChange;for(let t=!1;;){let r=e.to+c-n.to,i=r||e.endSide-n.endSide,u=i<0?e.to+c:n.to,d=Math.min(u,o);if(e.point||n.point?(e.point&&n.point&&Yk(e.point,n.point)&&cA(e.activeForPoint(e.to),n.activeForPoint(n.to))||a.comparePoint(s,d,e.point,n.point),t=!1):(t&&a.boundChange(s),d>s&&!cA(e.active,n.active)&&a.compareRange(s,d,e.active,n.active),l&&d<o&&(r||e.openEnd(u)!=n.openEnd(u))&&(t=!0)),u>o)break;s=u,i<=0&&e.next(),i>=0&&n.next()}}function cA(e,t){if(e.length!=t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!=t[n]&&!Yk(e[n],t[n]))return!1;return!0}function lA(e,t){for(let n=t,r=e.length-1;n<r;n++)e[n]=e[n+1];e.pop()}function uA(e,t,n){for(let n=e.length-1;n>=t;n--)e[n+1]=e[n];e[t]=n}function dA(e,t){let n=-1,r=1e9;for(let i=0;i<t.length;i++)(t[i]-r||e[i].endSide-e[n].endSide)<0&&(n=i,r=t[i]);return n}function fA(e,t,n=e.length){let r=0;for(let i=0;i<n&&i<e.length;)e.charCodeAt(i)==9?(r+=t-r%t,i++):(r++,i=RO(e,i));return r}function pA(e,t,n,r){for(let r=0,i=0;;){if(i>=t)return r;if(r==e.length)break;i+=e.charCodeAt(r)==9?n-i%n:1,r=RO(e,r)}return r===!0?-1:e.length}var mA=`ͼ`,hA=typeof Symbol>`u`?`__ͼ`:Symbol.for(mA),gA=typeof Symbol>`u`?`__styleSet`+Math.floor(Math.random()*1e8):Symbol(`styleSet`),_A=typeof globalThis<`u`?globalThis:typeof window<`u`?window:{},vA=class{constructor(e,t){this.rules=[];let{finish:n}=t||{};function r(e){return/^@/.test(e)?[e]:e.split(/,\s*/)}function i(e,t,a,o){let s=[],c=/^@(\w+)\b/.exec(e[0]),l=c&&c[1]==`keyframes`;if(c&&t==null)return a.push(e[0]+`;`);for(let n in t){let o=t[n];if(/&/.test(n))i(n.split(/,\s*/).map(t=>e.map(e=>t.replace(/&/,e))).reduce((e,t)=>e.concat(t)),o,a);else if(o&&typeof o==`object`){if(!c)throw RangeError(`The value of a property (`+n+`) should be a primitive value.`);i(r(n),o,s,l)}else o!=null&&s.push(n.replace(/_.*/,``).replace(/[A-Z]/g,e=>`-`+e.toLowerCase())+`: `+o+`;`)}(s.length||l)&&a.push((n&&!c&&!o?e.map(n):e).join(`, `)+` {`+s.join(` `)+`}`)}for(let t in e)i(r(t),e[t],this.rules)}getRules(){return this.rules.join(`
|
|
31
|
+
`)}static newName(){let e=_A[hA]||1;return _A[hA]=e+1,mA+e.toString(36)}static mount(e,t,n){let r=e[gA],i=n&&n.nonce;r?i&&r.setNonce(i):r=new bA(e,i),r.mount(Array.isArray(t)?t:[t],e)}},yA=new Map,bA=class{constructor(e,t){let n=e.ownerDocument||e,r=n.defaultView;if(!e.head&&e.adoptedStyleSheets&&r.CSSStyleSheet){let t=yA.get(n);if(t)return e[gA]=t;this.sheet=new r.CSSStyleSheet,yA.set(n,this)}else this.styleTag=n.createElement(`style`),t&&this.styleTag.setAttribute(`nonce`,t);this.modules=[],e[gA]=this}mount(e,t){let n=this.sheet,r=0,i=0;for(let t=0;t<e.length;t++){let a=e[t],o=this.modules.indexOf(a);if(o<i&&o>-1&&(this.modules.splice(o,1),i--,o=-1),o==-1){if(this.modules.splice(i++,0,a),n)for(let e=0;e<a.rules.length;e++)n.insertRule(a.rules[e],r++)}else{for(;i<o;)r+=this.modules[i++].rules.length;r+=a.rules.length,i++}}if(n)t.adoptedStyleSheets.indexOf(this.sheet)<0&&(t.adoptedStyleSheets=[this.sheet,...t.adoptedStyleSheets]);else{let e=``;for(let t=0;t<this.modules.length;t++)e+=this.modules[t].getRules()+`
|
|
32
|
+
`;this.styleTag.textContent=e;let n=t.head||t;this.styleTag.parentNode!=n&&n.insertBefore(this.styleTag,n.firstChild)}}setNonce(e){this.styleTag&&this.styleTag.getAttribute(`nonce`)!=e&&this.styleTag.setAttribute(`nonce`,e)}};function xA(){var e=arguments[0];typeof e==`string`&&(e=document.createElement(e));var t=1,n=arguments[1];if(n&&typeof n==`object`&&n.nodeType==null&&!Array.isArray(n)){for(var r in n)if(Object.prototype.hasOwnProperty.call(n,r)){var i=n[r];typeof i==`string`?e.setAttribute(r,i):i!=null&&(e[r]=i)}t++}for(;t<arguments.length;t++)SA(e,arguments[t]);return e}function SA(e,t){if(typeof t==`string`)e.appendChild(document.createTextNode(t));else if(t!=null){if(t.nodeType!=null)e.appendChild(t);else if(Array.isArray(t))for(var n=0;n<t.length;n++)SA(e,t[n]);else throw RangeError(`Unsupported child node: `+t)}}var CA=typeof navigator<`u`?navigator:{userAgent:``,vendor:``,platform:``},wA=typeof document<`u`?document:{documentElement:{style:{}}},TA=/Edge\/(\d+)/.exec(CA.userAgent),EA=/MSIE \d/.test(CA.userAgent),DA=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(CA.userAgent),OA=!!(EA||DA||TA),kA=!OA&&/gecko\/(\d+)/i.test(CA.userAgent),AA=!OA&&/Chrome\/(\d+)/.exec(CA.userAgent),jA=`webkitFontSmoothing`in wA.documentElement.style,MA=!OA&&/Apple Computer/.test(CA.vendor),NA=MA&&(/Mobile\/\w+/.test(CA.userAgent)||CA.maxTouchPoints>2),PA={mac:NA||/Mac/.test(CA.platform),windows:/Win/.test(CA.platform),linux:/Linux|X11/.test(CA.platform),ie:OA,ie_version:EA?wA.documentMode||6:DA?+DA[1]:TA?+TA[1]:0,gecko:kA,gecko_version:kA?+(/Firefox\/(\d+)/.exec(CA.userAgent)||[0,0])[1]:0,chrome:!!AA,chrome_version:AA?+AA[1]:0,ios:NA,android:/Android\b/.test(CA.userAgent),webkit:jA,webkit_version:jA?+(/\bAppleWebKit\/(\d+)/.exec(CA.userAgent)||[0,0])[1]:0,safari:MA,safari_version:MA?+(/\bVersion\/(\d+(\.\d+)?)/.exec(CA.userAgent)||[0,0])[1]:0,tabSize:wA.documentElement.style.tabSize==null?`-moz-tab-size`:`tab-size`};function FA(e,t){for(let n in e)n==`class`&&t.class?t.class+=` `+e.class:n==`style`&&t.style?t.style+=`;`+e.style:t[n]=e[n];return t}var IA=Object.create(null);function LA(e,t,n){if(e==t)return!0;e||=IA,t||=IA;let r=Object.keys(e),i=Object.keys(t);if(r.length-(n&&r.indexOf(n)>-1?1:0)!=i.length-(n&&i.indexOf(n)>-1?1:0))return!1;for(let a of r)if(a!=n&&(i.indexOf(a)==-1||e[a]!==t[a]))return!1;return!0}function RA(e,t){for(let n=e.attributes.length-1;n>=0;n--){let r=e.attributes[n].name;t[r]??e.removeAttribute(r)}for(let n in t){let r=t[n];n==`style`?e.style.cssText=r:e.getAttribute(n)!=r&&e.setAttribute(n,r)}}function zA(e,t,n){let r=!1;if(t)for(let i in t)n&&i in n||(r=!0,i==`style`?e.style.cssText=``:e.removeAttribute(i));if(n)for(let i in n)t&&t[i]==n[i]||(r=!0,i==`style`?e.style.cssText=n[i]:e.setAttribute(i,n[i]));return r}function BA(e){let t=Object.create(null);for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];t[r.name]=r.value}return t}var VA=class{eq(e){return!1}updateDOM(e,t,n){return!1}compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}get estimatedHeight(){return-1}get lineBreaks(){return 0}ignoreEvent(e){return!0}coordsAt(e,t,n){return null}get isHidden(){return!1}get editable(){return!1}destroy(e){}},HA=(function(e){return e[e.Text=0]=`Text`,e[e.WidgetBefore=1]=`WidgetBefore`,e[e.WidgetAfter=2]=`WidgetAfter`,e[e.WidgetRange=3]=`WidgetRange`,e})(HA||={}),UA=class extends Jk{constructor(e,t,n,r){super(),this.startSide=e,this.endSide=t,this.widget=n,this.spec=r}get heightRelevant(){return!1}static mark(e){return new WA(e)}static widget(e){let t=Math.max(-1e4,Math.min(1e4,e.side||0)),n=!!e.block;return t+=n&&!e.inlineOrder?t>0?3e8:-4e8:t>0?1e8:-1e8,new KA(e,t,t,n,e.widget||null,!1)}static replace(e){let t=!!e.block,n,r;if(e.isBlockGap)n=-5e8,r=4e8;else{let{start:i,end:a}=qA(e,t);n=(i?t?-3e8:-1:5e8)-1,r=(a?t?2e8:1:-6e8)+1}return new KA(e,n,r,t,e.widget||null,!0)}static line(e){return new GA(e)}static set(e,t=!1){return $k.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}};UA.none=$k.empty;var WA=class e extends UA{constructor(e){let{start:t,end:n}=qA(e);super(t?-1:5e8,n?1:-6e8,null,e),this.tagName=e.tagName||`span`,this.attrs=e.class&&e.attributes?FA(e.attributes,{class:e.class}):e.class?{class:e.class}:e.attributes||IA}eq(t){return this==t||t instanceof e&&this.tagName==t.tagName&&LA(this.attrs,t.attrs)}range(e,t=e){if(e>=t)throw RangeError(`Mark decorations may not be empty`);return super.range(e,t)}};WA.prototype.point=!1;var GA=class e extends UA{constructor(e){super(-2e8,-2e8,null,e)}eq(t){return t instanceof e&&this.spec.class==t.spec.class&&LA(this.spec.attributes,t.spec.attributes)}range(e,t=e){if(t!=e)throw RangeError(`Line decoration ranges must be zero-length`);return super.range(e,t)}};GA.prototype.mapMode=GO.TrackBefore,GA.prototype.point=!0;var KA=class e extends UA{constructor(e,t,n,r,i,a){super(t,n,i,e),this.block=r,this.isReplace=a,this.mapMode=r?t<=0?GO.TrackBefore:GO.TrackAfter:GO.TrackDel}get type(){return this.startSide==this.endSide?this.startSide<=0?HA.WidgetBefore:HA.WidgetAfter:HA.WidgetRange}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(t){return t instanceof e&&JA(this.widget,t.widget)&&this.block==t.block&&this.startSide==t.startSide&&this.endSide==t.endSide}range(e,t=e){if(this.isReplace&&(e>t||e==t&&this.startSide>0&&this.endSide<=0))throw RangeError(`Invalid range for replacement decoration`);if(!this.isReplace&&t!=e)throw RangeError(`Widget decorations can only have zero-length ranges`);return super.range(e,t)}};KA.prototype.point=!0;function qA(e,t=!1){let{inclusiveStart:n,inclusiveEnd:r}=e;return n??=e.inclusive,r??=e.inclusive,{start:n??t,end:r??t}}function JA(e,t){return e==t||!!(e&&t&&e.compare(t))}function YA(e,t,n,r=0){let i=n.length-1;i>=0&&n[i]+r>=e?n[i]=Math.max(n[i],t):n.push(e,t)}var XA=class e extends Jk{constructor(e,t,n){super(),this.tagName=e,this.attributes=t,this.rank=n}eq(t){return t==this||t instanceof e&&this.tagName==t.tagName&&LA(this.attributes,t.attributes)}static create(t){return new e(t.tagName,t.attributes||IA,t.rank==null?50:Math.max(0,Math.min(t.rank,100)))}static set(e,t=!1){return $k.of(e,t)}};XA.prototype.startSide=XA.prototype.endSide=-1;function ZA(e){let t;return t=e.nodeType==11?e.getSelection?e:e.ownerDocument:e,t.getSelection()}function QA(e,t){return t?e==t||e.contains(t.nodeType==1?t:t.parentNode):!1}function $A(e,t){if(!t.anchorNode)return!1;try{return QA(e,t.anchorNode)}catch{return!1}}function ej(e){return e.nodeType==3?_j(e,0,e.nodeValue.length).getClientRects():e.nodeType==1?e.getClientRects():[]}function tj(e,t,n,r){return n?ij(e,t,n,r,-1)||ij(e,t,n,r,1):!1}function nj(e){for(var t=0;;t++)if(e=e.previousSibling,!e)return t}function rj(e){return e.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(e.nodeName)}function ij(e,t,n,r,i){for(;;){if(e==n&&t==r)return!0;if(t==(i<0?0:aj(e))){if(e.nodeName==`DIV`)return!1;let n=e.parentNode;if(!n||n.nodeType!=1)return!1;t=nj(e)+(i<0?0:1),e=n}else if(e.nodeType==1){if(e=e.childNodes[t+(i<0?-1:0)],e.nodeType==1&&e.contentEditable==`false`)return!1;t=i<0?aj(e):0}else return!1}}function aj(e){return e.nodeType==3?e.nodeValue.length:e.childNodes.length}function oj(e,t){let{left:n,right:r}=e;if(n==r)return e;let i=t?n:r;return{left:i,right:i,top:e.top,bottom:e.bottom}}function sj(e){let t=e.visualViewport;return t?{left:0,right:t.width,top:0,bottom:t.height}:{left:0,right:e.innerWidth,top:0,bottom:e.innerHeight}}function cj(e,t){let n=t.width/e.offsetWidth,r=t.height/e.offsetHeight;return(n>.995&&n<1.005||!isFinite(n)||Math.abs(t.width-e.offsetWidth)<1)&&(n=1),(r>.995&&r<1.005||!isFinite(r)||Math.abs(t.height-e.offsetHeight)<1)&&(r=1),{scaleX:n,scaleY:r}}function lj(e,t,n,r,i,a,o,s){let c=e.ownerDocument,l=c.defaultView||window;for(let u=e,d=!1;u&&!d;)if(u.nodeType==1){let e,f=u==c.body,p=1,m=1;if(f)e=sj(l);else{if(/^(fixed|sticky)$/.test(getComputedStyle(u).position)&&(d=!0),u.scrollHeight<=u.clientHeight&&u.scrollWidth<=u.clientWidth){u=u.assignedSlot||u.parentNode;continue}let t=u.getBoundingClientRect();({scaleX:p,scaleY:m}=cj(u,t)),e={left:t.left,right:t.left+u.clientWidth*p,top:t.top,bottom:t.top+u.clientHeight*m}}let h=0,g=0;if(i==`nearest`)t.top<e.top+o?(g=t.top-(e.top+o),n>0&&t.bottom>e.bottom+g&&(g=t.bottom-e.bottom+o)):t.bottom>e.bottom-o&&(g=t.bottom-e.bottom+o,n<0&&t.top-g<e.top&&(g=t.top-(e.top+o)));else{let r=t.bottom-t.top,a=e.bottom-e.top;g=(i==`center`&&r<=a?t.top+r/2-a/2:i==`start`||i==`center`&&n<0?t.top-o:t.bottom-a+o)-e.top}if(r==`nearest`?t.left<e.left+a?(h=t.left-(e.left+a),n>0&&t.right>e.right+h&&(h=t.right-e.right+a)):t.right>e.right-a&&(h=t.right-e.right+a,n<0&&t.left<e.left+h&&(h=t.left-(e.left+a))):h=(r==`center`?t.left+(t.right-t.left)/2-(e.right-e.left)/2:r==`start`==s?t.left-a:t.right-(e.right-e.left)+a)-e.left,h||g){if(f)l.scrollBy(h,g);else{let e=0,n=0;if(g){let e=u.scrollTop;u.scrollTop+=g/m,n=(u.scrollTop-e)*m}if(h){let t=u.scrollLeft;u.scrollLeft+=h/p,e=(u.scrollLeft-t)*p}t={left:t.left-e,top:t.top-n,right:t.right-e,bottom:t.bottom-n},e&&Math.abs(e-h)<1&&(r=`nearest`),n&&Math.abs(n-g)<1&&(i=`nearest`)}}if(f)break;(t.top<e.top||t.bottom>e.bottom||t.left<e.left||t.right>e.right)&&(t={left:Math.max(t.left,e.left),right:Math.min(t.right,e.right),top:Math.max(t.top,e.top),bottom:Math.min(t.bottom,e.bottom)}),u=u.assignedSlot||u.parentNode}else if(u.nodeType==11)u=u.host;else break}function uj(e,t=!0){let n=e.ownerDocument,r=null,i=null;for(let a=e.parentNode;a&&!(a==n.body||(!t||r)&&i);)if(a.nodeType==1)!i&&a.scrollHeight>a.clientHeight&&(i=a),t&&!r&&a.scrollWidth>a.clientWidth&&(r=a),a=a.assignedSlot||a.parentNode;else if(a.nodeType==11)a=a.host;else break;return{x:r,y:i}}var dj=class{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:t,focusNode:n}=e;this.set(t,Math.min(e.anchorOffset,t?aj(t):0),n,Math.min(e.focusOffset,n?aj(n):0))}set(e,t,n,r){this.anchorNode=e,this.anchorOffset=t,this.focusNode=n,this.focusOffset=r}};function fj(e){let t=[];for(let n=e;n;n=n.nodeType==11?n.host:n.parentNode)n.nodeType==1&&t.push({node:n,left:n.scrollLeft,top:n.scrollTop});return t}function pj(e,t=!0){for(let{node:n,left:r,top:i}of e)t&&n.scrollTop!=i&&(n.scrollTop=i),n.scrollLeft!=r&&(n.scrollLeft=r)}var mj=null;PA.safari&&PA.safari_version>=26&&(mj=!1);function hj(e){if(e.setActive)return e.setActive();if(mj)return e.focus(mj);let t=fj(e);e.focus(mj==null?{get preventScroll(){return mj={preventScroll:!0},!0}}:void 0),mj||(mj=!1,pj(t))}var gj;function _j(e,t,n=t){let r=gj||=document.createRange();return r.setEnd(e,n),r.setStart(e,t),r}function vj(e,t,n,r){let i={key:t,code:t,keyCode:n,which:n,cancelable:!0};r&&({altKey:i.altKey,ctrlKey:i.ctrlKey,shiftKey:i.shiftKey,metaKey:i.metaKey}=r);let a=new KeyboardEvent(`keydown`,i);a.synthetic=!0,e.dispatchEvent(a);let o=new KeyboardEvent(`keyup`,i);return o.synthetic=!0,e.dispatchEvent(o),a.defaultPrevented||o.defaultPrevented}function yj(e){for(;e;){if(e&&(e.nodeType==9||e.nodeType==11&&e.host))return e;e=e.assignedSlot||e.parentNode}return null}function bj(e,t){let n=t.focusNode,r=t.focusOffset;if(!n||t.anchorNode!=n||t.anchorOffset!=r)return!1;for(r=Math.min(r,aj(n));;)if(r){if(n.nodeType!=1)return!1;let e=n.childNodes[r-1];e.contentEditable==`false`?r--:(n=e,r=aj(n))}else if(n==e)return!0;else r=nj(n),n=n.parentNode}function xj(e){return e instanceof Window?e.pageYOffset>Math.max(0,e.document.documentElement.scrollHeight-e.innerHeight-4):e.scrollTop>Math.max(1,e.scrollHeight-e.clientHeight-4)}function Sj(e,t){for(let n=e,r=t;;)if(n.nodeType==3&&r>0)return{node:n,offset:r};else if(n.nodeType==1&&r>0){if(n.contentEditable==`false`)return null;n=n.childNodes[r-1],r=aj(n)}else if(n.parentNode&&!rj(n))r=nj(n),n=n.parentNode;else return null}function Cj(e,t){for(let n=e,r=t;;)if(n.nodeType==3&&r<n.nodeValue.length)return{node:n,offset:r};else if(n.nodeType==1&&r<n.childNodes.length){if(n.contentEditable==`false`)return null;n=n.childNodes[r],r=0}else if(n.parentNode&&!rj(n))r=nj(n)+1,n=n.parentNode;else return null}var wj=class e{constructor(e,t,n=!0){this.node=e,this.offset=t,this.precise=n}static before(t,n){return new e(t.parentNode,nj(t),n)}static after(t,n){return new e(t.parentNode,nj(t)+1,n)}},Tj=(function(e){return e[e.LTR=0]=`LTR`,e[e.RTL=1]=`RTL`,e})(Tj||={}),Ej=Tj.LTR,Dj=Tj.RTL;function Oj(e){let t=[];for(let n=0;n<e.length;n++)t.push(1<<e[n]);return t}var kj=Oj(`88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008`),Aj=Oj(`4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333`),jj=Object.create(null),Mj=[];for(let e of[`()`,`[]`,`{}`]){let t=e.charCodeAt(0),n=e.charCodeAt(1);jj[t]=n,jj[n]=-t}function Nj(e){return e<=247?kj[e]:1424<=e&&e<=1524?2:1536<=e&&e<=1785?Aj[e-1536]:1774<=e&&e<=2220?4:8192<=e&&e<=8204?256:64336<=e&&e<=65023?4:1}var Pj=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/,Fj=class{get dir(){return this.level%2?Dj:Ej}constructor(e,t,n){this.from=e,this.to=t,this.level=n}side(e,t){return this.dir==t==e?this.to:this.from}forward(e,t){return e==(this.dir==t)}static find(e,t,n,r){let i=-1;for(let a=0;a<e.length;a++){let o=e[a];if(o.from<=t&&o.to>=t){if(o.level==n)return a;(i<0||(r==0?e[i].level>o.level:r<0?o.from<t:o.to>t))&&(i=a)}}if(i<0)throw RangeError(`Index out of range`);return i}};function Ij(e,t){if(e.length!=t.length)return!1;for(let n=0;n<e.length;n++){let r=e[n],i=t[n];if(r.from!=i.from||r.to!=i.to||r.direction!=i.direction||!Ij(r.inner,i.inner))return!1}return!0}var Lj=[];function Rj(e,t,n,r,i){for(let a=0;a<=r.length;a++){let o=a?r[a-1].to:t,s=a<r.length?r[a].from:n,c=a?256:i;for(let t=o,n=c,r=c;t<s;t++){let i=Nj(e.charCodeAt(t));i==512?i=n:i==8&&r==4&&(i=16),Lj[t]=i==4?2:i,i&7&&(r=i),n=i}for(let e=o,t=c,r=c;e<s;e++){let i=Lj[e];if(i==128)e<s-1&&t==Lj[e+1]&&t&24?i=Lj[e]=t:Lj[e]=256;else if(i==64){let i=e+1;for(;i<s&&Lj[i]==64;)i++;let a=e&&t==8||i<n&&Lj[i]==8?r==1?1:8:256;for(let t=e;t<i;t++)Lj[t]=a;e=i-1}else i==8&&r==1&&(Lj[e]=1);t=i,i&7&&(r=i)}}}function zj(e,t,n,r,i){let a=i==1?2:1;for(let o=0,s=0,c=0;o<=r.length;o++){let l=o?r[o-1].to:t,u=o<r.length?r[o].from:n;for(let t=l,n,r,o;t<u;t++)if(r=jj[n=e.charCodeAt(t)]){if(r<0){for(let e=s-3;e>=0;e-=3)if(Mj[e+1]==-r){let n=Mj[e+2],r=n&2?i:n&4?n&1?a:i:0;r&&(Lj[t]=Lj[Mj[e]]=r),s=e;break}}else if(Mj.length==189)break;else Mj[s++]=t,Mj[s++]=n,Mj[s++]=c}else if((o=Lj[t])==2||o==1){let e=o==i;c=+!e;for(let t=s-3;t>=0;t-=3){let n=Mj[t+2];if(n&2)break;if(e)Mj[t+2]|=2;else{if(n&4)break;Mj[t+2]|=4}}}}}function Bj(e,t,n,r){for(let i=0,a=r;i<=n.length;i++){let o=i?n[i-1].to:e,s=i<n.length?n[i].from:t;for(let c=o;c<s;){let o=Lj[c];if(o==256){let o=c+1;for(;;)if(o==s){if(i==n.length)break;o=n[i++].to,s=i<n.length?n[i].from:t}else if(Lj[o]==256)o++;else break;let l=a==1,u=l==((o<t?Lj[o]:r)==1)?l?1:2:r;for(let t=o,r=i,a=r?n[r-1].to:e;t>c;)t==a&&(t=n[--r].from,a=r?n[r-1].to:e),Lj[--t]=u;c=o}else a=o,c++}}}function Vj(e,t,n,r,i,a,o){let s=r%2?2:1;if(r%2==i%2)for(let c=t,l=0;c<n;){let t=!0,u=!1;if(l==a.length||c<a[l].from){let e=Lj[c];e!=s&&(t=!1,u=e==16)}let d=!t&&s==1?[]:null,f=t?r:r+1,p=c;run:for(;;)if(l<a.length&&p==a[l].from){if(u)break run;let m=a[l];if(!t)for(let e=m.to,t=l+1;;){if(e==n)break run;if(t<a.length&&a[t].from==e)e=a[t++].to;else if(Lj[e]==s)break run;else break}l++,d?d.push(m):(m.from>c&&o.push(new Fj(c,m.from,f)),Hj(e,m.direction==Ej==!(f%2)?r:r+1,i,m.inner,m.from,m.to,o),c=m.to),p=m.to}else if(p==n||(t?Lj[p]!=s:Lj[p]==s))break;else p++;d?Vj(e,c,p,r+1,i,d,o):c<p&&o.push(new Fj(c,p,f)),c=p}else for(let c=n,l=a.length;c>t;){let n=!0,u=!1;if(!l||c>a[l-1].to){let e=Lj[c-1];e!=s&&(n=!1,u=e==16)}let d=!n&&s==1?[]:null,f=n?r:r+1,p=c;run:for(;;)if(l&&p==a[l-1].to){if(u)break run;let m=a[--l];if(!n)for(let e=m.from,n=l;;){if(e==t)break run;if(n&&a[n-1].to==e)e=a[--n].from;else if(Lj[e-1]==s)break run;else break}d?d.push(m):(m.to<c&&o.push(new Fj(m.to,c,f)),Hj(e,m.direction==Ej==!(f%2)?r:r+1,i,m.inner,m.from,m.to,o),c=m.from),p=m.from}else if(p==t||(n?Lj[p-1]!=s:Lj[p-1]==s))break;else p--;d?Vj(e,p,c,r+1,i,d,o):p<c&&o.push(new Fj(p,c,f)),c=p}}function Hj(e,t,n,r,i,a,o){let s=t%2?2:1;Rj(e,i,a,r,s),zj(e,i,a,r,s),Bj(i,a,r,s),Vj(e,i,a,t,n,r,o)}function Uj(e,t,n){if(!e)return[new Fj(0,0,+(t==Dj))];if(t==Ej&&!n.length&&!Pj.test(e))return Wj(e.length);if(n.length)for(;e.length>Lj.length;)Lj[Lj.length]=256;let r=[],i=t==Ej?0:1;return Hj(e,i,i,n,0,e.length,r),r}function Wj(e){return[new Fj(0,e,0)]}var Gj=``;function Kj(e,t,n,r,i){let a=r.head-e.from,o=Fj.find(t,a,r.bidiLevel??-1,r.assoc),s=t[o],c=s.side(i,n);if(a==c){let e=o+=i?1:-1;if(e<0||e>=t.length)return null;s=t[o=e],a=s.side(!i,n),c=s.side(i,n)}let l=RO(e.text,a,s.forward(i,n));(l<s.from||l>s.to)&&(l=c),Gj=e.text.slice(Math.min(a,l),Math.max(a,l));let u=o==(i?t.length-1:0)?null:t[o+(i?1:-1)];return u&&l==c&&u.level+ +!i<s.level?Q.cursor(u.side(!i,n)+e.from,u.forward(i,n)?1:-1,u.level):Q.cursor(l+e.from,s.forward(i,n)?-1:1,s.level)}function qj(e,t,n){for(let r=t;r<n;r++){let t=Nj(e.charCodeAt(r));if(t==1)return Ej;if(t==2||t==4)return Dj}return Ej}var Jj=rk.define(),Yj=rk.define(),Xj=rk.define(),Zj=rk.define(),Qj=rk.define(),$j=rk.define(),eM=rk.define(),tM=rk.define(),nM=rk.define(),rM=rk.define({combine:e=>e.some(e=>e)}),iM=rk.define({combine:e=>e.some(e=>e)}),aM=rk.define(),oM=class e{constructor(e,t,n,r,i,a=!1){this.range=e,this.y=t,this.x=n,this.yMargin=r,this.xMargin=i,this.isSnapshot=a}map(t){return t.empty?this:new e(this.range.map(t),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(t){return this.range.to<=t.doc.length?this:new e(Q.cursor(t.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}},sM=jk.define({map:(e,t)=>e.map(t)}),cM=jk.define();function lM(e,t,n){let r=e.facet(Zj);r.length?r[0](t):window.onerror&&window.onerror(String(t),n,void 0,void 0,t)||(n?console.error(n+`:`,t):console.error(t))}var uM=rk.define({combine:e=>!e.length||e[0]}),dM=0,fM=rk.define({combine(e){return e.filter((t,n)=>{for(let r=0;r<n;r++)if(e[r].plugin==t.plugin)return!1;return!0})}}),pM=class e{constructor(e,t,n,r,i){this.id=e,this.create=t,this.domEventHandlers=n,this.domEventObservers=r,this.baseExtensions=i(this),this.extension=this.baseExtensions.concat(fM.of({plugin:this,arg:void 0}))}of(e){return this.baseExtensions.concat(fM.of({plugin:this,arg:e}))}static define(t,n){let{eventHandlers:r,eventObservers:i,provide:a,decorations:o}=n||{};return new e(dM++,t,r,i,e=>{let t=[];return o&&t.push(_M.of(t=>{let n=t.plugin(e);return n?o(n):UA.none})),a&&t.push(a(e)),t})}static fromClass(t,n){return e.define((e,n)=>new t(e,n),n)}},mM=class{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}get plugin(){return this.spec&&this.spec.plugin}update(e){if(!this.value){if(this.spec)try{this.value=this.spec.plugin.create(e,this.spec.arg)}catch(t){lM(e.state,t,`CodeMirror plugin crashed`),this.deactivate()}}else if(this.mustUpdate){let e=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(e)}catch(t){if(lM(e.state,t,`CodeMirror plugin crashed`),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}return this}destroy(e){if(this.value?.destroy)try{this.value.destroy()}catch(t){lM(e.state,t,`CodeMirror plugin crashed`)}}deactivate(){this.spec=this.value=null}},hM=rk.define(),gM=rk.define(),_M=rk.define(),vM=rk.define(),yM=rk.define(),bM=rk.define(),xM=rk.define();function SM(e,t){let n=e.state.facet(xM);if(!n.length)return n;let r=n.map(t=>t instanceof Function?t(e):t),i=[];return $k.spans(r,t.from,t.to,{point(){},span(e,n,r,a){let o=e-t.from,s=n-t.from,c=i;for(let e=r.length-1;e>=0;e--,a--){let n=r[e].spec.bidiIsolate,i;if(n??=qj(t.text,o,s),a>0&&c.length&&(i=c[c.length-1]).to==o&&i.direction==n)i.to=s,c=i.inner;else{let e={from:o,to:s,direction:n,inner:[]};c.push(e),c=e.inner}}}}),i}var CM=rk.define();function wM(e){let t=0,n=0,r=0,i=0;for(let a of e.state.facet(CM)){let o=a(e);o&&(o.left!=null&&(t=Math.max(t,o.left)),o.right!=null&&(n=Math.max(n,o.right)),o.top!=null&&(r=Math.max(r,o.top)),o.bottom!=null&&(i=Math.max(i,o.bottom)))}return{left:t,right:n,top:r,bottom:i}}var TM=rk.define(),EM=class e{constructor(e,t,n,r){this.fromA=e,this.toA=t,this.fromB=n,this.toB=r}join(t){return new e(Math.min(this.fromA,t.fromA),Math.max(this.toA,t.toA),Math.min(this.fromB,t.fromB),Math.max(this.toB,t.toB))}addToSet(e){let t=e.length,n=this;for(;t>0;t--){let r=e[t-1];if(!(r.fromA>n.toA)){if(r.toA<n.fromA)break;n=n.join(r),e.splice(t-1,1)}}return e.splice(t,0,n),e}static extendWithRanges(t,n){if(n.length==0)return t;let r=[];for(let i=0,a=0,o=0;;){let s=i<t.length?t[i].fromB:1e9,c=a<n.length?n[a]:1e9,l=Math.min(s,c);if(l==1e9)break;let u=l+o,d=l,f=u;for(;;)if(a<n.length&&n[a]<=d){let e=n[a+1];a+=2,d=Math.max(d,e);for(let e=i;e<t.length&&t[e].fromB<=d;e++)o=t[e].toA-t[e].toB;f=Math.max(f,e+o)}else if(i<t.length&&t[i].fromB<=d){let e=t[i++];d=Math.max(d,e.toB),f=Math.max(f,e.toA),o=e.toA-e.toB}else break;r.push(new e(u,f,l,d))}return r}},DM=class e{constructor(e,t,n){this.view=e,this.state=t,this.transactions=n,this.flags=0,this.startState=e.state,this.changes=qO.empty(this.startState.doc.length);for(let e of n)this.changes=this.changes.compose(e.changes);let r=[];this.changes.iterChangedRanges((e,t,n,i)=>r.push(new EM(e,t,n,i))),this.changedRanges=r}static create(t,n,r){return new e(t,n,r)}get viewportChanged(){return(this.flags&4)>0}get viewportMoved(){return(this.flags&8)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&18)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}},OM=[],kM=class{constructor(e,t,n=0){this.dom=e,this.length=t,this.flags=n,this.parent=null,e.cmTile=this}get breakAfter(){return this.flags&1}get children(){return OM}isWidget(){return!1}get isHidden(){return!1}isComposite(){return!1}isLine(){return!1}isText(){return!1}isBlock(){return!1}get domAttrs(){return null}sync(e){if(this.flags|=2,this.flags&4){this.flags&=-5;let e=this.domAttrs;e&&RA(this.dom,e)}}toString(){return this.constructor.name+(this.children.length?`(${this.children})`:``)+(this.breakAfter?`#`:``)}destroy(){this.parent=null}setDOM(e){this.dom=e,e.cmTile=this}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e,t=this.posAtStart){let n=t;for(let t of this.children){if(t==e)return n;n+=t.length+t.breakAfter}throw RangeError(`Invalid child in posBefore`)}posAfter(e){return this.posBefore(e)+e.length}covers(e){return!0}coordsIn(e,t,n){return null}domPosFor(e,t){let n=nj(this.dom),r=this.length?e>0:t>0;return new wj(this.parent.dom,n+ +!!r,e==0||e==this.length)}markDirty(e){this.flags&=-3,e&&(this.flags|=4),this.parent&&this.parent.flags&2&&this.parent.markDirty(!1)}get overrideDOMText(){return null}get root(){for(let e=this;e;e=e.parent)if(e instanceof MM)return e;return null}static get(e){return e.cmTile}},AM=class extends kM{constructor(e){super(e,0),this._children=[]}isComposite(){return!0}get children(){return this._children}get lastChild(){return this.children.length?this.children[this.children.length-1]:null}append(e){this.children.push(e),e.parent=this}sync(e){if(this.flags&2)return;super.sync(e);let t=this.dom,n=null,r,i=e?.node==t?e:null,a=0;for(let o of this.children){if(o.sync(e),a+=o.length+o.breakAfter,r=n?n.nextSibling:t.firstChild,i&&r!=o.dom&&(i.written=!0),o.dom.parentNode==t)for(;r&&r!=o.dom;)r=jM(r);else t.insertBefore(o.dom,r);n=o.dom}for(r=n?n.nextSibling:t.firstChild,i&&r&&(i.written=!0);r;)r=jM(r);this.length=a}};function jM(e){let t=e.nextSibling;return e.parentNode.removeChild(e),t}var MM=class extends AM{constructor(e,t){super(t),this.view=e}owns(e){for(;e;e=e.parent)if(e==this)return!0;return!1}isBlock(){return!0}nearest(e){for(;;){if(!e)return null;let t=kM.get(e);if(t&&this.owns(t))return t;e=e.parentNode}}blockTiles(e){for(let t=[],n=this,r=0,i=0;;)if(r==n.children.length){if(!t.length)return;n=n.parent,n.breakAfter&&i++,r=t.pop()}else{let a=n.children[r++];if(a instanceof NM)t.push(r),n=a,r=0;else{let t=i+a.length,n=e(a,i);if(n!==void 0)return n;i=t+a.breakAfter}}}resolveBlock(e,t){let n,r=-1,i,a=-1;if(this.blockTiles((o,s)=>{let c=s+o.length;if(e>=s&&e<=c){if(o.isWidget()&&t>=-1&&t<=1){if(o.flags&32)return!0;o.flags&16&&(n=void 0)}(s<e||e==c&&(t<-1?o.length:o.covers(1)))&&(!n||!o.isWidget()&&n.isWidget())&&(n=o,r=e-s),(c>e||e==s&&(t>1?o.length:o.covers(-1)))&&(!i||!o.isWidget()&&i.isWidget())&&(i=o,a=e-s)}}),!n&&!i)throw Error(`No tile at position `+e);return n&&t<0||!i?{tile:n,offset:r}:{tile:i,offset:a}}},NM=class e extends AM{constructor(e,t){super(e),this.wrapper=t}isBlock(){return!0}covers(e){return this.children.length?e<0?this.children[0].covers(-1):this.lastChild.covers(1):!1}get domAttrs(){return this.wrapper.attributes}static of(t,n){let r=new e(n||document.createElement(t.tagName),t);return n||(r.flags|=4),r}},PM=class e extends AM{constructor(e,t){super(e),this.attrs=t}isLine(){return!0}static start(t,n,r){let i=new e(n||document.createElement(`div`),t);return(!n||!r)&&(i.flags|=4),i}get domAttrs(){return this.attrs}resolveInline(e,t,n){let r=null,i=-1,a=null,o=-1;function s(e,c){for(let l=0,u=0;l<e.children.length&&u<=c;l++){let d=e.children[l],f=u+d.length;f>=c&&(d.isComposite()?s(d,c-u):(!a||a.isHidden&&(t>0&&!(a.flags&32)||n&&IM(a,d)))&&(f>c||d.flags&32&&t<=1)?(a=d,o=c-u):(u<c||d.flags&16&&!d.isHidden&&t>=-1)&&(r=d,i=c-u)),u=f}}s(this,e);let c=(t<0?r:a)||r||a;return c?{tile:c,offset:c==r?i:o}:null}coordsIn(e,t,n){let r=this.resolveInline(e,t,!0);return r?r.tile.coordsIn(Math.max(0,r.offset),t,n):FM(this)}domIn(e,t){let n=this.resolveInline(e,t);if(n){let{tile:e,offset:r}=n;if(this.dom.contains(e.dom))return e.isText()?new wj(e.dom,Math.min(e.dom.nodeValue.length,r)):e.domPosFor(r,e.flags&16?1:e.flags&32?-1:t);let i=n.tile.parent,a=!1;for(let e of i.children){if(a)return new wj(e.dom,0);e==n.tile&&(a=!0)}}return new wj(this.dom,0)}};function FM(e){let t=e.dom.lastChild;if(!t)return e.dom.getBoundingClientRect();let n=ej(t);return n[n.length-1]||null}function IM(e,t){let n=e.coordsIn(0,1),r=t.coordsIn(0,1);return n&&r&&r.top<n.bottom}var LM=class e extends AM{constructor(e,t){super(e),this.mark=t}get domAttrs(){return this.mark.attrs}static of(t,n){let r=new e(n||document.createElement(t.tagName),t);return n||(r.flags|=4),r}},RM=class e extends kM{constructor(e,t){super(e,t.length),this.text=t}sync(e){this.flags&2||(super.sync(e),this.dom.nodeValue!=this.text&&(e&&e.node==this.dom&&(e.written=!0),this.dom.nodeValue=this.text))}isText(){return!0}toString(){return JSON.stringify(this.text)}coordsIn(e,t,n){let r=this.dom.nodeValue.length;e>r&&(e=r);let i=e,a=e,o=0;e==0&&t<0||e==r&&t>=0?PA.chrome||PA.gecko||(e?(i--,o=1):a<r&&(a++,o=-1)):t<0?i--:a<r&&a++;let s=_j(this.dom,i,a).getClientRects();if(!s.length)return null;let c=s[(o?o<0:t>=0)?0:s.length-1];return PA.safari&&!o&&c.width==0&&(c=Array.prototype.find.call(s,e=>e.width)||c),n==null?c:oj(c,(o?o>0:t<0)==n)}static of(t,n){let r=new e(n||document.createTextNode(t),t);return n||(r.flags|=2),r}},zM=class e extends kM{constructor(e,t,n,r){super(e,t,r),this.widget=n}isWidget(){return!0}get isHidden(){return this.widget.isHidden}covers(e){return this.flags&48?!1:(this.flags&(e<0?64:128))>0}coordsIn(e,t){return this.coordsInWidget(e,t,!1)}coordsInWidget(e,t,n){let r=this.widget.coordsAt(this.dom,e,t);if(r)return r;if(n)return oj(this.dom.getBoundingClientRect(),this.length?e==0:t<=0);{let t=this.dom.getClientRects(),n=null;if(!t.length)return null;let r=this.flags&16?!0:this.flags&32?!1:e>0;for(let i=r?t.length-1:0;n=t[i],!(e>0?i==0:i==t.length-1||n.top<n.bottom);i+=r?-1:1);return oj(n,!r)}}get overrideDOMText(){if(!this.length)return DO.empty;let{root:e}=this;if(!e)return DO.empty;let t=this.posAtStart;return e.view.state.doc.slice(t,t+this.length)}destroy(){super.destroy(),this.widget.destroy(this.dom)}static of(t,n,r,i,a){return a||(a=t.toDOM(n),t.editable||(a.contentEditable=`false`)),new e(a,r,t,i)}},BM=class extends kM{constructor(e){let t=document.createElement(`img`);t.className=`cm-widgetBuffer`,t.setAttribute(`aria-hidden`,`true`),super(t,0,e)}get isHidden(){return!0}get overrideDOMText(){return DO.empty}coordsIn(e,t,n){let r=this.dom.getBoundingClientRect();return n==null?r:oj(r,t>0==n)}},VM=class{constructor(e){this.index=0,this.beforeBreak=!1,this.parents=[],this.tile=e}advance(e,t,n){let{tile:r,index:i,beforeBreak:a,parents:o}=this;for(;e||t>0;)if(!r.isComposite()){let t=r.length;if(i<t&&e){let a=Math.min(e,t-i);n&&n.skip(r,i,i+a),e-=a,i+=a}if(i==t)a=!!r.breakAfter,{tile:r,index:i}=o.pop(),i++;else if(!e)break}else if(a){if(!e)break;n&&n.break(),e--,a=!1}else if(i==r.children.length){if(!e&&!o.length)break;n&&n.leave(r),a=!!r.breakAfter,{tile:r,index:i}=o.pop(),i++}else{let s=r.children[i],c=s.breakAfter;(t>0?s.length<=e:s.length<e)&&(!n||n.skip(s,0,s.length)!==!1||!s.isComposite)?(a=!!c,i++,e-=s.length):(o.push({tile:r,index:i}),r=s,i=0,n&&s.isComposite()&&n.enter(s))}return this.tile=r,this.index=i,this.beforeBreak=a,this}get root(){return this.parents.length?this.parents[0].tile:this.tile}},HM=class{constructor(e,t,n,r){this.from=e,this.to=t,this.wrapper=n,this.rank=r}},UM=class{constructor(e,t,n){this.cache=e,this.root=t,this.blockWrappers=n,this.curLine=null,this.lastBlock=null,this.afterWidget=null,this.pos=0,this.wrappers=[],this.wrapperPos=0}addText(e,t,n,r){this.flushBuffer();let i=this.ensureMarks(t,n),a=i.lastChild;if(a&&a.isText()&&!(a.flags&8)&&a.length+e.length<512){this.cache.reused.set(a,2);let t=i.children[i.children.length-1]=new RM(a.dom,a.text+e);t.parent=i}else i.append(r||RM.of(e,this.cache.find(RM)?.dom));this.pos+=e.length,this.afterWidget=null}addComposition(e,t){let n=this.curLine;n.dom!=t.line.dom&&(n.setDOM(this.cache.reused.has(t.line)?$M(t.line.dom):t.line.dom),this.cache.reused.set(t.line,2));let r=n;for(let e=t.marks.length-1;e>=0;e--){let n=t.marks[e],i=r.lastChild;if(i instanceof LM&&i.mark.eq(n.mark))i.dom!=n.dom&&i.setDOM($M(n.dom)),r=i;else{if(this.cache.reused.get(n)){let e=kM.get(n.dom);e&&e.setDOM($M(n.dom))}let e=LM.of(n.mark,n.dom);r.append(e),r=e}this.cache.reused.set(n,2)}let i=kM.get(e.text);i&&this.cache.reused.set(i,2);let a=new RM(e.text,e.text.nodeValue);a.flags|=8,this.pos=e.range.toB,r.append(a)}addInlineWidget(e,t,n){let r=this.afterWidget&&e.flags&48&&(this.afterWidget.flags&48)==(e.flags&48);r||this.flushBuffer();let i=this.ensureMarks(t,n);!r&&!(e.flags&16)&&i.append(this.getBuffer(1)),i.append(e),this.pos+=e.length,this.afterWidget=e}addMark(e,t,n){this.flushBuffer(),this.ensureMarks(t,n).append(e),this.pos+=e.length,this.afterWidget=null}addBlockWidget(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}continueWidget(e){let t=this.afterWidget||this.lastBlock;t.length+=e,this.pos+=e}addLineStart(e,t){e||=XM;let n=PM.start(e,t||this.cache.find(PM)?.dom,!!t);this.getBlockPos().append(this.lastBlock=this.curLine=n)}addLine(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}addBreak(){this.lastBlock.flags|=1,this.endLine(),this.pos++}addLineStartIfNotCovered(e){this.blockPosCovered()||this.addLineStart(e)}ensureLine(e){this.curLine||this.addLineStart(e)}ensureMarks(e,t){let n=this.curLine;for(let r=e.length-1;r>=0;r--){let i=e[r],a;if(t>0&&(a=n.lastChild)&&a instanceof LM&&a.mark.eq(i))n=a,t--;else{let e=LM.of(i,this.cache.find(LM,e=>e.mark.eq(i))?.dom);n.append(e),n=e,t=0}}return n}endLine(){if(this.curLine){this.flushBuffer();let e=this.curLine.lastChild;(!e||!JM(this.curLine,!1)||e.dom.nodeName!=`BR`&&e.isWidget()&&!(PA.ios&&JM(this.curLine,!0)))&&this.curLine.append(this.cache.findWidget(tN,0,32)||new zM(tN.toDOM(),0,tN,32)),this.curLine=this.afterWidget=null}}updateBlockWrappers(){this.wrapperPos>this.pos+1e4&&(this.blockWrappers.goto(this.pos),this.wrappers.length=0);for(let e=this.wrappers.length-1;e>=0;e--)this.wrappers[e].to<this.pos&&this.wrappers.splice(e,1);for(let e=this.blockWrappers;e.value&&e.from<=this.pos;e.next())if(e.to>=this.pos){let t=e.rank*102+e.value.rank,n=new HM(e.from,e.to,e.value,t),r=this.wrappers.length;for(;r>0&&(this.wrappers[r-1].rank-n.rank||this.wrappers[r-1].to-n.to)<0;)r--;this.wrappers.splice(r,0,n)}this.wrapperPos=this.pos}getBlockPos(){this.updateBlockWrappers();let e=this.root;for(let t of this.wrappers){let n=e.lastChild;if(t.from<this.pos&&n instanceof NM&&n.wrapper.eq(t.wrapper))e=n;else{let n=NM.of(t.wrapper,this.cache.find(NM,e=>e.wrapper.eq(t.wrapper))?.dom);e.append(n),e=n}}return e}blockPosCovered(){let e=this.lastBlock;return e!=null&&!e.breakAfter&&(!e.isWidget()||(e.flags&160)>0)}getBuffer(e){let t=2|(e<0?16:32),n=this.cache.find(BM,void 0,1);return n&&(n.flags=t),n||new BM(t)}flushBuffer(){this.afterWidget&&!(this.afterWidget.flags&32)&&(this.afterWidget.parent.append(this.getBuffer(-1)),this.afterWidget=null)}},WM=class{constructor(e){this.skipCount=0,this.text=``,this.textOff=0,this.cursor=e.iter()}skip(e){this.textOff+e<=this.text.length?this.textOff+=e:(this.skipCount+=e-(this.text.length-this.textOff),this.text=``,this.textOff=0)}next(e){if(this.textOff==this.text.length){let{value:t,lineBreak:n,done:r}=this.cursor.next(this.skipCount);if(this.skipCount=0,r)throw Error(`Ran out of text content when drawing inline views`);this.text=t;let i=this.textOff=Math.min(e,t.length);return n?null:t.slice(0,i)}let t=Math.min(this.text.length,this.textOff+e),n=this.text.slice(this.textOff,t);return this.textOff=t,n}},GM=[zM,PM,RM,LM,BM,NM,MM];for(let e=0;e<GM.length;e++)GM[e].bucket=e;var KM=class{constructor(e){this.view=e,this.buckets=GM.map(()=>[]),this.index=GM.map(()=>0),this.reused=new Map}add(e){let t=e.constructor.bucket,n=this.buckets[t];n.length<6?n.push(e):n[this.index[t]=(this.index[t]+1)%6]=e}find(e,t,n=2){let r=e.bucket,i=this.buckets[r],a=this.index[r];for(let e=0;e<i.length;e++){let o=(e+a)%i.length,s=i[o];if((!t||t(s))&&!this.reused.has(s))return i.splice(o,1),o<a&&this.index[r]--,this.reused.set(s,n),s}return null}findWidget(e,t,n){let r=this.buckets[0];if(r.length)for(let i=0,a=0;;i++){if(i==r.length){if(a)return null;a=1,i=0}let o=r[i];if(!this.reused.has(o)&&(a==0?o.widget.compare(e):o.widget.constructor==e.constructor&&e.updateDOM(o.dom,this.view,o.widget)))return r.splice(i,1),i<this.index[0]&&this.index[0]--,o.widget==e&&o.length==t&&(o.flags&497)==n?(this.reused.set(o,1),o):(this.reused.set(o,2),new zM(o.dom,t,e,o.flags&-498|n))}}reuse(e){return this.reused.set(e,1),e}maybeReuse(e,t=2){if(!this.reused.has(e))return this.reused.set(e,t),e.dom}clear(){for(let e=0;e<this.buckets.length;e++)this.buckets[e].length=this.index[e]=0}},qM=class{constructor(e,t,n,r,i){this.view=e,this.decorations=r,this.disallowBlockEffectsFor=i,this.openWidget=!1,this.openMarks=0,this.cache=new KM(e),this.text=new WM(e.state.doc),this.builder=new UM(this.cache,new MM(e,e.contentDOM),$k.iter(n)),this.cache.reused.set(t,2),this.old=new VM(t),this.reuseWalker={skip:(e,t,n)=>{if(this.cache.add(e),e.isComposite())return!1},enter:e=>this.cache.add(e),leave:()=>{},break:()=>{}}}run(e,t){let n=t&&this.getCompositionContext(t.text);for(let r=0,i=0,a=0;;){let o=a<e.length?e[a++]:null,s=o?o.fromA:this.old.root.length;if(s>r){let e=s-r;this.preserve(e,!a,!o),r=s,i+=e}if(!o)break;t&&o.fromA<=t.range.fromA&&o.toA>=t.range.toA?(this.forward(o.fromA,t.range.fromA,t.range.fromA<t.range.toA?1:-1),this.emit(i,t.range.fromB),this.builder.flushBuffer(),this.cache.clear(),this.builder.addComposition(t,n),this.text.skip(t.range.toB-t.range.fromB),this.forward(t.range.fromA,o.toA),this.emit(t.range.toB,o.toB)):(this.forward(o.fromA,o.toA),this.emit(i,o.toB)),i=o.toB,r=o.toA}return this.builder.curLine&&this.builder.endLine(),this.builder.root}preserve(e,t,n){let r=QM(this.old),i=this.openMarks;this.old.advance(e,n?1:-1,{skip:(e,t,n)=>{if(e.isWidget()){if(this.openWidget)this.builder.continueWidget(n-t);else{let a=n>0||t<e.length?zM.of(e.widget,this.view,n-t,e.flags&496,this.cache.maybeReuse(e)):this.cache.reuse(e);a.flags&256?(a.flags&=-2,this.builder.addBlockWidget(a)):(this.builder.ensureLine(null),this.builder.addInlineWidget(a,r,i),i=r.length)}}else if(e.isText())this.builder.ensureLine(null),!t&&n==e.length&&!this.cache.reused.has(e)?this.builder.addText(e.text,r,i,this.cache.reuse(e)):(this.cache.add(e),this.builder.addText(e.text.slice(t,n),r,i)),i=r.length;else if(e.isLine())e.flags&=-2,this.cache.reused.set(e,1),this.builder.addLine(e);else if(e instanceof BM)this.cache.add(e);else if(e instanceof LM)this.builder.ensureLine(null),this.builder.addMark(e,r,i),this.cache.reused.set(e,1),i=r.length;else return!1;this.openWidget=!1},enter:e=>{e.isLine()?this.builder.addLineStart(e.attrs,this.cache.maybeReuse(e)):(this.cache.add(e),e instanceof LM&&r.unshift(e.mark)),this.openWidget=!1},leave:e=>{e.isLine()?r.length&&=i=0:e instanceof LM&&(r.shift(),i=Math.min(i,r.length))},break:()=>{this.builder.addBreak(),this.openWidget=!1}}),this.text.skip(e)}emit(e,t){let n=null,r=this.builder,i=-1,a=$k.spans(this.decorations,e,t,{point:(e,t,a,o,s,c)=>{if(a instanceof KA){if(this.disallowBlockEffectsFor[c]){if(a.block)throw RangeError(`Block decorations may not be specified via plugins`);if(t>this.view.state.doc.lineAt(e).to)throw RangeError(`Decorations that replace line breaks may not be specified via plugins`)}if(i=o.length,s>o.length)r.continueWidget(t-e);else{let i=a.widget||(a.block?eN.block:eN.inline),c=YM(a),l=this.cache.findWidget(i,t-e,c)||zM.of(i,this.view,t-e,c);a.block?(a.startSide>0&&r.addLineStartIfNotCovered(n),r.addBlockWidget(l)):(r.ensureLine(n),r.addInlineWidget(l,o,s))}n=null}else n=ZM(n,a);t>e&&this.text.skip(t-e)},span:(e,t,a,o)=>{for(let i=e;i<t;){let s=this.text.next(Math.min(512,t-i));s==null?(r.addLineStartIfNotCovered(n),r.addBreak(),i++):(r.ensureLine(n),r.addText(s,a,i==e?o:a.length),i+=s.length),n=null}i=a.length}});i>-1&&(this.openWidget=a>i),this.openWidget||r.addLineStartIfNotCovered(n),this.openMarks=a}forward(e,t,n=1){t-e<=10?this.old.advance(t-e,n,this.reuseWalker):(this.old.advance(5,-1,this.reuseWalker),this.old.advance(t-e-10,-1),this.old.advance(5,n,this.reuseWalker))}getCompositionContext(e){let t=[],n=null;for(let r=e.parentNode;;r=r.parentNode){let e=kM.get(r);if(r==this.view.contentDOM)break;e instanceof LM?t.push(e):e?.isLine()?n=e:e instanceof NM||(r.nodeName==`DIV`&&!n&&r!=this.view.contentDOM?n=new PM(r,XM):n||t.push(LM.of(new WA({tagName:r.nodeName.toLowerCase(),attributes:BA(r)}),r)))}return{line:n,marks:t}}};function JM(e,t){let n=e=>{for(let r of e.children)if((t?r.isText():r.length)||n(r))return!0;return!1};return n(e)}function YM(e){let t=e.isReplace?(e.startSide<0?64:0)|(e.endSide>0?128:0):e.startSide>0?32:16;return e.block&&(t|=256),t}var XM={class:`cm-line`};function ZM(e,t){let n=t.spec.attributes,r=t.spec.class;return!n&&!r?e:(e||={class:`cm-line`},n&&FA(n,e),r&&(e.class+=` `+r),e)}function QM(e){let t=[];for(let n=e.parents.length;n>1;n--){let r=n==e.parents.length?e.tile:e.parents[n].tile;r instanceof LM&&t.push(r.mark)}return t}function $M(e){let t=kM.get(e);return t&&t.setDOM(e.cloneNode()),e}var eN=class extends VA{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}};eN.inline=new eN(`span`),eN.block=new eN(`div`);var tN=new class extends VA{toDOM(){return document.createElement(`br`)}get isHidden(){return!0}get editable(){return!0}},nN=class{constructor(e){this.view=e,this.decorations=[],this.blockWrappers=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.editContextFormatting=UA.none,this.lastCompositionAfterCursor=!1,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.updateDeco(),this.tile=new MM(e,e.contentDOM),this.updateInner([new EM(0,0,0,e.state.doc.length)],null)}update(e){let t=e.changedRanges;this.minWidth>0&&t.length&&(t.every(({fromA:e,toA:t})=>t<this.minWidthFrom||e>this.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.updateEditContextFormatting(e);let n=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&(this.domChanged?.newSel?n=this.domChanged.newSel.head:!pN(e.changes,this.hasComposition)&&!e.selectionSet&&(n=e.state.selection.main.head));let r=n>-1?oN(this.view,e.changes,n):null;if(this.domChanged=null,this.hasComposition){let{from:n,to:r}=this.hasComposition;t=new EM(n,r,e.changes.mapPos(n,-1),e.changes.mapPos(r,1)).addToSet(t.slice())}this.hasComposition=r?{from:r.range.fromB,to:r.range.toB}:null,(PA.ie||PA.chrome)&&!r&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let i=this.decorations,a=this.blockWrappers;this.updateDeco();let o=lN(i,this.decorations,e.changes);o.length&&(t=EM.extendWithRanges(t,o));let s=dN(a,this.blockWrappers,e.changes);return s.length&&(t=EM.extendWithRanges(t,s)),r&&!t.some(e=>e.fromA<=r.range.fromA&&e.toA>=r.range.toA)&&(t=r.range.addToSet(t.slice())),this.tile.flags&2&&t.length==0?!1:(this.updateInner(t,r),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t){this.view.viewState.mustMeasureContent=!0;let{observer:n}=this.view;n.ignore(()=>{if(t||e.length){let n=this.tile,r=new qM(this.view,n,this.blockWrappers,this.decorations,this.dynamicDecorationMap);t&&kM.get(t.text)&&r.cache.reused.set(kM.get(t.text),2),this.tile=r.run(e,t),rN(n,r.cache.reused)}this.tile.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+`px`,this.tile.dom.style.flexBasis=this.minWidth?this.minWidth+`px`:``;let r=PA.chrome||PA.ios?{node:n.selectionRange.focusNode,written:!1}:void 0;this.tile.sync(r),r&&(r.written||n.selectionRange.focusNode!=r.node||!this.tile.dom.contains(r.node))&&(this.forceSelection=!0),this.tile.dom.style.height=``});let r=[];if(this.view.viewport.from||this.view.viewport.to<this.view.state.doc.length)for(let e of this.tile.children)e.isWidget()&&e.widget instanceof mN&&r.push(e.dom);n.updateGaps(r)}updateEditContextFormatting(e){this.editContextFormatting=this.editContextFormatting.map(e.changes);for(let t of e.transactions)for(let e of t.effects)e.is(cM)&&(this.editContextFormatting=e.value)}updateSelection(e=!1,t=!1){(e||!this.view.observer.selectionRange.focusNode)&&this.view.observer.readSelectionRange();let{dom:n}=this.tile,r=this.view.root.activeElement,i=r==n,a=!i&&!(this.view.state.facet(uM)||n.tabIndex>-1)&&$A(n,this.view.observer.selectionRange)&&!(r&&n.contains(r));if(!(i||t||a))return;let o=this.forceSelection;this.forceSelection=!1;let s=this.view.state.selection.main,c,l;if(s.empty?l=c=this.inlineDOMNearPos(s.anchor,s.assoc||1):(l=this.inlineDOMNearPos(s.head,s.head==s.from?1:-1),c=this.inlineDOMNearPos(s.anchor,s.anchor==s.from?1:-1)),PA.gecko&&s.empty&&!this.hasComposition&&iN(c)){let e=document.createTextNode(``);this.view.observer.ignore(()=>c.node.insertBefore(e,c.node.childNodes[c.offset]||null)),c=l=new wj(e,0),o=!0}let u=this.view.observer.selectionRange;(o||!u.focusNode||(!tj(c.node,c.offset,u.anchorNode,u.anchorOffset)||!tj(l.node,l.offset,u.focusNode,u.focusOffset))&&!this.suppressWidgetCursorChange(u,s))&&(this.view.observer.ignore(()=>{PA.android&&PA.chrome&&n.contains(u.focusNode)&&fN(u.focusNode,n)&&(n.blur(),n.focus({preventScroll:!0}));let e=ZA(this.view.root);if(e){if(s.empty){if(PA.gecko){let e=sN(c.node,c.offset);if(e&&e!=3){let t=(e==1?Sj:Cj)(c.node,c.offset);t&&(c=new wj(t.node,t.offset))}}e.collapse(c.node,c.offset),s.bidiLevel!=null&&e.caretBidiLevel!==void 0&&(e.caretBidiLevel=s.bidiLevel)}else if(e.extend){e.collapse(c.node,c.offset);try{e.extend(l.node,l.offset)}catch{}}else{let t=document.createRange();s.anchor>s.head&&([c,l]=[l,c]),t.setEnd(l.node,l.offset),t.setStart(c.node,c.offset),e.removeAllRanges(),e.addRange(t)}}a&&this.view.root.activeElement==n&&(n.blur(),r&&r.focus())}),this.view.observer.setSelectionRange(c,l)),this.impreciseAnchor=c.precise?null:new wj(u.anchorNode,u.anchorOffset),this.impreciseHead=l.precise?null:new wj(u.focusNode,u.focusOffset)}suppressWidgetCursorChange(e,t){return this.hasComposition&&t.empty&&tj(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)&&this.posFromDOM(e.focusNode,e.focusOffset)==t.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,t=e.state.selection.main,n=ZA(e.root),{anchorNode:r,anchorOffset:i}=e.observer.selectionRange;if(!n||!t.empty||!t.assoc||!n.modify)return;let a=this.lineAt(t.head,t.assoc);if(!a)return;let o=a.posAtStart;if(t.head==o||t.head==o+a.length)return;let s=this.coordsAt(t.head,-1),c=this.coordsAt(t.head,1);if(!s||!c||s.bottom>c.top)return;let l=this.domAtPos(t.head+t.assoc,t.assoc);n.collapse(l.node,l.offset),n.modify(`move`,t.assoc<0?`forward`:`backward`,`lineboundary`),e.observer.readSelectionRange();let u=e.observer.selectionRange;e.docView.posFromDOM(u.anchorNode,u.anchorOffset)!=t.from&&n.collapse(r,i)}posFromDOM(e,t){let n=this.tile.nearest(e);if(!n)return this.tile.dom.compareDocumentPosition(e)&2?0:this.view.state.doc.length;let r=n.posAtStart;if(n.isComposite()){let i;if(e==n.dom)i=n.dom.childNodes[t];else{let r=aj(e)==0?0:t==0?-1:1;for(;;){let t=e.parentNode;if(t==n.dom)break;r==0&&t.firstChild!=t.lastChild&&(r=e==t.firstChild?-1:1),e=t}i=r<0?e:e.nextSibling}if(i==n.dom.firstChild)return r;for(;i&&!kM.get(i);)i=i.nextSibling;if(!i)return r+n.length;for(let e=0,t=r;;e++){let r=n.children[e];if(r.dom==i)return t;t+=r.length+r.breakAfter}}else if(n.isText())return e==n.dom?r+t:r+(t?n.length:0);else return r}domAtPos(e,t){let{tile:n,offset:r}=this.tile.resolveBlock(e,t);return n.isWidget()?n.domPosFor(r,t):n.domIn(r,t)}inlineDOMNearPos(e,t){let n,r=-1,i=!1,a,o=-1,s=!1;return this.tile.blockTiles((t,c)=>{if(t.isWidget()){if(t.flags&32&&c>=e)return!0;t.flags&16&&(i=!0)}else{let l=c+t.length;if(c<=e&&(n=t,r=e-c,i=l<e),l>=e&&!a&&(a=t,o=e-c,s=c>e),c>e&&a)return!0}}),!n&&!a?this.domAtPos(e,t):(i&&a?n=null:s&&n&&(a=null),n&&t<0||!a?n.domIn(r,t):a.domIn(o,t))}coordsAt(e,t,n){let{tile:r,offset:i}=this.tile.resolveBlock(e,t);return r.isWidget()?r.widget instanceof mN?null:r.coordsInWidget(i,t,!0):r.coordsIn(i,t,n)}lineAt(e,t){let{tile:n}=this.tile.resolveBlock(e,t);return n.isLine()?n:null}coordsForChar(e){let{tile:t,offset:n}=this.tile.resolveBlock(e,1);if(!t.isLine())return null;function r(e,t){if(e.isComposite())for(let n of e.children){if(n.length>=t){let e=r(n,t);if(e)return e}if(t-=n.length,t<0)break}else if(e.isText()&&t<e.length){let n=RO(e.text,t);if(n==t)return null;let r=_j(e.dom,t,n).getClientRects();for(let e=0;e<r.length;e++){let t=r[e];if(e==r.length-1||t.top<t.bottom&&t.left<t.right)return t}}return null}return r(t,n)}measureVisibleLineHeights(e){let t=[],{from:n,to:r}=e,i=this.view.contentDOM.clientWidth,a=i>Math.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,o=-1,s=this.view.textDirection==Tj.LTR,c=0,l=(e,u,d)=>{for(let f=0;f<e.children.length&&!(u>r);f++){let r=e.children[f],p=u+r.length,m=r.dom.getBoundingClientRect(),{height:h}=m;if(d&&!f&&(c+=m.top-d.top),r instanceof NM)p>n&&l(r,u,m);else if(u>=n&&(c>0&&t.push(-c),t.push(h+c),c=0,a)){let e=r.dom.lastChild,t=e?ej(e):[];if(t.length){let e=t[t.length-1],n=s?e.right-m.left:m.right-e.left;n>o&&(o=n,this.minWidth=i,this.minWidthFrom=u,this.minWidthTo=p)}}d&&f==e.children.length-1&&(c+=d.bottom-m.bottom),u=p+r.breakAfter}};return l(this.tile,0,null),t}textDirectionAt(e){let{tile:t}=this.tile.resolveBlock(e,1);return getComputedStyle(t.dom).direction==`rtl`?Tj.RTL:Tj.LTR}measureTextSize(){let e=this.tile.blockTiles(e=>{if(e.isLine()&&e.children.length&&e.length<=20){let t=0,n;for(let r of e.children){if(!r.isText()||/[^ -~]/.test(r.text))return;let e=ej(r.dom);if(e.length!=1)return;t+=e[0].width,n=e[0].height}if(t)return{lineHeight:e.dom.getBoundingClientRect().height,charWidth:t/e.length,textHeight:n}}});if(e)return e;let t=document.createElement(`div`),n,r,i;return t.className=`cm-line`,t.style.width=`99999px`,t.style.position=`absolute`,t.textContent=`abc def ghi jkl mno pqr stu`,this.view.observer.ignore(()=>{this.tile.dom.appendChild(t);let e=ej(t.firstChild)[0];n=t.getBoundingClientRect().height,r=e&&e.width?e.width/27:7,i=e&&e.height?e.height:n,t.remove()}),{lineHeight:n,charWidth:r,textHeight:i}}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let n=0,r=0;;r++){let i=r==t.viewports.length?null:t.viewports[r],a=i?i.from-1:this.view.state.doc.length;if(a>n){let r=(t.lineBlockAt(a).bottom-t.lineBlockAt(n).top)/this.view.scaleY;e.push(UA.replace({widget:new mN(r),block:!0,inclusive:!0,isBlockGap:!0}).range(n,a))}if(!i)break;n=i.to+1}return UA.set(e)}updateDeco(){let e=1,t=this.view.state.facet(_M).map(t=>(this.dynamicDecorationMap[e++]=typeof t==`function`)?t(this.view):t),n=!1,r=this.view.state.facet(yM).map((e,t)=>{let r=typeof e==`function`;return r&&(n=!0),r?e(this.view):e});for(r.length&&(this.dynamicDecorationMap[e++]=n,t.push($k.join(r))),this.decorations=[this.editContextFormatting,...t,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];e<this.decorations.length;)this.dynamicDecorationMap[e++]=!1;this.blockWrappers=this.view.state.facet(vM).map(e=>typeof e==`function`?e(this.view):e)}scrollIntoView(e){if(e.isSnapshot){let t=this.view.viewState.lineBlockAt(e.range.head);this.view.scrollDOM.scrollTop=t.top-e.yMargin,this.view.scrollDOM.scrollLeft=e.xMargin;return}for(let t of this.view.state.facet(aM))try{if(t(this.view,e.range,e))return!0}catch(e){lM(this.view.state,e,`scroll handler`)}let{range:t}=e,n=this.coordsAt(t.head,t.assoc||(t.head>t.anchor?-1:1)),r;if(!n)return;!t.empty&&(r=this.coordsAt(t.anchor,t.anchor>t.head?-1:1))&&(n={left:Math.min(n.left,r.left),top:Math.min(n.top,r.top),right:Math.max(n.right,r.right),bottom:Math.max(n.bottom,r.bottom)});let i=wM(this.view),a={left:n.left-i.left,top:n.top-i.top,right:n.right+i.right,bottom:n.bottom+i.bottom},{offsetWidth:o,offsetHeight:s}=this.view.scrollDOM;if(lj(this.view.scrollDOM,a,t.head<t.anchor?-1:1,e.x,e.y,Math.max(Math.min(e.xMargin,o),-o),Math.max(Math.min(e.yMargin,s),-s),this.view.textDirection==Tj.LTR),window.visualViewport&&window.innerHeight-window.visualViewport.height>1&&(n.top>window.visualViewport.offsetTop+window.visualViewport.height||n.bottom<window.visualViewport.offsetTop)){let e=this.view.docView.lineAt(t.head,1);if(e){let t=fj(e.dom);e.dom.scrollIntoView({block:`nearest`}),pj(t,!1)}}}lineHasWidget(e){let t=e=>e.isWidget()||e.children.some(t);return t(this.tile.resolveBlock(e,1).tile)}destroy(){rN(this.tile)}};function rN(e,t){let n=t?.get(e);if(n!=1){n??e.destroy();for(let n of e.children)rN(n,t)}}function iN(e){return e.node.nodeType==1&&e.node.firstChild&&(e.offset==0||e.node.childNodes[e.offset-1].contentEditable==`false`)&&(e.offset==e.node.childNodes.length||e.node.childNodes[e.offset].contentEditable==`false`)}function aN(e,t){let n=e.observer.selectionRange;if(!n.focusNode)return null;let r=Sj(n.focusNode,n.focusOffset),i=Cj(n.focusNode,n.focusOffset),a=r||i;if(i&&r&&i.node!=r.node){let t=kM.get(i.node);if(!t||t.isText()&&t.text!=i.node.nodeValue)a=i;else if(e.docView.lastCompositionAfterCursor){let e=kM.get(r.node);!e||e.isText()&&e.text!=r.node.nodeValue||(a=i)}}if(e.docView.lastCompositionAfterCursor=a!=r,!a)return null;let o=t-a.offset;return{from:o,to:o+a.node.nodeValue.length,node:a.node}}function oN(e,t,n){let r=aN(e,n);if(!r)return null;let{node:i,from:a,to:o}=r,s=i.nodeValue;if(/[\n\r]/.test(s)||e.state.doc.sliceString(r.from,r.to)!=s)return null;let c=t.invertedDesc;return{range:new EM(c.mapPos(a),c.mapPos(o),a,o),text:i}}function sN(e,t){return e.nodeType==1?(t&&e.childNodes[t-1].contentEditable==`false`?1:0)|(t<e.childNodes.length&&e.childNodes[t].contentEditable==`false`?2:0):0}var cN=class{constructor(){this.changes=[]}compareRange(e,t){YA(e,t,this.changes)}comparePoint(e,t){YA(e,t,this.changes)}boundChange(e){YA(e,e,this.changes)}};function lN(e,t,n){let r=new cN;return $k.compare(e,t,n,r),r.changes}var uN=class{constructor(){this.changes=[]}compareRange(e,t){YA(e,t,this.changes)}comparePoint(){}boundChange(e){YA(e,e,this.changes)}};function dN(e,t,n){let r=new uN;return $k.compare(e,t,n,r),r.changes}function fN(e,t){for(let n=e;n&&n!=t;n=n.assignedSlot||n.parentNode)if(n.nodeType==1&&n.contentEditable==`false`)return!0;return!1}function pN(e,t){let n=!1;return t&&e.iterChangedRanges((e,r)=>{e<t.to&&r>t.from&&(n=!0)}),n}var mN=class extends VA{constructor(e){super(),this.height=e}toDOM(){let e=document.createElement(`div`);return e.className=`cm-gap`,this.updateDOM(e),e}eq(e){return e.height==this.height}updateDOM(e){return e.style.height=this.height+`px`,!0}get editable(){return!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}};function hN(e,t,n=1){let r=e.charCategorizer(t),i=e.doc.lineAt(t),a=t-i.from;if(i.length==0)return Q.cursor(t);a==0?n=1:a==i.length&&(n=-1);let o=a,s=a;n<0?o=RO(i.text,a,!1):s=RO(i.text,a);let c=r(i.text.slice(o,s));for(;o>0;){let e=RO(i.text,o,!1);if(r(i.text.slice(e,o))!=c)break;o=e}for(;s<i.length;){let e=RO(i.text,s);if(r(i.text.slice(s,e))!=c)break;s=e}return Q.undirectionalRange(o+i.from,s+i.from)}function gN(e,t,n,r,i){let a=Math.round((r-t.left)*e.defaultCharacterWidth);if(e.lineWrapping&&n.height>e.defaultLineHeight*1.5){let t=e.viewState.heightOracle.textHeight,r=Math.floor((i-n.top-(e.defaultLineHeight-t)*.5)/t);a+=r*e.viewState.heightOracle.lineLength}let o=e.state.sliceDoc(n.from,n.to);return n.from+pA(o,a,e.state.tabSize)}function _N(e,t,n){let r=e.lineBlockAt(t);if(Array.isArray(r.type)){let e;for(let i of r.type){if(i.from>t)break;if(!(i.to<t)){if(i.from<t&&i.to>t)return i;(!e||i.type==HA.Text&&(e.type!=i.type||(n<0?i.from<t:i.to>t)))&&(e=i)}}return e||r}return r}function vN(e,t,n,r){let i=_N(e,t.head,t.assoc||-1),a=!r||i.type!=HA.Text||!(e.lineWrapping||i.widgetLineBreaks)?null:e.coordsAtPos(t.assoc<0&&t.head>i.from?t.head-1:t.head);if(a){let t=e.dom.getBoundingClientRect(),r=e.textDirectionAt(i.from),o=e.posAtCoords({x:n==(r==Tj.LTR)?t.right-1:t.left+1,y:(a.top+a.bottom)/2});if(o!=null)return Q.cursor(o,n?-1:1)}return Q.cursor(n?i.to:i.from,n?-1:1)}function yN(e,t,n,r){let i=e.state.doc.lineAt(t.head),a=e.bidiSpans(i),o=e.textDirectionAt(i.from);for(let s=t,c=null;;){let t=Kj(i,a,o,s,n),l=Gj;if(!t){if(i.number==(n?e.state.doc.lines:1))return s;l=`
|
|
33
|
+
`,i=e.state.doc.line(i.number+(n?1:-1)),a=e.bidiSpans(i),t=e.visualLineSide(i,!n)}if(!c){if(!r)return t;c=r(l)}else if(!c(l))return s;s=t}}function bN(e,t,n){let r=e.state.charCategorizer(t),i=r(n);return e=>{let t=r(e);return i==Vk.Space&&(i=t),i==t}}function xN(e,t,n,r){let i=t.head,a=n?1:-1;if(i==(n?e.state.doc.length:0))return Q.cursor(i,t.assoc);let o=t.goalColumn,s,c=e.contentDOM.getBoundingClientRect(),l=e.coordsAtPos(i,t.assoc||((t.empty?n:t.head==t.from)?1:-1)),u=e.documentTop;if(l)o??=l.left-c.left,s=a<0?l.top:l.bottom;else{let t=e.viewState.lineBlockAt(i);o??=Math.min(c.right-c.left,e.defaultCharacterWidth*(i-t.from)),s=(a<0?t.top:t.bottom)+u}let d=c.left+o,f=e.viewState.heightOracle.textHeight>>1,p=r??f;for(let t=0;;t+=f){let r=s+(p+t)*a,i=EN(e,{x:d,y:r},!1,a);if(n?r>c.bottom:r<c.top)return Q.cursor(i.pos,i.assoc);let l=e.coordsAtPos(i.pos,i.assoc),u=l?(l.top+l.bottom)/2:0;if(!l||(n?u>s:u<s))return Q.cursor(i.pos,i.assoc,void 0,o)}}function SN(e,t,n){for(;;){let r=0;for(let i of e)i.between(t-1,t+1,(e,i,a)=>{if(t>e&&t<i){let a=r||n||(t-e<i-t?-1:1);t=a<0?e:i,r=a}});if(!r)return t}}function CN(e,t){let n=null;for(let r=0;r<t.ranges.length;r++){let i=t.ranges[r],a=null;if(i.empty){let t=SN(e,i.from,0);t!=i.from&&(a=Q.cursor(t,-1))}else{let t=SN(e,i.from,-1),n=SN(e,i.to,1);(t!=i.from||n!=i.to)&&(a=i.undirectional?Q.undirectionalRange(i.from,i.to):Q.range(i.from==i.anchor?t:n,i.from==i.head?t:n))}a&&(n||=t.ranges.slice(),n[r]=a)}return n?Q.create(n,t.mainIndex):t}function wN(e,t,n){let r=SN(e.state.facet(bM).map(t=>t(e)),n.from,t.head>n.from?-1:1);return r==n.from?n:Q.cursor(r,r<n.from?1:-1)}var TN=class{constructor(e,t){this.pos=e,this.assoc=t}};function EN(e,t,n,r){let i=e.contentDOM.getBoundingClientRect(),a=i.top+e.viewState.paddingTop,{x:o,y:s}=t,c=s-a,l;for(;;){if(c<0)return new TN(0,1);if(c>e.viewState.docHeight)return new TN(e.state.doc.length,-1);if(l=e.elementAtHeight(c),r==null)break;if(l.type==HA.Text){if(r<0?l.to<e.viewport.from:l.from>e.viewport.to)break;let t=e.docView.coordsAt(r<0?l.from:l.to,r>0?-1:1);if(t&&(r<0?t.top<=c+a:t.bottom>=c+a))break}let t=e.viewState.heightOracle.textHeight/2;c=r>0?l.bottom+t:l.top-t}if(e.viewport.from>=l.to||e.viewport.to<=l.from){if(n)return null;if(l.type==HA.Text){let t=gN(e,i,l,o,s);return new TN(t,t==l.from?1:-1)}}if(l.type!=HA.Text)return c<(l.top+l.bottom)/2?new TN(l.from,1):new TN(l.to,-1);let u=e.docView.lineAt(l.from,2);return(!u||u.length!=l.length)&&(u=e.docView.lineAt(l.from,-2)),new DN(e,o,s,e.textDirectionAt(l.from)).scanTile(u,l.from)}var DN=class{constructor(e,t,n,r){this.view=e,this.x=t,this.y=n,this.baseDir=r,this.line=null,this.spans=null}bidiSpansAt(e){return(!this.line||this.line.from>e||this.line.to<e)&&(this.line=this.view.state.doc.lineAt(e),this.spans=this.view.bidiSpans(this.line)),this}baseDirAt(e,t){let{line:n,spans:r}=this.bidiSpansAt(e);return r[Fj.find(r,e-n.from,-1,t)].level==this.baseDir}dirAt(e,t){let{line:n,spans:r}=this.bidiSpansAt(e);return r[Fj.find(r,e-n.from,-1,t)].dir}bidiIn(e,t){let{spans:n,line:r}=this.bidiSpansAt(e);return n.length>1||n.length&&(n[0].level!=this.baseDir||n[0].to+r.from<t)}scan(e,t,n=!1){let r=0,i=e.length-1,a=new Set,o=this.bidiIn(e[0],e[i]),s,c,l=-1,u=1e9,d;search:for(;r<i;){let n=i-r,f=r+i>>1;adjust:if(a.has(f)){for(let e=1;e<n;e++){let t=f+e;if(t>=i&&(t-=n),!a.has(t)){f=t;break adjust}}break search}a.add(f);let p=t(f),m=0;if(p)for(let e=0;e<p.length;e++){let t=p[e];if(!(t.width==0&&p.length>1)){if(t.bottom<this.y)(!s||s.bottom<t.bottom)&&(s=t),m=1;else if(t.top>this.y)(!c||c.top>t.top)&&(c=t),m=-1;else{let e=t.left>this.x?this.x-t.left:t.right<this.x?this.x-t.right:0,n=Math.abs(e);n<u&&(l=f,u=n,d=t),e&&(m=e<0==(this.baseDir==Tj.LTR)?-1:1)}}}m==-1&&(!o||this.baseDirAt(e[f],1))?i=f:m==1&&(!o||this.baseDirAt(e[f+1],-1))&&(r=f+1)}if(!d){if(!c&&!s)return{i:e[0],after:!1};let n=s&&(!c||this.y-s.bottom<c.top-this.y)?s:c;return this.y=(n.top+n.bottom)/2,this.scan(e,t,!0)}if(u&&!n){let{top:n,bottom:r}=d;if(s&&s.bottom>(n+n+r)/3)return this.y=s.bottom-1,this.scan(e,t,!0);if(c&&c.top<(n+r+r)/3)return this.y=c.top+1,this.scan(e,t,!0)}let f=(o?this.dirAt(e[l],1):this.baseDir)==Tj.LTR;return{i:l,after:this.x>(d.left+d.right)/2==f}}scanText(e,t){let n=[];for(let r=0;r<e.length;r=RO(e.text,r))n.push(t+r);n.push(t+e.length);let r=this.scan(n,r=>{let i=n[r]-t,a=n[r+1]-t;return _j(e.dom,i,a).getClientRects()});return r.after?new TN(n[r.i+1],-1):new TN(n[r.i],1)}scanTile(e,t){if(!e.length)return new TN(t,1);if(e.children.length==1){let n=e.children[0];if(n.isText())return this.scanText(n,t);if(n.isComposite())return this.scanTile(n,t)}let n=[t];for(let r=0,i=t;r<e.children.length;r++)n.push(i+=e.children[r].length);let r=this.scan(n,t=>{let n=e.children[t];return n.flags&48?null:(n.dom.nodeType==1?n.dom:_j(n.dom,0,n.length)).getClientRects()}),i=e.children[r.i],a=n[r.i];return i.isText()?this.scanText(i,a):i.isComposite()?this.scanTile(i,a):r.after?new TN(n[r.i+1],-1):new TN(a,1)}},ON=``,kN=class{constructor(e,t){this.points=e,this.view=t,this.text=``,this.lineSeparator=t.state.facet(Kk.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=ON}readRange(e,t){if(!e)return this;let n=e.parentNode;for(let r=e;;){this.findPointBefore(n,r);let e=this.text.length;this.readNode(r);let i=kM.get(r),a=r.nextSibling;if(a==t){i?.breakAfter&&!a&&n!=this.view.contentDOM&&this.lineBreak();break}let o=kM.get(a);(i&&o?i.breakAfter:(i?i.breakAfter:rj(r))||rj(a)&&(r.nodeName!=`BR`||i?.isWidget())&&this.text.length>e)&&!jN(a,t)&&this.lineBreak(),r=a}return this.findPointBefore(n,t),this}readTextNode(e){let t=e.nodeValue;for(let n of this.points)n.node==e&&(n.pos=this.text.length+Math.min(n.offset,t.length));for(let n=0,r=this.lineSeparator?null:/\r\n?|\n/g;;){let i=-1,a=1,o;if(this.lineSeparator?(i=t.indexOf(this.lineSeparator,n),a=this.lineSeparator.length):(o=r.exec(t))&&(i=o.index,a=o[0].length),this.append(t.slice(n,i<0?t.length:i)),i<0)break;if(this.lineBreak(),a>1)for(let t of this.points)t.node==e&&t.pos>this.text.length&&(t.pos-=a-1);n=i+a}}readNode(e){let t=kM.get(e),n=t&&t.overrideDOMText;if(n!=null){this.findPointInside(e,n.length);for(let e=n.iter();!e.next().done;)e.lineBreak?this.lineBreak():this.append(e.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName==`BR`?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let n of this.points)n.node==e&&e.childNodes[n.offset]==t&&(n.pos=this.text.length)}findPointInside(e,t){for(let n of this.points)(e.nodeType==3?n.node==e:e.contains(n.node))&&(n.pos=this.text.length+(AN(e,n.node,n.offset)?t:0))}};function AN(e,t,n){for(;;){if(!t||n<aj(t))return!1;if(t==e)return!0;n=nj(t)+1,t=t.parentNode}}function jN(e,t){let n;for(;!(e==t||!e);e=e.nextSibling){let t=kM.get(e);if(!t?.isWidget())return!1;t&&(n||=[]).push(t)}if(n){for(let e of n)if(e.overrideDOMText?.length)return!1}return!0}var MN=class{constructor(e,t){this.node=e,this.offset=t,this.pos=-1}},NN=class{constructor(e,t,n,r){this.typeOver=r,this.bounds=null,this.text=``,this.domChanged=t>-1;let{impreciseHead:i,impreciseAnchor:a}=e.docView,o=e.state.selection;if(e.state.readOnly&&t>-1)this.newSel=null;else if(t>-1&&(this.bounds=PN(e.docView.tile,t,n,0))){let t=i||a?[]:zN(e),n=new kN(t,e);n.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=n.text,this.newSel=BN(t,this.bounds.from)}else{let t=e.observer.selectionRange,n=i&&i.node==t.focusNode&&i.offset==t.focusOffset||!QA(e.contentDOM,t.focusNode)?o.main.head:e.docView.posFromDOM(t.focusNode,t.focusOffset),r=a&&a.node==t.anchorNode&&a.offset==t.anchorOffset||!QA(e.contentDOM,t.anchorNode)?o.main.anchor:e.docView.posFromDOM(t.anchorNode,t.anchorOffset),s=e.viewport;if((PA.ios||PA.chrome)&&n!=r&&Math.min(n,r)<=o.main.from&&Math.max(n,r)>=o.main.to&&(s.from>0||s.to<e.state.doc.length)){let t=Math.min(n,r),i=Math.max(n,r),a=s.from-t,o=s.to-i;(a==0||a==1||t==0)&&(o==0||o==-1||i==e.state.doc.length)&&(n=0,r=e.state.doc.length)}if(e.inputState.composing>-1&&o.ranges.length>1)this.newSel=o.replaceRange(Q.range(r,n));else if(e.lineWrapping&&r==n&&!(o.main.empty&&o.main.head==n)&&e.inputState.lastTouchTime>Date.now()-100){let t=e.coordsAtPos(n,-1),r=0;t&&(r=e.inputState.lastTouchY<=t.bottom?-1:1),this.newSel=Q.create([Q.cursor(n,r)])}else this.newSel=Q.single(r,n)}}};function PN(e,t,n,r){if(e.isComposite()){let i=-1,a=-1,o=-1,s=-1;for(let c=0,l=r,u=r;c<e.children.length;c++){let r=e.children[c],d=l+r.length;if(l<t&&d>n)return PN(r,t,n,l);if(d>=t&&i==-1&&(i=c,a=l),l>n&&r.dom.parentNode==e.dom){o=c,s=u;break}u=d,l=d+r.breakAfter}return{from:a,to:s<0?r+e.length:s,startDOM:(i?e.children[i-1].dom.nextSibling:null)||e.dom.firstChild,endDOM:o<e.children.length&&o>=0?e.children[o].dom:null}}return e.isText()?{from:r,to:r+e.length,startDOM:e.dom,endDOM:e.dom.nextSibling}:null}function FN(e,t){let n,{newSel:r}=t,{state:i}=e,a=i.selection.main,o=e.inputState.lastKeyTime>Date.now()-100?e.inputState.lastKeyCode:-1;if(t.bounds){let{from:e,to:r}=t.bounds,s=a.from,c=null;(o===8||PA.android&&t.text.length<r-e)&&(s=a.to,c=`end`);let l=i.doc.sliceString(e,r,ON),u,d;!a.empty&&a.from>=e&&a.to<=r&&(t.typeOver||l!=t.text)&&l.slice(0,a.from-e)==t.text.slice(0,a.from-e)&&l.slice(a.to-e)==t.text.slice(u=t.text.length-(l.length-(a.to-e)))?n={from:a.from,to:a.to,insert:DO.of(t.text.slice(a.from-e,u).split(ON))}:(d=RN(l,t.text,s-e,c))&&(PA.chrome&&o==13&&d.toB==d.from+2&&t.text.slice(d.from,d.toB)==``&&d.toB--,n={from:e+d.from,to:e+d.toA,insert:DO.of(t.text.slice(d.from,d.toB).split(ON))})}else r&&(!e.hasFocus&&i.facet(uM)||VN(r,a))&&(r=null);if(!n&&!r)return!1;if((PA.mac||PA.android)&&n&&n.from==n.to&&n.from==a.head-1&&/^\. ?$/.test(n.insert.toString())&&e.contentDOM.getAttribute(`autocorrect`)==`off`?(r&&n.insert.length==2&&(r=Q.single(r.main.anchor-1,r.main.head-1)),n={from:n.from,to:n.to,insert:DO.of([n.insert.toString().replace(`.`,` `)])}):i.doc.lineAt(a.from).to<a.to&&e.docView.lineHasWidget(a.to)&&e.inputState.insertingTextAt>Date.now()-50?n={from:a.from,to:a.to,insert:i.toText(e.inputState.insertingText)}:PA.chrome&&n&&n.from==n.to&&n.from==a.head&&n.insert.toString()==`
|
|
34
|
+
`&&e.lineWrapping&&(r&&=Q.single(r.main.anchor-1,r.main.head-1),n={from:a.from,to:a.to,insert:DO.of([` `])}),n)return IN(e,n,r,o);if(r&&!VN(r,a)){let t=!1,n=`select`;return e.inputState.lastSelectionTime>Date.now()-50&&(e.inputState.lastSelectionOrigin==`select`&&(t=!0),n=e.inputState.lastSelectionOrigin,n==`select.pointer`&&(r=CN(i.facet(bM).map(t=>t(e)),r))),e.dispatch({selection:r,scrollIntoView:t,userEvent:n}),!0}return!1}function IN(e,t,n,r=-1){if(PA.ios&&e.inputState.flushIOSKey(t))return!0;let i=e.state.selection.main;if(PA.android&&(t.to==i.to&&(t.from==i.from||t.from==i.from-1&&e.state.sliceDoc(t.from,i.from)==` `)&&t.insert.length==1&&t.insert.lines==2&&vj(e.contentDOM,`Enter`,13)||(t.from==i.from-1&&t.to==i.to&&t.insert.length==0||r==8&&t.insert.length<t.to-t.from&&t.to>i.head)&&vj(e.contentDOM,`Backspace`,8)||t.from==i.from&&t.to==i.to+1&&t.insert.length==0&&vj(e.contentDOM,`Delete`,46)))return!0;let a=t.insert.toString();e.inputState.composing>=0&&e.inputState.composing++;let o,s=()=>o||=LN(e,t,n);return e.state.facet($j).some(n=>n(e,t.from,t.to,a,s))||e.dispatch(s()),!0}function LN(e,t,n){let r,i=e.state,a=i.selection.main,o=-1;if(t.from==t.to&&t.from<a.from||t.from>a.to){let n=t.from<a.from?-1:1,r=n<0?a.from:a.to,s=SN(i.facet(bM).map(t=>t(e)),r,n);t.from==s&&(o=s)}if(o>-1)r={changes:t,selection:Q.cursor(t.from+t.insert.length,-1)};else if(t.from>=a.from&&t.to<=a.to&&t.to-t.from>=(a.to-a.from)/3&&(!n||n.main.empty&&n.main.from==t.from+t.insert.length)&&e.inputState.composing<0){let n=a.from<t.from?i.sliceDoc(a.from,t.from):``,o=a.to>t.to?i.sliceDoc(t.to,a.to):``;r=i.replaceSelection(e.state.toText(n+t.insert.sliceString(0,void 0,e.state.lineBreak)+o))}else{let o=i.changes(t),s=n&&n.main.to<=o.newLength?n.main:void 0;if(i.selection.ranges.length>1&&(e.inputState.composing>=0||e.inputState.compositionPendingChange)&&t.to<=a.to+10&&t.to>=a.to-10){let c=e.state.sliceDoc(t.from,t.to),l,u=n&&aN(e,n.main.head);if(u){let e=t.insert.length-(t.to-t.from);l={from:u.from,to:u.to-e}}else l=e.state.doc.lineAt(a.head);let d=a.to-t.to;r=i.changeByRange(n=>{if(n.from==a.from&&n.to==a.to)return{changes:o,range:s||n.map(o)};let r=n.to-d,u=r-c.length;if(e.state.sliceDoc(u,r)!=c||r>=l.from&&u<=l.to)return{range:n};let f=i.changes({from:u,to:r,insert:t.insert}),p=n.to-a.to;return{changes:f,range:s?Q.range(Math.max(0,s.anchor+p),Math.max(0,s.head+p)):n.map(f)}})}else r={changes:o,selection:s&&i.selection.replaceRange(s)}}let s=`input.type`;return(e.composing||e.inputState.compositionPendingChange&&e.inputState.compositionEndedAt>Date.now()-50)&&(e.inputState.compositionPendingChange=!1,s+=`.compose`,e.inputState.compositionFirstChange&&(s+=`.start`,e.inputState.compositionFirstChange=!1)),i.update(r,{userEvent:s,scrollIntoView:!0})}function RN(e,t,n,r){let i=Math.min(e.length,t.length),a=0;for(;a<i&&e.charCodeAt(a)==t.charCodeAt(a);)a++;if(a==i&&e.length==t.length)return null;let o=e.length,s=t.length;for(;o>0&&s>0&&e.charCodeAt(o-1)==t.charCodeAt(s-1);)o--,s--;if(r==`end`){let e=Math.max(0,a-Math.min(o,s));n-=o+e-a}if(o<a&&e.length<t.length){let e=n<=a&&n>=o?a-n:0;a-=e,s=a+(s-o),o=a}else if(s<a){let e=n<=a&&n>=s?a-n:0;a-=e,o=a+(o-s),s=a}return{from:a,toA:o,toB:s}}function zN(e){let t=[];if(e.root.activeElement!=e.contentDOM)return t;let{anchorNode:n,anchorOffset:r,focusNode:i,focusOffset:a}=e.observer.selectionRange;return n&&(t.push(new MN(n,r)),(i!=n||a!=r)&&t.push(new MN(i,a))),t}function BN(e,t){if(e.length==0)return null;let n=e[0].pos,r=e.length==2?e[1].pos:n;return n>-1&&r>-1?Q.single(n+t,r+t):null}function VN(e,t){return t.head==e.main.head&&t.anchor==e.main.anchor}var HN=class{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.touchActive=!1,this.lastTouchTime=0,this.lastTouchX=0,this.lastTouchY=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.lastWheelEvent=0,this.pendingIOSKey=void 0,this.lastIOSMomentumScroll=0,this.tabFocusMode=-1,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.insertingText=``,this.insertingTextAt=0,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,PA.safari&&e.contentDOM.addEventListener(`input`,()=>null),PA.gecko&&TP(e.contentDOM.ownerDocument)}handleEvent(e){!nP(this.view,e)||this.ignoreDuringComposition(e)||e.type==`keydown`&&this.keydown(e)||(this.view.updateState==0?this.runHandlers(e.type,e):Promise.resolve().then(()=>this.runHandlers(e.type,e)))}runHandlers(e,t){let n=this.handlers[e];if(n){for(let e of n.observers)e(this.view,t);for(let e of n.handlers){if(t.defaultPrevented)break;if(e(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=GN(e),n=this.handlers,r=this.view.contentDOM;for(let e in t)if(e!=`scroll`){let i=!t[e].handlers.length,a=n[e];a&&i!=!a.handlers.length&&(r.removeEventListener(e,this.handleEvent),a=null),a||r.addEventListener(e,this.handleEvent,{passive:i})}for(let e in n)e!=`scroll`&&!t[e]&&r.removeEventListener(e,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&this.tabFocusMode>-1&&(!this.tabFocusMode||Date.now()<=this.tabFocusMode))return!0;if(this.tabFocusMode>0&&e.keyCode!=27&&JN.indexOf(e.keyCode)<0&&(this.tabFocusMode=-1),PA.android&&PA.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;if(PA.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&(KN.some(t=>t.keyCode==e.keyCode)&&!e.ctrlKey||qN.indexOf(e.key)>-1&&e.ctrlKey)){let t={ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey,shiftKey:e.shiftKey};return t.shiftKey&&PA.ios&&!/^(off|none)$/.test(this.view.contentDOM.autocapitalize)&&UN(this.view.win)&&(t.shiftKey=!1),this.pendingIOSKey={key:e.key,keyCode:e.keyCode,mods:t},setTimeout(()=>this.flushIOSKey(),250),!0}return e.keyCode!=229&&this.view.observer.forceFlush(),!1}flushIOSKey(e){let t=this.pendingIOSKey;return!t||t.key==`Enter`&&e&&e.from<e.to&&/^\S+$/.test(e.insert.toString())?!1:(this.pendingIOSKey=void 0,vj(this.view.contentDOM,t.key,t.keyCode,t.mods))}ignoreDuringComposition(e){return!/^key/.test(e.type)||e.synthetic?!1:this.composing>0?!0:PA.safari&&!PA.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.view.observer.update(e),this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}};function UN(e){return e.visualViewport?e.visualViewport.height*e.visualViewport.scale/e.document.documentElement.clientHeight<.85:!1}function WN(e,t){return(n,r)=>{try{return t.call(e,r,n)}catch(e){lM(n.state,e)}}}function GN(e){let t=Object.create(null);function n(e){return t[e]||(t[e]={observers:[],handlers:[]})}for(let t of e){let e=t.spec,r=e&&e.plugin.domEventHandlers,i=e&&e.plugin.domEventObservers;if(r)for(let e in r){let i=r[e];i&&n(e).handlers.push(WN(t.value,i))}if(i)for(let e in i){let r=i[e];r&&n(e).observers.push(WN(t.value,r))}}for(let e in rP)n(e).handlers.push(rP[e]);for(let e in iP)n(e).observers.push(iP[e]);return t}var KN=[{key:`Backspace`,keyCode:8,inputType:`deleteContentBackward`},{key:`Enter`,keyCode:13,inputType:`insertParagraph`},{key:`Enter`,keyCode:13,inputType:`insertLineBreak`},{key:`Delete`,keyCode:46,inputType:`deleteContentForward`}],qN=`dthko`,JN=[16,17,18,20,91,92,224,225],YN=6;function XN(e){return Math.max(0,e)*.7+8}function ZN(e,t){return Math.max(Math.abs(e.clientX-t.clientX),Math.abs(e.clientY-t.clientY))}var QN=class{constructor(e,t,n,r){this.view=e,this.startEvent=t,this.style=n,this.mustSelect=r,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParents=uj(e.contentDOM),this.atoms=e.state.facet(bM).map(t=>t(e));let i=e.contentDOM.ownerDocument;i.addEventListener(`mousemove`,this.move=this.move.bind(this)),i.addEventListener(`mouseup`,this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(Kk.allowMultipleSelections)&&$N(e,t),this.dragging=tP(e,t)&&mP(t)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&ZN(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let t=0,n=0,r=0,i=0,a=this.view.win.innerWidth,o=this.view.win.innerHeight;this.scrollParents.x&&({left:r,right:a}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:i,bottom:o}=this.scrollParents.y.getBoundingClientRect());let s=wM(this.view);e.clientX-s.left<=r+YN?t=-XN(r-e.clientX):e.clientX+s.right>=a-YN&&(t=XN(e.clientX-a)),e.clientY-s.top<=i+YN?n=-XN(i-e.clientY):e.clientY+s.bottom>=o-YN&&(n=XN(e.clientY-o)),this.setScrollSpeed(t,n)}up(e){this.dragging??this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener(`mousemove`,this.move),e.removeEventListener(`mouseup`,this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,t){this.scrollSpeed={x:e,y:t},e||t?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){let{x:e,y:t}=this.scrollSpeed;e&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=e,e=0),t&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=t,t=0),(e||t)&&this.view.win.scrollBy(e,t),this.dragging===!1&&this.select(this.lastEvent)}select(e){let{view:t}=this,n=CN(this.atoms,this.style.get(e,this.extend,this.multiple));(this.mustSelect||!n.eq(t.state.selection,this.dragging===!1))&&this.view.dispatch({selection:n,userEvent:`select.pointer`}),this.mustSelect=!1}update(e){e.transactions.some(e=>e.isUserEvent(`input.type`))?this.destroy():this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}};function $N(e,t){let n=e.state.facet(Jj);return n.length?n[0](t):PA.mac?t.metaKey:t.ctrlKey}function eP(e,t){let n=e.state.facet(Yj);return n.length?n[0](t):PA.mac?!t.altKey:!t.ctrlKey}function tP(e,t){let{main:n}=e.state.selection;if(n.empty)return!1;let r=ZA(e.root);if(!r||r.rangeCount==0)return!0;let i=r.getRangeAt(0).getClientRects();for(let e=0;e<i.length;e++){let n=i[e];if(n.left<=t.clientX&&n.right>=t.clientX&&n.top<=t.clientY&&n.bottom>=t.clientY)return!0}return!1}function nP(e,t){if(!t.bubbles)return!0;if(t.defaultPrevented)return!1;for(let n=t.target,r;n!=e.contentDOM;n=n.parentNode)if(!n||n.nodeType==11||(r=kM.get(n))&&r.isWidget()&&!r.isHidden&&r.widget.ignoreEvent(t))return!1;return!0}var rP=Object.create(null),iP=Object.create(null),aP=PA.ie&&PA.ie_version<15||PA.ios&&PA.webkit_version<604;function oP(e){let t=e.dom.parentNode;if(!t)return;let n=t.appendChild(document.createElement(`textarea`));n.style.cssText=`position: fixed; left: -10000px; top: 10px`,n.focus(),setTimeout(()=>{e.focus(),n.remove(),cP(e,n.value)},50)}function sP(e,t,n){for(let r of e.facet(t))n=r(n,e);return n}function cP(e,t){t=sP(e.state,tM,t);let{state:n}=e,r,i=1,a=n.toText(t),o=a.lines==n.selection.ranges.length;if(bP!=null&&n.selection.ranges.every(e=>e.empty)&&bP==a.toString()){let e=-1;r=n.changeByRange(r=>{let s=n.doc.lineAt(r.from);if(s.from==e)return{range:r};e=s.from;let c=n.toText((o?a.line(i++).text:t)+n.lineBreak);return{changes:{from:s.from,insert:c},range:Q.cursor(r.from+c.length)}})}else r=o?n.changeByRange(e=>{let t=a.line(i++);return{changes:{from:e.from,to:e.to,insert:t.text},range:Q.cursor(e.from+t.length)}}):n.replaceSelection(a);e.dispatch(r,{userEvent:`input.paste`,scrollIntoView:!0})}iP.scroll=e=>{let t=e.inputState;t.lastScrollTop=e.scrollDOM.scrollTop,t.lastScrollLeft=e.scrollDOM.scrollLeft,PA.ios&&!t.touchActive&&(t.lastIOSMomentumScroll=Date.now())},iP.wheel=iP.mousewheel=e=>{e.inputState.lastWheelEvent=Date.now()},rP.keydown=(e,t)=>(e.inputState.setSelectionOrigin(`select`),t.keyCode==27&&e.inputState.tabFocusMode!=0&&(e.inputState.tabFocusMode=Date.now()+2e3),!1),iP.touchstart=(e,t)=>{let n=e.inputState,r=t.targetTouches[0];n.touchActive=!0,n.lastTouchTime=Date.now(),r&&(n.lastTouchX=r.clientX,n.lastTouchY=r.clientY),n.setSelectionOrigin(`select.pointer`)},iP.touchmove=e=>{e.inputState.setSelectionOrigin(`select.pointer`)},iP.touchend=(e,t)=>{e.inputState.touchActive=!1},rP.mousedown=(e,t)=>{if(e.observer.flush(),e.inputState.lastTouchTime>Date.now()-2e3)return!1;let n=null;for(let r of e.state.facet(Xj))if(n=r(e,t),n)break;if(!n&&t.button==0&&(n=hP(e,t)),n){let r=!e.hasFocus;e.inputState.startMouseSelection(new QN(e,t,n,r)),r&&e.observer.ignore(()=>{hj(e.contentDOM);let t=e.root.activeElement;t&&!t.contains(e.contentDOM)&&t.blur()});let i=e.inputState.mouseSelection;if(i)return i.start(t),i.dragging===!1}else e.inputState.setSelectionOrigin(`select.pointer`);return!1};function lP(e,t,n,r){if(r==1)return Q.cursor(t,n);if(r==2)return hN(e.state,t,n);{let r=e.docView.lineAt(t,n),i=e.state.doc.lineAt(r?r.posAtEnd:t),a=r?r.posAtStart:i.from,o=r?r.posAtEnd:i.to;return o<e.state.doc.length&&o==i.to&&o++,Q.undirectionalRange(a,o)}}var uP=PA.ie&&PA.ie_version<=11,dP=null,fP=0,pP=0;function mP(e){if(!uP)return e.detail;let t=dP,n=pP;return dP=e,pP=Date.now(),fP=!t||n>Date.now()-400&&Math.abs(t.clientX-e.clientX)<2&&Math.abs(t.clientY-e.clientY)<2?(fP+1)%3:1}function hP(e,t){let n=e.posAndSideAtCoords({x:t.clientX,y:t.clientY},!1),r=mP(t),i=e.state.selection;return{update(e){e.docChanged&&(n.pos=e.changes.mapPos(n.pos),i=i.map(e.changes))},get(t,a,o){let s=e.posAndSideAtCoords({x:t.clientX,y:t.clientY},!1),c,l=lP(e,s.pos,s.assoc,r);if(n.pos!=s.pos&&!a){let t=lP(e,n.pos,n.assoc,r),i=Math.min(t.from,l.from),a=Math.max(t.to,l.to);l=i<l.from?Q.range(i,a,l.assoc):Q.range(a,i,l.assoc)}return a?i.replaceRange(i.main.extend(l.from,l.to,l.assoc)):o&&r==1&&i.ranges.length>1&&(c=gP(i,s.pos))?c:o?i.addRange(l):Q.create([l])}}}function gP(e,t){for(let n=0;n<e.ranges.length;n++){let{from:r,to:i}=e.ranges[n];if(r<=t&&i>=t)return Q.create(e.ranges.slice(0,n).concat(e.ranges.slice(n+1)),e.mainIndex==n?0:e.mainIndex-+(e.mainIndex>n))}return null}rP.dragstart=(e,t)=>{let{selection:{main:n}}=e.state;if(t.target.draggable){let r=e.docView.tile.nearest(t.target);if(r&&r.isWidget()){let e=r.posAtStart,t=e+r.length;(e>=n.to||t<=n.from)&&(n=Q.undirectionalRange(e,t))}}let{inputState:r}=e;return r.mouseSelection&&(r.mouseSelection.dragging=!0),r.draggedContent=n,t.dataTransfer&&(t.dataTransfer.setData(`Text`,sP(e.state,nM,e.state.sliceDoc(n.from,n.to))),t.dataTransfer.effectAllowed=`copyMove`),!1},rP.dragend=e=>(e.inputState.draggedContent=null,!1);function _P(e,t,n,r){if(n=sP(e.state,tM,n),!n)return;let i=e.posAtCoords({x:t.clientX,y:t.clientY},!1),{draggedContent:a}=e.inputState,o=r&&a&&eP(e,t)?{from:a.from,to:a.to}:null,s={from:i,insert:n},c=e.state.changes(o?[o,s]:s);e.focus(),e.dispatch({changes:c,selection:{anchor:c.mapPos(i,-1),head:c.mapPos(i,1)},userEvent:o?`move.drop`:`input.drop`}),e.inputState.draggedContent=null}rP.drop=(e,t)=>{if(!t.dataTransfer)return!1;if(e.state.readOnly)return!0;let n=t.dataTransfer.files;if(n&&n.length){let r=Array(n.length),i=0,a=()=>{++i==n.length&&_P(e,t,r.filter(e=>e!=null).join(e.state.lineBreak),!1)};for(let e=0;e<n.length;e++){let t=new FileReader;t.onerror=a,t.onload=()=>{/[\x00-\x08\x0e-\x1f]{2}/.test(t.result)||(r[e]=t.result),a()},t.readAsText(n[e])}return!0}{let n=t.dataTransfer.getData(`Text`);if(n)return _P(e,t,n,!0),!0}return!1},rP.paste=(e,t)=>{if(e.state.readOnly)return!0;e.observer.flush();let n=aP?null:t.clipboardData;return n?(cP(e,n.getData(`text/plain`)||n.getData(`text/uri-list`)),!0):(oP(e),!1)};function vP(e,t){let n=e.dom.parentNode;if(!n)return;let r=n.appendChild(document.createElement(`textarea`));r.style.cssText=`position: fixed; left: -10000px; top: 10px`,r.value=t,r.focus(),r.selectionEnd=t.length,r.selectionStart=0,setTimeout(()=>{r.remove(),e.focus()},50)}function yP(e){let t=[],n=[],r=!1;for(let r of e.selection.ranges)r.empty||(t.push(e.sliceDoc(r.from,r.to)),n.push(r));if(!t.length){let i=-1;for(let{from:r}of e.selection.ranges){let a=e.doc.lineAt(r);a.number>i&&(t.push(a.text),n.push({from:a.from,to:Math.min(e.doc.length,a.to+1)})),i=a.number}r=!0}return{text:sP(e,nM,t.join(e.lineBreak)),ranges:n,linewise:r}}var bP=null;rP.copy=rP.cut=(e,t)=>{if(!$A(e.contentDOM,e.observer.selectionRange))return!1;let{text:n,ranges:r,linewise:i}=yP(e.state);if(!n&&!i)return!1;bP=i?n:null,t.type==`cut`&&!e.state.readOnly&&e.dispatch({changes:r,scrollIntoView:!0,userEvent:`delete.cut`});let a=aP?null:t.clipboardData;return a?(a.clearData(),a.setData(`text/plain`,n),!0):(vP(e,n),!1)};var xP=Ok.define();function SP(e,t){let n=[];for(let r of e.facet(eM)){let i=r(e,t);i&&n.push(i)}return n.length?e.update({effects:n,annotations:xP.of(!0)}):null}function CP(e){setTimeout(()=>{let t=e.hasFocus;if(t!=e.inputState.notifiedFocused){let n=SP(e.state,t);n?e.dispatch(n):e.update([])}},10)}iP.focus=e=>{e.inputState.lastFocusTime=Date.now(),!e.scrollDOM.scrollTop&&(e.inputState.lastScrollTop||e.inputState.lastScrollLeft)&&(e.scrollDOM.scrollTop=e.inputState.lastScrollTop,e.scrollDOM.scrollLeft=e.inputState.lastScrollLeft),CP(e)},iP.blur=e=>{e.observer.clearSelectionRange(),CP(e)},iP.compositionstart=iP.compositionupdate=e=>{e.observer.editContext||(e.inputState.compositionFirstChange??(e.inputState.compositionFirstChange=!0),e.inputState.composing<0&&(e.inputState.composing=0))},iP.compositionend=e=>{e.observer.editContext||(e.inputState.composing=-1,e.inputState.compositionEndedAt=Date.now(),e.inputState.compositionPendingKey=!0,e.inputState.compositionPendingChange=e.observer.pendingRecords().length>0,e.inputState.compositionFirstChange=null,PA.chrome&&PA.android?e.observer.flushSoon():e.inputState.compositionPendingChange?Promise.resolve().then(()=>e.observer.flush()):setTimeout(()=>{e.inputState.composing<0&&e.docView.hasComposition&&e.update([])},50))},iP.contextmenu=e=>{e.inputState.lastContextMenu=Date.now()},rP.beforeinput=(e,t)=>{if((t.inputType==`insertText`||t.inputType==`insertCompositionText`)&&(e.inputState.insertingText=t.data,e.inputState.insertingTextAt=Date.now()),t.inputType==`insertReplacementText`&&e.observer.editContext){let n=t.dataTransfer?.getData(`text/plain`),r=t.getTargetRanges();if(n&&r.length){let t=r[0];return IN(e,{from:e.posAtDOM(t.startContainer,t.startOffset),to:e.posAtDOM(t.endContainer,t.endOffset),insert:e.state.toText(n)},null),!0}}let n;if(PA.chrome&&PA.android&&(n=KN.find(e=>e.inputType==t.inputType))&&(e.observer.delayAndroidKey(n.key,n.keyCode),n.key==`Backspace`||n.key==`Delete`)){let t=window.visualViewport?.height||0;setTimeout(()=>{(window.visualViewport?.height||0)>t+10&&e.hasFocus&&(e.contentDOM.blur(),e.focus())},100)}return PA.ios&&t.inputType==`deleteContentForward`&&e.observer.flushSoon(),PA.safari&&t.inputType==`insertText`&&e.inputState.composing>=0&&setTimeout(()=>iP.compositionend(e,t),20),!1};var wP=new Set;function TP(e){wP.has(e)||(wP.add(e),e.addEventListener(`copy`,()=>{}),e.addEventListener(`cut`,()=>{}))}var EP=[`pre-wrap`,`normal`,`pre-line`,`break-spaces`],DP=!1;function OP(){DP=!1}var kP=class{constructor(e){this.lineWrapping=e,this.doc=DO.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30}heightForGap(e,t){let n=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(n+=Math.max(0,Math.ceil((t-e-n*this.lineLength*.5)/this.lineLength))),this.lineHeight*n}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/Math.max(1,this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return EP.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let n=0;n<e.length;n++){let r=e[n];r<0?n++:this.heightSamples[Math.floor(r*10)]||(t=!0,this.heightSamples[Math.floor(r*10)]=!0)}return t}refresh(e,t,n,r,i,a){let o=EP.indexOf(e)>-1,s=Math.abs(t-this.lineHeight)>.3||this.lineWrapping!=o;if(this.lineWrapping=o,this.lineHeight=t,this.charWidth=n,this.textHeight=r,this.lineLength=i,s){this.heightSamples={};for(let e=0;e<a.length;e++){let t=a[e];t<0?e++:this.heightSamples[Math.floor(t*10)]=!0}}return s}},AP=class{constructor(e,t){this.from=e,this.heights=t,this.index=0}get more(){return this.index<this.heights.length}},jP=class e{constructor(e,t,n,r,i){this.from=e,this.length=t,this.top=n,this.height=r,this._content=i}get type(){return typeof this._content==`number`?HA.Text:Array.isArray(this._content)?this._content:this._content.type}get to(){return this.from+this.length}get bottom(){return this.top+this.height}get widget(){return this._content instanceof KA?this._content.widget:null}get widgetLineBreaks(){return typeof this._content==`number`?this._content:0}join(t){let n=(Array.isArray(this._content)?this._content:[this]).concat(Array.isArray(t._content)?t._content:[t]);return new e(this.from,this.length+t.length,this.top,this.height+t.height,n)}},MP=(function(e){return e[e.ByPos=0]=`ByPos`,e[e.ByHeight=1]=`ByHeight`,e[e.ByPosNoHeight=2]=`ByPosNoHeight`,e})(MP||={}),NP=.001,PP=class e{constructor(e,t,n=2){this.length=e,this.height=t,this.flags=n}get outdated(){return(this.flags&2)>0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e){this.height!=e&&(Math.abs(this.height-e)>NP&&(DP=!0),this.height=e)}replace(t,n,r){return e.of(r)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,n,r){let i=this,a=n.doc;for(let o=r.length-1;o>=0;o--){let{fromA:s,toA:c,fromB:l,toB:u}=r[o],d=i.lineAt(s,MP.ByPosNoHeight,n.setDoc(t),0,0),f=d.to>=c?d:i.lineAt(c,MP.ByPosNoHeight,n,0,0);for(u+=f.to-c,c=f.to;o>0&&d.from<=r[o-1].toA;)s=r[o-1].fromA,l=r[o-1].fromB,o--,s<d.from&&(d=i.lineAt(s,MP.ByPosNoHeight,n,0,0));l+=d.from-s,s=d.from;let p=UP.build(n.setDoc(a),e,l,u);i=FP(i,i.replace(s,c,p))}return i.updateHeight(n,0)}static empty(){return new RP(0,0,0)}static of(t){if(t.length==1)return t[0];let n=0,r=t.length,i=0,a=0;for(;;)if(n==r){if(i>a*2){let e=t[n-1];e.break?t.splice(--n,1,e.left,null,e.right):t.splice(--n,1,e.left,e.right),r+=1+e.break,i-=e.size}else if(a>i*2){let e=t[r];e.break?t.splice(r,1,e.left,null,e.right):t.splice(r,1,e.left,e.right),r+=2+e.break,a-=e.size}else break}else if(i<a){let e=t[n++];e&&(i+=e.size)}else{let e=t[--r];e&&(a+=e.size)}let o=0;return t[n-1]==null?(o=1,n--):t[n]??(o=1,r++),new BP(e.of(t.slice(0,n)),o,e.of(t.slice(r)))}};function FP(e,t){return e==t?e:(e.constructor!=t.constructor&&(DP=!0),t)}PP.prototype.size=1;var IP=UA.replace({}),LP=class extends PP{constructor(e,t,n){super(e,t),this.deco=n,this.spaceAbove=0}mainBlock(e,t){return new jP(t,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.deco||0)}blockAt(e,t,n,r){return this.spaceAbove&&e<n+this.spaceAbove?new jP(r,0,n,this.spaceAbove,IP):this.mainBlock(n,r)}lineAt(e,t,n,r,i){let a=this.mainBlock(r,i);return this.spaceAbove?this.blockAt(0,n,r,i).join(a):a}forEachLine(e,t,n,r,i,a){e<=i+this.length&&t>=i&&a(this.lineAt(0,MP.ByPos,n,r,i))}setMeasuredHeight(e){let t=e.heights[e.index++];t<0?(this.spaceAbove=-t,t=e.heights[e.index++]):this.spaceAbove=0,this.setHeight(t)}updateHeight(e,t=0,n=!1,r){return r&&r.from<=t&&r.more&&this.setMeasuredHeight(r),this.outdated=!1,this}toString(){return`block(${this.length})`}},RP=class e extends LP{constructor(e,t,n){super(e,t,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0,this.spaceAbove=n}mainBlock(e,t){return new jP(t,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.breaks)}replace(t,n,r){let i=r[0];return r.length==1&&(i instanceof e||i instanceof zP&&i.flags&4)&&Math.abs(this.length-i.length)<10?(i instanceof zP?i=new e(i.length,this.height,this.spaceAbove):i.height=this.height,this.outdated||(i.outdated=!1),i):PP.of(r)}updateHeight(e,t=0,n=!1,r){return r&&r.from<=t&&r.more?this.setMeasuredHeight(r):(n||this.outdated)&&(this.spaceAbove=0,this.setHeight(Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))+this.breaks*e.lineHeight)),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:``}${this.widgetHeight?`:`+this.widgetHeight:``})`}},zP=class e extends PP{constructor(e){super(e,0)}heightMetrics(e,t){let n=e.doc.lineAt(t).number,r=e.doc.lineAt(t+this.length).number,i=r-n+1,a,o=0;if(e.lineWrapping){let t=Math.min(this.height,e.lineHeight*i);a=t/i,this.length>i+1&&(o=(this.height-t)/(this.length-i-1))}else a=this.height/i;return{firstLine:n,lastLine:r,perLine:a,perChar:o}}blockAt(e,t,n,r){let{firstLine:i,lastLine:a,perLine:o,perChar:s}=this.heightMetrics(t,r);if(t.lineWrapping){let i=r+(e<t.lineHeight?0:Math.round(Math.max(0,Math.min(1,(e-n)/this.height))*this.length)),a=t.doc.lineAt(i),c=o+a.length*s,l=Math.max(n,e-c/2);return new jP(a.from,a.length,l,c,0)}{let r=Math.max(0,Math.min(a-i,Math.floor((e-n)/o))),{from:s,length:c}=t.doc.line(i+r);return new jP(s,c,n+o*r,o,0)}}lineAt(e,t,n,r,i){if(t==MP.ByHeight)return this.blockAt(e,n,r,i);if(t==MP.ByPosNoHeight){let{from:t,to:r}=n.doc.lineAt(e);return new jP(t,r-t,0,0,0)}let{firstLine:a,perLine:o,perChar:s}=this.heightMetrics(n,i),c=n.doc.lineAt(e),l=o+c.length*s,u=c.number-a,d=r+o*u+s*(c.from-i-u);return new jP(c.from,c.length,Math.max(r,Math.min(d,r+this.height-l)),l,0)}forEachLine(e,t,n,r,i,a){e=Math.max(e,i),t=Math.min(t,i+this.length);let{firstLine:o,perLine:s,perChar:c}=this.heightMetrics(n,i);for(let l=e,u=r;l<=t;){let t=n.doc.lineAt(l);if(l==e){let n=t.number-o;u+=s*n+c*(e-i-n)}let r=s+c*t.length;a(new jP(t.from,t.length,u,r,0)),u+=r,l=t.to+1}}replace(t,n,r){let i=this.length-n;if(i>0){let t=r[r.length-1];t instanceof e?r[r.length-1]=new e(t.length+i):r.push(null,new e(i-1))}if(t>0){let n=r[0];n instanceof e?r[0]=new e(t+n.length):r.unshift(new e(t-1),null)}return PP.of(r)}decomposeLeft(t,n){n.push(new e(t-1),null)}decomposeRight(t,n){n.push(null,new e(this.length-t-1))}updateHeight(t,n=0,r=!1,i){let a=n+this.length;if(i&&i.from<=n+this.length&&i.more){let r=[],o=Math.max(n,i.from),s=-1;for(i.from>n&&r.push(new e(i.from-n-1).updateHeight(t,n));o<=a&&i.more;){let e=t.doc.lineAt(o).length;r.length&&r.push(null);let n=i.heights[i.index++],a=0;n<0&&(a=-n,n=i.heights[i.index++]),s==-1?s=n:Math.abs(n-s)>=NP&&(s=-2);let c=new RP(e,n,a);c.outdated=!1,r.push(c),o+=e+1}o<=a&&r.push(null,new e(a-o).updateHeight(t,o));let c=PP.of(r);return(s<0||Math.abs(c.height-this.height)>=NP||Math.abs(s-this.heightMetrics(t,n).perLine)>=NP)&&(DP=!0),FP(this,c)}return(r||this.outdated)&&(this.setHeight(t.heightForGap(n,n+this.length)),this.outdated=!1),this}toString(){return`gap(${this.length})`}},BP=class extends PP{constructor(e,t,n){super(e.length+t+n.length,e.height+n.height,t|(e.outdated||n.outdated?2:0)),this.left=e,this.right=n,this.size=e.size+n.size}get break(){return this.flags&1}blockAt(e,t,n,r){let i=n+this.left.height;return e<i?this.left.blockAt(e,t,n,r):this.right.blockAt(e,t,i,r+this.left.length+this.break)}lineAt(e,t,n,r,i){let a=r+this.left.height,o=i+this.left.length+this.break,s=t==MP.ByHeight?e<a:e<o,c=s?this.left.lineAt(e,t,n,r,i):this.right.lineAt(e,t,n,a,o);if(this.break||(s?c.to<o:c.from>o))return c;let l=t==MP.ByPosNoHeight?MP.ByPosNoHeight:MP.ByPos;return s?c.join(this.right.lineAt(o,l,n,a,o)):this.left.lineAt(o,l,n,r,i).join(c)}forEachLine(e,t,n,r,i,a){let o=r+this.left.height,s=i+this.left.length+this.break;if(this.break)e<s&&this.left.forEachLine(e,t,n,r,i,a),t>=s&&this.right.forEachLine(e,t,n,o,s,a);else{let c=this.lineAt(s,MP.ByPos,n,r,i);e<c.from&&this.left.forEachLine(e,c.from-1,n,r,i,a),c.to>=e&&c.from<=t&&a(c),t>c.to&&this.right.forEachLine(c.to+1,t,n,o,s,a)}}replace(e,t,n){let r=this.left.length+this.break;if(t<r)return this.balanced(this.left.replace(e,t,n),this.right);if(e>this.left.length)return this.balanced(this.left,this.right.replace(e-r,t-r,n));let i=[];e>0&&this.decomposeLeft(e,i);let a=i.length;for(let e of n)i.push(e);if(e>0&&VP(i,a-1),t<this.length){let e=i.length;this.decomposeRight(t,i),VP(i,e)}return PP.of(i)}decomposeLeft(e,t){let n=this.left.length;if(e<=n)return this.left.decomposeLeft(e,t);t.push(this.left),this.break&&(n++,e>=n&&t.push(null)),e>n&&this.right.decomposeLeft(e-n,t)}decomposeRight(e,t){let n=this.left.length,r=n+this.break;if(e>=r)return this.right.decomposeRight(e-r,t);e<n&&this.left.decomposeRight(e,t),this.break&&e<r&&t.push(null),t.push(this.right)}balanced(e,t){return e.size>2*t.size||t.size>2*e.size?PP.of(this.break?[e,null,t]:[e,t]):(this.left=FP(this.left,e),this.right=FP(this.right,t),this.setHeight(e.height+t.height),this.outdated=e.outdated||t.outdated,this.size=e.size+t.size,this.length=e.length+this.break+t.length,this)}updateHeight(e,t=0,n=!1,r){let{left:i,right:a}=this,o=t+i.length+this.break,s=null;return r&&r.from<=t+i.length&&r.more?s=i=i.updateHeight(e,t,n,r):i.updateHeight(e,t,n),r&&r.from<=o+a.length&&r.more?s=a=a.updateHeight(e,o,n,r):a.updateHeight(e,o,n),s?this.balanced(i,a):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?` `:`-`)+this.right}};function VP(e,t){let n,r;e[t]==null&&(n=e[t-1])instanceof zP&&(r=e[t+1])instanceof zP&&e.splice(t-1,3,new zP(n.length+1+r.length))}var HP=5,UP=class e{constructor(e,t){this.pos=e,this.oracle=t,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let e=Math.min(t,this.lineEnd),n=this.nodes[this.nodes.length-1];n instanceof RP?n.length+=e-this.pos:(e>this.pos||!this.isCovered)&&this.nodes.push(new RP(e-this.pos,-1,0)),this.writtenTo=e,t>e&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,n){if(e<t||n.heightRelevant){let r=n.widget?n.widget.estimatedHeight:0,i=n.widget?n.widget.lineBreaks:0;r<0&&(r=this.oracle.lineHeight);let a=t-e;n.block?this.addBlock(new LP(a,r,n)):(a||i||r>=HP)&&this.addLineDeco(r,i,a)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd<this.pos&&(this.lineEnd=this.oracle.doc.lineAt(this.pos).to)}enterLine(){if(this.lineStart>-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenTo<e&&((this.writtenTo<e-1||this.nodes[this.nodes.length-1]==null)&&this.nodes.push(this.blankContent(this.writtenTo,e-1)),this.nodes.push(null)),this.pos>e&&this.nodes.push(new RP(this.pos-e,-1,0)),this.writtenTo=this.pos}blankContent(e,t){let n=new zP(t-e);return this.oracle.doc.lineAt(e).to==t&&(n.flags|=4),n}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof RP)return e;let t=new RP(0,-1,0);return this.nodes.push(t),t}addBlock(e){this.enterLine();let t=e.deco;t&&t.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos+=e.length,t&&t.endSide>0&&(this.covering=e)}addLineDeco(e,t,n){let r=this.ensureLine();r.length+=n,r.collapsed+=n,r.widgetHeight=Math.max(r.widgetHeight,e),r.breaks+=t,this.writtenTo=this.pos+=n}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof RP)&&!this.isCovered?this.nodes.push(new RP(0,-1,0)):(this.writtenTo<this.pos||t==null)&&this.nodes.push(this.blankContent(this.writtenTo,this.pos));let n=e;for(let e of this.nodes)e instanceof RP&&e.updateHeight(this.oracle,n),n+=e?e.length:1;return this.nodes}static build(t,n,r,i){let a=new e(r,t);return $k.spans(n,r,i,a,0),a.finish(r)}};function WP(e,t,n){let r=new GP;return $k.compare(e,t,n,r,0),r.changes}var GP=class{constructor(){this.changes=[]}compareRange(){}comparePoint(e,t,n,r){(e<t||n&&n.heightRelevant||r&&r.heightRelevant)&&YA(e,t,this.changes,5)}};function KP(e,t){let n=e.getBoundingClientRect(),r=e.ownerDocument,i=r.defaultView||window,a=Math.max(0,n.left),o=Math.min(i.innerWidth,n.right),s=Math.max(0,n.top),c=Math.min(i.innerHeight,n.bottom);for(let t=e.parentNode;t&&t!=r.body;)if(t.nodeType==1){let n=t,r=window.getComputedStyle(n);if((n.scrollHeight>n.clientHeight||n.scrollWidth>n.clientWidth)&&r.overflow!=`visible`){let r=n.getBoundingClientRect();a=Math.max(a,r.left),o=Math.min(o,r.right),s=Math.max(s,r.top),c=Math.min(t==e.parentNode?i.innerHeight:c,r.bottom)}t=r.position==`absolute`||r.position==`fixed`?n.offsetParent:n.parentNode}else if(t.nodeType==11)t=t.host;else break;return{left:a-n.left,right:Math.max(a,o)-n.left,top:s-(n.top+t),bottom:Math.max(s,c)-(n.top+t)}}function qP(e){let t=e.getBoundingClientRect(),n=e.ownerDocument.defaultView||window;return t.left<n.innerWidth&&t.right>0&&t.top<n.innerHeight&&t.bottom>0}function JP(e,t){let n=e.getBoundingClientRect();return{left:0,right:n.right-n.left,top:t,bottom:n.bottom-(n.top+t)}}var YP=class{constructor(e,t,n,r){this.from=e,this.to=t,this.size=n,this.displaySize=r}static same(e,t){if(e.length!=t.length)return!1;for(let n=0;n<e.length;n++){let r=e[n],i=t[n];if(r.from!=i.from||r.to!=i.to||r.size!=i.size)return!1}return!0}draw(e,t){return UA.replace({widget:new XP(this.displaySize*(t?e.scaleY:e.scaleX),t)}).range(this.from,this.to)}},XP=class extends VA{constructor(e,t){super(),this.size=e,this.vertical=t}eq(e){return e.size==this.size&&e.vertical==this.vertical}toDOM(){let e=document.createElement(`div`);return this.vertical?e.style.height=this.size+`px`:(e.style.width=this.size+`px`,e.style.height=`2px`,e.style.display=`inline-block`),e}get estimatedHeight(){return this.vertical?this.size:-1}},ZP=class{constructor(e,t){this.view=e,this.state=t,this.pixelViewport={left:0,right:window.innerWidth,top:0,bottom:0},this.inView=!0,this.paddingTop=0,this.paddingBottom=0,this.contentDOMWidth=0,this.contentDOMHeight=0,this.editorHeight=0,this.editorWidth=0,this.scaleX=1,this.scaleY=1,this.scrollOffset=0,this.scrolledToBottom=!1,this.scrollAnchorPos=0,this.scrollAnchorHeight=-1,this.scaler=rF,this.scrollTarget=null,this.printing=!1,this.mustMeasureContent=!0,this.defaultTextDirection=Tj.LTR,this.visibleRanges=[],this.mustEnforceCursorAssoc=!1;let n=t.facet(gM).some(e=>typeof e!=`function`&&e.class==`cm-lineWrapping`);this.heightOracle=new kP(n),this.stateDeco=iF(t),this.heightMap=PP.empty().applyChanges(this.stateDeco,DO.empty,this.heightOracle.setDoc(t.doc),[new EM(0,0,0,t.doc.length)]);for(let e=0;e<2&&(this.viewport=this.getViewport(0,null),this.updateForViewport());e++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=UA.set(this.lineGaps.map(e=>e.draw(this,!1))),this.scrollParent=e.scrollDOM,this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let n=0;n<=1;n++){let r=n?t.head:t.anchor;if(!e.some(({from:e,to:t})=>r>=e&&r<=t)){let{from:t,to:n}=this.lineBlockAt(r);e.push(new QP(t,n))}}return this.viewports=e.sort((e,t)=>e.from-t.from),this.updateScaler()}updateScaler(){let e=this.scaler;return this.scaler=this.heightMap.height<=7e6?rF:new aF(this.heightOracle,this.heightMap,this.viewports),e.eq(this.scaler)?0:2}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(oF(e,this.scaler))})}update(e,t=null){this.state=e.state;let n=this.stateDeco;this.stateDeco=iF(this.state);let r=e.changedRanges,i=EM.extendWithRanges(r,WP(n,this.stateDeco,e?e.changes:qO.empty(this.state.doc.length))),a=this.heightMap.height,o=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollOffset);OP(),this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),i),(this.heightMap.height!=a||DP)&&(e.flags|=2),o?(this.scrollAnchorPos=e.changes.mapPos(o.from,-1),this.scrollAnchorHeight=o.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=a);let s=i.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.head<s.from||t.range.head>s.to)||!this.viewportIsAppropriate(s))&&(s=this.getViewport(0,t));let c=s.from!=this.viewport.from||s.to!=this.viewport.to;this.viewport=s,e.flags|=this.updateForViewport(),(c||!e.changes.empty||e.flags&2)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(e.changes),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&(e.selectionSet||e.focusChanged)&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(iM)&&(this.mustEnforceCursorAssoc=!0)}measure(){let{view:e}=this,t=e.contentDOM,n=window.getComputedStyle(t),r=this.heightOracle,i=n.whiteSpace;this.defaultTextDirection=n.direction==`rtl`?Tj.RTL:Tj.LTR;let a=this.heightOracle.mustRefreshForWrapping(i)||this.mustMeasureContent===`refresh`,o=t.getBoundingClientRect(),s=a||this.mustMeasureContent||this.contentDOMHeight!=o.height;this.contentDOMHeight=o.height,this.mustMeasureContent=!1;let c=0,l=0;if(o.width&&o.height){let{scaleX:e,scaleY:n}=cj(t,o);(e>.005&&Math.abs(this.scaleX-e)>.005||n>.005&&Math.abs(this.scaleY-n)>.005)&&(this.scaleX=e,this.scaleY=n,c|=16,a=s=!0)}let u=(parseInt(n.paddingTop)||0)*this.scaleY,d=(parseInt(n.paddingBottom)||0)*this.scaleY;(this.paddingTop!=u||this.paddingBottom!=d)&&(this.paddingTop=u,this.paddingBottom=d,c|=18),this.editorWidth!=e.scrollDOM.clientWidth&&(r.lineWrapping&&(s=!0),this.editorWidth=e.scrollDOM.clientWidth,c|=16);let f=uj(this.view.contentDOM,!1).y;f!=this.scrollParent&&(this.scrollParent=f,this.scrollAnchorHeight=-1,this.scrollOffset=0);let p=this.getScrollOffset();this.scrollOffset!=p&&(this.scrollAnchorHeight=-1,this.scrollOffset=p),this.scrolledToBottom=xj(this.scrollParent||e.win);let m=(this.printing?JP:KP)(t,this.paddingTop),h=m.top-this.pixelViewport.top,g=m.bottom-this.pixelViewport.bottom;this.pixelViewport=m;let _=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(_!=this.inView&&(this.inView=_,_&&(s=!0)),!this.inView&&!this.scrollTarget&&!qP(e.dom))return 0;let v=o.width;if((this.contentDOMWidth!=v||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=o.width,this.editorHeight=e.scrollDOM.clientHeight,c|=16),s){let t=e.docView.measureVisibleLineHeights(this.viewport);if(r.mustRefreshForHeights(t)&&(a=!0),a||r.lineWrapping&&Math.abs(v-this.contentDOMWidth)>r.charWidth){let{lineHeight:n,charWidth:o,textHeight:s}=e.docView.measureTextSize();a=n>0&&r.refresh(i,n,o,s,Math.max(5,v/o),t),a&&(e.docView.minWidth=0,c|=16)}h>0&&g>0?l=Math.max(h,g):h<0&&g<0&&(l=Math.min(h,g)),OP();for(let n of this.viewports){let i=n.from==this.viewport.from?t:e.docView.measureVisibleLineHeights(n);this.heightMap=(a?PP.empty().applyChanges(this.stateDeco,DO.empty,this.heightOracle,[new EM(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(r,0,a,new AP(n.from,i))}DP&&(c|=2)}let y=!this.viewportIsAppropriate(this.viewport,l)||this.scrollTarget&&(this.scrollTarget.range.head<this.viewport.from||this.scrollTarget.range.head>this.viewport.to);return y&&(c&2&&(c|=this.updateScaler()),this.viewport=this.getViewport(l,this.scrollTarget),c|=this.updateForViewport()),(c&2||y)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(a?[]:this.lineGaps,e)),c|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),c}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let n=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),r=this.heightMap,i=this.heightOracle,{visibleTop:a,visibleBottom:o}=this,s=new QP(r.lineAt(a-n*1e3,MP.ByHeight,i,0,0).from,r.lineAt(o+(1-n)*1e3,MP.ByHeight,i,0,0).to);if(t){let{head:e}=t.range;if(e<s.from||e>s.to){let n=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),a=r.lineAt(e,MP.ByPos,i,0,0),o;o=t.y==`center`?(a.top+a.bottom)/2-n/2:t.y==`start`||t.y==`nearest`&&e<s.from?a.top:a.bottom-n,s=new QP(r.lineAt(o-500,MP.ByHeight,i,0,0).from,r.lineAt(o+n+500,MP.ByHeight,i,0,0).to)}}return s}mapViewport(e,t){let n=t.mapPos(e.from,-1),r=t.mapPos(e.to,1);return new QP(this.heightMap.lineAt(n,MP.ByPos,this.heightOracle,0,0).from,this.heightMap.lineAt(r,MP.ByPos,this.heightOracle,0,0).to)}viewportIsAppropriate({from:e,to:t},n=0){if(!this.inView)return!0;let{top:r}=this.heightMap.lineAt(e,MP.ByPos,this.heightOracle,0,0),{bottom:i}=this.heightMap.lineAt(t,MP.ByPos,this.heightOracle,0,0),{visibleTop:a,visibleBottom:o}=this;return(e==0||r<=a-Math.max(10,Math.min(-n,250)))&&(t==this.state.doc.length||i>=o+Math.max(10,Math.min(n,250)))&&r>a-2e3&&i<o+2e3}mapLineGaps(e,t){if(!e.length||t.empty)return e;let n=[];for(let r of e)t.touchesRange(r.from,r.to)||n.push(new YP(t.mapPos(r.from),t.mapPos(r.to),r.size,r.displaySize));return n}ensureLineGaps(e,t){let n=this.heightOracle.lineWrapping,r=n?1e4:2e3,i=r>>1,a=r<<1;if(this.defaultTextDirection!=Tj.LTR&&!n)return[];let o=[],s=(r,a,c,l)=>{if(a-r<i)return;let u=this.state.selection.main,d=[u.from];u.empty||d.push(u.to);for(let e of d)if(e>r&&e<a){s(r,e-10,c,l),s(e+10,a,c,l);return}let f=nF(e,e=>e.from>=c.from&&e.to<=c.to&&Math.abs(e.from-r)<i&&Math.abs(e.to-a)<i&&!d.some(t=>e.from<t&&e.to>t));if(!f){if(a<c.to&&t&&n&&t.visibleRanges.some(e=>e.from<=a&&e.to>=a)){let e=t.moveToLineBoundary(Q.cursor(a),!1,!0).head;e>r&&(a=e)}let e=this.gapSize(c,r,a,l);f=new YP(r,a,e,n||e<2e6?e:2e6)}o.push(f)},c=t=>{if(t.length<a||t.type!=HA.Text)return;let i=$P(t.from,t.to,this.stateDeco);if(i.total<a)return;let o=this.scrollTarget?this.scrollTarget.range.head:null,c,l;if(n){let e=r/this.heightOracle.lineLength*this.heightOracle.lineHeight,n,a;if(o!=null){let r=tF(i,o),s=((this.visibleBottom-this.visibleTop)/2+e)/t.height;n=r-s,a=r+s}else n=(this.visibleTop-t.top-e)/t.height,a=(this.visibleBottom-t.top+e)/t.height;c=eF(i,n),l=eF(i,a)}else{let n=i.total*this.heightOracle.charWidth,a=r*this.heightOracle.charWidth,s=0;if(n>2e6)for(let n of e)n.from>=t.from&&n.from<t.to&&n.size!=n.displaySize&&n.from*this.heightOracle.charWidth+s<this.pixelViewport.left&&(s=n.size-n.displaySize);let u=this.pixelViewport.left+s,d=this.pixelViewport.right+s,f,p;if(o!=null){let e=tF(i,o),t=((d-u)/2+a)/n;f=e-t,p=e+t}else f=(u-a)/n,p=(d+a)/n;c=eF(i,f),l=eF(i,p)}c>t.from&&s(t.from,c,t,i),l<t.to&&s(l,t.to,t,i)};for(let e of this.viewportLines)Array.isArray(e.type)?e.type.forEach(c):c(e);return o}gapSize(e,t,n,r){let i=tF(r,n)-tF(r,t);return this.heightOracle.lineWrapping?e.height*i:r.total*this.heightOracle.charWidth*i}updateLineGaps(e){YP.same(e,this.lineGaps)||(this.lineGaps=e,this.lineGapDeco=UA.set(e.map(e=>e.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(e){let t=this.stateDeco;this.lineGaps.length&&(t=t.concat(this.lineGapDeco));let n=[];$k.spans(t,this.viewport.from,this.viewport.to,{span(e,t){n.push({from:e,to:t})},point(){}},20);let r=0;if(n.length!=this.visibleRanges.length)r=12;else for(let t=0;t<n.length&&!(r&8);t++){let i=this.visibleRanges[t],a=n[t];(i.from!=a.from||i.to!=a.to)&&(r|=4,e&&e.mapPos(i.from,-1)==a.from&&e.mapPos(i.to,1)==a.to||(r|=8))}return this.visibleRanges=n,r}lineBlockAt(e){return e>=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||oF(this.heightMap.lineAt(e,MP.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return e>=this.viewportLines[0].top&&e<=this.viewportLines[this.viewportLines.length-1].bottom&&this.viewportLines.find(t=>t.top<=e&&t.bottom>=e)||oF(this.heightMap.lineAt(this.scaler.fromDOM(e),MP.ByHeight,this.heightOracle,0,0),this.scaler)}getScrollOffset(){return(this.scrollParent==this.view.scrollDOM?this.scrollParent.scrollTop:(this.scrollParent?this.scrollParent.getBoundingClientRect().top:0)-this.view.contentDOM.getBoundingClientRect().top)*this.scaleY}scrollAnchorAt(e){let t=this.lineBlockAtHeight(e+8);return t.from>=this.viewport.from||this.viewportLines[0].top-e>200?t:this.viewportLines[0]}elementAtHeight(e){return oF(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}},QP=class{constructor(e,t){this.from=e,this.to=t}};function $P(e,t,n){let r=[],i=e,a=0;return $k.spans(n,e,t,{span(){},point(e,t){e>i&&(r.push({from:i,to:e}),a+=e-i),i=t}},20),i<t&&(r.push({from:i,to:t}),a+=t-i),{total:a,ranges:r}}function eF({total:e,ranges:t},n){if(n<=0)return t[0].from;if(n>=1)return t[t.length-1].to;let r=Math.floor(e*n);for(let e=0;;e++){let{from:n,to:i}=t[e],a=i-n;if(r<=a)return n+r;r-=a}}function tF(e,t){let n=0;for(let{from:r,to:i}of e.ranges){if(t<=i){n+=t-r;break}n+=i-r}return n/e.total}function nF(e,t){for(let n of e)if(t(n))return n}var rF={toDOM(e){return e},fromDOM(e){return e},scale:1,eq(e){return e==this}};function iF(e){let t=e.facet(_M).filter(e=>typeof e!=`function`),n=e.facet(yM).filter(e=>typeof e!=`function`);return n.length&&t.push($k.join(n)),t}var aF=class e{constructor(e,t,n){let r=0,i=0,a=0;this.viewports=n.map(({from:n,to:i})=>{let a=t.lineAt(n,MP.ByPos,e,0,0).top,o=t.lineAt(i,MP.ByPos,e,0,0).bottom;return r+=o-a,{from:n,to:i,top:a,bottom:o,domTop:0,domBottom:0}}),this.scale=(7e6-r)/(t.height-r);for(let e of this.viewports)e.domTop=a+(e.top-i)*this.scale,a=e.domBottom=e.domTop+(e.bottom-e.top),i=e.bottom}toDOM(e){for(let t=0,n=0,r=0;;t++){let i=t<this.viewports.length?this.viewports[t]:null;if(!i||e<i.top)return r+(e-n)*this.scale;if(e<=i.bottom)return i.domTop+(e-i.top);n=i.bottom,r=i.domBottom}}fromDOM(e){for(let t=0,n=0,r=0;;t++){let i=t<this.viewports.length?this.viewports[t]:null;if(!i||e<i.domTop)return n+(e-r)/this.scale;if(e<=i.domBottom)return i.top+(e-i.domTop);n=i.bottom,r=i.domBottom}}eq(t){return t instanceof e&&this.scale==t.scale&&this.viewports.length==t.viewports.length&&this.viewports.every((e,n)=>e.from==t.viewports[n].from&&e.to==t.viewports[n].to)}};function oF(e,t){if(t.scale==1)return e;let n=t.toDOM(e.top),r=t.toDOM(e.bottom);return new jP(e.from,e.length,n,r-n,Array.isArray(e._content)?e._content.map(e=>oF(e,t)):e._content)}var sF=rk.define({combine:e=>e.join(` `)}),cF=rk.define({combine:e=>e.indexOf(!0)>-1}),lF=vA.newName(),uF=vA.newName(),dF=vA.newName(),fF={"&light":`.`+uF,"&dark":`.`+dF};function pF(e,t,n){return new vA(t,{finish(t){return/&/.test(t)?t.replace(/&\w*/,t=>{if(t==`&`)return e;if(!n||!n[t])throw RangeError(`Unsupported selector: ${t}`);return n[t]}):e+` `+t}})}var mF=pF(`.`+lF,{"&":{position:`relative !important`,boxSizing:`border-box`,"&.cm-focused":{outline:`1px dotted #212121`},display:`flex !important`,flexDirection:`column`},".cm-scroller":{display:`flex !important`,alignItems:`flex-start !important`,fontFamily:`monospace`,lineHeight:1.4,height:`100%`,overflowX:`auto`,position:`relative`,zIndex:0,overflowAnchor:`none`},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:`block`,whiteSpace:`pre`,wordWrap:`normal`,boxSizing:`border-box`,minHeight:`100%`,padding:`4px 0`,outline:`none`,"&[contenteditable=true]":{WebkitUserModify:`read-write-plaintext-only`}},".cm-lineWrapping":{whiteSpace_fallback:`pre-wrap`,whiteSpace:`break-spaces`,wordBreak:`break-word`,overflowWrap:`anywhere`,flexShrink:1},"&light .cm-content":{caretColor:`black`},"&dark .cm-content":{caretColor:`white`},".cm-line":{display:`block`,padding:`0 2px 0 6px`},".cm-layer":{userSelect:`none`,position:`absolute`,left:0,top:0,contain:`size style`,"& > *":{position:`absolute`}},"&light .cm-selectionBackground":{background:`#d9d9d9`},"&dark .cm-selectionBackground":{background:`#222`},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:`#d7d4f0`},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:`#233`},".cm-cursorLayer":{pointerEvents:`none`},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:`steps(1) cm-blink 1.2s infinite`},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:`1.2px solid black`,marginLeft:`-0.6px`,pointerEvents:`none`},".cm-cursor":{display:`none`},"&dark .cm-cursor":{borderLeftColor:`#ddd`},".cm-selectionHandle":{backgroundColor:`currentColor`,width:`1.5px`},".cm-selectionHandle-start::before, .cm-selectionHandle-end::before":{content:`""`,backgroundColor:`inherit`,borderRadius:`50%`,width:`8px`,height:`8px`,position:`absolute`,left:`-3.25px`},".cm-selectionHandle-start::before":{top:`-8px`},".cm-selectionHandle-end::before":{bottom:`-8px`},".cm-dropCursor":{position:`absolute`},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:`block`},".cm-iso":{unicodeBidi:`isolate`},".cm-announced":{position:`fixed`,top:`-10000px`},"@media print":{".cm-announced":{display:`none`}},"&light .cm-activeLine":{backgroundColor:`#cceeff44`},"&dark .cm-activeLine":{backgroundColor:`#99eeff33`},"&light .cm-specialChar":{color:`red`},"&dark .cm-specialChar":{color:`#f78`},".cm-gutters":{flexShrink:0,display:`flex`,height:`100%`,boxSizing:`border-box`,zIndex:200},".cm-gutters-before":{insetInlineStart:0},".cm-gutters-after":{insetInlineEnd:0},"&light .cm-gutters":{backgroundColor:`#f5f5f5`,color:`#6c6c6c`,border:`0px solid #ddd`,"&.cm-gutters-before":{borderRightWidth:`1px`},"&.cm-gutters-after":{borderLeftWidth:`1px`}},"&dark .cm-gutters":{backgroundColor:`#333338`,color:`#ccc`},".cm-gutter":{display:`flex !important`,flexDirection:`column`,flexShrink:0,boxSizing:`border-box`,minHeight:`100%`,overflow:`hidden`},".cm-gutterElement":{boxSizing:`border-box`},".cm-lineNumbers .cm-gutterElement":{padding:`0 3px 0 5px`,minWidth:`20px`,textAlign:`right`,whiteSpace:`nowrap`},"&light .cm-activeLineGutter":{backgroundColor:`#e2f2ff`},"&dark .cm-activeLineGutter":{backgroundColor:`#222227`},".cm-panels":{boxSizing:`border-box`,position:`sticky`,left:0,right:0,zIndex:300},"&light .cm-panels":{backgroundColor:`#f5f5f5`,color:`black`},".cm-panels-top":{top:`0`},".cm-panels-bottom":{bottom:`0`},"&light .cm-panels-top":{borderBottom:`1px solid #ddd`},"&light .cm-panels-bottom":{borderTop:`1px solid #ddd`},"&dark .cm-panels":{backgroundColor:`#333338`,color:`white`},".cm-dialog":{padding:`2px 19px 4px 6px`,position:`relative`,"& label":{fontSize:`80%`}},".cm-dialog-close":{position:`absolute`,top:`3px`,right:`4px`,backgroundColor:`inherit`,border:`none`,font:`inherit`,fontSize:`14px`,padding:`0`},".cm-tab":{display:`inline-block`,overflow:`hidden`,verticalAlign:`bottom`},".cm-widgetBuffer":{verticalAlign:`text-top`,height:`1em`,width:0,display:`inline`},".cm-placeholder":{color:`#888`,display:`inline-block`,verticalAlign:`top`,userSelect:`none`},".cm-highlightSpace":{backgroundImage:`radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)`,backgroundPosition:`center`},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="20"><path stroke="%23888" stroke-width="1" fill="none" d="M1 10H196L190 5M190 15L196 10M197 4L197 16"/></svg>')`,backgroundSize:`auto 100%`,backgroundPosition:`right 90%`,backgroundRepeat:`no-repeat`},".cm-trailingSpace":{backgroundColor:`#ff332255`},".cm-button":{verticalAlign:`middle`,color:`inherit`,fontSize:`70%`,padding:`.2em 1em`,borderRadius:`1px`},"&light .cm-button":{backgroundImage:`linear-gradient(#eff1f5, #d9d9df)`,border:`1px solid #888`,"&:active":{backgroundImage:`linear-gradient(#b4b4b4, #d0d3d6)`}},"&dark .cm-button":{backgroundImage:`linear-gradient(#393939, #111)`,border:`1px solid #888`,"&:active":{backgroundImage:`linear-gradient(#111, #333)`}},".cm-textfield":{verticalAlign:`middle`,color:`inherit`,fontSize:`70%`,border:`1px solid silver`,padding:`.2em .5em`},"&light .cm-textfield":{backgroundColor:`white`},"&dark .cm-textfield":{border:`1px solid #555`,backgroundColor:`inherit`}},fF),hF={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},gF=PA.ie&&PA.ie_version<=11,_F=class{constructor(e){this.view=e,this.active=!1,this.editContext=null,this.selectionRange=new dj,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let e of t)this.queue.push(e);(PA.ie&&PA.ie_version<=11||PA.ios&&e.composing)&&t.some(e=>e.type==`childList`&&e.removedNodes.length||e.type==`characterData`&&e.oldValue.length>e.target.nodeValue.length)?this.flushSoon():this.flush()}),window.EditContext&&PA.android&&e.constructor.EDIT_CONTEXT!==!1&&!(PA.chrome&&PA.chrome_version<126)&&(this.editContext=new xF(e),e.state.facet(uM)&&(e.contentDOM.editContext=this.editContext.editContext)),gF&&(this.onCharData=e=>{this.queue.push({target:e.target,type:`characterData`,oldValue:e.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia(`print`)),typeof ResizeObserver==`function`&&(this.resizeScroll=new ResizeObserver(()=>{this.view.docView?.lastUpdate<Date.now()-75&&this.onResize()}),this.resizeScroll.observe(e.scrollDOM)),this.addWindowListeners(this.win=e.win),this.start(),typeof IntersectionObserver==`function`&&(this.intersection=new IntersectionObserver(e=>{this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),e.length>0&&e[e.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent(`Event`)))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(e=>{e.length>0&&e[e.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent(`Event`))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers(`scroll`,e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.editContext&&this.view.requestMeasure(this.editContext.measureReq),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(e){(e.type==`change`||!e.type)&&!e.matches||(this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500))}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((t,n)=>t!=e[n]))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:n}=this,r=this.selectionRange;if(n.state.facet(uM)?n.root.activeElement!=this.dom:!$A(this.dom,r))return;let i=r.anchorNode&&n.docView.tile.nearest(r.anchorNode);if(i&&i.isWidget()&&i.widget.ignoreEvent(e)){t||(this.selectionChanged=!1);return}(PA.ie&&PA.ie_version<=11||PA.android&&PA.chrome)&&!n.state.selection.main.empty&&r.focusNode&&tj(r.focusNode,r.focusOffset,r.anchorNode,r.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=ZA(e.root);if(!t)return!1;let n=PA.safari&&e.root.nodeType==11&&e.root.activeElement==this.dom&&bF(this.view,t)||t;if(!n||this.selectionRange.eq(n))return!1;let r=$A(this.dom,n);return r&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime<Date.now()-300&&bj(this.dom,n)?(this.view.inputState.lastFocusTime=0,e.docView.updateSelection(),!1):(this.selectionRange.setRange(n),r&&(this.selectionChanged=!0),!0)}setSelectionRange(e,t){this.selectionRange.set(e.node,e.offset,t.node,t.offset),this.selectionChanged=!1}clearSelectionRange(){this.selectionRange.set(null,0,null,0)}listenForScroll(){this.parentCheck=-1;let e=0,t=null;for(let n=this.dom;n;)if(n.nodeType==1)!t&&e<this.scrollTargets.length&&this.scrollTargets[e]==n?e++:t||=this.scrollTargets.slice(0,e),t&&t.push(n),n=n.assignedSlot||n.parentNode;else if(n.nodeType==11)n=n.host;else break;if(e<this.scrollTargets.length&&!t&&(t=this.scrollTargets.slice(0,e)),t){for(let e of this.scrollTargets)e.removeEventListener(`scroll`,this.onScroll);for(let e of this.scrollTargets=t)e.addEventListener(`scroll`,this.onScroll)}}ignore(e){if(!this.active)return e();try{return this.stop(),e()}finally{this.start(),this.clear()}}start(){this.active||=(this.observer.observe(this.dom,hF),gF&&this.dom.addEventListener(`DOMCharacterDataModified`,this.onCharData),!0)}stop(){this.active&&(this.active=!1,this.observer.disconnect(),gF&&this.dom.removeEventListener(`DOMCharacterDataModified`,this.onCharData))}clear(){this.processRecords(),this.queue.length=0,this.selectionChanged=!1}delayAndroidKey(e,t){if(!this.delayedAndroidKey){let e=()=>{let e=this.delayedAndroidKey;e&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=e.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&e.force&&vj(this.dom,e.key,e.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(e)}(!this.delayedAndroidKey||e==`Enter`)&&(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange<Date.now()-50||!!this.delayedAndroidKey?.force})}clearDelayedAndroidKey(){this.win.cancelAnimationFrame(this.flushingAndroidKey),this.delayedAndroidKey=null,this.flushingAndroidKey=-1}flushSoon(){this.delayedFlush<0&&(this.delayedFlush=this.view.win.requestAnimationFrame(()=>{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let t=-1,n=-1,r=!1;for(let i of e){let e=this.readMutation(i);e&&(e.typeOver&&(r=!0),t==-1?{from:t,to:n}=e:(t=Math.min(e.from,t),n=Math.max(e.to,n)))}return{from:t,to:n,typeOver:r}}readChange(){let{from:e,to:t,typeOver:n}=this.processRecords(),r=this.selectionChanged&&$A(this.dom,this.selectionRange);if(e<0&&!r)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let i=new NN(this.view,e,t,n);return this.view.docView.domChanged={newSel:i.newSel?i.newSel.main:null},i}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return this.view.requestMeasure(),!1;let n=this.view.state,r=FN(this.view,t);return this.view.state==n&&(t.domChanged||t.newSel&&!VN(this.view.state.selection,t.newSel.main))&&this.view.update([]),r}readMutation(e){let t=this.view.docView.tile.nearest(e.target);if(!t||t.isWidget())return null;if(t.markDirty(e.type==`attributes`),e.type==`childList`){let n=vF(t,e.previousSibling||e.target.previousSibling,-1),r=vF(t,e.nextSibling||e.target.nextSibling,1);return{from:n?t.posAfter(n):t.posAtStart,to:r?t.posBefore(r):t.posAtEnd,typeOver:!1}}return e.type==`characterData`?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener(`resize`,this.onResize),this.printQuery?this.printQuery.addEventListener?this.printQuery.addEventListener(`change`,this.onPrint):this.printQuery.addListener(this.onPrint):e.addEventListener(`beforeprint`,this.onPrint),e.addEventListener(`scroll`,this.onScroll),e.document.addEventListener(`selectionchange`,this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener(`scroll`,this.onScroll),e.removeEventListener(`resize`,this.onResize),this.printQuery?this.printQuery.removeEventListener?this.printQuery.removeEventListener(`change`,this.onPrint):this.printQuery.removeListener(this.onPrint):e.removeEventListener(`beforeprint`,this.onPrint),e.document.removeEventListener(`selectionchange`,this.onSelectionChange)}update(e){this.editContext&&(this.editContext.update(e),e.startState.facet(uM)!=e.state.facet(uM)&&(e.view.contentDOM.editContext=e.state.facet(uM)?this.editContext.editContext:null))}destroy(){var e,t,n;this.stop(),(e=this.intersection)==null||e.disconnect(),(t=this.gapIntersection)==null||t.disconnect(),(n=this.resizeScroll)==null||n.disconnect();for(let e of this.scrollTargets)e.removeEventListener(`scroll`,this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}};function vF(e,t,n){for(;t;){let r=kM.get(t);if(r&&r.parent==e)return r;let i=t.parentNode;t=i==e.dom?n>0?t.nextSibling:t.previousSibling:i}return null}function yF(e,t){let n=t.startContainer,r=t.startOffset,i=t.endContainer,a=t.endOffset,o=e.docView.domAtPos(e.state.selection.main.anchor,1);return tj(o.node,o.offset,i,a)&&([n,r,i,a]=[i,a,n,r]),{anchorNode:n,anchorOffset:r,focusNode:i,focusOffset:a}}function bF(e,t){if(t.getComposedRanges){let n=t.getComposedRanges(e.root)[0];if(n)return yF(e,n)}let n=null;function r(e){e.preventDefault(),e.stopImmediatePropagation(),n=e.getTargetRanges()[0]}return e.contentDOM.addEventListener(`beforeinput`,r,!0),e.dom.ownerDocument.execCommand(`indent`),e.contentDOM.removeEventListener(`beforeinput`,r,!0),n?yF(e,n):null}var xF=class{constructor(e){this.from=0,this.to=0,this.pendingContextChange=null,this.handlers=Object.create(null),this.composing=null,this.resetRange(e.state);let t=this.editContext=new window.EditContext({text:e.state.doc.sliceString(this.from,this.to),selectionStart:this.toContextPos(Math.max(this.from,Math.min(this.to,e.state.selection.main.anchor))),selectionEnd:this.toContextPos(e.state.selection.main.head)});this.handlers.textupdate=n=>{let r=e.state.selection.main,{anchor:i,head:a}=r,o=this.toEditorPos(n.updateRangeStart),s=this.toEditorPos(n.updateRangeEnd);e.inputState.composing>=0&&!this.composing&&(this.composing={contextBase:n.updateRangeStart,editorBase:o,drifted:!1});let c=s-o>n.text.length;o==this.from&&i<this.from?o=i:s==this.to&&i>this.to&&(s=i);let l=RN(e.state.sliceDoc(o,s),n.text,(c?r.from:r.to)-o,c?`end`:null);if(!l){let t=Q.single(this.toEditorPos(n.selectionStart),this.toEditorPos(n.selectionEnd));VN(t,r)||e.dispatch({selection:t,userEvent:`select`});return}let u={from:l.from+o,to:l.toA+o,insert:DO.of(n.text.slice(l.from,l.toB).split(`
|
|
35
|
+
`))};if((PA.mac||PA.android)&&u.from==a-1&&/^\. ?$/.test(n.text)&&e.contentDOM.getAttribute(`autocorrect`)==`off`&&(u={from:o,to:s,insert:DO.of([n.text.replace(`.`,` `)])}),this.pendingContextChange=u,!e.state.readOnly){let t=this.to-this.from+(u.to-u.from+u.insert.length);IN(e,u,Q.single(this.toEditorPos(n.selectionStart,t),this.toEditorPos(n.selectionEnd,t)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),u.from<u.to&&!u.insert.length&&e.inputState.composing>=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(t.text.slice(Math.max(0,n.updateRangeStart-1),Math.min(t.text.length,n.updateRangeStart+1)))&&this.handlers.compositionend(n)},this.handlers.characterboundsupdate=n=>{let r=[],i=null;for(let t=this.toEditorPos(n.rangeStart),a=this.toEditorPos(n.rangeEnd);t<a;t++){let n=e.coordsForChar(t);i=n&&new DOMRect(n.left,n.top,n.right-n.left,n.bottom-n.top)||i||new DOMRect,r.push(i)}t.updateCharacterBounds(n.rangeStart,r)},this.handlers.textformatupdate=t=>{let n=[];for(let e of t.getTextFormats()){let t=e.underlineStyle,r=e.underlineThickness;if(!/none/i.test(t)&&!/none/i.test(r)){let i=this.toEditorPos(e.rangeStart),a=this.toEditorPos(e.rangeEnd);if(i<a){let e=`text-decoration: underline ${/^[a-z]/.test(t)?t+` `:t==`Dashed`?`dashed `:t==`Squiggle`?`wavy `:``}${/thin/i.test(r)?1:2}px`;n.push(UA.mark({attributes:{style:e}}).range(i,a))}}}e.dispatch({effects:cM.of(UA.set(n))})},this.handlers.compositionstart=()=>{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:t}=this.composing;this.composing=null,t&&this.reset(e.state)}};for(let e in this.handlers)t.addEventListener(e,this.handlers[e]);this.measureReq={read:e=>{let t=ZA(e.root);t&&t.rangeCount&&this.editContext.updateSelectionBounds(t.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,n=!1,r=this.pendingContextChange;return e.changes.iterChanges((i,a,o,s,c)=>{if(n)return;let l=c.length-(a-i);if(r&&a>=r.to){if(r.from==i&&r.to==a&&r.insert.eq(c)){r=this.pendingContextChange=null,t+=l,this.to+=l;return}r=null,this.revertPending(e.state)}if(i+=t,a+=t,a<=this.from)this.from+=l,this.to+=l;else if(i<this.to){if(i<this.from||a>this.to||this.to-this.from+c.length>3e4){n=!0;return}this.editContext.updateText(this.toContextPos(i),this.toContextPos(a),c.toString()),this.to+=l}t+=l}),r&&!n&&this.revertPending(e.state),!n}update(e){let t=this.pendingContextChange,n=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(n.from,n.to)&&e.transactions.some(e=>!e.isUserEvent(`input.type`)&&e.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||t)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:t}=e.selection.main;this.from=Math.max(0,t-1e4),this.to=Math.min(e.doc.length,t+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.from+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,n=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),r=this.toContextPos(t.head);(this.editContext.selectionStart!=n||this.editContext.selectionEnd!=r)&&this.editContext.updateSelection(n,r)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to<e.doc.length&&this.to-t<500||this.to-this.from>3e4)}toEditorPos(e,t=this.to-this.from){e=Math.min(e,t);let n=this.composing;return n&&n.drifted?n.editorBase+(e-n.contextBase):e+this.from}toContextPos(e){let t=this.composing;return t&&t.drifted?t.contextBase+(e-t.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}},SF=class e{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement(`div`),this.scrollDOM=document.createElement(`div`),this.scrollDOM.tabIndex=-1,this.scrollDOM.className=`cm-scroller`,this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement(`div`),this.announceDOM.className=`cm-announced`,this.announceDOM.setAttribute(`aria-live`,`polite`),this.dom=document.createElement(`div`),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:t}=e;this.dispatchTransactions=e.dispatchTransactions||t&&(e=>e.forEach(e=>t(e,this)))||(e=>this.update(e)),this.dispatch=this.dispatch.bind(this),this._root=e.root||yj(e.parent)||document,this.viewState=new ZP(this,e.state||Kk.create(e)),e.scrollTo&&e.scrollTo.is(sM)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(fM).map(e=>new mM(e));for(let e of this.plugins)e.update(this);this.observer=new _F(this),this.inputState=new HN(this),this.inputState.ensureHandlers(this.plugins),this.docView=new nN(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),document.fonts?.ready&&document.fonts.ready.then(()=>{this.viewState.mustMeasureContent=`refresh`,this.requestMeasure()})}dispatch(...e){let t=e.length==1&&e[0]instanceof Mk?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(t,this)}update(t){if(this.updateState!=0)throw Error(`Calls to EditorView.update are not allowed while an update is in progress`);let n=!1,r=!1,i,a=this.state;for(let e of t){if(e.startState!=a)throw RangeError(`Trying to update state with a transaction that doesn't start from the previous state.`);a=e.state}if(this.destroyed){this.viewState.state=a;return}let o=this.hasFocus,s=0,c=null;t.some(e=>e.annotation(xP))?(this.inputState.notifiedFocused=o,s=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,c=SP(a,o),c||(s=1));let l=this.observer.delayedAndroidKey,u=null;if(l?(this.observer.clearDelayedAndroidKey(),u=this.observer.readChange(),(u&&!this.state.doc.eq(a.doc)||!this.state.selection.eq(a.selection))&&(u=null)):this.observer.clear(),a.facet(Kk.phrases)!=this.state.facet(Kk.phrases))return this.setState(a);i=DM.create(this,a,t),i.flags|=s;let d=this.viewState.scrollTarget;try{this.updateState=2;for(let n of t){if(d&&=d.map(n.changes),n.scrollIntoView){let{main:t}=n.state.selection,{x:r,y:i}=this.state.facet(e.cursorScrollMargin);d=new oM(t.empty?t:Q.cursor(t.head,t.head>t.anchor?-1:1),`nearest`,`nearest`,i,r)}for(let e of n.effects)e.is(sM)&&(d=e.value.clip(this.state))}this.viewState.update(i,d),this.bidiCache=TF.update(this.bidiCache,i.changes),i.empty||(this.updatePlugins(i),this.inputState.update(i)),n=this.docView.update(i),this.state.facet(TM)!=this.styleModules&&this.mountStyles(),r=this.updateAttrs(),this.showAnnouncements(t),this.docView.updateSelection(n,t.some(e=>e.isUserEvent(`select.pointer`)))}finally{this.updateState=0}if(i.startState.facet(sF)!=i.state.facet(sF)&&(this.viewState.mustMeasureContent=!0),(n||r||d||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),n&&this.docViewUpdate(),!i.empty)for(let e of this.state.facet(Qj))try{e(i)}catch(e){lM(this.state,e,`update listener`)}(c||u)&&Promise.resolve().then(()=>{c&&this.state==c.startState&&this.dispatch(c),u&&!FN(this,u)&&l.force&&vj(this.contentDOM,l.key,l.keyCode)})}setState(e){if(this.updateState!=0)throw Error(`Calls to EditorView.setState are not allowed while an update is in progress`);if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let e of this.plugins)e.destroy(this);this.viewState=new ZP(this,e),this.plugins=e.facet(fM).map(e=>new mM(e)),this.pluginMap.clear();for(let e of this.plugins)e.update(this);this.docView.destroy(),this.docView=new nN(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(fM),n=e.state.facet(fM);if(t!=n){let r=[];for(let i of n){let n=t.indexOf(i);if(n<0)r.push(new mM(i));else{let t=this.plugins[n];t.mustUpdate=e,r.push(t)}}for(let t of this.plugins)t.mustUpdate!=e&&t.destroy(this);this.plugins=r,this.pluginMap.clear()}else for(let t of this.plugins)t.mustUpdate=e;for(let e=0;e<this.plugins.length;e++)this.plugins[e].update(this);t!=n&&this.inputState.ensureHandlers(this.plugins)}docViewUpdate(){for(let e of this.plugins){let t=e.value;if(t&&t.docViewUpdate)try{t.docViewUpdate(this)}catch(e){lM(this.state,e,`doc view update listener`)}}}measure(e=!0){if(this.destroyed)return;if(this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,n=this.viewState.scrollParent,r=this.viewState.getScrollOffset(),{scrollAnchorPos:i,scrollAnchorHeight:a}=this.viewState;Math.abs(r-this.viewState.scrollOffset)>1&&(a=-1),this.viewState.scrollAnchorHeight=-1;try{for(let e=0;;e++){if(a<0){if(xj(n||this.win))i=-1,a=this.viewState.heightMap.height;else{let e=this.viewState.scrollAnchorAt(r);i=e.from,a=e.top}}this.updateState=1;let o=this.viewState.measure();if(!o&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(e>5){console.warn(this.measureRequests.length?`Measure loop restarted more than 5 times`:`Viewport failed to stabilize`);break}let s=[];o&4||([this.measureRequests,s]=[s,this.measureRequests]);let c=s.map(e=>{try{return e.read(this)}catch(e){return lM(this.state,e),wF}}),l=DM.create(this,this.state,[]),u=!1;l.flags|=o,t?t.flags|=o:t=l,this.updateState=2,l.empty||(this.updatePlugins(l),this.inputState.update(l),this.updateAttrs(),u=this.docView.update(l),u&&this.docViewUpdate());for(let e=0;e<s.length;e++)if(c[e]!=wF)try{let t=s[e];t.write&&t.write(c[e],this)}catch(e){lM(this.state,e)}if(u&&this.docView.updateSelection(!0),!l.viewportChanged&&this.measureRequests.length==0){if(this.viewState.editorHeight){if(this.viewState.scrollTarget){this.docView.scrollIntoView(this.viewState.scrollTarget),this.viewState.scrollTarget=null,a=-1;continue}{let e=((i<0?this.viewState.heightMap.height:this.viewState.lineBlockAt(i).top)-a)/this.scaleY;if((e>1||e<-1)&&!(PA.ios&&this.inputState.lastIOSMomentumScroll>Date.now()-100)&&(n==this.scrollDOM||this.hasFocus||Math.max(this.inputState.lastWheelEvent,this.inputState.lastTouchTime)>Date.now()-100)){r+=e,n?n.scrollTop+=e:this.win.scrollBy(0,e),a=-1;continue}}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let e of this.state.facet(Qj))e(t)}get themeClasses(){return lF+` `+(this.state.facet(cF)?dF:uF)+` `+this.state.facet(sF)}updateAttrs(){let e=EF(this,hM,{class:`cm-editor`+(this.hasFocus?` cm-focused `:` `)+this.themeClasses}),t={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,translate:`no`,contenteditable:this.state.facet(uM)?`true`:`false`,class:`cm-content`,style:`${PA.tabSize}: ${this.state.tabSize}`,role:`textbox`,"aria-multiline":`true`};this.state.readOnly&&(t[`aria-readonly`]=`true`),EF(this,gM,t);let n=this.observer.ignore(()=>{let n=zA(this.contentDOM,this.contentAttrs,t),r=zA(this.dom,this.editorAttrs,e);return n||r});return this.editorAttrs=e,this.contentAttrs=t,n}showAnnouncements(t){let n=!0;for(let r of t)for(let t of r.effects)if(t.is(e.announce)){n&&(this.announceDOM.textContent=``),n=!1;let e=this.announceDOM.appendChild(document.createElement(`div`));e.textContent=t.value}}mountStyles(){this.styleModules=this.state.facet(TM);let t=this.state.facet(e.cspNonce);vA.mount(this.root,this.styleModules.concat(mF).reverse(),t?{nonce:t}:void 0)}readMeasured(){if(this.updateState==2)throw Error(`Reading the editor layout isn't allowed during an update`);this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let t=0;t<this.measureRequests.length;t++)if(this.measureRequests[t].key===e.key){this.measureRequests[t]=e;return}}this.measureRequests.push(e)}}plugin(e){let t=this.pluginMap.get(e);return(t===void 0||t&&t.plugin!=e)&&this.pluginMap.set(e,t=this.plugins.find(t=>t.plugin==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,n){return wN(this,e,yN(this,e,t,n))}moveByGroup(e,t){return wN(this,e,yN(this,e,t,t=>bN(this,e.head,t)))}visualLineSide(e,t){let n=this.bidiSpans(e),r=this.textDirectionAt(e.from),i=n[t?n.length-1:0];return Q.cursor(i.side(t,r)+e.from,i.forward(!t,r)?1:-1)}moveToLineBoundary(e,t,n=!0){return vN(this,e,t,n)}moveVertically(e,t,n){return wN(this,e,xN(this,e,t,n))}domAtPos(e,t=1){return this.docView.domAtPos(e,t)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){this.readMeasured();let n=EN(this,e,t);return n&&n.pos}posAndSideAtCoords(e,t=!0){return this.readMeasured(),EN(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let n=this.state.doc.lineAt(e),r=this.bidiSpans(n),i=r[Fj.find(r,e-n.from,-1,t)];return this.docView.coordsAt(e,t,i.dir==Tj.RTL)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(rM)||e<this.viewport.from||e>this.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>CF)return Wj(e.length);let t=this.textDirectionAt(e.from),n;for(let r of this.bidiCache)if(r.from==e.from&&r.dir==t&&(r.fresh||Ij(r.isolates,n=SM(this,e))))return r.order;n||=SM(this,e);let r=Uj(e.text,t,n);return this.bidiCache.push(new TF(e.from,e.to,t,n,!0,r)),r}get hasFocus(){return(this.dom.ownerDocument.hasFocus()||PA.safari&&this.inputState?.lastContextMenu>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{hj(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){return sM.of(new oM(typeof e==`number`?Q.cursor(e):e,t.y??`nearest`,t.x??`nearest`,t.yMargin??5,t.xMargin??5))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,n=this.viewState.scrollAnchorAt(e);return sM.of(new oM(Q.cursor(n.from),`start`,`start`,n.top-e,t,!0))}setTabFocusMode(e){e==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof e==`boolean`?this.inputState.tabFocusMode=e?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+e)}static domEventHandlers(e){return pM.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return pM.define(()=>({}),{eventObservers:e})}static theme(e,t){let n=vA.newName(),r=[sF.of(n),TM.of(pF(`.${n}`,e))];return t&&t.dark&&r.push(cF.of(!0)),r}static baseTheme(e){return pk.lowest(TM.of(pF(`.`+lF,e,fF)))}static findFromDOM(e){let t=e.querySelector(`.cm-content`);return(t&&kM.get(t)||kM.get(e))?.root?.view||null}};SF.styleModule=TM,SF.inputHandler=$j,SF.clipboardInputFilter=tM,SF.clipboardOutputFilter=nM,SF.scrollHandler=aM,SF.focusChangeEffect=eM,SF.perLineTextDirection=rM,SF.exceptionSink=Zj,SF.updateListener=Qj,SF.editable=uM,SF.mouseSelectionStyle=Xj,SF.dragMovesSelection=Yj,SF.clickAddsSelectionRange=Jj,SF.decorations=_M,SF.blockWrappers=vM,SF.outerDecorations=yM,SF.atomicRanges=bM,SF.bidiIsolatedRanges=xM,SF.cursorScrollMargin=rk.define({combine:e=>{let t=5,n=5;for(let r of e)typeof r==`number`?t=n=r:{x:t,y:n}=r;return{x:t,y:n}}}),SF.scrollMargins=CM,SF.darkTheme=cF,SF.cspNonce=rk.define({combine:e=>e.length?e[0]:``}),SF.contentAttributes=gM,SF.editorAttributes=hM,SF.lineWrapping=SF.contentAttributes.of({class:`cm-lineWrapping`}),SF.announce=jk.define();var CF=4096,wF={},TF=class e{constructor(e,t,n,r,i,a){this.from=e,this.to=t,this.dir=n,this.isolates=r,this.fresh=i,this.order=a}static update(t,n){if(n.empty&&!t.some(e=>e.fresh))return t;let r=[],i=t.length?t[t.length-1].dir:Tj.LTR;for(let a=Math.max(0,t.length-10);a<t.length;a++){let o=t[a];o.dir==i&&!n.touchesRange(o.from,o.to)&&r.push(new e(n.mapPos(o.from,1),n.mapPos(o.to,-1),o.dir,o.isolates,!1,o.order))}return r}};function EF(e,t,n){for(let r=e.state.facet(t),i=r.length-1;i>=0;i--){let t=r[i],a=typeof t==`function`?t(e):t;a&&FA(a,n)}return n}var DF=PA.mac?`mac`:PA.windows?`win`:PA.linux?`linux`:`key`;function OF(e,t){let n=e.split(/-(?!$)/),r=n[n.length-1];r==`Space`&&(r=` `);let i,a,o,s;for(let e=0;e<n.length-1;++e){let r=n[e];if(/^(cmd|meta|m)$/i.test(r))s=!0;else if(/^a(lt)?$/i.test(r))i=!0;else if(/^(c|ctrl|control)$/i.test(r))a=!0;else if(/^s(hift)?$/i.test(r))o=!0;else if(/^mod$/i.test(r))t==`mac`?s=!0:a=!0;else throw Error(`Unrecognized modifier name: `+r)}return i&&(r=`Alt-`+r),a&&(r=`Ctrl-`+r),s&&(r=`Meta-`+r),o&&(r=`Shift-`+r),r}function kF(e,t,n){return t.altKey&&(e=`Alt-`+e),t.ctrlKey&&(e=`Ctrl-`+e),t.metaKey&&(e=`Meta-`+e),n!==!1&&t.shiftKey&&(e=`Shift-`+e),e}var AF=pk.default(SF.domEventHandlers({keydown(e,t){return zF(NF(t.state),e,t,`editor`)}})),jF=rk.define({enables:AF}),MF=new WeakMap;function NF(e){let t=e.facet(jF),n=MF.get(t);return n||MF.set(t,n=LF(t.reduce((e,t)=>e.concat(t),[]))),n}function PF(e,t,n){return zF(NF(e.state),t,e,n)}var FF=null,IF=4e3;function LF(e,t=DF){let n=Object.create(null),r=Object.create(null),i=(e,t)=>{let n=r[e];if(n==null)r[e]=t;else if(n!=t)throw Error(`Key binding `+e+` is used both as a regular binding and as a multi-stroke prefix`)},a=(e,r,a,o,s)=>{let c=n[e]||(n[e]=Object.create(null)),l=r.split(/ (?!$)/).map(e=>OF(e,t));for(let t=1;t<l.length;t++){let n=l.slice(0,t).join(` `);i(n,!0),c[n]||(c[n]={preventDefault:!0,stopPropagation:!1,run:[t=>{let r=FF={view:t,prefix:n,scope:e};return setTimeout(()=>{FF==r&&(FF=null)},IF),!0}]})}let u=l.join(` `);i(u,!1);let d=c[u]||(c[u]={preventDefault:!1,stopPropagation:!1,run:(c._any?.run)?.slice()||[]});a&&d.run.push(a),o&&(d.preventDefault=!0),s&&(d.stopPropagation=!0)};for(let r of e){let e=r.scope?r.scope.split(` `):[`editor`];if(r.any)for(let t of e){let e=n[t]||(n[t]=Object.create(null));e._any||={preventDefault:!1,stopPropagation:!1,run:[]};let{any:i}=r;for(let t in e)e[t].run.push(e=>i(e,RF))}let i=r[t]||r.key;if(i)for(let t of e)a(t,i,r.run,r.preventDefault,r.stopPropagation),r.shift&&a(t,`Shift-`+i,r.shift,r.preventDefault,r.stopPropagation)}return n}var RF=null;function zF(e,t,n,r){RF=t;let i=u(t),a=UO(VO(i,0))==i.length&&i!=` `,o=``,c=!1,l=!1,d=!1;FF&&FF.view==n&&FF.scope==r&&(o=FF.prefix+` `,JN.indexOf(t.keyCode)<0&&(l=!0,FF=null));let f=new Set,m=e=>{if(e){for(let t of e.run)if(!f.has(t)&&(f.add(t),t(n)))return e.stopPropagation&&(d=!0),!0;e.preventDefault&&(e.stopPropagation&&(d=!0),l=!0)}return!1},h=e[r],g,_;return h&&(m(h[o+kF(i,t,!a)])?c=!0:a&&(t.altKey||t.metaKey||t.ctrlKey)&&!(PA.windows&&t.ctrlKey&&t.altKey)&&!(PA.mac&&t.altKey&&!(t.ctrlKey||t.metaKey))&&(g=s[t.keyCode])&&g!=i?(m(h[o+kF(g,t,!0)])||t.shiftKey&&(_=p[t.keyCode])!=i&&_!=g&&m(h[o+kF(_,t,!1)]))&&(c=!0):a&&t.shiftKey&&m(h[o+kF(i,t,!0)])&&(c=!0),!c&&m(h._any)&&(c=!0)),l&&(c=!0),c&&d&&t.stopPropagation(),RF=null,c}var BF=class e{constructor(e,t,n,r,i){this.className=e,this.left=t,this.top=n,this.width=r,this.height=i}draw(){let e=document.createElement(`div`);return e.className=this.className,this.adjust(e),e}update(e,t){return t.className==this.className&&(this.adjust(e),!0)}adjust(e){e.style.left=this.left+`px`,e.style.top=this.top+`px`,this.width!=null&&(e.style.width=this.width+`px`),e.style.height=this.height+`px`}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}static forRange(t,n,r){if(r.empty){let i=t.coordsAtPos(r.head,r.assoc||1);if(!i)return[];let a=VF(t);return[new e(n,i.left-a.left,i.top-a.top,null,i.bottom-i.top)]}return UF(t,n,r)}};function VF(e){let t=e.scrollDOM.getBoundingClientRect();return{left:(e.textDirection==Tj.LTR?t.left:t.right-e.scrollDOM.clientWidth*e.scaleX)-e.scrollDOM.scrollLeft*e.scaleX,top:t.top-e.scrollDOM.scrollTop*e.scaleY}}function HF(e,t,n,r){let i=e.coordsAtPos(t,n*2);if(!i)return r;let a=e.dom.getBoundingClientRect(),o=(i.top+i.bottom)/2,s=e.posAtCoords({x:a.left+1,y:o}),c=e.posAtCoords({x:a.right-1,y:o});return s==null||c==null?r:{from:Math.max(r.from,Math.min(s,c)),to:Math.min(r.to,Math.max(s,c))}}function UF(e,t,n){if(n.to<=e.viewport.from||n.from>=e.viewport.to)return[];let r=Math.max(n.from,e.viewport.from),i=Math.min(n.to,e.viewport.to),a=e.textDirection==Tj.LTR,o=e.contentDOM,s=o.getBoundingClientRect(),c=VF(e),l=o.querySelector(`.cm-line`),u=l&&window.getComputedStyle(l),d=s.left+(u?parseInt(u.paddingLeft)+Math.min(0,parseInt(u.textIndent)):0),f=s.right-(u?parseInt(u.paddingRight):0),p=_N(e,r,1),m=_N(e,i,-1),h=p.type==HA.Text?p:null,g=m.type==HA.Text?m:null;if(h&&(e.lineWrapping||p.widgetLineBreaks)&&(h=HF(e,r,1,h)),g&&(e.lineWrapping||m.widgetLineBreaks)&&(g=HF(e,i,-1,g)),h&&g&&h.from==g.from&&h.to==g.to)return v(y(n.from,n.to,h));{let t=h?y(n.from,null,h):b(p,!1),r=g?y(null,n.to,g):b(m,!0),i=[];return(h||p).to<(g||m).from-(h&&g?1:0)||p.widgetLineBreaks>1&&t.bottom+e.defaultLineHeight/2<r.top?i.push(_(d,t.bottom,f,r.top)):t.bottom<r.top&&e.elementAtHeight((t.bottom+r.top)/2).type==HA.Text&&(t.bottom=r.top=(t.bottom+r.top)/2),v(t).concat(i).concat(v(r))}function _(e,n,r,i){return new BF(t,e-c.left,n-c.top,Math.max(0,r-e),i-n)}function v({top:e,bottom:t,horizontal:n}){let r=[];for(let i=0;i<n.length;i+=2)r.push(_(n[i],e,n[i+1],t));return r}function y(t,n,r){let i=1e9,o=-1e9,s=[];function c(t,n,c,l,u){let p=e.coordsAtPos(t,t==r.to?-2:2),m=e.coordsAtPos(c,c==r.from?2:-2);!p||!m||(i=Math.min(p.top,m.top,i),o=Math.max(p.bottom,m.bottom,o),u==Tj.LTR?s.push(a&&n?d:p.left,a&&l?f:m.right):s.push(!a&&l?d:m.left,!a&&n?f:p.right))}let l=t??r.from,u=n??r.to;for(let r of e.visibleRanges)if(r.to>l&&r.from<u)for(let i=Math.max(r.from,l),a=Math.min(r.to,u);;){let r=e.state.doc.lineAt(i);for(let o of e.bidiSpans(r)){let e=o.from+r.from,s=o.to+r.from;if(e>=a)break;s>i&&c(Math.max(e,i),t==null&&e<=l,Math.min(s,a),n==null&&s>=u,o.dir)}if(i=r.to+1,i>=a)break}return s.length==0&&c(l,t==null,u,n==null,e.textDirection),{top:i,bottom:o,horizontal:s}}function b(e,t){let n=s.top+(t?e.top:e.bottom);return{top:n,bottom:n,horizontal:[]}}}function WF(e,t){return e.constructor==t.constructor&&e.eq(t)}var GF=class{constructor(e,t){this.view=e,this.layer=t,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=e.scrollDOM.appendChild(document.createElement(`div`)),this.dom.classList.add(`cm-layer`),t.above&&this.dom.classList.add(`cm-layer-above`),t.class&&this.dom.classList.add(t.class),this.scale(),this.dom.setAttribute(`aria-hidden`,`true`),this.setOrder(e.state),e.requestMeasure(this.measureReq),t.mount&&t.mount(this.dom,e)}update(e){e.startState.facet(KF)!=e.state.facet(KF)&&this.setOrder(e.state),(this.layer.update(e,this.dom)||e.geometryChanged)&&(this.scale(),e.view.requestMeasure(this.measureReq))}docViewUpdate(e){this.layer.updateOnDocViewUpdate!==!1&&e.requestMeasure(this.measureReq)}setOrder(e){let t=0,n=e.facet(KF);for(;t<n.length&&n[t]!=this.layer;)t++;this.dom.style.zIndex=String((this.layer.above?150:-1)-t)}measure(){return this.layer.markers(this.view)}scale(){let{scaleX:e,scaleY:t}=this.view;(e!=this.scaleX||t!=this.scaleY)&&(this.scaleX=e,this.scaleY=t,this.dom.style.transform=`scale(${1/e}, ${1/t})`)}draw(e){if(e.length!=this.drawn.length||e.some((e,t)=>!WF(e,this.drawn[t]))){let t=this.dom.firstChild,n=0;for(let r of e)r.update&&t&&r.constructor&&this.drawn[n].constructor&&r.update(t,this.drawn[n])?(t=t.nextSibling,n++):this.dom.insertBefore(r.draw(),t);for(;t;){let e=t.nextSibling;t.remove(),t=e}this.drawn=e,PA.webkit&&(this.dom.style.display=this.dom.firstChild?``:`none`)}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}},KF=rk.define();function qF(e){return[pM.define(t=>new GF(t,e)),KF.of(e)]}var JF=rk.define({combine(e){return qk(e,{cursorBlinkRate:1200,drawRangeCursor:!0,iosSelectionHandles:!0},{cursorBlinkRate:(e,t)=>Math.min(e,t),drawRangeCursor:(e,t)=>e||t})}});function YF(e={}){return[JF.of(e),ZF,$F,tI,iM.of(!0)]}function XF(e){return e.startState.facet(JF)!=e.state.facet(JF)}var ZF=qF({above:!0,markers(e){let{state:t}=e,n=t.facet(JF),r=[];for(let i of t.selection.ranges){let a=i==t.selection.main;if(i.empty||n.drawRangeCursor&&!(a&&PA.ios&&n.iosSelectionHandles)){let t=a?`cm-cursor cm-cursor-primary`:`cm-cursor cm-cursor-secondary`,n=i.empty?i:Q.cursor(i.head,i.assoc);for(let i of BF.forRange(e,t,n))r.push(i)}}return r},update(e,t){e.transactions.some(e=>e.selection)&&(t.style.animationName=t.style.animationName==`cm-blink`?`cm-blink2`:`cm-blink`);let n=XF(e);return n&&QF(e.state,t),e.docChanged||e.selectionSet||n},mount(e,t){QF(t.state,e)},class:`cm-cursorLayer`});function QF(e,t){t.style.animationDuration=e.facet(JF).cursorBlinkRate+`ms`}var $F=qF({above:!1,markers(e){let t=[],{main:n,ranges:r}=e.state.selection;for(let n of r)if(!n.empty)for(let r of BF.forRange(e,`cm-selectionBackground`,n))t.push(r);if(PA.ios&&!n.empty&&e.state.facet(JF).iosSelectionHandles){for(let r of BF.forRange(e,`cm-selectionHandle cm-selectionHandle-start`,Q.cursor(n.from,1)))t.push(r);for(let r of BF.forRange(e,`cm-selectionHandle cm-selectionHandle-end`,Q.cursor(n.to,1)))t.push(r)}return t},update(e,t){return e.docChanged||e.selectionSet||e.viewportChanged||XF(e)},class:`cm-selectionLayer`}),eI=PA.gecko&&PA.gecko_version==153?`#ffffff01`:`transparent`,tI=pk.highest(SF.theme({".cm-line":{"& ::selection, &::selection":{backgroundColor:`${eI} !important`},caretColor:`transparent !important`},".cm-content":{caretColor:`transparent !important`,"& :focus":{caretColor:`initial !important`,"&::selection, & ::selection":{backgroundColor:`Highlight !important`}}}})),nI=jk.define({map(e,t){return e==null?null:t.mapPos(e)}}),rI=uk.define({create(){return null},update(e,t){return e!=null&&(e=t.changes.mapPos(e)),t.effects.reduce((e,t)=>t.is(nI)?t.value:e,e)}}),iI=pM.fromClass(class{constructor(e){this.view=e,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(e){var t;let n=e.state.field(rI);n==null?this.cursor!=null&&((t=this.cursor)==null||t.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement(`div`)),this.cursor.className=`cm-dropCursor`),(e.startState.field(rI)!=n||e.docChanged||e.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:e}=this,t=e.state.field(rI),n=t!=null&&e.coordsAtPos(t);if(!n)return null;let r=e.scrollDOM.getBoundingClientRect();return{left:n.left-r.left+e.scrollDOM.scrollLeft*e.scaleX,top:n.top-r.top+e.scrollDOM.scrollTop*e.scaleY,height:n.bottom-n.top}}drawCursor(e){if(this.cursor){let{scaleX:t,scaleY:n}=this.view;e?(this.cursor.style.left=e.left/t+`px`,this.cursor.style.top=e.top/n+`px`,this.cursor.style.height=e.height/n+`px`):this.cursor.style.left=`-100000px`}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(e){this.view.state.field(rI)!=e&&this.view.dispatch({effects:nI.of(e)})}},{eventObservers:{dragover(e){this.setDropPos(this.view.posAtCoords({x:e.clientX,y:e.clientY}))},dragleave(e){(e.target==this.view.contentDOM||!this.view.contentDOM.contains(e.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function aI(){return[rI,iI]}function oI(e,t,n,r,i){t.lastIndex=0;for(let a=e.iterRange(n,r),o=n,s;!a.next().done;o+=a.value.length)if(!a.lineBreak)for(;s=t.exec(a.value);)i(o+s.index,s)}function sI(e,t){let n=e.visibleRanges;if(n.length==1&&n[0].from==e.viewport.from&&n[0].to==e.viewport.to)return n;let r=[];for(let{from:i,to:a}of n)i=Math.max(e.state.doc.lineAt(i).from,i-t),a=Math.min(e.state.doc.lineAt(a).to,a+t),r.length&&r[r.length-1].to>=i?r[r.length-1].to=a:r.push({from:i,to:a});return r}var cI=class{constructor(e){let{regexp:t,decoration:n,decorate:r,boundary:i,maxLength:a=1e3}=e;if(!t.global)throw RangeError(`The regular expression given to MatchDecorator should have its 'g' flag set`);if(this.regexp=t,r)this.addMatch=(e,t,n,i)=>r(i,n,n+e[0].length,e,t);else if(typeof n==`function`)this.addMatch=(e,t,r,i)=>{let a=n(e,t,r);a&&i(r,r+e[0].length,a)};else if(n)this.addMatch=(e,t,r,i)=>i(r,r+e[0].length,n);else throw RangeError(`Either 'decorate' or 'decoration' should be provided to MatchDecorator`);this.boundary=i,this.maxLength=a}createDeco(e){let t=new tA,n=t.add.bind(t);for(let{from:t,to:r}of sI(e,this.maxLength))oI(e.state.doc,this.regexp,t,r,(t,r)=>this.addMatch(r,e,t,n));return t.finish()}updateDeco(e,t){let n=1e9,r=-1;return e.docChanged&&e.changes.iterChanges((t,i,a,o)=>{o>=e.view.viewport.from&&a<=e.view.viewport.to&&(n=Math.min(a,n),r=Math.max(o,r))}),e.viewportMoved||r-n>1e3?this.createDeco(e.view):r>-1?this.updateRange(e.view,t.map(e.changes),n,r):t}updateRange(e,t,n,r){for(let i of e.visibleRanges){let a=Math.max(i.from,n),o=Math.min(i.to,r);if(o>=a){let n=e.state.doc.lineAt(a),r=n.to<o?e.state.doc.lineAt(o):n,s=Math.max(i.from,n.from),c=Math.min(i.to,r.to);if(this.boundary){for(;a>n.from;a--)if(this.boundary.test(n.text[a-1-n.from])){s=a;break}for(;o<r.to;o++)if(this.boundary.test(r.text[o-r.from])){c=o;break}}let l=[],u,d=(e,t,n)=>l.push(n.range(e,t));if(n==r)for(this.regexp.lastIndex=s-n.from;(u=this.regexp.exec(n.text))&&u.index<c-n.from;)this.addMatch(u,e,u.index+n.from,d);else oI(e.state.doc,this.regexp,s,c,(t,n)=>this.addMatch(n,e,t,d));t=t.update({filterFrom:s,filterTo:c,filter:(e,t)=>e<s||t>c,add:l})}}return t}},lI=/x/.unicode==null?`g`:`gu`,uI=RegExp(`[\0-\b
|
|
36
|
+
--\u2028\u2029-]`,lI),dI={0:`null`,7:`bell`,8:`backspace`,10:`newline`,11:`vertical tab`,13:`carriage return`,27:`escape`,8203:`zero width space`,8204:`zero width non-joiner`,8205:`zero width joiner`,8206:`left-to-right mark`,8207:`right-to-left mark`,8232:`line separator`,8237:`left-to-right override`,8238:`right-to-left override`,8294:`left-to-right isolate`,8295:`right-to-left isolate`,8297:`pop directional isolate`,8233:`paragraph separator`,65279:`zero width no-break space`,65532:`object replacement`},fI=null;function pI(){if(fI==null&&typeof document<`u`&&document.body){let e=document.body.style;fI=(e.tabSize??e.MozTabSize)!=null}return fI||!1}var mI=rk.define({combine(e){let t=qk(e,{render:null,specialChars:uI,addSpecialChars:null});return(t.replaceTabs=!pI())&&(t.specialChars=RegExp(` |`+t.specialChars.source,lI)),t.addSpecialChars&&(t.specialChars=RegExp(t.specialChars.source+`|`+t.addSpecialChars.source,lI)),t}});function hI(e={}){return[mI.of(e),_I()]}var gI=null;function _I(){return gI||=pM.fromClass(class{constructor(e){this.view=e,this.decorations=UA.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(e.state.facet(mI)),this.decorations=this.decorator.createDeco(e)}makeDecorator(e){return new cI({regexp:e.specialChars,decoration:(t,n,r)=>{let{doc:i}=n.state,a=VO(t[0],0);if(a==9){let e=i.lineAt(r),t=n.state.tabSize,a=fA(e.text,t,r-e.from);return UA.replace({widget:new xI((t-a%t)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[a]||(this.decorationCache[a]=UA.replace({widget:new bI(e,a)}))},boundary:e.replaceTabs?void 0:/[^]/})}update(e){let t=e.state.facet(mI);e.startState.facet(mI)==t?this.decorations=this.decorator.updateDeco(e,this.decorations):(this.decorator=this.makeDecorator(t),this.decorations=this.decorator.createDeco(e.view))}},{decorations:e=>e.decorations})}var vI=`•`;function yI(e){return e>=32?vI:e==10?``:String.fromCharCode(9216+e)}var bI=class extends VA{constructor(e,t){super(),this.options=e,this.code=t}eq(e){return e.code==this.code}toDOM(e){let t=yI(this.code),n=e.state.phrase(`Control character`)+` `+(dI[this.code]||`0x`+this.code.toString(16)),r=this.options.render&&this.options.render(this.code,n,t);if(r)return r;let i=document.createElement(`span`);return i.textContent=t,i.title=n,i.setAttribute(`aria-label`,n),i.className=`cm-specialChar`,i}ignoreEvent(){return!1}},xI=class extends VA{constructor(e){super(),this.width=e}eq(e){return e.width==this.width}toDOM(){let e=document.createElement(`span`);return e.textContent=` `,e.className=`cm-tab`,e.style.width=this.width+`px`,e}ignoreEvent(){return!1}};function SI(){return wI}var CI=UA.line({class:`cm-activeLine`}),wI=pM.fromClass(class{constructor(e){this.decorations=this.getDeco(e)}update(e){(e.docChanged||e.selectionSet)&&(this.decorations=this.getDeco(e.view))}getDeco(e){let t=-1,n=[];for(let r of e.state.selection.ranges){let i=e.lineBlockAt(r.head);i.from>t&&(n.push(CI.range(i.from)),t=i.from)}return UA.set(n)}},{decorations:e=>e.decorations}),TI=class extends VA{constructor(e){super(),this.content=e}toDOM(e){let t=document.createElement(`span`);return t.className=`cm-placeholder`,t.style.pointerEvents=`none`,t.appendChild(typeof this.content==`string`?document.createTextNode(this.content):typeof this.content==`function`?this.content(e):this.content.cloneNode(!0)),t.setAttribute(`aria-hidden`,`true`),t}coordsAt(e){let t=e.firstChild?ej(e.firstChild):[];if(!t.length)return null;let n=window.getComputedStyle(e.parentNode),r=oj(t[0],n.direction!=`rtl`),i=parseInt(n.lineHeight);return r.bottom-r.top>i*1.5?{left:r.left,right:r.right,top:r.top,bottom:r.top+i}:r}ignoreEvent(){return!1}};function EI(e){let t=pM.fromClass(class{constructor(t){this.view=t,this.placeholder=e?UA.set([UA.widget({widget:new TI(e),side:1}).range(0)]):UA.none}get decorations(){return this.view.state.doc.length?UA.none:this.placeholder}},{decorations:e=>e.decorations});return typeof e==`string`?[t,SF.contentAttributes.of({"aria-placeholder":e})]:t}var DI=2e3;function OI(e,t,n){let r=Math.min(t.line,n.line),i=Math.max(t.line,n.line),a=[];if(t.off>DI||n.off>DI||t.col<0||n.col<0){let o=Math.min(t.off,n.off),s=Math.max(t.off,n.off);for(let t=r;t<=i;t++){let n=e.doc.line(t);n.length<=s&&a.push(Q.range(n.from+o,n.to+s))}}else{let o=Math.min(t.col,n.col),s=Math.max(t.col,n.col);for(let t=r;t<=i;t++){let n=e.doc.line(t),r=pA(n.text,o,e.tabSize,!0);if(r<0)a.push(Q.cursor(n.to));else{let t=pA(n.text,s,e.tabSize);a.push(Q.range(n.from+r,n.from+t))}}}return a}function kI(e,t){let n=e.coordsAtPos(e.viewport.from);return n?Math.round(Math.abs((n.left-t)/e.defaultCharacterWidth)):-1}function AI(e,t){let n=e.posAtCoords({x:t.clientX,y:t.clientY},!1),r=e.state.doc.lineAt(n),i=n-r.from,a=i>DI?-1:i==r.length?kI(e,t.clientX):fA(r.text,e.state.tabSize,n-r.from);return{line:r.number,col:a,off:i}}function jI(e,t){let n=AI(e,t),r=e.state.selection;return n?{update(e){if(e.docChanged){let t=e.changes.mapPos(e.startState.doc.line(n.line).from),i=e.state.doc.lineAt(t);n={line:i.number,col:n.col,off:Math.min(n.off,i.length)},r=r.map(e.changes)}},get(t,i,a){let o=AI(e,t);if(!o)return r;let s=OI(e.state,n,o);return s.length?a?Q.create(s.concat(r.ranges)):Q.create(s):r}}:null}function MI(e){let t=e?.eventFilter||(e=>e.altKey&&e.button==0);return SF.mouseSelectionStyle.of((e,n)=>t(n)?jI(e,n):null)}var NI={Alt:[18,e=>!!e.altKey],Control:[17,e=>!!e.ctrlKey],Shift:[16,e=>!!e.shiftKey],Meta:[91,e=>!!e.metaKey]},PI={style:`cursor: crosshair`};function FI(e={}){let[t,n]=NI[e.key||`Alt`],r=pM.fromClass(class{constructor(e){this.view=e,this.isDown=!1}set(e){this.isDown!=e&&(this.isDown=e,this.view.update([]))}},{eventObservers:{keydown(e){this.set(e.keyCode==t||n(e))},keyup(e){(e.keyCode==t||!n(e))&&this.set(!1)},mousemove(e){this.set(n(e))}}});return[r,SF.contentAttributes.of(e=>e.plugin(r)?.isDown?PI:null)]}var II=`-10000px`,LI=class{constructor(e,t,n,r){this.facet=t,this.createTooltipView=n,this.removeTooltipView=r,this.input=e.state.facet(t),this.tooltips=this.input.filter(e=>e);let i=null;this.tooltipViews=this.tooltips.map(e=>i=n(e,i))}update(e,t){var n;let r=e.state.facet(this.facet),i=r.filter(e=>e);if(r===this.input){for(let t of this.tooltipViews)t.update&&t.update(e);return!1}let a=[],o=t?[]:null;for(let n=0;n<i.length;n++){let r=i[n],s=-1;if(r){for(let e=0;e<this.tooltips.length;e++){let t=this.tooltips[e];t&&t.create==r.create&&(s=e)}if(s<0)a[n]=this.createTooltipView(r,n?a[n-1]:null),o&&(o[n]=!!r.above);else{let r=a[n]=this.tooltipViews[s];o&&(o[n]=t[s]),r.update&&r.update(e)}}}for(let e of this.tooltipViews)a.indexOf(e)<0&&(this.removeTooltipView(e),(n=e.destroy)==null||n.call(e));return t&&(o.forEach((e,n)=>t[n]=e),t.length=o.length),this.input=r,this.tooltips=i,this.tooltipViews=a,!0}};function RI(e){let t=e.dom.ownerDocument.documentElement;return{top:0,left:0,bottom:t.clientHeight,right:t.clientWidth}}var zI=rk.define({combine:e=>({position:PA.ios?`absolute`:e.find(e=>e.position)?.position||`fixed`,parent:e.find(e=>e.parent)?.parent||null,tooltipSpace:e.find(e=>e.tooltipSpace)?.tooltipSpace||RI})}),BI=new WeakMap,VI=pM.fromClass(class{constructor(e){this.view=e,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let t=e.state.facet(zI);this.position=t.position,this.parent=t.parent,this.classes=e.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.resizeObserver=typeof ResizeObserver==`function`?new ResizeObserver(()=>this.measureSoon()):null,this.manager=new LI(e,GI,(e,t)=>this.createTooltip(e,t),e=>{this.resizeObserver&&this.resizeObserver.unobserve(e.dom),e.dom.remove()}),this.above=this.manager.tooltips.map(e=>!!e.above),this.intersectionObserver=typeof IntersectionObserver==`function`?new IntersectionObserver(e=>{Date.now()>this.lastTransaction-50&&e.length>0&&e[e.length-1].intersectionRatio<1&&this.measureSoon()},{threshold:[1]}):null,this.observeIntersection(),e.win.addEventListener(`resize`,this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement(`div`),this.container.style.position=`relative`,this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let e of this.manager.tooltipViews)this.intersectionObserver.observe(e.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(e){e.transactions.length&&(this.lastTransaction=Date.now());let t=this.manager.update(e,this.above);t&&this.observeIntersection();let n=t||e.geometryChanged,r=e.state.facet(zI);if(r.position!=this.position&&!this.madeAbsolute){this.position=r.position;for(let e of this.manager.tooltipViews)e.dom.style.position=this.position;n=!0}if(r.parent!=this.parent){this.parent&&this.container.remove(),this.parent=r.parent,this.createContainer();for(let e of this.manager.tooltipViews)this.container.appendChild(e.dom);n=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);n&&this.maybeMeasure()}createTooltip(e,t){let n=e.create(this.view),r=t?t.dom:null;if(n.dom.classList.add(`cm-tooltip`),e.arrow&&!n.dom.querySelector(`.cm-tooltip > .cm-tooltip-arrow`)){let e=document.createElement(`div`);e.className=`cm-tooltip-arrow`,n.dom.appendChild(e)}return n.dom.style.position=this.position,n.dom.style.top=II,n.dom.style.left=`0px`,this.container.insertBefore(n.dom,r),n.mount&&n.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(n.dom),n}destroy(){var e,t,n;this.view.win.removeEventListener(`resize`,this.measureSoon);for(let t of this.manager.tooltipViews)t.dom.remove(),(e=t.destroy)==null||e.call(t);this.parent&&this.container.remove(),(t=this.resizeObserver)==null||t.disconnect(),(n=this.intersectionObserver)==null||n.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let e=1,t=1,n=!1;if(this.position==`fixed`&&this.manager.tooltipViews.length){let{dom:e}=this.manager.tooltipViews[0];if(PA.safari){let t=e.getBoundingClientRect();n=Math.abs(t.top+1e4)>1||Math.abs(t.left)>1}else n=!!e.offsetParent&&e.offsetParent!=this.container.ownerDocument.body}if(n||this.position==`absolute`){if(this.parent){let n=this.parent.getBoundingClientRect();n.width&&n.height&&(e=n.width/this.parent.offsetWidth,t=n.height/this.parent.offsetHeight)}else({scaleX:e,scaleY:t}=this.view.viewState)}let r=this.view.scrollDOM.getBoundingClientRect(),i=wM(this.view);return{visible:{left:r.left+i.left,top:r.top+i.top,right:r.right-i.right,bottom:r.bottom-i.bottom},parent:this.parent?this.container.getBoundingClientRect():this.view.dom.getBoundingClientRect(),pos:this.manager.tooltips.map((e,t)=>{let n=this.manager.tooltipViews[t];return n.getCoords?n.getCoords(e.pos):this.view.coordsAtPos(e.pos)}),size:this.manager.tooltipViews.map(({dom:e})=>e.getBoundingClientRect()),space:this.view.state.facet(zI).tooltipSpace(this.view),scaleX:e,scaleY:t,makeAbsolute:n}}writeMeasure(e){if(e.makeAbsolute){this.madeAbsolute=!0,this.position=`absolute`;for(let e of this.manager.tooltipViews)e.dom.style.position=`absolute`}let{visible:t,space:n,scaleX:r,scaleY:i}=e,a=[];for(let o=0;o<this.manager.tooltips.length;o++){let s=this.manager.tooltips[o],c=this.manager.tooltipViews[o],{dom:l}=c,u=e.pos[o],d=e.size[o];if(!u||s.clip!==!1&&(u.bottom<=Math.max(t.top,n.top)||u.top>=Math.min(t.bottom,n.bottom)||u.right<Math.max(t.left,n.left)-.1||u.left>Math.min(t.right,n.right)+.1)){l.style.top=II;continue}let f=s.arrow?c.dom.querySelector(`.cm-tooltip-arrow`):null,p=f?7:0,m=d.right-d.left,h=BI.get(c)??d.bottom-d.top,g=c.offset||WI,_=this.view.textDirection==Tj.LTR,v=d.width>n.right-n.left?_?n.left:n.right-d.width:_?Math.max(n.left,Math.min(u.left-(f?14:0)+g.x,n.right-m)):Math.min(Math.max(n.left,u.left-m+(f?14:0)-g.x),n.right-m),y=this.above[o];!s.strictSide&&(y?u.top-h-p-g.y<n.top:u.bottom+h+p+g.y>n.bottom)&&y==n.bottom-u.bottom>u.top-n.top&&(y=this.above[o]=!y);let b=(y?u.top-n.top:n.bottom-u.bottom)-p;if(b<h&&c.resize!==!1){if(b<this.view.defaultLineHeight){l.style.top=II;continue}BI.set(c,h),l.style.height=(h=b)/i+`px`}else l.style.height&&(l.style.height=``);let x=y?u.top-h-p-g.y:u.bottom+p+g.y,S=v+m;if(c.overlap!==!0)for(let e of a)e.left<S&&e.right>v&&e.top<x+h&&e.bottom>x&&(x=y?e.top-h-2-p:e.bottom+p+2);if(this.position==`absolute`?(l.style.top=(x-e.parent.top)/i+`px`,HI(l,(v-e.parent.left)/r)):(l.style.top=x/i+`px`,HI(l,v/r)),f){let e=u.left+(_?g.x:-g.x)-(v+14-7);f.style.left=e/r+`px`}c.overlap!==!0&&a.push({left:v,top:x,right:S,bottom:x+h}),l.classList.toggle(`cm-tooltip-above`,y),l.classList.toggle(`cm-tooltip-below`,!y),c.positioned&&c.positioned(e.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let e of this.manager.tooltipViews)e.dom.style.top=II}},{eventObservers:{scroll(){this.maybeMeasure()}}});function HI(e,t){let n=parseInt(e.style.left,10);(isNaN(n)||Math.abs(t-n)>1)&&(e.style.left=t+`px`)}var UI=SF.baseTheme({".cm-tooltip":{zIndex:500,boxSizing:`border-box`},"&light .cm-tooltip":{border:`1px solid #bbb`,backgroundColor:`#f5f5f5`},"&light .cm-tooltip-section:not(:first-child)":{borderTop:`1px solid #bbb`},"&dark .cm-tooltip":{backgroundColor:`#333338`,color:`white`},".cm-tooltip-arrow":{height:`7px`,width:`14px`,position:`absolute`,zIndex:-1,overflow:`hidden`,"&:before, &:after":{content:`''`,position:`absolute`,width:0,height:0,borderLeft:`7px solid transparent`,borderRight:`7px solid transparent`},".cm-tooltip-above &":{bottom:`-7px`,"&:before":{borderTop:`7px solid #bbb`},"&:after":{borderTop:`7px solid #f5f5f5`,bottom:`1px`}},".cm-tooltip-below &":{top:`-7px`,"&:before":{borderBottom:`7px solid #bbb`},"&:after":{borderBottom:`7px solid #f5f5f5`,top:`1px`}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:`#333338`,borderBottomColor:`#333338`},"&:after":{borderTopColor:`transparent`,borderBottomColor:`transparent`}}}),WI={x:0,y:0},GI=rk.define({enables:[VI,UI]}),KI=rk.define({combine:e=>e.reduce((e,t)=>e.concat(t),[])}),qI=class e{static create(t){return new e(t)}constructor(e){this.view=e,this.mounted=!1,this.dom=document.createElement(`div`),this.dom.classList.add(`cm-tooltip-hover`),this.manager=new LI(e,KI,(e,t)=>this.createHostedView(e,t),e=>e.dom.remove())}createHostedView(e,t){let n=e.create(this.view);return n.dom.classList.add(`cm-tooltip-section`),this.dom.insertBefore(n.dom,t?t.dom.nextSibling:this.dom.firstChild),this.mounted&&n.mount&&n.mount(this.view),n}mount(e){for(let t of this.manager.tooltipViews)t.mount&&t.mount(e);this.mounted=!0}positioned(e){for(let t of this.manager.tooltipViews)t.positioned&&t.positioned(e)}update(e){this.manager.update(e)}destroy(){var e;for(let t of this.manager.tooltipViews)(e=t.destroy)==null||e.call(t)}passProp(e){let t;for(let n of this.manager.tooltipViews){let r=n[e];if(r!==void 0){if(t===void 0)t=r;else if(t!==r)return}}return t}get offset(){return this.passProp(`offset`)}get getCoords(){return this.passProp(`getCoords`)}get overlap(){return this.passProp(`overlap`)}get resize(){return this.passProp(`resize`)}},JI=GI.compute([KI],e=>{let t=e.facet(KI);return t.length===0?null:{pos:Math.min(...t.map(e=>e.pos)),end:Math.max(...t.map(e=>e.end??e.pos)),create:qI.create,above:t[0].above,arrow:t.some(e=>e.arrow)}}),YI=rk.define(),XI=class{constructor(e,t,n,r,i,a){this.view=e,this.source=t,this.field=n,this.locked=r,this.setHover=i,this.hoverTime=a,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:e.dom,time:0},this.checkHover=this.checkHover.bind(this),e.dom.addEventListener(`mouseleave`,this.mouseleave=this.mouseleave.bind(this)),e.dom.addEventListener(`mousemove`,this.mousemove=this.mousemove.bind(this))}update(e){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout(()=>this.startHover(),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active.length)return;let e=Date.now()-this.lastMove.time;e<this.hoverTime?this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime-e):this.startHover()}startHover(){clearTimeout(this.restartTimeout);let{view:e,lastMove:t}=this,n=e.docView.tile.nearest(t.target);if(!n)return;let r,i=1;if(n.isWidget())r=n.posAtStart;else{if(r=e.posAtCoords(t),r==null)return;let n=e.coordsAtPos(r);if(!n||t.y<n.top||t.y>n.bottom||t.x<n.left-e.defaultCharacterWidth||t.x>n.right+e.defaultCharacterWidth)return;let a=e.bidiSpans(e.state.doc.lineAt(r)).find(e=>e.from<=r&&e.to>=r),o=a&&a.dir==Tj.RTL?-1:1;i=t.x<n.left?-o:o}this.activateHover(e,r,i)}activateHover(e,t,n,r){let i=this.source(e,t,n),a=t=>{if(t&&!(Array.isArray(t)&&!t.length)){let n=Array.isArray(t)?t:[t];r&&this.locked.set(n,r),e.dispatch({effects:this.setHover.of(n)})}};if(i&&`then`in i){let n=this.pending={pos:t};i.then(e=>{this.pending==n&&(this.pending=null,a(e))},t=>lM(e.state,t,`hover tooltip`))}else a(i)}get tooltip(){let e=this.view.plugin(VI),t=e?e.manager.tooltips.findIndex(e=>e.create==qI.create):-1;return t>-1?e.manager.tooltipViews[t]:null}mousemove(e){this.lastMove={x:e.clientX,y:e.clientY,target:e.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let{active:t,tooltip:n}=this;if(t.length&&!this.locked.has(t)&&n&&!QI(n.dom,e)||this.pending){let{pos:n}=t[0]||this.pending,r=t[0]?.end??n;(n==r?this.view.posAtCoords(this.lastMove)!=n:!$I(this.view,n,r,e.clientX,e.clientY))&&(this.view.dispatch({effects:this.setHover.of([])}),this.pending=null)}}mouseleave(e){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1;let{active:t}=this;if(t.length&&!this.locked.has(t)){let{tooltip:t}=this;t&&t.dom.contains(e.relatedTarget)?this.watchTooltipLeave(t.dom):this.view.dispatch({effects:this.setHover.of([])})}}watchTooltipLeave(e){let t=n=>{e.removeEventListener(`mouseleave`,t);let{active:r}=this;r.length&&!this.locked.has(r)&&!this.view.dom.contains(n.relatedTarget)&&this.view.dispatch({effects:this.setHover.of([])})};e.addEventListener(`mouseleave`,t)}destroy(){clearTimeout(this.hoverTimeout),clearTimeout(this.restartTimeout),this.view.dom.removeEventListener(`mouseleave`,this.mouseleave),this.view.dom.removeEventListener(`mousemove`,this.mousemove)}},ZI=4;function QI(e,t){let{left:n,right:r,top:i,bottom:a}=e.getBoundingClientRect(),o;if(o=e.querySelector(`.cm-tooltip-arrow`)){let e=o.getBoundingClientRect();i=Math.min(e.top,i),a=Math.max(e.bottom,a)}return t.clientX>=n-ZI&&t.clientX<=r+ZI&&t.clientY>=i-ZI&&t.clientY<=a+ZI}function $I(e,t,n,r,i,a){let o=e.scrollDOM.getBoundingClientRect(),s=e.documentTop+e.documentPadding.top+e.contentHeight;if(o.left>r||o.right<r||o.top>i||Math.min(o.bottom,s)<i)return!1;let c=e.posAtCoords({x:r,y:i},!1);return c>=t&&c<=n}function eL(e,t={}){let n=jk.define(),r=new WeakMap,i=uk.define({create(){return[]},update(e,a){let o=r.get(e);if(e.length&&(t.hideOnChange&&(a.docChanged||a.selection)||o&&o(a)?e=[]:t.hideOn&&(e=e.filter(e=>!t.hideOn(a,e)))),a.docChanged&&e.length){let t=[];for(let n of e){let e=a.changes.mapPos(n.pos,-1,GO.TrackDel);if(e!=null){let r=Object.assign(Object.create(null),n);r.pos=e,r.end!=null&&(r.end=a.changes.mapPos(r.end)),t.push(r)}}e=t}for(let t of a.effects)t.is(n)&&(e=t.value,o=void 0),(t.is(rL)&&!t.value||t.value==i)&&(e=[]);return e.length&&o&&r.set(e,o),e},provide:e=>KI.from(e)}),a=pM.define(a=>new XI(a,e,i,r,n,t.hoverTime||300));return{active:i,extension:[i,a,YI.of(a),JI]}}function tL(e,t,n,r={}){let i=e.state.facet(YI).map(t=>e.plugin(t)).filter(e=>!!e);if(r.tooltip&&r.tooltip.active){let e=i.find(e=>e.field==r.tooltip.active);e&&(i=[e])}for(let a of i)a.activateHover(e,t,n,r.until??(()=>!1))}function nL(e,t){let n=e.plugin(VI);if(!n)return null;let r=n.manager.tooltips.indexOf(t);return r<0?null:n.manager.tooltipViews[r]}var rL=jk.define(),iL=rk.define({combine(e){let t,n;for(let r of e)t||=r.topContainer,n||=r.bottomContainer;return{topContainer:t,bottomContainer:n}}});function aL(e,t){let n=e.plugin(oL),r=n?n.specs.indexOf(t):-1;return r>-1?n.panels[r]:null}var oL=pM.fromClass(class{constructor(e){this.input=e.state.facet(lL),this.specs=this.input.filter(e=>e),this.panels=this.specs.map(t=>t(e));let t=e.state.facet(iL);this.top=new sL(e,!0,t.topContainer),this.bottom=new sL(e,!1,t.bottomContainer),this.top.sync(this.panels.filter(e=>e.top)),this.bottom.sync(this.panels.filter(e=>!e.top));for(let e of this.panels)e.dom.classList.add(`cm-panel`),e.mount&&e.mount()}update(e){let t=e.state.facet(iL);this.top.container!=t.topContainer&&(this.top.sync([]),this.top=new sL(e.view,!0,t.topContainer)),this.bottom.container!=t.bottomContainer&&(this.bottom.sync([]),this.bottom=new sL(e.view,!1,t.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let n=e.state.facet(lL);if(n!=this.input){let t=n.filter(e=>e),r=[],i=[],a=[],o=[];for(let n of t){let t=this.specs.indexOf(n),s;t<0?(s=n(e.view),o.push(s)):(s=this.panels[t],s.update&&s.update(e)),r.push(s),(s.top?i:a).push(s)}this.specs=t,this.panels=r,this.top.sync(i),this.bottom.sync(a);for(let e of o)e.dom.classList.add(`cm-panel`),e.mount&&e.mount()}else for(let t of this.panels)t.update&&t.update(e)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:e=>SF.scrollMargins.of(t=>{let n=t.plugin(e);return n&&{top:n.top.scrollMargin(),bottom:n.bottom.scrollMargin()}})}),sL=class{constructor(e,t,n){this.view=e,this.top=t,this.container=n,this.dom=void 0,this.classes=``,this.panels=[],this.syncClasses()}sync(e){for(let t of this.panels)t.destroy&&e.indexOf(t)<0&&t.destroy();this.panels=e,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&=(this.dom.remove(),void 0);return}if(!this.dom){this.dom=document.createElement(`div`),this.dom.className=this.top?`cm-panels cm-panels-top`:`cm-panels cm-panels-bottom`;let e=this.container||this.view.dom;e.insertBefore(this.dom,this.top?e.firstChild:null)}let e=this.dom.firstChild;for(let t of this.panels)if(t.dom.parentNode==this.dom){for(;e!=t.dom;)e=cL(e);e=e.nextSibling}else this.dom.insertBefore(t.dom,e);for(;e;)e=cL(e)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let e of this.classes.split(` `))e&&this.container.classList.remove(e);for(let e of(this.classes=this.view.themeClasses).split(` `))e&&this.container.classList.add(e)}}};function cL(e){let t=e.nextSibling;return e.remove(),t}var lL=rk.define({enables:oL});function uL(e,t){let n,r=new Promise(e=>n=e),i=e=>mL(e,t,n);e.state.field(dL,!1)?e.dispatch({effects:fL.of(i)}):e.dispatch({effects:jk.appendConfig.of(dL.init(()=>[i]))});let a=pL.of(i);return{close:a,result:r.then(t=>((e.win.queueMicrotask||(t=>e.win.setTimeout(t,10)))(()=>{e.state.field(dL).indexOf(i)>-1&&e.dispatch({effects:a})}),t))}}var dL=uk.define({create(){return[]},update(e,t){for(let n of t.effects)n.is(fL)?e=[n.value].concat(e):n.is(pL)&&(e=e.filter(e=>e!=n.value));return e},provide:e=>lL.computeN([e],t=>t.field(e))}),fL=jk.define(),pL=jk.define();function mL(e,t,n){let r=t.content?t.content(e,()=>o(null)):null;if(!r){if(r=xA(`form`),t.input){let e=xA(`input`,t.input);/^(text|password|number|email|tel|url)$/.test(e.type)&&e.classList.add(`cm-textfield`),e.name||=`input`,r.appendChild(xA(`label`,(t.label||``)+`: `,e))}else r.appendChild(document.createTextNode(t.label||``));r.appendChild(document.createTextNode(` `)),r.appendChild(xA(`button`,{class:`cm-button`,type:`submit`},t.submitLabel||`OK`))}let i=r.nodeName==`FORM`?[r]:r.querySelectorAll(`form`);for(let e=0;e<i.length;e++){let t=i[e];t.addEventListener(`keydown`,e=>{e.keyCode==27?(e.preventDefault(),o(null)):e.keyCode==13&&(e.preventDefault(),o(t))}),t.addEventListener(`submit`,e=>{e.preventDefault(),o(t)})}let a=xA(`div`,r,xA(`button`,{onclick:()=>o(null),"aria-label":e.state.phrase(`close`),class:`cm-dialog-close`,type:`button`},[`×`]));t.class&&(a.className=t.class),a.classList.add(`cm-dialog`);function o(t){a.contains(a.ownerDocument.activeElement)&&e.focus(),n(t)}return{dom:a,top:t.top,mount:()=>{if(t.focus){let e;e=typeof t.focus==`string`?r.querySelector(t.focus):r.querySelector(`input`)||r.querySelector(`button`),e&&`select`in e?e.select():e&&`focus`in e&&e.focus()}}}}var hL=class extends Jk{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}};hL.prototype.elementClass=``,hL.prototype.toDOM=void 0,hL.prototype.mapMode=GO.TrackBefore,hL.prototype.startSide=hL.prototype.endSide=-1,hL.prototype.point=!0;var gL=rk.define(),_L=rk.define(),vL={class:``,renderEmptyElements:!1,elementStyle:``,markers:()=>$k.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{},side:`before`},yL=rk.define();function bL(e){return[SL(),yL.of({...vL,...e})]}var xL=rk.define({combine:e=>e.some(e=>e)});function SL(e){let t=[CL];return e&&e.fixed===!1&&t.push(xL.of(!0)),t}var CL=pM.fromClass(class{constructor(e){this.view=e,this.domAfter=null,this.prevViewport=e.viewport,this.dom=document.createElement(`div`),this.dom.className=`cm-gutters cm-gutters-before`,this.dom.setAttribute(`aria-hidden`,`true`),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+`px`,this.gutters=e.state.facet(yL).map(t=>new DL(e,t)),this.fixed=!e.state.facet(xL);for(let e of this.gutters)e.config.side==`after`?this.getDOMAfter().appendChild(e.dom):this.dom.appendChild(e.dom);this.fixed&&(this.dom.style.position=`sticky`),this.syncGutters(!1),e.scrollDOM.insertBefore(this.dom,e.contentDOM)}getDOMAfter(){return this.domAfter||(this.domAfter=document.createElement(`div`),this.domAfter.className=`cm-gutters cm-gutters-after`,this.domAfter.setAttribute(`aria-hidden`,`true`),this.domAfter.style.minHeight=this.view.contentHeight/this.view.scaleY+`px`,this.domAfter.style.position=this.fixed?`sticky`:``,this.view.scrollDOM.appendChild(this.domAfter)),this.domAfter}update(e){if(this.updateGutters(e)){let t=this.prevViewport,n=e.view.viewport,r=Math.min(t.to,n.to)-Math.max(t.from,n.from);this.syncGutters(r<(n.to-n.from)*.8)}if(e.geometryChanged){let e=this.view.contentHeight/this.view.scaleY+`px`;this.dom.style.minHeight=e,this.domAfter&&(this.domAfter.style.minHeight=e)}this.view.state.facet(xL)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?`sticky`:``,this.domAfter&&(this.domAfter.style.position=this.fixed?`sticky`:``)),this.prevViewport=e.view.viewport}syncGutters(e){let t=this.dom.nextSibling;e&&(this.dom.remove(),this.domAfter&&this.domAfter.remove());let n=$k.iter(this.view.state.facet(gL),this.view.viewport.from),r=[],i=this.gutters.map(e=>new EL(e,this.view.viewport,-this.view.documentPadding.top));for(let e of this.view.viewportLineBlocks)if(r.length&&(r=[]),Array.isArray(e.type)){let t=!0;for(let a of e.type)if(a.type==HA.Text&&t){TL(n,r,a.from);for(let e of i)e.line(this.view,a,r);t=!1}else if(a.widget)for(let e of i)e.widget(this.view,a)}else if(e.type==HA.Text){TL(n,r,e.from);for(let t of i)t.line(this.view,e,r)}else if(e.widget)for(let t of i)t.widget(this.view,e);for(let e of i)e.finish();e&&(this.view.scrollDOM.insertBefore(this.dom,t),this.domAfter&&this.view.scrollDOM.appendChild(this.domAfter))}updateGutters(e){let t=e.startState.facet(yL),n=e.state.facet(yL),r=e.docChanged||e.heightChanged||e.viewportChanged||!$k.eq(e.startState.facet(gL),e.state.facet(gL),e.view.viewport.from,e.view.viewport.to);if(t==n)for(let t of this.gutters)t.update(e)&&(r=!0);else{r=!0;let i=[];for(let r of n){let n=t.indexOf(r);n<0?i.push(new DL(this.view,r)):(this.gutters[n].update(e),i.push(this.gutters[n]))}for(let e of this.gutters)e.dom.remove(),i.indexOf(e)<0&&e.destroy();for(let e of i)e.config.side==`after`?this.getDOMAfter().appendChild(e.dom):this.dom.appendChild(e.dom);this.gutters=i}return r}destroy(){for(let e of this.gutters)e.destroy();this.dom.remove(),this.domAfter&&this.domAfter.remove()}},{provide:e=>SF.scrollMargins.of(t=>{let n=t.plugin(e);if(!n||n.gutters.length==0||!n.fixed)return null;let r=n.dom.offsetWidth*t.scaleX,i=n.domAfter?n.domAfter.offsetWidth*t.scaleX:0;return t.textDirection==Tj.LTR?{left:r,right:i}:{right:r,left:i}})});function wL(e){return Array.isArray(e)?e:[e]}function TL(e,t,n){for(;e.value&&e.from<=n;)e.from==n&&t.push(e.value),e.next()}var EL=class{constructor(e,t,n){this.gutter=e,this.height=n,this.i=0,this.cursor=$k.iter(e.markers,t.from)}addElement(e,t,n){let{gutter:r}=this,i=(t.top-this.height)/e.scaleY,a=t.height/e.scaleY;if(this.i==r.elements.length){let t=new OL(e,a,i,n);r.elements.push(t),r.dom.appendChild(t.dom)}else r.elements[this.i].update(e,a,i,n);this.height=t.bottom,this.i++}line(e,t,n){let r=[];TL(this.cursor,r,t.from),n.length&&(r=r.concat(n));let i=this.gutter.config.lineMarker(e,t,r);i&&r.unshift(i);let a=this.gutter;r.length==0&&!a.config.renderEmptyElements||this.addElement(e,t,r)}widget(e,t){let n=this.gutter.config.widgetMarker(e,t.widget,t),r=n?[n]:null;for(let n of e.state.facet(_L)){let i=n(e,t.widget,t);i&&(r||=[]).push(i)}r&&this.addElement(e,t,r)}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}},DL=class{constructor(e,t){this.view=e,this.config=t,this.elements=[],this.spacer=null,this.dom=document.createElement(`div`),this.dom.className=`cm-gutter`+(this.config.class?` `+this.config.class:``);for(let n in t.domEventHandlers)this.dom.addEventListener(n,r=>{let i=r.target,a;if(i!=this.dom&&this.dom.contains(i)){for(;i.parentNode!=this.dom;)i=i.parentNode;let e=i.getBoundingClientRect();a=(e.top+e.bottom)/2}else a=r.clientY;let o=e.lineBlockAtHeight(a-e.documentTop);t.domEventHandlers[n](e,o,r)&&r.preventDefault()});this.markers=wL(t.markers(e)),t.initialSpacer&&(this.spacer=new OL(e,0,0,[t.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+=`visibility: hidden; pointer-events: none`)}update(e){let t=this.markers;if(this.markers=wL(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let t=this.config.updateSpacer(this.spacer.markers[0],e);t!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[t])}let n=e.view.viewport;return!$k.eq(this.markers,t,n.from,n.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}},OL=class{constructor(e,t,n,r){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement(`div`),this.dom.className=`cm-gutterElement`,this.update(e,t,n,r)}update(e,t,n,r){this.height!=t&&(this.height=t,this.dom.style.height=t+`px`),this.above!=n&&(this.dom.style.marginTop=(this.above=n)?n+`px`:``),kL(this.markers,r)||this.setMarkers(e,r)}setMarkers(e,t){let n=`cm-gutterElement`,r=this.dom.firstChild;for(let i=0,a=0;;){let o=a,s=i<t.length?t[i++]:null,c=!1;if(s){let e=s.elementClass;e&&(n+=` `+e);for(let e=a;e<this.markers.length;e++)if(this.markers[e].compare(s)){o=e,c=!0;break}}else o=this.markers.length;for(;a<o;){let e=this.markers[a++];if(e.toDOM){e.destroy(r);let t=r.nextSibling;r.remove(),r=t}}if(!s)break;s.toDOM&&(c?r=r.nextSibling:this.dom.insertBefore(s.toDOM(e),r)),c&&a++}this.dom.className=n,this.markers=t}destroy(){this.setMarkers(null,[])}};function kL(e,t){if(e.length!=t.length)return!1;for(let n=0;n<e.length;n++)if(!e[n].compare(t[n]))return!1;return!0}var AL=rk.define(),jL=rk.define(),ML=rk.define({combine(e){return qk(e,{formatNumber:String,domEventHandlers:{}},{domEventHandlers(e,t){let n=Object.assign({},e);for(let e in t){let r=n[e],i=t[e];n[e]=r?(e,t,n)=>r(e,t,n)||i(e,t,n):i}return n}})}}),NL=class extends hL{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}};function PL(e,t){return e.state.facet(ML).formatNumber(t,e.state)}var FL=yL.compute([ML],e=>({class:`cm-lineNumbers`,renderEmptyElements:!1,markers(e){return e.state.facet(AL)},lineMarker(e,t,n){return n.some(e=>e.toDOM)?null:new NL(PL(e,e.state.doc.lineAt(t.from).number))},widgetMarker:(e,t,n)=>{for(let r of e.state.facet(jL)){let i=r(e,t,n);if(i)return i}return null},lineMarkerChange:e=>e.startState.facet(ML)!=e.state.facet(ML),initialSpacer(e){return new NL(PL(e,LL(e.state.doc.lines)))},updateSpacer(e,t){let n=PL(t.view,LL(t.view.state.doc.lines));return n==e.number?e:new NL(n)},domEventHandlers:e.facet(ML).domEventHandlers,side:`before`}));function IL(e={}){return[ML.of(e),SL(),FL]}function LL(e){let t=9;for(;t<e;)t=t*10+9;return t}var RL=new class extends hL{constructor(){super(...arguments),this.elementClass=`cm-activeLineGutter`}},zL=gL.compute([`selection`],e=>{let t=[],n=-1;for(let r of e.selection.ranges){let i=e.doc.lineAt(r.head).from;i>n&&(n=i,t.push(RL.range(i)))}return $k.of(t)});function BL(){return zL}var VL=1024,HL=0,UL=class{constructor(e,t){this.from=e,this.to=t}},WL=class{constructor(e={}){this.id=HL++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw Error(`This node type doesn't define a deserialize function`)}),this.combine=e.combine||null}add(e){if(this.perNode)throw RangeError(`Can't add per-node props to node types`);return typeof e!=`function`&&(e=qL.match(e)),t=>{let n=e(t);return n===void 0?null:[this,n]}}};WL.closedBy=new WL({deserialize:e=>e.split(` `)}),WL.openedBy=new WL({deserialize:e=>e.split(` `)}),WL.group=new WL({deserialize:e=>e.split(` `)}),WL.isolate=new WL({deserialize:e=>{if(e&&e!=`rtl`&&e!=`ltr`&&e!=`auto`)throw RangeError(`Invalid value for isolate: `+e);return e||`auto`}}),WL.contextHash=new WL({perNode:!0}),WL.lookAhead=new WL({perNode:!0}),WL.mounted=new WL({perNode:!0});var GL=class{constructor(e,t,n,r=!1){this.tree=e,this.overlay=t,this.parser=n,this.bracketed=r}static get(e){return e&&e.props&&e.props[WL.mounted.id]}},KL=Object.create(null),qL=class e{constructor(e,t,n,r=0){this.name=e,this.props=t,this.id=n,this.flags=r}static define(t){let n=t.props&&t.props.length?Object.create(null):KL,r=!!t.top|(t.skipped?2:0)|(t.error?4:0)|(t.name==null?8:0),i=new e(t.name||``,n,t.id,r);if(t.props){for(let e of t.props)if(Array.isArray(e)||(e=e(i)),e){if(e[0].perNode)throw RangeError(`Can't store a per-node prop on a node type`);n[e[0].id]=e[1]}}return i}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e==`string`){if(this.name==e)return!0;let t=this.prop(WL.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let n in e)for(let r of n.split(` `))t[r]=e[n];return e=>{for(let n=e.prop(WL.group),r=-1;r<(n?n.length:0);r++){let i=t[r<0?e.name:n[r]];if(i)return i}}}};qL.none=new qL(``,Object.create(null),0,8);var JL=class e{constructor(e){this.types=e;for(let t=0;t<e.length;t++)if(e[t].id!=t)throw RangeError(`Node type ids should correspond to array positions when creating a node set`)}extend(...t){let n=[];for(let e of this.types){let r=null;for(let n of t){let t=n(e);if(t){r||=Object.assign({},e.props);let n=t[1],i=t[0];i.combine&&i.id in r&&(n=i.combine(r[i.id],n)),r[i.id]=n}}n.push(r?new qL(e.name,r,e.id,e.flags):e)}return new e(n)}},YL=new WeakMap,XL=new WeakMap,ZL;(function(e){e[e.ExcludeBuffers=1]=`ExcludeBuffers`,e[e.IncludeAnonymous=2]=`IncludeAnonymous`,e[e.IgnoreMounts=4]=`IgnoreMounts`,e[e.IgnoreOverlays=8]=`IgnoreOverlays`,e[e.EnterBracketed=16]=`EnterBracketed`})(ZL||={});var QL=class e{constructor(e,t,n,r,i){if(this.type=e,this.children=t,this.positions=n,this.length=r,this.props=null,i&&i.length){this.props=Object.create(null);for(let[e,t]of i)this.props[typeof e==`number`?e:e.id]=t}}toString(){let e=GL.get(this);if(e&&!e.overlay)return e.tree.toString();let t=``;for(let e of this.children){let n=e.toString();n&&(t&&(t+=`,`),t+=n)}return this.type.name?(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(t.length?`(`+t+`)`:``):t}cursor(e=0){return new fR(this.topNode,e)}cursorAt(e,t=0,n=0){let r=new fR(YL.get(this)||this.topNode);return r.moveTo(e,t),YL.set(this,r._tree),r}get topNode(){return new iR(this,0,0,null)}resolve(e,t=0){let n=nR(YL.get(this)||this.topNode,e,t,!1);return YL.set(this,n),n}resolveInner(e,t=0){let n=nR(XL.get(this)||this.topNode,e,t,!0);return XL.set(this,n),n}resolveStack(e,t=0){return dR(this,e,t)}iterate(e){let{enter:t,leave:n,from:r=0,to:i=this.length}=e,a=e.mode||0,o=(a&ZL.IncludeAnonymous)>0;for(let e=this.cursor(a|ZL.IncludeAnonymous);;){let a=!1;if(e.from<=i&&e.to>=r&&(!o&&e.type.isAnonymous||t(e)!==!1)){if(e.firstChild())continue;a=!0}for(;a&&n&&(o||!e.type.isAnonymous)&&n(e),!e.nextSibling();){if(!e.parent())return;a=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(t={}){return this.children.length<=8?this:_R(qL.none,this.children,this.positions,0,this.children.length,0,this.length,(t,n,r)=>new e(this.type,t,n,r,this.propValues),t.makeTree||((t,n,r)=>new e(qL.none,t,n,r)))}static build(e){return mR(e)}};QL.empty=new QL(qL.none,[],[],0);var $L=class e{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new e(this.buffer,this.index)}},eR=class e{constructor(e,t,n){this.buffer=e,this.length=t,this.set=n}get type(){return qL.none}toString(){let e=[];for(let t=0;t<this.buffer.length;)e.push(this.childString(t)),t=this.buffer[t+3];return e.join(`,`)}childString(e){let t=this.buffer[e],n=this.buffer[e+3],r=this.set.types[t],i=r.name;if(/\W/.test(i)&&!r.isError&&(i=JSON.stringify(i)),e+=4,n==e)return i;let a=[];for(;e<n;)a.push(this.childString(e)),e=this.buffer[e+3];return i+`(`+a.join(`,`)+`)`}findChild(e,t,n,r,i){let{buffer:a}=this,o=-1;for(let s=e;s!=t&&!(tR(i,r,a[s+1],a[s+2])&&(o=s,n>0));s=a[s+3]);return o}slice(t,n,r){let i=this.buffer,a=new Uint16Array(n-t),o=0;for(let e=t,s=0;e<n;){a[s++]=i[e++],a[s++]=i[e++]-r;let n=a[s++]=i[e++]-r;a[s++]=i[e++]-t,o=Math.max(o,n)}return new e(a,o,this.set)}};function tR(e,t,n,r){switch(e){case-2:return n<t;case-1:return r>=t&&n<t;case 0:return n<t&&r>t;case 1:return n<=t&&r>t;case 2:return r>t;case 4:return!0}}function nR(e,t,n,r){for(;e.from==e.to||(n<1?e.from>=t:e.from>t)||(n>-1?e.to<=t:e.to<t);){let t=!r&&e instanceof iR&&e.index<0?null:e.parent;if(!t)return e;e=t}let i=r?0:ZL.IgnoreOverlays;if(r)for(let r=e,a=r.parent;a;r=a,a=r.parent)r instanceof iR&&r.index<0&&a.enter(t,n,i)?.from!=r.from&&(e=a);for(;;){let r=e.enter(t,n,i);if(!r)return e;e=r}}var rR=class{cursor(e=0){return new fR(this,e)}getChild(e,t=null,n=null){let r=aR(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return aR(this,e,t,n)}resolve(e,t=0){return nR(this,e,t,!1)}resolveInner(e,t=0){return nR(this,e,t,!0)}matchContext(e){return oR(this.parent,e)}enterUnfinishedNodesBefore(e){let t=this.childBefore(e),n=this;for(;t;){let e=t.lastChild;if(!e||e.to!=t.to)break;e.type.isError&&e.from==e.to?(n=t,t=e.prevSibling):t=e}return n}get node(){return this}get next(){return this.parent}},iR=class e extends rR{constructor(e,t,n,r){super(),this._tree=e,this.from=t,this.index=n,this._parent=r}get type(){return this._tree.type}get name(){return this._tree.type.name}get to(){return this.from+this._tree.length}nextChild(t,n,r,i,a=0){for(let o=this;;){for(let{children:s,positions:c}=o._tree,l=n>0?s.length:-1;t!=l;t+=n){let l=s[t],u=c[t]+o.from,d;if(!(!(a&ZL.EnterBracketed&&l instanceof QL&&(d=GL.get(l))&&!d.overlay&&d.bracketed&&r>=u&&r<=u+l.length)&&!tR(i,r,u,u+l.length))){if(l instanceof eR){if(a&ZL.ExcludeBuffers)continue;let e=l.findChild(0,l.buffer.length,n,r-u,i);if(e>-1)return new cR(new sR(o,l,t,u),null,e)}else if(a&ZL.IncludeAnonymous||!l.type.isAnonymous||pR(l)){let s;if(!(a&ZL.IgnoreMounts)&&(s=GL.get(l))&&!s.overlay)return new e(s.tree,u,t,o);let c=new e(l,u,t,o);return a&ZL.IncludeAnonymous||!c.type.isAnonymous?c:c.nextChild(n<0?l.children.length-1:0,n,r,i,a)}}}if(a&ZL.IncludeAnonymous||!o.type.isAnonymous||(t=o.index>=0?o.index+n:n<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}prop(e){return this._tree.prop(e)}enter(t,n,r=0){let i;if(!(r&ZL.IgnoreOverlays)&&(i=GL.get(this._tree))&&i.overlay){let a=t-this.from,o=r&ZL.EnterBracketed&&i.bracketed;for(let{from:t,to:r}of i.overlay)if((n>0||o?t<=a:t<a)&&(n<0||o?r>=a:r>a))return new e(i.tree,i.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,t,n,r)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}};function aR(e,t,n,r){let i=e.cursor(),a=[];if(!i.firstChild())return a;if(n!=null){for(let e=!1;!e;)if(e=i.type.is(n),!i.nextSibling())return a}for(;;){if(r!=null&&i.type.is(r))return a;if(i.type.is(t)&&a.push(i.node),!i.nextSibling())return r==null?a:[]}}function oR(e,t,n=t.length-1){for(let r=e;n>=0;r=r.parent){if(!r)return!1;if(!r.type.isAnonymous){if(t[n]&&t[n]!=r.name)return!1;n--}}return!0}var sR=class{constructor(e,t,n,r){this.parent=e,this.buffer=t,this.index=n,this.start=r}},cR=class e extends rR{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,n){super(),this.context=e,this._parent=t,this.index=n,this.type=e.buffer.set.types[e.buffer.buffer[n]]}child(t,n,r){let{buffer:i}=this.context,a=i.findChild(this.index+4,i.buffer[this.index+3],t,n-this.context.start,r);return a<0?null:new e(this.context,this,a)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}prop(e){return this.type.prop(e)}enter(t,n,r=0){if(r&ZL.ExcludeBuffers)return null;let{buffer:i}=this.context,a=i.findChild(this.index+4,i.buffer[this.index+3],n>0?1:-1,t-this.context.start,n);return a<0?null:new e(this.context,this,a)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:t}=this.context,n=t.buffer[this.index+3];return n<(this._parent?t.buffer[this._parent.index+3]:t.buffer.length)?new e(this.context,this._parent,n):this.externalSibling(1)}get prevSibling(){let{buffer:t}=this.context,n=this._parent?this._parent.index+4:0;return this.index==n?this.externalSibling(-1):new e(this.context,this._parent,t.findChild(n,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],t=[],{buffer:n}=this.context,r=this.index+4,i=n.buffer[this.index+3];if(i>r){let a=n.buffer[this.index+1];e.push(n.slice(r,i,a)),t.push(0)}return new QL(this.type,e,t,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}};function lR(e){if(!e.length)return null;let t=0,n=e[0];for(let r=1;r<e.length;r++){let i=e[r];(i.from>n.from||i.to<n.to)&&(n=i,t=r)}let r=n instanceof iR&&n.index<0?null:n.parent,i=e.slice();return r?i[t]=r:i.splice(t,1),new uR(i,n)}var uR=class{constructor(e,t){this.heads=e,this.node=t}get next(){return lR(this.heads)}};function dR(e,t,n){let r=e.resolveInner(t,n),i=null;for(let e=r instanceof iR?r:r.context.parent;e;e=e.parent)if(e.index<0){let a=e.parent;(i||=[r]).push(a.resolve(t,n)),e=a}else{let a=GL.get(e.tree);if(a&&a.overlay&&a.overlay[0].from<=t&&a.overlay[a.overlay.length-1].to>=t){let o=new iR(a.tree,a.overlay[0].from+e.from,-1,e);(i||=[r]).push(nR(o,t,n,!1))}}return i?lR(i):r}var fR=class{get name(){return this.type.name}constructor(e,t=0){if(this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,this.mode=t&~ZL.EnterBracketed,e instanceof iR)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let t=e._parent;t;t=t._parent)this.stack.unshift(t.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:n,buffer:r}=this.buffer;return this.type=t||r.set.types[r.buffer[e]],this.from=n+r.buffer[e+1],this.to=n+r.buffer[e+2],!0}yield(e){return e?e instanceof iR?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,n){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,n,this.mode));let{buffer:r}=this.buffer,i=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.buffer.start,n);return i<0?!1:(this.stack.push(this.index),this.yieldBuf(i))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,n=this.mode){return this.buffer?n&ZL.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,n))}parent(){if(!this.buffer)return this.yieldNode(this.mode&ZL.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&ZL.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,n=this.stack.length-1;if(e<0){let e=n<0?0:this.stack[n]+4;if(this.index!=e)return this.yieldBuf(t.findChild(e,this.index,-1,0,4))}else{let e=t.buffer[this.index+3];if(e<(n<0?t.buffer.length:t.buffer[this.stack[n]+3]))return this.yieldBuf(e)}return n<0&&this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode))}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,n,{buffer:r}=this;if(r){if(e>0){if(this.index<r.buffer.buffer.length)return!1}else for(let e=0;e<this.index;e++)if(r.buffer.buffer[e+3]<this.index)return!1;({index:t,parent:n}=r)}else({index:t,_parent:n}=this._tree);for(;n;{index:t,_parent:n}=n)if(t>-1)for(let r=t+e,i=e<0?-1:n._tree.children.length;r!=i;r+=e){let e=n._tree.children[r];if(this.mode&ZL.IncludeAnonymous||e instanceof eR||!e.type.isAnonymous||pR(e))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to<e))&&this.parent(););for(;this.enterChild(1,e,t););return this}get node(){if(!this.buffer)return this._tree;let e=this.bufferNode,t=null,n=0;if(e&&e.context==this.buffer)scan:for(let r=this.index,i=this.stack.length;i>=0;){for(let a=e;a;a=a._parent)if(a.index==r){if(r==this.index)return a;t=a,n=i+1;break scan}r=this.stack[--i]}for(let e=n;e<this.stack.length;e++)t=new cR(this.buffer,t,this.stack[e]);return this.bufferNode=new cR(this.buffer,t,this.index)}get tree(){return this.buffer?null:this._tree._tree}iterate(e,t){for(let n=0;;){let r=!1;if(this.type.isAnonymous||e(this)!==!1){if(this.firstChild()){n++;continue}this.type.isAnonymous||(r=!0)}for(;;){if(r&&t&&t(this),r=this.type.isAnonymous,!n)return;if(this.nextSibling())break;this.parent(),n--,r=!0}}}matchContext(e){if(!this.buffer)return oR(this.node.parent,e);let{buffer:t}=this.buffer,{types:n}=t.set;for(let r=e.length-1,i=this.stack.length-1;r>=0;i--){if(i<0)return oR(this._tree,e,r);let a=n[t.buffer[this.stack[i]]];if(!a.isAnonymous){if(e[r]&&e[r]!=a.name)return!1;r--}}return!0}};function pR(e){return e.children.some(e=>e instanceof eR||!e.type.isAnonymous||pR(e))}function mR(e){let{buffer:t,nodeSet:n,maxBufferLength:r=VL,reused:i=[],minRepeatType:a=n.types.length}=e,o=Array.isArray(t)?new $L(t,t.length):t,s=n.types,c=0,l=0;function u(e,t,_,v,y,b){let{id:x,start:S,end:C,size:w}=o,T=l,E=c;if(w<0){if(o.next(),w==-1){let t=i[x];_.push(t),v.push(S-e);return}if(w==-3){c=x;return}if(w==-4){l=x;return}throw RangeError(`Unrecognized record size: ${w}`)}let D=s[x],O,k,A=S-e;if(C-S<=r&&(k=h(o.pos-t,y))){let t=new Uint16Array(k.size-k.skip),r=o.pos-k.size,i=t.length;for(;o.pos>r;)i=g(k.start,t,i);O=new eR(t,C-k.start,n),A=k.start-e}else{let e=o.pos-w;o.next();let t=[],n=[],i=x>=a?x:-1,s=0,c=C;for(;o.pos>e;)i>=0&&o.id==i&&o.size>=0?(o.end<=c-r&&(p(t,n,S,s,o.end,c,i,T,E),s=t.length,c=o.end),o.next()):b>2500?d(S,e,t,n):u(S,e,t,n,i,b+1);if(i>=0&&s>0&&s<t.length&&p(t,n,S,s,S,c,i,T,E),t.reverse(),n.reverse(),i>-1&&s>0){let e=f(D,E);O=_R(D,t,n,0,t.length,0,C-S,e,e)}else O=m(D,t,n,C-S,T-C,E)}_.push(O),v.push(A)}function d(e,t,i,a){let s=[],c=0,l=-1;for(;o.pos>t;){let{id:e,start:t,end:n,size:i}=o;if(i>4)o.next();else if(l>-1&&t<l)break;else l<0&&(l=n-r),s.push(e,t,n),c++,o.next()}if(c){let t=new Uint16Array(c*4),r=s[s.length-2];for(let e=s.length-3,n=0;e>=0;e-=3)t[n++]=s[e],t[n++]=s[e+1]-r,t[n++]=s[e+2]-r,t[n++]=n;i.push(new eR(t,s[2]-r,n)),a.push(r-e)}}function f(e,t){return(n,r,i)=>{let a=0,o=n.length-1,s,c;if(o>=0&&(s=n[o])instanceof QL){if(!o&&s.type==e&&s.length==i)return s;(c=s.prop(WL.lookAhead))&&(a=r[o]+s.length+c)}return m(e,n,r,i,a,t)}}function p(e,t,r,i,a,o,s,c,l){let u=[],d=[];for(;e.length>i;)u.push(e.pop()),d.push(t.pop()+r-a);e.push(m(n.types[s],u,d,o-a,c-o,l)),t.push(a-r)}function m(e,t,n,r,i,a,o){if(a){let e=[WL.contextHash,a];o=o?[e].concat(o):[e]}if(i>25){let e=[WL.lookAhead,i];o=o?[e].concat(o):[e]}return new QL(e,t,n,r,o)}function h(e,t){let n=o.fork(),i=0,s=0,c=0,l=n.end-r,u={size:0,start:0,skip:0};scan:for(let r=n.pos-e;n.pos>r;){let e=n.size;if(n.id==t&&e>=0){u.size=i,u.start=s,u.skip=c,c+=4,i+=4,n.next();continue}let o=n.pos-e;if(e<0||o<r||n.start<l)break;let d=n.id>=a?4:0,f=n.start;for(n.next();n.pos>o;){if(n.size<0){if(n.size==-3||n.size==-4)d+=4;else break scan}else n.id>=a&&(d+=4);n.next()}s=f,i+=e,c+=d}return(t<0||i==e)&&(u.size=i,u.start=s,u.skip=c),u.size>4?u:void 0}function g(e,t,n){let{id:r,start:i,end:s,size:u}=o;if(o.next(),u>=0&&r<a){let a=n;if(u>4){let r=o.pos-(u-4);for(;o.pos>r;)n=g(e,t,n)}t[--n]=a,t[--n]=s-e,t[--n]=i-e,t[--n]=r}else u==-3?c=r:u==-4&&(l=r);return n}let _=[],v=[];for(;o.pos>0;)u(e.start||0,e.bufferStart||0,_,v,-1,0);let y=e.length??(_.length?v[0]+_[0].length:0);return new QL(s[e.topID],_.reverse(),v.reverse(),y)}var hR=new WeakMap;function gR(e,t){if(!e.isAnonymous||t instanceof eR||t.type!=e)return 1;let n=hR.get(t);if(n==null){n=1;for(let r of t.children){if(r.type!=e||!(r instanceof QL)){n=1;break}n+=gR(e,r)}hR.set(t,n)}return n}function _R(e,t,n,r,i,a,o,s,c){let l=0;for(let n=r;n<i;n++)l+=gR(e,t[n]);let u=Math.ceil(l*1.5/8),d=[],f=[];function p(t,n,r,i,o){for(let s=r;s<i;){let r=s,l=n[s],m=gR(e,t[s]);for(s++;s<i;s++){let n=gR(e,t[s]);if(m+n>=u)break;m+=n}if(s==r+1){if(m>u){let e=t[r];p(e.children,e.positions,0,e.children.length,n[r]+o);continue}d.push(t[r])}else{let i=n[s-1]+t[s-1].length-l;d.push(_R(e,t,n,r,s,l,i,null,c))}f.push(l+o-a)}}return p(t,n,r,i,0),(s||c)(d,f,o)}var vR=class{constructor(){this.map=new WeakMap}setBuffer(e,t,n){let r=this.map.get(e);r||this.map.set(e,r=new Map),r.set(t,n)}getBuffer(e,t){let n=this.map.get(e);return n&&n.get(t)}set(e,t){e instanceof cR?this.setBuffer(e.context.buffer,e.index,t):e instanceof iR&&this.map.set(e.tree,t)}get(e){return e instanceof cR?this.getBuffer(e.context.buffer,e.index):e instanceof iR?this.map.get(e.tree):void 0}cursorSet(e,t){e.buffer?this.setBuffer(e.buffer.buffer,e.index,t):this.map.set(e.tree,t)}cursorGet(e){return e.buffer?this.getBuffer(e.buffer.buffer,e.index):this.map.get(e.tree)}},yR=class e{constructor(e,t,n,r,i=!1,a=!1){this.from=e,this.to=t,this.tree=n,this.offset=r,this.open=!!i|(a?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(t,n=[],r=!1){let i=[new e(0,t.length,t,0,!1,r)];for(let e of n)e.to>t.length&&i.push(e);return i}static applyChanges(t,n,r=128){if(!n.length)return t;let i=[],a=1,o=t.length?t[0]:null;for(let s=0,c=0,l=0;;s++){let u=s<n.length?n[s]:null,d=u?u.fromA:1e9;if(d-c>=r)for(;o&&o.from<d;){let n=o;if(c>=n.from||d<=n.to||l){let t=Math.max(n.from,c)-l,r=Math.min(n.to,d)-l;n=t>=r?null:new e(t,r,n.tree,n.offset+l,s>0,!!u)}if(n&&i.push(n),o.to>d)break;o=a<t.length?t[a++]:null}if(!u)break;c=u.toA,l=u.toA-u.toB}return i}},bR=class{startParse(e,t,n){return typeof e==`string`&&(e=new xR(e)),n=n?n.length?n.map(e=>new UL(e.from,e.to)):[new UL(0,0)]:[new UL(0,e.length)],this.createParse(e,t||[],n)}parse(e,t,n){let r=this.startParse(e,t,n);for(;;){let e=r.advance();if(e)return e}}},xR=class{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}};new WL({perNode:!0});var SR=0,CR=class e{constructor(e,t,n,r){this.name=e,this.set=t,this.base=n,this.modified=r,this.id=SR++}toString(){let{name:e}=this;for(let t of this.modified)t.name&&(e=`${t.name}(${e})`);return e}static define(t,n){let r=typeof t==`string`?t:`?`;if(t instanceof e&&(n=t),n?.base)throw Error(`Can not derive from a modified tag`);let i=new e(r,[],null,[]);if(i.set.push(i),n)for(let e of n.set)i.set.push(e);return i}static defineModifier(e){let t=new TR(e);return e=>e.modified.indexOf(t)>-1?e:TR.get(e.base||e,e.modified.concat(t).sort((e,t)=>e.id-t.id))}},wR=0,TR=class e{constructor(e){this.name=e,this.instances=[],this.id=wR++}static get(t,n){if(!n.length)return t;let r=n[0].instances.find(e=>e.base==t&&ER(n,e.modified));if(r)return r;let i=[],a=new CR(t.name,i,t,n);for(let e of n)e.instances.push(a);let o=DR(n);for(let n of t.set)if(!n.modified.length)for(let t of o)i.push(e.get(n,t));return a}};function ER(e,t){return e.length==t.length&&e.every((e,n)=>e==t[n])}function DR(e){let t=[[]];for(let n=0;n<e.length;n++)for(let r=0,i=t.length;r<i;r++)t.push(t[r].concat(e[n]));return t.sort((e,t)=>t.length-e.length)}function OR(e){let t=Object.create(null);for(let n in e){let r=e[n];Array.isArray(r)||(r=[r]);for(let e of n.split(` `))if(e){let n=[],i=2,a=e;for(let t=0;;){if(a==`...`&&t>0&&t+3==e.length){i=1;break}let r=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(a);if(!r)throw RangeError(`Invalid path: `+e);if(n.push(r[0]==`*`?``:r[0][0]==`"`?JSON.parse(r[0]):r[0]),t+=r[0].length,t==e.length)break;let o=e[t++];if(t==e.length&&o==`!`){i=0;break}if(o!=`/`)throw RangeError(`Invalid path: `+e);a=e.slice(t)}let o=n.length-1,s=n[o];if(!s)throw RangeError(`Invalid path: `+e);t[s]=new AR(r,i,o>0?n.slice(0,o):null).sort(t[s])}}return kR.add(t)}var kR=new WL({combine(e,t){let n,r,i;for(;e||t;){if(!e||t&&e.depth>=t.depth?(i=t,t=t.next):(i=e,e=e.next),n&&n.mode==i.mode&&!i.context&&!n.context)continue;let a=new AR(i.tags,i.mode,i.context);n?n.next=a:r=a,n=a}return r}}),AR=class{constructor(e,t,n,r){this.tags=e,this.mode=t,this.context=n,this.next=r}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth<this.depth?(this.next=e,this):(e.next=this.sort(e.next),e)}get depth(){return this.context?this.context.length:0}};AR.empty=new AR([],2,null);function jR(e,t){let n=Object.create(null);for(let t of e)if(!Array.isArray(t.tag))n[t.tag.id]=t.class;else for(let e of t.tag)n[e.id]=t.class;let{scope:r,all:i=null}=t||{};return{style:e=>{let t=i;for(let r of e)for(let e of r.set){let r=n[e.id];if(r){t=t?t+` `+r:r;break}}return t},scope:r}}function MR(e,t){let n=null;for(let r of e){let e=r.style(t);e&&(n=n?n+` `+e:e)}return n}function NR(e,t,n,r=0,i=e.length){let a=new PR(r,Array.isArray(t)?t:[t],n);a.highlightRange(e.cursor(),r,i,``,a.highlighters),a.flush(i)}var PR=class{constructor(e,t,n){this.at=e,this.highlighters=t,this.span=n,this.class=``}startSpan(e,t){t!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=t)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,t,n,r,i){let{type:a,from:o,to:s}=e;if(o>=n||s<=t)return;a.isTop&&(i=this.highlighters.filter(e=>!e.scope||e.scope(a)));let c=r,l=FR(e)||AR.empty,u=MR(i,l.tags);if(u&&(c&&(c+=` `),c+=u,l.mode==1&&(r+=(r?` `:``)+u)),this.startSpan(Math.max(t,o),c),l.opaque)return;let d=e.tree&&e.tree.prop(WL.mounted);if(d&&d.overlay){let a=e.node.enter(d.overlay[0].from+o,1),l=this.highlighters.filter(e=>!e.scope||e.scope(d.tree.type)),u=e.firstChild();for(let f=0,p=o;;f++){let m=f<d.overlay.length?d.overlay[f]:null,h=m?m.from+o:s,g=Math.max(t,p),_=Math.min(n,h);if(g<_&&u)for(;e.from<_&&(this.highlightRange(e,g,_,r,i),this.startSpan(Math.min(_,e.to),c),!(e.to>=h||!e.nextSibling())););if(!m||h>n)break;p=m.to+o,p>t&&(this.highlightRange(a.cursor(),Math.max(t,m.from+o),Math.min(n,p),``,l),this.startSpan(Math.min(n,p),c))}u&&e.parent()}else if(e.firstChild()){d&&(r=``);do if(!(e.to<=t)){if(e.from>=n)break;this.highlightRange(e,t,n,r,i),this.startSpan(Math.min(n,e.to),c)}while(e.nextSibling());e.parent()}}};function FR(e){let t=e.type.prop(kR);for(;t&&t.context&&!e.matchContext(t.context);)t=t.next;return t||null}var IR=CR.define,LR=IR(),RR=IR(),zR=IR(RR),BR=IR(RR),VR=IR(),HR=IR(VR),UR=IR(VR),WR=IR(),GR=IR(WR),KR=IR(),qR=IR(),JR=IR(),YR=IR(JR),XR=IR(),$={comment:LR,lineComment:IR(LR),blockComment:IR(LR),docComment:IR(LR),name:RR,variableName:IR(RR),typeName:zR,tagName:IR(zR),propertyName:BR,attributeName:IR(BR),className:IR(RR),labelName:IR(RR),namespace:IR(RR),macroName:IR(RR),literal:VR,string:HR,docString:IR(HR),character:IR(HR),attributeValue:IR(HR),number:UR,integer:IR(UR),float:IR(UR),bool:IR(VR),regexp:IR(VR),escape:IR(VR),color:IR(VR),url:IR(VR),keyword:KR,self:IR(KR),null:IR(KR),atom:IR(KR),unit:IR(KR),modifier:IR(KR),operatorKeyword:IR(KR),controlKeyword:IR(KR),definitionKeyword:IR(KR),moduleKeyword:IR(KR),operator:qR,derefOperator:IR(qR),arithmeticOperator:IR(qR),logicOperator:IR(qR),bitwiseOperator:IR(qR),compareOperator:IR(qR),updateOperator:IR(qR),definitionOperator:IR(qR),typeOperator:IR(qR),controlOperator:IR(qR),punctuation:JR,separator:IR(JR),bracket:YR,angleBracket:IR(YR),squareBracket:IR(YR),paren:IR(YR),brace:IR(YR),content:WR,heading:GR,heading1:IR(GR),heading2:IR(GR),heading3:IR(GR),heading4:IR(GR),heading5:IR(GR),heading6:IR(GR),contentSeparator:IR(WR),list:IR(WR),quote:IR(WR),emphasis:IR(WR),strong:IR(WR),link:IR(WR),monospace:IR(WR),strikethrough:IR(WR),inserted:IR(),deleted:IR(),changed:IR(),invalid:IR(),meta:XR,documentMeta:IR(XR),annotation:IR(XR),processingInstruction:IR(XR),definition:CR.defineModifier(`definition`),constant:CR.defineModifier(`constant`),function:CR.defineModifier(`function`),standard:CR.defineModifier(`standard`),local:CR.defineModifier(`local`),special:CR.defineModifier(`special`)};for(let e in $){let t=$[e];t instanceof CR&&(t.name=e)}jR([{tag:$.link,class:`tok-link`},{tag:$.heading,class:`tok-heading`},{tag:$.emphasis,class:`tok-emphasis`},{tag:$.strong,class:`tok-strong`},{tag:$.keyword,class:`tok-keyword`},{tag:$.atom,class:`tok-atom`},{tag:$.bool,class:`tok-bool`},{tag:$.url,class:`tok-url`},{tag:$.labelName,class:`tok-labelName`},{tag:$.inserted,class:`tok-inserted`},{tag:$.deleted,class:`tok-deleted`},{tag:$.literal,class:`tok-literal`},{tag:$.string,class:`tok-string`},{tag:$.number,class:`tok-number`},{tag:[$.regexp,$.escape,$.special($.string)],class:`tok-string2`},{tag:$.variableName,class:`tok-variableName`},{tag:$.local($.variableName),class:`tok-variableName tok-local`},{tag:$.definition($.variableName),class:`tok-variableName tok-definition`},{tag:$.special($.variableName),class:`tok-variableName2`},{tag:$.definition($.propertyName),class:`tok-propertyName tok-definition`},{tag:$.typeName,class:`tok-typeName`},{tag:$.namespace,class:`tok-namespace`},{tag:$.className,class:`tok-className`},{tag:$.macroName,class:`tok-macroName`},{tag:$.propertyName,class:`tok-propertyName`},{tag:$.operator,class:`tok-operator`},{tag:$.comment,class:`tok-comment`},{tag:$.meta,class:`tok-meta`},{tag:$.invalid,class:`tok-invalid`},{tag:$.punctuation,class:`tok-punctuation`}]);var ZR=new WL;function QR(e){return rk.define({combine:e?t=>t.concat(e):void 0})}var $R=new WL,ez=class{constructor(e,t,n=[],r=``){this.data=e,this.name=r,Kk.prototype.hasOwnProperty(`tree`)||Object.defineProperty(Kk.prototype,"tree",{get(){return rz(this)}}),this.parser=t,this.extension=[fz.of(this),Kk.languageData.of((e,t,n)=>{let r=tz(e,t,n),i=r.type.prop(ZR);if(!i)return[];let a=e.facet(i),o=r.type.prop($R);if(o){let i=r.resolve(t-r.from,n);for(let t of o)if(t.test(i,e)){let n=e.facet(t.facet);return t.type==`replace`?n:n.concat(a)}}return a})].concat(n)}isActiveAt(e,t,n=-1){return tz(e,t,n).type.prop(ZR)==this.data}findRegions(e){let t=e.facet(fz);if(t?.data==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let n=[],r=(e,t)=>{if(e.prop(ZR)==this.data){n.push({from:t,to:t+e.length});return}let i=e.prop(WL.mounted);if(i){if(i.tree.prop(ZR)==this.data){if(i.overlay)for(let e of i.overlay)n.push({from:e.from+t,to:e.to+t});else n.push({from:t,to:t+e.length});return}if(i.overlay){let e=n.length;if(r(i.tree,i.overlay[0].from+t),n.length>e)return}}for(let n=0;n<e.children.length;n++){let i=e.children[n];i instanceof QL&&r(i,e.positions[n]+t)}};return r(rz(e),0),n}get allowsNesting(){return!0}};ez.setState=jk.define();function tz(e,t,n){let r=e.facet(fz),i=rz(e).topNode;if(!r||r.allowsNesting)for(let e=i;e;e=e.enter(t,n,ZL.ExcludeBuffers|ZL.EnterBracketed))e.type.isTop&&(i=e);return i}var nz=class e extends ez{constructor(e,t,n){super(e,t,[],n),this.parser=t}static define(t){let n=QR(t.languageData);return new e(n,t.parser.configure({props:[ZR.add(e=>e.isTop?n:void 0)]}),t.name)}configure(t,n){return new e(this.data,this.parser.configure(t),n||this.name)}get allowsNesting(){return this.parser.hasWrappers()}};function rz(e){let t=e.field(ez.state,!1);return t?t.tree:QL.empty}var iz=class{constructor(e){this.doc=e,this.cursorPos=0,this.string=``,this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,t){let n=this.cursorPos-this.string.length;return e<n||t>=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-n,t-n)}},az=null,oz=class e{constructor(e,t,n=[],r,i,a,o,s){this.parser=e,this.state=t,this.fragments=n,this.tree=r,this.treeLen=i,this.viewport=a,this.skipped=o,this.scheduleOn=s,this.parse=null,this.tempSkipped=[]}static create(t,n,r){return new e(t,n,[],QL.empty,0,r,[],null)}startParse(){return this.parser.startParse(new iz(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=QL.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{if(typeof e==`number`){let t=Date.now()+e;e=()=>Date.now()>t}for(this.parse||=this.startParse(),t!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&t<this.state.doc.length&&this.parse.stopAt(t);;){let n=this.parse.advance();if(n){if(this.fragments=this.withoutTempSkipped(yR.addTree(n,this.fragments,this.parse.stoppedAt!=null)),this.treeLen=this.parse.stoppedAt??this.state.doc.length,this.tree=n,this.parse=null,this.treeLen<(t??this.state.doc.length))this.parse=this.startParse();else return!0}if(e())return!1}})}takeTree(){let e,t;this.parse&&(e=this.parse.parsedPos)>=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(t=this.parse.advance()););}),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped(yR.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=az;az=this;try{return e()}finally{az=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=sz(e,t.from,t.to);return e}changes(t,n){let{fragments:r,tree:i,treeLen:a,viewport:o,skipped:s}=this;if(this.takeTree(),!t.empty){let e=[];if(t.iterChangedRanges((t,n,r,i)=>e.push({fromA:t,toA:n,fromB:r,toB:i})),r=yR.applyChanges(r,e),i=QL.empty,a=0,o={from:t.mapPos(o.from,-1),to:t.mapPos(o.to,1)},this.skipped.length){s=[];for(let e of this.skipped){let n=t.mapPos(e.from,1),r=t.mapPos(e.to,-1);n<r&&s.push({from:n,to:r})}}}return new e(this.parser,n,r,i,a,o,s,this.scheduleOn)}updateViewport(e){if(this.viewport.from==e.from&&this.viewport.to==e.to)return!1;this.viewport=e;let t=this.skipped.length;for(let t=0;t<this.skipped.length;t++){let{from:n,to:r}=this.skipped[t];n<e.to&&r>e.from&&(this.fragments=sz(this.fragments,n,r),this.skipped.splice(t--,1))}return this.skipped.length>=t?!1:(this.reset(),!0)}reset(){this.parse&&=(this.takeTree(),null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends bR{createParse(t,n,r){let i=r[0].from,a=r[r.length-1].to;return{parsedPos:i,advance(){let t=az;if(t){for(let e of r)t.tempSkipped.push(e);e&&(t.scheduleOn=t.scheduleOn?Promise.all([t.scheduleOn,e]):e)}return this.parsedPos=a,new QL(qL.none,[],[],a-i)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&t[0].from==0&&t[0].to>=e}static get(){return az}};function sz(e,t,n){return yR.applyChanges(e,[{fromA:t,toA:n,fromB:t,toB:n}])}var cz=class e{constructor(e){this.context=e,this.tree=e.tree}apply(t){if(!t.docChanged&&this.tree==this.context.tree)return this;let n=this.context.changes(t.changes,t.state),r=this.context.treeLen==t.startState.doc.length?void 0:Math.max(t.changes.mapPos(this.context.treeLen),n.viewport.to);return n.work(20,r)||n.takeTree(),new e(n)}static init(t){let n=Math.min(3e3,t.doc.length),r=oz.create(t.facet(fz).parser,t,{from:0,to:n});return r.work(20,n)||r.takeTree(),new e(r)}};ez.state=uk.define({create:cz.init,update(e,t){for(let e of t.effects)if(e.is(ez.setState))return e.value;return t.startState.facet(fz)==t.state.facet(fz)?e.apply(t):cz.init(t.state)}});var lz=e=>{let t=setTimeout(()=>e(),500);return()=>clearTimeout(t)};typeof requestIdleCallback<`u`&&(lz=e=>{let t=-1,n=setTimeout(()=>{t=requestIdleCallback(e,{timeout:400})},100);return()=>t<0?clearTimeout(n):cancelIdleCallback(t)});var uz=typeof navigator<`u`&&navigator.scheduling?.isInputPending?()=>navigator.scheduling.isInputPending():null,dz=pM.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(ez.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(ez.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=lz(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEnd<t&&(this.chunkEnd<0||this.view.hasFocus)&&(this.chunkEnd=t+3e4,this.chunkBudget=3e3),this.chunkBudget<=0)return;let{state:n,viewport:{to:r}}=this.view,i=n.field(ez.state);if(i.tree==i.context.tree&&i.context.isDone(r+1e5))return;let a=Date.now()+Math.min(this.chunkBudget,100,e&&!uz?Math.max(25,e.timeRemaining()-5):1e9),o=i.context.treeLen<r&&n.doc.length>r+1e3,s=i.context.work(()=>uz&&uz()||Date.now()>a,r+(o?0:1e5));this.chunkBudget-=Date.now()-t,(s||this.chunkBudget<=0)&&(i.context.takeTree(),this.view.dispatch({effects:ez.setState.of(new cz(i.context))})),this.chunkBudget>0&&!(s&&!o)&&this.scheduleWork(),this.checkAsyncSchedule(i.context)}checkAsyncSchedule(e){e.scheduleOn&&=(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(e=>lM(this.view.state,e)).then(()=>this.workScheduled--),null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),fz=rk.define({combine(e){return e.length?e[0]:null},enables:e=>[ez.state,dz,SF.contentAttributes.compute([e],t=>{let n=t.facet(e);return n&&n.name?{"data-language":n.name}:{}})]}),pz=class{constructor(e,t=[]){this.language=e,this.support=t,this.extension=[e,t]}},mz=rk.define(),hz=rk.define({combine:e=>{if(!e.length)return` `;let t=e[0];if(!t||/\S/.test(t)||Array.from(t).some(e=>e!=t[0]))throw Error(`Invalid indent unit: `+JSON.stringify(e[0]));return t}});function gz(e){let t=e.facet(hz);return t.charCodeAt(0)==9?e.tabSize*t.length:t.length}function _z(e,t){let n=``,r=e.tabSize,i=e.facet(hz)[0];if(i==` `){for(;t>=r;)n+=` `,t-=r;i=` `}for(let e=0;e<t;e++)n+=i;return n}function vz(e,t){e instanceof Kk&&(e=new yz(e));for(let n of e.state.facet(mz)){let r=n(e,t);if(r!==void 0)return r}let n=rz(e.state);return n.length>=t?xz(e,n,t):null}var yz=class{constructor(e,t={}){this.state=e,this.options=t,this.unit=gz(e)}lineAt(e,t=1){let n=this.state.doc.lineAt(e),{simulateBreak:r,simulateDoubleBreak:i}=this.options;return r!=null&&r>=n.from&&r<=n.to?i&&r==e?{text:``,from:e}:(t<0?r<e:r<=e)?{text:n.text.slice(r-n.from),from:r}:{text:n.text.slice(0,r-n.from),from:n.from}:n}textAfterPos(e,t=1){if(this.options.simulateDoubleBreak&&e==this.options.simulateBreak)return``;let{text:n,from:r}=this.lineAt(e,t);return n.slice(e-r,Math.min(n.length,e+100-r))}column(e,t=1){let{text:n,from:r}=this.lineAt(e,t),i=this.countColumn(n,e-r),a=this.options.overrideIndentation?this.options.overrideIndentation(r):-1;return a>-1&&(i+=a-this.countColumn(n,n.search(/\S|$/))),i}countColumn(e,t=e.length){return fA(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:n,from:r}=this.lineAt(e,t),i=this.options.overrideIndentation;if(i){let e=i(r);if(e>-1)return e}return this.countColumn(n,n.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}},bz=new WL;function xz(e,t,n){let r=t.resolveStack(n),i=t.resolveInner(n,-1).resolve(n,0).enterUnfinishedNodesBefore(n);if(i!=r.node){let e=[];for(let t=i;t&&!(t.from<r.node.from||t.to>r.node.to||t.from==r.node.from&&t.type==r.node.type);t=t.parent)e.push(t);for(let t=e.length-1;t>=0;t--)r={node:e[t],next:r}}return Sz(r,e,n)}function Sz(e,t,n){for(let r=e;r;r=r.next){let e=wz(r.node);if(e)return e(Ez.create(t,n,r))}return 0}function Cz(e){return e.pos==e.options.simulateBreak&&e.options.simulateDoubleBreak}function wz(e){let t=e.type.prop(bz);if(t)return t;let n=e.firstChild,r;if(n&&(r=n.type.prop(WL.closedBy))){let t=e.lastChild,n=t&&r.indexOf(t.name)>-1;return e=>Az(e,!0,1,void 0,n&&!Cz(e)?t.from:void 0)}return e.parent==null?Tz:null}function Tz(){return 0}var Ez=class e extends yz{constructor(e,t,n){super(e.state,e.options),this.base=e,this.pos=t,this.context=n}get node(){return this.context.node}static create(t,n,r){return new e(t,n,r)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(e){let t=this.state.doc.lineAt(e.from);for(;;){let n=e.resolve(t.from);for(;n.parent&&n.parent.from==n.from;)n=n.parent;if(Dz(n,e))break;t=this.state.doc.lineAt(n.from)}return this.lineIndent(t.from)}continue(){return Sz(this.context.next,this.base,this.pos)}};function Dz(e,t){for(let n=t;n;n=n.parent)if(e==n)return!0;return!1}function Oz(e){let t=e.node,n=t.childAfter(t.from),r=t.lastChild;if(!n)return null;let i=e.options.simulateBreak,a=e.state.doc.lineAt(n.from),o=i==null||i<=a.from?a.to:Math.min(a.to,i);for(let e=n.to;;){let i=t.childAfter(e);if(!i||i==r)return null;if(!i.type.isSkipped){if(i.from>=o)return null;let e=/^ */.exec(a.text.slice(n.to-a.from))[0].length;return{from:n.from,to:n.to+e}}e=i.to}}function kz({closing:e,align:t=!0,units:n=1}){return r=>Az(r,t,n,e)}function Az(e,t,n,r,i){let a=e.textAfter,o=a.match(/^\s*/)[0].length,s=r&&a.slice(o,o+r.length)==r||i==e.pos+o,c=t?Oz(e):null;return c?s?e.column(c.from):e.column(c.to):e.baseIndent+(s?0:e.unit*n)}var jz=e=>e.baseIndent;function Mz({except:e,units:t=1}={}){return n=>{let r=e&&e.test(n.textAfter);return n.baseIndent+(r?0:t*n.unit)}}var Nz=200;function Pz(){return Kk.transactionFilter.of(e=>{if(!e.docChanged||!e.isUserEvent(`input.type`)&&!e.isUserEvent(`input.complete`))return e;let t=e.startState.languageDataAt(`indentOnInput`,e.startState.selection.main.head);if(!t.length)return e;let n=e.newDoc,{head:r}=e.newSelection.main,i=n.lineAt(r);if(r>i.from+Nz)return e;let a=n.sliceString(i.from,r);if(!t.some(e=>e.test(a)))return e;let{state:o}=e,s=-1,c=[];for(let{head:e}of o.selection.ranges){let t=o.doc.lineAt(e);if(t.from==s)continue;s=t.from;let n=vz(o,t.from);if(n==null)continue;let r=/^\s*/.exec(t.text)[0],i=_z(o,n);r!=i&&c.push({from:t.from,to:t.from+r.length,insert:i})}return c.length?[e,{changes:c,sequential:!0}]:e})}var Fz=rk.define(),Iz=new WL;function Lz(e){let t=e.firstChild,n=e.lastChild;return t&&t.to<n.from?{from:t.to,to:n.type.isError?e.to:n.from}:null}function Rz(e,t,n){let r=rz(e);if(r.length<n)return null;let i=r.resolveStack(n,1),a=null;for(let o=i;o;o=o.next){let i=o.node;if(i.to<=n||i.from>n)continue;if(a&&i.from<t)break;let s=i.type.prop(Iz);if(s&&(i.to<r.length-50||r.length==e.doc.length||!zz(i))){let r=s(i,e);r&&r.from<=n&&r.from>=t&&r.to>n&&(a=r)}}return a}function zz(e){let t=e.lastChild;return t&&t.to==e.to&&t.type.isError}function Bz(e,t,n){for(let r of e.facet(Fz)){let i=r(e,t,n);if(i)return i}return Rz(e,t,n)}function Vz(e,t){let n=t.mapPos(e.from,1),r=t.mapPos(e.to,-1);return n>=r?void 0:{from:n,to:r}}var Hz=jk.define({map:Vz}),Uz=jk.define({map:Vz});function Wz(e){let t=[];for(let{head:n}of e.state.selection.ranges)t.some(e=>e.from<=n&&e.to>=n)||t.push(e.lineBlockAt(n));return t}var Gz=uk.define({create(){return UA.none},update(e,t){t.isUserEvent(`delete`)&&t.changes.iterChangedRanges((t,n)=>e=Kz(e,t,n)),e=e.map(t.changes);let n=[];for(let r of t.effects)r.is(Hz)&&!Jz(e,r.value.from,r.value.to)?n.push(r.value):r.is(Uz)&&(e=e.update({filter:(e,t)=>r.value.from!=e||r.value.to!=t,filterFrom:r.value.from,filterTo:r.value.to}));if(n.length){let{preparePlaceholder:r}=t.state.facet(tB),i=n.map(e=>(r?UA.replace({widget:new aB(r(t.state,e))}):iB).range(e.from,e.to));e=e.update({add:i})}return t.selection&&(e=Kz(e,t.selection.main.head)),e},provide:e=>SF.decorations.from(e),toJSON(e,t){let n=[];return e.between(0,t.doc.length,(e,t)=>{n.push(e,t)}),n},fromJSON(e){if(!Array.isArray(e)||e.length%2)throw RangeError(`Invalid JSON for fold state`);let t=[];for(let n=0;n<e.length;){let r=e[n++],i=e[n++];if(typeof r!=`number`||typeof i!=`number`)throw RangeError(`Invalid JSON for fold state`);t.push(iB.range(r,i))}return UA.set(t,!0)}});function Kz(e,t,n=t){let r=!1;return e.between(t,n,(e,i)=>{e<n&&i>t&&(r=!0)}),r?e.update({filterFrom:t,filterTo:n,filter:(e,r)=>e>=n||r<=t}):e}function qz(e,t,n){var r;let i=null;return(r=e.field(Gz,!1))==null||r.between(t,n,(e,t)=>{(!i||i.from>e)&&(i={from:e,to:t})}),i}function Jz(e,t,n){let r=!1;return e.between(t,t,(e,i)=>{e==t&&i==n&&(r=!0)}),r}function Yz(e,t){return e.field(Gz,!1)?t:t.concat(jk.appendConfig.of(nB()))}var Xz=e=>{for(let t of Wz(e)){let n=Bz(e.state,t.from,t.to);if(n)return e.dispatch({effects:Yz(e.state,[Hz.of(n),Qz(e,n)])}),!0}return!1},Zz=e=>{if(!e.state.field(Gz,!1))return!1;let t=[];for(let n of Wz(e)){let r=qz(e.state,n.from,n.to);r&&t.push(Uz.of(r),Qz(e,r,!1))}return t.length&&e.dispatch({effects:t}),t.length>0};function Qz(e,t,n=!0){let r=e.state.doc.lineAt(t.from).number,i=e.state.doc.lineAt(t.to).number;return SF.announce.of(`${e.state.phrase(n?`Folded lines`:`Unfolded lines`)} ${r} ${e.state.phrase(`to`)} ${i}.`)}var $z=[{key:`Ctrl-Shift-[`,mac:`Cmd-Alt-[`,run:Xz},{key:`Ctrl-Shift-]`,mac:`Cmd-Alt-]`,run:Zz},{key:`Ctrl-Alt-[`,run:e=>{let{state:t}=e,n=[];for(let r=0;r<t.doc.length;){let i=e.lineBlockAt(r),a=Bz(t,i.from,i.to);a&&n.push(Hz.of(a)),r=(a?e.lineBlockAt(a.to):i).to+1}return n.length&&e.dispatch({effects:Yz(e.state,n)}),!!n.length}},{key:`Ctrl-Alt-]`,run:e=>{let t=e.state.field(Gz,!1);if(!t||!t.size)return!1;let n=[];return t.between(0,e.state.doc.length,(e,t)=>{n.push(Uz.of({from:e,to:t}))}),e.dispatch({effects:n}),!0}}],eB={placeholderDOM:null,preparePlaceholder:null,placeholderText:`…`},tB=rk.define({combine(e){return qk(e,eB)}});function nB(e){let t=[Gz,lB];return e&&t.push(tB.of(e)),t}function rB(e,t){let{state:n}=e,r=n.facet(tB),i=t=>{let n=e.lineBlockAt(e.posAtDOM(t.target)),r=qz(e.state,n.from,n.to);r&&e.dispatch({effects:Uz.of(r)}),t.preventDefault()};if(r.placeholderDOM)return r.placeholderDOM(e,i,t);let a=document.createElement(`span`);return a.textContent=r.placeholderText,a.setAttribute(`aria-label`,n.phrase(`folded code`)),a.title=n.phrase(`unfold`),a.className=`cm-foldPlaceholder`,a.onclick=i,a}var iB=UA.replace({widget:new class extends VA{toDOM(e){return rB(e,null)}}}),aB=class extends VA{constructor(e){super(),this.value=e}eq(e){return this.value==e.value}toDOM(e){return rB(e,this.value)}},oB={openText:`⌄`,closedText:`›`,markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1},sB=class extends hL{constructor(e,t){super(),this.config=e,this.open=t}eq(e){return this.config==e.config&&this.open==e.open}toDOM(e){if(this.config.markerDOM)return this.config.markerDOM(this.open);let t=document.createElement(`span`);return t.textContent=this.open?this.config.openText:this.config.closedText,t.title=e.state.phrase(this.open?`Fold line`:`Unfold line`),t}};function cB(e={}){let t={...oB,...e},n=new sB(t,!0),r=new sB(t,!1),i=pM.fromClass(class{constructor(e){this.from=e.viewport.from,this.markers=this.buildMarkers(e)}update(e){(e.docChanged||e.viewportChanged||e.startState.facet(fz)!=e.state.facet(fz)||e.startState.field(Gz,!1)!=e.state.field(Gz,!1)||rz(e.startState)!=rz(e.state)||t.foldingChanged(e))&&(this.markers=this.buildMarkers(e.view))}buildMarkers(e){let t=new tA;for(let i of e.viewportLineBlocks){let a=qz(e.state,i.from,i.to)?r:Bz(e.state,i.from,i.to)?n:null;a&&t.add(i.from,i.from,a)}return t.finish()}}),{domEventHandlers:a}=t;return[i,bL({class:`cm-foldGutter`,markers(e){return e.plugin(i)?.markers||$k.empty},initialSpacer(){return new sB(t,!1)},domEventHandlers:{...a,click:(e,t,n)=>{if(a.click&&a.click(e,t,n))return!0;let r=qz(e.state,t.from,t.to);if(r)return e.dispatch({effects:Uz.of(r)}),!0;let i=Bz(e.state,t.from,t.to);return i?(e.dispatch({effects:Hz.of(i)}),!0):!1}}}),nB()]}var lB=SF.baseTheme({".cm-foldPlaceholder":{backgroundColor:`#eee`,border:`1px solid #ddd`,color:`#888`,borderRadius:`.2em`,margin:`0 1px`,padding:`0 1px`,cursor:`pointer`},".cm-foldGutter span":{padding:`0 1px`,cursor:`pointer`}}),uB=class e{constructor(e,t){this.specs=e;let n;function r(e){let t=vA.newName();return(n||=Object.create(null))[`.`+t]=e,t}let i=typeof t.all==`string`?t.all:t.all?r(t.all):void 0,a=t.scope;this.scope=a instanceof ez?e=>e.prop(ZR)==a.data:a?e=>e==a:void 0,this.style=jR(e.map(e=>({tag:e.tag,class:e.class||r(Object.assign({},e,{tag:null}))})),{all:i}).style,this.module=n?new vA(n):null,this.themeType=t.themeType}static define(t,n){return new e(t,n||{})}},dB=rk.define(),fB=rk.define({combine(e){return e.length?[e[0]]:null}});function pB(e){let t=e.facet(dB);return t.length?t:e.facet(fB)}function mB(e,t){let n=[gB],r;return e instanceof uB&&(e.module&&n.push(SF.styleModule.of(e.module)),r=e.themeType),t?.fallback?n.push(fB.of(e)):r?n.push(dB.computeN([SF.darkTheme],t=>t.facet(SF.darkTheme)==(r==`dark`)?[e]:[])):n.push(dB.of(e)),n}var hB=class{constructor(e){this.markCache=Object.create(null),this.tree=rz(e.state),this.decorations=this.buildDeco(e,pB(e.state)),this.decoratedTo=e.viewport.to}update(e){let t=rz(e.state),n=pB(e.state),r=n!=pB(e.startState),{viewport:i}=e.view,a=e.changes.mapPos(this.decoratedTo,1);t.length<i.to&&!r&&t.type==this.tree.type&&a>=i.to?(this.decorations=this.decorations.map(e.changes),this.decoratedTo=a):(t!=this.tree||e.viewportChanged||r)&&(this.tree=t,this.decorations=this.buildDeco(e.view,n),this.decoratedTo=i.to)}buildDeco(e,t){if(!t||!this.tree.length)return UA.none;let n=new tA;for(let{from:r,to:i}of e.visibleRanges)NR(this.tree,t,(e,t,r)=>{n.add(e,t,this.markCache[r]||(this.markCache[r]=UA.mark({class:r})))},r,i);return n.finish()}},gB=pk.high(pM.fromClass(hB,{decorations:e=>e.decorations})),_B=uB.define([{tag:$.meta,color:`#404740`},{tag:$.link,textDecoration:`underline`},{tag:$.heading,textDecoration:`underline`,fontWeight:`bold`},{tag:$.emphasis,fontStyle:`italic`},{tag:$.strong,fontWeight:`bold`},{tag:$.strikethrough,textDecoration:`line-through`},{tag:$.keyword,color:`#708`},{tag:[$.atom,$.bool,$.url,$.contentSeparator,$.labelName],color:`#219`},{tag:[$.literal,$.inserted],color:`#164`},{tag:[$.string,$.deleted],color:`#a11`},{tag:[$.regexp,$.escape,$.special($.string)],color:`#e40`},{tag:$.definition($.variableName),color:`#00f`},{tag:$.local($.variableName),color:`#30a`},{tag:[$.typeName,$.namespace],color:`#085`},{tag:$.className,color:`#167`},{tag:[$.special($.variableName),$.macroName],color:`#256`},{tag:$.definition($.propertyName),color:`#00c`},{tag:$.comment,color:`#940`},{tag:$.invalid,color:`#f00`}]),vB=SF.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:`#328c8252`},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:`#bb555544`}}),yB=1e4,bB=`()[]{}`,xB=rk.define({combine(e){return qk(e,{afterCursor:!0,brackets:bB,maxScanDistance:yB,renderMatch:wB})}}),SB=UA.mark({class:`cm-matchingBracket`}),CB=UA.mark({class:`cm-nonmatchingBracket`});function wB(e){let t=[],n=e.matched?SB:CB;return t.push(n.range(e.start.from,e.start.to)),e.end&&t.push(n.range(e.end.from,e.end.to)),t}function TB(e){let t=[],n=e.facet(xB);for(let r of e.selection.ranges){if(!r.empty)continue;let i=jB(e,r.head,-1,n)||r.head>0&&jB(e,r.head-1,1,n)||n.afterCursor&&(jB(e,r.head,1,n)||r.head<e.doc.length&&jB(e,r.head+1,-1,n));i&&(t=t.concat(n.renderMatch(i,e)))}return UA.set(t,!0)}var EB=[pM.fromClass(class{constructor(e){this.paused=!1,this.decorations=TB(e.state)}update(e){(e.docChanged||e.selectionSet||this.paused)&&(e.view.composing?(this.decorations=this.decorations.map(e.changes),this.paused=!0):(this.decorations=TB(e.state),this.paused=!1))}},{decorations:e=>e.decorations}),vB];function DB(e={}){return[xB.of(e),EB]}var OB=new WL;function kB(e,t,n){let r=e.prop(t<0?WL.openedBy:WL.closedBy);if(r)return r;if(e.name.length==1){let r=n.indexOf(e.name);if(r>-1&&r%2==+(t<0))return[n[r+t]]}return null}function AB(e){let t=e.type.prop(OB);return t?t(e.node):e}function jB(e,t,n,r={}){let i=r.maxScanDistance||yB,a=r.brackets||bB,o=rz(e),s=o.resolveInner(t,n);for(let r=s;r;r=r.parent){let i=kB(r.type,n,a);if(i&&r.from<r.to){let o=AB(r);if(o&&(n>0?t>=o.from&&t<o.to:t>o.from&&t<=o.to))return MB(e,t,n,r,o,i,a)}}return NB(e,t,n,o,s.type,i,a)}function MB(e,t,n,r,i,a,o){let s=r.parent,c={from:i.from,to:i.to},l=0,u=s?.cursor();if(u&&(n<0?u.childBefore(r.from):u.childAfter(r.to)))do if(n<0?u.to<=r.from:u.from>=r.to){if(l==0&&a.indexOf(u.type.name)>-1&&u.from<u.to){let e=AB(u);return{start:c,end:e?{from:e.from,to:e.to}:void 0,matched:!0}}if(kB(u.type,n,o))l++;else if(kB(u.type,-n,o)){if(l==0){let e=AB(u);return{start:c,end:e&&e.from<e.to?{from:e.from,to:e.to}:void 0,matched:!1}}l--}}while(n<0?u.prevSibling():u.nextSibling());return{start:c,matched:!1}}function NB(e,t,n,r,i,a,o){if(n<0?!t:t==e.doc.length)return null;let s=n<0?e.sliceDoc(t-1,t):e.sliceDoc(t,t+1),c=o.indexOf(s);if(c<0||c%2==0!=n>0)return null;let l={from:n<0?t-1:t,to:n>0?t+1:t},u=e.doc.iterRange(t,n>0?e.doc.length:0),d=0;for(let e=0;!u.next().done&&e<=a;){let a=u.value;n<0&&(e+=a.length);let s=t+e*n;for(let e=n>0?0:a.length-1,t=n>0?a.length:-1;e!=t;e+=n){let t=o.indexOf(a[e]);if(!(t<0||r.resolveInner(s+e,1).type!=i)){if(t%2==0==n>0)d++;else if(d==1)return{start:l,end:{from:s+e,to:s+e+1},matched:t>>1==c>>1};else d--}}n>0&&(e+=a.length)}return u.done?{start:l,matched:!1}:null}function PB(e,t,n,r=0,i=0){t??(t=e.search(/[^\s\u00a0]/),t==-1&&(t=e.length));let a=i;for(let i=r;i<t;i++)e.charCodeAt(i)==9?a+=n-a%n:a++;return a}var FB=class{constructor(e,t,n,r){this.string=e,this.tabSize=t,this.indentUnit=n,this.overrideIndent=r,this.pos=0,this.start=0,this.lastColumnPos=0,this.lastColumnValue=0}eol(){return this.pos>=this.string.length}sol(){return this.pos==0}peek(){return this.string.charAt(this.pos)||void 0}next(){if(this.pos<this.string.length)return this.string.charAt(this.pos++)}eat(e){let t=this.string.charAt(this.pos),n;if(n=typeof e==`string`?t==e:t&&(e instanceof RegExp?e.test(t):e(t)),n)return++this.pos,t}eatWhile(e){let t=this.pos;for(;this.eat(e););return this.pos>t}eatSpace(){let e=this.pos;for(;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e}skipToEnd(){this.pos=this.string.length}skipTo(e){let t=this.string.indexOf(e,this.pos);if(t>-1)return this.pos=t,!0}backUp(e){this.pos-=e}column(){return this.lastColumnPos<this.start&&(this.lastColumnValue=PB(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue),this.lastColumnPos=this.start),this.lastColumnValue}indentation(){return this.overrideIndent??PB(this.string,null,this.tabSize)}match(e,t,n){if(typeof e==`string`){let r=e=>n?e.toLowerCase():e;return r(this.string.substr(this.pos,e.length))==r(e)?(t!==!1&&(this.pos+=e.length),!0):null}{let n=this.string.slice(this.pos).match(e);return n&&n.index>0?null:(n&&t!==!1&&(this.pos+=n[0].length),n)}}current(){return this.string.slice(this.start,this.pos)}};function IB(e){return{name:e.name||``,token:e.token,blankLine:e.blankLine||(()=>{}),startState:e.startState||(()=>!0),copyState:e.copyState||LB,indent:e.indent||(()=>null),languageData:e.languageData||{},tokenTable:e.tokenTable||GB,mergeTokens:e.mergeTokens!==!1}}function LB(e){if(typeof e!=`object`)return e;let t={};for(let n in e){let r=e[n];t[n]=r instanceof Array?r.slice():r}return t}var RB=new WeakMap,zB=class e extends ez{constructor(e){let t=QR(e.languageData),n=IB(e),r,i=new class extends bR{createParse(e,t,n){return new UB(r,e,t,n)}};super(t,i,[],e.name),this.topNode=tV(t,this),r=this,this.streamParser=n,this.stateAfter=new WL({perNode:!0}),this.tokenTable=e.tokenTable?new ZB(n.tokenTable):QB}static define(t){return new e(t)}getIndent(e){let t,{overrideIndentation:n}=e.options;n&&(t=RB.get(e.state),t!=null&&t<e.pos-1e4&&(t=void 0));let r=BB(this,e.node.tree,e.node.from,e.node.from,t??e.pos),i,a;if(r?(a=r.state,i=r.pos+1):(a=this.streamParser.startState(e.unit),i=e.node.from),e.pos-i>1e4)return null;for(;i<e.pos;){let t=e.state.doc.lineAt(i),r=Math.min(e.pos,t.to);if(t.length){let i=n?n(t.from):-1,o=new FB(t.text,e.state.tabSize,e.unit,i<0?void 0:i);for(;o.pos<r-t.from;)WB(this.streamParser.token,o,a)}else this.streamParser.blankLine(a,e.unit);if(r==e.pos)break;i=t.to+1}let o=e.lineAt(e.pos);return n&&t==null&&RB.set(e.state,o.from),this.streamParser.indent(a,/^\s*(.*)/.exec(o.text)[1],e)}get allowsNesting(){return!1}};function BB(e,t,n,r,i){let a=n>=r&&n+t.length<=i&&t.prop(e.stateAfter);if(a)return{state:e.streamParser.copyState(a),pos:n+t.length};for(let a=t.children.length-1;a>=0;a--){let o=t.children[a],s=n+t.positions[a],c=o instanceof QL&&s<i&&BB(e,o,s,r,i);if(c)return c}return null}function VB(e,t,n,r,i){if(i&&n<=0&&r>=t.length)return t;!i&&n==0&&t.type==e.topNode&&(i=!0);for(let a=t.children.length-1;a>=0;a--){let o=t.positions[a],s=t.children[a],c;if(o<r&&s instanceof QL){if(!(c=VB(e,s,n-o,r-o,i)))break;return i?new QL(t.type,t.children.slice(0,a).concat(c),t.positions.slice(0,a+1),o+c.length):c}}return null}function HB(e,t,n,r,i){for(let i of t){let t=i.from+(i.openStart?25:0),a=i.to-(i.openEnd?25:0),o=t<=n&&a>n&&BB(e,i.tree,0-i.offset,n,a),s;if(o&&o.pos<=r&&(s=VB(e,i.tree,n+i.offset,o.pos+i.offset,!1)))return{state:o.state,tree:s}}return{state:e.streamParser.startState(i?gz(i):4),tree:QL.empty}}var UB=class{constructor(e,t,n,r){this.lang=e,this.input=t,this.fragments=n,this.ranges=r,this.stoppedAt=null,this.chunks=[],this.chunkPos=[],this.chunk=[],this.chunkReused=void 0,this.rangeIndex=0,this.to=r[r.length-1].to;let i=oz.get(),a=r[0].from,{state:o,tree:s}=HB(e,n,a,this.to,i?.state);this.state=o,this.parsedPos=this.chunkStart=a+s.length;for(let e=0;e<s.children.length;e++)this.chunks.push(s.children[e]),this.chunkPos.push(s.positions[e]);i&&this.parsedPos<i.viewport.from-1e5&&r.some(e=>e.from<=i.viewport.from&&e.to>=i.viewport.from)&&(this.state=this.lang.streamParser.startState(gz(i.state)),i.skipUntilInView(this.parsedPos,i.viewport.from),this.parsedPos=i.viewport.from),this.moveRangeIndex()}advance(){let e=oz.get(),t=this.stoppedAt==null?this.to:Math.min(this.to,this.stoppedAt),n=Math.min(t,this.chunkStart+512);for(e&&(n=Math.min(n,e.viewport.to));this.parsedPos<n;)this.parseLine(e);return this.chunkStart<this.parsedPos&&this.finishChunk(),this.parsedPos>=t?this.finish():e&&this.parsedPos>=e.viewport.to?(e.skipUntilInView(this.parsedPos,t),this.finish()):null}stopAt(e){this.stoppedAt=e}lineAfter(e){let t=this.input.chunk(e);if(this.input.lineChunks)t==`
|
|
37
|
+
`&&(t=``);else{let e=t.indexOf(`
|
|
38
|
+
`);e>-1&&(t=t.slice(0,e))}return e+t.length<=this.to?t:t.slice(0,this.to-e)}nextLine(){let e=this.parsedPos,t=this.lineAfter(e),n=e+t.length;for(let e=this.rangeIndex;;){let r=this.ranges[e].to;if(r>=n||(t=t.slice(0,r-(n-t.length)),e++,e==this.ranges.length))break;let i=this.ranges[e].from,a=this.lineAfter(i);t+=a,n=i+a.length}return{line:t,end:n}}skipGapsTo(e,t,n){for(;;){let r=this.ranges[this.rangeIndex].to,i=e+t;if(n>0?r>i:r>=i)break;let a=this.ranges[++this.rangeIndex].from;t+=a-r}return t}moveRangeIndex(){for(;this.ranges[this.rangeIndex].to<this.parsedPos;)this.rangeIndex++}emitToken(e,t,n,r){let i=4;if(this.ranges.length>1){r=this.skipGapsTo(t,r,1),t+=r;let e=this.chunk.length;r=this.skipGapsTo(n,r,-1),n+=r,i+=this.chunk.length-e}let a=this.chunk.length-4;return this.lang.streamParser.mergeTokens&&i==4&&a>=0&&this.chunk[a]==e&&this.chunk[a+2]==t?this.chunk[a+2]=n:this.chunk.push(e,t,n,i),r}parseLine(e){let{line:t,end:n}=this.nextLine(),r=0,{streamParser:i}=this.lang,a=new FB(t,e?e.state.tabSize:4,e?gz(e.state):2);if(a.eol())i.blankLine(this.state,a.indentUnit);else for(;!a.eol();){let e=WB(i.token,a,this.state);if(e&&(r=this.emitToken(this.lang.tokenTable.resolve(e),this.parsedPos+a.start,this.parsedPos+a.pos,r)),a.start>1e4)break}this.parsedPos=n,this.moveRangeIndex(),this.parsedPos<this.to&&this.parsedPos++}finishChunk(){let e=QL.build({buffer:this.chunk,start:this.chunkStart,length:this.parsedPos-this.chunkStart,nodeSet:qB,topID:0,maxBufferLength:512,reused:this.chunkReused});e=new QL(e.type,e.children,e.positions,e.length,[[this.lang.stateAfter,this.lang.streamParser.copyState(this.state)]]),this.chunks.push(e),this.chunkPos.push(this.chunkStart-this.ranges[0].from),this.chunk=[],this.chunkReused=void 0,this.chunkStart=this.parsedPos}finish(){return new QL(this.lang.topNode,this.chunks,this.chunkPos,this.parsedPos-this.ranges[0].from).balance()}};function WB(e,t,n){t.start=t.pos;for(let r=0;r<10;r++){let r=e(t,n);if(t.pos>t.start)return r}throw Error(`Stream parser failed to advance stream.`)}var GB=Object.create(null),KB=[qL.none],qB=new JL(KB),JB=[],YB=Object.create(null),XB=Object.create(null);for(let[e,t]of[[`variable`,`variableName`],[`variable-2`,`variableName.special`],[`string-2`,`string.special`],[`def`,`variableName.definition`],[`tag`,`tagName`],[`attribute`,`attributeName`],[`type`,`typeName`],[`builtin`,`variableName.standard`],[`qualifier`,`modifier`],[`error`,`invalid`],[`header`,`heading`],[`property`,`propertyName`]])XB[e]=eV(GB,t);var ZB=class{constructor(e){this.extra=e,this.table=Object.assign(Object.create(null),XB)}resolve(e){return e?this.table[e]||(this.table[e]=eV(this.extra,e)):0}},QB=new ZB(GB);function $B(e,t){JB.indexOf(e)>-1||(JB.push(e),console.warn(t))}function eV(e,t){let n=[];for(let r of t.split(` `)){let t=[];for(let n of r.split(`.`)){let r=e[n]||$[n];r?typeof r==`function`?t.length?t=t.map(r):$B(n,`Modifier ${n} used at start of tag`):t.length?$B(n,`Tag ${n} used as modifier`):t=Array.isArray(r)?r:[r]:$B(n,`Unknown highlighting tag ${n}`)}for(let e of t)n.push(e)}if(!n.length)return 0;let r=t.replace(/ /g,`_`),i=r+` `+n.map(e=>e.id),a=YB[i];if(a)return a.id;let o=YB[i]=qL.define({id:KB.length,name:r,props:[OR({[r]:n})]});return KB.push(o),o.id}function tV(e,t){let n=qL.define({id:KB.length,name:`Document`,props:[ZR.add(()=>e),bz.add(()=>e=>t.getIndent(e))],top:!0});return KB.push(n),n}Tj.RTL,Tj.LTR;var nV=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=sV(e.state,n.from);return r.line?iV(e):r.block?oV(e):!1};function rV(e,t){return({state:n,dispatch:r})=>{if(n.readOnly)return!1;let i=e(t,n);return i?(r(n.update(i)),!0):!1}}var iV=rV(fV,0),aV=rV(dV,0),oV=rV((e,t)=>dV(e,t,uV(t)),0);function sV(e,t){let n=e.languageDataAt(`commentTokens`,t,1);return n.length?n[0]:{}}var cV=50;function lV(e,{open:t,close:n},r,i){let a=e.sliceDoc(r-cV,r),o=e.sliceDoc(i,i+cV),s=/\s*$/.exec(a)[0].length,c=/^\s*/.exec(o)[0].length,l=a.length-s;if(a.slice(l-t.length,l)==t&&o.slice(c,c+n.length)==n)return{open:{pos:r-s,margin:s&&1},close:{pos:i+c,margin:c&&1}};let u,d;i-r<=100?u=d=e.sliceDoc(r,i):(u=e.sliceDoc(r,r+cV),d=e.sliceDoc(i-cV,i));let f=/^\s*/.exec(u)[0].length,p=/\s*$/.exec(d)[0].length,m=d.length-p-n.length;return u.slice(f,f+t.length)==t&&d.slice(m,m+n.length)==n?{open:{pos:r+f+t.length,margin:+!!/\s/.test(u.charAt(f+t.length))},close:{pos:i-p-n.length,margin:+!!/\s/.test(d.charAt(m-1))}}:null}function uV(e){let t=[];for(let n of e.selection.ranges){let r=e.doc.lineAt(n.from),i=n.to<=r.to?r:e.doc.lineAt(n.to);i.from>r.from&&i.from==n.to&&(i=n.to==r.to+1?r:e.doc.lineAt(n.to-1));let a=t.length-1;a>=0&&t[a].to>r.from?t[a].to=i.to:t.push({from:r.from+/^\s*/.exec(r.text)[0].length,to:i.to})}return t}function dV(e,t,n=t.selection.ranges){let r=n.map(e=>sV(t,e.from).block);if(!r.every(e=>e))return null;let i=n.map((e,n)=>lV(t,r[n],e.from,e.to));if(e!=2&&!i.every(e=>e))return{changes:t.changes(n.map((e,t)=>i[t]?[]:[{from:e.from,insert:r[t].open+` `},{from:e.to,insert:` `+r[t].close}]))};if(e!=1&&i.some(e=>e)){let e=[];for(let t=0,n;t<i.length;t++)if(n=i[t]){let i=r[t],{open:a,close:o}=n;e.push({from:a.pos-i.open.length,to:a.pos+a.margin},{from:o.pos-o.margin,to:o.pos+i.close.length})}return{changes:e}}return null}function fV(e,t,n=t.selection.ranges){let r=[],i=-1;ranges:for(let{from:e,to:a}of n){let n=r.length,o=1e9,s;for(let n=e;n<=a;){let c=t.doc.lineAt(n);if(s==null&&(s=sV(t,c.from).line,!s))continue ranges;if(c.from>i&&(e==a||a>c.from)){i=c.from;let e=/^\s*/.exec(c.text)[0].length,t=e==c.length,n=c.text.slice(e,e+s.length)==s?e:-1;e<c.text.length&&e<o&&(o=e),r.push({line:c,comment:n,token:s,indent:e,empty:t,single:!1})}n=c.to+1}if(o<1e9)for(let e=n;e<r.length;e++)r[e].indent<r[e].line.text.length&&(r[e].indent=o);r.length==n+1&&(r[n].single=!0)}if(e!=2&&r.some(e=>e.comment<0&&(!e.empty||e.single))){let e=[];for(let{line:t,token:n,indent:i,empty:a,single:o}of r)(o||!a)&&e.push({from:t.from+i,insert:n+` `});let n=t.changes(e);return{changes:n,selection:t.selection.map(n,1)}}if(e!=1&&r.some(e=>e.comment>=0)){let e=[];for(let{line:t,comment:n,token:i}of r)if(n>=0){let r=t.from+n,a=r+i.length;t.text[a-t.from]==` `&&a++,e.push({from:r,to:a})}return{changes:e}}return null}var pV=Ok.define(),mV=Ok.define(),hV=rk.define(),gV=rk.define({combine(e){return qk(e,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(n,r)=>e(n,r)||t(n,r)})}}),_V=uk.define({create(){return IV.empty},update(e,t){let n=t.state.facet(gV),r=t.annotation(pV);if(r){let i=wV.fromTransaction(t,r.selection),a=r.side,o=a==0?e.undone:e.done;return o=i?TV(o,o.length,n.minDepth,i):jV(o,t.startState.selection),new IV(a==0?r.rest:o,a==0?o:r.rest)}let i=t.annotation(mV);if((i==`full`||i==`before`)&&(e=e.isolate()),t.annotation(Mk.addToHistory)===!1)return t.changes.empty?e:e.addMapping(t.changes.desc);let a=wV.fromTransaction(t),o=t.annotation(Mk.time),s=t.annotation(Mk.userEvent);return a?e=e.addChanges(a,o,s,n,t):t.selection&&(e=e.addSelection(t.startState.selection,o,s,n.newGroupDelay)),(i==`full`||i==`after`)&&(e=e.isolate()),e},toJSON(e){return{done:e.done.map(e=>e.toJSON()),undone:e.undone.map(e=>e.toJSON())}},fromJSON(e){return new IV(e.done.map(wV.fromJSON),e.undone.map(wV.fromJSON))}});function vV(e={}){return[_V,gV.of(e),SF.domEventHandlers({beforeinput(e,t){let n=e.inputType==`historyUndo`?bV:e.inputType==`historyRedo`?xV:null;return n?(e.preventDefault(),n(t)):!1}})]}function yV(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let i=n.field(_V,!1);if(!i)return!1;let a=i.pop(e,n,t);return a?(r(a),!0):!1}}var bV=yV(0,!1),xV=yV(1,!1),SV=yV(0,!0),CV=yV(1,!0),wV=class e{constructor(e,t,n,r,i){this.changes=e,this.effects=t,this.mapped=n,this.startSelection=r,this.selectionsAfter=i}setSelAfter(t){return new e(this.changes,this.effects,this.mapped,this.startSelection,t)}toJSON(){return{changes:this.changes?.toJSON(),mapped:this.mapped?.toJSON(),startSelection:this.startSelection?.toJSON(),selectionsAfter:this.selectionsAfter.map(e=>e.toJSON())}}static fromJSON(t){return new e(t.changes&&qO.fromJSON(t.changes),[],t.mapped&&KO.fromJSON(t.mapped),t.startSelection&&Q.fromJSON(t.startSelection),t.selectionsAfter.map(Q.fromJSON))}static fromTransaction(t,n){let r=kV;for(let e of t.startState.facet(hV)){let n=e(t);n.length&&(r=r.concat(n))}return!r.length&&t.changes.empty?null:new e(t.changes.invert(t.startState.doc),r,void 0,n||t.startState.selection,kV)}static selection(t){return new e(void 0,kV,void 0,void 0,t)}};function TV(e,t,n,r){let i=t+1>n+20?t-n-1:0,a=e.slice(i,t);return a.push(r),a}function EV(e,t){let n=[],r=!1;return e.iterChangedRanges((e,t)=>n.push(e,t)),t.iterChangedRanges((e,t,i,a)=>{for(let e=0;e<n.length;){let t=n[e++],o=n[e++];a>=t&&i<=o&&(r=!0)}}),r}function DV(e,t){return e.ranges.length==t.ranges.length&&e.ranges.filter((e,n)=>e.empty!=t.ranges[n].empty).length===0}function OV(e,t){return e.length?t.length?e.concat(t):e:t}var kV=[],AV=200;function jV(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-AV));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),TV(e,e.length-1,1e9,n.setSelAfter(r)))}return[wV.selection([t])]}function MV(e){let t=e[e.length-1],n=e.slice();return n[e.length-1]=t.setSelAfter(t.selectionsAfter.slice(0,t.selectionsAfter.length-1)),n}function NV(e,t){if(!e.length)return e;let n=e.length,r=kV;for(;n;){let i=PV(e[n-1],t,r);if(i.changes&&!i.changes.empty||i.effects.length){let t=e.slice(0,n);return t[n-1]=i,t}t=i.mapped,n--,r=i.selectionsAfter}return r.length?[wV.selection(r)]:kV}function PV(e,t,n){let r=OV(e.selectionsAfter.length?e.selectionsAfter.map(e=>e.map(t)):kV,n);if(!e.changes)return wV.selection(r);let i=e.changes.map(t),a=t.mapDesc(e.changes,!0),o=e.mapped?e.mapped.composeDesc(a):a;return new wV(i,jk.mapEffects(e.effects,t),o,e.startSelection.map(a),r)}var FV=/^(input\.type|delete)($|\.)/,IV=class e{constructor(e,t,n=0,r=void 0){this.done=e,this.undone=t,this.prevTime=n,this.prevUserEvent=r}isolate(){return this.prevTime?new e(this.done,this.undone):this}addChanges(t,n,r,i,a){let o=this.done,s=o[o.length-1];return o=s&&s.changes&&!s.changes.empty&&t.changes&&(!r||FV.test(r))&&(!s.selectionsAfter.length&&n-this.prevTime<i.newGroupDelay&&i.joinToEvent(a,EV(s.changes,t.changes))||r==`input.type.compose`)?TV(o,o.length-1,i.minDepth,new wV(t.changes.compose(s.changes),OV(jk.mapEffects(t.effects,s.changes),s.effects),s.mapped,s.startSelection,kV)):TV(o,o.length,i.minDepth,t),new e(o,kV,n,r)}addSelection(t,n,r,i){let a=this.done.length?this.done[this.done.length-1].selectionsAfter:kV;return a.length>0&&n-this.prevTime<i&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&DV(a[a.length-1],t)?this:new e(jV(this.done,t),this.undone,n,r)}addMapping(t){return new e(NV(this.done,t),NV(this.undone,t),this.prevTime,this.prevUserEvent)}pop(e,t,n){let r=e==0?this.done:this.undone;if(r.length==0)return null;let i=r[r.length-1],a=i.selectionsAfter[0]||(i.startSelection?i.startSelection.map(i.changes.invertedDesc,1):t.selection);if(n&&i.selectionsAfter.length)return t.update({selection:i.selectionsAfter[i.selectionsAfter.length-1],annotations:pV.of({side:e,rest:MV(r),selection:a}),userEvent:e==0?`select.undo`:`select.redo`,scrollIntoView:!0});if(i.changes){let n=r.length==1?kV:r.slice(0,r.length-1);return i.mapped&&(n=NV(n,i.mapped)),t.update({changes:i.changes,selection:i.startSelection,effects:i.effects,annotations:pV.of({side:e,rest:n,selection:a}),filter:!1,userEvent:e==0?`undo`:`redo`,scrollIntoView:!0})}return null}};IV.empty=new IV(kV,kV);var LV=[{key:`Mod-z`,run:bV,preventDefault:!0},{key:`Mod-y`,mac:`Mod-Shift-z`,run:xV,preventDefault:!0},{linux:`Ctrl-Shift-z`,run:xV,preventDefault:!0},{key:`Mod-u`,run:SV,preventDefault:!0},{key:`Alt-u`,mac:`Mod-Shift-u`,run:CV,preventDefault:!0}];function RV(e,t){return Q.create(e.ranges.map(t),e.mainIndex)}function zV(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:`select`})}function BV({state:e,dispatch:t},n){let r=RV(e.selection,n);return!r.eq(e.selection,!0)&&(t(zV(e,r)),!0)}function VV(e,t){return Q.cursor(t?e.to:e.from)}function HV(e,t){return BV(e,n=>n.empty?e.moveByChar(n,t):VV(n,t))}function UV(e){return e.textDirectionAt(e.state.selection.main.head)==Tj.LTR}var WV=e=>HV(e,!UV(e)),GV=e=>HV(e,UV(e));function KV(e,t){return BV(e,n=>n.empty?e.moveByGroup(n,t):VV(n,t))}var qV=e=>KV(e,!UV(e)),JV=e=>KV(e,UV(e));typeof Intl<`u`&&Intl.Segmenter;function YV(e,t,n){if(t.type.prop(n))return!0;let r=t.to-t.from;return r&&(r>2||/[^\s,.;:]/.test(e.sliceDoc(t.from,t.to)))||t.firstChild}function XV(e,t,n){let r=rz(e).resolveInner(t.head),i=n?WL.closedBy:WL.openedBy;for(let a=t.head;;){let t=n?r.childAfter(a):r.childBefore(a);if(!t)break;YV(e,t,i)?r=t:a=n?t.to:t.from}let a=r.type.prop(i),o,s;return s=a&&(o=n?jB(e,r.from,1):jB(e,r.to,-1))&&o.matched?n?o.end.to:o.end.from:n?r.to:r.from,Q.cursor(s,n?-1:1)}var ZV=e=>BV(e,t=>XV(e.state,t,!UV(e))),QV=e=>BV(e,t=>XV(e.state,t,UV(e)));function $V(e,t){return BV(e,n=>{if(!n.empty)return VV(n,t);let r=e.moveVertically(n,t);return r.head==n.head?e.moveToLineBoundary(n,t):r})}var eH=e=>$V(e,!1),tH=e=>$V(e,!0);function nH(e){let t=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,n=0,r=0,i;if(t){for(let t of e.state.facet(SF.scrollMargins)){let i=t(e);i?.top&&(n=Math.max(i?.top,n)),i?.bottom&&(r=Math.max(i?.bottom,r))}i=e.scrollDOM.clientHeight-n-r}else i=(e.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:n,marginBottom:r,selfScroll:t,height:Math.max(e.defaultLineHeight,i-5)}}function rH(e,t){let n=nH(e),{state:r}=e,i=RV(r.selection,r=>r.empty?e.moveVertically(r,t,n.height):VV(r,t));if(i.eq(r.selection))return!1;let a;if(n.selfScroll){let t=e.coordsAtPos(r.selection.main.head),o=e.scrollDOM.getBoundingClientRect(),s=o.top+n.marginTop,c=o.bottom-n.marginBottom;t&&t.top>s&&t.bottom<c&&(a=SF.scrollIntoView(i.main.head,{y:`start`,yMargin:t.top-s}))}return e.dispatch(zV(r,i),{effects:a}),!0}var iH=e=>rH(e,!1),aH=e=>rH(e,!0);function oH(e,t,n){let r=e.lineBlockAt(t.head),i=e.moveToLineBoundary(t,n);if(i.head==t.head&&i.head!=(n?r.to:r.from)&&(i=e.moveToLineBoundary(t,n,!1)),!n&&i.head==r.from&&r.length){let n=/^\s*/.exec(e.state.sliceDoc(r.from,Math.min(r.from+100,r.to)))[0].length;n&&t.head!=r.from+n&&(i=Q.cursor(r.from+n))}return i}var sH=e=>BV(e,t=>oH(e,t,!0)),cH=e=>BV(e,t=>oH(e,t,!1)),lH=e=>BV(e,t=>oH(e,t,!UV(e))),uH=e=>BV(e,t=>oH(e,t,UV(e))),dH=e=>BV(e,t=>Q.cursor(e.lineBlockAt(t.head).from,1)),fH=e=>BV(e,t=>Q.cursor(e.lineBlockAt(t.head).to,-1));function pH(e,t,n){let r=!1,i=RV(e.selection,t=>{let i=jB(e,t.head,-1)||jB(e,t.head,1)||t.head>0&&jB(e,t.head-1,1)||t.head<e.doc.length&&jB(e,t.head+1,-1);if(!i||!i.end)return t;r=!0;let a=i.start.from==t.head?i.end.to:i.end.from;return n?Q.range(t.anchor,a):Q.cursor(a)});return r?(t(zV(e,i)),!0):!1}var mH=({state:e,dispatch:t})=>pH(e,t,!1);function hH(e,t,n){let r=RV(e.state.selection,e=>{e.undirectional&&e.head>=e.anchor!=t&&(e=Q.range(e.head,e.anchor));let r=n(e);return Q.range(e.anchor,r.head,r.goalColumn,r.bidiLevel||void 0,r.assoc)});return!r.eq(e.state.selection)&&(e.dispatch(zV(e.state,r)),!0)}function gH(e,t){return hH(e,t,n=>e.moveByChar(n,t))}var _H=e=>gH(e,!UV(e)),vH=e=>gH(e,UV(e));function yH(e,t){return hH(e,t,n=>e.moveByGroup(n,t))}var bH=e=>yH(e,!UV(e)),xH=e=>yH(e,UV(e)),SH=e=>{let t=!UV(e);return hH(e,t,n=>XV(e.state,n,t))},CH=e=>{let t=UV(e);return hH(e,t,n=>XV(e.state,n,t))};function wH(e,t){return hH(e,t,n=>e.moveVertically(n,t))}var TH=e=>wH(e,!1),EH=e=>wH(e,!0);function DH(e,t){return hH(e,t,n=>e.moveVertically(n,t,nH(e).height))}var OH=e=>DH(e,!1),kH=e=>DH(e,!0),AH=e=>hH(e,!0,t=>oH(e,t,!0)),jH=e=>hH(e,!1,t=>oH(e,t,!1)),MH=e=>{let t=!UV(e);return hH(e,t,n=>oH(e,n,t))},NH=e=>{let t=UV(e);return hH(e,t,n=>oH(e,n,t))},PH=e=>hH(e,!1,t=>Q.cursor(e.lineBlockAt(t.head).from)),FH=e=>hH(e,!0,t=>Q.cursor(e.lineBlockAt(t.head).to)),IH=({state:e,dispatch:t})=>(t(zV(e,{anchor:0})),!0),LH=({state:e,dispatch:t})=>(t(zV(e,{anchor:e.doc.length})),!0),RH=({state:e,dispatch:t})=>(t(zV(e,{anchor:e.selection.main.anchor,head:0})),!0),zH=({state:e,dispatch:t})=>(t(zV(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),BH=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:`select`})),!0),VH=({state:e,dispatch:t})=>{let n=oU(e).map(({from:t,to:n})=>Q.range(t,Math.min(n+1,e.doc.length)));return t(e.update({selection:Q.create(n),userEvent:`select`})),!0},HH=({state:e,dispatch:t})=>{let n=RV(e.selection,t=>{let n=rz(e),r=n.resolveStack(t.from,1);if(t.empty){let e=n.resolveStack(t.from,-1);e.node.from>=r.node.from&&e.node.to<=r.node.to&&(r=e)}for(let e=r;e;e=e.next){let{node:n}=e;if((n.from<t.from&&n.to>=t.to||n.to>t.to&&n.from<=t.from)&&e.next)return Q.range(n.to,n.from)}return t});return!n.eq(e.selection)&&(t(zV(e,n)),!0)};function UH(e,t){let{state:n}=e,r=n.selection,i=n.selection.ranges.slice();for(let r of n.selection.ranges){let a=n.doc.lineAt(r.head);if(t?a.to<e.state.doc.length:a.from>0)for(let n=r;;){let r=e.moveVertically(n,t);if(r.head<a.from||r.head>a.to){i.some(e=>e.head==r.head)||i.push(r);break}if(r.head==n.head)break;n=r}}return i.length!=r.ranges.length&&(e.dispatch(zV(n,Q.create(i,i.length-1))),!0)}var WH=e=>UH(e,!1),GH=e=>UH(e,!0),KH=({state:e,dispatch:t})=>{let n=e.selection,r=null;return n.ranges.length>1?r=Q.create([n.main]):n.main.empty||(r=Q.create([Q.cursor(n.main.head)])),r?(t(zV(e,r)),!0):!1};function qH(e,t){if(e.state.readOnly)return!1;let n=`delete.selection`,{state:r}=e,i=r.changeByRange(r=>{let{from:i,to:a}=r;if(i==a){let o=t(r);o<i?(n=`delete.backward`,o=JH(e,o,!1)):o>i&&(n=`delete.forward`,o=JH(e,o,!0)),i=Math.min(i,o),a=Math.max(a,o)}else i=JH(e,i,!1),a=JH(e,a,!0);return i==a?{range:r}:{changes:{from:i,to:a},range:Q.cursor(i,i<r.head?-1:1)}});return!i.changes.empty&&(e.dispatch(r.update(i,{scrollIntoView:!0,userEvent:n,effects:n==`delete.selection`?SF.announce.of(r.phrase(`Selection deleted`)):void 0})),!0)}function JH(e,t,n){if(e instanceof SF)for(let r of e.state.facet(SF.atomicRanges).map(t=>t(e)))r.between(t,t,(e,r)=>{e<t&&r>t&&(t=n?r:e)});return t}var YH=(e,t,n)=>qH(e,r=>{let i=r.from,{state:a}=e,o=a.doc.lineAt(i),s,c;if(n&&!t&&i>o.from&&i<o.from+200&&!/[^ \t]/.test(s=o.text.slice(0,i-o.from))){if(s[s.length-1]==` `)return i-1;let e=fA(s,a.tabSize)%gz(a)||gz(a);for(let t=0;t<e&&s[s.length-1-t]==` `;t++)i--;c=i}else c=RO(o.text,i-o.from,t,t)+o.from,c==i&&o.number!=(t?a.doc.lines:1)?c+=t?1:-1:!t&&/[\ufe00-\ufe0f]/.test(o.text.slice(c-o.from,i-o.from))&&(c=RO(o.text,c-o.from,!1,!1)+o.from);return c}),XH=e=>YH(e,!1,!0),ZH=e=>YH(e,!0,!1),QH=(e,t)=>qH(e,n=>{let r=n.head,{state:i}=e,a=i.doc.lineAt(r),o=i.charCategorizer(r);for(let e=null;;){if(r==(t?a.to:a.from)){r==n.head&&a.number!=(t?i.doc.lines:1)&&(r+=t?1:-1);break}let s=RO(a.text,r-a.from,t)+a.from,c=a.text.slice(Math.min(r,s)-a.from,Math.max(r,s)-a.from),l=o(c);if(e!=null&&l!=e)break;(c!=` `||r!=n.head)&&(e=l),r=s}return r}),$H=e=>QH(e,!1),eU=e=>QH(e,!0),tU=e=>qH(e,t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),nU=e=>qH(e,t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}),rU=e=>qH(e,t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),iU=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(e=>({changes:{from:e.from,to:e.to,insert:DO.of([``,``])},range:Q.cursor(e.from)}));return t(e.update(n,{scrollIntoView:!0,userEvent:`input`})),!0},aU=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(t=>{if(!t.empty||t.from==0||t.from==e.doc.length)return{range:t};let n=t.from,r=e.doc.lineAt(n),i=n==r.from?n-1:RO(r.text,n-r.from,!1)+r.from,a=n==r.to?n+1:RO(r.text,n-r.from,!0)+r.from;return{changes:{from:i,to:a,insert:e.doc.slice(n,a).append(e.doc.slice(i,n))},range:Q.cursor(a)}});return!n.changes.empty&&(t(e.update(n,{scrollIntoView:!0,userEvent:`move.character`})),!0)};function oU(e){let t=[],n=-1;for(let r of e.selection.ranges){let i=e.doc.lineAt(r.from),a=e.doc.lineAt(r.to);if(!r.empty&&r.to==a.from&&(a=e.doc.lineAt(r.to-1)),n>=i.number){let e=t[t.length-1];e.to=a.to,e.ranges.push(r)}else t.push({from:i.from,to:a.to,ranges:[r]});n=a.number+1}return t}function sU(e,t,n){if(e.readOnly)return!1;let r=[],i=[];for(let t of oU(e)){if(n?t.to==e.doc.length:t.from==0)continue;let a=e.doc.lineAt(n?t.to+1:t.from-1),o=a.length+1;if(n){r.push({from:t.to,to:a.to},{from:t.from,insert:a.text+e.lineBreak});for(let n of t.ranges)i.push(Q.range(Math.min(e.doc.length,n.anchor+o),Math.min(e.doc.length,n.head+o)))}else{r.push({from:a.from,to:t.from},{from:t.to,insert:e.lineBreak+a.text});for(let e of t.ranges)i.push(Q.range(e.anchor-o,e.head-o))}}return r.length?(t(e.update({changes:r,scrollIntoView:!0,selection:Q.create(i,e.selection.mainIndex),userEvent:`move.line`})),!0):!1}var cU=({state:e,dispatch:t})=>sU(e,t,!1),lU=({state:e,dispatch:t})=>sU(e,t,!0);function uU(e,t,n){if(e.readOnly)return!1;let r=[];for(let t of oU(e))n?r.push({from:t.from,insert:e.doc.slice(t.from,t.to)+e.lineBreak}):r.push({from:t.to,insert:e.lineBreak+e.doc.slice(t.from,t.to)});let i=e.changes(r);return t(e.update({changes:i,selection:e.selection.map(i,n?1:-1),scrollIntoView:!0,userEvent:`input.copyline`})),!0}var dU=({state:e,dispatch:t})=>uU(e,t,!1),fU=({state:e,dispatch:t})=>uU(e,t,!0),pU=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(oU(t).map(({from:e,to:n})=>(e>0?e--:n<t.doc.length&&n++,{from:e,to:n}))),r=RV(t.selection,t=>{let n;if(e.lineWrapping){let r=e.lineBlockAt(t.head),i=e.coordsAtPos(t.head,t.assoc||1);i&&(n=r.bottom+e.documentTop-i.bottom+e.defaultLineHeight/2)}return e.moveVertically(t,!0,n)}).map(n);return e.dispatch({changes:n,selection:r,scrollIntoView:!0,userEvent:`delete.line`}),!0};function mU(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n=rz(e).resolveInner(t),r=n.childBefore(t),i=n.childAfter(t),a;return r&&i&&r.to<=t&&i.from>=t&&(a=r.type.prop(WL.closedBy))&&a.indexOf(i.name)>-1&&e.doc.lineAt(r.to).from==e.doc.lineAt(i.from).from&&!/\S/.test(e.sliceDoc(r.to,i.from))?{from:r.to,to:i.from}:null}var hU=_U(!1),gU=_U(!0);function _U(e){return({state:t,dispatch:n})=>{if(t.readOnly)return!1;let r=t.changeByRange(n=>{let{from:r,to:i}=n,a=t.doc.lineAt(r),o=!e&&r==i&&mU(t,r);e&&(r=i=(i<=a.to?a:t.doc.lineAt(i)).to);let s=new yz(t,{simulateBreak:r,simulateDoubleBreak:!!o}),c=vz(s,r);for(c??=fA(/^\s*/.exec(t.doc.lineAt(r).text)[0],t.tabSize);i<a.to&&/\s/.test(a.text[i-a.from]);)i++;o?{from:r,to:i}=o:r>a.from&&r<a.from+100&&!/\S/.test(a.text.slice(0,r))&&(r=a.from);let l=[``,_z(t,c)];return o&&l.push(_z(t,s.lineIndent(a.from,-1))),{changes:{from:r,to:i,insert:DO.of(l)},range:Q.cursor(r+1+l[1].length)}});return n(t.update(r,{scrollIntoView:!0,userEvent:`input`})),!0}}function vU(e,t){let n=-1;return e.changeByRange(r=>{let i=[];for(let a=r.from;a<=r.to;){let o=e.doc.lineAt(a);o.number>n&&(r.empty||r.to>o.from)&&(t(o,i,r),n=o.number),a=o.to+1}let a=e.changes(i);return{changes:i,range:Q.range(a.mapPos(r.anchor,1),a.mapPos(r.head,1))}})}var yU=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new yz(e,{overrideIndentation:e=>n[e]??-1}),i=vU(e,(t,i,a)=>{let o=vz(r,t.from);if(o==null)return;/\S/.test(t.text)||(o=0);let s=/^\s*/.exec(t.text)[0],c=_z(e,o);(s!=c||a.from<t.from+s.length)&&(n[t.from]=o,i.push({from:t.from,to:t.from+s.length,insert:c}))});return i.changes.empty||t(e.update(i,{userEvent:`indent`})),!0},bU=({state:e,dispatch:t})=>!e.readOnly&&(t(e.update(vU(e,(t,n)=>{n.push({from:t.from,insert:e.facet(hz)})}),{userEvent:`input.indent`})),!0),xU=({state:e,dispatch:t})=>!e.readOnly&&(t(e.update(vU(e,(t,n)=>{let r=/^\s*/.exec(t.text)[0];if(!r)return;let i=fA(r,e.tabSize),a=0,o=_z(e,Math.max(0,i-gz(e)));for(;a<r.length&&a<o.length&&r.charCodeAt(a)==o.charCodeAt(a);)a++;n.push({from:t.from+a,to:t.from+r.length,insert:o.slice(a)})}),{userEvent:`delete.dedent`})),!0),SU=e=>(e.setTabFocusMode(),!0),CU=[{key:`Ctrl-b`,run:WV,shift:_H,preventDefault:!0},{key:`Ctrl-f`,run:GV,shift:vH},{key:`Ctrl-p`,run:eH,shift:TH},{key:`Ctrl-n`,run:tH,shift:EH},{key:`Ctrl-a`,run:dH,shift:PH},{key:`Ctrl-e`,run:fH,shift:FH},{key:`Ctrl-d`,run:ZH},{key:`Ctrl-h`,run:XH},{key:`Ctrl-k`,run:tU},{key:`Ctrl-Alt-h`,run:$H},{key:`Ctrl-o`,run:iU},{key:`Ctrl-t`,run:aU},{key:`Ctrl-v`,run:aH}],wU=[{key:`ArrowLeft`,run:WV,shift:_H,preventDefault:!0},{key:`Mod-ArrowLeft`,mac:`Alt-ArrowLeft`,run:qV,shift:bH,preventDefault:!0},{mac:`Cmd-ArrowLeft`,run:lH,shift:MH,preventDefault:!0},{key:`ArrowRight`,run:GV,shift:vH,preventDefault:!0},{key:`Mod-ArrowRight`,mac:`Alt-ArrowRight`,run:JV,shift:xH,preventDefault:!0},{mac:`Cmd-ArrowRight`,run:uH,shift:NH,preventDefault:!0},{key:`ArrowUp`,run:eH,shift:TH,preventDefault:!0},{mac:`Cmd-ArrowUp`,run:IH,shift:RH},{mac:`Ctrl-ArrowUp`,run:iH,shift:OH},{key:`ArrowDown`,run:tH,shift:EH,preventDefault:!0},{mac:`Cmd-ArrowDown`,run:LH,shift:zH},{mac:`Ctrl-ArrowDown`,run:aH,shift:kH},{key:`PageUp`,run:iH,shift:OH},{key:`PageDown`,run:aH,shift:kH},{key:`Home`,run:cH,shift:jH,preventDefault:!0},{key:`Mod-Home`,run:IH,shift:RH},{key:`End`,run:sH,shift:AH,preventDefault:!0},{key:`Mod-End`,run:LH,shift:zH},{key:`Enter`,run:hU,shift:hU},{key:`Mod-a`,run:BH},{key:`Backspace`,run:XH,shift:XH,preventDefault:!0},{key:`Delete`,run:ZH,preventDefault:!0},{key:`Mod-Backspace`,mac:`Alt-Backspace`,run:$H,preventDefault:!0},{key:`Mod-Delete`,mac:`Alt-Delete`,run:eU,preventDefault:!0},{mac:`Mod-Backspace`,run:nU,preventDefault:!0},{mac:`Mod-Delete`,run:rU,preventDefault:!0}].concat(CU.map(e=>({mac:e.key,run:e.run,shift:e.shift}))),TU=[{key:`Alt-ArrowLeft`,mac:`Ctrl-ArrowLeft`,run:ZV,shift:SH},{key:`Alt-ArrowRight`,mac:`Ctrl-ArrowRight`,run:QV,shift:CH},{key:`Alt-ArrowUp`,run:cU},{key:`Shift-Alt-ArrowUp`,run:dU},{key:`Alt-ArrowDown`,run:lU},{key:`Shift-Alt-ArrowDown`,run:fU},{key:`Mod-Alt-ArrowUp`,run:WH},{key:`Mod-Alt-ArrowDown`,run:GH},{key:`Escape`,run:KH},{key:`Mod-Enter`,run:gU},{key:`Alt-l`,mac:`Ctrl-l`,run:VH},{key:`Mod-i`,run:HH,preventDefault:!0},{key:`Mod-[`,run:xU},{key:`Mod-]`,run:bU},{key:`Mod-Alt-\\`,run:yU},{key:`Shift-Mod-k`,run:pU},{key:`Shift-Mod-\\`,run:mH},{key:`Mod-/`,run:nV},{key:`Alt-A`,run:aV},{key:`Ctrl-m`,mac:`Shift-Alt-m`,run:SU}].concat(wU),EU={key:`Tab`,run:bU,shift:xU},DU=[],OU=[];(()=>{let e=`lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5`.split(`,`).map(e=>e?parseInt(e,36):1);for(let t=0,n=0;t<e.length;t++)(t%2?OU:DU).push(n+=e[t])})();function kU(e){if(e<768)return!1;for(let t=0,n=DU.length;;){let r=t+n>>1;if(e<DU[r])n=r;else if(e>=OU[r])t=r+1;else return!0;if(t==n)return!1}}function AU(e){return e>=127462&&e<=127487}var jU=8205;function MU(e,t,n=!0,r=!0){return(n?NU:PU)(e,t,r)}function NU(e,t,n){if(t==e.length)return t;t&&IU(e.charCodeAt(t))&&LU(e.charCodeAt(t-1))&&t--;let r=FU(e,t);for(t+=RU(r);t<e.length;){let i=FU(e,t);if(r==jU||i==jU||n&&kU(i))t+=RU(i),r=i;else if(AU(i)){let n=0,r=t-2;for(;r>=0&&AU(FU(e,r));)n++,r-=2;if(n%2==0)break;t+=2}else break}return t}function PU(e,t,n){for(;t>1;){let r=NU(e,t-2,n);if(r<t)return r;t--}return 0}function FU(e,t){let n=e.charCodeAt(t);if(!LU(n)||t+1==e.length)return n;let r=e.charCodeAt(t+1);return IU(r)?(n-55296<<10)+(r-56320)+65536:n}function IU(e){return e>=56320&&e<57344}function LU(e){return e>=55296&&e<56320}function RU(e){return e<65536?1:2}var zU=class e{lineAt(e){if(e<0||e>this.length)throw RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,n){[e,t]=YU(this,e,t);let r=[];return this.decompose(0,e,r,2),n.length&&n.decompose(0,n.length,r,3),this.decompose(t,this.length,r,1),VU.from(r,this.length-(t-e)+n.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=YU(this,e,t);let n=[];return this.decompose(e,t,n,0),VU.from(n,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),n=this.length-this.scanIdentical(e,-1),r=new GU(this),i=new GU(e);for(let e=t,a=t;;){if(r.next(e),i.next(e),e=0,r.lineBreak!=i.lineBreak||r.done!=i.done||r.value!=i.value)return!1;if(a+=r.value.length,r.done||a>=n)return!0}}iter(e=1){return new GU(this,e)}iterRange(e,t=this.length){return new KU(this,e,t)}iterLines(e,t){let n;if(e==null)n=this.iter();else{t??=this.lines+1;let r=this.line(e).from;n=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new qU(n)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(t){if(t.length==0)throw RangeError(`A document must have at least one line`);return t.length==1&&!t[0]?e.empty:t.length<=32?new BU(t):VU.from(BU.split(t,[]))}},BU=class e extends zU{constructor(e,t=HU(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,n,r){for(let i=0;;i++){let a=this.text[i],o=r+a.length;if((t?n:o)>=e)return new JU(r,o,n,a);r=o+1,n++}}decompose(t,n,r,i){let a=t<=0&&n>=this.length?this:new e(WU(this.text,t,n),Math.min(n,this.length)-Math.max(0,t));if(i&1){let t=r.pop(),n=UU(a.text,t.text.slice(),0,a.length);if(n.length<=32)r.push(new e(n,t.length+a.length));else{let t=n.length>>1;r.push(new e(n.slice(0,t)),new e(n.slice(t)))}}else r.push(a)}replace(t,n,r){if(!(r instanceof e))return super.replace(t,n,r);[t,n]=YU(this,t,n);let i=UU(this.text,UU(r.text,WU(this.text,0,t)),n),a=this.length+r.length-(n-t);return i.length<=32?new e(i,a):VU.from(e.split(i,[]),a)}sliceString(e,t=this.length,n=`
|
|
39
|
+
`){[e,t]=YU(this,e,t);let r=``;for(let i=0,a=0;i<=t&&a<this.text.length;a++){let o=this.text[a],s=i+o.length;i>e&&a&&(r+=n),e<s&&t>i&&(r+=o.slice(Math.max(0,e-i),t-i)),i=s+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(t,n){let r=[],i=-1;for(let a of t)r.push(a),i+=a.length+1,r.length==32&&(n.push(new e(r,i)),r=[],i=-1);return i>-1&&n.push(new e(r,i)),n}},VU=class e extends zU{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let t of e)this.lines+=t.lines}lineInner(e,t,n,r){for(let i=0;;i++){let a=this.children[i],o=r+a.length,s=n+a.lines-1;if((t?s:o)>=e)return a.lineInner(e,t,n,r);r=o+1,n=s+1}}decompose(e,t,n,r){for(let i=0,a=0;a<=t&&i<this.children.length;i++){let o=this.children[i],s=a+o.length;if(e<=s&&t>=a){let i=r&(a<=e|(s>=t?2:0));a>=e&&s<=t&&!i?n.push(o):o.decompose(e-a,t-a,n,i)}a=s+1}}replace(t,n,r){if([t,n]=YU(this,t,n),r.lines<this.lines)for(let i=0,a=0;i<this.children.length;i++){let o=this.children[i],s=a+o.length;if(t>=a&&n<=s){let c=o.replace(t-a,n-a,r),l=this.lines-o.lines+c.lines;if(c.lines<l>>4&&c.lines>l>>6){let a=this.children.slice();return a[i]=c,new e(a,this.length-(n-t)+r.length)}return super.replace(a,s,c)}a=s+1}return super.replace(t,n,r)}sliceString(e,t=this.length,n=`
|
|
40
|
+
`){[e,t]=YU(this,e,t);let r=``;for(let i=0,a=0;i<this.children.length&&a<=t;i++){let o=this.children[i],s=a+o.length;a>e&&i&&(r+=n),e<s&&t>a&&(r+=o.sliceString(e-a,t-a,n)),a=s+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(t,n){if(!(t instanceof e))return 0;let r=0,[i,a,o,s]=n>0?[0,0,this.children.length,t.children.length]:[this.children.length-1,t.children.length-1,-1,-1];for(;;i+=n,a+=n){if(i==o||a==s)return r;let e=this.children[i],c=t.children[a];if(e!=c)return r+e.scanIdentical(c,n);r+=e.length+1}}static from(t,n=t.reduce((e,t)=>e+t.length+1,-1)){let r=0;for(let e of t)r+=e.lines;if(r<32){let e=[];for(let n of t)n.flatten(e);return new BU(e,n)}let i=Math.max(32,r>>5),a=i<<1,o=i>>1,s=[],c=0,l=-1,u=[];function d(t){let n;if(t.lines>a&&t instanceof e)for(let e of t.children)d(e);else t.lines>o&&(c>o||!c)?(f(),s.push(t)):t instanceof BU&&c&&(n=u[u.length-1])instanceof BU&&t.lines+n.lines<=32?(c+=t.lines,l+=t.length+1,u[u.length-1]=new BU(n.text.concat(t.text),n.length+1+t.length)):(c+t.lines>i&&f(),c+=t.lines,l+=t.length+1,u.push(t))}function f(){c!=0&&(s.push(u.length==1?u[0]:e.from(u,l)),l=-1,c=u.length=0)}for(let e of t)d(e);return f(),s.length==1?s[0]:new e(s,n)}};zU.empty=new BU([``],0);function HU(e){let t=-1;for(let n of e)t+=n.length+1;return t}function UU(e,t,n=0,r=1e9){for(let i=0,a=0,o=!0;a<e.length&&i<=r;a++){let s=e[a],c=i+s.length;c>=n&&(c>r&&(s=s.slice(0,r-i)),i<n&&(s=s.slice(n-i)),o?(t[t.length-1]+=s,o=!1):t.push(s)),i=c+1}return t}function WU(e,t,n){return UU(e,[``],t,n)}var GU=class{constructor(e,t=1){this.dir=t,this.done=!1,this.lineBreak=!1,this.value=``,this.nodes=[e],this.offsets=[t>0?1:(e instanceof BU?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let n=this.nodes.length-1,r=this.nodes[n],i=this.offsets[n],a=i>>1,o=r instanceof BU?r.text.length:r.children.length;if(a==(t>0?o:0)){if(n==0)return this.done=!0,this.value=``,this;t>0&&this.offsets[n-1]++,this.nodes.pop(),this.offsets.pop()}else if((i&1)==(t>0?0:1)){if(this.offsets[n]+=t,e==0)return this.lineBreak=!0,this.value=`
|
|
41
|
+
`,this;e--}else if(r instanceof BU){let i=r.text[a+(t<0?-1:0)];if(this.offsets[n]+=t,i.length>Math.max(0,e))return this.value=e==0?i:t>0?i.slice(e):i.slice(0,i.length-e),this;e-=i.length}else{let i=r.children[a+(t<0?-1:0)];e>i.length?(e-=i.length,this.offsets[n]+=t):(t<0&&this.offsets[n]--,this.nodes.push(i),this.offsets.push(t>0?1:(i instanceof BU?i.text.length:i.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},KU=class{constructor(e,t,n){this.value=``,this.done=!1,this.cursor=new GU(e,t>n?-1:1),this.pos=t>n?e.length:0,this.from=Math.min(t,n),this.to=Math.max(t,n)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value=``,this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let n=t<0?this.pos-this.from:this.to-this.pos;e>n&&(e=n),n-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=n?r:t<0?r.slice(r.length-n):r.slice(0,n),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=``}},qU=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value=``,this.done=!1}next(e=0){let{done:t,lineBreak:n,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value=``,this.afterBreak=!1):t?(this.done=!0,this.value=``):n?this.afterBreak?this.value=``:(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<`u`&&(zU.prototype[Symbol.iterator]=function(){return this.iter()},GU.prototype[Symbol.iterator]=KU.prototype[Symbol.iterator]=qU.prototype[Symbol.iterator]=function(){return this});var JU=class{constructor(e,t,n,r){this.from=e,this.to=t,this.number=n,this.text=r}get length(){return this.to-this.from}};function YU(e,t,n){return t=Math.max(0,Math.min(e.length,t)),[t,Math.max(t,Math.min(e.length,n))]}function XU(e,t,n=!0,r=!0){return MU(e,t,n,r)}function ZU(e){return e>=56320&&e<57344}function QU(e){return e>=55296&&e<56320}function $U(e,t){let n=e.charCodeAt(t);if(!QU(n)||t+1==e.length)return n;let r=e.charCodeAt(t+1);return ZU(r)?(n-55296<<10)+(r-56320)+65536:n}function eW(e){return e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode((e>>10)+55296,(e&1023)+56320))}function tW(e){return e<65536?1:2}var nW=/\r\n?|\n/,rW=(function(e){return e[e.Simple=0]=`Simple`,e[e.TrackDel=1]=`TrackDel`,e[e.TrackBefore=2]=`TrackBefore`,e[e.TrackAfter=3]=`TrackAfter`,e})(rW||={}),iW=class e{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;t<this.sections.length;t+=2)e+=this.sections[t];return e}get newLength(){let e=0;for(let t=0;t<this.sections.length;t+=2){let n=this.sections[t+1];e+=n<0?this.sections[t]:n}return e}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(e){for(let t=0,n=0,r=0;t<this.sections.length;){let i=this.sections[t++],a=this.sections[t++];a<0?(e(n,r,i),r+=i):r+=a,n+=i}}iterChangedRanges(e,t=!1){cW(this,e,t)}get invertedDesc(){let t=[];for(let e=0;e<this.sections.length;){let n=this.sections[e++],r=this.sections[e++];r<0?t.push(n,r):t.push(r,n)}return new e(t)}composeDesc(e){return this.empty?e:e.empty?this:uW(this,e)}mapDesc(e,t=!1){return e.empty?this:lW(this,e,t)}mapPos(e,t=-1,n=rW.Simple){let r=0,i=0;for(let a=0;a<this.sections.length;){let o=this.sections[a++],s=this.sections[a++],c=r+o;if(s<0){if(c>e)return i+(e-r);i+=o}else{if(n!=rW.Simple&&c>=e&&(n==rW.TrackDel&&r<e&&c>e||n==rW.TrackBefore&&r<e||n==rW.TrackAfter&&c>e))return null;if(c>e||c==e&&t<0&&!o)return e==r||t<0?i:i+s;i+=s}r=c}if(e>r)throw RangeError(`Position ${e} is out of range for changeset of length ${r}`);return i}touchesRange(e,t=e){for(let n=0,r=0;n<this.sections.length&&r<=t;){let i=this.sections[n++],a=this.sections[n++],o=r+i;if(a>=0&&r<=t&&o>=e)return r<e&&o>t?`cover`:!0;r=o}return!1}toString(){let e=``;for(let t=0;t<this.sections.length;){let n=this.sections[t++],r=this.sections[t++];e+=(e?` `:``)+n+(r>=0?`:`+r:``)}return e}toJSON(){return this.sections}static fromJSON(t){if(!Array.isArray(t)||t.length%2||t.some(e=>typeof e!=`number`))throw RangeError(`Invalid JSON representation of ChangeDesc`);return new e(t)}static create(t){return new e(t)}},aW=class e extends iW{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw RangeError(`Applying change set to a document with the wrong length`);return cW(this,(t,n,r,i,a)=>e=e.replace(r,r+(n-t),a),!1),e}mapDesc(e,t=!1){return lW(this,e,t,!0)}invert(t){let n=this.sections.slice(),r=[];for(let e=0,i=0;e<n.length;e+=2){let a=n[e],o=n[e+1];if(o>=0){n[e]=o,n[e+1]=a;let s=e>>1;for(;r.length<s;)r.push(zU.empty);r.push(a?t.slice(i,i+a):zU.empty)}i+=a}return new e(n,r)}compose(e){return this.empty?e:e.empty?this:uW(this,e,!0)}map(e,t=!1){return e.empty?this:lW(this,e,t,!0)}iterChanges(e,t=!1){cW(this,e,t)}get desc(){return iW.create(this.sections)}filter(t){let n=[],r=[],i=[],a=new dW(this);done:for(let e=0,o=0;;){let s=e==t.length?1e9:t[e++];for(;o<s||o==s&&a.len==0;){if(a.done)break done;let e=Math.min(a.len,s-o);oW(i,e,-1);let t=a.ins==-1?-1:a.off==0?a.ins:0;oW(n,e,t),t>0&&sW(r,n,a.text),a.forward(e),o+=e}let c=t[e++];for(;o<c;){if(a.done)break done;let e=Math.min(a.len,c-o);oW(n,e,-1),oW(i,e,a.ins==-1?-1:a.off==0?a.ins:0),a.forward(e),o+=e}}return{changes:new e(n,r),filtered:iW.create(i)}}toJSON(){let e=[];for(let t=0;t<this.sections.length;t+=2){let n=this.sections[t],r=this.sections[t+1];r<0?e.push(n):r==0?e.push([n]):e.push([n].concat(this.inserted[t>>1].toJSON()))}return e}static of(t,n,r){let i=[],a=[],o=0,s=null;function c(t=!1){if(!t&&!i.length)return;o<n&&oW(i,n-o,-1);let r=new e(i,a);s=s?s.compose(r.map(s)):r,i=[],a=[],o=0}function l(t){if(Array.isArray(t))for(let e of t)l(e);else if(t instanceof e){if(t.length!=n)throw RangeError(`Mismatched change set length (got ${t.length}, expected ${n})`);c(),s=s?s.compose(t.map(s)):t}else{let{from:e,to:s=e,insert:l}=t;if(e>s||e<0||s>n)throw RangeError(`Invalid change range ${e} to ${s} (in doc of length ${n})`);let u=l?typeof l==`string`?zU.of(l.split(r||nW)):l:zU.empty,d=u.length;if(e==s&&d==0)return;e<o&&c(),e>o&&oW(i,e-o,-1),oW(i,s-e,d),sW(a,i,u),o=s}}return l(t),c(!s),s}static empty(t){return new e(t?[t,-1]:[],[])}static fromJSON(t){if(!Array.isArray(t))throw RangeError(`Invalid JSON representation of ChangeSet`);let n=[],r=[];for(let e=0;e<t.length;e++){let i=t[e];if(typeof i==`number`)n.push(i,-1);else if(!Array.isArray(i)||typeof i[0]!=`number`||i.some((e,t)=>t&&typeof e!=`string`))throw RangeError(`Invalid JSON representation of ChangeSet`);else if(i.length==1)n.push(i[0],0);else{for(;r.length<e;)r.push(zU.empty);r[e]=zU.of(i.slice(1)),n.push(i[0],r[e].length)}}return new e(n,r)}static createSet(t,n){return new e(t,n)}};function oW(e,t,n,r=!1){if(t==0&&n<=0)return;let i=e.length-2;i>=0&&n<=0&&n==e[i+1]?e[i]+=t:i>=0&&t==0&&e[i]==0?e[i+1]+=n:r?(e[i]+=t,e[i+1]+=n):e.push(t,n)}function sW(e,t,n){if(n.length==0)return;let r=t.length-2>>1;if(r<e.length)e[e.length-1]=e[e.length-1].append(n);else{for(;e.length<r;)e.push(zU.empty);e.push(n)}}function cW(e,t,n){let r=e.inserted;for(let i=0,a=0,o=0;o<e.sections.length;){let s=e.sections[o++],c=e.sections[o++];if(c<0)i+=s,a+=s;else{let l=i,u=a,d=zU.empty;for(;l+=s,u+=c,c&&r&&(d=d.append(r[o-2>>1])),!(n||o==e.sections.length||e.sections[o+1]<0);)s=e.sections[o++],c=e.sections[o++];t(i,l,a,u,d),i=l,a=u}}}function lW(e,t,n,r=!1){let i=[],a=r?[]:null,o=new dW(e),s=new dW(t);for(let e=-1;;)if(o.done&&s.len||s.done&&o.len)throw Error(`Mismatched change set lengths`);else if(o.ins==-1&&s.ins==-1){let e=Math.min(o.len,s.len);oW(i,e,-1),o.forward(e),s.forward(e)}else if(s.ins>=0&&(o.ins<0||e==o.i||o.off==0&&(s.len<o.len||s.len==o.len&&!n))){let t=s.len;for(oW(i,s.ins,-1);t;){let n=Math.min(o.len,t);o.ins>=0&&e<o.i&&o.len<=n&&(oW(i,0,o.ins),a&&sW(a,i,o.text),e=o.i),o.forward(n),t-=n}s.next()}else if(o.ins>=0){let t=0,n=o.len;for(;n;)if(s.ins==-1){let e=Math.min(n,s.len);t+=e,n-=e,s.forward(e)}else if(s.ins==0&&s.len<n)n-=s.len,s.next();else break;oW(i,t,e<o.i?o.ins:0),a&&e<o.i&&sW(a,i,o.text),e=o.i,o.forward(o.len-n)}else if(o.done&&s.done)return a?aW.createSet(i,a):iW.create(i);else throw Error(`Mismatched change set lengths`)}function uW(e,t,n=!1){let r=[],i=n?[]:null,a=new dW(e),o=new dW(t);for(let e=!1;;)if(a.done&&o.done)return i?aW.createSet(r,i):iW.create(r);else if(a.ins==0)oW(r,a.len,0,e),a.next();else if(o.len==0&&!o.done)oW(r,0,o.ins,e),i&&sW(i,r,o.text),o.next();else if(a.done||o.done)throw Error(`Mismatched change set lengths`);else{let t=Math.min(a.len2,o.len),n=r.length;if(a.ins==-1){let n=o.ins==-1?-1:o.off?0:o.ins;oW(r,t,n,e),i&&n&&sW(i,r,o.text)}else o.ins==-1?(oW(r,a.off?0:a.len,t,e),i&&sW(i,r,a.textBit(t))):(oW(r,a.off?0:a.len,o.off?0:o.ins,e),i&&!o.off&&sW(i,r,o.text));e=(a.ins>t||o.ins>=0&&o.len>t)&&(e||r.length>n),a.forward2(t),o.forward(t)}}var dW=class{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i<e.length?(this.len=e[this.i++],this.ins=e[this.i++]):(this.len=0,this.ins=-2),this.off=0}get done(){return this.ins==-2}get len2(){return this.ins<0?this.len:this.ins}get text(){let{inserted:e}=this.set,t=this.i-2>>1;return t>=e.length?zU.empty:e[t]}textBit(e){let{inserted:t}=this.set,n=this.i-2>>1;return n>=t.length&&!e?zU.empty:t[n].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}},fW=class e{constructor(e,t,n,r){this.from=e,this.to=t,this.flags=n,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(t,n=-1){let r,i;return this.empty?r=i=t.mapPos(this.from,n):(r=t.mapPos(this.from,1),i=t.mapPos(this.to,-1)),r==this.from&&i==this.to?this:new e(r,i,this.flags,this.goalColumn)}extend(e,t=e,n=0){if(e<=this.anchor&&t>=this.anchor)return pW.range(e,t,void 0,void 0,n);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return pW.range(this.anchor,r,void 0,void 0,n)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!=`number`||typeof e.head!=`number`)throw RangeError(`Invalid JSON representation for SelectionRange`);return pW.range(e.anchor,e.head)}static create(t,n,r,i){return new e(t,n,r,i)}},pW=class e{constructor(e,t){this.ranges=e,this.mainIndex=t}map(t,n=-1){return t.empty?this:e.create(this.ranges.map(e=>e.map(t,n)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let n=0;n<this.ranges.length;n++)if(!this.ranges[n].eq(e.ranges[n],t))return!1;return!0}get main(){return this.ranges[this.mainIndex]}asSingle(){return this.ranges.length==1?this:new e([this.main],0)}addRange(t,n=!0){return e.create([t].concat(this.ranges),n?0:this.mainIndex+1)}replaceRange(t,n=this.mainIndex){let r=this.ranges.slice();return r[n]=t,e.create(r,this.mainIndex)}toJSON(){return{ranges:this.ranges.map(e=>e.toJSON()),main:this.mainIndex}}static fromJSON(t){if(!t||!Array.isArray(t.ranges)||typeof t.main!=`number`||t.main>=t.ranges.length)throw RangeError(`Invalid JSON representation for EditorSelection`);return new e(t.ranges.map(e=>fW.fromJSON(e)),t.main)}static single(t,n=t){return new e([e.range(t,n)],0)}static create(t,n=0){if(t.length==0)throw RangeError(`A selection needs at least one range`);for(let r=0,i=0;i<t.length;i++){let a=t[i];if(a.empty?a.from<=r:a.from<r)return e.normalized(t.slice(),n);r=a.to}return new e(t,n)}static cursor(e,t=0,n,r){return fW.create(e,e,(t==0?0:t<0?8:16)|(n==null?7:Math.min(6,n)),r)}static range(e,t,n,r,i){let a=r==null?7:Math.min(6,r);return!i&&e!=t&&(i=t<e?1:-1),i&&(a|=i<0?8:16),t<e?fW.create(t,e,a|32,n):fW.create(e,t,a,n)}static undirectionalRange(e,t){return fW.create(e,t,64,void 0)}static normalized(t,n=0){let r=t[n];t.sort((e,t)=>e.from-t.from),n=t.indexOf(r);for(let r=1;r<t.length;r++){let i=t[r],a=t[r-1];if(i.empty?i.from<=a.to:i.from<a.to){let o=a.from,s=Math.max(i.to,a.to);r<=n&&n--,t.splice(--r,2,i.anchor>i.head?e.range(s,o):e.range(o,s))}}return new e(t,n)}};function mW(e,t){for(let n of e.ranges)if(n.to>t)throw RangeError(`Selection points outside of document`)}var hW=0,gW=class e{constructor(e,t,n,r,i){this.combine=e,this.compareInput=t,this.compare=n,this.isStatic=r,this.id=hW++,this.default=e([]),this.extensions=typeof i==`function`?i(this):i}get reader(){return this}static define(t={}){return new e(t.combine||(e=>e),t.compareInput||((e,t)=>e===t),t.compare||(t.combine?(e,t)=>e===t:_W),!!t.static,t.enables)}of(e){return new vW([],this,0,e)}compute(e,t){if(this.isStatic)throw Error(`Can't compute a static facet`);return new vW(e,this,1,t)}computeN(e,t){if(this.isStatic)throw Error(`Can't compute a static facet`);return new vW(e,this,2,t)}from(e,t){return t||=e=>e,this.compute([e],n=>t(n.field(e)))}};function _W(e,t){return e==t||e.length==t.length&&e.every((e,n)=>e===t[n])}var vW=class{constructor(e,t,n,r){this.dependencies=e,this.facet=t,this.type=n,this.value=r,this.id=hW++}dynamicSlot(e){let t=this.value,n=this.facet.compareInput,r=this.id,i=e[r]>>1,a=this.type==2,o=!1,s=!1,c=[];for(let t of this.dependencies)t==`doc`?o=!0:t==`selection`?s=!0:(e[t.id]??1)&1||c.push(e[t.id]);return{create(e){return e.values[i]=t(e),1},update(e,r){if(o&&r.docChanged||s&&(r.docChanged||r.selection)||bW(e,c)){let r=t(e);if(a?!yW(r,e.values[i],n):!n(r,e.values[i]))return e.values[i]=r,1}return 0},reconfigure:(e,o)=>{let s,c=o.config.address[r];if(c!=null){let r=NW(o,c);if(this.dependencies.every(t=>t instanceof gW?o.facet(t)===e.facet(t):t instanceof CW?o.field(t,!1)==e.field(t,!1):!0)||(a?yW(s=t(e),r,n):n(s=t(e),r)))return e.values[i]=r,0}else s=t(e);return e.values[i]=s,1}}}get extension(){return this}};function yW(e,t,n){if(e.length!=t.length)return!1;for(let r=0;r<e.length;r++)if(!n(e[r],t[r]))return!1;return!0}function bW(e,t){let n=!1;for(let r of t)MW(e,r)&1&&(n=!0);return n}function xW(e,t,n){let r=n.map(t=>e[t.id]),i=n.map(e=>e.type),a=r.filter(e=>!(e&1)),o=e[t.id]>>1;function s(e){let n=[];for(let t=0;t<r.length;t++){let a=NW(e,r[t]);if(i[t]==2)for(let e of a)n.push(e);else n.push(a)}return t.combine(n)}return{create(e){for(let t of r)MW(e,t);return e.values[o]=s(e),1},update(e,n){if(!bW(e,a))return 0;let r=s(e);return t.compare(r,e.values[o])?0:(e.values[o]=r,1)},reconfigure(e,i){let a=bW(e,r),c=i.config.facets[t.id],l=i.facet(t);if(c&&!a&&_W(n,c))return e.values[o]=l,0;let u=s(e);return t.compare(u,l)?(e.values[o]=l,0):(e.values[o]=u,1)}}}var SW=gW.define({static:!0}),CW=class e{constructor(e,t,n,r,i){this.id=e,this.createF=t,this.updateF=n,this.compareF=r,this.spec=i,this.provides=void 0}static define(t){let n=new e(hW++,t.create,t.update,t.compare||((e,t)=>e===t),t);return t.provide&&(n.provides=t.provide(n)),n}create(e){return(e.facet(SW).find(e=>e.field==this)?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:e=>(e.values[t]=this.create(e),1),update:(e,n)=>{let r=e.values[t],i=this.updateF(r,n);return this.compareF(r,i)?0:(e.values[t]=i,1)},reconfigure:(e,n)=>{let r=e.facet(SW),i=n.facet(SW),a;return(a=r.find(e=>e.field==this))&&a!=i.find(e=>e.field==this)?(e.values[t]=a.create(e),1):n.config.address[this.id]==null?(e.values[t]=this.create(e),1):(e.values[t]=n.field(this),0)}}}init(e){return[this,SW.of({field:this,create:e})]}get extension(){return this}},wW={lowest:4,low:3,default:2,high:1,highest:0};function TW(e){return t=>new DW(t,e)}var EW={highest:TW(wW.highest),high:TW(wW.high),default:TW(wW.default),low:TW(wW.low),lowest:TW(wW.lowest)},DW=class{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}},OW=class e{of(e){return new kW(this,e)}reconfigure(t){return e.reconfigure.of({compartment:this,extension:t})}get(e){return e.config.compartments.get(this)}},kW=class{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}},AW=class e{constructor(e,t,n,r,i,a){for(this.base=e,this.compartments=t,this.dynamicSlots=n,this.address=r,this.staticValues=i,this.facets=a,this.statusTemplate=[];this.statusTemplate.length<n.length;)this.statusTemplate.push(0)}staticFacet(e){let t=this.address[e.id];return t==null?e.default:this.staticValues[t>>1]}static resolve(t,n,r){let i=[],a=Object.create(null),o=new Map;for(let e of jW(t,n,o))e instanceof CW?i.push(e):(a[e.facet.id]||(a[e.facet.id]=[])).push(e);let s=Object.create(null),c=[],l=[];for(let e of i)s[e.id]=l.length<<1,l.push(t=>e.slot(t));let u=r?.config.facets;for(let e in a){let t=a[e],n=t[0].facet,i=u&&u[e]||[];if(t.every(e=>e.type==0)){if(s[n.id]=c.length<<1|1,_W(i,t))c.push(r.facet(n));else{let e=n.combine(t.map(e=>e.value));c.push(r&&n.compare(e,r.facet(n))?r.facet(n):e)}}else{for(let e of t)e.type==0?(s[e.id]=c.length<<1|1,c.push(e.value)):(s[e.id]=l.length<<1,l.push(t=>e.dynamicSlot(t)));s[n.id]=l.length<<1,l.push(e=>xW(e,n,t))}}let d=l.map(e=>e(s));return new e(t,o,d,s,c,a)}};function jW(e,t,n){let r=[[],[],[],[],[]],i=new Map;function a(e,o){let s=i.get(e);if(s!=null){if(s<=o)return;let t=r[s].indexOf(e);t>-1&&r[s].splice(t,1),e instanceof kW&&n.delete(e.compartment)}if(i.set(e,o),Array.isArray(e))for(let t of e)a(t,o);else if(e instanceof kW){if(n.has(e.compartment))throw RangeError(`Duplicate use of compartment in extensions`);let r=t.get(e.compartment)||e.inner;n.set(e.compartment,r),a(r,o)}else if(e instanceof DW)a(e.inner,e.prec);else if(e instanceof CW)r[o].push(e),e.provides&&a(e.provides,o);else if(e instanceof vW)r[o].push(e),e.facet.extensions&&a(e.facet.extensions,wW.default);else{let t=e.extension;if(!t)throw Error(`Unrecognized extension value in extension set (${e}).`);if(t==e)throw Error(`Unrecognized extension value in extension set (${e}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);a(t,o)}}return a(e,wW.default),r.reduce((e,t)=>e.concat(t))}function MW(e,t){if(t&1)return 2;let n=t>>1,r=e.status[n];if(r==4)throw Error(`Cyclic dependency between fields and/or facets`);if(r&2)return r;e.status[n]=4;let i=e.computeSlot(e,e.config.dynamicSlots[n]);return e.status[n]=2|i}function NW(e,t){return t&1?e.config.staticValues[t>>1]:e.values[t>>1]}var PW=gW.define(),FW=gW.define({combine:e=>e.some(e=>e),static:!0}),IW=gW.define({combine:e=>e.length?e[0]:void 0,static:!0}),LW=gW.define(),RW=gW.define(),zW=gW.define(),BW=gW.define({combine:e=>e.length?e[0]:!1}),VW=class{constructor(e,t){this.type=e,this.value=t}static define(){return new HW}},HW=class{of(e){return new VW(this,e)}},UW=class{constructor(e){this.map=e}of(e){return new WW(this,e)}},WW=class e{constructor(e,t){this.type=e,this.value=t}map(t){let n=this.type.map(this.value,t);return n===void 0?void 0:n==this.value?this:new e(this.type,n)}is(e){return this.type==e}static define(e={}){return new UW(e.map||(e=>e))}static mapEffects(e,t){if(!e.length)return e;let n=[];for(let r of e){let e=r.map(t);e&&n.push(e)}return n}};WW.reconfigure=WW.define(),WW.appendConfig=WW.define();var GW=class e{constructor(t,n,r,i,a,o){this.startState=t,this.changes=n,this.selection=r,this.effects=i,this.annotations=a,this.scrollIntoView=o,this._doc=null,this._state=null,r&&mW(r,n.newLength),a.some(t=>t.type==e.time)||(this.annotations=a.concat(e.time.of(Date.now())))}static create(t,n,r,i,a,o){return new e(t,n,r,i,a,o)}get newDoc(){return this._doc||=this.changes.apply(this.startState.doc)}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(t){let n=this.annotation(e.userEvent);return!!(n&&(n==t||n.length>t.length&&n.slice(0,t.length)==t&&n[t.length]==`.`))}};GW.time=VW.define(),GW.userEvent=VW.define(),GW.addToHistory=VW.define(),GW.remote=VW.define();function KW(e,t){let n=[];for(let r=0,i=0;;){let a,o;if(r<e.length&&(i==t.length||t[i]>=e[r]))a=e[r++],o=e[r++];else if(i<t.length)a=t[i++],o=t[i++];else return n;!n.length||n[n.length-1]<a?n.push(a,o):n[n.length-1]<o&&(n[n.length-1]=o)}}function qW(e,t,n){let r,i,a;return n?(r=t.changes,i=aW.empty(t.changes.length),a=e.changes.compose(t.changes)):(r=t.changes.map(e.changes),i=e.changes.mapDesc(t.changes,!0),a=e.changes.compose(r)),{changes:a,selection:t.selection?t.selection.map(i):e.selection?.map(r),effects:WW.mapEffects(e.effects,r).concat(WW.mapEffects(t.effects,i)),annotations:e.annotations.length?e.annotations.concat(t.annotations):t.annotations,scrollIntoView:e.scrollIntoView||t.scrollIntoView}}function JW(e,t,n){let r=t.selection,i=$W(t.annotations);return t.userEvent&&(i=i.concat(GW.userEvent.of(t.userEvent))),{changes:t.changes instanceof aW?t.changes:aW.of(t.changes||[],n,e.facet(IW)),selection:r&&(r instanceof pW?r:pW.single(r.anchor,r.head)),effects:$W(t.effects),annotations:i,scrollIntoView:!!t.scrollIntoView}}function YW(e,t,n){let r=JW(e,t.length?t[0]:{},e.doc.length);t.length&&t[0].filter===!1&&(n=!1);for(let i=1;i<t.length;i++){t[i].filter===!1&&(n=!1);let a=!!t[i].sequential;r=qW(r,JW(e,t[i],a?r.changes.newLength:e.doc.length),a)}let i=GW.create(e,r.changes,r.selection,r.effects,r.annotations,r.scrollIntoView);return ZW(n?XW(i):i)}function XW(e){let t=e.startState,n=!0;for(let r of t.facet(LW)){let t=r(e);if(t===!1){n=!1;break}Array.isArray(t)&&(n=n===!0?t:KW(n,t))}if(n!==!0){let r,i;if(n===!1)i=e.changes.invertedDesc,r=aW.empty(t.doc.length);else{let t=e.changes.filter(n);r=t.changes,i=t.filtered.mapDesc(t.changes).invertedDesc}e=GW.create(t,r,e.selection&&e.selection.map(i),WW.mapEffects(e.effects,i),e.annotations,e.scrollIntoView)}let r=t.facet(RW);for(let n=r.length-1;n>=0;n--){let i=r[n](e);e=i instanceof GW?i:Array.isArray(i)&&i.length==1&&i[0]instanceof GW?i[0]:YW(t,$W(i),!1)}return e}function ZW(e){let t=e.startState,n=t.facet(zW),r=e;for(let i=n.length-1;i>=0;i--){let a=n[i](e);a&&Object.keys(a).length&&(r=qW(r,JW(t,a,e.changes.newLength),!0))}return r==e?e:GW.create(t,e.changes,e.selection,r.effects,r.annotations,r.scrollIntoView)}var QW=[];function $W(e){return e==null?QW:Array.isArray(e)?e:[e]}var eG=(function(e){return e[e.Word=0]=`Word`,e[e.Space=1]=`Space`,e[e.Other=2]=`Other`,e})(eG||={}),tG=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,nG;try{nG=RegExp(`[\\p{Alphabetic}\\p{Number}_]`,`u`)}catch{}function rG(e){if(nG)return nG.test(e);for(let t=0;t<e.length;t++){let n=e[t];if(/\w/.test(n)||n>``&&(n.toUpperCase()!=n.toLowerCase()||tG.test(n)))return!0}return!1}function iG(e){return t=>{if(!/\S/.test(t))return eG.Space;if(rG(t))return eG.Word;for(let n=0;n<e.length;n++)if(t.indexOf(e[n])>-1)return eG.Word;return eG.Other}}var aG=class e{constructor(e,t,n,r,i,a){this.config=e,this.doc=t,this.selection=n,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=i,a&&(a._state=this);for(let e=0;e<this.config.dynamicSlots.length;e++)MW(this,e<<1);this.computeSlot=null}field(e,t=!0){let n=this.config.address[e.id];if(n==null){if(t)throw RangeError(`Field is not present in this state`);return}return MW(this,n),NW(this,n)}update(...e){return YW(this,e,!0)}applyTransaction(t){let n=this.config,{base:r,compartments:i}=n;for(let e of t.effects)e.is(OW.reconfigure)?(n&&=(i=new Map,n.compartments.forEach((e,t)=>i.set(t,e)),null),i.set(e.value.compartment,e.value.extension)):e.is(WW.reconfigure)?(n=null,r=e.value):e.is(WW.appendConfig)&&(n=null,r=$W(r).concat(e.value));let a;n?a=t.startState.values.slice():(n=AW.resolve(r,i,this),a=new e(n,this.doc,this.selection,n.dynamicSlots.map(()=>null),(e,t)=>t.reconfigure(e,this),null).values);let o=t.startState.facet(FW)?t.newSelection:t.newSelection.asSingle();new e(n,t.newDoc,o,a,(e,n)=>n.update(e,t),t)}replaceSelection(e){return typeof e==`string`&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:pW.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,n=e(t.ranges[0]),r=this.changes(n.changes),i=[n.range],a=$W(n.effects);for(let n=1;n<t.ranges.length;n++){let o=e(t.ranges[n]),s=this.changes(o.changes),c=s.map(r);for(let e=0;e<n;e++)i[e]=i[e].map(c);let l=r.mapDesc(s,!0);i.push(o.range.map(l)),r=r.compose(c),a=WW.mapEffects(a,c).concat(WW.mapEffects($W(o.effects),l))}return{changes:r,selection:pW.create(i,t.mainIndex),effects:a}}changes(t=[]){return t instanceof aW?t:aW.of(t,this.doc.length,this.facet(e.lineSeparator))}toText(t){return zU.of(t.split(this.facet(e.lineSeparator)||nW))}sliceDoc(e=0,t=this.doc.length){return this.doc.sliceString(e,t,this.lineBreak)}facet(e){let t=this.config.address[e.id];return t==null?e.default:(MW(this,t),NW(this,t))}toJSON(e){let t={doc:this.sliceDoc(),selection:this.selection.toJSON()};if(e)for(let n in e){let r=e[n];r instanceof CW&&this.config.address[r.id]!=null&&(t[n]=r.spec.toJSON(this.field(e[n]),this))}return t}static fromJSON(t,n={},r){if(!t||typeof t.doc!=`string`)throw RangeError(`Invalid JSON representation for EditorState`);let i=[];if(r){for(let e in r)if(Object.prototype.hasOwnProperty.call(t,e)){let n=r[e],a=t[e];i.push(n.init(e=>n.spec.fromJSON(a,e)))}}return e.create({doc:t.doc,selection:pW.fromJSON(t.selection),extensions:n.extensions?i.concat([n.extensions]):i})}static create(t={}){let n=AW.resolve(t.extensions||[],new Map),r=t.doc instanceof zU?t.doc:zU.of((t.doc||``).split(n.staticFacet(e.lineSeparator)||nW)),i=t.selection?t.selection instanceof pW?t.selection:pW.single(t.selection.anchor,t.selection.head):pW.single(0);return mW(i,r.length),n.staticFacet(FW)||(i=i.asSingle()),new e(n,r,i,n.dynamicSlots.map(()=>null),(e,t)=>t.create(e),null)}get tabSize(){return this.facet(e.tabSize)}get lineBreak(){return this.facet(e.lineSeparator)||`
|
|
42
|
+
`}get readOnly(){return this.facet(BW)}phrase(t,...n){for(let n of this.facet(e.phrases))if(Object.prototype.hasOwnProperty.call(n,t)){t=n[t];break}return n.length&&(t=t.replace(/\$(\$|\d*)/g,(e,t)=>{if(t==`$`)return`$`;let r=+(t||1);return!r||r>n.length?e:n[r-1]})),t}languageDataAt(e,t,n=-1){let r=[];for(let i of this.facet(PW))for(let a of i(this,t,n))Object.prototype.hasOwnProperty.call(a,e)&&r.push(a[e]);return r}charCategorizer(e){let t=this.languageDataAt(`wordChars`,e);return iG(t.length?t[0]:``)}wordAt(e){let{text:t,from:n,length:r}=this.doc.lineAt(e),i=this.charCategorizer(e),a=e-n,o=e-n;for(;a>0;){let e=XU(t,a,!1);if(i(t.slice(e,a))!=eG.Word)break;a=e}for(;o<r;){let e=XU(t,o);if(i(t.slice(o,e))!=eG.Word)break;o=e}return a==o?null:pW.range(a+n,o+n)}};aG.allowMultipleSelections=FW,aG.tabSize=gW.define({combine:e=>e.length?e[0]:4}),aG.lineSeparator=IW,aG.readOnly=BW,aG.phrases=gW.define({compare(e,t){let n=Object.keys(e),r=Object.keys(t);return n.length==r.length&&n.every(n=>e[n]==t[n])}}),aG.languageData=PW,aG.changeFilter=LW,aG.transactionFilter=RW,aG.transactionExtender=zW,OW.reconfigure=WW.define();function oG(e,t,n={}){let r={};for(let t of e)for(let e of Object.keys(t)){let i=t[e],a=r[e];if(a===void 0)r[e]=i;else if(a!==i&&i!==void 0){if(Object.hasOwnProperty.call(n,e))r[e]=n[e](a,i);else throw Error(`Config merge conflict for field `+e)}}for(let e in t)r[e]===void 0&&(r[e]=t[e]);return r}var sG=class{eq(e){return this==e}range(e,t=e){return lG.create(e,t,this)}};sG.prototype.startSide=sG.prototype.endSide=0,sG.prototype.point=!1,sG.prototype.mapMode=rW.TrackDel;function cG(e,t){return e==t||e.constructor==t.constructor&&e.eq(t)}var lG=class e{constructor(e,t,n){this.from=e,this.to=t,this.value=n}static create(t,n,r){return new e(t,n,r)}};function uG(e,t){return e.from-t.from||e.value.startSide-t.value.startSide}var dG=class e{constructor(e,t,n,r){this.from=e,this.to=t,this.value=n,this.maxPoint=r}get length(){return pG(this.to)}findIndex(e,t,n,r=0){let i=n?this.to:this.from;for(let a=r,o=i.length;;){if(a==o)return a;let r=a+o>>1,s=i[r]-e||(n?this.value[r].endSide:this.value[r].startSide)-t;if(r==a)return s>=0?a:o;s>=0?o=r:a=r+1}}between(e,t,n,r){for(let i=this.findIndex(t,-1e9,!0),a=this.findIndex(n,1e9,!1,i);i<a;i++)if(r(this.from[i]+e,this.to[i]+e,this.value[i])===!1)return!1}map(t,n,r,i,a){let o=[],s=[],c=[],l=-1,u=-1;iter:for(let e=0;e<this.value.length;e++){let d=this.value[e],f=this.from[e]+t,p=this.to[e]+t,m,h;if(f==p){let e=n.mapPos(f,d.startSide,d.mapMode);if(e==null||(m=h=e,d.startSide!=d.endSide&&(h=n.mapPos(f,d.endSide),h<m)))continue}else if(m=n.mapPos(f,d.startSide),h=n.mapPos(p,d.endSide),m>h||m==h&&d.startSide>0&&d.endSide<=0)continue;if(!((h-m||d.endSide-d.startSide)<0)){if(l<0&&(l=m),d.point&&(u=Math.max(u,h-m)),(m-r||d.startSide-i)>=0)o.push(d),s.push(m-l),c.push(h-l),r=h,i=d.endSide;else{if(m==h)for(let e=o.length;e>0;e--){if((m-(c[e-1]+l)||d.startSide-o[e-1].endSide)>=0){o.splice(e,0,d),s.splice(e,0,m-l),c.splice(e,0,h-l);continue iter}if((m-(s[e-1]+l)||d.endSide-o[e-1].startSide)>0)break}a(m,h,d)}}}return{mapped:o.length?new e(s,c,o,u):null,pos:l}}},fG=class e{constructor(e,t,n,r){this.chunkPos=e,this.chunk=t,this.nextLayer=n,this.maxPoint=r}static create(t,n,r,i){return new e(t,n,r,i)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(t){let{add:n=[],sort:r=!1,filterFrom:i=0,filterTo:a=this.length}=t,o=t.filter;if(n.length==0&&!o)return this;if(r&&(n=n.slice().sort(uG)),this.isEmpty)return n.length?e.of(n):this;let s=new _G(this,null,-1).goto(0),c=0,l=[],u=new hG;for(;s.value||c<n.length;)if(c<n.length&&(s.from-n[c].from||s.startSide-n[c].value.startSide)>=0){let e=n[c++];u.addInner(e.from,e.to,e.value,!1)||l.push(e)}else s.rangeIndex==1&&s.chunkIndex<this.chunk.length&&(c==n.length||this.chunkEnd(s.chunkIndex)<n[c].from)&&(!o||i>this.chunkEnd(s.chunkIndex)||a<this.chunkPos[s.chunkIndex])&&u.addChunk(this.chunkPos[s.chunkIndex],this.chunk[s.chunkIndex])?s.nextChunk():((!o||i>s.to||a<s.from||o(s.from,s.to,s.value))&&(u.addInner(s.from,s.to,s.value,!1)||l.push(lG.create(s.from,s.to,s.value))),s.next());return u.finishInner(this.nextLayer.isEmpty&&!l.length?e.empty:this.nextLayer.update({add:l,filter:o,filterFrom:i,filterTo:a}))}map(t){if(t.empty||this.isEmpty)return this;let n=[],r=[],i=-1,a,o=(e,t,n)=>{a||=new hG,a.addRange(e,t,n,!1)};for(let e=0;e<this.chunk.length;e++){let a=this.chunkPos[e],s=this.chunk[e],c=t.touchesRange(a,a+s.length);if(c===!1)i=Math.max(i,s.maxPoint),n.push(s),r.push(t.mapPos(a));else if(c===!0){let[e,c]=n.length?[pG(r)+pG(n).length,pG(pG(n).value).endSide]:[-1,-1],{mapped:l,pos:u}=s.map(a,t,e,c,o);l&&(i=Math.max(i,l.maxPoint),n.push(l),r.push(u))}}let s=this.nextLayer.map(t);return a&&(s=a.finishInner(s)),n.length==0?s:new e(r,n,s||e.empty,i)}between(e,t,n){if(!this.isEmpty){for(let r=0;r<this.chunk.length;r++){let i=this.chunkPos[r],a=this.chunk[r];if(t>=i&&e<=i+a.length&&a.between(i,e-i,t-i,n)===!1)return}this.nextLayer.between(e,t,n)}}iter(e=0){return vG.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return vG.from(e).goto(t)}static compare(e,t,n,r,i=-1){let a=e.filter(e=>e.maxPoint>0||!e.isEmpty&&e.maxPoint>=i),o=t.filter(e=>e.maxPoint>0||!e.isEmpty&&e.maxPoint>=i),s=gG(a,o,n),c=new bG(a,s,i),l=new bG(o,s,i);n.iterGaps((e,t,n)=>xG(c,e,l,t,n,r)),n.empty&&n.length==0&&xG(c,0,l,0,0,r)}static eq(e,t,n=0,r){r??=1e9-1;let i=e.filter(e=>!e.isEmpty&&t.indexOf(e)<0),a=t.filter(t=>!t.isEmpty&&e.indexOf(t)<0);if(i.length!=a.length)return!1;if(!i.length)return!0;let o=gG(i,a),s=new bG(i,o,0).goto(n),c=new bG(a,o,0).goto(n);for(;;){if(s.to!=c.to||!SG(s.active,c.active)||s.point&&(!c.point||!cG(s.point,c.point)))return!1;if(s.to>r)return!0;s.next(),c.next()}}static spans(e,t,n,r,i=-1){let a=new bG(e,null,i).goto(t),o=t,s=a.openStart;for(;;){let e=Math.min(a.to,n);if(a.point){let n=a.activeForPoint(a.to),i=a.pointFrom<t?n.length+1:a.point.startSide<0?n.length:Math.min(n.length,s);r.point(o,e,a.point,n,i,a.pointRank),s=Math.min(a.openEnd(e),n.length)}else e>o&&(r.span(o,e,a.active,s),s=a.openEnd(e));if(a.to>n)return s+(a.point&&a.to>n?1:0);o=a.to,a.next()}}static of(e,t=!1){let n=new hG;for(let r of e instanceof lG?[e]:t?mG(e):e)n.add(r.from,r.to,r.value);return n.finish()}static join(t){if(!t.length)return e.empty;let n=pG(t);for(let r=t.length-2;r>=0;r--)for(let i=t[r];i!=e.empty;i=i.nextLayer)n=new e(i.chunkPos,i.chunk,n,Math.max(i.maxPoint,n.maxPoint));return n}};fG.empty=new fG([],[],null,-1);function pG(e){return e[e.length-1]}function mG(e){if(e.length>1)for(let t=e[0],n=1;n<e.length;n++){let r=e[n];if(uG(t,r)>0)return e.slice().sort(uG);t=r}return e}fG.empty.nextLayer=fG.empty;var hG=class e{finishChunk(e){this.chunks.push(new dG(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(e,t,n){this.addRange(e,t,n,!0)}addRange(t,n,r,i){this.addInner(t,n,r,i)||(this.nextLayer||=new e).addRange(t,n,r,i)}addInner(e,t,n,r){let i=e-this.lastTo||n.startSide-this.last.endSide;if(r&&i<=0&&(e-this.lastFrom||n.startSide-this.last.startSide)<0)throw Error("Ranges must be added sorted by `from` position and `startSide`");return i<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=n,this.lastFrom=e,this.lastTo=t,this.value.push(n),n.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let n=t.value.length-1;return this.last=t.value[n],this.lastFrom=t.from[n]+e,this.lastTo=t.to[n]+e,!0}finish(){return this.finishInner(fG.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=fG.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}};function gG(e,t,n){let r=new Map;for(let t of e)for(let e=0;e<t.chunk.length;e++)t.chunk[e].maxPoint<=0&&r.set(t.chunk[e],t.chunkPos[e]);let i=new Set;for(let e of t)for(let t=0;t<e.chunk.length;t++){let a=r.get(e.chunk[t]);a!=null&&(n?n.mapPos(a):a)==e.chunkPos[t]&&!n?.touchesRange(a,a+e.chunk[t].length)&&i.add(e.chunk[t])}return i}var _G=class{constructor(e,t,n,r=0){this.layer=e,this.skip=t,this.minPoint=n,this.rank=r}get startSide(){return this.value?this.value.startSide:0}get endSide(){return this.value?this.value.endSide:0}goto(e,t=-1e9){return this.chunkIndex=this.rangeIndex=0,this.gotoInner(e,t,!1),this}gotoInner(e,t,n){for(;this.chunkIndex<this.layer.chunk.length;){let t=this.layer.chunk[this.chunkIndex];if(!(this.skip&&this.skip.has(t)||this.layer.chunkEnd(this.chunkIndex)<e||t.maxPoint<this.minPoint))break;this.chunkIndex++,n=!1}if(this.chunkIndex<this.layer.chunk.length){let r=this.layer.chunk[this.chunkIndex].findIndex(e-this.layer.chunkPos[this.chunkIndex],t,!0);(!n||this.rangeIndex<r)&&this.setRangeIndex(r)}this.next()}forward(e,t){(this.to-e||this.endSide-t)<0&&this.gotoInner(e,t,!0)}next(){for(;;)if(this.chunkIndex==this.layer.chunk.length){this.from=this.to=1e9,this.value=null;break}else{let e=this.layer.chunkPos[this.chunkIndex],t=this.layer.chunk[this.chunkIndex],n=e+t.from[this.rangeIndex];if(this.from=n,this.to=e+t.to[this.rangeIndex],this.value=t.value[this.rangeIndex],this.setRangeIndex(this.rangeIndex+1),this.minPoint<0||this.value.point&&this.to-this.from>=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex<this.layer.chunk.length&&this.skip.has(this.layer.chunk[this.chunkIndex]);)this.chunkIndex++;this.rangeIndex=0}else this.rangeIndex=e}nextChunk(){this.chunkIndex++,this.rangeIndex=0,this.next()}compare(e){return this.from-e.from||this.startSide-e.startSide||this.rank-e.rank||this.to-e.to||this.endSide-e.endSide}},vG=class e{constructor(e){this.heap=e}static from(t,n=null,r=-1){let i=[];for(let e=0;e<t.length;e++)for(let a=t[e];!a.isEmpty;a=a.nextLayer)a.maxPoint>=r&&i.push(new _G(a,n,r,e));return i.length==1?i[0]:new e(i)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let n of this.heap)n.goto(e,t);for(let e=this.heap.length>>1;e>=0;e--)yG(this.heap,e);return this.next(),this}forward(e,t){for(let n of this.heap)n.forward(e,t);for(let e=this.heap.length>>1;e>=0;e--)yG(this.heap,e);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),yG(this.heap,0)}}};function yG(e,t){for(let n=e[t];;){let r=(t<<1)+1;if(r>=e.length)break;let i=e[r];if(r+1<e.length&&i.compare(e[r+1])>=0&&(i=e[r+1],r++),n.compare(i)<0)break;e[r]=n,e[t]=i,t=r}}var bG=class{constructor(e,t,n){this.minPoint=n,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=vG.from(e,t,n)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){CG(this.active,e),CG(this.activeTo,e),CG(this.activeRank,e),this.minActive=TG(this.active,this.activeTo)}addActive(e){let t=0,{value:n,to:r,rank:i}=this.cursor;for(;t<this.activeRank.length&&(i-this.activeRank[t]||r-this.activeTo[t])>0;)t++;wG(this.active,t,n),wG(this.activeTo,t,r),wG(this.activeRank,t,i),e&&wG(e,t,this.cursor.from),this.minActive=TG(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let n=this.openStart<0?[]:null;for(;;){let r=this.minActive;if(r>-1&&(this.activeTo[r]-this.cursor.from||this.active[r].endSide-this.cursor.startSide)<0){if(this.activeTo[r]>e){this.to=this.activeTo[r],this.endSide=this.active[r].endSide;break}this.removeActive(r),n&&CG(n,r)}else if(!this.cursor.value){this.to=this.endSide=1e9;break}else if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let e=this.cursor.value;if(!e.point)this.addActive(n),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from<this.cursor.to)this.cursor.next();else{this.point=e,this.pointFrom=this.cursor.from,this.pointRank=this.cursor.rank,this.to=this.cursor.to,this.endSide=e.endSide,this.cursor.next(),this.forward(this.to,this.endSide);break}}}if(n){this.openStart=0;for(let t=n.length-1;t>=0&&n[t]<e;t--)this.openStart++}}activeForPoint(e){if(!this.active.length)return this.active;let t=[];for(let n=this.active.length-1;n>=0&&!(this.activeRank[n]<this.pointRank);n--)(this.activeTo[n]>e||this.activeTo[n]==e&&this.active[n].endSide>=this.point.endSide)&&t.push(this.active[n]);return t.reverse()}openEnd(e){let t=0;for(let n=this.activeTo.length-1;n>=0&&this.activeTo[n]>e;n--)t++;return t}};function xG(e,t,n,r,i,a){e.goto(t),n.goto(r);let o=r+i,s=r,c=r-t,l=!!a.boundChange;for(let t=!1;;){let r=e.to+c-n.to,i=r||e.endSide-n.endSide,u=i<0?e.to+c:n.to,d=Math.min(u,o);if(e.point||n.point?(e.point&&n.point&&cG(e.point,n.point)&&SG(e.activeForPoint(e.to),n.activeForPoint(n.to))||a.comparePoint(s,d,e.point,n.point),t=!1):(t&&a.boundChange(s),d>s&&!SG(e.active,n.active)&&a.compareRange(s,d,e.active,n.active),l&&d<o&&(r||e.openEnd(u)!=n.openEnd(u))&&(t=!0)),u>o)break;s=u,i<=0&&e.next(),i>=0&&n.next()}}function SG(e,t){if(e.length!=t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!=t[n]&&!cG(e[n],t[n]))return!1;return!0}function CG(e,t){for(let n=t,r=e.length-1;n<r;n++)e[n]=e[n+1];e.pop()}function wG(e,t,n){for(let n=e.length-1;n>=t;n--)e[n+1]=e[n];e[t]=n}function TG(e,t){let n=-1,r=1e9;for(let i=0;i<t.length;i++)(t[i]-r||e[i].endSide-e[n].endSide)<0&&(n=i,r=t[i]);return n}var EG=typeof String.prototype.normalize==`function`?e=>e.normalize(`NFKD`):e=>e,DG=class{constructor(e,t,n=0,r=e.length,i,a){this.test=a,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer=``,this.bufferPos=0,this.iter=e.iterRange(n,r),this.bufferStart=n,this.normalize=i?e=>i(EG(e)):EG,this.query=this.normalize(t)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return $U(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let t=eW(e),n=this.bufferStart+this.bufferPos;this.bufferPos+=tW(e);let r=this.normalize(t);if(r.length)for(let e=0,i=n,a=!0;;e++){let n=r.charCodeAt(e),o=this.match(n,i,a,this.bufferPos+this.bufferStart,e==r.length-1);if(o)return this.value=o,this;if(e==r.length-1)break;a&&e<t.length&&t.charCodeAt(e)==n?i++:a=!1}}}match(e,t,n,r,i){let a=null;for(let t=0;t<this.matches.length;){let n=this.matches[t],o=!1;this.query.charCodeAt(n.index)==e&&(n.index==this.query.length-1?a={from:n.from,to:r,precise:i&&n.precise}:(n.index++,o=!0)),o?t++:this.matches.splice(t,1)}return this.query.charCodeAt(0)==e&&(this.query.length==1?a={from:t,to:r,precise:n&&i}:this.matches.push({from:t,index:1,precise:n})),a&&this.test&&!this.test(a.from,a.to,this.buffer,this.bufferStart)&&(a=null),a}};typeof Symbol<`u`&&(DG.prototype[Symbol.iterator]=function(){return this});var OG={from:-1,to:-1,match:/.*/.exec(``),precise:!0},kG=`gm`+(/x/.unicode==null?``:`u`),AG=class{constructor(e,t,n,r=0,i=e.length){if(this.text=e,this.to=i,this.curLine=``,this.done=!1,this.value=OG,/\\[sWDnr]|\n|\r|\[\^/.test(t))return new NG(e,t,n,r,i);this.re=new RegExp(t,kG+(n?.ignoreCase?`i`:``)),this.test=n?.test,this.iter=e.iter();let a=e.lineAt(r);this.curLineStart=a.from,this.matchPos=FG(e,r),this.getLine(this.curLineStart)}getLine(e){this.iter.next(e),this.iter.lineBreak?this.curLine=``:(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine=``:this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let t=this.matchPos<=this.to&&this.re.exec(this.curLine);if(t){let n=this.curLineStart+t.index,r=n+t[0].length;if(this.matchPos=FG(this.text,r+ +(n==r)),n==this.curLineStart+this.curLine.length&&this.nextLine(),(n<r||n>this.value.to)&&(!this.test||this.test(n,r,t)))return this.value={from:n,to:r,precise:!0,match:t},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),e=0;else return this.done=!0,this}}},jG=new WeakMap,MG=class e{constructor(e,t){this.from=e,this.text=t}get to(){return this.from+this.text.length}static get(t,n,r){let i=jG.get(t);if(!i||i.from>=r||i.to<=n){let i=new e(n,t.sliceString(n,r));return jG.set(t,i),i}if(i.from==n&&i.to==r)return i;let{text:a,from:o}=i;return o>n&&(a=t.sliceString(n,o)+a,o=n),i.to<r&&(a+=t.sliceString(i.to,r)),jG.set(t,new e(o,a)),new e(n,a.slice(n-o,r-o))}},NG=class{constructor(e,t,n,r,i){this.text=e,this.to=i,this.done=!1,this.value=OG,this.matchPos=FG(e,r),this.re=new RegExp(t,kG+(n?.ignoreCase?`i`:``)),this.test=n?.test,this.flat=MG.get(e,r,this.chunkEnd(r+5e3))}chunkEnd(e){return e>=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,t=this.re.exec(this.flat.text);if(t&&!t[0]&&t.index==e&&(this.re.lastIndex=e+1,t=this.re.exec(this.flat.text)),t){let e=this.flat.from+t.index,n=e+t[0].length;if((this.flat.to>=this.to||t.index+t[0].length<=this.flat.text.length-10)&&(!this.test||this.test(e,n,t)))return this.value={from:e,to:n,precise:!0,match:t},this.matchPos=FG(this.text,n+ +(e==n)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=MG.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}};typeof Symbol<`u`&&(AG.prototype[Symbol.iterator]=NG.prototype[Symbol.iterator]=function(){return this});function PG(e){try{return new RegExp(e,kG),!0}catch{return!1}}function FG(e,t){if(t>=e.length)return t;let n=e.lineAt(t),r;for(;t<n.to&&(r=n.text.charCodeAt(t-n.from))>=56320&&r<57344;)t++;return t}var IG=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:i}=uL(e,{label:t.phrase(`Go to line`),input:{type:`text`,name:`line`,value:n},focus:!0,submitLabel:t.phrase(`go`)});return i.then(n=>{let i=n&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(n.elements.line.value);if(!i){e.dispatch({effects:r});return}let a=t.doc.lineAt(t.selection.main.head),[,o,s,c,l]=i,u=c?+c.slice(1):0,d=s?+s:a.number;if(s&&l){let e=d/100;o&&(e=e*(o==`-`?-1:1)+a.number/t.doc.lines),d=Math.round(t.doc.lines*e)}else s&&o&&(d=d*(o==`-`?-1:1)+a.number);let f=t.doc.line(Math.max(1,Math.min(t.doc.lines,d))),p=pW.cursor(f.from+Math.max(0,Math.min(u,f.length)));e.dispatch({effects:[r,SF.scrollIntoView(p.from,{y:`center`})],selection:p})}),!0},LG={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},RG=gW.define({combine(e){return oG(e,LG,{highlightWordAroundCursor:(e,t)=>e||t,minSelectionLength:Math.min,maxMatches:Math.min})}});function zG(e){let t=[GG,WG];return e&&t.push(RG.of(e)),t}var BG=UA.mark({class:`cm-selectionMatch`}),VG=UA.mark({class:`cm-selectionMatch cm-selectionMatch-main`});function HG(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=eG.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=eG.Word)}function UG(e,t,n,r){return e(t.sliceDoc(n,n+1))==eG.Word&&e(t.sliceDoc(r-1,r))==eG.Word}var WG=pM.fromClass(class{constructor(e){this.decorations=this.getDeco(e)}update(e){(e.selectionSet||e.docChanged||e.viewportChanged)&&(this.decorations=this.getDeco(e.view))}getDeco(e){let t=e.state.facet(RG),{state:n}=e,r=n.selection;if(r.ranges.length>1)return UA.none;let i=r.main,a,o=null;if(i.empty){if(!t.highlightWordAroundCursor)return UA.none;let e=n.wordAt(i.head);if(!e)return UA.none;o=n.charCategorizer(i.head),a=n.sliceDoc(e.from,e.to)}else{let e=i.to-i.from;if(e<t.minSelectionLength||e>200)return UA.none;if(t.wholeWords){if(a=n.sliceDoc(i.from,i.to),o=n.charCategorizer(i.head),!(HG(o,n,i.from,i.to)&&UG(o,n,i.from,i.to)))return UA.none}else if(a=n.sliceDoc(i.from,i.to),!a)return UA.none}let s=[];for(let r of e.visibleRanges){let e=new DG(n.doc,a,r.from,r.to);for(;!e.next().done;){let{from:r,to:a}=e.value;if((!o||HG(o,n,r,a))&&(i.empty&&r<=i.from&&a>=i.to?s.push(VG.range(r,a)):(r>=i.to||a<=i.from)&&s.push(BG.range(r,a)),s.length>t.maxMatches))return UA.none}}return UA.set(s)}},{decorations:e=>e.decorations}),GG=SF.baseTheme({".cm-selectionMatch":{backgroundColor:`#99ff7780`},".cm-searchMatch .cm-selectionMatch":{backgroundColor:`transparent`}}),KG=({state:e,dispatch:t})=>{let{selection:n}=e,r=pW.create(n.ranges.map(t=>e.wordAt(t.head)||pW.cursor(t.head)),n.mainIndex);return!r.eq(n)&&(t(e.update({selection:r})),!0)};function qG(e,t){let{main:n,ranges:r}=e.selection,i=e.wordAt(n.head),a=i&&i.from==n.from&&i.to==n.to;for(let n=!1,i=new DG(e.doc,t,r[r.length-1].to);;)if(i.next(),i.done){if(n)return null;i=new DG(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),n=!0}else{if(n&&r.some(e=>e.from==i.value.from))continue;if(a){let t=e.wordAt(i.value.from);if(!t||t.from!=i.value.from||t.to!=i.value.to)continue}return i.value}}var JG=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(e=>e.from===e.to))return KG({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(t=>e.sliceDoc(t.from,t.to)!=r))return!1;let i=qG(e,r);return i?(t(e.update({selection:e.selection.addRange(pW.range(i.from,i.to),!1),effects:SF.scrollIntoView(i.to)})),!0):!1},YG=gW.define({combine(e){return oG(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new kK(e),scrollToMatch:e=>SF.scrollIntoView(e)})}}),XG=class{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||``,this.valid=!!this.search&&(!this.regexp||PG(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord,this.test=e.test}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(e,t)=>t==`n`?`
|
|
43
|
+
`:t==`r`?`\r`:t==`t`?` `:`\\`)}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord&&this.test==e.test}create(){return this.regexp?new sK(this):new tK(this)}getCursor(e,t=0,n){let r=e.doc?e:aG.create({doc:e});return n??=r.doc.length,this.regexp?rK(this,r,t,n):$G(this,r,t,n)}},ZG=class{constructor(e){this.spec=e}};function QG(e,t,n){return(r,i,a,o)=>n&&!n(r,i,a,o)?!1:e(r>=o&&i<=o+a.length?a.slice(r-o,i-o):t.doc.sliceString(r,i),t,r,i)}function $G(e,t,n,r){let i;return e.wholeWord&&(i=eK(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(i=QG(e.test,t,i)),new DG(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:e=>e.toLowerCase(),i)}function eK(e,t){return(n,r,i,a)=>((a>n||a+i.length<r)&&(a=Math.max(0,n-2),i=e.sliceString(a,Math.min(e.length,r+2))),(t(iK(i,n-a))!=eG.Word||t(aK(i,n-a))!=eG.Word)&&(t(aK(i,r-a))!=eG.Word||t(iK(i,r-a))!=eG.Word))}var tK=class extends ZG{constructor(e){super(e)}nextMatch(e,t,n){let r=$G(this.spec,e,n,e.doc.length).nextOverlapping();if(r.done){let n=Math.min(e.doc.length,t+this.spec.unquoted.length);r=$G(this.spec,e,0,n).nextOverlapping()}return r.done||r.value.from==t&&r.value.to==n?null:r.value}prevMatchInRange(e,t,n){for(let r=n;;){let n=Math.max(t,r-1e4-this.spec.unquoted.length),i=$G(this.spec,e,n,r),a=null;for(;!i.nextOverlapping().done;)a=i.value;if(a)return a;if(n==t)return null;r-=1e4}}prevMatch(e,t,n){let r=this.prevMatchInRange(e,0,t);return r||=this.prevMatchInRange(e,Math.max(0,n-this.spec.unquoted.length),e.doc.length),r&&(r.from!=t||r.to!=n)?r:null}getReplacement(e){return this.spec.unquote(this.spec.replace)}matchAll(e,t){let n=$G(this.spec,e,0,e.doc.length),r=[];for(;!n.next().done;){if(r.length>=t)return null;r.push(n.value)}return r}highlight(e,t,n,r){let i=$G(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(n+this.spec.unquoted.length,e.doc.length));for(;!i.next().done;)r(i.value.from,i.value.to)}};function nK(e,t,n){return(r,i,a)=>(!n||n(r,i,a))&&e(a[0],t,r,i)}function rK(e,t,n,r){let i;return e.wholeWord&&(i=oK(t.charCategorizer(t.selection.main.head))),e.test&&(i=nK(e.test,t,i)),new AG(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:i},n,r)}function iK(e,t){return e.slice(XU(e,t,!1),t)}function aK(e,t){return e.slice(t,XU(e,t))}function oK(e){return(t,n,r)=>!r[0].length||(e(iK(r.input,r.index))!=eG.Word||e(aK(r.input,r.index))!=eG.Word)&&(e(aK(r.input,r.index+r[0].length))!=eG.Word||e(iK(r.input,r.index+r[0].length))!=eG.Word)}var sK=class extends ZG{nextMatch(e,t,n){let r=rK(this.spec,e,n,e.doc.length).next();return r.done&&(r=rK(this.spec,e,0,t).next()),r.done?null:r.value}prevMatchInRange(e,t,n){for(let r=1;;r++){let i=Math.max(t,n-r*1e4),a=rK(this.spec,e,i,n),o=null;for(;!a.next().done;)o=a.value;if(o&&(i==t||o.from>i+10))return o;if(i==t)return null}}prevMatch(e,t,n){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,n,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(t,n)=>{if(n==`&`)return e.match[0];if(n==`$`)return`$`;for(let t=n.length;t>0;t--){let r=+n.slice(0,t);if(r>0&&r<e.match.length)return e.match[r]+n.slice(t)}return t})}matchAll(e,t){let n=rK(this.spec,e,0,e.doc.length),r=[];for(;!n.next().done;){if(r.length>=t)return null;r.push(n.value)}return r}highlight(e,t,n,r){let i=rK(this.spec,e,Math.max(0,t-250),Math.min(n+250,e.doc.length));for(;!i.next().done;)r(i.value.from,i.value.to)}},cK=WW.define(),lK=WW.define(),uK=CW.define({create(e){return new dK(CK(e).create(),null)},update(e,t){for(let n of t.effects)n.is(cK)?e=new dK(n.value.create(),e.panel):n.is(lK)&&(e=new dK(e.query,n.value?SK:null));return e},provide:e=>lL.from(e,e=>e.panel)}),dK=class{constructor(e,t){this.query=e,this.panel=t}},fK=UA.mark({class:`cm-searchMatch`}),pK=UA.mark({class:`cm-searchMatch cm-searchMatch-selected`}),mK=pM.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(uK))}update(e){let t=e.state.field(uK);(t!=e.startState.field(uK)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return UA.none;let{view:n}=this,r=new hG;for(let t=0,i=n.visibleRanges,a=i.length;t<a;t++){let{from:o,to:s}=i[t];for(;t<a-1&&s>i[t+1].from-500;)s=i[++t].to;e.highlight(n.state,o,s,(e,t)=>{let i=n.state.selection.ranges.some(n=>n.from==e&&n.to==t);r.add(e,t,i?pK:fK)})}return r.finish()}},{decorations:e=>e.decorations});function hK(e){return t=>{let n=t.state.field(uK,!1);return n&&n.query.spec.valid?e(t,n):EK(t)}}var gK=hK((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let i=pW.single(r.from,r.to),a=e.state.facet(YG);return e.dispatch({selection:i,effects:[NK(e,r),a.scrollToMatch(i.main,e)],userEvent:`select.search`}),TK(e),!0}),_K=hK((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,i=t.prevMatch(n,r,r);if(!i)return!1;let a=pW.single(i.from,i.to),o=e.state.facet(YG);return e.dispatch({selection:a,effects:[NK(e,i),o.scrollToMatch(a.main,e)],userEvent:`select.search`}),TK(e),!0}),vK=hK((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:pW.create(n.map(e=>pW.range(e.from,e.to))),userEvent:`select.search.matches`}),!0)}),yK=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:i}=n.main,a=[],o=0;for(let t=new DG(e.doc,e.sliceDoc(r,i));!t.next().done;){if(a.length>1e3)return!1;t.value.from==r&&(o=a.length),a.push(pW.range(t.value.from,t.value.to))}return t(e.update({selection:pW.create(a,o),userEvent:`select.search.matches`})),!0},bK=hK((e,{query:t})=>{let{state:n}=e,{from:r,to:i}=n.selection.main;if(n.readOnly)return!1;let a=t.nextMatch(n,r,r);if(!a)return!1;let o=a,s=[],c,l,u=[];o.precise?o.from==r&&o.to==i&&(l=n.toText(t.getReplacement(o)),s.push({from:o.from,to:o.to,insert:l}),o=t.nextMatch(n,o.from,o.to),u.push(SF.announce.of(n.phrase(`replaced match on line $`,n.doc.lineAt(r).number)+`.`))):o=t.nextMatch(n,o.from,o.to);let d=e.state.changes(s);return o&&(c=pW.single(o.from,o.to).map(d),u.push(NK(e,o)),u.push(n.facet(YG).scrollToMatch(c.main,e))),e.dispatch({changes:d,selection:c,effects:u,userEvent:`input.replace`}),!0}),xK=hK((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let r of t.matchAll(e.state,1e9)){let{from:e,to:i,precise:a}=r;a&&n.push({from:e,to:i,insert:t.getReplacement(r)})}if(!n.length)return!1;let r=e.state.phrase(`replaced $ matches`,n.length)+`.`;return e.dispatch({changes:n,effects:SF.announce.of(r),userEvent:`input.replace.all`}),!0});function SK(e){return e.state.facet(YG).createPanel(e)}function CK(e,t){let n=e.selection.main,r=n.empty||n.to>n.from+100?``:e.sliceDoc(n.from,n.to);if(t&&!r)return t;let i=e.facet(YG);return new XG({search:t?.literal??i.literal?r:r.replace(/\n/g,`\\n`),caseSensitive:t?.caseSensitive??i.caseSensitive,literal:t?.literal??i.literal,regexp:t?.regexp??i.regexp,wholeWord:t?.wholeWord??i.wholeWord})}function wK(e){let t=aL(e,SK);return t&&t.dom.querySelector(`[main-field]`)}function TK(e){let t=wK(e);t&&t==e.root.activeElement&&t.select()}var EK=e=>{let t=e.state.field(uK,!1);if(t&&t.panel){let n=wK(e);if(n&&n!=e.root.activeElement){let r=CK(e.state,t.query.spec);r.valid&&e.dispatch({effects:cK.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[lK.of(!0),t?cK.of(CK(e.state,t.query.spec)):WW.appendConfig.of(FK)]});return!0},DK=e=>{let t=e.state.field(uK,!1);if(!t||!t.panel)return!1;let n=aL(e,SK);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:lK.of(!1)}),!0},OK=[{key:`Mod-f`,run:EK,scope:`editor search-panel`},{key:`F3`,run:gK,shift:_K,scope:`editor search-panel`,preventDefault:!0},{key:`Mod-g`,run:gK,shift:_K,scope:`editor search-panel`,preventDefault:!0},{key:`Escape`,run:DK,scope:`editor search-panel`},{key:`Mod-Shift-l`,run:yK},{key:`Mod-Alt-g`,run:IG},{key:`Mod-d`,run:JG,preventDefault:!0}],kK=class{constructor(e){this.view=e;let t=this.query=e.state.field(uK).query.spec;this.commit=this.commit.bind(this),this.searchField=xA(`input`,{value:t.search,placeholder:AK(e,`Find`),"aria-label":AK(e,`Find`),class:`cm-textfield`,name:`search`,form:``,"main-field":`true`,onchange:this.commit,onkeyup:this.commit}),this.replaceField=xA(`input`,{value:t.replace,placeholder:AK(e,`Replace`),"aria-label":AK(e,`Replace`),class:`cm-textfield`,name:`replace`,form:``,onchange:this.commit,onkeyup:this.commit}),this.caseField=xA(`input`,{type:`checkbox`,name:`case`,form:``,checked:t.caseSensitive,onchange:this.commit}),this.reField=xA(`input`,{type:`checkbox`,name:`re`,form:``,checked:t.regexp,onchange:this.commit}),this.wordField=xA(`input`,{type:`checkbox`,name:`word`,form:``,checked:t.wholeWord,onchange:this.commit});function n(e,t,n){return xA(`button`,{class:`cm-button`,name:e,onclick:t,type:`button`},n)}this.dom=xA(`div`,{onkeydown:e=>this.keydown(e),class:`cm-search`},[this.searchField,n(`next`,()=>gK(e),[AK(e,`next`)]),n(`prev`,()=>_K(e),[AK(e,`previous`)]),n(`select`,()=>vK(e),[AK(e,`all`)]),xA(`label`,null,[this.caseField,AK(e,`match case`)]),xA(`label`,null,[this.reField,AK(e,`regexp`)]),xA(`label`,null,[this.wordField,AK(e,`by word`)]),...e.state.readOnly?[]:[xA(`br`),this.replaceField,n(`replace`,()=>bK(e),[AK(e,`replace`)]),n(`replaceAll`,()=>xK(e),[AK(e,`replace all`)])],xA(`button`,{name:`close`,onclick:()=>DK(e),"aria-label":AK(e,`close`),type:`button`},[`×`])])}commit(){let e=new XG({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});e.eq(this.query)||(this.query=e,this.view.dispatch({effects:cK.of(e)}))}keydown(e){PF(this.view,e,`search-panel`)?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?_K:gK)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),bK(this.view))}update(e){for(let t of e.transactions)for(let e of t.effects)e.is(cK)&&!e.value.eq(this.query)&&this.setQuery(e.value)}setQuery(e){this.query=e,this.searchField.value=e.search,this.replaceField.value=e.replace,this.caseField.checked=e.caseSensitive,this.reField.checked=e.regexp,this.wordField.checked=e.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(YG).top}};function AK(e,t){return e.state.phrase(t)}var jK=30,MK=/[\s\.,:;?!]/;function NK(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),i=e.state.doc.lineAt(n).to,a=Math.max(r.from,t-jK),o=Math.min(i,n+jK),s=e.state.sliceDoc(a,o);if(a!=r.from){for(let e=0;e<jK;e++)if(!MK.test(s[e+1])&&MK.test(s[e])){s=s.slice(e);break}}if(o!=i){for(let e=s.length-1;e>s.length-jK;e--)if(!MK.test(s[e-1])&&MK.test(s[e])){s=s.slice(0,e);break}}return SF.announce.of(`${e.state.phrase(`current match`)}. ${s} ${e.state.phrase(`on line`)} ${r.number}.`)}var PK=SF.baseTheme({".cm-panel.cm-search":{padding:`2px 6px 4px`,position:`relative`,"& [name=close]":{position:`absolute`,top:`0`,right:`4px`,backgroundColor:`inherit`,border:`none`,font:`inherit`,padding:0,margin:0},"& input, & button, & label":{margin:`.2em .6em .2em 0`},"& input[type=checkbox]":{marginRight:`.2em`},"& label":{fontSize:`80%`,whiteSpace:`pre`}},"&light .cm-searchMatch":{backgroundColor:`#ffff0054`},"&dark .cm-searchMatch":{backgroundColor:`#00ffff8a`},"&light .cm-searchMatch-selected":{backgroundColor:`#ff6a0054`},"&dark .cm-searchMatch-selected":{backgroundColor:`#ff00ff8a`}}),FK=[uK,EW.low(mK),PK],IK=class{constructor(e,t,n,r){this.state=e,this.pos=t,this.explicit=n,this.view=r,this.abortListeners=[],this.abortOnDocChange=!1}tokenBefore(e){let t=rz(this.state).resolveInner(this.pos,-1);for(;t&&e.indexOf(t.name)<0;)t=t.parent;return t?{from:t.from,to:this.pos,text:this.state.sliceDoc(t.from,this.pos),type:t.type}:null}matchBefore(e){let t=this.state.doc.lineAt(this.pos),n=Math.max(t.from,this.pos-250),r=t.text.slice(n-t.from,this.pos-t.from),i=r.search(UK(e,!1));return i<0?null:{from:n+i,to:this.pos,text:r.slice(i)}}get aborted(){return this.abortListeners==null}addEventListener(e,t,n){e==`abort`&&this.abortListeners&&(this.abortListeners.push(t),n&&n.onDocChange&&(this.abortOnDocChange=!0))}};function LK(e){let t=Object.keys(e).join(``),n=/\w/.test(t);return n&&(t=t.replace(/\w/g,``)),`[${n?`\\w`:``}${t.replace(/[^\w\s]/g,`\\$&`)}]`}function RK(e){let t=Object.create(null),n=Object.create(null);for(let{label:r}of e){t[r[0]]=!0;for(let e=1;e<r.length;e++)n[r[e]]=!0}let r=LK(t)+LK(n)+`*$`;return[RegExp(`^`+r),new RegExp(r)]}function zK(e){let t=e.map(e=>typeof e==`string`?{label:e}:e),[n,r]=t.every(e=>/^\w+$/.test(e.label))?[/\w*$/,/\w+$/]:RK(t);return e=>{let i=e.matchBefore(r);return i||e.explicit?{from:i?i.from:e.pos,options:t,validFor:n}:null}}function BK(e,t){return n=>{for(let t=rz(n.state).resolveInner(n.pos,-1);t;t=t.parent){if(e.indexOf(t.name)>-1)return null;if(t.type.isTop)break}return t(n)}}var VK=class{constructor(e,t,n,r){this.completion=e,this.source=t,this.match=n,this.score=r}};function HK(e){return e.selection.main.from}function UK(e,t){let{source:n}=e,r=t&&n[0]!=`^`,i=n[n.length-1]!=`$`;return!r&&!i?e:RegExp(`${r?`^`:``}(?:${n})${i?`$`:``}`,e.flags??(e.ignoreCase?`i`:``))}var WK=Ok.define();function GK(e,t,n,r){let{main:i}=e.selection,a=n-i.from,o=r-i.from;return{...e.changeByRange(s=>{if(s!=i&&n!=r&&e.sliceDoc(s.from+a,s.from+o)!=e.sliceDoc(n,r))return{range:s};let c=e.toText(t);return{changes:{from:s.from+a,to:r==i.from?s.to:s.from+o,insert:c},range:Q.cursor(s.from+a+c.length)}}),scrollIntoView:!0,userEvent:`input.complete`}}var KK=new WeakMap;function qK(e){if(!Array.isArray(e))return e;let t=KK.get(e);return t||KK.set(e,t=zK(e)),t}var JK=jk.define(),YK=jk.define(),XK=class{constructor(e){this.pattern=e,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let t=0;t<e.length;){let n=VO(e,t),r=UO(n);this.chars.push(n);let i=e.slice(t,t+r),a=i.toUpperCase();this.folded.push(VO(a==i?i.toLowerCase():a,0)),t+=r}this.astral=e.length!=this.chars.length}ret(e,t){return this.score=e,this.matched=t,this}match(e){if(this.pattern.length==0)return this.ret(-100,[]);if(e.length<this.pattern.length)return null;let{chars:t,folded:n,any:r,precise:i,byWord:a}=this;if(t.length==1){let r=VO(e,0),i=UO(r),a=i==e.length?0:-100;if(r!=t[0]){if(r==n[0])a+=-200;else return null}return this.ret(a,[0,i])}let o=e.indexOf(this.pattern);if(o==0)return this.ret(e.length==this.pattern.length?0:-100,[0,this.pattern.length]);let s=t.length,c=0;if(o<0){for(let i=0,a=Math.min(e.length,200);i<a&&c<s;){let a=VO(e,i);(a==t[c]||a==n[c])&&(r[c++]=i),i+=UO(a)}if(c<s)return null}let l=0,u=0,d=!1,f=0,p=-1,m=-1,h=/[a-z]/.test(e),g=!0;for(let r=0,c=Math.min(e.length,200),_=0;r<c&&u<s;){let c=VO(e,r);o<0&&(l<s&&c==t[l]&&(i[l++]=r),f<s&&(c==t[f]||c==n[f]?(f==0&&(p=r),m=r+1,f++):f=0));let v,y=c<255?c>=48&&c<=57||c>=97&&c<=122?2:+(c>=65&&c<=90):(v=HO(c))==v.toLowerCase()?v==v.toUpperCase()?0:2:1;(!r||y==1&&h||_==0&&y!=0)&&(t[u]==c||n[u]==c&&(d=!0)?a[u++]=r:a.length&&(g=!1)),_=y,r+=UO(c)}return u==s&&a[0]==0&&g?this.result(-100+(d?-200:0),a,e):f==s&&p==0?this.ret(-200-e.length+(m==e.length?0:-100),[0,m]):o>-1?this.ret(-700-e.length,[o,o+this.pattern.length]):f==s?this.ret(-900-e.length,[p,m]):u==s?this.result(-100+(d?-200:0)+-700+(g?0:-1100),a,e):t.length==2?null:this.result((r[0]?-700:0)+-200+-1100,r,e)}result(e,t,n){let r=[],i=0;for(let e of t){let t=e+(this.astral?UO(VO(n,e)):1);i&&r[i-1]==e?r[i-1]=t:(r[i++]=e,r[i++]=t)}return this.ret(e-n.length,r)}},ZK=class{constructor(e){this.pattern=e,this.matched=[],this.score=0,this.folded=e.toLowerCase()}match(e){if(e.length<this.pattern.length)return null;let t=e.slice(0,this.pattern.length),n=t==this.pattern?0:t.toLowerCase()==this.folded?-200:null;return n==null?null:(this.matched=[0,t.length],this.score=n+(e.length==this.pattern.length?0:-100),this)}},QK=rk.define({combine(e){return qk(e,{activateOnTyping:!0,activateOnCompletion:()=>!1,activateOnTypingDelay:100,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>``,optionClass:()=>``,aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:eq,filterStrict:!1,compareCompletions:(e,t)=>(e.sortText||e.label).localeCompare(t.sortText||t.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(e,t)=>e&&t,closeOnBlur:(e,t)=>e&&t,icons:(e,t)=>e&&t,tooltipClass:(e,t)=>n=>$K(e(n),t(n)),optionClass:(e,t)=>n=>$K(e(n),t(n)),addToOptions:(e,t)=>e.concat(t),filterStrict:(e,t)=>e||t})}});function $K(e,t){return e?t?e+` `+t:e:t}function eq(e,t,n,r,i,a){let o=e.textDirection==Tj.RTL,s=o,c=!1,l=`top`,u,d,f=t.left-i.left,p=i.right-t.right,m=r.right-r.left,h=r.bottom-r.top;if(s&&f<Math.min(m,p)?s=!1:!s&&p<Math.min(m,f)&&(s=!0),m<=(s?f:p))u=Math.max(i.top,Math.min(n.top,i.bottom-h))-t.top,d=Math.min(400,s?f:p);else{c=!0,d=Math.min(400,(o?t.right:i.right-t.left)-30);let e=i.bottom-t.bottom;e>=h||e>t.top?u=n.bottom-t.top:(l=`bottom`,u=t.bottom-n.top)}let g=(t.bottom-t.top)/a.offsetHeight,_=(t.right-t.left)/a.offsetWidth;return{style:`${l}: ${u/g}px; max-width: ${d/_}px`,class:`cm-completionInfo-`+(c?o?`left-narrow`:`right-narrow`:s?`left`:`right`)}}var tq=jk.define();function nq(e){let t=e.addToOptions.slice();return e.icons&&t.push({render(e){let t=document.createElement(`div`);return t.classList.add(`cm-completionIcon`),e.type&&t.classList.add(...e.type.split(/\s+/g).map(e=>`cm-completionIcon-`+e)),t.setAttribute(`aria-hidden`,`true`),t},position:20}),t.push({render(e,t,n,r){let i=document.createElement(`span`);i.className=`cm-completionLabel`;let a=e.displayLabel||e.label,o=0;for(let e=0;e<r.length;){let t=r[e++],n=r[e++];t>o&&i.appendChild(document.createTextNode(a.slice(o,t)));let s=i.appendChild(document.createElement(`span`));s.appendChild(document.createTextNode(a.slice(t,n))),s.className=`cm-completionMatchedText`,o=n}return o<a.length&&i.appendChild(document.createTextNode(a.slice(o))),i},position:50},{render(e){if(!e.detail)return null;let t=document.createElement(`span`);return t.className=`cm-completionDetail`,t.textContent=e.detail,t},position:80}),t.sort((e,t)=>e.position-t.position).map(e=>e.render)}function rq(e,t,n){if(e<=n)return{from:0,to:e};if(t<0&&(t=0),t<=e>>1){let e=Math.floor(t/n);return{from:e*n,to:(e+1)*n}}let r=Math.ceil((e-t)/n);return{from:e-r*n,to:e-(r-1)*n}}var iq=class{constructor(e,t,n){this.view=e,this.stateField=t,this.applyCompletion=n,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:e=>this.placeInfo(e),key:this},this.space=null,this.currentClass=``;let r=e.state.field(t),{options:i,selected:a}=r.open,o=e.state.facet(QK);this.optionContent=nq(o),this.optionClass=o.optionClass,this.tooltipClass=o.tooltipClass,this.range=rq(i.length,a,o.maxRenderedOptions),this.dom=document.createElement(`div`),this.dom.className=`cm-tooltip-autocomplete`,this.updateTooltipClass(e.state),this.dom.addEventListener(`mousedown`,n=>{let{options:r}=e.state.field(t).open;for(let t=n.target,i;t&&t!=this.dom;t=t.parentNode)if(t.nodeName==`LI`&&(i=/-(\d+)$/.exec(t.id))&&+i[1]<r.length){this.applyCompletion(e,r[+i[1]]),n.preventDefault();return}if(n.target==this.list){let t=this.list.classList.contains(`cm-completionListIncompleteTop`)&&n.clientY<this.list.firstChild.getBoundingClientRect().top?this.range.from-1:this.list.classList.contains(`cm-completionListIncompleteBottom`)&&n.clientY>this.list.lastChild.getBoundingClientRect().bottom?this.range.to:null;t!=null&&(e.dispatch({effects:tq.of(t)}),n.preventDefault())}}),this.dom.addEventListener(`focusout`,t=>{let n=e.state.field(this.stateField,!1);n&&n.tooltip&&e.state.facet(QK).closeOnBlur&&t.relatedTarget!=e.contentDOM&&e.dispatch({effects:YK.of(null)})}),this.showOptions(i,r.id)}mount(){this.updateSel()}showOptions(e,t){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(e,t,this.range)),this.list.addEventListener(`scroll`,()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}update(e){let t=e.state.field(this.stateField),n=e.startState.field(this.stateField);if(this.updateTooltipClass(e.state),t!=n){let{options:r,selected:i,disabled:a}=t.open;(!n.open||n.open.options!=r)&&(this.range=rq(r.length,i,e.state.facet(QK).maxRenderedOptions),this.showOptions(r,t.id)),this.updateSel(),a!=n.open?.disabled&&this.dom.classList.toggle(`cm-tooltip-autocomplete-disabled`,!!a)}}updateTooltipClass(e){let t=this.tooltipClass(e);if(t!=this.currentClass){for(let e of this.currentClass.split(` `))e&&this.dom.classList.remove(e);for(let e of t.split(` `))e&&this.dom.classList.add(e);this.currentClass=t}}positioned(e){this.space=e,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let e=this.view.state.field(this.stateField),t=e.open;(t.selected>-1&&t.selected<this.range.from||t.selected>=this.range.to)&&(this.range=rq(t.options.length,t.selected,this.view.state.facet(QK).maxRenderedOptions),this.showOptions(t.options,e.id));let n=this.updateSelectedOption(t.selected);if(n){this.destroyInfo();let{completion:r}=t.options[t.selected],{info:i}=r;if(!i)return;let a=typeof i==`string`?document.createTextNode(i):i(r);if(!a)return;`then`in a?a.then(t=>{t&&this.view.state.field(this.stateField,!1)==e&&this.addInfoPane(t,r)}).catch(e=>lM(this.view.state,e,`completion info`)):(this.addInfoPane(a,r),n.setAttribute(`aria-describedby`,this.info.id))}}addInfoPane(e,t){this.destroyInfo();let n=this.info=document.createElement(`div`);if(n.className=`cm-tooltip cm-completionInfo`,n.id=`cm-completionInfo-`+Math.floor(Math.random()*65535).toString(16),e.nodeType!=null)n.appendChild(e),this.infoDestroy=null;else{let{dom:t,destroy:r}=e;n.appendChild(t),this.infoDestroy=r||null}this.dom.appendChild(n),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(e){let t=null;for(let n=this.list.firstChild,r=this.range.from;n;n=n.nextSibling,r++)n.nodeName!=`LI`||!n.id?r--:r==e?n.hasAttribute(`aria-selected`)||(n.setAttribute(`aria-selected`,`true`),t=n):n.hasAttribute(`aria-selected`)&&(n.removeAttribute(`aria-selected`),n.removeAttribute(`aria-describedby`));return t&&oq(this.list,t),t}measureInfo(){let e=this.dom.querySelector(`[aria-selected]`);if(!e||!this.info)return null;let t=this.dom.getBoundingClientRect(),n=this.info.getBoundingClientRect(),r=e.getBoundingClientRect(),i=this.space;if(!i){let e=this.dom.ownerDocument.documentElement;i={left:0,top:0,right:e.clientWidth,bottom:e.clientHeight}}return r.top>Math.min(i.bottom,t.bottom)-10||r.bottom<Math.max(i.top,t.top)+10?null:this.view.state.facet(QK).positionInfo(this.view,t,r,n,i,this.dom)}placeInfo(e){this.info&&(e?(e.style&&(this.info.style.cssText=e.style),this.info.className=`cm-tooltip cm-completionInfo `+(e.class||``)):this.info.style.cssText=`top: -1e6px`)}createListBox(e,t,n){let r=document.createElement(`ul`);r.id=t,r.setAttribute(`role`,`listbox`),r.setAttribute(`aria-expanded`,`true`),r.setAttribute(`aria-label`,this.view.state.phrase(`Completions`)),r.addEventListener(`mousedown`,e=>{e.target==r&&e.preventDefault()});let i=null;for(let a=n.from;a<n.to;a++){let{completion:o,match:s}=e[a],{section:c}=o;if(c){let e=typeof c==`string`?c:c.name;if(e!=i&&(a>n.from||n.from==0)){if(i=e,typeof c!=`string`&&c.header)r.appendChild(c.header(c));else{let t=r.appendChild(document.createElement(`completion-section`));t.textContent=e}}}let l=r.appendChild(document.createElement(`li`));l.id=t+`-`+a,l.setAttribute(`role`,`option`);let u=this.optionClass(o);u&&(l.className=u);for(let e of this.optionContent){let t=e(o,this.view.state,this.view,s);t&&l.appendChild(t)}}return n.from&&r.classList.add(`cm-completionListIncompleteTop`),n.to<e.length&&r.classList.add(`cm-completionListIncompleteBottom`),r}destroyInfo(){this.info&&=(this.infoDestroy&&this.infoDestroy(),this.info.remove(),null)}destroy(){this.destroyInfo()}};function aq(e,t){return n=>new iq(n,e,t)}function oq(e,t){let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i=n.height/e.offsetHeight;r.top<n.top?e.scrollTop-=(n.top-r.top)/i:r.bottom>n.bottom&&(e.scrollTop+=(r.bottom-n.bottom)/i)}function sq(e){return(e.boost||0)*100+(e.apply?10:0)+(e.info?5:0)+ +!!e.type}function cq(e,t){let n=[],r=null,i=null,a=e=>{n.push(e);let{section:t}=e.completion;if(t){r||=[];let e=typeof t==`string`?t:t.name;r.some(t=>t.name==e)||r.push(typeof t==`string`?{name:e}:t)}},o=t.facet(QK);for(let r of e)if(r.hasResult()){let e=r.result.getMatch;if(r.result.filter===!1)for(let t of r.result.options)a(new VK(t,r.source,e?e(t):[],1e9-n.length));else{let n=t.sliceDoc(r.from,r.to),s,c=o.filterStrict?new ZK(n):new XK(n);for(let t of r.result.options)if(s=c.match(t.label)){let n=t.displayLabel?e?e(t,s.matched):[]:s.matched,o=s.score+(t.boost||0);if(a(new VK(t,r.source,n,o)),typeof t.section==`object`&&t.section.rank===`dynamic`){let{name:e}=t.section;i||=Object.create(null),i[e]=Math.max(o,i[e]||-1e9)}}}}if(r){let e=Object.create(null),t=0,a=(e,t)=>(e.rank===`dynamic`&&t.rank===`dynamic`?i[t.name]-i[e.name]:0)||(typeof e.rank==`number`?e.rank:1e9)-(typeof t.rank==`number`?t.rank:1e9)||(e.name<t.name?-1:1);for(let n of r.sort(a))t-=1e5,e[n.name]=t;for(let t of n){let{section:n}=t.completion;n&&(t.score+=e[typeof n==`string`?n:n.name])}}let s=[],c=null,l=o.compareCompletions;for(let e of n.sort((e,t)=>t.score-e.score||l(e.completion,t.completion))){let t=e.completion;!c||c.label!=t.label||c.detail!=t.detail||c.type!=null&&t.type!=null&&c.type!=t.type||c.apply!=t.apply||c.boost!=t.boost?s.push(e):sq(e.completion)>sq(c)&&(s[s.length-1]=e),c=e.completion}return s}var lq=class e{constructor(e,t,n,r,i,a){this.options=e,this.attrs=t,this.tooltip=n,this.timestamp=r,this.selected=i,this.disabled=a}setSelected(t,n){return t==this.selected||t>=this.options.length?this:new e(this.options,mq(n,t),this.tooltip,this.timestamp,t,this.disabled)}static build(t,n,r,i,a,o){if(i&&!o&&t.some(e=>e.isPending))return i.setDisabled();let s=cq(t,n);if(!s.length)return i&&t.some(e=>e.isPending)?i.setDisabled():null;let c=n.facet(QK).selectOnOpen?0:-1;if(i&&i.selected!=c&&i.selected!=-1){let e=i.options[i.selected].completion;for(let t=0;t<s.length;t++)if(s[t].completion==e){c=t;break}}return new e(s,mq(r,c),{pos:t.reduce((e,t)=>t.hasResult()?Math.min(e,t.from):e,1e8),create:Cq,above:a.aboveCursor},i?i.timestamp:Date.now(),c,!1)}map(t){return new e(this.options,this.attrs,{...this.tooltip,pos:t.mapPos(this.tooltip.pos)},this.timestamp,this.selected,this.disabled)}setDisabled(){return new e(this.options,this.attrs,this.tooltip,this.timestamp,this.selected,!0)}},uq=class e{constructor(e,t,n){this.active=e,this.id=t,this.open=n}static start(){return new e(hq,`cm-ac-`+Math.floor(Math.random()*2e6).toString(36),null)}update(t){let{state:n}=t,r=n.facet(QK),i=(r.override||n.languageDataAt(`autocomplete`,HK(n)).map(qK)).map(e=>(this.active.find(t=>t.source==e)||new _q(e,+!!this.active.some(e=>e.state!=0))).update(t,r));i.length==this.active.length&&i.every((e,t)=>e==this.active[t])&&(i=this.active);let a=this.open,o=t.effects.some(e=>e.is(bq));a&&t.docChanged&&(a=a.map(t.changes)),t.selection||i.some(e=>e.hasResult()&&t.changes.touchesRange(e.from,e.to))||!dq(i,this.active)||o?a=lq.build(i,n,this.id,a,r,o):a&&a.disabled&&!i.some(e=>e.isPending)&&(a=null),!a&&i.every(e=>!e.isPending)&&i.some(e=>e.hasResult())&&(i=i.map(e=>e.hasResult()?new _q(e.source,0):e));for(let e of t.effects)e.is(tq)&&(a&&=a.setSelected(e.value,this.id));return i==this.active&&a==this.open?this:new e(i,this.id,a)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?fq:pq}};function dq(e,t){if(e==t)return!0;for(let n=0,r=0;;){for(;n<e.length&&!e[n].hasResult();)n++;for(;r<t.length&&!t[r].hasResult();)r++;let i=n==e.length,a=r==t.length;if(i||a)return i==a;if(e[n++].result!=t[r++].result)return!1}}var fq={"aria-autocomplete":`list`},pq={};function mq(e,t){let n={"aria-autocomplete":`list`,"aria-haspopup":`listbox`,"aria-controls":e};return t>-1&&(n[`aria-activedescendant`]=e+`-`+t),n}var hq=[];function gq(e,t){if(e.isUserEvent(`input.complete`)){let n=e.annotation(WK);if(n&&t.activateOnCompletion(n))return 12}let n=e.isUserEvent(`input.type`);return n&&t.activateOnTyping?5:n?1:e.isUserEvent(`delete.backward`)?2:e.selection?8:e.docChanged?16:0}var _q=class e{constructor(e,t,n=!1){this.source=e,this.state=t,this.explicit=n}hasResult(){return!1}get isPending(){return this.state==1}update(t,n){let r=gq(t,n),i=this;(r&8||r&16&&this.touches(t))&&(i=new e(i.source,0)),r&4&&i.state==0&&(i=new e(this.source,1)),i=i.updateFor(t,r);for(let n of t.effects)if(n.is(JK))i=new e(i.source,1,n.value);else if(n.is(YK))i=new e(i.source,0);else if(n.is(bq))for(let e of n.value)e.source==i.source&&(i=e);return i}updateFor(e,t){return this.map(e.changes)}map(e){return this}touches(e){return e.changes.touchesRange(HK(e.state))}},vq=class e extends _q{constructor(e,t,n,r,i,a){super(e,3,t),this.limit=n,this.result=r,this.from=i,this.to=a}hasResult(){return!0}updateFor(t,n){if(!(n&3))return this.map(t.changes);let r=this.result;r.map&&!t.changes.empty&&(r=r.map(r,t.changes));let i=t.changes.mapPos(this.from),a=t.changes.mapPos(this.to,1),o=HK(t.state);if(o>a||!r||n&2&&(HK(t.startState)==this.from||o<this.limit))return new _q(this.source,n&4?1:0);let s=t.changes.mapPos(this.limit);return yq(r.validFor,t.state,i,a)?new e(this.source,this.explicit,s,r,i,a):r.update&&(r=r.update(r,i,a,new IK(t.state,o,!1)))?new e(this.source,this.explicit,s,r,r.from,r.to??HK(t.state)):new _q(this.source,1,this.explicit)}map(t){if(t.empty)return this;let n=this.result.map?this.result.map(this.result,t):this.result;return n?new e(this.source,this.explicit,t.mapPos(this.limit),n,t.mapPos(this.from),t.mapPos(this.to,1)):new _q(this.source,0)}touches(e){return e.changes.touchesRange(this.from,this.to)}};function yq(e,t,n,r){if(!e)return!1;let i=t.sliceDoc(n,r);return typeof e==`function`?e(i,n,r,t):UK(e,!0).test(i)}var bq=jk.define({map(e,t){return e.map(e=>e.map(t))}}),xq=uk.define({create(){return uq.start()},update(e,t){return e.update(t)},provide:e=>[GI.from(e,e=>e.tooltip),SF.contentAttributes.from(e,e=>e.attrs)]});function Sq(e,t){let n=t.completion.apply||t.completion.label,r=e.state.field(xq).active.find(e=>e.source==t.source);return r instanceof vq&&(typeof n==`string`?e.dispatch({...GK(e.state,n,r.from,r.to),annotations:WK.of(t.completion)}):n(e,t.completion,r.from,r.to),!0)}var Cq=aq(xq,Sq);function wq(e,t=`option`){return n=>{let r=n.state.field(xq,!1);if(!r||!r.open||r.open.disabled||Date.now()-r.open.timestamp<n.state.facet(QK).interactionDelay)return!1;let i=1,a;t==`page`&&(a=nL(n,r.open.tooltip))&&(i=Math.max(2,Math.floor(a.dom.offsetHeight/a.dom.querySelector(`li`).offsetHeight)-1));let{length:o}=r.open.options,s=r.open.selected>-1?r.open.selected+i*(e?1:-1):e?0:o-1;return s<0?s=t==`page`?0:o-1:s>=o&&(s=t==`page`?o-1:0),n.dispatch({effects:tq.of(s)}),!0}}var Tq=e=>{let t=e.state.field(xq,!1);return e.state.readOnly||!t||!t.open||t.open.selected<0||t.open.disabled||Date.now()-t.open.timestamp<e.state.facet(QK).interactionDelay?!1:Sq(e,t.open.options[t.open.selected])},Eq=e=>e.state.field(xq,!1)?(e.dispatch({effects:JK.of(!0)}),!0):!1,Dq=e=>{let t=e.state.field(xq,!1);return!t||!t.active.some(e=>e.state!=0)?!1:(e.dispatch({effects:YK.of(null)}),!0)},Oq=class{constructor(e,t){this.active=e,this.context=t,this.time=Date.now(),this.updates=[],this.done=void 0}},kq=50,Aq=1e3,jq=pM.fromClass(class{constructor(e){this.view=e,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let t of e.state.field(xq).active)t.isPending&&this.startQuery(t)}update(e){let t=e.state.field(xq),n=e.state.facet(QK);if(!e.selectionSet&&!e.docChanged&&e.startState.field(xq)==t)return;let r=e.transactions.some(e=>{let t=gq(e,n);return t&8||(e.selection||e.docChanged)&&!(t&3)});for(let t=0;t<this.running.length;t++){let n=this.running[t];if(r||n.context.abortOnDocChange&&e.docChanged||n.updates.length+e.transactions.length>kq&&Date.now()-n.time>Aq){for(let e of n.context.abortListeners)try{e()}catch(e){lM(this.view.state,e)}n.context.abortListeners=null,this.running.splice(t--,1)}else n.updates.push(...e.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),e.transactions.some(e=>e.effects.some(e=>e.is(JK)))&&(this.pendingStart=!0);let i=this.pendingStart?50:n.activateOnTypingDelay;if(this.debounceUpdate=t.active.some(e=>e.isPending&&!this.running.some(t=>t.active.source==e.source))?setTimeout(()=>this.startUpdate(),i):-1,this.composing!=0)for(let t of e.transactions)t.isUserEvent(`input.type`)?this.composing=2:this.composing==2&&t.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:e}=this.view,t=e.field(xq);for(let e of t.active)e.isPending&&!this.running.some(t=>t.active.source==e.source)&&this.startQuery(e);this.running.length&&t.open&&t.open.disabled&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(QK).updateSyncTime))}startQuery(e){let{state:t}=this.view,n=new IK(t,HK(t),e.explicit,this.view),r=new Oq(e,n);this.running.push(r),Promise.resolve(e.source(n)).then(e=>{r.context.aborted||(r.done=e||null,this.scheduleAccept())},e=>{this.view.dispatch({effects:YK.of(null)}),lM(this.view.state,e)})}scheduleAccept(){this.running.every(e=>e.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(QK).updateSyncTime))}accept(){this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],t=this.view.state.facet(QK),n=this.view.state.field(xq);for(let r=0;r<this.running.length;r++){let i=this.running[r];if(i.done===void 0)continue;if(this.running.splice(r--,1),i.done){let n=HK(i.updates.length?i.updates[0].startState:this.view.state),r=Math.min(n,i.done.from+ +!i.active.explicit),a=new vq(i.active.source,i.active.explicit,r,i.done,i.done.from,i.done.to??n);for(let e of i.updates)a=a.update(e,t);if(a.hasResult()){e.push(a);continue}}let a=n.active.find(e=>e.source==i.active.source);if(a&&a.isPending){if(i.done==null){let n=new _q(i.active.source,0);for(let e of i.updates)n=n.update(e,t);n.isPending||e.push(n)}else this.startQuery(a)}}(e.length||n.open&&n.open.disabled)&&this.view.dispatch({effects:bq.of(e)})}},{eventHandlers:{blur(e){let t=this.view.state.field(xq,!1);if(t&&t.tooltip&&this.view.state.facet(QK).closeOnBlur){let n=t.open&&nL(this.view,t.open.tooltip);(!n||!n.dom.contains(e.relatedTarget))&&setTimeout(()=>this.view.dispatch({effects:YK.of(null)}),10)}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:JK.of(!1)}),20),this.composing=0}}}),Mq=typeof navigator==`object`&&/Win/.test(navigator.platform),Nq=pk.highest(SF.domEventHandlers({keydown(e,t){let n=t.state.field(xq,!1);if(!n||!n.open||n.open.disabled||n.open.selected<0||e.key.length>1||e.ctrlKey&&!(Mq&&e.altKey)||e.metaKey)return!1;let r=n.open.options[n.open.selected],i=n.active.find(e=>e.source==r.source),a=r.completion.commitCharacters||i.result.commitCharacters;return a&&a.indexOf(e.key)>-1&&Sq(t,r),!1}})),Pq=SF.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:`monospace`,whiteSpace:`nowrap`,overflow:`hidden auto`,maxWidth_fallback:`700px`,maxWidth:`min(700px, 95vw)`,minWidth:`250px`,maxHeight:`10em`,height:`100%`,listStyle:`none`,margin:0,padding:0,"& > li, & > completion-section":{padding:`1px 3px`,lineHeight:1.2},"& > li":{overflowX:`hidden`,textOverflow:`ellipsis`,cursor:`pointer`},"& > completion-section":{display:`list-item`,borderBottom:`1px solid silver`,paddingLeft:`0.5em`,opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:`#17c`,color:`white`},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:`#777`},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:`#347`,color:`white`},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:`#444`},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:`"···"`,opacity:.5,display:`block`,textAlign:`center`,cursor:`pointer`},".cm-tooltip.cm-completionInfo":{position:`absolute`,padding:`3px 9px`,width:`max-content`,maxWidth:`400px`,boxSizing:`border-box`,whiteSpace:`pre-line`},".cm-completionInfo.cm-completionInfo-left":{right:`100%`},".cm-completionInfo.cm-completionInfo-right":{left:`100%`},".cm-completionInfo.cm-completionInfo-left-narrow":{right:`30px`},".cm-completionInfo.cm-completionInfo-right-narrow":{left:`30px`},"&light .cm-snippetField":{backgroundColor:`#00000022`},"&dark .cm-snippetField":{backgroundColor:`#ffffff22`},".cm-snippetFieldPosition":{verticalAlign:`text-top`,width:0,height:`1.15em`,display:`inline-block`,margin:`0 -0.7px -.7em`,borderLeft:`1.4px dotted #888`},".cm-completionMatchedText":{textDecoration:`underline`},".cm-completionDetail":{marginLeft:`0.5em`,fontStyle:`italic`},".cm-completionIcon":{fontSize:`90%`,width:`.8em`,display:`inline-block`,textAlign:`center`,paddingRight:`.6em`,opacity:`0.6`,boxSizing:`content-box`},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:`'ƒ'`}},".cm-completionIcon-class":{"&:after":{content:`'○'`}},".cm-completionIcon-interface":{"&:after":{content:`'◌'`}},".cm-completionIcon-variable":{"&:after":{content:`'𝑥'`}},".cm-completionIcon-constant":{"&:after":{content:`'𝐶'`}},".cm-completionIcon-type":{"&:after":{content:`'𝑡'`}},".cm-completionIcon-enum":{"&:after":{content:`'∪'`}},".cm-completionIcon-property":{"&:after":{content:`'□'`}},".cm-completionIcon-keyword":{"&:after":{content:`'🔑︎'`}},".cm-completionIcon-namespace":{"&:after":{content:`'▢'`}},".cm-completionIcon-text":{"&:after":{content:`'abc'`,fontSize:`50%`,verticalAlign:`middle`}}}),Fq=class{constructor(e,t,n,r){this.field=e,this.line=t,this.from=n,this.to=r}},Iq=class e{constructor(e,t,n){this.field=e,this.from=t,this.to=n}map(t){let n=t.mapPos(this.from,-1,GO.TrackDel),r=t.mapPos(this.to,1,GO.TrackDel);return n==null||r==null?null:new e(this.field,n,r)}},Lq=class e{constructor(e,t){this.lines=e,this.fieldPositions=t}instantiate(e,t){let n=[],r=[t],i=e.doc.lineAt(t),a=/^\s*/.exec(i.text)[0];for(let i of this.lines){if(n.length){let n=a,o=/^\t*/.exec(i)[0].length;for(let t=0;t<o;t++)n+=e.facet(hz);r.push(t+n.length-o),i=n+i.slice(o)}n.push(i),t+=i.length+1}return{text:n,ranges:this.fieldPositions.map(e=>new Iq(e.field,r[e.line]+e.from,r[e.line]+e.to))}}static parse(t){let n=[],r=[],i=[],a;for(let e of t.split(/\r\n?|\n/)){for(;a=/[#$]\{(?:(\d+)(?::([^{}]*))?|((?:\\[{}]|[^{}])*))\}/.exec(e);){let t=a[1]?+a[1]:null,o=a[2]||a[3]||``,s=-1;t===0&&(t=1e9);let c=o.replace(/\\[{}]/g,e=>e[1]);for(let e=0;e<n.length;e++)(t==null?c&&n[e].name==c:n[e].seq==t)&&(s=e);if(s<0){let e=0;for(;e<n.length&&(t==null||n[e].seq!=null&&n[e].seq<t);)e++;n.splice(e,0,{seq:t,name:c}),s=e;for(let e of i)e.field>=s&&e.field++}for(let e of i)if(e.line==r.length&&e.from>a.index){let t=a[2]?3+(a[1]||``).length:2;e.from-=t,e.to-=t}i.push(new Fq(s,r.length,a.index,a.index+c.length)),e=e.slice(0,a.index)+o+e.slice(a.index+a[0].length)}e=e.replace(/\\([{}])/g,(e,t,n)=>{for(let e of i)e.line==r.length&&e.from>n&&(e.from--,e.to--);return t}),r.push(e)}return new e(r,i)}},Rq=UA.widget({widget:new class extends VA{toDOM(){let e=document.createElement(`span`);return e.className=`cm-snippetFieldPosition`,e}ignoreEvent(){return!1}}}),zq=UA.mark({class:`cm-snippetField`}),Bq=class e{constructor(e,t){this.ranges=e,this.active=t,this.deco=UA.set(e.map(e=>(e.from==e.to?Rq:zq).range(e.from,e.to)),!0)}map(t){let n=[];for(let e of this.ranges){let r=e.map(t);if(!r)return null;n.push(r)}return new e(n,this.active)}selectionInsideField(e){return e.ranges.every(e=>this.ranges.some(t=>t.field==this.active&&t.from<=e.from&&t.to>=e.to))}},Vq=jk.define({map(e,t){return e&&e.map(t)}}),Hq=jk.define(),Uq=uk.define({create(){return null},update(e,t){for(let n of t.effects){if(n.is(Vq))return n.value;if(n.is(Hq)&&e)return new Bq(e.ranges,n.value)}return e&&t.docChanged&&(e=e.map(t.changes)),e&&t.selection&&!e.selectionInsideField(t.selection)&&(e=null),e},provide:e=>SF.decorations.from(e,e=>e?e.deco:UA.none)});function Wq(e,t){return Q.create(e.filter(e=>e.field==t).map(e=>Q.range(e.from,e.to)))}function Gq(e){let t=Lq.parse(e);return(e,n,r,i)=>{let{text:a,ranges:o}=t.instantiate(e.state,r),{main:s}=e.state.selection,c={changes:{from:r,to:i==s.from?s.to:i,insert:DO.of(a)},scrollIntoView:!0,annotations:n?[WK.of(n),Mk.userEvent.of(`input.complete`)]:void 0};if(o.length&&(c.selection=Wq(o,0)),o.some(e=>e.field>0)){let t=new Bq(o,0),n=c.effects=[Vq.of(t)];e.state.field(Uq,!1)===void 0&&n.push(jk.appendConfig.of([Uq,Yq,Zq,Pq]))}e.dispatch(e.state.update(c))}}function Kq(e){return({state:t,dispatch:n})=>{let r=t.field(Uq,!1);if(!r||e<0&&r.active==0)return!1;let i=r.active+e,a=e>0&&!r.ranges.some(t=>t.field==i+e);return n(t.update({selection:Wq(r.ranges,i),effects:Vq.of(a?null:new Bq(r.ranges,i)),scrollIntoView:!0})),!0}}var qq=[{key:`Tab`,run:Kq(1),shift:Kq(-1)},{key:`Escape`,run:({state:e,dispatch:t})=>e.field(Uq,!1)?(t(e.update({effects:Vq.of(null)})),!0):!1}],Jq=rk.define({combine(e){return e.length?e[0]:qq}}),Yq=pk.highest(jF.compute([Jq],e=>e.facet(Jq)));function Xq(e,t){return{...t,apply:Gq(e)}}var Zq=SF.domEventHandlers({mousedown(e,t){let n=t.state.field(Uq,!1),r;if(!n||(r=t.posAtCoords({x:e.clientX,y:e.clientY}))==null)return!1;let i=n.ranges.find(e=>e.from<=r&&e.to>=r);return!i||i.field==n.active?!1:(t.dispatch({selection:Wq(n.ranges,i.field),effects:Vq.of(n.ranges.some(e=>e.field>i.field)?new Bq(n.ranges,i.field):null),scrollIntoView:!0}),!0)}}),Qq={brackets:[`(`,`[`,`{`,`'`,`"`],before:`)]}:;>`,stringPrefixes:[]},$q=jk.define({map(e,t){return t.mapPos(e,-1,GO.TrackAfter)??void 0}}),eJ=new class extends Jk{};eJ.startSide=1,eJ.endSide=-1;var tJ=uk.define({create(){return $k.empty},update(e,t){if(e=e.map(t.changes),t.selection){let n=t.state.doc.lineAt(t.selection.main.head);e=e.update({filter:e=>e>=n.from&&e<=n.to})}for(let n of t.effects)n.is($q)&&(e=e.update({add:[eJ.range(n.value,n.value+1)]}));return e}});function nJ(){return[sJ,tJ]}var rJ=`()[]{}<>«»»«[]{}`;function iJ(e){for(let t=0;t<16;t+=2)if(rJ.charCodeAt(t)==e)return rJ.charAt(t+1);return HO(e<128?e:e+1)}function aJ(e,t){return e.languageDataAt(`closeBrackets`,t)[0]||Qq}var oJ=typeof navigator==`object`&&/Android\b/.test(navigator.userAgent),sJ=SF.inputHandler.of((e,t,n,r)=>{if((oJ?e.composing:e.compositionStarted)||e.state.readOnly)return!1;let i=e.state.selection.main;if(r.length>2||r.length==2&&UO(VO(r,0))==1||t!=i.from||n!=i.to)return!1;let a=lJ(e.state,r);return a?(e.dispatch(a),!0):!1}),cJ=[{key:`Backspace`,run:({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=aJ(e,e.selection.main.head).brackets||Qq.brackets,r=null,i=e.changeByRange(t=>{if(t.empty){let r=fJ(e.doc,t.head);for(let i of n)if(i==r&&dJ(e.doc,t.head)==iJ(VO(i,0)))return{changes:{from:t.head-i.length,to:t.head+i.length},range:Q.cursor(t.head-i.length)}}return{range:r=t}});return r||t(e.update(i,{scrollIntoView:!0,userEvent:`delete.backward`})),!r}}];function lJ(e,t){let n=aJ(e,e.selection.main.head),r=n.brackets||Qq.brackets;for(let i of r){let a=iJ(VO(i,0));if(t==i)return a==i?hJ(e,i,r.indexOf(i+i+i)>-1,n):pJ(e,i,a,n.before||Qq.before);if(t==a&&uJ(e,e.selection.main.from))return mJ(e,i,a)}return null}function uJ(e,t){let n=!1;return e.field(tJ).between(0,e.doc.length,e=>{e==t&&(n=!0)}),n}function dJ(e,t){let n=e.sliceString(t,t+2);return n.slice(0,UO(VO(n,0)))}function fJ(e,t){let n=e.sliceString(t-2,t);return UO(VO(n,0))==n.length?n:n.slice(1)}function pJ(e,t,n,r){let i=null,a=e.changeByRange(a=>{if(!a.empty)return{changes:[{insert:t,from:a.from},{insert:n,from:a.to}],effects:$q.of(a.to+t.length),range:Q.range(a.anchor+t.length,a.head+t.length)};let o=dJ(e.doc,a.head);return!o||/\s/.test(o)||r.indexOf(o)>-1?{changes:{insert:t+n,from:a.head},effects:$q.of(a.head+t.length),range:Q.cursor(a.head+t.length)}:{range:i=a}});return i?null:e.update(a,{scrollIntoView:!0,userEvent:`input.type`})}function mJ(e,t,n){let r=null,i=e.changeByRange(t=>t.empty&&dJ(e.doc,t.head)==n?{changes:{from:t.head,to:t.head+n.length,insert:n},range:Q.cursor(t.head+n.length)}:r={range:t});return r?null:e.update(i,{scrollIntoView:!0,userEvent:`input.type`})}function hJ(e,t,n,r){let i=r.stringPrefixes||Qq.stringPrefixes,a=null,o=e.changeByRange(r=>{if(!r.empty)return{changes:[{insert:t,from:r.from},{insert:t,from:r.to}],effects:$q.of(r.to+t.length),range:Q.range(r.anchor+t.length,r.head+t.length)};let o=r.head,s=dJ(e.doc,o),c;if(s==t){if(gJ(e,o))return{changes:{insert:t+t,from:o},effects:$q.of(o+t.length),range:Q.cursor(o+t.length)};if(uJ(e,o)){let r=n&&e.sliceDoc(o,o+t.length*3)==t+t+t?t+t+t:t;return{changes:{from:o,to:o+r.length,insert:r},range:Q.cursor(o+r.length)}}}else if(n&&e.sliceDoc(o-2*t.length,o)==t+t&&(c=vJ(e,o-2*t.length,i))>-1&&gJ(e,c))return{changes:{insert:t+t+t+t,from:o},effects:$q.of(o+t.length),range:Q.cursor(o+t.length)};else if(e.charCategorizer(o)(s)!=Vk.Word&&vJ(e,o,i)>-1&&!_J(e,o,t,i))return{changes:{insert:t+t,from:o},effects:$q.of(o+t.length),range:Q.cursor(o+t.length)};return{range:a=r}});return a?null:e.update(o,{scrollIntoView:!0,userEvent:`input.type`})}function gJ(e,t){let n=rz(e).resolveInner(t+1);return n.parent&&n.from==t}function _J(e,t,n,r){let i=rz(e).resolveInner(t,-1),a=r.reduce((e,t)=>Math.max(e,t.length),0);for(let o=0;o<5;o++){let o=e.sliceDoc(i.from,Math.min(i.to,i.from+n.length+a)),s=o.indexOf(n);if(!s||s>-1&&r.indexOf(o.slice(0,s))>-1){let t=i.firstChild;for(;t&&t.from==i.from&&t.to-t.from>n.length+s;){if(e.sliceDoc(t.to-n.length,t.to)==n)return!1;t=t.firstChild}return!0}let c=i.to==t&&i.parent;if(!c)break;i=c}return!1}function vJ(e,t,n){let r=e.charCategorizer(t);if(r(e.sliceDoc(t-1,t))!=Vk.Word)return t;for(let i of n){let n=t-i.length;if(e.sliceDoc(n,t)==i&&r(e.sliceDoc(n-1,n))!=Vk.Word)return n}return-1}function yJ(e={}){return[Nq,xq,QK.of(e),jq,xJ,Pq]}var bJ=[{key:`Ctrl-Space`,run:Eq},{mac:"Alt-`",run:Eq},{mac:`Alt-i`,run:Eq},{key:`Escape`,run:Dq},{key:`ArrowDown`,run:wq(!0)},{key:`ArrowUp`,run:wq(!1)},{key:`PageDown`,run:wq(!0,`page`)},{key:`PageUp`,run:wq(!1,`page`)},{key:`Enter`,run:Tq}],xJ=pk.highest(jF.computeN([QK],e=>e.facet(QK).defaultKeymap?[bJ]:[])),SJ=class{constructor(e,t,n){this.from=e,this.to=t,this.diagnostic=n}},CJ=class e{constructor(e,t,n){this.diagnostics=e,this.panel=t,this.selected=n}static init(t,n,r){let i=r.facet(LJ).markerFilter;i&&(t=i(t,r));let a=t.slice().sort((e,t)=>e.from-t.from||e.to-t.to),o=new tA,s=[],c=0,l=r.doc.iter(),u=0,d=r.doc.length;for(let e=0;;){let t=e==a.length?null:a[e];if(!t&&!s.length)break;let n,r;if(s.length)n=c,r=s.reduce((e,t)=>Math.min(e,t.to),t&&t.from>n?t.from:1e8);else{if(n=t.from,n>d)break;r=t.to,s.push(t),e++}for(;e<a.length;){let t=a[e];if(t.from==n&&(t.to>t.from||t.to==n))s.push(t),e++,r=Math.min(t.to,r);else{r=Math.min(t.from,r);break}}r=Math.min(r,d);let i=!1;if(s.some(e=>e.from==n&&(e.to==r||r==d))&&(i=n==r,!i&&r-n<10)){let e=n-(u+l.value.length);e>0&&(l.next(e),u=n);for(let e=n;;){if(e>=r){i=!0;break}if(!l.lineBreak&&u+l.value.length>e)break;e=u+l.value.length,u+=l.value.length,l.next()}}let f=JJ(s);if(i)o.add(n,n,UA.widget({widget:new VJ(f),diagnostics:s.slice()}));else{let e=s.reduce((e,t)=>t.markClass?e+` `+t.markClass:e,``);o.add(n,r,UA.mark({class:`cm-lintRange cm-lintRange-`+f+e,diagnostics:s.slice(),inclusiveEnd:s.some(e=>e.to>r)}))}if(c=r,c==d)break;for(let e=0;e<s.length;e++)s[e].to<=c&&s.splice(e--,1)}let f=o.finish();return new e(f,n,wJ(f))}};function wJ(e,t=null,n=0){let r=null;return e.between(n,1e9,(e,n,{spec:i})=>{if(!(t&&i.diagnostics.indexOf(t)<0)){if(!r)r=new SJ(e,n,t||i.diagnostics[0]);else if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;else r=new SJ(r.from,n,r.diagnostic)}}),r}function TJ(e,t){let n=t.pos,r=t.end||n,i=e.state.facet(LJ).hideOn(e,n,r);if(i!=null)return i;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(e=>e.is(DJ))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function EJ(e,t){return e.field(AJ,!1)?t:t.concat(jk.appendConfig.of(XJ))}var DJ=jk.define(),OJ=jk.define(),kJ=jk.define(),AJ=uk.define({create(){return new CJ(UA.none,null,null)},update(e,t){if(t.docChanged&&e.diagnostics.size){let n=e.diagnostics.map(t.changes),r=null,i=e.panel;if(e.selected){let i=t.changes.mapPos(e.selected.from,1);r=wJ(n,e.selected.diagnostic,i)||wJ(n,null,i)}!n.size&&i&&t.state.facet(LJ).autoPanel&&(i=null),e=new CJ(n,i,r)}for(let n of t.effects)if(n.is(DJ)){let r=t.state.facet(LJ).autoPanel?n.value.length?UJ.open:null:e.panel;e=CJ.init(n.value,r,t.state)}else n.is(OJ)?e=new CJ(e.diagnostics,n.value?UJ.open:null,e.selected):n.is(kJ)&&(e=new CJ(e.diagnostics,e.panel,n.value));return e},provide:e=>[lL.from(e,e=>e.panel),SF.decorations.from(e,e=>e.diagnostics)]}),jJ=UA.mark({class:`cm-lintRange cm-lintRange-active`});function MJ(e,t,n){let{diagnostics:r}=e.state.field(AJ),i,a=-1,o=-1;r.between(t-+(n<0),t+ +(n>0),(e,r,{spec:s})=>{if(t>=e&&t<=r&&(e==r||(t>e||n>0)&&(t<r||n<0)))return i=s.diagnostics,a=e,o=r,!1});let s=e.state.facet(LJ).tooltipFilter;return i&&s&&(i=s(i,e.state)),i?{pos:a,end:o,above:!0,create(){return{dom:NJ(e,i)}}}:null}function NJ(e,t){return xA(`ul`,{class:`cm-tooltip-lint`},t.map(t=>BJ(e,t,!1)))}var PJ=e=>{let t=e.state.field(AJ,!1);(!t||!t.panel)&&e.dispatch({effects:EJ(e.state,[OJ.of(!0)])});let n=aL(e,UJ.open);return n&&n.dom.querySelector(`.cm-panel-lint ul`).focus(),!0},FJ=e=>{let t=e.state.field(AJ,!1);return!t||!t.panel?!1:(e.dispatch({effects:OJ.of(!1)}),!0)},IJ=[{key:`Mod-Shift-m`,run:PJ,preventDefault:!0},{key:`F8`,run:e=>{let t=e.state.field(AJ,!1);if(!t)return!1;let n=e.state.selection.main,r=wJ(t.diagnostics,null,n.to+1);return!r&&(r=wJ(t.diagnostics,null,0),!r||r.from==n.from&&r.to==n.to)?!1:(e.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0}),tL(e,r.from,1,{tooltip:YJ,until:e=>e.docChanged||e.newSelection.main.head<r.from||e.newSelection.main.head>r.to}),!0)}}],LJ=rk.define({combine(e){return{sources:e.map(e=>e.source).filter(e=>e!=null),...qk(e.map(e=>e.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:RJ,tooltipFilter:RJ,needsRefresh:(e,t)=>e?t?n=>e(n)||t(n):e:t,hideOn:(e,t)=>e?t?(n,r,i)=>e(n,r,i)||t(n,r,i):e:t,autoPanel:(e,t)=>e||t})}}});function RJ(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function zJ(e){let t=[];if(e)actions:for(let{name:n}of e){for(let e=0;e<n.length;e++){let r=n[e];if(/[a-zA-Z]/.test(r)&&!t.some(e=>e.toLowerCase()==r.toLowerCase())){t.push(r);continue actions}}t.push(``)}return t}function BJ(e,t,n){let r=n?zJ(t.actions):[];return xA(`li`,{class:`cm-diagnostic cm-diagnostic-`+t.severity},xA(`span`,{class:`cm-diagnosticText`},t.renderMessage?t.renderMessage(e):t.message),t.actions?.map((n,i)=>{let a=!1,o=r=>{if(r.preventDefault(),a)return;a=!0;let i=wJ(e.state.field(AJ).diagnostics,t);i&&n.apply(e,i.from,i.to)},{name:s}=n,c=r[i]?s.indexOf(r[i]):-1,l=c<0?s:[s.slice(0,c),xA(`u`,s.slice(c,c+1)),s.slice(c+1)];return xA(`button`,{type:`button`,class:`cm-diagnosticAction`+(n.markClass?` `+n.markClass:``),onclick:o,onmousedown:o,"aria-label":` Action: ${s}${c<0?``:` (access key "${r[i]})"`}.`},l)}),t.source&&xA(`div`,{class:`cm-diagnosticSource`},t.source))}var VJ=class extends VA{constructor(e){super(),this.sev=e}eq(e){return e.sev==this.sev}toDOM(){return xA(`span`,{class:`cm-lintPoint cm-lintPoint-`+this.sev})}},HJ=class{constructor(e,t){this.diagnostic=t,this.id=`item_`+Math.floor(Math.random()*4294967295).toString(16),this.dom=BJ(e,t,!0),this.dom.id=this.id,this.dom.setAttribute(`role`,`option`)}},UJ=class e{constructor(e){this.view=e,this.items=[];let t=t=>{if(!(t.ctrlKey||t.altKey||t.metaKey)){if(t.keyCode==27)FJ(this.view),this.view.focus();else if(t.keyCode==38||t.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(t.keyCode==40||t.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(t.keyCode==36)this.moveSelection(0);else if(t.keyCode==35)this.moveSelection(this.items.length-1);else if(t.keyCode==13)this.view.focus();else if(t.keyCode>=65&&t.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:n}=this.items[this.selectedIndex],r=zJ(n.actions);for(let i=0;i<r.length;i++)if(r[i].toUpperCase().charCodeAt(0)==t.keyCode){let t=wJ(this.view.state.field(AJ).diagnostics,n);t&&n.actions[i].apply(e,t.from,t.to)}}else return;t.preventDefault()}},n=e=>{for(let t=0;t<this.items.length;t++)this.items[t].dom.contains(e.target)&&this.moveSelection(t)};this.list=xA(`ul`,{tabIndex:0,role:`listbox`,"aria-label":this.view.state.phrase(`Diagnostics`),onkeydown:t,onclick:n}),this.dom=xA(`div`,{class:`cm-panel-lint`},this.list,xA(`button`,{type:`button`,name:`close`,"aria-label":this.view.state.phrase(`close`),onclick:()=>FJ(this.view)},`×`)),this.update()}get selectedIndex(){let e=this.view.state.field(AJ).selected;if(!e)return-1;for(let t=0;t<this.items.length;t++)if(this.items[t].diagnostic==e.diagnostic)return t;return-1}update(){let{diagnostics:e,selected:t}=this.view.state.field(AJ),n=0,r=!1,i=null,a=new Set;for(e.between(0,this.view.state.doc.length,(e,o,{spec:s})=>{for(let e of s.diagnostics){if(a.has(e))continue;a.add(e);let o=-1,s;for(let t=n;t<this.items.length;t++)if(this.items[t].diagnostic==e){o=t;break}o<0?(s=new HJ(this.view,e),this.items.splice(n,0,s),r=!0):(s=this.items[o],o>n&&(this.items.splice(n,o-n),r=!0)),t&&s.diagnostic==t.diagnostic?s.dom.hasAttribute(`aria-selected`)||(s.dom.setAttribute(`aria-selected`,`true`),i=s):s.dom.hasAttribute(`aria-selected`)&&s.dom.removeAttribute(`aria-selected`),n++}});n<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)r=!0,this.items.pop();this.items.length==0&&(this.items.push(new HJ(this.view,{from:-1,to:-1,severity:`info`,message:this.view.state.phrase(`No diagnostics`)})),r=!0),i?(this.list.setAttribute(`aria-activedescendant`,i.id),this.view.requestMeasure({key:this,read:()=>({sel:i.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:e,panel:t})=>{let n=t.height/this.list.offsetHeight;e.top<t.top?this.list.scrollTop-=(t.top-e.top)/n:e.bottom>t.bottom&&(this.list.scrollTop+=(e.bottom-t.bottom)/n)}})):this.selectedIndex<0&&this.list.removeAttribute(`aria-activedescendant`),r&&this.sync()}sync(){let e=this.list.firstChild;function t(){let t=e;e=t.nextSibling,t.remove()}for(let n of this.items)if(n.dom.parentNode==this.list){for(;e!=n.dom;)t();e=n.dom.nextSibling}else this.list.insertBefore(n.dom,e);for(;e;)t()}moveSelection(e){if(this.selectedIndex<0)return;let t=wJ(this.view.state.field(AJ).diagnostics,this.items[e].diagnostic);t&&this.view.dispatch({selection:{anchor:t.from,head:t.to},scrollIntoView:!0,effects:kJ.of(t)})}static open(t){return new e(t)}};function WJ(e,t=`viewBox="0 0 40 40"`){return`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${t}>${encodeURIComponent(e)}</svg>')`}function GJ(e){return WJ(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${e}" fill="none" stroke-width=".7"/>`,`width="6" height="3"`)}var KJ=SF.baseTheme({".cm-diagnostic":{padding:`3px 6px 3px 8px`,marginLeft:`-1px`,display:`block`,whiteSpace:`pre-wrap`},".cm-diagnostic-error":{borderLeft:`5px solid #d11`},".cm-diagnostic-warning":{borderLeft:`5px solid orange`},".cm-diagnostic-info":{borderLeft:`5px solid #999`},".cm-diagnostic-hint":{borderLeft:`5px solid #66d`},".cm-diagnosticAction":{font:`inherit`,border:`none`,padding:`2px 4px`,backgroundColor:`#444`,color:`white`,borderRadius:`3px`,marginLeft:`8px`,cursor:`pointer`},".cm-diagnosticSource":{fontSize:`70%`,opacity:.7},".cm-lintRange":{backgroundPosition:`left bottom`,backgroundRepeat:`repeat-x`,paddingBottom:`0.7px`},".cm-lintRange-error":{backgroundImage:GJ(`#f11`)},".cm-lintRange-warning":{backgroundImage:GJ(`orange`)},".cm-lintRange-info":{backgroundImage:GJ(`#999`)},".cm-lintRange-hint":{backgroundImage:GJ(`#66d`)},".cm-lintRange-active":{backgroundColor:`#ffdd9980`},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:`relative`,"&:after":{content:`""`,position:`absolute`,bottom:0,left:`-2px`,borderLeft:`3px solid transparent`,borderRight:`3px solid transparent`,borderBottom:`4px solid #d11`}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:`orange`}},".cm-lintPoint-info":{"&:after":{borderBottomColor:`#999`}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:`#66d`}},".cm-panel.cm-panel-lint":{position:`relative`,"& ul":{maxHeight:`100px`,overflowY:`auto`,"& [aria-selected]":{backgroundColor:`#ddd`,"& u":{textDecoration:`underline`}},"&:focus [aria-selected]":{background_fallback:`#bdf`,backgroundColor:`Highlight`,color_fallback:`white`,color:`HighlightText`},"& u":{textDecoration:`none`},padding:0,margin:0},"& [name=close]":{position:`absolute`,top:`0`,right:`2px`,background:`inherit`,border:`none`,font:`inherit`,padding:0,margin:0}},"&dark .cm-lintRange-active":{backgroundColor:`#86714a80`},"&dark .cm-panel.cm-panel-lint ul":{"& [aria-selected]":{backgroundColor:`#2e343e`}}});function qJ(e){return e==`error`?4:e==`warning`?3:e==`info`?2:1}function JJ(e){let t=`hint`,n=1;for(let r of e){let e=qJ(r.severity);e>n&&(n=e,t=r.severity)}return t}var YJ=eL(MJ,{hideOn:TJ}),XJ=[AJ,SF.decorations.compute([AJ],e=>{let{selected:t,panel:n}=e.field(AJ);return!t||!n||t.from==t.to?UA.none:UA.set([jJ.range(t.from,t.to)])}),YJ,KJ],ZJ=function(e){e===void 0&&(e={});var t=e.crosshairCursor,n=t!==void 0&&t,r=[];e.closeBracketsKeymap!==!1&&(r=r.concat(cJ)),e.defaultKeymap!==!1&&(r=r.concat(TU)),e.searchKeymap!==!1&&(r=r.concat(OK)),e.historyKeymap!==!1&&(r=r.concat(LV)),e.foldKeymap!==!1&&(r=r.concat($z)),e.completionKeymap!==!1&&(r=r.concat(bJ)),e.lintKeymap!==!1&&(r=r.concat(IJ));var i=[];return e.lineNumbers!==!1&&i.push(IL()),e.highlightActiveLineGutter!==!1&&i.push(BL()),e.highlightSpecialChars!==!1&&i.push(hI()),e.history!==!1&&i.push(vV()),e.foldGutter!==!1&&i.push(cB()),e.drawSelection!==!1&&i.push(YF()),e.dropCursor!==!1&&i.push(aI()),e.allowMultipleSelections!==!1&&i.push(Kk.allowMultipleSelections.of(!0)),e.indentOnInput!==!1&&i.push(Pz()),e.syntaxHighlighting!==!1&&i.push(mB(_B,{fallback:!0})),e.bracketMatching!==!1&&i.push(DB()),e.closeBrackets!==!1&&i.push(nJ()),e.autocompletion!==!1&&i.push(yJ()),e.rectangularSelection!==!1&&i.push(MI()),n!==!1&&i.push(FI()),e.highlightActiveLine!==!1&&i.push(SI()),e.highlightSelectionMatches!==!1&&i.push(zG()),e.tabSize&&typeof e.tabSize==`number`&&i.push(hz.of(` `.repeat(e.tabSize))),i.concat([jF.of(r.flat())]).filter(Boolean)},QJ=`#e5c07b`,$J=`#e06c75`,eY=`#56b6c2`,tY=`#ffffff`,nY=`#abb2bf`,rY=`#7d8799`,iY=`#61afef`,aY=`#98c379`,oY=`#d19a66`,sY=`#c678dd`,cY=`#21252b`,lY=`#2c313a`,uY=`#282c34`,dY=`#353a42`,fY=`#3E4451`,pY=`#528bff`,mY=[SF.theme({"&":{color:nY,backgroundColor:uY},".cm-content":{caretColor:pY},".cm-cursor, .cm-dropCursor":{borderLeftColor:pY},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:fY},".cm-panels":{backgroundColor:cY,color:nY},".cm-panels.cm-panels-top":{borderBottom:`2px solid black`},".cm-panels.cm-panels-bottom":{borderTop:`2px solid black`},".cm-searchMatch":{backgroundColor:`#72a1ff59`,outline:`1px solid #457dff`},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:`#6199ff2f`},".cm-activeLine":{backgroundColor:`#6699ff0b`},".cm-selectionMatch":{backgroundColor:`#aafe661a`},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{backgroundColor:`#bad0f847`},".cm-gutters":{backgroundColor:uY,color:rY,border:`none`},".cm-activeLineGutter":{backgroundColor:lY},".cm-foldPlaceholder":{backgroundColor:`transparent`,border:`none`,color:`#ddd`},".cm-tooltip":{border:`none`,backgroundColor:dY},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:`transparent`,borderBottomColor:`transparent`},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:dY,borderBottomColor:dY},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:lY,color:nY}}},{dark:!0}),mB(uB.define([{tag:$.keyword,color:sY},{tag:[$.name,$.deleted,$.character,$.propertyName,$.macroName],color:$J},{tag:[$.function($.variableName),$.labelName],color:iY},{tag:[$.color,$.constant($.name),$.standard($.name)],color:oY},{tag:[$.definition($.name),$.separator],color:nY},{tag:[$.typeName,$.className,$.number,$.changed,$.annotation,$.modifier,$.self,$.namespace],color:QJ},{tag:[$.operator,$.operatorKeyword,$.url,$.escape,$.regexp,$.link,$.special($.string)],color:eY},{tag:[$.meta,$.comment],color:rY},{tag:$.strong,fontWeight:`bold`},{tag:$.emphasis,fontStyle:`italic`},{tag:$.strikethrough,textDecoration:`line-through`},{tag:$.link,color:rY,textDecoration:`underline`},{tag:$.heading,fontWeight:`bold`,color:$J},{tag:[$.atom,$.bool,$.special($.variableName)],color:oY},{tag:[$.processingInstruction,$.string,$.inserted],color:aY},{tag:$.invalid,color:tY}]))],hY=SF.theme({"&":{backgroundColor:`#fff`}},{dark:!1}),gY=function(e){e===void 0&&(e={});var t=e,n=t.indentWithTab,r=n===void 0||n,i=t.editable,a=i===void 0||i,o=t.readOnly,s=o!==void 0&&o,c=t.theme,l=c===void 0?`light`:c,u=t.placeholder,d=u===void 0?``:u,f=t.basicSetup,p=f===void 0||f,m=[];switch(r&&m.unshift(jF.of([EU])),p&&(typeof p==`boolean`?m.unshift(ZJ()):m.unshift(ZJ(p))),d&&m.unshift(EI(d)),l){case`light`:m.push(hY);break;case`dark`:m.push(mY);break;case`none`:break;default:m.push(l)}return a===!1&&m.push(SF.editable.of(!1)),s&&m.push(Kk.readOnly.of(!0)),[...m]},_Y=e=>({line:e.state.doc.lineAt(e.state.selection.main.from),lineCount:e.state.doc.lines,lineBreak:e.state.lineBreak,length:e.state.doc.length,readOnly:e.state.readOnly,tabSize:e.state.tabSize,selection:e.state.selection,selectionAsSingle:e.state.selection.asSingle().main,ranges:e.state.selection.ranges,selectionCode:e.state.sliceDoc(e.state.selection.main.from,e.state.selection.main.to),selections:e.state.selection.ranges.map(t=>e.state.sliceDoc(t.from,t.to)),selectedText:e.state.selection.ranges.some(e=>!e.empty)}),vY=class{constructor(e,t){this.timeLeftMS=void 0,this.timeoutMS=void 0,this.isCancelled=!1,this.isTimeExhausted=!1,this.callbacks=[],this.timeLeftMS=t,this.timeoutMS=t,this.callbacks.push(e)}tick(){if(!this.isCancelled&&!this.isTimeExhausted&&(this.timeLeftMS--,this.timeLeftMS<=0)){this.isTimeExhausted=!0;var e=this.callbacks.slice();this.callbacks.length=0,e.forEach(e=>{try{e()}catch(e){console.error(`TimeoutLatch callback error:`,e)}})}}cancel(){this.isCancelled=!0,this.callbacks.length=0}reset(){this.timeLeftMS=this.timeoutMS,this.isCancelled=!1,this.isTimeExhausted=!1}get isDone(){return this.isCancelled||this.isTimeExhausted}},yY=class{constructor(){this.interval=null,this.latches=new Set}add(e){this.latches.add(e),this.start()}remove(e){this.latches.delete(e),this.latches.size===0&&this.stop()}start(){this.interval===null&&(this.interval=setInterval(()=>{this.latches.forEach(e=>{e.tick(),e.isDone&&this.remove(e)})},1))}stop(){this.interval!==null&&(clearInterval(this.interval),this.interval=null)}},bY=null,xY=()=>typeof window>`u`?new yY:(bY||=new yY,bY),SY=SF.theme({"& .cm-scroller":{height:`100% !important`}}),CY=null,wY=null;function TY(e,t,n,r,i,a){if(!e&&!t&&!n&&!r&&!i&&!a)return null;var o=JSON.stringify({height:e,minHeight:t,maxHeight:n,width:r,minWidth:i,maxWidth:a});return o===CY?wY:(CY=o,wY=SF.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:i,maxWidth:a}}),wY)}var EY=Ok.define(),DY=200,OY=[];function kY(e){var t=e.value,n=e.selection,r=e.onChange,i=e.onStatistics,a=e.onCreateEditor,o=e.onUpdate,s=e.extensions,c=s===void 0?OY:s,l=e.autoFocus,u=e.theme,d=u===void 0?`light`:u,f=e.height,p=f===void 0?null:f,m=e.minHeight,h=m===void 0?null:m,g=e.maxHeight,_=g===void 0?null:g,v=e.width,y=v===void 0?null:v,b=e.minWidth,x=b===void 0?null:b,S=e.maxWidth,C=S===void 0?null:S,w=e.placeholder,T=w===void 0?``:w,E=e.editable,D=E===void 0||E,O=e.readOnly,k=O!==void 0&&O,A=e.indentWithTab,j=A===void 0||A,M=e.basicSetup,N=M===void 0||M,P=e.root,ee=e.initialState,F=(0,X.useState)(),I=F[0],te=F[1],ne=(0,X.useState)(),L=ne[0],re=ne[1],R=(0,X.useState)(),ie=R[0],ae=R[1],oe=(0,X.useState)(()=>({current:null}))[0],z=(0,X.useState)(()=>({current:null}))[0],se=TY(p,h,_,y,x,C),ce=SF.updateListener.of(e=>{e.docChanged&&typeof r==`function`&&!e.transactions.some(e=>e.annotation(EY))&&(oe.current?oe.current.reset():(oe.current=new vY(()=>{if(z.current){var e=z.current;z.current=null,e()}oe.current=null},DY),xY().add(oe.current)),r(e.state.doc.toString(),e)),i&&i(_Y(e))}),B=gY({theme:d,editable:D,readOnly:k,placeholder:T,indentWithTab:j,basicSetup:N}),V=[ce,...se?[se]:[],SY,...B];return o&&typeof o==`function`&&V.push(SF.updateListener.of(o)),V=V.concat(c),(0,X.useLayoutEffect)(()=>{if(I&&!ie){var e={doc:t,selection:n,extensions:V},r=ee?Kk.fromJSON(ee.json,e,ee.fields):Kk.create(e);if(ae(r),!L){var i=new SF({state:r,parent:I,root:P});re(i),a&&a(i,r)}}return()=>{L&&(ae(void 0),re(void 0))}},[I,ie]),(0,X.useEffect)(()=>{e.container&&te(e.container)},[e.container]),(0,X.useEffect)(()=>()=>{L&&(L.destroy(),re(void 0)),oe.current&&=(oe.current.cancel(),null)},[L]),(0,X.useEffect)(()=>{l&&L&&L.focus()},[l,L]),(0,X.useEffect)(()=>{L&&L.dispatch({effects:jk.reconfigure.of(V)})},[d,c,p,h,_,y,x,C,T,D,k,j,N,r,o]),(0,X.useEffect)(()=>{if(t!==void 0){var e=L?L.state.doc.toString():``;if(L&&t!==e){var n=oe.current&&!oe.current.isDone,r=()=>{L&&t!==L.state.doc.toString()&&L.dispatch({changes:{from:0,to:L.state.doc.toString().length,insert:t||``},annotations:[EY.of(!0)]})};n?z.current=r:r()}}},[t,L]),{state:ie,setState:ae,view:L,setView:re,container:I,setContainer:te}}var AY=[`className`,`value`,`selection`,`extensions`,`onChange`,`onStatistics`,`onCreateEditor`,`onUpdate`,`autoFocus`,`theme`,`height`,`minHeight`,`maxHeight`,`width`,`minWidth`,`maxWidth`,`basicSetup`,`placeholder`,`indentWithTab`,`editable`,`readOnly`,`root`,`initialState`],jY=(0,X.forwardRef)((e,t)=>{var n=e.className,r=e.value,i=r===void 0?``:r,a=e.selection,o=e.extensions,s=o===void 0?[]:o,c=e.onChange,l=e.onStatistics,u=e.onCreateEditor,d=e.onUpdate,f=e.autoFocus,p=e.theme,m=p===void 0?`light`:p,h=e.height,g=e.minHeight,_=e.maxHeight,v=e.width,y=e.minWidth,b=e.maxWidth,x=e.basicSetup,S=e.placeholder,C=e.indentWithTab,w=e.editable,T=e.readOnly,E=e.root,D=e.initialState,O=mO(e,AY),k=(0,X.useRef)(null),A=kY({root:E,value:i,autoFocus:f,theme:m,height:h,minHeight:g,maxHeight:_,width:v,minWidth:y,maxWidth:b,basicSetup:x,placeholder:S,indentWithTab:C,editable:w,readOnly:T,selection:a,onChange:c,onStatistics:l,onCreateEditor:u,onUpdate:d,extensions:s,initialState:D}),j=A.state,M=A.view,N=A.container,P=A.setContainer;(0,X.useImperativeHandle)(t,()=>({editor:k.current,state:j,view:M}),[k,N,j,M]);var ee=(0,X.useCallback)(e=>{k.current=e,P(e)},[P]);if(typeof i!=`string`)throw Error(`value must be typeof string but got `+typeof i);var F=typeof m==`string`?`cm-theme-`+m:`cm-theme`;return(0,Z.jsx)(`div`,ze({ref:ee,className:``+F+(n?` `+n:``)},O))});jY.displayName=`CodeMirror`;var MY=class e{constructor(e,t,n,r,i,a,o,s,c,l=0,u){this.p=e,this.stack=t,this.state=n,this.reducePos=r,this.pos=i,this.score=a,this.buffer=o,this.bufferBase=s,this.curContext=c,this.lookAhead=l,this.parent=u}toString(){return`[${this.stack.filter((e,t)=>t%3==0).concat(this.state)}]@${this.pos}${this.score?`!`+this.score:``}`}static start(t,n,r=0){let i=t.parser.context;return new e(t,[],n,r,r,0,[],0,i?new NY(i,i.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){let t=e>>19,n=e&65535,{parser:r}=this.p,i=this.reducePos<this.pos-25&&this.setLookAhead(this.pos),a=r.dynamicPrecedence(n);if(a&&(this.score+=a),t==0){n<r.minRepeatTerm&&this.reducePos<this.pos&&(this.reducePos=this.pos),this.pushState(r.getGoto(this.state,n,!0),this.reducePos),n<r.minRepeatTerm&&this.storeNode(n,this.reducePos,this.reducePos,i?8:4,!0),this.reduceContext(n,this.reducePos);return}let o=this.stack.length-(t-1)*3-(e&262144?6:0),s=o?this.stack[o-2]:this.p.ranges[0].from;n<r.minRepeatTerm&&s==this.reducePos&&this.reducePos<this.pos&&(this.reducePos=this.pos);let c=this.reducePos-s;c>=2e3&&!this.p.parser.nodeSet.types[n]?.isAnonymous&&(s==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=c):this.p.lastBigReductionSize<c&&(this.p.bigReductionCount=1,this.p.lastBigReductionStart=s,this.p.lastBigReductionSize=c));let l=o?this.stack[o-1]:0,u=this.bufferBase+this.buffer.length-l;if(n<r.minRepeatTerm||e&131072){let e=r.stateFlag(this.state,1)?this.pos:this.reducePos;this.storeNode(n,s,e,u+4,!0)}if(e&262144)this.state=this.stack[o];else{let e=this.stack[o-3];this.state=r.getGoto(e,n,!0)}for(;this.stack.length>o;)this.stack.pop();this.reduceContext(n,s)}storeNode(e,t,n,r=4,i=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]<this.buffer.length+this.bufferBase)){let e=this.buffer.length;if(e>0&&this.buffer[e-4]==0&&this.buffer[e-1]>-1){if(t==n)return;if(this.buffer[e-2]>=t){this.buffer[e-2]=n;return}}}if(!i||this.pos==n)this.buffer.push(e,t,n,r);else{let i=this.buffer.length;if(i>0&&(this.buffer[i-4]!=0||this.buffer[i-1]<0)){let e=!1;for(let t=i;t>0&&this.buffer[t-2]>n;t-=4)if(this.buffer[t-1]>=0){e=!0;break}if(e)for(;i>0&&this.buffer[i-2]>n;)this.buffer[i]=this.buffer[i-4],this.buffer[i+1]=this.buffer[i-3],this.buffer[i+2]=this.buffer[i-2],this.buffer[i+3]=this.buffer[i-1],i-=4,r>4&&(r-=4)}this.buffer[i]=e,this.buffer[i+1]=t,this.buffer[i+2]=n,this.buffer[i+3]=r}}shift(e,t,n,r){if(e&131072)this.pushState(e&65535,this.pos);else if(e&262144)this.pos=r,this.shiftContext(t,n),t<=this.p.parser.maxNode&&this.buffer.push(t,n,r,4);else{let i=e,{parser:a}=this.p;this.pos=r;let o=a.stateFlag(i,1);!o&&(r>n||t<=a.maxNode)&&(this.reducePos=r),this.pushState(i,o?n:Math.min(n,this.reducePos)),this.shiftContext(t,n),t<=a.maxNode&&this.buffer.push(t,n,r,4)}}apply(e,t,n,r){e&65536?this.reduce(e):this.shift(e,t,n,r)}useNode(e,t){let n=this.p.reused.length-1;(n<0||this.p.reused[n]!=e)&&(this.p.reused.push(e),n++);let r=this.pos;this.reducePos=this.pos=r+e.length,this.pushState(t,r),this.buffer.push(n,r,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let t=this,n=t.buffer.length;for(n&&t.buffer[n-4]==0&&(n-=4);n>0&&t.buffer[n-2]>t.reducePos;)n-=4;let r=t.buffer.slice(n),i=t.bufferBase+n;for(;t&&i==t.bufferBase;)t=t.parent;return new e(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,r,i,this.curContext,this.lookAhead,t)}recoverByDelete(e,t){let n=e<=this.p.parser.maxNode;n&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,n?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new PY(this);;){let n=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(n==0)return!1;if(!(n&65536))return!0;t.reduce(n)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let n=[];for(let r=0,i;r<t.length;r+=2)(i=t[r+1])!=this.state&&this.p.parser.hasAction(i,e)&&n.push(t[r],i);if(this.stack.length<120)for(let e=0;n.length<8&&e<t.length;e+=2){let r=t[e+1];n.some((e,t)=>t&1&&e==r)||n.push(t[e],r)}t=n}let n=[];for(let e=0;e<t.length&&n.length<4;e+=2){let r=t[e+1];if(r==this.state)continue;let i=this.split();i.pushState(r,this.pos),i.storeNode(0,i.pos,i.pos,4,!0),i.shiftContext(t[e],this.pos),i.reducePos=this.pos,i.score-=200,n.push(i)}return n}forceReduce(){let{parser:e}=this.p,t=e.stateSlot(this.state,5);if(!(t&65536))return!1;if(!e.validAction(this.state,t)){let n=t>>19,r=t&65535,i=this.stack.length-n*3;if(i<0||e.getGoto(this.stack[i],r,!1)<0){let e=this.findForcedReduction();if(e==null)return!1;t=e}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(t),!0}findForcedReduction(){let{parser:e}=this.p,t=[],n=(r,i)=>{if(!t.includes(r))return t.push(r),e.allActions(r,t=>{if(!(t&393216)){if(t&65536){let n=(t>>19)-i;if(n>1){let r=t&65535,i=this.stack.length-n*3;if(i>=0&&e.getGoto(this.stack[i],r,!1)>=0)return n<<19|65536|r}}else{let e=n(t,i+1);if(e!=null)return e}}})};return n(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.storeNode(0,this.pos,this.pos,4,!0),this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;t<this.stack.length;t+=3)if(this.stack[t]!=e.stack[t])return!1;return!0}get parser(){return this.p.parser}dialectEnabled(e){return this.p.parser.dialect.flags[e]}shiftContext(e,t){this.curContext&&this.updateContext(this.curContext.tracker.shift(this.curContext.context,e,this,this.p.stream.reset(t)))}reduceContext(e,t){this.curContext&&this.updateContext(this.curContext.tracker.reduce(this.curContext.context,e,this,this.p.stream.reset(t)))}emitContext(){let e=this.buffer.length-1;(e<0||this.buffer[e]!=-3)&&this.buffer.push(this.curContext.hash,this.pos,this.pos,-3)}emitLookAhead(){let e=this.buffer.length-1;(e<0||this.buffer[e]!=-4)&&this.buffer.push(this.lookAhead,this.pos,this.pos,-4)}updateContext(e){if(e!=this.curContext.context){let t=new NY(this.curContext.tracker,e);t.hash!=this.curContext.hash&&this.emitContext(),this.curContext=t}}setLookAhead(e){return e<=this.lookAhead?!1:(this.emitLookAhead(),this.lookAhead=e,!0)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}},NY=class{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}},PY=class{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,n=e>>19;n==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(n-1)*3;let r=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=r}},FY=class e{constructor(e,t,n){this.stack=e,this.pos=t,this.index=n,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(t,n=t.bufferBase+t.buffer.length){return new e(t,n,n-t.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new e(this.stack,this.pos,this.index)}};function IY(e,t=Uint16Array){if(typeof e!=`string`)return e;let n=null;for(let r=0,i=0;r<e.length;){let a=0;for(;;){let t=e.charCodeAt(r++),n=!1;if(t==126){a=65535;break}t>=92&&t--,t>=34&&t--;let i=t-32;if(i>=46&&(i-=46,n=!0),a+=i,n)break;a*=46}n?n[i++]=a:n=new t(a)}return n}var LY=class{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}},RY=new LY,zY=class{constructor(e,t){this.input=e,this.ranges=t,this.chunk=``,this.chunkOff=0,this.chunk2=``,this.chunk2Pos=0,this.next=-1,this.token=RY,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let n=this.range,r=this.rangeIndex,i=this.pos+e;for(;i<n.from;){if(!r)return null;let e=this.ranges[--r];i-=n.from-e.to,n=e}for(;t<0?i>n.to:i>=n.to;){if(r==this.ranges.length-1)return null;let e=this.ranges[++r];i+=e.from-n.to,n=e}return i}clipPos(e){if(e>=this.range.from&&e<this.range.to)return e;for(let t of this.ranges)if(t.to>e)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,n,r;if(t>=0&&t<this.chunk.length)n=this.pos+e,r=this.chunk.charCodeAt(t);else{let t=this.resolveOffset(e,1);if(t==null)return-1;if(n=t,n>=this.chunk2Pos&&n<this.chunk2Pos+this.chunk2.length)r=this.chunk2.charCodeAt(n-this.chunk2Pos);else{let e=this.rangeIndex,t=this.range;for(;t.to<=n;)t=this.ranges[++e];this.chunk2=this.input.chunk(this.chunk2Pos=n),n+this.chunk2.length>t.to&&(this.chunk2=this.chunk2.slice(0,t.to-n)),r=this.chunk2.charCodeAt(0)}}return n>=this.token.lookAhead&&(this.token.lookAhead=n+1),r}acceptToken(e,t=0){let n=t?this.resolveOffset(t,-1):this.pos;if(n==null||n<this.token.start)throw RangeError(`Token end out of bounds`);this.token.value=e,this.token.end=n}acceptTokenTo(e,t){this.token.value=e,this.token.end=t}getChunk(){if(this.pos>=this.chunk2Pos&&this.pos<this.chunk2Pos+this.chunk2.length){let{chunk:e,chunkPos:t}=this;this.chunk=this.chunk2,this.chunkPos=this.chunk2Pos,this.chunk2=e,this.chunk2Pos=t,this.chunkOff=this.pos-this.chunkPos}else{this.chunk2=this.chunk,this.chunk2Pos=this.chunkPos;let e=this.input.chunk(this.pos),t=this.pos+e.length;this.chunk=t>this.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.next=this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?-1:this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk=``,this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=RY,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e<this.range.from;)this.range=this.ranges[--this.rangeIndex];for(;e>=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e<this.chunkPos+this.chunk.length?this.chunkOff=e-this.chunkPos:(this.chunk=``,this.chunkOff=0),this.readNext()}return this}read(e,t){if(e>=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let n=``;for(let r of this.ranges){if(r.from>=t)break;r.to>e&&(n+=this.input.read(Math.max(r.from,e),Math.min(r.to,t)))}return n}},BY=class{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:n}=t.p;UY(this.data,e,t,this.id,n.data,n.tokenPrecTable)}};BY.prototype.contextual=BY.prototype.fallback=BY.prototype.extend=!1;var VY=class{constructor(e,t,n){this.precTable=t,this.elseToken=n,this.data=typeof e==`string`?IY(e):e}token(e,t){let n=e.pos,r=0;for(;;){let n=e.next<0,i=e.resolveOffset(1,1);if(UY(this.data,e,t,0,this.data,this.precTable),e.token.value>-1)break;if(this.elseToken==null)return;if(n||r++,i==null)break;e.reset(i,e.token)}r&&(e.reset(n,e.token),e.acceptToken(this.elseToken,r))}};VY.prototype.contextual=BY.prototype.fallback=BY.prototype.extend=!1;var HY=class{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}};function UY(e,t,n,r,i,a){let o=0,s=1<<r,{dialect:c}=n.p.parser;scan:for(;(s&e[o])!=0;){let n=e[o+1];for(let r=o+3;r<n;r+=2)if((e[r+1]&s)>0){let n=e[r];if(c.allows(n)&&(t.token.value==-1||t.token.value==n||GY(n,t.token.value,i,a))){t.acceptToken(n);break}}let r=t.next,l=0,u=e[o+2];if(t.next<0&&u>l&&e[n+u*3-3]==65535){o=e[n+u*3-1];continue scan}for(;l<u;){let i=l+u>>1,a=n+i+(i<<1),s=e[a],c=e[a+1]||65536;if(r<s)u=i;else if(r>=c)l=i+1;else{o=e[a+2],t.advance();continue scan}}break}}function WY(e,t,n){for(let r=t,i;(i=e[r])!=65535;r++)if(i==n)return r-t;return-1}function GY(e,t,n,r){let i=WY(n,r,t);return i<0||WY(n,r,e)<i}var KY=typeof process<`u`&&/\bparse\b/.test({}.LOG),qY=null;function JY(e,t,n){let r=e.cursor(ZL.IncludeAnonymous);for(r.moveTo(t);;)if(!(n<0?r.childBefore(t):r.childAfter(t)))for(;;){if((n<0?r.to<t:r.from>t)&&!r.type.isError)return n<0?Math.max(0,Math.min(r.to-1,t-25)):Math.min(e.length,Math.max(r.from+1,t+25));if(n<0?r.prevSibling():r.nextSibling())break;if(!r.parent())return n<0?0:e.length}}var YY=class{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?JY(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?JY(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(e<this.nextStart)return null;for(;this.fragment&&this.safeTo<=e;)this.nextFragment();if(!this.fragment)return null;for(;;){let t=this.trees.length-1;if(t<0)return this.nextFragment(),null;let n=this.trees[t],r=this.index[t];if(r==n.children.length){this.trees.pop(),this.start.pop(),this.index.pop();continue}let i=n.children[r],a=this.start[t]+n.positions[r];if(a>e)return this.nextStart=a,null;if(i instanceof QL){if(a==e){if(a<this.safeFrom)return null;let e=a+i.length;if(e<=this.safeTo){let t=i.prop(WL.lookAhead);if(!t||e+t<this.fragment.to)return i}}this.index[t]++,a+i.length>=Math.max(this.safeFrom,e)&&(this.trees.push(i),this.start.push(a),this.index.push(0))}else this.index[t]++,this.nextStart=a+i.length}}},XY=class{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(e=>new LY)}getActions(e){let t=0,n=null,{parser:r}=e.p,{tokenizers:i}=r,a=r.stateSlot(e.state,3),o=e.curContext?e.curContext.hash:0,s=0;for(let r=0;r<i.length;r++){if(!(1<<r&a))continue;let c=i[r],l=this.tokens[r];if(!(n&&!c.fallback)&&((c.contextual||l.start!=e.pos||l.mask!=a||l.context!=o)&&(this.updateCachedToken(l,c,e),l.mask=a,l.context=o),l.lookAhead>l.end+25&&(s=Math.max(l.lookAhead,s)),l.value!=0)){let r=t;if(l.extended>-1&&(t=this.addActions(e,l.extended,l.end,t)),t=this.addActions(e,l.value,l.end,t),!c.extend&&(n=l,t>r))break}}for(;this.actions.length>t;)this.actions.pop();return s&&e.setLookAhead(s),!n&&e.pos==this.stream.end&&(n=new LY,n.value=e.p.parser.eofTerm,n.start=n.end=e.pos,t=this.addActions(e,n.value,n.end,t)),this.mainToken=n,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new LY,{pos:n,p:r}=e;return t.start=n,t.end=Math.min(n+1,r.stream.end),t.value=n==r.stream.end?r.parser.eofTerm:0,t}updateCachedToken(e,t,n){let r=this.stream.clipPos(n.pos);if(t.token(this.stream.reset(r,e),n),e.value>-1){let{parser:t}=n.p;for(let r=0;r<t.specialized.length;r++)if(t.specialized[r]==e.value){let i=t.specializers[r](this.stream.read(e.start,e.end),n);if(i>=0&&n.p.parser.dialect.allows(i>>1)){i&1?e.extended=i>>1:e.value=i>>1;break}}}else e.value=0,e.end=this.stream.clipPos(r+1)}putAction(e,t,n,r){for(let t=0;t<r;t+=3)if(this.actions[t]==e)return r;return this.actions[r++]=e,this.actions[r++]=t,this.actions[r++]=n,r}addActions(e,t,n,r){let{state:i}=e,{parser:a}=e.p,{data:o}=a;for(let e=0;e<2;e++)for(let s=a.stateSlot(i,e?2:1);;s+=3){if(o[s]==65535){if(o[s+1]==1)s=rX(o,s+2);else{r==0&&o[s+1]==2&&(r=this.putAction(rX(o,s+2),t,n,r));break}}o[s]==t&&(r=this.putAction(rX(o,s+1),t,n,r))}return r}},ZY=class{constructor(e,t,n,r){this.parser=e,this.input=t,this.ranges=r,this.recovering=0,this.nextStackID=9812,this.minStackPos=0,this.reused=[],this.stoppedAt=null,this.lastBigReductionStart=-1,this.lastBigReductionSize=0,this.bigReductionCount=0,this.stream=new zY(t,r),this.tokens=new XY(e,this.stream),this.topTerm=e.top[1];let{from:i}=r[0];this.stacks=[MY.start(this,e.top[0],i)],this.fragments=n.length&&this.stream.end-i>e.bufferLength*4?new YY(n,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,n=this.stacks=[],r,i;if(this.bigReductionCount>300&&e.length==1){let[t]=e;for(;t.forceReduce()&&t.stack.length&&t.stack[t.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let a=0;a<e.length;a++){let o=e[a];for(;;){if(this.tokens.mainToken=null,o.pos>t)n.push(o);else if(this.advanceStack(o,n,e))continue;else{r||(r=[],i=[]),r.push(o);let e=this.tokens.getMainToken(o);i.push(e.value,e.end)}break}}if(!n.length){let e=r&&iX(r);if(e)return KY&&console.log(`Finish with `+this.stackID(e)),this.stackToTree(e);if(this.parser.strict)throw KY&&r&&console.log(`Stuck with token `+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):`none`)),SyntaxError(`No parse at `+t);this.recovering||=5}if(this.recovering&&r){let e=this.stoppedAt!=null&&r[0].pos>this.stoppedAt?r[0]:this.runRecovery(r,i,n);if(e)return KY&&console.log(`Force-finish `+this.stackID(e)),this.stackToTree(e.forceAll())}if(this.recovering){let e=this.recovering==1?1:this.recovering*3;if(n.length>e)for(n.sort((e,t)=>t.score-e.score);n.length>e;)n.pop();n.some(e=>e.reducePos>t)&&this.recovering--}else if(n.length>1){outer:for(let e=0;e<n.length-1;e++){let t=n[e];for(let r=e+1;r<n.length;r++){let i=n[r];if(t.sameState(i)||t.buffer.length>500&&i.buffer.length>500){if((t.score-i.score||t.buffer.length-i.buffer.length)>0)n.splice(r--,1);else{n.splice(e--,1);continue outer}}}}n.length>12&&(n.sort((e,t)=>t.score-e.score),n.splice(12,n.length-12))}this.minStackPos=n[0].pos;for(let e=1;e<n.length;e++)n[e].pos<this.minStackPos&&(this.minStackPos=n[e].pos);return null}stopAt(e){if(this.stoppedAt!=null&&this.stoppedAt<e)throw RangeError(`Can't move stoppedAt forward`);this.stoppedAt=e}advanceStack(e,t,n){let r=e.pos,{parser:i}=this,a=KY?this.stackID(e)+` -> `:``;if(this.stoppedAt!=null&&r>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let t=e.curContext&&e.curContext.tracker.strict,n=t?e.curContext.hash:0;for(let o=this.fragments.nodeAt(r);o;){let r=this.parser.nodeSet.types[o.type.id]==o.type?i.getGoto(e.state,o.type.id):-1;if(r>-1&&o.length&&(!t||(o.prop(WL.contextHash)||0)==n))return e.useNode(o,r),KY&&console.log(a+this.stackID(e)+` (via reuse of ${i.getName(o.type.id)})`),!0;if(!(o instanceof QL)||o.children.length==0||o.positions[0]>0)break;let s=o.children[0];if(s instanceof QL&&o.positions[0]==0)o=s;else break}}let o=i.stateSlot(e.state,4);if(o>0)return e.reduce(o),KY&&console.log(a+this.stackID(e)+` (via always-reduce ${i.getName(o&65535)})`),!0;if(e.stack.length>=8400)for(;e.stack.length>6e3&&e.forceReduce(););let s=this.tokens.getActions(e);for(let o=0;o<s.length;){let c=s[o++],l=s[o++],u=s[o++],d=o==s.length||!n,f=d?e:e.split(),p=this.tokens.mainToken;if(f.apply(c,l,p?p.start:f.pos,u),KY&&console.log(a+this.stackID(f)+` (via ${c&65536?`reduce of ${i.getName(c&65535)}`:`shift`} for ${i.getName(l)} @ ${r}${f==e?``:`, split`})`),d)return!0;f.pos>r?t.push(f):n.push(f)}return!1}advanceFully(e,t){let n=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>n)return QY(e,t),!0}}runRecovery(e,t,n){let r=null,i=!1;for(let a=0;a<e.length;a++){let o=e[a],s=t[a<<1],c=t[(a<<1)+1],l=KY?this.stackID(o)+` -> `:``;if(o.deadEnd&&(i||(i=!0,o.restart(),KY&&console.log(l+this.stackID(o)+` (restarted)`),this.advanceFully(o,n))))continue;let u=o.split(),d=l;for(let e=0;e<10&&u.forceReduce()&&(KY&&console.log(d+this.stackID(u)+` (via force-reduce)`),!this.advanceFully(u,n));e++)KY&&(d=this.stackID(u)+` -> `);for(let e of o.recoverByInsert(s))KY&&console.log(l+this.stackID(e)+` (via recover-insert)`),this.advanceFully(e,n);this.stream.end>o.pos?(c==o.pos&&(c++,s=0),o.recoverByDelete(s,c),KY&&console.log(l+this.stackID(o)+` (via recover-delete ${this.parser.getName(s)})`),QY(o,n)):(!r||r.score<u.score)&&(r=u)}return r}stackToTree(e){return e.close(),QL.build({buffer:FY.create(e),nodeSet:this.parser.nodeSet,topID:this.topTerm,maxBufferLength:this.parser.bufferLength,reused:this.reused,start:this.ranges[0].from,length:e.pos-this.ranges[0].from,minRepeatType:this.parser.minRepeatTerm})}stackID(e){let t=(qY||=new WeakMap).get(e);return t||qY.set(e,t=String.fromCodePoint(this.nextStackID++)),t+e}};function QY(e,t){for(let n=0;n<t.length;n++){let r=t[n];if(r.pos==e.pos&&r.sameState(e)){t[n].score<e.score&&(t[n]=e);return}}t.push(e)}var $Y=class{constructor(e,t,n){this.source=e,this.flags=t,this.disabled=n}allows(e){return!this.disabled||this.disabled[e]==0}},eX=e=>e,tX=class{constructor(e){this.start=e.start,this.shift=e.shift||eX,this.reduce=e.reduce||eX,this.reuse=e.reuse||eX,this.hash=e.hash||(()=>0),this.strict=e.strict!==!1}},nX=class e extends bR{constructor(e){if(super(),this.wrappers=[],e.version!=14)throw RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(` `);this.minRepeatTerm=t.length;for(let n=0;n<e.repeatNodeCount;n++)t.push(``);let n=Object.keys(e.topRules).map(t=>e.topRules[t][1]),r=[];for(let e=0;e<t.length;e++)r.push([]);function i(e,t,n){r[e].push([t,t.deserialize(String(n))])}if(e.nodeProps)for(let t of e.nodeProps){let e=t[0];typeof e==`string`&&(e=WL[e]);for(let n=1;n<t.length;){let r=t[n++];if(r>=0)i(r,e,t[n++]);else{let a=t[n+-r];for(let o=-r;o>0;o--)i(t[n++],e,a);n++}}}this.nodeSet=new JL(t.map((t,i)=>qL.define({name:i>=this.minRepeatTerm?void 0:t,id:i,props:r[i],top:n.indexOf(i)>-1,error:i==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(i)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=VL;let a=IY(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let e=0;e<this.specializerSpecs.length;e++)this.specialized[e]=this.specializerSpecs[e].term;this.specializers=this.specializerSpecs.map(aX),this.states=IY(e.states,Uint32Array),this.data=IY(e.stateData),this.goto=IY(e.goto),this.maxTerm=e.maxTerm,this.tokenizers=e.tokenizers.map(e=>typeof e==`number`?new BY(a,e):e),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,n){let r=new ZY(this,e,t,n);for(let i of this.wrappers)r=i(r,e,t,n);return r}getGoto(e,t,n=!1){let r=this.goto;if(t>=r[0])return-1;for(let i=r[t+1];;){let t=r[i++],a=t&1,o=r[i++];if(a&&n)return o;for(let n=i+(t>>1);i<n;i++)if(r[i]==e)return o;if(a)return-1}}hasAction(e,t){let n=this.data;for(let r=0;r<2;r++)for(let i=this.stateSlot(e,r?2:1),a;;i+=3){if((a=n[i])==65535){if(n[i+1]==1)a=n[i=rX(n,i+2)];else if(n[i+1]==2)return rX(n,i+2);else break}if(a==t||a==0)return rX(n,i+1)}return 0}stateSlot(e,t){return this.states[e*6+t]}stateFlag(e,t){return(this.stateSlot(e,0)&t)>0}validAction(e,t){return!!this.allActions(e,e=>e==t||null)}allActions(e,t){let n=this.stateSlot(e,4),r=n?t(n):void 0;for(let n=this.stateSlot(e,1);r==null;n+=3){if(this.data[n]==65535){if(this.data[n+1]==1)n=rX(this.data,n+2);else break}r=t(rX(this.data,n+1))}return r}nextStates(e){let t=[];for(let n=this.stateSlot(e,1);;n+=3){if(this.data[n]==65535){if(this.data[n+1]==1)n=rX(this.data,n+2);else break}if(!(this.data[n+2]&1)){let e=this.data[n+1];t.some((t,n)=>n&1&&t==e)||t.push(this.data[n],e)}}return t}configure(t){let n=Object.assign(Object.create(e.prototype),this);if(t.props&&(n.nodeSet=this.nodeSet.extend(...t.props)),t.top){let e=this.topRules[t.top];if(!e)throw RangeError(`Invalid top rule name ${t.top}`);n.top=e}return t.tokenizers&&(n.tokenizers=this.tokenizers.map(e=>{let n=t.tokenizers.find(t=>t.from==e);return n?n.to:e})),t.specializers&&(n.specializers=this.specializers.slice(),n.specializerSpecs=this.specializerSpecs.map((e,r)=>{let i=t.specializers.find(t=>t.from==e.external);if(!i)return e;let a=Object.assign(Object.assign({},e),{external:i.to});return n.specializers[r]=aX(a),a})),t.contextTracker&&(n.context=t.contextTracker),t.dialect&&(n.dialect=this.parseDialect(t.dialect)),t.strict!=null&&(n.strict=t.strict),t.wrap&&(n.wrappers=n.wrappers.concat(t.wrap)),t.bufferLength!=null&&(n.bufferLength=t.bufferLength),n}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),n=t.map(()=>!1);if(e)for(let r of e.split(` `)){let e=t.indexOf(r);e>=0&&(n[e]=!0)}let r=null;for(let e=0;e<t.length;e++)if(!n[e])for(let n=this.dialects[t[e]],i;(i=this.data[n++])!=65535;)(r||=new Uint8Array(this.maxTerm+1))[i]=1;return new $Y(e,n,r)}static deserialize(t){return new e(t)}};function rX(e,t){return e[t]|e[t+1]<<16}function iX(e){let t=null;for(let n of e){let e=n.p.stoppedAt;(n.pos==n.p.stream.end||e!=null&&n.pos>e)&&n.p.parser.stateFlag(n.state,2)&&(!t||t.score<n.score)&&(t=n)}return t}function aX(e){if(e.external){let t=+!!e.extend;return(n,r)=>e.external(n,r)<<1|t}return e.get}var oX=316,sX=317,cX=1,lX=2,uX=3,dX=4,fX=318,pX=320,mX=321,hX=5,gX=6,_X=0,vX=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],yX=125,bX=59,xX=47,SX=42,CX=43,wX=45,TX=60,EX=44,DX=63,OX=46,kX=91,AX=new tX({start:!1,shift(e,t){return t==hX||t==gX||t==pX?e:t==mX},strict:!1}),jX=new HY((e,t)=>{let{next:n}=e;(n==yX||n==-1||t.context)&&e.acceptToken(fX)},{contextual:!0,fallback:!0}),MX=new HY((e,t)=>{let{next:n}=e,r;vX.indexOf(n)>-1||(n!=xX||(r=e.peek(1))!=xX&&r!=SX)&&n!=yX&&n!=bX&&n!=-1&&!t.context&&e.acceptToken(oX)},{contextual:!0}),NX=new HY((e,t)=>{e.next==kX&&!t.context&&e.acceptToken(sX)},{contextual:!0}),PX=new HY((e,t)=>{let{next:n}=e;if(n==CX||n==wX){if(e.advance(),n==e.next){e.advance();let n=!t.context&&t.canShift(cX);e.acceptToken(n?cX:lX)}}else n==DX&&e.peek(1)==OX&&(e.advance(),e.advance(),(e.next<48||e.next>57)&&e.acceptToken(uX))},{contextual:!0});function FX(e,t){return e>=65&&e<=90||e>=97&&e<=122||e==95||e>=192||!t&&e>=48&&e<=57}var IX=new HY((e,t)=>{if(e.next!=TX||!t.dialectEnabled(_X)||(e.advance(),e.next==xX))return;let n=0;for(;vX.indexOf(e.next)>-1;)e.advance(),n++;if(FX(e.next,!0)){for(e.advance(),n++;FX(e.next,!1);)e.advance(),n++;for(;vX.indexOf(e.next)>-1;)e.advance(),n++;if(e.next==EX)return;for(let t=0;;t++){if(t==7){if(!FX(e.next,!0))return;break}if(e.next!=`extends`.charCodeAt(t))break;e.advance(),n++}}e.acceptToken(dX,-n)}),LX=OR({"get set async static":$.modifier,"for while do if else switch try catch finally return throw break continue default case defer":$.controlKeyword,"in of await yield void typeof delete instanceof as satisfies":$.operatorKeyword,"let var const using function class extends":$.definitionKeyword,"import export from":$.moduleKeyword,"with debugger new":$.keyword,TemplateString:$.special($.string),super:$.atom,BooleanLiteral:$.bool,this:$.self,null:$.null,Star:$.modifier,VariableName:$.variableName,"CallExpression/VariableName TaggedTemplateExpression/VariableName":$.function($.variableName),VariableDefinition:$.definition($.variableName),Label:$.labelName,PropertyName:$.propertyName,PrivatePropertyName:$.special($.propertyName),"CallExpression/MemberExpression/PropertyName":$.function($.propertyName),"FunctionDeclaration/VariableDefinition":$.function($.definition($.variableName)),"ClassDeclaration/VariableDefinition":$.definition($.className),"NewExpression/VariableName":$.className,PropertyDefinition:$.definition($.propertyName),PrivatePropertyDefinition:$.definition($.special($.propertyName)),UpdateOp:$.updateOperator,"LineComment Hashbang":$.lineComment,BlockComment:$.blockComment,Number:$.number,String:$.string,Escape:$.escape,ArithOp:$.arithmeticOperator,LogicOp:$.logicOperator,BitOp:$.bitwiseOperator,CompareOp:$.compareOperator,RegExp:$.regexp,Equals:$.definitionOperator,Arrow:$.function($.punctuation),": Spread":$.punctuation,"( )":$.paren,"[ ]":$.squareBracket,"{ }":$.brace,"InterpolationStart InterpolationEnd":$.special($.brace),".":$.derefOperator,", ;":$.separator,"@":$.meta,TypeName:$.typeName,TypeDefinition:$.definition($.typeName),"type enum interface implements namespace module declare":$.definitionKeyword,"abstract global Privacy readonly override":$.modifier,"is keyof unique infer asserts":$.operatorKeyword,JSXAttributeValue:$.attributeValue,JSXText:$.content,"JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag":$.angleBracket,"JSXIdentifier JSXNameSpacedName":$.tagName,"JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName":$.attributeName,"JSXBuiltin/JSXIdentifier":$.standard($.tagName)}),RX={__proto__:null,export:20,as:25,from:33,default:36,async:41,function:42,in:52,out:55,const:56,extends:60,this:64,true:72,false:72,null:84,void:88,typeof:92,super:108,new:142,delete:154,yield:163,await:167,class:172,public:235,private:235,protected:235,readonly:237,instanceof:256,satisfies:259,import:292,keyof:349,unique:353,infer:359,asserts:395,is:397,abstract:417,implements:419,type:421,let:424,var:426,using:429,interface:435,enum:439,namespace:445,module:447,declare:451,global:455,defer:471,for:476,of:485,while:488,with:492,do:496,if:500,else:502,switch:506,case:512,try:518,catch:522,finally:526,return:530,throw:534,break:538,continue:542,debugger:546},zX={__proto__:null,async:129,get:131,set:133,declare:195,public:197,private:197,protected:197,static:199,abstract:201,override:203,readonly:209,accessor:211,new:401},BX={__proto__:null,"<":193},VX=nX.deserialize({version:14,states:"$F|Q%TQlOOO%[QlOOO'_QpOOP(lO`OOO*zQ!0MxO'#CiO+RO#tO'#CjO+aO&jO'#CjO+oO#@ItO'#DaO.QQlO'#DgO.bQlO'#DrO%[QlO'#DzO0fQlO'#ESOOQ!0Lf'#E['#E[O1PQ`O'#EXOOQO'#Ep'#EpOOQO'#Il'#IlO1XQ`O'#GsO1dQ`O'#EoO1iQ`O'#EoO3hQ!0MxO'#JrO6[Q!0MxO'#JsO6uQ`O'#F]O6zQ,UO'#FtOOQ!0Lf'#Ff'#FfO7VO7dO'#FfO9XQMhO'#F|O9`Q`O'#F{OOQ!0Lf'#Js'#JsOOQ!0Lb'#Jr'#JrO9eQ`O'#GwOOQ['#K_'#K_O9pQ`O'#IYO9uQ!0LrO'#IZOOQ['#J`'#J`OOQ['#I_'#I_Q`QlOOQ`QlOOO9}Q!L^O'#DvO:UQlO'#EOO:]QlO'#EQO9kQ`O'#GsO:dQMhO'#CoO:rQ`O'#EnO:}Q`O'#EyO;hQMhO'#FeO;xQ`O'#GsOOQO'#K`'#K`O;}Q`O'#K`O<]Q`O'#G{O<]Q`O'#G|O<]Q`O'#HOO9kQ`O'#HRO=SQ`O'#HUO>kQ`O'#CeO>{Q`O'#HcO?TQ`O'#HiO?TQ`O'#HkO`QlO'#HmO?TQ`O'#HoO?TQ`O'#HrO?YQ`O'#HxO?_Q!0LsO'#IOO%[QlO'#IQO?jQ!0LsO'#ISO?uQ!0LsO'#IUO9uQ!0LrO'#IWO@QQ!0MxO'#CiOASQpO'#DlQOQ`OOO%[QlO'#EQOAjQ`O'#ETO:dQMhO'#EnOAuQ`O'#EnOBQQ!bO'#FeOOQ['#Cg'#CgOOQ!0Lb'#Dq'#DqOOQ!0Lb'#Jv'#JvO%[QlO'#JvOOQO'#Jy'#JyOOQO'#Ih'#IhOCQQpO'#EgOOQ!0Lb'#Ef'#EfOOQ!0Lb'#J}'#J}OC|Q!0MSO'#EgODWQpO'#EWOOQO'#Jx'#JxODlQpO'#JyOEyQpO'#EWODWQpO'#EgPFWO&2DjO'#CbPOOO)CD})CD}OOOO'#I`'#I`OFcO#tO,59UOOQ!0Lh,59U,59UOOOO'#Ia'#IaOFqO&jO,59UOGPQ!L^O'#DcOOOO'#Ic'#IcOGWO#@ItO,59{OOQ!0Lf,59{,59{OGfQlO'#IdOGyQ`O'#JtOIxQ!fO'#JtO+}QlO'#JtOJPQ`O,5:ROJgQ`O'#EpOJtQ`O'#KTOKPQ`O'#KSOKPQ`O'#KSOKXQ`O,5;^OK^Q`O'#KROOQ!0Ln,5:^,5:^OKeQlO,5:^OMcQ!0MxO,5:fONSQ`O,5:nONmQ!0LrO'#KQONtQ`O'#KPO9eQ`O'#KPO! YQ`O'#KPO! bQ`O,5;]O! gQ`O'#KPO!#lQ!fO'#JsOOQ!0Lh'#Ci'#CiO%[QlO'#ESO!$[Q!fO,5:sOOQS'#Jz'#JzOOQO-E<j-E<jO9kQ`O,5=_O!$rQ`O,5=_O!$wQlO,5;ZO!&zQMhO'#EkO!(eQ`O,5;ZO!(jQlO'#DyO!(tQpO,5;dO!(|QpO,5;dO%[QlO,5;dOOQ['#FT'#FTOOQ['#FV'#FVO%[QlO,5;eO%[QlO,5;eO%[QlO,5;eO%[QlO,5;eO%[QlO,5;eO%[QlO,5;eO%[QlO,5;eO%[QlO,5;eO%[QlO,5;eO%[QlO,5;eOOQ['#FZ'#FZO!)[QlO,5;tOOQ!0Lf,5;y,5;yOOQ!0Lf,5;z,5;zOOQ!0Lf,5;|,5;|O%[QlO'#IpO!+_Q!0LrO,5<iO%[QlO,5;eO!&zQMhO,5;eO!+|QMhO,5;eO!-nQMhO'#E^O%[QlO,5;wOOQ!0Lf,5;{,5;{O!-uQ,UO'#FjO!.rQ,UO'#KXO!.^Q,UO'#KXO!.yQ,UO'#KXOOQO'#KX'#KXO!/_Q,UO,5<SOOOW,5<`,5<`O!/pQlO'#FvOOOW'#Io'#IoO7VO7dO,5<QO!/wQ,UO'#FxOOQ!0Lf,5<Q,5<QO!0hQ$IUO'#CyOOQ!0Lh'#C}'#C}O!0{O#@ItO'#DRO!1iQMjO,5<eO!1pQ`O,5<hO!3YQ(CWO'#GXO!3jQ`O'#GYO!3oQ`O'#GYO!5_Q(CWO'#G^O!6dQpO'#GbOOQO'#Gn'#GnO!,TQMhO'#GmOOQO'#Gp'#GpO!,TQMhO'#GoO!7VQ$IUO'#JlOOQ!0Lh'#Jl'#JlO!7aQ`O'#JkO!7oQ`O'#JjO!7wQ`O'#CuOOQ!0Lh'#C{'#C{O!8YQ`O'#C}OOQ!0Lh'#DV'#DVOOQ!0Lh'#DX'#DXO!8_Q`O,5<eO1SQ`O'#DZO!,TQMhO'#GPO!,TQMhO'#GRO!8gQ`O'#GTO!8lQ`O'#GUO!3oQ`O'#G[O!,TQMhO'#GaO<]Q`O'#JkO!8qQ`O'#EqO!9`Q`O,5<gOOQ!0Lb'#Cr'#CrO!9hQ`O'#ErO!:bQpO'#EsOOQ!0Lb'#KR'#KRO!:iQ!0LrO'#KaO9uQ!0LrO,5=cO`QlO,5>tOOQ['#Jh'#JhOOQ[,5>u,5>uOOQ[-E<]-E<]O!<hQ!0MxO,5:bO!:]QpO,5:`O!?RQ!0MxO,5:jO%[QlO,5:jO!AiQ!0MxO,5:lOOQO,5@z,5@zO!BYQMhO,5=_O!BhQ!0LrO'#JiO9`Q`O'#JiO!ByQ!0LrO,59ZO!CUQpO,59ZO!C^QMhO,59ZO:dQMhO,59ZO!CiQ`O,5;ZO!CqQ`O'#HbO!DVQ`O'#KdO%[QlO,5;}O!:]QpO,5<PO!D_Q`O,5=zO!DdQ`O,5=zO!DiQ`O,5=zO!DwQ`O,5=zO9uQ!0LrO,5=zO<]Q`O,5=jOOQO'#Cy'#CyO!EOQpO,5=gO!EWQMhO,5=hO!EcQ`O,5=jO!EhQ!bO,5=mO!EpQ`O'#K`O?YQ`O'#HWO9kQ`O'#HYO!EuQ`O'#HYO:dQMhO'#H[O!EzQ`O'#H[OOQ[,5=p,5=pO!FPQ`O'#H]O!FbQ`O'#CoO!FgQ`O,59PO!FqQ`O,59PO!HvQlO,59POOQ[,59P,59PO!IWQ!0LrO,59PO%[QlO,59PO!KcQlO'#HeOOQ['#Hf'#HfOOQ['#Hg'#HgO`QlO,5=}O!KyQ`O,5=}O`QlO,5>TO`QlO,5>VO!LOQ`O,5>XO`QlO,5>ZO!LTQ`O,5>^O!LYQlO,5>dOOQ[,5>j,5>jO%[QlO,5>jO9uQ!0LrO,5>lOOQ[,5>n,5>nO#!dQ`O,5>nOOQ[,5>p,5>pO#!dQ`O,5>pOOQ[,5>r,5>rO##QQpO'#D_O%[QlO'#JvO##sQpO'#JvO##}QpO'#DmO#$`QpO'#DmO#&qQlO'#DmO#&xQ`O'#JuO#'QQ`O,5:WO#'VQ`O'#EtO#'eQ`O'#KUO#'mQ`O,5;_O#'rQpO'#DmO#(PQpO'#EVOOQ!0Lf,5:o,5:oO%[QlO,5:oO#(WQ`O,5:oO?YQ`O,5;YO!CUQpO,5;YO!C^QMhO,5;YO:dQMhO,5;YO#(`Q`O,5@bO#(eQ07dO,5:sOOQO-E<f-E<fO#)kQ!0MSO,5;RODWQpO,5:rO#)uQpO,5:rODWQpO,5;RO!ByQ!0LrO,5:rOOQ!0Lb'#Ej'#EjOOQO,5;R,5;RO%[QlO,5;RO#*SQ!0LrO,5;RO#*_Q!0LrO,5;RO!CUQpO,5:rOOQO,5;X,5;XO#*mQ!0LrO,5;RPOOO'#I^'#I^P#+RO&2DjO,58|POOO,58|,58|OOOO-E<^-E<^OOQ!0Lh1G.p1G.pOOOO-E<_-E<_OOOO,59},59}O#+^Q!bO,59}OOOO-E<a-E<aOOQ!0Lf1G/g1G/gO#+cQ!fO,5?OO+}QlO,5?OOOQO,5?U,5?UO#+mQlO'#IdOOQO-E<b-E<bO#+zQ`O,5@`O#,SQ!fO,5@`O#,ZQ`O,5@nOOQ!0Lf1G/m1G/mO%[QlO,5@oO#,cQ`O'#IjOOQO-E<h-E<hO#,ZQ`O,5@nOOQ!0Lb1G0x1G0xOOQ!0Ln1G/x1G/xOOQ!0Ln1G0Y1G0YO%[QlO,5@lO#,wQ!0LrO,5@lO#-YQ!0LrO,5@lO#-aQ`O,5@kO9eQ`O,5@kO#-iQ`O,5@kO#-wQ`O'#ImO#-aQ`O,5@kOOQ!0Lb1G0w1G0wO!(tQpO,5:uO!)PQpO,5:uOOQS,5:w,5:wO#.iQdO,5:wO#.qQMhO1G2yO9kQ`O1G2yOOQ!0Lf1G0u1G0uO#/PQ!0MxO1G0uO#0UQ!0MvO,5;VOOQ!0Lh'#GW'#GWO#0rQ!0MzO'#JlO!$wQlO1G0uO#2}Q!fO'#JwO%[QlO'#JwO#3XQ`O,5:eOOQ!0Lh'#D_'#D_OOQ!0Lf1G1O1G1OO%[QlO1G1OOOQ!0Lf1G1f1G1fO#3^Q`O1G1OO#5rQ!0MxO1G1PO#5yQ!0MxO1G1PO#8aQ!0MxO1G1PO#8hQ!0MxO1G1PO#;OQ!0MxO1G1PO#=fQ!0MxO1G1PO#=mQ!0MxO1G1PO#=tQ!0MxO1G1PO#@[Q!0MxO1G1PO#@cQ!0MxO1G1PO#BpQ?MtO'#CiO#DkQ?MtO1G1`O#DrQ?MtO'#JsO#EVQ!0MxO,5?[OOQ!0Lb-E<n-E<nO#GdQ!0MxO1G1PO#HaQ!0MzO1G1POOQ!0Lf1G1P1G1PO#IdQMjO'#J|O#InQ`O,5:xO#IsQ!0MxO1G1cO#JgQ,UO,5<WO#JoQ,UO,5<XO#JwQ,UO'#FoO#K`Q`O'#FnOOQO'#KY'#KYOOQO'#In'#InO#KeQ,UO1G1nOOQ!0Lf1G1n1G1nOOOW1G1y1G1yO#KvQ?MtO'#JrO#LQQ`O,5<bO!)[QlO,5<bOOOW-E<m-E<mOOQ!0Lf1G1l1G1lO#LVQpO'#KXOOQ!0Lf,5<d,5<dO#L_QpO,5<dO#LdQMhO'#DTOOOO'#Ib'#IbO#LkO#@ItO,59mOOQ!0Lh,59m,59mO%[QlO1G2PO!8lQ`O'#IrO#LvQ`O,5<zOOQ!0Lh,5<w,5<wO!,TQMhO'#IuO#MdQMjO,5=XO!,TQMhO'#IwO#NVQMjO,5=ZO!&zQMhO,5=]OOQO1G2S1G2SO#NaQ!dO'#CrO#NtQ(CWO'#ErO$ |QpO'#GbO$!dQ!dO,5<sO$!kQ`O'#K[O9eQ`O'#K[O$!yQ`O,5<uO$#aQ!dO'#C{O!,TQMhO,5<tO$#kQ`O'#GZO$$PQ`O,5<tO$$UQ!dO'#GWO$$cQ!dO'#K]O$$mQ`O'#K]O!&zQMhO'#K]O$$rQ`O,5<xO$$wQlO'#JvO$%RQpO'#GcO#$`QpO'#GcO$%dQ`O'#GgO!3oQ`O'#GkO$%iQ!0LrO'#ItO$%tQpO,5<|OOQ!0Lp,5<|,5<|O$%{QpO'#GcO$&YQpO'#GdO$&kQpO'#GdO$&pQMjO,5=XO$'QQMjO,5=ZOOQ!0Lh,5=^,5=^O!,TQMhO,5@VO!,TQMhO,5@VO$'bQ`O'#IyO$'vQ`O,5@UO$(OQ`O,59aOOQ!0Lh,59i,59iO$(TQ`O,5@VO$)TQ$IYO,59uOOQ!0Lh'#Jp'#JpO$)vQMjO,5<kO$*iQMjO,5<mO@zQ`O,5<oOOQ!0Lh,5<p,5<pO$*sQ`O,5<vO$*xQMjO,5<{O$+YQ`O'#KPO!$wQlO1G2RO$+_Q`O1G2RO9eQ`O'#KSO9eQ`O'#EtO%[QlO'#EtO9eQ`O'#I{O$+dQ!0LrO,5@{OOQ[1G2}1G2}OOQ[1G4`1G4`OOQ!0Lf1G/|1G/|OOQ!0Lf1G/z1G/zO$-fQ!0MxO1G0UOOQ[1G2y1G2yO!&zQMhO1G2yO%[QlO1G2yO#.tQ`O1G2yO$/jQMhO'#EkOOQ!0Lb,5@T,5@TO$/wQ!0LrO,5@TOOQ[1G.u1G.uO!ByQ!0LrO1G.uO!CUQpO1G.uO!C^QMhO1G.uO$0YQ`O1G0uO$0_Q`O'#CiO$0jQ`O'#KeO$0rQ`O,5=|O$0wQ`O'#KeO$0|Q`O'#KeO$1[Q`O'#JRO$1jQ`O,5AOO$1rQ!fO1G1iOOQ!0Lf1G1k1G1kO9kQ`O1G3fO@zQ`O1G3fO$1yQ`O1G3fO$2OQ`O1G3fO!DiQ`O1G3fO9uQ!0LrO1G3fOOQ[1G3f1G3fO!EcQ`O1G3UO!&zQMhO1G3RO$2TQ`O1G3ROOQ[1G3S1G3SO!&zQMhO1G3SO$2YQ`O1G3SO$2bQpO'#HQOOQ[1G3U1G3UO!6_QpO'#I}O!EhQ!bO1G3XOOQ[1G3X1G3XOOQ[,5=r,5=rO$2jQMhO,5=tO9kQ`O,5=tO$%dQ`O,5=vO9`Q`O,5=vO!CUQpO,5=vO!C^QMhO,5=vO:dQMhO,5=vO$2xQ`O'#KcO$3TQ`O,5=wOOQ[1G.k1G.kO$3YQ!0LrO1G.kO@zQ`O1G.kO$3eQ`O1G.kO9uQ!0LrO1G.kO$5mQ!fO,5AQO$5zQ`O,5AQO9eQ`O,5AQO$6VQlO,5>PO$6^Q`O,5>POOQ[1G3i1G3iO`QlO1G3iOOQ[1G3o1G3oOOQ[1G3q1G3qO?TQ`O1G3sO$6cQlO1G3uO$:gQlO'#HtOOQ[1G3x1G3xO$:tQ`O'#HzO?YQ`O'#H|OOQ[1G4O1G4OO$:|QlO1G4OO9uQ!0LrO1G4UOOQ[1G4W1G4WOOQ!0Lb'#G_'#G_O9uQ!0LrO1G4YO9uQ!0LrO1G4[O$?TQ`O,5@bO!)[QlO,5;`O9eQ`O,5;`O?YQ`O,5:XO!)[QlO,5:XO!CUQpO,5:XO$?YQ?MtO,5:XOOQO,5;`,5;`O$?dQpO'#IeO$?zQ`O,5@aOOQ!0Lf1G/r1G/rO$@SQpO'#IkO$@^Q`O,5@pOOQ!0Lb1G0y1G0yO#$`QpO,5:XOOQO'#Ig'#IgO$@fQpO,5:qOOQ!0Ln,5:q,5:qO#(ZQ`O1G0ZOOQ!0Lf1G0Z1G0ZO%[QlO1G0ZOOQ!0Lf1G0t1G0tO?YQ`O1G0tO!CUQpO1G0tO!C^QMhO1G0tOOQ!0Lb1G5|1G5|O!ByQ!0LrO1G0^OOQO1G0m1G0mO%[QlO1G0mO$@mQ!0LrO1G0mO$@xQ!0LrO1G0mO!CUQpO1G0^ODWQpO1G0^O$AWQ!0LrO1G0mOOQO1G0^1G0^O$AlQ!0MxO1G0mPOOO-E<[-E<[POOO1G.h1G.hOOOO1G/i1G/iO$AvQ!bO,5<iO$BOQ!fO1G4jOOQO1G4p1G4pO%[QlO,5?OO$BYQ`O1G5zO$BbQ`O1G6YO$BjQ!fO1G6ZO9eQ`O,5?UO$BtQ!0MxO1G6WO%[QlO1G6WO$CUQ!0LrO1G6WO$CgQ`O1G6VO$CgQ`O1G6VO9eQ`O1G6VO$CoQ`O,5?XO9eQ`O,5?XOOQO,5?X,5?XO$DTQ`O,5?XO$+YQ`O,5?XOOQO-E<k-E<kOOQS1G0a1G0aOOQS1G0c1G0cO#.lQ`O1G0cOOQ[7+(e7+(eO!&zQMhO7+(eO%[QlO7+(eO$DcQ`O7+(eO$DnQMhO7+(eO$D|Q!0MzO,5=XO$GXQ!0MzO,5=ZO$IdQ!0MzO,5=XO$KuQ!0MzO,5=ZO$NWQ!0MzO,59uO%!]Q!0MzO,5<kO%$hQ!0MzO,5<mO%&sQ!0MzO,5<{OOQ!0Lf7+&a7+&aO%)UQ!0MxO7+&aO%)xQlO'#IfO%*VQ`O,5@cO%*_Q!fO,5@cOOQ!0Lf1G0P1G0PO%*iQ`O7+&jOOQ!0Lf7+&j7+&jO%*nQ?MtO,5:fO%[QlO7+&zO%*xQ?MtO,5:bO%+VQ?MtO,5:jO%+aQ?MtO,5:lO%+kQMhO'#IiO%+uQ`O,5@hOOQ!0Lh1G0d1G0dOOQO1G1r1G1rOOQO1G1s1G1sO%+}Q!jO,5<ZO!)[QlO,5<YOOQO-E<l-E<lOOQ!0Lf7+'Y7+'YOOOW7+'e7+'eOOOW1G1|1G1|O%,YQ`O1G1|OOQ!0Lf1G2O1G2OOOOO,59o,59oO%,_Q!dO,59oOOOO-E<`-E<`OOQ!0Lh1G/X1G/XO%,fQ!0MxO7+'kOOQ!0Lh,5?^,5?^O%-YQMhO1G2fP%-aQ`O'#IrPOQ!0Lh-E<p-E<pO%-}QMjO,5?aOOQ!0Lh-E<s-E<sO%.pQMjO,5?cOOQ!0Lh-E<u-E<uO%.zQ!dO1G2wO%/RQ!dO'#CrO%/iQMhO'#KSO$$wQlO'#JvOOQ!0Lh1G2_1G2_O%/sQ`O'#IqO%0[Q`O,5@vO%0[Q`O,5@vO%0dQ`O,5@vO%0oQ`O,5@vOOQO1G2a1G2aO%0}QMjO1G2`O$+YQ`O'#K[O!,TQMhO1G2`O%1_Q(CWO'#IsO%1lQ`O,5@wO!&zQMhO,5@wO%1tQ!dO,5@wOOQ!0Lh1G2d1G2dO%4UQ!fO'#CiO%4`Q`O,5=POOQ!0Lb,5<},5<}O%4hQpO,5<}OOQ!0Lb,5=O,5=OOCwQ`O,5<}O%4sQpO,5<}OOQ!0Lb,5=R,5=RO$+YQ`O,5=VOOQO,5?`,5?`OOQO-E<r-E<rOOQ!0Lp1G2h1G2hO#$`QpO,5<}O$$wQlO,5=PO%5RQ`O,5=OO%5^QpO,5=OO!,TQMhO'#IuO%6WQMjO1G2sO!,TQMhO'#IwO%6yQMjO1G2uO%7TQMjO1G5qO%7_QMjO1G5qOOQO,5?e,5?eOOQO-E<w-E<wOOQO1G.{1G.{O!,TQMhO1G5qO!,TQMhO1G5qO!:]QpO,59wO%[QlO,59wOOQ!0Lh,5<j,5<jO%7lQ`O1G2ZO!,TQMhO1G2bO%7qQ!0MxO7+'mOOQ!0Lf7+'m7+'mO!$wQlO7+'mO%8eQ`O,5;`OOQ!0Lb,5?g,5?gOOQ!0Lb-E<y-E<yO%8jQ!dO'#K^O#(ZQ`O7+(eO4UQ!fO7+(eO$DfQ`O7+(eO%8tQ!0MvO'#CiO%9XQ!0MvO,5=SO%9lQ`O,5=SO%9tQ`O,5=SOOQ!0Lb1G5o1G5oOOQ[7+$a7+$aO!ByQ!0LrO7+$aO!CUQpO7+$aO!$wQlO7+&aO%9yQ`O'#JQO%:bQ`O,5APOOQO1G3h1G3hO9kQ`O,5APO%:bQ`O,5APO%:jQ`O,5APOOQO,5?m,5?mOOQO-E=P-E=POOQ!0Lf7+'T7+'TO%:oQ`O7+)QO9uQ!0LrO7+)QO9kQ`O7+)QO@zQ`O7+)QO%:tQ`O7+)QOOQ[7+)Q7+)QOOQ[7+(p7+(pO%:yQ!0MvO7+(mO!&zQMhO7+(mO!E^Q`O7+(nOOQ[7+(n7+(nO!&zQMhO7+(nO%;TQ`O'#KbO%;`Q`O,5=lOOQO,5?i,5?iOOQO-E<{-E<{OOQ[7+(s7+(sO%<rQpO'#HZOOQ[1G3`1G3`O!&zQMhO1G3`O%[QlO1G3`O%<yQ`O1G3`O%=UQMhO1G3`O9uQ!0LrO1G3bO$%dQ`O1G3bO9`Q`O1G3bO!CUQpO1G3bO!C^QMhO1G3bO%=dQ`O'#JPO%=xQ`O,5@}O%>QQpO,5@}OOQ!0Lb1G3c1G3cOOQ[7+$V7+$VO@zQ`O7+$VO9uQ!0LrO7+$VO%>]Q`O7+$VO%[QlO1G6lO%[QlO1G6mO%>bQ!0LrO1G6lO%>lQlO1G3kO%>sQ`O1G3kO%>xQlO1G3kOOQ[7+)T7+)TO9uQ!0LrO7+)_O`QlO7+)aOOQ['#Kh'#KhOOQ['#JS'#JSO%?PQlO,5>`OOQ[,5>`,5>`O%[QlO'#HuO%?^Q`O'#HwOOQ[,5>f,5>fO9eQ`O,5>fOOQ[,5>h,5>hOOQ[7+)j7+)jOOQ[7+)p7+)pOOQ[7+)t7+)tOOQ[7+)v7+)vO%?cQpO1G5|O%?}Q?MtO1G0zO%@XQ`O1G0zOOQO1G/s1G/sO%@dQ?MtO1G/sO?YQ`O1G/sO!)[QlO'#DmOOQO,5?P,5?POOQO-E<c-E<cOOQO,5?V,5?VOOQO-E<i-E<iO!CUQpO1G/sOOQO-E<e-E<eOOQ!0Ln1G0]1G0]OOQ!0Lf7+%u7+%uO#(ZQ`O7+%uOOQ!0Lf7+&`7+&`O?YQ`O7+&`O!CUQpO7+&`OOQO7+%x7+%xO$AlQ!0MxO7+&XOOQO7+&X7+&XO%[QlO7+&XO%@nQ!0LrO7+&XO!ByQ!0LrO7+%xO!CUQpO7+%xO%@yQ!0LrO7+&XO%AXQ!0MxO7++rO%[QlO7++rO%AiQ`O7++qO%AiQ`O7++qOOQO1G4s1G4sO9eQ`O1G4sO%AqQ`O1G4sOOQS7+%}7+%}O#(ZQ`O<<LPO4UQ!fO<<LPO%BPQ`O<<LPOOQ[<<LP<<LPO!&zQMhO<<LPO%[QlO<<LPO%BXQ`O<<LPO%BdQ!0MzO,5?aO%DoQ!0MzO,5?cO%FzQ!0MzO1G2`O%I]Q!0MzO1G2sO%KhQ!0MzO1G2uO%MsQ!fO,5?QO%[QlO,5?QOOQO-E<d-E<dO%M}Q`O1G5}OOQ!0Lf<<JU<<JUO%NVQ?MtO1G0uO&!^Q?MtO1G1PO&!eQ?MtO1G1PO&$fQ?MtO1G1PO&$mQ?MtO1G1PO&&nQ?MtO1G1PO&(oQ?MtO1G1PO&(vQ?MtO1G1PO&(}Q?MtO1G1PO&+OQ?MtO1G1PO&+VQ?MtO1G1PO&+^Q!0MxO<<JfO&-UQ?MtO1G1PO&.RQ?MvO1G1PO&/UQ?MvO'#JlO&1[Q?MtO1G1cO&1iQ?MtO1G0UO&1sQMjO,5?TOOQO-E<g-E<gO!)[QlO'#FqOOQO'#KZ'#KZOOQO1G1u1G1uO&1}Q`O1G1tO&2SQ?MtO,5?[OOOW7+'h7+'hOOOO1G/Z1G/ZO&2^Q!dO1G4xOOQ!0Lh7+(Q7+(QP!&zQMhO,5?^O!,TQMhO7+(cO&2eQ`O,5?]O9eQ`O,5?]O$+YQ`O,5?]OOQO-E<o-E<oO&2sQ`O1G6bO&2sQ`O1G6bO&2{Q`O1G6bO&3WQMjO7+'zO&3hQ!dO,5?_O&3rQ`O,5?_O!&zQMhO,5?_OOQO-E<q-E<qO&3wQ!dO1G6cO&4RQ`O1G6cO&4ZQ`O1G2kO!&zQMhO1G2kOOQ!0Lb1G2i1G2iOOQ!0Lb1G2j1G2jO%4hQpO1G2iO!CUQpO1G2iOCwQ`O1G2iOOQ!0Lb1G2q1G2qO&4`QpO1G2iO&4nQ`O1G2kO$+YQ`O1G2jOCwQ`O1G2jO$$wQlO1G2kO&4vQ`O1G2jO&5jQMjO,5?aOOQ!0Lh-E<t-E<tO&6]QMjO,5?cOOQ!0Lh-E<v-E<vO!,TQMhO7++]O&6gQMjO7++]O&6qQMjO7++]OOQ!0Lh1G/c1G/cO&7OQ`O1G/cOOQ!0Lh7+'u7+'uO&7TQMjO7+'|O&7eQ!0MxO<<KXOOQ!0Lf<<KX<<KXO&8XQ`O1G0zO!&zQMhO'#IzO&8^Q`O,5@xO&:`Q!fO<<LPO!&zQMhO1G2nO&:gQ!0LrO1G2nOOQ[<<G{<<G{O!ByQ!0LrO<<G{O&:xQ!0MxO<<I{OOQ!0Lf<<I{<<I{OOQO,5?l,5?lO&;lQ`O,5?lO&;qQ`O,5?lOOQO-E=O-E=OO&<PQ`O1G6kO&<PQ`O1G6kO9kQ`O1G6kO@zQ`O<<LlOOQ[<<Ll<<LlO&<XQ`O<<LlO9uQ!0LrO<<LlO9kQ`O<<LlOOQ[<<LX<<LXO%:yQ!0MvO<<LXOOQ[<<LY<<LYO!E^Q`O<<LYO&<^QpO'#I|O&<iQ`O,5@|O!)[QlO,5@|OOQ[1G3W1G3WOOQO'#JO'#JOO9uQ!0LrO'#JOO&<qQpO,5=uOOQ[,5=u,5=uO&<xQpO'#EgO&=PQpO'#GeO&=UQ`O7+(zO&=ZQ`O7+(zOOQ[7+(z7+(zO!&zQMhO7+(zO%[QlO7+(zO&=cQ`O7+(zOOQ[7+(|7+(|O9uQ!0LrO7+(|O$%dQ`O7+(|O9`Q`O7+(|O!CUQpO7+(|O&=nQ`O,5?kOOQO-E<}-E<}OOQO'#H^'#H^O&=yQ`O1G6iO9uQ!0LrO<<GqOOQ[<<Gq<<GqO@zQ`O<<GqO&>RQ`O7+,WO&>WQ`O7+,XO%[QlO7+,WO%[QlO7+,XOOQ[7+)V7+)VO&>]Q`O7+)VO&>bQlO7+)VO&>iQ`O7+)VOOQ[<<Ly<<LyOOQ[<<L{<<L{OOQ[-E=Q-E=QOOQ[1G3z1G3zO&>nQ`O,5>aOOQ[,5>c,5>cO&>sQ`O1G4QO9eQ`O7+&fO!)[QlO7+&fOOQO7+%_7+%_O&>xQ?MtO1G6ZO?YQ`O7+%_OOQ!0Lf<<Ia<<IaOOQ!0Lf<<Iz<<IzO?YQ`O<<IzOOQO<<Is<<IsO$AlQ!0MxO<<IsO%[QlO<<IsOOQO<<Id<<IdO!ByQ!0LrO<<IdO&?SQ!0LrO<<IsO&?_Q!0MxO<= ^O&?oQ`O<= ]OOQO7+*_7+*_O9eQ`O7+*_OOQ[ANAkANAkO&?wQ!fOANAkO!&zQMhOANAkO#(ZQ`OANAkO4UQ!fOANAkO&@OQ`OANAkO%[QlOANAkO&@WQ!0MzO7+'zO&BiQ!0MzO,5?aO&DtQ!0MzO,5?cO&GPQ!0MzO7+'|O&IbQ!fO1G4lO&IlQ?MtO7+&aO&KpQ?MvO,5=XO&MwQ?MvO,5=ZO&NXQ?MvO,5=XO&NiQ?MvO,5=ZO&NyQ?MvO,59uO'#PQ?MvO,5<kO'%SQ?MvO,5<mO''hQ?MvO,5<{O')^Q?MtO7+'kO')kQ?MtO7+'mO')xQ`O,5<]OOQO7+'`7+'`OOQ!0Lh7+*d7+*dO')}QMjO<<K}OOQO1G4w1G4wO'*UQ`O1G4wO'*aQ`O1G4wO'*oQ`O7++|O'*oQ`O7++|O!&zQMhO1G4yO'*wQ!dO1G4yO'+RQ`O7++}O'+ZQ`O7+(VO'+fQ!dO7+(VOOQ!0Lb7+(T7+(TOOQ!0Lb7+(U7+(UO!CUQpO7+(TOCwQ`O7+(TO'+pQ`O7+(VO!&zQMhO7+(VO$+YQ`O7+(UO'+uQ`O7+(VOCwQ`O7+(UO'+}QMjO<<NwO!,TQMhO<<NwOOQ!0Lh7+$}7+$}O',XQ!dO,5?fOOQO-E<x-E<xO',cQ!0MvO7+(YO!&zQMhO7+(YOOQ[AN=gAN=gO9kQ`O1G5WOOQO1G5W1G5WO',sQ`O1G5WO',xQ`O7+,VO',xQ`O7+,VO9uQ!0LrOANBWO@zQ`OANBWOOQ[ANBWANBWO'-QQ`OANBWOOQ[ANAsANAsOOQ[ANAtANAtO'-VQ`O,5?hOOQO-E<z-E<zO'-bQ?MtO1G6hOOQO,5?j,5?jOOQO-E<|-E<|OOQ[1G3a1G3aO'-lQ`O,5=POOQ[<<Lf<<LfO!&zQMhO<<LfO&=UQ`O<<LfO'-qQ`O<<LfO%[QlO<<LfOOQ[<<Lh<<LhO9uQ!0LrO<<LhO$%dQ`O<<LhO9`Q`O<<LhO'-yQpO1G5VO'.UQ`O7+,TOOQ[AN=]AN=]O9uQ!0LrOAN=]OOQ[<= r<= rOOQ[<= s<= sO'.^Q`O<= rO'.cQ`O<= sOOQ[<<Lq<<LqO'.hQ`O<<LqO'.mQlO<<LqOOQ[1G3{1G3{O?YQ`O7+)lO'.tQ`O<<JQO'/PQ?MtO<<JQOOQO<<Hy<<HyOOQ!0LfAN?fAN?fOOQOAN?_AN?_O$AlQ!0MxOAN?_OOQOAN?OAN?OO%[QlOAN?_OOQO<<My<<MyOOQ[G27VG27VO!&zQMhOG27VO#(ZQ`OG27VO'/ZQ!fOG27VO4UQ!fOG27VO'/bQ`OG27VO'/jQ?MtO<<JfO'/wQ?MvO1G2`O'1mQ?MvO,5?aO'3pQ?MvO,5?cO'5sQ?MvO1G2sO'7vQ?MvO1G2uO'9yQ?MtO<<KXO':WQ?MtO<<I{OOQO1G1w1G1wO!,TQMhOANAiOOQO7+*c7+*cO':eQ`O7+*cO':pQ`O<= hO':xQ!dO7+*eOOQ!0Lb<<Kq<<KqO$+YQ`O<<KqOCwQ`O<<KqO';SQ`O<<KqO!&zQMhO<<KqOOQ!0Lb<<Ko<<KoO!CUQpO<<KoO';_Q!dO<<KqOOQ!0Lb<<Kp<<KpO';iQ`O<<KqO!&zQMhO<<KqO$+YQ`O<<KpO';nQMjOANDcO';xQ!0MvO<<KtOOQO7+*r7+*rO9kQ`O7+*rO'<YQ`O<= qOOQ[G27rG27rO9uQ!0LrOG27rO@zQ`OG27rO!)[QlO1G5SO'<bQ`O7+,SO'<jQ`O1G2kO&=UQ`OANBQOOQ[ANBQANBQO!&zQMhOANBQO'<oQ`OANBQOOQ[ANBSANBSO9uQ!0LrOANBSO$%dQ`OANBSOOQO'#H_'#H_OOQO7+*q7+*qOOQ[G22wG22wOOQ[ANE^ANE^OOQ[ANE_ANE_OOQ[ANB]ANB]O'<wQ`OANB]OOQ[<<MW<<MWO!)[QlOAN?lOOQOG24yG24yO$AlQ!0MxOG24yO#(ZQ`OLD,qOOQ[LD,qLD,qO!&zQMhOLD,qO'<|Q!fOLD,qO'=TQ?MvO7+'zO'>yQ?MvO,5?aO'@|Q?MvO,5?cO'CPQ?MvO7+'|O'DuQMjOG27TOOQO<<M}<<M}OOQ!0LbANA]ANA]O$+YQ`OANA]OCwQ`OANA]O'EVQ!dOANA]OOQ!0LbANAZANAZO'E^Q`OANA]O!&zQMhOANA]O'EiQ!dOANA]OOQ!0LbANA[ANA[OOQO<<N^<<N^OOQ[LD-^LD-^O9uQ!0LrOLD-^O'EsQ?MtO7+*nOOQO'#Gf'#GfOOQ[G27lG27lO&=UQ`OG27lO!&zQMhOG27lOOQ[G27nG27nO9uQ!0LrOG27nOOQ[G27wG27wO'E}Q?MtOG25WOOQOLD*eLD*eOOQ[!$(!]!$(!]O#(ZQ`O!$(!]O!&zQMhO!$(!]O'FXQ!0MzOG27TOOQ!0LbG26wG26wO$+YQ`OG26wO'HjQ`OG26wOCwQ`OG26wO'HuQ!dOG26wO!&zQMhOG26wOOQ[!$(!x!$(!xOOQ[LD-WLD-WO&=UQ`OLD-WOOQ[LD-YLD-YOOQ[!)9Ew!)9EwO#(ZQ`O!)9EwOOQ!0LbLD,cLD,cO$+YQ`OLD,cOCwQ`OLD,cO'H|Q`OLD,cO'IXQ!dOLD,cOOQ[!$(!r!$(!rOOQ[!.K;c!.K;cO'I`Q?MvOG27TOOQ!0Lb!$( }!$( }O$+YQ`O!$( }OCwQ`O!$( }O'KUQ`O!$( }OOQ!0Lb!)9Ei!)9EiO$+YQ`O!)9EiOCwQ`O!)9EiOOQ!0Lb!.K;T!.K;TO$+YQ`O!.K;TOOQ!0Lb!4/0o!4/0oO!)[QlO'#DzO1PQ`O'#EXO'KaQ!fO'#JrO'KhQ!L^O'#DvO'KoQlO'#EOO'KvQ!fO'#CiO'N^Q!fO'#CiO!)[QlO'#EQO'NnQlO,5;ZO!)[QlO,5;eO!)[QlO,5;eO!)[QlO,5;eO!)[QlO,5;eO!)[QlO,5;eO!)[QlO,5;eO!)[QlO,5;eO!)[QlO,5;eO!)[QlO,5;eO!)[QlO,5;eO!)[QlO'#IpO(!qQ`O,5<iO!)[QlO,5;eO(!yQMhO,5;eO($dQMhO,5;eO!)[QlO,5;wO!&zQMhO'#GmO(!yQMhO'#GmO!&zQMhO'#GoO(!yQMhO'#GoO1SQ`O'#DZO1SQ`O'#DZO!&zQMhO'#GPO(!yQMhO'#GPO!&zQMhO'#GRO(!yQMhO'#GRO!&zQMhO'#GaO(!yQMhO'#GaO!)[QlO,5:jO($kQpO'#D_O($uQpO'#JvO!)[QlO,5@oO'NnQlO1G0uO(%PQ?MtO'#CiO!)[QlO1G2PO!&zQMhO'#IuO(!yQMhO'#IuO!&zQMhO'#IwO(!yQMhO'#IwO(%ZQ!dO'#CrO!&zQMhO,5<tO(!yQMhO,5<tO'NnQlO1G2RO!)[QlO7+&zO!&zQMhO1G2`O(!yQMhO1G2`O!&zQMhO'#IuO(!yQMhO'#IuO!&zQMhO'#IwO(!yQMhO'#IwO!&zQMhO1G2bO(!yQMhO1G2bO'NnQlO7+'mO'NnQlO7+&aO!&zQMhOANAiO(!yQMhOANAiO(%nQ`O'#EoO(%sQ`O'#EoO(%{Q`O'#F]O(&QQ`O'#EyO(&VQ`O'#KTO(&bQ`O'#KRO(&mQ`O,5;ZO(&rQMjO,5<eO(&yQ`O'#GYO('OQ`O'#GYO('TQ`O,5<eO(']Q`O,5<gO('eQ`O,5;ZO('mQ?MtO1G1`O('tQ`O,5<tO('yQ`O,5<tO((OQ`O,5<vO((TQ`O,5<vO((YQ`O1G2RO((_Q`O1G0uO((dQMjO<<K}O((kQMjO<<K}O((rQMhO'#F|O9`Q`O'#F{OAuQ`O'#EnO!)[QlO,5;tO!3oQ`O'#GYO!3oQ`O'#GYO!3oQ`O'#G[O!3oQ`O'#G[O!,TQMhO7+(cO!,TQMhO7+(cO%.zQ!dO1G2wO%.zQ!dO1G2wO!&zQMhO,5=]O!&zQMhO,5=]",stateData:"()x~O'|OS'}OSTOS(ORQ~OPYOQYOSfOY!VOaqOdzOeyOl!POpkOrYOskOtkOzkO|YO!OYO!SWO!WkO!XkO!_XO!iuO!lZO!oYO!pYO!qYO!svO!uwO!xxO!|]O$W|O$niO%h}O%j!QO%l!OO%m!OO%n!OO%q!RO%s!SO%v!TO%w!TO%y!UO&W!WO&^!XO&`!YO&b!ZO&d![O&g!]O&m!^O&s!_O&u!`O&w!aO&y!bO&{!cO(TSO(VTO(YUO(aVO(o[O~OWtO~P`OPYOQYOSfOd!jOe!iOpkOrYOskOtkOzkO|YO!OYO!SWO!WkO!XkO!_!eO!iuO!lZO!oYO!pYO!qYO!svO!u!gO!x!hO$W!kO$niO(T!dO(VTO(YUO(aVO(o[O~Oa!wOs!nO!S!oO!b!yO!c!vO!d!vO!|<VO#T!pO#U!pO#V!xO#W!pO#X!pO#[!zO#]!zO(U!lO(VTO(YUO(e!mO(o!sO~O(O!{O~OP]XR]X[]Xa]Xj]Xr]X!Q]X!S]X!]]X!l]X!p]X#R]X#S]X#`]X#kfX#n]X#o]X#p]X#q]X#r]X#s]X#t]X#u]X#v]X#x]X#z]X#{]X$Q]X'z]X(a]X(r]X(y]X(z]X~O!g%RX~P(qO_!}O(V#PO(W!}O(X#PO~O_#QO(X#PO(Y#PO(Z#QO~Ox#SO!U#TO(b#TO(c#VO~OPYOQYOSfOd!jOe!iOpkOrYOskOtkOzkO|YO!OYO!SWO!WkO!XkO!_!eO!iuO!lZO!oYO!pYO!qYO!svO!u!gO!x!hO$W!kO$niO(T<ZO(VTO(YUO(aVO(o[O~O![#ZO!]#WO!Y(hP!Y(vP~P+}O!^#cO~P`OPYOQYOSfOd!jOe!iOrYOskOtkOzkO|YO!OYO!SWO!WkO!XkO!_!eO!iuO!lZO!oYO!pYO!qYO!svO!u!gO!x!hO$W!kO$niO(VTO(YUO(aVO(o[O~Op#mO![#iO!|]O#i#lO#j#iO(T<[O!k(sP~P.iO!l#oO(T#nO~O!x#sO!|]O%h#tO~O#k#uO~O!g#vO#k#uO~OP$[OR#zO[$cOj$ROr$aO!Q#yO!S#{O!]$_O!l#xO!p$[O#R$RO#n$OO#o$PO#p$PO#q$PO#r$QO#s$RO#t$RO#u$bO#v$SO#x$UO#z$WO#{$XO(aVO(r$YO(y#|O(z#}O~Oa(fX'z(fX'w(fX!k(fX!Y(fX!_(fX%i(fX!g(fX~P1qO#S$dO#`$eO$Q$eOP(gXR(gX[(gXj(gXr(gX!Q(gX!S(gX!](gX!l(gX!p(gX#R(gX#n(gX#o(gX#p(gX#q(gX#r(gX#s(gX#t(gX#u(gX#v(gX#x(gX#z(gX#{(gX(a(gX(r(gX(y(gX(z(gX!_(gX%i(gX~Oa(gX'z(gX'w(gX!Y(gX!k(gXv(gX!g(gX~P4UO#`$eO~O$]$hO$_$gO$f$mO~OSfO!_$nO$i$oO$k$qO~Oh%VOj%dOk%dOp%WOr%XOs$tOt$tOz%YO|%ZO!O%]O!S${O!_$|O!i%bO!l$xO#j%cO$W%`O$t%^O$v%_O$y%aO(T$sO(VTO(YUO(a$uO(y$}O(z%POg(^P~Ol%[O~P7eO!l%eO~O!S%hO!_%iO(T%gO~O!g%mO~Oa%nO'z%nO~O!Q%rO~P%[O(U!lO~P%[O%n%vO~P%[Oh%VO!l%eO(T%gO(U!lO~Oe%}O!l%eO(T%gO~Oj$RO~O!_&PO(T%gO(U!lO(VTO(YUO`)WP~O!Q&SO!l&RO%j&VO&T&WO~P;SO!x#sO~O%s&YO!S)SX!_)SX(T)SX~O(T&ZO~Ol!PO!u&`O%j!QO%l!OO%m!OO%n!OO%q!RO%s!SO%v!TO%w!TO~Od&eOe&dO!x&bO%h&cO%{&aO~P<bOd&hOeyOl!PO!_&gO!u&`O!xxO!|]O%h}O%l!OO%m!OO%n!OO%q!RO%s!SO%v!TO%w!TO%y!UO~Ob&kO#`&nO%j&iO(U!lO~P=gO!l&oO!u&sO~O!l#oO~O!_XO~Oa%nO'x&{O'z%nO~Oa%nO'x'OO'z%nO~Oa%nO'x'QO'z%nO~O'w]X!Y]Xv]X!k]X&[]X!_]X%i]X!g]X~P(qO!b'_O!c'WO!d'WO(U!lO(VTO(YUO~Os'UO!S'TO!['XO(e'SO!^(iP!^(xP~P@nOn'bO!_'`O(T%gO~Oe'gO!l%eO(T%gO~O!Q&SO!l&RO~Os!nO!S!oO!|<VO#T!pO#U!pO#W!pO#X!pO(U!lO(VTO(YUO(e!mO(o!sO~O!b'mO!c'lO!d'lO#V!pO#['nO#]'nO~PBYOa%nOh%VO!g#vO!l%eO'z%nO(r'pO~O!p'tO#`'rO~PChOs!nO!S!oO(VTO(YUO(e!mO(o!sO~O!_XOs(mX!S(mX!b(mX!c(mX!d(mX!|(mX#T(mX#U(mX#V(mX#W(mX#X(mX#[(mX#](mX(U(mX(V(mX(Y(mX(e(mX(o(mX~O!c'lO!d'lO(U!lO~PDWO(P'xO(Q'xO(R'zO~O_!}O(V'|O(W!}O(X'|O~O_#QO(X'|O(Y'|O(Z#QO~Ov(OO~P%[Ox#SO!U#TO(b#TO(c(RO~O![(TO!Y'WX!Y'^X!]'WX!]'^X~P+}O!](VO!Y(hX~OP$[OR#zO[$cOj$ROr$aO!Q#yO!S#{O!](VO!l#xO!p$[O#R$RO#n$OO#o$PO#p$PO#q$PO#r$QO#s$RO#t$RO#u$bO#v$SO#x$UO#z$WO#{$XO(aVO(r$YO(y#|O(z#}O~O!Y(hX~PHRO!Y([O~O!Y(uX!](uX!g(uX!k(uX(r(uX~O#`(uX#k#dX!^(uX~PJUO#`(]O!Y(wX!](wX~O!](^O!Y(vX~O!Y(aO~O#`$eO~PJUO!^(bO~P`OR#zO!Q#yO!S#{O!l#xO(aVOP!na[!naj!nar!na!]!na!p!na#R!na#n!na#o!na#p!na#q!na#r!na#s!na#t!na#u!na#v!na#x!na#z!na#{!na(r!na(y!na(z!na~Oa!na'z!na'w!na!Y!na!k!nav!na!_!na%i!na!g!na~PKlO!k(cO~O!g#vO#`(dO(r'pO!](tXa(tX'z(tX~O!k(tX~PNXO!S%hO!_%iO!|]O#i(iO#j(hO(T%gO~O!](jO!k(sX~O!k(lO~O!S%hO!_%iO#j(hO(T%gO~OP(gXR(gX[(gXj(gXr(gX!Q(gX!S(gX!](gX!l(gX!p(gX#R(gX#n(gX#o(gX#p(gX#q(gX#r(gX#s(gX#t(gX#u(gX#v(gX#x(gX#z(gX#{(gX(a(gX(r(gX(y(gX(z(gX~O!g#vO!k(gX~P! uOR(nO!Q(mO!l#xO#S$dO!|!{a!S!{a~O!x!{a%h!{a!_!{a#i!{a#j!{a(T!{a~P!#vO!x(rO~OPYOQYOSfOd!jOe!iOpkOrYOskOtkOzkO|YO!OYO!SWO!WkO!XkO!_XO!iuO!lZO!oYO!pYO!qYO!svO!u!gO!x!hO$W!kO$niO(T!dO(VTO(YUO(aVO(o[O~Oh%VOp%WOr%XOs$tOt$tOz%YO|%ZO!O<sO!S${O!_$|O!i>VO!l$xO#j<yO$W%`O$t<uO$v<wO$y%aO(T(vO(VTO(YUO(a$uO(y$}O(z%PO~O#k(xO~O![(zO!k(kP~P%[O(e(|O(o[O~O!S)OO!l#xO(e(|O(o[O~OP<UOQ<UOSfOd>ROe!iOpkOr<UOskOtkOzkO|<UO!O<UO!SWO!WkO!XkO!_!eO!i<XO!lZO!o<UO!p<UO!q<UO!s<YO!u<]O!x!hO$W!kO$n>PO(T)]O(VTO(YUO(aVO(o[O~O!]$_Oa$qa'z$qa'w$qa!k$qa!Y$qa!_$qa%i$qa!g$qa~Ol)dO~P!&zOh%VOp%WOr%XOs$tOt$tOz%YO|%ZO!O%]O!S${O!_$|O!i%bO!l$xO#j%cO$W%`O$t%^O$v%_O$y%aO(T(vO(VTO(YUO(a$uO(y$}O(z%PO~Og(pP~P!,TO!Q)iO!g)hO!_$^X$Z$^X$]$^X$_$^X$f$^X~O!g)hO!_({X$Z({X$]({X$_({X$f({X~O!Q)iO~P!.^O!Q)iO!_({X$Z({X$]({X$_({X$f({X~O!_)kO$Z)oO$])jO$_)jO$f)pO~O![)sO~P!)[O$]$hO$_$gO$f)wO~On$zX!Q$zX#S$zX'y$zX(y$zX(z$zX~OgmXg$zXnmX!]mX#`mX~P!0SOx)yO(b)zO(c)|O~On*VO!Q*OO'y*PO(y$}O(z%PO~Og)}O~P!1WOg*WO~Oh%VOr%XOs$tOt$tOz%YO|%ZO!O<sO!S*YO!_*ZO!i>VO!l$xO#j<yO$W%`O$t<uO$v<wO$y%aO(VTO(YUO(a$uO(y$}O(z%PO~Op*`O}O(T&ZO~O!l+SO~O(T(vO~Op+WO!S%hO![#iO!_%iO!|]O#i#lO#j#iO(T%gO!k(sP~O!g#vO#k+XO~O!S%hOTX'z)TX~OP$[OR#zO[$cOj$ROr$aO!Q#yO!S#{O!l#xO!p$[O#R$RO#n$OO#o$PO#p$PO#q$PO#r$QO#s$RO#t$RO#u$bO#v$SO#x$UO#z$WO#{$XO(aVO(r$YO(y#|O(z#}O~Oa!ja!]!ja'z!ja'w!ja!Y!ja!k!jav!ja!_!ja%i!ja!g!ja~P!:tOR#zO!Q#yO!S#{O!l#xO(aVOP!ra[!raj!rar!ra!]!ra!p!ra#R!ra#n!ra#o!ra#p!ra#q!ra#r!ra#s!ra#t!ra#u!ra#v!ra#x!ra#z!ra#{!ra(r!ra(y!ra(z!ra~Oa!ra'z!ra'w!ra!Y!ra!k!rav!ra!_!ra%i!ra!g!ra~P!=[OR#zO!Q#yO!S#{O!l#xO(aVOP!ta[!taj!tar!ta!]!ta!p!ta#R!ta#n!ta#o!ta#p!ta#q!ta#r!ta#s!ta#t!ta#u!ta#v!ta#x!ta#z!ta#{!ta(r!ta(y!ta(z!ta~Oa!ta'z!ta'w!ta!Y!ta!k!tav!ta!_!ta%i!ta!g!ta~P!?rOh%VOn+gO!_'`O%i+fO~O!g+iOa(]X!_(]X'z(]X!](]X~Oa%nO!_XO'z%nO~Oh%VO!l%eO~Oh%VO!l%eO(T%gO~O!g#vO#k(xO~Ob+tO%j+uO(T+qO(VTO(YUO!^)XP~O!]+vO`)WX~O[+zO~O`+{O~O!_&PO(T%gO(U!lO`)WP~O%j,OO~P;SOh%VO#`,SO~Oh%VOn,VO!_$|O~O!_,XO~O!Q,ZO!_XO~O%n%vO~O!x,`O~Oe,eO~Ob,fO(T#nO(VTO(YUO!^)VP~Oe%}O~O%j!QO(T&ZO~P=gO[,kO`,jO~OPYOQYOSfOdzOeyOpkOrYOskOtkOzkO|YO!OYO!SWO!WkO!XkO!iuO!lZO!oYO!pYO!qYO!svO!xxO!|]O$niO%h}O(VTO(YUO(aVO(o[O~O!_!eO!u!gO$W!kO(T!dO~P!FyO`,jOa%nO'z%nO~OPYOQYOSfOd!jOe!iOpkOrYOskOtkOzkO|YO!OYO!SWO!WkO!XkO!_!eO!iuO!lZO!oYO!pYO!qYO!svO!x!hO$W!kO$niO(T!dO(VTO(YUO(aVO(o[O~Oa,pOl!OO!uwO%l!OO%m!OO%n!OO~P!IcO!l&oO~O&^,vO~O!_,xO~O&o,zO&q,{OP&laQ&laS&laY&laa&lad&lae&lal&lap&lar&las&lat&laz&la|&la!O&la!S&la!W&la!X&la!_&la!i&la!l&la!o&la!p&la!q&la!s&la!u&la!x&la!|&la$W&la$n&la%h&la%j&la%l&la%m&la%n&la%q&la%s&la%v&la%w&la%y&la&W&la&^&la&`&la&b&la&d&la&g&la&m&la&s&la&u&la&w&la&y&la&{&la'w&la(T&la(V&la(Y&la(a&la(o&la!^&la&e&lab&la&j&la~O(T-QO~Oh!eX!]!RX!^!RX!g!RX!g!eX!l!eX#`!RX~O!]!eX!^!eX~P#!iO!g-VO#`-UOh(jX!]#hX!^#hX!g(jX!l(jX~O!](jX!^(jX~P##[Oh%VO!g-XO!l%eO!]!aX!^!aX~Os!nO!S!oO(VTO(YUO(e!mO~OP<UOQ<UOSfOd>ROe!iOpkOr<UOskOtkOzkO|<UO!O<UO!SWO!WkO!XkO!_!eO!i<XO!lZO!o<UO!p<UO!q<UO!s<YO!u<]O!x!hO$W!kO$n>PO(VTO(YUO(aVO(o[O~O(T=QO~P#$qO!]-]O!^(iX~O!^-_O~O!g-VO#`-UO!]#hX!^#hX~O!]-`O!^(xX~O!^-bO~O!c-cO!d-cO(U!lO~P#$`O!^-fO~P'_On-iO!_'`O~O!Y-nO~Os!{a!b!{a!c!{a!d!{a#T!{a#U!{a#V!{a#W!{a#X!{a#[!{a#]!{a(U!{a(V!{a(Y!{a(e!{a(o!{a~P!#vO!p-sO#`-qO~PChO!c-uO!d-uO(U!lO~PDWOa%nO#`-qO'z%nO~Oa%nO!g#vO#`-qO'z%nO~Oa%nO!g#vO!p-sO#`-qO'z%nO(r'pO~O(P'xO(Q'xO(R-zO~Ov-{O~O!Y'Wa!]'Wa~P!:tO![.PO!Y'WX!]'WX~P%[O!](VO!Y(ha~O!Y(ha~PHRO!](^O!Y(va~O!S%hO![.TO!_%iO(T%gO!Y'^X!]'^X~O#`.VO!](ta!k(taa(ta'z(ta~O!g#vO~P#,wO!](jO!k(sa~O!S%hO!_%iO#j.ZO(T%gO~Op.`O!S%hO![.]O!_%iO!|]O#i._O#j.]O(T%gO!]'aX!k'aX~OR.dO!l#xO~Oh%VOn.gO!_'`O%i.fO~Oa#ci!]#ci'z#ci'w#ci!Y#ci!k#civ#ci!_#ci%i#ci!g#ci~P!:tOn>]O!Q*OO'y*PO(y$}O(z%PO~O#k#_aa#_a#`#_a'z#_a!]#_a!k#_a!_#_a!Y#_a~P#/sO#k(`XP(`XR(`X[(`Xa(`Xj(`Xr(`X!S(`X!l(`X!p(`X#R(`X#n(`X#o(`X#p(`X#q(`X#r(`X#s(`X#t(`X#u(`X#v(`X#x(`X#z(`X#{(`X'z(`X(a(`X(r(`X!k(`X!Y(`X'w(`Xv(`X!_(`X%i(`X!g(`X~P!6kO!].tO!k(kX~P!:tO!k.wO~O!Y.yO~OP$[OR#zO!Q#yO!S#{O!l#xO!p$[O(aVO[#mia#mij#mir#mi!]#mi#R#mi#o#mi#p#mi#q#mi#r#mi#s#mi#t#mi#u#mi#v#mi#x#mi#z#mi#{#mi'z#mi(r#mi(y#mi(z#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#n#mi~P#3cO#n$OO~P#3cOP$[OR#zOr$aO!Q#yO!S#{O!l#xO!p$[O#n$OO#o$PO#p$PO#q$PO(aVO[#mia#mij#mi!]#mi#R#mi#s#mi#t#mi#u#mi#v#mi#x#mi#z#mi#{#mi'z#mi(r#mi(y#mi(z#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#r#mi~P#6QO#r$QO~P#6QOP$[OR#zO[$cOj$ROr$aO!Q#yO!S#{O!l#xO!p$[O#R$RO#n$OO#o$PO#p$PO#q$PO#r$QO#s$RO#t$RO#u$bO(aVOa#mi!]#mi#x#mi#z#mi#{#mi'z#mi(r#mi(y#mi(z#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#v#mi~P#8oOP$[OR#zO[$cOj$ROr$aO!Q#yO!S#{O!l#xO!p$[O#R$RO#n$OO#o$PO#p$PO#q$PO#r$QO#s$RO#t$RO#u$bO#v$SO(aVO(z#}Oa#mi!]#mi#z#mi#{#mi'z#mi(r#mi(y#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#x$UO~P#;VO#x#mi~P#;VO#v$SO~P#8oOP$[OR#zO[$cOj$ROr$aO!Q#yO!S#{O!l#xO!p$[O#R$RO#n$OO#o$PO#p$PO#q$PO#r$QO#s$RO#t$RO#u$bO#v$SO#x$UO(aVO(y#|O(z#}Oa#mi!]#mi#{#mi'z#mi(r#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#z#mi~P#={O#z$WO~P#={OP]XR]X[]Xj]Xr]X!Q]X!S]X!l]X!p]X#R]X#S]X#`]X#kfX#n]X#o]X#p]X#q]X#r]X#s]X#t]X#u]X#v]X#x]X#z]X#{]X$Q]X(a]X(r]X(y]X(z]X!]]X!^]X~O$O]X~P#@jOP$[OR#zO[<mOj<bOr<kO!Q#yO!S#{O!l#xO!p$[O#R<bO#n<_O#o<`O#p<`O#q<`O#r<aO#s<bO#t<bO#u<lO#v<cO#x<eO#z<gO#{<hO(aVO(r$YO(y#|O(z#}O~O$O.{O~P#BwO#S$dO#`<nO$Q<nO$O(gX!^(gX~P! uOa'da!]'da'z'da'w'da!k'da!Y'dav'da!_'da%i'da!g'da~P!:tO[#mia#mij#mir#mi!]#mi#R#mi#r#mi#s#mi#t#mi#u#mi#v#mi#x#mi#z#mi#{#mi'z#mi(r#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~OP$[OR#zO!Q#yO!S#{O!l#xO!p$[O#n$OO#o$PO#p$PO#q$PO(aVO(y#mi(z#mi~P#EyOn>]O!Q*OO'y*PO(y$}O(z%POP#miR#mi!S#mi!l#mi!p#mi#n#mi#o#mi#p#mi#q#mi(a#mi~P#EyO!]/POg(pX~P!1WOg/RO~Oa$Pi!]$Pi'z$Pi'w$Pi!Y$Pi!k$Piv$Pi!_$Pi%i$Pi!g$Pi~P!:tO$]/SO$_/SO~O$]/TO$_/TO~O!g)hO#`/UO!_$cX$Z$cX$]$cX$_$cX$f$cX~O![/VO~O!_)kO$Z/XO$])jO$_)jO$f/YO~O!]<iO!^(fX~P#BwO!^/ZO~O!g)hO$f({X~O$f/]O~Ov/^O~P!&zOx)yO(b)zO(c/aO~O!S/dO~O(y$}On%aa!Q%aa'y%aa(z%aa!]%aa#`%aa~Og%aa$O%aa~P#L{O(z%POn%ca!Q%ca'y%ca(y%ca!]%ca#`%ca~Og%ca$O%ca~P#MnO!]fX!gfX!kfX!k$zX(rfX~P!0SOp%WOPP~P!1uOr*sO!b*qO!c*kO!d*kO!l*bO#[*rO%`*mO(U!lO(VTO(YUO~Os<}O!S/nO![+[O!^*pO(e<|O!^(xP~P$ [O!k/oO~P#/sO!]/pO!g#vO(r'pO!k)OX~O!k/uO~OnoX!QoX'yoX(yoX(zoX~O!g#vO!koX~P$#OOp/wO!S%hO![*^O!_%iO(T%gO!k)OP~O#k/xO~O!Y$zX!]$zX!g%RX~P!0SO!]/yO!Y)PX~P#/sO!g/{O~O!Y/}O~OpkO(T0OO~P.iOh%VOr0TO!g#vO!l%eO(r'pO~O!g+iO~Oa%nO!]0XO'z%nO~O!^0ZO~P!5iO!c0[O!d0[O(U!lO~P#$`Os!nO!S0]O(VTO(YUO(e!mO~O#[0_O~Og%aa!]%aa#`%aa$O%aa~P!1WOg%ca!]%ca#`%ca$O%ca~P!1WOj%dOk%dOl%dO(T&ZOg'mX!]'mX~O!]*yOg(^a~Og0hO~On0jO#`0iOg(_a!](_a~OR0kO!Q0kO!S0lO#S$dOn}a'y}a(y}a(z}a!]}a#`}a~Og}a$O}a~P$(cO!Q*OO'y*POn$sa(y$sa(z$sa!]$sa#`$sa~Og$sa$O$sa~P$)_O!Q*OO'y*POn$ua(y$ua(z$ua!]$ua#`$ua~Og$ua$O$ua~P$*QO#k0oO~Og%Ta!]%Ta#`%Ta$O%Ta~P!1WO!g#vO~O#k0rO~O!]+^Oa)Ta'z)Ta~OR#zO!Q#yO!S#{O!l#xO(aVOP!ri[!rij!rir!ri!]!ri!p!ri#R!ri#n!ri#o!ri#p!ri#q!ri#r!ri#s!ri#t!ri#u!ri#v!ri#x!ri#z!ri#{!ri(r!ri(y!ri(z!ri~Oa!ri'z!ri'w!ri!Y!ri!k!riv!ri!_!ri%i!ri!g!ri~P$+oOh%VOr%XOs$tOt$tOz%YO|%ZO!O<sO!S${O!_$|O!i>VO!l$xO#j<yO$W%`O$t<uO$v<wO$y%aO(VTO(YUO(a$uO(y$}O(z%PO~Op0{O%]0|O(T0zO~P$.VO!g+iOa(]a!_(]a'z(]a!](]a~O#k1SO~O[]X!]fX!^fX~O!]1TO!^)XX~O!^1VO~O[1WO~Ob1YO(T+qO(VTO(YUO~O!_&PO(T%gO`'uX!]'uX~O!]+vO`)Wa~O!k1]O~P!:tO[1`O~O`1aO~O#`1fO~On1iO!_$|O~O(e(|O!^)UP~Oh%VOn1rO!_1oO%i1qO~O[1|O!]1zO!^)VX~O!^1}O~O`2POa%nO'z%nO~O(T#nO(VTO(YUO~O#S$dO#`$eO$Q$eOP(gXR(gX[(gXr(gX!Q(gX!S(gX!](gX!l(gX!p(gX#R(gX#n(gX#o(gX#p(gX#q(gX#r(gX#s(gX#t(gX#u(gX#v(gX#x(gX#z(gX#{(gX(a(gX(r(gX(y(gX(z(gX~Oj2SO&[2TOa(gX~P$3pOj2SO#`$eO&[2TO~Oa2VO~P%[Oa2XO~O&e2[OP&ciQ&ciS&ciY&cia&cid&cie&cil&cip&cir&cis&cit&ciz&ci|&ci!O&ci!S&ci!W&ci!X&ci!_&ci!i&ci!l&ci!o&ci!p&ci!q&ci!s&ci!u&ci!x&ci!|&ci$W&ci$n&ci%h&ci%j&ci%l&ci%m&ci%n&ci%q&ci%s&ci%v&ci%w&ci%y&ci&W&ci&^&ci&`&ci&b&ci&d&ci&g&ci&m&ci&s&ci&u&ci&w&ci&y&ci&{&ci'w&ci(T&ci(V&ci(Y&ci(a&ci(o&ci!^&cib&ci&j&ci~Ob2bO!^2`O&j2aO~P`O!_XO!l2dO~O&q,{OP&liQ&liS&liY&lia&lid&lie&lil&lip&lir&lis&lit&liz&li|&li!O&li!S&li!W&li!X&li!_&li!i&li!l&li!o&li!p&li!q&li!s&li!u&li!x&li!|&li$W&li$n&li%h&li%j&li%l&li%m&li%n&li%q&li%s&li%v&li%w&li%y&li&W&li&^&li&`&li&b&li&d&li&g&li&m&li&s&li&u&li&w&li&y&li&{&li'w&li(T&li(V&li(Y&li(a&li(o&li!^&li&e&lib&li&j&li~O!Y2jO~O!]!aa!^!aa~P#BwOs!nO!S!oO![2pO(e!mO!]'XX!^'XX~P@nO!]-]O!^(ia~O!]'_X!^'_X~P!9|O!]-`O!^(xa~O!^2wO~P'_Oa%nO#`3QO'z%nO~Oa%nO!g#vO#`3QO'z%nO~Oa%nO!g#vO!p3UO#`3QO'z%nO(r'pO~Oa%nO'z%nO~P!:tO!]$_Ov$qa~O!Y'Wi!]'Wi~P!:tO!](VO!Y(hi~O!](^O!Y(vi~O!Y(wi!](wi~P!:tO!](ti!k(tia(ti'z(ti~P!:tO#`3WO!](ti!k(tia(ti'z(ti~O!](jO!k(si~O!S%hO!_%iO!|]O#i3]O#j3[O(T%gO~O!S%hO!_%iO#j3[O(T%gO~On3dO!_'`O%i3cO~Oh%VOn3dO!_'`O%i3cO~O#k%aaP%aaR%aa[%aaa%aaj%aar%aa!S%aa!l%aa!p%aa#R%aa#n%aa#o%aa#p%aa#q%aa#r%aa#s%aa#t%aa#u%aa#v%aa#x%aa#z%aa#{%aa'z%aa(a%aa(r%aa!k%aa!Y%aa'w%aav%aa!_%aa%i%aa!g%aa~P#L{O#k%caP%caR%ca[%caa%caj%car%ca!S%ca!l%ca!p%ca#R%ca#n%ca#o%ca#p%ca#q%ca#r%ca#s%ca#t%ca#u%ca#v%ca#x%ca#z%ca#{%ca'z%ca(a%ca(r%ca!k%ca!Y%ca'w%cav%ca!_%ca%i%ca!g%ca~P#MnO#k%aaP%aaR%aa[%aaa%aaj%aar%aa!S%aa!]%aa!l%aa!p%aa#R%aa#n%aa#o%aa#p%aa#q%aa#r%aa#s%aa#t%aa#u%aa#v%aa#x%aa#z%aa#{%aa'z%aa(a%aa(r%aa!k%aa!Y%aa'w%aa#`%aav%aa!_%aa%i%aa!g%aa~P#/sO#k%caP%caR%ca[%caa%caj%car%ca!S%ca!]%ca!l%ca!p%ca#R%ca#n%ca#o%ca#p%ca#q%ca#r%ca#s%ca#t%ca#u%ca#v%ca#x%ca#z%ca#{%ca'z%ca(a%ca(r%ca!k%ca!Y%ca'w%ca#`%cav%ca!_%ca%i%ca!g%ca~P#/sO#k}aP}a[}aa}aj}ar}a!l}a!p}a#R}a#n}a#o}a#p}a#q}a#r}a#s}a#t}a#u}a#v}a#x}a#z}a#{}a'z}a(a}a(r}a!k}a!Y}a'w}av}a!_}a%i}a!g}a~P$(cO#k$saP$saR$sa[$saa$saj$sar$sa!S$sa!l$sa!p$sa#R$sa#n$sa#o$sa#p$sa#q$sa#r$sa#s$sa#t$sa#u$sa#v$sa#x$sa#z$sa#{$sa'z$sa(a$sa(r$sa!k$sa!Y$sa'w$sav$sa!_$sa%i$sa!g$sa~P$)_O#k$uaP$uaR$ua[$uaa$uaj$uar$ua!S$ua!l$ua!p$ua#R$ua#n$ua#o$ua#p$ua#q$ua#r$ua#s$ua#t$ua#u$ua#v$ua#x$ua#z$ua#{$ua'z$ua(a$ua(r$ua!k$ua!Y$ua'w$uav$ua!_$ua%i$ua!g$ua~P$*QO#k%TaP%TaR%Ta[%Taa%Taj%Tar%Ta!S%Ta!]%Ta!l%Ta!p%Ta#R%Ta#n%Ta#o%Ta#p%Ta#q%Ta#r%Ta#s%Ta#t%Ta#u%Ta#v%Ta#x%Ta#z%Ta#{%Ta'z%Ta(a%Ta(r%Ta!k%Ta!Y%Ta'w%Ta#`%Tav%Ta!_%Ta%i%Ta!g%Ta~P#/sOa#cq!]#cq'z#cq'w#cq!Y#cq!k#cqv#cq!_#cq%i#cq!g#cq~P!:tO![3lO!]'YX!k'YX~P%[O!].tO!k(ka~O!].tO!k(ka~P!:tO!Y3oO~O$O!na!^!na~PKlO$O!ja!]!ja!^!ja~P#BwO$O!ra!^!ra~P!=[O$O!ta!^!ta~P!?rOg']X!]']X~P!,TO!]/POg(pa~OSfO!_4TO$d4UO~O!^4YO~Ov4ZO~P#/sOa$mq!]$mq'z$mq'w$mq!Y$mq!k$mqv$mq!_$mq%i$mq!g$mq~P!:tO!Y4]O~P!&zO!S4^O~O!Q*OO'y*PO(z%POn'ia(y'ia!]'ia#`'ia~Og'ia$O'ia~P%-fO!Q*OO'y*POn'ka(y'ka(z'ka!]'ka#`'ka~Og'ka$O'ka~P%.XO(r$YO~P#/sO!YfX!Y$zX!]fX!]$zX!g%RX#`fX~P!0SOp%WO(T=WO~P!1uOp4bO!S%hO![4aO!_%iO(T%gO!]'eX!k'eX~O!]/pO!k)Oa~O!]/pO!g#vO!k)Oa~O!]/pO!g#vO(r'pO!k)Oa~Og$|i!]$|i#`$|i$O$|i~P!1WO![4jO!Y'gX!]'gX~P!3tO!]/yO!Y)Pa~O!]/yO!Y)Pa~P#/sOP]XR]X[]Xj]Xr]X!Q]X!S]X!Y]X!]]X!l]X!p]X#R]X#S]X#`]X#kfX#n]X#o]X#p]X#q]X#r]X#s]X#t]X#u]X#v]X#x]X#z]X#{]X$Q]X(a]X(r]X(y]X(z]X~Oj%YX!g%YX~P%2OOj4oO!g#vO~Oh%VO!g#vO!l%eO~Oh%VOr4tO!l%eO(r'pO~Or4yO!g#vO(r'pO~Os!nO!S4zO(VTO(YUO(e!mO~O(y$}On%ai!Q%ai'y%ai(z%ai!]%ai#`%ai~Og%ai$O%ai~P%5oO(z%POn%ci!Q%ci'y%ci(y%ci!]%ci#`%ci~Og%ci$O%ci~P%6bOg(_i!](_i~P!1WO#`5QOg(_i!](_i~P!1WO!k5VO~Oa$oq!]$oq'z$oq'w$oq!Y$oq!k$oqv$oq!_$oq%i$oq!g$oq~P!:tO!Y5ZO~O!]5[O!_)QX~P#/sOa$zX!_$zX%^]X'z$zX!]$zX~P!0SO%^5_OaoX!_oX'zoX!]oX~P$#OOp5`O(T#nO~O%^5_O~Ob5fO%j5gO(T+qO(VTO(YUO!]'tX!^'tX~O!]1TO!^)Xa~O[5kO~O`5lO~O[5pO~Oa%nO'z%nO~P#/sO!]5uO#`5wO!^)UX~O!^5xO~Or6OOs!nO!S*iO!b!yO!c!vO!d!vO!|<VO#T!pO#U!pO#V!pO#W!pO#X!pO#[5}O#]!zO(U!lO(VTO(YUO(e!mO(o!sO~O!^5|O~P%;eOn6TO!_1oO%i6SO~Oh%VOn6TO!_1oO%i6SO~Ob6[O(T#nO(VTO(YUO!]'sX!^'sX~O!]1zO!^)Va~O(VTO(YUO(e6^O~O`6bO~Oj6eO&[6fO~PNXO!k6gO~P%[Oa6iO~Oa6iO~P%[Ob2bO!^6nO&j2aO~P`O!g6pO~O!g6rOh(ji!](ji!^(ji!g(ji!l(jir(ji(r(ji~O!]#hi!^#hi~P#BwO#`6sO!]#hi!^#hi~O!]!ai!^!ai~P#BwOa%nO#`6|O'z%nO~Oa%nO!g#vO#`6|O'z%nO~O!](tq!k(tqa(tq'z(tq~P!:tO!](jO!k(sq~O!S%hO!_%iO#j7TO(T%gO~O!_'`O%i7WO~On7[O!_'`O%i7WO~O#k'iaP'iaR'ia['iaa'iaj'iar'ia!S'ia!l'ia!p'ia#R'ia#n'ia#o'ia#p'ia#q'ia#r'ia#s'ia#t'ia#u'ia#v'ia#x'ia#z'ia#{'ia'z'ia(a'ia(r'ia!k'ia!Y'ia'w'iav'ia!_'ia%i'ia!g'ia~P%-fO#k'kaP'kaR'ka['kaa'kaj'kar'ka!S'ka!l'ka!p'ka#R'ka#n'ka#o'ka#p'ka#q'ka#r'ka#s'ka#t'ka#u'ka#v'ka#x'ka#z'ka#{'ka'z'ka(a'ka(r'ka!k'ka!Y'ka'w'kav'ka!_'ka%i'ka!g'ka~P%.XO#k$|iP$|iR$|i[$|ia$|ij$|ir$|i!S$|i!]$|i!l$|i!p$|i#R$|i#n$|i#o$|i#p$|i#q$|i#r$|i#s$|i#t$|i#u$|i#v$|i#x$|i#z$|i#{$|i'z$|i(a$|i(r$|i!k$|i!Y$|i'w$|i#`$|iv$|i!_$|i%i$|i!g$|i~P#/sO#k%aiP%aiR%ai[%aia%aij%air%ai!S%ai!l%ai!p%ai#R%ai#n%ai#o%ai#p%ai#q%ai#r%ai#s%ai#t%ai#u%ai#v%ai#x%ai#z%ai#{%ai'z%ai(a%ai(r%ai!k%ai!Y%ai'w%aiv%ai!_%ai%i%ai!g%ai~P%5oO#k%ciP%ciR%ci[%cia%cij%cir%ci!S%ci!l%ci!p%ci#R%ci#n%ci#o%ci#p%ci#q%ci#r%ci#s%ci#t%ci#u%ci#v%ci#x%ci#z%ci#{%ci'z%ci(a%ci(r%ci!k%ci!Y%ci'w%civ%ci!_%ci%i%ci!g%ci~P%6bO!]'Ya!k'Ya~P!:tO!].tO!k(ki~O$O#ci!]#ci!^#ci~P#BwOP$[OR#zO!Q#yO!S#{O!l#xO!p$[O(aVO[#mij#mir#mi#R#mi#o#mi#p#mi#q#mi#r#mi#s#mi#t#mi#u#mi#v#mi#x#mi#z#mi#{#mi$O#mi(r#mi(y#mi(z#mi!]#mi!^#mi~O#n#mi~P%NdO#n<_O~P%NdOP$[OR#zOr<kO!Q#yO!S#{O!l#xO!p$[O#n<_O#o<`O#p<`O#q<`O(aVO[#mij#mi#R#mi#s#mi#t#mi#u#mi#v#mi#x#mi#z#mi#{#mi$O#mi(r#mi(y#mi(z#mi!]#mi!^#mi~O#r#mi~P&!lO#r<aO~P&!lOP$[OR#zO[<mOj<bOr<kO!Q#yO!S#{O!l#xO!p$[O#R<bO#n<_O#o<`O#p<`O#q<`O#r<aO#s<bO#t<bO#u<lO(aVO#x#mi#z#mi#{#mi$O#mi(r#mi(y#mi(z#mi!]#mi!^#mi~O#v#mi~P&$tOP$[OR#zO[<mOj<bOr<kO!Q#yO!S#{O!l#xO!p$[O#R<bO#n<_O#o<`O#p<`O#q<`O#r<aO#s<bO#t<bO#u<lO#v<cO(aVO(z#}O#z#mi#{#mi$O#mi(r#mi(y#mi!]#mi!^#mi~O#x<eO~P&&uO#x#mi~P&&uO#v<cO~P&$tOP$[OR#zO[<mOj<bOr<kO!Q#yO!S#{O!l#xO!p$[O#R<bO#n<_O#o<`O#p<`O#q<`O#r<aO#s<bO#t<bO#u<lO#v<cO#x<eO(aVO(y#|O(z#}O#{#mi$O#mi(r#mi!]#mi!^#mi~O#z#mi~P&)UO#z<gO~P&)UOa#|y!]#|y'z#|y'w#|y!Y#|y!k#|yv#|y!_#|y%i#|y!g#|y~P!:tO[#mij#mir#mi#R#mi#r#mi#s#mi#t#mi#u#mi#v#mi#x#mi#z#mi#{#mi$O#mi(r#mi!]#mi!^#mi~OP$[OR#zO!Q#yO!S#{O!l#xO!p$[O#n<_O#o<`O#p<`O#q<`O(aVO(y#mi(z#mi~P&,QOn>^O!Q*OO'y*PO(y$}O(z%POP#miR#mi!S#mi!l#mi!p#mi#n#mi#o#mi#p#mi#q#mi(a#mi~P&,QO#S$dOP(`XR(`X[(`Xj(`Xn(`Xr(`X!Q(`X!S(`X!l(`X!p(`X#R(`X#n(`X#o(`X#p(`X#q(`X#r(`X#s(`X#t(`X#u(`X#v(`X#x(`X#z(`X#{(`X$O(`X'y(`X(a(`X(r(`X(y(`X(z(`X!](`X!^(`X~O$O$Pi!]$Pi!^$Pi~P#BwO$O!ri!^!ri~P$+oOg']a!]']a~P!1WO!^7nO~O!]'da!^'da~P#BwO!Y7oO~P#/sO!g#vO(r'pO!]'ea!k'ea~O!]/pO!k)Oi~O!]/pO!g#vO!k)Oi~Og$|q!]$|q#`$|q$O$|q~P!1WO!Y'ga!]'ga~P#/sO!g7vO~O!]/yO!Y)Pi~P#/sO!]/yO!Y)Pi~O!Y7yO~Oh%VOr8OO!l%eO(r'pO~Oj8QO!g#vO~Or8TO!g#vO(r'pO~O!Q*OO'y*PO(z%POn'ja(y'ja!]'ja#`'ja~Og'ja$O'ja~P&5RO!Q*OO'y*POn'la(y'la(z'la!]'la#`'la~Og'la$O'la~P&5tOg(_q!](_q~P!1WO#`8VOg(_q!](_q~P!1WO!Y8WO~Og%Oq!]%Oq#`%Oq$O%Oq~P!1WOa$oy!]$oy'z$oy'w$oy!Y$oy!k$oyv$oy!_$oy%i$oy!g$oy~P!:tO!g6rO~O!]5[O!_)Qa~O!_'`OP$TaR$Ta[$Taj$Tar$Ta!Q$Ta!S$Ta!]$Ta!l$Ta!p$Ta#R$Ta#n$Ta#o$Ta#p$Ta#q$Ta#r$Ta#s$Ta#t$Ta#u$Ta#v$Ta#x$Ta#z$Ta#{$Ta(a$Ta(r$Ta(y$Ta(z$Ta~O%i7WO~P&8fO%^8[Oa%[i!_%[i'z%[i!]%[i~Oa#cy!]#cy'z#cy'w#cy!Y#cy!k#cyv#cy!_#cy%i#cy!g#cy~P!:tO[8^O~Ob8`O(T+qO(VTO(YUO~O!]1TO!^)Xi~O`8dO~O(e(|O!]'pX!^'pX~O!]5uO!^)Ua~O!^8nO~P%;eO(o!sO~P$&YO#[8oO~O!_1oO~O!_1oO%i8qO~On8tO!_1oO%i8qO~O[8yO!]'sa!^'sa~O!]1zO!^)Vi~O!k8}O~O!k9OO~O!k9RO~O!k9RO~P%[Oa9TO~O!g9UO~O!k9VO~O!](wi!^(wi~P#BwOa%nO#`9_O'z%nO~O!](ty!k(tya(ty'z(ty~P!:tO!](jO!k(sy~O%i9bO~P&8fO!_'`O%i9bO~O#k$|qP$|qR$|q[$|qa$|qj$|qr$|q!S$|q!]$|q!l$|q!p$|q#R$|q#n$|q#o$|q#p$|q#q$|q#r$|q#s$|q#t$|q#u$|q#v$|q#x$|q#z$|q#{$|q'z$|q(a$|q(r$|q!k$|q!Y$|q'w$|q#`$|qv$|q!_$|q%i$|q!g$|q~P#/sO#k'jaP'jaR'ja['jaa'jaj'jar'ja!S'ja!l'ja!p'ja#R'ja#n'ja#o'ja#p'ja#q'ja#r'ja#s'ja#t'ja#u'ja#v'ja#x'ja#z'ja#{'ja'z'ja(a'ja(r'ja!k'ja!Y'ja'w'jav'ja!_'ja%i'ja!g'ja~P&5RO#k'laP'laR'la['laa'laj'lar'la!S'la!l'la!p'la#R'la#n'la#o'la#p'la#q'la#r'la#s'la#t'la#u'la#v'la#x'la#z'la#{'la'z'la(a'la(r'la!k'la!Y'la'w'lav'la!_'la%i'la!g'la~P&5tO#k%OqP%OqR%Oq[%Oqa%Oqj%Oqr%Oq!S%Oq!]%Oq!l%Oq!p%Oq#R%Oq#n%Oq#o%Oq#p%Oq#q%Oq#r%Oq#s%Oq#t%Oq#u%Oq#v%Oq#x%Oq#z%Oq#{%Oq'z%Oq(a%Oq(r%Oq!k%Oq!Y%Oq'w%Oq#`%Oqv%Oq!_%Oq%i%Oq!g%Oq~P#/sO!]'Yi!k'Yi~P!:tO$O#cq!]#cq!^#cq~P#BwO(y$}OP%aaR%aa[%aaj%aar%aa!S%aa!l%aa!p%aa#R%aa#n%aa#o%aa#p%aa#q%aa#r%aa#s%aa#t%aa#u%aa#v%aa#x%aa#z%aa#{%aa$O%aa(a%aa(r%aa!]%aa!^%aa~On%aa!Q%aa'y%aa(z%aa~P&IyO(z%POP%caR%ca[%caj%car%ca!S%ca!l%ca!p%ca#R%ca#n%ca#o%ca#p%ca#q%ca#r%ca#s%ca#t%ca#u%ca#v%ca#x%ca#z%ca#{%ca$O%ca(a%ca(r%ca!]%ca!^%ca~On%ca!Q%ca'y%ca(y%ca~P&LQOn>^O!Q*OO'y*PO(z%PO~P&IyOn>^O!Q*OO'y*PO(y$}O~P&LQOR0kO!Q0kO!S0lO#S$dOP}a[}aj}an}ar}a!l}a!p}a#R}a#n}a#o}a#p}a#q}a#r}a#s}a#t}a#u}a#v}a#x}a#z}a#{}a$O}a'y}a(a}a(r}a(y}a(z}a!]}a!^}a~O!Q*OO'y*POP$saR$sa[$saj$san$sar$sa!S$sa!l$sa!p$sa#R$sa#n$sa#o$sa#p$sa#q$sa#r$sa#s$sa#t$sa#u$sa#v$sa#x$sa#z$sa#{$sa$O$sa(a$sa(r$sa(y$sa(z$sa!]$sa!^$sa~O!Q*OO'y*POP$uaR$ua[$uaj$uan$uar$ua!S$ua!l$ua!p$ua#R$ua#n$ua#o$ua#p$ua#q$ua#r$ua#s$ua#t$ua#u$ua#v$ua#x$ua#z$ua#{$ua$O$ua(a$ua(r$ua(y$ua(z$ua!]$ua!^$ua~On>^O!Q*OO'y*PO(y$}O(z%PO~OP%TaR%Ta[%Taj%Tar%Ta!S%Ta!l%Ta!p%Ta#R%Ta#n%Ta#o%Ta#p%Ta#q%Ta#r%Ta#s%Ta#t%Ta#u%Ta#v%Ta#x%Ta#z%Ta#{%Ta$O%Ta(a%Ta(r%Ta!]%Ta!^%Ta~P''VO$O$mq!]$mq!^$mq~P#BwO$O$oq!]$oq!^$oq~P#BwO!^9oO~O$O9pO~P!1WO!g#vO!]'ei!k'ei~O!g#vO(r'pO!]'ei!k'ei~O!]/pO!k)Oq~O!Y'gi!]'gi~P#/sO!]/yO!Y)Pq~Or9wO!g#vO(r'pO~O[9yO!Y9xO~P#/sO!Y9xO~Oj:PO!g#vO~Og(_y!](_y~P!1WO!]'na!_'na~P#/sOa%[q!_%[q'z%[q!]%[q~P#/sO[:UO~O!]1TO!^)Xq~O`:YO~O#`:ZO!]'pa!^'pa~O!]5uO!^)Ui~P#BwO!S:]O~O!_1oO%i:`O~O(VTO(YUO(e:eO~O!]1zO!^)Vq~O!k:hO~O!k:iO~O!k:jO~O!k:jO~P%[O#`:mO!]#hy!^#hy~O!]#hy!^#hy~P#BwO%i:rO~P&8fO!_'`O%i:rO~O$O#|y!]#|y!^#|y~P#BwOP$|iR$|i[$|ij$|ir$|i!S$|i!l$|i!p$|i#R$|i#n$|i#o$|i#p$|i#q$|i#r$|i#s$|i#t$|i#u$|i#v$|i#x$|i#z$|i#{$|i$O$|i(a$|i(r$|i!]$|i!^$|i~P''VO!Q*OO'y*PO(z%POP'iaR'ia['iaj'ian'iar'ia!S'ia!l'ia!p'ia#R'ia#n'ia#o'ia#p'ia#q'ia#r'ia#s'ia#t'ia#u'ia#v'ia#x'ia#z'ia#{'ia$O'ia(a'ia(r'ia(y'ia!]'ia!^'ia~O!Q*OO'y*POP'kaR'ka['kaj'kan'kar'ka!S'ka!l'ka!p'ka#R'ka#n'ka#o'ka#p'ka#q'ka#r'ka#s'ka#t'ka#u'ka#v'ka#x'ka#z'ka#{'ka$O'ka(a'ka(r'ka(y'ka(z'ka!]'ka!^'ka~O(y$}OP%aiR%ai[%aij%ain%air%ai!Q%ai!S%ai!l%ai!p%ai#R%ai#n%ai#o%ai#p%ai#q%ai#r%ai#s%ai#t%ai#u%ai#v%ai#x%ai#z%ai#{%ai$O%ai'y%ai(a%ai(r%ai(z%ai!]%ai!^%ai~O(z%POP%ciR%ci[%cij%cin%cir%ci!Q%ci!S%ci!l%ci!p%ci#R%ci#n%ci#o%ci#p%ci#q%ci#r%ci#s%ci#t%ci#u%ci#v%ci#x%ci#z%ci#{%ci$O%ci'y%ci(a%ci(r%ci(y%ci!]%ci!^%ci~O$O$oy!]$oy!^$oy~P#BwO$O#cy!]#cy!^#cy~P#BwO!g#vO!]'eq!k'eq~O!]/pO!k)Oy~O!Y'gq!]'gq~P#/sOr:|O!g#vO(r'pO~O[;QO!Y;PO~P#/sO!Y;PO~Og(_!R!](_!R~P!1WOa%[y!_%[y'z%[y!]%[y~P#/sO!]1TO!^)Xy~O!]5uO!^)Uq~O(T;XO~O!_1oO%i;[O~O!k;_O~O%i;dO~P&8fOP$|qR$|q[$|qj$|qr$|q!S$|q!l$|q!p$|q#R$|q#n$|q#o$|q#p$|q#q$|q#r$|q#s$|q#t$|q#u$|q#v$|q#x$|q#z$|q#{$|q$O$|q(a$|q(r$|q!]$|q!^$|q~P''VO!Q*OO'y*PO(z%POP'jaR'ja['jaj'jan'jar'ja!S'ja!l'ja!p'ja#R'ja#n'ja#o'ja#p'ja#q'ja#r'ja#s'ja#t'ja#u'ja#v'ja#x'ja#z'ja#{'ja$O'ja(a'ja(r'ja(y'ja!]'ja!^'ja~O!Q*OO'y*POP'laR'la['laj'lan'lar'la!S'la!l'la!p'la#R'la#n'la#o'la#p'la#q'la#r'la#s'la#t'la#u'la#v'la#x'la#z'la#{'la$O'la(a'la(r'la(y'la(z'la!]'la!^'la~OP%OqR%Oq[%Oqj%Oqr%Oq!S%Oq!l%Oq!p%Oq#R%Oq#n%Oq#o%Oq#p%Oq#q%Oq#r%Oq#s%Oq#t%Oq#u%Oq#v%Oq#x%Oq#z%Oq#{%Oq$O%Oq(a%Oq(r%Oq!]%Oq!^%Oq~P''VOg%e!Z!]%e!Z#`%e!Z$O%e!Z~P!1WO!Y;hO~P#/sOr;iO!g#vO(r'pO~O[;kO!Y;hO~P#/sO!]'pq!^'pq~P#BwO!]#h!Z!^#h!Z~P#BwO#k%e!ZP%e!ZR%e!Z[%e!Za%e!Zj%e!Zr%e!Z!S%e!Z!]%e!Z!l%e!Z!p%e!Z#R%e!Z#n%e!Z#o%e!Z#p%e!Z#q%e!Z#r%e!Z#s%e!Z#t%e!Z#u%e!Z#v%e!Z#x%e!Z#z%e!Z#{%e!Z'z%e!Z(a%e!Z(r%e!Z!k%e!Z!Y%e!Z'w%e!Z#`%e!Zv%e!Z!_%e!Z%i%e!Z!g%e!Z~P#/sOr;tO!g#vO(r'pO~O!Y;uO~P#/sOr;|O!g#vO(r'pO~O!Y;}O~P#/sOP%e!ZR%e!Z[%e!Zj%e!Zr%e!Z!S%e!Z!l%e!Z!p%e!Z#R%e!Z#n%e!Z#o%e!Z#p%e!Z#q%e!Z#r%e!Z#s%e!Z#t%e!Z#u%e!Z#v%e!Z#x%e!Z#z%e!Z#{%e!Z$O%e!Z(a%e!Z(r%e!Z!]%e!Z!^%e!Z~P''VOr<QO!g#vO(r'pO~Ov(fX~P1qO!Q%rO~P!)[O(U!lO~P!)[O!YfX!]fX#`fX~P%2OOP]XR]X[]Xj]Xr]X!Q]X!S]X!]]X!]fX!l]X!p]X#R]X#S]X#`]X#`fX#kfX#n]X#o]X#p]X#q]X#r]X#s]X#t]X#u]X#v]X#x]X#z]X#{]X$Q]X(a]X(r]X(y]X(z]X~O!gfX!k]X!kfX(rfX~P'LTOP<UOQ<UOSfOd>ROe!iOpkOr<UOskOtkOzkO|<UO!O<UO!SWO!WkO!XkO!_XO!i<XO!lZO!o<UO!p<UO!q<UO!s<YO!u<]O!x!hO$W!kO$n>PO(T)]O(VTO(YUO(aVO(o[O~O!]<iO!^$qa~Oh%VOp%WOr%XOs$tOt$tOz%YO|%ZO!O<tO!S${O!_$|O!i>WO!l$xO#j<zO$W%`O$t<vO$v<xO$y%aO(T(vO(VTO(YUO(a$uO(y$}O(z%PO~Ol)dO~P(!yOr!eX(r!eX~P#!iOr(jX(r(jX~P##[O!^]X!^fX~P'LTO!YfX!Y$zX!]fX!]$zX#`fX~P!0SO#k<^O~O!g#vO#k<^O~O#`<nO~Oj<bO~O#`=OO!](wX!^(wX~O#`<nO!](uX!^(uX~O#k=PO~Og=RO~P!1WO#k=XO~O#k=YO~Og=RO(T&ZO~O!g#vO#k=ZO~O!g#vO#k=PO~O$O=[O~P#BwO#k=]O~O#k=^O~O#k=cO~O#k=dO~O#k=eO~O#k=fO~O$O=gO~P!1WO$O=hO~P!1WOl=sO~P7eOk#S#T#U#W#X#[#i#j#u$n$t$v$y%]%^%h%i%j%q%s%v%w%y%{~(OT#o!X'|(U#ps#n#qr!Q'}$]'}(T$_(e~",goto:"$9Y)]PPPPPP)^PP)aP)rP+W/]PPPP6mPP7TPP=QPPP@tPA^PA^PPPA^PCfPA^PA^PA^PCjPCoPD^PIWPPPI[PPPPI[L_PPPLeMVPI[PI[PP! eI[PPPI[PI[P!#lI[P!'S!(X!(bP!)U!)Y!)U!,gPPPPPPP!-W!(XPP!-h!/YP!2iI[I[!2n!5z!:h!:h!>gPPP!>oI[PPPPPPPPP!BOP!C]PPI[!DnPI[PI[I[I[I[I[PI[!FQP!I[P!LbP!Lf!Lp!Lt!LtP!IXP!Lx!LxP#!OP#!SI[PI[#!Y#%_CjA^PA^PA^A^P#&lA^A^#)OA^#+vA^#.SA^A^#.r#1W#1W#1]#1f#1W#1qPP#1WPA^#2ZA^#6YA^A^6mPPP#:_PPP#:x#:xP#:xP#;`#:xPP#;fP#;]P#;]#;y#;]#<e#<k#<n)aP#<q)aP#<z#<z#<zP)aP)aP)aP)aPP)aP#=Q#=TP#=T)aP#=XP#=[P)aP)aP)aP)aP)aP)a)aPP#=b#=h#=s#=y#>P#>V#>]#>k#>q#>{#?R#?]#?c#?s#?y#@k#@}#AT#AZ#Ai#BO#Cs#DR#DY#Et#FS#Gt#HS#HY#H`#Hf#Hp#Hv#H|#IW#Ij#IpPPPPPPPPPPP#IvPPPPPPP#Jk#Mx$ b$ i$ qPPP$']P$'f$*_$0x$0{$1O$1}$2Q$2X$2aP$2g$2jP$3W$3[$4S$5b$5g$5}PP$6S$6Y$6^$6a$6e$6i$7e$7|$8e$8i$8l$8o$8y$8|$9Q$9UR!|RoqOXst!Z#d%m&r&t&u&w,s,x2[2_Y!vQ'`-e1o5{Q%tvQ%|yQ&T|Q&j!VS'W!e-]Q'f!iS'l!r!yU*k$|*Z*oQ+o%}S+|&V&WQ,d&dQ-c'_Q-m'gQ-u'mQ0[*qQ1b,OQ1y,eR<{<Y%SdOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&r&t&u&w&{'T'b'r(T(V(](d(x(z)O)}*i+X+],p,s,x-i-q.P.V.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3l4z6T6e6f6i6|8t9T9_S#q]<V!r)_$Z$n'X)s-U-X/V2p4T5w6s:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>SU+P%]<s<tQ+t&PQ,f&gQ,m&oQ0x+gQ0}+iQ1Y+uQ2R,kQ3`.gQ5`0|Q5f1TQ6[1zQ7Y3dQ8`5gR9e7['QkOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>S!S!nQ!r!v!y!z$|'W'_'`'l'm'n*k*o*q*r-]-c-e-u0[0_1o5{5}%[$ti#v$b$c$d$x${%O%Q%^%_%c)y*R*T*V*Y*a*g*w*x+f+i,S,V.f/P/d/m/x/y/{0`0b0i0j0o1f1i1q3c4^4_4j4o5Q5[5_6S7W7v8Q8V8[8q9b9p9y:P:`:r;Q;[;d;k<l<m<o<p<q<r<u<v<w<x<y<z=S=T=U=V=X=Y=]=^=_=`=a=b=c=d=g=h>P>X>Y>]>^Q&X|Q'U!eS'[%i-`Q+t&PQ,P&WQ,f&gQ0n+SQ1Y+uQ1_+{Q2Q,jQ2R,kQ5f1TQ5o1aQ6[1zQ6_1|Q6`2PQ8`5gQ8c5lQ8|6bQ:X8dQ:f8yQ;V:YR<}*ZrnOXst!V!Z#d%m&i&r&t&u&w,s,x2[2_R,h&k&z^OPXYstuvwz!Z!`!g!j!o#S#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n%m%t&R&k&n&o&r&t&u&w&{'T'b'r(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>R>S[#]WZ#W#Z'X(T!b%jm#h#i#l$x%e%h(^(h(i(j*Y*^*b+Z+[+^,o-V.T.Z.[.]._/m/p2d3[3]4a6r7TQ%wxQ%{yW&Q|&V&W,OQ&_!TQ'c!hQ'e!iQ(q#sS+n%|%}Q+r&PQ,_&bQ,c&dS-l'f'gQ.i(rQ1R+oQ1X+uQ1Z+vQ1^+zQ1t,`S1x,d,eQ2|-mQ5e1TQ5i1WQ5n1`Q6Z1yQ8_5gQ8b5kQ8f5pQ:T8^R;T:U!U$zi$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Y!^%yy!i!u%{%|%}'V'e'f'g'k'u*j+n+o-Y-l-m-t0R0U1R2u2|3T4r4s4v7}9{Q+h%wQ,T&[Q,W&]Q,b&dQ.h(qQ1s,_U1w,c,d,eQ3e.iQ6U1tS6Y1x1yQ8x6Z#f>T#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k<o<q<u<w<y=S=U=X=]=_=a=c=g>]>^o>U<l<m<p<r<v<x<z=T=V=Y=^=`=b=d=hW%Ti%V*y>PS&[!Q&iQ&]!RQ&^!SU*}%[%d=sR,R&Y%]%Si#v$b$c$d$x${%O%Q%^%_%c)y*R*T*V*Y*a*g*w*x+f+i,S,V.f/P/d/m/x/y/{0`0b0i0j0o1f1i1q3c4^4_4j4o5Q5[5_6S7W7v8Q8V8[8q9b9p9y:P:`:r;Q;[;d;k<l<m<o<p<q<r<u<v<w<x<y<z=S=T=U=V=X=Y=]=^=_=`=a=b=c=d=g=h>P>X>Y>]>^T)z$u){V+P%]<s<tW'[!e%i*Z-`S(}#y#zQ+c%rQ+y&SS.b(m(nQ1j,XQ5T0kR8i5u'QkOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>S$i$^c#Y#e%q%s%u(S(Y(t(y)R)S)T)U)V)W)X)Y)Z)[)^)`)b)g)q+d+x-Z-x-}.S.U.s.v.z.|.}/O/b0p2k2n3O3V3k3p3q3r3s3t3u3v3w3x3y3z3{3|4P4Q4X5X5c6u6{7Q7a7b7k7l8k9X9]9g9m9n:o;W;`<W=vT#TV#U'RkOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>SQ'Y!eR2q-]!W!nQ!e!r!v!y!z$|'W'_'`'l'm'n*Z*k*o*q*r-]-c-e-u0[0_1o5{5}R1l,ZnqOXst!Z#d%m&r&t&u&w,s,x2[2_Q&y!^Q'v!xS(s#u<^Q+l%zQ,]&_Q,^&aQ-j'dQ-w'oS.r(x=PS0q+X=ZQ1P+mQ1n,[Q2c,zQ2e,{Q2m-WQ2z-kQ2}-oS5Y0r=eQ5a1QS5d1S=fQ6t2oQ6x2{Q6}3SQ8]5bQ9Y6vQ9Z6yQ9^7OR:l9V$d$]c#Y#e%s%u(S(Y(t(y)R)S)T)U)V)W)X)Y)Z)[)^)`)b)g)q+d+x-Z-x-}.S.U.s.v.z.}/O/b0p2k2n3O3V3k3p3q3r3s3t3u3v3w3x3y3z3{3|4P4Q4X5X5c6u6{7Q7a7b7k7l8k9X9]9g9m9n:o;W;`<W=vS(o#p'iQ)P#zS+b%q.|S.c(n(pR3^.d'QkOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>SS#q]<VQ&t!XQ&u!YQ&w![Q&x!]R2Z,vQ'a!hQ+e%wQ-h'cS.e(q+hQ2x-gW3b.h.i0w0yQ6w2yW7U3_3a3e5^U9a7V7X7ZU:q9c9d9fS;b:p:sQ;p;cR;x;qU!wQ'`-eT5y1o5{!Q_OXZ`st!V!Z#d#h%e%m&i&k&r&t&u&w(j,s,x.[2[2_]!pQ!r'`-e1o5{T#q]<V%^{OPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&o&r&t&u&w&{'T'b'r(T(V(](d(x(z)O)}*i+X+]+g,p,s,x-i-q.P.V.g.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3d3l4z6T6e6f6i6|7[8t9T9_S(}#y#zS.b(m(n!s=l$Z$n'X)s-U-X/V2p4T5w6s:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>SU$fd)_,mS(p#p'iU*v%R(w4OU0m+O.n7gQ5^0xQ7V3`Q9d7YR:s9em!tQ!r!v!y!z'`'l'm'n-e-u1o5{5}Q't!uS(f#g2US-s'k'wQ/s*]Q0R*jQ3U-vQ4f/tQ4r0TQ4s0UQ4x0^Q7r4`S7}4t4vS8R4y4{Q9r7sQ9v7yQ9{8OQ:Q8TS:{9w9xS;g:|;PS;s;h;iS;{;t;uS<P;|;}R<S<QQ#wbQ's!uS(e#g2US(g#m+WQ+Y%fQ+j%xQ+p&OU-r'k't'wQ.W(fU/r*]*`/wQ0S*jQ0V*lQ1O+kQ1u,aS3R-s-vQ3Z.`S4e/s/tQ4n0PS4q0R0^Q4u0WQ6W1vQ7P3US7q4`4bQ7u4fU7|4r4x4{Q8P4wQ8v6XS9q7r7sQ9u7yQ9}8RQ:O8SQ:c8wQ:y9rS:z9v9xQ;S:QQ;^:dS;f:{;PS;r;g;hS;z;s;uS<O;{;}Q<R<PQ<T<SQ=o=jQ={=tR=|=uV!wQ'`-e%^aOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&o&r&t&u&w&{'T'b'r(T(V(](d(x(z)O)}*i+X+]+g,p,s,x-i-q.P.V.g.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3d3l4z6T6e6f6i6|7[8t9T9_S#wz!j!r=i$Z$n'X)s-U-X/V2p4T5w6s:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>SR=o>R%^bOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&o&r&t&u&w&{'T'b'r(T(V(](d(x(z)O)}*i+X+]+g,p,s,x-i-q.P.V.g.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3d3l4z6T6e6f6i6|7[8t9T9_Q%fj!^%xy!i!u%{%|%}'V'e'f'g'k'u*j+n+o-Y-l-m-t0R0U1R2u2|3T4r4s4v7}9{S&Oz!jQ+k%yQ,a&dW1v,b,c,d,eU6X1w1x1yS8w6Y6ZQ:d8x!r=j$Z$n'X)s-U-X/V2p4T5w6s:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>SQ=t>QR=u>R%QeOPXYstuvw!Z!`!g!o#S#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&r&t&u&w&{'T'b'r(V(](d(x(z)O)}*i+X+]+g,p,s,x-i-q.P.V.g.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3d3l4z6T6e6f6i6|7[8t9T9_Y#bWZ#W#Z(T!b%jm#h#i#l$x%e%h(^(h(i(j*Y*^*b+Z+[+^,o-V.T.Z.[.]._/m/p2d3[3]4a6r7TQ,n&o!p=k$Z$n)s-U-X/V2p4T5w6s:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>SR=n'XU']!e%i*ZR2s-`%SdOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&r&t&u&w&{'T'b'r(T(V(](d(x(z)O)}*i+X+],p,s,x-i-q.P.V.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3l4z6T6e6f6i6|8t9T9_!r)_$Z$n'X)s-U-X/V2p4T5w6s:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>SQ,m&oQ0x+gQ3`.gQ7Y3dR9e7[!b$Tc#Y%q(S(Y(t(y)Z)[)`)g+x-x-}.S.U.s.v/b0p3O3V3k3{5X5c6{7Q7a9]:o<W!P<d)^)q-Z.|2k2n3p3y3z4P4X6u7b7k7l8k9X9g9m9n;W;`=v!f$Vc#Y%q(S(Y(t(y)W)X)Z)[)`)g+x-x-}.S.U.s.v/b0p3O3V3k3{5X5c6{7Q7a9]:o<W!T<f)^)q-Z.|2k2n3p3v3w3y3z4P4X6u7b7k7l8k9X9g9m9n;W;`=v!^$Zc#Y%q(S(Y(t(y)`)g+x-x-}.S.U.s.v/b0p3O3V3k3{5X5c6{7Q7a9]:o<WQ4_/kz>S)^)q-Z.|2k2n3p4P4X6u7b7k7l8k9X9g9m9n;W;`=vQ>X>ZR>Y>['QkOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>SS$oh$pR4U/U'XgOPWXYZhstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n$p%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/U/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>ST$kf$qQ$ifS)j$l)nR)v$qT$jf$qT)l$l)n'XhOPWXYZhstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n$p%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/U/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>ST$oh$pQ$rhR)u$p%^jOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&o&r&t&u&w&{'T'b'r(T(V(](d(x(z)O)}*i+X+]+g,p,s,x-i-q.P.V.g.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3d3l4z6T6e6f6i6|7[8t9T9_!s>Q$Z$n'X)s-U-X/V2p4T5w6s:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>S#glOPXZst!Z!`!o#S#d#o#{$n%m&k&n&o&r&t&u&w&{'T'b)O)s*i+]+g,p,s,x-i.g/V/n0]0l1r2S2T2V2X2[2_2a3d4T4z6T6e6f6i7[8t9T!U%Ri$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Y#f(w#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k<o<q<u<w<y=S=U=X=]=_=a=c=g>]>^Q+T%aQ/c*Oo4O<l<m<p<r<v<x<z=T=V=Y=^=`=b=d=h!U$yi$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>YQ*c$zU*l$|*Z*oQ+U%bQ0W*m#f=q#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k<o<q<u<w<y=S=U=X=]=_=a=c=g>]>^n=r<l<m<p<r<v<x<z=T=V=Y=^=`=b=d=hQ=w>TQ=x>UQ=y>VR=z>W!U%Ri$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Y#f(w#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k<o<q<u<w<y=S=U=X=]=_=a=c=g>]>^o4O<l<m<p<r<v<x<z=T=V=Y=^=`=b=d=hnoOXst!Z#d%m&r&t&u&w,s,x2[2_S*f${*YQ-R'OQ-S'QR4i/y%[%Si#v$b$c$d$x${%O%Q%^%_%c)y*R*T*V*Y*a*g*w*x+f+i,S,V.f/P/d/m/x/y/{0`0b0i0j0o1f1i1q3c4^4_4j4o5Q5[5_6S7W7v8Q8V8[8q9b9p9y:P:`:r;Q;[;d;k<l<m<o<p<q<r<u<v<w<x<y<z=S=T=U=V=X=Y=]=^=_=`=a=b=c=d=g=h>P>X>Y>]>^Q,U&]Q1h,WQ5s1gR8h5tV*n$|*Z*oU*n$|*Z*oT5z1o5{S0P*i/nQ4w0]T8S4z:]Q+j%xQ0V*lQ1O+kQ1u,aQ6W1vQ8v6XQ:c8wR;^:d!U%Oi$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Yx*R$v)e*S*u+V/v0d0e4R4g5R5S5W7p8U:R:x=p=}>OS0`*t0a#f<o#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k<o<q<u<w<y=S=U=X=]=_=a=c=g>]>^n<p<l<m<p<r<v<x<z=T=V=Y=^=`=b=d=h!d=S(u)c*[*e.j.m.q/_/k/|0v1e3h4[4h4l5r7]7`7w7z8X8Z9t9|:S:};R;e;j;v>Z>[`=T3}7c7f7j9h:t:w;yS=_.l3iT=`7e9k!U%Qi$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Y|*T$v)e*U*t+V/g/v0d0e4R4g4|5R5S5W7p8U:R:x=p=}>OS0b*u0c#f<q#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k<o<q<u<w<y=S=U=X=]=_=a=c=g>]>^n<r<l<m<p<r<v<x<z=T=V=Y=^=`=b=d=h!h=U(u)c*[*e.k.l.q/_/k/|0v1e3f3h4[4h4l5r7]7^7`7w7z8X8Z9t9|:S:};R;e;j;v>Z>[d=V3}7d7e7j9h9i:t:u:w;yS=a.m3jT=b7f9lrnOXst!V!Z#d%m&i&r&t&u&w,s,x2[2_Q&f!UR,p&ornOXst!V!Z#d%m&i&r&t&u&w,s,x2[2_R&f!UQ,Y&^R1d,RsnOXst!V!Z#d%m&i&r&t&u&w,s,x2[2_Q1p,_S6R1s1tU8p6P6Q6US:_8r8sS;Y:^:aQ;m;ZR;w;nQ&m!VR,i&iR6_1|R:f8yW&Q|&V&W,OR1Z+vQ&r!WR,s&sR,y&xT2],x2_R,}&yQ,|&yR2f,}Q'y!{R-y'ySsOtQ#dXT%ps#dQ#OTR'{#OQ#RUR'}#RQ){$uR/`){Q#UVR(Q#UQ#XWU(W#X(X.QQ(X#YR.Q(YQ-^'YR2r-^Q.u(yS3m.u3nR3n.vQ-e'`R2v-eY!rQ'`-e1o5{R'j!rQ/Q)eR4S/QU#_W%h*YU(_#_(`.RQ(`#`R.R(ZQ-a']R2t-at`OXst!V!Z#d%m&i&k&r&t&u&w,s,x2[2_S#hZ%eU#r`#h.[R.[(jQ(k#jQ.X(gW.a(k.X3X7RQ3X.YR7R3YQ)n$lR/W)nQ$phR)t$pQ$`cU)a$`-|<jQ-|<WR<j)qQ/q*]W4c/q4d7t9sU4d/r/s/tS7t4e4fR9s7u$e*Q$v(u)c)e*[*e*t*u+Q+R+V.l.m.o.p.q/_/g/i/k/v/|0d0e0v1e3f3g3h3}4R4[4g4h4l4|5O5R5S5W5r7]7^7_7`7e7f7h7i7j7p7w7z8U8X8Z9h9i9j9t9|:R:S:t:u:v:w:x:};R;e;j;v;y=p=}>O>Z>[Q/z*eU4k/z4m7xQ4m/|R7x4lS*o$|*ZR0Y*ox*S$v)e*t*u+V/v0d0e4R4g5R5S5W7p8U:R:x=p=}>O!d.j(u)c*[*e.l.m.q/_/k/|0v1e3h4[4h4l5r7]7`7w7z8X8Z9t9|:S:};R;e;j;v>Z>[U/h*S.j7ca7c3}7e7f7j9h:t:w;yQ0a*tQ3i.lU4}0a3i9kR9k7e|*U$v)e*t*u+V/g/v0d0e4R4g4|5R5S5W7p8U:R:x=p=}>O!h.k(u)c*[*e.l.m.q/_/k/|0v1e3f3h4[4h4l5r7]7^7`7w7z8X8Z9t9|:S:};R;e;j;v>Z>[U/j*U.k7de7d3}7e7f7j9h9i:t:u:w;yQ0c*uQ3j.mU5P0c3j9lR9l7fQ*z%UR0g*zQ5]0vR8Y5]Q+_%kR0u+_Q5v1jS8j5v:[R:[8kQ,[&_R1m,[Q5{1oR8m5{Q1{,fS6]1{8zR8z6_Q1U+rW5h1U5j8a:VQ5j1XQ8a5iR:V8bQ+w&QR1[+wQ2_,xR6m2_YrOXst#dQ&v!ZQ+a%mQ,r&rQ,t&tQ,u&uQ,w&wQ2Y,sS2],x2_R6l2[Q%opQ&z!_Q&}!aQ'P!bQ'R!cQ'q!uQ+`%lQ+l%zQ,Q&XQ,h&mQ-P&|W-p'k's't'wQ-w'oQ0X*nQ1P+mQ1c,PS2O,i,lQ2g-OQ2h-RQ2i-SQ2}-oW3P-r-s-v-xQ5a1QQ5m1_Q5q1eQ6V1uQ6a2QQ6k2ZU6z3O3R3UQ6}3SQ8]5bQ8e5oQ8g5rQ8l5zQ8u6WQ8{6`S9[6{7PQ9^7OQ:W8cQ:b8vQ:g8|Q:n9]Q;U:XQ;]:cQ;a:oQ;l;VR;o;^Q%zyQ'd!iQ'o!uU+m%{%|%}Q-W'VU-k'e'f'gS-o'k'uQ0Q*jS1Q+n+oQ2o-YS2{-l-mQ3S-tS4p0R0UQ5b1RQ6v2uQ6y2|Q7O3TU7{4r4s4vQ9z7}R;O9{S$wi>PR*{%VU%Ui%V>PR0f*yQ$viS(u#v+iS)c$b$cQ)e$dQ*[$xS*e${*YQ*t%OQ*u%QQ+Q%^Q+R%_Q+V%cQ.l<oQ.m<qQ.o<uQ.p<wQ.q<yQ/_)yQ/g*RQ/i*TQ/k*VQ/v*aS/|*g/mQ0d*wQ0e*xl0v+f,V.f1i1q3c6S7W8q9b:`:r;[;dQ1e,SQ3f=SQ3g=UQ3h=XS3}<l<mQ4R/PS4[/d4^Q4g/xQ4h/yQ4l/{Q4|0`Q5O0bQ5R0iQ5S0jQ5W0oQ5r1fQ7]=]Q7^=_Q7_=aQ7`=cQ7e<pQ7f<rQ7h<vQ7i<xQ7j<zQ7p4_Q7w4jQ7z4oQ8U5QQ8X5[Q8Z5_Q9h=YQ9i=TQ9j=VQ9t7vQ9|8QQ:R8VQ:S8[Q:t=^Q:u=`Q:v=bQ:w=dQ:x9pQ:}9yQ;R:PQ;e=gQ;j;QQ;v;kQ;y=hQ=p>PQ=}>XQ>O>YQ>Z>]R>[>^Q+O%]Q.n<sR7g<tnpOXst!Z#d%m&r&t&u&w,s,x2[2_Q!fPS#fZ#oQ&|!`W'h!o*i0]4zQ(P#SQ)Q#{Q)r$nS,l&k&nQ,q&oQ-O&{S-T'T/nQ-g'bQ.x)OQ/[)sQ0s+]Q0y+gQ2W,pQ2y-iQ3a.gQ4W/VQ5U0lQ6Q1rQ6c2SQ6d2TQ6h2VQ6j2XQ6o2aQ7Z3dQ7m4TQ8s6TQ9P6eQ9Q6fQ9S6iQ9f7[Q:a8tR:k9T#[cOPXZst!Z!`!o#d#o#{%m&k&n&o&r&t&u&w&{'T'b)O*i+]+g,p,s,x-i.g/n0]0l1r2S2T2V2X2[2_2a3d4z6T6e6f6i7[8t9TQ#YWQ#eYQ%quQ%svS%uw!gS(S#W(VQ(Y#ZQ(t#uQ(y#xQ)R$OQ)S$PQ)T$QQ)U$RQ)V$SQ)W$TQ)X$UQ)Y$VQ)Z$WQ)[$XQ)^$ZQ)`$_Q)b$aQ)g$eW)q$n)s/V4TQ+d%tQ+x&RS-Z'X2pQ-x'rS-}(T.PQ.S(]Q.U(dQ.s(xQ.v(zQ.z<UQ.|<XQ.}<YQ/O<]Q/b)}Q0p+XQ2k-UQ2n-XQ3O-qQ3V.VQ3k.tQ3p<^Q3q<_Q3r<`Q3s<aQ3t<bQ3u<cQ3v<dQ3w<eQ3x<fQ3y<gQ3z<hQ3{.{Q3|<kQ4P<nQ4Q<{Q4X<iQ5X0rQ5c1SQ6u=OQ6{3QQ7Q3WQ7a3lQ7b=PQ7k=RQ7l=ZQ8k5wQ9X6sQ9]6|Q9g=[Q9m=eQ9n=fQ:o9_Q;W:ZQ;`:mQ<W#SR=v>SR#[WR'Z!el!tQ!r!v!y!z'`'l'm'n-e-u1o5{5}S'V!e-]U*j$|*Z*oS-Y'W'_S0U*k*qQ0^*rQ2u-cQ4v0[R4{0_R({#xQ!fQT-d'`-e]!qQ!r'`-e1o5{Q#p]R'i<VR)f$dY!uQ'`-e1o5{Q'k!rS'u!v!yS'w!z5}S-t'l'mQ-v'nR3T-uT#kZ%eS#jZ%eS%km,oU(g#h#i#lS.Y(h(iQ.^(jQ0t+^Q3Y.ZU3Z.[.]._S7S3[3]R9`7Td#^W#W#Z%h(T(^*Y+Z.T/mr#gZm#h#i#l%e(h(i(j+^.Z.[.]._3[3]7TS*]$x*bQ/t*^Q2U,oQ2l-VQ4`/pQ6q2dQ7s4aQ9W6rT=m'X+[V#aW%h*YU#`W%h*YS(U#W(^U(Z#Z+Z/mS-['X+[T.O(T.TV'^!e%i*ZQ$lfR)x$qT)m$l)nR4V/UT*_$x*bT*h${*YQ0w+fQ1g,VQ3_.fQ5t1iQ6P1qQ7X3cQ8r6SQ9c7WQ:^8qQ:p9bQ;Z:`Q;c:rQ;n;[R;q;dnqOXst!Z#d%m&r&t&u&w,s,x2[2_Q&l!VR,h&itmOXst!U!V!Z#d%m&i&r&t&u&w,s,x2[2_R,o&oT%lm,oR1k,XR,g&gQ&U|S+}&V&WR1^,OR+s&PT&p!W&sT&q!W&sT2^,x2_",nodeNames:`⚠ ArithOp ArithOp ?. JSXStartTag LineComment BlockComment Script Hashbang ExportDeclaration export Star as VariableName String Escape from ; default FunctionDeclaration async function VariableDefinition > < TypeParamList in out const TypeDefinition extends ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation InterpolationStart NullType null VoidType void TypeofType typeof MemberExpression . PropertyName [ TemplateString Escape Interpolation super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewTarget new NewExpression ) ( ArgList UnaryExpression delete LogicOp BitOp YieldExpression yield AwaitExpression await ParenthesizedExpression ClassExpression class ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression TypeArgList CompareOp < declare Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly accessor Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof satisfies CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression InstantiationExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXSelfClosingTag JSXIdentifier JSXBuiltin JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast < ArrowFunction TypeParamList SequenceExpression InstantiationExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate asserts is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var using TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration defer ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement SingleExpression SingleClassItem`,maxTerm:380,context:AX,nodeProps:[[`isolate`,-8,5,6,14,37,39,51,53,55,``],[`group`,-26,9,17,19,68,207,211,215,216,218,221,224,234,237,243,245,247,249,252,258,264,266,268,270,272,274,275,`Statement`,-34,13,14,32,35,36,42,51,54,55,57,62,70,72,76,80,82,84,85,110,111,120,121,136,139,141,142,143,144,145,147,148,167,169,171,`Expression`,-23,31,33,37,41,43,45,173,175,177,178,180,181,182,184,185,186,188,189,190,201,203,205,206,`Type`,-3,88,103,109,`ClassItem`],[`openedBy`,23,`<`,38,`InterpolationStart`,56,`[`,60,`{`,73,`(`,160,`JSXStartCloseTag`],[`closedBy`,-2,24,168,`>`,40,`InterpolationEnd`,50,`]`,61,`}`,74,`)`,165,`JSXEndTag`]],propSources:[LX],skippedNodes:[0,5,6,278],repeatNodeCount:37,tokenData:"$Fq07[R!bOX%ZXY+gYZ-yZ[+g[]%Z]^.c^p%Zpq+gqr/mrs3cst:_tuEruvJSvwLkwx! Yxy!'iyz!(sz{!)}{|!,q|}!.O}!O!,q!O!P!/Y!P!Q!9j!Q!R#:O!R![#<_![!]#I_!]!^#Jk!^!_#Ku!_!`$![!`!a$$v!a!b$*T!b!c$,r!c!}Er!}#O$-|#O#P$/W#P#Q$4o#Q#R$5y#R#SEr#S#T$7W#T#o$8b#o#p$<r#p#q$=h#q#r$>x#r#s$@U#s$f%Z$f$g+g$g#BYEr#BY#BZ$A`#BZ$ISEr$IS$I_$A`$I_$I|Er$I|$I}$Dk$I}$JO$Dk$JO$JTEr$JT$JU$A`$JU$KVEr$KV$KW$A`$KW&FUEr&FU&FV$A`&FV;'SEr;'S;=`I|<%l?HTEr?HT?HU$A`?HUOEr(n%d_$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z&j&hT$i&jO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c&j&zP;=`<%l&c'|'U]$i&j(Z!bOY&}YZ&cZw&}wx&cx!^&}!^!_'}!_#O&}#O#P&c#P#o&}#o#p'}#p;'S&};'S;=`(l<%lO&}!b(SU(Z!bOY'}Zw'}x#O'}#P;'S'};'S;=`(f<%lO'}!b(iP;=`<%l'}'|(oP;=`<%l&}'[(y]$i&j(WpOY(rYZ&cZr(rrs&cs!^(r!^!_)r!_#O(r#O#P&c#P#o(r#o#p)r#p;'S(r;'S;=`*a<%lO(rp)wU(WpOY)rZr)rs#O)r#P;'S)r;'S;=`*Z<%lO)rp*^P;=`<%l)r'[*dP;=`<%l(r#S*nX(Wp(Z!bOY*gZr*grs'}sw*gwx)rx#O*g#P;'S*g;'S;=`+Z<%lO*g#S+^P;=`<%l*g(n+dP;=`<%l%Z07[+rq$i&j(Wp(Z!b'|0/lOX%ZXY+gYZ&cZ[+g[p%Zpq+gqr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p$f%Z$f$g+g$g#BY%Z#BY#BZ+g#BZ$IS%Z$IS$I_+g$I_$JT%Z$JT$JU+g$JU$KV%Z$KV$KW+g$KW&FU%Z&FU&FV+g&FV;'S%Z;'S;=`+a<%l?HT%Z?HT?HU+g?HUO%Z07[.ST(X#S$i&j'}0/lO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c07[.n_$i&j(Wp(Z!b'}0/lOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z)3p/x`$i&j!p),Q(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`0z!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW1V`#v(Ch$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`2X!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW2d_#v(Ch$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'At3l_(V':f$i&j(Z!bOY4kYZ5qZr4krs7nsw4kwx5qx!^4k!^!_8p!_#O4k#O#P5q#P#o4k#o#p8p#p;'S4k;'S;=`:X<%lO4k(^4r_$i&j(Z!bOY4kYZ5qZr4krs7nsw4kwx5qx!^4k!^!_8p!_#O4k#O#P5q#P#o4k#o#p8p#p;'S4k;'S;=`:X<%lO4k&z5vX$i&jOr5qrs6cs!^5q!^!_6y!_#o5q#o#p6y#p;'S5q;'S;=`7h<%lO5q&z6jT$d`$i&jO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c`6|TOr6yrs7]s;'S6y;'S;=`7b<%lO6y`7bO$d``7eP;=`<%l6y&z7kP;=`<%l5q(^7w]$d`$i&j(Z!bOY&}YZ&cZw&}wx&cx!^&}!^!_'}!_#O&}#O#P&c#P#o&}#o#p'}#p;'S&};'S;=`(l<%lO&}!r8uZ(Z!bOY8pYZ6yZr8prs9hsw8pwx6yx#O8p#O#P6y#P;'S8p;'S;=`:R<%lO8p!r9oU$d`(Z!bOY'}Zw'}x#O'}#P;'S'};'S;=`(f<%lO'}!r:UP;=`<%l8p(^:[P;=`<%l4k%9[:hh$i&j(Wp(Z!bOY%ZYZ&cZq%Zqr<Srs&}st%ZtuCruw%Zwx(rx!^%Z!^!_*g!_!c%Z!c!}Cr!}#O%Z#O#P&c#P#R%Z#R#SCr#S#T%Z#T#oCr#o#p*g#p$g%Z$g;'SCr;'S;=`El<%lOCr(r<__WS$i&j(Wp(Z!bOY<SYZ&cZr<Srs=^sw<Swx@nx!^<S!^!_Bm!_#O<S#O#P>`#P#o<S#o#pBm#p;'S<S;'S;=`Cl<%lO<S(Q=g]WS$i&j(Z!bOY=^YZ&cZw=^wx>`x!^=^!^!_?q!_#O=^#O#P>`#P#o=^#o#p?q#p;'S=^;'S;=`@h<%lO=^&n>gXWS$i&jOY>`YZ&cZ!^>`!^!_?S!_#o>`#o#p?S#p;'S>`;'S;=`?k<%lO>`S?XSWSOY?SZ;'S?S;'S;=`?e<%lO?SS?hP;=`<%l?S&n?nP;=`<%l>`!f?xWWS(Z!bOY?qZw?qwx?Sx#O?q#O#P?S#P;'S?q;'S;=`@b<%lO?q!f@eP;=`<%l?q(Q@kP;=`<%l=^'`@w]WS$i&j(WpOY@nYZ&cZr@nrs>`s!^@n!^!_Ap!_#O@n#O#P>`#P#o@n#o#pAp#p;'S@n;'S;=`Bg<%lO@ntAwWWS(WpOYApZrAprs?Ss#OAp#O#P?S#P;'SAp;'S;=`Ba<%lOAptBdP;=`<%lAp'`BjP;=`<%l@n#WBvYWS(Wp(Z!bOYBmZrBmrs?qswBmwxApx#OBm#O#P?S#P;'SBm;'S;=`Cf<%lOBm#WCiP;=`<%lBm(rCoP;=`<%l<S%9[C}i$i&j(o%1l(Wp(Z!bOY%ZYZ&cZr%Zrs&}st%ZtuCruw%Zwx(rx!Q%Z!Q![Cr![!^%Z!^!_*g!_!c%Z!c!}Cr!}#O%Z#O#P&c#P#R%Z#R#SCr#S#T%Z#T#oCr#o#p*g#p$g%Z$g;'SCr;'S;=`El<%lOCr%9[EoP;=`<%lCr07[FRk$i&j(Wp(Z!b$]#t(T,2j(e$I[OY%ZYZ&cZr%Zrs&}st%ZtuEruw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Er![!^%Z!^!_*g!_!c%Z!c!}Er!}#O%Z#O#P&c#P#R%Z#R#SEr#S#T%Z#T#oEr#o#p*g#p$g%Z$g;'SEr;'S;=`I|<%lOEr+dHRk$i&j(Wp(Z!b$]#tOY%ZYZ&cZr%Zrs&}st%ZtuGvuw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Gv![!^%Z!^!_*g!_!c%Z!c!}Gv!}#O%Z#O#P&c#P#R%Z#R#SGv#S#T%Z#T#oGv#o#p*g#p$g%Z$g;'SGv;'S;=`Iv<%lOGv+dIyP;=`<%lGv07[JPP;=`<%lEr(KWJ_`$i&j(Wp(Z!b#p(ChOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KWKl_$i&j$Q(Ch(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z,#xLva(z+JY$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sv%ZvwM{wx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KWNW`$i&j#z(Ch(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'At! c_(Y';W$i&j(WpOY!!bYZ!#hZr!!brs!#hsw!!bwx!$xx!^!!b!^!_!%z!_#O!!b#O#P!#h#P#o!!b#o#p!%z#p;'S!!b;'S;=`!'c<%lO!!b'l!!i_$i&j(WpOY!!bYZ!#hZr!!brs!#hsw!!bwx!$xx!^!!b!^!_!%z!_#O!!b#O#P!#h#P#o!!b#o#p!%z#p;'S!!b;'S;=`!'c<%lO!!b&z!#mX$i&jOw!#hwx6cx!^!#h!^!_!$Y!_#o!#h#o#p!$Y#p;'S!#h;'S;=`!$r<%lO!#h`!$]TOw!$Ywx7]x;'S!$Y;'S;=`!$l<%lO!$Y`!$oP;=`<%l!$Y&z!$uP;=`<%l!#h'l!%R]$d`$i&j(WpOY(rYZ&cZr(rrs&cs!^(r!^!_)r!_#O(r#O#P&c#P#o(r#o#p)r#p;'S(r;'S;=`*a<%lO(r!Q!&PZ(WpOY!%zYZ!$YZr!%zrs!$Ysw!%zwx!&rx#O!%z#O#P!$Y#P;'S!%z;'S;=`!']<%lO!%z!Q!&yU$d`(WpOY)rZr)rs#O)r#P;'S)r;'S;=`*Z<%lO)r!Q!'`P;=`<%l!%z'l!'fP;=`<%l!!b/5|!'t_!l/.^$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z#&U!)O_!k!Lf$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z-!n!*[b$i&j(Wp(Z!b(U%&f#q(ChOY%ZYZ&cZr%Zrs&}sw%Zwx(rxz%Zz{!+d{!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW!+o`$i&j(Wp(Z!b#n(ChOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z+;x!,|`$i&j(Wp(Z!br+4YOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z,$U!.Z_!]+Jf$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z07[!/ec$i&j(Wp(Z!b!Q.2^OY%ZYZ&cZr%Zrs&}sw%Zwx(rx!O%Z!O!P!0p!P!Q%Z!Q![!3Y![!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z#%|!0ya$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!O%Z!O!P!2O!P!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z#%|!2Z_![!L^$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad!3eg$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![!3Y![!^%Z!^!_*g!_!g%Z!g!h!4|!h#O%Z#O#P&c#P#R%Z#R#S!3Y#S#X%Z#X#Y!4|#Y#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad!5Vg$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx{%Z{|!6n|}%Z}!O!6n!O!Q%Z!Q![!8S![!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S!8S#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad!6wc$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![!8S![!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S!8S#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad!8_c$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![!8S![!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S!8S#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z07[!9uf$i&j(Wp(Z!b#o(ChOY!;ZYZ&cZr!;Zrs!<nsw!;Zwx!Lcxz!;Zz{#-}{!P!;Z!P!Q#/d!Q!^!;Z!^!_#(i!_!`#7S!`!a#8i!a!}!;Z!}#O#,f#O#P!Dy#P#o!;Z#o#p#(i#p;'S!;Z;'S;=`#-w<%lO!;Z?O!;fb$i&j(Wp(Z!b!X7`OY!;ZYZ&cZr!;Zrs!<nsw!;Zwx!Lcx!P!;Z!P!Q#&`!Q!^!;Z!^!_#(i!_!}!;Z!}#O#,f#O#P!Dy#P#o!;Z#o#p#(i#p;'S!;Z;'S;=`#-w<%lO!;Z>^!<w`$i&j(Z!b!X7`OY!<nYZ&cZw!<nwx!=yx!P!<n!P!Q!Eq!Q!^!<n!^!_!Gr!_!}!<n!}#O!KS#O#P!Dy#P#o!<n#o#p!Gr#p;'S!<n;'S;=`!L]<%lO!<n<z!>Q^$i&j!X7`OY!=yYZ&cZ!P!=y!P!Q!>|!Q!^!=y!^!_!@c!_!}!=y!}#O!CW#O#P!Dy#P#o!=y#o#p!@c#p;'S!=y;'S;=`!Ek<%lO!=y<z!?Td$i&j!X7`O!^&c!_#W&c#W#X!>|#X#Z&c#Z#[!>|#[#]&c#]#^!>|#^#a&c#a#b!>|#b#g&c#g#h!>|#h#i&c#i#j!>|#j#k!>|#k#m&c#m#n!>|#n#o&c#p;'S&c;'S;=`&w<%lO&c7`!@hX!X7`OY!@cZ!P!@c!P!Q!AT!Q!}!@c!}#O!Ar#O#P!Bq#P;'S!@c;'S;=`!CQ<%lO!@c7`!AYW!X7`#W#X!AT#Z#[!AT#]#^!AT#a#b!AT#g#h!AT#i#j!AT#j#k!AT#m#n!AT7`!AuVOY!ArZ#O!Ar#O#P!B[#P#Q!@c#Q;'S!Ar;'S;=`!Bk<%lO!Ar7`!B_SOY!ArZ;'S!Ar;'S;=`!Bk<%lO!Ar7`!BnP;=`<%l!Ar7`!BtSOY!@cZ;'S!@c;'S;=`!CQ<%lO!@c7`!CTP;=`<%l!@c<z!C][$i&jOY!CWYZ&cZ!^!CW!^!_!Ar!_#O!CW#O#P!DR#P#Q!=y#Q#o!CW#o#p!Ar#p;'S!CW;'S;=`!Ds<%lO!CW<z!DWX$i&jOY!CWYZ&cZ!^!CW!^!_!Ar!_#o!CW#o#p!Ar#p;'S!CW;'S;=`!Ds<%lO!CW<z!DvP;=`<%l!CW<z!EOX$i&jOY!=yYZ&cZ!^!=y!^!_!@c!_#o!=y#o#p!@c#p;'S!=y;'S;=`!Ek<%lO!=y<z!EnP;=`<%l!=y>^!Ezl$i&j(Z!b!X7`OY&}YZ&cZw&}wx&cx!^&}!^!_'}!_#O&}#O#P&c#P#W&}#W#X!Eq#X#Z&}#Z#[!Eq#[#]&}#]#^!Eq#^#a&}#a#b!Eq#b#g&}#g#h!Eq#h#i&}#i#j!Eq#j#k!Eq#k#m&}#m#n!Eq#n#o&}#o#p'}#p;'S&};'S;=`(l<%lO&}8r!GyZ(Z!b!X7`OY!GrZw!Grwx!@cx!P!Gr!P!Q!Hl!Q!}!Gr!}#O!JU#O#P!Bq#P;'S!Gr;'S;=`!J|<%lO!Gr8r!Hse(Z!b!X7`OY'}Zw'}x#O'}#P#W'}#W#X!Hl#X#Z'}#Z#[!Hl#[#]'}#]#^!Hl#^#a'}#a#b!Hl#b#g'}#g#h!Hl#h#i'}#i#j!Hl#j#k!Hl#k#m'}#m#n!Hl#n;'S'};'S;=`(f<%lO'}8r!JZX(Z!bOY!JUZw!JUwx!Arx#O!JU#O#P!B[#P#Q!Gr#Q;'S!JU;'S;=`!Jv<%lO!JU8r!JyP;=`<%l!JU8r!KPP;=`<%l!Gr>^!KZ^$i&j(Z!bOY!KSYZ&cZw!KSwx!CWx!^!KS!^!_!JU!_#O!KS#O#P!DR#P#Q!<n#Q#o!KS#o#p!JU#p;'S!KS;'S;=`!LV<%lO!KS>^!LYP;=`<%l!KS>^!L`P;=`<%l!<n=l!Ll`$i&j(Wp!X7`OY!LcYZ&cZr!Lcrs!=ys!P!Lc!P!Q!Mn!Q!^!Lc!^!_# o!_!}!Lc!}#O#%P#O#P!Dy#P#o!Lc#o#p# o#p;'S!Lc;'S;=`#&Y<%lO!Lc=l!Mwl$i&j(Wp!X7`OY(rYZ&cZr(rrs&cs!^(r!^!_)r!_#O(r#O#P&c#P#W(r#W#X!Mn#X#Z(r#Z#[!Mn#[#](r#]#^!Mn#^#a(r#a#b!Mn#b#g(r#g#h!Mn#h#i(r#i#j!Mn#j#k!Mn#k#m(r#m#n!Mn#n#o(r#o#p)r#p;'S(r;'S;=`*a<%lO(r8Q# vZ(Wp!X7`OY# oZr# ors!@cs!P# o!P!Q#!i!Q!}# o!}#O#$R#O#P!Bq#P;'S# o;'S;=`#$y<%lO# o8Q#!pe(Wp!X7`OY)rZr)rs#O)r#P#W)r#W#X#!i#X#Z)r#Z#[#!i#[#])r#]#^#!i#^#a)r#a#b#!i#b#g)r#g#h#!i#h#i)r#i#j#!i#j#k#!i#k#m)r#m#n#!i#n;'S)r;'S;=`*Z<%lO)r8Q#$WX(WpOY#$RZr#$Rrs!Ars#O#$R#O#P!B[#P#Q# o#Q;'S#$R;'S;=`#$s<%lO#$R8Q#$vP;=`<%l#$R8Q#$|P;=`<%l# o=l#%W^$i&j(WpOY#%PYZ&cZr#%Prs!CWs!^#%P!^!_#$R!_#O#%P#O#P!DR#P#Q!Lc#Q#o#%P#o#p#$R#p;'S#%P;'S;=`#&S<%lO#%P=l#&VP;=`<%l#%P=l#&]P;=`<%l!Lc?O#&kn$i&j(Wp(Z!b!X7`OY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#W%Z#W#X#&`#X#Z%Z#Z#[#&`#[#]%Z#]#^#&`#^#a%Z#a#b#&`#b#g%Z#g#h#&`#h#i%Z#i#j#&`#j#k#&`#k#m%Z#m#n#&`#n#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z9d#(r](Wp(Z!b!X7`OY#(iZr#(irs!Grsw#(iwx# ox!P#(i!P!Q#)k!Q!}#(i!}#O#+`#O#P!Bq#P;'S#(i;'S;=`#,`<%lO#(i9d#)th(Wp(Z!b!X7`OY*gZr*grs'}sw*gwx)rx#O*g#P#W*g#W#X#)k#X#Z*g#Z#[#)k#[#]*g#]#^#)k#^#a*g#a#b#)k#b#g*g#g#h#)k#h#i*g#i#j#)k#j#k#)k#k#m*g#m#n#)k#n;'S*g;'S;=`+Z<%lO*g9d#+gZ(Wp(Z!bOY#+`Zr#+`rs!JUsw#+`wx#$Rx#O#+`#O#P!B[#P#Q#(i#Q;'S#+`;'S;=`#,Y<%lO#+`9d#,]P;=`<%l#+`9d#,cP;=`<%l#(i?O#,o`$i&j(Wp(Z!bOY#,fYZ&cZr#,frs!KSsw#,fwx#%Px!^#,f!^!_#+`!_#O#,f#O#P!DR#P#Q!;Z#Q#o#,f#o#p#+`#p;'S#,f;'S;=`#-q<%lO#,f?O#-tP;=`<%l#,f?O#-zP;=`<%l!;Z07[#.[b$i&j(Wp(Z!b(O0/l!X7`OY!;ZYZ&cZr!;Zrs!<nsw!;Zwx!Lcx!P!;Z!P!Q#&`!Q!^!;Z!^!_#(i!_!}!;Z!}#O#,f#O#P!Dy#P#o!;Z#o#p#(i#p;'S!;Z;'S;=`#-w<%lO!;Z07[#/o_$i&j(Wp(Z!bT0/lOY#/dYZ&cZr#/drs#0nsw#/dwx#4Ox!^#/d!^!_#5}!_#O#/d#O#P#1p#P#o#/d#o#p#5}#p;'S#/d;'S;=`#6|<%lO#/d06j#0w]$i&j(Z!bT0/lOY#0nYZ&cZw#0nwx#1px!^#0n!^!_#3R!_#O#0n#O#P#1p#P#o#0n#o#p#3R#p;'S#0n;'S;=`#3x<%lO#0n05W#1wX$i&jT0/lOY#1pYZ&cZ!^#1p!^!_#2d!_#o#1p#o#p#2d#p;'S#1p;'S;=`#2{<%lO#1p0/l#2iST0/lOY#2dZ;'S#2d;'S;=`#2u<%lO#2d0/l#2xP;=`<%l#2d05W#3OP;=`<%l#1p01O#3YW(Z!bT0/lOY#3RZw#3Rwx#2dx#O#3R#O#P#2d#P;'S#3R;'S;=`#3r<%lO#3R01O#3uP;=`<%l#3R06j#3{P;=`<%l#0n05x#4X]$i&j(WpT0/lOY#4OYZ&cZr#4Ors#1ps!^#4O!^!_#5Q!_#O#4O#O#P#1p#P#o#4O#o#p#5Q#p;'S#4O;'S;=`#5w<%lO#4O00^#5XW(WpT0/lOY#5QZr#5Qrs#2ds#O#5Q#O#P#2d#P;'S#5Q;'S;=`#5q<%lO#5Q00^#5tP;=`<%l#5Q05x#5zP;=`<%l#4O01p#6WY(Wp(Z!bT0/lOY#5}Zr#5}rs#3Rsw#5}wx#5Qx#O#5}#O#P#2d#P;'S#5};'S;=`#6v<%lO#5}01p#6yP;=`<%l#5}07[#7PP;=`<%l#/d)3h#7ab$i&j$Q(Ch(Wp(Z!b!X7`OY!;ZYZ&cZr!;Zrs!<nsw!;Zwx!Lcx!P!;Z!P!Q#&`!Q!^!;Z!^!_#(i!_!}!;Z!}#O#,f#O#P!Dy#P#o!;Z#o#p#(i#p;'S!;Z;'S;=`#-w<%lO!;ZAt#8vb$Z#t$i&j(Wp(Z!b!X7`OY!;ZYZ&cZr!;Zrs!<nsw!;Zwx!Lcx!P!;Z!P!Q#&`!Q!^!;Z!^!_#(i!_!}!;Z!}#O#,f#O#P!Dy#P#o!;Z#o#p#(i#p;'S!;Z;'S;=`#-w<%lO!;Z'Ad#:Zp$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!O%Z!O!P!3Y!P!Q%Z!Q![#<_![!^%Z!^!_*g!_!g%Z!g!h!4|!h#O%Z#O#P&c#P#R%Z#R#S#<_#S#U%Z#U#V#?i#V#X%Z#X#Y!4|#Y#b%Z#b#c#>_#c#d#Bq#d#l%Z#l#m#Es#m#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#<jk$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!O%Z!O!P!3Y!P!Q%Z!Q![#<_![!^%Z!^!_*g!_!g%Z!g!h!4|!h#O%Z#O#P&c#P#R%Z#R#S#<_#S#X%Z#X#Y!4|#Y#b%Z#b#c#>_#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#>j_$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#?rd$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!R#AQ!R!S#AQ!S!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#AQ#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#A]f$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!R#AQ!R!S#AQ!S!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#AQ#S#b%Z#b#c#>_#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#Bzc$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!Y#DV!Y!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#DV#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#Dbe$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!Y#DV!Y!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#DV#S#b%Z#b#c#>_#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#E|g$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![#Ge![!^%Z!^!_*g!_!c%Z!c!i#Ge!i#O%Z#O#P&c#P#R%Z#R#S#Ge#S#T%Z#T#Z#Ge#Z#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#Gpi$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![#Ge![!^%Z!^!_*g!_!c%Z!c!i#Ge!i#O%Z#O#P&c#P#R%Z#R#S#Ge#S#T%Z#T#Z#Ge#Z#b%Z#b#c#>_#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z*)x#Il_!g$b$i&j$O)Lv(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z)[#Jv_al$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z04f#LS^h#)`#R-<U(Wp(Z!b$n7`OY*gZr*grs'}sw*gwx)rx!P*g!P!Q#MO!Q!^*g!^!_#Mt!_!`$ f!`#O*g#P;'S*g;'S;=`+Z<%lO*g(n#MXX$k&j(Wp(Z!bOY*gZr*grs'}sw*gwx)rx#O*g#P;'S*g;'S;=`+Z<%lO*g(El#M}Z#r(Ch(Wp(Z!bOY*gZr*grs'}sw*gwx)rx!_*g!_!`#Np!`#O*g#P;'S*g;'S;=`+Z<%lO*g(El#NyX$Q(Ch(Wp(Z!bOY*gZr*grs'}sw*gwx)rx#O*g#P;'S*g;'S;=`+Z<%lO*g(El$ oX#s(Ch(Wp(Z!bOY*gZr*grs'}sw*gwx)rx#O*g#P;'S*g;'S;=`+Z<%lO*g*)x$!ga#`*!Y$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`0z!`!a$#l!a#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(K[$#w_#k(Cl$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z*)x$%Vag!*r#s(Ch$f#|$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`$&[!`!a$'f!a#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW$&g_#s(Ch$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW$'qa#r(Ch$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`!a$(v!a#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW$)R`#r(Ch$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(Kd$*`a(r(Ct$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!a%Z!a!b$+e!b#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW$+p`$i&j#{(Ch(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z%#`$,}_!|$Ip$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z04f$.X_!S0,v$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(n$/]Z$i&jO!^$0O!^!_$0f!_#i$0O#i#j$0k#j#l$0O#l#m$2^#m#o$0O#o#p$0f#p;'S$0O;'S;=`$4i<%lO$0O(n$0VT_#S$i&jO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c#S$0kO_#S(n$0p[$i&jO!Q&c!Q![$1f![!^&c!_!c&c!c!i$1f!i#T&c#T#Z$1f#Z#o&c#o#p$3|#p;'S&c;'S;=`&w<%lO&c(n$1kZ$i&jO!Q&c!Q![$2^![!^&c!_!c&c!c!i$2^!i#T&c#T#Z$2^#Z#o&c#p;'S&c;'S;=`&w<%lO&c(n$2cZ$i&jO!Q&c!Q![$3U![!^&c!_!c&c!c!i$3U!i#T&c#T#Z$3U#Z#o&c#p;'S&c;'S;=`&w<%lO&c(n$3ZZ$i&jO!Q&c!Q![$0O![!^&c!_!c&c!c!i$0O!i#T&c#T#Z$0O#Z#o&c#p;'S&c;'S;=`&w<%lO&c#S$4PR!Q![$4Y!c!i$4Y#T#Z$4Y#S$4]S!Q![$4Y!c!i$4Y#T#Z$4Y#q#r$0f(n$4lP;=`<%l$0O#1[$4z_!Y#)l$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW$6U`#x(Ch$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z+;p$7c_$i&j(Wp(Z!b(a+4QOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z07[$8qk$i&j(Wp(Z!b(T,2j$_#t(e$I[OY%ZYZ&cZr%Zrs&}st%Ztu$8buw%Zwx(rx}%Z}!O$:f!O!Q%Z!Q![$8b![!^%Z!^!_*g!_!c%Z!c!}$8b!}#O%Z#O#P&c#P#R%Z#R#S$8b#S#T%Z#T#o$8b#o#p*g#p$g%Z$g;'S$8b;'S;=`$<l<%lO$8b+d$:qk$i&j(Wp(Z!b$_#tOY%ZYZ&cZr%Zrs&}st%Ztu$:fuw%Zwx(rx}%Z}!O$:f!O!Q%Z!Q![$:f![!^%Z!^!_*g!_!c%Z!c!}$:f!}#O%Z#O#P&c#P#R%Z#R#S$:f#S#T%Z#T#o$:f#o#p*g#p$g%Z$g;'S$:f;'S;=`$<f<%lO$:f+d$<iP;=`<%l$:f07[$<oP;=`<%l$8b#Jf$<{X!_#Hb(Wp(Z!bOY*gZr*grs'}sw*gwx)rx#O*g#P;'S*g;'S;=`+Z<%lO*g,#x$=sa(y+JY$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p#q$+e#q;'S%Z;'S;=`+a<%lO%Z)>v$?V_!^(CdvBr$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z?O$@a_!q7`$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z07[$Aq|$i&j(Wp(Z!b'|0/l$]#t(T,2j(e$I[OX%ZXY+gYZ&cZ[+g[p%Zpq+gqr%Zrs&}st%ZtuEruw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Er![!^%Z!^!_*g!_!c%Z!c!}Er!}#O%Z#O#P&c#P#R%Z#R#SEr#S#T%Z#T#oEr#o#p*g#p$f%Z$f$g+g$g#BYEr#BY#BZ$A`#BZ$ISEr$IS$I_$A`$I_$JTEr$JT$JU$A`$JU$KVEr$KV$KW$A`$KW&FUEr&FU&FV$A`&FV;'SEr;'S;=`I|<%l?HTEr?HT?HU$A`?HUOEr07[$D|k$i&j(Wp(Z!b'}0/l$]#t(T,2j(e$I[OY%ZYZ&cZr%Zrs&}st%ZtuEruw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Er![!^%Z!^!_*g!_!c%Z!c!}Er!}#O%Z#O#P&c#P#R%Z#R#SEr#S#T%Z#T#oEr#o#p*g#p$g%Z$g;'SEr;'S;=`I|<%lOEr",tokenizers:[MX,NX,PX,IX,2,3,4,5,6,7,8,9,10,11,12,13,14,jX,new VY("$S~RRtu[#O#Pg#S#T#|~_P#o#pb~gOx~~jVO#i!P#i#j!U#j#l!P#l#m!q#m;'S!P;'S;=`#v<%lO!P~!UO!U~~!XS!Q![!e!c!i!e#T#Z!e#o#p#Z~!hR!Q![!q!c!i!q#T#Z!q~!tR!Q![!}!c!i!}#T#Z!}~#QR!Q![!P!c!i!P#T#Z!P~#^R!Q![#g!c!i#g#T#Z#g~#jS!Q![#g!c!i#g#T#Z#g#q#r!P~#yP;=`<%l!P~$RO(c~~",141,340),new VY(`j~RQYZXz{^~^O(Q~~aP!P!Qd~iO(R~~`,25,323)],topRules:{Script:[0,7],SingleExpression:[1,276],SingleClassItem:[2,277]},dialects:{jsx:0,ts:15175},dynamicPrecedences:{80:1,82:1,94:1,169:1,199:1},specialized:[{term:327,get:e=>RX[e]||-1},{term:343,get:e=>zX[e]||-1},{term:95,get:e=>BX[e]||-1}],tokenPrec:15201}),HX=[Xq("function ${name}(${params}) {\n ${}\n}",{label:`function`,detail:`definition`,type:`keyword`}),Xq("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n ${}\n}",{label:`for`,detail:`loop`,type:`keyword`}),Xq("for (let ${name} of ${collection}) {\n ${}\n}",{label:`for`,detail:`of loop`,type:`keyword`}),Xq(`do {
|
|
44
|
+
\${}
|
|
45
|
+
} while (\${})`,{label:`do`,detail:`loop`,type:`keyword`}),Xq(`while (\${}) {
|
|
46
|
+
\${}
|
|
47
|
+
}`,{label:`while`,detail:`loop`,type:`keyword`}),Xq(`try {
|
|
48
|
+
\${}
|
|
49
|
+
} catch (\${error}) {
|
|
50
|
+
\${}
|
|
51
|
+
}`,{label:`try`,detail:`/ catch block`,type:`keyword`}),Xq(`if (\${}) {
|
|
52
|
+
\${}
|
|
53
|
+
}`,{label:`if`,detail:`block`,type:`keyword`}),Xq(`if (\${}) {
|
|
54
|
+
\${}
|
|
55
|
+
} else {
|
|
56
|
+
\${}
|
|
57
|
+
}`,{label:`if`,detail:`/ else block`,type:`keyword`}),Xq(`class \${name} {
|
|
58
|
+
constructor(\${params}) {
|
|
59
|
+
\${}
|
|
60
|
+
}
|
|
61
|
+
}`,{label:`class`,detail:`definition`,type:`keyword`}),Xq('import {${names}} from "${module}"\n${}',{label:`import`,detail:`named`,type:`keyword`}),Xq('import ${name} from "${module}"\n${}',{label:`import`,detail:`default`,type:`keyword`})],UX=HX.concat([Xq(`interface \${name} {
|
|
62
|
+
\${}
|
|
63
|
+
}`,{label:`interface`,detail:`definition`,type:`keyword`}),Xq("type ${name} = ${type}",{label:`type`,detail:`definition`,type:`keyword`}),Xq(`enum \${name} {
|
|
64
|
+
\${}
|
|
65
|
+
}`,{label:`enum`,detail:`definition`,type:`keyword`})]),WX=new vR,GX=new Set([`Script`,`Block`,`FunctionExpression`,`FunctionDeclaration`,`ArrowFunction`,`MethodDeclaration`,`ForStatement`]);function KX(e){return(t,n)=>{let r=t.node.getChild(`VariableDefinition`);return r&&n(r,e),!0}}var qX=[`FunctionDeclaration`],JX={FunctionDeclaration:KX(`function`),ClassDeclaration:KX(`class`),ClassExpression:()=>!0,EnumDeclaration:KX(`constant`),TypeAliasDeclaration:KX(`type`),NamespaceDeclaration:KX(`namespace`),VariableDefinition(e,t){e.matchContext(qX)||t(e,`variable`)},TypeDefinition(e,t){t(e,`type`)},__proto__:null};function YX(e,t){let n=WX.get(t);if(n)return n;let r=[],i=!0;function a(t,n){let i=e.sliceString(t.from,t.to);r.push({label:i,type:n})}return t.cursor(ZL.IncludeAnonymous).iterate(t=>{if(i)i=!1;else if(t.name){let e=JX[t.name];if(e&&e(t,a)||GX.has(t.name))return!1}else if(t.to-t.from>8192){for(let n of YX(e,t.node))r.push(n);return!1}}),WX.set(t,r),r}var XX=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,ZX=[`TemplateString`,`String`,`RegExp`,`LineComment`,`BlockComment`,`VariableDefinition`,`TypeDefinition`,`Label`,`PropertyDefinition`,`PropertyName`,`PrivatePropertyDefinition`,`PrivatePropertyName`,`JSXText`,`JSXAttributeValue`,`JSXOpenTag`,`JSXCloseTag`,`JSXSelfClosingTag`,`.`,`?.`];function QX(e){let t=rz(e.state).resolveInner(e.pos,-1);if(ZX.indexOf(t.name)>-1)return null;let n=t.name==`VariableName`||t.to-t.from<20&&XX.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let n=t;n;n=n.parent)GX.has(n.name)&&(r=r.concat(YX(e.state.doc,n)));return{options:r,from:n?t.from:e.pos,validFor:XX}}var $X=nz.define({name:`javascript`,parser:VX.configure({props:[bz.add({IfStatement:Mz({except:/^\s*({|else\b)/}),TryStatement:Mz({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:jz,SwitchBody:e=>{let t=e.textAfter,n=/^\s*\}/.test(t),r=/^\s*(case|default)\b/.test(t);return e.baseIndent+(n?0:r?1:2)*e.unit},Block:kz({closing:`}`}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":Mz({except:/^\s*{/}),JSXElement(e){let t=/^\s*<\//.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},JSXEscape(e){let t=/\s*\}/.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},"JSXOpenTag JSXSelfClosingTag"(e){return e.column(e.node.from)+e.unit}}),Iz.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":Lz,BlockComment(e){return{from:e.from+2,to:e.to-2}},JSXElement(e){let t=e.firstChild;if(!t||t.name==`JSXSelfClosingTag`)return null;let n=e.lastChild;return{from:t.to,to:n.type.isError?e.to:n.from}},"JSXSelfClosingTag JSXOpenTag"(e){let t=e.firstChild?.nextSibling,n=e.lastChild;return!t||t.type.isError?null:{from:t.to,to:n.type.isError?e.to:n.from}}})]}),languageData:{closeBrackets:{brackets:[`(`,`[`,`{`,`'`,`"`,"`"]},commentTokens:{line:`//`,block:{open:`/*`,close:`*/`}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:`$`}}),eZ={test:e=>/^JSX/.test(e.name),facet:QR({commentTokens:{block:{open:`{/*`,close:`*/}`}}})},tZ=$X.configure({dialect:`ts`},`typescript`),nZ=$X.configure({dialect:`jsx`,props:[$R.add(e=>e.isTop?[eZ]:void 0)]}),rZ=$X.configure({dialect:`jsx ts`,props:[$R.add(e=>e.isTop?[eZ]:void 0)]},`typescript`),iZ=e=>({label:e,type:`keyword`}),aZ=`break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield`.split(` `).map(iZ),oZ=aZ.concat([`declare`,`implements`,`private`,`protected`,`public`].map(iZ));function sZ(e={}){let t=e.jsx?e.typescript?rZ:nZ:e.typescript?tZ:$X,n=e.typescript?UX.concat(oZ):HX.concat(aZ);return new pz(t,[$X.data.of({autocomplete:BK(ZX,zK(n))}),$X.data.of({autocomplete:QX}),e.jsx?dZ:[]])}function cZ(e){for(;;){if(e.name==`JSXOpenTag`||e.name==`JSXSelfClosingTag`||e.name==`JSXFragmentTag`)return e;if(e.name==`JSXEscape`||!e.parent)return null;e=e.parent}}function lZ(e,t,n=e.length){for(let r=t?.firstChild;r;r=r.nextSibling)if(r.name==`JSXIdentifier`||r.name==`JSXBuiltin`||r.name==`JSXNamespacedName`||r.name==`JSXMemberExpression`)return e.sliceString(r.from,Math.min(r.to,n));return``}var uZ=typeof navigator==`object`&&/Android\b/.test(navigator.userAgent),dZ=SF.inputHandler.of((e,t,n,r,i)=>{if((uZ?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=`>`&&r!=`/`||!$X.isActiveAt(e.state,t,-1))return!1;let a=i(),{state:o}=a,s=o.changeByRange(e=>{let{head:t}=e,n=rz(o).resolveInner(t-1,-1),i;if(n.name==`JSXStartTag`&&(n=n.parent),!(o.doc.sliceString(t-1,t)!=r||n.name==`JSXAttributeValue`&&n.to>t)){if(r==`>`&&n.name==`JSXFragmentTag`)return{range:e,changes:{from:t,insert:`</>`}};if(r==`/`&&n.name==`JSXStartCloseTag`){let e=n.parent,r=e.parent;if(r&&e.from==t-2&&((i=lZ(o.doc,r.firstChild,t))||r.firstChild?.name==`JSXFragmentTag`)){let e=`${i}>`;return{range:Q.cursor(t+e.length,-1),changes:{from:t,insert:e}}}}else if(r==`>`){let r=cZ(n);if(r&&r.name==`JSXOpenTag`&&!/^\/?>|^<\//.test(o.doc.sliceString(t,t+2))&&(i=lZ(o.doc,r,t)))return{range:e,changes:{from:t,insert:`</${i}>`}}}}return{range:e}});return!s.changes.empty&&(e.dispatch([a,o.update(s,{userEvent:`input.complete`,scrollIntoView:!0})]),!0)}),fZ=OR({String:$.string,Number:$.number,"True False":$.bool,PropertyName:$.propertyName,Null:$.null,", :":$.separator,"[ ]":$.squareBracket,"{ }":$.brace}),pZ=nX.deserialize({version:14,states:"$bOVQPOOOOQO'#Cb'#CbOnQPO'#CeOvQPO'#ClOOQO'#Cr'#CrQOQPOOOOQO'#Cg'#CgO}QPO'#CfO!SQPO'#CtOOQO,59P,59PO![QPO,59PO!aQPO'#CuOOQO,59W,59WO!iQPO,59WOVQPO,59QOqQPO'#CmO!nQPO,59`OOQO1G.k1G.kOVQPO'#CnO!vQPO,59aOOQO1G.r1G.rOOQO1G.l1G.lOOQO,59X,59XOOQO-E6k-E6kOOQO,59Y,59YOOQO-E6l-E6l",stateData:`#O~OeOS~OQSORSOSSOTSOWQO_ROgPO~OVXOgUO~O^[O~PVO[^O~O]_OVhX~OVaO~O]bO^iX~O^dO~O]_OVha~O]bO^ia~O`,goto:"!kjPPPPPPkPPkqwPPPPk{!RPPP!XP!e!hXSOR^bQWQRf_TVQ_Q`WRg`QcZRicQTOQZRQe^RhbRYQR]R",nodeNames:`⚠ JsonText True False Null Number String } { Object Property PropertyName : , ] [ Array`,maxTerm:25,nodeProps:[[`isolate`,-2,6,11,``],[`openedBy`,7,`{`,14,`[`],[`closedBy`,8,`}`,15,`]`]],propSources:[fZ],skippedNodes:[0],repeatNodeCount:2,tokenData:"(|~RaXY!WYZ!W]^!Wpq!Wrs!]|}$u}!O$z!Q!R%T!R![&c![!]&t!}#O&y#P#Q'O#Y#Z'T#b#c'r#h#i(Z#o#p(r#q#r(w~!]Oe~~!`Wpq!]qr!]rs!xs#O!]#O#P!}#P;'S!];'S;=`$o<%lO!]~!}Og~~#QXrs!]!P!Q!]#O#P!]#U#V!]#Y#Z!]#b#c!]#f#g!]#h#i!]#i#j#m~#pR!Q![#y!c!i#y#T#Z#y~#|R!Q![$V!c!i$V#T#Z$V~$YR!Q![$c!c!i$c#T#Z$c~$fR!Q![!]!c!i!]#T#Z!]~$rP;=`<%l!]~$zO]~~$}Q!Q!R%T!R![&c~%YRT~!O!P%c!g!h%w#X#Y%w~%fP!Q![%i~%nRT~!Q![%i!g!h%w#X#Y%w~%zR{|&T}!O&T!Q![&Z~&WP!Q![&Z~&`PT~!Q![&Z~&hST~!O!P%c!Q![&c!g!h%w#X#Y%w~&yO[~~'OO_~~'TO^~~'WP#T#U'Z~'^P#`#a'a~'dP#g#h'g~'jP#X#Y'm~'rOR~~'uP#i#j'x~'{P#`#a(O~(RP#`#a(U~(ZOS~~(^P#f#g(a~(dP#i#j(g~(jP#X#Y(m~(rOQ~~(wOW~~(|OV~",tokenizers:[0],topRules:{JsonText:[0,1]},tokenPrec:0}),mZ=nz.define({name:`json`,parser:pZ.configure({props:[bz.add({Object:Mz({except:/^\s*\}/}),Array:Mz({except:/^\s*\]/})}),Iz.add({"Object Array":Lz})]}),languageData:{closeBrackets:{brackets:[`[`,`{`,`"`]},indentOnInput:/^\s*[\}\]]$/}});function hZ(){return new pz(mZ)}var gZ={};function _Z(e,t){for(var n=0;n<t.length;n++)gZ[t[n]]=e}var vZ=[`true`,`false`],yZ=[`if`,`then`,`do`,`else`,`elif`,`while`,`until`,`for`,`in`,`esac`,`fi`,`fin`,`fil`,`done`,`exit`,`set`,`unset`,`export`,`function`],bZ=`ab.awk.bash.beep.cat.cc.cd.chown.chmod.chroot.clear.cp.curl.cut.diff.echo.find.gawk.gcc.get.git.grep.hg.kill.killall.ln.ls.make.mkdir.openssl.mv.nc.nl.node.npm.ping.ps.restart.rm.rmdir.sed.service.sh.shopt.shred.source.sort.sleep.ssh.start.stop.su.sudo.svn.tee.telnet.top.touch.vi.vim.wall.wc.wget.who.write.yes.zsh`.split(`.`);_Z(`atom`,vZ),_Z(`keyword`,yZ),_Z(`builtin`,bZ);function xZ(e,t){if(e.eatSpace())return null;var n=e.sol(),r=e.next();if(r===`\\`)return e.next(),null;if(r===`'`||r===`"`||r==="`")return t.tokens.unshift(SZ(r,r==="`"?`quote`:`string`)),EZ(e,t);if(r===`#`)return n&&e.eat(`!`)?(e.skipToEnd(),`meta`):(e.skipToEnd(),`comment`);if(r===`$`)return t.tokens.unshift(wZ),EZ(e,t);if(r===`+`||r===`=`)return`operator`;if(r===`-`)return e.eat(`-`),e.eatWhile(/\w/),`attribute`;if(r==`<`){if(e.match(`<<`))return`operator`;var i=e.match(/^<-?\s*(?:['"]([^'"]*)['"]|([^'"\s]*))/);if(i)return t.tokens.unshift(TZ(i[1]||i[2])),`string.special`}if(/\d/.test(r)&&(e.eatWhile(/\d/),e.eol()||!/\w/.test(e.peek())))return`number`;e.eatWhile(/[\w-]/);var a=e.current();return e.peek()===`=`&&/\w+/.test(a)?`def`:gZ.hasOwnProperty(a)?gZ[a]:null}function SZ(e,t){var n=e==`(`?`)`:e==`{`?`}`:e;return function(r,i){for(var a,o=!1;(a=r.next())!=null;){if(a===n&&!o){i.tokens.shift();break}if(a===`$`&&!o&&e!==`'`&&r.peek()!=n){o=!0,r.backUp(1),i.tokens.unshift(wZ);break}if(!o&&e!==n&&a===e)return i.tokens.unshift(SZ(e,t)),EZ(r,i);if(!o&&/['"]/.test(a)&&!/['"]/.test(e)){i.tokens.unshift(CZ(a,`string`)),r.backUp(1);break}o=!o&&a===`\\`}return t}}function CZ(e,t){return function(n,r){return r.tokens[0]=SZ(e,t),n.next(),EZ(n,r)}}var wZ=function(e,t){t.tokens.length>1&&e.eat(`$`);var n=e.next();return/['"({]/.test(n)?(t.tokens[0]=SZ(n,n==`(`?`quote`:n==`{`?`def`:`string`),EZ(e,t)):(/\d/.test(n)||e.eatWhile(/\w/),t.tokens.shift(),`def`)};function TZ(e){return function(t,n){return t.sol()&&t.string==e&&n.tokens.shift(),t.skipToEnd(),`string.special`}}function EZ(e,t){return(t.tokens[0]||xZ)(e,t)}var DZ={name:`shell`,startState:function(){return{tokens:[]}},token:function(e,t){return EZ(e,t)},languageData:{autocomplete:vZ.concat(yZ,bZ),closeBrackets:{brackets:[`(`,`[`,`{`,`'`,`"`,"`"]},commentTokens:{line:`#`}}};function OZ(e){let t=(e||``).split(`.`).pop()?.toLowerCase();switch(t){case`js`:case`mjs`:case`ts`:return[sZ({typescript:t===`ts`})];case`json`:return[hZ()];case`sh`:case`bash`:return[zB.define(DZ)];default:return[]}}function kZ({value:e,onChange:t,path:n,className:r=``}){let i=(0,X.useMemo)(()=>OZ(n),[n]),{resolvedScheme:a}=vs();return(0,Z.jsx)(jY,{value:e,onChange:t,extensions:i,theme:a===`dark`?`dark`:`light`,className:r,basicSetup:{lineNumbers:!0,foldGutter:!0,highlightActiveLine:!0,bracketMatching:!0,autocompletion:!1}})}function AZ(e){return`/workspaces/${e}/hooks`}async function jZ(e){return await Y.get(AZ(e))||[]}async function MZ(e,t){return(await Y.get(`${AZ(e)}/${t}`))?.content??``}async function NZ(e,t,n){await Y.put(`${AZ(e)}/${t}`,{content:n})}async function PZ(e,t){await Y.delete(`${AZ(e)}/${t}`)}var FZ=[`example-`,`disabled-`,`_`];function IZ(e){let t=e.lastIndexOf(`/`);return{dir:t===-1?``:e.slice(0,t+1),base:t===-1?e:e.slice(t+1)}}function LZ(e){return FZ.find(t=>e.startsWith(t))??null}function RZ(e){return LZ(IZ(e).base)===null}function zZ(e){return IZ(e).base.startsWith(`example-`)}function BZ(e){let{dir:t,base:n}=IZ(e),r=LZ(n);return t+(r?n.slice(r.length):`disabled-${n}`)}async function VZ(e,t,n){if(RZ(t)===n)return t;let r=BZ(t);return await NZ(e,r,await MZ(e,t)),await PZ(e,t),r}function HZ(e){let t={};for(let n of e){let e;e=n.path.includes(`/`)?n.path.split(`/`)[0]:/^(?:example-|disabled-|_)?rules\.json$/.test(n.path)?`rules`:n.path.replace(/\.js$/,``),(t[e]||=[]).push(n)}return t}function UZ(e){let t=e.when?.event;return Array.isArray(t)?t.map(String):t?[String(t)]:[]}function WZ(e){let t=e.when?.pathExact??e.when?.path;return Array.isArray(t)?t.map(String):typeof t==`string`?[t]:[]}function GZ(e){let t=String(e||``).split(`/`).filter(Boolean);return t[0]===`workspace`&&t.length>=2?{backend:`workspace:${t[1]}`,rel:t.slice(2).join(`/`)}:t[0]===`device`?t.length>=3?{backend:t[2],rel:t.slice(3).join(`/`)}:null:t.length>=2?{backend:t[1],rel:t.slice(2).join(`/`)}:null}function KZ(e){return`dir:/${GZ(e)?.rel||``}`}function qZ(e){let t=new URLSearchParams;return e.kind&&e.kind!==`mirror`&&t.set(`addRuleKind`,e.kind),e.path&&t.set(`addRulePath`,e.path),e.target&&t.set(`addRuleTarget`,e.target),e.storeTo&&t.set(`addRuleStoreTo`,e.storeTo),e.storeFolder&&t.set(`addRuleStoreFolder`,e.storeFolder),t}function JZ(e){return String(e||``).replace(/^[a-z]+:/i,``).split(`/`).filter(Boolean).join(`/`)}function YZ(e){let t=e.filter(e=>e.path.startsWith(`started/`)&&e.path.includes(`backend-tree-sync`));return t.find(e=>RZ(e.path))?.path??t[0]?.path??null}var XZ=`rules.json`;async function ZZ(e){try{let t=await MZ(e,XZ),n=JSON.parse(t||`{}`);return Array.isArray(n.rules)?n.rules:[]}catch{return[]}}async function QZ(e,t){await NZ(e,XZ,JSON.stringify({$schema:`canvas.hook-rules/v1`,rules:t},null,2)+`
|
|
66
|
+
`)}async function $Z(e,t={}){let n=new URLSearchParams;t.status&&n.set(`status`,t.status),t.handler&&n.set(`handler`,t.handler),t.limit&&n.set(`limit`,String(t.limit));let r=n.toString();return await Y.get(`${AZ(e)}/pending${r?`?${r}`:``}`)||[]}async function eQ(e,t){return await Y.post(`${AZ(e)}/pending/decisions`,t)}async function tQ(e,t){return await Y.get(`${AZ(e)}/runs/${encodeURIComponent(t)}`)}async function nQ(e,t={}){let n=new URLSearchParams;t.limit&&n.set(`limit`,String(t.limit)),t.handler&&n.set(`handler`,t.handler),t.event&&n.set(`event`,t.event),t.failed&&n.set(`failed`,`true`);let r=n.toString();return await Y.get(`${AZ(e)}/runs${r?`?${r}`:``}`)||[]}var rQ=1e4,iQ=`canvas.hooks.backfillLimit`;function aQ(e){let t=Math.floor(Number(e));return!Number.isFinite(t)||t<1?100:Math.min(t,rQ)}function oQ(){try{let e=localStorage.getItem(iQ);return e?aQ(e):100}catch{return 100}}function sQ(e){let t=aQ(e);try{localStorage.setItem(iQ,String(t))}catch{}return t}function cQ(e){if(e.includes(`/`)){let t=e.split(`/`)[0];return t===`lib`||t===`rules`?null:t}return e.endsWith(`.js`)?e.replace(/\.js$/,``).replace(/^(?:example-|disabled-|_)/,``):null}async function lQ(e,t){return await Y.post(`${AZ(e)}/backfill`,t)}async function uQ(e,t){return await Y.post(`${AZ(e)}/run`,t)}async function dQ(e,t){return await Y.post(`${AZ(e)}/runs/${t}/replay`,{})}async function fQ(e){return await Y.get(`${AZ(e)}/meta`)}async function pQ(e,t){return await Y.post(`${AZ(e)}/generate`,t)}async function mQ(e,t){let n=await MZ(e,XZ),r=JSON.parse(n),i=Array.isArray(r)?r:r?.rules;if(!Array.isArray(i))throw Error(`The workspace rules file is invalid. Fix it in Rules before adding an Auto-Link.`);let a=(Array.isArray(t)?t:[t]).filter(e=>!i.some(t=>t.id===e.id));if(!a.length)return;let o=Array.isArray(r)?[...i,...a]:{...r,rules:[...i,...a]};await NZ(e,XZ,JSON.stringify(o,null,2)+`
|
|
67
|
+
`)}function hQ(e){return`/workspaces/${e}/scripts`}async function gQ(e){return await Y.get(hQ(e))||[]}async function _Q(e,t){return(await Y.get(`${hQ(e)}/${t}`))?.content??``}async function vQ(e,t,n){await Y.put(`${hQ(e)}/${t}`,{content:n})}async function yQ(e,t){await Y.delete(`${hQ(e)}/${t}`)}var bQ=[{value:``,label:`any item`},{value:`email`,label:`an email`},{value:`tab`,label:`a browser tab / link`},{value:`note`,label:`a note`},{value:`file`,label:`a file`},{value:`todo`,label:`a todo / task`}],xQ=[{value:`document.inserted`,label:`is added`,hint:`Fires when the item is created or uploaded.`},{value:`document.updated`,label:`is updated`,hint:`Fires on every edit of the item.`},{value:`document.linked`,label:`is filed into a folder`,hint:`Fires when the item is (re)filed into a tree path — the usual pair with "is added" for folder rules.`},{value:`document.unlinked`,label:`is removed from a folder`,hint:`Fires when the item leaves a tree path.`}],SQ=[{key:`pathExact`,label:`is directly in the folder`,hint:`Only this folder, excluding subfolders`},{key:`path`,label:`is under the folder`,hint:`/projects/canvas/UI or backends:/workspace/home/foo`},{key:`mime`,label:`file type is`,hint:`image/*, application/pdf`},{key:`from`,label:`sender contains`,hint:`boss@company.tld`},{key:`to`,label:`recipient (To/Cc) contains`,hint:`invoice@my-company.tld`},{key:`subject`,label:`subject contains`,hint:`invoice`},{key:`fromRegex`,label:`sender matches regex`,hint:`@(acme|example)\\.com$`},{key:`toRegex`,label:`recipient (To/Cc) matches regex`,hint:`^(billing|accounts)@`},{key:`subjectRegex`,label:`subject matches regex`,hint:`^invoice\\s+\\d+`},{key:`urlRegex`,label:`URL matches regex`,hint:`/(invoice|receipt)/`},{key:`urlHost`,label:`website is`,hint:`youtube.com`},{key:`urlContains`,label:`URL contains`,hint:`/watch?v=`},{key:`attachment`,label:`has an attachment of type`,hint:`application/pdf, or * for any`}],CQ=[{key:`store`,label:`keep the file on a storage backend`,icon:_e,tone:`text-sky-600 dark:text-sky-400 bg-sky-500/10`},{key:`download`,label:`download what the link points at`,icon:wn,tone:`text-rose-600 dark:text-rose-400 bg-rose-500/10`},{key:`link`,label:`file it into a folder`,icon:Dn,tone:`text-emerald-600 dark:text-emerald-400 bg-emerald-500/10`},{key:`unlink`,label:`remove it from a folder`,icon:Dn,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`tag`,label:`add tags`,icon:h,tone:`text-violet-600 dark:text-violet-400 bg-violet-500/10`},{key:`unstore`,label:`delete the file from a storage backend`,icon:tt,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`notify`,label:`send me a message`,icon:_,tone:`text-pink-600 dark:text-pink-400 bg-pink-500/10`},{key:`agent`,label:`ask an agent`,icon:st,tone:`text-indigo-600 dark:text-indigo-400 bg-indigo-500/10`},{key:`script`,label:`run a script`,icon:Oe,tone:`text-slate-600 dark:text-slate-300 bg-slate-500/10`},{key:`delete`,label:`delete it from Canvas`,icon:lt,tone:`text-destructive bg-destructive/10`},{key:`destroy`,label:`delete it everywhere`,icon:lt,tone:`text-destructive bg-destructive/10`}],wQ=e=>CQ.find(t=>t.key===e)||CQ[1],TQ=`{{title}}{{ext}}`,EQ=`{{YYYY}}/{{MM}}/{{YYYY}}{{MM}}{{DD}}_{{HH}}{{mm}}{{ss}}{{ext}}`,DQ=[{value:`auto`,label:`whatever it is (auto)`,hint:`arXiv → the PDF · YouTube, Vimeo, TikTok… → the video · image / video / PDF links → the file · anything else → the page.`},{value:`image`,label:`the file itself (image, PDF, …)`,hint:`Fetches the bytes the URL serves.`},{value:`video`,label:`the video (yt-dlp)`,hint:`Best video + audio, merged. Needs yt-dlp on the server.`},{value:`arxiv`,label:`the arXiv paper (PDF)`,hint:`Works for abs/ and pdf/ links.`},{value:`page`,label:`the page with its images & styles`,hint:`One page, offline-readable (wget --page-requisites).`},{value:`website`,label:`the whole website (mirror)`,hint:`Follows links on the same site up to the chosen depth.`}],OQ=[{value:`keep`,label:`keep the original file name`},{value:`title`,label:`use the item title as file name`},{value:`dated`,label:`photo style: 2024/07/20240714_183012.jpg`},{value:`custom`,label:`custom template…`}],kQ=e=>({kind:e,a:``,b:``,recursive:!1,storeFrom:``,storeFolder:``,storeName:`keep`,storeMode:`move`,storeConflict:`rename`,dlKind:`auto`,dlDepth:`2`,dlTags:``,keepLast:!0,notePath:``,noteTitle:``,filePath:``,fileBackend:`home`,fileInsert:``,notifyReply:!1}),AQ={id:null,description:``,events:[`document.inserted`],schema:``,cascade:!1,approval:!1,conditions:[],actions:[kQ(`link`)]},jQ=e=>e.split(`|`).map(e=>e.trim()).filter(Boolean);function MQ(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`rule-${Math.random().toString(36).slice(2,7)}`}var NQ=e=>e.split(`,`).map(e=>e.trim()).filter(Boolean),PQ=[{id:`store`,title:`Keep files in a real folder`,icon:_e,tone:`text-sky-600 dark:text-sky-400 bg-sky-500/10`,blurb:`Uploads land in the managed blob store. Pick a folder in Canvas and a folder on a storage backend — every file filed there is moved across, sub-folders kept.`,build:({backend:e})=>({...AQ,description:`Keep files in a real folder`,schema:`file`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:``}],actions:[{...kQ(`store`),a:e,recursive:!0}]})},{id:`photos`,title:`Sort photos by date`,icon:rn,tone:`text-emerald-600 dark:text-emerald-400 bg-emerald-500/10`,blurb:`Images filed into a folder are stored as Photos / 2024 / 07 / 20240714_183012.jpg — by the time the photo was taken (EXIF), not uploaded.`,build:({backend:e})=>({...AQ,description:`Sort photos by date`,schema:`file`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:``},{field:`mime`,value:`image/*`}],actions:[{...kQ(`store`),a:e,storeFolder:`Photos`,storeName:`dated`}]})},{id:`mirror`,title:`Mirror a storage folder`,icon:Dn,tone:`text-violet-600 dark:text-violet-400 bg-violet-500/10`,blurb:`Everything that appears under a folder of a storage backend shows up 1:1 in the Directory tree.`,build:()=>({...AQ,description:`Mirror a storage folder`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:`backends:/workspace/home/`}],actions:[{...kQ(`link`),a:`dir:/`,recursive:!0}]})},{id:`mail`,title:`File mail from a sender`,icon:vt,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`,blurb:`Emails from a person or domain are filed into a folder and you get a notification.`,build:()=>({...AQ,description:`Mail from …`,schema:`email`,conditions:[{field:`from`,value:``}],actions:[{...kQ(`link`),a:`/work/urgent`},{...kQ(`notify`),a:`New mail from {{doc.data.from}}: {{doc.data.subject}}`}]})},{id:`download`,title:`Download what links point at`,icon:wn,tone:`text-rose-600 dark:text-rose-400 bg-rose-500/10`,blurb:`Bookmarks filed into a folder are fetched for real — images, videos (yt-dlp), arXiv papers, a page or a whole website — saved to a folder and filed next to the link.`,build:({backend:e})=>({...AQ,description:`Download what links point at`,schema:`tab`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:``}],actions:[{...kQ(`download`),a:e,storeFolder:`Downloads`,recursive:!0}]})},{id:`agent`,title:`Ask an agent`,icon:st,tone:`text-indigo-600 dark:text-indigo-400 bg-indigo-500/10`,blurb:`Hand new items to an agent with a prompt; save its reply as a note or get it as a message.`,build:()=>({...AQ,description:`Summarize new items`,actions:[{...kQ(`agent`),b:`Summarize this in three bullet points.
|
|
68
|
+
|
|
69
|
+
Title: {{doc.data.title}}
|
|
70
|
+
{{doc.data.body}}`,notifyReply:!0}]})},{id:`blank`,title:`Start from scratch`,icon:Ln,tone:`text-muted-foreground bg-muted`,blurb:`An empty rule: choose what it reacts to, add conditions and actions.`,build:()=>({...AQ})}];function FQ(e){let t={event:e.events.length===1?e.events[0]:e.events};e.schema&&(t.schema=e.schema);let n={},r={};for(let t of e.conditions){let e=t.field.endsWith(`Regex`),i=e?t.value.trim()?[t.value]:[]:jQ(t.value);if(e&&i.length)try{new RegExp(t.value,`i`)}catch{throw Error(`Invalid regular expression for ${SQ.find(e=>e.key===t.field)?.label}: ${t.value}`)}if(i.length){if(t.field===`urlHost`||t.field===`urlContains`||t.field===`urlRegex`){let e=t.field===`urlHost`?`host`:t.field===`urlRegex`?`regex`:`contains`,n=r[e],a=[...Array.isArray(n)?n:n==null?[]:[n],...i];r[e]=a.length===1?a[0]:a}else(n[t.field.replace(/Regex$/,``)]||=[]).push(...e?i.map(e=>({regex:e})):i)}}for(let[e,r]of Object.entries(n))r?.length&&(t[e]=r.length===1?r[0]:r);Object.keys(r).length&&(t.url=r);let i=e=>{let t={};return e.notePath.trim()&&(t.note={path:e.notePath.trim(),...e.noteTitle.trim()?{title:e.noteTitle.trim()}:{}}),e.filePath.trim()&&(t.file={path:e.filePath.trim(),...e.fileBackend===`data`?{backend:`data`}:{},...e.fileInsert.trim()?{insert:e.fileInsert.trim()}:{}}),e.notifyReply&&(t.notify=!0),Object.keys(t).length?t:null},a=[];for(let t of e.actions){let e=t.a.trim(),n=t.b.trim(),r=t.recursive?{recursive:!0}:{};if(t.kind===`link`&&e&&a.push({action:`link`,paths:NQ(e),...r,...n?{tags:NQ(n)}:{}}),t.kind===`unlink`&&e&&a.push({action:`unlink`,paths:NQ(e),...r}),t.kind===`tag`&&e&&a.push({action:`tag`,tags:NQ(e)}),t.kind===`store`&&e){let i=t.storeFolder.trim().replace(/^\/+|\/+$/g,``),o=t.storeName===`title`?TQ:t.storeName===`dated`?EQ:t.storeName===`custom`?n:``;a.push({action:`store`,to:e,...t.storeFrom?{from:t.storeFrom}:{},mode:t.storeMode,...i?{folder:i}:{},...r,...o?{key:o}:{},onConflict:t.storeConflict})}if(t.kind===`download`){let i=t.storeFolder.trim().replace(/^\/+|\/+$/g,``),o=Number(t.dlDepth);a.push({action:`download`,to:e||`workspace:home`,...i?{folder:i}:{},...r,...t.dlKind===`auto`?{}:{kind:t.dlKind},...n?{insert:NQ(n)}:{},...t.dlTags.trim()?{tags:NQ(t.dlTags)}:{},...t.dlKind===`website`&&Number.isFinite(o)&&o>0&&o!==2?{depth:o}:{}})}if(t.kind===`unstore`&&e&&a.push({action:`unstore`,from:e,...n?{ifOn:n}:{},...t.keepLast?{}:{keepLast:!1}}),t.kind===`notify`&&e&&a.push({action:`notify`,message:e}),t.kind===`delete`&&a.push({action:`delete`}),t.kind===`destroy`&&a.push({action:`destroy`}),t.kind===`agent`&&e&&n){let r=i(t);a.push({action:`agent`,slug:e,prompt:n,...r?{output:r}:{}})}if(t.kind===`script`&&e){let n=i(t);a.push({action:`script`,path:e,...n?{output:n}:{}})}}return{id:e.id||MQ(e.description),enabled:!0,...e.description?{description:e.description}:{},...e.cascade?{cascade:!0}:{},...e.approval?{approval:!0}:{},...e.editable?.length?{editable:e.editable}:{},...e.ttl===void 0?{}:{ttl:e.ttl},when:t,then:a}}function IQ(e){let{event:t,schema:n,from:r,to:i,subject:a,path:o,pathExact:s,mime:c,url:l,attachment:u,...d}=e.when;if(Object.keys(d).length>0)return null;let f=Array.isArray(t)?t:[t];if(!f.length||!f.every(e=>typeof e==`string`&&xQ.some(t=>t.value===e))||n!==void 0&&typeof n!=`string`)return null;let p=[],m=(e,t)=>{let n=Array.isArray(t)?t:[t];if(e.endsWith(`Regex`)){if(!n.every(e=>typeof e==`string`))return!1;for(let t of n)p.push({field:e,value:t})}else if([`from`,`to`,`subject`].includes(e))for(let t of n)if(typeof t==`string`)p.push({field:e,value:t});else if(t&&typeof t==`object`&&Object.keys(t).length===1&&typeof t.regex==`string`)p.push({field:`${e}Regex`,value:t.regex});else return!1;else{if(!n.every(e=>typeof e==`string`))return!1;p.push({field:e,value:n.join(` | `)})}return!0};if(o!==void 0&&!m(`path`,o)||s!==void 0&&!m(`pathExact`,s)||c!==void 0&&!m(`mime`,c)||r!==void 0&&!m(`from`,r)||i!==void 0&&!m(`to`,i)||a!==void 0&&!m(`subject`,a)||u!==void 0&&!m(`attachment`,u))return null;if(l!==void 0){if(typeof l==`string`)p.push({field:`urlContains`,value:l});else if(l&&typeof l==`object`){let e=l;if(Object.keys(e).filter(e=>e!==`host`&&e!==`contains`&&e!==`regex`).length||e.host!==void 0&&!m(`urlHost`,e.host)||e.contains!==void 0&&!m(`urlContains`,e.contains)||e.regex!==void 0&&!m(`urlRegex`,e.regex))return null}else return null}let h=e=>{let t=e.output&&typeof e.output==`object`?e.output:{};if(Object.keys(t).filter(e=>e!==`note`&&e!==`file`&&e!==`notify`).length)return null;let n=t.note&&typeof t.note==`object`?t.note:{},r=t.file&&typeof t.file==`object`?t.file:{};return Object.keys(r).filter(e=>e!==`path`&&e!==`backend`&&e!==`insert`).length?null:{notePath:typeof n.path==`string`?n.path:``,noteTitle:typeof n.title==`string`?n.title:``,filePath:typeof r.path==`string`?r.path:``,fileBackend:r.backend===`data`?`data`:`home`,fileInsert:typeof r.insert==`string`?r.insert:``,notifyReply:t.notify===!0}},g=[];for(let t of e.then||[]){if(t.approval!==void 0)return null;if(t.action===`link`&&Array.isArray(t.paths))g.push({...kQ(`link`),a:t.paths.join(`, `),b:Array.isArray(t.tags)?t.tags.join(`, `):``,recursive:t.recursive===!0});else if(t.action===`unlink`&&Array.isArray(t.paths))g.push({...kQ(`unlink`),a:t.paths.join(`, `),recursive:t.recursive===!0});else if(t.action===`tag`&&Array.isArray(t.tags))g.push({...kQ(`tag`),a:t.tags.join(`, `)});else if(t.action===`notify`&&typeof t.message==`string`)g.push({...kQ(`notify`),a:t.message});else if(t.action===`store`&&typeof t.to==`string`){if(t.folder!==void 0&&typeof t.folder!=`string`||t.key!==void 0&&typeof t.key!=`string`)return null;let e=typeof t.key==`string`?t.key:``;g.push({...kQ(`store`),a:t.to,b:e===TQ||e===EQ?``:e,storeFolder:typeof t.folder==`string`?t.folder:``,recursive:t.recursive===!0,storeName:e?e===TQ?`title`:e===EQ?`dated`:`custom`:`keep`,storeFrom:typeof t.from==`string`?t.from:Array.isArray(t.from)?String(t.from[0]??``):``,storeMode:t.mode===`copy`?`copy`:`move`,storeConflict:t.onConflict===`error`||t.onConflict===`overwrite`?t.onConflict:`rename`})}else if(t.action===`download`){let e=new Set([`action`,`to`,`folder`,`recursive`,`kind`,`insert`,`tags`,`depth`]);if(Object.keys(t).some(t=>!e.has(t)))return null;let n=typeof t.kind==`string`?t.kind:`auto`;if(!DQ.some(e=>e.value===n))return null;let r=Array.isArray(t.insert)?t.insert:typeof t.insert==`string`?[t.insert]:[];if(!r.every(e=>typeof e==`string`))return null;g.push({...kQ(`download`),a:typeof t.to==`string`?t.to:`workspace:home`,b:r.join(`, `),storeFolder:typeof t.folder==`string`?t.folder:``,recursive:t.recursive===!0,dlKind:n,dlDepth:typeof t.depth==`number`?String(t.depth):`2`,dlTags:Array.isArray(t.tags)?t.tags.join(`, `):``})}else if(t.action===`unstore`&&(typeof t.from==`string`||Array.isArray(t.from))){let e=e=>Array.isArray(e)?String(e[0]??``):typeof e==`string`?e:``;g.push({...kQ(`unstore`),a:e(t.from),b:e(t.ifOn),keepLast:t.keepLast!==!1})}else if(t.action===`delete`)g.push(kQ(`delete`));else if(t.action===`destroy`)g.push(kQ(`destroy`));else if(t.action===`agent`&&typeof t.slug==`string`&&typeof t.prompt==`string`){let e=h(t);if(!e)return null;g.push({...kQ(`agent`),a:t.slug,b:t.prompt,...e})}else if(t.action===`script`&&typeof t.path==`string`){let e=h(t);if(!e)return null;g.push({...kQ(`script`),a:t.path,...e})}else return null}return{id:e.id,description:e.description||``,events:f,schema:typeof n==`string`?n:``,cascade:e.cascade===!0,approval:e.approval===!0,...e.editable?.length?{editable:e.editable}:{},...e.ttl===void 0?{}:{ttl:e.ttl},conditions:p,actions:g.length?g:[kQ(`link`)]}}var LQ=(e,t)=>t.find(t=>t.value===e)?.label?.replace(/\s\(\d+\)$/,``)||(e?String(e).replace(/^data\/schema\//,``):`any item`);function RQ(e,t=bQ){let n=e.when,r=UZ(e).map(e=>xQ.find(t=>t.value===e)?.label||e).join(` or `),i=[`When ${LQ(n.schema,t)} ${r}`],a=e=>Array.isArray(e)?e.join(` or `):typeof e==`object`&&e?JSON.stringify(e):String(e),o={path:`under`,pathExact:`directly in`,mime:`type`,from:`from`,to:`to`,subject:`subject`,url:`url`,attachment:`attachment`};for(let e of[`path`,`pathExact`,`mime`,`from`,`to`,`subject`,`url`,`attachment`])n[e]!==void 0&&i.push(`${o[e]} ${a(n[e])}`);return i.join(` · `)}function zQ(e){let t=e.output||{},n=t.note||{},r=t.file||{};return[n.path?`reply → note ${n.path}`:``,r.path?`reply → file ${r.backend===`data`?`data:`:`home/`}${r.path}${r.insert?` (indexed at ${r.insert})`:``}`:``,t.notify?`reply → notify`:``].filter(Boolean).join(`, `)}function BQ(e){if(e.action===`link`)return`file into ${e.paths?.join(`, `)}${e.recursive===!0?` (sub-folders kept)`:``}`;if(e.action===`unlink`)return`remove from ${e.paths?.join(`, `)}${e.recursive===!0?` (sub-folders kept)`:``}`;if(e.action===`tag`)return`tag ${e.tags?.join(`, `)}`;if(e.action===`store`){let t=typeof e.folder==`string`&&e.folder?`/${e.folder}`:``,n=e.key===TQ?`, named by title`:e.key===EQ?`, by date`:typeof e.key==`string`&&e.key?`, as ${e.key}`:``;return`${e.mode===`copy`?`copy`:`move`} the file to ${e.to}${t}${e.recursive===!0?` (sub-folders kept)`:``}${n}`}if(e.action===`download`){let t=DQ.find(t=>t.value===(e.kind||`auto`)),n=typeof e.folder==`string`&&e.folder?`/${e.folder}`:``,r=Array.isArray(e.insert)&&e.insert.length?`, filed at ${e.insert.join(`, `)}`:`, filed next to the link`;return`download ${t?.value===`auto`?`the link (auto-detected)`:t?.label||e.kind} to ${e.to||`workspace:home`}${n}${e.recursive===!0?` (sub-folders kept)`:``}${r}`}if(e.action===`unstore`)return`delete the file from ${Array.isArray(e.from)?e.from.join(`, `):e.from}${e.ifOn?` once it is on ${Array.isArray(e.ifOn)?e.ifOn.join(`, `):e.ifOn}`:``}`;if(e.action===`notify`)return`notify me`;if(e.action===`delete`)return`delete from Canvas (keeps stored files/mail)`;if(e.action===`destroy`)return`⚠ delete everywhere (index + storage)`;if(e.action===`agent`){let t=zQ(e);return`ask agent "${e.slug}"${t?` (${t})`:``}`}if(e.action===`script`){let t=zQ(e);return`run ${e.path}${t?` (${t})`:``}`}return e.action}function VQ(e){return(e.then||[]).map(BQ).join(` · `)||`(no actions)`}function HQ(e){return WZ(e).length>0&&(e.then||[]).length>0&&(e.then||[]).every(e=>e.action===`link`||e.action===`unlink`||e.action===`store`||e.action===`unstore`)}function UQ(e){let t={};for(let n of e){if(n.handlerType!==`rule`)continue;let e=t[n.handler]||={count:0,errors:0,last:n};e.count++,n.status===`error`&&e.errors++,n.ts>e.last.ts&&(e.last=n)}return t}function WQ(e){let t=Date.now()-new Date(e).getTime();if(!Number.isFinite(t)||t<0)return``;let n=Math.floor(t/6e4);if(n<1)return`just now`;if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function GQ(e){return e.some(e=>e.address===`workspace:home`)?`workspace:home`:e.find(e=>e.address!==`workspace:data`)?.address||e[0]?.address||``}function KQ(e){if(e.kind===`download`){let t=e.path?` filed under ${e.path.replace(/^(ctx|dir):/,``)}`:``;return{...AQ,description:`Download links${t}`,schema:`tab`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:e.path||``}],actions:[{...kQ(`download`),a:e.storeTo||``,storeFolder:e.storeFolder||`Downloads`,recursive:!0}]}}if(e.kind===`store`){let t=e.path?` filed under ${e.path.replace(/^(ctx|dir):/,``)}`:``;return{...AQ,description:e.storeTo?`Keep files${t} on ${e.storeTo}${e.storeFolder?`/${e.storeFolder}`:``}`:`Keep files${t} in a real folder`,schema:`file`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:e.path||``}],actions:[{...kQ(`store`),a:e.storeTo||``,storeFolder:e.storeFolder||``,recursive:!0}]}}return{...AQ,description:`Mirror ${e.path} into ${e.target}`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:e.path||``}],actions:[{...kQ(`link`),a:e.target||`dir:/`,recursive:!0}]}}var qQ=`h-10 w-full rounded-md border bg-background px-3 text-sm outline-none focus:ring-2 focus:ring-ring disabled:opacity-50`,JQ=`h-10 text-sm`;function YQ({label:e,hint:t,children:n,className:r}){return(0,Z.jsxs)(`label`,{className:K(`flex min-w-0 flex-col gap-1.5`,r),children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:e}),n,t&&(0,Z.jsx)(`span`,{className:`text-xs leading-relaxed text-muted-foreground`,children:t})]})}function XQ({checked:e,onChange:t,label:n,hint:r,disabled:i}){return(0,Z.jsxs)(`button`,{type:`button`,role:`switch`,"aria-checked":e,disabled:i,onClick:()=>t(!e),className:K(`flex w-full items-start gap-3 rounded-lg border p-3 text-left transition-colors hover:bg-accent/40 disabled:cursor-not-allowed disabled:opacity-50`,e&&`border-primary/40 bg-primary/5`),children:[(0,Z.jsx)(`span`,{className:K(`mt-0.5 inline-flex h-5 w-9 shrink-0 items-center rounded-full p-0.5 transition-colors`,e?`bg-primary`:`bg-muted-foreground/30`),children:(0,Z.jsx)(`span`,{className:K(`h-4 w-4 rounded-full bg-background shadow transition-transform`,e&&`translate-x-4`)})}),(0,Z.jsxs)(`span`,{className:`min-w-0`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:n}),r&&(0,Z.jsx)(`span`,{className:`block text-xs leading-relaxed text-muted-foreground`,children:r})]})]})}function ZQ({value:e,options:t,onChange:n}){return(0,Z.jsx)(`div`,{className:`inline-flex h-10 rounded-md border bg-background p-1`,children:t.map(t=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>n(t.value),className:K(`rounded px-3 text-sm transition-colors`,e===t.value?`bg-primary text-primary-foreground shadow-sm`:`text-muted-foreground hover:text-foreground`),children:t.label},t.value))})}function QQ({active:e,onClick:t,children:n,title:r}){return(0,Z.jsx)(`button`,{type:`button`,title:r,onClick:t,"aria-pressed":e,className:K(`h-9 rounded-full border px-3.5 text-sm transition-colors`,e?`border-primary bg-primary/10 font-medium text-foreground`:`text-muted-foreground hover:bg-accent hover:text-foreground`),children:n})}function $Q({step:e,title:t,hint:n}){return(0,Z.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,Z.jsx)(`span`,{className:`mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-primary/10 text-sm font-semibold text-primary`,children:e}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`text-base font-semibold leading-7`,children:t}),n&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:n})]})]})}function e$({icon:e,tone:t,size:n=`md`}){return(0,Z.jsx)(`span`,{className:K(`inline-flex shrink-0 items-center justify-center rounded-xl`,n===`lg`?`h-12 w-12`:`h-10 w-10`,t),children:(0,Z.jsx)(e,{className:n===`lg`?`h-6 w-6`:`h-5 w-5`})})}function t$({workspaceId:e,onOpenJson:t,onShowRuns:n,backfillLimit:r,prefill:i,onPrefillConsumed:a}){let{showToast:o}=oo(),[s,c]=(0,X.useState)([]),[l,u]=(0,X.useState)({}),d=e=>{nQ(e,{limit:500}).then(e=>u(UQ(e))).catch(()=>u({}))},[f,p]=(0,X.useState)(!0),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)([]),[S,C]=(0,X.useState)([]),w=(0,X.useRef)(null),[T,E]=(0,X.useState)(e);e!==T&&(E(e),p(!0)),(0,X.useEffect)(()=>{ZZ(e).then(e=>c(e)).finally(()=>p(!1)),d(e)},[e]);let[D,O]=(0,X.useState)(null);i!==D&&(O(i),i&&(h(KQ(i)),_(!1))),(0,X.useEffect)(()=>{i&&a?.()},[i,a]),(0,X.useEffect)(()=>{gQ(e).then(e=>x(e.map(e=>e.path))).catch(()=>x([]))},[e]),(0,X.useEffect)(()=>{va(e).then(e=>{let t=e.filter(e=>e.kind===`storage`&&e.config?.readOnly!==!0);C(t);let n=GQ(t);n&&h(e=>e&&e.actions.some(e=>(e.kind===`store`||e.kind===`download`)&&!e.a)?{...e,actions:e.actions.map(e=>(e.kind===`store`||e.kind===`download`)&&!e.a?{...e,a:n}:e)}:e)}).catch(()=>C([]))},[e]);let[k,A]=(0,X.useState)(bQ);(0,X.useEffect)(()=>{fQ(e).then(e=>{e.schemas?.length&&A([{value:``,label:`any item`},...e.schemas.map(e=>({value:e.id,label:`${e.name} (${e.count})`}))])}).catch(()=>{})},[e]);let j=async(t,n)=>{y(!0);try{return await QZ(e,t),c(t),o({title:n,description:`rules.json updated (committed to workspace git)`}),!0}catch(e){return o({title:`Error`,description:e instanceof Error?e.message:`Failed to save rules`,variant:`destructive`}),!1}finally{y(!1)}},M=async()=>{if(!m)return;let e;try{e=FQ(m)}catch(e){o({title:`Invalid condition`,description:e instanceof Error?e.message:`Invalid regular expression`,variant:`destructive`});return}if(!e.then.length){o({title:`Add an action`,description:`Pick at least one "then" action and fill in its fields.`,variant:`destructive`});return}let t=m.id?s.map(t=>t.id===m.id?{...e,enabled:t.enabled!==!1}:t):[...s,e];await j(t,m.id?`Rule updated`:`Rule created`)&&h(null)},N=e=>j(s.map(t=>t.id===e?{...t,enabled:t.enabled===!1}:t),`Rule toggled`),P=e=>{confirm(`Delete rule "${e}"?`)&&j(s.filter(t=>t.id!==e),`Rule deleted`)},[ee,F]=(0,X.useState)(null),I=async t=>{F(t);try{let n=await lQ(e,{ruleId:t,dryRun:!0,limit:r}),i=n.results.filter(e=>e.matched).length;if(!i){o({title:`Apply to existing items`,description:`No matches among ${n.processed} existing documents (conditions evaluate against each document's current tree placements). Raise the batch size in the toolbar to cover more.`});return}if(!confirm(`Rule "${t}" matches ${i} of ${n.processed} existing documents. Run its actions on them now?`))return;let a=await lQ(e,{ruleId:t,limit:r});o({title:`Done`,description:`${a.matched} documents processed, ${a.failed} failed. Details in the Runs tab`,...a.failed?{variant:`destructive`}:{}})}catch(e){o({title:`Backfill failed`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{F(null),d(e)}},te=(e,t)=>h(n=>n&&{...n,[e]:t}),ne=e=>{h(e.build({backend:GQ(S)})),_(!1),requestAnimationFrame(()=>w.current?.scrollIntoView({behavior:`smooth`,block:`start`}))},re=e=>{let n=IQ(e);n?(h(n),_(!1),requestAnimationFrame(()=>w.current?.scrollIntoView({behavior:`smooth`,block:`start`}))):t?.()},[R,ie]=(0,X.useState)(null),ae=(e,t)=>t.treeType===`context`?e:t.treeName===`directory`?`dir:${e}`:`${t.treeName}:${e}`,oe=(e,t)=>{if(!R||!m||!e.length){ie(null);return}if(R.target===`storeFolder`){let t=GZ(e[0]);te(`actions`,m.actions.map((e,n)=>n===R.index?{...e,storeFolder:t?.rel||``,...t?.backend&&S.some(e=>e.address===t.backend)?{a:t.backend}:{}}:e))}else if(R.target===`condition`){let n=e.map(e=>ae(e,t));te(`conditions`,m.conditions.map((e,t)=>t===R.index?{...e,value:n.join(` | `)}:e))}else{let n=e.map(e=>ae(e,t));te(`actions`,m.actions.map((e,t)=>t===R.index?e.kind===`download`?{...e,b:n.join(`, `)}:{...e,a:n.join(`, `)}:e))}ie(null)},z=(e,t,n=`Browse…`)=>(0,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`outline`,className:`h-10 shrink-0 px-3`,title:n,onClick:()=>ie({target:e,index:t}),children:[(0,Z.jsx)(L,{className:`h-4 w-4 sm:mr-1.5`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:`Browse`})]}),se=!!m?.conditions.some(e=>(e.field===`path`||e.field===`pathExact`)&&e.value.trim()),ce=e=>`${e.address}${e.address===`workspace:data`?` — managed blob store (default)`:e.address===`workspace:home`?` — workspace home folder`:e.driver?` — ${e.driver}`:``}`,B=(e,t,n,r=`workspace:home`)=>S.length?(0,Z.jsxs)(`select`,{className:qQ,value:e,onChange:e=>t(e.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:n}),S.map(e=>(0,Z.jsx)(`option`,{value:e.address,children:ce(e)},e.address)),e&&!S.some(t=>t.address===e)&&(0,Z.jsx)(`option`,{value:e,children:e})]}):(0,Z.jsx)(q,{className:K(JQ,`font-mono`),placeholder:r,value:e,onChange:e=>t(e.target.value)}),V=s.filter(HQ),le=s.filter(e=>!HQ(e)),ue=({rule:e})=>{let t=e.enabled!==!1,r=IQ(e)!==null,i=l[e.id],a=wQ(e.then?.[0]?.action||`link`),o=WZ(e);return(0,Z.jsxs)(`div`,{className:K(`flex flex-col gap-3 rounded-xl border bg-card p-4 transition-opacity sm:flex-row sm:items-start sm:gap-4`,!t&&`opacity-60`),children:[(0,Z.jsx)(e$,{icon:a.icon,tone:a.tone}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,Z.jsx)(`h3`,{className:`text-base font-semibold leading-6`,children:e.description||e.id}),e.approval===!0&&(0,Z.jsx)(`span`,{className:`rounded-full bg-warning/15 px-2 py-0.5 text-xs font-medium text-warning`,children:`needs approval`}),e.cascade===!0&&(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:`incl. automation-created`}),!r&&(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,title:`This rule uses matchers the builder cannot show; edit it as JSON.`,children:`JSON only`})]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:RQ(e,k)}),(0,Z.jsxs)(`p`,{className:`flex items-start gap-1.5 text-sm`,children:[(0,Z.jsx)(_t,{className:`mt-1 h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{children:VQ(e)})]}),o.length>0&&(0,Z.jsx)(`p`,{className:`truncate font-mono text-xs text-muted-foreground`,title:o.join(` | `),children:o.join(` | `)}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:i?(0,Z.jsxs)(`button`,{type:`button`,className:K(`underline-offset-2 hover:underline`,i.last.status===`error`&&`text-destructive`,!n&&`cursor-default hover:no-underline`),title:n?`Show this rule's run log`:i.last.error||i.last.skipReason||``,onClick:()=>n?.(e.id),children:[`ran `,i.count,`×`,i.errors?` (${i.errors} failed)`:``,` · last `,i.last.status,` `,WQ(i.last.ts)]}):`not run yet`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 self-end sm:self-start`,children:[(0,Z.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":t,disabled:v,title:t?`Enabled — click to pause`:`Paused — click to enable`,onClick:()=>N(e.id),className:K(`mr-1 inline-flex h-6 w-11 items-center rounded-full p-0.5 transition-colors`,t?`bg-primary`:`bg-muted-foreground/30`),children:(0,Z.jsx)(`span`,{className:K(`h-5 w-5 rounded-full bg-background shadow transition-transform`,t&&`translate-x-5`)})}),(0,Z.jsxs)(J,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5`,title:`Apply this rule to existing items (dry-run first)`,disabled:ee!==null,onClick:()=>I(e.id),children:[ee===e.id?(0,Z.jsx)(Wn,{className:`h-4 w-4 animate-spin`}):(0,Z.jsx)(an,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{className:`ml-1.5 hidden md:inline`,children:`Apply`})]}),(0,Z.jsxs)(J,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5`,title:r?`Edit rule`:`Edit as JSON`,onClick:()=>re(e),children:[r?(0,Z.jsx)(ye,{className:`h-4 w-4`}):(0,Z.jsx)(On,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{className:`ml-1.5 hidden md:inline`,children:`Edit`})]}),(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5 text-destructive hover:text-destructive`,title:`Delete rule`,onClick:()=>P(e.id),children:(0,Z.jsx)(lt,{className:`h-4 w-4`})})]})]})},de=(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsx)(`h3`,{className:`text-base font-semibold`,children:`What should happen automatically?`}),g&&(0,Z.jsxs)(J,{size:`sm`,variant:`ghost`,onClick:()=>_(!1),children:[(0,Z.jsx)(je,{className:`mr-1 h-4 w-4`}),` Close`]})]}),(0,Z.jsx)(`div`,{className:`grid min-w-0 grid-cols-[repeat(auto-fill,minmax(min(100%,17rem),1fr))] gap-3`,children:PQ.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>ne(e),className:`flex min-w-0 items-start gap-3 rounded-xl border bg-card p-4 text-left transition-colors hover:border-primary/50 hover:bg-accent/40`,children:[(0,Z.jsx)(e$,{icon:e.icon,tone:e.tone,size:`lg`}),(0,Z.jsxs)(`span`,{className:`min-w-0`,children:[(0,Z.jsx)(`span`,{className:`block text-base font-semibold leading-6`,children:e.title}),(0,Z.jsx)(`span`,{className:`mt-1 block break-words text-sm leading-relaxed text-muted-foreground`,children:e.blurb})]})]},e.id))})]});return(0,Z.jsxs)(`div`,{className:`space-y-5`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:`Rules`}),(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Rules run automatically as items arrive or get filed — no code needed. Stored in`,` `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`rules.json`}),` in the workspace git.`]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[t&&(0,Z.jsxs)(J,{variant:`ghost`,onClick:t,title:`Edit rules.json directly`,children:[(0,Z.jsx)(On,{className:`mr-1.5 h-4 w-4`}),` JSON`]}),(0,Z.jsxs)(J,{onClick:()=>{h(null),_(!0)},disabled:g,children:[(0,Z.jsx)(nn,{className:`mr-1.5 h-4 w-4`}),` New rule`]})]})]}),g&&!m&&de,m&&(0,Z.jsxs)(`div`,{ref:w,className:`scroll-mt-4 space-y-6 rounded-xl border bg-card p-4 sm:p-6`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Z.jsx)(`h3`,{className:`text-lg font-semibold`,children:m.id?`Edit rule`:`New rule`}),(0,Z.jsxs)(J,{variant:`ghost`,size:`sm`,onClick:()=>h(null),children:[(0,Z.jsx)(je,{className:`mr-1 h-4 w-4`}),` Cancel`]})]}),(0,Z.jsx)(YQ,{label:`Name`,hint:`Shown in the list and the run log.`,children:(0,Z.jsx)(q,{className:`h-11 text-base`,placeholder:`Keep UI designs in Projects/Canvas/UI`,value:m.description,onChange:e=>te(`description`,e.target.value)})}),(0,Z.jsxs)(`section`,{className:`space-y-4`,children:[(0,Z.jsx)($Q,{step:1,title:`When…`,hint:`What the rule reacts to. All conditions must match; repeat a condition for either/or.`}),(0,Z.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-[minmax(0,220px)_1fr]`,children:[(0,Z.jsx)(YQ,{label:`Item`,children:(0,Z.jsxs)(`select`,{className:qQ,value:m.schema,onChange:e=>te(`schema`,e.target.value),children:[k.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value)),m.schema&&!k.some(e=>e.value===m.schema)&&(0,Z.jsx)(`option`,{value:m.schema,children:m.schema.replace(/^data\/schema\//,``)})]})}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,Z.jsxs)(`span`,{className:`text-sm font-medium`,children:[`Event `,(0,Z.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(any of)`})]}),(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:xQ.map(e=>{let t=m.events.includes(e.value);return(0,Z.jsx)(QQ,{active:t,title:e.hint,onClick:()=>{let n=t?m.events.filter(t=>t!==e.value):[...m.events,e.value];n.length&&te(`events`,n)},children:e.label},e.value)})})]})]}),m.conditions.length>0&&(0,Z.jsx)(`div`,{className:`space-y-2`,children:m.conditions.map((e,t)=>{let n=SQ.find(t=>t.key===e.field);return(0,Z.jsxs)(`div`,{className:`grid grid-cols-[2.25rem_1fr_auto] items-center gap-2 sm:grid-cols-[2.25rem_minmax(0,240px)_1fr_auto]`,children:[(0,Z.jsx)(`span`,{className:`text-xs font-medium uppercase tracking-wide text-muted-foreground`,title:`Same condition again = either may match (OR); different conditions must all match (AND)`,children:m.conditions.slice(0,t).some(t=>t.field.replace(/Regex$/,``)===e.field.replace(/Regex$/,``))?`or`:`and`}),(0,Z.jsx)(`select`,{className:qQ,value:e.field,onChange:e=>te(`conditions`,m.conditions.map((n,r)=>r===t?{...n,field:e.target.value}:n)),children:SQ.map(e=>(0,Z.jsx)(`option`,{value:e.key,children:e.label},e.key))}),(0,Z.jsxs)(`div`,{className:`order-4 col-span-3 flex gap-2 sm:order-3 sm:col-span-1`,children:[(0,Z.jsx)(q,{className:K(JQ,`font-mono`),placeholder:n?.hint,value:e.value,onChange:e=>te(`conditions`,m.conditions.map((n,r)=>r===t?{...n,value:e.target.value}:n))}),(e.field===`path`||e.field===`pathExact`)&&z(`condition`,t,`Browse the workspace trees`)]}),(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,className:`order-3 h-10 w-10 p-0 text-muted-foreground sm:order-4`,title:`Remove condition`,onClick:()=>te(`conditions`,m.conditions.filter((e,n)=>n!==t)),children:(0,Z.jsx)(je,{className:`h-4 w-4`})})]},t)})}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,onClick:()=>te(`conditions`,[...m.conditions,{field:m.schema===`email`?`from`:`path`,value:``}]),children:[(0,Z.jsx)(nn,{className:`mr-1 h-4 w-4`}),` Add condition`]}),(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[`Contains matches literal text. Regex is case-insensitive: enter the pattern without /…/ delimiters; | stays part of the expression. For other filters, separate alternatives with `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`|`}),`, e.g. `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`image/* | video/*`}),`.`]})]})]}),(0,Z.jsxs)(`section`,{className:`space-y-4`,children:[(0,Z.jsx)($Q,{step:2,title:`Then…`,hint:`Actions run in order. The item keeps its id, tags and folders unless an action says otherwise.`}),m.actions.map((t,n)=>{let r=e=>te(`actions`,m.actions.map((t,r)=>r===n?{...t,...e}:t)),i=wQ(t.kind),a=n=>(0,Z.jsxs)(`div`,{className:`space-y-3 rounded-lg border border-dashed p-3`,children:[(0,Z.jsxs)(`p`,{className:`text-sm font-medium`,children:[`What to do with the `,n]}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsx)(YQ,{label:`Save as a note at`,hint:`Context path by default, dir:/path for the directory tree.`,children:(0,Z.jsx)(uC,{inputClassName:JQ,placeholder:`/notes/summaries (optional)`,value:t.notePath,onChange:e=>r({notePath:e}),fixedWorkspaceName:e,pickerTitle:`Save note under…`,onPickTarget:(e,t)=>r({notePath:t.treeType===`directory`?`dir:${e}`:e})})}),t.notePath.trim()&&(0,Z.jsx)(YQ,{label:`Note title`,children:(0,Z.jsx)(q,{className:JQ,placeholder:`Summary: {{doc.data.subject}}`,value:t.noteTitle,onChange:e=>r({noteTitle:e.target.value})})}),(0,Z.jsx)(YQ,{label:`Save as a file at`,hint:`Relative path under the workspace home folder or in the data blob store.`,children:(0,Z.jsx)(q,{className:K(JQ,`font-mono`),placeholder:`logs/agent.log (optional)`,value:t.filePath,onChange:e=>r({filePath:e.target.value})})}),t.filePath.trim()&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(YQ,{label:`File lives in`,children:(0,Z.jsxs)(`select`,{className:qQ,value:t.fileBackend,onChange:e=>r({fileBackend:e.target.value}),children:[(0,Z.jsx)(`option`,{value:`home`,children:`the workspace home folder`}),(0,Z.jsx)(`option`,{value:`data`,children:`the data blob store`})]})}),(0,Z.jsx)(YQ,{label:`Also file the saved file under`,hint:`Index it as a document at this tree path.`,children:(0,Z.jsx)(uC,{inputClassName:JQ,placeholder:`/path (optional)`,value:t.fileInsert,onChange:e=>r({fileInsert:e}),fixedWorkspaceName:e,tabs:[`context`],pickerTitle:`File under…`,onPickTarget:e=>r({fileInsert:e})})})]})]}),(0,Z.jsx)(XQ,{checked:t.notifyReply,onChange:e=>r({notifyReply:e}),label:`Send it to me as a message`})]}),o=t.storeFolder.trim().replace(/^\/+|\/+$/g,``),s=t.kind===`store`&&t.a?`${t.a}/${[o,t.recursive&&se?`<sub-folders>`:``,t.storeName===`keep`?`<original name>`:t.storeName===`title`?`<title>.<ext>`:t.storeName===`dated`?EQ:t.b||`<name>`].filter(Boolean).join(`/`)}`:``;return(0,Z.jsxs)(`div`,{className:`space-y-4 rounded-xl border bg-background p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Z.jsx)(e$,{icon:i.icon,tone:i.tone}),(0,Z.jsx)(`select`,{className:K(qQ,`flex-1 font-medium`),value:t.kind,onChange:e=>r(kQ(e.target.value)),children:CQ.map(e=>(0,Z.jsx)(`option`,{value:e.key,children:e.label},e.key))}),(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,className:`h-10 w-10 shrink-0 p-0 text-muted-foreground`,title:`Remove action`,disabled:m.actions.length===1,onClick:()=>te(`actions`,m.actions.filter((e,t)=>t!==n)),children:(0,Z.jsx)(je,{className:`h-4 w-4`})})]}),(t.kind===`link`||t.kind===`unlink`)&&(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(YQ,{label:t.kind===`link`?`Folder(s)`:`Remove from folder(s)`,hint:`Context-tree path by default; dir:/path for the directory tree. Comma-separate several.`,children:(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{className:K(JQ,`font-mono`),placeholder:t.kind===`link`?`/work/urgent or dir:/projects/x`:`/inbox or dir:/staging`,value:t.a,onChange:e=>r({a:e.target.value})}),z(`action`,n)]})}),t.kind===`link`&&(0,Z.jsx)(YQ,{label:`Tags`,hint:`Optional, comma-separated.`,children:(0,Z.jsx)(q,{className:K(JQ,`font-mono`),placeholder:`custom/design, ui`,value:t.b,onChange:e=>r({b:e.target.value})})}),(0,Z.jsx)(XQ,{checked:t.recursive,onChange:e=>r({recursive:e}),label:`Keep sub-folders`,hint:se?`The part of the item's path below the "is under the folder" prefix is appended to the target: …/foo/a/b → target/a/b.`:`Needs an "is under the folder" condition to know where sub-folders start.`,disabled:!se})]}),t.kind===`tag`&&(0,Z.jsx)(YQ,{label:`Tags`,hint:`Comma-separated.`,children:(0,Z.jsx)(q,{className:K(JQ,`font-mono`),placeholder:`urgent, follow-up`,value:t.a,onChange:e=>r({a:e.target.value})})}),t.kind===`store`&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,Z.jsx)(YQ,{label:`Storage backend`,hint:`Where the file's bytes should live. Only writable backends are listed.`,children:B(t.a,e=>r({a:e}),`pick a backend…`)}),(0,Z.jsx)(YQ,{label:`Folder on that backend`,hint:`Relative to the backend root. Leave empty for the root.`,children:(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{className:K(JQ,`font-mono`),placeholder:`Projects/Canvas/UI`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),z(`storeFolder`,n,`Browse storage backends`)]})}),(0,Z.jsx)(YQ,{label:`File name`,children:(0,Z.jsx)(`select`,{className:qQ,value:t.storeName,onChange:e=>r({storeName:e.target.value}),children:OQ.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))})}),(0,Z.jsx)(YQ,{label:`Move or copy`,hint:t.storeMode===`move`?`The blob-store copy is removed once the file is safely there.`:`The file stays in the blob store as well.`,children:(0,Z.jsx)(ZQ,{value:t.storeMode,onChange:e=>r({storeMode:e}),options:[{value:`move`,label:`Move`},{value:`copy`,label:`Copy`}]})}),t.storeName===`custom`&&(0,Z.jsx)(YQ,{className:`sm:col-span-2`,label:`Name template`,hint:`Tokens: {{YYYY}} {{MM}} {{DD}} {{HH}} {{mm}} {{ss}} (photo capture time when present), {{ext}} {{basename}} {{filename}} {{title}} {{id}}, plus {{doc.…}} fields. Slashes create sub-folders.`,children:(0,Z.jsx)(q,{className:K(JQ,`font-mono`),placeholder:`{{YYYY}}-{{MM}}-{{DD}} {{title}}{{ext}}`,value:t.b,onChange:e=>r({b:e.target.value})})})]}),(0,Z.jsx)(XQ,{checked:t.recursive,onChange:e=>r({recursive:e}),label:`Keep sub-folders`,hint:se?`Filed under …/UI/mobile → stored under Folder/mobile. Needs the "is under the folder" condition above.`:`Add an "is under the folder" condition to mirror sub-folders.`,disabled:!se}),s&&(0,Z.jsxs)(`p`,{className:`flex flex-wrap items-center gap-2 rounded-lg bg-muted/60 px-3 py-2 text-sm`,children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Files land in`}),(0,Z.jsx)(`span`,{className:`break-all font-mono`,children:s})]}),(0,Z.jsxs)(`details`,{className:`group rounded-lg border`,children:[(0,Z.jsxs)(`summary`,{className:`flex cursor-pointer select-none items-center gap-2 px-3 py-2 text-sm font-medium`,children:[(0,Z.jsx)(Ne,{className:`h-4 w-4 transition-transform group-open:rotate-180`}),` More options`]}),(0,Z.jsxs)(`div`,{className:`grid gap-4 border-t p-3 sm:grid-cols-2`,children:[(0,Z.jsx)(YQ,{label:`Only when the file is currently on`,hint:`Guard that keeps the rule idempotent. Default: any backend other than the target.`,children:B(t.storeFrom,e=>r({storeFrom:e}),`any other backend`,`workspace:data (optional)`)}),(0,Z.jsx)(YQ,{label:`If the name is already taken`,children:(0,Z.jsxs)(`select`,{className:qQ,value:t.storeConflict,onChange:e=>r({storeConflict:e.target.value}),children:[(0,Z.jsx)(`option`,{value:`rename`,children:`add -1, -2, … to the name`}),(0,Z.jsx)(`option`,{value:`error`,children:`skip the file`}),(0,Z.jsx)(`option`,{value:`overwrite`,children:`overwrite the existing file`})]})})]})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Moves the stored bytes only — the item keeps its id, tags and every folder it is filed in.`})]}),t.kind===`download`&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,Z.jsx)(YQ,{label:`Download`,hint:DQ.find(e=>e.value===t.dlKind)?.hint,children:(0,Z.jsx)(`select`,{className:qQ,value:t.dlKind,onChange:e=>r({dlKind:e.target.value}),children:DQ.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))})}),t.dlKind===`website`?(0,Z.jsx)(YQ,{label:`Mirror depth`,hint:`How many link hops to follow on the same site (1–5).`,children:(0,Z.jsx)(q,{type:`number`,min:1,max:5,className:K(JQ,`sm:max-w-32`),value:t.dlDepth,onChange:e=>r({dlDepth:e.target.value})})}):(0,Z.jsx)(`div`,{className:`hidden sm:block`}),(0,Z.jsx)(YQ,{label:`Storage backend`,hint:`Where the downloaded file's bytes should live.`,children:B(t.a,e=>r({a:e}),`workspace:home (default)`)}),(0,Z.jsx)(YQ,{label:`Folder on that backend`,hint:`Relative to the backend root.`,children:(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{className:K(JQ,`font-mono`),placeholder:`Downloads`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),z(`storeFolder`,n,`Browse storage backends`)]})}),(0,Z.jsx)(YQ,{label:`File the download under`,hint:`Leave empty to file it in the same folder(s) as the link. Comma-separate several.`,children:(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{className:K(JQ,`font-mono`),placeholder:`same folders as the link`,value:t.b,onChange:e=>r({b:e.target.value})}),z(`action`,n)]})}),(0,Z.jsx)(YQ,{label:`Tags for the download`,hint:`Optional, comma-separated.`,children:(0,Z.jsx)(q,{className:K(JQ,`font-mono`),placeholder:`downloaded, custom/paper`,value:t.dlTags,onChange:e=>r({dlTags:e.target.value})})})]}),(0,Z.jsx)(XQ,{checked:t.recursive,onChange:e=>r({recursive:e}),label:`Keep sub-folders`,hint:se?`A link filed under …/folder/a/b is downloaded into Folder/a/b.`:`Add an "is under the folder" condition to mirror sub-folders.`,disabled:!se}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`The link stays as it is; the download becomes a new file item next to it. Each link is downloaded once per rule. Videos need `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`yt-dlp`}),`, pages and websites `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`wget`}),` on the server.`]})]}),t.kind===`unstore`&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,Z.jsx)(YQ,{label:`Delete the file from`,children:B(t.a,e=>r({a:e}),`pick a backend…`,`workspace:data`)}),(0,Z.jsx)(YQ,{label:`…but only once it is also on`,hint:`Safety: the copy is dropped only after another backend holds the file.`,children:B(t.b,e=>r({b:e}),`anywhere else`,`workspace:home (optional)`)})]}),(0,Z.jsx)(XQ,{checked:t.keepLast,onChange:e=>r({keepLast:e}),label:`Never delete the last copy`,hint:`Off means the rule may delete the only remaining copy of a file. Leave it on unless you mean exactly that.`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Deletes the stored bytes on that backend only — copies elsewhere and the item itself are kept.`})]}),t.kind===`notify`&&(0,Z.jsx)(YQ,{label:`Message`,hint:`Templates work: {{doc.data.subject}}, {{doc.data.from}}, {{doc.data.url}}, {{doc.data.title}}…`,children:(0,Z.jsx)(q,{className:JQ,placeholder:`New mail from {{doc.data.from}}: {{doc.data.subject}}`,value:t.a,onChange:e=>r({a:e.target.value})})}),t.kind===`delete`&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Removes the item from the Canvas index. Files, blobs and mail on storage backends stay untouched.`}),t.kind===`destroy`&&(0,Z.jsx)(`p`,{className:`rounded-lg border border-destructive/40 bg-destructive/5 p-3 text-sm text-destructive`,children:`⚠ Irreversible: deletes the stored bytes too (blobs, workspace files, mail on the server), then removes the item from the index.`}),t.kind===`agent`&&(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(YQ,{label:`Agent`,hint:`The agent's slug.`,children:(0,Z.jsx)(q,{className:K(JQ,`font-mono sm:max-w-xs`),placeholder:`assistant`,value:t.a,onChange:e=>r({a:e.target.value})})}),(0,Z.jsx)(YQ,{label:`Prompt`,hint:`Templates over the full document: {{doc.data.subject}}, {{doc.data.body}} / {{doc.data.bodyHtml}} (emails), {{doc.data.url}}… Objects are inserted as JSON.`,children:(0,Z.jsx)(`textarea`,{className:`min-h-28 w-full rounded-md border bg-background p-3 text-sm outline-none focus:ring-2 focus:ring-ring`,placeholder:`Dear agent, you will get an email subject and body. Summarize it in plain markdown.
|
|
71
|
+
|
|
72
|
+
Subject: {{doc.data.subject}}
|
|
73
|
+
Body: {{doc.data.body}}`,value:t.b,onChange:e=>r({b:e.target.value})})}),a(`reply`)]}),t.kind===`script`&&(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(YQ,{label:`Script`,hint:`From the Scripts section of this workspace.`,children:b.length?(0,Z.jsxs)(`select`,{className:K(qQ,`font-mono sm:max-w-md`),value:t.a,onChange:e=>r({a:e.target.value}),children:[(0,Z.jsx)(`option`,{value:``,children:`pick a script…`}),b.map(e=>(0,Z.jsx)(`option`,{value:`scripts/${e}`,children:e},e))]}):(0,Z.jsx)(q,{className:K(JQ,`font-mono sm:max-w-md`),placeholder:`scripts/my-script.sh`,value:t.a,onChange:e=>r({a:e.target.value})})}),a(`output`)]})]},n)}),(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,onClick:()=>te(`actions`,[...m.actions,kQ(`tag`)]),children:[(0,Z.jsx)(nn,{className:`mr-1 h-4 w-4`}),` Add another action`]})]}),(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsx)($Q,{step:3,title:`Options`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsx)(XQ,{checked:m.approval,onChange:e=>te(`approval`,e),label:`Ask me before running`,hint:`Actions are held in the Pending queue for review — approve (optionally amended) or decline — instead of running automatically.`}),(0,Z.jsx)(XQ,{checked:m.cascade,onChange:e=>te(`cascade`,e),label:`Also react to items created by automation`,hint:`Off by default so rules, hooks and agents cannot trigger each other in a loop. A server-side depth limit still stops runaway chains.`})]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2 border-t pt-4`,children:[(0,Z.jsxs)(J,{className:`h-10 px-5`,onClick:M,disabled:v,children:[v?(0,Z.jsx)(Wn,{className:`mr-1.5 h-4 w-4 animate-spin`}):(0,Z.jsx)(Re,{className:`mr-1.5 h-4 w-4`}),` `,m.id?`Save changes`:`Create rule`]}),(0,Z.jsx)(J,{className:`h-10`,variant:`outline`,onClick:()=>h(null),children:`Cancel`})]})]}),R&&(0,Z.jsx)(sp,{onClose:()=>ie(null),children:(0,Z.jsx)(ap,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,fixedWorkspaceName:e,multiple:R.target!==`storeFolder`,tabs:R.target===`condition`?[`context`,`directory`,`backends`]:R.target===`storeFolder`?[`backends`]:[`context`,`directory`],title:R.target===`condition`?`Match items under…`:R.target===`storeFolder`?`Store files under…`:`File into…`,confirmLabel:R.target===`storeFolder`?`Use folder`:`Use path`,onConfirm:oe,onClose:()=>ie(null)})}),f?(0,Z.jsx)(`p`,{className:`rounded-xl border p-6 text-center text-sm text-muted-foreground`,children:`Loading…`}):s.length===0?!g&&!m&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`rounded-xl border border-dashed p-6 text-center`,children:[(0,Z.jsx)(`p`,{className:`text-base font-medium`,children:`No rules yet`}),(0,Z.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:`Pick a starting point below, or right-click a folder in the tree and choose “Create rule…”.`})]}),de]}):(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[V.length>0&&(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsxs)(`h3`,{className:`flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-muted-foreground`,children:[(0,Z.jsx)(Dn,{className:`h-4 w-4`}),` Folder & storage rules`,(0,Z.jsx)(`span`,{className:`font-normal normal-case tracking-normal`,children:`· right-click a folder in the tree to add one`})]}),(0,Z.jsx)(`div`,{className:`space-y-3`,children:V.map(e=>(0,Z.jsx)(ue,{rule:e},e.id))})]}),le.length>0&&(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[V.length>0&&(0,Z.jsxs)(`h3`,{className:`flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-muted-foreground`,children:[(0,Z.jsx)(Ln,{className:`h-4 w-4`}),` Other rules`]}),(0,Z.jsx)(`div`,{className:`space-y-3`,children:le.map(e=>(0,Z.jsx)(ue,{rule:e},e.id))})]})]})]})}var n$=[`pending`,`approved`,`declined`,`failed`,`expired`,`all`],r$={pending:`text-warning dark:text-warning`,approved:`text-success dark:text-success`,declined:`text-muted-foreground`,failed:`text-destructive`,expired:`text-muted-foreground line-through`};function i$(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return`now`;if(n<60)return`${n}m`;let r=Math.floor(n/60);return r<24?`${r}h`:`${Math.floor(r/24)}d`}function a$(e,t){return t.split(`.`).reduce((e,t)=>typeof e==`object`&&e?e[t]:void 0,e)}function o$(e){let t=e.split(`.`);return t.slice(Math.max(t.length-2,2)).join(`.`)}var s$=/(body|content|message|text|prompt)$/i;function c$({action:e,amend:t,onAmend:n}){return e.editable?.length?(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.editable.map(r=>{let i=a$(e,r),a=typeof i==`string`,o=r in t?t[r]:i,s=a?String(o??``):JSON.stringify(o,null,2),c=a&&(s$.test(r)||s.length>80);return(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[(0,Z.jsxs)(`span`,{className:`font-medium text-muted-foreground`,children:[o$(r),(0,Z.jsx)(`span`,{className:`ml-1.5 font-mono text-[10px] opacity-60`,children:r}),r in t&&(0,Z.jsx)(`span`,{className:`ml-1.5 text-warning dark:text-warning`,children:`edited`})]}),c?(0,Z.jsx)(`textarea`,{className:`mt-1 w-full rounded-md border bg-background px-2 py-1.5 font-mono text-xs outline-none focus:ring-2 focus:ring-ring min-h-[100px]`,value:s,onChange:e=>n(r,e.target.value)}):(0,Z.jsx)(`input`,{className:`mt-1 w-full h-8 rounded-md border bg-background px-2 font-mono text-xs outline-none focus:ring-2 focus:ring-ring`,value:s,onChange:e=>{if(a){n(r,e.target.value);return}try{n(r,JSON.parse(e.target.value))}catch{n(r,e.target.value)}}})]},r)})}):null}function l$({workspaceId:e,onPendingCount:t}){let{showToast:n}=oo(),r=kb(),[i,a]=(0,X.useState)(`pending`),[o,s]=(0,X.useState)([]),[c,l]=(0,X.useState)(!0),[u,d]=(0,X.useState)(new Set),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)({}),[g,_]=(0,X.useState)(!1),v=(0,X.useCallback)(()=>$Z(e,{status:i===`all`?void 0:i,limit:200}).then(e=>{s(e),d(t=>new Set(e.filter(e=>e.status===`pending`&&t.has(e.actionId)).map(e=>e.actionId))),t?.(i===`pending`?e.length:e.filter(e=>e.status===`pending`).length)}).catch(()=>{n({title:`Error`,description:`Failed to load pending actions`,variant:`destructive`})}).finally(()=>l(!1)),[e,i]),y=(0,X.useCallback)(async()=>{l(!0),await v()},[v]),[b,x]=(0,X.useState)(`${e}|${i}`),S=`${e}|${i}`;S!==b&&(x(S),l(!0)),(0,X.useEffect)(()=>{v()},[v]),Gy(r,`workspace:${e}`,(0,X.useMemo)(()=>{let e=()=>{y()};return{"action.proposed":e,"action.approved":e,"action.declined":e,"action.failed":e}},[y]));let C=o.filter(e=>e.status===`pending`),w=C.length>0&&C.every(e=>u.has(e.actionId)),T=()=>{d(w?new Set:new Set(C.map(e=>e.actionId)))},E=e=>{d(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},D=(e,t,n)=>{h(r=>({...r,[e]:{...r[e],[t]:n}}))},O=async(t,r)=>{if(!(!t.length&&!r.length)){_(!0);try{let i=await eQ(e,{approve:t.map(e=>{let t=m[e];return t&&Object.keys(t).length?{actionId:e,amend:t}:e}),decline:r}),a=i.results.filter(e=>e.status===`error`||e.status===`failed`);a.length?n({title:`${a.length} of ${i.decided} failed`,description:a.map(e=>`${e.actionId}: ${e.error??`execution failed`}`).join(`; `),variant:`destructive`}):n({title:t.length&&r.length?`Decisions applied`:t.length?`Approved ${t.length}`:`Declined ${r.length}`,description:t.length?`Approved actions executed with their original provenance.`:void 0}),h(e=>{let n={...e};for(let e of[...t,...r])delete n[e];return n}),d(new Set),f&&[...t,...r].includes(f)&&p(null),await y()}catch(e){n({title:`Decision failed`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{_(!1)}}};return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 flex-wrap`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`select`,{className:`h-8 rounded-md border bg-background px-2 text-xs outline-none focus:ring-2 focus:ring-ring`,value:i,onChange:e=>a(e.target.value),children:n$.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))}),(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,onClick:()=>void y(),title:`Reload`,children:(0,Z.jsx)(M,{className:`h-4 w-4`})})]}),u.size>0&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[u.size,` selected`]}),(0,Z.jsxs)(J,{size:`sm`,disabled:g,onClick:()=>void O([...u],[]),children:[(0,Z.jsx)(ur,{className:`mr-1 h-3.5 w-3.5`}),` Approve`]}),(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,disabled:g,onClick:()=>void O([],[...u]),children:[(0,Z.jsx)(je,{className:`mr-1 h-3.5 w-3.5`}),` Decline`]})]})]}),(0,Z.jsx)(`div`,{className:`border rounded-lg overflow-auto max-h-[560px]`,children:c?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground p-3`,children:`Loading...`}):o.length===0?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground p-3`,children:i===`pending`?`Nothing waiting for review. Rules or hooks with approval enabled queue their actions here.`:`No ${i===`all`?``:i+` `}actions recorded.`}):(0,Z.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,Z.jsx)(`thead`,{className:`text-xs text-muted-foreground border-b sticky top-0 bg-background`,children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{className:`px-3 py-2 w-8`,children:C.length>0&&(0,Z.jsx)(`input`,{type:`checkbox`,checked:w,onChange:T,title:`Select all pending`})}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Proposed action`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Handler`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Age`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Status`}),(0,Z.jsx)(`th`,{className:`px-2 py-2 w-40`})]})}),(0,Z.jsx)(`tbody`,{children:o.map(e=>{let t=e.status===`pending`||e.status===`failed`,n=f===e.actionId,r=e.envelope?.payload?.document;return(0,Z.jsxs)(X.Fragment,{children:[(0,Z.jsxs)(`tr`,{className:`border-b last:border-0 align-top hover:bg-muted/40 cursor-pointer`,onClick:()=>p(n?null:e.actionId),children:[(0,Z.jsx)(`td`,{className:`px-3 py-2`,onClick:e=>e.stopPropagation(),children:e.status===`pending`&&(0,Z.jsx)(`input`,{type:`checkbox`,checked:u.has(e.actionId),onChange:()=>E(e.actionId)})}),(0,Z.jsxs)(`td`,{className:`px-3 py-2`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 font-medium`,children:[n?(0,Z.jsx)(Ne,{className:`h-3 w-3 shrink-0`}):(0,Z.jsx)(B,{className:`h-3 w-3 shrink-0`}),e.title,e.editable?.length>0&&(0,Z.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide rounded bg-muted-foreground/15 px-1 py-0.5 text-muted-foreground shrink-0`,children:`editable`})]}),e.summary&&(0,Z.jsx)(`span`,{className:`block text-xs text-muted-foreground pl-4`,children:e.summary})]}),(0,Z.jsxs)(`td`,{className:`px-3 py-2 font-mono text-xs whitespace-nowrap`,children:[(0,Z.jsxs)(`span`,{className:`text-muted-foreground`,children:[e.handlerType,`:`]}),e.handler,e.event&&(0,Z.jsxs)(`span`,{className:`block text-muted-foreground`,children:[e.event,r?.id?` · doc ${r.id}`:``]})]}),(0,Z.jsx)(`td`,{className:`px-3 py-2 text-xs whitespace-nowrap`,title:e.ts,children:i$(e.ts)}),(0,Z.jsxs)(`td`,{className:`px-3 py-2 text-xs`,children:[(0,Z.jsx)(`span`,{className:r$[e.status],children:e.status}),e.amended&&(0,Z.jsx)(`span`,{className:`block text-muted-foreground`,children:`amended`}),e.decidedBy&&(0,Z.jsx)(`span`,{className:`block text-muted-foreground truncate max-w-[120px]`,title:e.decidedBy,children:e.decidedBy})]}),(0,Z.jsx)(`td`,{className:`px-2 py-2 whitespace-nowrap text-right`,onClick:e=>e.stopPropagation(),children:t&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(J,{size:`sm`,className:`h-7 px-2`,disabled:g,title:e.status===`failed`?`Retry (re-approve)`:`Approve and execute`,onClick:()=>void O([e.actionId],[]),children:(0,Z.jsx)(ur,{className:`h-3.5 w-3.5`})}),e.status===`pending`&&(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,className:`h-7 px-2 text-muted-foreground`,disabled:g,title:`Decline`,onClick:()=>void O([],[e.actionId]),children:(0,Z.jsx)(je,{className:`h-3.5 w-3.5`})})]})})]}),n&&(0,Z.jsxs)(`tr`,{className:`border-b last:border-0 bg-muted/20`,children:[(0,Z.jsx)(`td`,{className:`px-3 py-3`}),(0,Z.jsxs)(`td`,{className:`px-3 py-3 space-y-3`,colSpan:5,children:[t&&e.editable?.length>0&&(0,Z.jsx)(c$,{action:e,amend:m[e.actionId]??{},onAmend:(t,n)=>D(e.actionId,t,n)}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Actions on approve`}),(0,Z.jsx)(`pre`,{className:`mt-1 rounded border bg-background p-2 font-mono text-xs overflow-auto max-h-56`,children:JSON.stringify(e.actions,null,2)})]}),e.result&&e.result.length>0&&(0,Z.jsx)(`div`,{className:`text-xs font-mono`,children:e.result.map((e,t)=>(0,Z.jsxs)(`span`,{className:`mr-2 ${e.status===`error`?`text-destructive`:`text-muted-foreground`}`,children:[e.action,`:`,e.status,e.error?` (${e.error})`:``]},t))}),(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground font-mono`,children:[e.actionId,` · origin `,e.provenance?.origin,e.provenance?.causedBy?` · causedBy ${e.provenance.causedBy}`:``,e.expiresAt?` · expires ${new Date(e.expiresAt).toLocaleString()}`:``]})]})]})]},e.actionId)})})]})})]})}var u$=`#!/usr/bin/env bash
|
|
74
|
+
# Called from a hook via: spawn('bash', [script, ...args])
|
|
75
|
+
set -euo pipefail
|
|
76
|
+
`;function d$({workspaceId:e,prefillRule:t,onPrefillConsumed:n,initialSection:r,initialRunsHandler:i,initialRunId:a}){let{showToast:o}=oo(),[s,c]=(0,X.useState)(r??`rules`),[l,u]=(0,X.useState)(t);t!==l&&(u(t),t&&c(`rules`));let[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)([]),[h,g]=(0,X.useState)(!0),[_,v]=(0,X.useState)(null),[y,b]=(0,X.useState)(``),[S,C]=(0,X.useState)(!1),[w,T]=(0,X.useState)(!1),[E,D]=(0,X.useState)(!1),[O,k]=(0,X.useState)(null),[j,N]=(0,X.useState)(`document.inserted`),[P,ee]=(0,X.useState)(``),[F,I]=(0,X.useState)([]),[te,ne]=(0,X.useState)(!1),[L,re]=(0,X.useState)([]),[R,ie]=(0,X.useState)(!1),[ae,oe]=(0,X.useState)(i||null),[z,se]=(0,X.useState)(a?{runId:a,run:null}:null),ce=e=>{se(t=>t?.runId===e?null:{runId:e,run:null})};(0,X.useEffect)(()=>{if(!z||z.run||z.error)return;let t=!1;return tQ(e,z.runId).then(e=>{t||se(t=>t?.runId===e.runId?{runId:e.runId,run:e}:t)}).catch(e=>{t||se(t=>t?.runId===z.runId?{...t,error:e instanceof Error?e.message:`Failed to load run`}:t)}),()=>{t=!0}},[e,z]);let[B,V]=(0,X.useState)(null),[le,ue]=(0,X.useState)(!1),[de,fe]=(0,X.useState)(0),[pe,me]=(0,X.useState)(null),[H,he]=(0,X.useState)(()=>oQ()),[ge,_e]=(0,X.useState)(()=>String(oQ())),ve=()=>{let e=sQ(aQ(ge));he(e),_e(String(e))};(0,X.useEffect)(()=>{let t=!1;return $Z(e,{status:`pending`,limit:500}).then(e=>{t||fe(e.length)}).catch(()=>{}),()=>{t=!0}},[e]),gf(()=>ue(!1),le);let ye=async t=>{if(confirm(`Replay ${t.handlerType} "${t.handler}" for ${t.event} (docs ${(t.docIds||[]).join(`, `)})?`)){V(t.runId);try{let n=await dQ(e,t.runId);o({title:`Replayed`,description:`${t.handler} → ${n.status}`}),await Se()}catch(e){o({title:`Replay failed`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{V(null)}}},be=s===`scripts`?{list:gQ,get:_Q,save:vQ,del:yQ}:{list:jZ,get:MZ,save:NZ,del:PZ},xe=s===`hooks`||s===`scripts`,Se=async()=>{if(s!==`rules`&&s!==`pending`){if(s===`runs`){try{g(!0),re(await nQ(e,{limit:100,failed:R||void 0,handler:ae||void 0}))}catch{o({title:`Error`,description:`Failed to load hook runs`,variant:`destructive`})}finally{g(!1)}return}try{g(!0),m(await be.list(e))}catch{o({title:`Error`,description:`Failed to load ${s}`,variant:`destructive`})}finally{g(!1)}}};(0,X.useEffect)(()=>{Se()},[e,s,R,ae]);let Ce=e=>{e!==s&&(S&&!confirm(`Discard unsaved changes?`)||(c(e),v(null),b(``),C(!1),D(!1)))},G=async t=>{if(!(S&&!confirm(`Discard unsaved changes?`)))try{v(t),b(await be.get(e,t)),C(!1)}catch{o({title:`Error`,description:`Failed to open ${t}`,variant:`destructive`})}},we=async()=>{if(_)try{T(!0),await be.save(e,_,y),C(!1),o({title:`Saved`,description:`${_} saved`}),await Se()}catch{o({title:`Error`,description:`Failed to save ${_}`,variant:`destructive`})}finally{T(!1)}},Te=async t=>{let n=RZ(t);try{let r=await VZ(e,t,!n);_===t&&v(r),await Se(),o({title:n?`Disabled`:`Enabled`,description:r})}catch{o({title:`Error`,description:`Failed to toggle ${t}`,variant:`destructive`})}},Ee=async t=>{let n=cQ(t);if(!n||!RZ(t)&&!confirm(`${t} is disabled. Run it anyway?`))return;let r=n.startsWith(`document.`);if(!(r&&!confirm(`Run ${t} against up to ${H} existing documents (event ${n})?`))){me(t);try{if(r){let r=await lQ(e,{hookFile:t,event:n,limit:H});o({title:`Run finished`,description:`${r.processed} documents processed, ${r.failed} failed. Details in the Runs tab`,...r.failed?{variant:`destructive`}:{}})}else{let r=await uQ(e,{hookFile:t,event:n});o({title:r.status===`error`?`Run failed`:`Run finished`,description:r.status===`error`?`${t}: ${r.error||`see the Runs tab`}`:`${t} → ${r.status}${r.durationMs==null?``:` in ${r.durationMs}ms`}`,...r.status===`error`?{variant:`destructive`}:{}})}}catch(e){o({title:`Run failed`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{me(null)}}},De=async t=>{if(confirm(`Delete ${s===`hooks`?`hook`:`script`} ${t}?`))try{await be.del(e,t),_===t&&(v(null),b(``),C(!1)),await Se(),o({title:`Deleted`,description:`${t} deleted`})}catch{o({title:`Error`,description:`Failed to delete ${t}`,variant:`destructive`})}},ke=async()=>{if(!O)try{k(await fQ(e))}catch{o({title:`Error`,description:`Failed to load hook metadata`,variant:`destructive`})}},Ae=async()=>{D(!E),s===`hooks`&&await ke()},Me=async()=>{f(!d),await ke()},Pe=async()=>{let t=P.trim().replace(/^\/+/,``);if(!t){o({title:`Error`,description:`Give the script a name (e.g. on-image.sh)`,variant:`destructive`});return}try{ne(!0),await vQ(e,t,u$),D(!1),ee(``),await Se(),await G(t)}catch{o({title:`Error`,description:`Failed to create script`,variant:`destructive`})}finally{ne(!1)}},Fe=e=>{I(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},Ie=async()=>{if(!P.trim()){o({title:`Error`,description:`Give the hook a name`,variant:`destructive`});return}try{ne(!0);let{path:t}=await pQ(e,{event:j,name:P.trim(),actions:F});D(!1),ee(``),I([]),await Se(),await G(t),o({title:`Created`,description:`${t}. Edit the TODOs, then enable it`})}catch{o({title:`Error`,description:`Failed to create hook`,variant:`destructive`})}finally{ne(!1)}},Le=s===`hooks`?HZ(p):{scripts:p},ze=`${Yr}/workspaces/${e}/git`;return(0,Z.jsxs)(`div`,{className:`@container space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 @3xl:flex-row @3xl:items-start @3xl:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 @3xl:min-w-[18rem] @3xl:flex-1`,children:[(0,Z.jsx)(`h3`,{className:`text-lg font-medium`,children:`Automation`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Rules are simple click-to-build automations (Outlook-style). Hooks are their programmable big brother; scripts are the shell helpers hooks spawn. Everything commits to the workspace git repo.`})]}),(0,Z.jsx)(`div`,{className:`flex min-w-0 flex-col gap-2 @3xl:max-w-[60%] @3xl:flex-row @3xl:items-center`,children:(0,Z.jsx)(`div`,{className:`w-full min-w-0 @3xl:w-auto`,children:(0,Z.jsx)(nm,{className:`border-b-0`,active:s,onChange:Ce,tabs:[{id:`pending`,label:de>0?`Pending (${de})`:`Pending`,icon:A},{id:`rules`,label:`Rules`,icon:Ln},{id:`hooks`,label:`Hooks`,icon:Je},{id:`scripts`,label:`Scripts`,icon:Oe},{id:`runs`,label:`Runs`,icon:U}]})})})]}),(s===`runs`||xe)&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[s===`runs`&&(0,Z.jsxs)(Z.Fragment,{children:[ae&&(0,Z.jsxs)(`button`,{type:`button`,className:`inline-flex items-center gap-1 rounded-full border bg-muted/50 px-2.5 py-1 font-mono text-xs hover:bg-muted`,title:`Showing runs of this rule / hook only — click to clear`,onClick:()=>oe(null),children:[ae,` `,(0,Z.jsx)(je,{className:`h-3 w-3`})]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:R,onChange:e=>ie(e.target.checked)}),`failed only`]}),(0,Z.jsxs)(J,{size:`sm`,variant:`ghost`,onClick:Se,title:`Reload`,children:[(0,Z.jsx)(M,{className:`mr-1.5 h-4 w-4`}),` Reload`]})]}),xe&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(J,{size:`sm`,variant:`ghost`,onClick:Se,title:`Reload`,children:[(0,Z.jsx)(M,{className:`mr-1.5 h-4 w-4`}),` Reload`]}),(0,Z.jsxs)(J,{size:`sm`,variant:`ghost`,onClick:Me,title:`Hook context API & classifier reference`,children:[(0,Z.jsx)(rt,{className:`mr-1.5 h-4 w-4`}),` Reference`]}),(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,onClick:Ae,children:[(0,Z.jsx)(nn,{className:`mr-2 h-4 w-4`}),` `,s===`hooks`?`New Hook`:`New Script`]})]})]}),s===`pending`&&(0,Z.jsx)(l$,{workspaceId:e,onPendingCount:fe}),s===`rules`&&(0,Z.jsx)(t$,{workspaceId:e,backfillLimit:H,onShowRuns:e=>{oe(e),Ce(`runs`)},prefill:t,onPrefillConsumed:n,onOpenJson:async()=>{try{await MZ(e,`rules.json`)}catch{await NZ(e,`rules.json`,JSON.stringify({$schema:`canvas.hook-rules/v1`,rules:[]},null,2)+`
|
|
77
|
+
`).catch(()=>{})}c(`hooks`),G(`rules.json`)}}),s===`runs`&&(0,Z.jsx)(`div`,{className:`border rounded-lg overflow-auto max-h-[560px]`,children:h?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground p-3`,children:`Loading...`}):L.length===0?(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground p-3`,children:[`No runs recorded yet`,R?` (failed only)`:``,`. Runs appear here every time a rule or hook executes.`]}):(0,Z.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,Z.jsx)(`thead`,{className:`text-xs text-muted-foreground border-b sticky top-0 bg-background`,children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Time`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Handler`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Event`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Docs`}),(0,Z.jsx)(`th`,{className:`text-right font-medium px-3 py-2`,children:`ms`}),(0,Z.jsx)(`th`,{className:`text-left font-medium px-3 py-2`,children:`Status`}),(0,Z.jsx)(`th`,{className:`px-2 py-2`})]})}),(0,Z.jsx)(`tbody`,{children:L.map(e=>(0,Z.jsxs)(X.Fragment,{children:[(0,Z.jsxs)(`tr`,{className:`border-b last:border-0 align-top hover:bg-muted/40`,children:[(0,Z.jsx)(`td`,{className:`px-3 py-1.5 whitespace-nowrap text-xs text-muted-foreground`,title:e.ts,children:new Date(e.ts).toLocaleString()}),(0,Z.jsxs)(`td`,{className:`px-3 py-1.5 font-mono text-xs`,children:[(0,Z.jsxs)(`span`,{className:`text-muted-foreground`,children:[e.handlerType,`:`]}),e.handler,e.origin!==`user`&&(0,Z.jsxs)(`span`,{className:`ml-1.5 text-[10px] uppercase tracking-wide rounded bg-muted-foreground/15 px-1 py-0.5 text-muted-foreground`,children:[e.origin,e.depth?` d${e.depth}`:``]})]}),(0,Z.jsxs)(`td`,{className:`px-3 py-1.5 font-mono text-xs`,children:[e.event,e.batch?` (batch)`:``]}),(0,Z.jsx)(`td`,{className:`px-3 py-1.5 font-mono text-xs`,children:(e.docIds||[]).join(`, `)}),(0,Z.jsx)(`td`,{className:`px-3 py-1.5 text-right font-mono text-xs`,children:e.durationMs}),(0,Z.jsxs)(`td`,{className:`px-3 py-1.5 text-xs`,children:[(0,Z.jsx)(`span`,{className:e.status===`error`?`text-destructive font-medium`:e.status===`skipped`?`text-muted-foreground`:`text-success dark:text-success`,children:e.status}),e.error&&(0,Z.jsx)(`span`,{className:`block text-destructive/80 font-mono break-all`,children:e.error}),e.skipReason&&(0,Z.jsx)(`span`,{className:`block text-muted-foreground`,children:e.skipReason}),e.actions&&e.actions.length>0&&(0,Z.jsx)(`span`,{className:`block text-muted-foreground font-mono`,children:e.actions.map(e=>`${e.action}:${e.status}`).join(` `)}),e.actions?.filter(e=>e.error).map((e,t)=>(0,Z.jsxs)(`span`,{className:`block break-all font-mono ${e.status===`error`?`text-destructive/80`:`text-muted-foreground`}`,children:[e.action,`: `,e.error]},t))]}),(0,Z.jsxs)(`td`,{className:`px-2 py-1.5 whitespace-nowrap`,children:[(0,Z.jsxs)(J,{size:`sm`,variant:`ghost`,className:`h-6 px-1.5 touch-target`,title:e.traceLines?`Execution log (${e.traceLines} lines)`:`Execution log`,onClick:()=>ce(e.runId),children:[(0,Z.jsx)(sr,{className:`h-3.5 w-3.5`}),(0,Z.jsx)(Ne,{className:`ml-0.5 h-3 w-3 transition-transform ${z?.runId===e.runId?`rotate-180`:``}`})]}),e.handlerType!==`dispatch`&&(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,className:`h-6 w-6 p-0 touch-target`,title:`Replay this run (reloads the document, re-runs the handler)`,disabled:B!==null,onClick:()=>ye(e),children:(0,Z.jsx)($n,{className:`h-3 w-3 ${B===e.runId?`animate-spin`:``}`})})]})]}),z?.runId===e.runId&&(0,Z.jsx)(`tr`,{className:`border-b last:border-0 bg-muted/30`,children:(0,Z.jsx)(`td`,{colSpan:7,className:`px-3 py-2`,children:(0,Z.jsx)(f$,{state:z})})})]},e.runId))})]})}),xe&&d&&O&&(0,Z.jsxs)(`div`,{className:`border rounded-lg p-4 space-y-4 bg-muted/30 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`h4`,{className:`font-medium mb-2`,children:[`Hook context (`,(0,Z.jsx)(`span`,{className:`font-mono`,children:`ctx`}),`)`]}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:O.contextApi?.map(e=>(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`code`,{className:`rounded bg-muted px-1 py-0.5 font-mono text-xs`,children:e.signature}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mt-0.5`,children:e.description})]},e.name))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`h4`,{className:`font-medium mb-2`,children:[`Classifier (`,(0,Z.jsx)(`span`,{className:`font-mono`,children:`const c = ctx.classify()`}),`)`]}),(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:O.classifier.predicates.map(e=>(0,Z.jsx)(`code`,{className:`rounded bg-muted px-1 py-0.5 font-mono text-xs`,children:e},e))}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground mt-2`,children:[`Fields: `,O.classifier.fields.map(e=>(0,Z.jsxs)(`code`,{className:`font-mono`,children:[e,` `]},e)),`(never throws; all predicates are false for a null/unknown document).`]})]}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Full reference: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`docs/hooks.md`}),` in the server repo.`]})]}),E&&s===`scripts`&&(0,Z.jsxs)(`div`,{className:`border rounded-lg p-3 flex gap-2 items-center bg-muted/50`,children:[(0,Z.jsx)(q,{placeholder:`on-image.sh`,value:P,onChange:e=>ee(e.target.value),className:`font-mono text-sm`}),(0,Z.jsx)(J,{size:`sm`,onClick:Pe,disabled:te,children:`Create`}),(0,Z.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>D(!1),children:`Cancel`})]}),E&&s===`hooks`&&(0,Z.jsxs)(`div`,{className:`border rounded-lg p-4 space-y-3 bg-muted/50`,children:[(0,Z.jsxs)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-3`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-xs font-semibold text-muted-foreground block mb-1`,children:`1. When (event)`}),(0,Z.jsx)(`select`,{className:`w-full h-9 rounded-md border bg-background px-2 font-mono text-sm outline-none focus:ring-2 focus:ring-ring`,value:j,onChange:e=>N(e.target.value),children:(O?.events??[]).map(e=>(0,Z.jsxs)(`option`,{value:e.name,children:[e.name,`: `,e.description]},e.name))}),O&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground mt-1 font-mono`,children:[`payload: `,O.events.find(e=>e.name===j)?.payload]}),(0,Z.jsx)(`label`,{className:`text-xs font-semibold text-muted-foreground block mt-3 mb-1`,children:`2. Name`}),(0,Z.jsx)(q,{placeholder:`my-hook`,value:P,onChange:e=>ee(e.target.value),className:`font-mono text-sm`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-xs font-semibold text-muted-foreground block mb-1`,children:`3. Then (actions; pick any)`}),(0,Z.jsx)(`div`,{className:`space-y-1 max-h-52 overflow-auto pr-1`,children:(O?.actions??[]).map(e=>(0,Z.jsxs)(`label`,{className:`flex items-start gap-2 text-sm rounded px-2 py-1 hover:bg-muted cursor-pointer`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`mt-1`,checked:F.includes(e.id),onChange:()=>Fe(e.id)}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:e.label}),(0,Z.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:e.description})]})]},e.id))})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(J,{size:`sm`,onClick:Ie,disabled:te||!O,children:te?`Creating…`:`Create skeleton`}),(0,Z.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>D(!1),children:`Cancel`}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Creates a disabled skeleton. Edit the TODOs, then enable it. Simple match→action automations can also go into `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`rules.json`}),` (no code).`]})]})]}),xe&&(0,Z.jsxs)(`div`,{className:`grid grid-cols-1 md:grid-cols-3 gap-4`,children:[(0,Z.jsx)(`div`,{className:`md:col-span-1 border rounded-lg p-2 max-h-[480px] overflow-auto`,children:h?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground p-2`,children:`Loading...`}):p.length===0?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground p-2`,children:`No hooks yet.`}):Object.entries(Le).map(([e,t])=>(0,Z.jsxs)(`div`,{className:`mb-2`,children:[(0,Z.jsx)(`div`,{className:`text-xs font-semibold text-muted-foreground px-2 py-1`,children:e}),t.map(e=>{let t=RZ(e.path);return(0,Z.jsxs)(`div`,{className:`flex items-center justify-between rounded px-2 py-1 cursor-pointer text-sm ${_===e.path?`bg-muted`:`hover:bg-muted/50`} ${t?``:`opacity-50`}`,onClick:()=>G(e.path),children:[(0,Z.jsxs)(`span`,{className:`font-mono truncate flex items-center gap-1.5`,children:[e.path,s===`hooks`&&zZ(e.path)&&(0,Z.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide rounded bg-muted-foreground/15 px-1 py-0.5 text-muted-foreground shrink-0`,children:`example`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center`,children:[s===`hooks`&&cQ(e.path)&&(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,className:`h-6 w-6 p-0 touch-target`,title:cQ(e.path)?.startsWith(`document.`)?`Run against up to ${H} existing documents`:`Run now`,disabled:pe!==null,onClick:t=>{t.stopPropagation(),Ee(e.path)},children:(0,Z.jsx)(W,{className:`h-3 w-3 ${pe===e.path?`animate-pulse`:``}`})}),s===`hooks`&&(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,className:`h-6 w-6 p-0 touch-target`,title:t?`Disable`:`Enable`,onClick:t=>{t.stopPropagation(),Te(e.path)},children:t?(0,Z.jsx)(on,{className:`h-3 w-3`}):(0,Z.jsx)(x,{className:`h-3 w-3 text-muted-foreground`})}),(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,className:`h-6 w-6 p-0 text-destructive hover:text-destructive touch-target`,onClick:t=>{t.stopPropagation(),De(e.path)},children:(0,Z.jsx)(lt,{className:`h-3 w-3`})})]})]},e.path)})]},e))}),(0,Z.jsx)(`div`,{className:le?`fixed inset-0 z-50 bg-background p-4 flex flex-col`:`md:col-span-2 border rounded-lg p-2 flex flex-col`,children:_?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`mb-2 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsxs)(`span`,{className:`font-mono text-sm truncate`,children:[_,S?` •`:``]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1`,children:[s===`hooks`&&cQ(_)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(J,{size:`sm`,variant:`outline`,className:`h-8`,title:RZ(_)?`Disable this hook (renames it with a disabled- prefix)`:`Enable this hook (strips the prefix)`,onClick:()=>Te(_),children:RZ(_)?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(on,{className:`mr-1.5 h-3.5 w-3.5`}),` Enabled`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(x,{className:`mr-1.5 h-3.5 w-3.5 text-muted-foreground`}),` Disabled`]})}),(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,className:`h-8`,title:`Run this hook now`,disabled:pe!==null||S,onClick:()=>Ee(_),children:[(0,Z.jsx)(W,{className:`mr-1.5 h-3.5 w-3.5 ${pe===_?`animate-pulse`:``}`}),` Run`]})]}),(0,Z.jsxs)(J,{size:`sm`,onClick:we,disabled:w||!S,children:[(0,Z.jsx)(Re,{className:`mr-2 h-4 w-4`}),` Save`]}),(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,className:`h-8 w-8 p-0`,title:le?`Exit full screen (Esc)`:`Edit full screen`,onClick:()=>ue(!le),children:le?(0,Z.jsx)(ct,{className:`h-4 w-4`}):(0,Z.jsx)(gn,{className:`h-4 w-4`})})]})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-auto rounded border text-sm ${le?``:`min-h-[400px] max-h-viewport-pane`}`,children:(0,Z.jsx)(kZ,{value:y,path:_,onChange:e=>{b(e),C(!0)}})})]}):(0,Z.jsxs)(`div`,{className:`flex-1 flex items-center justify-center text-sm text-muted-foreground min-h-[400px]`,children:[`Select a `,s===`hooks`?`hook`:`script`,` to edit, or create a new one.`]})})]}),(s===`rules`||s===`hooks`)&&(0,Z.jsxs)(`label`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground`,title:`1–10000. Raise it when "Apply to existing items" reports fewer matches than you expect.`,children:[(0,Z.jsx)(Ot,{className:`h-3.5 w-3.5 shrink-0`}),(0,Z.jsx)(`span`,{children:`Apply / run in batches of`}),(0,Z.jsx)(q,{type:`number`,min:1,max:1e4,step:100,value:ge,onChange:e=>_e(e.target.value),onBlur:ve,onKeyDown:e=>{e.key===`Enter`&&(ve(),e.target.blur())},className:`h-7 w-20 px-2 text-xs`}),(0,Z.jsx)(`span`,{children:`documents per pass — the rule "Apply" button and manual hook runs stop after that many.`})]}),(0,Z.jsxs)(`p`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Je,{className:`h-3.5 w-3.5 shrink-0`}),(0,Z.jsxs)(`span`,{children:[`Everything here lives in the workspace git repo. Clone it with`,` `,(0,Z.jsxs)(`code`,{className:`break-all rounded bg-muted px-1 py-0.5 font-mono select-all`,children:[`git clone `,ze.replace(`://`,`://canvas@`)]}),` `,`(password: a canvas API token; the `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`canvas@`}),` username is arbitrary but git needs one). Pushes hot-reload hooks.`]})]})]})}function f$({state:e}){if(e.error)return(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:e.error});if(!e.run)return(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading…`});let t=e.run,n={error:`text-destructive`,warn:`text-warning`,info:`text-foreground`,debug:`text-muted-foreground`};return(0,Z.jsxs)(`div`,{className:`space-y-2 text-xs`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-x-4 gap-y-1 text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{children:[`run `,(0,Z.jsx)(`span`,{className:`font-mono`,children:t.runId})]}),(0,Z.jsxs)(`span`,{children:[`trigger `,(0,Z.jsx)(`span`,{className:`font-mono`,children:t.trigger})]}),t.eventId&&(0,Z.jsxs)(`span`,{children:[`event `,(0,Z.jsx)(`span`,{className:`font-mono`,children:t.eventId})]}),(0,Z.jsxs)(`span`,{children:[t.durationMs,` ms`]})]}),t.actions&&t.actions.length>0&&(0,Z.jsx)(`ol`,{className:`space-y-0.5 font-mono`,children:t.actions.map((e,t)=>(0,Z.jsxs)(`li`,{className:e.status===`error`?`text-destructive`:e.status===`skipped`?`text-muted-foreground`:``,children:[t+1,`. `,e.action,` → `,e.status,e.error?` — ${e.error}`:``]},t))}),t.trace&&t.trace.length>0?(0,Z.jsx)(`pre`,{className:`max-h-96 overflow-auto rounded-md border bg-background p-2 font-mono text-[11px] leading-relaxed whitespace-pre-wrap break-all`,children:t.trace.map((e,t)=>(0,Z.jsxs)(`span`,{className:`block ${n[e.level]||``}`,children:[(0,Z.jsxs)(`span`,{className:`text-muted-foreground`,children:[`+`,String(e.t).padStart(5,` `),`ms `]}),(0,Z.jsxs)(`span`,{className:`uppercase text-muted-foreground`,children:[e.level.padEnd(5,` `),` `]}),e.msg]},t))}):(0,Z.jsxs)(`p`,{className:`text-muted-foreground`,children:[`No execution log recorded for this run`,t.error?``:` (older runs predate tracing)`,`.`]})]})}function p$({workspaceName:e}){let{showToast:t}=oo(),[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(!1),[o,s]=(0,X.useState)([]),[c,l]=(0,X.useState)(!1),u=(0,X.useCallback)(async()=>{a(!0);try{r(await Yi(e))}catch(e){t({title:`Error`,description:e instanceof Error?e.message:`Failed to load the trash`,variant:`destructive`})}finally{a(!1)}},[e]);(0,X.useEffect)(()=>{u()},[u]);let d=(0,X.useCallback)(e=>o.includes(e),[o]),f=async(e,t)=>{s(t=>[...t,...e]);try{await t()}finally{s(t=>t.filter(t=>!e.includes(t)))}},p=n=>f([n.id],async()=>{try{let i=await Hr(e,[n.id]);i.failed?.length?t({title:`Not restored`,description:i.failed[0]?.error||`No restore target recorded`,variant:`destructive`}):(t({title:`Restored`,description:`Document put back where it was.`}),r(e=>e.filter(e=>e.id!==n.id)))}catch(e){t({title:`Error`,description:e instanceof Error?e.message:`Failed to restore`,variant:`destructive`})}}),m=n=>f([n.id],async()=>{try{await ei(e,[n.id]),t({title:`Deleted`,description:`Document permanently deleted.`}),r(e=>e.filter(e=>e.id!==n.id))}catch(e){t({title:`Error`,description:e instanceof Error?e.message:`Failed to delete`,variant:`destructive`})}}),h=async()=>{if(!c){l(!0);return}l(!1);try{let n=await ei(e);t({title:`Trash emptied`,description:`${n.destroyed?.length??0} document(s) permanently deleted.`}),r([])}catch(e){t({title:`Error`,description:e instanceof Error?e.message:`Failed to empty the trash`,variant:`destructive`})}},g=(0,X.useMemo)(()=>n.map(e=>{let t=mo(e),n=(e.trashed?.placements??[]).flatMap(e=>e.paths.map(t=>`${e.tree}:${t}`));return{document:e,title:t.title,origin:n,trashedAt:e.trashed?.trashedAt||null}}),[n]);return(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-medium`,children:`Trash`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1 max-w-2xl`,children:`Removing a document from a path detaches it; when that was its last place, it lands here so nothing goes missing. Restoring puts it back everywhere it was. Emptying deletes for real: from the index and from canvas-owned storage, never from external backends.`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 max-sm:flex-wrap`,children:[(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>u(),disabled:i,children:[(0,Z.jsx)(M,{className:`mr-2 h-3.5 w-3.5 ${i?`animate-spin`:``}`}),`Refresh`]}),(0,Z.jsxs)(J,{variant:c?`destructive`:`outline`,size:`sm`,onClick:h,onBlur:()=>l(!1),disabled:n.length===0,children:[(0,Z.jsx)(lt,{className:`mr-2 h-3.5 w-3.5`}),c?`Click again to delete everything`:`Empty trash`]})]})]}),i&&n.length===0&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading…`}),!i&&n.length===0&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`The trash is empty.`}),g.length>0&&(0,Z.jsx)(`div`,{className:`border rounded-md divide-y`,children:g.map(({document:e,title:t,origin:n,trashedAt:r})=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm`,children:t}),(0,Z.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[n.length>0?`from ${n.join(`, `)}`:`no recorded origin`,r?` · ${new Date(r).toLocaleString()}`:``]})]}),(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>p(e),disabled:d(e.id)||n.length===0,title:n.length===0?`Nothing recorded to restore to`:`Put it back where it was`,children:[(0,Z.jsx)($n,{className:`mr-2 h-3.5 w-3.5`}),`Restore`]}),(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:()=>m(e),disabled:d(e.id),title:`Delete permanently`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]},e.id))})]})}var m$=e=>`${Kr.workspaces}/${encodeURIComponent(e)}`;async function h$(e){return await Y.get(`${m$(e)}/mirrors`)||[]}async function g$(e,t){await Y.delete(`${m$(e)}/mirrors/${encodeURIComponent(t)}`)}async function _$(e,t=10){return Y.get(`${m$(e)}/mirrors/protection?sample=${t}`)}async function v$(e,t,n){return(await Y.patch(`${m$(e)}/mirrors/${encodeURIComponent(t)}`,n)).replica}async function y$(e){return await Y.get(`${m$(e)}/sync/conflicts`)||[]}async function b$(e,t,n){return Y.post(`${m$(e)}/sync/conflicts/${t}/resolve`,{keep:n})}var x$=e=>{if(e==null||e===``)return`—`;let t=new Date(e);return Number.isNaN(t.getTime())?`—`:t.toLocaleString(void 0,{dateStyle:`medium`,timeStyle:`short`})},S$=e=>e==null?`—`:e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:e<1073741824?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`,C$=e=>e?e.slice(0,12):`—`;function w$({mirror:e,now:t,busy:n,onForget:r,onRequired:i}){let a=e.mirror,o=!e.lastSeen||t-new Date(e.lastSeen).getTime()>6e5,s=e.replica?.role===`cache`||a.client===`fuse`,c=e.replica?.required===!0,l=a.direction||(a.client===`fuse`?`bi`:void 0);return(0,Z.jsx)(`div`,{className:`rounded-lg border p-3`,children:(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start gap-3 min-w-0`,children:[(0,Z.jsx)(St,{className:`h-4 w-4 text-muted-foreground mt-0.5 shrink-0`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:e.name||e.deviceId}),a.client&&(0,Z.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] font-mono uppercase`,children:a.client}),l&&(0,Z.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] font-mono`,title:l===`pull`?`Backup target: the hub is the only writer`:l===`push`?`One-shot import: local is the only writer`:`Both ways`,children:l===`pull`?`⇣ pull`:l===`push`?`⇡ push`:`⇅ bi`}),c&&(0,Z.jsx)(`span`,{className:`rounded bg-emerald-500/15 px-1.5 py-0.5 text-[10px] font-mono text-emerald-700 dark:text-emerald-300`,title:`Counts toward protection`,children:`required`}),(0,Z.jsx)(`span`,{className:`rounded px-1.5 py-0.5 text-[10px] font-mono ${o?`bg-muted text-muted-foreground`:`bg-emerald-500/15 text-emerald-700 dark:text-emerald-300`}`,children:a.state||(o?`offline`:`online`)})]}),a.path&&(0,Z.jsx)(`p`,{className:`mt-0.5 text-[11px] font-mono text-muted-foreground truncate`,children:a.path}),(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-x-4 gap-y-0.5 text-[11px] text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{title:`Change-log entries the device has not applied yet`,children:[`lag `,e.lag??`—`]}),(0,Z.jsxs)(`span`,{title:`Local changes waiting to be pushed`,children:[`pending `,a.pending??0]}),(a.failed??0)>0&&(0,Z.jsxs)(`span`,{className:`text-destructive`,children:[`failed `,a.failed]}),(a.conflicts??0)>0&&(0,Z.jsxs)(`span`,{className:`text-amber-600 dark:text-amber-400`,children:[`conflicts `,a.conflicts]}),(a.skipped??0)>0&&(0,Z.jsxs)(`span`,{children:[`skipped `,a.skipped]}),(a.reverted??0)>0&&(0,Z.jsxs)(`span`,{title:`Local edits parked in .workspace/conflicts and replaced by the hub version`,children:[`reverted `,a.reverted]}),e.behind!=null&&(0,Z.jsxs)(`span`,{title:`Documents whose current version this device does not hold yet`,className:e.behind>0&&c?`text-amber-600 dark:text-amber-400`:``,children:[`behind `,e.behind]}),(0,Z.jsxs)(`span`,{children:[`last sync `,x$(a.lastSync)]}),(0,Z.jsxs)(`span`,{children:[`seen `,x$(e.lastSeen)]}),a.prefixes&&a.prefixes.length>0&&(0,Z.jsx)(`span`,{className:`font-mono`,children:a.prefixes.join(`, `)})]}),a.lastError&&(0,Z.jsx)(`p`,{className:`mt-1 text-[11px] text-destructive`,children:a.lastError}),(0,Z.jsxs)(`label`,{className:`mt-2 flex items-center gap-2 text-[11px] ${s?`text-muted-foreground`:``}`,title:s?`A cache never counts toward protection`:`A document is protected once every required replica holds its current version`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`h-3 w-3`,checked:c,disabled:n||s,onChange:e=>i(e.target.checked)}),`required for protection`]})]})]}),(0,Z.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:r,disabled:n,title:`Forget this mirror record (the device is not revoked)`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})})}function T$({p:e}){let t=e.required.length===0,n=e.unprotected??0,r=t||n>0?Vt:Mt,i=t?`text-muted-foreground`:n>0?`text-amber-600 dark:text-amber-400`:`text-emerald-700 dark:text-emerald-300`;return(0,Z.jsx)(`div`,{className:`rounded-lg border p-3`,children:(0,Z.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,Z.jsx)(r,{className:`h-4 w-4 mt-0.5 shrink-0 ${i}`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 text-[11px]`,children:[t?(0,Z.jsxs)(`p`,{className:`text-sm`,children:[`No replica is marked `,(0,Z.jsx)(`span`,{className:`font-medium`,children:`required`}),` yet — nothing is counted as protected. Tick it on the device that must hold every document (the backup).`]}):(0,Z.jsxs)(`p`,{className:`text-sm`,children:[(0,Z.jsxs)(`span`,{className:`font-medium ${i}`,children:[e.protected??0,` of `,e.total-e.unversioned]}),` documents are held at their current version by every required replica`,n>0&&(0,Z.jsxs)(`span`,{className:i,children:[` · `,n,` not yet`]}),e.partial&&(0,Z.jsxs)(`span`,{className:`text-muted-foreground`,children:[` (first `,e.total,` checked)`]})]}),e.oldestUnprotected.length>0&&(0,Z.jsxs)(`ul`,{className:`mt-1 space-y-0.5 font-mono text-muted-foreground`,children:[e.oldestUnprotected.slice(0,5).map(e=>(0,Z.jsxs)(`li`,{className:`truncate`,title:`document ${e.docId} v${e.version}`,children:[e.key,` `,(0,Z.jsxs)(`span`,{className:`opacity-70`,children:[`· `,x$(e.mtime)]})]},`${e.docId}:${e.key}`)),e.oldestUnprotected.length>5&&(0,Z.jsxs)(`li`,{children:[`… and `,e.oldestUnprotected.length-5,` more`]})]})]})]})})}function E$({conflict:e,busy:t,onResolve:n}){let r=!e.hub;return(0,Z.jsxs)(`div`,{className:`rounded-lg border p-3 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,Z.jsx)(at,{className:`h-4 w-4 text-amber-500 mt-0.5 shrink-0`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium font-mono break-all`,children:e.key}),(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`from `,(0,Z.jsx)(`span`,{className:`font-medium`,children:e.deviceName||e.device||`unknown device`}),` · `,x$(e.ts),e.mode===`rename`&&e.conflictKey&&(0,Z.jsxs)(Z.Fragment,{children:[` · already on disk as `,(0,Z.jsx)(`span`,{className:`font-mono`,children:e.conflictKey})]})]})]})]}),(0,Z.jsxs)(`div`,{className:`grid grid-cols-1 gap-2 text-[11px] sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`rounded border border-dashed p-2`,children:[(0,Z.jsx)(`div`,{className:`text-muted-foreground`,children:`Hub version (keeps the name)`}),e.hub?(0,Z.jsxs)(`div`,{className:`font-mono`,children:[C$(e.hub.sha256),` · `,S$(e.hub.size),` · `,x$(e.hub.mtime)]}):(0,Z.jsx)(`div`,{className:`italic text-muted-foreground`,children:`no file at this key any more`})]}),(0,Z.jsxs)(`div`,{className:`rounded border border-dashed p-2`,children:[(0,Z.jsx)(`div`,{className:`text-muted-foreground`,children:`Incoming version (the device’s)`}),(0,Z.jsxs)(`div`,{className:`font-mono`,children:[C$(e.incoming.sha256),` · `,S$(e.incoming.size),` · `,x$(e.incoming.mtime)]})]})]}),e.resolvable?(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:t||r,onClick:()=>n(`hub`),title:`Discard the device's version`,children:`Keep hub`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:t,onClick:()=>n(`incoming`),title:`The device's bytes replace the hub's; tags, relations and placements move over`,children:`Keep incoming`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:t,onClick:()=>n(`both`),title:`Keep the hub file and add the device's version under a conflict name`,children:`Keep both`})]}):(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Dropbox-style conflict copy: both files are on disk, delete the one you do not need.`})]})}function D$({workspaceId:e,workspaceUuid:t}){let{showToast:n}=oo(),[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)([]),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(0),h=(0,X.useRef)(null),g=(0,X.useCallback)(async(t=!1)=>{if(e){t||u(!0);try{let[t,n,r]=await Promise.all([h$(e),y$(e),_$(e).catch(()=>null)]);i(t),o(n),c(r),m(Date.now())}catch(e){t||n({title:`Error`,description:e instanceof Error?e.message:`Failed to load sync state`,variant:`destructive`})}finally{t||u(!1)}}},[e]);(0,X.useEffect)(()=>{g()},[g]),(0,X.useEffect)(()=>{if(!t)return;let e=`workspace:${t}`,n=()=>Wu.emit(`subscribe`,{channel:e}),r=Wu.on(`connect`,n);n();let i=e=>{let n=e;n?.workspaceId&&n.workspaceId!==t||(h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{h.current=null,g(!0)},800))},a=[`backend.changed`,`sync.conflict.created`,`sync.conflict.resolved`].map(e=>Wu.on(e,i));return()=>{r(),a.forEach(e=>e()),Wu.emit(`unsubscribe`,{channel:e}),h.current&&=(clearTimeout(h.current),null)}},[t,g]);let _=async t=>{f(`mirror:${t}`);try{await g$(e,t),i(e=>e.filter(e=>e.deviceId!==t)),n({title:`Forgotten`,description:`Mirror record removed. The device keeps running and will report again if it still syncs this workspace.`})}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to forget mirror`,variant:`destructive`})}finally{f(null)}},v=async(t,r)=>{f(`mirror:${t}`);try{let n=await v$(e,t,{required:r});i(e=>e.map(e=>e.deviceId===t?{...e,replica:{role:n.role,required:n.required}}:e)),c(await _$(e).catch(()=>null))}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to update replica policy`,variant:`destructive`})}finally{f(null)}},y=async(t,r)=>{f(`conflict:${t.docId}`);try{let i=await b$(e,t.docId,r);o(e=>e.filter(e=>e.docId!==t.docId));let a=r===`hub`?`kept the hub version`:r===`incoming`?`the device version now holds the name`:`kept both (${i.resultKey||`conflict copy`})`;n({title:`Resolved`,description:`${t.key}: ${a}`})}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to resolve conflict`,variant:`destructive`})}finally{f(null)}};return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Device mirrors`}),(0,Z.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[`Devices keeping this workspace’s files in sync (canvas-fuse `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`--mirror`}),`, canvas-edge). Lag counts change-log entries the device has not applied yet.`]})]}),(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>g(),disabled:l,children:[(0,Z.jsx)(M,{className:`mr-2 h-3.5 w-3.5 ${l?`animate-spin`:``}`}),`Refresh`]})]}),l&&r.length===0&&a.length===0?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(M,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):r.length===0?(0,Z.jsxs)(`div`,{className:`rounded-lg border border-dashed p-4 text-xs text-muted-foreground`,children:[`No device mirrors this workspace yet. Mount it with `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`canvas-fuse mount -w <workspace> ~/Workspaces --mirror`}),` on a device and it shows up here.`]}):(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[s&&(0,Z.jsx)(T$,{p:s}),r.map(e=>(0,Z.jsx)(w$,{mirror:e,now:p,busy:d===`mirror:${e.deviceId}`,onForget:()=>_(e.deviceId),onRequired:t=>v(e.deviceId,t)},e.deviceId))]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Conflicts`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`A device and the hub both changed the same file. The hub’s version keeps the filename; decide what happens to the device’s. Tags, relations and placements follow whichever version survives.`})]}),a.length===0?(0,Z.jsx)(`div`,{className:`rounded-lg border border-dashed p-4 text-xs text-muted-foreground`,children:`Nothing to resolve.`}):(0,Z.jsx)(`div`,{className:`space-y-2`,children:a.map(e=>(0,Z.jsx)(E$,{conflict:e,busy:d===`conflict:${e.docId}`,onResolve:t=>y(e,t)},e.docId))})]})}function O$({workspaceId:e,address:t}){let[n,r]=(0,X.useState)(!1),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(``);return(0,X.useEffect)(()=>{if(!n)return;let r=!1,i,o=async()=>{try{let n=await sm(e,t);r||(a(n),s(``))}catch(e){r||s(e instanceof Error?e.message:`Connection unavailable`)}r||(i=setTimeout(()=>void o(),3e3))};return o(),()=>{r=!0,clearTimeout(i)}},[e,t,n]),(0,Z.jsxs)(`div`,{className:`mb-2`,children:[(0,Z.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>r(!n),children:n?`Close connection panel`:`Pair / connection status`}),n&&(0,Z.jsxs)(`div`,{className:`space-y-2 p-2 text-xs`,children:[(0,Z.jsx)(`p`,{children:o||i?.state||`Connecting…`}),(0,Z.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>{window.confirm(`Forget the current session and pair this account again?`)&&lm(e,t).catch(e=>s(e.message))},children:`Pair again`}),i?.qr&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{children:`WhatsApp → Settings → Linked devices → Link a device.`}),(0,Z.jsx)(`img`,{className:`max-w-full`,src:i.qr,width:256,height:256,alt:`WhatsApp device pairing QR code`})]}),i?.chats.length?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{children:`Copy the conversations you want into this account’s Conversation IDs setting.`}),(0,Z.jsx)(`div`,{className:`max-h-48 overflow-auto`,children:i.chats.map(e=>(0,Z.jsxs)(`p`,{children:[e.name,` · `,(0,Z.jsx)(`code`,{className:`select-all`,children:e.id})]},e.id))})]}):null]})]})}var k$={github:{label:`GitHub Issues`,icon:`mdi:github`,blurb:`Issues from the listed repos sync as todos. Token optional for public repos.`,fields:[{key:`address`,label:`Account label`,placeholder:`e.g. canvas-ui`,required:!0},{key:`token`,label:`Personal access token`,hint:`Optional for public repos; required for write-back.`,secret:!0},{key:`repos`,label:`Repositories`,placeholder:`owner/repo, one per line`,hint:`Issues from each repo sync as todos.`,list:!0,required:!0},{key:`writeBack`,label:`Manage issues from Canvas`,hint:`Create, edit and close issues. Needs a PAT with repo scope.`,bool:!0},{key:`pruneRemoved`,label:`Remove items deleted at the source`,hint:`After each sync, issues that no longer exist in the repo are dropped from the mirror (kept as location-less orphans until database retention GC; skipped whenever the repo can’t be fully listed).`,bool:!0}]},slack:{label:`Slack`,icon:`mdi:slack`,blurb:`Channel messages sync as message documents. Bot/user token with channels:read + channels:history.`,fields:[{key:`address`,label:`Workspace label`,placeholder:`e.g. acme`,required:!0},{key:`token`,label:`Token (xoxb-… / xoxp-…)`,secret:!0,required:!0},{key:`channels`,label:`Conversations (channel names or IDs; DM IDs need im:read + im:history)`,list:!0},{key:`directMessages`,label:`Include direct messages`,hint:`Requires im:read, im:history, mpim:read and mpim:history.`,bool:!0},{key:`writeBack`,label:`Allow sending from Canvas`,hint:`Token also needs chat:write.`,bool:!0},{key:`allowAgentSend`,label:`Allow agents with workspace write access to send`,bool:!0}]},whatsapp:{label:`WhatsApp (linked device)`,icon:`mdi:whatsapp`,blurb:`Pair your phone with Canvas, then choose conversations. Uses Baileys; separate from WhatsApp Business.`,fields:[{key:`address`,label:`Account label`,placeholder:`personal`,required:!0},{key:`chats`,label:`Conversation IDs to sync (one per line; available after pairing)`,list:!0},{key:`writeBack`,label:`Allow sending from Canvas`,bool:!0},{key:`allowAgentSend`,label:`Allow agents with workspace write access to send`,bool:!0}]},gcal:{label:`Google Calendar`,icon:`mdi:calendar-month`,blurb:`Events sync as calendar entries (recurring series kept as series). Offline-access OAuth credentials.`,fields:[{key:`address`,label:`Account label`,placeholder:`e.g. me-gmail`,required:!0},{key:`clientId`,label:`OAuth client id`,required:!0},{key:`clientSecret`,label:`OAuth client secret`,secret:!0,required:!0},{key:`refreshToken`,label:`Refresh token`,secret:!0,required:!0},{key:`calendars`,label:`Calendar ids (empty = primary)`,list:!0}]},caldav:{label:`CalDAV`,icon:`mdi:calendar-sync`,blurb:`Any CalDAV endpoint (GroupOffice, Nextcloud, Radicale, SOGo…). Read-only by default; enable write-back to create events from Canvas.`,fields:[{key:`address`,label:`Account label`,placeholder:`e.g. groupoffice`,required:!0},{key:`url`,label:`CalDAV URL (calendar home or one calendar)`,placeholder:`https://host/caldav/user`,required:!0},{key:`username`,label:`Username`},{key:`password`,label:`Password`,secret:!0},{key:`calendars`,label:`Calendars (names, empty = all)`,list:!0},{key:`writeBack`,label:`Create events from Canvas`,hint:`Write-back into the CalDAV calendar.`,bool:!0}]},teams:{label:`MS Teams`,icon:`mdi:microsoft-teams`,blurb:`Channel messages via Microsoft Graph (app-only credentials, admin-consented ChannelMessage.Read.All).`,fields:[{key:`address`,label:`Tenant label`,placeholder:`e.g. corp`,required:!0},{key:`tenantId`,label:`Tenant id`,required:!0},{key:`clientId`,label:`Client id`,required:!0},{key:`clientSecret`,label:`Client secret`,secret:!0,required:!0},{key:`teams`,label:`Team ids (one per line)`,list:!0,required:!0}]}};function A$(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(Boolean)}function j$({workspaceId:e}){let{showToast:t}=oo(),[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[l,u]=(0,X.useState)({}),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),h=(0,X.useCallback)(async()=>{let t=await va(e).catch(()=>[]);r(t.filter(e=>e.kind===`connector`))},[e]),g=async()=>{m(!0);try{await h()}finally{m(!1)}};(0,X.useEffect)(()=>{let t=!1;return va(e).then(e=>{t||r(e.filter(e=>e.kind===`connector`))}).catch(()=>{}),()=>{t=!0}},[e]);let _=n.some(e=>e.status===`syncing`);(0,X.useEffect)(()=>{if(!_)return;let e=setInterval(()=>{h()},4e3);return()=>clearInterval(e)},[_,h]);let v=e=>{let t=k$[e.driver];if(!t)return;let n=e.config||{},r={};for(let i of t.fields){if(i.key===`address`){r.address=e.address;continue}if(i.secret)continue;if(i.key===`writeBack`){r.writeBack=n.readOnly===!1&&(![`slack`,`whatsapp`].includes(e.driver)||n.sendEnabled===!0)?`true`:``;continue}let t=n[i.key];if(i.list){r[i.key]=Array.isArray(t)?t.join(`
|
|
78
|
+
`):``;continue}t!=null&&(r[i.key]=String(t))}u(r),a(e.driver),s(e)},y=()=>{a(null),s(null),u({})},b=async()=>{if(!i)return;let n=k$[i],r={};for(let e of n.fields){let n=(l[e.key]||``).trim();if(!n){if(e.required&&!(o&&e.secret)){t({title:`${e.label} is required`,variant:`destructive`});return}o&&!e.secret&&(r[e.key]=e.list?[]:!e.bool&&``);continue}r[e.key]=e.list?A$(n):e.bool?n===`true`:n}n.fields.some(e=>e.key===`writeBack`)&&([`slack`,`whatsapp`].includes(i)&&(r.sendEnabled=r.writeBack===!0),r.readOnly=r.writeBack!==!0,delete r.writeBack),f(!0);try{o?await aa(e,o.driver,o.address,r):await Xi(e,i,r),y(),await h(),t({title:o?`Connector updated; sync restarted`:`Connector saved; first sync started`})}catch(e){t({title:`Failed to save connector`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{f(!1)}},x=async n=>{try{await da(e,n.driver,n.address),t({title:`Syncing ${n.driver}/${n.address}`}),setTimeout(()=>{h()},1500)}catch(e){t({title:`Sync failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}},S=async n=>{if(window.confirm(`Remove ${n.driver}/${n.address}? Synced documents stay in the backends tree until purged.`))try{await Nr(e,n.driver,n.address),await h()}catch(e){t({title:`Remove failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}};return(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Connectors`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`GitHub issues, Slack, Google Calendar, CalDAV and MS Teams, polled into the backends tree (read-only unless write-back is enabled).`})]}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:p,onClick:()=>{g()},title:`Refresh`,children:(0,Z.jsx)(M,{className:`h-3.5 w-3.5 ${p?`animate-spin`:``}`})})]}),n.length>0&&(0,Z.jsx)(`div`,{className:`mt-3 space-y-2`,children:n.map(t=>{let n=k$[t.driver];return(0,Z.jsxs)(`div`,{className:`rounded-md border p-3`,children:[t.driver===`whatsapp`&&(0,Z.jsx)(O$,{workspaceId:e,address:t.address}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(c,{icon:n?.icon||`mdi:cloud-sync`,width:16,height:16,className:`shrink-0`}),(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:n?.label||t.driver}),(0,Z.jsx)(`span`,{className:`font-mono text-xs text-muted-foreground`,children:t.address}),(0,Z.jsx)(`span`,{className:`flex-1`}),(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:t.status===`syncing`,onClick:()=>{x(t)},children:[(0,Z.jsx)(M,{className:`mr-1 h-3 w-3 ${t.status===`syncing`?`animate-spin`:``}`}),t.status===`syncing`?`Syncing`:`Sync now`]}),(0,Z.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>v(t),title:`Edit connector`,children:(0,Z.jsx)(ye,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>{S(t)},title:`Remove connector`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5 text-destructive`})})]}),(0,Z.jsxs)(`div`,{className:`mt-1.5 flex flex-wrap gap-2 text-[11px] text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{children:[`status: `,t.status]}),t.lastSyncAt&&(0,Z.jsxs)(`span`,{children:[`last sync: `,new Date(t.lastSyncAt).toLocaleString()]}),t.treePath&&(0,Z.jsx)(`span`,{className:`font-mono`,children:t.treePath})]}),t.lastError&&(0,Z.jsx)(`p`,{className:`mt-1 text-[11px] text-destructive`,children:t.lastError})]},`${t.driver}:${t.address}`)})}),i?(0,Z.jsxs)(`div`,{className:`mt-3 rounded-md border p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(c,{icon:k$[i].icon,width:16,height:16}),(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:o?`Edit ${k$[i].label}`:k$[i].label}),o&&(0,Z.jsx)(`span`,{className:`font-mono text-xs text-muted-foreground`,children:o.address}),(0,Z.jsx)(`span`,{className:`flex-1`}),(0,Z.jsx)(`button`,{type:`button`,onClick:y,className:`p-1 text-muted-foreground hover:text-foreground`,"aria-label":`Cancel`,children:(0,Z.jsx)(je,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:k$[i].blurb}),(0,Z.jsx)(`div`,{className:`mt-2 grid gap-2 sm:grid-cols-2`,children:k$[i].fields.map(e=>(0,Z.jsxs)(`label`,{className:`text-xs ${e.list||e.bool?`sm:col-span-2`:``}`,children:[!e.bool&&(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:e.label}),e.bool?(0,Z.jsxs)(`span`,{className:`mt-1 flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:l[e.key]===`true`,onChange:t=>u(n=>({...n,[e.key]:t.target.checked?`true`:``})),className:`h-4 w-4 accent-primary`}),(0,Z.jsx)(`span`,{children:e.label})]}):e.list?(0,Z.jsx)(`textarea`,{value:l[e.key]||``,onChange:t=>u(n=>({...n,[e.key]:t.target.value})),placeholder:e.placeholder,rows:2,className:`mt-1 w-full rounded-md border border-input bg-background px-2 py-1.5 text-xs placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`}):(0,Z.jsx)(q,{type:e.secret?`password`:`text`,value:l[e.key]||``,disabled:!!o&&e.key===`address`,onChange:t=>u(n=>({...n,[e.key]:t.target.value})),placeholder:o&&e.secret?`Leave blank to keep current`:e.placeholder,autoComplete:`off`,className:`mt-1 h-8 text-xs`}),e.hint&&(0,Z.jsx)(`span`,{className:`mt-0.5 block text-[11px] text-muted-foreground/80`,children:e.hint})]},e.key))}),(0,Z.jsx)(J,{type:`button`,size:`sm`,className:`mt-3`,disabled:d,onClick:()=>{b()},children:d?`Saving…`:o?`Save changes & sync`:`Save & sync`})]}):(0,Z.jsx)(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:Object.entries(k$).map(([e,t])=>(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{a(e),u({})},children:[(0,Z.jsx)(nn,{className:`mr-1 h-3 w-3`}),(0,Z.jsx)(c,{icon:t.icon,width:14,height:14,className:`mr-1`}),t.label]},e))})]})}var M$={host:``,port:993,tls:!0,allowSelfSigned:!0,user:``,password:``,pollInterval:6e4,initialSyncDays:180,smtp:{enabled:!1,host:``,port:587,secure:!1,user:``,password:``,from:``,sentFolder:`Sent`,appendSent:!1,allowAgentSend:!1}};function N$(e){let t=e.config||{};return{host:String(t.host||``),port:Number(t.port??993),tls:t.tls!==!1,allowSelfSigned:t.allowSelfSigned!==!1,user:String(t.user||e.address),password:``,pollInterval:Number(t.pollInterval??6e4),initialSyncDays:Number(t.initialSyncDays??180),smtp:{...M$.smtp,...t.smtp||{},password:``}}}function P$({workspaceId:e,enabled:t}){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(M$),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)([`INBOX`]),[m,h]=(0,X.useState)(!0),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(null),{showToast:S}=oo(),C=(0,X.useMemo)(()=>[...n].sort((e,t)=>e.address.localeCompare(t.address)),[n]),w=(0,X.useMemo)(()=>n.find(e=>e.address===i)||null,[n,i]),T=(0,X.useCallback)(()=>va(e,`imap`).then(e=>r(e)).catch(e=>{S({title:`Error`,description:e instanceof Error?e.message:`Failed to load IMAP accounts`,variant:`destructive`})}).finally(()=>h(!1)),[e,S]),E=(0,X.useCallback)(async()=>{h(!0),await T()},[T]),[D,O]=(0,X.useState)(e);e!==D&&(O(e),h(!0)),(0,X.useEffect)(()=>{T()},[T]);let k=(0,X.useCallback)(async(t,n)=>{_(!0);try{let r=t?await Ui(e,`imap`,t.address):await vr(e,`imap`,{host:(n?.host||``).trim(),port:Number(n?.port)||993,tls:n?.tls!==!1,allowSelfSigned:n?.allowSelfSigned!==!1,user:(n?.user||``).trim(),password:n?.password||``,folder:`INBOX`});d(r.filter(e=>e.selectable))}catch(e){S({title:`IMAP Error`,description:e instanceof Error?e.message:`Failed to discover folders`,variant:`destructive`})}finally{_(!1)}},[e,S]),A=()=>{s(!1),a(null),l(M$),d([]),p([`INBOX`])},j=e=>{if(i===e.address){A();return}s(!1),a(e.address),l(N$(e)),d([]),p((e.containers||[]).map(e=>e.name)),k(e)},N=()=>{A(),s(!0)},P=(e,t)=>l(n=>({...n,[e]:t})),ee=e=>p(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),F=(0,X.useMemo)(()=>{let e=new Map(u.map(e=>[e.path,e]));for(let t of f)e.has(t)||e.set(t,{name:t,path:t,delimiter:`/`,selectable:!0,attributes:[]});return[...e.values()].sort((e,t)=>e.path.localeCompare(t.path))},[u,f]),I=async()=>{y(!0);try{let t=f.length?f:[`INBOX`],n={host:c.host.trim(),user:c.user.trim(),port:Number(c.port)||993,tls:c.tls,allowSelfSigned:c.allowSelfSigned,pollInterval:Number(c.pollInterval)||6e4,initialSyncDays:Math.max(0,Number(c.initialSyncDays)||0),smtp:c.smtp,...c.password?{password:c.password}:{}};if(w){await aa(e,`imap`,w.address,n);let r=new Set((w.containers||[]).map(e=>e.name)),i=t.filter(e=>!r.has(e)),a=[...r].filter(e=>!t.includes(e));i.length&&await Di(e,`imap`,w.address,i);for(let t of a)await Rr(e,`imap`,w.address,t)}else{await Xi(e,`imap`,{...n,password:c.password,folder:t[0]});let r=c.user.trim();t.length>1&&await Di(e,`imap`,r,t.slice(1))}await E(),s(!1),a(c.user.trim()),S({title:`Saved`,description:`IMAP account ${c.user.trim()} saved; sync runs in the background`})}catch(e){S({title:`Error`,description:e instanceof Error?e.message:`Failed to save IMAP account`,variant:`destructive`})}finally{y(!1)}},te=async()=>{if(!(!w||!window.confirm(`Delete IMAP account ${w.address} and all its folders?`))){x(`delete:${w.address}`);try{await Nr(e,`imap`,w.address),await E(),A(),S({title:`Deleted`,description:`IMAP account ${w.address} deleted`})}catch(e){S({title:`Error`,description:e instanceof Error?e.message:`Failed to delete account`,variant:`destructive`})}finally{x(null)}}},ne=async(t,n)=>{x(`${t}:${n}`);try{t===`test`?await Zi(e,`imap`,n):await da(e,`imap`,n),await E(),S({title:`Success`,description:t===`sync`?`${n} sync started (runs in the background)`:`${n} test completed`})}catch(e){S({title:`Error`,description:e instanceof Error?e.message:`Failed to ${t}`,variant:`destructive`})}finally{x(null)}},L=async(t,n)=>{x(`folder-sync:${t}:${n}`);try{await Sa(e,`imap`,t,n),await E(),S({title:`Synced`,description:`${t} · ${n}`})}catch(e){S({title:`Error`,description:e instanceof Error?e.message:`Failed to sync folder`,variant:`destructive`})}finally{x(null)}},re=(0,Z.jsxs)(`div`,{className:`grid gap-3`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(bu,{htmlFor:`imap-host`,children:`Host`}),(0,Z.jsx)(q,{id:`imap-host`,value:c.host,disabled:!!w,onChange:e=>P(`host`,e.target.value),placeholder:`imap.example.com`})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(bu,{htmlFor:`imap-user`,children:`User (account)`}),(0,Z.jsx)(q,{id:`imap-user`,value:c.user,disabled:!!w,onChange:e=>P(`user`,e.target.value),placeholder:`me@example.com`})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(bu,{htmlFor:`imap-password`,children:`Password`}),(0,Z.jsx)(q,{id:`imap-password`,type:`password`,value:c.password,onChange:e=>P(`password`,e.target.value),placeholder:w?`Leave blank to keep current password`:`Password`})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(bu,{htmlFor:`imap-port`,children:`Port`}),(0,Z.jsx)(q,{id:`imap-port`,type:`number`,value:String(c.port),onChange:e=>P(`port`,Number(e.target.value||993))})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsx)(bu,{children:`Folders to sync`}),(0,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>void k(w,c),disabled:g||!w&&(!c.host.trim()||!c.user.trim()||!c.password),children:[g?(0,Z.jsx)(Wn,{className:`h-3 w-3 animate-spin`}):(0,Z.jsx)(ot,{className:`h-3 w-3`}),` Discover folders`]})]}),(0,Z.jsx)(`div`,{className:`max-h-56 overflow-y-auto rounded-md border p-2`,children:F.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:g?`Discovering folders…`:w?`No folders found on the server.`:`Fill in host, user and password, then discover the account’s folders. INBOX is synced by default.`}):(0,Z.jsx)(`div`,{className:`space-y-0.5`,children:F.map(e=>{let t=e.path.split(e.delimiter||`/`).length-1,n=u.some(t=>t.path===e.path);return(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 rounded px-2 py-1 text-xs hover:bg-accent/50`,style:{paddingLeft:`${8+t*14}px`},children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:f.includes(e.path),onChange:()=>ee(e.path)}),(0,Z.jsx)(`span`,{className:`font-mono truncate`,children:e.path}),!n&&u.length>0&&(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`(subscribed, not on server)`})]},e.path)})})}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[f.length,` folder`,f.length===1?``:`s`,` selected; each synced as its own container. Unchecking a synced folder removes it on Save.`]})]}),(0,Z.jsxs)(`fieldset`,{className:`rounded border p-3 space-y-3 sm:col-span-2`,children:[(0,Z.jsx)(`legend`,{className:`px-1 text-sm font-medium`,children:`Outgoing email (SMTP)`}),(0,Z.jsxs)(`label`,{className:`flex gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:c.smtp.enabled,onChange:e=>P(`smtp`,{...c.smtp,enabled:e.target.checked})}),`Allow sending from Canvas`]}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[[`host`,`user`,`password`,`from`,`sentFolder`].map(e=>(0,Z.jsxs)(`label`,{className:`text-xs`,children:[{host:`SMTP host`,user:`SMTP username`,password:`SMTP password (blank keeps current)`,from:`From address`,sentFolder:`Sent folder`}[e],(0,Z.jsx)(q,{type:e===`password`?`password`:`text`,value:c.smtp[e],autoComplete:`off`,onChange:t=>P(`smtp`,{...c.smtp,[e]:t.target.value})})]},e)),(0,Z.jsxs)(`label`,{className:`text-xs`,children:[`Port`,(0,Z.jsx)(q,{type:`number`,min:1,max:65535,value:c.smtp.port,onChange:e=>P(`smtp`,{...c.smtp,port:Number(e.target.value)})})]})]}),(0,Z.jsxs)(`label`,{className:`flex gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:c.smtp.secure,onChange:e=>P(`smtp`,{...c.smtp,secure:e.target.checked})}),`Implicit TLS (usually port 465; otherwise STARTTLS is required)`]}),(0,Z.jsxs)(`label`,{className:`flex gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:c.smtp.appendSent,onChange:e=>P(`smtp`,{...c.smtp,appendSent:e.target.checked})}),`Save a copy in the IMAP Sent folder (leave off if your provider does this automatically)`]}),(0,Z.jsxs)(`label`,{className:`flex gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:c.smtp.allowAgentSend,onChange:e=>P(`smtp`,{...c.smtp,allowAgentSend:e.target.checked})}),`Allow agents with workspace write access to send`]})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(bu,{htmlFor:`imap-lookback`,children:`Initial sync lookback (days)`}),(0,Z.jsx)(q,{id:`imap-lookback`,type:`number`,min:`0`,value:String(c.initialSyncDays),onChange:e=>P(`initialSyncDays`,Number(e.target.value||0))}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`First sync only (lastUid 0). Set 0 to import the whole mailbox.`})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(bu,{htmlFor:`imap-poll`,children:`Poll interval (ms)`}),(0,Z.jsx)(q,{id:`imap-poll`,type:`number`,value:String(c.pollInterval),onChange:e=>P(`pollInterval`,Number(e.target.value||6e4))})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-4 text-xs`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:c.tls,onChange:e=>P(`tls`,e.target.checked)}),` TLS`]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:c.allowSelfSigned,onChange:e=>P(`allowSelfSigned`,e.target.checked)}),` Allow self-signed`]})]})]});return(0,Z.jsxs)(`div`,{className:`space-y-3 border-t pt-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`h4`,{className:`text-sm font-medium`,children:`IMAP Accounts`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Each account mirrors under /imap/<account> in the backends tree; its folders are synced as containers. Click an account to edit its settings.`})]}),!t&&(0,Z.jsx)(`p`,{className:`rounded-md border bg-muted/40 p-2 text-xs text-muted-foreground`,children:`Enable the IMAP service before polling starts. Accounts can still be configured while it is off.`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,onClick:o?A:N,children:[(0,Z.jsx)(vt,{className:`h-3 w-3`}),` `,o?`Cancel`:`New Account`]}),(0,Z.jsxs)(J,{size:`sm`,variant:`ghost`,onClick:E,disabled:m,children:[m?(0,Z.jsx)(Wn,{className:`h-3 w-3 animate-spin`}):(0,Z.jsx)(M,{className:`h-3 w-3`}),` Refresh`]})]}),(0,Z.jsx)(`div`,{className:`rounded-md border`,children:(0,Z.jsx)(`div`,{className:`max-h-[32rem] overflow-y-auto p-2 space-y-1`,children:C.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No IMAP accounts configured.`}):C.map(t=>{let n=i===t.address;return(0,Z.jsxs)(`div`,{className:`rounded px-2 py-2 text-xs transition-colors ${n?`bg-accent/40`:`hover:bg-accent/50`}`,children:[(0,Z.jsxs)(`button`,{onClick:()=>j(t),className:`w-full text-left`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-1.5 font-medium`,children:[n?(0,Z.jsx)(Ne,{className:`h-3 w-3 shrink-0`}):(0,Z.jsx)(B,{className:`h-3 w-3 shrink-0`}),t.address]}),(0,Z.jsx)(`span`,{className:`shrink-0 ${t.status===`error`?`text-destructive`:`text-muted-foreground`}`,children:t.status})]}),(0,Z.jsxs)(`div`,{className:`pl-[18px] text-muted-foreground`,children:[String(t.config?.host||``),` · `,(t.containers||[]).length,` folder(s)`]}),t.lastError&&(0,Z.jsxs)(`div`,{className:`pl-[18px] text-destructive`,children:[`error: `,t.lastError]})]}),n&&(0,Z.jsxs)(`div`,{className:`mt-2 space-y-3 border-t pt-2`,children:[(0,Z.jsx)(`div`,{className:`space-y-0.5`,children:(t.containers||[]).map(n=>(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded bg-background/60 px-2 py-1`,children:[(0,Z.jsx)(`span`,{className:`font-mono truncate`,children:n.name}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 shrink-0`,children:[(0,Z.jsx)(`button`,{title:`Sync folder`,className:`p-1 hover:bg-accent rounded`,onClick:()=>L(t.address,n.name),disabled:!!b,children:b===`folder-sync:${t.address}:${n.name}`?(0,Z.jsx)(Wn,{className:`h-3 w-3 animate-spin`}):(0,Z.jsx)(M,{className:`h-3 w-3`})}),(0,Z.jsx)(`button`,{title:`Remove folder`,className:`p-1 hover:bg-destructive/10 text-destructive rounded`,onClick:()=>Rr(e,`imap`,t.address,n.name).then(E).catch(e=>S({title:`Error`,description:e instanceof Error?e.message:`Failed to remove folder`,variant:`destructive`})),disabled:!!b,children:(0,Z.jsx)(lt,{className:`h-3 w-3`})})]})]},n.name))}),re,(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsxs)(J,{size:`sm`,onClick:I,disabled:v,children:[v?(0,Z.jsx)(Wn,{className:`h-3 w-3 animate-spin`}):(0,Z.jsx)(Re,{className:`h-3 w-3`}),` Save`]}),(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,disabled:!!b,onClick:()=>ne(`test`,t.address),children:[b===`test:${t.address}`?(0,Z.jsx)(Wn,{className:`h-3 w-3 animate-spin`}):(0,Z.jsx)(vt,{className:`h-3 w-3`}),` Test`]}),(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,disabled:!!b,onClick:()=>ne(`sync`,t.address),children:[b===`sync:${t.address}`?(0,Z.jsx)(Wn,{className:`h-3 w-3 animate-spin`}):(0,Z.jsx)(M,{className:`h-3 w-3`}),` Sync all`]}),(0,Z.jsxs)(J,{size:`sm`,variant:`destructive`,disabled:!!b,onClick:te,children:[b===`delete:${t.address}`?(0,Z.jsx)(Wn,{className:`h-3 w-3 animate-spin`}):(0,Z.jsx)(lt,{className:`h-3 w-3`}),` Delete`]})]})]})]},t.address)})})}),o&&(0,Z.jsxs)(`div`,{className:`space-y-3 rounded-md border p-3`,children:[(0,Z.jsx)(`h5`,{className:`text-xs font-medium`,children:`New IMAP account`}),re,(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsxs)(J,{size:`sm`,onClick:I,disabled:v,children:[v?(0,Z.jsx)(Wn,{className:`h-3 w-3 animate-spin`}):(0,Z.jsx)(Re,{className:`h-3 w-3`}),` Save`]}),(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,onClick:A,children:`Cancel`})]})]})]})}function F$({workspaceId:e}){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(``),[l,u]=(0,X.useState)([`read`]),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)(!0),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(new Set),[y,b]=(0,X.useState)(``),[x,S]=(0,X.useState)(!1),{showToast:C}=oo(),[w,T]=(0,X.useState)(e);e!==w&&(T(e),i(!0));let E=(0,X.useCallback)(()=>Y.get(`/workspaces/${e}/tokens`).then(e=>{n((e||[]).map(e=>({...e,hash:e.hash||e.tokenHash||``})).filter(e=>e.hash))}).catch(()=>{C({title:`Error`,description:`Failed to load workspace tokens`,variant:`destructive`})}).finally(()=>{i(!1)}),[e,C]);(0,X.useEffect)(()=>{E()},[E]);let D=async()=>{if(!s.trim()){C({title:`Error`,description:`Token description is required`,variant:`destructive`});return}try{o(!0);let t=null;if(!p&&d){let e=new Date(d);e.setHours(23,59,59,999),t=e.toISOString()}let n={description:s,permissions:l,expiresAt:t},r=await Y.post(`/workspaces/${e}/tokens`,n);r&&r.token&&b(r.token),c(``),u([`read`]),f(``),m(!0),g(!1),i(!0),await E(),C({title:`Success`,description:`Workspace sharing token created successfully`,variant:`default`})}catch{C({title:`Error`,description:`Failed to create token`,variant:`destructive`})}finally{o(!1)}},O=async t=>{try{await Y.delete(`/workspaces/${e}/tokens/${t}`),C({title:`Success`,description:`Token revoked successfully`}),i(!0),await E()}catch{C({title:`Error`,description:`Failed to revoke token`,variant:`destructive`})}},k=e=>{let t=new Set(_);t.has(e)?t.delete(e):t.add(e),v(t)},A=e=>_.has(e)?e:`${e.substring(0,8)}...${e.substring(e.length-8)}`,j=async e=>{try{await navigator.clipboard.writeText(e),C({title:`Copied`,description:`Token hash copied to clipboard`})}catch{C({title:`Error`,description:`Failed to copy to clipboard`,variant:`destructive`})}};return(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsx)(`h3`,{className:`text-lg font-medium`,children:`Workspace Sharing Tokens`}),(0,Z.jsxs)(J,{onClick:()=>g(!h),size:`sm`,variant:`outline`,children:[(0,Z.jsx)(nn,{className:`mr-2 h-4 w-4`}),`Create Token`]})]}),h&&(0,Z.jsxs)(`div`,{className:`border rounded-lg p-4 space-y-4 bg-muted/50`,children:[(0,Z.jsx)(q,{placeholder:`Token description (e.g., 'John's laptop')`,value:s,onChange:e=>c(e.target.value)}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-sm font-medium mb-2 block`,children:`Permissions`}),(0,Z.jsx)(`div`,{className:`flex gap-2 flex-wrap`,children:[`read`,`write`,`admin`].map(e=>(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:l.includes(e),onChange:t=>{t.target.checked?u([...l,e]):u(l.filter(t=>t!==e))}}),(0,Z.jsx)(`span`,{className:`text-sm`,children:e})]},e))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-sm font-medium mb-2 block`,children:`Token Expiry`}),(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:p,onChange:e=>{m(e.target.checked),e.target.checked&&f(``)}}),(0,Z.jsx)(`span`,{className:`text-sm`,children:`Never expires`})]}),!p&&(0,Z.jsx)(q,{type:`date`,placeholder:`Expiry date`,value:d,onChange:e=>f(e.target.value),min:new Date().toISOString().split(`T`)[0]})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(J,{onClick:D,disabled:a,children:`Create Token`}),(0,Z.jsx)(J,{variant:`outline`,onClick:()=>g(!1),children:`Cancel`})]})]}),y&&(0,Z.jsxs)(`div`,{className:`p-4 border rounded-md bg-muted/50`,children:[(0,Z.jsxs)(`div`,{className:`flex justify-between items-center mb-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold`,children:`Your New Workspace Sharing Token`}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:async()=>{try{await navigator.clipboard.writeText(y),S(!0),C({title:`Success`,description:`Token copied to clipboard`}),setTimeout(()=>S(!1),2e3)}catch{C({title:`Error`,description:`Failed to copy token to clipboard`,variant:`destructive`})}},children:x?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(ur,{className:`mr-2 h-4 w-4`}),`Copied`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Ct,{className:`mr-2 h-4 w-4`}),`Copy`]})})]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mb-2`,children:`Make sure to copy your workspace sharing token now. You won't be able to see it again!`}),(0,Z.jsx)(`div`,{className:`p-2 bg-background border rounded font-mono text-sm break-all outline-none focus:ring-2 focus:ring-ring`,children:y}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,className:`mt-2`,onClick:()=>b(``),children:`Dismiss`})]}),(0,Z.jsx)(I$,{workspaceId:e}),r?(0,Z.jsxs)(`div`,{className:`text-center py-4`,children:[(0,Z.jsx)(`div`,{className:`animate-spin rounded-full h-6 w-6 border-b-2 border-primary mx-auto touch-target`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mt-2`,children:`Loading tokens...`})]}):t.length===0?(0,Z.jsxs)(`div`,{className:`text-center py-8 text-muted-foreground`,children:[(0,Z.jsx)(`p`,{children:`No sharing tokens created yet.`}),(0,Z.jsx)(`p`,{className:`text-sm`,children:`Create a token to share this workspace with others.`})]}):(0,Z.jsx)(`div`,{className:`space-y-3`,children:t.map(e=>(0,Z.jsxs)(`div`,{className:`border rounded-lg p-3 flex items-center justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 mb-1`,children:[(0,Z.jsx)(`span`,{className:`font-medium text-sm`,children:e.description}),(0,Z.jsx)(`span`,{className:`text-xs bg-muted px-2 py-1 rounded`,children:e.permissions.join(`, `)})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`span`,{className:`font-mono`,children:A(e.hash)}),(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,onClick:()=>k(e.hash),children:_.has(e.hash)?(0,Z.jsx)(ln,{className:`h-3 w-3`}):(0,Z.jsx)(Dt,{className:`h-3 w-3`})}),(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,onClick:()=>j(e.hash),children:(0,Z.jsx)(Ct,{className:`h-3 w-3`})})]}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[`Created: `,new Date(e.createdAt).toLocaleDateString(),e.expiresAt?(0,Z.jsxs)(`span`,{children:[` • Expires: `,new Date(e.expiresAt).toLocaleDateString()]}):(0,Z.jsx)(`span`,{children:` • Never expires`})]})]}),(0,Z.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>O(e.hash),className:`text-destructive hover:text-destructive`,children:(0,Z.jsx)(lt,{className:`h-4 w-4`})})]},e.hash))})]})}function I$({workspaceId:e}){let{showToast:t}=oo(),[n,r]=(0,X.useState)(``),[i,a]=(0,X.useState)([`read`]),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)([]),u=(0,X.useCallback)(()=>Y.get(`/workspaces/${e}/shares`).then(e=>l(Array.isArray(e)?e:e?.emailShares||[])).catch(()=>{}),[e]);(0,X.useEffect)(()=>{u()},[u]);let d=async()=>{if(n.trim())try{s(!0),await Y.post(`/workspaces/${e}/shares`,{userEmail:n.trim(),permissions:i}),r(``),a([`read`]),await u(),t({title:`Success`,description:`Access granted`})}catch(e){t({title:`Error`,description:e instanceof Error?e.message:`Failed to grant access`,variant:`destructive`})}finally{s(!1)}},f=async n=>{try{await Y.delete(`/workspaces/${e}/shares/${encodeURIComponent(n)}`),await u(),t({title:`Success`,description:`Access revoked`})}catch(e){t({title:`Error`,description:e instanceof Error?e.message:`Failed to revoke`,variant:`destructive`})}};return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(`h4`,{className:`font-medium`,children:`Email-based Shares`}),(0,Z.jsxs)(`div`,{className:`flex gap-2 flex-wrap items-center`,children:[(0,Z.jsx)(q,{placeholder:`user@local.server`,value:n,onChange:e=>r(e.target.value),className:`max-w-xs`}),(0,Z.jsx)(`div`,{className:`flex gap-2`,children:[`read`,`write`,`admin`].map(e=>(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:i.includes(e),onChange:t=>{t.target.checked?a([...i,e]):a(i.filter(t=>t!==e))}}),e]},e))}),(0,Z.jsx)(J,{size:`sm`,onClick:d,disabled:o,children:`Add`})]}),c.length>0&&(0,Z.jsx)(`div`,{className:`space-y-2`,children:c.map(e=>(0,Z.jsxs)(`div`,{className:`flex items-center justify-between border rounded p-2`,children:[(0,Z.jsxs)(`div`,{className:`text-sm`,children:[(0,Z.jsx)(`div`,{className:`font-medium`,children:e.userEmail}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[e.permissions.join(`, `),e.grantedAt?` • ${new Date(e.grantedAt).toLocaleDateString()}`:``]})]}),(0,Z.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>f(e.userEmail),className:`text-destructive hover:text-destructive`,children:`Revoke`})]},e.userEmail))})]})}var L$=[{value:`read`,label:`Read`,hint:`Browse and search`},{value:`write`,label:`Read & write`,hint:`Add, edit and organise documents`},{value:`admin`,label:`Admin`,hint:`Everything except sharing and deleting`}],R$=e=>e.includes(`admin`)?`admin`:e.includes(`write`)?`write`:`read`;function z$({workspaceId:e}){let{showToast:t}=oo(),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(!0),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(`user`),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(`read`),[m,h]=(0,X.useState)(e);e!==m&&(h(e),a(!0));let g=(0,X.useCallback)(()=>Mi(e).then(r).catch(()=>r(null)).finally(()=>a(!1)),[e]);(0,X.useEffect)(()=>{g()},[g]);let _=n?.isOwner===!0,v=n?.members??[],y=async n=>{n.preventDefault();let r=u.trim();if(r){s(`grant`);try{let n=await Qi(e,c===`user`?{email:r}:{group:r},[f]);d(``),await g();let i=c===`user`?r:`group ${r}`;t({title:`Shared`,description:n.type===`user`&&n.userExists===!1?`${i} has no account here yet — the share applies as soon as they sign in.`:`Access granted to ${i}.`})}catch(e){t({title:`Could not share`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{s(null)}}},b=async(n,r)=>{let i=`${n.type}:${n.principal}`;s(i);try{await Hi(e,n.type,n.principal,[r]),await g()}catch(e){t({title:`Could not update`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{s(null)}},x=async n=>{let r=`${n.type}:${n.principal}`;s(r);try{await ba(e,n.type,n.principal),await g(),t({title:`Access revoked`,description:`${n.principal} no longer has access.`})}catch(e){t({title:`Could not revoke`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{s(null)}};return n&&n.shareable===!1?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Your universe workspace is private and cannot be shared.`}):(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:_?`People and groups who can open this workspace.`:`You are a member of this workspace; only its owner can change the list.`}),(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{a(!0),g()},disabled:i,children:[(0,Z.jsx)(M,{className:K(`mr-2 h-3.5 w-3.5`,i&&`animate-spin`)}),`Refresh`]})]}),i?(0,Z.jsx)(`div`,{className:`rounded-md border p-4 text-sm text-muted-foreground`,children:`Loading members…`}):v.length===0?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Not shared with anyone.`}):v.map(e=>{let t=`${e.type}:${e.principal}`,n=R$(e.permissions);return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-md border p-3 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-start gap-2`,children:[e.type===`group`?(0,Z.jsx)(Ue,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}):(0,Z.jsx)(Ze,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-medium`,title:e.principal,children:e.principal}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[e.type===`group`?`Group`:`User`,e.description?` · ${e.description}`:``,e.grantedAt?` · since ${new Date(e.grantedAt).toLocaleDateString()}`:``]}),e.type===`user`&&e.userExists===!1&&(0,Z.jsxs)(`div`,{className:`mt-1 flex items-center gap-1 text-[11px] text-warning`,children:[(0,Z.jsx)(be,{className:`h-3 w-3`}),` No account yet — applies at first sign-in`]})]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[_?(0,Z.jsx)(`select`,{value:n,disabled:o===t,onChange:t=>b(e,t.target.value),className:`rounded-md border border-input bg-background px-2 py-1 text-xs focus:outline-none focus:ring-2 focus:ring-ring`,title:`Access level`,children:L$.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))}):(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs`,children:L$.find(e=>e.value===n)?.label}),_&&(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,className:`text-destructive hover:text-destructive`,disabled:o===t,onClick:()=>x(e),title:`Revoke access`,children:(0,Z.jsx)(pe,{className:`h-3.5 w-3.5`})})]})]},t)})]}),_&&(0,Z.jsxs)(`form`,{onSubmit:y,className:`space-y-3 rounded-md border p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-sm font-medium`,children:[`Share with`,(0,Z.jsx)(`div`,{className:`inline-flex overflow-hidden rounded-md border`,children:[`user`,`group`].map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>l(e),className:K(`px-3 py-1 text-xs`,c===e?`bg-primary text-primary-foreground`:`bg-background text-muted-foreground hover:bg-muted`),children:e===`user`?`a person`:`a group`},e))})]}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-[1fr_auto]`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(q,{type:c===`user`?`email`:`text`,value:u,onChange:e=>d(e.target.value),placeholder:c===`user`?`colleague@corp.tld`:`team-a or cn=team-a,ou=groups,dc=corp,dc=tld`,autoComplete:`off`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:c===`user`?`The share is keyed by e-mail: it works even before the person signs in for the first time.`:`Directory group (LDAP/AD memberOf — full DN or just the CN) or a group an admin assigned to local accounts.`})]}),(0,Z.jsx)(`div`,{children:(0,Z.jsx)(`select`,{value:f,onChange:e=>p(e.target.value),className:`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`,title:L$.find(e=>e.value===f)?.hint,children:L$.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))})})]}),(0,Z.jsx)(J,{type:`submit`,size:`sm`,disabled:o===`grant`||!u.trim(),children:o===`grant`?`Sharing…`:`Share workspace`})]})]})}function B$({workspaceId:e,workspaceName:t,isActive:n,onChanged:r}){let{showToast:i}=oo(),[a,o]=(0,X.useState)([]),[s,c]=(0,X.useState)(!0),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(null),[y,b]=(0,X.useState)(null),[x,S]=(0,X.useState)(``),C=(0,X.useRef)(null),w=(0,X.useCallback)(async()=>{try{o(n?await Ei(e):[])}catch{o([])}finally{c(!1)}},[e,n]);(0,X.useEffect)(()=>{w()},[w]);let T=async()=>{if(!(n&&!window.confirm(`'${t}' is running. It has to be stopped to be exported — its index is only consistent on disk once it has flushed.\n\nStop it and export now?`))){u(!0);try{let t=await Lr(e,{stop:!0});f(t.stoppedWorkspace),i({title:`Workspace exported`,description:`${t.name} — ${mi(t.size)}`}),await w(),t.stoppedWorkspace&&r?.()}catch(e){i({title:`Export failed`,description:e instanceof Error?e.message:`Failed to export workspace`,variant:`destructive`})}finally{u(!1)}}},E=async()=>{m(!0);try{await ii(e),f(!1),i({title:`Workspace started`,description:`'${t}' is running again.`}),r?.()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to start workspace`,variant:`destructive`})}finally{m(!1)}},D=async e=>{g(e.name);try{await Jr(e.name)}catch(e){i({title:`Download failed`,description:e instanceof Error?e.message:`Failed to download archive`,variant:`destructive`})}finally{g(null)}},O=async e=>{if(window.confirm(`Delete ${e.name}? The archive is removed from the server; any copy you already downloaded is untouched.`)){g(e.name);try{await ui(e.name),await w()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete archive`,variant:`destructive`})}finally{g(null)}}},k=async e=>{b(`uploading`),v(0),S(``);try{let t=await ha(e,e=>{v(Math.round(e*100)),e>=1&&b(`server`)},e=>S(ua[e.phase]||e.phase));i({title:`Workspace imported`,description:`'${t.label||t.name}' was extracted, validated and loaded.`}),r?.(),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){i({title:`Import failed`,description:e instanceof Error?e.message:`Failed to import workspace`,variant:`destructive`})}finally{b(null),v(null),S(``),C.current&&(C.current.value=``)}},A=y!==null;return(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(Ke,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Export & Import`})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Export packs this workspace into a single compressed archive you can download and move elsewhere. The workspace is stopped first — an export of a running workspace would capture a half-written index.`}),(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2`,children:[(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:l||A,onClick:T,children:[(0,Z.jsx)(Ke,{className:`mr-2 h-3.5 w-3.5 ${l?`animate-pulse`:``}`}),l?`Exporting…`:`Export Workspace`]}),(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:s||l,onClick:()=>void w(),children:[(0,Z.jsx)(M,{className:`mr-2 h-3.5 w-3.5 ${s?`animate-spin`:``}`}),`Refresh`]}),d&&(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:p,onClick:E,children:p?`Starting…`:`Start workspace again`})]}),(0,Z.jsxs)(`div`,{className:`mt-4 border-t pt-3`,children:[(0,Z.jsx)(`h3`,{className:`text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Archives`}),s?(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`Loading…`}):a.length===0?(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`No exports yet.`}):(0,Z.jsx)(`ul`,{className:`mt-2 space-y-2`,children:a.map(e=>(0,Z.jsxs)(`li`,{className:`flex flex-col gap-2 rounded-md border p-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate font-mono text-xs`,children:e.name}),(0,Z.jsxs)(`div`,{className:`mt-0.5 text-[11px] text-muted-foreground`,children:[mi(e.size),` · `,new Date(e.createdAt).toLocaleString()]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:h===e.name,onClick:()=>D(e),title:`Download (${mi(e.size)})`,children:(0,Z.jsx)(wn,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:h===e.name,onClick:()=>O(e),className:`text-destructive hover:text-destructive`,title:`Delete archive`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})]},e.name))})]}),(0,Z.jsxs)(`div`,{className:`mt-4 border-t pt-3`,children:[(0,Z.jsx)(`h3`,{className:`text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Import`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Pick a workspace archive from your local drive. It is uploaded into your home, extracted into your Workspaces folder, validated and loaded as a new workspace.`}),(0,Z.jsx)(`input`,{ref:C,type:`file`,accept:`.tar.gz,.tgz,.tar.bz2,.tbz2,.tbz,application/gzip,application/x-bzip2`,className:`hidden`,onChange:e=>{let t=e.target.files?.[0];t&&k(t)}}),(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-3`,children:[(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:A||l,onClick:()=>C.current?.click(),children:[(0,Z.jsx)(ne,{className:`mr-2 h-3.5 w-3.5`}),`Import from local drive…`]}),y===`uploading`&&(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[`Uploading… `,_,`%`]}),y===`server`&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:x||`Extracting, validating and loading…`})]})]})]})}var V$={"workspace:home":{title:`Workspace Home`,description:`User-managed roaming home folder, exported through WebDAV and watched for changes. Mirrored into the backends tree.`},"workspace:data":{title:`Workspace Data`,description:`Managed content-addressable blob store (deduped, checksum-keyed). Opaque by design: the tree is the navigation; not meant for direct edits or export.`},s3:{title:`S3`,description:`Remote object storage. Placeholder until Stored gets a real S3 driver.`},imap:{title:`IMAP`,description:`Mailbox data source; ingested mail lands in the backends tree.`}},H$=[{id:`git`,title:`Git`,description:`Git-backed dotfile access.`},{id:`webdav`,title:`WebDAV`,description:`Mountable access to the workspace home backend.`},{id:`imapSync`,title:`IMAP Sync Worker`,description:`Background mailbox polling and ingestion.`}];function U$({checked:e,disabled:t,onClick:n}){return(0,Z.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":e,disabled:t,onClick:n,className:`relative inline-flex h-5 w-9 shrink-0 rounded-full border-2 border-transparent transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${e?`bg-primary`:`bg-muted-foreground/30`}`,children:(0,Z.jsx)(`span`,{className:`pointer-events-none inline-block h-4 w-4 rounded-full bg-background shadow transition-transform ${e?`translate-x-4`:`translate-x-0`}`})})}function W$({workspaceId:e,onAdded:t}){let[n,r]=(0,X.useState)(!1),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(!1),{showToast:m}=oo(),h=()=>{a(``),s(``),l(!1),d(!1)};return n?(0,Z.jsxs)(`form`,{onSubmit:async n=>{if(n.preventDefault(),!(!i.trim()||!o.trim())){p(!0);try{await Xi(e,`file`,{name:i.trim(),path:o.trim(),watch:c,readOnly:u}),m({title:`Added`,description:`${i.trim()} mounted; initial scan running in the background`}),h(),r(!1),await t()}catch(e){m({title:`Error`,description:e instanceof Error?e.message:`Failed to add folder backend`,variant:`destructive`})}finally{p(!1)}}},className:`w-full space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(ot,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Add local folder`})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Index a folder on the server host as a data source. Files stay in place; the index records them as device-scoped locations, so they remain addressable if the workspace moves to another server.`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Name`}),(0,Z.jsx)(q,{value:i,onChange:e=>a(e.target.value),placeholder:`Financial Reports`,required:!0})]}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Absolute path on server`}),(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`/mnt/data/reports`,required:!0,className:`font-mono`})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-6 text-[11px] text-muted-foreground`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5`,children:[`watch`,(0,Z.jsx)(U$,{checked:c,onClick:()=>l(e=>!e)})]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5`,title:`Never delete bytes in this folder. Destroy degrades to a reference drop. Recommended for folders managed outside Canvas.`,children:[`read-only`,(0,Z.jsx)(U$,{checked:u,onClick:()=>d(e=>!e)})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(J,{type:`submit`,size:`sm`,disabled:f||!i.trim()||!o.trim(),children:f?`Adding…`:`Add folder`}),(0,Z.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,disabled:f,onClick:()=>{h(),r(!1)},children:`Cancel`})]})]}):(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>r(!0),children:[(0,Z.jsx)(ot,{className:`mr-2 h-3.5 w-3.5`}),`Add local folder`]})}function G$({workspaceId:e,onAdded:t}){let[n,r]=(0,X.useState)(!1),[i,a]=(0,X.useState)({name:``,clientId:``,clientSecret:``,refreshToken:``,folderId:``}),[o,s]=(0,X.useState)(!1),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(!1),{showToast:p}=oo(),m=e=>t=>a(n=>({...n,[e]:t.target.value})),h=()=>{a({name:``,clientId:``,clientSecret:``,refreshToken:``,folderId:``}),s(!1),u(!1)},g=i.name.trim()&&i.clientId.trim()&&i.clientSecret.trim()&&i.refreshToken.trim();return n?(0,Z.jsxs)(`form`,{onSubmit:async n=>{if(n.preventDefault(),g){f(!0);try{await Xi(e,`gdrive`,{name:i.name.trim(),clientId:i.clientId.trim(),clientSecret:i.clientSecret.trim(),refreshToken:i.refreshToken.trim(),folderId:i.folderId.trim()||`root`,watch:o,readOnly:l}),p({title:`Added`,description:`${i.name.trim()} connected; initial scan running in the background`}),h(),r(!1),await t()}catch(e){p({title:`Error`,description:e instanceof Error?e.message:`Failed to add Google Drive backend`,variant:`destructive`})}finally{f(!1)}}},className:`w-full space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(c,{icon:`mdi:google-drive`,width:16,height:16,className:`text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Add Google Drive`})]}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Index a Drive folder (or the whole My Drive) as a remote data source. Files are hashed from Drive metadata, uploads are queued through the workspace cache. Needs an OAuth client with the `,(0,Z.jsx)(`code`,{children:`drive`}),` scope and an offline-access refresh token — the same kind of credentials as the Google Calendar connector.`]}),(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Name`}),(0,Z.jsx)(q,{value:i.name,onChange:m(`name`),placeholder:`Work Drive`,required:!0})]}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Folder id (empty = My Drive root)`}),(0,Z.jsx)(q,{value:i.folderId,onChange:m(`folderId`),placeholder:`1AbC…`,className:`font-mono`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`OAuth client id`}),(0,Z.jsx)(q,{value:i.clientId,onChange:m(`clientId`),required:!0,className:`font-mono`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`OAuth client secret`}),(0,Z.jsx)(q,{type:`password`,value:i.clientSecret,onChange:m(`clientSecret`),required:!0,className:`font-mono`,autoComplete:`off`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1 sm:col-span-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Refresh token`}),(0,Z.jsx)(q,{type:`password`,value:i.refreshToken,onChange:m(`refreshToken`),required:!0,className:`font-mono`,autoComplete:`off`})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-6 text-[11px] text-muted-foreground`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5`,title:`Poll the Drive changes feed (every 60s) so edits made in Drive show up without a manual re-sync.`,children:[`watch`,(0,Z.jsx)(U$,{checked:o,onClick:()=>s(e=>!e)})]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5`,title:`Never delete files in this Drive. Destroy degrades to a reference drop.`,children:[`read-only`,(0,Z.jsx)(U$,{checked:l,onClick:()=>u(e=>!e)})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(J,{type:`submit`,size:`sm`,disabled:d||!g,children:d?`Checking…`:`Add Drive`}),(0,Z.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,disabled:d,onClick:()=>{h(),r(!1)},children:`Cancel`})]})]}):(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>r(!0),children:[(0,Z.jsx)(c,{icon:`mdi:google-drive`,width:14,height:14,className:`mr-2`}),`Add Google Drive`]})}function K$({workspaceId:e,backend:t}){let[n,r]=(0,X.useState)(t.usage??null),[i,a]=(0,X.useState)(!1),{showToast:o}=oo();return(0,Z.jsxs)(`button`,{type:`button`,onClick:async()=>{a(!0);try{r(await Fr(e,t.driver,t.address))}catch(e){o({title:`Error`,description:e instanceof Error?e.message:`Failed to compute size`,variant:`destructive`})}finally{a(!1)}},disabled:i,className:`flex items-center gap-1.5 rounded border px-2 py-1 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50`,title:n?`Computed ${new Date(n.computedAt).toLocaleString()}; click to refresh`:`Compute on-disk size (walks the backend folder; may take a while)`,children:[(0,Z.jsx)(_e,{className:`h-3 w-3 ${i?`animate-pulse`:``}`}),i?`Calculating…`:n?mi(n.bytes):`Size`]})}function q$({workspaceId:e}){let[t,n]=(0,X.useState)(!1),{showToast:r}=oo();return(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:t,onClick:async()=>{n(!0);try{let{removed:t}=await Vi(e);r({title:`Thumbnail cache cleared`,description:`${t} cached thumbnail(s) removed`})}catch(e){r({title:`Error`,description:e instanceof Error?e.message:`Failed to clear thumbnail cache`,variant:`destructive`})}finally{n(!1)}},title:`Remove all cached thumbnails; they regenerate on demand`,children:[(0,Z.jsx)(lt,{className:`mr-2 h-3.5 w-3.5 ${t?`animate-pulse`:``}`}),t?`Clearing…`:`Clear thumbnails`]})}function J$({workspaceId:e}){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!1),{showToast:a}=oo();return(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(_e,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Disk usage`})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Total on-disk size of this workspace (index, blobs, home, cache): what an export or sync would move. Computed on demand; may take a while on large workspaces.`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3`,children:[t&&(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:mi(t.bytes)}),(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:r,onClick:async()=>{i(!0);try{n(await ri(e))}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to compute workspace size`,variant:`destructive`})}finally{i(!1)}},children:[(0,Z.jsx)(M,{className:`mr-2 h-3.5 w-3.5 ${r?`animate-spin`:``}`}),r?`Calculating…`:t?`Recalculate`:`Calculate size`]})]})]}),t&&(0,Z.jsx)(`div`,{className:`mt-3 grid grid-cols-2 gap-x-6 gap-y-1 border-t pt-3 sm:grid-cols-3`,children:Object.entries(t.breakdown).sort(([,e],[,t])=>t-e).map(([e,t])=>(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs`,children:[(0,Z.jsx)(`span`,{className:`truncate font-mono text-muted-foreground`,children:e}),(0,Z.jsx)(`span`,{children:mi(t)})]},e))})]})}function Y$({backend:e,busy:t,onSave:n}){let r=e.config||{},i=Array.isArray(r.exclude)?r.exclude:[],a=Array.isArray(r.effectiveExclusions)?r.effectiveExclusions:[],o=Math.max(a.length-i.length,0),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(i.join(`
|
|
79
|
+
`)),[d,f]=(0,X.useState)(!1),p=i.join(`
|
|
80
|
+
`),[m,h]=(0,X.useState)(p);return m!==p&&(h(p),u(p)),(0,Z.jsxs)(`div`,{className:`mt-3 border-t pt-3`,children:[(0,Z.jsxs)(`button`,{type:`button`,className:`text-[11px] font-medium text-muted-foreground hover:text-foreground`,onClick:()=>c(!s),children:[`Sync exclusions `,i.length>0?`(${i.length} custom`:`(defaults only`,o>0?`, ${o} default)`:`)`,` `,s?`▾`:`▸`]}),s&&(0,Z.jsxs)(`div`,{className:`mt-2 space-y-2`,children:[(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`One glob pattern per line, e.g. `,(0,Z.jsx)(`code`,{className:`font-mono`,children:`**/node_modules/**`}),` or `,(0,Z.jsx)(`code`,{className:`font-mono`,children:`**/target/**`}),`. Defaults (dotfiles, node_modules, __pycache__, caches, …) always apply. Changes take effect immediately for the watcher; run Re-sync to also unlink already-mirrored entries.`]}),(0,Z.jsx)(`textarea`,{className:`w-full min-h-[80px] rounded-md border bg-background p-2 font-mono text-xs`,value:l,onChange:e=>u(e.target.value),placeholder:`**/node_modules/**
|
|
81
|
+
**/dist/**`,spellCheck:!1}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(J,{type:`button`,size:`sm`,disabled:t||l.split(`
|
|
82
|
+
`).map(e=>e.trim()).filter(Boolean).join(`
|
|
83
|
+
`)===i.join(`
|
|
84
|
+
`),onClick:()=>n(l.split(`
|
|
85
|
+
`).map(e=>e.trim()).filter(Boolean)),children:`Save exclusions`}),o>0&&(0,Z.jsxs)(`button`,{type:`button`,className:`text-[11px] text-muted-foreground hover:text-foreground`,onClick:()=>f(!d),children:[d?`Hide`:`Show`,` default patterns`]})]}),d&&(0,Z.jsx)(`pre`,{className:`max-h-40 overflow-auto rounded-md bg-muted/50 p-2 font-mono text-[11px] text-muted-foreground`,children:a.filter(e=>!i.includes(e)).join(`
|
|
86
|
+
`)})]})]})}function X$({device:e,linked:t,busy:n,onLink:r,onUnlink:i,onUpdate:a}){let[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(e.name),[u,d]=(0,X.useState)(e.description??``),f=()=>{c.trim()&&(c!==e.name||u!==(e.description??``))&&a({name:c.trim(),description:u.trim()||void 0}),s(!1)},p=()=>{l(e.name),d(e.description??``),s(!1)};return(0,Z.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start gap-3 min-w-0`,children:[(0,Z.jsx)(kn,{className:`h-4 w-4 text-muted-foreground mt-0.5 shrink-0`}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[o?(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(q,{value:c,onChange:e=>l(e.target.value),className:`h-7 text-sm`,placeholder:`Device name`,autoFocus:!0,onKeyDown:e=>{e.key===`Enter`&&f(),e.key===`Escape`&&p()}}),(0,Z.jsx)(q,{value:u,onChange:e=>d(e.target.value),className:`h-7 text-xs`,placeholder:`Description (optional)`,onKeyDown:e=>{e.key===`Enter`&&f(),e.key===`Escape`&&p()}})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium`,children:e.name}),e.description&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground mt-0.5`,children:e.description})]}),(0,Z.jsxs)(`div`,{className:`mt-1.5 flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] text-muted-foreground font-mono`,children:[(0,Z.jsx)(`span`,{children:e.deviceId}),e.platform&&(0,Z.jsx)(`span`,{children:e.platform}),e.arch&&(0,Z.jsx)(`span`,{children:e.arch}),e.type&&(0,Z.jsx)(`span`,{children:e.type})]})]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[o?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:f,disabled:!c.trim(),children:(0,Z.jsx)(ur,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:p,children:(0,Z.jsx)(je,{className:`h-3.5 w-3.5`})})]}):(0,Z.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>s(!0),title:`Edit name/description`,children:(0,Z.jsx)(ye,{className:`h-3.5 w-3.5`})}),t?(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:n,onClick:i,className:`text-destructive hover:text-destructive`,title:`Remove from workspace`,children:(0,Z.jsx)(pe,{className:`h-3.5 w-3.5`})}):(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:n,onClick:r,title:`Link to workspace`,children:(0,Z.jsx)(qt,{className:`h-3.5 w-3.5`})}),t&&(0,Z.jsx)(`span`,{className:`rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-medium text-primary`,children:`linked`})]})]})})}function Z$({allDevices:e,linkedDevices:t,isLoading:n,deviceBusy:r,onRefresh:i,onLink:a,onUnlink:o,onUpdate:s}){let c=new Set(t.map(e=>e.deviceId));return n?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(M,{className:`h-4 w-4 animate-spin`}),`Loading devices…`]}):(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[c.size,` of `,e.length,` registered device`,e.length===1?``:`s`,` linked to this workspace.`]}),(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:i,disabled:n,children:[(0,Z.jsx)(M,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),e.length===0?(0,Z.jsxs)(`div`,{className:`rounded-md border p-4 text-sm text-muted-foreground`,children:[`No devices registered. Devices register themselves on first connection via `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`POST /auth/devices/register`}),`.`]}):(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.map(e=>(0,Z.jsx)(X$,{device:e,linked:c.has(e.deviceId),busy:r===e.deviceId,onLink:()=>a(e.deviceId),onUnlink:()=>o(e.deviceId),onUpdate:t=>s(e.deviceId,t)},e.deviceId))})]})}function Q$({label:e,value:t,mono:n=!1}){return(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-4 py-2 border-b last:border-0`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground shrink-0`,children:e}),(0,Z.jsx)(`span`,{className:`text-xs text-right ${n?`font-mono`:``}`,children:t??`—`})]})}function $$({workspaceName:e,current:t,weights:n,floorMode:r,relativeMargin:i,onDone:a}){let[o,s]=(0,X.useState)(t==null?``:String(t)),[c,l]=(0,X.useState)(r??`relative`),[u,d]=(0,X.useState)(i==null?`0.035`:String(i)),[f,p]=(0,X.useState)(n?.fts==null?`2`:String(n.fts)),[m,h]=(0,X.useState)(n?.dense==null?`1`:String(n.dense)),[g,_]=(0,X.useState)(n?.image==null?`2`:String(n.image)),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(null),[S,C]=(0,X.useState)(Lx);return(0,Z.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:`How photo relevance is decided`}),(0,Z.jsxs)(`select`,{value:c,onChange:e=>l(e.target.value),className:`h-8 rounded-md border border-input bg-transparent px-2 text-xs`,children:[(0,Z.jsx)(`option`,{value:`relative`,children:`Relative to the best match (recommended)`}),(0,Z.jsx)(`option`,{value:`absolute`,children:`Absolute distance cutoff`})]}),(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Photo-vs-text distances shift with every query and every model, so one fixed cutoff travels badly: a value tuned for one model keeps everything (or nothing) on the next. Relative anchors on the best match for THIS query and survives a re-embed.`})]}),c===`relative`&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:`Window width (distance from the best match)`}),(0,Z.jsx)(q,{value:u,onChange:e=>d(e.target.value),placeholder:`0.035`,className:`h-8 w-28 font-mono text-xs`,inputMode:`decimal`}),(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Wider keeps photos that match your query only partly, which is what a photo matching TWO things (a snowy window) looks like, since it sits further from each one than a pure example does. Too wide and everything gets in.`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:c===`relative`?`Hard ceiling (cosine distance, 0–2; blank = off)`:`Image relevance floor (cosine distance, 0–2; blank = off)`}),(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`0.95`,className:`h-8 w-28 font-mono text-xs`,inputMode:`decimal`}),(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:c===`relative`?`Nothing beyond this counts as a match however close it is to the best one. This is what lets a search of something you have no photos of come back empty. Without it, a relative window always returns its nearest photo.`:`Lower = stricter (fewer, more-relevant photos); raise if relevant photos are missing.`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:`Hybrid fusion weights (0 disables a signal)`}),(0,Z.jsx)(`div`,{className:`flex flex-wrap items-end gap-x-3 gap-y-2`,children:[[`lexical`,f,p],[`text semantic`,m,h],[`image`,g,_]].map(([e,t,n])=>(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`span`,{className:`block text-[11px] text-muted-foreground`,children:e}),(0,Z.jsx)(q,{value:t,onChange:e=>n(e.target.value),className:`h-8 w-16 font-mono text-xs`,inputMode:`decimal`})]},e))}),(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Ranking mix: lexical (filenames/content) · text semantics · photo matches. Equal lexical/image ranks a matching photo like a matching document.`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(J,{size:`sm`,variant:`outline`,onClick:async()=>{y(!0),x(null);try{let t=o.trim(),n=t===``?null:Number(t);if(n!==null&&!Number.isFinite(n)){x(`Enter a number (e.g. 0.95) or leave empty`);return}let r={fts:Number(f),dense:Number(m),image:Number(g)};if(Object.values(r).some(e=>!Number.isFinite(e)||e<0)){x(`Weights must be numbers ≥ 0`);return}let i=Number(u.trim());if(c===`relative`&&(!Number.isFinite(i)||i<=0)){x(`Window width must be a positive number (e.g. 0.035)`);return}await Ci(e,{imageMaxDistance:n,imageFloorMode:c,...c===`relative`?{imageRelativeMargin:i}:{},searchWeights:r}),x(`Saved`),a()}catch(e){x(e instanceof Error?e.message:`Failed to save`)}finally{y(!1)}},disabled:v,children:v?`Saving…`:`Save`}),b&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:b})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5 border-t border-border pt-3`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:S,onChange:e=>{Rx(e.target.checked),C(e.target.checked)}}),(0,Z.jsx)(`span`,{children:`Debug query`})]}),(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Attaches the raw (unfloored) image distances to each search and shows them above the document list: the numbers this floor should be picked from. Local to this browser; costs a little extra work per query, so leave it off day to day.`})]})]})}function e1({stats:e,isLoading:t,onRefresh:n,workspaceName:r}){return t?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(M,{className:`h-4 w-4 animate-spin`}),`Loading stats…`]}):(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Live snapshot from synapsd. Click refresh for updated counts.`}),(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:n,disabled:t,children:[(0,Z.jsx)(M,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),(0,Z.jsx)(r1,{workspaceName:r,vectorSpaces:Object.keys(e?.semantic?.vectorSpaces||{}),onDone:n}),e?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,Z.jsx)(Jt,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Core Index`})]}),(0,Z.jsx)(Q$,{label:`Backend`,value:e.dbBackend,mono:!0}),(0,Z.jsx)(Q$,{label:`Status`,value:e.status}),(0,Z.jsx)(Q$,{label:`Path`,value:e.dbPath,mono:!0}),(0,Z.jsx)(Q$,{label:`Documents`,value:e.documentCount?.toLocaleString()}),(0,Z.jsx)(Q$,{label:`Metadata entries`,value:e.metadataCount?.toLocaleString()}),(0,Z.jsx)(Q$,{label:`Checksum index`,value:e.checksumIndexSize?.toLocaleString()}),(0,Z.jsx)(Q$,{label:`Bitmap store`,value:e.bitmapStoreSize?.toLocaleString()}),(0,Z.jsx)(Q$,{label:`Bitmap cache`,value:e.bitmapCacheSize?.toLocaleString()}),(0,Z.jsx)(Q$,{label:`Deleted (pending GC)`,value:e.deletedDocumentsCount?.toLocaleString()})]}),e.fts&&(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,Z.jsx)(At,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Full-Text Search (LanceDB)`})]}),`ready`in e.fts&&(0,Z.jsx)(Q$,{label:`Ready`,value:String(e.fts.ready)}),e.fts.rowCount!==void 0&&(0,Z.jsx)(Q$,{label:`Row count`,value:e.fts.rowCount?.toLocaleString()}),e.fts.error&&(0,Z.jsx)(Q$,{label:`Error`,value:(0,Z.jsx)(`span`,{className:`text-destructive`,children:e.fts.error})})]}),e.semantic&&(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,Z.jsx)(At,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Semantic / Vector Search`})]}),(0,Z.jsx)(Q$,{label:`Enabled`,value:String(e.semantic.enabled)}),e.semantic.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[e.inferd?.routing?Object.entries(e.inferd.routing).map(([e,t])=>(0,Z.jsx)(Q$,{label:`Embeds → ${e}`,value:(0,Z.jsx)(`span`,{className:`font-mono text-[11px]`,children:t.join(`, `)})},`route-${e}`)):(0,Z.jsx)(Q$,{label:`Text-embeddable (gap default)`,value:e.semantic.embeddableSchemas?.join(`, `)}),e.semantic.vectorSpaces&&Object.entries(e.semantic.vectorSpaces).map(([e,t])=>(0,Z.jsx)(Q$,{label:`Space: ${e} (${t.dim??`?`}-d)`,value:t.error?(0,Z.jsx)(`span`,{className:`text-destructive`,children:t.error}):`${(t.embeddedDocs??0).toLocaleString()} docs · ${(t.chunkRows??0).toLocaleString()} vectors`},e)),(0,Z.jsx)(Q$,{label:`Photo relevance`,value:e.semantic.imageFloorMode===`absolute`?`absolute cutoff`:`relative ±${e.semantic.imageRelativeMargin??.035}`,mono:!0}),(0,Z.jsx)(Q$,{label:e.semantic.imageFloorMode===`absolute`?`Image relevance floor`:`Hard ceiling`,value:e.semantic.imageMaxDistance==null?`off`:e.semantic.imageMaxDistance,mono:!0}),(0,Z.jsx)(Q$,{label:`Fusion weights (lexical · text · image)`,value:`${e.semantic.searchWeights?.fts??2} · ${e.semantic.searchWeights?.dense??1} · ${e.semantic.searchWeights?.image??2}`,mono:!0}),(0,Z.jsx)($$,{workspaceName:r,current:e.semantic.imageMaxDistance,weights:e.semantic.searchWeights,floorMode:e.semantic.imageFloorMode,relativeMargin:e.semantic.imageRelativeMargin,onDone:n})]})]})]}):(0,Z.jsx)(`div`,{className:`rounded-md border p-4 text-sm text-muted-foreground`,children:`No stats available.`})]})}function t1(){let{workspaceName:e,tab:t}=Yc(),[n,r]=mu(),i=n.get(`section`),a=[`pending`,`rules`,`hooks`,`scripts`,`runs`].find(e=>e===i),o=n.get(`handler`)||void 0,s=n.get(`run`)||void 0,l=n.get(`addRuleKind`),u=n.get(`addRulePath`),d=n.get(`addRuleTarget`),f=n.get(`addRuleStoreTo`),p=n.get(`addRuleStoreFolder`),m=(0,X.useMemo)(()=>l===`store`||l===`download`?!u&&!f&&!p?null:{kind:l,path:u||``,storeTo:f||``,storeFolder:p||``}:u?{kind:`mirror`,path:u,target:d||`dir:/`}:null,[l,u,d,f,p]),h=(0,X.useCallback)(()=>{r(e=>{for(let t of[`addRuleKind`,`addRulePath`,`addRuleTarget`,`addRuleStoreTo`,`addRuleStoreFolder`])e.delete(t);return e},{replace:!0})},[r]),g=Gc(),{showToast:_}=oo(),v=Cm(),{openM2Drawer:y}=Eb(),b=EC(t);(0,X.useEffect)(()=>{t!==b&&g(`/workspaces/${e}/settings/${b}`,{replace:!0})},[t,b,e,g]);let[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(0),[T,E]=(0,X.useState)(!0),[D,O]=(0,X.useState)(!1),[k,A]=(0,X.useState)(!1),[j,N]=(0,X.useState)(``),[P,ee]=(0,X.useState)(``),[F,I]=(0,X.useState)(`#FFFFFF`),[te,ne]=(0,X.useState)(null),[L,re]=(0,X.useState)(null),[R,ie]=(0,X.useState)([]),[ae,oe]=(0,X.useState)(null),[z,se]=(0,X.useState)([]),[ce,B]=(0,X.useState)(null),[V,le]=(0,X.useState)(null),[ue,de]=(0,X.useState)(!1),[fe,me]=(0,X.useState)([]),[H,he]=(0,X.useState)([]),[ge,_e]=(0,X.useState)(!1),[ve,ye]=(0,X.useState)(null),U=e||x?.id||``,be=(0,X.useRef)(U);(0,X.useEffect)(()=>{be.current=U});let xe=(0,X.useCallback)(async e=>{let t=e??be.current;if(t)try{let e=await li(t);ie(e.publicCanvasShares)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to load shares`,variant:`destructive`})}},[_]),Se=(0,X.useCallback)(async e=>{let t=e??be.current;if(t){de(!0);try{let e=await Si(t);le(e)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to load DB stats`,variant:`destructive`})}finally{de(!1)}}},[_]),Ce=(0,X.useCallback)(async e=>{let t=e??be.current;if(t){_e(!0);try{let[e,n]=await Promise.all([gC(),yC(t)]);me(e),he(n)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to load devices`,variant:`destructive`})}finally{_e(!1)}}},[_]),W=async e=>{ye(e);try{await bC(U,e),await Ce(),_({title:`Linked`,description:`Device linked to workspace`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to link device`,variant:`destructive`})}finally{ye(null)}},G=async e=>{ye(e);try{await xC(U,e),he(t=>t.filter(t=>t.deviceId!==e)),_({title:`Unlinked`,description:`Device removed from workspace`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to unlink device`,variant:`destructive`})}finally{ye(null)}},we=async(e,t)=>{ye(`edit:${e}`);try{let n=await _C(e,t);me(t=>t.map(t=>t.deviceId===e?{...t,...n}:t)),_({title:`Saved`,description:`Device updated`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to update device`,variant:`destructive`})}finally{ye(null)}},Te=(0,X.useCallback)(async e=>{let t=e??be.current;if(!t)return;let[n,r]=await Promise.all([fa(t).catch(()=>null),va(t).catch(()=>[])]);oe(n),se(r.filter(e=>e.kind===`storage`))},[]),Ee=z.some(e=>e.resyncing);(0,X.useEffect)(()=>{if(!Ee||!U)return;let e=setInterval(()=>{Te()},4e3);return()=>clearInterval(e)},[Ee,U,Te]),(0,X.useEffect)(()=>{async function t(){try{let t=(await Or()).find(t=>t.name===e||t.id===e);t&&(S(t),N(t.label||``),ee(t.description||``),I(t.color||`#FFFFFF`),ne(t.icon??null),t.status===`active`&&await Promise.all([xe(e||t.id),Te(e||t.id)]))}catch{_({title:`Error`,description:`Failed to load workspace`,variant:`destructive`})}finally{E(!1)}}t()},[e,xe,Te,_,C]),(0,X.useEffect)(()=>{let e=()=>w(e=>e+1);return window.addEventListener(`workspaces:refresh`,e),()=>window.removeEventListener(`workspaces:refresh`,e)},[]);let De=(0,X.useRef)(!1),Oe=(0,X.useRef)(!1);(0,X.useEffect)(()=>{De.current=!!V||ue,Oe.current=ge||fe.length>0}),(0,X.useEffect)(()=>{x?.status===`active`&&b===`db`&&U&&!De.current&&Se(),x?.status===`active`&&b===`devices`&&U&&!Oe.current&&Ce()},[b,U,x?.status,Se,Ce]);let ke=async e=>{if(e.preventDefault(),x){O(!0);try{await ja(U,{label:j.trim(),description:P.trim(),color:F,icon:te}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),_({title:`Saved`,description:`Workspace settings updated`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{O(!1)}}},Ae=async()=>{if(x&&window.confirm(`Destroy workspace "${x.label||x.name}"? This cannot be undone.`)){A(!0);try{await Ka(U),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),_({title:`Destroyed`,description:`${x.label||x.name} has been removed`}),g(`/workspaces`)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Destroy failed`,variant:`destructive`})}finally{A(!1)}}},je=()=>{for(let t of[e,x?.name,x?.id])t&&oa(t,`backends`);window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:U}}))},Me=async e=>{if(e.config?.supported!==!1){B(`backend:${e.address}`);try{await aa(U,e.driver,e.address,{enabled:!e.enabled}),await Te(),je(),_({title:`Saved`,description:`${e.address} ${e.enabled?`disabled`:`enabled`}`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to update backend`,variant:`destructive`})}finally{B(null)}}},Ne=async(e,t,n)=>{B(`${n}:${e.address}`);try{await aa(U,e.driver,e.address,t),await Te()}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to update backend`,variant:`destructive`})}finally{B(null)}},Pe=async e=>{let t=typeof e.config?.label==`string`&&e.config.label||e.address;if(window.confirm(`Remove backend "${t}"? No files are deleted; indexed entries remain until purged from the backends tree.`)){B(`remove:${e.address}`);try{await Nr(U,e.driver,e.address),await Te(),je(),_({title:`Removed`,description:`${t} unmounted`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to remove backend`,variant:`destructive`})}finally{B(null)}}},Fe=async e=>{B(`resync:${e.address}`);try{await da(U,e.driver,e.address),await Te(),_({title:`Re-syncing`,description:`${e.address} scan started`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Re-sync failed`,variant:`destructive`})}finally{B(null)}},Ie=async e=>{B(`test:${e.address}`);try{await Zi(U,e.driver,e.address),_({title:`Connected`,description:`${e.address}: credentials and root folder verified`})}catch(e){_({title:`Connection failed`,description:e instanceof Error?e.message:`Test failed`,variant:`destructive`})}finally{B(null)}},Le=async e=>{B(`stopsync:${e.address}`);try{await Ii(U,e.driver,e.address),await Te(),_({title:`Sync stopped`,description:`${e.address}: indexed files are kept; Re-sync resumes where it left off`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to stop sync`,variant:`destructive`})}finally{B(null)}},Re=async(e,t)=>{B(`service:${e}`);try{t?await ta(U,e):await Mr(U,e),await Te(),_({title:t?`Disabled`:`Enabled`,description:`${e} ${t?`disabled`:`enabled`}`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to toggle service`,variant:`destructive`})}finally{B(null)}},ze=async e=>{let t=`${window.location.origin}${e.url}`;await navigator.clipboard?.writeText(t),_({title:`Copied`,description:t})},Be=async e=>{if(x&&window.confirm(`Revoke public share for "${e.path}"?`)){B(`share:${e.code}`);try{await Br(U,e.code),await xe(U),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:U}})),_({title:`Revoked`,description:`Public canvas link no longer works`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to revoke share`,variant:`destructive`})}finally{B(null)}}},Ve=wC.find(e=>e.id===b);return T?(0,Z.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Loading...`}):x?(0,Z.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-5xl p-6 pb-12 max-md:px-4 max-md:pb-rail-stack`,children:[(0,Z.jsx)(By,{compact:!0,className:`mb-6 border-b pb-4`,title:`${Ve.label} - ${x.label||x.name}`,description:`This workspace · ${Ve.description}`,backTo:`/workspaces/${e}`,onBack:v?()=>y(`workspaces`,`settings`,e??null):void 0}),x.status!==`active`&&b!==`general`&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Start this workspace to access these settings. General settings and protection remain available while stopped.`}),b===`general`&&(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`form`,{onSubmit:ke,className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ws-label`,className:`text-sm font-medium`,children:`Label`}),(0,Z.jsx)(q,{id:`ws-label`,value:j,onChange:e=>N(e.target.value),placeholder:`Workspace Label`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ws-description`,className:`text-sm font-medium`,children:`Description`}),(0,Z.jsx)(q,{id:`ws-description`,value:P,onChange:e=>ee(e.target.value),placeholder:`Description (optional)`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-sm font-medium`,children:`Icon & color`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`button`,{type:`button`,title:`Pick icon & color`,onClick:e=>re({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360)}),className:`flex h-10 w-10 items-center justify-center rounded-md border hover:bg-accent`,children:(0,Z.jsx)(c,{icon:te||`ph:stack-fill`,width:22,height:22,color:If(F)})}),(0,Z.jsx)(q,{id:`ws-color`,type:`color`,value:F,onChange:e=>I(e.target.value),className:`h-10 w-16 p-1`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>I(Nf()),children:`Randomize`})]})]}),(0,Z.jsx)(J,{type:`submit`,disabled:D||!j.trim(),children:D?`Saving...`:`Save Changes`})]}),L&&(0,Z.jsx)(Wy,{x:L.x,y:L.y,current:{icon:te??void 0,color:F},onChange:e=>{`icon`in e&&ne(e.icon??null),`color`in e&&e.color&&I(e.color)},onClose:()=>re(null)}),(0,Z.jsx)(nO,{currentMode:x.protection?.mode,workspaceId:U,isActive:x.status===`active`,onChanged:()=>w(e=>e+1)}),x.status===`active`&&(0,Z.jsx)(n1,{workspaceName:e}),x.status===`active`&&(0,Z.jsx)(J$,{workspaceId:U}),(0,Z.jsx)(B$,{workspaceId:U,workspaceName:x.label||x.name,isActive:x.status===`active`,onChanged:()=>w(e=>e+1)}),(0,Z.jsxs)(`section`,{className:`rounded-lg border border-destructive/30 p-4`,children:[(0,Z.jsx)(`h2`,{className:`mb-3 text-sm font-semibold text-destructive`,children:`Danger Zone`}),(0,Z.jsxs)(J,{variant:`destructive`,disabled:k,onClick:Ae,children:[(0,Z.jsx)(lt,{className:`mr-2 h-4 w-4`}),k?`Destroying...`:`Destroy Workspace`]})]})]}),x.status===`active`&&b===`shares`&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-3`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Members`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Share this workspace with teammates by e-mail or with a whole directory group. It shows up in their workspace list on this server.`})]}),(0,Z.jsx)(z$,{workspaceId:U})]}),(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Public Canvas Shares`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Active public canvas links for this workspace.`})]}),(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>xe(),children:[(0,Z.jsx)(M,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),R.length===0?(0,Z.jsx)(`div`,{className:`rounded-md border p-4 text-sm text-muted-foreground`,children:`No public canvas shares. Good.`}):R.map(e=>{let t=`${window.location.origin}${e.url}`;return(0,Z.jsxs)(`div`,{className:`rounded-md border p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate font-mono text-sm`,children:e.path}),(0,Z.jsxs)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:[e.treeName,` / `,e.treeType,` - created `,new Date(e.createdAt).toLocaleString()]}),e.lockedBy?.length>0&&(0,Z.jsxs)(`div`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`locks: `,e.lockedBy.join(`, `)]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>ze(e),children:(0,Z.jsx)(Ct,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>window.open(t,`_blank`,`noreferrer`),children:(0,Z.jsx)(Gn,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:ce===`share:${e.code}`,onClick:()=>Be(e),className:`text-destructive hover:text-destructive`,children:(0,Z.jsx)(pe,{className:`h-3.5 w-3.5`})})]})]}),(0,Z.jsx)(`div`,{className:`mt-2 truncate rounded bg-muted/40 px-2 py-1 font-mono text-xs text-muted-foreground`,children:t})]},e.code)})]}),(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-3`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Workspace ACL Tokens`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Generate token-based workspace access for devices, scripts, and other users.`})]}),(0,Z.jsx)(F$,{workspaceId:U})]})]}),x.status===`active`&&b===`data`&&(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[z.map(e=>{let t=e.config||{},n=e.address,r=t.device||null,i=e.driver===`gdrive`,a=(e.driver===`file`||i)&&t.managed!==!0&&!V$[n],o=V$[n]||{title:typeof t.label==`string`&&t.label||n,description:i?`Google Drive${typeof t.account==`string`&&t.account&&t.account!==t.label?` (${t.account})`:``}, folder ${typeof t.folderId==`string`&&t.folderId?t.folderId:`root`}${e.treePath?`, mirrored at ${e.treePath}`:``}.`:a?`Local folder${r?.name?` on ${r.name}`:``}, indexed in place${e.treePath?` and mirrored at ${e.treePath}`:``}.`:`Workspace data backend.`},s=t.supported!==!1,l=n===`workspace:data`,u=s&&!l,d=u&&t.managed!==!0,f=Ef(e);return(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(c,{icon:f.icon,width:16,height:16,color:f.color,className:`shrink-0`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:o.title}),!s&&(0,Z.jsx)(`span`,{className:`rounded bg-muted px-2 py-0.5 text-[11px] text-muted-foreground`,children:`unsupported`})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:o.description}),typeof t.root==`string`&&t.root&&(0,Z.jsx)(`p`,{className:`mt-2 truncate font-mono text-xs text-muted-foreground`,children:t.root}),(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-2 text-[11px] text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{children:[`status: `,e.status]}),e.resyncing&&(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 font-medium text-primary`,children:[(0,Z.jsx)(M,{className:`h-3 w-3 animate-spin`}),`indexing`,e.progress?` ${e.progress.scanned}${e.progress.total==null?``:` / ${e.progress.total}`}`:``]}),r?.name&&(0,Z.jsxs)(`span`,{title:r.id,children:[`device: `,r.name]}),t.readOnly===!0&&(0,Z.jsx)(`span`,{className:`rounded bg-warning/15 px-1.5 py-0.5 font-medium text-warning`,children:`read-only`}),e.lastSyncAt&&(0,Z.jsxs)(`span`,{children:[`last scan: `,new Date(e.lastSyncAt).toLocaleString()]})]}),e.lastError&&(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-destructive`,children:e.lastError}),t.readOnly===!0&&(0,Z.jsx)(`p`,{className:`mt-1 text-[11px] text-warning`,children:`Read-only: the web UI / REST API never deletes bytes on this backend. Destroy degrades to a reference drop. Recommended when the folder is exported elsewhere (e.g. via Samba).`})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-3`,children:[e.capabilities?.sync&&s&&(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,title:`Scan this backend in the background whenever the workspace starts. Manual scans remain available when off.`,children:[`Scan on start`,(0,Z.jsx)(U$,{checked:t.scanOnStart===!0,disabled:ce===`startup:${n}`,onClick:()=>Ne(e,{scanOnStart:t.scanOnStart!==!0},`startup`)})]}),(e.driver===`file`||i)&&u&&(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5 text-[11px] text-muted-foreground`,title:i?`Poll the Drive changes feed so edits made in Drive show up without a manual re-sync.`:void 0,children:[`Watch for changes`,(0,Z.jsx)(U$,{checked:!!t.watch,disabled:!e.enabled||ce===`watch:${n}`,onClick:()=>Ne(e,{watch:!t.watch},`watch`)})]}),d&&(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5 text-[11px] text-muted-foreground`,title:`Read-only: Destroy never deletes bytes on this backend (references are dropped instead). Important when the folder is exported via Samba or shared otherwise.`,children:[`read-only`,(0,Z.jsx)(U$,{checked:t.readOnly===!0,disabled:ce===`readonly:${n}`,onClick:()=>Ne(e,{readOnly:t.readOnly!==!0},`readonly`)})]}),(e.driver===`file`||e.driver===`cacache`)&&s&&(0,Z.jsx)(K$,{workspaceId:U,backend:e}),e.capabilities?.test&&(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:ce===`test:${n}`,onClick:()=>Ie(e),title:`Verify credentials and root folder`,children:[(0,Z.jsx)(At,{className:`mr-2 h-3.5 w-3.5`}),ce===`test:${n}`?`Testing…`:`Test`]}),e.capabilities?.sync&&(e.resyncing?(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:ce===`stopsync:${n}`,onClick:()=>Le(e),title:`Stop the running scan. Files indexed so far are kept; Re-sync later resumes where it left off (unchanged files are skipped).`,children:[(0,Z.jsx)($t,{className:`mr-2 h-3.5 w-3.5 fill-current`}),ce===`stopsync:${n}`?`Stopping…`:`Stop sync`]}):(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:ce===`resync:${n}`,onClick:()=>Fe(e),children:[(0,Z.jsx)(M,{className:`mr-2 h-3.5 w-3.5 ${ce===`resync:${n}`?`animate-spin`:``}`}),`Re-sync`]})),l?(0,Z.jsx)(`span`,{className:`rounded bg-muted px-2 py-0.5 text-[11px] text-muted-foreground`,title:`Structural workspace store; cannot be disabled`,children:`always on`}):(0,Z.jsx)(U$,{checked:!!e.enabled,disabled:!u||ce===`backend:${n}`,onClick:()=>Me(e)}),a&&(0,Z.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,className:`text-destructive hover:text-destructive`,disabled:ce===`remove:${n}`,title:`Unmount this folder (no files are deleted)`,onClick:()=>Pe(e),children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})]}),e.driver===`file`&&s&&!l&&(0,Z.jsx)(Y$,{backend:e,busy:ce===`exclude:${n}`,onSave:t=>Ne(e,{exclude:t},`exclude`)})]},n)}),(0,Z.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-4`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(c,{icon:`ph:lightning-fill`,width:16,height:16,className:`shrink-0 text-warning`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Stored Cache`})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Internal working store: local copies of remote resources and derived artifacts (thumbnails). Regenerable; safe to clear.`})]}),(0,Z.jsx)(`div`,{className:`flex shrink-0 items-center gap-3 max-sm:w-full max-sm:flex-wrap`,children:(0,Z.jsx)(q$,{workspaceId:U})})]})}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-start`,children:[(0,Z.jsx)(W$,{workspaceId:U,onAdded:async()=>{await Te(),je()}}),(0,Z.jsx)(G$,{workspaceId:U,onAdded:async()=>{await Te(),je()}})]}),e&&(0,Z.jsx)(`section`,{className:`border-t pt-4`,children:(0,Z.jsx)(p$,{workspaceName:e})})]}),x.status===`active`&&b===`db`&&(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[U&&(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Embeddings`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Which model turns this workspace's content into vectors, and where those vectors live.`})]}),(0,Z.jsx)(pO,{workspaceId:U,workspaceName:e})]}),(0,Z.jsx)(e1,{stats:V,isLoading:ue,onRefresh:()=>Se(),workspaceName:e})]}),x.status===`active`&&b===`devices`&&(0,Z.jsx)(Z$,{allDevices:fe,linkedDevices:H,isLoading:ge,deviceBusy:ve,onRefresh:()=>Ce(),onLink:W,onUnlink:G,onUpdate:we}),x.status===`active`&&b===`sync`&&(0,Z.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,Z.jsx)(D$,{workspaceId:U,workspaceUuid:x?.id})}),x.status===`active`&&b===`services`&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[U&&(0,Z.jsx)(j$,{workspaceId:U}),(0,Z.jsx)(`div`,{className:`space-y-3`,children:H$.map(e=>{let t=ae?.[e.id]||ae?.[e.id===`git`?`dotfiles`:e.id===`webdav`?`home`:`imap`],n=!!t?.enabled;return(0,Z.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(Gt,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:e.title})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:e.description}),(0,Z.jsxs)(`p`,{className:`mt-2 text-[11px] text-muted-foreground`,children:[`initialized: `,t?.initialized?`true`:`false`]})]}),(0,Z.jsx)(U$,{checked:n,disabled:ce===`service:${e.id}`,onClick:()=>Re(e.id,n)})]})},e.id)})}),(0,Z.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,Z.jsx)(P$,{workspaceId:U,enabled:!!(ae?.imap?.enabled||ae?.imapSync?.enabled)})})]}),x.status===`active`&&b===`hooks`&&(0,Z.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,Z.jsx)(d$,{workspaceId:U,prefillRule:m,onPrefillConsumed:h,initialSection:a,initialRunsHandler:o,initialRunId:s})})]})}):(0,Z.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Workspace not found`})}function n1({workspaceName:e}){let{selected:t,setSelected:n,tree:r,setTree:i,toggle:a}=Mb(),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(null);return(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Default folders`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Create a set of common folders with matching icons and colors.`}),(0,Z.jsx)(`div`,{className:`mt-3`,children:(0,Z.jsx)(Nb,{selected:t,onToggle:a,tree:r,onTreeChange:i,disabled:o,idPrefix:`settings-default-folders`})}),(0,Z.jsxs)(`div`,{className:`mt-3 flex items-center gap-3`,children:[(0,Z.jsx)(J,{type:`button`,size:`sm`,disabled:o||t.size===0,onClick:async()=>{s(!0),l(null);let{ok:i,failed:a}=await jb(e,Array.from(t),r);s(!1),l(a?`${i} created, ${a} failed`:`${i} folder(s) created`),n(new Set)},children:o?`Creating…`:`Create ${t.size||``} folder(s)`}),c&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:c})]})]})}function r1({workspaceName:e,vectorSpaces:t,onDone:n}){let[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)(null),s=async(e,t,r)=>{if(!(r&&!window.confirm(r))){i(e),o(null);try{let e=await t();o(e.message),n()}catch(e){o(e instanceof Error?e.message:`Reindex failed`)}finally{i(null)}}},c=[{title:`Bitmaps`,ops:[{key:`timelines`,label:`Reindex timelines`,description:`Rebuild the created/updated timelines from document data.`,fn:()=>dD(e)},{key:`mime`,label:`Reindex MIME types`,description:`Rebuild the per-MIME-type presence bitmaps (data/mime/*) from stored docs. Backfills blobs indexed before mime bitmaps existed.`,fn:()=>mD(e)}]},{title:`Full-text (BM25)`,ops:[{key:`fts`,label:`Backfill`,description:`Index documents missing from the full-text table. Fast, skips already-indexed.`,fn:()=>fD(e)},{key:`fts-rebuild`,label:`Rebuild`,description:`Wipe the full-text table and rebuild from scratch. Use when counts drift.`,confirm:`Wipe the FTS index and rebuild it from scratch?`,fn:()=>fD(e,!0)},{key:`fts-optimize`,label:`Optimize`,description:`Compact fragments + prune old versions of the full-text table.`,fn:()=>pD(e,`fts`)}]},...t.length>0?[{title:`Vector tables (LanceDB)`,ops:t.map(t=>({key:`${t}-optimize`,label:`Optimize ${t}`,description:`Compact fragments + prune old versions of the '${t}' vector table and rebuild its ANN index.`,fn:()=>pD(e,t)}))}]:[]];return(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-center gap-2`,children:[(0,Z.jsx)(M,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Index maintenance`})]}),(0,Z.jsx)(`p`,{className:`mb-3 text-xs text-muted-foreground`,children:`Runs against this workspace. Reindex operations are idempotent.`}),(0,Z.jsx)(`div`,{className:`space-y-4`,children:c.map(e=>(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:e.title}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.ops.map(e=>(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,className:`w-44 justify-start`,disabled:r!==null,onClick:()=>s(e.key,e.fn,e.confirm),children:[r===e.key&&(0,Z.jsx)(M,{className:`mr-2 h-3 w-3 animate-spin`}),e.label]}),(0,Z.jsx)(`span`,{className:`min-w-0 flex-1 basis-52 text-xs text-muted-foreground`,children:e.description})]},e.key))})]},e.title))}),a&&(0,Z.jsx)(`p`,{className:`mt-3 text-xs text-muted-foreground`,children:a})]})}var i1=[{value:`documentRead`,label:`Read`},{value:`documentWrite`,label:`Write`},{value:`documentReadWrite`,label:`Read & write`}];function a1(){let{contextId:e,tab:t}=Yc(),[n]=mu(),r=n.get(`ownerId`)||void 0,i=Gc(),{showToast:a}=oo(),{selectEntity:o,openM2Drawer:s,closeM2:c}=Eb(),l=Cm(),u=OC(t),d=r?`?ownerId=${encodeURIComponent(r)}`:``;(0,X.useEffect)(()=>{t!==u&&e&&i(`/contexts/${e}/settings/${u}${d}`,{replace:!0})},[t,u,e,d,i]);let[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(!0),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(null),[E,D]=(0,X.useState)(``),[O,k]=(0,X.useState)(``),[A,j]=(0,X.useState)(),[N,P]=(0,X.useState)([]),[ee,F]=(0,X.useState)(!1),[I,te]=(0,X.useState)(``),[ne,L]=(0,X.useState)(i1[0].value),[re,R]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!e)return;let t=!1;return $o(e,r).then(e=>{t||(p(e),o(e.id),x(e.name||``),C(e.description||``),T(typeof e.metadata?.ui?.color==`string`?e.metadata.ui.color:null),D(e.url||``),k(e.baseUrl||``))}).catch(()=>{t||a({title:`Error`,description:`Failed to load context`,variant:`destructive`})}).finally(()=>{t||h(!1)}),()=>{t=!0}},[e,r,o,a]);let ie=(t=e)=>{t&&(F(!0),ps(t).then(P).catch(()=>P([])).finally(()=>F(!1)))};(0,X.useEffect)(()=>{if(u!==`shares`||!e)return;let t=!1;return ps(e).then(e=>{t||P(e)}).catch(()=>{t||P([])}),()=>{t=!0}},[u,e]);let ae=async t=>{if(t.preventDefault(),e){_(!0);try{let t=await Mo(e,{name:b.trim(),description:S.trim(),metadata:{...f?.metadata,ui:{...f?.metadata?.ui,color:w}}},r);p(t),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),a({title:`Saved`,description:`Context updated`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{_(!1)}}},oe=async t=>{if(t.preventDefault(),e){_(!0);try{await Promise.all([Po(e,E.trim(),r,A),zo(e,{baseUrl:O.trim()||null},r)]),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),a({title:`Saved`,description:`Context URL updated`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{_(!1)}}},z=async()=>{if(e&&window.confirm(`Delete context "${e}"? This cannot be undone.`)){y(!0);try{await os(e,r),c(),o(null),a({title:`Deleted`,description:`Context "${e}" removed`}),i(`/contexts`,{replace:!0})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Delete failed`,variant:`destructive`})}finally{y(!1)}}},se=async t=>{if(t.preventDefault(),!(!e||!I.trim())){R(`grant`);try{await ds(e,I.trim(),ne),te(``),ie(),a({title:`Shared`,description:`Access granted to ${I.trim()}`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to grant access`,variant:`destructive`})}finally{R(null)}}},ce=async t=>{if(e&&window.confirm(`Revoke ${t.userEmail}'s access to "${e}"?`)){R(t.userEmail);try{await ko(e,t.userEmail),ie(),a({title:`Revoked`,description:`${t.userEmail} no longer has access`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to revoke access`,variant:`destructive`})}finally{R(null)}}};if(m)return(0,Z.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Loading...`});if(!f)return(0,Z.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Context not found`});let B=DC.find(e=>e.id===u),V=`/contexts/${e}${d}`;return(0,Z.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-3xl p-6 pb-12 max-md:px-4 max-md:pb-rail-stack`,children:[(0,Z.jsx)(By,{compact:!0,className:`mb-6 border-b pb-4`,title:`${B.label} - ${f.name||f.id}`,description:B.description,backTo:V,onBack:l?()=>s(`contexts`,`settings`,f.id):void 0}),u===`general`&&(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`form`,{onSubmit:ae,className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-sm font-medium`,children:`Context ID`}),(0,Z.jsx)(`div`,{className:`mt-1 flex h-10 items-center rounded-md bg-muted px-3 font-mono text-sm text-muted-foreground`,children:f.id})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ctx-name`,className:`text-sm font-medium`,children:`Name`}),(0,Z.jsx)(q,{id:`ctx-name`,value:b,onChange:e=>x(e.target.value),placeholder:`My Context`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ctx-description`,className:`text-sm font-medium`,children:`Description`}),(0,Z.jsx)(q,{id:`ctx-description`,value:S,onChange:e=>C(e.target.value),placeholder:`Optional description`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ctx-color`,className:`text-sm font-medium`,children:`Color`}),(0,Z.jsxs)(`div`,{className:`mt-1 flex items-center gap-2`,children:[(0,Z.jsx)(q,{id:`ctx-color`,type:`color`,value:/^#[0-9a-f]{6}$/i.test(w||f.color||``)?w||f.color:`#808080`,onChange:e=>T(e.target.value),className:`h-10 w-16 p-1`,disabled:g}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:g||w===null,onClick:()=>T(null),children:`Use inherited color`})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:w===null?`Using the tree folder or workspace color.`:`Applies only to this context.`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-sm font-medium`,children:`Workspace`}),(0,Z.jsx)(`div`,{className:`mt-1 flex h-10 items-center rounded-md bg-muted px-3 text-sm text-muted-foreground`,children:f.workspaceName||f.workspaceId||f.workspace})]}),(0,Z.jsx)(J,{type:`submit`,disabled:g,children:g?`Saving...`:`Save Changes`})]}),(0,Z.jsxs)(`section`,{className:`rounded-lg border border-destructive/30 p-4`,children:[(0,Z.jsx)(`h2`,{className:`mb-3 text-sm font-semibold text-destructive`,children:`Danger Zone`}),(0,Z.jsxs)(J,{variant:`destructive`,disabled:v,onClick:z,children:[(0,Z.jsx)(lt,{className:`mr-2 h-4 w-4`}),v?`Deleting...`:`Delete Context`]})]})]}),u===`location`&&(0,Z.jsxs)(`form`,{onSubmit:oe,className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ctx-url`,className:`text-sm font-medium`,children:`URL`}),(0,Z.jsx)(uC,{id:`ctx-url`,value:E,onChange:D,fixedWorkspaceName:f.workspaceName,pickerTitle:`Switch context to…`,placeholder:`workspace://path`,onPickTarget:(e,t)=>{D(`${t.workspaceName}://${e.replace(/^\/+/,``)}`),j(t.treeName)}}),A&&(0,Z.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[`Destination tree: `,A]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`label`,{htmlFor:`ctx-base-url`,className:`text-sm font-medium`,children:[`Base URL `,(0,Z.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional)`})]}),(0,Z.jsx)(uC,{id:`ctx-base-url`,value:O,onChange:k,fixedWorkspaceName:f.workspaceName,placeholder:`workspace://base/path`,pickerTitle:`Pick a base path…`})]}),(0,Z.jsx)(J,{type:`submit`,disabled:g,children:g?`Saving...`:`Save Changes`})]}),u===`shares`&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`People with access`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Only the context owner can see and change this list.`})]}),(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>ie(),disabled:ee,children:[(0,Z.jsx)(M,{className:K(`mr-2 h-3.5 w-3.5`,ee&&`animate-spin`)}),`Refresh`]})]}),N.length===0?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Not shared with anyone.`}):N.map(e=>(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3 rounded-md border p-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-medium`,children:e.userEmail}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[i1.find(t=>t.value===e.accessLevel)?.label||e.accessLevel||`unknown access`,e.sharedAt&&` - since ${new Date(e.sharedAt).toLocaleDateString()}`]})]}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,className:`text-destructive hover:text-destructive`,disabled:re===e.userEmail,onClick:()=>ce(e),children:(0,Z.jsx)(pe,{className:`h-3.5 w-3.5`})})]},e.userEmail))]}),(0,Z.jsxs)(`form`,{onSubmit:se,className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Grant access`}),(0,Z.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`share-email`,className:`text-sm font-medium`,children:`User email`}),(0,Z.jsx)(q,{id:`share-email`,type:`email`,value:I,onChange:e=>te(e.target.value),placeholder:`person@example.com`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`The user must already have an account on this server.`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`share-level`,className:`text-sm font-medium`,children:`Access level`}),(0,Z.jsx)(`select`,{id:`share-level`,value:ne,onChange:e=>L(e.target.value),className:`mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`,children:i1.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))})]})]}),(0,Z.jsx)(J,{type:`submit`,disabled:re===`grant`||!I.trim(),children:re===`grant`?`Sharing...`:`Share context`})]})]})]})})}function o1({status:e}){let t={running:{icon:tn,color:`text-success`,bg:`bg-success-subtle`,label:`Running`},stopped:{icon:j,color:`text-muted-foreground`,bg:`bg-muted`,label:`Stopped`},starting:{icon:Qn,color:`text-info`,bg:`bg-info-subtle`,label:`Starting`},stopping:{icon:Qn,color:`text-warning`,bg:`bg-warning-subtle`,label:`Stopping`},error:{icon:be,color:`text-destructive`,bg:`bg-destructive-subtle`,label:`Error`},created:{icon:At,color:`text-muted-foreground`,bg:`bg-muted`,label:`Created`},configured:{icon:At,color:`text-info`,bg:`bg-info-subtle`,label:`Configured`},removed:{icon:j,color:`text-destructive`,bg:`bg-destructive-subtle`,label:`Removed`}},n=t[e]||t.created,r=n.icon;return(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium ${n.bg} ${n.color}`,children:[(0,Z.jsx)(r,{className:`w-3 h-3`}),n.label]})}function s1(){let[e,t]=(0,X.useState)([]),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null);gf(()=>s(null),o!==null);let[c,l]=Jy(),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(``),[g,_]=(0,X.useState)(``),[v,y]=(0,X.useState)(``),[b,x]=(0,X.useState)(!1),{showToast:S}=oo(),C=Yu(),w=(0,X.useCallback)(async()=>{try{r(!0);let e=await wD.listRoles({type:`workspace`,userId:C?.id});t(e),a(null)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch roles`;a(t)}finally{r(!1)}},[C?.id]);(0,X.useEffect)(()=>{let e=()=>w();e();let t=setInterval(e,3e4);return()=>clearInterval(t)},[w]),(0,X.useEffect)(()=>{c&&(wD.listTemplates().then(e=>{let t=e.filter(e=>e.type===`workspace`);d(t),h(e=>e||t[0]?.id||``)}).catch(()=>d([])),Or().then(e=>{p(e),y(t=>t||e[0]?.id||``)}).catch(()=>p([])))},[c]);let T=async e=>{if(e.preventDefault(),!(!m||!g.trim()||!v)){x(!0);try{let e=await wD.createRole({template:m,name:g.trim(),type:`workspace`,userId:C?.id,workspaceId:v});_(``),l(!1),await w(),S({title:`Created`,description:`Role "${e.name}" created`})}catch(e){S({title:`Error`,description:e instanceof Error?e.message:`Failed to create role`,variant:`destructive`})}finally{x(!1)}}},E=async e=>{try{await wD.startRole(e.id),S({title:`Success`,description:`Role "${e.name}" started successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to start role`;S({title:`Error`,description:t,variant:`destructive`})}},D=async e=>{try{await wD.stopRole(e.id),S({title:`Success`,description:`Role "${e.name}" stopped successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to stop role`;S({title:`Error`,description:t,variant:`destructive`})}},O=async e=>{try{await wD.restartRole(e.id),S({title:`Success`,description:`Role "${e.name}" restarted successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to restart role`;S({title:`Error`,description:t,variant:`destructive`})}},A=async e=>{try{let t=await wD.getRoleLogs(e.id,100);s({role:e,logs:t})}catch(e){let t=e instanceof Error?e.message:`Failed to fetch logs`;S({title:`Error`,description:t,variant:`destructive`})}};return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(By,{title:`My Roles`,description:`Manage your workspace roles and services`,actions:(0,Z.jsxs)(Z.Fragment,{children:[!c&&(0,Z.jsxs)(J,{onClick:()=>l(!0),children:[(0,Z.jsx)(nn,{className:`mr-2 h-4 w-4`}),`Create Role`]}),(0,Z.jsxs)(J,{onClick:w,variant:`outline`,children:[(0,Z.jsx)(k,{className:`mr-2 h-4 w-4`}),`Refresh`]})]})}),c&&(0,Z.jsx)(Ky,{title:`Create New Role`,onClose:()=>l(!1),children:(0,Z.jsxs)(`form`,{onSubmit:T,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`role-template`,className:`mb-1 block text-sm font-medium`,children:`Template`}),(0,Z.jsxs)(`select`,{id:`role-template`,className:`w-full rounded-md border border-border bg-background px-3 py-2`,value:m,onChange:e=>h(e.target.value),disabled:b||u.length===0,children:[u.length===0&&(0,Z.jsx)(`option`,{value:``,children:`No workspace templates available`}),u.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.name,` - `,e.description]},e.id))]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`role-name`,className:`mb-1 block text-sm font-medium`,children:`Role Name`}),(0,Z.jsx)(q,{id:`role-name`,value:g,onChange:e=>_(e.target.value),placeholder:`e.g., canvas-sshd`,disabled:b})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`role-workspace`,className:`mb-1 block text-sm font-medium`,children:`Workspace`}),(0,Z.jsxs)(`select`,{id:`role-workspace`,className:`w-full rounded-md border border-border bg-background px-3 py-2`,value:v,onChange:e=>y(e.target.value),disabled:b||f.length===0,children:[f.length===0&&(0,Z.jsx)(`option`,{value:``,children:`No workspaces available. Create one first.`}),f.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.label||e.name},e.id))]})]}),(0,Z.jsxs)(J,{type:`submit`,disabled:b||!m||!g.trim()||!v,children:[(0,Z.jsx)(nn,{className:`mr-2 h-4 w-4`}),b?`Creating…`:`Create Role`]})]})}),n?(0,Z.jsx)(`div`,{className:`text-center py-8`,children:`Loading roles...`}):i?(0,Z.jsx)(`div`,{className:`text-center py-8 text-destructive`,children:i}):e.length===0?(0,Z.jsxs)(`div`,{className:`text-center py-12 border rounded-lg`,children:[(0,Z.jsx)(Gt,{className:`w-12 h-12 mx-auto text-muted-foreground mb-4`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:`You don't have any workspace roles yet`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mt-2`,children:`Contact your administrator to set up roles for your workspaces`})]}):(0,Z.jsx)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4`,children:e.map(e=>(0,Z.jsxs)(`div`,{className:`border rounded-lg p-6 space-y-4 hover:shadow-elevation-2 transition-shadow`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex-1`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold text-lg`,children:e.name}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.template})]}),(0,Z.jsx)(o1,{status:e.status})]}),e.container&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,Z.jsx)(Gt,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`truncate`,children:e.container.name})]})}),(0,Z.jsxs)(`div`,{className:`flex gap-2 pt-2`,children:[e.status===`stopped`||e.status===`created`?(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,onClick:()=>E(e),className:`flex-1`,children:[(0,Z.jsx)(W,{className:`w-4 h-4 mr-2`}),`Start`]}):e.status===`running`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,onClick:()=>D(e),className:`flex-1`,children:[(0,Z.jsx)($t,{className:`w-4 h-4 mr-2`}),`Stop`]}),(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,onClick:()=>O(e),className:`flex-1`,children:[(0,Z.jsx)(k,{className:`w-4 h-4 mr-2`}),`Restart`]})]}):(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,disabled:!0,className:`flex-1`,children:[(0,Z.jsx)(Qn,{className:`w-4 h-4 mr-2`}),e.status]}),(0,Z.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>A(e),title:`View Logs`,children:(0,Z.jsx)(_n,{className:`w-4 h-4`})})]})]},e.id))}),(0,Z.jsxs)(`div`,{className:`border-t pt-6`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold mb-4`,children:`Global Services`}),(0,Z.jsxs)(`div`,{className:`text-sm text-muted-foreground space-y-2`,children:[(0,Z.jsx)(`p`,{children:`Global roles are server-wide services managed by your administrator. These include services like SSH access, storage, and other shared infrastructure.`}),(0,Z.jsx)(`p`,{children:`To check the status of global services, contact your system administrator.`})]})]}),o&&(0,Z.jsx)(`div`,{className:`fixed inset-0 bg-scrim flex items-center justify-center z-50`,children:(0,Z.jsxs)(`div`,{className:`bg-background rounded-lg shadow-elevation-3 max-w-4xl w-full mx-4 max-h-viewport-modal flex flex-col`,children:[(0,Z.jsxs)(`div`,{className:`p-6 border-b`,children:[(0,Z.jsxs)(`h2`,{className:`text-xl font-bold`,children:[o.role.name,` - Logs`]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:o.role.template})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-6`,children:(0,Z.jsx)(`div`,{"data-scheme":`dark`,className:`bg-background text-success p-4 rounded font-mono text-xs overflow-x-auto`,children:o.logs.length===0?(0,Z.jsx)(`div`,{className:`text-muted-foreground`,children:`No logs available`}):(0,Z.jsx)(`pre`,{children:o.logs.join(`
|
|
87
|
+
`)})})}),(0,Z.jsx)(`div`,{className:`p-4 border-t flex justify-end`,children:(0,Z.jsx)(J,{onClick:()=>s(null),children:`Close`})})]})})]})}function c1(){return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(By,{title:`Remotes`,description:`Connect to remote Canvas instances`}),(0,Z.jsx)(`div`,{className:`flex flex-col items-center justify-center py-12 space-y-4`,children:(0,Z.jsxs)(`div`,{className:`text-center`,children:[(0,Z.jsx)(`h2`,{className:`text-2xl font-semibold mb-2`,children:`Coming Soon`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground max-w-md`,children:`Remote connection management is currently under development. Check back later for updates.`})]})})]})}var l1=[`note`,`todo`,`link`,`file`,`photo`];function u1(){let{kind:e}=Yc(),t=Gc();return e===`sketch`?(0,Z.jsx)(_l,{to:`/apps/sketch?add=1`,replace:!0}):!e||!l1.includes(e)?(0,Z.jsx)(_l,{to:`/home`,replace:!0}):(0,Z.jsx)(WS,{initialKind:e,onInitialCardClose:()=>t(`/home`)})}var d1=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(yl,{index:!0,element:(0,Z.jsx)(eC,{})},`r1`),(0,Z.jsx)(yl,{path:`home`,element:(0,Z.jsx)($S,{})},`r2`),(0,Z.jsx)(yl,{path:`share-target`,element:(0,Z.jsx)(sC,{})},`r3`),(0,Z.jsx)(yl,{path:`apps/add/:kind`,element:(0,Z.jsx)(u1,{})},`r4`),(0,Z.jsx)(yl,{path:`workspaces`,element:(0,Z.jsx)(Vb,{})},`r5`),(0,Z.jsx)(yl,{path:`workspaces/:workspaceName`,element:(0,Z.jsx)(Jx,{})},`r6`),(0,Z.jsx)(yl,{path:`workspaces/:workspaceName/settings`,element:(0,Z.jsx)(t1,{})},`r7`),(0,Z.jsx)(yl,{path:`workspaces/:workspaceName/settings/:tab`,element:(0,Z.jsx)(t1,{})},`r8`),(0,Z.jsx)(yl,{path:`workspaces/:workspaceName/path/*`,element:(0,Z.jsx)(Jx,{})},`r9`),(0,Z.jsx)(yl,{path:`workspaces/:workspaceName/trees/:treeName`,element:(0,Z.jsx)(Jx,{})},`r10`),(0,Z.jsx)(yl,{path:`workspaces/:workspaceName/trees/:treeName/path/*`,element:(0,Z.jsx)(Jx,{})},`r11`),(0,Z.jsx)(yl,{path:`contexts`,element:(0,Z.jsx)(dC,{})},`r12`),(0,Z.jsx)(yl,{path:`contexts/:contextId`,element:(0,Z.jsx)(pC,{})},`r13`),(0,Z.jsx)(yl,{path:`contexts/:contextId/settings`,element:(0,Z.jsx)(a1,{})},`r14`),(0,Z.jsx)(yl,{path:`contexts/:contextId/settings/:tab`,element:(0,Z.jsx)(a1,{})},`r15`),(0,Z.jsx)(yl,{path:`agents`,element:(0,Z.jsx)(jD,{})},`r16`),(0,Z.jsx)(yl,{path:`agents/:agentId`,element:(0,Z.jsx)(qD,{})},`r17`),(0,Z.jsx)(yl,{path:`agents/:agentId/:sessionId`,element:(0,Z.jsx)(qD,{})},`r18`),(0,Z.jsx)(yl,{path:`agents/:agentId/settings`,element:(0,Z.jsx)(tO,{})},`r19`),(0,Z.jsx)(yl,{path:`agents/:agentId/settings/:tab`,element:(0,Z.jsx)(tO,{})},`r20`),(0,Z.jsx)(yl,{path:`roles`,element:(0,Z.jsx)(s1,{})},`r21`),(0,Z.jsx)(yl,{path:`remotes`,element:(0,Z.jsx)(c1,{})},`r22`),(0,Z.jsx)(yl,{path:`settings`,element:(0,Z.jsx)(_w,{})},`settings`),(0,Z.jsx)(yl,{path:`appearance`,element:(0,Z.jsx)(TT,{})},`r23`),(0,Z.jsx)(yl,{path:`key-bindings`,element:(0,Z.jsx)(PT,{})},`key-bindings`),(0,Z.jsx)(yl,{path:`offline`,element:(0,Z.jsx)(yE,{})},`r24`),(0,Z.jsx)(yl,{path:`about`,element:(0,Z.jsx)(SE,{})},`r25`),(0,Z.jsx)(yl,{path:`api-tokens`,element:(0,Z.jsx)(hC,{})},`r26`),(0,Z.jsx)(yl,{path:`devices`,element:(0,Z.jsx)(CC,{})},`r27`),(0,Z.jsx)(yl,{path:`embedding`,element:(0,Z.jsx)(rD,{})},`r28`),(0,Z.jsx)(yl,{path:`shared`,element:(0,Z.jsx)(iD,{})},`r29`),(0,Z.jsx)(yl,{path:`admin/users`,element:(0,Z.jsx)(OD,{})},`r30`),(0,Z.jsx)(yl,{path:`admin/contexts`,element:(0,Z.jsx)(vD,{})},`r31`),(0,Z.jsx)(yl,{path:`admin/workspaces`,element:(0,Z.jsx)(_D,{})},`r32`),(0,Z.jsx)(yl,{path:`admin/agents`,element:(0,Z.jsx)(yD,{})},`r33`),(0,Z.jsx)(yl,{path:`admin/logs`,element:(0,Z.jsx)(CD,{})},`r34`),(0,Z.jsx)(yl,{path:`admin/roles`,element:(0,Z.jsx)(DD,{})},`r35`),(0,Z.jsx)(yl,{path:`admin/embedding`,element:(0,Z.jsx)(kD,{})},`r36`)]});function f1(e){if(typeof e!=`string`||!e.startsWith(`/`)||e.startsWith(`//`)||/[\\\u0000-\u0020]/.test(e))return null;let t=new URL(e,`https://canvas.invalid`);return t.origin!==`https://canvas.invalid`||/^\/(?:login|register|pub|share-target|apps|next)(?:\/|$)/.test(t.pathname)||t.pathname===`/`||[...t.searchParams.keys()].some(e=>/token|password|secret|code/i.test(e))?null:t.pathname+t.search+t.hash}function p1(e){let t=2166136261;for(let n of e)t=Math.imul(t^n.charCodeAt(0),16777619);return`canvas:last-screen:${t>>>0}`}var m1=Sl(d1),h1=e=>{let t=f1(e);return t&&Is(m1,t)?t:null};function g1(){let e=Hc(),[t]=(0,X.useState)(()=>{if(e.pathname!==`/`||e.search||e.hash)return null;try{let t=localStorage.getItem(`authToken`);return t?{key:e.key,path:h1(localStorage.getItem(p1(t)))||`/home`}:null}catch{return{key:e.key,path:`/home`}}}),n=t&&e.key===t.key&&e.pathname===`/`;return(0,X.useEffect)(()=>{if(n)return;let t=h1(e.pathname+e.search+e.hash);if(t)try{let e=localStorage.getItem(`authToken`);e&&localStorage.setItem(p1(e),t)}catch{}},[e.pathname,e.search,e.hash,n]),n?(0,Z.jsx)(_l,{to:t.path,replace:!0}):null}var _1={activeSection:null,m0Open:!1,m1Open:!1,m2Open:!1,m2View:null,selectedEntityId:null,user:null};function v1(e,t){switch(t.type){case`SET_SECTION`:return{...e,activeSection:t.section,m1Open:t.section!==null,m2Open:!1,m2View:null,selectedEntityId:null};case`TOGGLE_SECTION`:return e.activeSection===t.section&&e.m1Open?{...e,activeSection:null,m1Open:!1,m2Open:!1,m2View:null}:{...e,activeSection:t.section,m1Open:!0,m2Open:!1,m2View:null,selectedEntityId:null};case`TOGGLE_M0`:return e.m0Open?{...e,m0Open:!1,activeSection:null,m1Open:!1,m2Open:!1,m2View:null}:{...e,m0Open:!0};case`CLOSE_M0`:return{...e,m0Open:!1};case`CLOSE_M1`:return{...e,activeSection:null,m1Open:!1,m2Open:!1,m2View:null};case`OPEN_M2`:return{...e,m2Open:!0,m2View:t.view,selectedEntityId:t.entityId===void 0?e.selectedEntityId:t.entityId};case`OPEN_M2_DRAWER`:return{...e,m0Open:!0,activeSection:t.section,m1Open:!0,m2Open:!0,m2View:t.view,selectedEntityId:t.entityId};case`OPEN_M1_DRAWER`:return{...e,m0Open:!0,activeSection:t.section,m1Open:!0,m2Open:!1,m2View:null,selectedEntityId:null};case`CLOSE_M2`:return{...e,m2Open:!1,m2View:null};case`SELECT_ENTITY`:return{...e,selectedEntityId:t.entityId};case`SYNC_FROM_URL`:return t.section===e.activeSection&&t.entityId===e.selectedEntityId&&t.m2View===e.m2View&&!(t.mobile&&(e.m1Open||e.m0Open))?e:{...e,activeSection:t.section,m0Open:!t.mobile&&e.m0Open,m1Open:!t.mobile&&t.section!==null,selectedEntityId:t.entityId,m2Open:t.m2View!==null,m2View:t.m2View};case`SET_USER`:return{...e,user:t.user};default:return e}}function y1({children:e}){let[t,n]=(0,X.useReducer)(v1,_1);Ob(t,n),(0,X.useEffect)(()=>{let e=Yu();if(e){n({type:`SET_USER`,user:e});return}let t=!1;return Xu().then(e=>{!t&&e&&n({type:`SET_USER`,user:e})}).catch(()=>{}),()=>{t=!0}},[]);let r={state:t,dispatch:n,setSection:(0,X.useCallback)(e=>{n({type:`SET_SECTION`,section:e})},[]),toggleSection:(0,X.useCallback)(e=>{n({type:`TOGGLE_SECTION`,section:e})},[]),toggleM0:(0,X.useCallback)(()=>{n({type:`TOGGLE_M0`})},[]),closeM0:(0,X.useCallback)(()=>{n({type:`CLOSE_M0`})},[]),closeM1:(0,X.useCallback)(()=>{n({type:`CLOSE_M1`})},[]),openM2:(0,X.useCallback)((e,t)=>{n({type:`OPEN_M2`,view:e,entityId:t})},[]),openM2Drawer:(0,X.useCallback)((e,t,r)=>{n({type:`OPEN_M2_DRAWER`,section:e,view:t,entityId:r})},[]),openM1Drawer:(0,X.useCallback)(e=>{n({type:`OPEN_M1_DRAWER`,section:e})},[]),closeM2:(0,X.useCallback)(()=>{n({type:`CLOSE_M2`})},[]),selectEntity:(0,X.useCallback)(e=>{n({type:`SELECT_ENTITY`,entityId:e})},[])};return(0,Z.jsx)(Tb.Provider,{value:r,children:e})}function b1(){return(0,X.useSyncExternalStore)(Qr,Dr,()=>!1)}function x1(e,t){let n=null,r=!1,i,a;function o(){clearTimeout(i),!r&&Dr()&&(i=setTimeout(()=>{s()},3e4))}function s(s=!1){if(n)return n;if(r)return Promise.resolve(!1);clearTimeout(i),a=new AbortController;let c=setTimeout(()=>a?.abort(),5e3);return n=(async()=>{try{let n=await fetch(e,{cache:`no-store`,credentials:`omit`,signal:a.signal});if(!n.ok||n.headers.get(`x-canvas-offline`)===`fallback`)throw Error(`Unavailable`);if((await n.json()).status!==`success`)throw Error(`Not a Canvas response`);if(r)return!1;let i=Dr();return yr(),(i||s)&&t(),!0}catch{return r||na(),!1}finally{clearTimeout(c),n=null,o()}})(),n}let c=Qr(o),l=()=>{s()};return window.addEventListener(`online`,l),o(),{retry:s,stop(){r=!0,clearTimeout(i),a?.abort(),c(),window.removeEventListener(`online`,l)}}}var S1;function C1(){S1=x1(`${Yr}/ping`,()=>Wu.retryNow());let e=()=>{S1?.retry()},t=Wu.on(`connect_error`,e),n=Wu.on(`disconnect`,e);return()=>{t(),n(),S1?.stop(),S1=void 0}}function w1(){return S1?.retry(!0)??Promise.resolve(!1)}function T1(){let e=b1(),[t,n]=(0,X.useState)(!1);return e?(0,Z.jsxs)(`details`,{className:`relative`,children:[(0,Z.jsx)(`summary`,{"aria-label":`Offline — connection options`,title:`Offline — cached content available`,className:`flex h-10 w-10 cursor-pointer list-none items-center justify-center rounded-lg text-amber-600 hover:bg-accent/50 [&::-webkit-details-marker]:hidden`,children:(0,Z.jsx)(qe,{className:`h-5 w-5`})}),(0,Z.jsxs)(`div`,{className:`absolute bottom-0 left-full z-50 ml-2 w-60 max-w-[calc(100vw-5rem)] rounded-lg border bg-popover p-3 text-popover-foreground shadow-lg`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,role:`status`,children:`Offline`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`You can browse cached documents. We’ll reconnect automatically when the server is available.`}),(0,Z.jsx)(`button`,{type:`button`,disabled:t,onClick:async()=>{n(!0);try{await w1()}finally{n(!1)}},className:`mt-3 rounded-md bg-secondary px-3 py-2 text-xs font-medium hover:bg-accent disabled:opacity-50`,children:t?`Checking…`:`Retry now`})]})]}):null}var E1=Fe,D1=E,O1=Zn,k1=X.forwardRef(({className:e,sideOffset:t=4,...n},r)=>(0,Z.jsx)(er,{children:(0,Z.jsx)(xt,{ref:r,sideOffset:t,className:K(`z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]`,e),...n})}));k1.displayName=xt.displayName;var A1=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(pt,{ref:n,className:K(`relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full`,e),...t}));A1.displayName=pt.displayName;var j1=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(ir,{ref:n,className:K(`aspect-square h-full w-full`,e),...t}));j1.displayName=ir.displayName;var M1=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(qn,{ref:n,className:K(`flex h-full w-full items-center justify-center rounded-full bg-muted`,e),...t}));M1.displayName=qn.displayName;function N1({section:e,icon:t,label:n,disabled:r}){let{state:i,toggleSection:a}=Eb(),o=i.activeSection===e;return(0,Z.jsxs)(D1,{children:[(0,Z.jsx)(O1,{asChild:!0,children:(0,Z.jsxs)(`button`,{type:`button`,disabled:r,"aria-label":n,onClick:()=>!r&&e&&a(e),className:K(`relative flex items-center justify-center w-10 h-10 rounded-lg transition-colors`,o?`bg-accent text-foreground`:`text-muted-foreground hover:text-foreground hover:bg-accent/50`,r&&`opacity-30 cursor-not-allowed`),children:[o&&(0,Z.jsx)(`span`,{className:`absolute right-0 top-1/2 -translate-y-1/2 w-0.5 h-5 bg-foreground rounded-l`}),t]})}),(0,Z.jsx)(k1,{side:`right`,sideOffset:8,children:n})]})}function P1({path:e,icon:t,label:n,section:r=`settings`}){let i=Gc(),{setSection:a}=Eb();return(0,Z.jsxs)(D1,{children:[(0,Z.jsx)(O1,{asChild:!0,children:(0,Z.jsx)(`button`,{type:`button`,"aria-label":n,onClick:()=>{a(r),i(e)},className:`flex items-center justify-center w-10 h-10 rounded-lg text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors`,children:t})}),(0,Z.jsx)(k1,{side:`right`,sideOffset:8,children:n})]})}function F1(){let{state:e,toggleM0:t}=Eb(),n=b1();return(0,Z.jsxs)(`button`,{type:`button`,onClick:t,"aria-label":`${e.m0Open?`Close menu`:`Open menu`}${n?` — offline, connection options in menu`:``}`,"data-shell":`rail`,className:`fixed bottom-rail-inset left-2 z-nav flex h-rail w-rail items-center justify-center rounded-full bg-foreground text-background shadow-elevation-4 md:hidden`,children:[e.m0Open?(0,Z.jsx)(je,{className:`h-5 w-5`}):(0,Z.jsx)(zn,{className:`h-5 w-5`}),n&&(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`absolute right-0 top-0 h-3 w-3 rounded-full border-2 border-background bg-amber-500`})]})}function I1(){let{state:e,closeM0:t,closeM1:n}=Eb(),{state:r,setView:i,closeT1:a}=hs(),o=Gc(),{showToast:s}=oo(),c=e.user?.userType===`admin`,l=()=>{r.t1Open?a():i(`tools`),n(),t()},u=(0,X.useCallback)(async()=>{try{await Y.post(`/auth/logout`),localStorage.removeItem(`authToken`),o(`/login`)}catch{s({title:`Error`,description:`Logout failed`,variant:`destructive`})}},[o,s]);return(0,Z.jsxs)(E1,{delayDuration:200,children:[e.m0Open&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-nav-scrim bg-scrim animate-fade-in md:hidden`,onClick:t,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{"data-shell":`rail`,className:K(`flex flex-col items-center w-rail h-full bg-transparent shrink-0`,e.m0Open?`max-md:fixed max-md:left-2 max-md:top-2 max-md:bottom-rail-stack max-md:z-rail max-md:h-auto max-md:rounded-[var(--panel-radius)] max-md:bg-card max-md:surface-glass max-md:shadow-elevation-5 max-md:animate-fade-in`:`max-md:hidden`),children:[(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-12 w-full shrink-0`,children:(0,Z.jsx)(`button`,{type:`button`,"aria-label":`Canvas home`,onClick:()=>o(`/home`),className:`flex items-center justify-center w-10 h-10 rounded-lg hover:bg-accent/50 transition-colors`,children:(0,Z.jsx)(`img`,{src:`/images/logo-br_128x128.png`,alt:``,className:`w-6 h-6`})})}),(0,Z.jsxs)(`nav`,{className:`flex flex-col items-center gap-1 py-2 flex-1 min-h-0 overflow-y-auto`,children:[(0,Z.jsx)(N1,{section:`contexts`,icon:(0,Z.jsx)(ar,{className:`w-5 h-5`}),label:`Contexts`}),(0,Z.jsx)(N1,{section:`workspaces`,icon:(0,Z.jsx)(Jn,{className:`w-5 h-5`}),label:`Workspaces`}),(0,Z.jsx)(N1,{section:`agents`,icon:(0,Z.jsx)(H,{className:`w-5 h-5`}),label:`Agents`}),(0,Z.jsx)(P1,{path:`/roles`,section:null,icon:(0,Z.jsx)(un,{className:`w-5 h-5`}),label:`Roles`}),c&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`w-6 h-px bg-border my-2`}),(0,Z.jsx)(P1,{path:`/admin/users`,icon:(0,Z.jsx)(Ue,{className:`w-5 h-5`}),label:`All Users`}),(0,Z.jsx)(P1,{path:`/admin/logs`,icon:(0,Z.jsx)(_n,{className:`w-5 h-5`}),label:`Server Logs`}),(0,Z.jsx)(P1,{path:`/admin/workspaces`,icon:(0,Z.jsx)(nt,{className:`w-5 h-5`}),label:`All Workspaces`}),(0,Z.jsx)(P1,{path:`/admin/agents`,icon:(0,Z.jsx)(H,{className:`w-5 h-5`}),label:`All Agents`}),(0,Z.jsx)(P1,{path:`/admin/roles`,icon:(0,Z.jsx)(un,{className:`w-5 h-5`}),label:`All Roles`})]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col items-center gap-1 py-2 shrink-0`,children:[(0,Z.jsx)(`div`,{className:`w-6 h-px bg-border mb-2`}),(0,Z.jsx)(T1,{}),(0,Z.jsxs)(D1,{children:[(0,Z.jsx)(O1,{asChild:!0,children:(0,Z.jsx)(`button`,{type:`button`,onClick:l,"aria-label":r.t1Open?`Close toolbox`:`Open toolbox`,className:K(`flex items-center justify-center w-10 h-10 rounded-lg transition-colors`,r.t1Open?`bg-accent text-foreground`:`text-muted-foreground hover:text-foreground hover:bg-accent/50`),children:(0,Z.jsx)(cr,{className:`w-5 h-5`})})}),(0,Z.jsx)(k1,{side:`right`,sideOffset:8,children:`Toolbox`})]}),(0,Z.jsx)(P1,{path:`/settings`,section:`settings`,icon:(0,Z.jsx)(mn,{className:`w-5 h-5`}),label:`Settings`}),(0,Z.jsxs)(D1,{children:[(0,Z.jsx)(O1,{asChild:!0,children:(0,Z.jsx)(`button`,{type:`button`,"aria-label":e.user?.email?`Profile: ${e.user.email}`:`Profile`,onClick:()=>o(`/home`),className:`flex items-center justify-center w-10 h-10 rounded-lg hover:bg-accent/50 transition-colors`,children:(0,Z.jsx)(A1,{className:`h-7 w-7 touch-target`,children:(0,Z.jsx)(M1,{className:`text-[10px] bg-muted`,children:e.user?.email?(e=>e.split(`@`)[0].split(`.`).map(e=>e.charAt(0).toUpperCase()).join(``).slice(0,2))(e.user.email):`U`})})})}),(0,Z.jsx)(k1,{side:`right`,sideOffset:8,children:e.user?.email?.split(`@`)[0]||`Profile`})]}),(0,Z.jsxs)(D1,{children:[(0,Z.jsx)(O1,{asChild:!0,children:(0,Z.jsx)(`button`,{type:`button`,"aria-label":`Log out`,onClick:u,className:`flex items-center justify-center w-10 h-10 rounded-lg text-destructive hover:bg-destructive/10 transition-colors`,children:(0,Z.jsx)(bn,{className:`w-5 h-5`})})}),(0,Z.jsx)(k1,{side:`right`,sideOffset:8,children:`Logout`})]})]})]})]})}function L1(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(!1),a=(0,X.useRef)(!1),o=(0,X.useRef)(!1),s=(0,X.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await Uo();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch contexts:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,X.useRef)(s);(0,X.useEffect)(()=>{c.current=s});let l=(0,X.useCallback)(()=>{a.current=!1,s()},[s]);return(0,X.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,X.useEffect)(()=>{if(!e)return;let t=()=>Wu.emit(`subscribe`,{channel:`context`}),r=()=>Wu.emit(`unsubscribe`,{channel:`context`}),i=Wu.on(`connect`,()=>{t(),s()});t();let o=e=>{let t=e;!t?.id||!t?.userId||n(e=>e.some(e=>e.id===t.id&&e.userId===t.userId)?e:[...e,t])},l=e=>{let t=e;!t?.id||!t?.userId||n(e=>e.map(e=>e.id===t.id&&e.userId===t.userId?{...e,...t}:e))},u=e=>{let t=e,r=t?.contextId??t?.id;r&&n(e=>e.filter(e=>e.id!==r))},d=e=>{let t=e;!t?.id||!t?.userId||n(e=>e.map(e=>e.id===t.id&&e.userId===t.userId?{...e,...t}:e))},f=()=>{a.current=!1,c.current()},p=[[`context:created`,o],[`context.created`,o],[`context:updated`,l],[`context.updated`,l],[`context:deleted`,u],[`context.deleted`,u],[`context:url:changed`,d],[`context.url.set`,d],[`context:url:set`,d],[`workspace:status:changed`,f],[`workspace.status.changed`,f]];return p.forEach(([e,t])=>Wu.on(e,t)),()=>{r(),i?.(),p.forEach(([e,t])=>Wu.off(e,t))}},[e,s]),(0,X.useEffect)(()=>{let e=e=>{let t=e.detail;n(e=>e.filter(e=>!Lo(e,t)))};return window.addEventListener(Io,e),()=>window.removeEventListener(Io,e)},[]),(0,X.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`contexts:refresh`,e),()=>window.removeEventListener(`contexts:refresh`,e)},[s]),{contexts:(0,X.useMemo)(()=>Lb(t),[t]),isLoading:r,refresh:l}}function R1(){let{state:e,selectEntity:t,openM2:n,closeM2:r}=Eb(),i=Cm(),{contexts:a,isLoading:o}=L1(e.activeSection===`contexts`),{showToast:s}=oo(),l=Gc(),[u,d]=(0,X.useState)(null),f=u&&u.base===a?u.order:a,p=e=>e.isShared===!0||e.type===`shared`,{rowProps:m,handleProps:h,draggingIndex:g,insertLineClass:_}=Bb((e,t)=>{let n=Rb(f,e,t);d({base:a,order:n}),zb(n,(e,t)=>p(e)?Promise.resolve():zo(e.id,{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`contexts:refresh`)),e&&s({title:`Partial reorder`,description:`${e} context(s) could not be reordered`,variant:`destructive`})})}),v=e=>{t(e.id),l(`/contexts/${e.id}`)};return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:`Contexts`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{r(),l(`/contexts?create=1`)},title:`Create context`,"aria-label":`Create context`,className:`flex items-center justify-center w-6 h-6 rounded-full bg-foreground text-background hover:opacity-80 transition-opacity`,children:(0,Z.jsx)(nn,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:o&&a.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):a.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No contexts found`}):(0,Z.jsx)(`div`,{className:`space-y-1.5 px-2`,children:f.map((r,a)=>{let o=e.selectedEntityId===r.id,s=p(r),u=r.workspaceActive!==!1,d=If(r.color);return(0,Z.jsxs)(`div`,{...m(a),"data-active":o||void 0,className:K(`group relative rounded-md py-2.5 pl-3 pr-7 transition-all shadow-elevation-1`,u?`cursor-pointer hover:shadow `+(o?`bg-accent shadow`:`bg-card hover:bg-accent/50`):`cursor-not-allowed opacity-50 bg-card`,_(a,f.length),g===a&&`opacity-60`),onClick:()=>u&&v(r),title:u?void 0:`Workspace "${r.workspaceName}" is not active`,children:[s?(0,Z.jsx)(`div`,{className:K(`absolute inset-y-0 right-0 w-4 rounded-r-md`,!d&&`bg-muted`),style:d?{backgroundColor:d}:void 0}):(0,Z.jsx)(`button`,{type:`button`,...h(a),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:K(`absolute inset-y-0 right-0 flex w-4 cursor-grab items-center justify-center rounded-r-md active:cursor-grabbing`,!d&&`bg-muted`),style:d?{backgroundColor:d}:void 0,children:(0,Z.jsx)(lr,{className:K(`h-3.5 w-3.5`,Lf(d))})}),(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(c,{icon:r.icon||`ph:stack-fill`,width:16,height:16,color:d,className:K(`mt-0.5 shrink-0`,!d&&`text-muted-foreground`)}),(0,Z.jsx)(`span`,{className:`text-sm font-medium truncate flex-1`,children:r.name||r.id}),s&&(0,Z.jsx)(`span`,{className:`rounded-full bg-info/10 px-1.5 py-0.5 text-[9px] text-info shrink-0`,children:`Shared`}),u&&(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),t(r.id),n(`detail`,r.id)},className:`reveal-on-hover shrink-0 mt-0.5`,title:`Switch context URL`,children:(0,Z.jsx)(qt,{className:`w-3.5 h-3.5 text-muted-foreground hover:text-foreground`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),t(r.id),i?n(`settings`,r.id):l(`/contexts/${r.id}/settings/general`)},className:`reveal-on-hover shrink-0 mt-0.5`,title:`Settings`,children:(0,Z.jsx)(mn,{className:`w-3.5 h-3.5 text-muted-foreground hover:text-foreground`})})]}),r.name&&(0,Z.jsx)(`div`,{className:`text-[10px] text-muted-foreground/60 truncate font-mono`,children:r.id}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5`,children:r.url||`/`}),r.ownerEmail&&(0,Z.jsx)(`div`,{className:`text-[10px] text-muted-foreground truncate mt-0.5`,children:r.ownerEmail})]},`${r.userId||`u`}-${r.id}`)})})})]})}function z1({title:e,onBack:t,action:n,className:r,icon:i,accentColor:a}){let{closeM1:o}=Eb(),s=If(a);return(0,Z.jsxs)(`div`,{className:K(`flex items-center h-12 px-2 border-b border-border shrink-0 gap-1`,r),style:{...s?{borderLeft:`6px solid ${s}`}:{},borderBottomWidth:3,...s?{borderBottomColor:s}:{}},children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:t,className:`flex items-center gap-0.5 h-8 rounded px-1 hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors flex-1 min-w-0`,title:`Back`,children:[(0,Z.jsx)(ve,{className:`w-4 h-4 shrink-0`}),i&&(0,Z.jsx)(c,{icon:i,width:16,height:16,color:s,className:K(`mr-1 shrink-0`,!s&&`text-muted-foreground`)}),(0,Z.jsx)(`span`,{className:`text-sm font-semibold truncate`,children:e})]}),n&&(0,Z.jsx)(`div`,{className:`shrink-0`,children:n}),(0,Z.jsx)(`button`,{type:`button`,onClick:o,className:`flex h-8 w-8 shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Close menu`,"aria-label":`Close menu`,children:(0,Z.jsx)(je,{className:`w-4 h-4`})})]})}var B1=22,V1=44,H1=4;function U1(e,t){if(!t)return null;let n=String(e||``).split(`/`).filter(Boolean);return n[0]===`workspace`&&n.length>=2?{address:`workspace:${n[1]}`,key:n.slice(2).join(`/`)}:n[0]===`device`&&n.length>=3?{address:n[2],key:n.slice(3).join(`/`)}:n[0]===`file`&&n.length>=2?{address:n[1],key:n.slice(2).join(`/`)}:null}function W1(e,t){if(!t)return null;let n=String(e||``).split(`/`).filter(Boolean);return n[0]===`workspace`&&n.length>=2?`workspace:${n[1]}`:n[0]===`device`?n.length>=3?n[2]:null:n.length>=2?n[1]:null}function G1({x:e,y:t,node:n,path:r,isBackendsTree:i,onClose:a,onShowContent:o,onOpenToSide:s,sourceLayer:c,targetLayers:l,clipboard:u,onStartInlineCreate:d,onChangeIcon:f,onNewCanvas:p,onShareCanvas:m,onRemove:h,onRename:g,onLock:_,onUnlock:v,onDestroy:y,onMerge:b,onSubtract:x,onMergeDown:S,onSubtractDown:C,onResyncBackend:w,onAddRule:T,onSyncFolderTree:E,onAddStoreRule:D,onRenameBackendFolder:O,onDeleteBackendFolder:k,onCopy:A,onCut:j,onPaste:N,pastedDocumentIds:P,onPasteDocuments:ee,isPinned:F,onTogglePin:I}){let ne=c&&l.size>0&&c.path===r,re=!i&&(S||C)&&r!==`/`&&n.type!==`canvas`&&r.split(`/`).filter(Boolean).length>1,R=c&&l.size>0&&(c.path===r||l.has(r)),ie=async e=>{try{await e()}catch(e){alert(e instanceof Error?e.message:String(e))}a()},ae=(e,t,n,r=!1)=>(0,Z.jsxs)(`button`,{type:`button`,className:K(`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,r&&`text-destructive hover:bg-destructive/10`),onClick:()=>ie(n),children:[e,t]});return(0,Z.jsxs)(_f,{x:e,y:t,onClose:a,className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:[o&&ae((0,Z.jsx)(Dt,{className:`w-3 h-3`}),`Show layer content`,async()=>{o(r,n.id||void 0)}),s&&ae((0,Z.jsx)(Dt,{className:`w-3 h-3`}),`Open to the side`,async()=>{s(r)}),(o||s)&&(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),n.type===`canvas`&&m&&ae((0,Z.jsx)(Tn,{className:`w-3 h-3`}),`Share canvas`,async()=>{await m(r)}),n.type===`canvas`&&m&&(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),w&&W1(r,i)&&(0,Z.jsxs)(Z.Fragment,{children:[ae((0,Z.jsx)(M,{className:`w-3 h-3`}),`Resync backend (${W1(r,i)})`,async()=>{await w(r)}),(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),i&&W1(r,i)&&(T||E||D)&&(0,Z.jsxs)(Z.Fragment,{children:[T&&ae((0,Z.jsx)(Dn,{className:`w-3 h-3`}),`Auto-Link documents to…`,async()=>{T(r)}),D&&U1(r,i)&&ae((0,Z.jsx)(_e,{className:`w-3 h-3`}),`Create storage rule…`,async()=>{D(r)}),E&&ae((0,Z.jsx)(L,{className:`w-3 h-3`}),`Sync folders into Directory`,async()=>{await E(r)}),(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),!i&&D&&r!==`/`&&(0,Z.jsxs)(Z.Fragment,{children:[ae((0,Z.jsx)(_e,{className:`w-3 h-3`}),`Create rule…`,async()=>{D(r)}),ae((0,Z.jsx)(wn,{className:`w-3 h-3`}),`Create download rule…`,async()=>{D(r,`download`)}),(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),(!i||U1(r,i))&&(0,Z.jsxs)(`button`,{type:`button`,className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,onClick:()=>{d(r),a()},children:[(0,Z.jsx)(nn,{className:`w-3 h-3`}),`New folder here`]}),O&&U1(r,i)?.key&&ae((0,Z.jsx)(Pe,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=r.split(`/`).pop()||``,t=prompt(`New folder name:`,e);!t||t===e||await O(r,t)}),k&&U1(r,i)?.key&&ae((0,Z.jsx)(lt,{className:`w-3 h-3`}),`Delete folder`,async()=>{confirm(`Delete folder "${r.split(`/`).pop()}" and its contents from the backend?`)&&await k(r)},!0),p&&!i&&(0,Z.jsxs)(`button`,{type:`button`,className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,onClick:()=>{p(r),a()},children:[(0,Z.jsx)(mt,{className:`w-3 h-3 text-primary`}),`New canvas here…`]}),r!==`/`&&I&&ae(F?(0,Z.jsx)(te,{className:`w-3 h-3`}):(0,Z.jsx)(De,{className:`w-3 h-3`}),F?`Unpin`:`Pin`,async()=>{await I()}),r!==`/`&&f&&(0,Z.jsxs)(`button`,{type:`button`,className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,onClick:()=>{f(),a()},children:[(0,Z.jsx)(z,{className:`w-3 h-3`}),`Change icon`]}),r!==`/`&&!n.locked&&g&&!i&&ae((0,Z.jsx)(Pe,{className:`w-3 h-3`}),`Rename`,async()=>{let e=r.split(`/`).pop()||``,t=prompt(`New name:`,e);!t||t===e||await g(r,t)}),(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),ae((0,Z.jsx)(Ct,{className:`w-3 h-3`}),`Copy`,async()=>A(r)),!i&&ae((0,Z.jsx)(wt,{className:`w-3 h-3`}),`Cut`,async()=>j(r)),u&&!i&&ae((0,Z.jsx)(Ve,{className:`w-3 h-3`}),`Paste (${u.mode})`,async()=>N(r)),P&&P.length>0&&ee&&ae((0,Z.jsx)(Ve,{className:`w-3 h-3`}),`Paste ${P.length} document(s)`,async()=>{await ee(r,P)}),r!==`/`&&!n.locked&&h&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),ae((0,Z.jsx)(lt,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${r}"?`)&&await h(r,!1)},!0),ae((0,Z.jsx)(lt,{className:`w-3 h-3`}),`Remove recursive`,async()=>{confirm(`Remove "${r}" and all children?`)&&await h(r,!0)},!0),i&&(0,Z.jsxs)(Z.Fragment,{children:[ae((0,Z.jsx)(lt,{className:`w-3 h-3`}),`Remove and purge documents`,async()=>{confirm(`Remove "${r}" and all children, and PERMANENTLY purge every document under it from the index?`)&&await h(r,!0,!0)},!0),ae((0,Z.jsx)(lt,{className:`w-3 h-3`}),`Remove, purge and destroy on backend`,async()=>{confirm(`Remove "${r}" and all children, purge every document under it from the index, and PERMANENTLY DELETE the mirrored files/messages on the backend?`)&&await h(r,!0,!0,!0)},!0)]})]}),(_||v||y)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),n.locked?v&&ae((0,Z.jsx)(Et,{className:`w-3 h-3`}),`Unlock layer`,async()=>{await v(n.id)}):_&&ae((0,Z.jsx)(Fn,{className:`w-3 h-3`}),`Lock layer`,async()=>{await _(n.id)}),n.locked&&n.lockedBy&&n.lockedBy.length>0&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`px-3 pt-1 pb-0.5 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`Locked by`}),n.lockedBy.map(e=>(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-3 py-1 text-xs`,children:[(0,Z.jsx)(`span`,{className:`truncate`,title:e,children:e}),v&&(0,Z.jsx)(`button`,{type:`button`,title:`Remove lock held by ${e}`,className:`shrink-0 text-muted-foreground hover:text-destructive`,onClick:()=>ie(async()=>{await v(n.id,e)}),children:(0,Z.jsx)(Et,{className:`w-3 h-3`})})]},e))]}),r!==`/`&&!n.locked&&y&&ae((0,Z.jsx)(lt,{className:`w-3 h-3`}),`Destroy layer`,async()=>{confirm(`Permanently destroy layer "${n.label||n.name}" and its bitmap?`)&&await y(n.id)},!0)]}),re&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),S&&ae((0,Z.jsx)(Un,{className:`w-3 h-3`}),`Merge down (into ancestors)`,async()=>{confirm(`Merge "${n.label||n.name}" into every layer above it on\n${r}\n\nAfter this, ${r} lists its documents.`)&&await S(r)}),C&&ae((0,Z.jsx)(Xt,{className:`w-3 h-3`}),`Subtract from ancestors`,async()=>{confirm(`Remove "${n.label||n.name}"'s documents from every layer above it on\n${r}\n\nUndo of "Merge down". Documents an ancestor holds for other reasons are removed from it too.`)&&await C(r)})]}),ne&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),b&&ae((0,Z.jsx)(ar,{className:`w-3 h-3`}),`Merge this layer into ${l.size} selected`,async()=>{confirm(`Merge "${r}" (source) INTO:\n${Array.from(l.keys()).join(`
|
|
88
|
+
`)}\n\nThe selected layers gain this layer's documents. This layer is unchanged.`)&&await b(n.id,Array.from(l.values()))}),x&&ae((0,Z.jsx)(ar,{className:`w-3 h-3`}),`Subtract this layer from ${l.size} selected`,async()=>{confirm(`Subtract "${r}" (source) FROM:\n${Array.from(l.keys()).join(`
|
|
89
|
+
`)}\n\nThe selected layers lose this layer's documents. This layer is unchanged.`)&&await x(n.id,Array.from(l.values()))})]}),R&&!ne&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),(0,Z.jsxs)(`div`,{className:`px-3 py-1.5 text-[10px] text-muted-foreground italic`,children:[`This is a target. Right-click the source (`,c?.path,`) to merge/subtract`]})]})]})}function K1({onConfirm:e,onCancel:t,placeholder:n=`folder name…`}){let r=(0,X.useRef)(null);(0,X.useEffect)(()=>{r.current?.focus()},[]);let i=()=>{let n=r.current?.value.trim()??``;n?e(n):t()};return(0,Z.jsxs)(`div`,{className:`flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 bg-card ring-1 ring-primary/50 shadow-elevation-3 text-sm font-medium`,children:[(0,Z.jsx)(B,{className:`w-4 h-4 opacity-0 shrink-0`}),(0,Z.jsx)(`input`,{ref:r,className:`flex-1 bg-transparent outline-none min-w-0 text-sm font-medium placeholder:font-normal placeholder:text-muted-foreground`,placeholder:n,onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),i()),e.key===`Escape`&&t()},onBlur:i})]})}function q1(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function J1(e,t,n){let r=q1(t,e.name);return r.toLowerCase().includes(n)||(e.label||``).toLowerCase().includes(n)?!0:e.children?.some(e=>J1(e,r,n))??!1}function Y1({node:e,parentPath:t,depth:n,isLast:r,selectedPath:i,pendingPath:a,contentPath:o,readOnly:s,sourceLayer:l,targetLayers:u,clipboard:d,searchQuery:f,inlineCreateParent:p,onSelect:m,onShiftSelect:h,onShowContent:g,onCtrl:_,onCtxMenu:v,onConfirmCreate:y,onCancelCreate:b,onOpenPicker:x,styleOverrides:S,dragOverPath:C,isCopyDrag:w,onDragStart:T,onDragEnter:E,onDragOver:D,onDragLeave:O,onDragEnd:k,onDrop:A,resyncingPaths:j,accordion:N=!1,trail:P=[]}){let ee=df(),F=q1(t,e.name),I=S.get(F)??Df(e),[te,ne]=(0,X.useState)(()=>i!==`/`&&(i===F||i.startsWith(F+`/`))),[L,re]=(0,X.useState)(i);if(L!==i&&(re(i),i!==`/`&&i.startsWith(F+`/`)&&ne(!0)),f&&!J1(e,t,f))return null;let R=te||p===F||f.length>0,ie=e.children&&e.children.length>0,ae=i===F,oe=a===F,z=l?.path===F,se=u.has(F),ce=e.type===`canvas`,V=t=>{if(t.ctrlKey||t.metaKey){_(F,e.id);return}if(t.shiftKey&&h){h(F);return}m(F)},le=[...P].reverse().find(Boolean)??null,ue=I.color||le,de=N?[...P,ue]:P,fe=i!==`/`&&i.startsWith(F+`/`),pe=!z&&!se,me=pe&&ae,H=(e,t)=>`color-mix(in oklab, ${e} ${t}%, var(--card))`,he=e=>`color-mix(in oklab, currentColor ${e}%, transparent)`,ge=Math.min(n,5),_e=R&&!!ie,ve=n>0&&le?le:ue,ye=pe&&!me&&!e.locked&&_e,U=ve?Math.min(12+ge*5+(fe?6:0),34):Math.min(ge*7+(fe?5:0)+(oe?3:0),30),be=me?`var(--primary)`:z?H(`var(--info)`,22):se?H(`var(--warning)`,22):e.locked?H(`var(--warning)`,20+ge*4):ye?ue?H(ue,84):H(`var(--foreground)`,38):H(ve||`var(--foreground)`,U),xe=me?`text-primary-foreground`:ye&&ue?Rf(ue):`text-foreground`,Se=N&&R&&ie&&n<H1,Ce=(0,Z.jsxs)(`div`,{"data-active":ae||void 0,className:K(`group relative flex cursor-pointer select-none items-stretch overflow-hidden text-sm`,`after:pointer-events-none after:absolute after:inset-0 after:bg-foreground/0 after:transition-colors hover:after:bg-foreground/[0.07]`,xe,z&&`ring-1 ring-inset ring-info/40`,se&&!z&&`ring-1 ring-inset ring-warning/40`,C===F&&!s&&!w&&`ring-2 ring-inset ring-info`,C===F&&!s&&w&&`ring-2 ring-inset ring-success`),style:{height:V1,background:be,borderBottom:`1px solid ${he(14)}`,...Se?{position:`sticky`,top:n*V1,zIndex:20-n}:{}},draggable:!s,onClick:V,...s?{}:ee,onContextMenu:t=>{s||(t.preventDefault(),v(t,F,e))},onDragStart:e=>{s||T(F,e)},onDragEnter:e=>{s||E(F,e)},onDragOver:e=>{s||D(F,e)},onDragLeave:e=>O(F,e),onDragEnd:()=>k(),onDrop:e=>{s||A(F,e)},children:[P.length>0&&(0,Z.jsx)(`span`,{className:`flex shrink-0 gap-px`,"aria-hidden":!0,children:P.map((e,t)=>(0,Z.jsx)(`span`,{className:`w-[3px]`,style:{background:e||he(28)}},t))}),(()=>{let t=I.color?{background:I.color}:le?{background:`color-mix(in oklab, ${le} 45%, transparent)`}:{background:he(10)},n=(0,Z.jsx)(c,{icon:I.icon||(ce?`ph:squares-four-fill`:`ph:folder-fill`),width:18,height:18,className:K(`shrink-0`,I.color?Lf(I.color):me?`text-primary-foreground`:ye?`text-current`:`text-foreground/80`)}),r=`flex w-10 shrink-0 items-center justify-center`;return x?(0,Z.jsx)(`button`,{type:`button`,className:r,style:t,title:`Change icon`,onClick:t=>{hr()||(t.stopPropagation(),x(t,F,e))},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),x(t,F,e)},children:n}):(0,Z.jsx)(`span`,{className:r,style:t,children:n})})(),(0,Z.jsx)(`span`,{className:K(`min-w-0 flex-1 self-center truncate px-2.5`,ae||fe||_e?`font-semibold`:`font-medium`),title:e.description||void 0,children:e.label||e.name}),j?.has(F)&&(0,Z.jsx)(M,{className:`mr-1 h-3.5 w-3.5 shrink-0 animate-spin self-center opacity-70`,"aria-label":`Indexing`}),!s&&(0,Z.jsx)(`button`,{type:`button`,className:`reveal-on-hover shrink-0 self-center rounded p-1 hover:bg-foreground/10`,onClick:t=>{t.stopPropagation(),v(t,F,e)},children:(0,Z.jsx)(jt,{className:`h-4 w-4`})}),(0,Z.jsx)(`button`,{type:`button`,className:K(`relative z-[1] flex w-12 shrink-0 cursor-pointer items-center justify-center transition-colors`,`bg-[color-mix(in_oklab,currentColor_9%,transparent)] hover:bg-[color-mix(in_oklab,currentColor_24%,transparent)] active:bg-[color-mix(in_oklab,currentColor_32%,transparent)]`,!ie&&p!==F&&`invisible`),style:{borderLeft:`1px solid ${he(16)}`},"aria-label":R?`Collapse`:`Expand`,"aria-expanded":R,title:R?`Collapse`:`Expand`,onClick:e=>{e.stopPropagation(),ne(e=>!e)},children:R?(0,Z.jsx)(Ne,{className:`h-5 w-5`,strokeWidth:2.25}):(0,Z.jsx)(B,{className:`h-5 w-5`,strokeWidth:2.25})})]});return(0,Z.jsxs)(`div`,{className:`relative`,children:[N?Ce:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`pointer-events-none absolute top-0 w-px bg-border`,style:{left:`-${B1/2}px`,...r?{height:`1.375rem`}:{bottom:0}}}),(0,Z.jsx)(`div`,{className:`pointer-events-none absolute top-[1.375rem] h-px bg-border`,style:{left:`-${B1/2}px`,width:`${B1/2}px`}}),(0,Z.jsxs)(`div`,{"data-active":ae||void 0,className:K(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none overflow-hidden`,`shadow-elevation-3 hover:shadow-elevation-4 text-sm`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,z&&`ring-1 ring-info/40 bg-info/10 before:bg-info`,se&&!z&&`ring-1 ring-warning/40 bg-warning/10 before:bg-warning`,!z&&!se&&ae&&!e.locked&&`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`,!z&&!se&&ae&&e.locked&&`bg-warning/15 hover:bg-warning/20 before:bg-primary`,!z&&!se&&!ae&&oe&&`bg-primary/[0.03] before:bg-transparent`,!z&&!se&&!ae&&!oe&&!e.locked&&`bg-card hover:bg-primary/[0.04] before:bg-transparent`,!z&&!se&&!ae&&e.locked&&`bg-warning/15 hover:bg-warning/20 before:bg-warning`,C===F&&!s&&!w&&`ring-2 ring-info bg-info-subtle/50`,C===F&&!s&&w&&`ring-2 ring-success bg-success-subtle/50`),style:{borderRight:I.color?`4px solid ${I.color}`:`4px solid transparent`},draggable:!s,onClick:V,...s?{}:ee,onContextMenu:t=>{s||(t.preventDefault(),v(t,F,e))},onDragStart:e=>{s||T(F,e)},onDragEnter:e=>{s||E(F,e)},onDragOver:e=>{s||D(F,e)},onDragLeave:e=>O(F,e),onDragEnd:()=>k(),onDrop:e=>{s||A(F,e)},children:[(0,Z.jsx)(`button`,{type:`button`,className:K(`shrink-0 text-muted-foreground hover:text-foreground`,!ie&&p!==F&&`invisible`),onClick:e=>{e.stopPropagation(),ne(e=>!e)},children:R?(0,Z.jsx)(Ne,{className:`w-4 h-4`}):(0,Z.jsx)(B,{className:`w-4 h-4`})}),(()=>{let t=(0,Z.jsx)(c,{icon:I.icon||(ce?`ph:squares-four-fill`:`ph:folder-fill`),width:16,height:16,color:I.color||void 0,className:K(`shrink-0`,!I.color&&(ce?`text-primary`:`text-muted-foreground`))});return x?(0,Z.jsx)(`button`,{type:`button`,className:`shrink-0 rounded p-0.5 -m-0.5 hover:bg-muted-foreground/10 touch-target`,title:`Change icon`,onClick:t=>{hr()||(t.stopPropagation(),x(t,F,e))},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),x(t,F,e)},children:t}):t})(),(0,Z.jsx)(`span`,{className:`flex-1 truncate font-medium`,title:e.description||void 0,children:e.label||e.name}),j?.has(F)&&(0,Z.jsx)(M,{className:`w-3.5 h-3.5 shrink-0 animate-spin text-muted-foreground`,"aria-label":`Indexing`}),!s&&(0,Z.jsx)(`button`,{type:`button`,className:`shrink-0 reveal-on-hover p-1 rounded hover:bg-muted-foreground/10 text-muted-foreground`,onClick:t=>{t.stopPropagation(),v(t,F,e)},children:(0,Z.jsx)(jt,{className:`w-4 h-4`})})]})]}),R&&(ie||p===F)&&(0,Z.jsxs)(`div`,{className:N?void 0:`ml-[22px] mt-2 mb-1 space-y-1.5`,children:[p===F&&(0,Z.jsx)(K1,{onConfirm:e=>y(F,e),onCancel:b}),e.children?.map((t,r)=>(0,Z.jsx)(Y1,{node:t,parentPath:F,depth:n+1,isLast:r===(e.children?.length??0)-1,selectedPath:i,pendingPath:a,contentPath:o,readOnly:s,sourceLayer:l,targetLayers:u,clipboard:d,searchQuery:f,inlineCreateParent:p,onSelect:m,onShiftSelect:h,onShowContent:g,onCtrl:_,onCtxMenu:v,onConfirmCreate:y,onCancelCreate:b,onOpenPicker:x,styleOverrides:S,dragOverPath:C,isCopyDrag:w,onDragStart:T,onDragEnter:E,onDragOver:D,onDragLeave:O,onDragEnd:k,onDrop:A,resyncingPaths:j,accordion:N,trail:de},t.id||t.name))]})]})}function X1({root:e,treeName:t=`context`,isBackendsTree:n=!1,selectedPath:r,pendingPath:i,onSelect:a,isLoading:o=!1,readOnly:s=!1,onAddRule:c,onSyncFolderTree:l,onAddStoreRule:u,rootLabel:d,contentPath:f,onShowContent:p,onOpenToSide:m,onShiftSelect:h,onInsertPath:g,onNewCanvas:_,onShareCanvas:v,onRemovePath:y,onRenamePath:b,onMovePath:x,onCopyPath:S,pastedDocumentIds:C,onPasteDocuments:w,onLockLayer:T,onUnlockLayer:E,onDestroyLayer:D,onMergeLayer:O,onSubtractLayer:k,onMergeDown:A,onSubtractDown:j,onResyncBackend:M,onCreateBackendFolder:N,onRenameBackendFolder:P,onDeleteBackendFolder:ee,onUpdateNode:F,isPathPinned:I,onTogglePin:te,searchQuery:ne=``,resyncingPaths:L}){let re=Gw(),[R,ie]=(0,X.useState)(null),[ae,oe]=(0,X.useState)(null),[z,se]=(0,X.useState)(new Map),[ce,B]=(0,X.useState)(null),[V,le]=(0,X.useState)(null),[ue,de]=(0,X.useState)(new Map),[fe,pe]=(0,X.useState)(e),me=(0,X.useRef)(new Map),H=(0,X.useRef)(null),[he,ge]=(0,X.useState)(null);if(e!==fe){pe(e);let t=he;de(t?new Map([[t.path,t.style]]):new Map)}let[_e,ve]=(0,X.useState)(null),[ye,U]=(0,X.useState)(null),[be,xe]=(0,X.useState)(!1),[Se,Ce]=(0,X.useState)(!1),[W,G]=(0,X.useState)(!1),we=(0,X.useRef)(!1),Te=(0,X.useRef)(null),Ee=(0,X.useRef)(t),De=(0,X.useRef)(!1),Oe=(0,X.useRef)(!1);(0,X.useEffect)(()=>{let e=e=>{ie(e.detail??null)};return window.addEventListener(`tree:path-clipboard`,e),()=>window.removeEventListener(`tree:path-clipboard`,e)},[]),(0,X.useEffect)(()=>{let e=e=>{let t=e.ctrlKey||e.altKey||Oe.current;De.current=t,xe(t)};return window.addEventListener(`keydown`,e),window.addEventListener(`keyup`,e),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`keyup`,e)}},[]);let ke=(0,X.useCallback)((e,n,r)=>{if(Ee.current!==t)return!0;let i=e.endsWith(`/`)?e.slice(0,-1):e,a=n.endsWith(`/`)?n.slice(0,-1):n,o=i.substring(0,i.lastIndexOf(`/`))||`/`;return!(a.startsWith(i+`/`)||i===a||!r&&a===o)},[t]),Ae=(0,X.useCallback)((e,n)=>{Te.current=e,Ee.current=t,n.dataTransfer.setData(`text/plain`,e),n.dataTransfer.setData(`application/x-canvas-tree-path`,JSON.stringify({path:e,treeName:t})),n.dataTransfer.effectAllowed=`copyMove`},[t]),je=e=>e.ctrlKey||e.altKey||Oe.current,Me=(0,X.useCallback)((e,t)=>{let n=Te.current,r=je(t);r!==De.current&&(De.current=r,xe(r)),!(n&&!ke(n,e,r))&&(t.preventDefault(),U(e))},[ke]),Pe=(0,X.useCallback)((e,t)=>{let n=je(t);n!==De.current&&(De.current=n,xe(n));let r=Te.current;if(r&&!ke(r,e,n)){t.dataTransfer.dropEffect=`none`;return}t.preventDefault(),t.dataTransfer.dropEffect=n?`copy`:`move`},[ke]),Fe=(0,X.useCallback)((e,t)=>{t.currentTarget.contains(t.relatedTarget)||U(t=>t===e?null:t)},[]),Ie=(0,X.useCallback)(()=>{Te.current=null,Ee.current=t,De.current=!1,xe(!1),U(null)},[t]),Le=(0,X.useCallback)(async(e,r)=>{r.preventDefault();let i=(()=>{try{return JSON.parse(r.dataTransfer.getData(`application/json`))}catch{return null}})();if(i?.type===`document`&&Array.isArray(i.documentIds)&&i.documentIds.length){if(Te.current=null,De.current=!1,xe(!1),U(null),w)try{await w(e,i.documentIds)}catch(e){alert(e instanceof Error?e.message:String(e))}return}let a=(()=>{try{return JSON.parse(r.dataTransfer.getData(`application/x-canvas-tree-path`))}catch{return null}})(),o=a?.path||r.dataTransfer.getData(`text/plain`),s=a?.treeName||Ee.current||t,c=je(r)||De.current;if(Te.current=null,Ee.current=t,De.current=!1,xe(!1),U(null),!o)return;let l=r.shiftKey,u=s!==t;if(!(!u&&o===e)&&!(!u&&!ke(o,e,c)))try{if(c&&S)await S(o,e,l,s,t);else if(!c&&x){let r=we.current&&!n&&!!A;await x(o,e,l,s,t,r?{mergeDown:r}:void 0)}}catch(e){alert(e instanceof Error?e.message:String(e))}},[ke,S,x,w,t,n,A]),Re=ne.toLowerCase().trim(),ze=(0,X.useCallback)((e,t,n)=>{e.stopPropagation(),B({x:e.clientX,y:e.clientY,path:t,node:n})},[]),Be=(0,X.useCallback)((e,t,n)=>{e.stopPropagation(),H.current=null,ge(null),le({x:e.clientX,y:e.clientY,path:t,node:n})},[]),Ve=(0,X.useCallback)(e=>{if(!V||!F)return;let t=V.path,n={...ue.get(t)??(H.current?.path===t?H.current.style:Df(V.node)),...e};H.current={path:t,style:n},ge({path:t,style:n}),de(e=>new Map(e).set(t,n));let r=kf(V.node.metadata,n),i=me.current,a=i.get(t);a&&clearTimeout(a),i.set(t,setTimeout(()=>{i.delete(t),F(t,{metadata:r}).catch(e=>alert(e instanceof Error?e.message:String(e)))},350))},[V,F,ue]),He=(0,X.useCallback)((e,t)=>{ae?e===ae.path?(oe(null),se(new Map)):se(n=>{let r=new Map(n);return r.has(e)?r.delete(e):r.set(e,t),r}):(oe({path:e,id:t}),se(new Map))},[ae]),Ue=(0,X.useCallback)(async e=>{!R||!x||!S||R.treeName===t&&(e===R.path||e.startsWith(R.path+`/`))||(R.mode===`cut`?(await x(R.path,e,!1,R.treeName,t),ie(null),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:null}))):await S(R.path,e,!0,R.treeName,t))},[R,x,S,t]);(0,X.useEffect)(()=>{if(s)return;let e=e=>{let n=e.target;if(n?.tagName===`INPUT`||n?.tagName===`TEXTAREA`||e.key!==`F6`)return;if(e.preventDefault(),R?.mode===`cut`){Ue(r);return}let i={mode:`cut`,path:r,treeName:t};ie(i),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:i}))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[R,Ue,s,r,t]);let We=(0,X.useCallback)(async(e,t)=>{ve(null);let r=e===`/`?`/${t}`:`${e}/${t}`;try{U1(e,n)&&N?await N(e,t)&&a(r):g&&await g(r,!0)&&a(r)}catch(e){alert(e instanceof Error?e.message:String(e))}},[g,N,a,n]),Ge=(0,X.useCallback)(()=>{ve(null)},[]),Ke=(0,X.useCallback)(t=>{if(s||!y||t.key!==`Delete`&&t.key!==`Backspace`)return;let n=t.target;if(n?.tagName!==`INPUT`&&n?.tagName!==`TEXTAREA`&&!(!r||r===`/`)){if(t.preventDefault(),xr(e,r)?.locked){alert(`"${r}" is locked`);return}confirm(`Remove "${r}"?`)&&y(r,!1).catch(e=>alert(e instanceof Error?e.message:String(e)))}},[s,y,r,e]),qe=(0,X.useCallback)(()=>{Ce(e=>{let t=!e;return Oe.current=t,De.current=t,xe(t),t})},[]);if(o)return(0,Z.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading tree…`});if(!e)return(0,Z.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`No tree available`});let Je=ae||z.size>0,Ye={accordion:re,selectedPath:r,pendingPath:i,contentPath:f,readOnly:s,sourceLayer:ae,targetLayers:z,clipboard:R,searchQuery:Re,inlineCreateParent:_e,onSelect:a,onShiftSelect:h,onShowContent:p,onCtrl:He,onCtxMenu:ze,onConfirmCreate:We,onCancelCreate:Ge,onOpenPicker:F?Be:void 0,styleOverrides:ue,dragOverPath:ye,isCopyDrag:be,onDragStart:Ae,onDragEnter:Me,onDragOver:Pe,onDragLeave:Fe,onDragEnd:Ie,onDrop:Le,resyncingPaths:L};return(0,Z.jsxs)(`div`,{className:`px-3 py-2 space-y-1.5 outline-none`,tabIndex:0,onKeyDown:Ke,children:[!s&&(0,Z.jsxs)(`div`,{className:`flex items-center justify-end px-1 pb-0.5 text-[10px]`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:qe,title:`Toggle drag-drop mode (or hold Ctrl / Alt while dragging)`,className:K(`px-2 py-0.5 rounded-full border transition-colors select-none`,Se?`border-success bg-success/15 text-success dark:text-success`:`border-border text-muted-foreground hover:bg-muted`),children:Se?`Drag → Copy`:`Drag → Move`}),A&&!n&&!Se&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>G(e=>(we.current=!e,!e)),title:`When moving a layer, also merge it into its new ancestors so the new path lists its documents`,className:K(`ml-1 px-2 py-0.5 rounded-full border transition-colors select-none`,W?`border-info bg-info/15 text-info dark:text-info`:`border-border text-muted-foreground hover:bg-muted`),children:W?`+ merge down`:`merge down: off`})]}),Je&&(0,Z.jsxs)(`div`,{className:`flex items-center justify-between px-1 pb-1 text-[10px] text-muted-foreground`,children:[(0,Z.jsx)(`span`,{children:ae?`Source: ${ae.path} · ${z.size} target(s)`:`Select source with ⌃-click`}),(0,Z.jsx)(`button`,{type:`button`,className:`hover:text-foreground underline`,onClick:()=>{oe(null),se(new Map)},children:`clear`})]}),(0,Z.jsxs)(`div`,{"data-active":r===`/`&&!f||void 0,className:K(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none`,`shadow-elevation-3 hover:shadow-elevation-4 text-sm`,r===`/`&&!f?`bg-primary/[0.06]`:`bg-card hover:bg-primary/[0.04]`,ye===`/`&&!s&&!be&&`ring-2 ring-info bg-info-subtle/50`,ye===`/`&&!s&&be&&`ring-2 ring-success bg-success-subtle/50`),style:{borderRight:`4px solid transparent`},onClick:()=>a(`/`),onDragEnter:e=>{s||Me(`/`,e)},onDragOver:e=>{s||Pe(`/`,e)},onDragLeave:e=>Fe(`/`,e),onDrop:e=>{s||Le(`/`,e)},onContextMenu:e=>{!s&&g&&(e.preventDefault(),B({x:e.clientX,y:e.clientY,path:`/`,node:{id:``,name:`/`,label:`/`,type:`root`,description:``,color:null,locked:!1,children:[]}}))},children:[(0,Z.jsx)(Ne,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`flex-1 font-medium truncate`,children:[`/ `,d&&(0,Z.jsxs)(`span`,{className:`text-muted-foreground font-normal`,children:[`[`,d,`]`]})]}),!s&&g&&(0,Z.jsx)(`button`,{type:`button`,className:`shrink-0 reveal-on-hover p-1 rounded hover:bg-muted-foreground/10 text-muted-foreground`,onClick:e=>{e.stopPropagation(),B({x:e.clientX,y:e.clientY,path:`/`,node:{id:``,name:`/`,label:`/`,type:`root`,description:``,color:null,locked:!1,children:[]}})},children:(0,Z.jsx)(jt,{className:`w-4 h-4`})})]}),(0,Z.jsxs)(`div`,{className:re?`mt-1.5 border-t border-border/60`:`ml-[22px] mt-1.5 space-y-1.5`,children:[_e===`/`&&(0,Z.jsx)(K1,{onConfirm:e=>We(`/`,e),onCancel:Ge}),e.children?.map((t,n)=>(0,Z.jsx)(Y1,{node:t,parentPath:`/`,depth:0,isLast:n===(e.children?.length??0)-1,...Ye},t.id||t.name)),!e.children?.length&&_e!==`/`&&(0,Z.jsx)(`div`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})]}),ce&&(0,Z.jsx)(G1,{x:ce.x,y:ce.y,node:ce.node,path:ce.path,isBackendsTree:n,onClose:()=>B(null),onShowContent:p,onOpenToSide:m?e=>m(e,t):void 0,sourceLayer:ae,targetLayers:z,clipboard:R,onStartInlineCreate:e=>ve(e),onChangeIcon:F?()=>Be({clientX:ce.x,clientY:ce.y,stopPropagation:()=>{}},ce.path,ce.node):void 0,onNewCanvas:_,onShareCanvas:v,onRemove:s?void 0:y,onRename:s?void 0:b,onLock:s?void 0:T,onUnlock:s?void 0:E,onDestroy:s?void 0:D,onMerge:s?void 0:O,onSubtract:s?void 0:k,onMergeDown:s?void 0:A,onSubtractDown:s?void 0:j,onResyncBackend:M,onAddRule:c,onSyncFolderTree:l,onAddStoreRule:u,onRenameBackendFolder:P,onDeleteBackendFolder:ee,onCopy:e=>{let n={mode:`copy`,path:e,treeName:t};ie(n),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:n}))},onCut:e=>{let n={mode:`cut`,path:e,treeName:t};ie(n),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:n}))},onPaste:Ue,pastedDocumentIds:C,onPasteDocuments:w,isPinned:I?I(ce.path):!1,onTogglePin:te?()=>te(ce.path,ce.node):void 0}),V&&F&&(0,Z.jsx)(Wy,{x:V.x,y:V.y,current:ue.get(V.path)??Df(V.node),onChange:Ve,onClose:()=>le(null)})]})}function Z1({contextId:e,workspaceId:t,treeName:n,onRefresh:r}){let i=n||`context`,a=i===`directory`,o=(0,X.useCallback)((e=150)=>{r&&setTimeout(r,e),t&&setTimeout(()=>window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:t}})),e)},[r,t]),s=(0,X.useCallback)(async(n,r=!0)=>{let a;if(e)a=await Jo(e,n,r);else if(t)a=await Fi(t,n,r,i);else return!1;let s=Of(n);if(a&&s)try{e?await Vo(e,n,s):t&&await _a(t,n,s,i)}catch{}return o(),a},[e,t,i,o]),c=(0,X.useCallback)(async(n,r=!1,a=!1,s=!1)=>{let c;if(e)c=await Bo(e,n,r);else if(t)c=await hi(t,n,r,i,a,s);else return!1;return o(),c},[e,t,i,o]),l=(0,X.useCallback)(async(n,r)=>{let a;if(e){let t=n.split(`/`);t[t.length-1]=r,a=await Wo(e,n,t.join(`/`),!1)}else if(t)a=await _a(t,n,{name:r},i);else return!1;return o(),a},[e,t,i,o]),u=(0,X.useCallback)(async(n,r,a=!1,s=i,c=i,l={})=>{let u;if(e)u=await Wo(e,n,r,a,l);else if(t)u=await ea(t,n,r,a,s,c,l);else return!1;return o(),u},[e,t,i,o]),d=(0,X.useCallback)(async n=>{let r;if(e)r=await fs(e,n);else if(t)r=await ra(t,n,i);else return null;return o(),r},[e,t,i,o]),f=(0,X.useCallback)(async n=>{let r;if(e)r=await Ro(e,n);else if(t)r=await zi(t,n,i);else return null;return o(),r},[e,t,i,o]),p=(0,X.useCallback)(async(n,r,a=!1,s=i,c=i)=>{let l;if(e)l=await Xo(e,n,r,a);else if(t)l=await sa(t,n,r,a,s,c);else return!1;return o(),l},[e,t,i,o]),m=(0,X.useCallback)(async(n,r)=>e?await Vo(e,n,r):t?await _a(t,n,r,i):!1,[e,t,i]),h=(0,X.useCallback)(async(n,r)=>{let a;if(e)a=await jo(e,n,r);else if(t)a=await br(t,n,r,i);else return null;return o(),a},[e,t,i,o]),g=(0,X.useCallback)(async(n,r)=>{let a;if(e)a=await ts(e,n,r);else if(t)a=await Oa(t,n,r,i);else return null;return o(),a},[e,t,i,o]),_=(0,X.useCallback)(async e=>{if(!t)return!1;let n=await $r(t,e,t,i);return o(300),n},[t,i,o]),v=(0,X.useCallback)(async(e,n)=>{if(!t)return!1;try{await Ta(t,e,n??t,i)}catch(e){if(!(e instanceof Error)||!/still locked by/i.test(e.message))throw e}return o(300),!0},[t,i,o]),y=(0,X.useCallback)(async e=>{if(!t)return!1;let n=await Zr(t,e,i);return o(),n},[t,i,o]),b=(0,X.useCallback)(async e=>{if(!t)return!1;let n=await va(t).catch(()=>[]),r=wa(e,n);return r?(await da(t,r.driver,r.address),o(300),!0):!1},[t,o]),x=(0,X.useCallback)(async(e,n)=>{if(!t)return!1;let r=await va(t).catch(()=>[]),i=Ni(e,r);if(!i)return!1;let a=i.key?`${i.key}/${n}`:n;return await Di(t,i.driver,i.address,[a]),o(200),!0},[t,o]),S=(0,X.useCallback)(async(e,n)=>{if(!t)return!1;let r=await va(t).catch(()=>[]),i=Ni(e,r);return!i||!i.key?!1:(await Ir(t,i.driver,i.address,i.key,n),o(200),!0)},[t,o]),C=(0,X.useCallback)(async e=>{if(!t)return!1;let n=await va(t).catch(()=>[]),r=Ni(e,n);return!r||!r.key?!1:(await Rr(t,r.driver,r.address,r.key),o(200),!0)},[t,o]);return{onInsertPath:s,onRemovePath:c,onRenamePath:l,onMovePath:u,onCopyPath:p,onUpdateNode:m,onMergeLayer:h,onSubtractLayer:g,onMergeDown:a?void 0:d,onSubtractDown:a?void 0:f,onLockLayer:t?_:void 0,onUnlockLayer:t?v:void 0,onDestroyLayer:t&&!a?y:void 0,onResyncBackend:t?b:void 0,onCreateBackendFolder:t?x:void 0,onRenameBackendFolder:t?S:void 0,onDeleteBackendFolder:t?C:void 0}}function Q1(){let{state:e,closeM2:t,closeM1:n,closeM0:r,openM2:i}=Eb(),a=Cm(),o=Gc(),s=e.selectedEntityId,{showToast:c}=oo(),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(``),[h,g]=(0,X.useState)(),[_,v]=(0,X.useState)(``),[y,b]=(0,X.useState)(`/`),[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(!1),[T,E]=(0,X.useState)(null),[D,O]=(0,X.useState)(!1),k=(0,X.useCallback)(async e=>{w(!0);try{let t=await Ko(e);f(t),E(null)}catch(e){E(e instanceof Error?e.message:`Failed to load the tree`)}finally{w(!1)}},[]);(0,X.useEffect)(()=>{if(!s)return;let e=s,t=!1;async function n(){try{let n=await $o(e);if(t)return;u(n),m(n.url||``),g(void 0),v(``),S(null),b(n.path||`/`),w(!0);try{let n=await Ko(e);t||(f(n),E(null))}catch(e){t||E(e instanceof Error?e.message:`Failed to load the tree`)}finally{t||w(!1)}}catch{t||c({title:`Error`,description:`Failed to load context`,variant:`destructive`})}}return n(),()=>{t=!0}},[s,c]);let A=Z1({contextId:s??void 0,onRefresh:()=>{s&&k(s)}}),j=e=>{g(void 0),S(e),m(l?.workspaceName?`${l.workspaceName}://${e.replace(/^\//,``)}`:e)},M=l!=null&&(p.trim()!==(l.url||``)||h!==void 0);return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsx)(z1,{title:s||`Context`,icon:l?.icon||`ph:stack-fill`,accentColor:l?.color,onBack:t,action:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{s&&(a?i(`settings`,s):o(`/contexts/${s}/settings/general`))},className:`flex items-center justify-center w-8 h-8 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Settings`,children:(0,Z.jsx)(mn,{className:`w-3.5 h-3.5`})})}),(0,Z.jsxs)(`div`,{className:`p-3 border-b border-border shrink-0`,children:[(0,Z.jsx)(`div`,{className:`text-[10px] text-muted-foreground mb-1.5 font-medium uppercase tracking-wide`,children:`Context URL`}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(uC,{value:p,fixedWorkspaceName:l?.workspaceName,pickerTitle:`Switch context to…`,onPickTarget:(e,t)=>{m(`${t.workspaceName}://${e.replace(/^\/+/,``)}`),g(t.treeName),S(null)},onChange:m,className:`min-w-0 flex-1`,inputClassName:K(`text-xs h-7 font-mono transition-colors`,M&&`border-warning/60 bg-warning/10`),placeholder:`workspace://path`}),(0,Z.jsx)(J,{size:`sm`,className:`h-7 px-2 text-xs shrink-0`,onClick:async()=>{if(!s)return;let e=s;O(!0);try{await Po(e,p,void 0,h);let t=await $o(e);u(t),m(t.url||``),b(t.path||`/`),S(null),g(void 0),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),await k(e),c({title:`Saved`,description:`Context URL updated`}),window.matchMedia(`(max-width: 767px)`).matches&&(n(),r())}catch(e){c({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{O(!1)}},disabled:D,children:D?`…`:`Set`})]})]}),h&&(0,Z.jsxs)(`p`,{className:`px-3 py-1 text-xs text-muted-foreground`,children:[`Destination tree: `,h,` · press Set to apply`]}),(0,Z.jsx)(`div`,{className:`px-3 py-2 border-b shrink-0`,children:(0,Z.jsx)(q,{"aria-label":`Search context tree`,placeholder:`Search paths…`,value:_,onChange:e=>v(e.target.value),className:`h-7 text-xs`})}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,children:[(0,Z.jsxs)(`div`,{className:`text-[10px] text-muted-foreground px-3 pt-2 pb-1 font-medium uppercase tracking-wide shrink-0`,children:[l?.workspaceName||`Workspace`,` · `,d?.type===`directory`?`directory`:`context`,` tree`]}),T&&!d&&(0,Z.jsx)(`p`,{className:`px-3 pb-1 text-xs text-destructive`,children:T}),(0,Z.jsx)(X1,{root:d,searchQuery:_,selectedPath:y,pendingPath:x,onSelect:j,isLoading:C,rootLabel:l?.workspaceName,...A})]})]})}function $1({items:e,activeId:t,onSelect:n}){let[r,i]=(0,X.useState)(``),a=e.filter(e=>ib(r,e.label,e.description||``));return(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:(0,Z.jsxs)(`div`,{className:`space-y-1 px-2`,children:[(0,Z.jsx)(q,{type:`search`,"aria-label":`Search settings sections`,placeholder:`Find a setting…`,className:`mb-3`,value:r,onChange:e=>i(e.target.value)}),!a.length&&(0,Z.jsx)(`p`,{role:`status`,className:`p-3 text-sm text-muted-foreground`,children:`No matching settings.`}),a.map(e=>{let r=e.id===t;return(0,Z.jsxs)(`button`,{type:`button`,"aria-current":r?`page`:void 0,onClick:()=>n(e.id),className:K(`flex w-full items-center gap-2.5 rounded-md px-3 py-2 text-left transition-colors`,r?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50 hover:text-foreground`),children:[(0,Z.jsx)(`span`,{className:K(`shrink-0`,r?`text-foreground`:`text-muted-foreground`),children:e.icon}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium text-foreground`,children:e.label}),e.description&&(0,Z.jsx)(`span`,{className:`mt-1 block text-xs leading-relaxed text-muted-foreground`,children:e.description})]}),(0,Z.jsx)(B,{className:K(`h-3.5 w-3.5 shrink-0`,r?`opacity-100`:`opacity-0`)})]},e.id)})]})})}function e0(){let{state:e,closeM2:t}=Eb(),n=Cm(),r=Gc(),i=Hc(),a=e.selectedEntityId,[o,s]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!a)return;let e=!1;return $o(a).then(t=>{e||s(t)}).catch(()=>{}),()=>{e=!0}},[a]);let c=i.pathname.split(`/`).filter(Boolean),l=c[2]===`settings`?OC(c[3]):null,u=a?`/contexts/${a}`:null,d=(0,X.useMemo)(()=>DC.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,Z.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(z1,{title:`Settings: ${o?.name||a||`Context`}`,icon:o?.icon||`ph:stack-fill`,accentColor:o?.color??null,onBack:()=>u&&!n?r(u):t(),action:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>u&&r(u),className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Open context`,children:(0,Z.jsx)(Gn,{className:`h-3.5 w-3.5`})})}),(0,Z.jsx)($1,{items:d,activeId:l,onSelect:e=>a&&r(`/contexts/${a}/settings/${e}`)})]})}function t0(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(!1),a=(0,X.useRef)(!1),o=(0,X.useRef)(!1),s=(0,X.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await Or();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch workspaces:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,X.useCallback)(()=>{a.current=!1,s()},[s]);return(0,X.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,X.useEffect)(()=>{if(!e)return;let t=()=>Wu.emit(`subscribe`,{channel:`workspace`}),r=()=>Wu.emit(`unsubscribe`,{channel:`workspace`}),i=Wu.on(`connect`,()=>{t(),s()});t();let a=e=>{let t=e,r=t?.workspaceId??t?.id,i=t?.status;!r||!i||n(e=>e.map(e=>e.id===r?{...e,status:i}:e))},o=e=>{let t=e?.workspace??e;t?.id&&n(e=>e.some(e=>e.id===t.id)?e:[...e,t])},c=e=>{let t=e,r=t?.workspaceId??t?.id;r&&n(e=>e.filter(e=>e.id!==r))},l=[[`workspace:status:changed`,a],[`workspace.status.changed`,a],[`workspace:created`,o],[`workspace.created`,o],[`workspace:deleted`,c],[`workspace.deleted`,c]];return l.forEach(([e,t])=>Wu.on(e,t)),()=>{r(),i?.(),l.forEach(([e,t])=>Wu.off(e,t))}},[e,s]),(0,X.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`workspaces:refresh`,e),()=>window.removeEventListener(`workspaces:refresh`,e)},[s]),{workspaces:(0,X.useMemo)(()=>Lb(t),[t]),isLoading:r,refresh:c}}function n0({status:e}){return(0,Z.jsx)(`span`,{className:K(`inline-block w-2 h-2 rounded-full shrink-0`,e===`active`?`bg-success`:e===`error`?`bg-destructive`:`bg-muted-foreground`),title:e})}function r0(){let{state:e,selectEntity:t,openM2:n,closeM2:r}=Eb(),i=Cm(),{workspaces:a,isLoading:o}=t0(e.activeSection===`workspaces`),{showToast:s}=oo(),l=Gc(),[u,d]=(0,X.useState)(new Set),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(new Map),g=(0,X.useRef)(new Map),[_,v]=(0,X.useState)(null),y=_&&_.base===a?_.order:a,{rowProps:b,handleProps:x,draggingIndex:S,insertLineClass:C}=Bb((e,t)=>{let n=Rb(y,e,t);v({base:a,order:n}),zb(n,(e,t)=>ja(zy(e),{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e&&s({title:`Partial reorder`,description:`${e} workspace(s) could not be reordered`,variant:`destructive`})})}),w=e=>m.get(zy(e))??{icon:e.icon??void 0,color:e.color??void 0},T=(e,t,n)=>{let r={...t,...n};h(t=>new Map(t).set(e,r));let i=g.current,a=i.get(e);a&&clearTimeout(a),i.set(e,setTimeout(()=>{i.delete(e);let t={icon:r.icon??null};r.color&&(t.color=r.color),ja(e,t).then(()=>window.dispatchEvent(new CustomEvent(`workspaces:refresh`))).catch(e=>s({title:`Error`,description:e instanceof Error?e.message:`Update failed`,variant:`destructive`}))},350))},E=e=>{t(zy(e)),n(`detail`,zy(e)),!i&&eb(zy(e))&&l(tb(zy(e)))},D=async(e,t)=>{e.stopPropagation(),d(e=>new Set(e).add(zy(t)));try{await ii(zy(t)),s({title:`Success`,description:`${t.label||t.name} started`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){s({title:`Error`,description:e instanceof Error?e.message:`Start failed`,variant:`destructive`})}finally{d(e=>{let n=new Set(e);return n.delete(zy(t)),n})}},O=async(e,t)=>{e.stopPropagation(),d(e=>new Set(e).add(zy(t)));try{await _r(zy(t)),s({title:`Success`,description:`${t.label||t.name} stopped`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){s({title:`Error`,description:e instanceof Error?e.message:`Stop failed`,variant:`destructive`})}finally{d(e=>{let n=new Set(e);return n.delete(zy(t)),n})}};return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:`Workspaces`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{r(),l(`/workspaces?create=1`)},title:`Create workspace`,"aria-label":`Create workspace`,className:`flex items-center justify-center w-6 h-6 rounded-full bg-foreground text-background hover:opacity-80 transition-opacity`,children:(0,Z.jsx)(nn,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:o&&a.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):a.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No workspaces found`}):(0,Z.jsx)(`div`,{className:`space-y-1.5 px-2`,children:y.map((r,a)=>{let o=e.selectedEntityId===zy(r),s=u.has(zy(r)),d=r.status!==`active`,f=w(r),m=If(f.color);return(0,Z.jsxs)(`div`,{...b(a),"data-active":o||void 0,className:K(`group relative rounded-md py-2.5 pl-3 pr-7 transition-all shadow-elevation-1`,o?`bg-accent shadow cursor-pointer hover:shadow`:d?`bg-card opacity-60 cursor-not-allowed`:`bg-card hover:bg-accent/50 cursor-pointer hover:shadow`,C(a,y.length),S===a&&`opacity-60`),onClick:()=>{d||E(r)},children:[(0,Z.jsx)(`button`,{type:`button`,...x(a),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:K(`absolute inset-y-0 right-0 flex w-4 cursor-grab items-center justify-center rounded-r-md active:cursor-grabbing`,!m&&`bg-muted`),style:m?{backgroundColor:m}:void 0,children:(0,Z.jsx)(lr,{className:K(`h-3.5 w-3.5`,Lf(m))})}),(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`button`,{type:`button`,title:`Change icon`,onClick:e=>{hr()||(e.stopPropagation(),p({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360),name:zy(r)}))},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),p({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360),name:zy(r)})},className:`shrink-0 rounded p-0.5 hover:bg-muted-foreground/10 touch-target`,children:(0,Z.jsx)(c,{icon:f.icon||`ph:stack-fill`,width:18,height:18,color:m,className:K(!m&&`text-muted-foreground`)})}),(0,Z.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(n0,{status:r.status}),(0,Z.jsx)(`span`,{className:`text-sm font-medium truncate`,children:r.label||r.name})]})}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5 shrink-0`,children:[r.status===`active`?(0,Z.jsx)(`button`,{type:`button`,disabled:s,onClick:e=>O(e,r),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Stop`,children:(0,Z.jsx)($t,{className:`w-3.5 h-3.5`})}):(0,Z.jsx)(`button`,{type:`button`,disabled:s,onClick:e=>D(e,r),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Start`,children:(0,Z.jsx)(W,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),t(zy(r)),i?n(`settings`,zy(r)):l(`/workspaces/${zy(r)}/settings/general`)},className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground transition-colors`,title:`Settings`,children:(0,Z.jsx)(mn,{className:`w-3.5 h-3.5`})})]})]}),r.description&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-3.5`,children:r.description}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 mt-1 pl-3.5`,children:[r.host&&(0,Z.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate`,children:r.host}),r.ownerEmail&&(0,Z.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate`,children:r.ownerEmail})]})]},r.id||r.name)})})}),f&&(()=>{let e=a.find(e=>zy(e)===f.name);if(!e)return null;let t=w(e);return(0,Z.jsx)(Wy,{x:f.x,y:f.y,current:t,onChange:e=>T(f.name,t,e),onClose:()=>p(null)})})()]})}function i0(e,t){let n=(0,X.useRef)(null),r=(0,X.useRef)(0);return(0,X.useEffect)(()=>{if(!e)return;let n=e=>{if(e.defaultPrevented||e.repeat||e.isComposing||e.getModifierState(`AltGraph`))return;let n=e.target;if(n instanceof Element&&n.closest(`input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"], [role="dialog"], [role="alertdialog"]`)||document.querySelector(`[aria-modal="true"], dialog[open]`))return;let r=jT(e);if(!r)return;let i=kT(),a=r===i.previousTree?-1:+(r===i.nextTree);a&&(e.preventDefault(),t(a))};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[e,t]),{onTouchStart(e){r.current=0,n.current=e.touches.length===1?{x:e.touches[0].clientX,y:e.touches[0].clientY}:null},onTouchMove(e){e.touches.length!==1&&(n.current=null)},onTouchCancel(){n.current=null},onTouchEnd(i){if(!n.current||!e)return;let a=i.changedTouches[0],o=NT(a.clientX-n.current.x,a.clientY-n.current.y);n.current=null,o&&(r.current=Date.now()+500,i.stopPropagation(),t(o))},onClickCapture(e){Date.now()<r.current&&(e.preventDefault(),e.stopPropagation(),r.current=0)}}}function a0(e,t,n,r=!1){if(!t.startsWith(`/`)||!n.length)throw Error(`Choose a source folder and at least one destination.`);let i=new Map;for(let e of n){if(![`context`,`directory`].includes(e.tree)||!e.path.startsWith(`/`))throw Error(`Choose a context or directory destination.`);if(e.path.includes(`{{`))throw Error(`Auto-Link destinations cannot contain {{ template markers.`);i.set(`${e.tree}:${e.path}`,e)}return{id:e,enabled:!0,description:`Auto-Link backends:${t} → ${[...i.keys()].join(`, `)}`,cascade:!0,when:{event:[`document.inserted`,`document.updated`,`document.linked`],...r?{path:`backends:${t}`}:{pathExact:`backends:${t}`}},then:[...i.values()].map(e=>({action:`link`,paths:[`${e.tree===`context`?`ctx`:`dir`}:${e.path}`],...r?{recursive:!0}:{}}))}}function o0(e,t,n,r=!1,i=`forward`,a=`copy`,o){let s=a0(e,t,n,r);if(i===`forward`)return[s];let c=t.split(`/`).filter(Boolean);if(c.length<2||t.includes(`{{`)||c.some(e=>e===`.`||e===`..`))throw Error(`Choose a backend folder with a valid storage address.`);if(!o)throw Error(`Choose a writable backend folder.`);let l=o.address,u=o.key,d=[...new Map(n.map(e=>[`${e.tree}:${e.path}`,e])).values()],f={id:`${e}-reverse`,enabled:!0,description:`Auto-Link ${d.map(e=>`${e.tree}:${e.path}`).join(`, `)} → backends:${t} (${a})`,cascade:!1,when:{event:[`document.inserted`,`document.linked`],[r?`path`:`pathExact`]:d.map(e=>`${e.tree}:${e.path}`)},then:[{action:`store`,to:l,folder:u,mode:a,autoLink:!0,onConflict:`error`,...r?{recursive:!0}:{}}]};return i===`both`?[s,f]:[f]}function s0({workspaceId:e,sourcePath:t,onClose:n,onManageRules:r}){let[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(`forward`),[u,d]=(0,X.useState)(`copy`),[f,p]=(0,X.useState)(0),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(!0),[v]=(0,X.useState)(()=>`autolink-${crypto.randomUUID()}`),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(!1),[C,w]=(0,X.useState)(!1),[T,E]=(0,X.useState)(``),[D,O]=(0,X.useState)(0),[k,A]=(0,X.useState)(0),[j,M]=(0,X.useState)(0);gf(n,!x&&!o);let N=()=>{x||n()};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(sp,{onClose:N,children:(0,Z.jsxs)(`section`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`autolink-title`,className:`${op} flex flex-col overflow-hidden rounded-2xl border bg-card shadow-elevation-4`,children:[(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Z.jsxs)(`h2`,{id:`autolink-title`,className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(qt,{className:`h-4 w-4`}),`Auto-Link folder`]}),(0,Z.jsx)(`button`,{type:`button`,onClick:N,disabled:x,"aria-label":`Close`,className:`p-1 disabled:opacity-40`,children:(0,Z.jsx)(je,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-5 overflow-y-auto p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Backend folder`}),(0,Z.jsx)(`p`,{className:`mt-1 break-words text-sm`,children:t})]}),(0,Z.jsxs)(`fieldset`,{disabled:x||y,className:`space-y-2 text-sm`,children:[(0,Z.jsx)(`label`,{className:`block font-medium`,htmlFor:`autolink-direction`,children:`Direction`}),(0,Z.jsxs)(`select`,{id:`autolink-direction`,className:`w-full rounded-md border bg-background p-2`,value:c,onChange:e=>l(e.target.value),children:[(0,Z.jsx)(`option`,{value:`forward`,children:`Backend → virtual tree`}),(0,Z.jsx)(`option`,{value:`reverse`,children:`Virtual tree → backend`}),(0,Z.jsx)(`option`,{value:`both`,children:`Both`})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c===`forward`?`Link indexed files into your virtual paths. Files stay where they are.`:`Store files explicitly added to these virtual paths in the backend folder. Documents appearing through context filters are not copied.`}),c!==`forward`&&(0,Z.jsxs)(`details`,{children:[(0,Z.jsx)(`summary`,{className:`cursor-pointer`,children:`Advanced: storage operation`}),(0,Z.jsxs)(`label`,{className:`mt-2 flex items-start gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:u===`move`,onChange:e=>d(e.target.checked?`move`:`copy`)}),`Move instead of copy — release the source only after the destination is safely stored.`]})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`h3`,{className:`text-sm font-medium`,children:`Virtual paths`}),i.map((e,t)=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 rounded-lg border p-2 text-sm`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.tree===`context`?`Context tree`:`Directory tree`}),(0,Z.jsx)(`p`,{className:`break-words`,children:e.path})]}),!y&&(0,Z.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e.tree}:${e.path}`,disabled:x,onClick:()=>a(e=>e.filter((e,n)=>n!==t)),children:(0,Z.jsx)(je,{className:`h-4 w-4`})})]},`${e.tree}:${e.path}`)),!y&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,disabled:x,onClick:()=>s(!0),children:[(0,Z.jsx)(nn,{className:`mr-1 h-4 w-4`}),`Add virtual path…`]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Choose a context path, a directory path, or both.`})]}),(0,Z.jsxs)(`fieldset`,{disabled:x||y,className:`space-y-3 text-sm`,children:[(0,Z.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>h(e.target.checked),className:`mt-1`}),`Recursive — include subfolders and recreate their structure at each destination`]}),(0,Z.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:g,onChange:e=>_(e.target.checked),className:`mt-1`}),`Apply to existing documents`]})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Without Recursive, only direct folder contents are included. Context paths keep their usual layer membership. Both creates two independently manageable rules in workspace Rules. Removing rules keeps existing files and links. Renames and deletions are not synchronized. Filename conflicts stop the transfer without overwriting.`}),x&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm`,children:y?`Applying to existing documents… ${k} processed`:`Saving Auto-Link…`}),C&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[`Auto-Link is enabled for future documents.`,g?` ${k} existing document matches processed.`:``]}),j>0&&(0,Z.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[j,` document operations failed. Check the rule’s run log in Rules and rerun it after resolving the errors.`]}),T&&(0,Z.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[y?`Auto-Link is enabled. `:``,T]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2 border-t p-3`,children:[(0,Z.jsx)(J,{variant:`ghost`,disabled:x,onClick:r,children:`Manage rules`}),C?(0,Z.jsx)(J,{onClick:n,children:`Done`}):(0,Z.jsx)(J,{disabled:x||!i.length,onClick:async()=>{if(!x){S(!0),E(``);try{let n=c===`forward`?void 0:Fo(t,await va(e));if(n?.driver===`cacache`)throw Error(`Choose a backend that preserves folder paths.`);let r=o0(v,t,i,m,c,u,n);if(y||(await mQ(e,r),b(!0)),g){for(let t=f;t<r.length;t++){let n=t===f?D:0;for(;n!==null;){let i=await lQ(e,{ruleId:r[t].id,limit:100,offset:n});if(A(e=>e+i.matched-i.failed),M(e=>e+i.failed),i.nextOffset===void 0)throw Error(`The rule is enabled, but applying the full folder needs an updated server. Use Rules to rerun existing documents after updating.`);n=i.nextOffset,n!==null&&O(n)}p(t+1),O(0)}window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`))}w(!0)}catch(e){E(e instanceof Error?e.message:`Could not configure Auto-Link`)}finally{S(!1)}}},children:x?`Applying…`:y?`Retry existing documents`:`Enable Auto-Link`})]})]})}),o&&(0,Z.jsx)(sp,{onClose:()=>s(!1),children:(0,Z.jsx)(ap,{fixedWorkspaceName:e,title:`Choose virtual paths`,confirmLabel:`Add paths`,sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,onClose:()=>s(!1),onConfirm:(e,t)=>{a(n=>{let r=[...n];for(let n of e)r.some(e=>e.tree===t.treeType&&e.path===n)||r.push({tree:t.treeType,path:n});return r}),s(!1)}})})]})}async function c0(){return await Y.get(`${Yr}/users/me/config/webui`)??{}}async function l0(e){return await Y.put(`${Yr}/users/me/config/webui`,e)??e}var u0=`application/x-canvas-workspace-pin`;function d0({pins:e,isLoading:t,searchQuery:n=``,activeKey:r,onOpen:i,onShowInTree:a,onUnpin:o,onMove:s}){let[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),p=n.toLowerCase().trim(),m=p?e.filter(e=>(e.label||e.name||``).toLowerCase().includes(p)||e.path.toLowerCase().includes(p)||(e.description||``).toLowerCase().includes(p)):e,h=()=>{u(null),f(null)},g=async()=>{let t=d,n=l;if(h(),!n||!t||t.id===n)return;let r=t.id;if(t.id&&!t.before&&(r=e[e.findIndex(e=>e.id===t.id)+1]?.id??null),r!==n)try{await s(n,r)}catch(e){alert(e instanceof Error?e.message:String(e))}};return t&&!e.length?(0,Z.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading pins…`}):e.length?m.length?(0,Z.jsx)(`div`,{className:`p-2 flex flex-col gap-2`,onDragOver:e=>{l&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`)},onDrop:e=>{e.preventDefault(),l&&!d&&f({id:null,before:!1}),g()},children:m.map(e=>{let t=e.resolvable===!1,n=If(e.color),s=e.icon||(e.type===`canvas`?`ph:squares-four-fill`:`ph:folder-fill`),m=r===ca(e.tree,e.path),_=d?.id===e.id&&d.before,v=d?.id===e.id&&!d.before;return(0,Z.jsxs)(`div`,{role:`button`,tabIndex:0,"data-active":m||void 0,draggable:!p,onDragStart:t=>{t.dataTransfer.setData(u0,e.id),t.dataTransfer.setData(`text/plain`,e.path),t.dataTransfer.effectAllowed=`move`,u(e.id)},onDragEnd:h,onDragOver:t=>{if(!l||l===e.id)return;t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientY<n.top+n.height/2;f(t=>t?.id===e.id&&t.before===r?t:{id:e.id,before:r})},onDrop:e=>{e.preventDefault(),e.stopPropagation(),g()},onClick:()=>{t||i(e)},onKeyDown:n=>{n.target===n.currentTarget&&(n.key===`Enter`||n.key===` `)&&!t&&(n.preventDefault(),i(e))},title:t?`${e.path} — folder no longer exists`:`Open ${e.tree}:${e.path}`,className:K(`group relative flex items-stretch gap-2.5 rounded-lg border bg-card shadow-elevation-1 text-left transition-colors`,t?`opacity-70 cursor-default`:`cursor-pointer hover:bg-accent/40`,m&&`ring-1 ring-primary/60`,l===e.id&&`opacity-40`,_&&`border-t-2 border-t-primary`,v&&`border-b-2 border-b-primary`),style:{borderLeft:`5px solid ${n??`transparent`}`},children:[(0,Z.jsx)(`div`,{className:`flex items-center justify-center w-12 shrink-0 rounded-l-[5px] my-0 self-stretch`,style:n?{backgroundColor:`${n}22`}:void 0,children:t?(0,Z.jsx)(at,{className:`w-5 h-5 text-warning`}):(0,Z.jsx)(c,{icon:s,width:22,height:22,color:n,className:K(!n&&(e.type===`canvas`?`text-primary`:`text-muted-foreground`))})}),(0,Z.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1 py-2 pr-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5 min-w-0`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-semibold leading-tight truncate`,children:e.label||e.name||e.path.split(`/`).pop()}),e.locked&&(0,Z.jsx)(Fn,{className:`w-3 h-3 shrink-0 text-warning`})]}),(0,Z.jsxs)(`span`,{className:`text-[11px] text-muted-foreground truncate leading-tight font-mono mt-0.5`,children:[e.tree,`:`,e.path]}),e.description&&(0,Z.jsx)(`span`,{className:`text-[11px] text-muted-foreground/80 truncate leading-tight mt-1`,children:e.description}),t&&(0,Z.jsx)(`span`,{className:`text-[11px] text-warning leading-tight mt-1`,children:`Folder no longer exists`})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-between py-1.5 pr-1.5 shrink-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Z.jsx)(`button`,{type:`button`,disabled:t,onClick:t=>{t.stopPropagation(),a(e)},title:`Show in tree`,"aria-label":`Show in tree`,className:`flex items-center justify-center w-6 h-6 rounded text-muted-foreground reveal-on-hover focus-visible:opacity-100 hover:bg-accent hover:text-foreground transition-colors disabled:opacity-40 disabled:cursor-default`,children:(0,Z.jsx)(L,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:async t=>{t.stopPropagation();try{await o(e)}catch(e){alert(e instanceof Error?e.message:String(e))}},title:`Unpin`,"aria-label":`Unpin`,className:`flex items-center justify-center w-6 h-6 rounded text-muted-foreground reveal-on-hover hover:bg-destructive/10 hover:text-destructive transition-colors`,children:(0,Z.jsx)(te,{className:`w-3.5 h-3.5`})})]}),!p&&(0,Z.jsx)(lr,{className:`w-3.5 h-3.5 text-muted-foreground/50 cursor-grab active:cursor-grabbing`,"aria-hidden":!0})]})]},e.id)})}):(0,Z.jsxs)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:[`No pins match “`,n,`”`]}):(0,Z.jsxs)(`div`,{className:`px-3 py-6 text-xs text-muted-foreground text-center space-y-1`,children:[(0,Z.jsx)(`p`,{children:`No pinned folders yet.`}),(0,Z.jsxs)(`p`,{className:`text-muted-foreground/70`,children:[`Right-click a folder in the context or directory tree and choose `,(0,Z.jsx)(`span`,{className:`font-medium`,children:`Pin`}),`.`]})]})}var f0=[`pins`,`context`,`layers`,`directory`,`backends`],p0=e=>typeof e==`string`&&f0.includes(e),m0=e=>{let t=Array.isArray(e)?e.filter(p0).filter((e,t,n)=>n.indexOf(e)===t):[];return[...t,...f0.filter(e=>!t.includes(e))]},h0={pins:(0,Z.jsx)(De,{className:`w-3.5 h-3.5`}),context:(0,Z.jsx)(Je,{className:`w-3.5 h-3.5`}),layers:(0,Z.jsx)(ar,{className:`w-3.5 h-3.5`}),directory:(0,Z.jsx)(L,{className:`w-3.5 h-3.5`}),backends:(0,Z.jsx)(Jt,{className:`w-3.5 h-3.5`})},g0={pins:`Pins`,context:`Context tree`,layers:`Context layers`,directory:`Directory tree`,backends:`Backends tree`},_0=e=>e===`directory`||e===`backends`?e:Da,v0=(e,t)=>t?`layers`:e===`directory`?`directory`:e===`backends`?`backends`:`context`;function y0(){let{state:e}=Eb();return e.selectedEntityId?(0,Z.jsx)(Gb,{workspaceName:e.selectedEntityId,children:(0,Z.jsx)(b0,{})}):null}function b0(){let{state:e,closeM2:t,openM2:n}=Eb(),r=yg(),i=Cm(),a=e.selectedEntityId,o=Gc(),s=Hc(),{treeName:c,path:l}=iv(s.pathname),u=new URLSearchParams(s.search).get(`layer`)===`1`,d=new URLSearchParams(s.search).get(`layerId`),f=/\/trees\/|\/path(\/|$)/.test(s.pathname)||!!d,p=f?v0(c,d):f0[0],[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)({icon:null,color:null}),[b,x]=(0,X.useState)(p),[S,C]=(0,X.useState)(null),[w,T]=(0,X.useState)(null),[E,D]=(0,X.useState)(null),[O,k]=(0,X.useState)([]),[A,j]=(0,X.useState)(!1),[M,N]=(0,X.useState)(!1),[P,ee]=(0,X.useState)(!1),[F,I]=(0,X.useState)(!1),[te,ne]=(0,X.useState)(l),[L,re]=(0,X.useState)(new Set),[R,ie]=(0,X.useState)(u&&l!==`/`?l:null),[ae,oe]=(0,X.useState)(``),[z,se]=(0,X.useState)(null),[ce,B]=(0,X.useState)(null),[V,le]=(0,X.useState)([]),[ue,de]=(0,X.useState)(!1),[fe,pe]=(0,X.useState)(!1),me=(0,X.useRef)(null),H=(0,X.useRef)(!1),[he,ge]=(0,X.useState)(!1),[_e,ve]=(0,X.useState)(f0),ye=!f;(0,X.useEffect)(()=>{let e=!1;return c0().then(t=>{if(e)return;let n=m0(t?.m2?.tabOrder);ve(n),ye&&x(e=>e===f0[0]?n[0]:e)}).catch(()=>{}),()=>{e=!0}},[]);let U=(0,X.useCallback)(async e=>{let t=_e;ve(e);try{let t=await c0();await l0({...t,m2:{...t.m2,tabOrder:e}})}catch{ve(t)}},[_e]),[be,xe]=(0,X.useState)(null),[Se,Ce]=(0,X.useState)(null),W=()=>{xe(null),Ce(null)},G=()=>{if(be&&Se&&be!==Se.id){let e=_e.filter(e=>e!==be),t=e.indexOf(Se.id);t>=0&&(e.splice(Se.before?t:t+1,0,be),e.some((e,t)=>e!==_e[t])&&U(e))}W()};(0,X.useEffect)(()=>{let e=e=>se(e.detail??null);return window.addEventListener(`documents:clipboard`,e),()=>window.removeEventListener(`documents:clipboard`,e)},[]);let[we,Te]=(0,X.useState)(l);l!==we&&(Te(l),ne(l));let Ee=(0,X.useCallback)(async(e,t,n=!1)=>{let r=t===`context`?j:t===`directory`?N:ee,i=t===`context`?C:t===`directory`?T:D;r(!0);try{n&&oa(e,t),i(await fi(e,t,{force:n}))}catch{}finally{r(!1)}},[]),De=(0,X.useCallback)(async e=>{de(!0);try{le(await Va(e))}catch{}finally{de(!1)}},[]),Oe=(0,X.useCallback)(async e=>{I(!0);try{let t=await Wa(e,`context`);k(t)}catch{k([])}finally{I(!1)}},[]);(0,X.useEffect)(()=>{if(!a)return;let e=a,t=!1;async function n(){j(!0),N(!0),ee(!0),I(!0);try{let[n,r,i]=await Promise.allSettled([fi(e,`context`),fi(e,`directory`),fi(e,`backends`)]);if(vi(e).then(e=>{t||(h(e.label||null),_(e.id||null),y({icon:e.icon??null,color:e.color??null}))}).catch(()=>{}),t)return;n.status===`fulfilled`&&C(n.value),r.status===`fulfilled`&&T(r.value),i.status===`fulfilled`&&D(i.value),De(e)}finally{t||(j(!1),N(!1),ee(!1))}try{let n=await Wa(e,`context`);t||k(n)}catch{}finally{t||I(!1)}}return n(),()=>{t=!0}},[a,De]);let ke=(0,X.useCallback)(e=>{Ee(e,`context`,!0),Ee(e,`directory`,!0),Ee(e,`backends`,!0),Oe(e),De(e)},[Ee,Oe,De]),Ae=(0,X.useCallback)(()=>{a&&ke(a)},[a,ke]);(0,X.useEffect)(()=>{if(!a)return;let e=e=>{e.detail?.workspaceName===a&&ke(a)};return window.addEventListener(`workspace:tree:refresh`,e),()=>window.removeEventListener(`workspace:tree:refresh`,e)},[a,ke]),(0,X.useEffect)(()=>{if(!a)return;let e=!1;return va(a).then(t=>{e||re(new Set(t.filter(e=>e.resyncing&&e.treePath).map(e=>e.treePath)))}).catch(()=>{}),()=>{e=!0}},[a]),(0,X.useEffect)(()=>{if(!a)return;let e=[`workspace:${a}`,g?`workspace:${g}`:null].filter(Boolean),t=()=>e.forEach(e=>Wu.emit(`subscribe`,{channel:e})),n=Wu.on(`connect`,t);t();let r=null,i=()=>{r&&clearTimeout(r),r=setTimeout(()=>ke(a),200)},o=[`context.path.changed`,`tree.path.inserted`,`tree.path.moved`,`tree.path.removed`,`tree.path.copied`,`tree.layer.updated`,`tree.layer.merged`,`tree.layer.subtracted`,`tree.recalculated`,`tree.created`,`tree.deleted`,`tree.renamed`];o.forEach(e=>Wu.on(e,i));let s=e=>{if(e?.workspaceId&&g&&e.workspaceId!==g)return;let t=e?.treePath;t&&(re(n=>{let r=new Set(n);return e.resyncing?r.add(t):r.delete(t),r}),e.resyncing||i())};Wu.on(`backend.resync.changed`,s);let c=e=>{e?.workspaceId&&g&&e.workspaceId!==g||De(a)};return Wu.on(`pins.changed`,c),()=>{r&&clearTimeout(r),e.forEach(e=>Wu.emit(`unsubscribe`,{channel:e})),n?.(),o.forEach(e=>Wu.off(e,i)),Wu.off(`backend.resync.changed`,s),Wu.off(`pins.changed`,c)}},[a,g,ke,De]);let[je,Me]=(0,X.useState)(null),Ne=`${s.pathname}|${s.search}`;if(Ne!==je){Me(Ne);let{treeName:e,path:t}=iv(s.pathname),n=new URLSearchParams(s.search).get(`layerId`),r=/\/trees\/|\/path(\/|$)/.test(s.pathname)||!!n;fe?pe(!1):x(r||he?r?v0(e,n):b:_e[0]),ne(t),ie(t===`/`?null:t)}let{showToast:Pe}=oo(),Fe=(0,X.useCallback)(async e=>{if(!a)return!1;let t=GZ(e);if(!t)throw Error(`Not a backend folder`);let n=YZ(await jZ(a));if(!n)throw Error(`No backend-tree-sync hook in this workspace (git/hooks/started/). Recreate the seed hooks from Settings → Hooks.`);let r=await uQ(a,{hookFile:n,payload:{backend:t.backend,subdir:t.rel,target:KZ(e)}});if(r.status===`error`)throw Error(r.error||`Sync failed`);return Pe({title:`Folders synced`,description:`${t.backend}${t.rel?`/${t.rel}`:``} → ${KZ(e)} (see Hooks → Runs)`}),ke(a),!0},[a,Pe,ke]),Ie=Z1({workspaceId:a??void 0,treeName:_0(b),onRefresh:Ae}),Le=new Set(V.map(e=>ca(e.tree,e.path))),Re=_0(b),ze=(0,X.useCallback)(e=>Le.has(ca(Re,e)),[V,Re]),Be=(0,X.useCallback)(async e=>{if(!a)return;let t=V.find(t=>ca(t.tree,t.path)===ca(Re,e));t?await Pi(a,t.id):await Xr(a,e,Re),await De(a)},[a,V,Re,De]),Ve=(0,X.useCallback)(async e=>{if(a){le(t=>t.filter(t=>t.id!==e.id));try{await Pi(a,e.id)}finally{await De(a)}}},[a,De]),He=(0,X.useCallback)(async(e,t)=>{if(!a)return;let n=V.find(t=>t.id===e);if(!n)return;let r=V.filter(t=>t.id!==e),i=t===null?r.length:r.findIndex(e=>e.id===t);if(i===-1)return;let o=[...r.slice(0,i),n,...r.slice(i)];if(!o.every((e,t)=>e===V[t])){le(o);try{le(await _i(a,o.map(e=>e.id)))}catch(e){throw await De(a),e}}},[a,V,De]),Ue=(0,X.useCallback)(e=>{if(!a)return;pe(!0),ne(e.path),ie(null);let t=av(a,e.path,e.tree);if(r){r.activateRow(`pin:${a}:${e.id}`,e.label||e.name||e.path,t);return}o(t)},[a,o,r]),We=(0,X.useCallback)(e=>{!a||e.resolvable===!1||(pe(!1),ge(!0),x(v0(e.tree)),ne(e.path),ie(null),oe(``),H.current=!0,r?.setFocus(`main`),o(av(a,e.path,e.tree)))},[a,o,r]),Ge=b===`context`?S:b===`directory`?w:b===`backends`?E:null,Ke=b===`context`?A:b===`directory`?M:b===`backends`&&P;(0,X.useEffect)(()=>{if(!H.current||Ke||b===`pins`)return;let e=me.current?.querySelector(`[data-active="true"]`);e&&(e.scrollIntoView({block:`nearest`,inline:`nearest`}),H.current=!1)},[b,te,Ge,Ke]);let qe=(0,X.useCallback)(e=>{ge(!0),x(e),ne(`/`),ie(null),oe(``)},[]),Je=(0,X.useCallback)(e=>{qe(MT(_e,b,e))},[_e,b,qe]),Ye=i0(e.m2Open,Je),Xe=e=>{ie(null),ne(e);let t=_0(b);r?.setFocus(`main`),o(av(a,e,t))},Ze=(0,X.useCallback)((e,t)=>{ne(e),ie(e);let n=_0(b),i=new URLSearchParams;i.set(`layer`,`1`),t&&i.set(`layerId`,t),r?.setFocus(`main`),o(`${av(a,e,n)}?${i.toString()}`)},[a,b,o,r]),Qe=(0,X.useCallback)((e,t)=>{if(a){if(r){r.openCanvas({kind:`route`,location:av(a,e,t)});return}window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:a,treeName:t,path:e}}))}},[a,r]),$e=(0,X.useCallback)(async e=>{if(!a)return;let t=_0(b),n=await wi(a,e,t),r=`${window.location.origin}${n.url}`;await navigator.clipboard?.writeText(r),alert(`Canvas share link copied:\n${r}`)},[a,b]),et=ae.toLowerCase().trim(),tt=et?O.filter(e=>e.name.toLowerCase().includes(et)||(e.label||``).toLowerCase().includes(et)||(e.description||``).toLowerCase().includes(et)):O;return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsx)(z1,{title:m||a||`Workspace`,icon:v.icon||`ph:stack-fill`,accentColor:v.color,onBack:t,action:(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>a&&o(tb(a)),className:`flex items-center justify-center w-8 h-8 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Open workspace`,children:(0,Z.jsx)(Gn,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{i?n(`settings`,a??null):o(`/workspaces/${a}/settings/general`)},className:`flex items-center justify-center w-8 h-8 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Settings`,children:(0,Z.jsx)(mn,{className:`w-3.5 h-3.5`})})]})}),(0,Z.jsx)(`div`,{...Ye,className:`flex border-b border-border shrink-0 touch-pan-y`,"aria-label":`Workspace trees`,children:_e.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>qe(e),title:`${g0[e]} — drag to reorder; the first tab opens by default`,"aria-label":g0[e],"aria-pressed":b===e,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(`text/plain`,e),t.dataTransfer.effectAllowed=`move`,xe(e)},onDragEnd:W,onDragOver:t=>{if(!be||be===e)return;t.preventDefault(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientX<n.left+n.width/2;Ce(t=>t?.id===e&&t.before===r?t:{id:e,before:r})},onDrop:e=>{e.preventDefault(),G()},className:K(`relative flex-1 flex items-center justify-center py-2 transition-colors`,b===e?`text-foreground border-b-2 border-foreground -mb-px`:`text-muted-foreground hover:text-foreground`,be===e&&`opacity-40`,Se?.id===e&&Se.before&&`shadow-[inset_2px_0_0_0_hsl(var(--primary))]`,Se?.id===e&&!Se.before&&`shadow-[inset_-2px_0_0_0_hsl(var(--primary))]`),children:[h0[e],e===`pins`&&V.length>0&&(0,Z.jsx)(`span`,{className:`absolute top-1 right-[calc(50%-14px)] min-w-[14px] h-[14px] px-0.5 rounded-full bg-primary text-primary-foreground text-[9px] leading-[14px] text-center font-medium`,children:V.length})]},e))}),(0,Z.jsx)(`div`,{className:`px-2 py-1.5 border-b border-border shrink-0 shadow-elevation-2 z-10`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-md border bg-muted/40 px-2 py-1`,children:[(0,Z.jsx)(Xn,{className:`w-3 h-3 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`input`,{className:`flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground min-w-0`,placeholder:b===`layers`?`Search layers…`:b===`pins`?`Search pins…`:`Search paths…`,value:ae,onChange:e=>oe(e.target.value)})]})}),(0,Z.jsx)(`div`,{ref:me,className:`flex-1 overflow-y-auto`,children:b===`pins`?(0,Z.jsx)(d0,{pins:V,isLoading:ue,searchQuery:ae,activeKey:ca(c,l),onOpen:Ue,onShowInTree:We,onUnpin:Ve,onMove:He}):b===`layers`?(0,Z.jsx)(D0,{layers:tt,isLoading:F,wsName:a??``,onSelect:e=>{let t=new URLSearchParams;t.set(`layerId`,e.id),t.set(`layer`,`1`),o(`${av(a,`/`)}?${t.toString()}`)},onLock:async e=>{await $r(a,e.id,a,`context`),ke(a)},onUnlock:async e=>{await Ta(a,e.id,a,`context`),ke(a)},onRename:async(e,t)=>{await pi(a,e.id,t,`context`),ke(a)},onDestroy:async e=>{confirm(`Destroy layer "${e.label||e.name}"? This cannot be undone.`)&&(await Zr(a,e.id,`context`),ke(a))}}):(0,Z.jsx)(X1,{root:Ge,treeName:b,isBackendsTree:b===`backends`,onShiftSelect:r?e=>Qe(e,_0(b)):void 0,selectedPath:te,contentPath:R,onSelect:Xe,onShowContent:b===`context`?Ze:void 0,onOpenToSide:Qe,onShareCanvas:$e,onNewCanvas:a&&b!==`backends`?e=>{o(`${av(a,e,b)}?createCanvas=1`)}:void 0,isLoading:Ke,rootLabel:a??void 0,searchQuery:ae,resyncingPaths:b===`backends`?L:void 0,onAddRule:a&&b===`backends`?B:void 0,onSyncFolderTree:a&&b===`backends`?Fe:void 0,onAddStoreRule:a?(e,t=`store`)=>{let n=b===`backends`?(()=>{let n=GZ(e);return{kind:t,storeTo:n?.backend||``,storeFolder:n?.rel||``}})():{kind:t,path:`${b===`directory`?`dir`:`ctx`}:${e}`,storeFolder:t===`download`?`Downloads`:JZ(e)};o(`/workspaces/${a}/settings/hooks?${qZ(n).toString()}`)}:void 0,pastedDocumentIds:z?.documentIds,isPathPinned:b===`backends`?void 0:ze,onTogglePin:a&&b!==`backends`?Be:void 0,onPasteDocuments:a&&b!==`backends`?async(e,t)=>{let n=b===`directory`?`directory`:`context`,r=b===`directory`?`directory`:Da,i=await qr(a,e,t,r,n);return i&&(z&&(se(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}))),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:a,path:e,treeName:r}}))),i}:void 0,...Ie})}),ce&&a&&(0,Z.jsx)(s0,{workspaceId:a,sourcePath:ce,onClose:()=>B(null),onManageRules:()=>{B(null),o(`/workspaces/${a}/settings/hooks?section=rules`)}})]})}var x0={canvas:{label:`Canvases`,order:0},dataset:{label:`Datasets`,order:1},context:{label:`Context layers`,order:2},workspace:{label:`Workspaces`,order:3},universe:{label:`Universe`,order:4},label:{label:`Labels`,order:5},system:{label:`System`,order:6}},S0=100,C0=e=>e&&e.charAt(0).toUpperCase()+e.slice(1),w0=e=>x0[e]??{label:`${C0(e)} layers`,order:S0};function T0({type:e}){return e===`canvas`?(0,Z.jsx)(mt,{className:`w-3.5 h-3.5 shrink-0 text-primary`,"aria-label":`Canvas`}):e===`dataset`?(0,Z.jsx)(Jt,{className:`w-3.5 h-3.5 shrink-0 text-secondary`,"aria-label":`Dataset`}):(0,Z.jsx)(ar,{className:`w-3.5 h-3.5 shrink-0 text-muted-foreground/60`,"aria-label":`Layer`})}function E0(e){let t=new Map;for(let n of e){let e=n.type||`context`,r=t.get(e);r?r.push(n):t.set(e,[n])}return[...t.entries()].map(([e,t])=>({type:e,items:t,meta:w0(e)})).sort((e,t)=>e.meta.order-t.meta.order||e.meta.label.localeCompare(t.meta.label)).map(({type:e,items:t,meta:n})=>({type:e,label:n.label,items:t}))}function D0({layers:e,isLoading:t,onSelect:n,onLock:r,onUnlock:i,onRename:a,onDestroy:o}){let[s,c]=(0,X.useState)(null),l=(0,X.useRef)(null);if((0,X.useEffect)(()=>{s&&l.current?.focus()},[s]),t)return(0,Z.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading layers…`});if(!e.length)return(0,Z.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`No layers found`});let u=async(e,t)=>{e.stopPropagation();try{await t()}catch(e){alert(e instanceof Error?e.message:String(e))}},d=async(e,t)=>{c(null);let n=t.trim();if(!(!n||n===e.name))try{await a(e,n)}catch(e){alert(e instanceof Error?e.message:String(e))}},f=E0(e);return(0,Z.jsx)(`div`,{className:`px-2 py-1.5 space-y-2`,children:f.map(e=>(0,Z.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,Z.jsxs)(`div`,{className:`px-1 pt-1 pb-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground`,children:[e.label,(0,Z.jsxs)(`span`,{className:`ml-1 text-muted-foreground/60`,children:[`(`,e.items.length,`)`]})]}),e.items.map(e=>(0,Z.jsxs)(`div`,{className:`group flex items-center gap-2 rounded-l-md px-2 py-1.5 text-xs bg-card shadow-elevation-1 cursor-pointer hover:bg-accent/40 transition-colors`,style:{borderRight:e.color?`4px solid ${e.color}`:`4px solid transparent`},onClick:()=>s!==e.id&&n(e),children:[(0,Z.jsx)(`div`,{className:K(`w-2 h-2 rounded-full shrink-0`,!e.color&&`bg-muted-foreground/20`),style:e.color?{backgroundColor:e.color}:void 0}),(0,Z.jsx)(T0,{type:e.type}),s===e.id?(0,Z.jsx)(`input`,{ref:l,defaultValue:e.label||e.name,className:`flex-1 bg-transparent outline-none min-w-0 font-medium border-b border-primary`,onClick:e=>e.stopPropagation(),onKeyDown:t=>{t.key===`Enter`&&d(e,t.target.value),t.key===`Escape`&&c(null)},onBlur:t=>d(e,t.target.value)}):(0,Z.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:e.label||e.name}),e.locked&&s!==e.id&&(0,Z.jsx)(Fn,{className:`w-2.5 h-2.5 shrink-0 text-warning group-hover:hidden`}),s!==e.id&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5 reveal-on-hover`,children:[e.locked?(0,Z.jsx)(`button`,{type:`button`,title:`Unlock layer`,className:`p-0.5 rounded hover:bg-muted-foreground/10 text-warning hover:text-foreground touch-target`,onClick:t=>u(t,()=>i(e)),children:(0,Z.jsx)(Et,{className:`w-3 h-3`})}):(0,Z.jsx)(`button`,{type:`button`,title:`Lock layer`,className:`p-0.5 rounded hover:bg-muted-foreground/10 text-muted-foreground hover:text-foreground touch-target`,onClick:t=>u(t,()=>r(e)),children:(0,Z.jsx)(Fn,{className:`w-3 h-3`})}),!e.locked&&(0,Z.jsx)(`button`,{type:`button`,title:`Rename layer`,className:`p-0.5 rounded hover:bg-muted-foreground/10 text-muted-foreground hover:text-foreground touch-target`,onClick:t=>{t.stopPropagation(),c(e.id)},children:(0,Z.jsx)(Pe,{className:`w-3 h-3`})}),!e.locked&&(0,Z.jsx)(`button`,{type:`button`,title:`Destroy layer`,className:`p-0.5 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive touch-target`,onClick:t=>u(t,()=>o(e)),children:(0,Z.jsx)(lt,{className:`w-3 h-3`})})]})]},e.id))]},e.type))})}function O0(){let{state:e,closeM2:t}=Eb(),n=Cm(),r=Gc(),i=Hc(),a=e.selectedEntityId,[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)({icon:null,color:null});(0,X.useEffect)(()=>{if(!a)return;let e=!1;return vi(a).then(t=>{e||(s(t.label||null),l({icon:t.icon??null,color:t.color??null}))}).catch(()=>{}),()=>{e=!0}},[a]);let u=i.pathname.split(`/`).filter(Boolean),d=u[2]===`settings`?EC(u[3]):null,f=(0,X.useMemo)(()=>wC.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,Z.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(z1,{title:`Settings: ${o||a||`Workspace`}`,icon:c.icon||`ph:stack-fill`,accentColor:c.color,onBack:()=>{n||!a?t():r(`/workspaces/${a}`)},action:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>a&&r(`/workspaces/${a}`),className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Open workspace`,children:(0,Z.jsx)(Gn,{className:`h-3.5 w-3.5`})})}),(0,Z.jsx)($1,{items:f,activeId:d,onSelect:e=>a&&r(`/workspaces/${a}/settings/${e}`)})]})}function k0(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(!1),a=(0,X.useRef)(!1),o=(0,X.useRef)(!1),s=(0,X.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await KC();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch agents:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,X.useCallback)(()=>{a.current=!1,s()},[s]);return(0,X.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,X.useEffect)(()=>{if(!e)return;let t=()=>Wu.emit(`subscribe`,{channel:`agent`}),r=()=>Wu.emit(`unsubscribe`,{channel:`agent`}),i=Wu.on(`connect`,()=>{t(),s()});t();let a=e=>{let t=e?.agent??e;t?.id&&n(e=>e.some(e=>e.id===t.id)?e:[...e,t])},o=e=>{let t=e?.agent??e;t?.id&&n(e=>e.map(e=>e.id===t.id?{...e,...t}:e))},c=e=>{let t=e,r=t?.agentId??t?.id;r&&n(e=>e.filter(e=>e.id!==r))},l=e=>{let t=e,r=t?.agentId??t?.id,i=t?.status;!r||!i||n(e=>e.map(e=>e.id===r?{...e,status:i}:e))},u=[[`agent:created`,a],[`agent.created`,a],[`agent:updated`,o],[`agent.updated`,o],[`agent:deleted`,c],[`agent.deleted`,c],[`agent:status:changed`,l],[`agent.status.changed`,l]];return u.forEach(([e,t])=>Wu.on(e,t)),()=>{r(),i?.(),u.forEach(([e,t])=>Wu.off(e,t))}},[e,s]),(0,X.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`agents:refresh`,e),()=>window.removeEventListener(`agents:refresh`,e)},[s]),{agents:t,isLoading:r,refresh:c}}function A0({status:e}){return(0,Z.jsx)(`span`,{className:K(`inline-block w-2 h-2 rounded-full shrink-0`,e===`active`?`bg-success`:e===`error`?`bg-destructive`:e===`starting`||e===`stopping`?`bg-warning`:`bg-muted-foreground`),title:e})}function j0(){let{state:e,selectEntity:t,openM2:n,closeM2:r}=Eb(),i=Cm(),{agents:a,isLoading:o,refresh:s}=k0(e.activeSection===`agents`),{showToast:c}=oo(),[l,u]=(0,X.useState)(new Set),d=Gc(),f=e=>{t(e.id),n(`detail`,e.id),d(`/agents/${encodeURIComponent(e.name||e.id)}`)},p=async(e,t)=>{e.stopPropagation(),u(e=>new Set(e).add(t.id));try{await ow(t.id),s(),c({title:`Success`,description:`${t.label||t.name} started`})}catch(e){c({title:`Error`,description:e instanceof Error?e.message:`Start failed`,variant:`destructive`})}finally{u(e=>{let n=new Set(e);return n.delete(t.id),n})}},m=async(e,t)=>{e.stopPropagation(),u(e=>new Set(e).add(t.id));try{await sw(t.id),s(),c({title:`Success`,description:`${t.label||t.name} stopped`})}catch(e){c({title:`Error`,description:e instanceof Error?e.message:`Stop failed`,variant:`destructive`})}finally{u(e=>{let n=new Set(e);return n.delete(t.id),n})}};return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:`Agents`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{r(),d(`/agents?create=1`)},title:`Create agent`,"aria-label":`Create agent`,className:`flex items-center justify-center w-6 h-6 rounded-full bg-foreground text-background hover:opacity-80 transition-opacity`,children:(0,Z.jsx)(nn,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:o&&a.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):a.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No agents found`}):(0,Z.jsx)(`div`,{className:`space-y-1.5 px-2`,children:a.map(r=>{let a=e.selectedEntityId===r.id,o=l.has(r.id);return(0,Z.jsxs)(`div`,{"data-active":a||void 0,className:K(`group relative rounded-md px-3 py-2.5 cursor-pointer transition-all shadow-elevation-1 hover:shadow`,a?`bg-accent shadow`:`bg-card hover:bg-accent/50`),style:{borderRight:`6px solid ${r.color||`transparent`}`,borderRadius:r.color?`6px 0 0 6px`:void 0},onClick:()=>f(r),children:[(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(A0,{status:r.status}),(0,Z.jsx)(`span`,{className:`text-sm font-medium truncate`,children:r.label||r.name})]})}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5 shrink-0`,children:[r.status===`active`?(0,Z.jsx)(`button`,{type:`button`,disabled:o,onClick:e=>m(e,r),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Stop`,children:(0,Z.jsx)($t,{className:`w-3.5 h-3.5`})}):(0,Z.jsx)(`button`,{type:`button`,disabled:o,onClick:e=>p(e,r),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Start`,children:(0,Z.jsx)(W,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),t(r.id),i?n(`settings`,r.id):d(`/agents/${encodeURIComponent(r.name||r.id)}/settings/identity`)},className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground transition-colors`,title:`Settings`,children:(0,Z.jsx)(mn,{className:`w-3.5 h-3.5`})})]})]}),r.description&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-3.5`,children:r.description})]},r.id)})})})]})}function M0(e){return e.name?.trim()?e.name.trim():e.firstMessage?.trim()?e.firstMessage.trim():e.isExperimental?`Experimental`:e.id.slice(0,8)}function N0(e){let t=new Date(e.updatedAt).toLocaleString();return e.messageCount>0?`${e.messageCount} msg${e.messageCount===1?``:`s`} • ${t}`:`Empty • ${t}`}function P0(e){return e.sessions.sessions.find(t=>t.id===e.current.sessionId||t.path===e.current.sessionFile||t.id===e.sessions.currentSessionId||t.path===e.sessions.currentSessionPath||t.isCurrent)||null}function F0(){let{state:e,closeM2:t}=Eb(),n=e.selectedEntityId||``,r=Gc(),{showToast:i}=oo(),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(``),{current:h,sessions:g,isLoading:_,error:v,refresh:y,create:b,select:x,rename:S,remove:C}=LD(n);(0,X.useEffect)(()=>{n&&(qC(n).then(o).catch(()=>{}),y().catch(e=>{i({title:`Error`,description:e instanceof Error?e.message:`Failed to load sessions`,variant:`destructive`})}))},[n,y,i]);let w=(0,X.useMemo)(()=>g?.sessions?g.currentSessionId?g.sessions.find(e=>e.id===g.currentSessionId)||null:g.currentSessionPath?g.sessions.find(e=>e.path===g.currentSessionPath)||null:g.sessions.find(e=>e.isCurrent)||null:null,[g]),T=a?.name||n,E=e=>e?.slug||e?.id,D=e=>{let t=typeof e==`string`?e:E(e);r(t?`/agents/${encodeURIComponent(T)}/${encodeURIComponent(t)}`:`/agents/${encodeURIComponent(T)}`)},O=async()=>{try{let e=await b({mode:`persistent`,name:l.trim()||void 0});c(!1),u(``),D(P0(e))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to create session`,variant:`destructive`})}},k=async()=>{try{let e=await b({mode:`experimental`});D(P0(e))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to open experimental session`,variant:`destructive`})}},A=async()=>{try{await b({mode:`incognito`}),D()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to open incognito session`,variant:`destructive`})}},j=async e=>{try{e.isExperimental?await x({mode:`experimental`}):await x({mode:`persistent`,sessionId:e.id}),D(e)}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to select session`,variant:`destructive`})}},M=async e=>{if(p.trim())try{let t=(await S(e.id,p.trim())).sessions.sessions.find(t=>t.id===e.id);f(null),m(``),w?.id===e.id&&D(t||e)}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to rename session`,variant:`destructive`})}},N=async e=>{if(!e.isExperimental&&window.confirm(`Delete session "${M0(e)}"?`))try{await C(e.id),D()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete session`,variant:`destructive`})}};return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(z1,{title:a?.label||a?.name||n,onBack:t,action:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(`/agents/${encodeURIComponent(T)}/settings`),className:`flex h-8 w-8 items-center justify-center rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Agent settings`,children:(0,Z.jsx)(mn,{className:`h-3.5 w-3.5`})})}),(0,Z.jsxs)(`div`,{className:`border-b border-border px-4 py-3`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-semibold`,children:`Sessions`}),(0,Z.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:g?.mode===`incognito`?`Incognito mode`:g?.mode===`experimental`?`Experimental mode`:`Persistent history`}),(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[(0,Z.jsxs)(J,{size:`sm`,variant:s?`default`:`outline`,onClick:()=>{c(e=>!e),u(``)},disabled:_,children:[(0,Z.jsx)(nn,{className:`mr-1 h-3.5 w-3.5`}),`New`]}),(0,Z.jsxs)(J,{size:`sm`,variant:g?.mode===`experimental`?`default`:`outline`,onClick:k,disabled:_,children:[(0,Z.jsx)(Be,{className:`mr-1 h-3.5 w-3.5`}),`Experimental`]}),(0,Z.jsx)(J,{size:`sm`,variant:g?.mode===`incognito`?`default`:`outline`,onClick:A,disabled:_,children:`Incognito`})]})]}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-2`,children:[v&&(0,Z.jsx)(`div`,{className:`px-2 py-2 text-xs text-destructive`,children:v}),s&&(0,Z.jsxs)(`div`,{className:`mb-2 rounded-md border bg-muted/20 p-2`,children:[(0,Z.jsx)(`div`,{className:`mb-2 text-xs text-muted-foreground`,children:`Name the new session or leave it blank.`}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:l,onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),O()),e.key===`Escape`&&(c(!1),u(``))},placeholder:`Debugging auth`,className:`h-8`}),(0,Z.jsx)(J,{size:`sm`,onClick:O,disabled:_,children:`Create`})]})]}),g?.sessions.length?(0,Z.jsx)(`div`,{className:`space-y-1.5`,children:g.sessions.map(e=>{let t=w?.id===e.id&&g.mode!==`incognito`,n=d===e.id;return(0,Z.jsx)(`div`,{onClick:()=>j(e),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),j(e))},role:`button`,tabIndex:_?-1:0,className:`group w-full rounded-md border px-3 py-2 text-left transition-colors ${t?`border-foreground bg-accent`:`border-transparent hover:bg-accent/50`} ${_?`opacity-60`:``}`,children:(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`,children:n?(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:p,onChange:e=>m(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:t=>{t.key===`Enter`&&(t.preventDefault(),M(e)),t.key===`Escape`&&(f(null),m(``))},placeholder:`Session name`,className:`h-8`}),(0,Z.jsx)(J,{size:`sm`,onClick:t=>{t.stopPropagation(),M(e)},disabled:!p.trim()||_,children:`Save`})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`truncate text-sm font-medium`,children:M0(e)}),e.isExperimental&&(0,Z.jsx)(`span`,{className:`rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] text-primary`,children:`∞`}),e.isCurrent&&(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:`Current`})]}),(0,Z.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:N0(e)})]})}),!n&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5 reveal-on-hover`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),f(e.id),m(e.name||M0(e))},className:`flex h-7 w-7 items-center justify-center rounded hover:bg-muted-foreground/10 text-muted-foreground touch-target`,title:`Rename`,children:(0,Z.jsx)(dr,{className:`h-3.5 w-3.5`})}),!e.isExperimental&&(0,Z.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),N(e)},className:`flex h-7 w-7 items-center justify-center rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive touch-target`,title:`Delete session`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})]})},e.id)})}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center text-center text-muted-foreground`,children:(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-sm`,children:_?`Loading sessions...`:`No persistent sessions yet.`}),(0,Z.jsx)(`div`,{className:`mt-1 text-xs`,children:"Use `New`, `Experimental`, or `Incognito`."})]})}),h?.mode===`incognito`&&(0,Z.jsx)(`div`,{className:`mt-3 rounded-md border border-dashed px-3 py-2 text-xs text-muted-foreground`,children:`Incognito session is active. It lives in memory and stays out of the session list.`})]})]})}function I0(){let{state:e,closeM2:t}=Eb(),n=Cm(),r=Gc(),i=Hc(),a=e.selectedEntityId,[o,s]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!a)return;let e=!1;return qC(a).then(t=>{e||s(t)}).catch(()=>{}),()=>{e=!0}},[a]);let c=i.pathname.split(`/`).filter(Boolean),l=c[2]===`settings`?AC(c[3]):null,u=encodeURIComponent(o?.name||a||``),d=(0,X.useMemo)(()=>kC.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,Z.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(z1,{title:`Settings: ${o?.label||o?.name||a||`Agent`}`,accentColor:o?.color??null,onBack:()=>{n||!u?t():r(`/agents/${u}`)},action:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>u&&r(`/agents/${u}`),className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Open agent`,children:(0,Z.jsx)(Gn,{className:`h-3.5 w-3.5`})})}),(0,Z.jsx)($1,{items:d,activeId:l,onSelect:e=>u&&r(`/agents/${u}/settings/${e}`)})]})}function L0(){let e=Hc(),{state:t}=Eb(),[n,r]=(0,X.useState)(``),i=(0,X.useRef)(null);(0,X.useLayoutEffect)(()=>{let e=i.current,t=e?.querySelector(`[aria-current="page"]`);if(!e||!t)return;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();r.top<n.top?e.scrollTop+=r.top-n.top:r.bottom>n.bottom&&(e.scrollTop+=r.bottom-n.bottom)},[e.pathname,t.user?.userType]);let a=nb.filter(e=>e.id!==`server`||t.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(t=>ib(n,e.label,t.label,t.description))})).filter(e=>e.items.length);return(0,Z.jsxs)(`nav`,{"aria-label":`Settings`,className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-3 border-b border-border p-3`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Settings`}),(0,Z.jsx)(q,{type:`search`,"aria-label":`Search settings menu`,placeholder:`Find a setting…`,value:n,onChange:e=>r(e.target.value)})]}),(0,Z.jsxs)(`div`,{ref:i,className:`min-h-0 flex-1 space-y-4 overflow-y-auto p-2`,children:[a.map(t=>(0,Z.jsxs)(`section`,{"aria-label":t.label,children:[(0,Z.jsx)(`h2`,{className:`px-3 py-2 text-xs font-semibold text-muted-foreground`,children:t.label}),t.items.map(({path:t,icon:n,label:r,description:i})=>(0,Z.jsxs)(cu,{to:t,"aria-current":e.pathname===t?`page`:void 0,className:K(`flex items-start gap-3 rounded-md px-3 py-2 text-left hover:bg-accent/50`,e.pathname===t&&`bg-accent`),children:[(0,Z.jsx)(n,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:r}),(0,Z.jsx)(`span`,{className:`mt-0.5 block text-xs leading-relaxed text-muted-foreground`,children:i})]})]},t))]},t.id)),!a.length&&(0,Z.jsx)(`p`,{role:`status`,className:`p-3 text-sm text-muted-foreground`,children:`No settings match. Try “cache”, “model” or “token”.`})]})]})}var R0=280,z0=220,B0=560;function V0(){let{state:e}=Eb(),{activeSection:t,m2View:n}=e;if(t===`contexts`){if(n===`settings`)return(0,Z.jsx)(e0,{});if(n===`detail`)return(0,Z.jsx)(Q1,{})}if(t===`workspaces`){if(n===`settings`)return(0,Z.jsx)(O0,{});if(n===`detail`)return(0,Z.jsx)(y0,{})}if(t===`agents`){if(n===`settings`)return(0,Z.jsx)(I0,{});if(n===`detail`)return(0,Z.jsx)(F0,{})}return null}function H0(){let{state:e,closeM1:t,closeM2:n}=Eb();gf(t,e.m1Open&&!e.m2Open),gf(n,e.m2Open);let r=Cm(),[i,a]=(0,X.useState)(R0),[o,s]=(0,X.useState)(!1),c=(0,X.useRef)(null),l=(0,X.useCallback)(e=>{e.preventDefault(),s(!0),c.current={startX:e.clientX,startWidth:i};let t=e=>{if(!c.current)return;let t=e.clientX-c.current.startX,n=Math.min(B0,Math.max(z0,c.current.startWidth+t));a(n)},n=()=>{c.current=null,s(!1),window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n)};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[i]),u=r&&e.m1Open;return(0,Z.jsxs)(Z.Fragment,{children:[u&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-40 bg-scrim animate-fade-in`,onClick:t,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{style:e.m1Open&&!u?{width:i}:void 0,className:K(`flex-shrink-0 overflow-hidden bg-card surface-glass`,!o&&!u&&`transition-[width] duration-200 ease-out`,e.m1Open?`rounded-[var(--panel-radius)] shadow-elevation-2`:`w-0`,u?`fixed bottom-2 left-[calc(0.5rem+var(--spacing-rail)+0.5rem)] right-2 top-2 z-40 shadow-elevation-5 animate-fade-in`:`relative`),children:[(0,Z.jsxs)(`div`,{className:K(`absolute inset-0 flex flex-col transition-opacity duration-200 ease-out`,e.m2Open&&`opacity-0 pointer-events-none`),style:u?void 0:{minWidth:i},children:[e.activeSection===`contexts`&&(0,Z.jsx)(R1,{}),e.activeSection===`workspaces`&&(0,Z.jsx)(r0,{}),e.activeSection===`agents`&&(0,Z.jsx)(j0,{}),e.activeSection===`admin`&&(0,Z.jsx)(L0,{}),e.activeSection===`settings`&&(0,Z.jsx)(L0,{})]}),(0,Z.jsx)(`div`,{className:K(`absolute inset-0 z-10 bg-card flex flex-col transition-transform duration-200 ease-out`,e.m2Open?`translate-x-0`:`translate-x-full`),children:e.m2Open&&(0,Z.jsx)(V0,{})}),e.m1Open&&!u&&(0,Z.jsx)(`div`,{onMouseDown:l,className:`absolute right-0 top-0 bottom-0 z-20 w-1 cursor-col-resize hover:bg-primary/20 transition-colors`})]})]})}var U0=`canvas:readerWidth`,W0=320,G0=1600;function K0(){try{let e=Number(sessionStorage.getItem(U0));return Number.isFinite(e)&&e>=W0&&e<=G0?e:null}catch{return null}}var q0=K0(),J0=new Set;function Y0(e){return J0.add(e),()=>{J0.delete(e)}}function X0(e){q0=e===null?null:Math.round(Math.max(W0,Math.min(G0,e)));try{q0===null?sessionStorage.removeItem(U0):sessionStorage.setItem(U0,String(q0))}catch{}J0.forEach(e=>e())}function Z0(){return(0,X.useSyncExternalStore)(Y0,()=>q0,()=>null)}var Q0=320,$0=1600;function e2({edge:e}){let t=Z0(),n=(0,X.useRef)(null),r=e===`left`?-1:1;return(0,Z.jsx)(`div`,{role:`separator`,"aria-label":`Resize document reader`,"aria-orientation":`vertical`,"aria-valuemin":Q0,"aria-valuemax":$0,"aria-valuenow":t??560,tabIndex:0,title:`Drag to resize; arrow keys adjust width; double-click to reset`,className:`absolute inset-y-0 ${e===`left`?`left-0`:`right-0`} z-20 hidden w-2 touch-none cursor-col-resize select-none hover:bg-primary/20 focus-visible:bg-primary/20 focus-visible:outline-none md:block`,onPointerDown:t=>{if(t.button!==0)return;t.preventDefault(),t.stopPropagation();let r=t.currentTarget.closest(`[data-reader-pane]`),i=e===`left`?(r.parentElement?.clientWidth??window.innerWidth)-240:window.innerWidth;n.current={x:t.clientX,width:r.getBoundingClientRect().width,max:Math.max(Q0,i)},t.currentTarget.setPointerCapture(t.pointerId)},onPointerMove:e=>{n.current&&X0(Math.min(n.current.max,n.current.width+r*(e.clientX-n.current.x)))},onPointerUp:e=>{n.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)},onPointerCancel:()=>{n.current=null},onLostPointerCapture:()=>{n.current=null},onDoubleClick:()=>X0(null),onKeyDown:e=>{if(e.key!==`ArrowLeft`&&e.key!==`ArrowRight`&&e.key!==`Home`)return;e.preventDefault(),e.stopPropagation();let t=e.currentTarget.closest(`[data-reader-pane]`);e.key===`Home`?X0(null):X0(t.getBoundingClientRect().width+(e.key===`ArrowRight`?1:-1)*r*(e.shiftKey?64:16))}})}function t2(e){return e.schema===`data/schema/note`?vn:e.schema===`data/schema/tab`?fn:e.schema===`data/schema/file`?Bn:e.schema===`data/schema/message/email`?vt:yt}function n2({entry:e,onClose:t,frame:n}={}){let r=Pp(),i=e??r.entry,a=t??r.close,{document:o,refresh:s}=Ug(i?.workspaceId,i?.document??null);if(!i||!o)return null;let{workspaceId:c}=i;return(0,Z.jsx)(lS,{title:mo(o).title,icon:t2(o),onClose:a,onSave:async e=>(await qr(c,e.path,[o.id],e.treeName,e.treeType),[o.id]),canSave:!0,successMessage:`Linked`,lockedWorkspaceName:c,relationSubjectId:o.id,frame:n,fillParent:!0,fullWidthContent:kh(o)===Fm,children:(0,Z.jsx)(Hg,{document:o,workspaceId:c,onChanged:s,compact:!0},`${c}:${o.id}`)})}function r2(e){let[t]=e.split(`/`).filter(Boolean);return!t||t===`home`||t===`share-target`}function i2(e){let[t,n]=e.split(`/`).filter(Boolean);return[`contexts`,`workspaces`,`agents`].includes(t)&&!!n}var a2=`max-md:fixed max-md:left-2 max-md:right-2 max-md:top-2 max-md:bottom-2 max-md:z-side max-md:py-0 max-md:pr-0 max-md:rounded-2xl max-md:shadow-elevation-5 max-md:animate-fade-in`,o2=`fixed inset-0 z-side-scrim bg-scrim animate-fade-in md:hidden`;function s2(){let e=Z0(),{pathname:t}=Hc(),n=i2(t),r=r2(t),{entry:i,close:a}=Pp();return(0,Z.jsx)(`div`,{className:K(`relative flex flex-col flex-1 min-w-0`,!r&&`surface-sheet`),children:(0,Z.jsxs)(`div`,{className:`flex flex-1 min-h-0 gap-shell`,children:[(0,Z.jsx)(`main`,{id:`content-area`,className:K(`relative flex-1 min-h-0 min-w-0 overflow-auto`,!n&&!r&&`p-page max-md:pb-rail-stack`),children:(0,Z.jsx)(vl,{})}),i&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:o2,onClick:a,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{"data-reader-pane":!0,style:{"--reader-width":`${e??560}px`,"--document-card-width":`100%`},className:K(`relative flex shrink-0 items-stretch py-2 pr-2 md:w-[var(--reader-width)] md:max-w-[calc(100%_-_240px)]`,a2),children:[(0,Z.jsx)(e2,{edge:`left`}),(0,Z.jsx)(n2,{})]})]})]})})}function c2(){let{state:e,setView:t}=hs(),{pathname:n}=Hc();return e.t1Open||e.addOpen||!r2(n)?null:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(`tools`),"aria-label":`Open toolbox`,title:`Open toolbox`,className:`fixed z-50 hidden md:flex h-16 w-16 items-center justify-center rounded-full shadow-elevation-4 transition-colors bottom-fab-inset right-6 bg-foreground text-background hover:bg-foreground`,children:(0,Z.jsx)(Ot,{className:`h-7 w-7`,strokeWidth:1.75,"aria-hidden":!0})})}var l2={current:null,sessions:null,isLoading:!1,error:null};function u2(e){return e instanceof Error?e.message:`Session request failed`}function d2({children:e}){let[t,n]=(0,X.useState)({}),r=(0,X.useCallback)((e,t)=>{n(n=>({...n,[e]:{...n[e]||l2,...t}}))},[]),i=(0,X.useCallback)((e,t)=>(r(e,{current:t.current,sessions:t.sessions,isLoading:!1,error:null}),t),[r]),a=(0,X.useCallback)(async e=>{if(e){r(e,{isLoading:!0,error:null});try{let[t,n]=await Promise.all([JC(e),YC(e)]);r(e,{current:t,sessions:n,isLoading:!1,error:null})}catch(t){throw r(e,{isLoading:!1,error:u2(t)}),t}}},[r]),o=(0,X.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await XC(e,t))}catch(t){throw r(e,{isLoading:!1,error:u2(t)}),t}},[i,r]),s=(0,X.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await ZC(e,t))}catch(t){throw r(e,{isLoading:!1,error:u2(t)}),t}},[i,r]),c=(0,X.useCallback)(async(e,t,n)=>{r(e,{isLoading:!0,error:null});try{return i(e,await QC(e,t,{name:n}))}catch(t){throw r(e,{isLoading:!1,error:u2(t)}),t}},[i,r]),l=(0,X.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await $C(e,t))}catch(t){throw r(e,{isLoading:!1,error:u2(t)}),t}},[i,r]),u=(0,X.useMemo)(()=>({getState:e=>t[e]||l2,refresh:a,create:o,select:s,rename:c,remove:l}),[t,a,o,s,c,l]);return(0,Z.jsx)(ID.Provider,{value:u,children:e})}var f2=`data/schema/`,p2={"data/schema/file":{label:`Files`,icon:_n},"data/schema/note":{label:`Notes`,icon:vn},"data/schema/task":{label:`Todos`,icon:zt},"data/schema/tab":{label:`Tabs`,icon:C},"data/schema/message/email":{label:`Emails`,icon:vt},"data/schema/link":{label:`Links`,icon:fn},"data/schema/identity":{label:`Identities`,icon:Ze},"data/schema/drawing":{label:`Sketches`,icon:re}};function m2(e){return p2[e]??{label:e.startsWith(`data/schema/`)?e.slice(12).replace(/(^|\/)(\w)/g,(e,t,n)=>t+n.toUpperCase()):e,icon:h}}function h2(e){return p2[e]?.icon??h}function g2(e){return{...e,lens:bx.lens}}function _2(e,t){return JSON.stringify(g2(e))!==JSON.stringify(g2(t??bx))}var v2={t1Open:!1,t1View:null,toolsTab:`features`,appsAppletId:null,t2Open:!1,t2AgentId:null,addOpen:!1,addKind:null,addRelateTo:null,editDocument:null,editWorkspaceId:null,activeContextPath:null,activeContextType:null,activeWorkspaceName:null,activeTreeName:null,activeCanvasId:null,activeContextId:null,activeAccentColor:null,filters:bx,geoSelection:null,mapDocuments:[],mapWorkspaceId:null,savedFilters:null,savedSearchQuery:null,isDirty:!1,isSaving:!1,availableBitmaps:[],bitmapsLoading:!1,availableTimelines:[],timelineScales:{},timelinesLoading:!1};function y2(e,t){switch(t.type){case`SET_VIEW`:return{...e,t1Open:t.view!==null,t1View:t.view};case`TOGGLE_VIEW`:return e.t1View===t.view?{...e,t1Open:!1,t1View:null}:{...e,t1Open:!0,t1View:t.view};case`CLOSE_T1`:return{...e,t1Open:!1,t1View:null,t2Open:!1,t2AgentId:null};case`OPEN_T2_AGENT`:return{...e,t2Open:!0,t2AgentId:t.agentId};case`CLOSE_T2`:return{...e,t2Open:!1,t2AgentId:null};case`OPEN_ADD`:return{...e,addOpen:!0,addKind:t.kind,addRelateTo:t.relateTo===void 0?e.addRelateTo:t.relateTo,editDocument:null,editWorkspaceId:null};case`CLOSE_ADD`:return{...e,addOpen:!1,addKind:null,addRelateTo:null,editDocument:null,editWorkspaceId:null};case`OPEN_EDIT`:return{...e,addOpen:!0,addKind:null,addRelateTo:null,editDocument:t.document,editWorkspaceId:t.workspaceId};case`SET_TOOLS_TAB`:return{...e,toolsTab:t.tab};case`SET_APPS_APPLET`:return{...e,appsAppletId:t.appletId};case`SET_ACCENT_COLOR`:return e.activeAccentColor===t.color?e:{...e,activeAccentColor:t.color};case`SET_GEO_SELECTION`:return{...e,geoSelection:t.selection};case`SET_MAP_DOCUMENTS`:return e.mapDocuments===t.documents&&e.mapWorkspaceId===t.workspaceId?e:{...e,mapDocuments:t.documents,mapWorkspaceId:t.workspaceId};case`SET_NAVIGATION`:{let n=e.activeContextType===t.contextType&&e.activeContextId===t.contextId&&e.activeCanvasId===t.canvasId;return{...e,activeWorkspaceName:t.workspaceName,activeTreeName:t.treeName,activeCanvasId:t.canvasId,activeContextId:t.contextId,activeContextType:t.contextType,activeContextPath:t.contextPath,geoSelection:null,...n?{}:{filters:bx,savedFilters:null,savedSearchQuery:null,isDirty:!1}}}case`SET_CONTEXT_SCOPE`:return e.activeContextType!==`context`||e.activeWorkspaceName===t.workspaceName&&e.activeContextPath===t.contextPath&&e.activeTreeName===t.treeId?e:{...e,activeWorkspaceName:t.workspaceName,activeContextPath:t.contextPath,activeTreeName:t.treeId};case`SET_FILTERS`:return{...e,filters:t.filters,isDirty:e.activeContextType!==null&&_2(t.filters,e.savedFilters)};case`SET_SAVED_FILTERS`:{let n=t.hydrating===!0&&e.isDirty,r=n?e.filters:t.savedFilters??bx;return{...e,savedFilters:t.savedFilters,savedSearchQuery:t.savedSearchQuery??null,filters:r,isDirty:n?_2(r,t.savedFilters):!1}}case`SET_SAVING`:return{...e,isSaving:t.isSaving};case`SET_BITMAPS`:return{...e,availableBitmaps:t.keys,bitmapsLoading:!1};case`SET_BITMAPS_LOADING`:return{...e,bitmapsLoading:t.loading};case`SET_TIMELINES`:return{...e,availableTimelines:t.names,timelineScales:t.scales??e.timelineScales,timelinesLoading:!1};case`SET_TIMELINES_LOADING`:return{...e,timelinesLoading:t.loading};default:return e}}var b2=`toolbox:session:filters`;function x2(){try{let e=localStorage.getItem(b2);if(!e)return null;let t=JSON.parse(e);return{...bx,...t,features:{...bx.features,...t.features??{}},timeline:{...bx.timeline,...t.timeline??{}},geo:{...bx.geo,...t.geo??{}},lens:bx.lens,sort:{...yx,...t.sort??{}}}}catch{return null}}function S2(e){try{localStorage.setItem(b2,JSON.stringify(g2(e)))}catch{}}function C2(e){if(!e?.toolbox)return null;try{let t=e.toolbox;return{features:{allOf:t.features?.allOf??[],anyOf:t.features?.anyOf??[],noneOf:t.features?.noneOf??[]},timeline:{quickFilter:t.timeline?.quickFilter??null,customRanges:t.timeline?.customRanges??(t.timeline?.customRange?[t.timeline.customRange]:[]),indexCreated:t.timeline?.indexCreated??!0,indexUpdated:t.timeline?.indexUpdated??!0,indexDeleted:t.timeline?.indexDeleted??!1,contentEvents:t.timeline?.contentEvents??!1,selectedTimelines:t.timeline?.selectedTimelines??[]},geo:{bbox:t.geo?.bbox??null},lens:bx.lens,sort:{sortBy:t.sort?.sortBy??yx.sortBy,order:t.sort?.order===`asc`?`asc`:`desc`}}}catch{return null}}function w2(e,t){let n=e;for(let e of t.split(`/`).filter(Boolean))if(n=n?.children?.find(t=>t.name===e)??null,!n)break;return n}function T2({children:e}){let[t,n]=(0,X.useReducer)(y2,v2),r=Hc(),i=new URLSearchParams(r.search).get(`ownerId`)||void 0,a=(0,X.useRef)(t);(0,X.useEffect)(()=>{a.current=t}),(0,X.useEffect)(()=>{let e=!1,t=r.pathname.split(`/`).filter(Boolean),i=t[0]===`workspaces`&&t[1]||null,o=t[0]===`contexts`&&t[1]||null,{path:s,treeName:c}=i?iv(r.pathname):{path:`/`,treeName:``},l=t=>{if(e)return;let r=t?`canvas`:o?`context`:null,l=a.current;l.activeContextType!==null&&r===null&&S2(l.filters),n({type:`SET_NAVIGATION`,workspaceName:i,treeName:i?c:null,canvasId:t,contextId:o,contextType:r,contextPath:i?s:null})};return i&&s!==`/`?(fi(i,c).then(t=>{if(e)return;let n=w2(t,s);l(n?.type===`canvas`?n.id:null)}).catch(()=>l(null)),()=>{e=!0}):(l(null),()=>{e=!0})},[r.pathname]),(0,X.useEffect)(()=>{let e=t.activeWorkspaceName;e&&(n({type:`SET_BITMAPS_LOADING`,loading:!0}),Ki(e).then(e=>{n({type:`SET_BITMAPS`,keys:e})}))},[t.activeWorkspaceName]),(0,X.useEffect)(()=>{let e=t.activeWorkspaceName;e&&(n({type:`SET_TIMELINES_LOADING`,loading:!0}),di(e).then(e=>{n({type:`SET_TIMELINES`,names:e.map(e=>e.name),scales:Object.fromEntries(e.filter(e=>e.scales?.length).map(e=>[e.name,e.scales]))})}))},[t.activeWorkspaceName]),(0,X.useEffect)(()=>{let{activeContextType:e,activeCanvasId:r,activeWorkspaceName:i,activeTreeName:a,activeContextPath:o}=t;if(e!==`context`){if(e===`canvas`&&r&&i&&o)fi(i,a||`context`).then(e=>{let t=w2(e,o),r=C2(t?.metadata);n({type:`SET_SAVED_FILTERS`,savedFilters:r,savedSearchQuery:t?.querySpec?.query??null,hydrating:!0})}).catch(()=>{n({type:`SET_SAVED_FILTERS`,savedFilters:null,savedSearchQuery:null,hydrating:!0})});else{let e=x2();n({type:`SET_SAVED_FILTERS`,savedFilters:e,savedSearchQuery:null})}}},[t.activeCanvasId,t.activeContextPath,t.activeContextType,t.activeTreeName,t.activeWorkspaceName]),(0,X.useEffect)(()=>{let{activeContextType:e,activeContextId:r}=t;if(e!==`context`||!r)return;let a=!1,o=0,s=e=>{let t=++o;return $o(r,i).then(r=>{if(a||t!==o)return;let i=r.metadata,s=C2(i);n({type:`SET_CONTEXT_SCOPE`,workspaceName:r.workspaceName||r.workspaceId||null,contextPath:r.path||`/`,treeId:r.treeId||null}),e&&n({type:`SET_SAVED_FILTERS`,savedFilters:s,savedSearchQuery:typeof i?.toolboxSearchQuery==`string`?i.toolboxSearchQuery:null,hydrating:!0})}).catch(()=>{a||e&&n({type:`SET_SAVED_FILTERS`,savedFilters:null,savedSearchQuery:null,hydrating:!0})})};s(!0);let c=()=>{s(!1)},l=Wu.on(`context.url.set`,e=>{e?.id===r&&c()});return window.addEventListener(`contexts:refresh`,c),()=>{a=!0,l(),window.removeEventListener(`contexts:refresh`,c)}},[t.activeContextId,t.activeContextType,i]),(0,X.useEffect)(()=>{t.activeContextType===null&&S2(t.filters)},[t.filters,t.activeContextType]);let o=(0,X.useCallback)(e=>n({type:`SET_VIEW`,view:e}),[]),s=(0,X.useCallback)(e=>n({type:`TOGGLE_VIEW`,view:e}),[]),c=(0,X.useCallback)(()=>n({type:`CLOSE_T1`}),[]),l=(0,X.useCallback)(e=>n({type:`OPEN_T2_AGENT`,agentId:e}),[]),u=(0,X.useCallback)(()=>n({type:`CLOSE_T2`}),[]),d=(0,X.useCallback)(e=>n({type:`OPEN_ADD`,kind:e}),[]),f=(0,X.useCallback)(()=>n({type:`OPEN_ADD`,kind:null,relateTo:null}),[]),p=(0,X.useCallback)(e=>n({type:`OPEN_ADD`,kind:null,relateTo:e}),[]),m=(0,X.useCallback)(()=>n({type:`CLOSE_ADD`}),[]),h=(0,X.useCallback)((e,t)=>n({type:`OPEN_EDIT`,document:e,workspaceId:t}),[]),g=(0,X.useCallback)(e=>n({type:`SET_TOOLS_TAB`,tab:e}),[]),_=(0,X.useCallback)(e=>n({type:`SET_APPS_APPLET`,appletId:e}),[]),v=(0,X.useCallback)(e=>n({type:`SET_ACCENT_COLOR`,color:e}),[]),y=(0,X.useCallback)(e=>{n({type:`SET_FILTERS`,filters:e})},[]),b=(0,X.useCallback)((e,t)=>{let{filters:r}=a.current,i=e.startsWith(f2),o=i?r.features.allOf.filter(t=>t!==e):t?[...new Set([...r.features.allOf,e])]:r.features.allOf.filter(t=>t!==e),s=i&&t?[...new Set([...r.features.anyOf,e])]:r.features.anyOf.filter(t=>t!==e),c=r.features.noneOf.filter(t=>t!==e);n({type:`SET_FILTERS`,filters:{...r,features:{allOf:o,anyOf:s,noneOf:c}}})},[]),x=(0,X.useCallback)((e,t)=>{let{filters:r}=a.current,i=r.features.allOf.filter(t=>t!==e),o=r.features.anyOf.filter(t=>t!==e),s=r.features.noneOf.filter(t=>t!==e);t===`allOf`?i.push(e):t===`anyOf`?o.push(e):t===`noneOf`&&s.push(e),n({type:`SET_FILTERS`,filters:{...r,features:{allOf:i,anyOf:o,noneOf:s}}})},[]),S=(0,X.useCallback)(()=>{let{filters:e}=a.current;n({type:`SET_FILTERS`,filters:{...bx,timeline:{...e.timeline,quickFilter:null,customRanges:[],customRange:null,selectedTimelines:[]}}})},[]),C=(0,X.useCallback)(e=>{let{filters:t}=a.current;n({type:`SET_FILTERS`,filters:{...t,sort:e}})},[]),w=(0,X.useCallback)(e=>{let{filters:t}=a.current;n({type:`SET_FILTERS`,filters:{...t,timeline:{...t.timeline,...e}}})},[]),T=(0,X.useCallback)(e=>{let{filters:t}=a.current;n({type:`SET_FILTERS`,filters:{...t,geo:{...t.geo,bbox:e}}})},[]),E=(0,X.useCallback)(e=>{let{filters:t}=a.current;n({type:`SET_FILTERS`,filters:{...t,lens:{...t.lens,gps:e}}})},[]),D=(0,X.useCallback)(e=>{let{filters:t}=a.current;n({type:`SET_FILTERS`,filters:{...t,lens:{...t.lens,ids:e}}})},[]),O=(0,X.useCallback)(e=>{n({type:`SET_GEO_SELECTION`,selection:e})},[]),k=(0,X.useCallback)((e,t=null)=>{n({type:`SET_MAP_DOCUMENTS`,documents:e,workspaceId:t})},[]),A=(0,X.useCallback)(async()=>{let{activeContextType:e,activeContextId:t,activeWorkspaceName:o,activeTreeName:s,activeContextPath:c,filters:l,isSaving:u}=a.current;if(!u){n({type:`SET_SAVING`,isSaving:!0});try{if(e===`canvas`&&o&&c){let e=s||`context`,t=w2(await fi(o,e),c),n=new URLSearchParams(r.search).get(`q`)||new URLSearchParams(r.search).get(`search`)||``;await _a(o,c,{metadata:{...t?.metadata||{},toolbox:g2(l)},querySpec:{features:l.features,filters:[...wx(l.timeline),...xx(l.geo)],query:n.trim()||void 0,sort:l.sort?.sortBy?l.sort:null}},e),oa(o,e)}else if(e===`context`&&t){let e=(await $o(t,i)).metadata||{},n=new URLSearchParams(r.search).get(`q`)||new URLSearchParams(r.search).get(`search`)||``;await Mo(t,{metadata:{...e,toolbox:g2(l),toolboxSearchQuery:n.trim()||void 0},features:l.features,filters:[...wx(l.timeline),...xx(l.geo)]},i)}let a=new URLSearchParams(r.search).get(`q`)||new URLSearchParams(r.search).get(`search`)||``;n({type:`SET_SAVED_FILTERS`,savedFilters:l,savedSearchQuery:a.trim()||null})}finally{n({type:`SET_SAVING`,isSaving:!1})}}},[r.search,i]),j=(0,X.useCallback)(e=>{let t=a.current.availableBitmaps.filter(t=>t!==e);n({type:`SET_BITMAPS`,keys:t});let r=a.current.filters,i={...r,features:{allOf:r.features.allOf.filter(t=>t!==e),anyOf:r.features.anyOf.filter(t=>t!==e),noneOf:r.features.noneOf.filter(t=>t!==e)}};JSON.stringify(i.features)!==JSON.stringify(r.features)&&n({type:`SET_FILTERS`,filters:i})},[]),M=(0,X.useCallback)(async e=>{let t=a.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await si(t,e),j(e)},[j]),N=(0,X.useCallback)(async e=>{let t=a.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);let n=await Cr(t,e);return j(e),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:t}})),n.documentsDeleted},[j]),P=(0,X.useCallback)(()=>{let e=a.current.activeWorkspaceName;e&&(n({type:`SET_TIMELINES_LOADING`,loading:!0}),di(e).then(e=>{n({type:`SET_TIMELINES`,names:e.map(e=>e.name),scales:Object.fromEntries(e.filter(e=>e.scales?.length).map(e=>[e.name,e.scales]))})}))},[]),ee=(0,X.useCallback)(async e=>{let t=a.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await Ai(t,e),P()},[P]),F=(0,X.useCallback)(async e=>{let t=a.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await kr(t,e);let r=a.current.availableTimelines.filter(t=>t!==e);n({type:`SET_TIMELINES`,names:r});let i=a.current.filters,o=i.timeline.selectedTimelines.filter(t=>t!==e);o.length!==i.timeline.selectedTimelines.length&&n({type:`SET_FILTERS`,filters:{...i,timeline:{...i.timeline,selectedTimelines:o}}})},[]),{features:I,timeline:te,geo:ne,lens:L}=t.filters,re=I.allOf.length>0||I.anyOf.length>0||I.noneOf.length>0||te.quickFilter!==null||(te.customRanges?.length??0)>0||(te.selectedTimelines?.length??0)>0||ne.bbox!==null||L.gps!==null||L.ids!==null;return(0,Z.jsx)(Ho.Provider,{value:{state:t,setView:o,toggleView:s,closeT1:c,openAgentT2:l,closeT2:u,openAdd:d,openAddPicker:f,openAddRelated:p,closeAdd:m,openEdit:h,setToolsTab:g,openApplet:_,setAccentColor:v,setFilters:y,setFeatureToggle:b,setFeatureMode:x,clearFilters:S,hasActiveFilters:re,setTimelineFilter:w,setGeoBBox:T,setLensGps:E,setLensIds:D,setGeoSelection:O,setMapDocuments:k,setSort:C,saveFilters:A,deleteBitmap:M,deleteDataset:N,createTimeline:ee,deleteTimeline:F,refreshTimelines:P},children:e})}var E2=`references`;function D2(e){return e?e.documents.map(e=>({predicate:E2,direction:`out`,targetId:e.id,document:e})):[]}function O2(e,t){let[n,r]=(0,X.useState)(()=>D2(t)),[i,a]=(0,X.useState)([...xa]),o=e?.mode===`context`?e.contextId:null,[s,c]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!o)return;let e=!1;return cs({mode:`context`,contextId:o}).then(t=>{e||c({contextId:o,workspaceName:t.workspaceName})}).catch(()=>{}),()=>{e=!0}},[o]);let l=e?.mode===`workspace`?e.workspaceName:o&&s?.contextId===o?s.workspaceName:t?.workspaceName??null;return(0,X.useEffect)(()=>{let e=!1;if(l)return bi(l).then(t=>{e||a(t)}),()=>{e=!0}},[l]),{rows:n,predicates:i,workspaceName:l,add:(0,X.useCallback)(async(e,t,i)=>{let a=i.filter(r=>!n.some(n=>n.targetId===r&&n.predicate===e&&n.direction===t));if(a.length===0)return;let o=await Promise.all(a.map(e=>l?gr(l,e).catch(()=>null):Promise.resolve(null)));r(n=>[...n,...a.map((n,r)=>({predicate:e,direction:t,targetId:n,document:o[r]??null}))])},[n,l]),update:(0,X.useCallback)((e,t)=>{r(n=>n.map((n,r)=>r===e?{...n,...t}:n))},[]),remove:(0,X.useCallback)(e=>{r(t=>t.filter((t,n)=>n!==e))},[]),write:(0,X.useCallback)(async e=>{if(n.length===0||e.length===0||!l)return 0;let t=new Map;for(let e of n){let n=`${e.direction}:${e.predicate}`,r=t.get(n)??{predicate:e.predicate,direction:e.direction,targets:[]};r.targets.push(e.targetId),t.set(n,r)}let r=0;for(let n of e)for(let e of t.values())try{await Wi(l,n,e.predicate,e.targets,e.direction)}catch(t){r+=1,console.error(`Failed to relate document`,n,e.predicate,t)}return r<e.length*t.size&&Kp(),r},[n,l]),hasRows:n.length>0}}function k2({f:e,idPrefix:t}){let[n,r]=(0,X.useState)(!1),[i,a]=(0,X.useState)(!1),o=!e.workspaceName;return(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(bu,{children:`Related documents`}),(0,Z.jsxs)(J,{type:`button`,variant:`ghost`,size:`sm`,className:`h-7 px-2 text-xs`,disabled:o,onClick:()=>r(!0),title:o?`No workspace to relate within`:`Pick documents the new one relates to`,children:[(0,Z.jsx)(nn,{className:`mr-1 h-3 w-3`}),` Add`]})]}),e.rows.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None. Relations are written right after the document is created.`}):(0,Z.jsx)(`ul`,{className:`space-y-1`,children:e.rows.map((n,r)=>{let i=n.document?mo(n.document).title:`Document ${n.targetId}`,a=`${t}-relation-${r}`;return(0,Z.jsxs)(`li`,{className:`flex items-center gap-1.5 rounded-md border border-input px-2 py-1.5 text-sm`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>e.update(r,{direction:n.direction===`out`?`in`:`out`}),className:`shrink-0 rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground`,title:n.direction===`out`?`The new document ${n.predicate} this one (click to flip)`:`This document ${n.predicate} the new one (click to flip)`,"aria-label":`Flip relation direction`,children:n.direction===`out`?(0,Z.jsx)(_t,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Pn,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`label`,{htmlFor:a,className:`sr-only`,children:`Predicate`}),(0,Z.jsx)(`select`,{id:a,value:n.predicate,onChange:t=>e.update(r,{predicate:t.target.value}),className:`w-[9.5rem] shrink-0 rounded-md border border-input bg-background px-1.5 py-1 font-mono text-[11px] focus:outline-none focus:ring-2 focus:ring-ring`,children:(e.predicates.includes(n.predicate)?e.predicates:[n.predicate,...e.predicates]).map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))}),n.document?(0,Z.jsx)(Jf,{document:n.document,size:3.5}):null,(0,Z.jsx)(`span`,{className:K(`min-w-0 flex-1 truncate`,!n.document&&`italic text-muted-foreground`),title:`#${n.targetId}`,children:i}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>e.remove(r),className:`shrink-0 rounded p-0.5 text-muted-foreground hover:bg-destructive/10 hover:text-destructive`,title:`Remove`,"aria-label":`Remove relation`,children:(0,Z.jsx)(je,{className:`h-3.5 w-3.5`})})]},`${n.direction}:${n.predicate}:${n.targetId}`)})}),n&&e.workspaceName&&(0,Z.jsx)(sp,{onClose:()=>{i||r(!1)},children:(0,Z.jsx)(ap,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,title:`Relate to…`,confirmLabel:`Add`,tabs:[`relations`],fixedWorkspaceName:e.workspaceName,documentCount:1,saving:i,relationPredicates:e.predicates.length?e.predicates:[`references`],relationExcludeIds:new Set(e.rows.map(e=>e.targetId)),onClose:()=>r(!1),onConfirm:()=>{},onConfirmRelation:async({predicate:t,direction:n,targetIds:i})=>{a(!0);try{await e.add(t,n,i),r(!1)}finally{a(!1)}}})})]})}function A2(){let{closeAdd:e,state:t}=hs(),n=rs(),{showSuccessToast:r,showErrorToast:i}=Ya(),a=aS(),o=O2(n,t.addRelateTo),s=DS(t.activeWorkspaceName),c=!!n&&a.canSave;return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`note-title`,children:`Title`}),(0,Z.jsx)(q,{id:`note-title`,value:a.title,onChange:e=>a.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{children:`Body`}),(0,Z.jsx)(yo,{kind:`markdown`,value:a.content,onChange:a.setContent,placeholder:`Write your note…`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`note-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`note-comment`,value:a.comment,onChange:e=>a.setComment(e.target.value),rows:2,placeholder:`Optional; context you can't infer from the body`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{children:`Tags`}),(0,Z.jsx)(up,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,Z.jsx)(sS,{geotag:a.geotag,idPrefix:`note-geotag`}),(0,Z.jsx)(k2,{f:o,idPrefix:`note`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:ss(n)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,Z.jsx)(J,{size:`sm`,onClick:async()=>{if(n)try{let t=await a.save(n),i=await o.write(t);r(i?`Note created; some relations failed`:`Note created`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create note`)}},disabled:!c,children:a.saving?`Saving…`:`Save note`})]})]})}function j2(){let{closeAdd:e,state:t}=hs(),n=rs(),{showSuccessToast:r,showErrorToast:i}=Ya(),a=mS(),o=O2(n,t.addRelateTo),s=DS(t.activeWorkspaceName),c=!!n&&a.canSave;return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`link-url`,children:`URL`}),(0,Z.jsx)(q,{id:`link-url`,value:a.url,onChange:e=>a.setUrl(e.target.value),placeholder:`https://example.com`,autoFocus:!0}),a.showUrlError&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`link-title`,children:`Title`}),(0,Z.jsx)(q,{id:`link-title`,value:a.title,onChange:e=>a.setTitle(e.target.value),placeholder:`Optional display title`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{children:`Tags`}),(0,Z.jsx)(up,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,Z.jsx)(sS,{geotag:a.geotag,idPrefix:`link-geotag`}),(0,Z.jsx)(k2,{f:o,idPrefix:`link`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:ss(n)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,Z.jsx)(J,{size:`sm`,onClick:async()=>{if(n)try{let t=await a.save(n),i=await o.write(t);r(i?`Link created; some relations failed`:`Link created`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create link`)}},disabled:!c,children:a.saving?`Saving…`:`Save link`})]})]})}function M2(e){let[t,n]=(0,X.useState)({key:``,list:[]});return(0,X.useEffect)(()=>{if(!e)return;let t=!1;return va(e,`github`).then(async r=>{let i=r.filter(e=>e.capabilities?.write),a=[];for(let t of i){let n=await Ma(e,`github`,t.address).catch(()=>[]);for(let e of n){if(e.writable===!1)continue;let n=e.id||e.name;a.push({driver:`github`,address:t.address,container:n,label:`GitHub: ${n}`})}}t||n({key:e,list:a})}).catch(()=>{t||n({key:e,list:[]})}),()=>{t=!0}},[e]),e&&t.key===e?t.list:[]}function N2(){let{closeAdd:e,state:t}=hs(),n=rs(),{showSuccessToast:r,showErrorToast:i}=Ya(),a=ch(),o=O2(n,t.addRelateTo),s=DS(t.activeWorkspaceName),c=M2(t.activeWorkspaceName),[l,u]=(0,X.useState)(`canvas`),[d,f]=(0,X.useState)(!1),p=c.find(e=>`${e.driver}:${e.address}:${e.container}`===l),m=p?a.title.trim().length>0&&!d:!!n&&a.canSave,h=async()=>{if(p){f(!0);try{await qi(t.activeWorkspaceName||``,p.driver,p.address,p.container,{title:a.title.trim(),...a.description.trim()?{description:a.description.trim()}:{},...a.tags.length?{labels:a.tags}:{}}),r(`Issue created in ${p.container}`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create issue`)}finally{f(!1)}return}if(n)try{let t=await a.save(n),i=await o.write(t);r(i?`Todo created; some relations failed`:`Todo created`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create todo`)}};return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsx)(Jh,{...a}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{children:`Tags`}),(0,Z.jsx)(up,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`todo-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`todo-comment`,value:a.comment,onChange:e=>a.setComment(e.target.value),rows:3,placeholder:`Optional context`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]}),c.length>0&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`todo-destination`,children:`Save to`}),(0,Z.jsxs)(`select`,{id:`todo-destination`,value:l,onChange:e=>u(e.target.value),className:`flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-elevation-1 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`,children:[(0,Z.jsxs)(`option`,{value:`canvas`,children:[`Canvas: `,ss(n)]}),c.map(e=>(0,Z.jsx)(`option`,{value:`${e.driver}:${e.address}:${e.container}`,children:e.label},`${e.driver}:${e.address}:${e.container}`))]}),p&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Creates a GitHub issue (due date, priority and status stay Canvas-side until the issue syncs back).`})]}),(0,Z.jsx)(sS,{geotag:a.geotag,idPrefix:`todo-geotag`}),!p&&(0,Z.jsx)(k2,{f:o,idPrefix:`todo`}),!p&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:ss(n)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving||d,children:`Cancel`}),(0,Z.jsx)(J,{size:`sm`,onClick:h,disabled:!m,children:a.saving||d?`Saving…`:p?`Create issue`:`Save todo`})]})]})}function P2(){let{closeAdd:e,state:t}=hs(),n=rs(),{showSuccessToast:r,showErrorToast:i}=Ya(),a=rg(),o=O2(n,t.addRelateTo),s=DS(t.activeWorkspaceName),c=async()=>{if(n)try{let t=await a.save(n),i=await o.write(t);r(i?`Identity created; some relations failed`:`Identity created`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create identity`)}};return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsx)(cg,{idPrefix:`add-identity`,workspaceName:t.activeWorkspaceName??void 0,...a,emailValid:a.emailValid}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{children:`Tags`}),(0,Z.jsx)(up,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`identity-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`identity-comment`,value:a.comment,onChange:e=>a.setComment(e.target.value),rows:3,placeholder:`How you know them, where they came from…`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]}),(0,Z.jsx)(k2,{f:o,idPrefix:`identity`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:ss(n)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,Z.jsx)(J,{size:`sm`,onClick:c,disabled:!n||!a.canSave,children:a.saving?`Saving…`:`Save identity`})]})]})}function F2({capture:e=!1}={}){let{closeAdd:t,state:n}=hs(),r=rs(),i=r?.mode===`workspace`&&r.treeName===`backends`,a=O2(r,n.addRelateTo),{showSuccessToast:o,showErrorToast:s}=Ya(),c=(0,X.useRef)(null),[l,u]=(0,X.useState)(!1),d=bS(),{items:f,running:p}=d,[m,h]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(r?.mode!==`context`)return;let e=!1;return cs(r).then(t=>{e||h({contextId:r.contextId,workspaceName:t.workspaceName})}).catch(()=>{}),()=>{e=!0}},[r]);let g=AS(r?.mode===`workspace`?r.workspaceName:r&&m?.contextId===r.contextId?m.workspaceName:null),_=e=>{e&&d.addFiles(Array.from(e))},v=e=>{e.preventDefault(),u(!1),_(e.dataTransfer.files)},y=f.filter(e=>e.status===`error`).length,b=f.filter(e=>e.status===`done`).length,x=f.length-b,S=!!r&&!p&&x>0;return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),u(!0)},onDragLeave:()=>u(!1),onDrop:v,onClick:()=>c.current?.click(),className:K(`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-md border border-dashed px-4 py-8 text-center transition-colors`,l?`border-primary bg-primary/5`:`border-input hover:bg-muted/40`),children:[(0,Z.jsx)(ne,{className:`h-6 w-6 text-muted-foreground touch-target`}),(0,Z.jsx)(`p`,{className:`text-sm`,children:e?`Take a photo or video`:`Drag & drop files here`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e?`click to open the camera`:`or click to browse`}),(0,Z.jsx)(`input`,{ref:c,type:`file`,multiple:!0,accept:e?`image/*,video/*`:void 0,capture:e?`environment`:void 0,className:`hidden`,onChange:e=>{_(e.target.files),e.target.value=``}})]}),(0,Z.jsx)(TS,{items:f,running:p,onRemove:d.removeItem}),!i&&(0,Z.jsx)(NS,{fields:g,idPrefix:`file`,multiple:f.length>1}),(0,Z.jsx)(k2,{f:a,idPrefix:`file`}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[ss(r),i?`. Existing files are never overwritten.`:``]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>p?d.cancel():t(),children:`Cancel`}),(0,Z.jsx)(J,{size:`sm`,onClick:async()=>{if(!(!S||!r))try{let e=i?null:await g.geotag.capture(),n=await d.start(r,(t,n)=>jS(t,n,{tags:g.tags,comment:g.comment,geo:e})),c=await a.write(n.docIds);if(n.failed===0){let e=n.resumed?` (${n.resumed} already uploaded)`:``,r=c?`; some relations failed`:``;o(`${n.done} file(s) uploaded${e}${r}`),t()}else s(`${n.failed} of ${n.total} file(s) failed — retry keeps what already made it`)}catch(e){s(e instanceof Error?e.message:`Failed to upload files`)}},disabled:!S,children:p?`Uploading…`:y>0?(0,Z.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,Z.jsx)($n,{className:`h-3.5 w-3.5`}),`Retry failed (`,y,`)`]}):`Add files`})]})]})}function I2(){let{closeAdd:e}=hs(),t=rs(),{showSuccessToast:n,showErrorToast:r}=Ya(),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(!1),c=i.trim().replace(/^\/+|\/+$/g,``),l=!!t&&!!c&&!o,u=async()=>{if(!(!l||!t)){s(!0);try{let{workspaceName:r,path:i,treeName:a}=await cs(t),o=i===`/`?``:i;if(a===`backends`){let e=await as(r,i);await Di(r,e.driver,e.address,[[e.key,c].filter(Boolean).join(`/`)]),qo(t)}else await Fi(r,`${o}/${c}`,!0,a);n(`Folder created`),e()}catch(e){r(e instanceof Error?e.message:`Failed to create folder`)}finally{s(!1)}}};return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`add-folder-name`,children:`Folder name`}),(0,Z.jsx)(q,{id:`add-folder-name`,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&u()},placeholder:`e.g. projects/alpha`,autoFocus:!0}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Nested paths are created as needed. Target: `,ss(t)]})]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:e,disabled:o,children:`Cancel`}),(0,Z.jsx)(J,{size:`sm`,onClick:u,disabled:!l,children:o?`Creating…`:`Create folder`})]})]})}function L2(){let{openAddPicker:e,closeAdd:t}=hs(),n=rs(),{showSuccessToast:r,showErrorToast:i}=Ya(),[a,o]=(0,X.useState)(!1);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:e,"aria-hidden":!0}),(0,Z.jsx)(`div`,{className:`fixed inset-y-0 right-0 z-picker flex items-stretch py-2 pr-2 max-md:bottom-2 max-md:left-2 max-md:top-2 max-md:py-0 max-md:pr-0 max-md:animate-fade-in`,children:(0,Z.jsx)(jp,{sizeClassName:`h-full w-[420px] max-w-full max-md:w-full max-md:shadow-elevation-5`,fixedWorkspaceName:n?.mode===`workspace`?n.workspaceName:void 0,saving:a,onConfirm:async e=>{o(!0);try{await es(n,e),r(`${e.length} document${e.length===1?``:`s`} added`),t()}catch(e){i(e instanceof Error?e.message:`Failed to add documents`)}finally{o(!1)}},onClose:e})})]})}function R2(e,t){let[n,r]=(0,X.useState)(String(e.data?.title??``)),[i,a]=(0,X.useState)(String(e.data?.content??``)),[o,s]=(0,X.useState)(fp(e.metadata?.features)),[c,l]=(0,X.useState)(!1),u=i.trim().length>0&&!c;async function d(){l(!0);try{await Li(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:{...n.trim()?{title:n.trim()}:{},content:i},metadata:{features:dp(o)}}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`))}finally{l(!1)}}return{title:n,setTitle:r,content:i,setContent:a,tags:o,setTags:s,saving:c,canSave:u,save:d}}function z2(){let{state:e,closeAdd:t}=hs(),{editDocument:n,editWorkspaceId:r}=e,{showSuccessToast:i,showErrorToast:a}=Ya();return!n||!r?null:(0,Z.jsx)(B2,{doc:n,workspaceId:r,onCancel:t,onSaved:t,showSuccessToast:i,showErrorToast:a})}function B2({doc:e,workspaceId:t,onCancel:n,onSaved:r,showSuccessToast:i,showErrorToast:a}){let o=R2(e,t),s=DS(t);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`edit-note-title`,children:`Title`}),(0,Z.jsx)(q,{id:`edit-note-title`,value:o.title,onChange:e=>o.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,Z.jsxs)(`div`,{className:`flex flex-1 flex-col gap-1.5`,children:[(0,Z.jsx)(bu,{children:`Body`}),(0,Z.jsx)(`div`,{className:`flex-1`,children:(0,Z.jsx)(yo,{kind:`markdown`,value:o.content,onChange:o.setContent,placeholder:`Write your note…`})})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{children:`Tags`}),(0,Z.jsx)(up,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:n,disabled:o.saving,children:`Cancel`}),(0,Z.jsx)(J,{size:`sm`,onClick:async()=>{try{await o.save(),i(`Note updated`),r()}catch(e){a(e instanceof Error?e.message:`Failed to update note`)}},disabled:!o.canSave,children:o.saving?`Saving…`:`Save note`})]})]})}function V2(e,t){let n=fp(e.metadata?.features),[r,i]=(0,X.useState)(String(e.data?.label??``)),[a,o]=(0,X.useState)(n.length?n:e.data?.tags??[]),[s,c]=(0,X.useState)(!1),l=!s;async function u(){c(!0);try{let n=a.map(e=>e.trim()).filter(Boolean);await Li(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:{...e.data,...r.trim()?{label:r.trim()}:{},tags:n},metadata:{features:dp(a)}}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`))}finally{c(!1)}}return{url:String(e.data?.uri??e.data?.url??``),label:r,setLabel:i,tags:a,setTags:o,saving:s,canSave:l,save:u}}function H2(){let{state:e,closeAdd:t}=hs(),{editDocument:n,editWorkspaceId:r}=e,{showSuccessToast:i,showErrorToast:a}=Ya();return!n||!r?null:(0,Z.jsx)(U2,{doc:n,workspaceId:r,onCancel:t,onSaved:t,showSuccessToast:i,showErrorToast:a})}function U2({doc:e,workspaceId:t,onCancel:n,onSaved:r,showSuccessToast:i,showErrorToast:a}){let o=V2(e,t),s=DS(t);return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(bu,{children:[`URL `,(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`(frozen)`})]}),(0,Z.jsx)(q,{value:o.url,disabled:!0,className:`font-mono text-xs`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{htmlFor:`edit-link-label`,children:`Label`}),(0,Z.jsx)(q,{id:`edit-link-label`,value:o.label,onChange:e=>o.setLabel(e.target.value),placeholder:`Optional display name`,autoFocus:!0})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(bu,{children:`Tags`}),(0,Z.jsx)(up,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:n,disabled:o.saving,children:`Cancel`}),(0,Z.jsx)(J,{size:`sm`,onClick:async()=>{try{await o.save(),i(`Link updated`),r()}catch(e){a(e instanceof Error?e.message:`Failed to update link`)}},disabled:!o.canSave,children:o.saving?`Saving…`:`Save link`})]})]})}var W2=380,G2=300,K2=560,q2={message:{label:`New Message`,icon:v},note:{label:`New Note`,icon:vn},link:{label:`New Link`,icon:fn},todo:{label:`New Todo`,icon:zt},identity:{label:`New Identity`,icon:Ze},sketch:{label:`New Sketch`,icon:re},file:{label:`Add Files`,icon:ne},photo:{label:`Photo/Video`,icon:w},existing:{label:`Add Existing`,icon:Qt},folder:{label:`New Folder`,icon:ot}};function J2(){let{state:e,openAdd:t,closeAdd:n}=hs();gf(n,e.addOpen);let{addOpen:r,addKind:i,editDocument:a}=e,o=rs(),s=us(o),c=s.isBackend&&!!i&&![`file`,`photo`,`folder`,`message`].includes(i),l=e.activeWorkspaceName,u=!l||!!e.addRelateTo,d=c||i===`message`&&u,f=s.isBackend?[`note`,`link`,`todo`,`identity`,`sketch`,`existing`]:[];u&&f.push(`message`);let p=o?.mode===`workspace`?`${o.workspaceName}:${o.treeName}:${o.path}`:o?.contextId,m=Gc();(0,X.useEffect)(()=>{!r||i!==`sketch`||s.isBackend||(n(),m($x.createUrl(o)))},[r,i,o,n,m,s.isBackend]);let h=wm(),[g,_]=(0,X.useState)(W2),v=(0,X.useRef)(null),y=(0,X.useCallback)(e=>{e.preventDefault(),v.current={startX:e.clientX,startWidth:g};let t=e=>{if(!v.current)return;let t=v.current.startX-e.clientX,n=Math.min(K2,Math.max(G2,v.current.startWidth+t));_(n)},n=()=>{v.current=null,window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n)};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[g]);if(!r)return null;let b=!!a,x=!b&&(!i||d),S,C;return b?(S=a.schema===`data/schema/note`?`Edit Note`:`Edit Link`,C=a.schema===`data/schema/note`?vn:fn):i&&!d?(S=q2[i].label,C=q2[i].icon):(S=`Add`,C=nn),(0,Z.jsxs)(Z.Fragment,{children:[h&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-panel-scrim bg-scrim animate-fade-in`,onClick:n,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{style:h?void 0:{width:g},className:K(`flex flex-col overflow-hidden rounded-[var(--panel-radius)] border bg-card surface-glass`,h?`fixed bottom-2 left-2 right-2 top-2 z-panel shadow-elevation-5 animate-fade-in`:`relative shrink-0 shadow-elevation-3`),children:[!h&&(0,Z.jsx)(`div`,{onMouseDown:y,className:`absolute left-0 top-0 bottom-0 z-10 w-1 cursor-col-resize transition-colors hover:bg-primary/20`}),(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[b?(0,Z.jsx)(ye,{className:`h-4 w-4`}):(0,Z.jsx)(C,{className:`h-4 w-4`}),S]}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground transition-colors hover:text-foreground`,"aria-label":`Close`,children:(0,Z.jsx)(je,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,children:[b&&a.schema===`data/schema/note`&&(0,Z.jsx)(z2,{}),b&&a.schema===`data/schema/link`&&(0,Z.jsx)(H2,{}),!b&&x&&e.addRelateTo&&(0,Z.jsxs)(`p`,{className:`border-b px-4 py-2 text-xs text-muted-foreground`,children:[`The new document will be related to `,e.addRelateTo.documents.length,` selected document`,e.addRelateTo.documents.length===1?``:`s`,`.`]}),!b&&s.isBackend&&i!==`message`&&(0,Z.jsx)(`p`,{className:`border-b px-4 py-3 text-xs text-muted-foreground`,children:s.loading?`Checking storage destination…`:s.error||`Files are saved directly to this backend folder. Notes and other database documents belong in context or directory trees.`}),!b&&x&&(!s.isBackend||s.destination)&&(0,Z.jsx)(nS,{onSelect:t,omit:f}),!b&&i===`message`&&!u&&l&&(0,Z.jsx)(fm,{workspaceId:l,onClose:n},l),!b&&!s.isBackend&&i===`note`&&(0,Z.jsx)(A2,{}),!b&&!s.isBackend&&i===`link`&&(0,Z.jsx)(j2,{}),!b&&!s.isBackend&&i===`todo`&&(0,Z.jsx)(N2,{}),!b&&!s.isBackend&&i===`identity`&&(0,Z.jsx)(P2,{}),!b&&(!s.isBackend||s.destination)&&i===`file`&&(0,Z.jsx)(F2,{},p),!b&&(!s.isBackend||s.destination)&&i===`photo`&&(0,Z.jsx)(F2,{capture:!0},p),!b&&!s.isBackend&&i===`existing`&&(0,Z.jsx)(L2,{}),!b&&(!s.isBackend||s.destination)&&i===`folder`&&(0,Z.jsx)(I2,{},p)]})]})]})}var Y2=(0,X.createContext)(null);function X2(){return(0,X.useContext)(Y2)}function Z2(){let e=X2(),t=e?.notifications??[];return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsx)(`div`,{className:`flex items-center justify-between px-4 h-12 bg-foreground shrink-0`,children:(0,Z.jsx)(`span`,{className:`text-sm font-medium text-background`,children:`Home`})}),(0,Z.jsx)(`div`,{className:`px-4 py-4 border-b border-border shrink-0`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,Z.jsx)(Qn,{className:`w-4 h-4`}),(0,Z.jsx)(`span`,{className:`text-xs font-mono`,children:new Date().toLocaleTimeString()})]})}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(_,{className:`w-3.5 h-3.5 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:`Notifications`})]}),t.length>0&&(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,className:`h-6 px-1.5 text-xs text-muted-foreground`,onClick:()=>void e?.clear(),title:`Clear notifications`,children:(0,Z.jsx)(lt,{className:`w-3 h-3`})})]}),t.length===0?(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground text-center py-10 border border-dashed rounded-lg`,children:`No notifications`}):(0,Z.jsx)(`div`,{className:`space-y-2`,children:[...t].reverse().map(e=>(0,Z.jsxs)(`div`,{className:`rounded-lg border p-2.5`,children:[(0,Z.jsx)(`p`,{className:`text-xs whitespace-pre-wrap break-words`,children:e.text}),(0,Z.jsx)(`p`,{className:`mt-1 text-[10px] text-muted-foreground`,children:new Date(e.timestamp).toLocaleString()})]},e.id))})]})]})}var Q2=l();Do();var $2=`#8b5cf6`,e4=`#94a3b8`,t4={color:$2,weight:2,fillColor:$2,fillOpacity:.12},n4={color:$2,weight:2,dashArray:`5,5`,fillColor:$2,fillOpacity:.06},r4=e=>Math.round(e*1e6)/1e6;function i4(e){let t=e<10?32:e<100?38:44,n=`<div style="display:flex;align-items:center;justify-content:center;width:${t}px;height:${t}px;border-radius:9999px;background:${$2};color:#fff;border:2px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.4);font:600 12px system-ui,sans-serif;cursor:pointer">${e}</div>`;return hp.default.divIcon({html:n,className:`canvas-map-cluster`,iconSize:[t,t],iconAnchor:[t/2,t/2]})}var a4=e=>e.replace(/[&<>"']/g,e=>({"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`})[e]),o4=new Map;function s4(e){let t=o4.get(e);return t??(t=(0,Q2.renderToStaticMarkup)((0,X.createElement)(h2(e),{width:13,height:13,strokeWidth:2.5})),o4.set(e,t)),t}var c4=new Map;function l4(e,t){let n=`${e}|${+!!t}`,r=c4.get(n);if(!r){let i=`<div style="display:flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:9999px;background:${t?$2:e4};color:#fff;border:2px solid #fff;box-shadow:0 1px 3px rgba(0,0,0,.4);cursor:pointer">${s4(e)}</div>`;r=hp.default.divIcon({html:i,className:`canvas-map-pin`,iconSize:[26,26],iconAnchor:[13,13]}),c4.set(n,r)}return r}function u4(){let{state:e,setGeoSelection:t,setGeoBBox:n}=hs(),{mapDocuments:r,geoSelection:i,mapWorkspaceId:a}=e,o=e.filters.geo.bbox,{open:s}=gg(),c=(0,X.useRef)(null),l=(0,X.useRef)(null),u=(0,X.useRef)(null),d=(0,X.useRef)(null),f=(0,X.useRef)(null),p=(0,X.useRef)([]),m=(0,X.useRef)(!1),[h,g]=(0,X.useState)(`idle`),[_,v]=(0,X.useState)(0),y=(0,X.useRef)(h),b=(0,X.useMemo)(()=>r.reduce((e,t)=>e+ +!!Ig(t),0),[r]),x=(0,X.useMemo)(()=>i?r.reduce((e,t)=>{let n=Ig(t);return e+(n&&Rg(n.lat,n.lon,i)?1:0)},0):0,[r,i]),S=(0,X.useCallback)(()=>{let e=f.current;if(!e)return;e.clearLayers();let t=p.current;t.length!==0&&(t.length>=2&&hp.default.polyline(t,n4).addTo(e),t.forEach(t=>hp.default.circleMarker(t,{radius:4,color:$2,weight:2,fillColor:`#fff`,fillOpacity:1}).addTo(e)))},[]),C=(0,X.useCallback)(()=>{p.current=[],v(0),f.current?.clearLayers()},[]),w=(0,X.useCallback)(()=>{let e=p.current;e.length>=3&&t({kind:`polygon`,points:e.map(e=>({lat:r4(e.lat),lon:r4(e.lng)}))}),C(),g(`idle`)},[t,C]),T=(0,X.useCallback)(()=>{C(),g(`idle`),t(null),n(null)},[C,t,n]);(0,X.useEffect)(()=>{let e=c.current;if(!e||l.current)return;let t=hp.default.map(e,{center:[20,0],zoom:2,worldCopyJump:!0});hp.default.tileLayer(`https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`,{attribution:`© OpenStreetMap contributors`,maxZoom:19}).addTo(t),u.current=hp.default.markerClusterGroup({showCoverageOnHover:!1,maxClusterRadius:44,spiderfyOnMaxZoom:!0,chunkedLoading:!0,iconCreateFunction:e=>i4(e.getChildCount())}).addTo(t),f.current=hp.default.layerGroup().addTo(t),l.current=t;let r=t.getContainer(),i=null,a=null,o=()=>{a&&=(a.remove(),null)},s=e=>{if(y.current===`rect`){e.preventDefault(),i=t.mouseEventToLatLng(e),o();try{r.setPointerCapture(e.pointerId)}catch{}}},m=e=>{if(y.current!==`rect`||!i)return;e.preventDefault();let n=hp.default.latLngBounds(i,t.mouseEventToLatLng(e));a?a.setBounds(n):a=hp.default.rectangle(n,n4).addTo(t)},h=e=>{if(y.current!==`rect`||!i)return;let a=hp.default.latLngBounds(i,t.mouseEventToLatLng(e));i=null,o();try{r.releasePointerCapture(e.pointerId)}catch{}let s=a.getSouthWest(),c=a.getNorthEast();s.lat!==c.lat&&s.lng!==c.lng&&n({minLat:r4(s.lat),minLon:r4(s.lng),maxLat:r4(c.lat),maxLon:r4(c.lng)}),g(`idle`)};r.addEventListener(`pointerdown`,s),r.addEventListener(`pointermove`,m),r.addEventListener(`pointerup`,h),r.addEventListener(`pointercancel`,h);let _=e=>{y.current===`polygon`&&(p.current=[...p.current,e.latlng],v(p.current.length),S())};t.on(`click`,_);let b=new ResizeObserver(()=>t.invalidateSize());b.observe(e);let x=window.setTimeout(()=>t.invalidateSize(),120);return()=>{r.removeEventListener(`pointerdown`,s),r.removeEventListener(`pointermove`,m),r.removeEventListener(`pointerup`,h),r.removeEventListener(`pointercancel`,h),t.off(`click`,_),b.disconnect(),window.clearTimeout(x),t.remove(),l.current=null,u.current=null,f.current=null,d.current=null}},[t,n,S]),(0,X.useEffect)(()=>{y.current=h;let e=l.current;if(!e)return;let t=e.getContainer();h!==`polygon`&&p.current.length&&C(),h===`rect`?(e.dragging.disable(),e.doubleClickZoom.disable(),t.style.cursor=`crosshair`,t.style.touchAction=`none`):h===`polygon`?(e.dragging.enable(),e.doubleClickZoom.disable(),t.style.cursor=`crosshair`,t.style.touchAction=``):(e.dragging.enable(),e.doubleClickZoom.enable(),t.style.cursor=``,t.style.touchAction=``)},[h,C]),(0,X.useEffect)(()=>{let e=l.current,t=c.current;if(!e||!t)return;let n=new ResizeObserver(()=>e.invalidateSize());return n.observe(t),()=>n.disconnect()},[]),(0,X.useEffect)(()=>{let e=l.current,t=u.current;if(!e||!t)return;t.clearLayers();let n=[],o=[];for(let e of r){let t=Ig(e);if(!t)continue;n.push([t.lat,t.lon]);let r=!i||Rg(t.lat,t.lon,i),c=hp.default.marker([t.lat,t.lon],{icon:l4(e.schema,r),opacity:i&&!r?.55:1,zIndexOffset:r?1e3:0});c.bindTooltip(a4(mo(e).title),{direction:`top`,offset:[0,-14]}),c.on(`click`,()=>{y.current===`idle`&&s(e,a??``)}),o.push(c)}t.addLayers(o),!m.current&&n.length&&!i&&(m.current=!0,e.fitBounds(hp.default.latLngBounds(n),{padding:[30,30],maxZoom:14,animate:!1}))},[r,i,s,a]),(0,X.useEffect)(()=>{let e=l.current;if(!e||(d.current&&=(d.current.remove(),null),!o&&!i))return;let t=hp.default.layerGroup();o&&hp.default.rectangle(hp.default.latLngBounds([o.minLat,o.minLon],[o.maxLat,o.maxLon]),t4).addTo(t),i?.kind===`polygon`&&hp.default.polygon(i.points.map(e=>[e.lat,e.lon]),t4).addTo(t),t.addTo(e),d.current=t},[o,i]);let E=h===`rect`?`Drag a box on the map…`:h===`polygon`?`Tap to add points${_?` · ${_}`:``}`:o||i?`Area selected`:`Pan & pick an area`,D=`flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-xs font-medium transition-colors`;return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 border-b border-border px-3 py-2 shrink-0`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>g(h===`rect`?`idle`:`rect`),className:K(D,h===`rect`?`border-primary bg-primary/10 text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Drag a rectangle to select an area`,children:[(0,Z.jsx)($t,{className:`h-3.5 w-3.5`}),`Box`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>g(h===`polygon`?`idle`:`polygon`),className:K(D,h===`polygon`?`border-primary bg-primary/10 text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Tap points to enclose an area`,children:[(0,Z.jsx)(Se,{className:`h-3.5 w-3.5`}),`Polygon`]}),h===`polygon`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:w,disabled:_<3,className:K(D,`border-primary bg-primary text-primary-foreground hover:bg-primary disabled:opacity-40 disabled:hover:bg-primary`),title:`Close the polygon and filter`,children:[(0,Z.jsx)(ur,{className:`h-3.5 w-3.5`}),`Finish`]}),_>0&&(0,Z.jsx)(`button`,{type:`button`,onClick:C,className:K(D,`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Discard the points placed so far`,children:(0,Z.jsx)(je,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:T,disabled:!o&&!i&&h===`idle`,className:K(D,`border-border text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-40 disabled:hover:bg-transparent`),title:`Clear the area selection`,children:[(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`}),`Clear`]}),(0,Z.jsx)(`span`,{className:`ml-auto text-[11px] text-muted-foreground`,children:E})]}),(0,Z.jsxs)(`div`,{className:`relative isolate flex-1 min-h-0`,children:[(0,Z.jsx)(`div`,{ref:c,className:`absolute inset-0`}),b===0&&(0,Z.jsx)(`div`,{className:`pointer-events-none absolute inset-0 z-[2] flex items-center justify-center`,children:(0,Z.jsxs)(`div`,{className:`rounded-lg border bg-card/95 px-4 py-3 text-center shadow-elevation-2`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium text-foreground`,children:`No located documents`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None of the current results carry location metadata.`})]})})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t border-border px-3 py-2 shrink-0 text-[11px] text-muted-foreground`,children:[(0,Z.jsx)(Zt,{className:`h-3 w-3`}),b,` of `,r.length,` located`,i&&(0,Z.jsxs)(`span`,{className:`text-foreground font-medium`,children:[`· `,x,` in area`]})]})]})}var d4=[{label:`25 m`,m:25},{label:`100 m`,m:100},{label:`500 m`,m:500},{label:`2 km`,m:2e3},{label:`10 km`,m:1e4}],f4=`h-7 rounded-md border border-input bg-transparent px-1.5 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,p4=`h-7 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,m4=e=>Math.round(e*1e4)/1e4;function h4(){let{state:e,setLensGps:t}=hs(),n=e.filters.lens,r=e.activeWorkspaceName,[i,a]=(0,X.useState)(n.gps!==null),[o,s]=(0,X.useState)(n.gps?.radiusM??100),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(0),[f,p]=(0,X.useState)(`prompt`),m=(0,X.useRef)(null),h=(0,X.useRef)(o);(0,X.useEffect)(()=>{h.current=o},[o]);let g=`geolocation`in navigator&&window.isSecureContext;(0,X.useEffect)(()=>{if(!navigator.permissions?.query)return;let e=null;return navigator.permissions.query({name:`geolocation`}).then(t=>{e=t,p(t.state===`granted`?`granted`:t.state===`denied`?`denied`:`prompt`),t.onchange=()=>p(t.state===`granted`?`granted`:t.state===`denied`?`denied`:`prompt`)}).catch(()=>{}),()=>{e&&(e.onchange=null)}},[]),(0,X.useEffect)(()=>{if(!i||!g)return;let e=navigator.geolocation.watchPosition(e=>{let n=m4(e.coords.latitude),r=m4(e.coords.longitude);t({lat:n,lon:r,radiusM:h.current})},e=>l(e.code===e.PERMISSION_DENIED?`Location permission denied.`:e.message),{enableHighAccuracy:!0,maximumAge:15e3,timeout:2e4});return m.current=e,()=>{navigator.geolocation.clearWatch(e),m.current=null}},[i,g,u,t]);let _=e=>{a(e),l(null),e||t(null)},v=()=>{l(null),a(!0),d(e=>e+1)},y=e=>{s(e),n.gps&&t({...n.gps,radiusM:e})},b=oy(),{rateMs:x,setRateMs:S,maxDistance:C,setMaxDistance:T,error:E}=b,D=b.running&&b.consumer===`filter`,O=b.running&&b.consumer!==`filter`;sy(D);let k=e=>{r&&b.start(e,`filter`,{workspaceRef:r})},A=D;return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-3 text-sm`,children:[(0,Z.jsxs)(`section`,{className:`space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:i,disabled:!g,onChange:e=>_(e.target.checked)}),(0,Z.jsx)(cn,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`span`,{children:`Refine with GPS`})]}),(0,Z.jsx)(`select`,{className:f4,value:o,onChange:e=>y(Number(e.target.value)),disabled:!i,children:d4.map(e=>(0,Z.jsx)(`option`,{value:e.m,children:e.label},e.m))})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:g?f===`denied`?(0,Z.jsx)(`span`,{className:`text-destructive`,children:`Location is blocked for this site. Allow it in your browser/app settings, then retry.`}):c?(0,Z.jsxs)(`span`,{className:`text-destructive`,children:[c,` `,(0,Z.jsx)(`button`,{type:`button`,onClick:v,className:`underline hover:text-foreground`,children:`Request again`})]}):n.gps?`Showing documents within ${o>=1e3?`${o/1e3} km`:`${o} m`} of ${n.gps.lat}, ${n.gps.lon}.`:i?`Waiting for a position fix…`:`Resurface documents geotagged near your current position.`:`Needs a secure context (https or localhost) with location access.`})]}),(0,Z.jsxs)(`section`,{className:`space-y-2 border-t border-border pt-3`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[A?(0,Z.jsxs)(`button`,{type:`button`,onClick:b.stop,className:`flex h-7 items-center gap-1 rounded-md bg-destructive px-2.5 text-xs font-medium text-destructive-foreground hover:bg-destructive/90`,children:[(0,Z.jsx)(we,{className:`h-3.5 w-3.5`}),` Stop `,b.source===`camera`?`camera`:`recording`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>k(`camera`),disabled:!r||O,className:`flex h-7 items-center gap-1 rounded-md bg-foreground px-2.5 text-xs font-medium text-background hover:bg-foreground/90 disabled:opacity-50`,children:[(0,Z.jsx)(w,{className:`h-3.5 w-3.5`}),` Camera`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>k(`screen`),disabled:!r||O,className:`flex h-7 items-center gap-1 rounded-md bg-foreground px-2.5 text-xs font-medium text-background hover:bg-foreground/90 disabled:opacity-50`,children:[(0,Z.jsx)(kn,{className:`h-3.5 w-3.5`}),` Desktop`]})]}),(0,Z.jsx)(`select`,{className:f4,value:x,onChange:e=>S(Number(e.target.value)),disabled:!r,title:`Frame rate. High rates (10–30 fps) are experimental; the loop never overlaps requests, so the effective rate is capped by search latency.`,children:uy.map(e=>(0,Z.jsx)(`option`,{value:e.ms,children:e.label},e.ms))}),(0,Z.jsx)(`input`,{className:K(p4,`w-24`),placeholder:`max dist`,inputMode:`decimal`,value:C,onChange:e=>T(e.target.value),title:`Cosine-distance floor (0 = identical). Empty = top-K (loose but tunable).`})]}),(0,Z.jsx)(`div`,{className:K(`relative overflow-hidden rounded-lg border border-border bg-black/80`,A?`aspect-video`:`hidden`),children:(0,Z.jsx)(my,{className:`h-full w-full object-cover`})}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:E?(0,Z.jsx)(`span`,{className:`text-destructive`,children:E}):A?`Live: view narrowed to ${b.lastCount??`…`} match${b.lastCount===1?``:`es`}. Frames are ephemeral, never stored. Closing the toolbox keeps it running.`:O?`The Lens applet is using the camera. Stop it there first.`:r?`Point a camera (or share a screen). The view narrows to what the feed matches.`:`Open a workspace to refine with a live feed.`})]})]})}var g4={"crud:created":`var(--data-5)`,"crud:updated":`var(--data-8)`,"crud:deleted":`var(--data-3)`,content:`var(--data-10)`,tasks:`var(--data-1)`};function _4(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return(t%360+360)%360}function v4(e){return g4[e]??`oklch(var(--data-l) var(--data-c) ${_4(e)})`}var y4=[{label:`Day`,cells:[`yesterday`,`today`,`tomorrow`]},{label:`Week`,cells:[`lastWeek`,`thisWeek`,`nextWeek`]},{label:`Month`,cells:[`lastMonth`,`thisMonth`,`nextMonth`]},{label:`Year`,cells:[`lastYear`,`thisYear`,`nextYear`]}],b4=[{label:`Decade`,cells:[`lastDecade`,`thisDecade`,`nextDecade`]},{label:`Century`,cells:[`lastCentury`,`thisCentury`,`nextCentury`]},{label:`Millennium`,cells:[`lastMillennium`,`thisMillennium`,`nextMillennium`]}],x4=[`Yesterday`,`Today`,`Tomorrow`],S4=[{label:`Millennium`,unit:`millennium`},{label:`Century`,unit:`century`},{label:`Decade`,unit:`decade`},{label:`Year`,unit:`year`},{label:`Month`,unit:`month`},{label:`Week`,unit:`week`}],C4=10,w4=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function T4(e,t){let n=new Date;switch(e){case`millennium`:{let e=Math.floor(n.getFullYear()/1e3)*1e3;return new Date(e-t*1e3,0,1)}case`century`:{let e=Math.floor(n.getFullYear()/100)*100;return new Date(e-t*100,0,1)}case`decade`:{let e=Math.floor(n.getFullYear()/10)*10;return new Date(e-t*10,0,1)}case`year`:return new Date(n.getFullYear()-t,0,1);case`month`:return new Date(n.getFullYear(),n.getMonth()-t,1);case`week`:{let e=(n.getDay()+6)%7,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()-e);return r.setDate(r.getDate()-t*7),r}}}function E4(e,t){let n=new Date(t);switch(e){case`millennium`:n.setFullYear(n.getFullYear()+1e3);break;case`century`:n.setFullYear(n.getFullYear()+100);break;case`decade`:n.setFullYear(n.getFullYear()+10);break;case`year`:n.setFullYear(n.getFullYear()+1);break;case`month`:n.setMonth(n.getMonth()+1);break;case`week`:n.setDate(n.getDate()+7)}return n}function D4(e,t,n){if(n===0)return`Now`;switch(e){case`millennium`:case`century`:case`decade`:{let e=t.getFullYear();return e<=0?`${1-e} BCE`:`${e}`}case`year`:return`${t.getFullYear()}`;case`month`:return`${w4[t.getMonth()]} ${t.getFullYear()}`;case`week`:{let e=new Date(t);return e.setDate(e.getDate()+6),`${t.getDate()} ${w4[t.getMonth()]} – ${e.getDate()} ${w4[e.getMonth()]}`}}}function O4(e,t){return Array.from({length:t},(t,n)=>{let r=T4(e,n),i=E4(e,r);return{offset:n,label:D4(e,r,n),start:r,end:i,isNow:n===0}})}var k4={yesterday:5,today:5,tomorrow:5,lastWeek:5,thisWeek:5,nextWeek:5,lastMonth:4,thisMonth:4,nextMonth:4,lastYear:3,thisYear:3,nextYear:3,lastDecade:2,thisDecade:2,nextDecade:2,lastCentury:1,thisCentury:1,nextCentury:1,lastMillennium:0,thisMillennium:0,nextMillennium:0};function A4(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function j4(e,t){let n=I4(e);return n?(n.setDate(n.getDate()+t),A4(n)):e}function M4(e){let t=[...e].sort((e,t)=>e.start.localeCompare(t.start)),n=[];for(let e of t){let t=n[n.length-1];t&&e.start<=j4(t.end,1)?e.end>t.end&&(t.end=e.end):n.push({...e})}return n}function N4(e,t){let n=e.find(e=>t>=e.start&&t<=e.end);if(!n)return M4([...e,{start:t,end:t}]);let r=e.filter(e=>e!==n);return n.start<=j4(t,-1)&&r.push({start:n.start,end:j4(t,-1)}),j4(t,1)<=n.end&&r.push({start:j4(t,1),end:n.end}),r.sort((e,t)=>e.start.localeCompare(t.start))}function P4(e,t){if(e===`week`||e===`month`){let e=new Date(t.end);return e.setDate(e.getDate()-1),{start:A4(t.start),end:A4(e)}}return{start:String(t.start.getFullYear()),end:String(t.end.getFullYear()-1)}}function F4({quickFilterKey:e,activeRangeCount:t,onSelectRanges:n,histogramNames:r}){let{state:i}=hs(),{activeWorkspaceName:a,activeTreeName:o,activeContextPath:s,filters:c}=i,[l,u]=(0,X.useState)(3),[d,f]=(0,X.useState)(C4),[p,m]=(0,X.useState)(new Set),[h,g]=(0,X.useState)([]),[_,v]=(0,X.useState)(e);e!==_&&(v(e),e&&k4[e]!==void 0&&u(k4[e]),m(new Set));let[y,b]=(0,X.useState)(t);t!==y&&(b(t),t===0&&m(new Set));let x=S4[l],S=O4(x.unit,d),C=JSON.stringify(c.features)+JSON.stringify(c.geo),w=r.join(`,`);(0,X.useEffect)(()=>{if(!a||r.length===0)return;let e=!1,t=setTimeout(()=>{Ga(a,{names:r,buckets:O4(x.unit,d).map(e=>P4(x.unit,e)),context:s??`/`,...o?{treeNameOrTreeId:o}:{},allOf:c.features.allOf,anyOf:c.features.anyOf,noneOf:c.features.noneOf,filters:xx(c.geo),applyCanvasSpec:!1}).then(t=>{e||g(t)}).catch(()=>{e||g([])})},250);return()=>{e=!0,clearTimeout(t)}},[a,o,s,x.unit,d,w,C]);let T=a&&r.length>0?h:[],E=Math.max(1,...T.map(e=>e.total)),D=e=>{u(t=>Math.max(0,Math.min(5,t+e))),f(C4),m(new Set)},O=(0,X.useCallback)((e,t)=>{m(r=>{let i;if(t&&r.size>0){let t=Math.min(e,...r),n=Math.max(e,...r);i=new Set(r);for(let e=t;e<=n;e++)i.add(e)}else i=new Set(r),i.has(e)?i.delete(e):i.add(e);let a=[...i].sort((e,t)=>e-t),o=[];for(let e of a){let t=o[o.length-1];t&&e===t[1]+1?t[1]=e:o.push([e,e])}return n(o.map(([e,t])=>{let n=S.find(e=>e.offset===t).start,r=new Date(S.find(t=>t.offset===e).end);return r.setDate(r.getDate()-1),{start:A4(n),end:A4(r)}})),i})},[S,n]);return(0,Z.jsxs)(`div`,{className:`w-48 shrink-0 flex flex-col border-r border-border bg-muted/20`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-1 px-2 py-1.5 border-b border-border shrink-0`,children:[(0,Z.jsx)(`span`,{className:`text-[11px] font-semibold text-foreground/80 select-none`,children:x.label}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>D(1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Zoom in (finer periods)`,children:(0,Z.jsx)(se,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>D(-1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Zoom out (coarser periods)`,children:(0,Z.jsx)(F,{className:`w-3.5 h-3.5`})})]})]}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto p-1.5 space-y-1 touch-target`,children:[S.map(e=>{let t=p.has(e.offset),n=T[e.offset],r=n?.total??0,i=r>0?Math.log1p(r)/Math.log1p(E):0,a=n&&r>0?`: ${r} doc${r===1?``:`s`} (${Object.entries(n.counts).map(([e,t])=>`${e}: ${t}`).join(`, `)})`:``;return(0,Z.jsxs)(`button`,{type:`button`,onClick:t=>O(e.offset,t.shiftKey),title:`${e.isNow?`Now`:e.label}${a}. Click to tag, shift-click to fill range`,className:K(`w-full flex items-center gap-2 rounded-2xl px-3 py-1.5 text-xs font-medium transition-colors select-none text-left`,t?`bg-primary text-primary-foreground`:e.isNow?`bg-primary/10 text-primary hover:bg-primary/20`:`bg-card text-foreground hover:bg-muted shadow-elevation-1`),children:[e.isNow&&(0,Z.jsx)(Qn,{className:`w-3 h-3 shrink-0`}),(0,Z.jsxs)(`span`,{className:`flex-1 min-w-0 flex flex-col`,children:[(0,Z.jsxs)(`span`,{className:`flex items-baseline justify-between gap-1`,children:[(0,Z.jsx)(`span`,{className:`truncate`,children:e.label}),r>0&&(0,Z.jsx)(`span`,{className:K(`text-[9px] tabular-nums shrink-0`,t?`text-primary-foreground/80`:`text-muted-foreground/70`),children:r})]}),r>0&&(0,Z.jsx)(`span`,{className:`mt-1 flex h-[3px] overflow-hidden rounded-full`,style:{width:`${Math.max(8,i*100)}%`},children:Object.entries(n.counts).map(([e,t])=>(0,Z.jsx)(`span`,{style:{width:`${t/r*100}%`,backgroundColor:v4(e)}},e))})]})]},e.offset)}),d<200&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>f(e=>e+C4),className:`w-full text-[11px] text-muted-foreground/60 hover:text-muted-foreground py-1.5 transition-colors text-center`,children:`Show older…`})]})]})}function I4(e){let t=/^(-?\d{1,6})-(\d{2})-(\d{2})$/.exec(e);return t?new Date(Number(t[1]),Number(t[2])-1,Number(t[3])):null}function L4({ranges:e,onCommitRange:t,onToggleDay:n}){let r=new Date,[i,a]=(0,X.useState)(()=>{let t=e[0]?.start&&I4(e[0].start)||r;return{y:t.getFullYear(),m:t.getMonth()}}),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(null),u=e=>a(t=>{let n=new Date(t.y,t.m+e,1);return{y:n.getFullYear(),m:n.getMonth()}}),d=(e,r)=>{if(r){n(e),s(null),l(null);return}if(!o){s(e);return}let[i,a]=o<=e?[o,e]:[e,o];t(i,a),s(null),l(null)},f=new Date(i.y,i.m,1),p=new Date(f);p.setDate(p.getDate()-(f.getDay()+6)%7);let m=Array.from({length:42},(e,t)=>{let n=new Date(p);return n.setDate(n.getDate()+t),n}),[h,g]=o?c&&c!==o?o<=c?[o,c]:[c,o]:[o,o]:[null,null],_=t=>e.some(e=>t>=e.start&&t<=e.end),v=t=>e.some(e=>t===e.start||t===e.end),y=A4(r);return(0,Z.jsxs)(`div`,{className:`select-none`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>u(-12),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Previous year`,children:(0,Z.jsx)(I,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>u(-1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Previous month`,children:(0,Z.jsx)(ve,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>a({y:r.getFullYear(),m:r.getMonth()}),className:`text-xs font-semibold text-foreground hover:text-primary transition-colors`,title:`Jump to current month`,children:[w4[i.m],` `,i.y]}),(0,Z.jsxs)(`div`,{className:`flex items-center`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>u(1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Next month`,children:(0,Z.jsx)(B,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>u(12),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Next year`,children:(0,Z.jsx)(Ee,{className:`w-3.5 h-3.5`})})]})]}),(0,Z.jsx)(`div`,{className:`grid grid-cols-7 mb-0.5`,children:[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`].map(e=>(0,Z.jsx)(`span`,{className:`text-center text-[9px] font-semibold uppercase text-muted-foreground/60 py-0.5`,children:e},e))}),(0,Z.jsx)(`div`,{className:`grid grid-cols-7 gap-y-0.5`,children:m.map(e=>{let t=A4(e),n=e.getMonth()===i.m,r=h!==null&&g!==null&&t>=h&&t<=g,a=t===h||t===g,s=!o&&_(t),c=a||s&&v(t);return(0,Z.jsx)(`button`,{type:`button`,onClick:e=>d(t,e.ctrlKey||e.metaKey),onMouseEnter:()=>o&&l(t),className:K(`h-6 text-[11px] tabular-nums transition-colors`,c?`bg-primary text-primary-foreground rounded-md`:r||s?`bg-primary/15 text-foreground`:n?`text-foreground hover:bg-muted rounded-md`:`text-muted-foreground/40 hover:bg-muted rounded-md`,t===y&&!c&&`font-bold text-primary`),children:e.getDate()},t)})}),(0,Z.jsx)(`p`,{className:`mt-1.5 text-[10px] text-muted-foreground/70`,children:o?`From ${o}: pick the end date`:`Click start + end. Ctrl+click adds/removes single days.`})]})}function R4({label:e,checked:t,onChange:n,color:r}){return(0,Z.jsxs)(`div`,{role:`switch`,"aria-checked":t,tabIndex:0,onClick:()=>n(!t),onKeyDown:e=>(e.key===` `||e.key===`Enter`)&&n(!t),className:`flex items-center justify-between gap-3 cursor-pointer select-none outline-none focus-visible:ring-2 focus-visible:ring-ring rounded`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 min-w-0`,children:[(0,Z.jsx)(`span`,{className:`w-2 h-2 rounded-full shrink-0`,style:{backgroundColor:r}}),(0,Z.jsx)(`span`,{className:`text-sm text-foreground truncate`,children:e})]}),(0,Z.jsx)(`div`,{className:K(`relative w-10 h-5 rounded-full transition-colors shrink-0`,!t&&`bg-accent dark:bg-muted-foreground`),style:t?{backgroundColor:r}:void 0,children:(0,Z.jsx)(`div`,{className:K(`absolute top-[2px] w-4 h-4 rounded-full bg-background shadow-elevation-1 transition-transform`,t?`translate-x-[22px]`:`translate-x-[2px]`)})})]})}function z4(){let{state:e,setTimelineFilter:t,createTimeline:n,deleteTimeline:r,refreshTimelines:i}=hs(),{timeline:a}=e.filters,{availableTimelines:o,timelineScales:s,timelinesLoading:c}=e,[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(`quick`),[_,v]=(0,X.useState)(!1),{showToast:y}=oo(),b=new Set(a.selectedTimelines??[]),x=(0,X.useMemo)(()=>{let e=[];return a.indexCreated&&e.push(`crud:created`),a.indexUpdated&&e.push(`crud:updated`),a.indexDeleted&&e.push(`crud:deleted`),a.contentEvents&&e.push(`content`),e.push(...a.selectedTimelines??[]),e.length>0?e:[`crud:created`]},[a.indexCreated,a.indexUpdated,a.indexDeleted,a.contentEvents,a.selectedTimelines]),S=e=>{let n=new Set(b);n.has(e)?n.delete(e):n.add(e),t({selectedTimelines:[...n]})},C=async()=>{let e=l.trim();if(e){f(!0);try{await n(e),u(``),y({title:`Timeline created`,description:e})}catch(e){y({title:`Failed to create timeline`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{f(!1)}}},w=async e=>{if(window.confirm(`Delete timeline "${e}"?\n\nThis removes all interval data for this timeline.`)){m(e);try{await r(e),y({title:`Timeline deleted`,description:e})}catch(e){y({title:`Failed to delete timeline`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{m(null)}}},T=o.filter(e=>!e.startsWith(`crud:`)&&e!==`content`),E=Cx(a),D=E.length>0,O=(0,X.useCallback)(e=>{t({customRanges:e,customRange:null,...e.length>0?{quickFilter:null}:{}})},[t]),k=e=>{t({quickFilter:a.quickFilter===e?null:e,customRanges:[],customRange:null})},A=e=>{t({customRanges:E.filter((t,n)=>n!==e),customRange:null})},j=(e,t)=>(0,Z.jsxs)(`div`,{className:`grid grid-cols-[3.5rem_1fr_1fr_1fr] gap-1 items-center`,children:[(0,Z.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:e.label}),e.cells.map((e,n)=>{let r=a.quickFilter===e&&!D;return(0,Z.jsx)(`button`,{type:`button`,onClick:()=>k(e),className:K(`text-xs px-1.5 py-1 rounded-md transition-colors truncate`,r?`bg-primary text-primary-foreground font-medium`:`bg-muted/50 text-foreground hover:bg-muted`),title:e,children:t?x4[n]:[`Last`,`This`,`Next`][n]},e)})]},e.label);return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0`,children:[(0,Z.jsx)(F4,{quickFilterKey:a.quickFilter,activeRangeCount:E.length,onSelectRanges:O,histogramNames:x}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4 space-y-5`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:h===`quick`?`Quick filter`:`Date range`}),(0,Z.jsxs)(`div`,{className:`flex rounded-md overflow-hidden border border-border divide-x divide-border`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>g(`quick`),className:K(`px-2 py-0.5 transition-colors`,h===`quick`?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Quick filters`,children:(0,Z.jsx)(ge,{className:`w-3 h-3`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>g(`calendar`),className:K(`px-2 py-0.5 transition-colors`,h===`calendar`?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Calendar range picker`,children:(0,Z.jsx)(oe,{className:`w-3 h-3`})})]})]}),h===`quick`?(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`grid grid-cols-[3.5rem_1fr_1fr_1fr] gap-1`,children:[(0,Z.jsx)(`span`,{}),[`Last`,`This`,`Next`].map(e=>(0,Z.jsx)(`span`,{className:`text-center text-[9px] font-semibold uppercase tracking-wide text-muted-foreground/60`,children:e},e))]}),y4.map((e,t)=>j(e,t===0)),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>v(e=>!e),className:`flex items-center gap-1 text-[11px] text-muted-foreground/70 hover:text-muted-foreground pt-1 transition-colors`,children:[(0,Z.jsx)(Ne,{className:K(`w-3 h-3 transition-transform`,!_&&`-rotate-90`)}),`Deep time`]}),_&&b4.map(e=>j(e,!1))]}):(0,Z.jsx)(L4,{ranges:E,onCommitRange:(e,n)=>t({customRanges:[{start:e,end:n}],customRange:null,quickFilter:null}),onToggleDay:e=>t({customRanges:N4(E,e),customRange:null,quickFilter:null})}),D&&(0,Z.jsx)(`div`,{className:`mt-2 space-y-1`,children:E.map((e,t)=>(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded-md bg-primary/10 border border-primary/30 px-2.5 py-1.5`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-foreground truncate`,children:e.start===e.end?e.start:`${e.start} → ${e.end}`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>A(t),className:`text-muted-foreground hover:text-foreground shrink-0`,title:`Remove range`,children:(0,Z.jsx)(je,{className:`w-3.5 h-3.5`})})]},`${e.start}..${e.end}`))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:`Apply to`}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(R4,{label:`crud:created`,checked:a.indexCreated,onChange:e=>t({indexCreated:e}),color:v4(`crud:created`)}),(0,Z.jsx)(R4,{label:`crud:updated`,checked:a.indexUpdated,onChange:e=>t({indexUpdated:e}),color:v4(`crud:updated`)}),(0,Z.jsx)(R4,{label:`crud:deleted`,checked:a.indexDeleted,onChange:e=>t({indexDeleted:e}),color:v4(`crud:deleted`)}),(0,Z.jsx)(R4,{label:`content`,checked:a.contentEvents,onChange:e=>t({contentEvents:e}),color:v4(`content`)})]}),(0,Z.jsx)(`p`,{className:`text-[10px] text-muted-foreground/70 mt-1`,children:`content = content-derived timestamps (EXIF, logs, extracted periods)`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:`Domain timelines`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>i(),className:`text-muted-foreground/60 hover:text-muted-foreground transition-colors`,title:`Refresh timelines`,children:(0,Z.jsx)(M,{className:`w-3 h-3`})})]}),c?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 py-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Wn,{className:`w-3 h-3 animate-spin`}),`Loading…`]}):T.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground py-1`,children:`No domain timelines yet`}):(0,Z.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:T.map(e=>{let t=b.has(e),n=v4(e);return(0,Z.jsxs)(`div`,{className:K(`flex items-center gap-2.5 group rounded-md px-2 py-1.5 cursor-pointer transition-colors`,t?`bg-muted/60`:`hover:bg-muted/30`),onClick:()=>S(e),children:[(0,Z.jsx)(`div`,{className:K(`shrink-0 w-4 h-4 rounded border-2 flex items-center justify-center transition-colors`,!t&&`border-muted-foreground/40 bg-transparent group-hover:border-muted-foreground/70`),style:t?{backgroundColor:n,borderColor:n}:void 0,children:t&&(0,Z.jsx)(`svg`,{className:K(`w-2.5 h-2.5`,Lf(n)),viewBox:`0 0 10 10`,fill:`none`,children:(0,Z.jsx)(`path`,{d:`M2 5l2.5 2.5L8 3`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,Z.jsx)(`span`,{className:`flex-1 text-sm text-foreground truncate select-none`,children:e}),(s[e]?.length??0)>0&&(0,Z.jsx)(`span`,{className:`shrink-0 text-[10px] px-1 py-0.5 rounded bg-muted text-muted-foreground select-none`,title:`Observed granularity for "${e}" — each entry is indexed at its own precision (a bare year at year cells, a full date at day cells)`,children:(s[e]??[]).join(`·`)}),(0,Z.jsx)(`button`,{type:`button`,disabled:p===e,onClick:t=>{t.stopPropagation(),w(e)},className:`shrink-0 p-1 rounded text-muted-foreground/40 hover:text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50 reveal-on-hover`,title:`Delete timeline "${e}"`,children:p===e?(0,Z.jsx)(Wn,{className:`w-3 h-3 animate-spin`}):(0,Z.jsx)(lt,{className:`w-3 h-3`})})]},e)})}),(0,Z.jsxs)(`div`,{className:`mt-3 flex gap-1.5`,children:[(0,Z.jsx)(`input`,{type:`text`,value:l,onChange:e=>u(e.target.value),onKeyDown:e=>e.key===`Enter`&&C(),placeholder:`New timeline (e.g. wikipedia, trips)…`,title:`A timeline is a named time axis. Entries index at their own precision — a bare year at year granularity, a full date at day granularity — nothing to configure.`,className:`flex-1 px-2 py-1 text-xs rounded-md bg-muted border border-transparent focus:border-ring focus:outline-none`}),(0,Z.jsx)(`button`,{type:`button`,onClick:C,disabled:d||!l.trim(),className:`shrink-0 p-1.5 rounded-md bg-muted hover:bg-muted/80 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50 touch-target`,title:`Create timeline`,children:d?(0,Z.jsx)(Wn,{className:`w-3.5 h-3.5 animate-spin`}):(0,Z.jsx)(nn,{className:`w-3.5 h-3.5`})})]})]})]})]})}var B4={data:`Data`,"data/backend":`Backends`,"data/mime":`MIME types`,"data/dataset":`Datasets`,client:`Client`,tag:`Tags`,device:`Device`,custom:`Custom`,feature:`Feature`},V4=`data/dataset/default`;function H4(e){let t=new Map;for(let n of e){let e=n.startsWith(`data/backend/`)?`data/backend`:n.startsWith(`data/mime/`)?`data/mime`:n.startsWith(`data/dataset/`)?`data/dataset`:n.split(`/`)[0];t.has(e)||t.set(e,[]),t.get(e).push(n)}return t}var U4=[`off`,`anyOf`,`allOf`,`noneOf`];function W4(e){return U4[(U4.indexOf(e)+1)%U4.length]}var G4=[{m:`anyOf`,label:`any`,on:`bg-info text-info-foreground`},{m:`allOf`,label:`all`,on:`bg-success text-success-foreground`},{m:`noneOf`,label:`not`,on:`bg-destructive text-destructive-foreground`}];function K4({mode:e,onSet:t}){return(0,Z.jsx)(`div`,{className:`flex shrink-0 rounded-md overflow-hidden border border-border divide-x divide-border`,children:G4.map(n=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(e===n.m?`off`:n.m),className:K(`px-2 py-0.5 text-[11px] font-medium transition-colors`,e===n.m?n.on:`bg-transparent text-muted-foreground hover:bg-muted hover:text-foreground`),title:`${n.label}: ${n.m}`,children:n.label},n.m))})}function q4({keys:e,modeOf:t,onCycle:n}){return e.length?(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:`Document types`}),(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3`,children:e.map(e=>{let{label:r,icon:i}=m2(e),a=t(e),o=G4.find(e=>e.m===a);return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>n(e),title:`${e}: ${a===`off`?`tap to filter`:a}`,className:K(`relative flex flex-col items-center justify-center gap-1.5 rounded-lg border p-3 min-h-[4.5rem] transition-colors select-none`,a===`off`?`border-border bg-muted/40 text-foreground hover:bg-muted`:a===`anyOf`?`border-info bg-info/10 text-foreground`:a===`allOf`?`border-success bg-success/10 text-foreground`:`border-destructive bg-destructive/10 text-foreground`),children:[o&&(0,Z.jsx)(`span`,{className:K(`absolute right-1.5 top-1.5 rounded px-1 py-0.5 text-[9px] font-semibold leading-none`,o.on),children:o.label}),(0,Z.jsx)(i,{className:`h-5 w-5 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-xs font-medium leading-none`,children:r})]},e)})})]}):null}function J4(){let{state:e,setFeatureMode:t,clearFilters:n,hasActiveFilters:r,deleteBitmap:i,deleteDataset:a}=hs(),{availableBitmaps:o,bitmapsLoading:s,filters:c}=e,l=new Set(c.features.allOf),u=new Set(c.features.anyOf),d=new Set(c.features.noneOf),f=e=>l.has(e)?`allOf`:u.has(e)?`anyOf`:d.has(e)?`noneOf`:`off`,[p,m]=(0,X.useState)(``),[h,g]=(0,X.useState)(null),{showToast:_}=oo(),v=async e=>{if(e.startsWith(`data/dataset/`)&&e!==V4){let t=e.slice(13);if(!window.confirm(`Drop dataset "${t}"?\n\nALL documents stamped with this dataset will be PERMANENTLY DELETED. Documents in other datasets (or the default dataset) are unaffected. Re-ingesting recreates the dataset from scratch.`))return;g(e);try{let n=await a(e);_({title:`Dataset dropped`,description:`"${t}": ${n} document(s) deleted`})}catch(e){_({title:`Dataset drop failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{g(null)}return}if(!e.startsWith(`data/`)&&window.confirm(`Delete bitmap "${e}"?\n\nThis removes the bitmap from the database. Documents are unaffected, but any features/filters relying on this bitmap will lose their grouping.`)){g(e);try{await i(e),_({title:`Bitmap deleted`,description:e})}catch(e){_({title:`Delete failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{g(null)}}};if(s)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,Z.jsx)(Wn,{className:`w-4 h-4 animate-spin text-muted-foreground`})});let y=[...c.features.allOf,...c.features.anyOf,...c.features.noneOf],b=[...new Set([...o,...y])];if(!b.length)return(0,Z.jsx)(`div`,{className:`p-4 text-xs text-muted-foreground text-center py-10`,children:`No feature bitmaps found`});let x=p.trim().toLowerCase(),S=x?b.filter(e=>e.toLowerCase().includes(x)):b,C=S.filter(e=>e.startsWith(f2)).sort((e,t)=>{let n=Object.keys(p2),r=n.indexOf(e),i=n.indexOf(t);return(r===-1?n.length:r)-(i===-1?n.length:i)||e.localeCompare(t)}),w=H4(S.filter(e=>!e.startsWith(f2))),T=w.get(`data/dataset`);return T&&!T.includes(V4)&&(!x||V4.includes(x))&&T.unshift(V4),(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`px-4 py-2 border-b border-border shrink-0 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(Xn,{className:`absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none`}),(0,Z.jsx)(`input`,{type:`text`,value:p,onChange:e=>m(e.target.value),placeholder:`Search features…`,className:`w-full pl-7 pr-3 py-1.5 text-xs rounded-md bg-muted border border-transparent focus:border-ring focus:outline-none`})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:n,disabled:!r,className:`flex items-center gap-1.5 w-full justify-center px-2.5 py-1.5 text-xs rounded-md border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-40 disabled:hover:bg-transparent`,children:[(0,Z.jsx)(je,{className:`w-3 h-3`}),`Clear all filters`]})]}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto p-4 space-y-5`,children:[(0,Z.jsx)(q4,{keys:C,modeOf:f,onCycle:e=>t(e,W4(f(e)))}),w.size===0&&C.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground text-center py-6`,children:`No matches`}):Array.from(w.entries()).map(([e,n])=>(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:B4[e]??e}),(0,Z.jsx)(`div`,{className:`flex flex-col gap-1`,children:n.map((e,n)=>{let r=e.startsWith(`data/`),i=e===V4,a=e.startsWith(`data/dataset/`)&&!i,o=f(e);return(0,Z.jsxs)(`div`,{onClick:()=>t(e,W4(o)),role:`button`,tabIndex:0,onKeyDown:n=>{(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),t(e,W4(o)))},className:K(`flex items-center gap-2 group rounded-md pl-2 pr-1.5 py-1 border-l-2 transition-colors cursor-pointer select-none`,n%2==0?`bg-muted/50`:`bg-transparent`,`hover:bg-muted`,o===`off`?`border-l-transparent`:o===`anyOf`?`border-l-blue-500 !bg-info/10`:o===`allOf`?`border-l-emerald-500 !bg-success/10`:`border-l-rose-500 !bg-destructive/10`),children:[(0,Z.jsxs)(`span`,{className:`flex-1 min-w-0 text-xs font-mono text-foreground truncate`,title:i?`Virtual dataset: documents not stamped with any dataset. Included by default; "not" hides them, "all" shows only them.`:e,children:[e,i&&(0,Z.jsx)(`span`,{className:`ml-1.5 text-[10px] text-muted-foreground font-sans`,children:`virtual · on by default`})]}),(0,Z.jsx)(`span`,{onClick:e=>e.stopPropagation(),children:(0,Z.jsx)(K4,{mode:o,onSet:n=>t(e,n)})}),(!r||a)&&(0,Z.jsx)(`button`,{type:`button`,disabled:h===e,onClick:t=>{t.stopPropagation(),v(e)},className:`shrink-0 p-1 rounded text-muted-foreground/40 hover:text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50 reveal-on-hover`,title:a?`Drop dataset "${e.slice(13)}" (DELETES its documents)`:`Delete bitmap "${e}" from database`,"aria-label":a?`Drop dataset ${e}`:`Delete bitmap ${e}`,children:h===e?(0,Z.jsx)(Wn,{className:`w-3.5 h-3.5 animate-spin`}):(0,Z.jsx)(lt,{className:`w-3.5 h-3.5`})})]},e)})})]},e))]})]})}function Y4(){let{state:e,setToolsTab:t,saveFilters:n,clearFilters:r,hasActiveFilters:i}=hs(),{toolsTab:a,isDirty:o,isSaving:s,activeContextType:c,savedSearchQuery:l}=e,u=Hc(),d=new URLSearchParams(u.search).get(`q`)||new URLSearchParams(u.search).get(`search`)||``,f=c!==null&&d.trim()!==(l||``),p=c!==null&&(o||f);return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsx)(`div`,{className:`flex border-b border-border shrink-0`,children:[{id:`features`,label:`Features`},{id:`timeline`,label:`Timeline`},{id:`map`,label:`Map`},{id:`lens`,label:`Lens`}].map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(e.id),className:K(`flex-1 py-2.5 text-xs transition-colors`,a===e.id?`-mb-px border-b-2 border-foreground font-semibold text-foreground`:`font-medium text-muted-foreground hover:text-foreground`),children:e.label},e.id))}),(i||p)&&(0,Z.jsxs)(`div`,{className:`flex items-center justify-end gap-2 border-b border-border px-3 py-1.5 shrink-0`,children:[i&&(0,Z.jsxs)(`button`,{type:`button`,onClick:r,className:`flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:`Clear all active filters`,children:[(0,Z.jsx)(je,{className:`w-3 h-3`}),`Clear`]}),p&&(0,Z.jsxs)(`button`,{type:`button`,onClick:n,disabled:s,className:`flex items-center gap-1.5 rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground transition-colors hover:bg-primary disabled:opacity-60`,children:[s?(0,Z.jsx)(Wn,{className:`w-3 h-3 animate-spin`}):(0,Z.jsx)(Re,{className:`w-3 h-3`}),`Save filters`]})]}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-hidden`,children:[a===`features`&&(0,Z.jsx)(J4,{}),a===`timeline`&&(0,Z.jsx)(z4,{}),a===`map`&&(0,Z.jsx)(u4,{}),a===`lens`&&(0,Z.jsx)(h4,{})]})]})}function X4({status:e}){return(0,Z.jsx)(`span`,{className:K(`inline-block w-2 h-2 rounded-full shrink-0`,e===`active`?`bg-success`:e===`error`?`bg-destructive`:e===`starting`||e===`stopping`?`bg-warning`:`bg-muted-foreground`),title:e})}function Z4(){let{openAgentT2:e}=hs(),{setSection:t}=Eb(),n=Gc(),{agents:r,isLoading:i,refresh:a}=k0(!0),{showToast:o}=oo(),[s,c]=(0,X.useState)(new Set),l=(e,t)=>c(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r}),u=async(e,t)=>{e.stopPropagation(),l(t.id,!0);try{await ow(t.id),a()}catch(e){o({title:`Error`,description:e instanceof Error?e.message:`Failed`,variant:`destructive`})}finally{l(t.id,!1)}},d=async(e,t)=>{e.stopPropagation(),l(t.id,!0);try{await sw(t.id),a()}catch(e){o({title:`Error`,description:e instanceof Error?e.message:`Failed`,variant:`destructive`})}finally{l(t.id,!1)}};return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsx)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:`Agents`})}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:i&&r.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading…`}):r.length===0?(0,Z.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-12 text-muted-foreground`,children:[(0,Z.jsx)(H,{className:`w-8 h-8 opacity-30`}),(0,Z.jsx)(`span`,{className:`text-xs`,children:`No agents yet`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{t(`agents`),n(`/agents?create=1`)},className:`text-xs text-primary hover:underline`,children:`Create an agent`})]}):(0,Z.jsx)(`div`,{className:`space-y-1 px-2`,children:r.map(t=>{let n=s.has(t.id);return(0,Z.jsxs)(`div`,{className:`group relative px-3 py-2.5 cursor-pointer transition-colors bg-card hover:bg-accent/50`,style:{borderLeft:`6px solid ${t.color||`transparent`}`},onClick:()=>e(t.id),children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(X4,{status:t.status}),(0,Z.jsx)(`span`,{className:`text-sm font-medium flex-1 truncate`,children:t.label||t.name}),(0,Z.jsx)(`div`,{className:`flex items-center gap-0.5 shrink-0 reveal-on-hover`,children:t.status===`active`?(0,Z.jsx)(`button`,{type:`button`,disabled:n,onClick:e=>d(e,t),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50`,title:`Stop`,children:(0,Z.jsx)($t,{className:`w-3 h-3`})}):(0,Z.jsx)(`button`,{type:`button`,disabled:n,onClick:e=>u(e,t),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50`,title:`Start`,children:(0,Z.jsx)(W,{className:`w-3 h-3`})})})]}),t.description&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-4`,children:t.description})]},t.id)})})})]})}function Q4(){return(0,Z.jsx)(`div`,{className:`flex h-full flex-col`,children:(0,Z.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center gap-3 p-8 text-center`,children:[(0,Z.jsx)(`div`,{className:`flex h-12 w-12 items-center justify-center rounded-full bg-muted`,children:(0,Z.jsx)(_,{className:`h-5 w-5 text-muted-foreground`})}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium text-foreground`,children:`No notifications yet`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This is where activity, agent updates, and alerts will appear once notifications are wired in.`})]})]})})}function $4(e){if(!e)return``;if(typeof e.errorMessage==`string`&&e.errorMessage.trim())return e.errorMessage.trim();let t=e.content;return typeof t==`string`?t:Array.isArray(t)&&t.filter(e=>e?.type===`text`&&typeof e.text==`string`).map(e=>e.text??``).join(`
|
|
90
|
+
`)||``}function e3(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(null),s=(0,X.useRef)(null),[c,l]=(0,X.useState)(e);return c!==e&&(l(e),e||n([])),(0,X.useEffect)(()=>{let t=!1;if(e)return JC(e).then(e=>{t||n(e.messages.map(e=>({role:e.role,content:e.content,isComplete:!0,...e.metadata?.reasoning?{reasoning:e.metadata.reasoning}:{},...e.metadata?{metadata:e.metadata}:{}})))}).catch(()=>{t||n([])}),()=>{t=!0}},[e]),{messages:t,isStreaming:r,error:a,send:(0,X.useCallback)(async t=>{if(r||!t.trim()||!e)return;o(null),n(e=>[...e,{role:`user`,content:t,isComplete:!0},{role:`assistant`,content:``,isComplete:!1}]),i(!0);try{await ow(e)}catch(e){let t=e instanceof Error?e.message:void 0;if(!t?.includes(`not active`)&&!t?.includes(`already`)){o(t??`Failed to start agent`),i(!1);return}}s.current=new AbortController;let a=``,c=``,l=``,u;try{await Y.stream(`${Yr}/agents/${e}/prompt/stream`,{message:t},{signal:s.current.signal,onChunk:e=>{a+=e;let t=a.split(`
|
|
91
|
+
`);a=t.pop()??``;for(let e of t){if(!e.startsWith(`data: `))continue;let t=e.slice(6).trim();if(t===`[DONE]`)return;try{let e=JSON.parse(t);if(e.type===`chunk`)c+=e.delta||``,n(e=>{let t=[...e];return t[t.length-1]={role:`assistant`,content:c,isComplete:!1,...l?{reasoning:l}:{},...u?{metadata:u}:{}},t});else if(e.type===`thinking`)l=`${l}${e.delta||``}`.trim(),n(e=>{let t=[...e],n=t[t.length-1]?.content||c;return t[t.length-1]={role:`assistant`,content:n,isComplete:!1,...l?{reasoning:l}:{},...u?{metadata:u}:{}},t});else if(e.type===`complete`){let t=Array.isArray(e.messages)?[...e.messages].reverse().find(e=>e?.role===`assistant`):null,r=$4(t),i=FC(t)||l;u=IC(t),n(e=>{let t=[...e],n=c||t[t.length-1]?.content||``;return t[t.length-1]={role:`assistant`,content:r||n,isComplete:!0,...i?{reasoning:i}:{},...u?{metadata:u}:{}},t})}else e.type===`error`&&o(e.error)}catch{}}},onError:e=>{e.name!==`AbortError`&&o(e.message)},onComplete:()=>{n(e=>{let t=[...e],n=t[t.length-1];return n&&!n.isComplete&&(t[t.length-1]={...n,isComplete:!0}),t}),i(!1)}})}catch(e){let t=e instanceof Error?e:null;t?.name!==`AbortError`&&o(t?.message??`Stream failed`),n(e=>{let t=[...e],n=t[t.length-1];return n&&!n.isComplete&&(t[t.length-1]={...n,isComplete:!0}),t}),i(!1)}},[e,r]),sendVoice:(0,X.useCallback)(async t=>{if(!(r||!e)){o(null),i(!0),n(e=>[...e,{role:`user`,content:`🎤 Transcribing…`,isComplete:!1}]);try{let r=await pw(e,t);n(e=>{let t=[...e];return t[t.length-1]={role:`user`,content:`🎤 ${r.transcript}`,isComplete:!0},[...t,{role:`assistant`,content:r.reply,isComplete:!0}]}),r.audio&&r.audioMimeType&&new Audio(`data:${r.audioMimeType};base64,${r.audio}`).play().catch(()=>{})}catch(e){o(e instanceof Error?e.message:`Voice prompt failed`),n(e=>{let t=[...e],n=t[t.length-1];return n?.role===`user`&&!n.isComplete&&t.pop(),t})}finally{i(!1)}}},[e,r]),stop:(0,X.useCallback)(()=>{s.current?.abort(),i(!1)},[]),clear:(0,X.useCallback)(()=>{n([]),o(null)},[])}}function t3(){let[e,t]=(0,X.useState)(!1),[n,r]=(0,X.useState)(null),i=(0,X.useRef)(null),a=(0,X.useRef)([]);return{isRecording:e,recorderError:n,start:(0,X.useCallback)(async()=>{if(!i.current){if(r(null),!navigator.mediaDevices?.getUserMedia||typeof MediaRecorder>`u`){r(`Audio recording is not supported in this browser`);return}try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),n=MediaRecorder.isTypeSupported(`audio/webm;codecs=opus`)?`audio/webm;codecs=opus`:void 0,r=new MediaRecorder(e,n?{mimeType:n}:void 0);a.current=[],r.ondataavailable=e=>{e.data.size>0&&a.current.push(e.data)},r.start(),i.current=r,t(!0)}catch(e){let t=e instanceof Error?e:null;r(t?.name===`NotAllowedError`?`Microphone access denied`:t?.message??`Could not start recording`)}}},[]),stop:(0,X.useCallback)(()=>{let e=i.current;return e?new Promise(n=>{e.onstop=()=>{e.stream.getTracks().forEach(e=>e.stop()),i.current=null,t(!1);let r=e.mimeType||`audio/webm`,o=new Blob(a.current,{type:r});a.current=[],n(o.size>0?o:null)},e.stop()}):Promise.resolve(null)},[]),cancel:(0,X.useCallback)(()=>{let e=i.current;e&&(e.onstop=()=>{e.stream.getTracks().forEach(e=>e.stop())},e.stop(),i.current=null,a.current=[],t(!1))},[])}}function n3({agentId:e,onClose:t}){let[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),{showToast:m}=oo(),h=Ao(),g=h?.state.activeContextType===`context`?h.state.activeContextId:null,_=h?.state.activeContextPath??null,v=(0,X.useRef)(null),y=(0,X.useRef)(null),{messages:b,isStreaming:x,error:S,send:C,sendVoice:w,stop:T,clear:E}=e3(e),{isRecording:D,recorderError:O,start:k,stop:A}=t3();(0,X.useEffect)(()=>{qC(e).then(r).catch(()=>{}),VC(e).then(l).catch(()=>l(null))},[e]),(0,X.useEffect)(()=>{fw().then(e=>s(!!(e.enabled&&e.stt))).catch(()=>s(!1))},[]),(0,X.useEffect)(()=>{b.length!==0&&v.current?.scrollIntoView({behavior:`smooth`})},[b]);let j=c?.binding.type===`context`&&!!g&&c?.binding.context===g,M=c?c.binding.type===`global`?`scope: global`:c.binding.type===`context`?j?`scoped to this context`:`context-bound`:`scope: ${c.binding.workspaceName||c.binding.workspace}${c.binding.type===`path`?`:${c.binding.path||`/`}`:``}`:`no canvas access`,N=async()=>{if(!g||u)return;let t=g||_;if(window.confirm(`Bind "${n?.label||n?.name||e}" to the current context (${t})? This mints a new canvas token and restarts the agent if it is running.`)){d(!0);try{let t=await HC(e,{binding:{type:`context`,context:g},permissions:[`read`,`write`]});l(t.access),p(t.token)}catch(e){m({title:`Error`,description:e instanceof Error?e.message:`Bind failed`,variant:`destructive`})}finally{d(!1)}}},P=async()=>{let e=i.trim();!e||x||(a(``),y.current?.focus(),await C(e))};return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-3 h-12 border-b border-border shrink-0`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:t,className:`p-1 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Back to agents`,children:(0,Z.jsx)(Pn,{className:`w-4 h-4`})}),n?.color&&(0,Z.jsx)(`span`,{className:`w-2.5 h-2.5 rounded-full shrink-0`,style:{backgroundColor:n.color}}),(0,Z.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium truncate`,children:n?.label||n?.name||e}),(0,Z.jsx)(`div`,{className:`text-[10px] leading-tight text-muted-foreground truncate`,title:M,children:M})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:E,className:`p-1 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Clear chat`,children:(0,Z.jsx)(lt,{className:`w-3.5 h-3.5`})})]}),g&&!j&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 border-b border-border bg-muted/40 text-xs shrink-0`,children:[(0,Z.jsxs)(`span`,{className:`flex-1 truncate text-muted-foreground`,title:g||_||void 0,children:[`Toolbox context: `,g||_]}),(0,Z.jsx)(`button`,{type:`button`,disabled:u,onClick:N,className:`shrink-0 rounded border border-input px-2 py-1 hover:bg-accent disabled:opacity-50`,children:u?`Binding…`:`Bind to this context`})]}),f&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 border-b border-border bg-warning/10 text-xs shrink-0`,children:[(0,Z.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:`Token (shown once):`}),(0,Z.jsx)(`code`,{className:`flex-1 truncate font-mono`,children:f}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>navigator.clipboard?.writeText(f),className:`shrink-0 rounded border border-input px-2 py-1 hover:bg-accent`,children:`Copy`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(null),className:`shrink-0 rounded px-1.5 py-1 hover:bg-accent`,title:`Dismiss`,children:`×`})]}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto px-4 py-3 space-y-3`,children:[b.length===0&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground text-center py-10`,children:n?`Chat with ${n.label||n.name}`:`Loading…`}),b.map((e,t)=>(0,Z.jsxs)(`div`,{className:K(`text-sm rounded-lg px-3 py-2 max-w-[85%] break-words`,e.role===`user`?`ml-auto bg-foreground text-background`:`mr-auto bg-muted text-foreground`),children:[(0,Z.jsx)(PD,{reasoning:e.role===`assistant`?e.reasoning:void 0,metadata:e.role===`assistant`?e.metadata:void 0,isStreaming:!e.isComplete,compact:!0}),e.role===`assistant`?(0,Z.jsx)(Bm,{content:e.content||(e.isComplete?``:`…`)}):(0,Z.jsx)(`span`,{className:`whitespace-pre-wrap`,children:e.content})]},t)),(S||O)&&(0,Z.jsx)(`div`,{className:`text-xs text-destructive text-center py-1`,children:S||O}),(0,Z.jsx)(`div`,{ref:v})]}),(0,Z.jsx)(`div`,{className:`p-3 border-t border-border shrink-0`,children:(0,Z.jsxs)(`div`,{className:`flex gap-2 items-end`,children:[(0,Z.jsx)(`textarea`,{ref:y,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),P())},placeholder:`Message…`,rows:2,className:`flex-1 resize-y text-sm px-3 py-2 border border-input bg-background rounded-md focus:outline-none focus:ring-1 focus:ring-ring min-h-[38px] max-h-[120px]`}),o&&(0,Z.jsx)(`button`,{type:`button`,onClick:async()=>{if(D){let e=await A();e&&await w(e)}else x||await k()},disabled:x&&!D,className:K(`flex items-center justify-center w-9 h-9 rounded-md transition-opacity shrink-0 disabled:opacity-40`,D?`bg-destructive text-destructive-foreground hover:opacity-90 animate-pulse`:`bg-muted text-foreground hover:bg-accent`),title:D?`Stop recording and send`:`Record a voice message`,children:D?(0,Z.jsx)($t,{className:`w-4 h-4`}):(0,Z.jsx)(it,{className:`w-4 h-4`})}),x?(0,Z.jsx)(`button`,{type:`button`,onClick:T,className:`flex items-center justify-center w-9 h-9 rounded-md bg-destructive text-destructive-foreground hover:opacity-90 transition-opacity shrink-0`,title:`Stop`,children:(0,Z.jsx)($t,{className:`w-4 h-4`})}):(0,Z.jsx)(`button`,{type:`button`,onClick:P,disabled:!i.trim(),className:`flex items-center justify-center w-9 h-9 rounded-md bg-foreground text-background hover:opacity-90 disabled:opacity-40 transition-opacity shrink-0`,title:`Send`,children:(0,Z.jsx)(gt,{className:`w-4 h-4`})})]})})]})}function r3(){let{state:e,openApplet:t}=hs(),[n,r]=(0,X.useState)(`context`),i=e.appsAppletId,a=i?Sy.find(e=>e.id===i):null;if(a)return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-2 py-1.5`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(null),className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Back to applets`,title:`Back to applets`,children:(0,Z.jsx)(Pn,{className:`h-4 w-4`})}),(0,Z.jsx)(a.icon,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:a.label})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,Z.jsx)(a.Component,{})})]});let o=Cy(n);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(`div`,{className:`flex shrink-0 border-b border-border`,children:[`context`,`global`].map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(e),className:K(`flex-1 py-2.5 text-xs capitalize transition-colors`,n===e?`-mb-px border-b-2 border-foreground font-semibold text-foreground`:`font-medium text-muted-foreground hover:text-foreground`),children:e},e))}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3`,children:[!o.length&&(0,Z.jsxs)(`p`,{className:`py-10 text-center text-sm text-muted-foreground`,children:[`No `,n,` applets yet.`]}),(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-2`,children:o.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>t(e.id),className:`flex min-h-[4.5rem] flex-col items-center justify-center gap-1.5 rounded-lg border border-border bg-muted/40 p-3 text-foreground transition-colors hover:bg-muted`,title:e.description,children:[(0,Z.jsx)(e.icon,{className:`h-5 w-5 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-xs font-medium leading-none`,children:e.label})]},e.id))})]})]})}var i3=[{view:`apps`,icon:Jn,label:`Apps`},{view:`tools`,icon:Ot,label:`Filters`},{view:`agents`,icon:H,label:`Agents`},{view:`notifications`,icon:_,label:`Notifications`}],a3=420,o3=340,s3=`toolbox:width`,c3=360,l3=48,u3=e=>{let t=typeof window<`u`?window.innerWidth:1600,n=Math.max(o3,Math.min(Math.round(t*.7),t-l3-c3));return Math.max(o3,Math.min(e,n))},d3=()=>typeof window<`u`?Math.round(window.innerWidth/2):720;function f3(){let{state:e,setView:t,closeT1:n,closeT2:r}=hs();gf(n,e.t1Open&&!e.t2Open),gf(r,e.t2Open);let{t1Open:i,t1View:a,t2Open:o,t2AgentId:s,activeAccentColor:c}=e,l=wm(),[u,d]=(0,X.useState)(()=>{let e=typeof window<`u`?Number(localStorage.getItem(s3)):NaN;return Number.isFinite(e)&&e>0?e:a3}),f=(0,X.useCallback)(e=>{d(e);try{localStorage.setItem(s3,String(e))}catch{}},[]),p=(0,X.useRef)(null),m=(0,X.useCallback)(e=>{e.preventDefault(),p.current={startX:e.clientX,startWidth:u};let t=e=>{if(!p.current)return;let t=u3(p.current.startWidth-(e.clientX-p.current.startX));d(t)},n=()=>{p.current=null,window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n),d(e=>{try{localStorage.setItem(s3,String(e))}catch{}return e})};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[u]),h=u>=d3()*.9;return(0,X.useEffect)(()=>{let e=()=>d(e=>u3(e));return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),!i||!a?null:(0,Z.jsxs)(Z.Fragment,{children:[l&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-panel-scrim bg-scrim animate-fade-in`,onClick:n,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{style:l?void 0:{width:u},className:K(`flex flex-col overflow-hidden border bg-card surface-glass text-foreground`,l?`fixed bottom-2 left-2 right-2 top-2 z-panel rounded-2xl shadow-elevation-5 animate-fade-in`:`relative shrink-0 rounded-[var(--panel-radius)] shadow-elevation-3`),children:[!l&&(0,Z.jsx)(`div`,{onMouseDown:m,className:`absolute left-0 top-0 z-20 h-full w-1.5 cursor-col-resize hover:bg-primary/20`,title:`Drag to resize`,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between gap-1 border-b-[3px] px-2`,style:c?{borderBottomColor:c}:void 0,children:[(0,Z.jsx)(`div`,{className:`flex items-center gap-1`,children:i3.map(({view:e,icon:n,label:r})=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(e),"aria-label":r,title:r,className:K(`flex h-8 w-8 items-center justify-center rounded-md transition-colors`,a===e?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:(0,Z.jsx)(n,{className:`h-4 w-4 shrink-0`})},e))}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[!l&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>f(h?a3:u3(d3())),className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,"aria-label":h?`Shrink toolbox`:`Expand toolbox`,title:h?`Shrink toolbox`:`Expand to half screen`,children:h?(0,Z.jsx)(ct,{className:`h-4 w-4`}):(0,Z.jsx)(gn,{className:`h-4 w-4`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,"aria-label":`Close toolbox`,children:(0,Z.jsx)(je,{className:`h-4 w-4`})})]})]}),(0,Z.jsxs)(`div`,{className:`relative flex min-h-0 flex-1 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col ${o&&s?`invisible`:``}`,children:[a===`home`&&(0,Z.jsx)(Z2,{}),a===`apps`&&(0,Z.jsx)(r3,{}),a===`tools`&&(0,Z.jsx)(Y4,{}),a===`agents`&&(0,Z.jsx)(Z4,{}),a===`notifications`&&(0,Z.jsx)(Q4,{})]}),o&&s&&(0,Z.jsx)(`div`,{className:`absolute inset-0 z-10 flex flex-col bg-background`,children:(0,Z.jsx)(n3,{agentId:s,onClose:r})})]})]})]})}function p3(){let{running:e,hasViewer:t,paused:n,source:r,lastCount:i,error:a,setPaused:o,stop:s,reopen:c}=oy();if(!e||t)return null;let l=r===`screen`?kn:w;return(0,Z.jsxs)(`div`,{className:K(`fixed right-4 w-56 overflow-hidden rounded-xl border border-border bg-card shadow-elevation-4 z-panel animate-fade-in`,`bottom-fab-inset md:bottom-[calc(var(--spacing-fab-inset)+5rem)]`),role:`status`,"aria-label":`Lens feed running`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:c,title:`Back to Lens`,className:`relative block w-full cursor-pointer bg-black/80 aspect-video`,children:[(0,Z.jsx)(my,{className:`h-full w-full object-cover`}),n&&(0,Z.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-black/50 text-xs font-medium text-white`,children:`paused`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 px-2 py-1.5`,children:[(0,Z.jsx)(l,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-[11px] text-muted-foreground`,children:a?(0,Z.jsx)(`span`,{className:`text-destructive`,children:a}):n?`paused`:`live · ${i??`…`} match${i===1?``:`es`}`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>o(!n),"aria-label":n?`Resume Lens`:`Pause Lens`,title:n?`Resume searching`:`Pause searching (camera stays on)`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:n?(0,Z.jsx)(W,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(T,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:c,"aria-label":`Reopen Lens panel`,title:`Reopen Lens`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(gn,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:s,"aria-label":`Stop Lens feed`,title:`Stop the feed`,className:`rounded p-1 text-destructive transition-colors hover:bg-destructive/10`,children:(0,Z.jsx)(we,{className:`h-3.5 w-3.5`})})]})]})}function m3({children:e}){let[t,n]=(0,X.useState)(null),r={entry:t,open:(e,t)=>n({document:e,workspaceId:t}),close:()=>n(null)};return(0,Z.jsx)(Mp.Provider,{value:r,children:e})}var h3={key:`desk`,label:`Desk`,main:`/`,mainExpanded:!1,entries:[]},g3=0,_3=()=>`c${++g3}`;function v3(e,t){return e.kind===`route`&&t.kind===`route`?e.location===t.location:e.kind===`document`&&t.kind===`document`&&e.document.id===t.document.id&&e.workspaceId===t.workspaceId}function y3({children:e}){let t=Hc(),n=Gc(),[r,i]=(0,X.useState)([h3]),[a,o]=(0,X.useState)(0),[s,c]=(0,X.useState)(_g),l=(0,X.useRef)(r),u=(0,X.useRef)(a),d=(0,X.useRef)(s);(0,X.useEffect)(()=>{l.current=r,u.current=a,d.current=s},[r,a,s]);let f=(0,X.useCallback)((e,t)=>{let n=l.current.slice();n[e]=t,l.current=n,i(n)},[]),p=(0,X.useCallback)(e=>{let t=u.current,n=l.current[t];n&&f(t,e(n))},[f]),m=t.pathname+t.search;(0,X.useEffect)(()=>{p(e=>e.main===m?e:{...e,main:m})},[m,p]);let h=(0,X.useCallback)(e=>{let t=l.current[u.current];if(!t)return;let n=t.entries.find(t=>v3(e,t));if(n){c(n.id);return}let r={...e,id:_3()},i=t.entries.findIndex(e=>e.id===d.current),a=t.entries.slice();a.splice(i>=0?i+1:0,0,r),p(e=>({...e,entries:a})),d.current=r.id,c(r.id)},[p]),g=(0,X.useCallback)((e,t)=>{h({kind:`document`,document:e,workspaceId:t})},[h]),_=(0,X.useCallback)((e,t)=>{let n=`document-preview`;p(r=>{let i=r.entries.find(e=>e.id===n),a={kind:`document`,id:n,document:e,workspaceId:t,expanded:i?.expanded};return{...r,entries:[a,...r.entries.filter(e=>e.id!==n)]}}),d.current=n,c(n)},[p]),v=(0,X.useCallback)(e=>{p(t=>({...t,entries:t.entries.filter(t=>t.id!==e)})),c(t=>t===e?_g:t)},[p]),y=(0,X.useCallback)((e,t)=>{p(n=>({...n,entries:n.entries.map(n=>n.id===e&&n.kind===`route`?{...n,location:t}:n)}))},[p]),b=(0,X.useCallback)(e=>{p(t=>e===`main`?{...t,mainExpanded:!t.mainExpanded}:{...t,entries:t.entries.map(t=>t.id===e?{...t,expanded:!t.expanded}:t)})},[p]),x=(0,X.useCallback)(e=>{let t=l.current[e];t&&(u.current=e,o(e),c(_g),n(t.main))},[n]),S=(0,X.useCallback)((e,t,n)=>{let r=l.current.findIndex(t=>t.key===e);if(r>=0){x(r);return}let a=[...l.current,{key:e,label:t,main:n,mainExpanded:!1,entries:[]}];l.current=a,i(a),x(a.length-1)},[x]),C=(0,X.useCallback)(e=>{x(u.current+e)},[x]),w=(0,X.useCallback)(e=>{let t=l.current.findIndex(t=>t.key===e);if(t<=0)return;let n=l.current.filter(t=>t.key!==e);l.current=n,i(n);let r=u.current;r===t?x(Math.min(t,n.length-1)):r>t&&(u.current=r-1,o(r-1))},[x]),T=(0,X.useMemo)(()=>({rows:r,activeRow:a,focus:s,setFocus:c,openCanvas:h,openDocument:g,closeCanvas:v,navigateCanvas:y,toggleExpanded:b,activateRow:S,moveRow:C,closeRow:w}),[r,a,s,h,g,v,y,b,S,C,w]),E=(0,X.useMemo)(()=>({entry:null,open:g,preview:_,close:()=>{}}),[g,_]);return(0,Z.jsx)(vg.Provider,{value:T,children:(0,Z.jsx)(Mp.Provider,{value:E,children:e})})}function b3(e){return Ms(typeof e==`string`?Ns(e):e)}function x3({location:e,onNavigate:t}){let n=(0,X.useMemo)(()=>{let t=Ns(e);return{pathname:t.pathname||`/`,search:t.search||``,hash:t.hash||``,state:null,key:e}},[e]),r=(0,X.useMemo)(()=>({basename:`/`,static:!1,useTransitions:void 0,future:{},navigator:{createHref:b3,go:()=>{},push:e=>t(b3(e)),replace:e=>t(b3(e))}}),[t]);return(0,Z.jsx)(jc.Provider,{value:r,children:(0,Z.jsx)(Mc.Provider,{value:{location:n,navigationType:Cs.Push},children:(0,Z.jsx)(Nc.Provider,{value:{outlet:null,matches:[],isDataRoute:!1},children:(0,Z.jsx)(xl,{children:d1})})})})}var S3=`input, textarea, select, [contenteditable=""], [contenteditable="true"]`,C3=420,w3=e=>e<=0?0:e>=1?1:e<.5?2**(20*e-10)/2:(2-2**(-20*e+10))/2;function T3(e,t,n){if(window.matchMedia(`(prefers-reduced-motion: reduce)`).matches)return e.scrollLeft=t,n?.(),()=>{};let r=e.scrollLeft,i=t-r;if(Math.abs(i)<1)return n?.(),()=>{};let a=e.style.scrollSnapType;e.style.scrollSnapType=`none`;let o=performance.now(),s=0,c=t=>{let l=Math.min(1,(t-o)/C3);e.scrollLeft=r+i*w3(l),l<1?s=requestAnimationFrame(c):(e.style.scrollSnapType=a,n?.())};return s=requestAnimationFrame(c),()=>{cancelAnimationFrame(s),e.style.scrollSnapType=a}}function E3(e,t){let n=parseFloat(getComputedStyle(e).gap)||0,r=t.getBoundingClientRect().left-e.getBoundingClientRect().left+e.scrollLeft,i=r+t.offsetWidth,a=e.scrollLeft,o=a+e.clientWidth;return r<a?Math.max(0,r-n):i>o?i+n-e.clientWidth:a}function D3({section:e}){return e===`contexts`?(0,Z.jsx)(R1,{}):e===`workspaces`?(0,Z.jsx)(r0,{}):e===`agents`?(0,Z.jsx)(j0,{}):e===`admin`||e===`settings`?(0,Z.jsx)(L0,{}):null}function O3(e,t){if(e?.kind===`document`)return mo(e.document).title;let n=(e?.kind===`route`?e.location:t).split(/[?#]/)[0];if(n===`/settings`)return`Settings`;let r=nb.flatMap(e=>[...e.items]).find(e=>e.path===n);if(r)return r.label;let i=n.split(`/`).filter(Boolean);return i.length===0?`Desk`:decodeURIComponent(i[i.length-1])}function k3({id:e,title:t,expanded:n,focused:r,onFocus:i,onToggleExpanded:a,onClose:o,badge:s,contentHeader:c,children:l}){let u=Z0();return(0,Z.jsxs)(`section`,{"data-reader-pane":c?!0:void 0,style:c&&!n&&u?{"--reader-width":`${u}px`,transition:`none`}:void 0,"data-strip-col":e,className:K(`strip-canvas surface-sheet relative`,n&&`strip-canvas--wide`,r&&`strip-canvas--focused`),onPointerDownCapture:()=>i(e),"aria-label":t,children:[c&&!n&&(0,Z.jsx)(e2,{edge:`right`}),!c&&(0,Z.jsxs)(`header`,{className:`strip-canvas-bar`,children:[s&&(0,Z.jsx)(`span`,{className:`strip-row-label`,children:s}),(0,Z.jsx)(`span`,{className:`strip-canvas-title`,title:t,children:t}),(0,Z.jsx)(`button`,{type:`button`,className:`strip-canvas-btn`,title:n?`Card size`:`Expand to full width`,"aria-pressed":n,onClick:()=>a(e),children:n?(0,Z.jsx)(ct,{className:`size-3.5`}):(0,Z.jsx)(gn,{className:`size-3.5`})}),o&&(0,Z.jsx)(`button`,{type:`button`,className:`strip-canvas-btn`,title:s?`Close row`:`Close canvas`,onClick:()=>o(e),children:(0,Z.jsx)(je,{className:`size-3.5`})})]}),(0,Z.jsx)(`div`,{className:`strip-canvas-body`,children:l})]})}function A3(e){return K(`relative flex-1 min-h-0 min-w-0 overflow-auto`,!i2(e)&&!r2(e)&&`p-page`)}function j3({row:e,pathname:t,rowLabel:n,onCloseRow:r}){let{focus:i,setFocus:a,toggleExpanded:o,closeCanvas:s,navigateCanvas:c}=yg(),l=(0,X.useCallback)(e=>t=>c(e,t),[c]);return(0,Z.jsxs)(Z.Fragment,{children:[t===`/`?(0,Z.jsx)(`div`,{hidden:!0,children:(0,Z.jsx)(vl,{})}):(0,Z.jsx)(k3,{id:_g,title:O3(null,t),expanded:e.mainExpanded,focused:i===_g,onFocus:a,onToggleExpanded:o,badge:n,onClose:r,children:(0,Z.jsx)(`main`,{id:`content-area`,className:A3(t),children:(0,Z.jsx)(vl,{})})}),e.entries.map(e=>(0,Z.jsx)(k3,{id:e.id,title:O3(e,t),expanded:!!e.expanded,focused:i===e.id,onFocus:a,onToggleExpanded:o,contentHeader:e.kind===`document`,onClose:s,children:e.kind===`route`?(0,Z.jsx)(`div`,{className:A3(e.location.split(`?`)[0]),children:(0,Z.jsx)(x3,{location:e.location,onNavigate:l(e.id)})}):(0,Z.jsx)(`div`,{className:`flex flex-1 min-h-0 min-w-0 items-stretch`,children:(0,Z.jsx)(n2,{entry:e,onClose:()=>s(e.id),frame:{expanded:!!e.expanded,onToggleExpanded:()=>o(e.id)}})})},e.id))]})}function M3({row:e}){return(0,Z.jsxs)(`div`,{className:`strip-ghost-row`,"aria-hidden":!0,children:[(0,Z.jsx)(`span`,{className:`strip-ghost-chip strip-ghost-chip--main`,children:O3(null,e.main)}),e.entries.map(t=>(0,Z.jsx)(`span`,{className:`strip-ghost-chip`,children:O3(t,e.main)},t.id))]})}function N3(){let{state:e,closeM1:t,closeM2:n}=Eb(),{rows:r,activeRow:i,focus:a,setFocus:o,moveRow:s,closeRow:c}=yg(),{pathname:l}=Hc(),u=Cb(),d=(0,X.useRef)(null);gf(t,e.m1Open&&!e.m2Open),gf(n,e.m2Open),(0,X.useLayoutEffect)(()=>{let e=d.current;if(!e)return;let t=()=>{e.style.setProperty(`--strip-w`,`${e.clientWidth}px`),e.style.setProperty(`--strip-h`,`${e.clientHeight}px`)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let f=(0,X.useRef)(e.m1Open);(0,X.useEffect)(()=>{e.m1Open&&!f.current&&!e.m2Open&&o(`m1`),f.current=e.m1Open},[e.m1Open,e.m2Open,o]);let p=(0,X.useRef)(e.m2Open);(0,X.useEffect)(()=>{e.m2Open&&!p.current&&o(`m2`),!e.m2Open&&p.current&&a===`m2`&&o(e.m1Open?`m1`:_g),p.current=e.m2Open},[e.m2Open,e.m1Open,a,o]),(0,X.useEffect)(()=>{!e.m1Open&&a===`m1`&&o(_g)},[e.m1Open,a,o]),(0,X.useEffect)(()=>{let e=d.current,t=e?.querySelector(`[data-strip-col="${CSS.escape(a)}"]`);if(!(!e||!t))return T3(e,E3(e,t))},[a,r,i,e.m1Open,e.m2Open]);let m=(0,X.useCallback)(()=>{let t=r[i];return[...e.m1Open?[`m1`]:[],...e.m2Open?[`m2`]:[],...l===`/`?[]:[_g],...t?t.entries.map(e=>e.id):[]]},[r,i,e.m1Open,e.m2Open,l]);return(0,X.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||!e.key.startsWith(`Arrow`)||!wb(e,u))return;let t=e.target;if(!(t?.closest(S3)||t?.closest(`[role="dialog"]`))){if(e.key===`ArrowLeft`||e.key===`ArrowRight`){let t=m(),n=t[Math.max(0,t.indexOf(a))+(e.key===`ArrowRight`?1:-1)];if(!n)return;e.preventDefault(),o(n)}else(e.key===`ArrowUp`||e.key===`ArrowDown`)&&r.length>1&&(e.preventDefault(),s(e.key===`ArrowDown`?1:-1))}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[m,a,o,s,r.length,u]),(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`strip-shell flex h-viewport w-full overflow-hidden surface-desk gap-shell p-shell`,children:[(0,Z.jsx)(I1,{}),(0,Z.jsxs)(`div`,{ref:d,className:`strip-scroller`,children:[e.m1Open&&(0,Z.jsx)(`div`,{"data-strip-col":`m1`,className:K(`strip-col strip-menu-col`,a===`m1`&&`strip-col--focused`),onPointerDownCapture:()=>o(`m1`),children:(0,Z.jsx)(D3,{section:e.activeSection})}),e.m2Open&&(0,Z.jsx)(`div`,{"data-strip-col":`m2`,className:K(`strip-col strip-menu-col`,a===`m2`&&`strip-col--focused`),onPointerDownCapture:()=>o(`m2`),children:(0,Z.jsx)(V0,{})}),(0,Z.jsx)(`div`,{className:`strip-rows`,style:{transform:`translateY(${-i*100}%)`},children:r.map((e,t)=>(0,Z.jsx)(`div`,{className:K(`strip-row`,t===i&&`strip-row--active`),children:(0,Z.jsx)(`div`,{className:`strip-row-canvases`,children:t===i?(0,Z.jsx)(j3,{row:e,pathname:l,rowLabel:r.length>1?e.label:void 0,onCloseRow:t>0?()=>c(e.key):void 0}):(0,Z.jsx)(M3,{row:e})})},e.key))})]}),(0,Z.jsx)(J2,{}),(0,Z.jsx)(f3,{})]}),(0,Z.jsx)(c2,{}),(0,Z.jsx)(F1,{}),(0,Z.jsx)(p3,{})]})}function P3(){let e=mb();return(0,Z.jsx)(y1,{children:(0,Z.jsx)(d2,{children:(0,Z.jsx)(T2,{children:(0,Z.jsx)(hy,{children:(0,Z.jsx)(m3,{children:e===`strip`?(0,Z.jsx)(y3,{children:(0,Z.jsx)(Ty,{children:(0,Z.jsx)(N3,{})})}):(0,Z.jsxs)(Ty,{children:[(0,Z.jsxs)(`div`,{className:`flex h-viewport w-full overflow-hidden surface-desk gap-shell p-shell`,children:[(0,Z.jsx)(I1,{}),(0,Z.jsx)(H0,{}),(0,Z.jsx)(s2,{}),(0,Z.jsx)(J2,{}),(0,Z.jsx)(f3,{})]}),(0,Z.jsx)(c2,{}),(0,Z.jsx)(F1,{}),(0,Z.jsx)(p3,{})]})})})})})})}var F3=Cn,I3=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Ht,{ref:n,className:K(`fixed top-0 right-0 z-toast flex max-h-screen w-full flex-col-reverse gap-2 p-4 sm:right-0 sm:flex-col md:max-w-[420px]`,e),...t}));I3.displayName=Ht.displayName;var L3=fr(`group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-elevation-3 transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full`,{variants:{variant:{default:`border bg-background`,destructive:`destructive group border-destructive bg-destructive text-destructive-foreground`}},defaultVariants:{variant:`default`}}),R3=X.forwardRef(({className:e,variant:t,...n},r)=>(0,Z.jsx)(dn,{ref:r,className:K(L3({variant:t}),e),...n}));R3.displayName=dn.displayName;var z3=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Hn,{ref:n,className:K(`inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive`,e),...t}));z3.displayName=Hn.displayName;var B3=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(kt,{ref:n,className:K(`absolute right-2 top-2 rounded-md p-1 text-foreground/50 reveal-on-hover hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-[.destructive]:text-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive group-[.destructive]:focus:ring-offset-destructive`,e),"toast-close":``,...t,children:(0,Z.jsx)(je,{className:`h-4 w-4`})}));B3.displayName=kt.displayName;var V3=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Kt,{ref:n,className:K(`text-sm font-semibold`,e),...t}));V3.displayName=Kt.displayName;var H3=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Lt,{ref:n,className:K(`text-sm opacity-90`,e),...t}));H3.displayName=Lt.displayName;function U3({children:e}){let[t,n]=(0,X.useState)([]),r=(0,X.useRef)(new Set),i=(0,X.useCallback)(e=>{if(Ar(e.description)||Ar(e.title))return;let t=`${e.title}:${e.description??``}`;if(r.current.has(t))return;r.current.add(t);let i=Math.random().toString(36).substring(2,9);n(t=>[...t,{...e,id:i}]),setTimeout(()=>{n(e=>e.filter(e=>e.id!==i)),r.current.delete(t)},5e3)},[]),a=(0,X.useMemo)(()=>({showToast:i}),[i]);return(0,Z.jsx)(Ja.Provider,{value:a,children:(0,Z.jsxs)(F3,{children:[e,t.map(e=>(0,Z.jsxs)(R3,{variant:e.variant,children:[(0,Z.jsxs)(`div`,{className:`grid gap-1`,children:[(0,Z.jsx)(V3,{children:e.title}),e.description!=null&&(0,Z.jsx)(H3,{children:e.description})]}),(0,Z.jsx)(B3,{})]},e.id)),(0,Z.jsx)(I3,{})]})})}async function W3(){return await Y.get(`/messaging/notifications`,{noAuthRedirect:!0})||[]}async function G3(){await Y.delete(`/messaging/notifications`,{noAuthRedirect:!0})}function K3({children:e}){let[t,n]=(0,X.useState)([]),{showToast:r}=oo();(0,X.useEffect)(()=>{let e=!1;W3().then(t=>{e||n(t)}).catch(()=>{});let t=Wu.on(`notification`,e=>{let t=e;!t?.id||!t?.text||(n(e=>e.some(e=>e.id===t.id)?e:[...e,t].slice(-50)),r({title:`Notification`,description:t.text}))});return()=>{e=!0,t?.()}},[r]);let i=(0,X.useCallback)(async()=>{n([]),await G3().catch(()=>{})},[]);return(0,Z.jsx)(Y2.Provider,{value:{notifications:t,clear:i},children:e})}var q3=e=>`${e.workspaceName}\0${e.treeName}\0${e.path}`;function J3({children:e}){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0);(0,X.useEffect)(()=>{let e=!1;return c0().then(t=>{e||n(t)}).catch(()=>{e||n({})}).finally(()=>{e||i(!1)}),()=>{e=!0}},[]);let a=(0,X.useMemo)(()=>t?.home?.pinnedCanvases??[],[t]),[o]=(0,X.useState)(()=>YS(c0,l0,n)),s=(0,X.useCallback)(e=>a.some(t=>q3(t)===q3(e)),[a]),c=(0,X.useCallback)(async e=>{let t=crypto.randomUUID();await o(n=>n.some(t=>q3(t)===q3(e))?n:[...n,{id:t,...e}])},[o]),l=(0,X.useCallback)(async e=>{await o(t=>t.filter(t=>t.id!==e))},[o]),u=(0,X.useCallback)(async(e,t)=>{await o(n=>n.map(n=>n.id===e?{...n,minimized:t}:n))},[o]),d=(0,X.useCallback)(async(e,t)=>{await o(n=>{let r=n.find(t=>t.id===e);if(!r||e===t)return n;let i=n.filter(t=>t.id!==e),a=t===null?i.length:i.findIndex(e=>e.id===t);return a===-1?n:[...i.slice(0,a),r,...i.slice(a)]})},[o]),f=(0,X.useMemo)(()=>({pins:a,isLoading:r,isPinned:s,pin:c,unpin:l,movePin:d,setMinimized:u}),[a,r,s,c,l,d,u]);return(0,Z.jsx)(Tx.Provider,{value:f,children:e})}var Y3=(0,X.lazy)(()=>m(()=>import(`./NextShell-CIyIaK3b.js`),__vite__mapDeps([26,3,4,11,9,10,12,27])));function X3(){let{showToast:e}=oo();return(0,X.useEffect)(()=>{$i((t,n)=>{e({title:`Error`,description:n?`${t.message} (${n})`:t.message,variant:`destructive`})})},[e]),(0,X.useEffect)(()=>C1(),[]),(0,Z.jsxs)(su,{children:[(0,Z.jsx)(g1,{}),(0,Z.jsx)(Ry,{}),(0,Z.jsxs)(xl,{children:[(0,Z.jsx)(yl,{path:`/login`,element:(0,Z.jsx)(od,{children:(0,Z.jsx)(nd,{})})}),(0,Z.jsx)(yl,{path:`/register`,element:(0,Z.jsx)(od,{children:(0,Z.jsx)(rd,{})})}),(0,Z.jsx)(yl,{path:`/pub/c/:code`,element:(0,Z.jsx)(Bv,{})}),(0,Z.jsx)(yl,{path:`/apps/:appletId`,element:(0,Z.jsx)(ad,{children:(0,Z.jsx)(Dy,{})})}),(0,Z.jsx)(yl,{path:`/next/*`,element:(0,Z.jsx)(ad,{children:(0,Z.jsx)(X.Suspense,{fallback:null,children:(0,Z.jsx)(Y3,{})})})}),(0,Z.jsx)(yl,{path:`/`,element:(0,Z.jsx)(ad,{children:(0,Z.jsx)(K3,{children:(0,Z.jsx)(J3,{children:(0,Z.jsx)(P3,{})})})}),children:d1}),(0,Z.jsx)(yl,{path:`*`,element:(0,Z.jsx)(_l,{to:`/`,replace:!0})})]})]})}function Z3(){return(0,Z.jsx)(_T,{children:(0,Z.jsx)(U3,{children:(0,Z.jsx)(X3,{})})})}Fw(),(0,ys.createRoot)(document.getElementById(`root`)).render((0,Z.jsx)(X.StrictMode,{children:(0,Z.jsx)(Z3,{})}));
|