termdock 1.4.198 → 1.4.199
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{App-B2nTzqxn.js → App-DzU5e73Z.js} +3 -3
- package/dist/client/assets/App-DzU5e73Z.js.br +0 -0
- package/dist/client/assets/App-DzU5e73Z.js.gz +0 -0
- package/dist/client/assets/{ChangeWalkthroughPanel-8XBpObo8.js → ChangeWalkthroughPanel-CLe_Mm4u.js} +1 -1
- package/dist/client/assets/ChangeWalkthroughPanel-CLe_Mm4u.js.br +0 -0
- package/dist/client/assets/ChangeWalkthroughPanel-CLe_Mm4u.js.gz +0 -0
- package/dist/client/assets/{DagPlayground-BrvWN-BF.js → DagPlayground-Badsbf-8.js} +1 -1
- package/dist/client/assets/DagPlayground-Badsbf-8.js.br +0 -0
- package/dist/client/assets/DagPlayground-Badsbf-8.js.gz +0 -0
- package/dist/client/assets/{DiffLab-B_6noZdn.js → DiffLab-D_xUbRBZ.js} +1 -1
- package/dist/client/assets/DiffLab-D_xUbRBZ.js.br +0 -0
- package/dist/client/assets/DiffLab-D_xUbRBZ.js.gz +0 -0
- package/dist/client/assets/{DiffReview-BYnopIh6.js → DiffReview-CZEYztDY.js} +1 -1
- package/dist/client/assets/DiffReview-CZEYztDY.js.br +0 -0
- package/dist/client/assets/DiffReview-CZEYztDY.js.gz +0 -0
- package/dist/client/assets/{DiffReviewLab-DgGq28V3.js → DiffReviewLab-DS0B2tZH.js} +1 -1
- package/dist/client/assets/DiffReviewLab-DS0B2tZH.js.br +0 -0
- package/dist/client/assets/DiffReviewLab-DS0B2tZH.js.gz +0 -0
- package/dist/client/assets/{DiffViewer-DBB2Nxe-.js → DiffViewer-DyC8uspo.js} +1 -1
- package/dist/client/assets/DiffViewer-DyC8uspo.js.br +0 -0
- package/dist/client/assets/DiffViewer-DyC8uspo.js.gz +0 -0
- package/dist/client/assets/{ModelPreview-cxnQVfjP.js → ModelPreview-CXP6AnKa.js} +1 -1
- package/dist/client/assets/ModelPreview-CXP6AnKa.js.br +0 -0
- package/dist/client/assets/ModelPreview-CXP6AnKa.js.gz +0 -0
- package/dist/client/assets/RightSidebar-ITHYo4dC.js +1678 -0
- package/dist/client/assets/RightSidebar-ITHYo4dC.js.br +0 -0
- package/dist/client/assets/RightSidebar-ITHYo4dC.js.gz +0 -0
- package/dist/client/assets/{abnfDiagram-VCTEODGH-53wXKK7P.js → abnfDiagram-VCTEODGH-DN0Pmpzq.js} +1 -1
- package/dist/client/assets/abnfDiagram-VCTEODGH-DN0Pmpzq.js.br +0 -0
- package/dist/client/assets/abnfDiagram-VCTEODGH-DN0Pmpzq.js.gz +0 -0
- package/dist/client/assets/{app-C6U2Oauh.js → app-DiV950OT.js} +12 -12
- package/dist/client/assets/app-DiV950OT.js.br +0 -0
- package/dist/client/assets/app-DiV950OT.js.gz +0 -0
- package/dist/client/assets/{arc-4tt2sKMs.js → arc-Coohao90.js} +1 -1
- package/dist/client/assets/arc-Coohao90.js.br +0 -0
- package/dist/client/assets/arc-Coohao90.js.gz +0 -0
- package/dist/client/assets/{architectureDiagram-5GKGNRK7-Clcm83eD.js → architectureDiagram-5GKGNRK7-DCNgnFJl.js} +1 -1
- package/dist/client/assets/architectureDiagram-5GKGNRK7-DCNgnFJl.js.br +0 -0
- package/dist/client/assets/architectureDiagram-5GKGNRK7-DCNgnFJl.js.gz +0 -0
- package/dist/client/assets/{blockDiagram-I7D4REHJ-CfdVuYkG.js → blockDiagram-I7D4REHJ-B7ygjzpe.js} +1 -1
- package/dist/client/assets/blockDiagram-I7D4REHJ-B7ygjzpe.js.br +0 -0
- package/dist/client/assets/blockDiagram-I7D4REHJ-B7ygjzpe.js.gz +0 -0
- package/dist/client/assets/{c4Diagram-7LVT6UL2-BHtwHuZs.js → c4Diagram-7LVT6UL2-D3AflhSp.js} +1 -1
- package/dist/client/assets/c4Diagram-7LVT6UL2-D3AflhSp.js.br +0 -0
- package/dist/client/assets/c4Diagram-7LVT6UL2-D3AflhSp.js.gz +0 -0
- package/dist/client/assets/channel-BCZxsRzH.js +1 -0
- package/dist/client/assets/{chunk-2Q5K7J3B-BVNi4bCF.js → chunk-2Q5K7J3B-qAR0dKhs.js} +1 -1
- package/dist/client/assets/{chunk-5VM5RSS4-lA-EJ6oE.js → chunk-5VM5RSS4-h6gCyzoE.js} +1 -1
- package/dist/client/assets/{chunk-F27PBJKO-CrWbPzSA.js → chunk-F27PBJKO-DhbhE3St.js} +1 -1
- package/dist/client/assets/chunk-F27PBJKO-DhbhE3St.js.br +0 -0
- package/dist/client/assets/chunk-F27PBJKO-DhbhE3St.js.gz +0 -0
- package/dist/client/assets/{chunk-IMKFNOWR-yohtKh6p.js → chunk-IMKFNOWR-DhKtP3rl.js} +1 -1
- package/dist/client/assets/chunk-IMKFNOWR-DhKtP3rl.js.br +0 -0
- package/dist/client/assets/chunk-IMKFNOWR-DhKtP3rl.js.gz +0 -0
- package/dist/client/assets/{chunk-JWPE2WC7-DvZqwUFX.js → chunk-JWPE2WC7-CtO_XmtJ.js} +1 -1
- package/dist/client/assets/{chunk-POPQ4Y6H-DiGp5sHG.js → chunk-POPQ4Y6H-D-B40pN4.js} +1 -1
- package/dist/client/assets/{chunk-SVP7TREG-B-1tHXph.js → chunk-SVP7TREG-DE_IFQjb.js} +1 -1
- package/dist/client/assets/chunk-SVP7TREG-DE_IFQjb.js.br +0 -0
- package/dist/client/assets/chunk-SVP7TREG-DE_IFQjb.js.gz +0 -0
- package/dist/client/assets/{chunk-TICWLB2K-DGO5T9qo.js → chunk-TICWLB2K-B10O7y1x.js} +1 -1
- package/dist/client/assets/chunk-TICWLB2K-B10O7y1x.js.br +0 -0
- package/dist/client/assets/chunk-TICWLB2K-B10O7y1x.js.gz +0 -0
- package/dist/client/assets/{chunk-XXDRQBXY-BC6AmHii.js → chunk-XXDRQBXY-DHXtKiu_.js} +1 -1
- package/dist/client/assets/classDiagram-ZZMXUADV-B5ArMHli.js +1 -0
- package/dist/client/assets/classDiagram-v2-VYDZK3BY-B5ArMHli.js +1 -0
- package/dist/client/assets/{cose-bilkent-JH36ORCC-Bph_dwwU.js → cose-bilkent-JH36ORCC-DJKA9UdZ.js} +1 -1
- package/dist/client/assets/cose-bilkent-JH36ORCC-DJKA9UdZ.js.br +0 -0
- package/dist/client/assets/cose-bilkent-JH36ORCC-DJKA9UdZ.js.gz +0 -0
- package/dist/client/assets/{cynefin-OW5HDTMX-CSaZ7osN.js → cynefin-OW5HDTMX-CwZU_wwP.js} +1 -1
- package/dist/client/assets/cynefin-OW5HDTMX-CwZU_wwP.js.br +0 -0
- package/dist/client/assets/cynefin-OW5HDTMX-CwZU_wwP.js.gz +0 -0
- package/dist/client/assets/{cynefinDiagram-5FMLGOSQ-Jj0ksAR5.js → cynefinDiagram-5FMLGOSQ-BiJN9Cnt.js} +1 -1
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-BiJN9Cnt.js.br +0 -0
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-BiJN9Cnt.js.gz +0 -0
- package/dist/client/assets/{dagre-GXQ25YYZ-DqOb5Z8X.js → dagre-GXQ25YYZ-nVpIr5ip.js} +1 -1
- package/dist/client/assets/dagre-GXQ25YYZ-nVpIr5ip.js.br +0 -0
- package/dist/client/assets/dagre-GXQ25YYZ-nVpIr5ip.js.gz +0 -0
- package/dist/client/assets/{diagram-S7CK7UJ4-BjVavRpU.js → diagram-S7CK7UJ4-KNkAB_hR.js} +1 -1
- package/dist/client/assets/diagram-S7CK7UJ4-KNkAB_hR.js.br +0 -0
- package/dist/client/assets/diagram-S7CK7UJ4-KNkAB_hR.js.gz +0 -0
- package/dist/client/assets/{diagram-UQ7AKVKN-BUi_Iz8S.js → diagram-UQ7AKVKN-CxzPGhEm.js} +1 -1
- package/dist/client/assets/diagram-UQ7AKVKN-CxzPGhEm.js.br +0 -0
- package/dist/client/assets/diagram-UQ7AKVKN-CxzPGhEm.js.gz +0 -0
- package/dist/client/assets/{diagram-VSXAHHWV-yGmUbeDV.js → diagram-VSXAHHWV-CbYDl51x.js} +1 -1
- package/dist/client/assets/diagram-VSXAHHWV-CbYDl51x.js.br +0 -0
- package/dist/client/assets/diagram-VSXAHHWV-CbYDl51x.js.gz +0 -0
- package/dist/client/assets/{diagram-VX7I27RA-1wI9D0Xy.js → diagram-VX7I27RA-BO1XNjDC.js} +1 -1
- package/dist/client/assets/diagram-VX7I27RA-BO1XNjDC.js.br +0 -0
- package/dist/client/assets/diagram-VX7I27RA-BO1XNjDC.js.gz +0 -0
- package/dist/client/assets/{diagram-Z3DM3KII-Ah9R4yGC.js → diagram-Z3DM3KII-LoXQSb8P.js} +1 -1
- package/dist/client/assets/diagram-Z3DM3KII-LoXQSb8P.js.br +0 -0
- package/dist/client/assets/diagram-Z3DM3KII-LoXQSb8P.js.gz +0 -0
- package/dist/client/assets/{ebnfDiagram-PWID7BFC-Bc9e_6tX.js → ebnfDiagram-PWID7BFC-hMcytdH5.js} +1 -1
- package/dist/client/assets/ebnfDiagram-PWID7BFC-hMcytdH5.js.br +0 -0
- package/dist/client/assets/ebnfDiagram-PWID7BFC-hMcytdH5.js.gz +0 -0
- package/dist/client/assets/{erDiagram-RLTQ6QDP-CcDEtpQh.js → erDiagram-RLTQ6QDP-DVpu6wuk.js} +1 -1
- package/dist/client/assets/erDiagram-RLTQ6QDP-DVpu6wuk.js.br +0 -0
- package/dist/client/assets/erDiagram-RLTQ6QDP-DVpu6wuk.js.gz +0 -0
- package/dist/client/assets/{flowDiagram-HODETNUW-yJnnTJvd.js → flowDiagram-HODETNUW-C34wUKry.js} +1 -1
- package/dist/client/assets/flowDiagram-HODETNUW-C34wUKry.js.br +0 -0
- package/dist/client/assets/{flowDiagram-HODETNUW-yJnnTJvd.js.gz → flowDiagram-HODETNUW-C34wUKry.js.gz} +0 -0
- package/dist/client/assets/{ganttDiagram-EL5Y4UJY-DazfV-Pr.js → ganttDiagram-EL5Y4UJY-BH1zJQsQ.js} +1 -1
- package/dist/client/assets/ganttDiagram-EL5Y4UJY-BH1zJQsQ.js.br +0 -0
- package/dist/client/assets/ganttDiagram-EL5Y4UJY-BH1zJQsQ.js.gz +0 -0
- package/dist/client/assets/{gestureArbiter-CIH61YPG.js → gestureArbiter-CcSl2ujx.js} +1 -1
- package/dist/client/assets/gestureArbiter-CcSl2ujx.js.br +0 -0
- package/dist/client/assets/gestureArbiter-CcSl2ujx.js.gz +0 -0
- package/dist/client/assets/{gitGraphDiagram-WWUBYQGX-I_lUerNQ.js → gitGraphDiagram-WWUBYQGX-C11si3Qx.js} +1 -1
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-C11si3Qx.js.br +0 -0
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-C11si3Qx.js.gz +0 -0
- package/dist/client/assets/{infoDiagram-27XIBGKW-DEo4Zn5O.js → infoDiagram-27XIBGKW-bRE18M4P.js} +1 -1
- package/dist/client/assets/{ishikawaDiagram-5VMMS53U-CiefWGfu.js → ishikawaDiagram-5VMMS53U-B_afVFwF.js} +1 -1
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-B_afVFwF.js.br +0 -0
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-B_afVFwF.js.gz +0 -0
- package/dist/client/assets/{journeyDiagram-3NMN7TZE-BHDqhmj7.js → journeyDiagram-3NMN7TZE-Ds5r_Wtf.js} +1 -1
- package/dist/client/assets/journeyDiagram-3NMN7TZE-Ds5r_Wtf.js.br +0 -0
- package/dist/client/assets/journeyDiagram-3NMN7TZE-Ds5r_Wtf.js.gz +0 -0
- package/dist/client/assets/{kanban-definition-UXKFOSKX-C5EVX9Si.js → kanban-definition-UXKFOSKX-DTzBlDtk.js} +1 -1
- package/dist/client/assets/kanban-definition-UXKFOSKX-DTzBlDtk.js.br +0 -0
- package/dist/client/assets/kanban-definition-UXKFOSKX-DTzBlDtk.js.gz +0 -0
- package/dist/client/assets/{layout-BsZ6KtNp.js → layout-DTD7PlPT.js} +1 -1
- package/dist/client/assets/{layout-BsZ6KtNp.js.br → layout-DTD7PlPT.js.br} +0 -0
- package/dist/client/assets/layout-DTD7PlPT.js.gz +0 -0
- package/dist/client/assets/{linear-gI0rPpZO.js → linear-B0VSRzSz.js} +1 -1
- package/dist/client/assets/linear-B0VSRzSz.js.br +0 -0
- package/dist/client/assets/linear-B0VSRzSz.js.gz +0 -0
- package/dist/client/assets/{mermaid.core-DN5JSxkg.js → mermaid.core-CHCXje56.js} +5 -5
- package/dist/client/assets/mermaid.core-CHCXje56.js.br +0 -0
- package/dist/client/assets/mermaid.core-CHCXje56.js.gz +0 -0
- package/dist/client/assets/{mindmap-definition-YA3MSWOX-CctHLCOq.js → mindmap-definition-YA3MSWOX-CkpE64Kj.js} +1 -1
- package/dist/client/assets/mindmap-definition-YA3MSWOX-CkpE64Kj.js.br +0 -0
- package/dist/client/assets/mindmap-definition-YA3MSWOX-CkpE64Kj.js.gz +0 -0
- package/dist/client/assets/{passwordBootstrap-CUBwV9a2.js → passwordBootstrap-DwalkAEW.js} +1 -1
- package/dist/client/assets/{passwordBootstrap-CUBwV9a2.js.br → passwordBootstrap-DwalkAEW.js.br} +0 -0
- package/dist/client/assets/passwordBootstrap-DwalkAEW.js.gz +0 -0
- package/dist/client/assets/{pegDiagram-XKGWAZYB-BOxyckzz.js → pegDiagram-XKGWAZYB-DJUcJv5V.js} +1 -1
- package/dist/client/assets/pegDiagram-XKGWAZYB-DJUcJv5V.js.br +0 -0
- package/dist/client/assets/pegDiagram-XKGWAZYB-DJUcJv5V.js.gz +0 -0
- package/dist/client/assets/{pieDiagram-E7YTZNPT-hBT7FUaD.js → pieDiagram-E7YTZNPT-D3cB1Ka8.js} +1 -1
- package/dist/client/assets/pieDiagram-E7YTZNPT-D3cB1Ka8.js.br +0 -0
- package/dist/client/assets/pieDiagram-E7YTZNPT-D3cB1Ka8.js.gz +0 -0
- package/dist/client/assets/{quadrantDiagram-AXDQQJYC-C76EhRIn.js → quadrantDiagram-AXDQQJYC-CzNm8oC0.js} +1 -1
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-CzNm8oC0.js.br +0 -0
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-CzNm8oC0.js.gz +0 -0
- package/dist/client/assets/{railroadDiagram-O6MQD6OU-C0OkFlWF.js → railroadDiagram-O6MQD6OU-RrgUnRbK.js} +1 -1
- package/dist/client/assets/railroadDiagram-O6MQD6OU-RrgUnRbK.js.br +0 -0
- package/dist/client/assets/railroadDiagram-O6MQD6OU-RrgUnRbK.js.gz +0 -0
- package/dist/client/assets/{referenceLongPress-C2o_5tJ3.js → referenceLongPress-D_ZVnzDj.js} +1 -1
- package/dist/client/assets/referenceLongPress-D_ZVnzDj.js.br +0 -0
- package/dist/client/assets/referenceLongPress-D_ZVnzDj.js.gz +0 -0
- package/dist/client/assets/{requirementDiagram-BXWQKSXE-CMlSQQ_a.js → requirementDiagram-BXWQKSXE-BnUgwrOQ.js} +1 -1
- package/dist/client/assets/requirementDiagram-BXWQKSXE-BnUgwrOQ.js.br +0 -0
- package/dist/client/assets/requirementDiagram-BXWQKSXE-BnUgwrOQ.js.gz +0 -0
- package/dist/client/assets/{sankeyDiagram-P5KCCOFB-DbwnoS5J.js → sankeyDiagram-P5KCCOFB-CbsoBj05.js} +1 -1
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-CbsoBj05.js.br +0 -0
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-CbsoBj05.js.gz +0 -0
- package/dist/client/assets/{sequenceDiagram-WJ2MYXX4-MThPpc05.js → sequenceDiagram-WJ2MYXX4-BrY-_So-.js} +1 -1
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-BrY-_So-.js.br +0 -0
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-BrY-_So-.js.gz +0 -0
- package/dist/client/assets/{sizeCapture-INFHLROL-Dv47MfN9.js → sizeCapture-INFHLROL-DDiy82F_.js} +1 -1
- package/dist/client/assets/sizeCapture-INFHLROL-DDiy82F_.js.br +0 -0
- package/dist/client/assets/sizeCapture-INFHLROL-DDiy82F_.js.gz +0 -0
- package/dist/client/assets/{sparkles-C5GIf57F.js → sparkles-Dl-H6uxM.js} +1 -1
- package/dist/client/assets/{stateDiagram-D77RDMKH-BQMqsv45.js → stateDiagram-D77RDMKH-D3NJFpkP.js} +1 -1
- package/dist/client/assets/stateDiagram-D77RDMKH-D3NJFpkP.js.br +0 -0
- package/dist/client/assets/stateDiagram-D77RDMKH-D3NJFpkP.js.gz +0 -0
- package/dist/client/assets/stateDiagram-v2-MP3YSRHH-C6czsLUg.js +1 -0
- package/dist/client/assets/{swimlanes-42K2YHIH-DKZcb7w-.js → swimlanes-42K2YHIH-CdaSFDwF.js} +1 -1
- package/dist/client/assets/swimlanes-42K2YHIH-CdaSFDwF.js.br +0 -0
- package/dist/client/assets/{swimlanes-42K2YHIH-DKZcb7w-.js.gz → swimlanes-42K2YHIH-CdaSFDwF.js.gz} +0 -0
- package/dist/client/assets/swimlanesDiagram-VR7AAH4N-DYwcwm-Q.js +8 -0
- package/dist/client/assets/{timeline-definition-24CTP7MA-C1PZiVJx.js → timeline-definition-24CTP7MA-MZaskkec.js} +1 -1
- package/dist/client/assets/timeline-definition-24CTP7MA-MZaskkec.js.br +0 -0
- package/dist/client/assets/timeline-definition-24CTP7MA-MZaskkec.js.gz +0 -0
- package/dist/client/assets/{triangle-alert-BB655vyE.js → triangle-alert-CnVIEUVW.js} +1 -1
- package/dist/client/assets/{vennDiagram-4TSXK5OY-CxBRn0Fl.js → vennDiagram-4TSXK5OY-zyOkW8ff.js} +1 -1
- package/dist/client/assets/vennDiagram-4TSXK5OY-zyOkW8ff.js.br +0 -0
- package/dist/client/assets/vennDiagram-4TSXK5OY-zyOkW8ff.js.gz +0 -0
- package/dist/client/assets/{wardleyDiagram-VM6X3IG4-D57k3iEF.js → wardleyDiagram-VM6X3IG4-Bsa0_bdg.js} +1 -1
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-Bsa0_bdg.js.br +0 -0
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-Bsa0_bdg.js.gz +0 -0
- package/dist/client/assets/{xychartDiagram-S5SC5T6Z-rv8u8ZHA.js → xychartDiagram-S5SC5T6Z-a-LJDOd7.js} +1 -1
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-a-LJDOd7.js.br +0 -0
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-a-LJDOd7.js.gz +0 -0
- package/dist/client/index.html +1 -1
- package/dist/client/index.html.br +0 -0
- package/dist/client/index.html.gz +0 -0
- package/dist/client/sw.js +1 -1
- package/dist/client/sw.js.br +0 -0
- package/dist/client/sw.js.gz +0 -0
- package/dist/server/routes/filesystem.js +54 -19
- package/dist/server/routes/terminal.js +14 -1
- package/dist/server/utils/settings.js +22 -0
- package/package.json +1 -1
- package/runtime-manifest.json +3 -3
- package/dist/client/assets/App-B2nTzqxn.js.br +0 -0
- package/dist/client/assets/App-B2nTzqxn.js.gz +0 -0
- package/dist/client/assets/ChangeWalkthroughPanel-8XBpObo8.js.br +0 -0
- package/dist/client/assets/ChangeWalkthroughPanel-8XBpObo8.js.gz +0 -0
- package/dist/client/assets/DagPlayground-BrvWN-BF.js.br +0 -0
- package/dist/client/assets/DagPlayground-BrvWN-BF.js.gz +0 -0
- package/dist/client/assets/DiffLab-B_6noZdn.js.br +0 -0
- package/dist/client/assets/DiffLab-B_6noZdn.js.gz +0 -0
- package/dist/client/assets/DiffReview-BYnopIh6.js.br +0 -0
- package/dist/client/assets/DiffReview-BYnopIh6.js.gz +0 -0
- package/dist/client/assets/DiffReviewLab-DgGq28V3.js.br +0 -0
- package/dist/client/assets/DiffReviewLab-DgGq28V3.js.gz +0 -0
- package/dist/client/assets/DiffViewer-DBB2Nxe-.js.br +0 -0
- package/dist/client/assets/DiffViewer-DBB2Nxe-.js.gz +0 -0
- package/dist/client/assets/ModelPreview-cxnQVfjP.js.br +0 -0
- package/dist/client/assets/ModelPreview-cxnQVfjP.js.gz +0 -0
- package/dist/client/assets/RightSidebar-BrLZH29S.js +0 -1678
- package/dist/client/assets/RightSidebar-BrLZH29S.js.br +0 -0
- package/dist/client/assets/RightSidebar-BrLZH29S.js.gz +0 -0
- package/dist/client/assets/abnfDiagram-VCTEODGH-53wXKK7P.js.br +0 -0
- package/dist/client/assets/abnfDiagram-VCTEODGH-53wXKK7P.js.gz +0 -0
- package/dist/client/assets/app-C6U2Oauh.js.br +0 -0
- package/dist/client/assets/app-C6U2Oauh.js.gz +0 -0
- package/dist/client/assets/arc-4tt2sKMs.js.br +0 -0
- package/dist/client/assets/arc-4tt2sKMs.js.gz +0 -0
- package/dist/client/assets/architectureDiagram-5GKGNRK7-Clcm83eD.js.br +0 -0
- package/dist/client/assets/architectureDiagram-5GKGNRK7-Clcm83eD.js.gz +0 -0
- package/dist/client/assets/blockDiagram-I7D4REHJ-CfdVuYkG.js.br +0 -0
- package/dist/client/assets/blockDiagram-I7D4REHJ-CfdVuYkG.js.gz +0 -0
- package/dist/client/assets/c4Diagram-7LVT6UL2-BHtwHuZs.js.br +0 -0
- package/dist/client/assets/c4Diagram-7LVT6UL2-BHtwHuZs.js.gz +0 -0
- package/dist/client/assets/channel-B2oxQFp_.js +0 -1
- package/dist/client/assets/chunk-F27PBJKO-CrWbPzSA.js.br +0 -0
- package/dist/client/assets/chunk-F27PBJKO-CrWbPzSA.js.gz +0 -0
- package/dist/client/assets/chunk-IMKFNOWR-yohtKh6p.js.br +0 -0
- package/dist/client/assets/chunk-IMKFNOWR-yohtKh6p.js.gz +0 -0
- package/dist/client/assets/chunk-SVP7TREG-B-1tHXph.js.br +0 -0
- package/dist/client/assets/chunk-SVP7TREG-B-1tHXph.js.gz +0 -0
- package/dist/client/assets/chunk-TICWLB2K-DGO5T9qo.js.br +0 -0
- package/dist/client/assets/chunk-TICWLB2K-DGO5T9qo.js.gz +0 -0
- package/dist/client/assets/classDiagram-ZZMXUADV-CQOHLrnb.js +0 -1
- package/dist/client/assets/classDiagram-v2-VYDZK3BY-CQOHLrnb.js +0 -1
- package/dist/client/assets/cose-bilkent-JH36ORCC-Bph_dwwU.js.br +0 -0
- package/dist/client/assets/cose-bilkent-JH36ORCC-Bph_dwwU.js.gz +0 -0
- package/dist/client/assets/cynefin-OW5HDTMX-CSaZ7osN.js.br +0 -0
- package/dist/client/assets/cynefin-OW5HDTMX-CSaZ7osN.js.gz +0 -0
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-Jj0ksAR5.js.br +0 -0
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-Jj0ksAR5.js.gz +0 -0
- package/dist/client/assets/dagre-GXQ25YYZ-DqOb5Z8X.js.br +0 -0
- package/dist/client/assets/dagre-GXQ25YYZ-DqOb5Z8X.js.gz +0 -0
- package/dist/client/assets/diagram-S7CK7UJ4-BjVavRpU.js.br +0 -0
- package/dist/client/assets/diagram-S7CK7UJ4-BjVavRpU.js.gz +0 -0
- package/dist/client/assets/diagram-UQ7AKVKN-BUi_Iz8S.js.br +0 -0
- package/dist/client/assets/diagram-UQ7AKVKN-BUi_Iz8S.js.gz +0 -0
- package/dist/client/assets/diagram-VSXAHHWV-yGmUbeDV.js.br +0 -0
- package/dist/client/assets/diagram-VSXAHHWV-yGmUbeDV.js.gz +0 -0
- package/dist/client/assets/diagram-VX7I27RA-1wI9D0Xy.js.br +0 -0
- package/dist/client/assets/diagram-VX7I27RA-1wI9D0Xy.js.gz +0 -0
- package/dist/client/assets/diagram-Z3DM3KII-Ah9R4yGC.js.br +0 -0
- package/dist/client/assets/diagram-Z3DM3KII-Ah9R4yGC.js.gz +0 -0
- package/dist/client/assets/ebnfDiagram-PWID7BFC-Bc9e_6tX.js.br +0 -0
- package/dist/client/assets/ebnfDiagram-PWID7BFC-Bc9e_6tX.js.gz +0 -0
- package/dist/client/assets/erDiagram-RLTQ6QDP-CcDEtpQh.js.br +0 -0
- package/dist/client/assets/erDiagram-RLTQ6QDP-CcDEtpQh.js.gz +0 -0
- package/dist/client/assets/flowDiagram-HODETNUW-yJnnTJvd.js.br +0 -0
- package/dist/client/assets/ganttDiagram-EL5Y4UJY-DazfV-Pr.js.br +0 -0
- package/dist/client/assets/ganttDiagram-EL5Y4UJY-DazfV-Pr.js.gz +0 -0
- package/dist/client/assets/gestureArbiter-CIH61YPG.js.br +0 -0
- package/dist/client/assets/gestureArbiter-CIH61YPG.js.gz +0 -0
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-I_lUerNQ.js.br +0 -0
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-I_lUerNQ.js.gz +0 -0
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-CiefWGfu.js.br +0 -0
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-CiefWGfu.js.gz +0 -0
- package/dist/client/assets/journeyDiagram-3NMN7TZE-BHDqhmj7.js.br +0 -0
- package/dist/client/assets/journeyDiagram-3NMN7TZE-BHDqhmj7.js.gz +0 -0
- package/dist/client/assets/kanban-definition-UXKFOSKX-C5EVX9Si.js.br +0 -0
- package/dist/client/assets/kanban-definition-UXKFOSKX-C5EVX9Si.js.gz +0 -0
- package/dist/client/assets/layout-BsZ6KtNp.js.gz +0 -0
- package/dist/client/assets/linear-gI0rPpZO.js.br +0 -0
- package/dist/client/assets/linear-gI0rPpZO.js.gz +0 -0
- package/dist/client/assets/mermaid.core-DN5JSxkg.js.br +0 -0
- package/dist/client/assets/mermaid.core-DN5JSxkg.js.gz +0 -0
- package/dist/client/assets/mindmap-definition-YA3MSWOX-CctHLCOq.js.br +0 -0
- package/dist/client/assets/mindmap-definition-YA3MSWOX-CctHLCOq.js.gz +0 -0
- package/dist/client/assets/passwordBootstrap-CUBwV9a2.js.gz +0 -0
- package/dist/client/assets/pegDiagram-XKGWAZYB-BOxyckzz.js.br +0 -0
- package/dist/client/assets/pegDiagram-XKGWAZYB-BOxyckzz.js.gz +0 -0
- package/dist/client/assets/pieDiagram-E7YTZNPT-hBT7FUaD.js.br +0 -0
- package/dist/client/assets/pieDiagram-E7YTZNPT-hBT7FUaD.js.gz +0 -0
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-C76EhRIn.js.br +0 -0
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-C76EhRIn.js.gz +0 -0
- package/dist/client/assets/railroadDiagram-O6MQD6OU-C0OkFlWF.js.br +0 -0
- package/dist/client/assets/railroadDiagram-O6MQD6OU-C0OkFlWF.js.gz +0 -0
- package/dist/client/assets/referenceLongPress-C2o_5tJ3.js.br +0 -0
- package/dist/client/assets/referenceLongPress-C2o_5tJ3.js.gz +0 -0
- package/dist/client/assets/requirementDiagram-BXWQKSXE-CMlSQQ_a.js.br +0 -0
- package/dist/client/assets/requirementDiagram-BXWQKSXE-CMlSQQ_a.js.gz +0 -0
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-DbwnoS5J.js.br +0 -0
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-DbwnoS5J.js.gz +0 -0
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-MThPpc05.js.br +0 -0
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-MThPpc05.js.gz +0 -0
- package/dist/client/assets/sizeCapture-INFHLROL-Dv47MfN9.js.br +0 -0
- package/dist/client/assets/sizeCapture-INFHLROL-Dv47MfN9.js.gz +0 -0
- package/dist/client/assets/stateDiagram-D77RDMKH-BQMqsv45.js.br +0 -0
- package/dist/client/assets/stateDiagram-D77RDMKH-BQMqsv45.js.gz +0 -0
- package/dist/client/assets/stateDiagram-v2-MP3YSRHH-BRUElrwt.js +0 -1
- package/dist/client/assets/swimlanes-42K2YHIH-DKZcb7w-.js.br +0 -0
- package/dist/client/assets/swimlanesDiagram-VR7AAH4N-EvdYcr5I.js +0 -8
- package/dist/client/assets/timeline-definition-24CTP7MA-C1PZiVJx.js.br +0 -0
- package/dist/client/assets/timeline-definition-24CTP7MA-C1PZiVJx.js.gz +0 -0
- package/dist/client/assets/vennDiagram-4TSXK5OY-CxBRn0Fl.js.br +0 -0
- package/dist/client/assets/vennDiagram-4TSXK5OY-CxBRn0Fl.js.gz +0 -0
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-D57k3iEF.js.br +0 -0
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-D57k3iEF.js.gz +0 -0
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-rv8u8ZHA.js.br +0 -0
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-rv8u8ZHA.js.gz +0 -0
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/passwordBootstrap-
|
|
2
|
-
import{r as Wa,a as Qp,g as Iu}from"./react-XDCjal2T.js";import{b as F,r as eg,R as Ue}from"./dnd-BCFAPC0L.js";import{L as tg,l as rg}from"./terminal-C7X98Amf.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))n(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const i of s.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&n(i)}).observe(document,{childList:!0,subtree:!0});function r(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function n(o){if(o.ep)return;o.ep=!0;const s=r(o);fetch(o.href,s)}})();const ng="modulepreload",og=function(t){return"/"+t},Yc={},Kt=function(e,r,n){let o=Promise.resolve();if(r&&r.length>0){let c=function(l){return Promise.all(l.map(d=>Promise.resolve(d).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),a=i?.nonce||i?.getAttribute("nonce");o=c(r.map(l=>{if(l=og(l),l in Yc)return;Yc[l]=!0;const d=l.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${u}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":ng,d||(f.as="script"),f.crossOrigin="",f.href=l,a&&f.setAttribute("nonce",a),document.head.appendChild(f),d)return new Promise((h,g)=>{f.addEventListener("load",h),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${l}`)))})}))}function s(i){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=i,window.dispatchEvent(a),!a.defaultPrevented)throw i}return o.then(i=>{for(const a of i||[])a.status==="rejected"&&s(a.reason);return e().catch(s)})};var zs={exports:{}},dn={};var Zc;function sg(){if(Zc)return dn;Zc=1;var t=Wa(),e=Symbol.for("react.element"),r=Symbol.for("react.fragment"),n=Object.prototype.hasOwnProperty,o=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function i(a,c,l){var d,u={},f=null,h=null;l!==void 0&&(f=""+l),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(h=c.ref);for(d in c)n.call(c,d)&&!s.hasOwnProperty(d)&&(u[d]=c[d]);if(a&&a.defaultProps)for(d in c=a.defaultProps,c)u[d]===void 0&&(u[d]=c[d]);return{$$typeof:e,type:a,key:f,ref:h,props:u,_owner:o.current}}return dn.Fragment=r,dn.jsx=i,dn.jsxs=i,dn}var Jc;function ig(){return Jc||(Jc=1,zs.exports=sg()),zs.exports}var p=ig();const sr="termdock-secure-target-v1",Ga="termdock-secure-entry-v1",ag=new Set([sr,Ga,"termdock-color-theme","termdock:locale","termdock.federation.connections.v1"]),lo=typeof Storage>"u"?void 0:Storage.prototype.getItem,Vs=typeof Storage>"u"?void 0:Storage.prototype.setItem,Qc="termdock-secure-legacy-owner",Hn=typeof window<"u"&&window.parent!==window&&location.pathname==="/workspace.html";function cg(){if(typeof window>"u")return null;try{if(Hn){const e=new URLSearchParams(location.search).get("termdock-workspace"),r=JSON.parse(localStorage.getItem("termdock.federation.connections.v1")||"[]"),n=Array.isArray(r)?r.find(o=>o?.targetPeerId===e):void 0;return n&&typeof n.url=="string"&&typeof n.targetPeerId=="string"?{...n,serviceName:n.label||n.serviceName}:null}const t=JSON.parse(sessionStorage.getItem(sr)??localStorage.getItem(sr)??"null");return t&&typeof t.url=="string"&&typeof t.targetPeerId=="string"?t:null}catch{return null}}let vs=cg();const _r=vs?.targetPeerId??"unpaired";function Dr(){return vs}function Cu(t){if(vs=t,Hn)return;const e=JSON.stringify(t);sessionStorage.setItem(sr,e),localStorage.setItem(sr,e)}function lg(){vs=null,!Hn&&(localStorage.removeItem(sr),sessionStorage.removeItem(sr),localStorage.removeItem(Ga))}function _n(t,e=_r){return ag.has(t)||t.startsWith("termdock-secure-")?t:`termdock-service:${e}:${t}`}function dg(t){if(!(!lo||!Vs))try{if(lo.call(localStorage,Qc))return;Vs.call(localStorage,Qc,t);for(const r of[localStorage,sessionStorage]){const n=Array.from({length:r.length},(o,s)=>r.key(s)).filter(o=>!!o);for(const o of n){if(o.startsWith("termdock-service:")||_n(o,t)===o)continue;const s=_n(o,t),i=lo.call(r,o);i!==null&&lo.call(r,s)===null&&Vs.call(r,s,i)}}}catch{}}let el=!1;function ug(){if(el||typeof Storage>"u")return;el=!0;const t=Storage.prototype.getItem,e=Storage.prototype.setItem,r=Storage.prototype.removeItem;Storage.prototype.getItem=function(n){return t.call(this,_n(String(n)))},Storage.prototype.setItem=function(n,o){e.call(this,_n(String(n)),o)},Storage.prototype.removeItem=function(n){r.call(this,_n(String(n)))}}ug();const tl={pending:0,failed:1,expired:1,delivered:2,read:3},uo=32768,Ho="remote:";function Ye(t,e){return e.startsWith(Ho)?e:`${Ho}${encodeURIComponent(t)}:${encodeURIComponent(e)}`}function qe(t){if(!t.startsWith(Ho))return null;const e=t.slice(Ho.length).split(":");if(e.length!==2)return null;try{return{origin:decodeURIComponent(e[0]),id:decodeURIComponent(e[1])}}catch{return null}}function Ws(t,e){const r=qe(e);return r?.origin===t?r.id:e}function fo(t,e){return{...t,fromSessionId:t.fromSessionId?e(t.fromSessionId):null,toSessionId:e(t.toSessionId)}}function Gs(t,e){if(!t)return;const r=Object.fromEntries(Object.entries(t).map(([n,o])=>[e(n),o]));return Object.keys(r).length?r:void 0}class fg{constructor(e){this.services=e}services;snapshots=new Map;reachable=new Set;groups=new Map;messages=new Map;sessions=new Map;diagnostics=new Map;serviceErrors=new Map;inFlight=null;catalogInFlight=null;async refresh(){return this.inFlight?this.inFlight:(this.inFlight=this.synchronize().finally(()=>{this.inFlight=null}),this.inFlight)}async refreshCatalog(){return this.catalogInFlight?this.catalogInFlight:(this.catalogInFlight=this.discover().finally(()=>{this.catalogInFlight=null}),this.catalogInFlight)}async discover(){const e=this.services();this.serviceErrors.clear();const r=await Promise.all(e.map(async n=>{try{const o=await n.request("/collaboration-federation");if(!Array.isArray(o.groups)||!Array.isArray(o.sessions)||!Array.isArray(o.messages))throw new Error("协作目录响应无效,请更新服务");return{service:n,data:o}}catch(o){return this.serviceErrors.set(n.origin,o instanceof Error?o.message.slice(0,300):"协作目录请求失败"),null}}));this.reachable.clear();for(const n of r){if(!n)continue;const{service:o,data:s}=n;for(const[i,a]of Object.entries(s.transportDiagnostics??{}))(!this.diagnostics.has(i)||a.checked_at>this.diagnostics.get(i).checked_at)&&this.diagnostics.set(i,a);this.reachable.add(o.origin),this.snapshots.set(o.origin,s);for(const i of s.groups){const a={...i,sessionIds:i.sessionIds.map(l=>Ye(o.origin,l)),roles:Gs(i.roles,l=>Ye(o.origin,l))},c=this.groups.get(i.id);(!c||a.updatedAt>c.updatedAt)&&this.groups.set(i.id,a)}for(const i of s.messages)this.mergeMessage(fo(i,a=>Ye(o.origin,a)))}this.sessions.clear();for(const n of this.groups.values())for(const o of n.remoteSessions??[])this.sessions.set(o.sessionId,{...o,serviceConnected:!1,status:"offline",serviceCheckedAt:Date.now()});for(const[n,o]of this.snapshots){const s=this.reachable.has(n);for(const i of o.sessions){const a=Ye(n,i.sessionId);this.sessions.set(a,{...i,sessionId:a,serviceOrigin:n,serviceLabel:e.find(c=>c.origin===n)?.label??n,serviceConnected:s,serviceCheckedAt:Date.now(),status:s?i.status:"offline"})}}}async synchronize(){await this.refreshCatalog();const e=this.services();for(const r of this.messages.values()){const n=qe(r.toSessionId)?.origin;if(r.status==="pending"&&n&&!this.reachable.has(n)){const o=this.diagnostics.get(r.id);this.diagnostics.set(r.id,{...o,relay_online:!0,peer_reachable:!1,attempt_count:o?.attempt_count??0,next_retry_at:Date.now()+2e3,last_error:"PEER_UNREACHABLE",checked_at:Date.now()})}}await Promise.all(e.filter(r=>this.reachable.has(r.origin)).map(async r=>{for(const n of this.groups.values())if(!(!this.snapshots.get(r.origin)?.groups.some(s=>s.id===n.id)&&!n.sessionIds.some(s=>qe(s)?.origin===r.origin)))try{await this.push(r,n)}catch{this.reachable.delete(r.origin)}})),await Promise.all(e.filter(r=>this.reachable.has(r.origin)).map(async r=>{if(!((this.snapshots.get(r.origin)?.protocolVersion??1)<2))for(const n of this.groups.values()){if(n.deleted||!n.sessionIds.some(s=>qe(s)?.origin===r.origin))continue;const o=[...this.diagnostics].filter(([s])=>this.messages.get(s)?.groupId===n.id).map(([s,i])=>({message_id:s,diagnostic:i,...this.messages.get(s)?.status==="failed"?{failure_reason:this.messages.get(s)?.failureReason}:{}}));if(o.length)try{await r.request("/collaboration-federation","POST",{group:this.groupForService(n,r.origin),messages:[],transport:o})}catch{}}}))}mergeMessage(e){const r=this.messages.get(e.id),n=tl;if((!r||n[e.status]>n[r.status])&&this.messages.set(e.id,e),this.messages.size>2e3){const o=[...this.messages.values()].find(s=>s.status!=="pending"&&s.status!=="failed");o&&this.messages.delete(o.id)}}groupForService(e,r){const n=e.sessionIds.filter(o=>qe(o)?.origin!==r).map(o=>{const s=qe(o),i=this.sessions.get(o);return{sessionId:o,name:i?.name??s.id,cwd:i?.cwd??"",status:i?.status??"offline",capability:i?.capability??"",currentTask:i?.currentTask??"",updatedAt:i?.updatedAt??0,agent:i?.agent??null,backendSessionId:null,agentNativeSessionId:null,serviceOrigin:s.origin,serviceLabel:i?.serviceLabel??s.origin,serviceConnected:this.reachable.has(s.origin),serviceCheckedAt:Date.now()}});return{...e,sessionIds:e.sessionIds.map(o=>Ws(r,o)),remoteSessions:n,roles:Gs(e.roles,o=>Ws(r,o))}}async push(e,r){const n=tl,o=new Map((this.snapshots.get(e.origin)?.messages??[]).map(i=>[i.id,i])),s=[...this.messages.values()].filter(i=>i.groupId===r.id&&(!o.has(i.id)||n[i.status]>n[o.get(i.id).status])).map(i=>fo(i,a=>Ws(e.origin,a)));if(!s.length){await e.request("/collaboration-federation","POST",{group:this.groupForService(r,e.origin),messages:[]});return}for(const i of s){const a=this.messages.get(i.id),c=qe(a.toSessionId)?.origin===e.origin,l=this.diagnostics.get(i.id);if(c&&l?.next_retry_at&&l.next_retry_at>Date.now()&&l.last_error!=="PEER_UNREACHABLE")continue;const d={relay_online:!0,peer_reachable:!0,attempt_count:(l?.attempt_count??0)+(c?1:0),next_retry_at:null,last_error:null,checked_at:Date.now(),fragments_sent:0,fragments_total:0},u=this.snapshots.get(e.origin)?.protocolVersion??1;if(u<2&&(String(i.content??"").length>2e4||i.responseKind||i.task||i.metadata||i.expiresAt||i.status==="failed"||i.status==="expired")){c&&(this.messages.set(i.id,{...a,status:"failed",failureReason:"PEER_UPGRADE_REQUIRED"}),this.diagnostics.set(i.id,{...d,last_error:"PEER_UPGRADE_REQUIRED"}));continue}try{const f=new TextEncoder().encode(JSON.stringify(i));if(u>=2&&f.length>uo&&!o.has(i.id)){const h=Math.ceil(f.length/uo),g=Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",f)),m=>m.toString(16).padStart(2,"0")).join("");d.fragments_total=h;for(let m=0;m<h;m++){const y=await e.request("/collaboration-federation","POST",{group:this.groupForService(r,e.origin),messages:[],fragments:[{message_id:i.id,group_id:r.id,index:m,total:h,sha256:g,data:btoa(String.fromCharCode(...f.subarray(m*uo,(m+1)*uo)))}]}),w=y.fragmentReceipts?.find(I=>I.message_id===i.id);if(!w||m===h-1&&!w.complete)throw new Error("FRAGMENT_ACK_MISSING");d.fragments_sent=w.received;for(const I of y.messages??[])this.mergeMessage(fo(I,v=>Ye(e.origin,v)));if(c){this.diagnostics.set(i.id,{...d,checked_at:Date.now()});const I=this.services().find(v=>v.origin===qe(a.fromSessionId??"")?.origin);I&&I.origin!==e.origin&&(this.snapshots.get(I.origin)?.protocolVersion??1)>=2&&await I.request("/collaboration-federation","POST",{group:this.groupForService(r,I.origin),messages:[],transport:[{message_id:i.id,diagnostic:d}]}).catch(()=>{})}}}else{const h=await e.request("/collaboration-federation","POST",{group:this.groupForService(r,e.origin),messages:[i]});if(!(h.messages??[]).some(g=>g.id===i.id))throw new Error("PEER_REJECTED_MESSAGE");for(const g of h.messages??[])this.mergeMessage(fo(g,m=>Ye(e.origin,m)))}c&&this.diagnostics.set(i.id,{...d,checked_at:Date.now()})}catch(f){c&&this.diagnostics.set(i.id,{...d,checked_at:Date.now(),peer_reachable:null,last_error:f instanceof Error?f.message.slice(0,300):"RELAY_REQUEST_FAILED",next_retry_at:Date.now()+Math.min(3e4,1e3*2**Math.min(d.attempt_count,5))})}}}async peers(e){if(!this.services().some(r=>r.origin===e))throw new Error("当前服务未连接");return await this.refreshCatalog(),{protocolVersion:2,origin:e,sessions:[...this.sessions.values()].filter(r=>qe(r.sessionId)?.origin!==e),services:[...this.snapshots.keys(),...this.services().map(r=>r.origin)].filter((r,n,o)=>o.indexOf(r)===n).map(r=>({origin:r,label:this.services().find(n=>n.origin===r)?.label??r,connected:this.reachable.has(r),error:this.serviceErrors.get(r)}))}}async list(e){const r=this.services().find(s=>s.origin===e);if(!r)throw new Error("当前服务未连接");const[n,o]=await Promise.all([this.peers(e),r.request("/collaboration-groups")]);return{groups:o.groups,sessions:[...n.sessions,...o.sessions]}}async save(e,r){await this.refreshCatalog();const n=this.services().find(u=>u.origin===e);if(!n)throw new Error("当前服务未连接");const o=await n.request("/collaboration-groups"),s=r.id?o.groups.find(u=>u.id===r.id):void 0;if(r.id&&!s)throw new Error("协作组已删除,请刷新列表");if(s&&r.expectedUpdatedAt!==void 0&&r.expectedUpdatedAt!==s.updatedAt)throw new Error("协作组已被修改,请重新打开成员管理后再保存");for(const u of this.sessions.keys())qe(u)?.origin===e&&this.sessions.delete(u);for(const u of o.sessions){const f=Ye(e,u.sessionId);this.sessions.set(f,{...u,sessionId:f,serviceOrigin:e,serviceLabel:n.label,serviceConnected:!0})}if(!r.id?.startsWith("cross-")&&!r.sessionIds.some(u=>qe(u)))return n.request("/collaboration-groups","POST",r);if(!this.reachable.has(e))throw new Error("当前服务需要升级 Termdock 后才能跨服务组队");const i=[...new Set(r.sessionIds.map(u=>Ye(e,u)))],a=new Set(s?.sessionIds.map(u=>Ye(e,u))??[]);if(!r.name?.trim()||i.length<2||i.some(u=>!a.has(u)&&(!this.sessions.has(u)||!this.reachable.has(qe(u).origin))))throw new Error("所选成员已变化或服务不可达,请刷新后重新选择;尚未保存任何修改");const c=s?.federated?{...s,sessionIds:s.sessionIds.map(u=>Ye(e,u))}:void 0,l=Gs(s?.roles,u=>Ye(e,u)),d={id:c?.id??`cross-${crypto.randomUUID()}`,name:r.name.trim(),sessionIds:i,...l?{roles:Object.fromEntries(Object.entries(l).filter(([u])=>i.includes(u)))}:{},createdAt:c?.createdAt??Date.now(),updatedAt:Math.max(Date.now(),(c?.updatedAt??0)+1),federated:!0};if(s&&!s.federated){if(o.capabilities?.groupPromotion!==1)throw new Error("当前服务需要升级后才能将已有组转换为跨服务组;原组和记录均未修改");const u=await n.request(`/collaboration-groups/${encodeURIComponent(s.id)}/promote`,"POST",{group:this.groupForService(d,e),expectedUpdatedAt:r.expectedUpdatedAt??s.updatedAt});d.updatedAt=u.group.updatedAt,d.createdAt=u.group.createdAt}else await n.request("/collaboration-federation","POST",{group:this.groupForService(d,e),messages:[],...c?{expectedUpdatedAt:r.expectedUpdatedAt??c.updatedAt}:{}});return this.groups.set(d.id,d),{group:this.groupForService(d,e)}}async remove(e,r){const n=this.services().find(o=>o.origin===e);if(!n)throw new Error("当前服务未连接");await n.request(`/collaboration-groups/${encodeURIComponent(r)}`,"DELETE")}}const xs="termdock.federation.connections.v1",Qi="termdock:services-changed",Xa="termdock-secure-removed-services",qo=t=>[t.id,t.targetPeerId,t.serviceOrigin||t.url].filter(e=>!!e);function Ya(){try{const t=JSON.parse(localStorage.getItem(Xa)||"[]");return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}catch{return[]}}function Le(t){const e=t.trim();if(!e)throw new Error("请输入服务地址。");const r=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(e)?e:`https://${e}`);r.protocol==="wss:"&&(r.protocol="https:"),r.protocol==="ws:"&&(r.protocol="http:");const n=["localhost","127.0.0.1","[::1]"].includes(r.hostname);if(!["https:","http:"].includes(r.protocol)||r.protocol==="http:"&&!n)throw new Error("请使用 HTTPS 服务地址。");if(r.username||r.password||r.search||r.hash||!["/","/api/federation/secure"].includes(r.pathname))throw new Error("请输入服务首页地址,不要包含账号或额外参数。");return r.origin}function Ss(t){if(!t||typeof t!="object")return;const e=t;if(typeof e.url=="string")try{const r=Le(e.url),n=typeof e.targetPeerId=="string"&&e.targetPeerId?e.targetPeerId:void 0,o=(typeof e.label=="string"?e.label:typeof e.serviceName=="string"?e.serviceName:"").trim().slice(0,120)||new URL(r).host;return{id:typeof e.id=="string"&&e.id?e.id:n||r,url:r,label:o,...n?{targetPeerId:n}:{},...typeof e.serviceOrigin=="string"?{serviceOrigin:Le(e.serviceOrigin)}:{},...typeof e.entryServiceId=="string"&&e.entryServiceId?{entryServiceId:e.entryServiceId}:{},...Array.isArray(e.routes)?{routes:e.routes.slice(0,4).flatMap(s=>{try{return s&&typeof s.targetPeerId=="string"&&s.targetPeerId?[{url:Le(s.url),targetPeerId:s.targetPeerId}]:[]}catch{return[]}})}:{}}}catch{return}}function wt(t,e){return t.targetPeerId&&e.targetPeerId?t.targetPeerId===e.targetPeerId:(t.serviceOrigin||t.url)===(e.serviceOrigin||e.url)}function Ru(t){const e=[];for(const r of t){const n=e.findIndex(o=>wt(o,r));n<0?e.push(r):e[n]={...e[n],...r,id:e[n].id}}return e}function Zn(){return typeof window>"u"?void 0:window.termdockDesktop}function Ht(){try{const t=JSON.parse(localStorage.getItem(xs)||"[]");return Array.isArray(t)?Ru(t.map(Ss).filter(e=>!!e)):[]}catch{return[]}}function Tu(t){localStorage.setItem(xs,JSON.stringify(t.map(e=>({...e,serviceName:e.label})))),window.dispatchEvent(new Event(Qi))}let un;async function We(){const t=Zn();if(!t?.serviceConnections||!t.saveServiceConnection)return Ht();if(un)return un;un=(async()=>{let e=await t.serviceConnections();const r=Ht();for(const n of r)e.some(o=>wt(o,n))||(e=await(t.importServiceConnection||t.saveServiceConnection)(n));return r.length&&localStorage.removeItem(xs),e})();try{return await un}finally{un=void 0}}async function Et(t){const e=Ss(t);if(!e)throw new Error("服务地址无效。");const r=Zn();if(r?.saveServiceConnection)return r.saveServiceConnection(e);const n=Ht(),o=n.find(a=>a.id===e.id||wt(a,e)),s=new Set([...qo(e),...o?qo(o):[]]);localStorage.setItem(Xa,JSON.stringify(Ya().filter(a=>!s.has(a))));const i=Ru([...n.filter(a=>a!==o),{...o,...e,id:o?.id||e.id}]);return Tu(i),i}async function hg(t){const e=Ss(t);if(!e)throw new Error("服务地址无效。");const r=Zn();if(r?.importServiceConnection)return r.importServiceConnection(e);if(r?.serviceConnections){const n=await r.serviceConnections();return n.some(o=>wt(o,e))?Et(e):n}return qo(e).some(n=>Ya().includes(n))?Ht():Et(e)}async function pg(t){const e=Zn();if(e?.removeServiceConnection)return e.removeServiceConnection(t);const r=Ht(),n=r.find(s=>s.id===t);n&&localStorage.setItem(Xa,JSON.stringify([...new Set([...Ya(),...qo(n)])].slice(-768)));const o=r.filter(s=>s.id!==t);return Tu(o),o}function Pu(t){const e=n=>{(n.key===xs||n.key===null)&&t()};window.addEventListener(Qi,t),window.addEventListener("storage",e);const r=Zn()?.onServiceConnections?.(t);return()=>{window.removeEventListener(Qi,t),window.removeEventListener("storage",e),r?.()}}class gg extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}let mg=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},tt=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};class Nu extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class Lu extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}}class wg extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class yg extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class Es extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}const Bu=Symbol.for("@libp2p/peer-id");function bg(t){return typeof t?.handleEvent=="function"}function vg(t){return t===!0||t===!1}function xg(t){return vg(t)?t:t?.capture??!1}function ea(t){const e={capture:xg(t),once:!!t?.once};return t?.passive!=null&&(e.passive=t?.passive),t?.signal!=null&&(e.signal=t?.signal),e}function rl(t,e){return ea(t).capture===ea(e).capture}class Sg extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){const o=ea(n);if(o?.signal?.aborted===!0)return;const s=l=>{o.once&&this.removeEventListener(e,r,o),bg(r)?r.handleEvent(l):r(l)};let i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(l=>l.callback!==r?!1:rl(l.options,o)))return;super.addEventListener(e,s,o);const c=()=>{this.removeEventListener(e,r,o)};o.signal?.addEventListener("abort",c),i.push({callback:r,wrapper:s,options:o,onAbort:c})}removeEventListener(e,r,n){const o=this.#e.get(e);if(o==null){super.removeEventListener(e,r??null,n);return}this.#e.set(e,o.filter(s=>s.callback===r&&rl(s.options,n)?(super.removeEventListener(e,s.wrapper,n),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}}const Eg=Symbol.for("@libp2p/service-capabilities");function Ag(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function As(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function kg(t){return new TextEncoder().encode(t)}function Ig(t){return new TextDecoder().decode(t)}function Cg(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var m=0,y=0,w=0,I=g.length;w!==I&&g[w]===0;)w++,m++;for(var v=(I-w)*d+1>>>0,A=new Uint8Array(v);w!==I;){for(var B=g[w],T=0,N=v-1;(B!==0||T<y)&&N!==-1;N--,T++)B+=256*A[N]>>>0,A[N]=B%a>>>0,B=B/a>>>0;if(B!==0)throw new Error("Non-zero carry");y=T,w++}for(var k=v-y;k!==v&&A[k]===0;)k++;for(var x=c.repeat(m);k<v;++k)x+=t.charAt(A[k]);return x}function f(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var m=0;if(g[m]!==" "){for(var y=0,w=0;g[m]===c;)y++,m++;for(var I=(g.length-m)*l+1>>>0,v=new Uint8Array(I);g[m];){var A=r[g.charCodeAt(m)];if(A===255)return;for(var B=0,T=I-1;(A!==0||B<w)&&T!==-1;T--,B++)A+=a*v[T]>>>0,v[T]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");w=B,m++}if(g[m]!==" "){for(var N=I-w;N!==I&&v[N]===0;)N++;for(var k=new Uint8Array(y+(I-N)),x=y;N!==I;)k[x++]=v[N++];return k}}}function h(g){var m=f(g);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:h}}var Rg=Cg,Tg=Rg;class Pg{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Ng{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;const o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return _u(this,e)}}class Lg{decoders;constructor(e){this.decoders=e}or(e){return _u(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function _u(t,e){return new Lg({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class Bg{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Pg(e,r,n),this.decoder=new Ng(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function ks({name:t,prefix:e,encode:r,decode:n}){return new Bg(t,e,r,n)}function Jn({name:t,prefix:e,alphabet:r}){const{encode:n,decode:o}=Tg(r,t);return ks({prefix:e,name:t,encode:n,decode:s=>As(o(s))})}function _g(t,e,r,n){let o=t.length;for(;t[o-1]==="=";)--o;const s=new Uint8Array(o*r/8|0);let i=0,a=0,c=0;for(let l=0;l<o;++l){const d=e[t[l]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|d,i+=r,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Dg(t,e,r){const n=e[e.length-1]==="=",o=(1<<r)-1;let s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function Og(t){const e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function Ae({name:t,prefix:e,bitsPerChar:r,alphabet:n}){const o=Og(n);return ks({prefix:e,name:t,encode(s){return Dg(s,n,r)},decode(s){return _g(s,o,r,t)}})}const Ne=Jn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Fg=Jn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Mg=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Ne,base58flickr:Fg},Symbol.toStringTag,{value:"Module"})),Dn=Ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),jg=Ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ug=Ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),$g=Ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Hg=Ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),qg=Ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Kg=Ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zg=Ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Vg=Ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Wg=Object.freeze(Object.defineProperty({__proto__:null,base32:Dn,base32hex:Hg,base32hexpad:Kg,base32hexpadupper:zg,base32hexupper:qg,base32pad:Ug,base32padupper:$g,base32upper:jg,base32z:Vg},Symbol.toStringTag,{value:"Module"})),_o=Jn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Gg=Jn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Xg=Object.freeze(Object.defineProperty({__proto__:null,base36:_o,base36upper:Gg},Symbol.toStringTag,{value:"Module"}));var Yg=Du,nl=128,Zg=-128,Jg=Math.pow(2,31);function Du(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Jg;)e[r++]=t&255|nl,t/=128;for(;t&Zg;)e[r++]=t&255|nl,t>>>=7;return e[r]=t|0,Du.bytes=r-n+1,e}var Qg=ta,em=128,ol=127;function ta(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw ta.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&ol)<<o:(i&ol)*Math.pow(2,o),o+=7}while(i>=em);return ta.bytes=s-n,r}var tm=Math.pow(2,7),rm=Math.pow(2,14),nm=Math.pow(2,21),om=Math.pow(2,28),sm=Math.pow(2,35),im=Math.pow(2,42),am=Math.pow(2,49),cm=Math.pow(2,56),lm=Math.pow(2,63),dm=function(t){return t<tm?1:t<rm?2:t<nm?3:t<om?4:t<sm?5:t<im?6:t<am?7:t<cm?8:t<lm?9:10},um={encode:Yg,decode:Qg,encodingLength:dm},Ko=um;function ra(t,e=0){return[Ko.decode(t,e),Ko.decode.bytes]}function zo(t,e,r=0){return Ko.encode(t,e,r),e}function Vo(t){return Ko.encodingLength(t)}function Qn(t,e){const r=e.byteLength,n=Vo(t),o=n+Vo(r),s=new Uint8Array(o+r);return zo(t,s,0),zo(r,s,n),s.set(e,o),new Za(t,r,e,s)}function Ou(t){const e=As(t),[r,n]=ra(e),[o,s]=ra(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Za(r,o,i,e)}function fm(t,e){if(t===e)return!0;{const r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Ag(t.bytes,r.bytes)}}class Za{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}}function sl(t,e){const{bytes:r,version:n}=t;return n===0?pm(r,na(t),e??Ne.encoder):gm(r,na(t),e??Dn.encoder)}const il=new WeakMap;function na(t){const e=il.get(t);if(e==null){const r=new Map;return il.set(t,r),r}return e}class ce{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:e,multihash:r}=this;if(e!==fn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==mm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ce.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:e,digest:r}=this.multihash,n=Qn(e,r);return ce.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return ce.equals(this,e)}static equals(e,r){const n=r;return n!=null&&e.code===n.code&&e.version===n.version&&fm(e.multihash,n.multihash)}toString(e){return sl(this,e)}toJSON(){return{"/":sl(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;const r=e;if(r instanceof ce)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){const{version:n,code:o,multihash:s,bytes:i}=r;return new ce(n,o,s,i??al(n,o,s.bytes))}else if(r[wm]===!0){const{version:n,multihash:o,code:s}=r,i=Ou(o);return ce.create(n,s,i)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==fn)throw new Error(`Version 0 CID must use dag-pb (code: ${fn}) block encoding`);return new ce(e,r,n,n.bytes)}case 1:{const o=al(e,r,n.bytes);return new ce(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return ce.create(0,fn,e)}static createV1(e,r){return ce.create(1,e,r)}static decode(e){const[r,n]=ce.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){const r=ce.inspectBytes(e),n=r.size-r.multihashSize,o=As(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");const s=o.subarray(r.multihashSize-r.digestSize),i=new Za(r.multihashCode,r.digestSize,s,o);return[r.version===0?ce.createV0(i):ce.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0;const n=()=>{const[u,f]=ra(e.subarray(r));return r+=f,u};let o=n(),s=fn;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);const i=r,a=n(),c=n(),l=r+c,d=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:l}}static parse(e,r){const[n,o]=hm(e,r),s=ce.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return na(s).set(n,e),s}}function hm(t,e){switch(t[0]){case"Q":{const r=e??Ne;return[Ne.prefix,r.decode(`${Ne.prefix}${t}`)]}case Ne.prefix:{const r=e??Ne;return[Ne.prefix,r.decode(t)]}case Dn.prefix:{const r=e??Dn;return[Dn.prefix,r.decode(t)]}case _o.prefix:{const r=e??_o;return[_o.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function pm(t,e,r){const{prefix:n}=r;if(n!==Ne.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const o=e.get(n);if(o==null){const s=r.encode(t).slice(1);return e.set(n,s),s}else return o}function gm(t,e,r){const{prefix:n}=r,o=e.get(n);if(o==null){const s=r.encode(t);return e.set(n,s),s}else return o}const fn=112,mm=18;function al(t,e,r){const n=Vo(t),o=n+Vo(e),s=new Uint8Array(o+r.byteLength);return zo(t,s,0),zo(e,s,n),s.set(r,o),s}const wm=Symbol.for("@ipld/js-cid/CID"),Fu=0,ym="identity",Mu=As;function bm(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return Qn(Fu,Mu(t))}const eo={code:Fu,name:ym,encode:Mu,digest:bm};function rt(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function Be(t=0){return new Uint8Array(t)}function At(t=0){return new Uint8Array(t)}function oa(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));const r=At(e);let n=0;for(const o of t)r.set(o,n),n+=o.length;return r}const ju=Symbol.for("@achingbrain/uint8arraylist");function cl(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(const n of t){const o=r+n.byteLength;if(e<o)return{buf:n,index:e-r};r=o}throw new RangeError("index is out of bounds")}function ho(t){return!!t?.[ju]}class re{bufs;length;[ju]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let r=0;for(const n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(ho(n)){r+=n.byteLength;for(const o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...e){this.prependAll(e)}prependAll(e){let r=0;for(const n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(ho(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(e){const r=cl(this.bufs,e);return r.buf[r.index]}set(e,r){const n=cl(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(ho(e))for(let n=0;n<e.length;n++)this.set(r+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,r){const{bufs:n,length:o}=this._subList(e,r);return oa(n,o)}subarray(e,r){const{bufs:n,length:o}=this._subList(e,r);return n.length===1?n[0]:oa(n,o)}sublist(e,r){const{bufs:n,length:o}=this._subList(e,r),s=new re;return s.length=o,s.bufs=n,s}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};const n=[];let o=0;for(let s=0;s<this.bufs.length;s++){const i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;const l=e>=a&&e<c,d=r>a&&r<=c;if(l&&d){if(e===a&&r===c){n.push(i);break}const u=e-a;n.push(i.subarray(u,u+(r-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(d){if(r===c){n.push(i);break}n.push(i.subarray(0,r-a));break}n.push(i)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!ho(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const n=e instanceof Uint8Array?e:e.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.length===0)return r>this.length?this.length:r;const o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");const s=256,i=new Int32Array(s);for(let u=0;u<s;u++)i[u]=-1;for(let u=0;u<o;u++)i[n[u]]=u;const a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1;let d;for(let u=r;u<=c;u+=d){d=0;for(let f=l;f>=0;f--){const h=this.get(u+f);if(n[f]!==h){d=Math.max(1,f-a[h]);break}}if(d===0)return u}return-1}getInt8(e){const r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){const n=At(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){const n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){const o=Be(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,e)}getInt32(e,r){const n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){const o=Be(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,e)}getBigInt64(e,r){const n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){const o=Be(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,e)}getUint8(e){const r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){const n=At(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){const n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){const o=Be(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,e)}getUint32(e,r){const n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){const o=Be(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,e)}getBigUint64(e,r){const n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){const o=Be(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,e)}getFloat32(e,r){const n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){const o=Be(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,e)}getFloat64(e,r){const n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){const o=Be(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof re)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!rt(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){const n=new re;return n.bufs=e,r==null&&(r=e.reduce((o,s)=>o+s.byteLength,0)),n.length=r,n}}const vm=Jn({prefix:"9",name:"base10",alphabet:"0123456789"}),xm=Object.freeze(Object.defineProperty({__proto__:null,base10:vm},Symbol.toStringTag,{value:"Module"})),Sm=Ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Em=Ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Am=Object.freeze(Object.defineProperty({__proto__:null,base16:Sm,base16upper:Em},Symbol.toStringTag,{value:"Module"})),km=Ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Im=Object.freeze(Object.defineProperty({__proto__:null,base2:km},Symbol.toStringTag,{value:"Module"})),Uu=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Cm=Uu.reduce((t,e,r)=>(t[r]=e,t),[]),Rm=Uu.reduce((t,e,r)=>{const n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function Tm(t){return t.reduce((e,r)=>(e+=Cm[r],e),"")}function Pm(t){const e=[];for(const r of t){const n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);const o=Rm[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}const Nm=ks({prefix:"🚀",name:"base256emoji",encode:Tm,decode:Pm}),Lm=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:Nm},Symbol.toStringTag,{value:"Module"})),Bm=Ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),_m=Ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Dm=Ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Om=Ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Fm=Object.freeze(Object.defineProperty({__proto__:null,base64:Bm,base64pad:_m,base64url:Dm,base64urlpad:Om},Symbol.toStringTag,{value:"Module"})),Mm=Ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),jm=Object.freeze(Object.defineProperty({__proto__:null,base8:Mm},Symbol.toStringTag,{value:"Module"})),Um=ks({prefix:"\0",name:"identity",encode:t=>Ig(t),decode:t=>kg(t)}),$m=Object.freeze(Object.defineProperty({__proto__:null,identity:Um},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const Hm=20;function qm({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new Km(t,e,r,n,o)}class Km{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??Hm,this.maxDigestLength=s}digest(e,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?ll(n,this.code,r?.truncate):n.then(o=>ll(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}}function ll(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return Qn(e,t)}function zm(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}const Ja=qm({name:"sha2-256",code:18,encode:zm("SHA-256")}),dl={...$m,...Im,...jm,...xm,...Am,...Wg,...Xg,...Mg,...Fm,...Lm};function $u(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const ul=$u("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Xs=$u("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=At(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Hu={utf8:ul,"utf-8":ul,hex:dl.base16,latin1:Xs,ascii:Xs,binary:Xs,...dl};function we(t,e="utf8"){const r=Hu[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function J(t,e="utf8"){const r=Hu[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}const Vm=parseInt("11111",2),sa=parseInt("10000000",2),Wm=parseInt("01111111",2),fl={0:hn,1:hn,2:Gm,3:Zm,4:Jm,5:Ym,6:Xm,16:hn,22:hn,48:hn};function nn(t,e={offset:0}){const r=t[e.offset]&Vm;if(e.offset++,fl[r]!=null)return fl[r](t,e);throw new Error("No decoder for tag "+r)}function to(t,e){let r=0;if((t[e.offset]&sa)===sa){const n=t[e.offset]&Wm;let o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=t[e.offset].toString(16).padStart(2,"0");r=parseInt(o,16)}else r=t[e.offset],e.offset++;return r}function hn(t,e){to(t,e);const r=[];for(;!(e.offset>=t.byteLength);){const n=nn(t,e);if(n===null)break;r.push(n)}return r}function Gm(t,e){const r=to(t,e),n=e.offset,o=e.offset+r,s=[];for(let i=n;i<o;i++)i===n&&t[i]===0||s.push(t[i]);return e.offset+=r,Uint8Array.from(s)}function Xm(t,e){const r=to(t,e),n=e.offset+r,o=t[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){const l=t[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let d=0;for(let u=0;u<c.length;u++)d+=c[u]<<u*7;a+=`.${d}`,c=[]}}return a}function Ym(t,e){return e.offset++,null}function Zm(t,e){const r=to(t,e),n=t[e.offset];e.offset++;const o=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Jm(t,e){const r=to(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function Qm(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);const r=new re;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function Is(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);const e=Qm(t.byteLength);return new re(Uint8Array.from([e.byteLength|sa]),e)}function je(t){const e=new re,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new re(Uint8Array.from([2]),Is(e),e)}function Qa(t){const e=Uint8Array.from([0]),r=new re(e,t);return new re(Uint8Array.from([3]),Is(r),r)}function ew(t){return new re(Uint8Array.from([4]),Is(t),t)}function xt(t,e=48){const r=new re;for(const n of t)r.append(n);return new re(Uint8Array.from([e]),Is(r),r)}async function tw(t,e,r){const n=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["sign"]);r?.signal?.throwIfAborted();const o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function rw(t,e,r,n){const o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();const s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,r.subarray());return n?.signal?.throwIfAborted(),s}const nw=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),ow=Uint8Array.from([6,5,43,129,4,0,34]),sw=Uint8Array.from([6,5,43,129,4,0,35]),qu={ext:!0,kty:"EC",crv:"P-256"},Ku={ext:!0,kty:"EC",crv:"P-384"},zu={ext:!0,kty:"EC",crv:"P-521"},Or=32,Fr=48,Mr=66;function iw(t){const e=nn(t);return aw(e)}function aw(t){const e=t[1],r=J(e,"base64url"),n=t[2][1][0],o=1;let s,i;if(e.byteLength===Or)return s=J(n.subarray(o,o+Or),"base64url"),i=J(n.subarray(o+Or),"base64url"),new Ys({...qu,key_ops:["sign"],d:r,x:s,y:i});if(e.byteLength===Fr)return s=J(n.subarray(o,o+Fr),"base64url"),i=J(n.subarray(o+Fr),"base64url"),new Ys({...Ku,key_ops:["sign"],d:r,x:s,y:i});if(e.byteLength===Mr)return s=J(n.subarray(o,o+Mr),"base64url"),i=J(n.subarray(o+Mr),"base64url"),new Ys({...zu,key_ops:["sign"],d:r,x:s,y:i});throw new tt(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function Vu(t){const e=nn(t);return cw(e)}function cw(t){const e=t[1][1][0],r=1;let n,o;if(e.byteLength===Or*2+1)return n=J(e.subarray(r,r+Or),"base64url"),o=J(e.subarray(r+Or),"base64url"),new Do({...qu,key_ops:["verify"],x:n,y:o});if(e.byteLength===Fr*2+1)return n=J(e.subarray(r,r+Fr),"base64url"),o=J(e.subarray(r+Fr),"base64url"),new Do({...Ku,key_ops:["verify"],x:n,y:o});if(e.byteLength===Mr*2+1)return n=J(e.subarray(r,r+Mr),"base64url"),o=J(e.subarray(r+Mr),"base64url"),new Do({...zu,key_ops:["verify"],x:n,y:o});throw new tt(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function lw(t){return xt([je(Uint8Array.from([1])),ew(we(t.d??"","base64url")),xt([Wu(t.crv)],160),xt([Qa(new re(Uint8Array.from([4]),we(t.x??"","base64url"),we(t.y??"","base64url")))],161)]).subarray()}function dw(t){return xt([je(Uint8Array.from([1])),xt([Wu(t.crv)],160),xt([Qa(new re(Uint8Array.from([4]),we(t.x??"","base64url"),we(t.y??"","base64url")))],161)]).subarray()}function Wu(t){if(t==="P-256")return nw;if(t==="P-384")return ow;if(t==="P-521")return sw;throw new tt(`Invalid curve ${t}`)}class Do{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=dw(this.jwk)),this._raw}toMultihash(){return eo.digest(Ls(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return Ne.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:rt(this.raw,e.raw)}async verify(e,r,n){return rw(this.jwk,r,e,n)}}class Ys{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Do({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=lw(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:rt(this.raw,e.raw)}async sign(e,r){return tw(this.jwk,e,r)}}const Ar=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function ro(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ia(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function hr(t,...e){if(!ro(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Gu(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ia(t.outputLen),ia(t.blockLen)}function Wo(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function uw(t,e){hr(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Xr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Zs(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function st(t,e){return t<<32-e|t>>>e}const Xu=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",fw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function tr(t){if(hr(t),Xu)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=fw[t[r]];return e}const ft={_0:48,_9:57,A:65,F:70,a:97,f:102};function hl(t){if(t>=ft._0&&t<=ft._9)return t-ft._0;if(t>=ft.A&&t<=ft.F)return t-(ft.A-10);if(t>=ft.a&&t<=ft.f)return t-(ft.a-10)}function Go(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Xu)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){const i=hl(t.charCodeAt(s)),a=hl(t.charCodeAt(s+1));if(i===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function hw(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ec(t){return typeof t=="string"&&(t=hw(t)),hr(t),t}function ct(...t){let e=0;for(let n=0;n<t.length;n++){const o=t[n];hr(o),e+=o.length}const r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){const s=t[n];r.set(s,o),o+=s.length}return r}class Yu{}function Zu(t){const e=n=>t().update(ec(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function tc(t=32){if(Ar&&typeof Ar.getRandomValues=="function")return Ar.getRandomValues(new Uint8Array(t));if(Ar&&typeof Ar.randomBytes=="function")return Uint8Array.from(Ar.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function pw(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,l=n?0:4;t.setUint32(e+c,i,n),t.setUint32(e+l,a,n)}function gw(t,e,r){return t&e^~t&r}function mw(t,e,r){return t&e^t&r^e&r}let Ju=class extends Yu{constructor(e,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Zs(this.buffer)}update(e){Wo(this),e=ec(e),hr(e);const{view:r,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){const a=Math.min(o-this.pos,s-i);if(a===o){const c=Zs(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Wo(this),uw(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:o,isLE:s}=this;let{pos:i}=this;r[i++]=128,Xr(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let u=i;u<o;u++)r[u]=0;pw(n,o-8,BigInt(this.length*8),s),this.process(n,0);const a=Zs(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}};const Tt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ke=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),po=BigInt(2**32-1),pl=BigInt(32);function ww(t,e=!1){return e?{h:Number(t&po),l:Number(t>>pl&po)}:{h:Number(t>>pl&po)|0,l:Number(t&po)|0}}function yw(t,e=!1){const r=t.length;let n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){const{h:i,l:a}=ww(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}const gl=(t,e,r)=>t>>>r,ml=(t,e,r)=>t<<32-r|e>>>r,kr=(t,e,r)=>t>>>r|e<<32-r,Ir=(t,e,r)=>t<<32-r|e>>>r,go=(t,e,r)=>t<<64-r|e>>>r-32,mo=(t,e,r)=>t>>>r-32|e<<64-r;function ht(t,e,r,n){const o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}const bw=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),vw=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,xw=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Sw=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0,Ew=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0),Aw=(t,e,r,n,o,s)=>e+r+n+o+s+(t/2**32|0)|0,kw=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Pt=new Uint32Array(64);class Iw extends Ju{constructor(e=32){super(64,e,8,!1),this.A=Tt[0]|0,this.B=Tt[1]|0,this.C=Tt[2]|0,this.D=Tt[3]|0,this.E=Tt[4]|0,this.F=Tt[5]|0,this.G=Tt[6]|0,this.H=Tt[7]|0}get(){const{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,r){for(let u=0;u<16;u++,r+=4)Pt[u]=e.getUint32(r,!1);for(let u=16;u<64;u++){const f=Pt[u-15],h=Pt[u-2],g=st(f,7)^st(f,18)^f>>>3,m=st(h,17)^st(h,19)^h>>>10;Pt[u]=m+Pt[u-7]+g+Pt[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=st(a,6)^st(a,11)^st(a,25),h=d+f+gw(a,c,l)+kw[u]+Pt[u]|0,m=(st(n,2)^st(n,13)^st(n,22))+mw(n,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,l,d)}roundClean(){Xr(Pt)}destroy(){this.set(0,0,0,0,0,0,0,0),Xr(this.buffer)}}const Qu=yw(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Cw=Qu[0],Rw=Qu[1],Nt=new Uint32Array(80),Lt=new Uint32Array(80);class Tw extends Ju{constructor(e=64){super(128,e,16,!1),this.Ah=ke[0]|0,this.Al=ke[1]|0,this.Bh=ke[2]|0,this.Bl=ke[3]|0,this.Ch=ke[4]|0,this.Cl=ke[5]|0,this.Dh=ke[6]|0,this.Dl=ke[7]|0,this.Eh=ke[8]|0,this.El=ke[9]|0,this.Fh=ke[10]|0,this.Fl=ke[11]|0,this.Gh=ke[12]|0,this.Gl=ke[13]|0,this.Hh=ke[14]|0,this.Hl=ke[15]|0}get(){const{Ah:e,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:f,Gh:h,Gl:g,Hh:m,Hl:y}=this;return[e,r,n,o,s,i,a,c,l,d,u,f,h,g,m,y]}set(e,r,n,o,s,i,a,c,l,d,u,f,h,g,m,y){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=d|0,this.Fh=u|0,this.Fl=f|0,this.Gh=h|0,this.Gl=g|0,this.Hh=m|0,this.Hl=y|0}process(e,r){for(let v=0;v<16;v++,r+=4)Nt[v]=e.getUint32(r),Lt[v]=e.getUint32(r+=4);for(let v=16;v<80;v++){const A=Nt[v-15]|0,B=Lt[v-15]|0,T=kr(A,B,1)^kr(A,B,8)^gl(A,B,7),N=Ir(A,B,1)^Ir(A,B,8)^ml(A,B,7),k=Nt[v-2]|0,x=Lt[v-2]|0,S=kr(k,x,19)^go(k,x,61)^gl(k,x,6),R=Ir(k,x,19)^mo(k,x,61)^ml(k,x,6),P=xw(N,R,Lt[v-7],Lt[v-16]),b=Sw(P,T,S,Nt[v-7],Nt[v-16]);Nt[v]=b|0,Lt[v]=P|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:f,Fh:h,Fl:g,Gh:m,Gl:y,Hh:w,Hl:I}=this;for(let v=0;v<80;v++){const A=kr(u,f,14)^kr(u,f,18)^go(u,f,41),B=Ir(u,f,14)^Ir(u,f,18)^mo(u,f,41),T=u&h^~u&m,N=f&g^~f&y,k=Ew(I,B,N,Rw[v],Lt[v]),x=Aw(k,w,A,T,Cw[v],Nt[v]),S=k|0,R=kr(n,o,28)^go(n,o,34)^go(n,o,39),P=Ir(n,o,28)^mo(n,o,34)^mo(n,o,39),b=n&s^n&a^s&a,E=o&i^o&c^i&c;w=m|0,I=y|0,m=h|0,y=g|0,h=u|0,g=f|0,{h:u,l:f}=ht(l|0,d|0,x|0,S|0),l=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;const C=bw(S,P,E);n=vw(C,x,R,b),o=C|0}({h:n,l:o}=ht(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ht(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ht(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=ht(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:f}=ht(this.Eh|0,this.El|0,u|0,f|0),{h,l:g}=ht(this.Fh|0,this.Fl|0,h|0,g|0),{h:m,l:y}=ht(this.Gh|0,this.Gl|0,m|0,y|0),{h:w,l:I}=ht(this.Hh|0,this.Hl|0,w|0,I|0),this.set(n,o,s,i,a,c,l,d,u,f,h,g,m,y,w,I)}roundClean(){Xr(Nt,Lt)}destroy(){Xr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const ef=Zu(()=>new Iw),Pw=Zu(()=>new Tw);const rc=BigInt(0),aa=BigInt(1);function ir(t,e=""){if(typeof t!="boolean"){const r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function Qe(t,e,r=""){const n=ro(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){const i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function wo(t){const e=t.toString(16);return e.length&1?"0"+e:e}function tf(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?rc:BigInt("0x"+t)}function Cs(t){return tf(tr(t))}function qn(t){return hr(t),tf(tr(Uint8Array.from(t).reverse()))}function nc(t,e){return Go(t.toString(16).padStart(e*2,"0"))}function rf(t,e){return nc(t,e).reverse()}function fe(t,e,r){let n;if(typeof e=="string")try{n=Go(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(ro(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const o=n.length;if(typeof r=="number"&&o!==r)throw new Error(t+" of length "+r+" expected, got "+o);return n}function wl(t){return Uint8Array.from(t)}const Js=t=>typeof t=="bigint"&&rc<=t;function Nw(t,e,r){return Js(t)&&Js(e)&&Js(r)&&e<=t&&t<r}function ca(t,e,r,n){if(!Nw(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function nf(t){let e;for(e=0;t>rc;t>>=aa,e+=1);return e}const no=t=>(aa<<BigInt(t))-aa;function Lw(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");const n=h=>new Uint8Array(h),o=h=>Uint8Array.of(h);let s=n(t),i=n(t),a=0;const c=()=>{s.fill(1),i.fill(0),a=0},l=(...h)=>r(i,s,...h),d=(h=n(0))=>{i=l(o(0),h),s=l(),h.length!==0&&(i=l(o(1),h),s=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const g=[];for(;h<e;){s=l();const m=s.slice();g.push(m),h+=s.length}return ct(...g)};return(h,g)=>{c(),d(h);let m;for(;!(m=g(u()));)d();return c(),m}}function oo(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(o,s,i){const a=t[o];if(i&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([o,s])=>n(o,s,!1)),Object.entries(r).forEach(([o,s])=>n(o,s,!0))}function Xo(t){const e=new WeakMap;return(r,...n)=>{const o=e.get(r);if(o!==void 0)return o;const s=t(r,...n);return e.set(r,s),s}}const _e=BigInt(0),Ee=BigInt(1),Yt=BigInt(2),of=BigInt(3),sf=BigInt(4),af=BigInt(5),Bw=BigInt(7),cf=BigInt(8),_w=BigInt(9),lf=BigInt(16);function ye(t,e){const r=t%e;return r>=_e?r:e+r}function ue(t,e,r){let n=t;for(;e-- >_e;)n*=n,n%=r;return n}function yl(t,e){if(t===_e)throw new Error("invert: expected non-zero number");if(e<=_e)throw new Error("invert: expected positive modulus, got "+e);let r=ye(t,e),n=e,o=_e,s=Ee;for(;r!==_e;){const a=n/r,c=n%r,l=o-s*a;n=r,r=c,o=s,s=l}if(n!==Ee)throw new Error("invert: does not exist");return ye(o,e)}function oc(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function df(t,e){const r=(t.ORDER+Ee)/sf,n=t.pow(e,r);return oc(t,n,e),n}function Dw(t,e){const r=(t.ORDER-af)/cf,n=t.mul(e,Yt),o=t.pow(n,r),s=t.mul(e,o),i=t.mul(t.mul(s,Yt),o),a=t.mul(s,t.sub(i,t.ONE));return oc(t,a,e),a}function Ow(t){const e=pr(t),r=uf(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+Bw)/lf;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,n);const u=a.mul(l,o),f=a.mul(l,s),h=a.eql(a.sqr(d),c),g=a.eql(a.sqr(u),c);l=a.cmov(l,d,h),d=a.cmov(f,u,g);const m=a.eql(a.sqr(d),c),y=a.cmov(l,d,m);return oc(a,y,c),y}}function uf(t){if(t<of)throw new Error("sqrt is not defined for small field");let e=t-Ee,r=0;for(;e%Yt===_e;)e/=Yt,r++;let n=Yt;const o=pr(t);for(;bl(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return df;let s=o.pow(n,e);const i=(e+Ee)/Yt;return function(c,l){if(c.is0(l))return l;if(bl(c,l)!==1)throw new Error("Cannot find square root");let d=r,u=c.mul(c.ONE,s),f=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let g=1,m=c.sqr(f);for(;!c.eql(m,c.ONE);)if(g++,m=c.sqr(m),g===d)throw new Error("Cannot find square root");const y=Ee<<BigInt(d-g-1),w=c.pow(u,y);d=g,u=c.sqr(w),f=c.mul(f,u),h=c.mul(h,w)}return h}}function Fw(t){return t%sf===of?df:t%cf===af?Dw:t%lf===_w?Ow(t):uf(t)}const Mw=(t,e)=>(ye(t,e)&Ee)===Ee,jw=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Uw(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=jw.reduce((n,o)=>(n[o]="function",n),e);return oo(t,r),t}function $w(t,e,r){if(r<_e)throw new Error("invalid exponent, negatives unsupported");if(r===_e)return t.ONE;if(r===Ee)return e;let n=t.ONE,o=e;for(;r>_e;)r&Ee&&(n=t.mul(n,o)),o=t.sqr(o),r>>=Ee;return n}function ff(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),o=e.reduce((i,a,c)=>t.is0(a)?i:(n[c]=i,t.mul(i,a)),t.ONE),s=t.inv(o);return e.reduceRight((i,a,c)=>t.is0(a)?i:(n[c]=t.mul(i,n[c]),t.mul(i,a)),s),n}function bl(t,e){const r=(t.ORDER-Ee)/Yt,n=t.pow(e,r),o=t.eql(n,t.ONE),s=t.eql(n,t.ZERO),i=t.eql(n,t.neg(t.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function hf(t,e){e!==void 0&&ia(e);const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function pr(t,e,r=!1,n={}){if(t<=_e)throw new Error("invalid field: expected ORDER > 0, got "+t);let o,s,i=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const f=e;f.BITS&&(o=f.BITS),f.sqrt&&(s=f.sqrt),typeof f.isLE=="boolean"&&(r=f.isLE),typeof f.modFromBytes=="boolean"&&(i=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(o=e),n.sqrt&&(s=n.sqrt);const{nBitLength:c,nByteLength:l}=hf(t,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:l,MASK:no(c),ZERO:_e,ONE:Ee,allowedLengths:a,create:f=>ye(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return _e<=f&&f<t},is0:f=>f===_e,isValidNot0:f=>!u.is0(f)&&u.isValid(f),isOdd:f=>(f&Ee)===Ee,neg:f=>ye(-f,t),eql:(f,h)=>f===h,sqr:f=>ye(f*f,t),add:(f,h)=>ye(f+h,t),sub:(f,h)=>ye(f-h,t),mul:(f,h)=>ye(f*h,t),pow:(f,h)=>$w(u,f,h),div:(f,h)=>ye(f*yl(h,t),t),sqrN:f=>f*f,addN:(f,h)=>f+h,subN:(f,h)=>f-h,mulN:(f,h)=>f*h,inv:f=>yl(f,t),sqrt:s||(f=>(d||(d=Fw(t)),d(u,f))),toBytes:f=>r?rf(f,l):nc(f,l),fromBytes:(f,h=!0)=>{if(a){if(!a.includes(f.length)||f.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);const m=new Uint8Array(l);m.set(f,r?0:m.length-f.length),f=m}if(f.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+f.length);let g=r?qn(f):Cs(f);if(i&&(g=ye(g,t)),!h&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:f=>ff(u,f),cmov:(f,h,g)=>g?h:f});return Object.freeze(u)}function pf(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function gf(t){const e=pf(t);return e+Math.ceil(e/2)}function Hw(t,e,r=!1){const n=t.length,o=pf(e),s=gf(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const i=r?qn(t):Cs(t),a=ye(i,e-Ee)+Ee;return r?rf(a,o):nc(a,o)}const Yr=BigInt(0),Zt=BigInt(1);function Yo(t,e){const r=e.negate();return t?r:e}function Jt(t,e){const r=ff(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function mf(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Qs(t,e){mf(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1),o=2**t,s=no(t),i=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function vl(t,e,r){const{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r;let a=Number(t&o),c=t>>i;a>n&&(a-=s,c+=Zt);const l=e*n,d=l+Math.abs(a)-1,u=a===0,f=a<0,h=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:f,isNegF:h,offsetF:l}}function qw(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function Kw(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const ei=new WeakMap,wf=new WeakMap;function ti(t){return wf.get(t)||1}function xl(t){if(t!==Yr)throw new Error("invalid wNAF")}class yf{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let o=e;for(;r>Yr;)r&Zt&&(n=n.add(o)),o=o.double(),r>>=Zt;return n}precomputeWindow(e,r){const{windows:n,windowSize:o}=Qs(r,this.bits),s=[];let i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE;const i=Qs(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:f,offsetF:h}=vl(n,a,i);n=c,d?s=s.add(Yo(f,r[h])):o=o.add(Yo(u,r[l]))}return xl(n),{p:o,f:s}}wNAFUnsafe(e,r,n,o=this.ZERO){const s=Qs(e,this.bits);for(let i=0;i<s.windows&&n!==Yr;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=vl(n,i,s);if(n=a,!l){const u=r[c];o=o.add(d?u.negate():u)}}return xl(n),o}getPrecomputes(e,r,n){let o=ei.get(r);return o||(o=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(o=n(o)),ei.set(r,o))),o}cached(e,r,n){const o=ti(e);return this.wNAF(o,this.getPrecomputes(o,e,n),r)}unsafe(e,r,n,o){const s=ti(e);return s===1?this._unsafeLadder(e,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),r,o)}createCache(e,r){mf(r,this.bits),wf.set(e,r),ei.delete(e)}hasCache(e){return ti(e)!==1}}function zw(t,e,r,n){let o=e,s=t.ZERO,i=t.ZERO;for(;r>Yr||n>Yr;)r&Zt&&(s=s.add(o)),n&Zt&&(i=i.add(o)),o=o.double(),r>>=Zt,n>>=Zt;return{p1:s,p2:i}}function bf(t,e,r,n){qw(r,t),Kw(n,e);const o=r.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,a=nf(BigInt(o));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=no(c),d=new Array(Number(l)+1).fill(i),u=Math.floor((e.BITS-1)/c)*c;let f=i;for(let h=u;h>=0;h-=c){d.fill(i);for(let m=0;m<s;m++){const y=n[m],w=Number(y>>BigInt(h)&l);d[w]=d[w].add(r[m])}let g=i;for(let m=d.length-1,y=i;m>0;m--)y=y.add(d[m]),g=g.add(y);if(f=f.add(g),h!==0)for(let m=0;m<c;m++)f=f.double()}return f}function Sl(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Uw(e),e}else return pr(t,{isLE:r})}function vf(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>Yr))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Sl(e.p,r.Fp,n),s=Sl(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}const Bt=BigInt(0),be=BigInt(1),ri=BigInt(2),Vw=BigInt(8);function Ww(t,e,r,n){const o=t.sqr(r),s=t.sqr(n),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function Gw(t,e={}){const r=vf("edwards",t,e,e.FpFnLE),{Fp:n,Fn:o}=r;let s=r.CURVE;const{h:i}=s;oo(e,{},{uvRatio:"function"});const a=ri<<BigInt(o.BYTES*8)-be,c=y=>n.create(y),l=e.uvRatio||((y,w)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,w))}}catch{return{isValid:!1,value:Bt}}});if(!Ww(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(y,w,I=!1){const v=I?be:Bt;return ca("coordinate "+y,w,v,a),w}function u(y){if(!(y instanceof g))throw new Error("ExtendedPoint expected")}const f=Xo((y,w)=>{const{X:I,Y:v,Z:A}=y,B=y.is0();w==null&&(w=B?Vw:n.inv(A));const T=c(I*w),N=c(v*w),k=n.mul(A,w);if(B)return{x:Bt,y:be};if(k!==be)throw new Error("invZ was invalid");return{x:T,y:N}}),h=Xo(y=>{const{a:w,d:I}=s;if(y.is0())throw new Error("bad point: ZERO");const{X:v,Y:A,Z:B,T}=y,N=c(v*v),k=c(A*A),x=c(B*B),S=c(x*x),R=c(N*w),P=c(x*c(R+k)),b=c(S+c(I*c(N*k)));if(P!==b)throw new Error("bad point: equation left != right (1)");const E=c(v*A),C=c(B*T);if(E!==C)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(w,I,v,A){this.X=d("x",w),this.Y=d("y",I),this.Z=d("z",v,!0),this.T=d("t",A),Object.freeze(this)}static CURVE(){return s}static fromAffine(w){if(w instanceof g)throw new Error("extended point not allowed");const{x:I,y:v}=w||{};return d("x",I),d("y",v),new g(I,v,be,c(I*v))}static fromBytes(w,I=!1){const v=n.BYTES,{a:A,d:B}=s;w=wl(Qe(w,v,"point")),ir(I,"zip215");const T=wl(w),N=w[v-1];T[v-1]=N&-129;const k=qn(T),x=I?a:n.ORDER;ca("point.y",k,Bt,x);const S=c(k*k),R=c(S-be),P=c(B*S-A);let{isValid:b,value:E}=l(R,P);if(!b)throw new Error("bad point: invalid y coordinate");const C=(E&be)===be,L=(N&128)!==0;if(!I&&E===Bt&&L)throw new Error("bad point: x=0 and x_0=1");return L!==C&&(E=c(-E)),g.fromAffine({x:E,y:k})}static fromHex(w,I=!1){return g.fromBytes(fe("point",w),I)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,I=!0){return m.createCache(this,w),I||this.multiply(ri),this}assertValidity(){h(this)}equals(w){u(w);const{X:I,Y:v,Z:A}=this,{X:B,Y:T,Z:N}=w,k=c(I*N),x=c(B*A),S=c(v*N),R=c(T*A);return k===x&&S===R}is0(){return this.equals(g.ZERO)}negate(){return new g(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:w}=s,{X:I,Y:v,Z:A}=this,B=c(I*I),T=c(v*v),N=c(ri*c(A*A)),k=c(w*B),x=I+v,S=c(c(x*x)-B-T),R=k+T,P=R-N,b=k-T,E=c(S*P),C=c(R*b),L=c(S*b),M=c(P*R);return new g(E,C,M,L)}add(w){u(w);const{a:I,d:v}=s,{X:A,Y:B,Z:T,T:N}=this,{X:k,Y:x,Z:S,T:R}=w,P=c(A*k),b=c(B*x),E=c(N*v*R),C=c(T*S),L=c((A+B)*(k+x)-P-b),M=C-E,$=C+E,j=c(b-I*P),D=c(L*M),_=c($*j),O=c(L*j),q=c(M*$);return new g(D,_,q,O)}subtract(w){return this.add(w.negate())}multiply(w){if(!o.isValidNot0(w))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:I,f:v}=m.cached(this,w,A=>Jt(g,A));return Jt(g,[I,v])[0]}multiplyUnsafe(w,I=g.ZERO){if(!o.isValid(w))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return w===Bt?g.ZERO:this.is0()||w===be?this:m.unsafe(this,w,v=>Jt(g,v),I)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(w){return f(this,w)}clearCofactor(){return i===be?this:this.multiplyUnsafe(i)}toBytes(){const{x:w,y:I}=this.toAffine(),v=n.toBytes(I);return v[v.length-1]|=w&be?128:0,v}toHex(){return tr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(w){return Jt(g,w)}static msm(w,I){return bf(g,o,w,I)}_setWindowSize(w){this.precompute(w)}toRawBytes(){return this.toBytes()}}g.BASE=new g(s.Gx,s.Gy,be,c(s.Gx*s.Gy)),g.ZERO=new g(Bt,be,be,Bt),g.Fp=n,g.Fn=o;const m=new yf(g,o.BITS);return g.BASE.precompute(8),g}function Xw(t,e,r={}){if(typeof e!="function")throw new Error('"hash" function param is required');oo(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n}=r,{BASE:o,Fp:s,Fn:i}=t,a=r.randomBytes||tc,c=r.adjustScalarBytes||(x=>x),l=r.domain||((x,S,R)=>{if(ir(R,"phflag"),S.length||R)throw new Error("Contexts/pre-hash are not supported");return x});function d(x){return i.create(qn(x))}function u(x){const S=v.secretKey;x=fe("private key",x,S);const R=fe("hashed private key",e(x),2*S),P=c(R.slice(0,S)),b=R.slice(S,2*S),E=d(P);return{head:P,prefix:b,scalar:E}}function f(x){const{head:S,prefix:R,scalar:P}=u(x),b=o.multiply(P),E=b.toBytes();return{head:S,prefix:R,scalar:P,point:b,pointBytes:E}}function h(x){return f(x).pointBytes}function g(x=Uint8Array.of(),...S){const R=ct(...S);return d(e(l(R,fe("context",x),!!n)))}function m(x,S,R={}){x=fe("message",x),n&&(x=n(x));const{prefix:P,scalar:b,pointBytes:E}=f(S),C=g(R.context,P,x),L=o.multiply(C).toBytes(),M=g(R.context,L,E,x),$=i.create(C+M*b);if(!i.isValid($))throw new Error("sign failed: invalid s");const j=ct(L,i.toBytes($));return Qe(j,v.signature,"result")}const y={zip215:!0};function w(x,S,R,P=y){const{context:b,zip215:E}=P,C=v.signature;x=fe("signature",x,C),S=fe("message",S),R=fe("publicKey",R,v.publicKey),E!==void 0&&ir(E,"zip215"),n&&(S=n(S));const L=C/2,M=x.subarray(0,L),$=qn(x.subarray(L,C));let j,D,_;try{j=t.fromBytes(R,E),D=t.fromBytes(M,E),_=o.multiplyUnsafe($)}catch{return!1}if(!E&&j.isSmallOrder())return!1;const O=g(b,D.toBytes(),j.toBytes(),S);return D.add(j.multiplyUnsafe(O)).subtract(_).clearCofactor().is0()}const I=s.BYTES,v={secretKey:I,publicKey:I,signature:2*I,seed:I};function A(x=a(v.seed)){return Qe(x,v.seed,"seed")}function B(x){const S=k.randomSecretKey(x);return{secretKey:S,publicKey:h(S)}}function T(x){return ro(x)&&x.length===i.BYTES}function N(x,S){try{return!!t.fromBytes(x,S)}catch{return!1}}const k={getExtendedPublicKey:f,randomSecretKey:A,isValidSecretKey:T,isValidPublicKey:N,toMontgomery(x){const{y:S}=t.fromBytes(x),R=v.publicKey,P=R===32;if(!P&&R!==57)throw new Error("only defined for 25519 and 448");const b=P?s.div(be+S,be-S):s.div(S-be,S+be);return s.toBytes(b)},toMontgomerySecret(x){const S=v.secretKey;Qe(x,S);const R=e(x.subarray(0,S));return c(R).subarray(0,S)},randomPrivateKey:A,precompute(x=8,S=t.BASE){return S.precompute(x,!1)}};return Object.freeze({keygen:B,getPublicKey:h,sign:m,verify:w,utils:k,Point:t,lengths:v})}function Yw(t){const e={a:t.a,d:t.d,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp,n=pr(e.n,t.nBitLength,!0),o={Fp:r,Fn:n,uvRatio:t.uvRatio},s={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:o,hash:t.hash,eddsaOpts:s}}function Zw(t,e){const r=e.Point;return Object.assign({},e,{ExtendedPoint:r,CURVE:t,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}function Jw(t){const{CURVE:e,curveOpts:r,hash:n,eddsaOpts:o}=Yw(t),s=Gw(e,r),i=Xw(s,n,o);return Zw(t,i)}const Qw=BigInt(1),El=BigInt(2);BigInt(3);const ey=BigInt(5),ty=BigInt(8),sc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),xf={p:sc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ty,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ry(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=sc,a=t*t%s*t%s,c=ue(a,El,s)*a%s,l=ue(c,Qw,s)*t%s,d=ue(l,ey,s)*l%s,u=ue(d,e,s)*d%s,f=ue(u,r,s)*u%s,h=ue(f,n,s)*f%s,g=ue(h,o,s)*h%s,m=ue(g,o,s)*h%s,y=ue(m,e,s)*d%s;return{pow_p_5_8:ue(y,El,s)*t%s,b2:a}}function ny(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Al=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function oy(t,e){const r=sc,n=ye(e*e*e,r),o=ye(n*n*e,r),s=ry(t*o).pow_p_5_8;let i=ye(t*n*s,r);const a=ye(e*i*i,r),c=i,l=ye(i*Al,r),d=a===t,u=a===ye(-t,r),f=a===ye(-t*Al,r);return d&&(i=c),(u||f)&&(i=l),Mw(i,r)&&(i=ye(-i,r)),{isValid:d||u,value:i}}const sy=pr(xf.p,{isLE:!0}),iy={...xf,Fp:sy,hash:Pw,adjustScalarBytes:ny,uvRatio:oy},Zo=Jw(iy);class kl extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}}class Il extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class ay extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}const kt={get(t=globalThis){const e=t.crypto;if(e?.subtle==null)throw new ay("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}},Jo=32,gt=64,la=32;let jr;const Sf=(async()=>{try{return await kt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function cy(){const t=Zo.utils.randomPrivateKey(),e=Zo.getPublicKey(t);return{privateKey:gy(t,e),publicKey:e}}async function ly(t,e){let r;t.length===gt?r=t.subarray(0,32):r=t;const n={crv:"Ed25519",kty:"OKP",x:J(t.subarray(32),"base64url"),d:J(r,"base64url"),ext:!0,key_ops:["sign"]},o=await kt.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await kt.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function dy(t,e){const r=t.subarray(0,la);return Zo.sign(e instanceof Uint8Array?e:e.subarray(),r)}async function uy(t,e){return jr==null&&(jr=await Sf),jr?ly(t,e):dy(t,e)}async function fy(t,e,r){if(t.buffer instanceof ArrayBuffer){const n=await kt.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await kt.get().subtle.verify({name:"Ed25519"},n,e,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function hy(t,e,r){return Zo.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}async function py(t,e,r){return jr==null&&(jr=await Sf),jr?fy(t,e,r):hy(t,e,r)}function gy(t,e){const r=new Uint8Array(gt);for(let n=0;n<la;n++)r[n]=t[n],r[la+n]=e[n];return r}function Rs(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}class Ef{type="Ed25519";raw;constructor(e){this.raw=Kn(e,Jo)}toMultihash(){return eo.digest(Ls(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return Ne.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:rt(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();const o=py(this.raw,r,e);return Rs(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}}class da{type="Ed25519";raw;publicKey;constructor(e,r){this.raw=Kn(e,gt),this.publicKey=new Ef(r)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:rt(this.raw,e.raw)}sign(e,r){r?.signal?.throwIfAborted();const n=uy(this.raw,e);return Rs(n)?n.then(o=>(r?.signal?.throwIfAborted(),o)):(r?.signal?.throwIfAborted(),n)}}function my(t){if(t.length>gt){t=Kn(t,gt+Jo);const n=t.subarray(0,gt),o=t.subarray(gt,t.length);return new da(n,o)}t=Kn(t,gt);const e=t.subarray(0,gt),r=t.subarray(Jo);return new da(e,r)}function Af(t){return t=Kn(t,Jo),new Ef(t)}async function wy(){const{privateKey:t,publicKey:e}=cy();return new da(t,e)}function Kn(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new tt(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}const yy=Math.pow(2,7),by=Math.pow(2,14),vy=Math.pow(2,21),ic=Math.pow(2,28),ac=Math.pow(2,35),cc=Math.pow(2,42),lc=Math.pow(2,49),te=128,Ie=127;function gr(t){if(t<yy)return 1;if(t<by)return 2;if(t<vy)return 3;if(t<ic)return 4;if(t<ac)return 5;if(t<cc)return 6;if(t<lc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function kf(t,e,r=0){switch(gr(t)){case 8:e[r++]=t&255|te,t/=128;case 7:e[r++]=t&255|te,t/=128;case 6:e[r++]=t&255|te,t/=128;case 5:e[r++]=t&255|te,t/=128;case 4:e[r++]=t&255|te,t>>>=7;case 3:e[r++]=t&255|te,t>>>=7;case 2:e[r++]=t&255|te,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function xy(t,e,r=0){switch(gr(t)){case 8:e.set(r++,t&255|te),t/=128;case 7:e.set(r++,t&255|te),t/=128;case 6:e.set(r++,t&255|te),t/=128;case 5:e.set(r++,t&255|te),t/=128;case 4:e.set(r++,t&255|te),t>>>=7;case 3:e.set(r++,t&255|te),t>>>=7;case 2:e.set(r++,t&255|te),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function If(t,e){let r=t[e],n=0;if(n+=r&Ie,r<te||(r=t[e+1],n+=(r&Ie)<<7,r<te)||(r=t[e+2],n+=(r&Ie)<<14,r<te)||(r=t[e+3],n+=(r&Ie)<<21,r<te)||(r=t[e+4],n+=(r&Ie)*ic,r<te)||(r=t[e+5],n+=(r&Ie)*ac,r<te)||(r=t[e+6],n+=(r&Ie)*cc,r<te)||(r=t[e+7],n+=(r&Ie)*lc,r<te))return n;throw new RangeError("Could not decode varint")}function Sy(t,e){let r=t.get(e),n=0;if(n+=r&Ie,r<te||(r=t.get(e+1),n+=(r&Ie)<<7,r<te)||(r=t.get(e+2),n+=(r&Ie)<<14,r<te)||(r=t.get(e+3),n+=(r&Ie)<<21,r<te)||(r=t.get(e+4),n+=(r&Ie)*ic,r<te)||(r=t.get(e+5),n+=(r&Ie)*ac,r<te)||(r=t.get(e+6),n+=(r&Ie)*cc,r<te)||(r=t.get(e+7),n+=(r&Ie)*lc,r<te))return n;throw new RangeError("Could not decode varint")}function Ey(t,e,r=0){return e==null&&(e=At(gr(t))),e instanceof Uint8Array?kf(t,e,r):xy(t,e,r)}function Cf(t,e=0){return t instanceof Uint8Array?If(t,e):Sy(t,e)}const dc=new Float32Array([-0]),Ut=new Uint8Array(dc.buffer);function Ay(t,e,r){dc[0]=t,e[r]=Ut[0],e[r+1]=Ut[1],e[r+2]=Ut[2],e[r+3]=Ut[3]}function ky(t,e){return Ut[0]=t[e],Ut[1]=t[e+1],Ut[2]=t[e+2],Ut[3]=t[e+3],dc[0]}const uc=new Float64Array([-0]),Ce=new Uint8Array(uc.buffer);function Iy(t,e,r){uc[0]=t,e[r]=Ce[0],e[r+1]=Ce[1],e[r+2]=Ce[2],e[r+3]=Ce[3],e[r+4]=Ce[4],e[r+5]=Ce[5],e[r+6]=Ce[6],e[r+7]=Ce[7]}function Cy(t,e){return Ce[0]=t[e],Ce[1]=t[e+1],Ce[2]=t[e+2],Ce[3]=t[e+3],Ce[4]=t[e+4],Ce[5]=t[e+5],Ce[6]=t[e+6],Ce[7]=t[e+7],uc[0]}const Ry=BigInt(Number.MAX_SAFE_INTEGER),Ty=BigInt(Number.MIN_SAFE_INTEGER);class Re{lo;hi;constructor(e,r){this.lo=e|0,this.hi=r|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){const r=~this.lo+1>>>0;let n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){const r=~this.lo+1>>>0;let n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return rr;if(e<Ry&&e>Ty)return this.fromNumber(Number(e));const r=e<0n;r&&(e=-e);let n=e>>32n,o=e-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>Cl&&(o=0n,++n>Cl&&(n=0n))),new Re(Number(o),Number(n))}static fromNumber(e){if(e===0)return rr;const r=e<0;r&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new Re(n,o)}static from(e){return typeof e=="number"?Re.fromNumber(e):typeof e=="bigint"?Re.fromBigInt(e):typeof e=="string"?Re.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new Re(e.low>>>0,e.high>>>0):rr}}const rr=new Re(0,0);rr.toBigInt=function(){return 0n};rr.zzEncode=rr.zzDecode=function(){return this};rr.length=function(){return 1};const Cl=4294967296n;function Py(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:(r&64512)===55296&&(t.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Ny(t,e,r){if(r-e<1)return"";let o;const s=[];let i=0,a;for(;e<r;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Rf(t,e,r){const n=r;let o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[r++]=o:o<2048?(e[r++]=o>>6|192,e[r++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[r++]=o>>18|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128,e[r++]=o&63|128):(e[r++]=o>>12|224,e[r++]=o>>6&63|128,e[r++]=o&63|128);return r-n}function Ze(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function yo(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}class Ly{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Ze(this,10);return e}int32(){return this.uint32()|0}sint32(){const e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Ze(this,4);return yo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ze(this,4);return yo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ze(this,4);const e=ky(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ze(this,4);const e=Cy(this.buf,this.pos);return this.pos+=8,e}bytes(){const e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw Ze(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){const e=this.bytes();return Ny(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Ze(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Ze(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new Re(0,0);let r=0;if(this.len-this.pos>4){for(;r<4;++r)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw Ze(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,e}if(this.len-this.pos>4){for(;r<5;++r)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;r<5;++r){if(this.pos>=this.len)throw Ze(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Ze(this,8);const e=yo(this.buf,this.pos+=4),r=yo(this.buf,this.pos+=4);return new Re(e,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=If(this.buf,this.pos);return this.pos+=gr(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function By(t){return new Ly(t instanceof Uint8Array?t:t.subarray())}function Ts(t,e,r){const n=By(t);return e.decode(n,void 0,r)}function _y(t){let n,o=8192;return function(i){if(i<1||i>4096)return At(i);o+i>8192&&(n=At(8192),o=0);const a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}class Rn{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}}function ni(){}class Dy{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const Oy=_y();function Fy(t){return globalThis.Buffer!=null?At(t):Oy(t)}class ua{len;head;tail;states;constructor(){this.len=0,this.head=new Rn(ni,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new Rn(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new jy((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(bo,10,Re.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const r=Re.fromBigInt(e);return this._push(bo,r.length(),r)}uint64Number(e){return this._push(kf,gr(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const r=Re.fromBigInt(e).zzEncode();return this._push(bo,r.length(),r)}sint64Number(e){const r=Re.fromNumber(e).zzEncode();return this._push(bo,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(oi,1,e?1:0)}fixed32(e){return this._push(pn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const r=Re.fromBigInt(e);return this._push(pn,4,r.lo)._push(pn,4,r.hi)}fixed64Number(e){const r=Re.fromNumber(e);return this._push(pn,4,r.lo)._push(pn,4,r.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Ay,4,e)}double(e){return this._push(Iy,8,e)}bytes(e){const r=e.length>>>0;return r===0?this._push(oi,1,0):this.uint32(r)._push(Uy,r,e)}string(e){const r=Py(e);return r!==0?this.uint32(r)._push(Rf,r,e):this._push(oi,1,0)}fork(){return this.states=new Dy(this),this.head=this.tail=new Rn(ni,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Rn(ni,0,0),this.len=0),this}ldelim(){const e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=r,this.len+=n),this}finish(){let e=this.head.next;const r=Fy(this.len);let n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}}function oi(t,e,r){e[r]=t&255}function My(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}class jy extends Rn{next;constructor(e,r){super(My,e,r),this.next=void 0}}function bo(t,e,r){for(;t.hi!==0;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}function pn(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function Uy(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(ua.prototype.bytes=function(t){const e=t.length>>>0;return this.uint32(e),e>0&&this._push($y,e,t),this},ua.prototype.string=function(t){const e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(Hy,e,t),this});function $y(t,e,r){e.set(t,r)}function Hy(t,e,r){t.length<40?Rf(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(we(t),r)}function qy(){return new ua}function Ps(t,e){const r=qy();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var Qo;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(Qo||(Qo={}));function Tf(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function Ky(t){function e(o){if(t[o.toString()]==null)throw new Error("Invalid enum value");return t[o]}const r=function(s,i){const a=e(s);i.int32(a)},n=function(s){const i=s.int32();return e(i)};return Tf("enum",Qo.VARINT,r,n)}function Ns(t,e){return Tf("message",Qo.LENGTH_DELIMITED,t,e)}class Rl extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var le;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(le||(le={}));var fa;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(fa||(fa={}));(function(t){t.codec=()=>Ky(fa)})(le||(le={}));var ar;(function(t){let e;t.codec=()=>(e==null&&(e=Ns((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),le.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{const s={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){const a=r.uint32();switch(a>>>3){case 1:{s.Type=le.codec().decode(r);break}case 2:{s.Data=r.bytes();break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ps(r,t.codec()),t.decode=(r,n)=>Ts(r,t.codec(),n)})(ar||(ar={}));var es;(function(t){let e;t.codec=()=>(e==null&&(e=Ns((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),le.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{const s={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){const a=r.uint32();switch(a>>>3){case 1:{s.Type=le.codec().decode(r);break}case 2:{s.Data=r.bytes();break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ps(r,t.codec()),t.decode=(r,n)=>Ts(r,t.codec(),n)})(es||(es={}));const Pf=ef;class Nf{type="RSA";jwk;_raw;_multihash;constructor(e,r){this.jwk=e,this._multihash=r}get raw(){return this._raw==null&&(this._raw=Bf(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ce.createV1(114,this._multihash)}toString(){return Ne.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:rt(this.raw,e.raw)}verify(e,r,n){return sb(this.jwk,r,e,n)}}class zy{type="RSA";jwk;_raw;publicKey;constructor(e,r){this.jwk=e,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=Yy(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:rt(this.raw,e.raw)}sign(e,r){return ob(this.jwk,e,r)}}const Vy=8192,Lf=18,Wy=1062,Gy=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Xy(t){return{n:J(t[1],"base64url"),e:J(t[2],"base64url"),d:J(t[3],"base64url"),p:J(t[4],"base64url"),q:J(t[5],"base64url"),dp:J(t[6],"base64url"),dq:J(t[7],"base64url"),qi:J(t[8],"base64url"),kty:"RSA"}}function Yy(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new tt("JWK was missing components");return xt([je(Uint8Array.from([0])),je(we(t.n,"base64url")),je(we(t.e,"base64url")),je(we(t.d,"base64url")),je(we(t.p,"base64url")),je(we(t.q,"base64url")),je(we(t.dp,"base64url")),je(we(t.dq,"base64url")),je(we(t.qi,"base64url"))]).subarray()}function Zy(t){const e=nn(t[1],{offset:0});return{kty:"RSA",n:J(e[0],"base64url"),e:J(e[1],"base64url")}}function Bf(t){if(t.n==null||t.e==null)throw new tt("JWK was missing components");return xt([Gy,Qa(xt([je(we(t.n,"base64url")),je(we(t.e,"base64url"))]))]).subarray()}function Jy(t){const e=nn(t);return Qy(e)}function Qy(t){const e=Xy(t);return rb(e)}function eb(t,e){if(t.byteLength>=Wy)throw new Nu("Key size is too large");const r=nn(t,{offset:0});return tb(r,t,e)}function tb(t,e,r){const n=Zy(t);if(r==null){const o=Pf(ar.encode({Type:le.RSA,Data:e}));r=Qn(Lf,o)}return new Nf(n,r)}function rb(t){if(ib(t)>Vy)throw new tt("Key size is too large");const e=nb(t),r=Pf(ar.encode({Type:le.RSA,Data:Bf(e.publicKey)})),n=Qn(Lf,r);return new zy(e.privateKey,new Nf(e.publicKey,n))}function nb(t){if(t==null)throw new tt("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function ob(t,e,r){const n=await kt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();const o=await kt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function sb(t,e,r,n){const o=await kt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();const s=await kt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),s}function ib(t){if(t.kty!=="RSA")throw new tt("invalid key type");if(t.n==null)throw new tt("invalid key modulus");return we(t.n,"base64url").length*8}class _f extends Yu{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Gu(e);const n=ec(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),Xr(s)}update(e){return Wo(this),this.iHash.update(e),this}digestInto(e){Wo(this),hr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Df=(t,e,r)=>new _f(t,e).update(r).digest();Df.create=(t,e)=>new _f(t,e);const Tl=(t,e)=>(t+(t>=0?e:-e)/Of)/e;function ab(t,e,r){const[[n,o],[s,i]]=e,a=Tl(i*t,r),c=Tl(-o*t,r);let l=t-a*n-c*s,d=-a*o-c*i;const u=l<yt,f=d<yt;u&&(l=-l),f&&(d=-d);const h=no(Math.ceil(nf(r)/2))+Ur;if(l<yt||l>=h||d<yt||d>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:f,k2:d}}function ha(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function si(t,e){const r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return ir(r.lowS,"lowS"),ir(r.prehash,"prehash"),r.format!==void 0&&ha(r.format),r}class cb extends Error{constructor(e=""){super(e)}}const mt={Err:cb,_tlv:{encode:(t,e)=>{const{Err:r}=mt;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const n=e.length/2,o=wo(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?wo(o.length/2|128):"";return wo(t)+s+o+e},decode(t,e){const{Err:r}=mt;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const o=e[n++],s=!!(o&128);let i=0;if(!s)i=o;else{const c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(n,n+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(t){const{Err:e}=mt;if(t<yt)throw new e("integer: negative integers are not allowed");let r=wo(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=mt;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Cs(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=mt,o=fe("signature",t),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,s),{v:l,l:d}=n.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(t){const{_tlv:e,_int:r}=mt,n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),s=n+o;return e.encode(48,s)}},yt=BigInt(0),Ur=BigInt(1),Of=BigInt(2),vo=BigInt(3),lb=BigInt(4);function Nr(t,e){const{BYTES:r}=t;let n;if(typeof e=="bigint")n=e;else{let o=fe("private key",e);try{n=t.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function db(t,e={}){const r=vf("weierstrass",t,e),{Fp:n,Fn:o}=r;let s=r.CURVE;const{h:i,n:a}=s;oo(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Mf(n,o);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(P,b,E){const{x:C,y:L}=b.toAffine(),M=n.toBytes(C);if(ir(E,"isCompressed"),E){d();const $=!n.isOdd(L);return ct(Ff($),M)}else return ct(Uint8Array.of(4),M,n.toBytes(L))}function f(P){Qe(P,void 0,"Point");const{publicKey:b,publicKeyUncompressed:E}=l,C=P.length,L=P[0],M=P.subarray(1);if(C===b&&(L===2||L===3)){const $=n.fromBytes(M);if(!n.isValid($))throw new Error("bad point: is not on curve, wrong x");const j=m($);let D;try{D=n.sqrt(j)}catch(q){const H=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}d();const _=n.isOdd(D);return(L&1)===1!==_&&(D=n.neg(D)),{x:$,y:D}}else if(C===E&&L===4){const $=n.BYTES,j=n.fromBytes(M.subarray(0,$)),D=n.fromBytes(M.subarray($,$*2));if(!y(j,D))throw new Error("bad point: is not on curve");return{x:j,y:D}}else throw new Error(`bad point: got length ${C}, expected compressed=${b} or uncompressed=${E}`)}const h=e.toBytes||u,g=e.fromBytes||f;function m(P){const b=n.sqr(P),E=n.mul(b,P);return n.add(n.add(E,n.mul(P,s.a)),s.b)}function y(P,b){const E=n.sqr(b),C=m(P);return n.eql(E,C)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const w=n.mul(n.pow(s.a,vo),lb),I=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(w,I)))throw new Error("bad curve params: a or b");function v(P,b,E=!1){if(!n.isValid(b)||E&&n.is0(b))throw new Error(`bad point coordinate ${P}`);return b}function A(P){if(!(P instanceof x))throw new Error("ProjectivePoint expected")}function B(P){if(!c||!c.basises)throw new Error("no endo");return ab(P,c.basises,o.ORDER)}const T=Xo((P,b)=>{const{X:E,Y:C,Z:L}=P;if(n.eql(L,n.ONE))return{x:E,y:C};const M=P.is0();b==null&&(b=M?n.ONE:n.inv(L));const $=n.mul(E,b),j=n.mul(C,b),D=n.mul(L,b);if(M)return{x:n.ZERO,y:n.ZERO};if(!n.eql(D,n.ONE))throw new Error("invZ was invalid");return{x:$,y:j}}),N=Xo(P=>{if(P.is0()){if(e.allowInfinityPoint&&!n.is0(P.Y))return;throw new Error("bad point: ZERO")}const{x:b,y:E}=P.toAffine();if(!n.isValid(b)||!n.isValid(E))throw new Error("bad point: x or y not field elements");if(!y(b,E))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function k(P,b,E,C,L){return E=new x(n.mul(E.X,P),E.Y,E.Z),b=Yo(C,b),E=Yo(L,E),b.add(E)}class x{constructor(b,E,C){this.X=v("x",b),this.Y=v("y",E,!0),this.Z=v("z",C),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){const{x:E,y:C}=b||{};if(!b||!n.isValid(E)||!n.isValid(C))throw new Error("invalid affine point");if(b instanceof x)throw new Error("projective point not allowed");return n.is0(E)&&n.is0(C)?x.ZERO:new x(E,C,n.ONE)}static fromBytes(b){const E=x.fromAffine(g(Qe(b,void 0,"point")));return E.assertValidity(),E}static fromHex(b){return x.fromBytes(fe("pointHex",b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,E=!0){return R.createCache(this,b),E||this.multiply(vo),this}assertValidity(){N(this)}hasEvenY(){const{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){A(b);const{X:E,Y:C,Z:L}=this,{X:M,Y:$,Z:j}=b,D=n.eql(n.mul(E,j),n.mul(M,L)),_=n.eql(n.mul(C,j),n.mul($,L));return D&&_}negate(){return new x(this.X,n.neg(this.Y),this.Z)}double(){const{a:b,b:E}=s,C=n.mul(E,vo),{X:L,Y:M,Z:$}=this;let j=n.ZERO,D=n.ZERO,_=n.ZERO,O=n.mul(L,L),q=n.mul(M,M),H=n.mul($,$),K=n.mul(L,M);return K=n.add(K,K),_=n.mul(L,$),_=n.add(_,_),j=n.mul(b,_),D=n.mul(C,H),D=n.add(j,D),j=n.sub(q,D),D=n.add(q,D),D=n.mul(j,D),j=n.mul(K,j),_=n.mul(C,_),H=n.mul(b,H),K=n.sub(O,H),K=n.mul(b,K),K=n.add(K,_),_=n.add(O,O),O=n.add(_,O),O=n.add(O,H),O=n.mul(O,K),D=n.add(D,O),H=n.mul(M,$),H=n.add(H,H),O=n.mul(H,K),j=n.sub(j,O),_=n.mul(H,q),_=n.add(_,_),_=n.add(_,_),new x(j,D,_)}add(b){A(b);const{X:E,Y:C,Z:L}=this,{X:M,Y:$,Z:j}=b;let D=n.ZERO,_=n.ZERO,O=n.ZERO;const q=s.a,H=n.mul(s.b,vo);let K=n.mul(E,M),z=n.mul(C,$),W=n.mul(L,j),X=n.add(E,C),G=n.add(M,$);X=n.mul(X,G),G=n.add(K,z),X=n.sub(X,G),G=n.add(E,L);let Y=n.add(M,j);return G=n.mul(G,Y),Y=n.add(K,W),G=n.sub(G,Y),Y=n.add(C,L),D=n.add($,j),Y=n.mul(Y,D),D=n.add(z,W),Y=n.sub(Y,D),O=n.mul(q,G),D=n.mul(H,W),O=n.add(D,O),D=n.sub(z,O),O=n.add(z,O),_=n.mul(D,O),z=n.add(K,K),z=n.add(z,K),W=n.mul(q,W),G=n.mul(H,G),z=n.add(z,W),W=n.sub(K,W),W=n.mul(q,W),G=n.add(G,W),K=n.mul(z,G),_=n.add(_,K),K=n.mul(Y,G),D=n.mul(X,D),D=n.sub(D,K),K=n.mul(X,z),O=n.mul(Y,O),O=n.add(O,K),new x(D,_,O)}subtract(b){return this.add(b.negate())}is0(){return this.equals(x.ZERO)}multiply(b){const{endo:E}=e;if(!o.isValidNot0(b))throw new Error("invalid scalar: out of range");let C,L;const M=$=>R.cached(this,$,j=>Jt(x,j));if(E){const{k1neg:$,k1:j,k2neg:D,k2:_}=B(b),{p:O,f:q}=M(j),{p:H,f:K}=M(_);L=q.add(K),C=k(E.beta,O,H,$,D)}else{const{p:$,f:j}=M(b);C=$,L=j}return Jt(x,[C,L])[0]}multiplyUnsafe(b){const{endo:E}=e,C=this;if(!o.isValid(b))throw new Error("invalid scalar: out of range");if(b===yt||C.is0())return x.ZERO;if(b===Ur)return C;if(R.hasCache(this))return this.multiply(b);if(E){const{k1neg:L,k1:M,k2neg:$,k2:j}=B(b),{p1:D,p2:_}=zw(x,C,M,j);return k(E.beta,D,_,L,$)}else return R.unsafe(C,b)}multiplyAndAddUnsafe(b,E,C){const L=this.multiplyUnsafe(E).add(b.multiplyUnsafe(C));return L.is0()?void 0:L}toAffine(b){return T(this,b)}isTorsionFree(){const{isTorsionFree:b}=e;return i===Ur?!0:b?b(x,this):R.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:b}=e;return i===Ur?this:b?b(x,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(b=!0){return ir(b,"isCompressed"),this.assertValidity(),h(x,this,b)}toHex(b=!0){return tr(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(b=!0){return this.toBytes(b)}_setWindowSize(b){this.precompute(b)}static normalizeZ(b){return Jt(x,b)}static msm(b,E){return bf(x,o,b,E)}static fromPrivateKey(b){return x.BASE.multiply(Nr(o,b))}}x.BASE=new x(s.Gx,s.Gy,n.ONE),x.ZERO=new x(n.ZERO,n.ONE,n.ZERO),x.Fp=n,x.Fn=o;const S=o.BITS,R=new yf(x,e.endo?Math.ceil(S/2):S);return x.BASE.precompute(8),x}function Ff(t){return Uint8Array.of(t?2:3)}function Mf(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function ub(t,e={}){const{Fn:r}=t,n=e.randomBytes||tc,o=Object.assign(Mf(t.Fp,r),{seed:gf(r.ORDER)});function s(h){try{return!!Nr(r,h)}catch{return!1}}function i(h,g){const{publicKey:m,publicKeyUncompressed:y}=o;try{const w=h.length;return g===!0&&w!==m||g===!1&&w!==y?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return Hw(Qe(h,o.seed,"seed"),r.ORDER)}function c(h,g=!0){return t.BASE.multiply(Nr(r,h)).toBytes(g)}function l(h){const g=a(h);return{secretKey:g,publicKey:c(g)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:g,publicKey:m,publicKeyUncompressed:y}=o;if(r.allowedLengths||g===m)return;const w=fe("key",h).length;return w===m||w===y}function u(h,g,m=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(g)===!1)throw new Error("second arg must be public key");const y=Nr(r,h);return t.fromHex(g).multiply(y).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>Nr(r,h),precompute(h=8,g=t.BASE){return g.precompute(h,!1)}},lengths:o})}function fb(t,e,r={}){Gu(e),oo(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=r.randomBytes||tc,o=r.hmac||((E,...C)=>Df(e,E,ct(...C))),{Fp:s,Fn:i}=t,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h}=ub(t,r),g={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function y(E){const C=a>>Ur;return E>C}function w(E,C){if(!i.isValidNot0(C))throw new Error(`invalid signature ${E}: out of range 1..Point.Fn.ORDER`);return C}function I(E,C){ha(C);const L=h.signature,M=C==="compact"?L:C==="recovered"?L+1:void 0;return Qe(E,M,`${C} signature`)}class v{constructor(C,L,M){this.r=w("r",C),this.s=w("s",L),M!=null&&(this.recovery=M),Object.freeze(this)}static fromBytes(C,L=m){I(C,L);let M;if(L==="der"){const{r:_,s:O}=mt.toSig(Qe(C));return new v(_,O)}L==="recovered"&&(M=C[0],L="compact",C=C.subarray(1));const $=i.BYTES,j=C.subarray(0,$),D=C.subarray($,$*2);return new v(i.fromBytes(j),i.fromBytes(D),M)}static fromHex(C,L){return this.fromBytes(Go(C),L)}addRecoveryBit(C){return new v(this.r,this.s,C)}recoverPublicKey(C){const L=s.ORDER,{r:M,s:$,recovery:j}=this;if(j==null||![0,1,2,3].includes(j))throw new Error("recovery id invalid");if(a*Of<L&&j>1)throw new Error("recovery id is ambiguous for h>1 curve");const _=j===2||j===3?M+a:M;if(!s.isValid(_))throw new Error("recovery id 2 or 3 invalid");const O=s.toBytes(_),q=t.fromBytes(ct(Ff((j&1)===0),O)),H=i.inv(_),K=B(fe("msgHash",C)),z=i.create(-K*H),W=i.create($*H),X=t.BASE.multiplyUnsafe(z).add(q.multiplyUnsafe(W));if(X.is0())throw new Error("point at infinify");return X.assertValidity(),X}hasHighS(){return y(this.s)}toBytes(C=m){if(ha(C),C==="der")return Go(mt.hexFromSig(this));const L=i.toBytes(this.r),M=i.toBytes(this.s);if(C==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return ct(Uint8Array.of(this.recovery),L,M)}return ct(L,M)}toHex(C){return tr(this.toBytes(C))}assertValidity(){}static fromCompact(C){return v.fromBytes(fe("sig",C),"compact")}static fromDER(C){return v.fromBytes(fe("sig",C),"der")}normalizeS(){return this.hasHighS()?new v(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return tr(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return tr(this.toBytes("compact"))}}const A=r.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");const L=Cs(C),M=C.length*8-c;return M>0?L>>BigInt(M):L},B=r.bits2int_modN||function(C){return i.create(A(C))},T=no(c);function N(E){return ca("num < 2^"+c,E,yt,T),i.toBytes(E)}function k(E,C){return Qe(E,void 0,"message"),C?Qe(e(E),void 0,"prehashed message"):E}function x(E,C,L){if(["recovered","canonical"].some(z=>z in L))throw new Error("sign() legacy options not supported");const{lowS:M,prehash:$,extraEntropy:j}=si(L,g);E=k(E,$);const D=B(E),_=Nr(i,C),O=[N(_),N(D)];if(j!=null&&j!==!1){const z=j===!0?n(h.secretKey):j;O.push(fe("extraEntropy",z))}const q=ct(...O),H=D;function K(z){const W=A(z);if(!i.isValidNot0(W))return;const X=i.inv(W),G=t.BASE.multiply(W).toAffine(),Y=i.create(G.x);if(Y===yt)return;const se=i.create(X*i.create(H+Y*_));if(se===yt)return;let Pe=(G.x===Y?0:2)|Number(G.y&Ur),Oe=se;return M&&y(se)&&(Oe=i.neg(se),Pe^=1),new v(Y,Oe,Pe)}return{seed:q,k2sig:K}}function S(E,C,L={}){E=fe("message",E);const{seed:M,k2sig:$}=x(E,C,L);return Lw(e.outputLen,i.BYTES,o)(M,$)}function R(E){let C;const L=typeof E=="string"||ro(E),M=!L&&E!==null&&typeof E=="object"&&typeof E.r=="bigint"&&typeof E.s=="bigint";if(!L&&!M)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(M)C=new v(E.r,E.s);else if(L){try{C=v.fromBytes(fe("sig",E),"der")}catch($){if(!($ instanceof mt.Err))throw $}if(!C)try{C=v.fromBytes(fe("sig",E),"compact")}catch{return!1}}return C||!1}function P(E,C,L,M={}){const{lowS:$,prehash:j,format:D}=si(M,g);if(L=fe("publicKey",L),C=k(fe("message",C),j),"strict"in M)throw new Error("options.strict was renamed to lowS");const _=D===void 0?R(E):v.fromBytes(fe("sig",E),D);if(_===!1)return!1;try{const O=t.fromBytes(L);if($&&_.hasHighS())return!1;const{r:q,s:H}=_,K=B(C),z=i.inv(H),W=i.create(K*z),X=i.create(q*z),G=t.BASE.multiplyUnsafe(W).add(O.multiplyUnsafe(X));return G.is0()?!1:i.create(G.x)===q}catch{return!1}}function b(E,C,L={}){const{prehash:M}=si(L,g);return C=k(C,M),v.fromBytes(E,"recovered").recoverPublicKey(C).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h,Point:t,sign:S,verify:P,recoverPublicKey:b,Signature:v,hash:e})}function hb(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp;let n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0;const o=pr(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),s={Fp:r,Fn:o,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function pb(t){const{CURVE:e,curveOpts:r}=hb(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}function gb(t,e){const r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,hf(r.Fn.ORDER,r.Fn.BITS))})}function mb(t){const{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:o}=pb(t),s=db(e,r),i=fb(s,n,o);return gb(t,i)}function wb(t,e){const r=n=>mb({...t,hash:n});return{...r(e),create:r}}const fc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},yb={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Pl=BigInt(2);function bb(t){const e=fc.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,u=ue(d,r,e)*d%e,f=ue(u,r,e)*d%e,h=ue(f,Pl,e)*l%e,g=ue(h,o,e)*h%e,m=ue(g,s,e)*g%e,y=ue(m,a,e)*m%e,w=ue(y,c,e)*y%e,I=ue(w,a,e)*m%e,v=ue(I,r,e)*d%e,A=ue(v,i,e)*g%e,B=ue(A,n,e)*l%e,T=ue(B,Pl,e);if(!pa.eql(pa.sqr(T),t))throw new Error("Cannot find square root");return T}const pa=pr(fc.p,{sqrt:bb}),qt=wb({...fc,Fp:pa,lowS:!0,endo:yb},ef);function vb(t,e,r){const n=Ja.digest(e instanceof Uint8Array?e:e.subarray());if(Rs(n))return n.then(({digest:o})=>(r?.signal?.throwIfAborted(),qt.sign(o,t).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new kl(String(o))});try{return qt.sign(n.digest,t).toDERRawBytes()}catch(o){throw new kl(String(o))}}function xb(t,e,r,n){const o=Ja.digest(r instanceof Uint8Array?r:r.subarray());if(Rs(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),qt.verify(e,s,t))).catch(s=>{throw s.name==="AbortError"?s:new Il(String(s))});try{return n?.signal?.throwIfAborted(),qt.verify(e,o.digest,t)}catch(s){throw new Il(String(s))}}class jf{type="secp256k1";raw;_key;constructor(e){this._key=Ib(e),this.raw=Ab(this._key)}toMultihash(){return eo.digest(Ls(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return Ne.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:rt(this.raw,e.raw)}verify(e,r,n){return xb(this._key,r,e,n)}}class Sb{type="secp256k1";raw;publicKey;constructor(e,r){this.raw=kb(e),this.publicKey=new jf(r??Cb(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:rt(this.raw,e.raw)}sign(e,r){return vb(this.raw,e,r)}}function Eb(t){return new Sb(t)}function Uf(t){return new jf(t)}function Ab(t){return qt.ProjectivePoint.fromHex(t).toRawBytes(!0)}function kb(t){try{return qt.getPublicKey(t,!0),t}catch(e){throw new Lu(String(e))}}function Ib(t){try{return qt.ProjectivePoint.fromHex(t),t}catch(e){throw new Nu(String(e))}}function Cb(t){try{return qt.getPublicKey(t,!0)}catch(e){throw new Lu(String(e))}}async function Rb(t,e){return wy()}function ga(t,e){const{Type:r,Data:n}=ar.decode(t),o=n??new Uint8Array;switch(r){case le.RSA:return eb(o,e);case le.Ed25519:return Af(o);case le.secp256k1:return Uf(o);case le.ECDSA:return Vu(o);default:throw new Es}}function Tb(t){const{Type:e,Data:r}=ar.decode(t.digest),n=r??new Uint8Array;switch(e){case le.Ed25519:return Af(n);case le.secp256k1:return Uf(n);case le.ECDSA:return Vu(n);default:throw new Es}}function Ls(t){return ar.encode({Type:le[t.type],Data:t.raw})}function Pb(t){const e=es.decode(t),r=e.Data??new Uint8Array;switch(e.Type){case le.RSA:return Jy(r);case le.Ed25519:return my(r);case le.secp256k1:return Eb(r);case le.ECDSA:return iw(r);default:throw new Es}}function Nb(t){return es.encode({Type:le[t.type],Data:t.raw})}const $f=Symbol.for("nodejs.util.inspect.custom"),Lb=114;class hc{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Bu]=!0;toString(){return this.string==null&&(this.string=Ne.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ce.createV1(Lb,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return rt(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return rt(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[$f](){return`PeerId(${this.toString()})`}}class Hf extends hc{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class qf extends hc{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class Kf extends hc{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}const Bb=2336;class zf{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=eo.digest(we(this.url))}[$f](){return`PeerId(${this.url})`}[Bu]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ce.createV1(Bb,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=J(e)),e.toString()===this.toString())}}const _b=114,Nl=2336;function Db(t,e){let r;if(t.charAt(0)==="1"||t.charAt(0)==="Q")r=Ou(Ne.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return Ob(ce.parse(t));throw new tt('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return Vf(r)}function Zr(t){if(t.type==="Ed25519")return new qf({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new Kf({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new Hf({multihash:t.toCID().multihash,publicKey:t});throw new Es}function Vf(t){if(Mb(t))return new Hf({multihash:t});if(Fb(t))try{const e=Tb(t);if(e.type==="Ed25519")return new qf({multihash:t,publicKey:e});if(e.type==="secp256k1")return new Kf({multihash:t,publicKey:e})}catch{const r=J(t.digest);return new zf(new URL(r))}throw new yg("Supplied PeerID Multihash is invalid")}function Ob(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==_b&&t.code!==Nl)throw new wg("Supplied PeerID CID is invalid");if(t.code===Nl){const e=J(t.multihash.digest);return new zf(new URL(e))}return Vf(t.multihash)}function Fb(t){return t.code===eo.code}function Mb(t){return t.code===Ja.code}class Wf extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}}class jb extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class gn extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}class Ll extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}}class Ub extends Event{data;constructor(e,r){super("message",r),this.data=e}}class pc extends Event{error;local;constructor(e,r,n){super("close",n),this.error=r,this.local=e}}class $b extends pc{constructor(e,r){super(!0,e,r)}}class Hb extends pc{constructor(e,r){super(!1,e,r)}}const qb=t=>t/2**32|0,Kb=t=>t>>>0;function zb(t,e,r,n){const o=qb(r),s=Kb(r);t.setUint32(e,n?s:o,n),t.setUint32(e+4,n?o:s,n)}function ma(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const wa=t=>t?`"${t}" `:"";function It(t,e=""){if(typeof t!="number")throw new TypeError(wa(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(wa(e)+"expected integer >= 0, got "+t);return t}function Ct(t,e,r=""){if(ma(t)&&(e===void 0||t.length===e))return t;e!==void 0&&It(e,"length");const n=ma(t),o=e!==void 0?` of length ${e}`:"",s=n?`length=${t.length}`:`type=${typeof t}`,i=wa(r)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}function gc(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(It(t.outputLen),It(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}const Vb=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)},Bl=(t,e)=>{Vb(t,e);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(t,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function ts(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function Gf(t,e){Ct(t,void 0,"output");const r=e.outputLen;if(!(t.length>=r))throw new RangeError('"output" expected length >= '+r)}function _k(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function nr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function ii(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function it(t,e){return t<<32-e|t>>>e}function Dk(t,e){return t<<e|t>>>32-e>>>0}const Wb=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Gb(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Xb(t){for(let e=0;e<t.length;e++)t[e]=Gb(t[e]);return t}const Ok=Wb?t=>t:Xb,Xf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Yb=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function mc(t){if(Ct(t),Xf)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Yb[t[r]];return e}function _l(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function Yf(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Xf)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}const e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){const i=_l(t.charCodeAt(s)),a=_l(t.charCodeAt(s+1));if(i===void 0||a===void 0){const c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Zb(t){const e=globalThis;if(typeof e.scheduler?.yield=="function"){const r=e.scheduler.yield();return t&&r.catch(t),r}return new Promise(r=>e.setTimeout(r,0))}async function Fk(t,e,r,n){if(It(t,"iters"),It(e,"tick"),typeof r!="function")throw new TypeError("callback must be a function");let o=Date.now();for(let s=0;s<t;s++){r(s);const i=Date.now()-o;i>=0&&i<e||(await Zb(n),o=Date.now())}}function Jb(t){if(typeof t!="string")throw new TypeError("string expected");const e=new TextEncoder().encode(t);try{return new Uint8Array(e)}finally{nr(e)}}function Mk(t,e=""){return typeof t=="string"?Jb(t):Ct(t,void 0,e)}function Qb(t,e,r="opts"){return Bl(t,"defaults"),e!==void 0&&Bl(e,r),Object.assign(Object.create(null),t,e)}function e0(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=Qb({},e,"info");const r=(o,s)=>t(s).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function t0(t=32){It(t,"bytesLength");const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}const r0=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function n0(t,e,r){return t&e^~t&r}function o0(t,e,r){return t&e^t&r^e&r}class s0{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,o){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=ii(this.buffer)}update(e){ts(this),Ct(e);const{view:r,buffer:n,blockLen:o}=this,s=e.length;let i=!1;for(let a=0;a<s;){const c=Math.min(o-this.pos,s-a);if(c===o){const l=ii(e);for(;o<=s-a;a+=o)this.process(l,a);i=!0;continue}n.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(r,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){ts(this),Gf(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:o,isLE:s}=this;let{pos:i}=this;r[i++]=128,r.fill(0,i),this.padOffset>o-i&&(this.process(n,0),r.fill(0)),zb(n,o-8,this.length*8,s),this.process(n,0),this.roundClean();const a=e===r?n:ii(e),c=this.outputLen,l=c/4,d=this.get();if(c%4||l>d.length)throw new Error("invalid outputLen");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneIntoMeta(e){const{buffer:r,length:n,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=n,e.pos=i,i&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const i0=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),a0=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),_t=new Uint32Array(64);class c0 extends s0{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,r){super(64,e,8,!1),this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){const{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,r){for(let u=0;u<16;u++,r+=4)_t[u]=e.getUint32(r,!1);for(let u=16;u<64;u++){const f=_t[u-15],h=_t[u-2],g=it(f,7)^it(f,18)^f>>>3,m=it(h,17)^it(h,19)^h>>>10;_t[u]=m+_t[u-7]+g+_t[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=it(a,6)^it(a,11)^it(a,25),h=d+f+n0(a,c,l)+a0[u]+_t[u]|0,m=(it(n,2)^it(n,13)^it(n,22))+o0(n,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,l,d)}roundClean(){nr(_t)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),nr(this.buffer)}}class l0 extends c0{constructor(){super(32,i0)}}const ai=e0(()=>new l0,r0(1));function Zf(t,e,r=()=>{}){if(!Array.isArray(t))throw new TypeError(`"${e}" expected array, got type=${typeof t}`);for(let n=0;n<t.length;n++)r(t[n],`${e}[${n}]`);return t}const $r=(t,e,r)=>Ct(t,e,r),Jf=It;function Hr(t,e="object"){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`);return t}function On(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}const d0=mc,u0=t=>Yf(t),Qf=ma,eh=t=>t0(t),rs=BigInt(0),Dl=BigInt(1),f0=t=>t?`"${t}" `:"";function Bs(t,e=""){if(typeof t!="boolean")throw new TypeError(f0(e)+"expected boolean, got type="+typeof t);return t}function h0(t){if(typeof t=="bigint"){if(!or(t))throw new RangeError("positive bigint expected, got "+t)}else Jf(t);return t}function ya(t,e=""){if(typeof t!="number"){const r=e&&`"${e}" `;throw new TypeError(r+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){const r=e&&`"${e}" `;throw new RangeError(r+"expected safe integer, got "+t)}}function th(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?rs:BigInt("0x"+t)}function rh(t){return th(mc(t))}function ns(t){return th(mc(zn(Ct(t)).reverse()))}function nh(t,e){if(It(e),e===0)throw new Error("zero output length is invalid");t=h0(t);const r=e*2,n=t.toString(16);if(n.length>r)throw new RangeError("number is too large");return Yf(n.padStart(r,"0"))}function oh(t,e){return nh(t,e).reverse()}function zn(t){return Uint8Array.from($r(t))}function or(t){return typeof t=="bigint"&&rs<=t}function sh(t,e,r){return or(t)&&or(e)&&or(r)&&e<=t&&t<r}function Fn(t,e,r,n){if(!sh(e,r,n))throw new RangeError("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function p0(t){if(t<rs)throw new Error("expected non-negative bigint, got "+t);return t===rs?0:t.toString(2).length}const g0=t=>(ya(t,"n"),(Dl<<BigInt(t))-Dl);function os(t,e={},r={},n="object"){Hr(t,n),Hr(e,"fields"),Hr(r,"optFields");function o(i,a,c){const l=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,d=t[i];if(!Object.hasOwn(t,i)&&(c?d!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&d===void 0)return;const u=typeof d;if(u!==a||d===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${u}`)}const s=(i,a)=>Object.entries(i).forEach(([c,l])=>o(c,l,a));s(e,!1),s(r,!0)}const xe=BigInt(0),ae=BigInt(1),Qt=BigInt(2),ih=BigInt(3),wc=BigInt(4),ah=BigInt(5),m0=BigInt(7),ch=BigInt(8),w0=BigInt(9),y0=BigInt(15),lh=BigInt(16),b0=BigInt("0x10000000000000000");function ie(t,e){if(e<=xe)throw new Error("mod: expected positive modulus, got "+e);const r=t%e;return r>=xe?r:e+r}function v0(t,e,r){if(r<=ae)throw new Error("pow: expected modulus > 1, got "+r);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<xe)throw new Error("invalid exponent, negatives unsupported");if(e===xe)return ae;if(e===ae)return t;let n=t%r;if(n<xe&&(n+=r),e<b0){let a=ae;for(;e>xe;)e&ae&&(a=a*n%r),n=n*n%r,e>>=ae;return a}const o=[];for(;e>xe;)o.push(Number(e&y0)),e>>=wc;const s=new Array(16);s[0]=ae,s[1]=n;for(let a=2;a<16;a++)s[a]=s[a-1]*n%r;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%r,i=i*i%r,i=i*i%r,i=i*i%r;const c=o[a];c!==0&&(i=i*s[c]%r)}return i}function Je(t,e,r){if(r<=ae)throw new Error("pow2: expected modulus > 1, got "+r);if(e<xe)throw new Error("pow2: expected non-negative exponent, got "+e);let n=t;for(;e-- >xe;)n*=n,n%=r;return n}function Ol(t,e){if(t===xe)throw new Error("invert: expected non-zero number");if(e<=ae)throw new Error("invert: expected modulus > 1, got "+e);let r=ie(t,e),n=e,o=xe,s=ae;for(;r!==xe;){const a=n/r,c=n-r*a,l=o-s*a;n=r,r=c,o=s,s=l}if(n!==ae)throw new Error("invert: does not exist");return ie(o,e)}function yc(t,e,r){const n=t;if(!n.eql(n.sqr(e),r))throw new Error("Cannot find square root")}function bc(t,e){if((t&ae)===xe)throw new Error(e+": expected odd modulus, got "+t)}function dh(t,e){const r=t,n=(r.ORDER+ae)/wc,o=r.pow(e,n);return yc(r,o,e),o}function x0(t,e){const r=t,n=(r.ORDER-ah)/ch,o=r.mul(e,Qt),s=r.pow(o,n),i=r.mul(e,s),a=r.mul(r.mul(i,Qt),s),c=r.mul(i,r.sub(a,r.ONE));return yc(r,c,e),c}function S0(t){const e=vc(t),r=uh(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+m0)/lh;return((a,c)=>{const l=a;let d=l.pow(c,i),u=l.mul(d,n);const f=l.mul(d,o),h=l.mul(d,s),g=l.eql(l.sqr(u),c),m=l.eql(l.sqr(f),c);d=l.cmov(d,u,g),u=l.cmov(h,f,m);const y=l.eql(l.sqr(u),c),w=l.cmov(d,u,y);return yc(l,w,c),w})}function uh(t){if(t<ih)throw new Error("sqrt is not defined for small field");bc(t,"tonelliShanks");let e=t-ae,r=0;for(;e%Qt===xe;)e/=Qt,r++;let n=Qt;const o=vc(t);for(;ss(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return dh;let s=o.pow(n,e);const i=(e+ae)/Qt;return function(c,l){const d=c;if(d.is0(l))return l;if(ss(d,l)!==1)throw new Error("Cannot find square root");let u=r,f=d.mul(d.ONE,s),h=d.pow(l,e),g=d.pow(l,i);for(;!d.eql(h,d.ONE);){if(d.is0(h))throw new Error("Cannot find square root: probably non-prime P");let m=1,y=d.sqr(h);for(;!d.eql(y,d.ONE);)if(m++,y=d.sqr(y),m===u)throw new Error("Cannot find square root");const w=ae<<BigInt(u-m-1),I=d.pow(f,w);u=m,f=d.sqr(I),h=d.mul(h,f),g=d.mul(g,I)}return g}}function E0(t){return bc(t,"Fp.sqrt"),t%wc===ih?dh:t%ch===ah?x0:t%lh===w0?S0(t):uh(t)}const A0=(t,e)=>(ie(t,e)&ae)===ae,k0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Vn(t){if(Hr(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);ya(t.BYTES,"BYTES"),ya(t.BITS,"BITS");for(const e of k0)On(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=ae)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function fh(t,e,r=!1){Vn(t),Zf(e,"nums"),Bs(r,"passZero");const n=t,o=new Array(e.length).fill(r?n.ZERO:void 0),s=e.reduce((a,c,l)=>n.is0(c)?a:(o[l]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,l)=>n.is0(c)?a:(o[l]=n.mul(a,o[l]),n.mul(a,c)),i),o}function ss(t,e){Vn(t);const r=t;bc(r.ORDER,"FpLegendre");const n=(r.ORDER-ae)/Qt,o=r.pow(e,n),s=r.eql(o,r.ONE),i=r.eql(o,r.ZERO),a=r.eql(o,r.neg(r.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function I0(t,e){if(e!==void 0&&Jf(e),t<=xe)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);const r=p0(t);if(e!==void 0&&e<r)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${r})`);const n=e!==void 0?e:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}const Fl=new WeakMap;class Ml{ORDER;BITS;BYTES;isLE;ZERO=xe;ONE=ae;_lengths;_mod;constructor(e,r={}){if(e<=ae)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));const{nBitLength:o,nByteLength:s}=I0(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return ie(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return xe<=e&&e<this.ORDER}is0(e){return e===xe}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ae)===ae}neg(e){return ie(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return ie(e*e,this.ORDER)}add(e,r){return ie(e+r,this.ORDER)}sub(e,r){return ie(e-r,this.ORDER)}mul(e,r){return ie(e*r,this.ORDER)}pow(e,r){return v0(e,r,this.ORDER)}div(e,r){return ie(e*Ol(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return Ol(e,this.ORDER)}sqrt(e){let r=Fl.get(this);return r||Fl.set(this,r=E0(this.ORDER)),r(this,e)}toBytes(e){return this.isLE?oh(e,this.BYTES):nh(e,this.BYTES)}fromBytes(e,r=!1){$r(e);const{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);const l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?ns(e):rh(e);if(a&&(c=ie(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return fh(this,e,!0)}cmov(e,r,n){return Bs(n,"condition"),n?r:e}}function vc(t,e={}){return Object.freeze(Ml.prototype),new Ml(t,e)}const xc=BigInt(0),Wn=BigInt(1),C0=BigInt(4),ci=16,jl=128,R0=5,Ul=2**31;function Sc(t){const e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);On(e.fromAffine,"Point.fromAffine"),On(e.fromBytes,"Point.fromBytes"),On(e.fromHex,"Point.fromHex"),Hr(e.BASE,"Point.BASE"),Hr(e.ZERO,"Point.ZERO"),Vn(e.Fp),Vn(e.Fn)}function T0(t,e){Sc(t),hh(e,t);const r=fh(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function P0(t,e,r=1){if(!Number.isSafeInteger(t)||t<r||t>e)throw new Error("invalid window size, expected ["+r+".."+e+"], got W="+t)}function N0(t,e){const r=t*(4*e+128);if(r>Ul)throw new Error("invalid window size: table would need ~"+Math.ceil(r/2**20)+" MiB, max "+Ul/2**20+" MiB")}function L0(t,e){if(t!==void 0){On(t,"randomBytes");try{const r=t(e);if(!Qf(r)||r.length!==e)return}catch{return}return t}}function hh(t,e){Zf(t,"points"),t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function B0(t,e,r){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,o)=>{if(!(r===void 0?e.isValid(n):or(n)&&n<r))throw new Error("invalid scalar at index "+o)})}const ph=new WeakMap;function li(t){return ph.get(t)||1}function _0(t,e){const r=t.double(),n=[t];for(let o=1;o<e;o++)n.push(n[o-1].add(r));return n}function D0(t,e){const r=2**e,n=r/2,o=BigInt(r-1),s=[];for(;t>xc;){let i=0;t&Wn&&(i=Number(t&o),i>=n&&(i-=r),t-=BigInt(i)),s.push(i),t>>=Wn}return s}function O0(t,e,r){const n=2**e,o=n/2,s=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<r;c++){let l=Number(t&s);t>>=i,l>o&&(l-=n,t+=Wn),a.push(l)}if(t!==xc)throw new Error("invalid wnaf");return a}function F0(t,e,r){let n=0;for(const s of r)n=Math.max(n,s.length);let o=t;for(let s=n-1;s>=0;s--){s!==n-1&&(o=o.double());for(let i=0;i<r.length;i++){const a=r[i][s];if(a){const c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}class M0{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,r){Sc(e),this.randomBytes=L0(r,ci),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,r,n){const o=Math.ceil(n/r)+1,s=2**(r-1),i=[];let a=e;for(let c=0;c<o;c++){let l=a;for(let d=0;d<s;d++)i.push(l),l=l.add(a);a=i[i.length-1].double()}return{W:r,bits:n,windows:o,comp:i}}wnafCachedCT(e,r){const{W:n,windows:o,comp:s}=e,i=2**(n-1),a=O0(r,n,o);let c=this.ZERO,l=this.BASE;for(let d=0;d<o;d++){const u=a[d],f=d*i,h=Math.abs(u)-1;let g=s[f];for(let y=1;y<i;y++)g=y===h?s[f+y]:g;const m=g.negate();u===0?l=l.add(s[f]):c=c.add(u<0?m:g)}return{p:c,f:l}}getWnafPrecomputes(e,r,n,o){let s=this.wnafPrecomputes.get(r),i=s?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(r,e,n),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(r,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,r){if(this.assertPoint(e),!sh(r,Wn,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,r,n,o){const s=li(e);return s===1?this.fixedWindowCT(e,r,n):this.wnafCachedCT(this.getWnafPrecomputes(s,e,n,o),r)}mulCT(e,r,n){return this.validateMulInput(e,r),this.runCT(e,r,this.bits,n)}mulCTBlinded(e,r,n){if(this.validateMulInput(e,r),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");const o=this.Point.Fn.BITS+jl,s=this.randomBytes(ci);if(!Qf(s)||s.length!==ci)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;const i=r+rh(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,n)}fixedWindowCT(e,r,n){const o=R0,s=1<<o,i=g0(o),a=new Array(s);a[0]=this.ZERO;for(let d=1;d<s;d++)a[d]=a[d-1].add(e);const c=Math.ceil(n/o);let l=this.ZERO;for(let d=c-1;d>=0;d--){if(d!==c-1)for(let h=0;h<o;h++)l=l.double();const u=Number(r>>BigInt(d*o)&i);let f=a[0];for(let h=1;h<s;h++)f=h===u?a[h]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(e,r){return this.randomBytes===void 0?!1:r===Wn?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,r,n,o){return this.shouldBlind(e,n)?this.mulCTBlinded(e,r,o):this.mulCT(e,r,o)}mulUnsafe(e,r,n){if(this.assertPoint(e),!or(r))throw new Error("invalid scalar");const o=li(e);if(o===1||r>=this.Point.Fn.ORDER)return j0(this.Point,[e],[r],!0);const s=this.getWnafPrecomputes(o,e,this.bits,n);return this.wnafCachedCT(s,r).p}setWindowSize(e,r){this.assertPoint(e),P0(r,this.bits);const n=Math.ceil((this.bits+jl)/r)+1;N0(n*2**(r-1),this.Point.Fp.BYTES),ph.set(e,r),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return li(e)!==1}}function j0(t,e,r,n=!1){if(Sc(t),hh(e,t),Bs(n,"allowOversized"),B0(r,t.Fn,n?t.Fn.ORDER**C0:void 0),e.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const o=e.map(i=>_0(i,4)),s=r.map(i=>D0(i,4));return F0(t.ZERO,o,s)}function $l(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Vn(e),e}else return vc(t,{isLE:r})}function U0(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);os(r);for(const c of["p","n","h"]){const l=e[c];if(!(or(l)&&l!==xc))throw new Error(`CURVE.${c} must be positive bigint`)}const o=$l(e.p,r.Fp,n),s=$l(e.n,r.Fn,n),a=["Gx","Gy","a","d"];for(const c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function $0(t,e){return function(n){const o=t(n);return{secretKey:o,publicKey:e(o)}}}const xo=BigInt(0),So=BigInt(1),Eo=BigInt(2),H0=BigInt(4),Hl=BigInt(8);function q0(t,e,r,n){const o=t.sqr(r),s=t.sqr(n),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function K0(t,e={}){os(e,{},{},"extraOpts");const r=e,n=U0("edwards",t,r,r.FpFnLE),{Fp:o,Fn:s}=n;let i=n.CURVE;const{h:a}=i;if(ss(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(ss(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");os(r,{},{uvRatio:"function",randomBytes:"function"});const c=r.randomBytes===void 0?eh:r.randomBytes,l=Eo<<BigInt(o.BYTES*8)-So;function d(I){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(I)}const u=r.uvRatio===void 0?(I,v)=>{try{return{isValid:!0,value:o.sqrt(o.div(I,v))}}catch{return{isValid:!1,value:xo}}}:r.uvRatio;if(!q0(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");const f=o.eql(i.a,o.neg(o.ONE))?I=>o.neg(I):o.eql(i.a,o.ONE)?I=>I:I=>o.mul(i.a,I);function h(I,v,A=!1){const B=A?So:xo;return Fn("coordinate "+I,v,B,l),v}function g(I){if(!(I instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(i.Gx,i.Gy,o.ONE,o.mul(i.Gx,i.Gy));static ZERO=new m(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(v,A,B,T){this.X=h("x",v),this.Y=h("y",A),this.Z=h("z",B,!0),this.T=h("t",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(v){if(v instanceof m)throw new Error("extended point not allowed");const{x:A,y:B}=v||{};return h("x",A),h("y",B),new m(A,B,o.ONE,o.mul(A,B))}static fromBytes(v,A=!1){const B=o.BYTES,{a:T,d:N}=i;v=zn($r(v,B,"point")),Bs(A,"zip215");const k=zn(v),x=v[B-1];k[B-1]=x&-129;const S=ns(k),R=A?l:o.ORDER;Fn("point.y",S,xo,R);const P=o.sqr(S),b=o.sub(P,o.ONE),E=o.sub(o.mulN(N,P),T);let{isValid:C,value:L}=u(b,E);if(!C)throw new Error("bad point: invalid y coordinate");const M=d(L),$=(x&128)!==0;if(!A&&o.is0(L)&&$)throw new Error("bad point: x=0 and x_0=1");return $!==M&&(L=o.neg(L)),m.fromAffine({x:L,y:S})}static fromHex(v,A=!1){return m.fromBytes(u0(v),A)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=6,A=!0){return w.setWindowSize(this,v),A||this.multiply(Eo),this}assertValidity(){const v=this,{a:A,d:B}=i;if(v.is0())throw new Error("bad point: ZERO");const{X:T,Y:N,Z:k,T:x}=v,S=o.sqr(T),R=o.sqr(N),P=o.sqr(k),b=o.sqr(P),E=o.mul(S,A),C=o.mul(o.add(E,R),P),L=o.add(b,o.mul(B,o.mul(S,R)));if(!o.eql(C,L))throw new Error("bad point: equation left != right (1)");const M=o.mul(T,N),$=o.mul(k,x);if(!o.eql(M,$))throw new Error("bad point: equation left != right (2)")}equals(v){g(v);const{X:A,Y:B,Z:T}=this,{X:N,Y:k,Z:x}=v,S=o.mul(A,x),R=o.mul(N,T),P=o.mul(B,x),b=o.mul(k,T);return o.eql(S,R)&&o.eql(P,b)}is0(){return this.equals(m.ZERO)}negate(){return new m(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){const{X:v,Y:A,Z:B}=this,T=o.sqr(v),N=o.sqr(A),k=o.mul(o.sqr(B),Eo),x=f(T),S=o.addN(v,A),R=o.sub(o.subN(o.sqr(S),T),N),P=o.addN(x,N),b=o.subN(P,k),E=o.subN(x,N),C=o.mul(R,b),L=o.mul(P,E),M=o.mul(R,E),$=o.mul(b,P);return new m(C,L,$,M)}add(v){g(v);const{d:A}=i,{X:B,Y:T,Z:N,T:k}=this,{X:x,Y:S,Z:R,T:P}=v,b=o.mul(B,x),E=o.mul(T,S),C=o.mul(o.mulN(k,A),P),L=o.mul(N,R),M=o.sub(o.subN(o.mulN(o.addN(B,T),o.addN(x,S)),b),E),$=o.subN(L,C),j=o.addN(L,C),D=o.sub(E,f(b)),_=o.mul(M,$),O=o.mul(j,D),q=o.mul(M,D),H=o.mul($,j);return new m(_,O,H,q)}subtract(v){return g(v),this.add(v.negate())}multiply(v){if(!s.isValidNot0(v))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");const{p:A,f:B}=w.mulSecret(this,v,a,y);return y([A,B])[0]}multiplyUnsafe(v){if(!s.isValid(v))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return v===xo?m.ZERO:this.is0()||v===So?this:w.mulUnsafe(this,v,y)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.mulUnsafe(this,i.n).is0()}toAffine(v){const A=this;let B=v;if(B!=null&&typeof B!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof B);const{X:T,Y:N,Z:k}=A,x=A.is0();B==null&&(B=x?o.create(Hl):o.inv(k));const S=o.mul(T,B),R=o.mul(N,B),P=o.mul(k,B);if(x)return{x:o.ZERO,y:o.ONE};if(!o.eql(P,o.ONE))throw new Error("invZ was invalid");return{x:S,y:R}}clearCofactor(){return a===So?this:a===Eo?this.double():a===H0?this.double().double():a===Hl?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){const{x:v,y:A}=this.toAffine(),B=o.toBytes(A);return B[B.length-1]|=d(v)?128:0,B}toHex(){return d0(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const y=I=>T0(m,I),w=new M0(m,c);return w.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}const Wt=BigInt(0),ze=BigInt(1),Ao=BigInt(2);function ql(t,e){return t+e-(e>>ze<<ze)}function z0(t){const e=BigInt(6)*t;return(r,n,o)=>{const s=n+o,a=((e+o-n)*r+n)%t;return{x_2:a,x_3:s-a}}}function V0(t){return os(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...t})}function W0(t){const e=V0(t),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=e.scalarMultBase,c=n==="x25519";if(!c&&n!=="x448")throw new Error("invalid type");const l=i===void 0?eh:i,d=c?255:448,u=z0(r),f=c?32:56,h=BigInt(c?9:5),g=BigInt(c?121665:39081),m=c?Ao**BigInt(254):Ao**BigInt(447),y=c?BigInt(8)*(Ao**BigInt(251)-ze):BigInt(4)*(Ao**BigInt(445)-ze),w=m+y+ze,I=L=>ie(L,r),v=A(h);function A(L){return oh(I(L),f)}function B(L){const M=zn($r(L,f,"uCoordinate"));return c&&(M[31]&=127),I(ns(M))}function T(L){return ns(o(zn($r(L,f,"scalar"))))}const N=new Set(c?[Wt,ze,r-ze,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[Wt,ze,r-ze]);function k(L,M){const $=B(M);if(N.has($))throw new Error("invalid private or public key received");const j=P($,T(L));if(j===Wt)throw new Error("invalid private or public key received");return A(j)}function x(L){if(a===void 0)return k(L,v);const M=T(L);Fn("scalar",M,m,w);const $=I(a(M));if($===Wt)throw new Error("invalid private or public key received");return A($)}const S=x,R=k;function P(L,M){Fn("u",L,Wt,r),Fn("scalar",M,m,w);const $=M,j=L;let D=ze,_=Wt,O=L,q=ze;const H=$^$>>ze;for(let W=BigInt(d-1);W>=Wt;W--){const X=ql(r,H>>W);({x_2:D,x_3:O}=u(X,D,O)),{x_2:_,x_3:q}=u(X,_,q);const G=D+_,Y=I(G*G),se=D-_,Pe=I(se*se),Oe=Y-Pe,oe=O+q,ot=O-q,vr=I(ot*G),Rt=I(oe*se),Xe=vr+Rt,ao=vr-Rt;O=I(Xe*Xe),q=I(j*I(ao*ao)),D=I(Y*Pe),_=I(Oe*(Y+I(g*Oe)))}const K=ql(r,$);({x_2:D,x_3:O}=u(K,D,O)),{x_2:_,x_3:q}=u(K,_,q);const z=s(_);return I(D*z)}const b={secretKey:f,publicKey:f,seed:f},E=L=>(L=L===void 0?l(f):L,$r(L,b.seed,"seed"),L),C={randomSecretKey:E};return Object.freeze(b),Object.freeze(C),Object.freeze({keygen:$0(E,S),getSharedSecret:R,getPublicKey:S,scalarMult:k,scalarMultBase:x,utils:C,GuBytes:v.slice(),lengths:b})}const Kl=BigInt(0),G0=BigInt(1),zl=BigInt(2),X0=BigInt(3),Y0=BigInt(5),Z0=BigInt(8),_s=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),J0={p:_s,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Z0,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function gh(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=_s,a=t*t%s*t%s,c=Je(a,zl,s)*a%s,l=Je(c,G0,s)*t%s,d=Je(l,Y0,s)*l%s,u=Je(d,e,s)*d%s,f=Je(u,r,s)*u%s,h=Je(f,n,s)*f%s,g=Je(h,o,s)*h%s,m=Je(g,o,s)*h%s,y=Je(m,e,s)*d%s;return{pow_p_5_8:Je(y,zl,s)*t%s,b2:a}}function Q0(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Vl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ev(t,e){const r=_s,n=ie(e*e*e,r),o=ie(n*n*e,r),s=gh(t*o).pow_p_5_8;let i=ie(t*n*s,r);const a=ie(e*i*i,r),c=i,l=ie(i*Vl,r),d=a===t,u=a===ie(-t,r),f=a===ie(-t*Vl,r);return d&&(i=c),(u||f)&&(i=l),A0(i,r)&&(i=ie(-i,r)),{isValid:d||u,value:i}}const Wl=K0(J0,{uvRatio:ev}),ko=(()=>{const t=_s,e=r=>{const{pow_p_5_8:n,b2:o}=gh(r);return ie(Je(n,X0,t)*o,t)};return W0({P:t,type:"x25519",powPminus2:e,adjustScalarBytes:Q0,scalarMultBase:r=>{const n=ie(r,Wl.Fn.ORDER);if(n===Kl)return Kl;const o=Wl.BASE.multiply(n);return ie((o.Z+o.Y)*e(ie(o.Z-o.Y,t)),t)}})})();class Gl{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(gc(e),Ct(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),nr(o)}update(e){return ts(this),this.iHash.update(e),this}digestInto(e){ts(this),Gf(e,this),this.finished=!0;const r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});const{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const mh=(()=>{const t=((e,r,n)=>new Gl(e,r).update(n).digest());return t.create=(e,r)=>new Gl(e,r),t})();function Xl(){const t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}class Yl{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}}class di{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Yl(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){const r=this.head;this.head=r.next=new Yl(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){const r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}class tv extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}}function rv(t={}){return nv(r=>{const n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function nv(t,e){e=e??{};let r=e.onEnd,n=new di,o,s,i,a=Xl();const c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,w)=>{s=I=>{s=null,n.push(I);try{y(t(n))}catch(v){w(v)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Xl()})}},l=y=>s!=null?s(y):(n.push(y),o),d=y=>(n=new di,s!=null?s({error:y}):(n.push({error:y}),o)),u=y=>{if(i)return o;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},f=y=>i?o:(i=!0,y!=null?d(y):l({done:!0})),h=()=>(n=new di,f(),{done:!0}),g=y=>(f(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:g,push:u,end:f,get readableLength(){return n.size},onEmpty:async y=>{const w=y?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let I,v;w!=null&&(I=new Promise((A,B)=>{v=()=>{B(new tv)},w.addEventListener("abort",v)}));try{await Promise.race([a.promise,I])}finally{v!=null&&w!=null&&w?.removeEventListener("abort",v)}}},r==null)return o;const m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),r!=null&&(r(y),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:u,end(y){return m.end(y),r!=null&&(r(y),r=void 0),o},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},o}class Ec extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,Ec)}}const Zl=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function ov(t,e){const{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e;let a,c;const d=new Promise((u,f)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){f(Zl(i));return}if(i&&(c=()=>{f(Zl(i))},i.addEventListener("abort",c,{once:!0})),t.then(u,f),r===Number.POSITIVE_INFINITY)return;const h=new Ec;a=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(g){f(g)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?u():o instanceof Error?f(o):(h.message=o??`Promise timed out after ${r} milliseconds`,f(h))},r)}).finally(()=>{d.clear(),c&&i&&i.removeEventListener("abort",c)});return d.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},d}const sv=t=>{const e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function iv(t,e,r){let n;const o=new Promise((s,i)=>{if(r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();const a=[e].flat(),c=[],{addListener:l,removeListener:d}=sv(t),u=async(...h)=>{const g=r.multiArgs?h:h[0];if(r.filter)try{if(!await r.filter(g))return}catch(m){n(),i(m);return}c.push(g),r.count===c.length&&(n(),s(c))},f=(...h)=>{n(),i(r.rejectionMultiArgs?h:h[0])};n=()=>{for(const h of a)d(h,u);for(const h of r.rejectionEvents)a.includes(h)||d(h,f)};for(const h of a)l(h,u);for(const h of r.rejectionEvents)a.includes(h)||l(h,f);r.signal&&r.signal.addEventListener("abort",()=>{f(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){const s=ov(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function av(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};const n=iv(t,e,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}class is extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class cv extends Error{static name="StreamClosedError";name="StreamClosedError"}function lv(t){return t.reason}function wh(t,e,r){if(e==null||t==null)return t;const n=lv;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let o;return Promise.race([t,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}const dv=Math.pow(2,20)*4;class yh extends Sg{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??dv,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new re,this.writeBuffer=new re,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);const r=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",r);const n=o=>{this.onDrainPromise?.reject(o.error??new cv)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),wh(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;const e=rv(),r=s=>{e.push(s.data)};this.addEventListener("message",r);const n=s=>{e.end(s.error)};this.addEventListener("close",n);const o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new gn(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new $b(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new gn("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new gn("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new gn(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new gn(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");const e=new jb;this.dispatchEvent(new Hb(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new pc))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0;const r=this.writeBuffer.byteLength;let n=0;for(;this.writeBuffer.byteLength>0;){const o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}const s=this.writeBuffer.sublist(0,o),i=new re(s);this.writeBuffer.consume(s.byteLength);const a=this.sendData(s);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,r,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}const e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new Ub(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Ll(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Ll(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}}const uv=4194304;class Jl extends Error{static name="UnwrappedError";name="UnwrappedError"}class bh extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class fv extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class hv extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function pv(t){return typeof t?.closeRead=="function"}function gv(t){return typeof t?.close=="function"}function ui(t){return pv(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:gv(t)?t.status!=="open":!1}function mv(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function wv(t,e){const r=e?.maxBufferSize??uv,n=new re;let o,s=!1;if(!mv(t))throw new Wf("Argument should be a Stream or a Multiaddr");const i=d=>{if(n.append(d.data),n.byteLength>r){const u=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${u} > ${r}`))}o?.resolve()};t.addEventListener("message",i);const a=d=>{d.error!=null?o?.reject(d.error):o?.resolve()};t.addEventListener("close",a);const c=()=>{o?.resolve()};t.addEventListener("remoteCloseWrite",c);const l={readBuffer:n,async read(d){if(s===!0)throw new Jl("Stream was unwrapped");if(ui(t)){if(d?.bytes==null)return null;if(n.byteLength<d.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,d.bytes),new is(`Unexpected EOF - stream closed after reading ${n.byteLength}/${d.bytes} bytes`)}const u=d?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=u){o.resolve();break}if(await wh(o.promise,d?.signal),ui(t)){if(n.byteLength===0&&d?.bytes==null)return null;break}o=Promise.withResolvers()}const f=d?.bytes??n.byteLength;if(n.byteLength<f){if(ui(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,f),new is(`Unexpected EOF - stream closed while reading ${n.byteLength}/${f} bytes`);return l.read(d)}const h=n.sublist(0,f);return n.consume(f),h},async write(d,u){if(s===!0)throw new Jl("Stream was unwrapped");t.send(d)||await av(t,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",i),t.removeEventListener("close",a),t.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.push(n))),t}};return l}function Ql(t,e={}){const r=wv(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=gr(e.maxDataLength));const n=e?.lengthDecoder??Cf,o=e?.lengthEncoder??Ey;return{async read(i){let a=-1;const c=new re;for(;;){const d=await r.read({...i,bytes:1});if(d==null)break;c.append(d);try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new bh("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new hv(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new fv(`Message length too long - ${a} > ${e.maxDataLength}`);const l=await r.read({...i,bytes:a});if(l==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new is(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw t.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new is(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await r.write(new re(o(i.byteLength),i),a)},async writeV(i,a){const c=new re(...i.flatMap(l=>[o(l.byteLength),l]));await r.write(c,a)},unwrap(){return r.unwrap()}}}const yv=1024*1024*4,bv=1024*1024*4;class vv{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new re,this.maxBufferSize=e.maxBufferSize??yv,this.maxDataLength=e.maxDataLength??bv,this.lengthDecoder=e.lengthDecoder??Cf,this.encodingLength=e.encodingLength??gr}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new Wf(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let r;try{r=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(r<0||r>this.maxDataLength)throw new bh("Invalid message length");const n=this.encodingLength(r),o=n+r;if(this.buffer.byteLength>=o){const s=this.buffer.sublist(n,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}}var xv={};const Gn=65535,ed=Gn-16,so=!!xv?.DUMP_SESSION_KEYS,td=16;function ba(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const as=t=>t?`"${t}" `:"";function va(t,e=""){if(typeof t!="boolean")throw new TypeError(as(e)+"expected boolean, got type="+typeof t);return t}function qr(t,e=""){if(typeof t!="number")throw new TypeError(as(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(as(e)+"expected integer >= 0, got "+t);return t}function ve(t,e,r=""){if(ba(t)&&(e===void 0||t.length===e))return t;e!==void 0&&qr(e,"length");const n=ba(t),o=e!==void 0?` of length ${e}`:"",s=n?`length=${t.length}`:`type=${typeof t}`,i=as(r)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}const rd=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`)};function nd(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function Sv(t,e){ve(t,void 0,"output");const r=e.outputLen;if(!(t.length>=r))throw new RangeError('"output" expected length >= '+r)}function bt(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function $t(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Ev(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const Kr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Av(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function kv(t){for(let e=0;e<t.length;e++)t[e]=Av(t[e]);return t}const er=Kr?t=>t:kv;function Iv(t,e){return!t.byteLength||!e.byteLength?!1:t.buffer===e.buffer&&t.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<t.byteOffset+t.byteLength}function Cv(t,e){if(Iv(t,e)&&t.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function Rv(t,e){return rd(t,"defaults"),rd(e,"opts"),Object.assign(t,e)}function Tv(t,e){if(t=ve(t),e=ve(e),t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Pv(t,e,r){const n=e,o=(()=>[]),s=(a,c)=>n(c,...o(a)).update(a).digest(),i=n(new Uint8Array(t),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>n(a,...c),s}const Nv=(t,e)=>{function r(n,...o){if(ve(n,void 0,"key"),t.nonceLength!==void 0){const u=o[0];ve(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}const s=t.tagLength,i=t.nonceLength!==void 0?1:0;if(!t.withAAD){for(let u=i;u<o.length;u++)if(ba(o[u]))throw new Error("AAD not supported")}t.withAAD&&o[i]!==void 0&&ve(o[i],void 0,"AAD");const a=e(n,...o),c=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");ve(f,void 0,"output")}};let l=!1;return{encrypt(u,f){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,ve(u,void 0,"data"),c(a.encrypt.length,f),a.encrypt(u,f)},decrypt(u,f){if(ve(u,void 0,"data"),s&&u.length<s)throw new Error('"ciphertext" expected length >= tagLength='+s);return c(a.decrypt.length,f),a.decrypt(u,f)}}}return Object.assign(r,t),r};function xa(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(ve(e,t,"output"),r&&!cs(e))throw new Error("invalid output, must be aligned");return e}function Lv(t,e,r){qr(t),qr(e),va(r);const n=new Uint8Array(16),o=Ev(n);return o.setBigUint64(0,BigInt(e),r),o.setBigUint64(8,BigInt(t),r),n}function cs(t){return t.byteOffset%4===0}function ls(t){return Uint8Array.from(ve(t))}const vh=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),Bv=er(bt(vh("expand 16-byte k"))),_v=er(bt(vh("expand 32-byte k")));function ee(t,e){return t<<e|t>>>32-e}const mn=64,Dv=16,Sa=2**32-1,od=Uint32Array.of();function Ov(t,e,r,n,o,s,i,a){const c=o.length,l=new Uint8Array(mn),d=bt(l),u=Kr&&cs(o)&&cs(s),f=u?bt(o):od,h=u?bt(s):od;if(!Kr){for(let g=0;g<c;i++){if(t(e,r,n,d,i,a),er(d),i>=Sa)throw new Error("arx: counter overflow");const m=Math.min(mn,c-g);for(let y=0,w;y<m;y++)w=g+y,s[w]=o[w]^l[y];g+=m}return}for(let g=0;g<c;i++){if(t(e,r,n,d,i,a),i>=Sa)throw new Error("arx: counter overflow");const m=Math.min(mn,c-g);if(u&&m===mn){const y=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,I;w<Dv;w++)I=y+w,h[I]=f[I]^d[w];g+=mn;continue}for(let y=0,w;y<m;y++)w=g+y,s[w]=o[w]^l[y];g+=m}}function Fv(t,e){const{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Rv({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return qr(o),qr(i),va(s),va(r),(a,c,l,d,u=0)=>{ve(a,void 0,"key"),ve(c,void 0,"nonce"),ve(l,void 0,"data");const f=l.length,h=d!==void 0;if(d=xa(f,d,!1),h&&Cv(l,d),qr(u),u<0||u>=Sa)throw new Error("arx: counter overflow");const g=[];let m=a.length,y,w;if(m===32)g.push(y=ls(a)),w=_v;else if(m===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),w=Bv,g.push(y);else throw ve(a,32,"arx key"),new Error("invalid key size");(!Kr||!cs(c))&&g.push(c=ls(c));let I=bt(y);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");const B=c.subarray(0,16);if(Kr)n(w,I,bt(B),I);else{const T=er(Uint32Array.from(w));n(T,I,bt(B),I),$t(T),er(I)}c=c.subarray(16)}else Kr||er(I);const v=16-o;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){const B=new Uint8Array(12);B.set(c,s?0:12-c.length),c=B,g.push(c)}const A=er(bt(c));try{return Ov(t,w,I,A,l,d,u,i),d}finally{$t(...g)}}}function Se(t,e){return t[e++]&255|(t[e++]&255)<<8}class Mv{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=ls(ve(e,32,"key"));const r=Se(e,0),n=Se(e,2),o=Se(e,4),s=Se(e,6),i=Se(e,8),a=Se(e,10),c=Se(e,12),l=Se(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let d=0;d<8;d++)this.pad[d]=Se(e,16+2*d)}process(e,r,n=!1){const o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],d=i[3],u=i[4],f=i[5],h=i[6],g=i[7],m=i[8],y=i[9],w=Se(e,r+0),I=Se(e,r+2),v=Se(e,r+4),A=Se(e,r+6),B=Se(e,r+8),T=Se(e,r+10),N=Se(e,r+12),k=Se(e,r+14);let x=s[0]+(w&8191),S=s[1]+((w>>>13|I<<3)&8191),R=s[2]+((I>>>10|v<<6)&8191),P=s[3]+((v>>>7|A<<9)&8191),b=s[4]+((A>>>4|B<<12)&8191),E=s[5]+(B>>>1&8191),C=s[6]+((B>>>14|T<<2)&8191),L=s[7]+((T>>>11|N<<5)&8191),M=s[8]+((N>>>8|k<<8)&8191),$=s[9]+(k>>>5|o),j=0,D=j+x*a+S*(5*y)+R*(5*m)+P*(5*g)+b*(5*h);j=D>>>13,D&=8191,D+=E*(5*f)+C*(5*u)+L*(5*d)+M*(5*l)+$*(5*c),j+=D>>>13,D&=8191;let _=j+x*c+S*a+R*(5*y)+P*(5*m)+b*(5*g);j=_>>>13,_&=8191,_+=E*(5*h)+C*(5*f)+L*(5*u)+M*(5*d)+$*(5*l),j+=_>>>13,_&=8191;let O=j+x*l+S*c+R*a+P*(5*y)+b*(5*m);j=O>>>13,O&=8191,O+=E*(5*g)+C*(5*h)+L*(5*f)+M*(5*u)+$*(5*d),j+=O>>>13,O&=8191;let q=j+x*d+S*l+R*c+P*a+b*(5*y);j=q>>>13,q&=8191,q+=E*(5*m)+C*(5*g)+L*(5*h)+M*(5*f)+$*(5*u),j+=q>>>13,q&=8191;let H=j+x*u+S*d+R*l+P*c+b*a;j=H>>>13,H&=8191,H+=E*(5*y)+C*(5*m)+L*(5*g)+M*(5*h)+$*(5*f),j+=H>>>13,H&=8191;let K=j+x*f+S*u+R*d+P*l+b*c;j=K>>>13,K&=8191,K+=E*a+C*(5*y)+L*(5*m)+M*(5*g)+$*(5*h),j+=K>>>13,K&=8191;let z=j+x*h+S*f+R*u+P*d+b*l;j=z>>>13,z&=8191,z+=E*c+C*a+L*(5*y)+M*(5*m)+$*(5*g),j+=z>>>13,z&=8191;let W=j+x*g+S*h+R*f+P*u+b*d;j=W>>>13,W&=8191,W+=E*l+C*c+L*a+M*(5*y)+$*(5*m),j+=W>>>13,W&=8191;let X=j+x*m+S*g+R*h+P*f+b*u;j=X>>>13,X&=8191,X+=E*d+C*l+L*c+M*a+$*(5*y),j+=X>>>13,X&=8191;let G=j+x*y+S*m+R*g+P*h+b*f;j=G>>>13,G&=8191,G+=E*u+C*d+L*l+M*c+$*a,j+=G>>>13,G&=8191,j=(j<<2)+j|0,j=j+D|0,D=j&8191,j=j>>>13,_+=j,s[0]=D,s[1]=_,s[2]=O,s[3]=q,s[4]=H,s[5]=K,s[6]=z,s[7]=W,s[8]=X,s[9]=G}finalize(){const{h:e,pad:r}=this,n=new Uint16Array(10);let o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+r[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+r[a]|0)+(i>>>16)|0,e[a]=i&65535;$t(n)}update(e){nd(this),ve(e),e=ls(e);const{buffer:r,blockLen:n}=this,o=e.length;for(let s=0;s<o;){const i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,$t(this.h,this.r,this.buffer,this.pad)}digestInto(e){nd(this),Sv(e,this),this.finished=!0;const{buffer:r,h:n}=this;let{pos:o}=this;if(o){for(r[o++]=1;o<16;o++)r[o]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}}const jv=Pv(32,t=>new Mv(t));function Uv(t,e,r,n,o,s=20){let i=t[0],a=t[1],c=t[2],l=t[3],d=e[0],u=e[1],f=e[2],h=e[3],g=e[4],m=e[5],y=e[6],w=e[7],I=o,v=r[0],A=r[1],B=r[2],T=i,N=a,k=c,x=l,S=d,R=u,P=f,b=h,E=g,C=m,L=y,M=w,$=I,j=v,D=A,_=B;for(let q=0;q<s;q+=2)T=T+S|0,$=ee($^T,16),E=E+$|0,S=ee(S^E,12),T=T+S|0,$=ee($^T,8),E=E+$|0,S=ee(S^E,7),N=N+R|0,j=ee(j^N,16),C=C+j|0,R=ee(R^C,12),N=N+R|0,j=ee(j^N,8),C=C+j|0,R=ee(R^C,7),k=k+P|0,D=ee(D^k,16),L=L+D|0,P=ee(P^L,12),k=k+P|0,D=ee(D^k,8),L=L+D|0,P=ee(P^L,7),x=x+b|0,_=ee(_^x,16),M=M+_|0,b=ee(b^M,12),x=x+b|0,_=ee(_^x,8),M=M+_|0,b=ee(b^M,7),T=T+R|0,_=ee(_^T,16),L=L+_|0,R=ee(R^L,12),T=T+R|0,_=ee(_^T,8),L=L+_|0,R=ee(R^L,7),N=N+P|0,$=ee($^N,16),M=M+$|0,P=ee(P^M,12),N=N+P|0,$=ee($^N,8),M=M+$|0,P=ee(P^M,7),k=k+b|0,j=ee(j^k,16),E=E+j|0,b=ee(b^E,12),k=k+b|0,j=ee(j^k,8),E=E+j|0,b=ee(b^E,7),x=x+S|0,D=ee(D^x,16),C=C+D|0,S=ee(S^C,12),x=x+S|0,D=ee(D^x,8),C=C+D|0,S=ee(S^C,7);let O=0;n[O++]=i+T|0,n[O++]=a+N|0,n[O++]=c+k|0,n[O++]=l+x|0,n[O++]=d+S|0,n[O++]=u+R|0,n[O++]=f+P|0,n[O++]=h+b|0,n[O++]=g+E|0,n[O++]=m+C|0,n[O++]=y+L|0,n[O++]=w+M|0,n[O++]=I+$|0,n[O++]=v+j|0,n[O++]=A+D|0,n[O++]=B+_|0}const $v=Fv(Uv,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Hv=new Uint8Array(16),sd=(t,e)=>{t.update(e);const r=e.length%16;r&&t.update(Hv.subarray(r))},qv=new Uint8Array(32);function id(t,e,r,n,o){o!==void 0&&ve(o,void 0,"AAD");const s=t(e,r,qv),i=Lv(n.length,o?o.length:0,!0),a=jv.create(s);o&&sd(a,o),sd(a,n),a.update(i);const c=a.digest();return $t(s,i),c}const Kv=t=>(e,r,n)=>({encrypt(s,i){const a=s.length;i=xa(a+16,i,!1),i.set(s);const c=i.subarray(0,-16);t(e,r,c,c,1);const l=id(t,e,r,c,n);return i.set(l,a),$t(l),i},decrypt(s,i){i=xa(s.length-16,i,!1);const a=s.subarray(0,-16),c=s.subarray(-16),l=id(t,e,r,a,n);if(!Tv(c,l))throw $t(l),new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,r,i,i,1),$t(l),i}}),ad=Nv({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},Kv($v));function zv(t,e,r){return gc(t),r===void 0&&(r=new Uint8Array(t.outputLen)),mh(t,r,e)}const wn=Uint8Array.of(0),Vv=Uint8Array.of();function Wv(t,e,r,n=32,o){gc(t),It(n,"length"),Ct(e,void 0,"prk");const s=t.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(n>255*s)throw new Error("Length must be <= 255*HashLen");const i=Math.ceil(n/s);if(r===void 0?r=Vv:Ct(r,void 0,"info"),!i)return new Uint8Array;const a=new Uint8Array(i*s),{iHash:c,oHash:l}=mh.create(t,e),d=new Uint8Array(s),u=i>1?t.create():void 0;for(let h=0;h<i-1;h++){wn[0]=h+1;const g=c._cloneInto(u);h&&g.update(d),g.update(r).update(wn).digestInto(d),l._cloneInto(u).update(d).digestInto(d),a.set(d,s*h)}if(wn[0]=i,i>1&&c.update(d),c.update(r).update(wn).digestInto(d),l.update(d).digestInto(d),a.set(d,s*(i-1)),c.destroy(),l.destroy(),u?.destroy(),d!==a&&nr(d),nr(wn),n===a.length)return a;const f=a.slice(0,n);return nr(a),f}const xh={hashSHA256(t){return ai(t.subarray())},getHKDF(t,e){const r=zv(ai,e,t),o=Wv(ai,r,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){const t=ko.utils.randomSecretKey();return{publicKey:ko.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:ko.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return ko.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,r,n){return ad(n,e,r).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,r,n,o){return ad(n,e,r).decrypt(t.subarray(),o)}},Gv=xh;function Xv(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,r)=>t.generateX25519SharedKey(e.privateKey,r).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}const ds=t=>{const e=At(2);return e[0]=t>>8,e[1]=t,e};ds.bytes=2;const us=t=>{if(t.length<2)throw RangeError("Could not decode int16BE");if(t instanceof Uint8Array){let e=0;return e+=t[0]<<8,e+=t[1],e}return t.getUint16(0)};us.bytes=2;function Yv(t){return{xxHandshakeSuccesses:t.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:t.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:t.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:t.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:t.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Sh(t,e){!e.enabled||!so||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${J(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${J(t.privateKey,"hex")}`)):e("Missing local static keys."))}function Eh(t,e){!e.enabled||!so||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${J(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${J(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Zv(t,e){!e.enabled||!so||e(t?`REMOTE_STATIC_PUBLIC_KEY ${J(t.subarray(),"hex")}`:"Missing remote static public key.")}function Ah(t,e){!e.enabled||!so||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${J(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function kh(t,e,r){!r.enabled||!so||(r(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&J(t.k,"hex")}`),r(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&J(e.k,"hex")}`))}class Mn extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=Mn.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}const Jv=0,Qv=4294967295,ex="Cipherstate has reached maximum n, a new handshake must be performed";class tx{n;bytes;view;constructor(e=Jv){this.n=e,this.bytes=Be(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>Qv)throw new Error(ex)}}const zr=Be(0);class Io{k;n;crypto;constructor(e,r=void 0,n=0){this.crypto=e,this.k=r,this.n=new tx(n)}hasKey(){return!!this.k}encryptWithAd(e,r){if(!this.hasKey())return r;this.n.assertValue();const n=this.crypto.encrypt(r,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,r,n){if(!this.hasKey())return r;this.n.assertValue();const o=this.crypto.decrypt(r,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}}class rx{cs;ck;h;crypto;constructor(e,r){this.crypto=e;const n=we(r,"utf-8");this.h=ox(e,n),this.ck=this.h,this.cs=new Io(e)}mixKey(e){const[r,n]=this.crypto.hkdf(this.ck,e);this.ck=r,this.cs=new Io(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new re(this.h,e))}encryptAndHash(e){const r=this.cs.encryptWithAd(this.h,e);return this.mixHash(r),r}decryptAndHash(e){const r=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),r}split(){const[e,r]=this.crypto.hkdf(this.ck,zr);return[new Io(this.crypto,e),new Io(this.crypto,r)]}}class nx{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:r,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=e;this.crypto=r,this.ss=new rx(r,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<r+32)throw new Error("message is not long enough");this.re=e.sublist(r,r+32),this.ss.mixHash(this.re)}readS(e,r=0){if(this.rs)throw new Error("remote static public key is already set");const n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<r+n)throw new Error("message is not long enough");const o=e.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class Ih extends nx{writeMessageA(e){return new re(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const r=this.writeE();this.writeEE();const n=this.writeS();return this.writeES(),new re(r,n,this.ss.encryptAndHash(e))}writeMessageC(e){const r=this.writeS();return this.writeSE(),new re(r,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(r){throw new Mn(`handshake stage 0 validation fail: ${r.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();const r=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+r))}catch(r){throw new Mn(`handshake stage 1 validation fail: ${r.message}`)}}readMessageC(e){try{const r=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(r))}catch(r){throw new Mn(`handshake stage 2 validation fail: ${r.message}`)}}}function ox(t,e){if(e.length<=32){const r=Be(32);return r.set(e),r}else return t.hash(e)}var fs;(function(t){let e;t.codec=()=>(e==null&&(e=Ns((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.webtransportCerthashes!=null)for(const s of r.webtransportCerthashes)n.uint32(10),n.bytes(s);if(r.streamMuxers!=null)for(const s of r.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{const s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?r.len:r.pos+n;for(;r.pos<i;){const a=r.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new Rl('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(r.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new Rl('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(r.string());break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ps(r,t.codec()),t.decode=(r,n)=>Ts(r,t.codec(),n)})(fs||(fs={}));var hs;(function(t){let e;t.codec=()=>(e==null&&(e=Ns((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.identityKey!=null&&r.identityKey.byteLength>0&&(n.uint32(10),n.bytes(r.identityKey)),r.identitySig!=null&&r.identitySig.byteLength>0&&(n.uint32(18),n.bytes(r.identitySig)),r.extensions!=null&&(n.uint32(34),fs.codec().encode(r.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{const s={identityKey:Be(0),identitySig:Be(0)},i=n==null?r.len:r.pos+n;for(;r.pos<i;){const a=r.uint32();switch(a>>>3){case 1:{s.identityKey=r.bytes();break}case 2:{s.identitySig=r.bytes();break}case 4:{s.extensions=fs.codec().decode(r,r.uint32(),{limits:o.limits?.extensions});break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ps(r,t.codec()),t.decode=(r,n)=>Ts(r,t.codec(),n)})(hs||(hs={}));async function Ch(t,e,r){const n=await t.sign(Th(e));return hs.encode({identityKey:Ls(t.publicKey),identitySig:n,extensions:r})}async function Rh(t,e,r){try{const n=hs.decode(t),o=ga(n.identityKey);if(r?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${r}`);if(!e)throw new Error("Remote static does not exist");const s=Th(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new gg(n.message)}}function Th(t){const e=we("noise-libp2p-static-key:");return t instanceof Uint8Array?oa([e,t],e.length+t.length):(t.prepend(e),t)}class sx extends yh{stream;handshake;metrics;decoder;constructor(e,r,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=r,this.metrics=n,this.decoder=new vv({lengthDecoder:us,maxBufferSize:16*1024*1024,encodingLength:()=>2});const o=c=>{try{for(const l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",o);const s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);const i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);const a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){const r=new re;for(let n=0;n<e.byteLength;n+=ed){let o=n+ed;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),r.append(ds(s.byteLength)),r.append(s)}return r}decrypt(e){const r=new re;for(let n=0;n<e.byteLength;n+=Gn){let o=n+Gn;if(o>e.byteLength&&(o=e.byteLength),o-td<n)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(n,o):s=e.sublist(n,o);const i=e.subarray(n,o-td);try{const a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),r.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return r}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}}function cd(t,e,r){return new sx(t,e,r)}async function ix(t,e){const{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Ch(s,a.publicKey,l),u=new Ih({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Sh(u.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(u.writeMessageA(zr),e),r.trace("Stage 0 - Initiator finished sending first message."),Eh(u.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");const f=u.readMessageB(await n.read(e));r.trace("Stage 1 - Initiator received the message."),Ah(u.re,r),Zv(u.rs,r),r.trace("Initiator going to check remote's signature...");const h=await Rh(f,u.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(u.writeMessageC(d),e),r.trace("Stage 2 - Initiator sent message with signed payload.");const[g,m]=u.ss.split();return kh(g,m,r),{payload:h,encrypt:y=>g.encryptWithAd(zr,y),decrypt:(y,w)=>m.decryptWithAd(zr,y,w)}}async function ax(t,e){const{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Ch(s,a.publicKey,l),u=new Ih({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Sh(u.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),u.readMessageA(await n.read(e)),r.trace("Stage 0 - Responder received first message."),Ah(u.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(u.writeMessageB(d),e),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Eh(u.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");const f=u.readMessageC(await n.read(e));r.trace("Stage 2 - Responder received the message, finished handshake.");const h=await Rh(f,u.rs,c),[g,m]=u.ss.split();return kh(g,m,r),{payload:h,encrypt:y=>m.encryptWithAd(zr,y),decrypt:(y,w)=>g.decryptWithAd(zr,y,w)}}class cx{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,r={}){const{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=r,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");const c=s??Gv;this.crypto=Xv(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?Yv(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??Be(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Eg]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,r){const n=e.log?.newScope("noise")??this.log,o=Ql(e,{lengthEncoder:ds,lengthDecoder:us,maxDataLength:Gn}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=ga(s.payload.identityKey);return{connection:cd(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Zr(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;const r=this.components.upgrader.getStreamMuxers();if(r!=null)for(const n of e){const o=r.get(n);if(o!=null)return o}if(e.length)throw new mg("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,r){const n=e.log?.newScope("noise")??this.log,o=Ql(e,{lengthEncoder:ds,lengthDecoder:us,maxDataLength:Gn}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=ga(s.payload.identityKey);return{connection:cd(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Zr(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,r,n,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await ix({connection:e,privateKey:r,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,r,n,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await ax({connection:e,privateKey:r,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}}function lx(t={}){return e=>new cx(e,t)}const dx="termdock-e2ee-v1",ld=3600*1e3,dd=512*1024*1024,Ea=4*1024*1024,Oo=()=>{},Ds=Object.assign(Oo,{enabled:!1,error:Oo,trace:Oo,newScope:()=>Ds});Object.freeze(Ds);async function Ph(){const t=await Rb();return{privateKey:t,peerId:Zr(t.publicKey).toString()}}function ux(t){return btoa(String.fromCharCode(...Nb(t.privateKey)))}function ud(t){if(t.length>512||!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Invalid identity encoding");const e=Pb(Uint8Array.from(atob(t),r=>r.charCodeAt(0)));if(e.type!=="Ed25519")throw new Error("Only Ed25519 device identities are supported");return{privateKey:e,peerId:Zr(e.publicKey).toString()}}class Nh{constructor(e=Oo){this.consumed=e}consumed;chunks=[];size=0;ended=!1;error;wake;push(e){if(this.ended)throw this.error??new Error("Byte stream closed");if(this.size+e.byteLength>Ea)throw new Error("Secure stream buffer limit exceeded");this.chunks.push(e.slice()),this.size+=e.byteLength,this.wake?.()}end(e){this.ended=!0,this.error??=e,this.wake?.()}async*[Symbol.asyncIterator](){for(;;){if(this.error)throw this.error;const e=this.chunks.shift();if(e)this.size-=e.byteLength,yield e,this.consumed();else{if(this.ended)return;await new Promise(r=>{this.wake=r})}}}}class fx extends yh{constructor(e,r){super({log:Ds,direction:r?"outbound":"inbound",maxReadBufferLength:Ea,maxWriteBufferLength:Ea}),this.duplex=e,this.finished=e.sink(this.outgoing).catch(n=>{this.abort(Jr(n))}),this.readTransport()}duplex;outgoing=new Nh(()=>this.onMuxerDrain());finished;async readTransport(){try{for await(const e of this.duplex.source)this.onData(e.slice());this.onTransportClosed()}catch(e){this.onTransportClosed(Jr(e))}}sendData(e){return this.outgoing.push(e.subarray()),{sentBytes:e.byteLength,canSendMore:!1}}sendReset(e){this.outgoing.end(e),this.duplex.close?.(e)}sendPause(){}sendResume(){}async close(){this.outgoing.end(),this.duplex.close?.(),this.onTransportClosed(),await this.finished}}function Jr(t){return t instanceof Error?t:new Error("Secure transport failed")}class hx extends Error{code="E2EE_REHANDSHAKE_REQUIRED";constructor(){super("Encrypted connection lifetime reached; establish a new handshake without replaying pending input")}}function px(t){const e=t?.maxAgeMs??ld,r=t?.maxBytesPerDirection??dd;if(!Number.isSafeInteger(e)||e<=0||e>ld||!Number.isSafeInteger(r)||r<=0||r>dd)throw new Error("Encrypted connection limits cannot exceed the production maximum");return{maxAgeMs:e,maxBytesPerDirection:r}}async function gx(t){const{identity:e,duplex:r,initiator:n,targetPinnedPeerId:o,signal:s}=t,i=px(t.limits);if(typeof Reflect.get(Promise,"withResolvers")!="function"||typeof globalThis.crypto?.getRandomValues!="function")throw new Error("End-to-end encryption requires Node.js 22+ or a modern browser with Promise.withResolvers and secure random support");if(n&&!o)throw new Error("A pinned target identity is required");const a=o?Db(o):void 0;if(a&&a.type!=="Ed25519")throw new Error("Only Ed25519 target identities are supported");if(e.peerId!==Zr(e.privateKey.publicKey).toString())throw new Error("Local identity mismatch");if(s?.aborted)throw s.reason??new Error("Connection aborted");const c=new fx(r,n),l=new AbortController,d=setTimeout(()=>{const h=new Error("Encrypted handshake timed out");l.abort(h),c.abort(h)},15e3),u=()=>{l.abort(s?.reason),c.abort(Jr(s?.reason))};s?.addEventListener("abort",u,{once:!0}),c.addEventListener("close",()=>s?.removeEventListener("abort",u),{once:!0});const f=lx({crypto:xh,prologueBytes:new TextEncoder().encode(dx)})({privateKey:e.privateKey,peerId:Zr(e.privateKey.publicKey),logger:{forComponent:()=>Ds},upgrader:{getStreamMuxers:()=>new Map}});try{const h=await(n?f.secureOutbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}):f.secureInbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}));if(h.remotePeer.type!=="Ed25519")throw new Error("Unsupported remote identity");return{authenticatedPeerId:h.remotePeer.toString(),duplex:mx(h.connection,i)}}catch(h){throw c.abort(Jr(h)),h}finally{clearTimeout(d),s?.removeEventListener("abort",u)}}function mx(t,e){const r=new Nh,n=performance.now(),o=Date.now();let s=0,i=0,a;const c=()=>(a??=new hx,r.end(a),t.abort(a),a),l=setTimeout(c,e.maxAgeMs);typeof l=="object"&&l.unref?.();const d=(f,h)=>{if(a)throw a;if(Math.max(performance.now()-n,Date.now()-o)>=e.maxAgeMs||f+h>=e.maxBytesPerDirection)throw c()};t.addEventListener("message",f=>{try{d(i,f.data.byteLength),i+=f.data.byteLength,r.push(f.data.subarray())}catch(h){t.abort(Jr(h))}}),t.addEventListener("close",f=>{clearTimeout(l),r.end(f.error)},{once:!0});let u=!1;return{source:r,async sink(f){if(u)throw new Error("Secure sink already consumed");u=!0;try{for await(const h of f)d(s,h.byteLength),s+=h.byteLength,t.send(h)||await t.onDrain()}catch(h){throw t.abort(Jr(h)),h}},close(f){f?t.abort(f):t.close()}}}class Ac{constructor(e=64){this.limit=e}limit;items=[];wake;ended=!1;error;push(e){if(this.ended)throw new Error("Channel closed");if(this.items.length>=this.limit)throw this.end(new Error("Channel queue exceeded")),this.error;this.items.push(e),this.wake?.()}end(e){this.ended=!0,this.error??=e,this.wake?.()}async*[Symbol.asyncIterator](){for(;;){if(this.error)throw this.error;const e=this.items.shift();if(e!==void 0){yield e;continue}if(this.ended)return;await new Promise(r=>{this.wake=r}),this.wake=void 0}}}const fi=2*1024*1024,wx=new TextEncoder,yx=new TextDecoder("utf-8",{fatal:!0});class bx{constructor(e){this.duplex=e;const r=this;this.done=e.sink((async function*(){for await(const n of r.outgoing)try{yield n}finally{r.outgoingBytes-=n.byteLength}})()),this.done.catch(n=>this.close(n instanceof Error?n:new Error("Transport failed")))}duplex;outgoing=new Ac(256);outgoingBytes=0;done;send(e){const r=wx.encode(JSON.stringify(e));if(r.length>fi)throw new Error("Record too large");const n=new Uint8Array(r.length+4);if(new DataView(n.buffer).setUint32(0,r.length),n.set(r,4),this.outgoingBytes+n.byteLength>4*1024*1024)throw new Error("Record queue byte budget exceeded");this.outgoingBytes+=n.byteLength;try{this.outgoing.push(n)}catch(o){throw this.outgoingBytes-=n.byteLength,o}}close(e){this.outgoing.end(e),this.duplex.close?.(e)}async*read(){let e=new Uint8Array(0);for await(const r of this.duplex.source){if(e.length+r.length>fi*2+8)throw new Error("Record buffer exceeded");const n=new Uint8Array(e.length+r.length);for(n.set(e),n.set(r,e.length),e=n;e.length>=4;){const o=new DataView(e.buffer,e.byteOffset,4).getUint32(0);if(o>fi||o===0)throw new Error("Invalid record size");if(e.length<o+4)break;const s=JSON.parse(yx.decode(e.subarray(4,o+4)));if(!s||typeof s!="object"||typeof s.id!="string"||typeof s.type!="string")throw new Error("Invalid record");yield s,e=e.slice(o+4)}}if(e.length)throw new Error("Truncated record")}}function Lh(t){let e="";for(let r=0;r<t.length;r+=8192)e+=String.fromCharCode(...t.subarray(r,r+8192));return btoa(e)}function Bh(t){const e=atob(t);return Uint8Array.from(e,r=>r.charCodeAt(0))}function vx(t){const e=new Ac(64);t.binaryType="arraybuffer";const r=n=>{e.end(n),t.close(1e3)};return t.addEventListener("message",n=>{try{if(!(n.data instanceof ArrayBuffer)||n.data.byteLength>1024*1024)throw new Error("Invalid encrypted frame");e.push(new Uint8Array(n.data))}catch{r(new Error("Encrypted transport rejected frame"))}}),t.addEventListener("close",()=>e.end()),t.addEventListener("error",()=>e.end(new Error("Encrypted transport disconnected"))),{source:e,close:r,async sink(n){try{for await(const o of n)for(let s=0;s<o.length;s+=64*1024){const i=Date.now();for(;t.bufferedAmount>256*1024;){if(t.readyState!==1||Date.now()-i>15e3)throw new Error("Encrypted transport congested");await new Promise(a=>setTimeout(a,10))}if(t.readyState!==1)throw new Error("Encrypted transport closed");t.send(o.subarray(s,s+64*1024))}}catch(o){throw r(o instanceof Error?o:new Error("Encrypted transport failed")),o}}}}const _h=8,Dh=128,xx=5*1024*1024,Sx=Dh+_h+8,Ex=256,Co=3e4,yn=64*1024;function Mt(t){return t instanceof Error?t:new Error(String(t??"Secure connection closed"))}function fd(t){if(!t.startsWith("/")||t.startsWith("//")||t.includes("#"))throw new Error("A local API path is required");return t}class Oh extends EventTarget{constructor(e,r,n){super(),this.url=e,this.transmit=r,this.disconnect=n}url;transmit;disconnect;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;binaryType="arraybuffer";bufferedAmount=0;protocol="termdock-e2ee-v1";extensions="";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;send(e){if(this.readyState!==1)throw new Error("Secure socket is not open");if(typeof e!="string"||new TextEncoder().encode(e).length>1024*1024)throw new Error("Unsupported socket payload");this.transmit(e)}close(e=1e3,r=""){this.readyState!==3&&(this.disconnect(),this.finish(e,r))}accept(e){if(this.readyState!==3)if(e.type==="ws-ready"){this.readyState=1;const r=new Event("open");this.dispatchEvent(r),this.onopen?.(r)}else if(e.type==="ws-data"&&typeof e.data=="string"){const r=new MessageEvent("message",{data:e.data});this.dispatchEvent(r),this.onmessage?.(r)}else e.type==="ws-close"?this.finish(typeof e.code=="number"?e.code:1e3,typeof e.reason=="string"?e.reason:""):e.type==="error"&&this.fail(Mt(e.error))}fail(e){if(this.readyState===3)return;const r=new Event("error");this.dispatchEvent(r),this.onerror?.(r),this.finish(1006,e.message)}finish(e,r){if(this.readyState===3)return;this.readyState=3;const n=new CloseEvent("close",{code:e,reason:r,wasClean:e===1e3});this.dispatchEvent(n),this.onclose?.(n)}}class Ax{constructor(e,r,n){this.channel=e,this.identity=r,this.targetPeerId=n,this.read().catch(o=>this.close(Mt(o))),e.done.catch(o=>this.close(Mt(o)))}channel;identity;targetPeerId;pending=new Map;waiting=[];stopped=!1;closeReason;get canSwitchTransport(){return![...this.pending.values()].some(e=>e.kind==="http")&&!this.waiting.some(e=>e.kind==="http")}get closed(){return this.stopped}hasCapacity(e){if(this.pending.size>=Sx)return!1;const r=[...this.pending.values()].filter(n=>n.kind===e).length;return e==="http"?r<_h:e==="socket"?r<Dh:!0}allocate(e){if(this.stopped)throw this.closeReason??new Error("Secure connection closed");const r=crypto.randomUUID(),n=new Ac(4);return this.pending.set(r,{queue:n,kind:e}),{id:r,queue:n}}reserve(e,r){return r?.aborted?Promise.reject(r.reason):this.stopped?Promise.reject(this.closeReason??new Error("Secure connection closed")):this.hasCapacity(e)?Promise.resolve(this.allocate(e)):this.waiting.length>=Ex?Promise.reject(new Error("连接繁忙,请稍后重试。")):new Promise((n,o)=>{const s=l=>{this.waiting=this.waiting.filter(d=>d!==c),c.cleanup(),o(l)},i=()=>s(r?.reason??new Error("Request aborted")),a=setTimeout(()=>s(new Error("连接等待超时,请重试。")),Co),c={kind:e,resolve:n,reject:o,cleanup:()=>{clearTimeout(a),r?.removeEventListener("abort",i)}};this.waiting.push(c),r?.addEventListener("abort",i,{once:!0})})}dispatchWaiting(){if(!this.stopped)for(let e=0;e<this.waiting.length;){const r=this.waiting[e];if(!this.hasCapacity(r.kind)){e++;continue}this.waiting.splice(e,1),r.cleanup(),r.resolve(this.allocate(r.kind))}}async read(){try{for await(const e of this.channel.read()){const r=this.pending.get(e.id);r&&(r.socket?(r.socket.accept(e),(e.type==="ws-close"||e.type==="error")&&this.release(e.id)):(r.queue.push(e),(e.type==="end"||e.type==="error")&&(r.cancelUpload?.(),this.release(e.id))))}}finally{this.close(new Error("Secure connection closed"))}}release(e){this.pending.get(e)?.queue.end(),this.pending.delete(e),this.dispatchWaiting()}async request(e,r){const{id:n,queue:o}=await this.reserve("request"),s=setTimeout(()=>this.close(new Error("Secure connection timed out")),Math.max(1e3,Math.min(Co,r?.timeoutMs??Co)));try{if(this.stopped)throw this.closeReason;this.channel.send({...e,id:n});const i=(await o[Symbol.asyncIterator]().next()).value;if(!i)throw new Error("Secure request closed");if(i.type==="error")throw Mt(i.error);return i}finally{clearTimeout(s),this.release(n)}}openSocket(e){fd(e);let r;const n=new AbortController,o=new Oh(e,s=>{r&&this.channel.send({id:r,type:"ws-data",data:s})},()=>{if(n.abort(),r)try{this.channel.send({id:r,type:"ws-close"})}finally{this.release(r)}});return this.reserve("socket",n.signal).then(s=>{if(r=s.id,o.readyState===3){this.release(r);return}const i=this.pending.get(r);if(!i)throw new Error("Secure connection closed");i.socket=o,this.channel.send({id:r,type:"ws-open",path:e})}).catch(s=>{r&&this.release(r),o.fail(Mt(s))}),o}async fetch(e,r){const n=typeof location>"u"?"https://termdock.invalid":location.origin,o=e instanceof Request?e:null,s=new URL(o?.url??String(e),n);if(s.origin!==n)throw new Error("Only current-service API requests are supported");const i=new Request(s,o?new Request(o,r):r),a=i.method.toUpperCase(),c=fd(s.pathname+s.search),l=s.pathname==="/api/terminal/fs/upload"?110*1024*1024:xx;if(i.signal.aborted)throw i.signal.reason;const d={};i.headers.forEach((A,B)=>{["cookie","authorization","host","connection","content-length"].includes(B)||(d[B]=A)});const{id:u,queue:f}=await this.reserve("http",i.signal),h=f[Symbol.asyncIterator]();let g;const m=()=>{g?.cancel().catch(()=>{})},y=this.pending.get(u);if(!y)throw new Error("Secure connection closed");y.cancelUpload=m;const w=()=>{m();try{this.channel.send({id:u,type:"cancel"})}catch{}f.end(Mt(i.signal.reason??"Request aborted")),this.release(u)};i.signal.addEventListener("abort",w,{once:!0});const I=()=>{i.signal.removeEventListener("abort",w),this.release(u)},v=async()=>{let A;try{const B=(await Promise.race([h.next(),new Promise((T,N)=>{A=setTimeout(()=>N(new Error("服务响应超时,请重试。")),Co)})])).value;if(!B)throw new Error("Secure response ended unexpectedly");if(B.type==="error")throw Mt(B.error);return B}finally{clearTimeout(A)}};try{if(i.signal.aborted)throw i.signal.reason;if(this.channel.send({id:u,type:"http",method:a,path:c,headers:d}),i.body){const k=i.body.getReader();g=k;let x=0,S=0;try{for(;;){const{done:R,value:P}=await k.read();if(R)break;if(x+=P.byteLength,x>l)throw new Error("Request body exceeds upload limit");for(let b=0;b<P.byteLength;b+=yn){if(this.channel.send({id:u,type:"upload",data:Lh(P.subarray(b,b+yn))}),(await v()).type!=="upload-ack")throw new Error("Invalid upload acknowledgement");S+=Math.min(yn,P.byteLength-b),r?.onUploadProgress?.(S)}}}catch(R){throw await k.cancel(R).catch(()=>{}),R}finally{g=void 0,k.releaseLock()}}if(i.signal.aborted||this.stopped)throw new Error("Request aborted");this.channel.send({id:u,type:"upload-end"});const A=await v();if(A.type!=="head"||typeof A.status!="number")throw new Error("Invalid response header");const B=new Headers(A.headers);if(a==="HEAD"||[204,205,304].includes(A.status)){if((await v()).type!=="end")throw new Error("Unexpected response body");return I(),new Response(null,{status:A.status,headers:B})}let T=!1;const N=new ReadableStream({pull:async k=>{try{T&&(this.channel.send({id:u,type:"ack"}),T=!1);const x=await v();if(x.type==="end"){k.close(),I();return}if(x.type!=="chunk"||typeof x.data!="string")throw new Error("Invalid response chunk");const S=Bh(x.data);if(S.length>yn)throw new Error("Response chunk exceeds budget");k.enqueue(S),T=!0}catch(x){k.error(x),w(),I()}},cancel:()=>{w(),I()}},{highWaterMark:yn,size:k=>k.byteLength});return new Response(N,{status:A.status,headers:B})}catch(A){throw w(),I(),A}}close(e=new Error("Secure connection closed")){if(!this.stopped){this.stopped=!0,this.closeReason=e;for(const r of this.waiting.splice(0))r.cleanup(),r.reject(e);for(const r of this.pending.values())r.queue.end(e),r.cancelUpload?.(),r.socket?.fail(e);this.pending.clear(),this.channel.close(e)}}}async function cr(t){const e=new URL(t.url);if(!["wss:","ws:"].includes(e.protocol))throw new Error("A WebSocket endpoint is required");if(e.protocol==="ws:"&&!["127.0.0.1","localhost","[::1]"].includes(e.hostname))throw new Error("Remote secure channels require WSS");const r=t.identity??await Ph(),n=(t.socketFactory??(c=>new WebSocket(c)))(e.href),o=vx(n),s=new AbortController,i=setTimeout(()=>s.abort(new Error("Secure handshake timed out")),2e4),a=t.signal?AbortSignal.any([t.signal,s.signal]):s.signal;try{await new Promise((d,u)=>{if(a.aborted){u(a.reason);return}const f=()=>{a.removeEventListener("abort",m),n.removeEventListener("open",h),n.removeEventListener("error",g),n.removeEventListener("close",g)},h=()=>{f(),d()},g=()=>{f(),u(new Error("Secure transport unavailable"))},m=()=>{f(),u(a.reason)};a.addEventListener("abort",m,{once:!0}),n.addEventListener("open",h),n.addEventListener("error",g),n.addEventListener("close",g),n.readyState===1&&h()});const c=await gx({identity:r,duplex:o,initiator:!0,targetPinnedPeerId:t.targetPeerId,signal:a}),l=new Ax(new bx(c.duplex),r,c.authenticatedPeerId);if(t.pairingCode)try{await l.request({type:"pair",code:t.pairingCode})}catch(d){throw l.close(Mt(d)),d}return l}catch(c){throw n.close(),c}finally{clearTimeout(i)}}const hd=256*1024,kx=1024*1024;class Ix extends EventTarget{constructor(e,r,n=o=>new WebSocket(o)){if(super(),this.url=e,!/^[a-zA-Z0-9_.:-]{1,160}$/.test(r))throw new Error("Invalid target identity");this.upstream=n(e),this.deadline=setTimeout(()=>this.fail("Relay connection timed out"),2e4),this.upstream.addEventListener("message",o=>{if(this.readyState!==3)try{if(typeof o.data!="string"||new TextEncoder().encode(o.data).length>hd)throw new Error("Invalid relay envelope");const s=JSON.parse(o.data);if(s.type==="ready"&&!this.requested){this.requested=!0,this.transmit({type:"open",streamId:this.streamId,serviceId:r});return}if(s.streamId!==this.streamId)return;if(s.type==="opened"&&this.readyState===0){clearTimeout(this.deadline),this.readyState=1;const l=new Event("open");this.dispatchEvent(l),this.onopen?.(l);return}if(s.type==="close"){this.finish(1001,"Relay route closed"),this.upstream.close();return}if(s.type!=="data"||this.readyState!==1||s.encoding!=="base64"||typeof s.payload!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(s.payload))throw new Error("Invalid ciphertext relay frame");const i=Bh(s.payload),a=this.binaryType==="blob"?new Blob([i]):i.buffer,c=new MessageEvent("message",{data:a});this.dispatchEvent(c),this.onmessage?.(c)}catch{this.fail("Relay protocol rejected frame")}}),this.upstream.addEventListener("close",o=>this.finish(o.code||1006,"Relay disconnected")),this.upstream.addEventListener("error",()=>this.fail("Relay transport unavailable"))}url;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;protocol="";extensions="";binaryType="arraybuffer";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;upstream;streamId=crypto.randomUUID();requested=!1;deadline;get bufferedAmount(){return this.upstream.bufferedAmount}transmit(e){const r=JSON.stringify(e);if(this.upstream.readyState!==1||this.upstream.bufferedAmount+r.length>kx||r.length>hd)throw new Error("Relay unavailable or congested");this.upstream.send(r)}send(e){if(this.readyState!==1)throw new Error("Relay socket is not open");let r;if(ArrayBuffer.isView(e))r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof ArrayBuffer)r=new Uint8Array(e);else throw new Error("Relay secure transport requires binary bytes");try{this.transmit({type:"data",streamId:this.streamId,encoding:"base64",payload:Lh(r)})}catch(n){throw this.fail("Relay transport congested"),n}}close(e=1e3,r=""){if(this.readyState!==3){try{this.requested&&this.transmit({type:"close",streamId:this.streamId})}catch{}this.finish(e,r),this.upstream.close()}}fail(e){if(this.readyState===3)return;const r=new Event("error");this.dispatchEvent(r),this.onerror?.(r),this.finish(1006,e),this.upstream.close()}finish(e,r){if(this.readyState===3)return;clearTimeout(this.deadline),this.readyState=3;const n=new CloseEvent("close",{code:e,reason:r,wasClean:e===1e3});this.dispatchEvent(n),this.onclose?.(n)}}function Fh(t){return e=>new Ix(e,t)}function Cx(t){if(typeof t!="string"||!t.startsWith("/api/")||/[\\\x00-\x20\x7f#]/.test(t))return null;const e=t.split("?")[0];if(e.includes("//"))return null;try{const n=e.split("/").map((o,s)=>{if(s===0||o===""&&s===e.split("/").length-1)return o;const i=decodeURIComponent(o);if(!i||i==="."||i===".."||/[\\/\x00-\x1f\x7f]/.test(i)||/%[a-f0-9]{2}/i.test(i))throw new Error("Ambiguous API path");return i}).join("/");return n.endsWith("/")&&!n.startsWith("/api/terminal/fs/preview/")?null:n}catch{return null}}function Rx(t){if(!("serviceWorker"in navigator))return()=>{};const e=new Set,r=n=>{if(n.source!==navigator.serviceWorker.controller||n.data?.type!=="termdock-secure-fetch"||n.ports.length!==1)return;const o=n.ports[0],{path:s,method:i,headers:a,body:c,expectedTargetPeerId:l,previewPrefix:d}=n.data;let u;try{u=new URL(s,location.origin)}catch{o.close();return}if(u.origin!==location.origin||!u.pathname.startsWith("/api/")||e.size>=32||typeof i!="string"||c!==void 0&&(!(c instanceof ArrayBuffer)||c.byteLength>5*1024*1024)){o.postMessage({type:"error"}),o.close();return}if(d!==void 0&&(typeof d!="string"||!d.endsWith("/")||!/^\/api\/terminal\/fs\/preview\/[a-f0-9]{32}\//.test(d)||!["GET","HEAD"].includes(i)||!Cx(u.pathname)?.startsWith(d))){o.postMessage({type:"error"}),o.close();return}const f=new AbortController;let h,g,m=!1,y=!1;const w=()=>{y||(y=!0,e.delete(w),f.abort(),h?.cancel().catch(()=>{}),o.close())};e.add(w),o.onmessage=I=>{if(I.data?.type==="cancel"){w();return}I.data?.type!=="pull"||m||y||(m=!0,(async()=>{if(!h){o.postMessage({type:"end"}),w();return}if(!g?.length){const A=await h.read();if(A.done){o.postMessage({type:"end"}),w();return}g=A.value}const v=g.slice(0,64*1024);g=g.subarray(v.length),o.postMessage({type:"chunk",data:v.buffer},[v.buffer])})().catch(()=>{o.postMessage({type:"error"}),w()}).finally(()=>{m=!1}))},o.onmessageerror=w,o.start(),(async()=>{const I=await t();if(y)return;if(l&&l!==I.targetPeerId)throw new Error("Preview target changed");const v=await I.fetch(u.pathname+u.search,{method:i,headers:a,body:["GET","HEAD"].includes(i)?void 0:c,signal:f.signal});if(y){await v.body?.cancel();return}h=v.body?.getReader();const A={};v.headers.forEach((B,T)=>{A[T]=B}),o.postMessage({type:"head",status:v.status,headers:A,bodyless:!h,targetPeerId:I.targetPeerId})})().catch(()=>{y||(o.postMessage({type:"error"}),w())})};return navigator.serviceWorker.addEventListener("message",r),()=>{navigator.serviceWorker.removeEventListener("message",r);for(const n of[...e])n()}}class Ve extends Error{constructor(){super("Device authorization expired or revoked")}}const Ro=new WeakMap;function on(t,e={}){const r=Ro.get(t);if(!t.closed&&r&&(!r.settled||Date.now()-r.at<(e.maxAgeMs??1e3)))return r.pending;const n={at:Date.now(),settled:!1,pending:void 0},o=Tx(t,e.timeoutMs??5e3).then(s=>(n.at=Date.now(),n.settled=!0,s),s=>{throw Ro.get(t)===n&&Ro.delete(t),s});return n.pending=o,Ro.set(t,n),o}async function Tx(t,e){const r=await t.request({type:"permissions"},{timeoutMs:e});if(r.type!=="result"||typeof r.fullService!="boolean"||!Array.isArray(r.grants))throw new Error("Invalid permission response");const n=r.grants,o=r.fullService===!0;if(!o&&n.length===0)throw new Ve;return{fullService:o,grants:n,canManage:o&&n.length>0||n.some(s=>s.actions.includes("authorization.manage"))}}const Mh="termdock-secure-last-path:",Px=10*6e4;function jh(t){try{const e=JSON.parse(sessionStorage.getItem(Mh+t)||"null");return e&&typeof e.key=="string"&&Date.now()-e.at<Px?e.key:void 0}catch{return}}function Uh(t,e){try{sessionStorage.setItem(Mh+t,JSON.stringify({key:e,at:Date.now()}))}catch{}}function $h(t,e,r=!1){return new Promise((n,o)=>{let s=0,i=0,a=!1,c,l;const d=new Set,u=()=>{clearTimeout(l);for(const h of d)h.abort();d.clear()},f=()=>{if(a)return;if(s>=t.length){i||(a=!0,u(),o(c||new Error("没有可用的连接路线。")));return}if(i>=(r?1:2))return;const h=t[s++],g=performance.now(),m=w=>{performance.getEntriesByName("termdock:connection-path").length>64&&performance.clearMeasures("termdock:connection-path"),performance.measure("termdock:connection-path",{start:g,end:performance.now(),detail:{path:h.key.startsWith("relay:")?"relay":"direct",ok:w}})},y=new AbortController;d.add(y),i++,h.run(y.signal).then(w=>{if(m(!0),d.delete(y),a){e(w);return}a=!0,u(),n({value:w,key:h.key})},w=>{if(m(!1),d.delete(y),i--,!a){if(c=w,w instanceof Ve){a=!0,u(),o(w);return}f()}}),clearTimeout(l),!r&&s<t.length&&(l=setTimeout(f,400))};f()})}const Hh="termdock-workspace",Aa="termdock:workspace-visibility",ka="termdock:workspace-activate";function kc(){return window.parent!==window&&location.pathname==="/workspace.html"&&new URLSearchParams(location.search).get(Hh)||"root"}let pd,gd;function St(){try{if(window.parent===window)return window.__termdockWorkspaceHost;const t=window.parent.__termdockWorkspaceHost;return t&&t!==pd&&(pd=t,gd={...t,subscribe(e){const r=t.subscribe(e),n=o=>{o.persisted||r()};return window.addEventListener("pagehide",n),()=>{r(),window.removeEventListener("pagehide",n)}}}),t?gd:void 0}catch{return}}function hi(){const t=St();return!t||t.snapshot().activeKey===kc()}function ps(t,e=!0){return St()?.activate(t,e)??!1}function Tn(t){St()?.report(kc(),t)}const Ia="termdock-secure-workspace-session:";function jk(t){if(t)try{const e=JSON.parse(localStorage.getItem(Ia+t)||"null");return localStorage.removeItem(Ia+t),e&&typeof e.sessionId=="string"&&Date.now()-e.at<6e4?e.sessionId:void 0}catch{return}}function Nx(t){if(window.parent!==window||window.termdockDesktop)return;if(window.__termdockWorkspaceHost)return window.__termdockWorkspaceHost;let e={activeKey:"root",items:[{key:"root",service:t,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]};try{const c=sessionStorage.getItem("termdock-secure-last-workspace"),l=t&&c!==t.targetPeerId?Ht().find(d=>d.targetPeerId===c):void 0;l?.targetPeerId&&(e={activeKey:l.targetPeerId,items:[...e.items,{key:l.targetPeerId,service:l,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]})}catch{}const r=new Set,n=new Map([["root",window]]),o=new Set,s=()=>{for(const c of[...r])c()},i=(c,l)=>{try{const d=l.document.createEvent("CustomEvent");if(d.initCustomEvent(Aa,!1,!1,{active:e.activeKey===c}),l.dispatchEvent(d),e.activeKey===c){const u=l.document.createEvent("Event");if(u.initEvent("resize",!1,!1),l.dispatchEvent(u),o.delete(c)){const f=l.document.createEvent("Event");f.initEvent(ka,!1,!1),l.dispatchEvent(f)}}else l.document.activeElement?.blur?.()}catch{}},a={snapshot:()=>e,subscribe:c=>(r.add(c),()=>{r.delete(c)}),activate(c,l=!0){const d=Ss(c);if(!d?.targetPeerId)return!1;const u=e.items.find(g=>g.service?.targetPeerId===d.targetPeerId),f=u?.key||d.targetPeerId,h=u?{...u,service:d,touchedAt:Date.now()}:{key:f,service:d,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()};e={activeKey:f,items:u?e.items.map(g=>g===u?h:g):[...e.items,h]};try{sessionStorage.setItem("termdock-secure-last-workspace",d.targetPeerId)}catch{}l&&o.add(f),s();for(const[g,m]of n)i(g,m);return!0},report(c,l){const d=e.items.find(f=>f.key===c);if(!d||l.service&&d.service?.targetPeerId&&l.service.targetPeerId!==d.service.targetPeerId)return;const u={...d,...l};JSON.stringify(u)!==JSON.stringify(d)&&(e={...e,items:e.items.map(f=>f===d?u:f)},s())},attach(c,l){l?(n.set(c,l),i(c,l)):n.delete(c)},focusSession(c,l){const d=Ht().find(f=>f.targetPeerId===c);if(!d)return!1;try{localStorage.setItem(Ia+c,JSON.stringify({sessionId:l,at:Date.now()}))}catch{return!1}a.activate(d,!1);const u=n.get(e.activeKey);if(u){const f=u.document.createEvent("CustomEvent");f.initCustomEvent("termdock:workspace-session",!1,!1,null),u.dispatchEvent(f)}return!0}};return window.__termdockWorkspaceHost=a,a}let pi;async function Ge(){return pi||(pi=(async()=>{const t=await new Promise((e,r)=>{const n=indexedDB.open("termdock-device-identity",1);n.onupgradeneeded=()=>n.result.createObjectStore("keys"),n.onsuccess=()=>e(n.result),n.onerror=()=>r(n.error)});try{const e=await new Promise((o,s)=>{const i=t.transaction("keys").objectStore("keys").get("identity");i.onsuccess=()=>o(i.result),i.onerror=()=>s(i.error)});if(e)return ud(e);const r=await Ph();let n=r;return await new Promise((o,s)=>{const i=t.transaction("keys","readwrite"),a=i.objectStore("keys"),c=a.get("identity");c.onsuccess=()=>{typeof c.result=="string"?n=ud(c.result):a.put(ux(r),"identity")},i.oncomplete=()=>o(),i.onerror=()=>s(i.error)}),n}finally{t.close()}})()),pi}const lr="termdock:secure-state";let Q,bn,$e,Xn="direct",gi=!1,md=0;const Qr=globalThis.fetch.bind(globalThis);function ne(){return Dr()}function vn(){return Q}function Lx(){return $e}function qh(){Q?.close(),$e?.close(),Q=void 0,$e=void 0}async function Kh(){const t=await Qr("/api/auth/status",{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error("Failed to query auth status");return t.json()}async function Bx(){if(ne()){await lt();return}if((await Kh()).enabled)return;const t=await Qr("/api/auth/open/parameters",{cache:"no-store"});if(!t.ok)throw new Error("Open service unavailable");const{serviceIdentity:e}=await t.json();if(typeof e!="string"||!e)throw new Error("Invalid service identity");await et({url:location.origin,targetPeerId:e,serviceName:location.hostname})}async function _x(t,e){const{startPasswordBootstrap:r,finishPasswordBootstrap:n}=await Kt(async()=>{const{startPasswordBootstrap:l,finishPasswordBootstrap:d}=await import("./passwordBootstrap-CUBwV9a2.js");return{startPasswordBootstrap:l,finishPasswordBootstrap:d}},__vite__mapDeps([0,1,2,3])),o=l=>t===location.origin?l:new URL(l,t).href,s=async(l,d)=>{const u=await Qr(o(l),{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(15e3),...d?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}:{}});if(!u.ok)throw new Error(u.status===429?"尝试次数较多,请稍后再试。":u.status===401?"密码不正确,请重新输入。":"暂时无法登录这台服务,请稍后重试。");return u.json()},{saltHex:i}=await s("/api/auth/password/parameters"),a=await Ge(),c=await r(e,i);try{const l=await s("/api/auth/password/start",{startLoginRequest:c.startLoginRequest,clientIdentity:a.peerId});let d;try{d=await n(c,l,{clientIdentity:a.peerId,origin:location.origin})}catch{throw new Error("密码不正确,或服务身份无法验证。请检查后重试。")}return await s("/api/auth/password/finish",{attemptId:d.attemptId,finishLoginRequest:d.finishLoginRequest}),{url:t,targetPeerId:d.serverIdentity,serviceName:new URL(t).host,serviceOrigin:t}}finally{c.passwordKey=""}}async function Ic(t,e){const r=ne();if(r&&(r.serviceOrigin||r.url)===t)return await Ca(r,e),r;try{return await _x(t,e)}catch(n){if(!(n instanceof TypeError)&&!(n instanceof DOMException))throw n;const o=(await We()).find(i=>i.targetPeerId&&(i.serviceOrigin||i.url)===t);if(!o?.targetPeerId)throw new Error("暂时连不上这台服务,请检查地址和网络。");const s={...o,targetPeerId:o.targetPeerId,serviceName:o.label};return await Ca(s,e),s}}async function Ca(t,e){const r=await zh(t),{startPasswordBootstrap:n,finishPasswordBootstrap:o}=await Kt(async()=>{const{startPasswordBootstrap:i,finishPasswordBootstrap:a}=await import("./passwordBootstrap-CUBwV9a2.js");return{startPasswordBootstrap:i,finishPasswordBootstrap:a}},__vite__mapDeps([0,1,2,3]));let s;try{const i=await r.request({type:"password-parameters"},{timeoutMs:5e3});s=await n(e,String(i.saltHex));const a=await r.request({type:"password-start",startLoginRequest:s.startLoginRequest,origin:location.origin}),c=await o(s,a,{clientIdentity:(await Ge()).peerId,origin:location.origin});if(c.serverIdentity!==t.targetPeerId)throw new Error("服务身份发生变化。");await r.request({type:"password-finish",attemptId:c.attemptId,finishLoginRequest:c.finishLoginRequest})}catch{throw new Error("暂时无法登录,请检查目标服务密码与入口授权后重试。")}finally{s&&(s.passwordKey=""),r.close()}}async function Dx(t){try{const e=ne(),r=e?.serviceOrigin||location.origin,n=await Ic(r,t);return await et({...n,routes:e?.routes,serviceName:e?.serviceName||n.serviceName}),Response.json({ok:!0})}catch(e){return Response.json({error:e instanceof Error?e.message:"暂时无法登录,请重试。",code:"INVALID_PASSWORD"},{status:401})}}async function wd(t,e){const r=Le(t),n=(await We()).find(i=>(i.serviceOrigin||i.url)===r&&i.targetPeerId);if(e===void 0&&n?.targetPeerId)try{return await et({...n,targetPeerId:n.targetPeerId,serviceName:n.label}),{}}catch(i){if(!(i instanceof Ve))throw i}if(e!==void 0){const i=await Ic(r,e);if(n?.targetPeerId&&n.targetPeerId!==i.targetPeerId)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await et({...i,routes:n?.routes,serviceName:n?.label||i.serviceName}),{}}const o=await Qr(new URL("/api/auth/open/parameters",r).href,{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(1e4)}).catch(()=>{throw new Error("暂时连不上这台服务,请检查地址和网络后重试。")});if(o.status===403)return{passwordRequired:!0};if(!o.ok)throw new Error("这台服务暂时不可用,请稍后重试。");const{serviceIdentity:s}=await o.json();if(typeof s!="string"||!s)throw new Error("这不是可连接的 Termdock 服务。");if(n?.targetPeerId&&n.targetPeerId!==s)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await et({url:r,targetPeerId:s,serviceName:n?.label||new URL(r).host,serviceOrigin:r}),{}}function dr(t){const e=[...t.routes||[]];if(t.entryServiceId&&t.entryServiceId!==t.targetPeerId&&e.unshift({url:t.url,targetPeerId:t.entryServiceId}),!e.length&&t.routes===void 0)try{const r=JSON.parse(localStorage.getItem(Ga)||"null");r&&r.targetPeerId!==t.targetPeerId&&new URL(r.url).host===new URL(t.url).host&&e.push(r)}catch{}return e.flatMap((r,n)=>{try{return r.targetPeerId&&r.targetPeerId!==t.targetPeerId&&e.findIndex(o=>o.targetPeerId===r.targetPeerId)===n?[{url:Le(r.url),targetPeerId:r.targetPeerId}]:[]}catch{return[]}}).slice(0,4)}function io(t){const e=dr(t),r=[t.serviceOrigin||t.url,...(t.routes||[]).slice(0,4).filter(o=>o.targetPeerId===t.targetPeerId).map(o=>o.url)],n=new Set;for(const o of r)try{const s=Le(o);e.some(i=>i.url===s)||n.add(s)}catch{}return[...n]}function ur(t){const e=new URL("/api/federation/secure",Le(t));return e.protocol=e.protocol==="https:"?"wss:":"ws:",e.href}async function zt(t,e){return cr({url:ur(t.url),targetPeerId:t.targetPeerId,identity:await Ge(),signal:e?AbortSignal.any([e,AbortSignal.timeout(5e3)]):AbortSignal.timeout(5e3)})}async function zh(t,e){const r=await Ge(),n=io(t).map(i=>({key:`direct:${i}`,run:a=>cr({url:ur(i),targetPeerId:t.targetPeerId,identity:r,signal:AbortSignal.any([a,AbortSignal.timeout(8e3),...e?[e]:[]])})}));for(const i of dr(t))n.push({key:`relay:${i.targetPeerId}:${i.url}`,run:async a=>{e&&(a=AbortSignal.any([a,e]));const c=[Q,$e].find(d=>d&&!d.closed&&d.targetPeerId===i.targetPeerId),l=c||await zt(i,a);try{if(a.aborted)throw a.reason;const d=await l.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(a.aborted)throw a.reason;if(typeof d.routeToken!="string")throw new Error("入口未允许此设备连接该服务。");const u=new URL(ur(i.url));return u.pathname="/api/federation/relay",u.searchParams.set("routeToken",d.routeToken),await cr({url:u.href,targetPeerId:t.targetPeerId,identity:r,socketFactory:Fh(t.targetPeerId),signal:AbortSignal.any([a,AbortSignal.timeout(8e3)])})}finally{c||l.close()}}});const o=jh(t.targetPeerId);n.sort((i,a)=>+(a.key===o)-+(i.key===o));const s=await $h(n,i=>i.close());return Uh(t.targetPeerId,s.key),s.value}async function Ox(t,e){const r=await zh(t,e),n=()=>r.close();e.addEventListener("abort",n,{once:!0});try{if(e.aborted||(await on(r,{timeoutMs:3e3}),e.aborted))throw e.reason;return r}catch(o){throw r.close(),o}finally{e.removeEventListener("abort",n)}}async function et(t,e={}){const r=Q,n=$e,o=await Ge(),s=Le(t.serviceOrigin||t.url),i=(await We()).find(w=>w.targetPeerId===t.targetPeerId),a={...t,routes:t.routes??i?.routes},c=dr(a),l=io(a);let d,u,f=t.pairingCode,h="direct";const g=new Set,m=new Map,y=async(w,I)=>{if(r&&!r.closed&&r.targetPeerId===w.targetPeerId)return r;if(n&&!n.closed&&n.targetPeerId===w.targetPeerId)return n;const v=m.get(w.targetPeerId);if(v&&!v.closed)return v;const A=await zt(w,I);return g.add(A),m.set(w.targetPeerId,A),A};try{if(t.routeCode&&t.entryServiceId){const k=c.find(R=>R.targetPeerId===t.entryServiceId);if(!k)throw new Error("邀请缺少入口信息。");if((await(await y(k)).request({type:"route-pair",code:t.routeCode})).serviceId!==t.targetPeerId)throw new Error("邀请的目标服务不一致。");t.routeOnly&&await Et({id:t.targetPeerId,url:s,label:t.serviceName||new URL(s).host,targetPeerId:t.targetPeerId,serviceOrigin:s,routes:c})}const w=[],I=async(k,x)=>{const S=()=>k.close();x.addEventListener("abort",S,{once:!0});try{if(x.aborted||(await on(k),x.aborted))throw x.reason}catch(R){throw k.close(),R}finally{x.removeEventListener("abort",S)}};for(const k of l)w.push({key:`direct:${k}`,run:async x=>{const S=await cr({url:ur(k),targetPeerId:t.targetPeerId,pairingCode:f,identity:o,signal:AbortSignal.any([x,AbortSignal.timeout(8e3)])});return f=void 0,await I(S,x),{client:S,path:"direct"}}});for(const k of c)w.push({key:`relay:${k.targetPeerId}:${k.url}`,run:async x=>{let S,R;try{if(S=await y(k,x),x.aborted)throw x.reason;const P=await S.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(x.aborted)throw x.reason;if(typeof P.routeToken!="string"||!P.routeToken)throw new Error("入口未允许此设备连接该服务。");const b=new URL(ur(k.url));return b.pathname="/api/federation/relay",b.searchParams.set("routeToken",P.routeToken),R=await cr({url:b.href,targetPeerId:t.targetPeerId,pairingCode:f,identity:o,socketFactory:Fh(t.targetPeerId),signal:AbortSignal.any([x,AbortSignal.timeout(8e3)])}),f=void 0,await I(R,x),{client:R,entry:S,path:"relay"}}catch(P){throw R?.close(),S&&S!==n&&S!==r&&S.close(),P}}});const v=jh(t.targetPeerId);w.sort((k,x)=>+(x.key===v)-+(k.key===v));const A=await $h(w,k=>{k.client.close(),k.entry&&k.entry!==r&&k.entry!==n&&k.entry.close()},!!f);if(d=A.value.client,u=A.value.entry,h=A.value.path,Uh(t.targetPeerId,A.key),Q!==r&&Q&&!Q.closed&&Q.targetPeerId===t.targetPeerId){d.close();for(const k of g)k!==$e&&k.close();return Q}h==="direct"&&new URL(s).host===location.host&&dg(t.targetPeerId);const B=(await We()).find(k=>k.targetPeerId===t.targetPeerId||!k.targetPeerId&&(k.serviceOrigin||k.url)===s),T=B?.label||t.serviceName||new URL(s).host,N={url:s,targetPeerId:t.targetPeerId,serviceName:T,serviceOrigin:s,routes:a.routes??c};if(await(e.rememberOnly?hg:Et)({id:B?.id||t.targetPeerId,...N,label:T}),_r!=="unpaired"&&_r!==t.targetPeerId&&St()&&ps({id:B?.id||t.targetPeerId,...N,label:T})){d.close();for(const k of g)k!==r&&k!==n&&k.close();return r||d}Cu(N),Q=d,Xn=h,$e=u;for(const k of new Set([r,n,...g]))k&&k!==d&&k!==u&&k.close();return _r!==t.targetPeerId?(location.reload(),new Promise(()=>{})):(window.dispatchEvent(new Event(lr)),d)}catch(w){d?.close();for(const I of g)I!==n&&I.close();throw w}}async function Fx(){const t=Q,e=ne();if(Date.now()-md<6e4||gi||Xn!=="relay"||!t||t.closed||!t.canSwitchTransport||!e?.serviceOrigin)return;gi=!0,md=Date.now();let r;try{for(const o of io(e))try{r=await cr({url:ur(o),targetPeerId:e.targetPeerId,identity:await Ge(),signal:AbortSignal.timeout(3e3)}),await on(r);break}catch(s){if(r?.close(),r=void 0,s instanceof Ve)throw s}if(!r||Q!==t||!t.canSwitchTransport)return;const n=$e;Q=r,r=void 0,$e=void 0,Xn="direct",t.close(),n?.close(),window.dispatchEvent(new Event(lr))}catch(n){n instanceof Ve&&Q===t&&(qh(),window.dispatchEvent(new Event("auth:unauthorized")))}finally{r?.close(),gi=!1}}function Mx(){return Xn}async function lt(){if(Q&&!Q.closed)return Q;if(Q=void 0,bn)return bn;const t=ne();if(!t)throw new Error("DEVICE_PAIRING_REQUIRED");return bn=et(t,{rememberOnly:!0}).catch(e=>{if(Q&&!Q.closed&&Q.targetPeerId===t.targetPeerId)return Q;throw e}).finally(()=>{bn=void 0}),bn}function jx(t){const e=new URL(t,location.href);if(Q&&!Q.closed)return Q.openSocket(e.pathname+e.search);let r;const n=new Oh(t,o=>r?.send(o),()=>r?.close());return lt().then(o=>{n.readyState!==3&&(r=o.openSocket(e.pathname+e.search),r.onopen=()=>n.accept({type:"ws-ready",id:""}),r.onmessage=s=>n.accept({type:"ws-data",id:"",data:s.data}),r.onclose=s=>n.accept({type:"ws-close",id:"",code:s.code,reason:s.reason}),r.onerror=()=>n.fail(new Error("Encrypted connection unavailable")))}).catch(o=>n.fail(o)),n}function Ux(){Rx(lt),window.fetch=async(t,e)=>{const r=new URL(t instanceof Request?t.url:String(t),location.href);if(!r.pathname.startsWith("/api/"))return Qr(t,e);if(r.origin!==location.origin)throw new Error("Remote business API requires a paired encrypted service");if(r.pathname==="/api/meta")return Qr(t,e);if(r.pathname==="/api/auth/status"){if(!ne()){const o=await Kh();return Response.json({enabled:o.enabled,authenticated:!1})}try{const o=await on(await lt());return Response.json({enabled:o.grants.length>0,authenticated:!0})}catch(o){if(o instanceof Ve)return Response.json({enabled:!0,authenticated:!1});throw o}}if(r.pathname==="/api/auth/login"){const s=await new Request(t instanceof Request?t:r.href,e).json();return Dx(typeof s.password=="string"?s.password:"")}if(r.pathname==="/api/csrf-token")return Response.json({csrfToken:"encrypted-device-channel"});if(r.pathname==="/api/auth/logout")return Q&&!Q.closed&&await Q.request({type:"logout"}),Q?.close(),$e?.close(),Q=void 0,$e=void 0,lg(),location.reload(),Response.json({ok:!0});const n=await lt();return t instanceof Request?n.fetch(t,e):n.fetch(r.pathname+r.search,e)}}async function $x(t){if(!t.targetPeerId)throw new Error("请先连接这台服务,再查看可中转的服务。");for(const e of io({...t,targetPeerId:t.targetPeerId})){let r;const n={url:e,targetPeerId:t.targetPeerId};try{r=await zt(n)}catch{continue}try{const o=await r.request({type:"route-targets"},{timeoutMs:5e3});if(!Array.isArray(o.items))throw new Error("入口服务需要更新后才能查看中转列表。");return{route:n,canManage:o.canManage===!0,items:o.items}}catch(o){throw o instanceof Error&&/UNKNOWN|UNSUPPORTED/i.test(o.message)?new Error("入口服务需要更新后才能查看中转列表。"):o}finally{r.close()}}throw new Error("暂时连不上中转入口,请检查地址和网络后重试。")}async function Hx(t,e){const r=await zt(t);try{const n=await r.request({type:"route-targets"},{timeoutMs:5e3}),o=(Array.isArray(n.items)?n.items:[]).find(c=>c.serviceId===e);if(!o)throw new Error("该服务已不可见,请刷新列表或请入口管理员授权。");if(!o.available)throw new Error("入口暂时无法中转到这台服务,请稍后重试。");const s=(await We()).find(c=>c.targetPeerId===o.serviceId),i=[t,...(s?.routes||[]).filter(c=>c.targetPeerId!==t.targetPeerId)];if(i.length>4)throw new Error("这台服务已保存 4 个备用连接,请先移除一个后重试。");if(!o.authorized){if(!n.canManage)throw new Error("请先让入口管理员授权此设备。");await r.request({type:"route-grant",serviceId:o.serviceId,subjectId:(await Ge()).peerId})}const a=s?.serviceOrigin||s?.url||o.url||t.url;return{url:a,serviceOrigin:a,targetPeerId:o.serviceId,serviceName:s?.label||o.label||(o.url?new URL(o.url).host:`中转服务 ${o.serviceId.slice(0,8)}`),routes:i}}finally{r.close()}}async function qx(t,e){const r=await zt(t);try{const n=await r.request({type:"route-access"},{timeoutMs:5e3}),o=(await Ge()).peerId;return{canManage:n.canManage===!0,grants:(Array.isArray(n.grants)?n.grants:[]).filter(s=>s.subjectId===o&&s.targetServiceId===e)}}finally{r.close()}}async function Kx(t,e,r){if(r!==void 0&&(await Ic(Le(e.url),r)).targetPeerId!==e.targetPeerId)throw new Error("入口服务的身份已改变,请重新连接并确认。");const n=await zt(e);try{await n.request({type:"route-grant",serviceId:t.targetPeerId,subjectId:(await Ge()).peerId,url:Le(t.serviceOrigin||t.url)})}finally{n.close()}}async function zx(t,e){const r=await zt(e);try{const n=await r.request({type:"route-access"},{timeoutMs:5e3}),o=(await Ge()).peerId,s=(Array.isArray(n.grants)?n.grants:[]).filter(i=>i.subjectId===o&&i.targetServiceId===t&&i.active);for(const i of s)await r.request({type:"route-revoke",grantId:i.id})}finally{r.close()}}async function Vh(t,e){const r=await zt(e);try{const n=await r.request({type:"route-invite-create",serviceId:t.targetPeerId});if(typeof n.routeCode!="string"||typeof n.expiresAt!="number")throw new Error("暂时无法生成备用连接邀请。");return{routeCode:n.routeCode,expiresAt:n.expiresAt}}finally{r.close()}}async function Fo(t,e){const r=(await We()).find(o=>o.id===t.id||t.targetPeerId&&o.targetPeerId===t.targetPeerId)||t;await Et({...r,url:r.serviceOrigin||r.url,entryServiceId:void 0,routes:e});const n=ne();n&&n.targetPeerId===t.targetPeerId&&Cu({...n,url:n.serviceOrigin||n.url,entryServiceId:void 0,routes:e})}async function Vx(t,e){const r=t.targetPeerId;if(!r)throw new Error("请先连接这台服务,再添加备用地址。");let n;try{n=Le(e)}catch{throw new Error("请输入有效的 HTTPS 地址,例如 https://电脑地址:9834。")}const o=async()=>(await We()).find(a=>a.targetPeerId===r)||t,s=a=>{const c=a.routes??dr({...a,targetPeerId:r});if(Le(a.serviceOrigin||a.url)===n||c.some(l=>Le(l.url)===n))throw new Error("这个地址已经在连接列表中。");if(c.length>=4)throw new Error("最多保存 4 个备用地址或入口,请先移除不再使用的连接。");return[...c,{url:n,targetPeerId:r}]};s(await o());let i;try{try{i=await cr({url:ur(n),targetPeerId:r,identity:await Ge(),signal:AbortSignal.timeout(5e3)}),await on(i)}catch(l){throw l instanceof Ve?new Error("这台服务尚未授权当前设备,请先恢复设备授权。"):new Error("无法验证这个地址。请确认能访问该地址、HTTPS 证书受信任,且运行的是同一台 Termdock 服务。")}const a=await o(),c=s(a);if(await Fo(a,c),ne()?.targetPeerId===r&&_r===r&&(!Q||Q.closed)){const l=Q,d=$e;Q=i,i=void 0,$e=void 0,Xn="direct",l?.close(),d?.close(),window.dispatchEvent(new Event(lr))}return c}finally{i?.close()}}async function yd(t,e){await Ca(t,e),await et({...t,pairingCode:void 0,routeCode:void 0})}function Wx(t,e){return e.aborted?Promise.reject(e.reason):new Promise((r,n)=>{const o=()=>n(e.reason);e.addEventListener("abort",o,{once:!0}),t.then(r,n).finally(()=>e.removeEventListener("abort",o))})}function Wh(){if(window.termdockDesktop||window.parent!==window)return;if(window.__termdockCollaboration)return window.__termdockCollaboration;const t=new Map;let e=[],r=!1;const n=l=>{const d=l.targetPeerId;if(ne()?.targetPeerId===d)return lt();const u=t.get(d);if(u)return u.then(h=>h.closed?(t.get(d)===u&&t.delete(d),n(l)):h);const f=Ox({...l,targetPeerId:d},AbortSignal.timeout(12e3)).then(h=>{if(r||t.get(d)!==f)throw h.close(),new Error("服务连接已移除");return h}).catch(h=>{throw t.get(d)===f&&t.delete(d),h});return t.set(d,f),f},o=()=>{const l=ne(),d=Ht();l&&!d.some(f=>f.targetPeerId===l.targetPeerId)&&d.push({...l,id:l.targetPeerId,label:l.serviceName||l.serviceOrigin||l.url});const u=new Set(d.map(f=>f.targetPeerId));for(const[f,h]of t)u.has(f)||(t.delete(f),h.then(g=>g.close()).catch(()=>{}));e=d.filter(f=>!!f.targetPeerId).map(f=>({origin:f.serviceOrigin||f.url,label:f.label,request:async(h,g="GET",m)=>{if(!/^\/collaboration-(?:federation|groups)(?:\/[^?#]*)?$/.test(h))throw new Error("无效的协作请求");const y=AbortSignal.timeout(18e3),w=await Wx(n(f),y),I=new Headers({"Content-Type":"application/json"});if(g!=="GET"&&g!=="HEAD"){const B=await w.fetch("/api/csrf-token",{signal:y});if(!B.ok)throw new Error("无法读取目标服务的请求令牌");const T=await B.json();if(typeof T.csrfToken!="string")throw new Error("目标服务的请求令牌无效");I.set("X-XSRF-TOKEN",T.csrfToken)}const v=await w.fetch(`/api/terminal/operations${h}`,{method:g,headers:I,signal:y,...m===void 0?{}:{body:JSON.stringify(m)}}),A=v.status===204?void 0:await v.json();if(!v.ok)throw new Error(A?.error||"服务不可达或未授权协作访问");return A}}))},s=new fg(()=>e),i={peers:l=>(o(),s.peers(l)),save:async(l,d)=>{o();const u=await s.save(l,d);return a(),u}},a=async()=>{r||document.hidden||!navigator.onLine||!ne()||(o(),!(e.length<2)&&await s.refresh().catch(()=>{}))};window.__termdockCollaboration=i;const c=window.setInterval(()=>{a()},2e3);return document.addEventListener("visibilitychange",a),window.addEventListener("online",a),window.addEventListener("pageshow",a),window.addEventListener("pagehide",l=>{if(!l.persisted){r=!0,clearInterval(c);for(const d of t.values())d.then(u=>u.close()).catch(()=>{});t.clear()}}),a(),i}function Gh(){if(!window.termdockDesktop)try{if(window.parent===window)return Wh();if(location.pathname==="/workspace.html"&&window.parent.location.origin===location.origin)return window.parent.__termdockCollaboration}catch{}}var To={},bd;function Gx(){if(bd)return To;bd=1;var t=Qp();return To.createRoot=t.createRoot,To.hydrateRoot=t.hydrateRoot,To}var Xx=Gx();const Yx=Iu(Xx);const Xh=(...t)=>t.filter((e,r,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===r).join(" ").trim();const Zx=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const Jx=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,r,n)=>n?n.toUpperCase():r.toLowerCase());const vd=t=>{const e=Jx(t);return e.charAt(0).toUpperCase()+e.slice(1)};var mi={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Qx=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1},eS=F.createContext({}),tS=()=>F.useContext(eS),rS=F.forwardRef(({color:t,size:e,strokeWidth:r,absoluteStrokeWidth:n,className:o="",children:s,iconNode:i,...a},c)=>{const{size:l=24,strokeWidth:d=2,absoluteStrokeWidth:u=!1,color:f="currentColor",className:h=""}=tS()??{},g=n??u?Number(r??d)*24/Number(e??l):r??d;return F.createElement("svg",{ref:c,...mi,width:e??l??mi.width,height:e??l??mi.height,stroke:t??f,strokeWidth:g,className:Xh("lucide",h,o),...!s&&!Qx(a)&&{"aria-hidden":"true"},...a},[...i.map(([m,y])=>F.createElement(m,y)),...Array.isArray(s)?s:[s]])});const Te=(t,e)=>{const r=F.forwardRef(({className:n,...o},s)=>F.createElement(rS,{ref:s,iconNode:e,className:Xh(`lucide-${Zx(vd(t))}`,`lucide-${t}`,n),...o}));return r.displayName=vd(t),r};const nS=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Yh=Te("arrow-left",nS);const oS=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],sS=Te("arrow-right",oS);const iS=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M11.68 2.009A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673c-.824-.85-1.678-1.731-2.21-3.348",key:"xaq59h"}],["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}]],aS=Te("bell-dot",iS);const cS=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Cc=Te("check",cS);const lS=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],dS=Te("chevron-down",lS);const uS=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],fr=Te("chevron-right",uS);const fS=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Zh=Te("copy",fS);const hS=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],pS=Te("ellipsis",hS);const gS=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],He=Te("loader-circle",gS);const mS=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],wS=Te("monitor",mS);const yS=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],bS=Te("pencil",yS);const vS=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Jh=Te("plus",vS);const xS=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],Os=Te("server",xS);const SS=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],Qh=Te("smartphone",SS);const ES=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],AS=Te("terminal",ES);const kS=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],IS=Te("x",kS);let Lr=null;function CS(t){return!Lr||!t?!1:(Lr(t),!0)}function Uk(t){Lr=t;const e=r=>{const{text:n,nonce:o}=r.detail??{};!n||Lr!==t||(t(n),r.stopImmediatePropagation(),o&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:o,ok:!0}})))};return window.addEventListener("termdock-insert-reference",e,!0),()=>{Lr===t&&(Lr=null),window.removeEventListener("termdock-insert-reference",e,!0)}}const RS=/^[A-Za-z0-9_@%+=:,./-]$/;function TS(t){return Array.from(t,e=>(e.codePointAt(0)??0)>127||RS.test(e)?e:`\\${e}`).join("")}function PS(t,e){if(!e)return!1;try{const r=new URL(e.serviceOrigin||e.url);return r.origin===t&&/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})$/.test(r.hostname)&&!(e.routes??[]).some(n=>n.targetPeerId!==e.targetPeerId)}catch{return!1}}function NS(t){const e=s=>s.target instanceof Element?s.target.closest("[data-termdock-terminal-dropzone]"):null,r=()=>!PS(location.origin,Dr()),n=s=>{const i=e(s);!i||!r()||!s.dataTransfer?.types.includes("Files")||(s.preventDefault(),s.stopImmediatePropagation(),s.dataTransfer.dropEffect="copy",i.dataset.nativeFileDrag="true",i.dataset.nativeFileDropState="remote")},o=s=>{const i=e(s),a=Array.from(s.dataTransfer?.files??[]);if(!i||!a.length||!r())return;s.preventDefault(),s.stopImmediatePropagation();const c=i.dataset.termdockTerminalDropzone??"";i.dataset.nativeFileDrag="true",i.dataset.nativeFileDropState="uploading",Kt(async()=>{const{uploadFiles:l}=await Promise.resolve().then(()=>G2);return{uploadFiles:l}},void 0).then(({uploadFiles:l})=>l("/tmp",a)).then(l=>{if(l.files.length!==a.length||l.files.some(d=>!d.path))throw new Error("Upload did not return every file path");delete i.dataset.nativeFileDrag,delete i.dataset.nativeFileDropState,t({sessionKey:c,paths:l.files.map(d=>d.path)})}).catch(l=>{i.dataset.nativeFileDropState="error",i.dispatchEvent(new CustomEvent("termdock:file-drop-error",{bubbles:!0,detail:l instanceof Error?l.message:"File upload failed"})),window.setTimeout(()=>{i.dataset.nativeFileDropState==="error"&&(delete i.dataset.nativeFileDrag,delete i.dataset.nativeFileDropState)},3e3)})};return window.addEventListener("dragover",n,!0),window.addEventListener("drop",o,!0),()=>{window.removeEventListener("dragover",n,!0),window.removeEventListener("drop",o,!0)}}function ep(){return typeof window>"u"?null:window.termdockDesktop??null}const wi=new Set;let xd=!1;function $k(t){const e=ep();if(!e)return()=>{};if(wi.add(t),!xd){const r=n=>{if(!CS(n.paths.map(TS).join(" ")+" "))for(const o of wi)o(n)};NS(r),e.onNativeFileDrop(r),xd=!0}return()=>{wi.delete(t)}}function tp(t=navigator.userAgent,e=navigator.maxTouchPoints){const r=/iPad/.test(t)||/Macintosh/.test(t)&&e>1?"iPad":/iPhone/.test(t)?"iPhone":/Android/.test(t)?"Android":/Windows/.test(t)?"Windows":/Macintosh|Mac OS X/.test(t)?"Mac":/Linux/.test(t)?"Linux":"设备",n=/Electron/.test(t)?"Termdock":/Edg\//.test(t)?"Edge":/Firefox|FxiOS/.test(t)?"Firefox":/Chrome|CriOS/.test(t)?"Chrome":/Safari/.test(t)?"Safari":"浏览器";return`${r} · ${n}`}let LS;function BS(){return LS??=(async()=>{const t=navigator.userAgent,[e,r]=tp().split(" · "),n=/(?:Edg|Firefox|FxiOS|Chrome|CriOS|Version)\/([\d.]+)/g,o=[...t.matchAll(n)],s=/(?:CPU (?:iPhone )?OS |Mac OS X |Android )([\d._]+)/.exec(t)?.[1]?.replaceAll("_","."),i={system:`${e}${s?` ${s}`:""}`,client:`${r}${o.length?` ${o.at(-1)[1]}`:""}`,mode:matchMedia("(display-mode: standalone)").matches||navigator.standalone?"已安装的网页应用":"网页"},a=ep();if(a){i.mode="桌面客户端";const l=/Electron\/([\d.]+)/.exec(t)?.[1];i.client=l?`Termdock(Electron ${l})`:"Termdock";try{Object.assign(i,await a.deviceInfo?.())}catch{}return i}const c=navigator.userAgentData;try{const l=await c?.getHighEntropyValues(["model","architecture","bitness","platformVersion"]);typeof l?.model=="string"&&l.model&&(i.model=l.model),typeof l?.architecture=="string"&&l.architecture&&(i.arch=`${l.architecture}${l.bitness?` ${l.bitness} 位`:""}`)}catch{}return i})()}function _S({service:t,onBusyChange:e,onConnect:r,onConnectWithPassword:n}){const[o,s]=F.useState(),[i,a]=F.useState(!0),[c,l]=F.useState(!1),[d,u]=F.useState(""),[f,h]=F.useState(0),[g,m]=F.useState(),[y,w]=F.useState("");F.useEffect(()=>{let A=!1;return a(!0),u(""),s(void 0),$x(t).then(B=>{A||s(B)}).catch(B=>{A||u(B instanceof Error?B.message:"暂时无法读取中转列表,请重试。")}).finally(()=>{A||a(!1)}),()=>{A=!0}},[t.id,t.url,f]);const I=async A=>{if(!c){l(!0),e(!0),u("");try{await A()}catch(B){u(B instanceof Error?B.message:"暂时无法连接,请重试。")}finally{l(!1),e(!1)}}},v=async A=>{const B=await Hx(o.route,A.serviceId);try{await r(B)}catch(T){if(!(T instanceof Ve))throw T;m(B)}};return p.jsxs("div",{className:"service-form",children:[g?p.jsxs("form",{className:"service-form",onSubmit:A=>{A.preventDefault(),I(async()=>{try{await n?.(g,y)}finally{w("")}})},children:[p.jsxs("p",{className:"service-help",children:["已通过“",t.label,"”连接到“",g.serviceName,"”。请登录目标服务,完成此设备的访问授权。"]}),n?p.jsxs(p.Fragment,{children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"目标服务密码"}),p.jsx("input",{type:"password",autoFocus:!0,required:!0,autoComplete:"current-password",value:y,disabled:c,onChange:A=>w(A.target.value)})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:c||!y,children:c?"正在登录…":"登录并连接"})]}):p.jsx("p",{className:"service-help",children:"请让目标服务管理员邀请此设备后再连接。"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>{m(void 0),w(""),u(""),h(A=>A+1)},children:"返回中转列表"})]}):p.jsxs(p.Fragment,{children:[p.jsxs("p",{className:"service-help",children:["通过“",t.label,"”连接下方服务。",o?.canManage?"选择未授权的服务会授权此设备使用该中转。":"这里只显示已授权给此设备的中转。","目标服务会单独验证访问权限。"]}),i?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在读取可中转的服务…"]}):o&&p.jsxs("div",{className:"service-list",children:[o.items.map(A=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:c||!A.available,onClick:()=>{I(()=>v(A))},children:[p.jsx("span",{className:"service-icon",children:p.jsx(Os,{size:19})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:A.label||(A.url?new URL(A.url).host:`中转服务 ${A.serviceId.slice(0,8)}`)}),p.jsx("span",{className:"service-description",children:A.available?A.authorized?"已获中转授权 · 连接":"授权此设备并连接":"中转暂不可用"})]}),p.jsx(fr,{size:16})]},A.serviceId)),o.items.length===0&&p.jsx("p",{className:"service-empty",children:o.canManage?"暂无可中转的服务。可在本机 Mac 客户端连接目标服务,或在目标服务的“备用连接”中启用本入口。":"暂无已授权的中转服务,请让入口管理员分享备用连接邀请。"})]}),c&&p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在授权并连接目标服务…"]}),!i&&p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>h(A=>A+1),children:"刷新列表"})]}),d&&p.jsx("p",{className:"service-error",role:"alert",children:d})]})}const Ra="#termdock-invite=";function rp(t){const e=new URL(t.entryUrl);e.hash="",e.search="",e.pathname="/";const r=new TextEncoder().encode(JSON.stringify(t));return e.hash=Ra.slice(1)+btoa(String.fromCharCode(...r)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),e.href}function gs(t){const e=new URL(t);if(!["https:","http:"].includes(e.protocol)||!e.hash.startsWith(Ra))throw new Error("这不是有效的 Termdock 邀请链接");const r=e.hash.slice(Ra.length);if(r.length>8192)throw new Error("邀请链接过长");let n;try{const i=r.replace(/-/g,"+").replace(/_/g,"/");n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(atob(i),a=>a.charCodeAt(0))))}catch{throw new Error("邀请链接不完整,请重新复制")}if(n.v!==1||typeof n.serviceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(n.serviceId)||n.routeOnly!==!0&&(typeof n.code!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(n.code)))throw new Error("邀请信息无效或版本不兼容");const o=new URL(n.entryUrl);if(o.origin!==e.origin||o.username||o.password||!["https:","http:"].includes(o.protocol))throw new Error("邀请地址与服务不一致");if(o.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(o.hostname))throw new Error("远程邀请需要 HTTPS");if(n.entryServiceId!==void 0&&(typeof n.entryServiceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(n.entryServiceId)))throw new Error("邀请入口身份无效");if(n.routeCode!==void 0&&(typeof n.routeCode!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(n.routeCode)||!n.entryServiceId))throw new Error("邀请入口权限无效");if(n.routeOnly===!0&&(!n.entryServiceId||!n.routeCode||n.code!==void 0))throw new Error("备用连接邀请不完整");let s=o.origin;if(n.serviceUrl!==void 0){const i=new URL(n.serviceUrl);if(!["https:","http:"].includes(i.protocol)||i.username||i.password)throw new Error("目标服务地址无效");s=n.entryServiceId&&n.entryServiceId!==n.serviceId?i.origin:o.origin}return{url:o.origin,targetPeerId:n.serviceId,pairingCode:n.code,...n.routeOnly===!0?{routeOnly:!0}:{},serviceOrigin:s,serviceName:typeof n.name=="string"?n.name.slice(0,120):void 0,entryServiceId:n.entryServiceId,routeCode:n.routeCode}}function DS({service:t,onBusyChange:e}){const r={...t,targetPeerId:t.targetPeerId,serviceName:t.label},[n,o]=F.useState(()=>t.routes??dr(r)),[s,i]=F.useState([]),[a,c]=F.useState(!0),[l,d]=F.useState(!1),[u,f]=F.useState(""),h=D=>{d(D),e(D)},[g,m]=F.useState(),[y,w]=F.useState(""),[I,v]=F.useState(""),[A,B]=F.useState(""),[T,N]=F.useState(!1),[k,x]=F.useState(),[S,R]=F.useState(),[P,b]=F.useState(!1);F.useEffect(()=>{let D=!1;return We().then(_=>{D||i(_.filter(O=>O.targetPeerId&&O.targetPeerId!==t.targetPeerId))}).catch(()=>{D||f("暂时无法读取可用服务。")}).finally(()=>{D||c(!1)}),()=>{D=!0}},[t.targetPeerId]);const E=D=>s.find(_=>_.targetPeerId===D.targetPeerId)?.label||new URL(D.url).host,C=async D=>{h(!0),f(""),B("");try{await D()}catch(_){const O=_ instanceof Error?_.message:"";f(/AUTHORIZATION|DENIED/.test(O)?"当前设备没有入口管理权限。请让管理员分享备用连接邀请,或使用入口密码授权。":"暂时无法完成。请确认入口能连接目标服务,且目标地址、证书和授权有效。")}finally{h(!1)}},L=async(D,_)=>{const O={url:D.serviceOrigin||D.url,targetPeerId:D.targetPeerId};await C(async()=>{const q=await qx(O,r.targetPeerId);if(!q.grants.some(K=>K.active)){if(!q.canManage&&_===void 0){m(D);return}await Kx(r,O,_)}const H=[...n.filter(K=>K.targetPeerId!==O.targetPeerId),O];await Fo(t,H),o(H),m(void 0),w("")})};if(S)return p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["把链接发给需要使用此备用连接的人。它只允许通过入口连接“",t.label,"”,对方仍需获得目标服务的访问权限。"]}),p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用连接邀请"}),p.jsx("input",{readOnly:!0,value:S,onFocus:D=>D.target.select()})]}),p.jsxs("button",{type:"button",className:"service-button service-primary",onClick:()=>{navigator.clipboard.writeText(S).then(()=>b(!0)).catch(()=>f("无法自动复制,请长按链接复制。"))},children:[p.jsx(Zh,{size:16}),P?"已复制":"复制邀请链接"]}),p.jsx("button",{type:"button",className:"service-button service-secondary",onClick:()=>{R(void 0),b(!1)},children:"返回备用连接"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});if(g)return p.jsxs("form",{className:"service-form",onSubmit:D=>{D.preventDefault(),L(g,y).finally(()=>w(""))},children:[p.jsxs("p",{className:"service-help",children:["需要“",g.label,"”的管理员授权。若这是你的服务,可以使用它的密码;否则请管理员分享备用连接邀请。"]}),p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"入口服务密码"}),p.jsx("input",{type:"password",required:!0,value:y,onChange:D=>w(D.target.value),autoComplete:"current-password",disabled:l,autoFocus:!0})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||!y,children:l?"正在授权…":"授权并启用"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{m(void 0),w("")},children:"取消"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});const M=n.filter(D=>D.targetPeerId===r.targetPeerId),$=n.filter(D=>D.targetPeerId!==r.targetPeerId),j=async()=>{if(!l){h(!0),N(!0),f(""),B("");try{o(await Vx({...t,routes:n},I)),v(""),B("备用地址已验证并保存。")}catch(D){f(D instanceof Error?D.message:"暂时无法添加地址,请重试。")}finally{h(!1),N(!1)}}};return p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"电脑换了网络?添加它在新网络下的地址,原地址连不上时会自动尝试。只接受同一台服务。"}),p.jsxs("form",{className:"service-form",onSubmit:D=>{D.preventDefault(),j()},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用地址"}),p.jsx("input",{value:I,onChange:D=>{v(D.target.value),f(""),B("")},required:!0,disabled:l||n.length>=4,inputMode:"url",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:192.168.10.20:9834"})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||n.length>=4||!I.trim(),children:T?p.jsxs(p.Fragment,{children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在验证…"]}):"验证并添加"})]}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u}),A&&p.jsx("p",{role:"status",className:"service-help",children:A}),n.length>=4&&p.jsx("p",{className:"service-help",children:"已保存 4 个备用连接。移除不再使用的地址或入口后,可以继续添加。"}),p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"首选地址"}),p.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url})]}),M.length>0&&p.jsx("div",{className:"service-list",children:M.map(D=>p.jsxs("div",{className:"service-route-item",children:[p.jsxs("div",{className:"service-route-line",children:[p.jsx("span",{className:"service-address service-route-address",children:D.url}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`移除地址 ${D.url}`,disabled:l,onClick:()=>x(D),children:"移除"})]}),k?.targetPeerId===D.targetPeerId&&k.url===D.url&&p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"从备用连接中移除此地址?不会停止正在运行的终端。"}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>x(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{C(async()=>{const _=n.filter(O=>O.targetPeerId!==D.targetPeerId||O.url!==D.url);await Fo(t,_),o(_),x(void 0)})},children:"确认移除"})]})]})]},D.url))}),p.jsxs("details",{className:"service-relay-options",children:[p.jsxs("summary",{children:["通过其他服务中转",$.length?`(${$.length})`:""]}),p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"所有直连地址都不可用时,尝试下方已授权入口;直连恢复后自动切回。"}),$.length>0&&p.jsx("div",{className:"service-list",children:$.map(D=>p.jsxs("div",{className:"service-route-item",children:[p.jsxs("div",{className:"service-route-line",children:[p.jsx("span",{className:"service-icon",children:p.jsx(Os,{size:18})}),p.jsx("span",{className:"service-name",children:E(D)}),p.jsx(Cc,{size:16,className:"service-selected"})]}),k?.targetPeerId===D.targetPeerId?p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["撤销此设备经“",E(D),"”连接目标的权限?如当前无法直连,目标服务将断开。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>x(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{C(async()=>{await zx(r.targetPeerId,D);const _=n.filter(O=>O.targetPeerId!==D.targetPeerId);await Fo(t,_),o(_),x(void 0)})},children:"确认撤销"})]})]}):p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{C(async()=>{const _=await Vh(r,D);R(rp({v:1,routeOnly:!0,serviceId:r.targetPeerId,name:t.label,serviceUrl:t.serviceOrigin||t.url,entryUrl:D.url,entryServiceId:D.targetPeerId,routeCode:_.routeCode}))})},children:"分享备用连接"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>x(D),children:"撤销授权"})]})]},D.targetPeerId))}),a?p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"添加中转入口"}),s.filter(D=>!n.some(_=>_.targetPeerId===D.targetPeerId)).map(D=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:l||n.length>=4,onClick:()=>{L(D)},children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:D.label}),p.jsx("span",{className:"service-description",children:"验证并授权后启用"})]}),p.jsx(fr,{size:16})]},D.id)),s.length===0&&p.jsx("p",{className:"service-empty",children:"添加并登录另一台服务后,可以将它设为中转入口。"})]})]})]}),l&&!T&&p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在验证连接与授权…"]})]})}function OS({current:t,renderRoutes:e,renderRelayServices:r,onOpen:n,onAdd:o,onInvite:s,hideHeader:i,onNavigation:a,onBusyChange:c,initiallyAdding:l=!1}){const[d,u]=F.useState([]),[f,h]=F.useState(!0),[g,m]=F.useState(l?{kind:"add"}:{kind:"list"}),[y,w]=F.useState(!1),I=F.useCallback(b=>{w(b),c?.(b)},[c]),[v,A]=F.useState(""),B=F.useCallback(()=>{m(b=>b.kind==="routes"||b.kind==="relay-services"?{kind:"edit",service:b.service}:{kind:"list"}),A("")},[]),T=g.kind==="add"?"添加服务":g.kind==="edit"?"服务设置":g.kind==="routes"?"备用连接":g.kind==="relay-services"?"可中转的服务":void 0;F.useEffect(()=>{a?.({title:T,...T?{back:B}:{}})},[T,B,a]),F.useEffect(()=>{let b=!1,E=0;const C=async()=>{const M=++E;try{const $=await We();!b&&E===M&&(u($),A(""))}catch{!b&&E===M&&A("暂时无法读取服务列表,请重试。")}finally{!b&&E===M&&h(!1)}};C();const L=Pu(()=>{C()});return()=>{b=!0,L()}},[]);const N=async b=>{if(!y){I(!0),A("");try{await b()}catch(E){A(E instanceof Error?E.message:"暂时无法完成,请重试。")}finally{I(!1)}}},k=g.kind==="edit"||g.kind==="routes"||g.kind==="relay-services"?d.find(b=>wt(b,g.service))||g.service:void 0,x=t?d.find(b=>wt(b,t))||t:void 0,S=d.filter(b=>!t||!wt(b,t)),R=x?[x,...S]:S,P=p.jsxs(p.Fragment,{children:[f?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{className:"service-list",children:[R.map(b=>{const E=!!t&&wt(b,t);return p.jsxs("div",{className:"service-row",children:[p.jsxs("button",{type:"button",className:"service-row-open",disabled:y||E,onClick:()=>{N(async()=>{(await n(b))?.passwordRequired&&m({kind:"add",input:b.serviceOrigin||b.url,passwordRequired:!0})})},"aria-label":E?`当前服务 ${b.label}`:`打开 ${b.label}`,children:[p.jsx("span",{className:"service-icon",children:p.jsx(Os,{size:20})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:b.label}),p.jsx("span",{className:"service-description",children:E?"当前服务":new URL(b.serviceOrigin||b.url).host})]}),E?p.jsx(Cc,{size:17,className:"service-selected"}):p.jsx(fr,{size:16,className:"service-muted"})]}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`管理 ${b.label}`,disabled:y,onClick:()=>{m({kind:"edit",service:b}),A("")},children:p.jsx(pS,{size:19})})]},b.id)}),R.length===0&&p.jsx("p",{className:"service-empty",children:"还没有添加服务。连接你的电脑,或粘贴收到的邀请链接。"})]}),p.jsxs("div",{className:`service-actions${s?" service-actions-pair":""}`,children:[p.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:y,onClick:()=>{m({kind:"add"}),A("")},children:[p.jsx(Jh,{size:16}),"添加服务"]}),s&&p.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:y,onClick:s,children:[p.jsx(Qh,{size:16}),"邀请设备"]})]})]});return p.jsxs("div",{className:"service-manager",children:[!i&&p.jsxs("div",{className:"service-heading",children:[T&&p.jsx("button",{type:"button",className:"service-icon-button","aria-label":"返回服务",disabled:y,onClick:B,children:p.jsx(Yh,{size:20})}),p.jsx("h2",{children:T||"服务"})]}),g.kind==="relay-services"?r?.(k,I):g.kind==="routes"?e?.(k,I):g.kind==="list"?P:g.kind==="add"?p.jsx(FS,{onSave:b=>N(async()=>{const E=Le(b);u(await Et({id:E,url:E,label:new URL(E).host})),B()}),initialInput:g.input,passwordRequired:g.passwordRequired,busy:y,onSubmit:async(b,E)=>{let C;return await N(async()=>{C=await o(b,E),C?.passwordRequired||B()}),C}}):p.jsx(MS,{onRelayServices:r&&g.service.targetPeerId?()=>m({kind:"relay-services",service:g.service}):void 0,onRoutes:e&&g.service.targetPeerId?()=>m({kind:"routes",service:g.service}):void 0,service:k,busy:y,canRemove:!t||!wt(g.service,t),onSave:b=>{N(async()=>{u(await Et({...k,label:b})),B()})},onRemove:()=>{N(async()=>{u(await pg(g.service.id)),B()})}}),v&&p.jsx("p",{className:"service-error",role:"alert",children:v})]})}function FS({busy:t,onSubmit:e,onSave:r,initialInput:n="",passwordRequired:o=!1}){const[s,i]=F.useState(n),[a,c]=F.useState(""),[l,d]=F.useState(o);return p.jsxs("form",{className:"service-form",onSubmit:async u=>{u.preventDefault(),(await e(s.trim(),l?a:void 0))?.passwordRequired&&d(!0),c("")},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务地址或邀请链接"}),p.jsx("input",{value:s,onChange:u=>{i(u.target.value),d(!1),c("")},disabled:t,required:!0,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:电脑地址:9834 或 https://…"})]}),l?p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务密码"}),p.jsx("input",{type:"password",value:a,onChange:u=>c(u.target.value),disabled:t,required:!0,autoFocus:!0,autoComplete:"current-password",placeholder:"输入这台服务的密码"})]}):p.jsx("p",{className:"service-help",children:"连接自己的服务,输入地址即可;收到邀请时,粘贴完整链接。"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:t||!s.trim()||s.includes("#termdock-invite="),onClick:()=>{r(s.trim())},children:"仅保存,不连接"}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:t||!s.trim()||l&&!a,children:t?p.jsxs(p.Fragment,{children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在连接…"]}):l?"登录并连接":"继续"})]})}function MS({service:t,busy:e,canRemove:r,onSave:n,onRemove:o,onRoutes:s,onRelayServices:i}){const[a,c]=F.useState(t.label),[l,d]=F.useState(!1);return p.jsxs("form",{className:"service-form",onSubmit:u=>{u.preventDefault(),n(a.trim())},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务名称"}),p.jsx("input",{value:a,onChange:u=>c(u.target.value),disabled:e,required:!0,maxLength:120,placeholder:"例如:办公室电脑"})]}),p.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:e||!a.trim(),children:"保存名称"}),i&&p.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:i,children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:"可中转的服务"}),p.jsx("span",{className:"service-description",children:"通过这台服务连接其他电脑"})]}),p.jsx(fr,{size:16})]}),s&&p.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:s,children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:"备用连接"}),p.jsx("span",{className:"service-description",children:"添加其他网络地址或授权入口"})]}),p.jsx(fr,{size:16})]}),r&&p.jsx("div",{className:"service-remove",children:l?p.jsxs(p.Fragment,{children:[p.jsxs("p",{className:"service-help",children:["从列表移除“",t.label,"”?不会停止服务或删除终端。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:e,onClick:()=>d(!1),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:o,children:"确认移除"})]})]}):p.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:()=>d(!0),children:"移除服务"})})]})}var Cr={},yi,Sd;function jS(){return Sd||(Sd=1,yi=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),yi}var bi={},Dt={},Ed;function mr(){if(Ed)return Dt;Ed=1;let t;const e=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Dt.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},Dt.getSymbolTotalCodewords=function(n){return e[n]},Dt.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Dt.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');t=n},Dt.isKanjiModeEnabled=function(){return typeof t<"u"},Dt.toSJIS=function(n){return t(n)},Dt}var vi={},Ad;function Rc(){return Ad||(Ad=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+r)}}t.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},t.from=function(n,o){if(t.isValid(n))return n;try{return e(n)}catch{return o}}})(vi)),vi}var xi,kd;function US(){if(kd)return xi;kd=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(e){const r=Math.floor(e/8);return(this.buffer[r]>>>7-e%8&1)===1},put:function(e,r){for(let n=0;n<r;n++)this.putBit((e>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),e&&(this.buffer[r]|=128>>>this.length%8),this.length++}},xi=t,xi}var Si,Id;function $S(){if(Id)return Si;Id=1;function t(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return t.prototype.set=function(e,r,n,o){const s=e*this.size+r;this.data[s]=n,o&&(this.reservedBit[s]=!0)},t.prototype.get=function(e,r){return this.data[e*this.size+r]},t.prototype.xor=function(e,r,n){this.data[e*this.size+r]^=n},t.prototype.isReserved=function(e,r){return this.reservedBit[e*this.size+r]},Si=t,Si}var Ei={},Cd;function HS(){return Cd||(Cd=1,(function(t){const e=mr().getSymbolSize;t.getRowColCoords=function(n){if(n===1)return[];const o=Math.floor(n/7)+2,s=e(n),i=s===145?26:Math.ceil((s-13)/(2*o-2))*2,a=[s-7];for(let c=1;c<o-1;c++)a[c]=a[c-1]-i;return a.push(6),a.reverse()},t.getPositions=function(n){const o=[],s=t.getRowColCoords(n),i=s.length;for(let a=0;a<i;a++)for(let c=0;c<i;c++)a===0&&c===0||a===0&&c===i-1||a===i-1&&c===0||o.push([s[a],s[c]]);return o}})(Ei)),Ei}var Ai={},Rd;function qS(){if(Rd)return Ai;Rd=1;const t=mr().getSymbolSize,e=7;return Ai.getPositions=function(n){const o=t(n);return[[0,0],[o-e,0],[0,o-e]]},Ai}var ki={},Td;function KS(){return Td||(Td=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},t.from=function(o){return t.isValid(o)?parseInt(o,10):void 0},t.getPenaltyN1=function(o){const s=o.size;let i=0,a=0,c=0,l=null,d=null;for(let u=0;u<s;u++){a=c=0,l=d=null;for(let f=0;f<s;f++){let h=o.get(u,f);h===l?a++:(a>=5&&(i+=e.N1+(a-5)),l=h,a=1),h=o.get(f,u),h===d?c++:(c>=5&&(i+=e.N1+(c-5)),d=h,c=1)}a>=5&&(i+=e.N1+(a-5)),c>=5&&(i+=e.N1+(c-5))}return i},t.getPenaltyN2=function(o){const s=o.size;let i=0;for(let a=0;a<s-1;a++)for(let c=0;c<s-1;c++){const l=o.get(a,c)+o.get(a,c+1)+o.get(a+1,c)+o.get(a+1,c+1);(l===4||l===0)&&i++}return i*e.N2},t.getPenaltyN3=function(o){const s=o.size;let i=0,a=0,c=0;for(let l=0;l<s;l++){a=c=0;for(let d=0;d<s;d++)a=a<<1&2047|o.get(l,d),d>=10&&(a===1488||a===93)&&i++,c=c<<1&2047|o.get(d,l),d>=10&&(c===1488||c===93)&&i++}return i*e.N3},t.getPenaltyN4=function(o){let s=0;const i=o.data.length;for(let c=0;c<i;c++)s+=o.data[c];return Math.abs(Math.ceil(s*100/i/5)-10)*e.N4};function r(n,o,s){switch(n){case t.Patterns.PATTERN000:return(o+s)%2===0;case t.Patterns.PATTERN001:return o%2===0;case t.Patterns.PATTERN010:return s%3===0;case t.Patterns.PATTERN011:return(o+s)%3===0;case t.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case t.Patterns.PATTERN101:return o*s%2+o*s%3===0;case t.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case t.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}t.applyMask=function(o,s){const i=s.size;for(let a=0;a<i;a++)for(let c=0;c<i;c++)s.isReserved(c,a)||s.xor(c,a,r(o,c,a))},t.getBestMask=function(o,s){const i=Object.keys(t.Patterns).length;let a=0,c=1/0;for(let l=0;l<i;l++){s(l),t.applyMask(l,o);const d=t.getPenaltyN1(o)+t.getPenaltyN2(o)+t.getPenaltyN3(o)+t.getPenaltyN4(o);t.applyMask(l,o),d<c&&(c=d,a=l)}return a}})(ki)),ki}var Po={},Pd;function np(){if(Pd)return Po;Pd=1;const t=Rc(),e=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return Po.getBlocksCount=function(o,s){switch(s){case t.L:return e[(o-1)*4+0];case t.M:return e[(o-1)*4+1];case t.Q:return e[(o-1)*4+2];case t.H:return e[(o-1)*4+3];default:return}},Po.getTotalCodewordsCount=function(o,s){switch(s){case t.L:return r[(o-1)*4+0];case t.M:return r[(o-1)*4+1];case t.Q:return r[(o-1)*4+2];case t.H:return r[(o-1)*4+3];default:return}},Po}var Ii={},xn={},Nd;function zS(){if(Nd)return xn;Nd=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let n=1;for(let o=0;o<255;o++)t[o]=n,e[n]=o,n<<=1,n&256&&(n^=285);for(let o=255;o<512;o++)t[o]=t[o-255]})(),xn.log=function(n){if(n<1)throw new Error("log("+n+")");return e[n]},xn.exp=function(n){return t[n]},xn.mul=function(n,o){return n===0||o===0?0:t[e[n]+e[o]]},xn}var Ld;function VS(){return Ld||(Ld=1,(function(t){const e=zS();t.mul=function(n,o){const s=new Uint8Array(n.length+o.length-1);for(let i=0;i<n.length;i++)for(let a=0;a<o.length;a++)s[i+a]^=e.mul(n[i],o[a]);return s},t.mod=function(n,o){let s=new Uint8Array(n);for(;s.length-o.length>=0;){const i=s[0];for(let c=0;c<o.length;c++)s[c]^=e.mul(o[c],i);let a=0;for(;a<s.length&&s[a]===0;)a++;s=s.slice(a)}return s},t.generateECPolynomial=function(n){let o=new Uint8Array([1]);for(let s=0;s<n;s++)o=t.mul(o,new Uint8Array([1,e.exp(s)]));return o}})(Ii)),Ii}var Ci,Bd;function WS(){if(Bd)return Ci;Bd=1;const t=VS();function e(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(n){this.degree=n,this.genPoly=t.generateECPolynomial(this.degree)},e.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(n.length+this.degree);o.set(n);const s=t.mod(o,this.genPoly),i=this.degree-s.length;if(i>0){const a=new Uint8Array(this.degree);return a.set(s,i),a}return s},Ci=e,Ci}var Ri={},Ti={},Pi={},_d;function op(){return _d||(_d=1,Pi.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),Pi}var at={},Dd;function sp(){if(Dd)return at;Dd=1;const t="[0-9]+",e="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
|
|
3
|
-
]))+`;at.KANJI=new RegExp(r,"g"),at.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),at.BYTE=new RegExp(n,"g"),at.NUMERIC=new RegExp(t,"g"),at.ALPHANUMERIC=new RegExp(e,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+t+"$"),i=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return at.testKanji=function(c){return o.test(c)},at.testNumeric=function(c){return s.test(c)},at.testAlphanumeric=function(c){return i.test(c)},at}var
|
|
4
|
-
Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),n.put(s,13)}},
|
|
5
|
-
Suggested mode is: `+e.toString(A));switch(v===e.KANJI&&!a.isKanjiModeEnabled()&&(v=e.BYTE),v){case e.NUMERIC:return new r(w);case e.ALPHANUMERIC:return new n(w);case e.KANJI:return new s(w);case e.BYTE:return new o(w)}}t.fromArray=function(I){return I.reduce(function(v,A){return typeof A=="string"?v.push(y(A,null)):A.data&&v.push(y(A.data,A.mode)),v},[])},t.fromString=function(I,v){const A=u(I,a.isKanjiModeEnabled()),B=g(A),T=m(B,v),N=c.find_path(T.map,"start","end"),k=[];for(let x=1;x<N.length-1;x++)k.push(T.table[N[x]].node);return t.fromArray(h(k))},t.rawSplit=function(I){return t.fromArray(u(I,a.isKanjiModeEnabled()))}})(
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/passwordBootstrap-DwalkAEW.js","assets/react-XDCjal2T.js","assets/dnd-BCFAPC0L.js","assets/terminal-C7X98Amf.js","assets/App-DzU5e73Z.js","assets/gestureArbiter-CcSl2ujx.js","assets/gestureArbiter-C2J0D0kV.css","assets/referenceLongPress-D_ZVnzDj.js","assets/triangle-alert-CnVIEUVW.js","assets/DagPlayground-Badsbf-8.js","assets/ChangeWalkthroughPanel-CLe_Mm4u.js","assets/sparkles-Dl-H6uxM.js","assets/DiffLab-D_xUbRBZ.js","assets/DiffViewer-DyC8uspo.js","assets/DiffViewer-T3uj2-aP.css","assets/DiffReviewLab-DS0B2tZH.js","assets/DiffReview-CZEYztDY.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as Ya,a as rg,g as Tu}from"./react-XDCjal2T.js";import{b as F,r as ng,R as Ue}from"./dnd-BCFAPC0L.js";import{L as og,l as sg}from"./terminal-C7X98Amf.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))n(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const i of s.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&n(i)}).observe(document,{childList:!0,subtree:!0});function r(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function n(o){if(o.ep)return;o.ep=!0;const s=r(o);fetch(o.href,s)}})();const ig="modulepreload",ag=function(t){return"/"+t},Qc={},Vt=function(e,r,n){let o=Promise.resolve();if(r&&r.length>0){let c=function(l){return Promise.all(l.map(d=>Promise.resolve(d).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),a=i?.nonce||i?.getAttribute("nonce");o=c(r.map(l=>{if(l=ag(l),l in Qc)return;Qc[l]=!0;const d=l.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${u}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":ig,d||(f.as="script"),f.crossOrigin="",f.href=l,a&&f.setAttribute("nonce",a),document.head.appendChild(f),d)return new Promise((h,g)=>{f.addEventListener("load",h),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${l}`)))})}))}function s(i){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=i,window.dispatchEvent(a),!a.defaultPrevented)throw i}return o.then(i=>{for(const a of i||[])a.status==="rejected"&&s(a.reason);return e().catch(s)})};var Gs={exports:{}},dn={};var el;function cg(){if(el)return dn;el=1;var t=Ya(),e=Symbol.for("react.element"),r=Symbol.for("react.fragment"),n=Object.prototype.hasOwnProperty,o=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function i(a,c,l){var d,u={},f=null,h=null;l!==void 0&&(f=""+l),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(h=c.ref);for(d in c)n.call(c,d)&&!s.hasOwnProperty(d)&&(u[d]=c[d]);if(a&&a.defaultProps)for(d in c=a.defaultProps,c)u[d]===void 0&&(u[d]=c[d]);return{$$typeof:e,type:a,key:f,ref:h,props:u,_owner:o.current}}return dn.Fragment=r,dn.jsx=i,dn.jsxs=i,dn}var tl;function lg(){return tl||(tl=1,Gs.exports=cg()),Gs.exports}var p=lg();const sr="termdock-secure-target-v1",Za="termdock-secure-entry-v1",dg=new Set([sr,Za,"termdock-color-theme","termdock:locale","termdock.federation.connections.v1"]),ho=typeof Storage>"u"?void 0:Storage.prototype.getItem,Xs=typeof Storage>"u"?void 0:Storage.prototype.setItem,rl="termdock-secure-legacy-owner",zn=typeof window<"u"&&window.parent!==window&&location.pathname==="/workspace.html";function ug(){if(typeof window>"u")return null;try{if(zn){const e=new URLSearchParams(location.search).get("termdock-workspace"),r=JSON.parse(localStorage.getItem("termdock.federation.connections.v1")||"[]"),n=Array.isArray(r)?r.find(o=>o?.targetPeerId===e):void 0;return n&&typeof n.url=="string"&&typeof n.targetPeerId=="string"?{...n,serviceName:n.label||n.serviceName}:null}const t=JSON.parse(sessionStorage.getItem(sr)??localStorage.getItem(sr)??"null");return t&&typeof t.url=="string"&&typeof t.targetPeerId=="string"?t:null}catch{return null}}let Es=ug();const _r=Es?.targetPeerId??"unpaired";function Dr(){return Es}function Pu(t){if(Es=t,zn)return;const e=JSON.stringify(t);sessionStorage.setItem(sr,e),localStorage.setItem(sr,e)}function fg(){Es=null,!zn&&(localStorage.removeItem(sr),sessionStorage.removeItem(sr),localStorage.removeItem(Za))}function On(t,e=_r){return dg.has(t)||t.startsWith("termdock-secure-")?t:`termdock-service:${e}:${t}`}function hg(t){if(!(!ho||!Xs))try{if(ho.call(localStorage,rl))return;Xs.call(localStorage,rl,t);for(const r of[localStorage,sessionStorage]){const n=Array.from({length:r.length},(o,s)=>r.key(s)).filter(o=>!!o);for(const o of n){if(o.startsWith("termdock-service:")||On(o,t)===o)continue;const s=On(o,t),i=ho.call(r,o);i!==null&&ho.call(r,s)===null&&Xs.call(r,s,i)}}}catch{}}let nl=!1;function pg(){if(nl||typeof Storage>"u")return;nl=!0;const t=Storage.prototype.getItem,e=Storage.prototype.setItem,r=Storage.prototype.removeItem;Storage.prototype.getItem=function(n){return t.call(this,On(String(n)))},Storage.prototype.setItem=function(n,o){e.call(this,On(String(n)),o)},Storage.prototype.removeItem=function(n){r.call(this,On(String(n)))}}pg();const ol={pending:0,failed:1,expired:1,delivered:2,read:3},po=32768,Vo="remote:";function Ye(t,e){return e.startsWith(Vo)?e:`${Vo}${encodeURIComponent(t)}:${encodeURIComponent(e)}`}function qe(t){if(!t.startsWith(Vo))return null;const e=t.slice(Vo.length).split(":");if(e.length!==2)return null;try{return{origin:decodeURIComponent(e[0]),id:decodeURIComponent(e[1])}}catch{return null}}function Ys(t,e){const r=qe(e);return r?.origin===t?r.id:e}function go(t,e){return{...t,fromSessionId:t.fromSessionId?e(t.fromSessionId):null,toSessionId:e(t.toSessionId)}}function Zs(t,e){if(!t)return;const r=Object.fromEntries(Object.entries(t).map(([n,o])=>[e(n),o]));return Object.keys(r).length?r:void 0}class gg{constructor(e){this.services=e}services;snapshots=new Map;reachable=new Set;groups=new Map;messages=new Map;sessions=new Map;diagnostics=new Map;serviceErrors=new Map;inFlight=null;catalogInFlight=null;async refresh(){return this.inFlight?this.inFlight:(this.inFlight=this.synchronize().finally(()=>{this.inFlight=null}),this.inFlight)}async refreshCatalog(){return this.catalogInFlight?this.catalogInFlight:(this.catalogInFlight=this.discover().finally(()=>{this.catalogInFlight=null}),this.catalogInFlight)}async discover(){const e=this.services();this.serviceErrors.clear();const r=await Promise.all(e.map(async n=>{try{const o=await n.request("/collaboration-federation");if(!Array.isArray(o.groups)||!Array.isArray(o.sessions)||!Array.isArray(o.messages))throw new Error("协作目录响应无效,请更新服务");return{service:n,data:o}}catch(o){return this.serviceErrors.set(n.origin,o instanceof Error?o.message.slice(0,300):"协作目录请求失败"),null}}));this.reachable.clear();for(const n of r){if(!n)continue;const{service:o,data:s}=n;for(const[i,a]of Object.entries(s.transportDiagnostics??{}))(!this.diagnostics.has(i)||a.checked_at>this.diagnostics.get(i).checked_at)&&this.diagnostics.set(i,a);this.reachable.add(o.origin),this.snapshots.set(o.origin,s);for(const i of s.groups){const a={...i,sessionIds:i.sessionIds.map(l=>Ye(o.origin,l)),roles:Zs(i.roles,l=>Ye(o.origin,l))},c=this.groups.get(i.id);(!c||a.updatedAt>c.updatedAt)&&this.groups.set(i.id,a)}for(const i of s.messages)this.mergeMessage(go(i,a=>Ye(o.origin,a)))}this.sessions.clear();for(const n of this.groups.values())for(const o of n.remoteSessions??[])this.sessions.set(o.sessionId,{...o,serviceConnected:!1,status:"offline",serviceCheckedAt:Date.now()});for(const[n,o]of this.snapshots){const s=this.reachable.has(n);for(const i of o.sessions){const a=Ye(n,i.sessionId);this.sessions.set(a,{...i,sessionId:a,serviceOrigin:n,serviceLabel:e.find(c=>c.origin===n)?.label??n,serviceConnected:s,serviceCheckedAt:Date.now(),status:s?i.status:"offline"})}}}async synchronize(){await this.refreshCatalog();const e=this.services();for(const r of this.messages.values()){const n=qe(r.toSessionId)?.origin;if(r.status==="pending"&&n&&!this.reachable.has(n)){const o=this.diagnostics.get(r.id);this.diagnostics.set(r.id,{...o,relay_online:!0,peer_reachable:!1,attempt_count:o?.attempt_count??0,next_retry_at:Date.now()+2e3,last_error:"PEER_UNREACHABLE",checked_at:Date.now()})}}await Promise.all(e.filter(r=>this.reachable.has(r.origin)).map(async r=>{for(const n of this.groups.values())if(!(!this.snapshots.get(r.origin)?.groups.some(s=>s.id===n.id)&&!n.sessionIds.some(s=>qe(s)?.origin===r.origin)))try{await this.push(r,n)}catch{this.reachable.delete(r.origin)}})),await Promise.all(e.filter(r=>this.reachable.has(r.origin)).map(async r=>{if(!((this.snapshots.get(r.origin)?.protocolVersion??1)<2))for(const n of this.groups.values()){if(n.deleted||!n.sessionIds.some(s=>qe(s)?.origin===r.origin))continue;const o=[...this.diagnostics].filter(([s])=>this.messages.get(s)?.groupId===n.id).map(([s,i])=>({message_id:s,diagnostic:i,...this.messages.get(s)?.status==="failed"?{failure_reason:this.messages.get(s)?.failureReason}:{}}));if(o.length)try{await r.request("/collaboration-federation","POST",{group:this.groupForService(n,r.origin),messages:[],transport:o})}catch{}}}))}mergeMessage(e){const r=this.messages.get(e.id),n=ol;if((!r||n[e.status]>n[r.status])&&this.messages.set(e.id,e),this.messages.size>2e3){const o=[...this.messages.values()].find(s=>s.status!=="pending"&&s.status!=="failed");o&&this.messages.delete(o.id)}}groupForService(e,r){const n=e.sessionIds.filter(o=>qe(o)?.origin!==r).map(o=>{const s=qe(o),i=this.sessions.get(o);return{sessionId:o,name:i?.name??s.id,cwd:i?.cwd??"",status:i?.status??"offline",capability:i?.capability??"",currentTask:i?.currentTask??"",updatedAt:i?.updatedAt??0,agent:i?.agent??null,backendSessionId:null,agentNativeSessionId:null,serviceOrigin:s.origin,serviceLabel:i?.serviceLabel??s.origin,serviceConnected:this.reachable.has(s.origin),serviceCheckedAt:Date.now()}});return{...e,sessionIds:e.sessionIds.map(o=>Ys(r,o)),remoteSessions:n,roles:Zs(e.roles,o=>Ys(r,o))}}async push(e,r){const n=ol,o=new Map((this.snapshots.get(e.origin)?.messages??[]).map(i=>[i.id,i])),s=[...this.messages.values()].filter(i=>i.groupId===r.id&&(!o.has(i.id)||n[i.status]>n[o.get(i.id).status])).map(i=>go(i,a=>Ys(e.origin,a)));if(!s.length){await e.request("/collaboration-federation","POST",{group:this.groupForService(r,e.origin),messages:[]});return}for(const i of s){const a=this.messages.get(i.id),c=qe(a.toSessionId)?.origin===e.origin,l=this.diagnostics.get(i.id);if(c&&l?.next_retry_at&&l.next_retry_at>Date.now()&&l.last_error!=="PEER_UNREACHABLE")continue;const d={relay_online:!0,peer_reachable:!0,attempt_count:(l?.attempt_count??0)+(c?1:0),next_retry_at:null,last_error:null,checked_at:Date.now(),fragments_sent:0,fragments_total:0},u=this.snapshots.get(e.origin)?.protocolVersion??1;if(u<2&&(String(i.content??"").length>2e4||i.responseKind||i.task||i.metadata||i.expiresAt||i.status==="failed"||i.status==="expired")){c&&(this.messages.set(i.id,{...a,status:"failed",failureReason:"PEER_UPGRADE_REQUIRED"}),this.diagnostics.set(i.id,{...d,last_error:"PEER_UPGRADE_REQUIRED"}));continue}try{const f=new TextEncoder().encode(JSON.stringify(i));if(u>=2&&f.length>po&&!o.has(i.id)){const h=Math.ceil(f.length/po),g=Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",f)),m=>m.toString(16).padStart(2,"0")).join("");d.fragments_total=h;for(let m=0;m<h;m++){const y=await e.request("/collaboration-federation","POST",{group:this.groupForService(r,e.origin),messages:[],fragments:[{message_id:i.id,group_id:r.id,index:m,total:h,sha256:g,data:btoa(String.fromCharCode(...f.subarray(m*po,(m+1)*po)))}]}),w=y.fragmentReceipts?.find(I=>I.message_id===i.id);if(!w||m===h-1&&!w.complete)throw new Error("FRAGMENT_ACK_MISSING");d.fragments_sent=w.received;for(const I of y.messages??[])this.mergeMessage(go(I,v=>Ye(e.origin,v)));if(c){this.diagnostics.set(i.id,{...d,checked_at:Date.now()});const I=this.services().find(v=>v.origin===qe(a.fromSessionId??"")?.origin);I&&I.origin!==e.origin&&(this.snapshots.get(I.origin)?.protocolVersion??1)>=2&&await I.request("/collaboration-federation","POST",{group:this.groupForService(r,I.origin),messages:[],transport:[{message_id:i.id,diagnostic:d}]}).catch(()=>{})}}}else{const h=await e.request("/collaboration-federation","POST",{group:this.groupForService(r,e.origin),messages:[i]});if(!(h.messages??[]).some(g=>g.id===i.id))throw new Error("PEER_REJECTED_MESSAGE");for(const g of h.messages??[])this.mergeMessage(go(g,m=>Ye(e.origin,m)))}c&&this.diagnostics.set(i.id,{...d,checked_at:Date.now()})}catch(f){c&&this.diagnostics.set(i.id,{...d,checked_at:Date.now(),peer_reachable:null,last_error:f instanceof Error?f.message.slice(0,300):"RELAY_REQUEST_FAILED",next_retry_at:Date.now()+Math.min(3e4,1e3*2**Math.min(d.attempt_count,5))})}}}async peers(e){if(!this.services().some(r=>r.origin===e))throw new Error("当前服务未连接");return await this.refreshCatalog(),{protocolVersion:2,origin:e,sessions:[...this.sessions.values()].filter(r=>qe(r.sessionId)?.origin!==e),services:[...this.snapshots.keys(),...this.services().map(r=>r.origin)].filter((r,n,o)=>o.indexOf(r)===n).map(r=>({origin:r,label:this.services().find(n=>n.origin===r)?.label??r,connected:this.reachable.has(r),error:this.serviceErrors.get(r)}))}}async list(e){const r=this.services().find(s=>s.origin===e);if(!r)throw new Error("当前服务未连接");const[n,o]=await Promise.all([this.peers(e),r.request("/collaboration-groups")]);return{groups:o.groups,sessions:[...n.sessions,...o.sessions]}}async save(e,r){await this.refreshCatalog();const n=this.services().find(u=>u.origin===e);if(!n)throw new Error("当前服务未连接");const o=await n.request("/collaboration-groups"),s=r.id?o.groups.find(u=>u.id===r.id):void 0;if(r.id&&!s)throw new Error("协作组已删除,请刷新列表");if(s&&r.expectedUpdatedAt!==void 0&&r.expectedUpdatedAt!==s.updatedAt)throw new Error("协作组已被修改,请重新打开成员管理后再保存");for(const u of this.sessions.keys())qe(u)?.origin===e&&this.sessions.delete(u);for(const u of o.sessions){const f=Ye(e,u.sessionId);this.sessions.set(f,{...u,sessionId:f,serviceOrigin:e,serviceLabel:n.label,serviceConnected:!0})}if(!r.id?.startsWith("cross-")&&!r.sessionIds.some(u=>qe(u)))return n.request("/collaboration-groups","POST",r);if(!this.reachable.has(e))throw new Error("当前服务需要升级 Termdock 后才能跨服务组队");const i=[...new Set(r.sessionIds.map(u=>Ye(e,u)))],a=new Set(s?.sessionIds.map(u=>Ye(e,u))??[]);if(!r.name?.trim()||i.length<2||i.some(u=>!a.has(u)&&(!this.sessions.has(u)||!this.reachable.has(qe(u).origin))))throw new Error("所选成员已变化或服务不可达,请刷新后重新选择;尚未保存任何修改");const c=s?.federated?{...s,sessionIds:s.sessionIds.map(u=>Ye(e,u))}:void 0,l=Zs(s?.roles,u=>Ye(e,u)),d={id:c?.id??`cross-${crypto.randomUUID()}`,name:r.name.trim(),sessionIds:i,...l?{roles:Object.fromEntries(Object.entries(l).filter(([u])=>i.includes(u)))}:{},createdAt:c?.createdAt??Date.now(),updatedAt:Math.max(Date.now(),(c?.updatedAt??0)+1),federated:!0};if(s&&!s.federated){if(o.capabilities?.groupPromotion!==1)throw new Error("当前服务需要升级后才能将已有组转换为跨服务组;原组和记录均未修改");const u=await n.request(`/collaboration-groups/${encodeURIComponent(s.id)}/promote`,"POST",{group:this.groupForService(d,e),expectedUpdatedAt:r.expectedUpdatedAt??s.updatedAt});d.updatedAt=u.group.updatedAt,d.createdAt=u.group.createdAt}else await n.request("/collaboration-federation","POST",{group:this.groupForService(d,e),messages:[],...c?{expectedUpdatedAt:r.expectedUpdatedAt??c.updatedAt}:{}});return this.groups.set(d.id,d),{group:this.groupForService(d,e)}}async remove(e,r){const n=this.services().find(o=>o.origin===e);if(!n)throw new Error("当前服务未连接");await n.request(`/collaboration-groups/${encodeURIComponent(r)}`,"DELETE")}}const As="termdock.federation.connections.v1",ta="termdock:services-changed",Ja="termdock-secure-removed-services",Wo=t=>[t.id,t.targetPeerId,t.serviceOrigin||t.url].filter(e=>!!e);function Qa(){try{const t=JSON.parse(localStorage.getItem(Ja)||"[]");return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}catch{return[]}}function Be(t){const e=t.trim();if(!e)throw new Error("请输入服务地址。");const r=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(e)?e:`https://${e}`);r.protocol==="wss:"&&(r.protocol="https:"),r.protocol==="ws:"&&(r.protocol="http:");const n=["localhost","127.0.0.1","[::1]"].includes(r.hostname);if(!["https:","http:"].includes(r.protocol)||r.protocol==="http:"&&!n)throw new Error("请使用 HTTPS 服务地址。");if(r.username||r.password||r.search||r.hash||!["/","/api/federation/secure"].includes(r.pathname))throw new Error("请输入服务首页地址,不要包含账号或额外参数。");return r.origin}function ks(t){if(!t||typeof t!="object")return;const e=t;if(typeof e.url=="string")try{const r=Be(e.url),n=typeof e.targetPeerId=="string"&&e.targetPeerId?e.targetPeerId:void 0,o=(typeof e.label=="string"?e.label:typeof e.serviceName=="string"?e.serviceName:"").trim().slice(0,120)||new URL(r).host;return{id:typeof e.id=="string"&&e.id?e.id:n||r,url:r,label:o,...n?{targetPeerId:n}:{},...typeof e.serviceOrigin=="string"?{serviceOrigin:Be(e.serviceOrigin)}:{},...typeof e.entryServiceId=="string"&&e.entryServiceId?{entryServiceId:e.entryServiceId}:{},...Array.isArray(e.routes)?{routes:e.routes.slice(0,4).flatMap(s=>{try{return s&&typeof s.targetPeerId=="string"&&s.targetPeerId?[{url:Be(s.url),targetPeerId:s.targetPeerId}]:[]}catch{return[]}})}:{}}}catch{return}}function wt(t,e){return t.targetPeerId&&e.targetPeerId?t.targetPeerId===e.targetPeerId:(t.serviceOrigin||t.url)===(e.serviceOrigin||e.url)}function Nu(t){const e=[];for(const r of t){const n=e.findIndex(o=>wt(o,r));n<0?e.push(r):e[n]={...e[n],...r,id:e[n].id}}return e}function eo(){return typeof window>"u"?void 0:window.termdockDesktop}function Kt(){try{const t=JSON.parse(localStorage.getItem(As)||"[]");return Array.isArray(t)?Nu(t.map(ks).filter(e=>!!e)):[]}catch{return[]}}function Lu(t){localStorage.setItem(As,JSON.stringify(t.map(e=>({...e,serviceName:e.label})))),window.dispatchEvent(new Event(ta))}let un;async function We(){const t=eo();if(!t?.serviceConnections||!t.saveServiceConnection)return Kt();if(un)return un;un=(async()=>{let e=await t.serviceConnections();const r=Kt();for(const n of r)e.some(o=>wt(o,n))||(e=await(t.importServiceConnection||t.saveServiceConnection)(n));return r.length&&localStorage.removeItem(As),e})();try{return await un}finally{un=void 0}}async function Et(t){const e=ks(t);if(!e)throw new Error("服务地址无效。");const r=eo();if(r?.saveServiceConnection)return r.saveServiceConnection(e);const n=Kt(),o=n.find(a=>a.id===e.id||wt(a,e)),s=new Set([...Wo(e),...o?Wo(o):[]]);localStorage.setItem(Ja,JSON.stringify(Qa().filter(a=>!s.has(a))));const i=Nu([...n.filter(a=>a!==o),{...o,...e,id:o?.id||e.id}]);return Lu(i),i}async function mg(t){const e=ks(t);if(!e)throw new Error("服务地址无效。");const r=eo();if(r?.importServiceConnection)return r.importServiceConnection(e);if(r?.serviceConnections){const n=await r.serviceConnections();return n.some(o=>wt(o,e))?Et(e):n}return Wo(e).some(n=>Qa().includes(n))?Kt():Et(e)}async function wg(t){const e=eo();if(e?.removeServiceConnection)return e.removeServiceConnection(t);const r=Kt(),n=r.find(s=>s.id===t);n&&localStorage.setItem(Ja,JSON.stringify([...new Set([...Qa(),...Wo(n)])].slice(-768)));const o=r.filter(s=>s.id!==t);return Lu(o),o}function Bu(t){const e=n=>{(n.key===As||n.key===null)&&t()};window.addEventListener(ta,t),window.addEventListener("storage",e);const r=eo()?.onServiceConnections?.(t);return()=>{window.removeEventListener(ta,t),window.removeEventListener("storage",e),r?.()}}class yg extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}let bg=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},tt=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};class _u extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class Du extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}}class vg extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class xg extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class Is extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}const Ou=Symbol.for("@libp2p/peer-id");function Sg(t){return typeof t?.handleEvent=="function"}function Eg(t){return t===!0||t===!1}function Ag(t){return Eg(t)?t:t?.capture??!1}function ra(t){const e={capture:Ag(t),once:!!t?.once};return t?.passive!=null&&(e.passive=t?.passive),t?.signal!=null&&(e.signal=t?.signal),e}function sl(t,e){return ra(t).capture===ra(e).capture}class kg extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){const o=ra(n);if(o?.signal?.aborted===!0)return;const s=l=>{o.once&&this.removeEventListener(e,r,o),Sg(r)?r.handleEvent(l):r(l)};let i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(l=>l.callback!==r?!1:sl(l.options,o)))return;super.addEventListener(e,s,o);const c=()=>{this.removeEventListener(e,r,o)};o.signal?.addEventListener("abort",c),i.push({callback:r,wrapper:s,options:o,onAbort:c})}removeEventListener(e,r,n){const o=this.#e.get(e);if(o==null){super.removeEventListener(e,r??null,n);return}this.#e.set(e,o.filter(s=>s.callback===r&&sl(s.options,n)?(super.removeEventListener(e,s.wrapper,n),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}}const Ig=Symbol.for("@libp2p/service-capabilities");function Cg(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function Cs(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function Rg(t){return new TextEncoder().encode(t)}function Tg(t){return new TextDecoder().decode(t)}function Pg(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var m=0,y=0,w=0,I=g.length;w!==I&&g[w]===0;)w++,m++;for(var v=(I-w)*d+1>>>0,A=new Uint8Array(v);w!==I;){for(var B=g[w],T=0,N=v-1;(B!==0||T<y)&&N!==-1;N--,T++)B+=256*A[N]>>>0,A[N]=B%a>>>0,B=B/a>>>0;if(B!==0)throw new Error("Non-zero carry");y=T,w++}for(var k=v-y;k!==v&&A[k]===0;)k++;for(var x=c.repeat(m);k<v;++k)x+=t.charAt(A[k]);return x}function f(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var m=0;if(g[m]!==" "){for(var y=0,w=0;g[m]===c;)y++,m++;for(var I=(g.length-m)*l+1>>>0,v=new Uint8Array(I);g[m];){var A=r[g.charCodeAt(m)];if(A===255)return;for(var B=0,T=I-1;(A!==0||B<w)&&T!==-1;T--,B++)A+=a*v[T]>>>0,v[T]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");w=B,m++}if(g[m]!==" "){for(var N=I-w;N!==I&&v[N]===0;)N++;for(var k=new Uint8Array(y+(I-N)),x=y;N!==I;)k[x++]=v[N++];return k}}}function h(g){var m=f(g);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:h}}var Ng=Pg,Lg=Ng;class Bg{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class _g{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;const o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Fu(this,e)}}class Dg{decoders;constructor(e){this.decoders=e}or(e){return Fu(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function Fu(t,e){return new Dg({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class Og{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Bg(e,r,n),this.decoder=new _g(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function Rs({name:t,prefix:e,encode:r,decode:n}){return new Og(t,e,r,n)}function to({name:t,prefix:e,alphabet:r}){const{encode:n,decode:o}=Lg(r,t);return Rs({prefix:e,name:t,encode:n,decode:s=>Cs(o(s))})}function Fg(t,e,r,n){let o=t.length;for(;t[o-1]==="=";)--o;const s=new Uint8Array(o*r/8|0);let i=0,a=0,c=0;for(let l=0;l<o;++l){const d=e[t[l]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|d,i+=r,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Mg(t,e,r){const n=e[e.length-1]==="=",o=(1<<r)-1;let s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function jg(t){const e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function Ae({name:t,prefix:e,bitsPerChar:r,alphabet:n}){const o=jg(n);return Rs({prefix:e,name:t,encode(s){return Mg(s,n,r)},decode(s){return Fg(s,o,r,t)}})}const Le=to({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ug=to({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),$g=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Le,base58flickr:Ug},Symbol.toStringTag,{value:"Module"})),Fn=Ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Hg=Ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),qg=Ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Kg=Ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),zg=Ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Vg=Ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Wg=Ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Gg=Ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Xg=Ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Yg=Object.freeze(Object.defineProperty({__proto__:null,base32:Fn,base32hex:zg,base32hexpad:Wg,base32hexpadupper:Gg,base32hexupper:Vg,base32pad:qg,base32padupper:Kg,base32upper:Hg,base32z:Xg},Symbol.toStringTag,{value:"Module"})),Mo=to({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Zg=to({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Jg=Object.freeze(Object.defineProperty({__proto__:null,base36:Mo,base36upper:Zg},Symbol.toStringTag,{value:"Module"}));var Qg=Mu,il=128,em=-128,tm=Math.pow(2,31);function Mu(t,e,r){e=e||[],r=r||0;for(var n=r;t>=tm;)e[r++]=t&255|il,t/=128;for(;t&em;)e[r++]=t&255|il,t>>>=7;return e[r]=t|0,Mu.bytes=r-n+1,e}var rm=na,nm=128,al=127;function na(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw na.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&al)<<o:(i&al)*Math.pow(2,o),o+=7}while(i>=nm);return na.bytes=s-n,r}var om=Math.pow(2,7),sm=Math.pow(2,14),im=Math.pow(2,21),am=Math.pow(2,28),cm=Math.pow(2,35),lm=Math.pow(2,42),dm=Math.pow(2,49),um=Math.pow(2,56),fm=Math.pow(2,63),hm=function(t){return t<om?1:t<sm?2:t<im?3:t<am?4:t<cm?5:t<lm?6:t<dm?7:t<um?8:t<fm?9:10},pm={encode:Qg,decode:rm,encodingLength:hm},Go=pm;function oa(t,e=0){return[Go.decode(t,e),Go.decode.bytes]}function Xo(t,e,r=0){return Go.encode(t,e,r),e}function Yo(t){return Go.encodingLength(t)}function ro(t,e){const r=e.byteLength,n=Yo(t),o=n+Yo(r),s=new Uint8Array(o+r);return Xo(t,s,0),Xo(r,s,n),s.set(e,o),new ec(t,r,e,s)}function ju(t){const e=Cs(t),[r,n]=oa(e),[o,s]=oa(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new ec(r,o,i,e)}function gm(t,e){if(t===e)return!0;{const r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Cg(t.bytes,r.bytes)}}class ec{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}}function cl(t,e){const{bytes:r,version:n}=t;return n===0?wm(r,sa(t),e??Le.encoder):ym(r,sa(t),e??Fn.encoder)}const ll=new WeakMap;function sa(t){const e=ll.get(t);if(e==null){const r=new Map;return ll.set(t,r),r}return e}class ce{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:e,multihash:r}=this;if(e!==fn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==bm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ce.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:e,digest:r}=this.multihash,n=ro(e,r);return ce.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return ce.equals(this,e)}static equals(e,r){const n=r;return n!=null&&e.code===n.code&&e.version===n.version&&gm(e.multihash,n.multihash)}toString(e){return cl(this,e)}toJSON(){return{"/":cl(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;const r=e;if(r instanceof ce)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){const{version:n,code:o,multihash:s,bytes:i}=r;return new ce(n,o,s,i??dl(n,o,s.bytes))}else if(r[vm]===!0){const{version:n,multihash:o,code:s}=r,i=ju(o);return ce.create(n,s,i)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==fn)throw new Error(`Version 0 CID must use dag-pb (code: ${fn}) block encoding`);return new ce(e,r,n,n.bytes)}case 1:{const o=dl(e,r,n.bytes);return new ce(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return ce.create(0,fn,e)}static createV1(e,r){return ce.create(1,e,r)}static decode(e){const[r,n]=ce.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){const r=ce.inspectBytes(e),n=r.size-r.multihashSize,o=Cs(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");const s=o.subarray(r.multihashSize-r.digestSize),i=new ec(r.multihashCode,r.digestSize,s,o);return[r.version===0?ce.createV0(i):ce.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0;const n=()=>{const[u,f]=oa(e.subarray(r));return r+=f,u};let o=n(),s=fn;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);const i=r,a=n(),c=n(),l=r+c,d=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:l}}static parse(e,r){const[n,o]=mm(e,r),s=ce.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return sa(s).set(n,e),s}}function mm(t,e){switch(t[0]){case"Q":{const r=e??Le;return[Le.prefix,r.decode(`${Le.prefix}${t}`)]}case Le.prefix:{const r=e??Le;return[Le.prefix,r.decode(t)]}case Fn.prefix:{const r=e??Fn;return[Fn.prefix,r.decode(t)]}case Mo.prefix:{const r=e??Mo;return[Mo.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function wm(t,e,r){const{prefix:n}=r;if(n!==Le.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const o=e.get(n);if(o==null){const s=r.encode(t).slice(1);return e.set(n,s),s}else return o}function ym(t,e,r){const{prefix:n}=r,o=e.get(n);if(o==null){const s=r.encode(t);return e.set(n,s),s}else return o}const fn=112,bm=18;function dl(t,e,r){const n=Yo(t),o=n+Yo(e),s=new Uint8Array(o+r.byteLength);return Xo(t,s,0),Xo(e,s,n),s.set(r,o),s}const vm=Symbol.for("@ipld/js-cid/CID"),Uu=0,xm="identity",$u=Cs;function Sm(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return ro(Uu,$u(t))}const no={code:Uu,name:xm,encode:$u,digest:Sm};function rt(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function _e(t=0){return new Uint8Array(t)}function At(t=0){return new Uint8Array(t)}function ia(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));const r=At(e);let n=0;for(const o of t)r.set(o,n),n+=o.length;return r}const Hu=Symbol.for("@achingbrain/uint8arraylist");function ul(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(const n of t){const o=r+n.byteLength;if(e<o)return{buf:n,index:e-r};r=o}throw new RangeError("index is out of bounds")}function mo(t){return!!t?.[Hu]}class re{bufs;length;[Hu]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let r=0;for(const n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(mo(n)){r+=n.byteLength;for(const o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...e){this.prependAll(e)}prependAll(e){let r=0;for(const n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(mo(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(e){const r=ul(this.bufs,e);return r.buf[r.index]}set(e,r){const n=ul(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(mo(e))for(let n=0;n<e.length;n++)this.set(r+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,r){const{bufs:n,length:o}=this._subList(e,r);return ia(n,o)}subarray(e,r){const{bufs:n,length:o}=this._subList(e,r);return n.length===1?n[0]:ia(n,o)}sublist(e,r){const{bufs:n,length:o}=this._subList(e,r),s=new re;return s.length=o,s.bufs=n,s}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};const n=[];let o=0;for(let s=0;s<this.bufs.length;s++){const i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;const l=e>=a&&e<c,d=r>a&&r<=c;if(l&&d){if(e===a&&r===c){n.push(i);break}const u=e-a;n.push(i.subarray(u,u+(r-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(d){if(r===c){n.push(i);break}n.push(i.subarray(0,r-a));break}n.push(i)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!mo(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const n=e instanceof Uint8Array?e:e.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.length===0)return r>this.length?this.length:r;const o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");const s=256,i=new Int32Array(s);for(let u=0;u<s;u++)i[u]=-1;for(let u=0;u<o;u++)i[n[u]]=u;const a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1;let d;for(let u=r;u<=c;u+=d){d=0;for(let f=l;f>=0;f--){const h=this.get(u+f);if(n[f]!==h){d=Math.max(1,f-a[h]);break}}if(d===0)return u}return-1}getInt8(e){const r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){const n=At(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){const n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){const o=_e(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,e)}getInt32(e,r){const n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){const o=_e(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,e)}getBigInt64(e,r){const n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){const o=_e(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,e)}getUint8(e){const r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){const n=At(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){const n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){const o=_e(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,e)}getUint32(e,r){const n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){const o=_e(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,e)}getBigUint64(e,r){const n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){const o=_e(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,e)}getFloat32(e,r){const n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){const o=_e(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,e)}getFloat64(e,r){const n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){const o=_e(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof re)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!rt(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){const n=new re;return n.bufs=e,r==null&&(r=e.reduce((o,s)=>o+s.byteLength,0)),n.length=r,n}}const Em=to({prefix:"9",name:"base10",alphabet:"0123456789"}),Am=Object.freeze(Object.defineProperty({__proto__:null,base10:Em},Symbol.toStringTag,{value:"Module"})),km=Ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Im=Ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Cm=Object.freeze(Object.defineProperty({__proto__:null,base16:km,base16upper:Im},Symbol.toStringTag,{value:"Module"})),Rm=Ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Tm=Object.freeze(Object.defineProperty({__proto__:null,base2:Rm},Symbol.toStringTag,{value:"Module"})),qu=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Pm=qu.reduce((t,e,r)=>(t[r]=e,t),[]),Nm=qu.reduce((t,e,r)=>{const n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function Lm(t){return t.reduce((e,r)=>(e+=Pm[r],e),"")}function Bm(t){const e=[];for(const r of t){const n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);const o=Nm[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}const _m=Rs({prefix:"🚀",name:"base256emoji",encode:Lm,decode:Bm}),Dm=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:_m},Symbol.toStringTag,{value:"Module"})),Om=Ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Fm=Ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Mm=Ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),jm=Ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Um=Object.freeze(Object.defineProperty({__proto__:null,base64:Om,base64pad:Fm,base64url:Mm,base64urlpad:jm},Symbol.toStringTag,{value:"Module"})),$m=Ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Hm=Object.freeze(Object.defineProperty({__proto__:null,base8:$m},Symbol.toStringTag,{value:"Module"})),qm=Rs({prefix:"\0",name:"identity",encode:t=>Tg(t),decode:t=>Rg(t)}),Km=Object.freeze(Object.defineProperty({__proto__:null,identity:qm},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const zm=20;function Vm({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new Wm(t,e,r,n,o)}class Wm{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??zm,this.maxDigestLength=s}digest(e,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?fl(n,this.code,r?.truncate):n.then(o=>fl(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}}function fl(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return ro(e,t)}function Gm(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}const tc=Vm({name:"sha2-256",code:18,encode:Gm("SHA-256")}),hl={...Km,...Tm,...Hm,...Am,...Cm,...Yg,...Jg,...$g,...Um,...Dm};function Ku(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const pl=Ku("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Js=Ku("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=At(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),zu={utf8:pl,"utf-8":pl,hex:hl.base16,latin1:Js,ascii:Js,binary:Js,...hl};function we(t,e="utf8"){const r=zu[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function J(t,e="utf8"){const r=zu[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}const Xm=parseInt("11111",2),aa=parseInt("10000000",2),Ym=parseInt("01111111",2),gl={0:hn,1:hn,2:Zm,3:ew,4:tw,5:Qm,6:Jm,16:hn,22:hn,48:hn};function nn(t,e={offset:0}){const r=t[e.offset]&Xm;if(e.offset++,gl[r]!=null)return gl[r](t,e);throw new Error("No decoder for tag "+r)}function oo(t,e){let r=0;if((t[e.offset]&aa)===aa){const n=t[e.offset]&Ym;let o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=t[e.offset].toString(16).padStart(2,"0");r=parseInt(o,16)}else r=t[e.offset],e.offset++;return r}function hn(t,e){oo(t,e);const r=[];for(;!(e.offset>=t.byteLength);){const n=nn(t,e);if(n===null)break;r.push(n)}return r}function Zm(t,e){const r=oo(t,e),n=e.offset,o=e.offset+r,s=[];for(let i=n;i<o;i++)i===n&&t[i]===0||s.push(t[i]);return e.offset+=r,Uint8Array.from(s)}function Jm(t,e){const r=oo(t,e),n=e.offset+r,o=t[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){const l=t[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let d=0;for(let u=0;u<c.length;u++)d+=c[u]<<u*7;a+=`.${d}`,c=[]}}return a}function Qm(t,e){return e.offset++,null}function ew(t,e){const r=oo(t,e),n=t[e.offset];e.offset++;const o=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function tw(t,e){const r=oo(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function rw(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);const r=new re;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function Ts(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);const e=rw(t.byteLength);return new re(Uint8Array.from([e.byteLength|aa]),e)}function je(t){const e=new re,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new re(Uint8Array.from([2]),Ts(e),e)}function rc(t){const e=Uint8Array.from([0]),r=new re(e,t);return new re(Uint8Array.from([3]),Ts(r),r)}function nw(t){return new re(Uint8Array.from([4]),Ts(t),t)}function xt(t,e=48){const r=new re;for(const n of t)r.append(n);return new re(Uint8Array.from([e]),Ts(r),r)}async function ow(t,e,r){const n=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["sign"]);r?.signal?.throwIfAborted();const o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function sw(t,e,r,n){const o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();const s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,r.subarray());return n?.signal?.throwIfAborted(),s}const iw=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),aw=Uint8Array.from([6,5,43,129,4,0,34]),cw=Uint8Array.from([6,5,43,129,4,0,35]),Vu={ext:!0,kty:"EC",crv:"P-256"},Wu={ext:!0,kty:"EC",crv:"P-384"},Gu={ext:!0,kty:"EC",crv:"P-521"},Or=32,Fr=48,Mr=66;function lw(t){const e=nn(t);return dw(e)}function dw(t){const e=t[1],r=J(e,"base64url"),n=t[2][1][0],o=1;let s,i;if(e.byteLength===Or)return s=J(n.subarray(o,o+Or),"base64url"),i=J(n.subarray(o+Or),"base64url"),new Qs({...Vu,key_ops:["sign"],d:r,x:s,y:i});if(e.byteLength===Fr)return s=J(n.subarray(o,o+Fr),"base64url"),i=J(n.subarray(o+Fr),"base64url"),new Qs({...Wu,key_ops:["sign"],d:r,x:s,y:i});if(e.byteLength===Mr)return s=J(n.subarray(o,o+Mr),"base64url"),i=J(n.subarray(o+Mr),"base64url"),new Qs({...Gu,key_ops:["sign"],d:r,x:s,y:i});throw new tt(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function Xu(t){const e=nn(t);return uw(e)}function uw(t){const e=t[1][1][0],r=1;let n,o;if(e.byteLength===Or*2+1)return n=J(e.subarray(r,r+Or),"base64url"),o=J(e.subarray(r+Or),"base64url"),new jo({...Vu,key_ops:["verify"],x:n,y:o});if(e.byteLength===Fr*2+1)return n=J(e.subarray(r,r+Fr),"base64url"),o=J(e.subarray(r+Fr),"base64url"),new jo({...Wu,key_ops:["verify"],x:n,y:o});if(e.byteLength===Mr*2+1)return n=J(e.subarray(r,r+Mr),"base64url"),o=J(e.subarray(r+Mr),"base64url"),new jo({...Gu,key_ops:["verify"],x:n,y:o});throw new tt(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function fw(t){return xt([je(Uint8Array.from([1])),nw(we(t.d??"","base64url")),xt([Yu(t.crv)],160),xt([rc(new re(Uint8Array.from([4]),we(t.x??"","base64url"),we(t.y??"","base64url")))],161)]).subarray()}function hw(t){return xt([je(Uint8Array.from([1])),xt([Yu(t.crv)],160),xt([rc(new re(Uint8Array.from([4]),we(t.x??"","base64url"),we(t.y??"","base64url")))],161)]).subarray()}function Yu(t){if(t==="P-256")return iw;if(t==="P-384")return aw;if(t==="P-521")return cw;throw new tt(`Invalid curve ${t}`)}class jo{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=hw(this.jwk)),this._raw}toMultihash(){return no.digest(Ds(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return Le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:rt(this.raw,e.raw)}async verify(e,r,n){return sw(this.jwk,r,e,n)}}class Qs{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new jo({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=fw(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:rt(this.raw,e.raw)}async sign(e,r){return ow(this.jwk,e,r)}}const Ar=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function so(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ca(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function hr(t,...e){if(!so(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Zu(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ca(t.outputLen),ca(t.blockLen)}function Zo(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function pw(t,e){hr(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Xr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function ei(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function st(t,e){return t<<32-e|t>>>e}const Ju=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",gw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function tr(t){if(hr(t),Ju)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=gw[t[r]];return e}const ft={_0:48,_9:57,A:65,F:70,a:97,f:102};function ml(t){if(t>=ft._0&&t<=ft._9)return t-ft._0;if(t>=ft.A&&t<=ft.F)return t-(ft.A-10);if(t>=ft.a&&t<=ft.f)return t-(ft.a-10)}function Jo(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Ju)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){const i=ml(t.charCodeAt(s)),a=ml(t.charCodeAt(s+1));if(i===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function mw(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function nc(t){return typeof t=="string"&&(t=mw(t)),hr(t),t}function ct(...t){let e=0;for(let n=0;n<t.length;n++){const o=t[n];hr(o),e+=o.length}const r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){const s=t[n];r.set(s,o),o+=s.length}return r}class Qu{}function ef(t){const e=n=>t().update(nc(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function oc(t=32){if(Ar&&typeof Ar.getRandomValues=="function")return Ar.getRandomValues(new Uint8Array(t));if(Ar&&typeof Ar.randomBytes=="function")return Uint8Array.from(Ar.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function ww(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,l=n?0:4;t.setUint32(e+c,i,n),t.setUint32(e+l,a,n)}function yw(t,e,r){return t&e^~t&r}function bw(t,e,r){return t&e^t&r^e&r}let tf=class extends Qu{constructor(e,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=ei(this.buffer)}update(e){Zo(this),e=nc(e),hr(e);const{view:r,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){const a=Math.min(o-this.pos,s-i);if(a===o){const c=ei(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Zo(this),pw(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:o,isLE:s}=this;let{pos:i}=this;r[i++]=128,Xr(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let u=i;u<o;u++)r[u]=0;ww(n,o-8,BigInt(this.length*8),s),this.process(n,0);const a=ei(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}};const Pt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ke=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),wo=BigInt(2**32-1),wl=BigInt(32);function vw(t,e=!1){return e?{h:Number(t&wo),l:Number(t>>wl&wo)}:{h:Number(t>>wl&wo)|0,l:Number(t&wo)|0}}function xw(t,e=!1){const r=t.length;let n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){const{h:i,l:a}=vw(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}const yl=(t,e,r)=>t>>>r,bl=(t,e,r)=>t<<32-r|e>>>r,kr=(t,e,r)=>t>>>r|e<<32-r,Ir=(t,e,r)=>t<<32-r|e>>>r,yo=(t,e,r)=>t<<64-r|e>>>r-32,bo=(t,e,r)=>t>>>r-32|e<<64-r;function ht(t,e,r,n){const o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}const Sw=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Ew=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Aw=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),kw=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0,Iw=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0),Cw=(t,e,r,n,o,s)=>e+r+n+o+s+(t/2**32|0)|0,Rw=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Nt=new Uint32Array(64);class Tw extends tf{constructor(e=32){super(64,e,8,!1),this.A=Pt[0]|0,this.B=Pt[1]|0,this.C=Pt[2]|0,this.D=Pt[3]|0,this.E=Pt[4]|0,this.F=Pt[5]|0,this.G=Pt[6]|0,this.H=Pt[7]|0}get(){const{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,r){for(let u=0;u<16;u++,r+=4)Nt[u]=e.getUint32(r,!1);for(let u=16;u<64;u++){const f=Nt[u-15],h=Nt[u-2],g=st(f,7)^st(f,18)^f>>>3,m=st(h,17)^st(h,19)^h>>>10;Nt[u]=m+Nt[u-7]+g+Nt[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=st(a,6)^st(a,11)^st(a,25),h=d+f+yw(a,c,l)+Rw[u]+Nt[u]|0,m=(st(n,2)^st(n,13)^st(n,22))+bw(n,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,l,d)}roundClean(){Xr(Nt)}destroy(){this.set(0,0,0,0,0,0,0,0),Xr(this.buffer)}}const rf=xw(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Pw=rf[0],Nw=rf[1],Lt=new Uint32Array(80),Bt=new Uint32Array(80);class Lw extends tf{constructor(e=64){super(128,e,16,!1),this.Ah=ke[0]|0,this.Al=ke[1]|0,this.Bh=ke[2]|0,this.Bl=ke[3]|0,this.Ch=ke[4]|0,this.Cl=ke[5]|0,this.Dh=ke[6]|0,this.Dl=ke[7]|0,this.Eh=ke[8]|0,this.El=ke[9]|0,this.Fh=ke[10]|0,this.Fl=ke[11]|0,this.Gh=ke[12]|0,this.Gl=ke[13]|0,this.Hh=ke[14]|0,this.Hl=ke[15]|0}get(){const{Ah:e,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:f,Gh:h,Gl:g,Hh:m,Hl:y}=this;return[e,r,n,o,s,i,a,c,l,d,u,f,h,g,m,y]}set(e,r,n,o,s,i,a,c,l,d,u,f,h,g,m,y){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=d|0,this.Fh=u|0,this.Fl=f|0,this.Gh=h|0,this.Gl=g|0,this.Hh=m|0,this.Hl=y|0}process(e,r){for(let v=0;v<16;v++,r+=4)Lt[v]=e.getUint32(r),Bt[v]=e.getUint32(r+=4);for(let v=16;v<80;v++){const A=Lt[v-15]|0,B=Bt[v-15]|0,T=kr(A,B,1)^kr(A,B,8)^yl(A,B,7),N=Ir(A,B,1)^Ir(A,B,8)^bl(A,B,7),k=Lt[v-2]|0,x=Bt[v-2]|0,S=kr(k,x,19)^yo(k,x,61)^yl(k,x,6),R=Ir(k,x,19)^bo(k,x,61)^bl(k,x,6),P=Aw(N,R,Bt[v-7],Bt[v-16]),b=kw(P,T,S,Lt[v-7],Lt[v-16]);Lt[v]=b|0,Bt[v]=P|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:f,Fh:h,Fl:g,Gh:m,Gl:y,Hh:w,Hl:I}=this;for(let v=0;v<80;v++){const A=kr(u,f,14)^kr(u,f,18)^yo(u,f,41),B=Ir(u,f,14)^Ir(u,f,18)^bo(u,f,41),T=u&h^~u&m,N=f&g^~f&y,k=Iw(I,B,N,Nw[v],Bt[v]),x=Cw(k,w,A,T,Pw[v],Lt[v]),S=k|0,R=kr(n,o,28)^yo(n,o,34)^yo(n,o,39),P=Ir(n,o,28)^bo(n,o,34)^bo(n,o,39),b=n&s^n&a^s&a,E=o&i^o&c^i&c;w=m|0,I=y|0,m=h|0,y=g|0,h=u|0,g=f|0,{h:u,l:f}=ht(l|0,d|0,x|0,S|0),l=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;const C=Sw(S,P,E);n=Ew(C,x,R,b),o=C|0}({h:n,l:o}=ht(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ht(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ht(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=ht(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:f}=ht(this.Eh|0,this.El|0,u|0,f|0),{h,l:g}=ht(this.Fh|0,this.Fl|0,h|0,g|0),{h:m,l:y}=ht(this.Gh|0,this.Gl|0,m|0,y|0),{h:w,l:I}=ht(this.Hh|0,this.Hl|0,w|0,I|0),this.set(n,o,s,i,a,c,l,d,u,f,h,g,m,y,w,I)}roundClean(){Xr(Lt,Bt)}destroy(){Xr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const nf=ef(()=>new Tw),Bw=ef(()=>new Lw);const sc=BigInt(0),la=BigInt(1);function ir(t,e=""){if(typeof t!="boolean"){const r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function Qe(t,e,r=""){const n=so(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){const i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function vo(t){const e=t.toString(16);return e.length&1?"0"+e:e}function of(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?sc:BigInt("0x"+t)}function Ps(t){return of(tr(t))}function Vn(t){return hr(t),of(tr(Uint8Array.from(t).reverse()))}function ic(t,e){return Jo(t.toString(16).padStart(e*2,"0"))}function sf(t,e){return ic(t,e).reverse()}function fe(t,e,r){let n;if(typeof e=="string")try{n=Jo(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(so(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const o=n.length;if(typeof r=="number"&&o!==r)throw new Error(t+" of length "+r+" expected, got "+o);return n}function vl(t){return Uint8Array.from(t)}const ti=t=>typeof t=="bigint"&&sc<=t;function _w(t,e,r){return ti(t)&&ti(e)&&ti(r)&&e<=t&&t<r}function da(t,e,r,n){if(!_w(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function af(t){let e;for(e=0;t>sc;t>>=la,e+=1);return e}const io=t=>(la<<BigInt(t))-la;function Dw(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");const n=h=>new Uint8Array(h),o=h=>Uint8Array.of(h);let s=n(t),i=n(t),a=0;const c=()=>{s.fill(1),i.fill(0),a=0},l=(...h)=>r(i,s,...h),d=(h=n(0))=>{i=l(o(0),h),s=l(),h.length!==0&&(i=l(o(1),h),s=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const g=[];for(;h<e;){s=l();const m=s.slice();g.push(m),h+=s.length}return ct(...g)};return(h,g)=>{c(),d(h);let m;for(;!(m=g(u()));)d();return c(),m}}function ao(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(o,s,i){const a=t[o];if(i&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([o,s])=>n(o,s,!1)),Object.entries(r).forEach(([o,s])=>n(o,s,!0))}function Qo(t){const e=new WeakMap;return(r,...n)=>{const o=e.get(r);if(o!==void 0)return o;const s=t(r,...n);return e.set(r,s),s}}const De=BigInt(0),Ee=BigInt(1),Yt=BigInt(2),cf=BigInt(3),lf=BigInt(4),df=BigInt(5),Ow=BigInt(7),uf=BigInt(8),Fw=BigInt(9),ff=BigInt(16);function ye(t,e){const r=t%e;return r>=De?r:e+r}function ue(t,e,r){let n=t;for(;e-- >De;)n*=n,n%=r;return n}function xl(t,e){if(t===De)throw new Error("invert: expected non-zero number");if(e<=De)throw new Error("invert: expected positive modulus, got "+e);let r=ye(t,e),n=e,o=De,s=Ee;for(;r!==De;){const a=n/r,c=n%r,l=o-s*a;n=r,r=c,o=s,s=l}if(n!==Ee)throw new Error("invert: does not exist");return ye(o,e)}function ac(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function hf(t,e){const r=(t.ORDER+Ee)/lf,n=t.pow(e,r);return ac(t,n,e),n}function Mw(t,e){const r=(t.ORDER-df)/uf,n=t.mul(e,Yt),o=t.pow(n,r),s=t.mul(e,o),i=t.mul(t.mul(s,Yt),o),a=t.mul(s,t.sub(i,t.ONE));return ac(t,a,e),a}function jw(t){const e=pr(t),r=pf(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+Ow)/ff;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,n);const u=a.mul(l,o),f=a.mul(l,s),h=a.eql(a.sqr(d),c),g=a.eql(a.sqr(u),c);l=a.cmov(l,d,h),d=a.cmov(f,u,g);const m=a.eql(a.sqr(d),c),y=a.cmov(l,d,m);return ac(a,y,c),y}}function pf(t){if(t<cf)throw new Error("sqrt is not defined for small field");let e=t-Ee,r=0;for(;e%Yt===De;)e/=Yt,r++;let n=Yt;const o=pr(t);for(;Sl(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return hf;let s=o.pow(n,e);const i=(e+Ee)/Yt;return function(c,l){if(c.is0(l))return l;if(Sl(c,l)!==1)throw new Error("Cannot find square root");let d=r,u=c.mul(c.ONE,s),f=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let g=1,m=c.sqr(f);for(;!c.eql(m,c.ONE);)if(g++,m=c.sqr(m),g===d)throw new Error("Cannot find square root");const y=Ee<<BigInt(d-g-1),w=c.pow(u,y);d=g,u=c.sqr(w),f=c.mul(f,u),h=c.mul(h,w)}return h}}function Uw(t){return t%lf===cf?hf:t%uf===df?Mw:t%ff===Fw?jw(t):pf(t)}const $w=(t,e)=>(ye(t,e)&Ee)===Ee,Hw=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function qw(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=Hw.reduce((n,o)=>(n[o]="function",n),e);return ao(t,r),t}function Kw(t,e,r){if(r<De)throw new Error("invalid exponent, negatives unsupported");if(r===De)return t.ONE;if(r===Ee)return e;let n=t.ONE,o=e;for(;r>De;)r&Ee&&(n=t.mul(n,o)),o=t.sqr(o),r>>=Ee;return n}function gf(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),o=e.reduce((i,a,c)=>t.is0(a)?i:(n[c]=i,t.mul(i,a)),t.ONE),s=t.inv(o);return e.reduceRight((i,a,c)=>t.is0(a)?i:(n[c]=t.mul(i,n[c]),t.mul(i,a)),s),n}function Sl(t,e){const r=(t.ORDER-Ee)/Yt,n=t.pow(e,r),o=t.eql(n,t.ONE),s=t.eql(n,t.ZERO),i=t.eql(n,t.neg(t.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function mf(t,e){e!==void 0&&ca(e);const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function pr(t,e,r=!1,n={}){if(t<=De)throw new Error("invalid field: expected ORDER > 0, got "+t);let o,s,i=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const f=e;f.BITS&&(o=f.BITS),f.sqrt&&(s=f.sqrt),typeof f.isLE=="boolean"&&(r=f.isLE),typeof f.modFromBytes=="boolean"&&(i=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(o=e),n.sqrt&&(s=n.sqrt);const{nBitLength:c,nByteLength:l}=mf(t,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:l,MASK:io(c),ZERO:De,ONE:Ee,allowedLengths:a,create:f=>ye(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return De<=f&&f<t},is0:f=>f===De,isValidNot0:f=>!u.is0(f)&&u.isValid(f),isOdd:f=>(f&Ee)===Ee,neg:f=>ye(-f,t),eql:(f,h)=>f===h,sqr:f=>ye(f*f,t),add:(f,h)=>ye(f+h,t),sub:(f,h)=>ye(f-h,t),mul:(f,h)=>ye(f*h,t),pow:(f,h)=>Kw(u,f,h),div:(f,h)=>ye(f*xl(h,t),t),sqrN:f=>f*f,addN:(f,h)=>f+h,subN:(f,h)=>f-h,mulN:(f,h)=>f*h,inv:f=>xl(f,t),sqrt:s||(f=>(d||(d=Uw(t)),d(u,f))),toBytes:f=>r?sf(f,l):ic(f,l),fromBytes:(f,h=!0)=>{if(a){if(!a.includes(f.length)||f.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);const m=new Uint8Array(l);m.set(f,r?0:m.length-f.length),f=m}if(f.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+f.length);let g=r?Vn(f):Ps(f);if(i&&(g=ye(g,t)),!h&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:f=>gf(u,f),cmov:(f,h,g)=>g?h:f});return Object.freeze(u)}function wf(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function yf(t){const e=wf(t);return e+Math.ceil(e/2)}function zw(t,e,r=!1){const n=t.length,o=wf(e),s=yf(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const i=r?Vn(t):Ps(t),a=ye(i,e-Ee)+Ee;return r?sf(a,o):ic(a,o)}const Yr=BigInt(0),Zt=BigInt(1);function es(t,e){const r=e.negate();return t?r:e}function Jt(t,e){const r=gf(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function bf(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ri(t,e){bf(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1),o=2**t,s=io(t),i=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function El(t,e,r){const{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r;let a=Number(t&o),c=t>>i;a>n&&(a-=s,c+=Zt);const l=e*n,d=l+Math.abs(a)-1,u=a===0,f=a<0,h=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:f,isNegF:h,offsetF:l}}function Vw(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function Ww(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const ni=new WeakMap,vf=new WeakMap;function oi(t){return vf.get(t)||1}function Al(t){if(t!==Yr)throw new Error("invalid wNAF")}class xf{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let o=e;for(;r>Yr;)r&Zt&&(n=n.add(o)),o=o.double(),r>>=Zt;return n}precomputeWindow(e,r){const{windows:n,windowSize:o}=ri(r,this.bits),s=[];let i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE;const i=ri(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:f,offsetF:h}=El(n,a,i);n=c,d?s=s.add(es(f,r[h])):o=o.add(es(u,r[l]))}return Al(n),{p:o,f:s}}wNAFUnsafe(e,r,n,o=this.ZERO){const s=ri(e,this.bits);for(let i=0;i<s.windows&&n!==Yr;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=El(n,i,s);if(n=a,!l){const u=r[c];o=o.add(d?u.negate():u)}}return Al(n),o}getPrecomputes(e,r,n){let o=ni.get(r);return o||(o=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(o=n(o)),ni.set(r,o))),o}cached(e,r,n){const o=oi(e);return this.wNAF(o,this.getPrecomputes(o,e,n),r)}unsafe(e,r,n,o){const s=oi(e);return s===1?this._unsafeLadder(e,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),r,o)}createCache(e,r){bf(r,this.bits),vf.set(e,r),ni.delete(e)}hasCache(e){return oi(e)!==1}}function Gw(t,e,r,n){let o=e,s=t.ZERO,i=t.ZERO;for(;r>Yr||n>Yr;)r&Zt&&(s=s.add(o)),n&Zt&&(i=i.add(o)),o=o.double(),r>>=Zt,n>>=Zt;return{p1:s,p2:i}}function Sf(t,e,r,n){Vw(r,t),Ww(n,e);const o=r.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,a=af(BigInt(o));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=io(c),d=new Array(Number(l)+1).fill(i),u=Math.floor((e.BITS-1)/c)*c;let f=i;for(let h=u;h>=0;h-=c){d.fill(i);for(let m=0;m<s;m++){const y=n[m],w=Number(y>>BigInt(h)&l);d[w]=d[w].add(r[m])}let g=i;for(let m=d.length-1,y=i;m>0;m--)y=y.add(d[m]),g=g.add(y);if(f=f.add(g),h!==0)for(let m=0;m<c;m++)f=f.double()}return f}function kl(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return qw(e),e}else return pr(t,{isLE:r})}function Ef(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>Yr))throw new Error(`CURVE.${c} must be positive bigint`)}const o=kl(e.p,r.Fp,n),s=kl(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}const _t=BigInt(0),be=BigInt(1),si=BigInt(2),Xw=BigInt(8);function Yw(t,e,r,n){const o=t.sqr(r),s=t.sqr(n),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function Zw(t,e={}){const r=Ef("edwards",t,e,e.FpFnLE),{Fp:n,Fn:o}=r;let s=r.CURVE;const{h:i}=s;ao(e,{},{uvRatio:"function"});const a=si<<BigInt(o.BYTES*8)-be,c=y=>n.create(y),l=e.uvRatio||((y,w)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,w))}}catch{return{isValid:!1,value:_t}}});if(!Yw(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(y,w,I=!1){const v=I?be:_t;return da("coordinate "+y,w,v,a),w}function u(y){if(!(y instanceof g))throw new Error("ExtendedPoint expected")}const f=Qo((y,w)=>{const{X:I,Y:v,Z:A}=y,B=y.is0();w==null&&(w=B?Xw:n.inv(A));const T=c(I*w),N=c(v*w),k=n.mul(A,w);if(B)return{x:_t,y:be};if(k!==be)throw new Error("invZ was invalid");return{x:T,y:N}}),h=Qo(y=>{const{a:w,d:I}=s;if(y.is0())throw new Error("bad point: ZERO");const{X:v,Y:A,Z:B,T}=y,N=c(v*v),k=c(A*A),x=c(B*B),S=c(x*x),R=c(N*w),P=c(x*c(R+k)),b=c(S+c(I*c(N*k)));if(P!==b)throw new Error("bad point: equation left != right (1)");const E=c(v*A),C=c(B*T);if(E!==C)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(w,I,v,A){this.X=d("x",w),this.Y=d("y",I),this.Z=d("z",v,!0),this.T=d("t",A),Object.freeze(this)}static CURVE(){return s}static fromAffine(w){if(w instanceof g)throw new Error("extended point not allowed");const{x:I,y:v}=w||{};return d("x",I),d("y",v),new g(I,v,be,c(I*v))}static fromBytes(w,I=!1){const v=n.BYTES,{a:A,d:B}=s;w=vl(Qe(w,v,"point")),ir(I,"zip215");const T=vl(w),N=w[v-1];T[v-1]=N&-129;const k=Vn(T),x=I?a:n.ORDER;da("point.y",k,_t,x);const S=c(k*k),R=c(S-be),P=c(B*S-A);let{isValid:b,value:E}=l(R,P);if(!b)throw new Error("bad point: invalid y coordinate");const C=(E&be)===be,L=(N&128)!==0;if(!I&&E===_t&&L)throw new Error("bad point: x=0 and x_0=1");return L!==C&&(E=c(-E)),g.fromAffine({x:E,y:k})}static fromHex(w,I=!1){return g.fromBytes(fe("point",w),I)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,I=!0){return m.createCache(this,w),I||this.multiply(si),this}assertValidity(){h(this)}equals(w){u(w);const{X:I,Y:v,Z:A}=this,{X:B,Y:T,Z:N}=w,k=c(I*N),x=c(B*A),S=c(v*N),R=c(T*A);return k===x&&S===R}is0(){return this.equals(g.ZERO)}negate(){return new g(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:w}=s,{X:I,Y:v,Z:A}=this,B=c(I*I),T=c(v*v),N=c(si*c(A*A)),k=c(w*B),x=I+v,S=c(c(x*x)-B-T),R=k+T,P=R-N,b=k-T,E=c(S*P),C=c(R*b),L=c(S*b),M=c(P*R);return new g(E,C,M,L)}add(w){u(w);const{a:I,d:v}=s,{X:A,Y:B,Z:T,T:N}=this,{X:k,Y:x,Z:S,T:R}=w,P=c(A*k),b=c(B*x),E=c(N*v*R),C=c(T*S),L=c((A+B)*(k+x)-P-b),M=C-E,$=C+E,j=c(b-I*P),D=c(L*M),_=c($*j),O=c(L*j),q=c(M*$);return new g(D,_,q,O)}subtract(w){return this.add(w.negate())}multiply(w){if(!o.isValidNot0(w))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:I,f:v}=m.cached(this,w,A=>Jt(g,A));return Jt(g,[I,v])[0]}multiplyUnsafe(w,I=g.ZERO){if(!o.isValid(w))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return w===_t?g.ZERO:this.is0()||w===be?this:m.unsafe(this,w,v=>Jt(g,v),I)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(w){return f(this,w)}clearCofactor(){return i===be?this:this.multiplyUnsafe(i)}toBytes(){const{x:w,y:I}=this.toAffine(),v=n.toBytes(I);return v[v.length-1]|=w&be?128:0,v}toHex(){return tr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(w){return Jt(g,w)}static msm(w,I){return Sf(g,o,w,I)}_setWindowSize(w){this.precompute(w)}toRawBytes(){return this.toBytes()}}g.BASE=new g(s.Gx,s.Gy,be,c(s.Gx*s.Gy)),g.ZERO=new g(_t,be,be,_t),g.Fp=n,g.Fn=o;const m=new xf(g,o.BITS);return g.BASE.precompute(8),g}function Jw(t,e,r={}){if(typeof e!="function")throw new Error('"hash" function param is required');ao(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n}=r,{BASE:o,Fp:s,Fn:i}=t,a=r.randomBytes||oc,c=r.adjustScalarBytes||(x=>x),l=r.domain||((x,S,R)=>{if(ir(R,"phflag"),S.length||R)throw new Error("Contexts/pre-hash are not supported");return x});function d(x){return i.create(Vn(x))}function u(x){const S=v.secretKey;x=fe("private key",x,S);const R=fe("hashed private key",e(x),2*S),P=c(R.slice(0,S)),b=R.slice(S,2*S),E=d(P);return{head:P,prefix:b,scalar:E}}function f(x){const{head:S,prefix:R,scalar:P}=u(x),b=o.multiply(P),E=b.toBytes();return{head:S,prefix:R,scalar:P,point:b,pointBytes:E}}function h(x){return f(x).pointBytes}function g(x=Uint8Array.of(),...S){const R=ct(...S);return d(e(l(R,fe("context",x),!!n)))}function m(x,S,R={}){x=fe("message",x),n&&(x=n(x));const{prefix:P,scalar:b,pointBytes:E}=f(S),C=g(R.context,P,x),L=o.multiply(C).toBytes(),M=g(R.context,L,E,x),$=i.create(C+M*b);if(!i.isValid($))throw new Error("sign failed: invalid s");const j=ct(L,i.toBytes($));return Qe(j,v.signature,"result")}const y={zip215:!0};function w(x,S,R,P=y){const{context:b,zip215:E}=P,C=v.signature;x=fe("signature",x,C),S=fe("message",S),R=fe("publicKey",R,v.publicKey),E!==void 0&&ir(E,"zip215"),n&&(S=n(S));const L=C/2,M=x.subarray(0,L),$=Vn(x.subarray(L,C));let j,D,_;try{j=t.fromBytes(R,E),D=t.fromBytes(M,E),_=o.multiplyUnsafe($)}catch{return!1}if(!E&&j.isSmallOrder())return!1;const O=g(b,D.toBytes(),j.toBytes(),S);return D.add(j.multiplyUnsafe(O)).subtract(_).clearCofactor().is0()}const I=s.BYTES,v={secretKey:I,publicKey:I,signature:2*I,seed:I};function A(x=a(v.seed)){return Qe(x,v.seed,"seed")}function B(x){const S=k.randomSecretKey(x);return{secretKey:S,publicKey:h(S)}}function T(x){return so(x)&&x.length===i.BYTES}function N(x,S){try{return!!t.fromBytes(x,S)}catch{return!1}}const k={getExtendedPublicKey:f,randomSecretKey:A,isValidSecretKey:T,isValidPublicKey:N,toMontgomery(x){const{y:S}=t.fromBytes(x),R=v.publicKey,P=R===32;if(!P&&R!==57)throw new Error("only defined for 25519 and 448");const b=P?s.div(be+S,be-S):s.div(S-be,S+be);return s.toBytes(b)},toMontgomerySecret(x){const S=v.secretKey;Qe(x,S);const R=e(x.subarray(0,S));return c(R).subarray(0,S)},randomPrivateKey:A,precompute(x=8,S=t.BASE){return S.precompute(x,!1)}};return Object.freeze({keygen:B,getPublicKey:h,sign:m,verify:w,utils:k,Point:t,lengths:v})}function Qw(t){const e={a:t.a,d:t.d,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp,n=pr(e.n,t.nBitLength,!0),o={Fp:r,Fn:n,uvRatio:t.uvRatio},s={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:o,hash:t.hash,eddsaOpts:s}}function ey(t,e){const r=e.Point;return Object.assign({},e,{ExtendedPoint:r,CURVE:t,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}function ty(t){const{CURVE:e,curveOpts:r,hash:n,eddsaOpts:o}=Qw(t),s=Zw(e,r),i=Jw(s,n,o);return ey(t,i)}const ry=BigInt(1),Il=BigInt(2);BigInt(3);const ny=BigInt(5),oy=BigInt(8),cc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Af={p:cc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:oy,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function sy(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=cc,a=t*t%s*t%s,c=ue(a,Il,s)*a%s,l=ue(c,ry,s)*t%s,d=ue(l,ny,s)*l%s,u=ue(d,e,s)*d%s,f=ue(u,r,s)*u%s,h=ue(f,n,s)*f%s,g=ue(h,o,s)*h%s,m=ue(g,o,s)*h%s,y=ue(m,e,s)*d%s;return{pow_p_5_8:ue(y,Il,s)*t%s,b2:a}}function iy(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Cl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ay(t,e){const r=cc,n=ye(e*e*e,r),o=ye(n*n*e,r),s=sy(t*o).pow_p_5_8;let i=ye(t*n*s,r);const a=ye(e*i*i,r),c=i,l=ye(i*Cl,r),d=a===t,u=a===ye(-t,r),f=a===ye(-t*Cl,r);return d&&(i=c),(u||f)&&(i=l),$w(i,r)&&(i=ye(-i,r)),{isValid:d||u,value:i}}const cy=pr(Af.p,{isLE:!0}),ly={...Af,Fp:cy,hash:Bw,adjustScalarBytes:iy,uvRatio:ay},ts=ty(ly);class Rl extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}}class Tl extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class dy extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}const kt={get(t=globalThis){const e=t.crypto;if(e?.subtle==null)throw new dy("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}},rs=32,gt=64,ua=32;let jr;const kf=(async()=>{try{return await kt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function uy(){const t=ts.utils.randomPrivateKey(),e=ts.getPublicKey(t);return{privateKey:yy(t,e),publicKey:e}}async function fy(t,e){let r;t.length===gt?r=t.subarray(0,32):r=t;const n={crv:"Ed25519",kty:"OKP",x:J(t.subarray(32),"base64url"),d:J(r,"base64url"),ext:!0,key_ops:["sign"]},o=await kt.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await kt.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function hy(t,e){const r=t.subarray(0,ua);return ts.sign(e instanceof Uint8Array?e:e.subarray(),r)}async function py(t,e){return jr==null&&(jr=await kf),jr?fy(t,e):hy(t,e)}async function gy(t,e,r){if(t.buffer instanceof ArrayBuffer){const n=await kt.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await kt.get().subtle.verify({name:"Ed25519"},n,e,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function my(t,e,r){return ts.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}async function wy(t,e,r){return jr==null&&(jr=await kf),jr?gy(t,e,r):my(t,e,r)}function yy(t,e){const r=new Uint8Array(gt);for(let n=0;n<ua;n++)r[n]=t[n],r[ua+n]=e[n];return r}function Ns(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}class If{type="Ed25519";raw;constructor(e){this.raw=Wn(e,rs)}toMultihash(){return no.digest(Ds(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return Le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:rt(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();const o=wy(this.raw,r,e);return Ns(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}}class fa{type="Ed25519";raw;publicKey;constructor(e,r){this.raw=Wn(e,gt),this.publicKey=new If(r)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:rt(this.raw,e.raw)}sign(e,r){r?.signal?.throwIfAborted();const n=py(this.raw,e);return Ns(n)?n.then(o=>(r?.signal?.throwIfAborted(),o)):(r?.signal?.throwIfAborted(),n)}}function by(t){if(t.length>gt){t=Wn(t,gt+rs);const n=t.subarray(0,gt),o=t.subarray(gt,t.length);return new fa(n,o)}t=Wn(t,gt);const e=t.subarray(0,gt),r=t.subarray(rs);return new fa(e,r)}function Cf(t){return t=Wn(t,rs),new If(t)}async function vy(){const{privateKey:t,publicKey:e}=uy();return new fa(t,e)}function Wn(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new tt(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}const xy=Math.pow(2,7),Sy=Math.pow(2,14),Ey=Math.pow(2,21),lc=Math.pow(2,28),dc=Math.pow(2,35),uc=Math.pow(2,42),fc=Math.pow(2,49),te=128,Ce=127;function gr(t){if(t<xy)return 1;if(t<Sy)return 2;if(t<Ey)return 3;if(t<lc)return 4;if(t<dc)return 5;if(t<uc)return 6;if(t<fc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Rf(t,e,r=0){switch(gr(t)){case 8:e[r++]=t&255|te,t/=128;case 7:e[r++]=t&255|te,t/=128;case 6:e[r++]=t&255|te,t/=128;case 5:e[r++]=t&255|te,t/=128;case 4:e[r++]=t&255|te,t>>>=7;case 3:e[r++]=t&255|te,t>>>=7;case 2:e[r++]=t&255|te,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Ay(t,e,r=0){switch(gr(t)){case 8:e.set(r++,t&255|te),t/=128;case 7:e.set(r++,t&255|te),t/=128;case 6:e.set(r++,t&255|te),t/=128;case 5:e.set(r++,t&255|te),t/=128;case 4:e.set(r++,t&255|te),t>>>=7;case 3:e.set(r++,t&255|te),t>>>=7;case 2:e.set(r++,t&255|te),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function Tf(t,e){let r=t[e],n=0;if(n+=r&Ce,r<te||(r=t[e+1],n+=(r&Ce)<<7,r<te)||(r=t[e+2],n+=(r&Ce)<<14,r<te)||(r=t[e+3],n+=(r&Ce)<<21,r<te)||(r=t[e+4],n+=(r&Ce)*lc,r<te)||(r=t[e+5],n+=(r&Ce)*dc,r<te)||(r=t[e+6],n+=(r&Ce)*uc,r<te)||(r=t[e+7],n+=(r&Ce)*fc,r<te))return n;throw new RangeError("Could not decode varint")}function ky(t,e){let r=t.get(e),n=0;if(n+=r&Ce,r<te||(r=t.get(e+1),n+=(r&Ce)<<7,r<te)||(r=t.get(e+2),n+=(r&Ce)<<14,r<te)||(r=t.get(e+3),n+=(r&Ce)<<21,r<te)||(r=t.get(e+4),n+=(r&Ce)*lc,r<te)||(r=t.get(e+5),n+=(r&Ce)*dc,r<te)||(r=t.get(e+6),n+=(r&Ce)*uc,r<te)||(r=t.get(e+7),n+=(r&Ce)*fc,r<te))return n;throw new RangeError("Could not decode varint")}function Iy(t,e,r=0){return e==null&&(e=At(gr(t))),e instanceof Uint8Array?Rf(t,e,r):Ay(t,e,r)}function Pf(t,e=0){return t instanceof Uint8Array?Tf(t,e):ky(t,e)}const hc=new Float32Array([-0]),Ht=new Uint8Array(hc.buffer);function Cy(t,e,r){hc[0]=t,e[r]=Ht[0],e[r+1]=Ht[1],e[r+2]=Ht[2],e[r+3]=Ht[3]}function Ry(t,e){return Ht[0]=t[e],Ht[1]=t[e+1],Ht[2]=t[e+2],Ht[3]=t[e+3],hc[0]}const pc=new Float64Array([-0]),Re=new Uint8Array(pc.buffer);function Ty(t,e,r){pc[0]=t,e[r]=Re[0],e[r+1]=Re[1],e[r+2]=Re[2],e[r+3]=Re[3],e[r+4]=Re[4],e[r+5]=Re[5],e[r+6]=Re[6],e[r+7]=Re[7]}function Py(t,e){return Re[0]=t[e],Re[1]=t[e+1],Re[2]=t[e+2],Re[3]=t[e+3],Re[4]=t[e+4],Re[5]=t[e+5],Re[6]=t[e+6],Re[7]=t[e+7],pc[0]}const Ny=BigInt(Number.MAX_SAFE_INTEGER),Ly=BigInt(Number.MIN_SAFE_INTEGER);class Te{lo;hi;constructor(e,r){this.lo=e|0,this.hi=r|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){const r=~this.lo+1>>>0;let n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){const r=~this.lo+1>>>0;let n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return rr;if(e<Ny&&e>Ly)return this.fromNumber(Number(e));const r=e<0n;r&&(e=-e);let n=e>>32n,o=e-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>Pl&&(o=0n,++n>Pl&&(n=0n))),new Te(Number(o),Number(n))}static fromNumber(e){if(e===0)return rr;const r=e<0;r&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new Te(n,o)}static from(e){return typeof e=="number"?Te.fromNumber(e):typeof e=="bigint"?Te.fromBigInt(e):typeof e=="string"?Te.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new Te(e.low>>>0,e.high>>>0):rr}}const rr=new Te(0,0);rr.toBigInt=function(){return 0n};rr.zzEncode=rr.zzDecode=function(){return this};rr.length=function(){return 1};const Pl=4294967296n;function By(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:(r&64512)===55296&&(t.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function _y(t,e,r){if(r-e<1)return"";let o;const s=[];let i=0,a;for(;e<r;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Nf(t,e,r){const n=r;let o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[r++]=o:o<2048?(e[r++]=o>>6|192,e[r++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[r++]=o>>18|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128,e[r++]=o&63|128):(e[r++]=o>>12|224,e[r++]=o>>6&63|128,e[r++]=o&63|128);return r-n}function Ze(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function xo(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}class Dy{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Ze(this,10);return e}int32(){return this.uint32()|0}sint32(){const e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Ze(this,4);return xo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ze(this,4);return xo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ze(this,4);const e=Ry(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ze(this,4);const e=Py(this.buf,this.pos);return this.pos+=8,e}bytes(){const e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw Ze(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){const e=this.bytes();return _y(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Ze(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Ze(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new Te(0,0);let r=0;if(this.len-this.pos>4){for(;r<4;++r)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw Ze(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,e}if(this.len-this.pos>4){for(;r<5;++r)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;r<5;++r){if(this.pos>=this.len)throw Ze(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Ze(this,8);const e=xo(this.buf,this.pos+=4),r=xo(this.buf,this.pos+=4);return new Te(e,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=Tf(this.buf,this.pos);return this.pos+=gr(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function Oy(t){return new Dy(t instanceof Uint8Array?t:t.subarray())}function Ls(t,e,r){const n=Oy(t);return e.decode(n,void 0,r)}function Fy(t){let n,o=8192;return function(i){if(i<1||i>4096)return At(i);o+i>8192&&(n=At(8192),o=0);const a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}class Pn{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}}function ii(){}class My{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const jy=Fy();function Uy(t){return globalThis.Buffer!=null?At(t):jy(t)}class ha{len;head;tail;states;constructor(){this.len=0,this.head=new Pn(ii,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new Pn(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Hy((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(So,10,Te.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const r=Te.fromBigInt(e);return this._push(So,r.length(),r)}uint64Number(e){return this._push(Rf,gr(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const r=Te.fromBigInt(e).zzEncode();return this._push(So,r.length(),r)}sint64Number(e){const r=Te.fromNumber(e).zzEncode();return this._push(So,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(ai,1,e?1:0)}fixed32(e){return this._push(pn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const r=Te.fromBigInt(e);return this._push(pn,4,r.lo)._push(pn,4,r.hi)}fixed64Number(e){const r=Te.fromNumber(e);return this._push(pn,4,r.lo)._push(pn,4,r.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Cy,4,e)}double(e){return this._push(Ty,8,e)}bytes(e){const r=e.length>>>0;return r===0?this._push(ai,1,0):this.uint32(r)._push(qy,r,e)}string(e){const r=By(e);return r!==0?this.uint32(r)._push(Nf,r,e):this._push(ai,1,0)}fork(){return this.states=new My(this),this.head=this.tail=new Pn(ii,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Pn(ii,0,0),this.len=0),this}ldelim(){const e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=r,this.len+=n),this}finish(){let e=this.head.next;const r=Uy(this.len);let n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}}function ai(t,e,r){e[r]=t&255}function $y(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}class Hy extends Pn{next;constructor(e,r){super($y,e,r),this.next=void 0}}function So(t,e,r){for(;t.hi!==0;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}function pn(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function qy(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(ha.prototype.bytes=function(t){const e=t.length>>>0;return this.uint32(e),e>0&&this._push(Ky,e,t),this},ha.prototype.string=function(t){const e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(zy,e,t),this});function Ky(t,e,r){e.set(t,r)}function zy(t,e,r){t.length<40?Nf(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(we(t),r)}function Vy(){return new ha}function Bs(t,e){const r=Vy();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var ns;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(ns||(ns={}));function Lf(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function Wy(t){function e(o){if(t[o.toString()]==null)throw new Error("Invalid enum value");return t[o]}const r=function(s,i){const a=e(s);i.int32(a)},n=function(s){const i=s.int32();return e(i)};return Lf("enum",ns.VARINT,r,n)}function _s(t,e){return Lf("message",ns.LENGTH_DELIMITED,t,e)}class Nl extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var le;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(le||(le={}));var pa;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(pa||(pa={}));(function(t){t.codec=()=>Wy(pa)})(le||(le={}));var ar;(function(t){let e;t.codec=()=>(e==null&&(e=_s((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),le.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{const s={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){const a=r.uint32();switch(a>>>3){case 1:{s.Type=le.codec().decode(r);break}case 2:{s.Data=r.bytes();break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Bs(r,t.codec()),t.decode=(r,n)=>Ls(r,t.codec(),n)})(ar||(ar={}));var os;(function(t){let e;t.codec=()=>(e==null&&(e=_s((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),le.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{const s={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){const a=r.uint32();switch(a>>>3){case 1:{s.Type=le.codec().decode(r);break}case 2:{s.Data=r.bytes();break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Bs(r,t.codec()),t.decode=(r,n)=>Ls(r,t.codec(),n)})(os||(os={}));const Bf=nf;class _f{type="RSA";jwk;_raw;_multihash;constructor(e,r){this.jwk=e,this._multihash=r}get raw(){return this._raw==null&&(this._raw=Of(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ce.createV1(114,this._multihash)}toString(){return Le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:rt(this.raw,e.raw)}verify(e,r,n){return cb(this.jwk,r,e,n)}}class Gy{type="RSA";jwk;_raw;publicKey;constructor(e,r){this.jwk=e,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=Qy(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:rt(this.raw,e.raw)}sign(e,r){return ab(this.jwk,e,r)}}const Xy=8192,Df=18,Yy=1062,Zy=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Jy(t){return{n:J(t[1],"base64url"),e:J(t[2],"base64url"),d:J(t[3],"base64url"),p:J(t[4],"base64url"),q:J(t[5],"base64url"),dp:J(t[6],"base64url"),dq:J(t[7],"base64url"),qi:J(t[8],"base64url"),kty:"RSA"}}function Qy(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new tt("JWK was missing components");return xt([je(Uint8Array.from([0])),je(we(t.n,"base64url")),je(we(t.e,"base64url")),je(we(t.d,"base64url")),je(we(t.p,"base64url")),je(we(t.q,"base64url")),je(we(t.dp,"base64url")),je(we(t.dq,"base64url")),je(we(t.qi,"base64url"))]).subarray()}function eb(t){const e=nn(t[1],{offset:0});return{kty:"RSA",n:J(e[0],"base64url"),e:J(e[1],"base64url")}}function Of(t){if(t.n==null||t.e==null)throw new tt("JWK was missing components");return xt([Zy,rc(xt([je(we(t.n,"base64url")),je(we(t.e,"base64url"))]))]).subarray()}function tb(t){const e=nn(t);return rb(e)}function rb(t){const e=Jy(t);return sb(e)}function nb(t,e){if(t.byteLength>=Yy)throw new _u("Key size is too large");const r=nn(t,{offset:0});return ob(r,t,e)}function ob(t,e,r){const n=eb(t);if(r==null){const o=Bf(ar.encode({Type:le.RSA,Data:e}));r=ro(Df,o)}return new _f(n,r)}function sb(t){if(lb(t)>Xy)throw new tt("Key size is too large");const e=ib(t),r=Bf(ar.encode({Type:le.RSA,Data:Of(e.publicKey)})),n=ro(Df,r);return new Gy(e.privateKey,new _f(e.publicKey,n))}function ib(t){if(t==null)throw new tt("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function ab(t,e,r){const n=await kt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();const o=await kt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function cb(t,e,r,n){const o=await kt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();const s=await kt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),s}function lb(t){if(t.kty!=="RSA")throw new tt("invalid key type");if(t.n==null)throw new tt("invalid key modulus");return we(t.n,"base64url").length*8}class Ff extends Qu{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Zu(e);const n=nc(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),Xr(s)}update(e){return Zo(this),this.iHash.update(e),this}digestInto(e){Zo(this),hr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Mf=(t,e,r)=>new Ff(t,e).update(r).digest();Mf.create=(t,e)=>new Ff(t,e);const Ll=(t,e)=>(t+(t>=0?e:-e)/jf)/e;function db(t,e,r){const[[n,o],[s,i]]=e,a=Ll(i*t,r),c=Ll(-o*t,r);let l=t-a*n-c*s,d=-a*o-c*i;const u=l<yt,f=d<yt;u&&(l=-l),f&&(d=-d);const h=io(Math.ceil(af(r)/2))+Ur;if(l<yt||l>=h||d<yt||d>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:f,k2:d}}function ga(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function ci(t,e){const r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return ir(r.lowS,"lowS"),ir(r.prehash,"prehash"),r.format!==void 0&&ga(r.format),r}class ub extends Error{constructor(e=""){super(e)}}const mt={Err:ub,_tlv:{encode:(t,e)=>{const{Err:r}=mt;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const n=e.length/2,o=vo(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?vo(o.length/2|128):"";return vo(t)+s+o+e},decode(t,e){const{Err:r}=mt;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const o=e[n++],s=!!(o&128);let i=0;if(!s)i=o;else{const c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(n,n+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(t){const{Err:e}=mt;if(t<yt)throw new e("integer: negative integers are not allowed");let r=vo(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=mt;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ps(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=mt,o=fe("signature",t),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,s),{v:l,l:d}=n.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(t){const{_tlv:e,_int:r}=mt,n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),s=n+o;return e.encode(48,s)}},yt=BigInt(0),Ur=BigInt(1),jf=BigInt(2),Eo=BigInt(3),fb=BigInt(4);function Nr(t,e){const{BYTES:r}=t;let n;if(typeof e=="bigint")n=e;else{let o=fe("private key",e);try{n=t.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function hb(t,e={}){const r=Ef("weierstrass",t,e),{Fp:n,Fn:o}=r;let s=r.CURVE;const{h:i,n:a}=s;ao(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=$f(n,o);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(P,b,E){const{x:C,y:L}=b.toAffine(),M=n.toBytes(C);if(ir(E,"isCompressed"),E){d();const $=!n.isOdd(L);return ct(Uf($),M)}else return ct(Uint8Array.of(4),M,n.toBytes(L))}function f(P){Qe(P,void 0,"Point");const{publicKey:b,publicKeyUncompressed:E}=l,C=P.length,L=P[0],M=P.subarray(1);if(C===b&&(L===2||L===3)){const $=n.fromBytes(M);if(!n.isValid($))throw new Error("bad point: is not on curve, wrong x");const j=m($);let D;try{D=n.sqrt(j)}catch(q){const H=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}d();const _=n.isOdd(D);return(L&1)===1!==_&&(D=n.neg(D)),{x:$,y:D}}else if(C===E&&L===4){const $=n.BYTES,j=n.fromBytes(M.subarray(0,$)),D=n.fromBytes(M.subarray($,$*2));if(!y(j,D))throw new Error("bad point: is not on curve");return{x:j,y:D}}else throw new Error(`bad point: got length ${C}, expected compressed=${b} or uncompressed=${E}`)}const h=e.toBytes||u,g=e.fromBytes||f;function m(P){const b=n.sqr(P),E=n.mul(b,P);return n.add(n.add(E,n.mul(P,s.a)),s.b)}function y(P,b){const E=n.sqr(b),C=m(P);return n.eql(E,C)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const w=n.mul(n.pow(s.a,Eo),fb),I=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(w,I)))throw new Error("bad curve params: a or b");function v(P,b,E=!1){if(!n.isValid(b)||E&&n.is0(b))throw new Error(`bad point coordinate ${P}`);return b}function A(P){if(!(P instanceof x))throw new Error("ProjectivePoint expected")}function B(P){if(!c||!c.basises)throw new Error("no endo");return db(P,c.basises,o.ORDER)}const T=Qo((P,b)=>{const{X:E,Y:C,Z:L}=P;if(n.eql(L,n.ONE))return{x:E,y:C};const M=P.is0();b==null&&(b=M?n.ONE:n.inv(L));const $=n.mul(E,b),j=n.mul(C,b),D=n.mul(L,b);if(M)return{x:n.ZERO,y:n.ZERO};if(!n.eql(D,n.ONE))throw new Error("invZ was invalid");return{x:$,y:j}}),N=Qo(P=>{if(P.is0()){if(e.allowInfinityPoint&&!n.is0(P.Y))return;throw new Error("bad point: ZERO")}const{x:b,y:E}=P.toAffine();if(!n.isValid(b)||!n.isValid(E))throw new Error("bad point: x or y not field elements");if(!y(b,E))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function k(P,b,E,C,L){return E=new x(n.mul(E.X,P),E.Y,E.Z),b=es(C,b),E=es(L,E),b.add(E)}class x{constructor(b,E,C){this.X=v("x",b),this.Y=v("y",E,!0),this.Z=v("z",C),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){const{x:E,y:C}=b||{};if(!b||!n.isValid(E)||!n.isValid(C))throw new Error("invalid affine point");if(b instanceof x)throw new Error("projective point not allowed");return n.is0(E)&&n.is0(C)?x.ZERO:new x(E,C,n.ONE)}static fromBytes(b){const E=x.fromAffine(g(Qe(b,void 0,"point")));return E.assertValidity(),E}static fromHex(b){return x.fromBytes(fe("pointHex",b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,E=!0){return R.createCache(this,b),E||this.multiply(Eo),this}assertValidity(){N(this)}hasEvenY(){const{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){A(b);const{X:E,Y:C,Z:L}=this,{X:M,Y:$,Z:j}=b,D=n.eql(n.mul(E,j),n.mul(M,L)),_=n.eql(n.mul(C,j),n.mul($,L));return D&&_}negate(){return new x(this.X,n.neg(this.Y),this.Z)}double(){const{a:b,b:E}=s,C=n.mul(E,Eo),{X:L,Y:M,Z:$}=this;let j=n.ZERO,D=n.ZERO,_=n.ZERO,O=n.mul(L,L),q=n.mul(M,M),H=n.mul($,$),K=n.mul(L,M);return K=n.add(K,K),_=n.mul(L,$),_=n.add(_,_),j=n.mul(b,_),D=n.mul(C,H),D=n.add(j,D),j=n.sub(q,D),D=n.add(q,D),D=n.mul(j,D),j=n.mul(K,j),_=n.mul(C,_),H=n.mul(b,H),K=n.sub(O,H),K=n.mul(b,K),K=n.add(K,_),_=n.add(O,O),O=n.add(_,O),O=n.add(O,H),O=n.mul(O,K),D=n.add(D,O),H=n.mul(M,$),H=n.add(H,H),O=n.mul(H,K),j=n.sub(j,O),_=n.mul(H,q),_=n.add(_,_),_=n.add(_,_),new x(j,D,_)}add(b){A(b);const{X:E,Y:C,Z:L}=this,{X:M,Y:$,Z:j}=b;let D=n.ZERO,_=n.ZERO,O=n.ZERO;const q=s.a,H=n.mul(s.b,Eo);let K=n.mul(E,M),z=n.mul(C,$),W=n.mul(L,j),X=n.add(E,C),G=n.add(M,$);X=n.mul(X,G),G=n.add(K,z),X=n.sub(X,G),G=n.add(E,L);let Y=n.add(M,j);return G=n.mul(G,Y),Y=n.add(K,W),G=n.sub(G,Y),Y=n.add(C,L),D=n.add($,j),Y=n.mul(Y,D),D=n.add(z,W),Y=n.sub(Y,D),O=n.mul(q,G),D=n.mul(H,W),O=n.add(D,O),D=n.sub(z,O),O=n.add(z,O),_=n.mul(D,O),z=n.add(K,K),z=n.add(z,K),W=n.mul(q,W),G=n.mul(H,G),z=n.add(z,W),W=n.sub(K,W),W=n.mul(q,W),G=n.add(G,W),K=n.mul(z,G),_=n.add(_,K),K=n.mul(Y,G),D=n.mul(X,D),D=n.sub(D,K),K=n.mul(X,z),O=n.mul(Y,O),O=n.add(O,K),new x(D,_,O)}subtract(b){return this.add(b.negate())}is0(){return this.equals(x.ZERO)}multiply(b){const{endo:E}=e;if(!o.isValidNot0(b))throw new Error("invalid scalar: out of range");let C,L;const M=$=>R.cached(this,$,j=>Jt(x,j));if(E){const{k1neg:$,k1:j,k2neg:D,k2:_}=B(b),{p:O,f:q}=M(j),{p:H,f:K}=M(_);L=q.add(K),C=k(E.beta,O,H,$,D)}else{const{p:$,f:j}=M(b);C=$,L=j}return Jt(x,[C,L])[0]}multiplyUnsafe(b){const{endo:E}=e,C=this;if(!o.isValid(b))throw new Error("invalid scalar: out of range");if(b===yt||C.is0())return x.ZERO;if(b===Ur)return C;if(R.hasCache(this))return this.multiply(b);if(E){const{k1neg:L,k1:M,k2neg:$,k2:j}=B(b),{p1:D,p2:_}=Gw(x,C,M,j);return k(E.beta,D,_,L,$)}else return R.unsafe(C,b)}multiplyAndAddUnsafe(b,E,C){const L=this.multiplyUnsafe(E).add(b.multiplyUnsafe(C));return L.is0()?void 0:L}toAffine(b){return T(this,b)}isTorsionFree(){const{isTorsionFree:b}=e;return i===Ur?!0:b?b(x,this):R.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:b}=e;return i===Ur?this:b?b(x,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(b=!0){return ir(b,"isCompressed"),this.assertValidity(),h(x,this,b)}toHex(b=!0){return tr(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(b=!0){return this.toBytes(b)}_setWindowSize(b){this.precompute(b)}static normalizeZ(b){return Jt(x,b)}static msm(b,E){return Sf(x,o,b,E)}static fromPrivateKey(b){return x.BASE.multiply(Nr(o,b))}}x.BASE=new x(s.Gx,s.Gy,n.ONE),x.ZERO=new x(n.ZERO,n.ONE,n.ZERO),x.Fp=n,x.Fn=o;const S=o.BITS,R=new xf(x,e.endo?Math.ceil(S/2):S);return x.BASE.precompute(8),x}function Uf(t){return Uint8Array.of(t?2:3)}function $f(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function pb(t,e={}){const{Fn:r}=t,n=e.randomBytes||oc,o=Object.assign($f(t.Fp,r),{seed:yf(r.ORDER)});function s(h){try{return!!Nr(r,h)}catch{return!1}}function i(h,g){const{publicKey:m,publicKeyUncompressed:y}=o;try{const w=h.length;return g===!0&&w!==m||g===!1&&w!==y?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return zw(Qe(h,o.seed,"seed"),r.ORDER)}function c(h,g=!0){return t.BASE.multiply(Nr(r,h)).toBytes(g)}function l(h){const g=a(h);return{secretKey:g,publicKey:c(g)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:g,publicKey:m,publicKeyUncompressed:y}=o;if(r.allowedLengths||g===m)return;const w=fe("key",h).length;return w===m||w===y}function u(h,g,m=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(g)===!1)throw new Error("second arg must be public key");const y=Nr(r,h);return t.fromHex(g).multiply(y).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>Nr(r,h),precompute(h=8,g=t.BASE){return g.precompute(h,!1)}},lengths:o})}function gb(t,e,r={}){Zu(e),ao(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=r.randomBytes||oc,o=r.hmac||((E,...C)=>Mf(e,E,ct(...C))),{Fp:s,Fn:i}=t,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h}=pb(t,r),g={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function y(E){const C=a>>Ur;return E>C}function w(E,C){if(!i.isValidNot0(C))throw new Error(`invalid signature ${E}: out of range 1..Point.Fn.ORDER`);return C}function I(E,C){ga(C);const L=h.signature,M=C==="compact"?L:C==="recovered"?L+1:void 0;return Qe(E,M,`${C} signature`)}class v{constructor(C,L,M){this.r=w("r",C),this.s=w("s",L),M!=null&&(this.recovery=M),Object.freeze(this)}static fromBytes(C,L=m){I(C,L);let M;if(L==="der"){const{r:_,s:O}=mt.toSig(Qe(C));return new v(_,O)}L==="recovered"&&(M=C[0],L="compact",C=C.subarray(1));const $=i.BYTES,j=C.subarray(0,$),D=C.subarray($,$*2);return new v(i.fromBytes(j),i.fromBytes(D),M)}static fromHex(C,L){return this.fromBytes(Jo(C),L)}addRecoveryBit(C){return new v(this.r,this.s,C)}recoverPublicKey(C){const L=s.ORDER,{r:M,s:$,recovery:j}=this;if(j==null||![0,1,2,3].includes(j))throw new Error("recovery id invalid");if(a*jf<L&&j>1)throw new Error("recovery id is ambiguous for h>1 curve");const _=j===2||j===3?M+a:M;if(!s.isValid(_))throw new Error("recovery id 2 or 3 invalid");const O=s.toBytes(_),q=t.fromBytes(ct(Uf((j&1)===0),O)),H=i.inv(_),K=B(fe("msgHash",C)),z=i.create(-K*H),W=i.create($*H),X=t.BASE.multiplyUnsafe(z).add(q.multiplyUnsafe(W));if(X.is0())throw new Error("point at infinify");return X.assertValidity(),X}hasHighS(){return y(this.s)}toBytes(C=m){if(ga(C),C==="der")return Jo(mt.hexFromSig(this));const L=i.toBytes(this.r),M=i.toBytes(this.s);if(C==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return ct(Uint8Array.of(this.recovery),L,M)}return ct(L,M)}toHex(C){return tr(this.toBytes(C))}assertValidity(){}static fromCompact(C){return v.fromBytes(fe("sig",C),"compact")}static fromDER(C){return v.fromBytes(fe("sig",C),"der")}normalizeS(){return this.hasHighS()?new v(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return tr(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return tr(this.toBytes("compact"))}}const A=r.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");const L=Ps(C),M=C.length*8-c;return M>0?L>>BigInt(M):L},B=r.bits2int_modN||function(C){return i.create(A(C))},T=io(c);function N(E){return da("num < 2^"+c,E,yt,T),i.toBytes(E)}function k(E,C){return Qe(E,void 0,"message"),C?Qe(e(E),void 0,"prehashed message"):E}function x(E,C,L){if(["recovered","canonical"].some(z=>z in L))throw new Error("sign() legacy options not supported");const{lowS:M,prehash:$,extraEntropy:j}=ci(L,g);E=k(E,$);const D=B(E),_=Nr(i,C),O=[N(_),N(D)];if(j!=null&&j!==!1){const z=j===!0?n(h.secretKey):j;O.push(fe("extraEntropy",z))}const q=ct(...O),H=D;function K(z){const W=A(z);if(!i.isValidNot0(W))return;const X=i.inv(W),G=t.BASE.multiply(W).toAffine(),Y=i.create(G.x);if(Y===yt)return;const se=i.create(X*i.create(H+Y*_));if(se===yt)return;let Ne=(G.x===Y?0:2)|Number(G.y&Ur),Fe=se;return M&&y(se)&&(Fe=i.neg(se),Ne^=1),new v(Y,Fe,Ne)}return{seed:q,k2sig:K}}function S(E,C,L={}){E=fe("message",E);const{seed:M,k2sig:$}=x(E,C,L);return Dw(e.outputLen,i.BYTES,o)(M,$)}function R(E){let C;const L=typeof E=="string"||so(E),M=!L&&E!==null&&typeof E=="object"&&typeof E.r=="bigint"&&typeof E.s=="bigint";if(!L&&!M)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(M)C=new v(E.r,E.s);else if(L){try{C=v.fromBytes(fe("sig",E),"der")}catch($){if(!($ instanceof mt.Err))throw $}if(!C)try{C=v.fromBytes(fe("sig",E),"compact")}catch{return!1}}return C||!1}function P(E,C,L,M={}){const{lowS:$,prehash:j,format:D}=ci(M,g);if(L=fe("publicKey",L),C=k(fe("message",C),j),"strict"in M)throw new Error("options.strict was renamed to lowS");const _=D===void 0?R(E):v.fromBytes(fe("sig",E),D);if(_===!1)return!1;try{const O=t.fromBytes(L);if($&&_.hasHighS())return!1;const{r:q,s:H}=_,K=B(C),z=i.inv(H),W=i.create(K*z),X=i.create(q*z),G=t.BASE.multiplyUnsafe(W).add(O.multiplyUnsafe(X));return G.is0()?!1:i.create(G.x)===q}catch{return!1}}function b(E,C,L={}){const{prehash:M}=ci(L,g);return C=k(C,M),v.fromBytes(E,"recovered").recoverPublicKey(C).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h,Point:t,sign:S,verify:P,recoverPublicKey:b,Signature:v,hash:e})}function mb(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp;let n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0;const o=pr(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),s={Fp:r,Fn:o,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function wb(t){const{CURVE:e,curveOpts:r}=mb(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}function yb(t,e){const r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,mf(r.Fn.ORDER,r.Fn.BITS))})}function bb(t){const{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:o}=wb(t),s=hb(e,r),i=gb(s,n,o);return yb(t,i)}function vb(t,e){const r=n=>bb({...t,hash:n});return{...r(e),create:r}}const gc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},xb={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Bl=BigInt(2);function Sb(t){const e=gc.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,u=ue(d,r,e)*d%e,f=ue(u,r,e)*d%e,h=ue(f,Bl,e)*l%e,g=ue(h,o,e)*h%e,m=ue(g,s,e)*g%e,y=ue(m,a,e)*m%e,w=ue(y,c,e)*y%e,I=ue(w,a,e)*m%e,v=ue(I,r,e)*d%e,A=ue(v,i,e)*g%e,B=ue(A,n,e)*l%e,T=ue(B,Bl,e);if(!ma.eql(ma.sqr(T),t))throw new Error("Cannot find square root");return T}const ma=pr(gc.p,{sqrt:Sb}),zt=vb({...gc,Fp:ma,lowS:!0,endo:xb},nf);function Eb(t,e,r){const n=tc.digest(e instanceof Uint8Array?e:e.subarray());if(Ns(n))return n.then(({digest:o})=>(r?.signal?.throwIfAborted(),zt.sign(o,t).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new Rl(String(o))});try{return zt.sign(n.digest,t).toDERRawBytes()}catch(o){throw new Rl(String(o))}}function Ab(t,e,r,n){const o=tc.digest(r instanceof Uint8Array?r:r.subarray());if(Ns(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),zt.verify(e,s,t))).catch(s=>{throw s.name==="AbortError"?s:new Tl(String(s))});try{return n?.signal?.throwIfAborted(),zt.verify(e,o.digest,t)}catch(s){throw new Tl(String(s))}}class Hf{type="secp256k1";raw;_key;constructor(e){this._key=Tb(e),this.raw=Cb(this._key)}toMultihash(){return no.digest(Ds(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return Le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:rt(this.raw,e.raw)}verify(e,r,n){return Ab(this._key,r,e,n)}}class kb{type="secp256k1";raw;publicKey;constructor(e,r){this.raw=Rb(e),this.publicKey=new Hf(r??Pb(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:rt(this.raw,e.raw)}sign(e,r){return Eb(this.raw,e,r)}}function Ib(t){return new kb(t)}function qf(t){return new Hf(t)}function Cb(t){return zt.ProjectivePoint.fromHex(t).toRawBytes(!0)}function Rb(t){try{return zt.getPublicKey(t,!0),t}catch(e){throw new Du(String(e))}}function Tb(t){try{return zt.ProjectivePoint.fromHex(t),t}catch(e){throw new _u(String(e))}}function Pb(t){try{return zt.getPublicKey(t,!0)}catch(e){throw new Du(String(e))}}async function Nb(t,e){return vy()}function wa(t,e){const{Type:r,Data:n}=ar.decode(t),o=n??new Uint8Array;switch(r){case le.RSA:return nb(o,e);case le.Ed25519:return Cf(o);case le.secp256k1:return qf(o);case le.ECDSA:return Xu(o);default:throw new Is}}function Lb(t){const{Type:e,Data:r}=ar.decode(t.digest),n=r??new Uint8Array;switch(e){case le.Ed25519:return Cf(n);case le.secp256k1:return qf(n);case le.ECDSA:return Xu(n);default:throw new Is}}function Ds(t){return ar.encode({Type:le[t.type],Data:t.raw})}function Bb(t){const e=os.decode(t),r=e.Data??new Uint8Array;switch(e.Type){case le.RSA:return tb(r);case le.Ed25519:return by(r);case le.secp256k1:return Ib(r);case le.ECDSA:return lw(r);default:throw new Is}}function _b(t){return os.encode({Type:le[t.type],Data:t.raw})}const Kf=Symbol.for("nodejs.util.inspect.custom"),Db=114;class mc{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ou]=!0;toString(){return this.string==null&&(this.string=Le.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ce.createV1(Db,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return rt(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return rt(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Kf](){return`PeerId(${this.toString()})`}}class zf extends mc{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class Vf extends mc{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class Wf extends mc{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}const Ob=2336;class Gf{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=no.digest(we(this.url))}[Kf](){return`PeerId(${this.url})`}[Ou]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ce.createV1(Ob,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=J(e)),e.toString()===this.toString())}}const Fb=114,_l=2336;function Mb(t,e){let r;if(t.charAt(0)==="1"||t.charAt(0)==="Q")r=ju(Le.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return jb(ce.parse(t));throw new tt('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return Xf(r)}function Zr(t){if(t.type==="Ed25519")return new Vf({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new Wf({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new zf({multihash:t.toCID().multihash,publicKey:t});throw new Is}function Xf(t){if($b(t))return new zf({multihash:t});if(Ub(t))try{const e=Lb(t);if(e.type==="Ed25519")return new Vf({multihash:t,publicKey:e});if(e.type==="secp256k1")return new Wf({multihash:t,publicKey:e})}catch{const r=J(t.digest);return new Gf(new URL(r))}throw new xg("Supplied PeerID Multihash is invalid")}function jb(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==Fb&&t.code!==_l)throw new vg("Supplied PeerID CID is invalid");if(t.code===_l){const e=J(t.multihash.digest);return new Gf(new URL(e))}return Xf(t.multihash)}function Ub(t){return t.code===no.code}function $b(t){return t.code===tc.code}class Yf extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}}class Hb extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class gn extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}class Dl extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}}class qb extends Event{data;constructor(e,r){super("message",r),this.data=e}}class wc extends Event{error;local;constructor(e,r,n){super("close",n),this.error=r,this.local=e}}class Kb extends wc{constructor(e,r){super(!0,e,r)}}class zb extends wc{constructor(e,r){super(!1,e,r)}}const Vb=t=>t/2**32|0,Wb=t=>t>>>0;function Gb(t,e,r,n){const o=Vb(r),s=Wb(r);t.setUint32(e,n?s:o,n),t.setUint32(e+4,n?o:s,n)}function ya(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const ba=t=>t?`"${t}" `:"";function It(t,e=""){if(typeof t!="number")throw new TypeError(ba(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(ba(e)+"expected integer >= 0, got "+t);return t}function Ct(t,e,r=""){if(ya(t)&&(e===void 0||t.length===e))return t;e!==void 0&&It(e,"length");const n=ya(t),o=e!==void 0?` of length ${e}`:"",s=n?`length=${t.length}`:`type=${typeof t}`,i=ba(r)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}function yc(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(It(t.outputLen),It(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}const Xb=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)},Ol=(t,e)=>{Xb(t,e);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(t,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function ss(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function Zf(t,e){Ct(t,void 0,"output");const r=e.outputLen;if(!(t.length>=r))throw new RangeError('"output" expected length >= '+r)}function jk(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function nr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function li(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function it(t,e){return t<<32-e|t>>>e}function Uk(t,e){return t<<e|t>>>32-e>>>0}const Yb=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Zb(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Jb(t){for(let e=0;e<t.length;e++)t[e]=Zb(t[e]);return t}const $k=Yb?t=>t:Jb,Jf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qb=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function bc(t){if(Ct(t),Jf)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Qb[t[r]];return e}function Fl(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function Qf(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Jf)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}const e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){const i=Fl(t.charCodeAt(s)),a=Fl(t.charCodeAt(s+1));if(i===void 0||a===void 0){const c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function e0(t){const e=globalThis;if(typeof e.scheduler?.yield=="function"){const r=e.scheduler.yield();return t&&r.catch(t),r}return new Promise(r=>e.setTimeout(r,0))}async function Hk(t,e,r,n){if(It(t,"iters"),It(e,"tick"),typeof r!="function")throw new TypeError("callback must be a function");let o=Date.now();for(let s=0;s<t;s++){r(s);const i=Date.now()-o;i>=0&&i<e||(await e0(n),o=Date.now())}}function t0(t){if(typeof t!="string")throw new TypeError("string expected");const e=new TextEncoder().encode(t);try{return new Uint8Array(e)}finally{nr(e)}}function qk(t,e=""){return typeof t=="string"?t0(t):Ct(t,void 0,e)}function r0(t,e,r="opts"){return Ol(t,"defaults"),e!==void 0&&Ol(e,r),Object.assign(Object.create(null),t,e)}function n0(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=r0({},e,"info");const r=(o,s)=>t(s).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function o0(t=32){It(t,"bytesLength");const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}const s0=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function i0(t,e,r){return t&e^~t&r}function a0(t,e,r){return t&e^t&r^e&r}class c0{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,o){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=li(this.buffer)}update(e){ss(this),Ct(e);const{view:r,buffer:n,blockLen:o}=this,s=e.length;let i=!1;for(let a=0;a<s;){const c=Math.min(o-this.pos,s-a);if(c===o){const l=li(e);for(;o<=s-a;a+=o)this.process(l,a);i=!0;continue}n.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(r,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){ss(this),Zf(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:o,isLE:s}=this;let{pos:i}=this;r[i++]=128,r.fill(0,i),this.padOffset>o-i&&(this.process(n,0),r.fill(0)),Gb(n,o-8,this.length*8,s),this.process(n,0),this.roundClean();const a=e===r?n:li(e),c=this.outputLen,l=c/4,d=this.get();if(c%4||l>d.length)throw new Error("invalid outputLen");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneIntoMeta(e){const{buffer:r,length:n,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=n,e.pos=i,i&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const l0=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),d0=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Dt=new Uint32Array(64);class u0 extends c0{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,r){super(64,e,8,!1),this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){const{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,r){for(let u=0;u<16;u++,r+=4)Dt[u]=e.getUint32(r,!1);for(let u=16;u<64;u++){const f=Dt[u-15],h=Dt[u-2],g=it(f,7)^it(f,18)^f>>>3,m=it(h,17)^it(h,19)^h>>>10;Dt[u]=m+Dt[u-7]+g+Dt[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=it(a,6)^it(a,11)^it(a,25),h=d+f+i0(a,c,l)+d0[u]+Dt[u]|0,m=(it(n,2)^it(n,13)^it(n,22))+a0(n,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,l,d)}roundClean(){nr(Dt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),nr(this.buffer)}}class f0 extends u0{constructor(){super(32,l0)}}const di=n0(()=>new f0,s0(1));function eh(t,e,r=()=>{}){if(!Array.isArray(t))throw new TypeError(`"${e}" expected array, got type=${typeof t}`);for(let n=0;n<t.length;n++)r(t[n],`${e}[${n}]`);return t}const $r=(t,e,r)=>Ct(t,e,r),th=It;function Hr(t,e="object"){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`);return t}function Mn(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}const h0=bc,p0=t=>Qf(t),rh=ya,nh=t=>o0(t),is=BigInt(0),Ml=BigInt(1),g0=t=>t?`"${t}" `:"";function Os(t,e=""){if(typeof t!="boolean")throw new TypeError(g0(e)+"expected boolean, got type="+typeof t);return t}function m0(t){if(typeof t=="bigint"){if(!or(t))throw new RangeError("positive bigint expected, got "+t)}else th(t);return t}function va(t,e=""){if(typeof t!="number"){const r=e&&`"${e}" `;throw new TypeError(r+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){const r=e&&`"${e}" `;throw new RangeError(r+"expected safe integer, got "+t)}}function oh(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?is:BigInt("0x"+t)}function sh(t){return oh(bc(t))}function as(t){return oh(bc(Gn(Ct(t)).reverse()))}function ih(t,e){if(It(e),e===0)throw new Error("zero output length is invalid");t=m0(t);const r=e*2,n=t.toString(16);if(n.length>r)throw new RangeError("number is too large");return Qf(n.padStart(r,"0"))}function ah(t,e){return ih(t,e).reverse()}function Gn(t){return Uint8Array.from($r(t))}function or(t){return typeof t=="bigint"&&is<=t}function ch(t,e,r){return or(t)&&or(e)&&or(r)&&e<=t&&t<r}function jn(t,e,r,n){if(!ch(e,r,n))throw new RangeError("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function w0(t){if(t<is)throw new Error("expected non-negative bigint, got "+t);return t===is?0:t.toString(2).length}const y0=t=>(va(t,"n"),(Ml<<BigInt(t))-Ml);function cs(t,e={},r={},n="object"){Hr(t,n),Hr(e,"fields"),Hr(r,"optFields");function o(i,a,c){const l=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,d=t[i];if(!Object.hasOwn(t,i)&&(c?d!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&d===void 0)return;const u=typeof d;if(u!==a||d===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${u}`)}const s=(i,a)=>Object.entries(i).forEach(([c,l])=>o(c,l,a));s(e,!1),s(r,!0)}const xe=BigInt(0),ae=BigInt(1),Qt=BigInt(2),lh=BigInt(3),vc=BigInt(4),dh=BigInt(5),b0=BigInt(7),uh=BigInt(8),v0=BigInt(9),x0=BigInt(15),fh=BigInt(16),S0=BigInt("0x10000000000000000");function ie(t,e){if(e<=xe)throw new Error("mod: expected positive modulus, got "+e);const r=t%e;return r>=xe?r:e+r}function E0(t,e,r){if(r<=ae)throw new Error("pow: expected modulus > 1, got "+r);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<xe)throw new Error("invalid exponent, negatives unsupported");if(e===xe)return ae;if(e===ae)return t;let n=t%r;if(n<xe&&(n+=r),e<S0){let a=ae;for(;e>xe;)e&ae&&(a=a*n%r),n=n*n%r,e>>=ae;return a}const o=[];for(;e>xe;)o.push(Number(e&x0)),e>>=vc;const s=new Array(16);s[0]=ae,s[1]=n;for(let a=2;a<16;a++)s[a]=s[a-1]*n%r;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%r,i=i*i%r,i=i*i%r,i=i*i%r;const c=o[a];c!==0&&(i=i*s[c]%r)}return i}function Je(t,e,r){if(r<=ae)throw new Error("pow2: expected modulus > 1, got "+r);if(e<xe)throw new Error("pow2: expected non-negative exponent, got "+e);let n=t;for(;e-- >xe;)n*=n,n%=r;return n}function jl(t,e){if(t===xe)throw new Error("invert: expected non-zero number");if(e<=ae)throw new Error("invert: expected modulus > 1, got "+e);let r=ie(t,e),n=e,o=xe,s=ae;for(;r!==xe;){const a=n/r,c=n-r*a,l=o-s*a;n=r,r=c,o=s,s=l}if(n!==ae)throw new Error("invert: does not exist");return ie(o,e)}function xc(t,e,r){const n=t;if(!n.eql(n.sqr(e),r))throw new Error("Cannot find square root")}function Sc(t,e){if((t&ae)===xe)throw new Error(e+": expected odd modulus, got "+t)}function hh(t,e){const r=t,n=(r.ORDER+ae)/vc,o=r.pow(e,n);return xc(r,o,e),o}function A0(t,e){const r=t,n=(r.ORDER-dh)/uh,o=r.mul(e,Qt),s=r.pow(o,n),i=r.mul(e,s),a=r.mul(r.mul(i,Qt),s),c=r.mul(i,r.sub(a,r.ONE));return xc(r,c,e),c}function k0(t){const e=Ec(t),r=ph(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+b0)/fh;return((a,c)=>{const l=a;let d=l.pow(c,i),u=l.mul(d,n);const f=l.mul(d,o),h=l.mul(d,s),g=l.eql(l.sqr(u),c),m=l.eql(l.sqr(f),c);d=l.cmov(d,u,g),u=l.cmov(h,f,m);const y=l.eql(l.sqr(u),c),w=l.cmov(d,u,y);return xc(l,w,c),w})}function ph(t){if(t<lh)throw new Error("sqrt is not defined for small field");Sc(t,"tonelliShanks");let e=t-ae,r=0;for(;e%Qt===xe;)e/=Qt,r++;let n=Qt;const o=Ec(t);for(;ls(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return hh;let s=o.pow(n,e);const i=(e+ae)/Qt;return function(c,l){const d=c;if(d.is0(l))return l;if(ls(d,l)!==1)throw new Error("Cannot find square root");let u=r,f=d.mul(d.ONE,s),h=d.pow(l,e),g=d.pow(l,i);for(;!d.eql(h,d.ONE);){if(d.is0(h))throw new Error("Cannot find square root: probably non-prime P");let m=1,y=d.sqr(h);for(;!d.eql(y,d.ONE);)if(m++,y=d.sqr(y),m===u)throw new Error("Cannot find square root");const w=ae<<BigInt(u-m-1),I=d.pow(f,w);u=m,f=d.sqr(I),h=d.mul(h,f),g=d.mul(g,I)}return g}}function I0(t){return Sc(t,"Fp.sqrt"),t%vc===lh?hh:t%uh===dh?A0:t%fh===v0?k0(t):ph(t)}const C0=(t,e)=>(ie(t,e)&ae)===ae,R0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Xn(t){if(Hr(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);va(t.BYTES,"BYTES"),va(t.BITS,"BITS");for(const e of R0)Mn(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=ae)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function gh(t,e,r=!1){Xn(t),eh(e,"nums"),Os(r,"passZero");const n=t,o=new Array(e.length).fill(r?n.ZERO:void 0),s=e.reduce((a,c,l)=>n.is0(c)?a:(o[l]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,l)=>n.is0(c)?a:(o[l]=n.mul(a,o[l]),n.mul(a,c)),i),o}function ls(t,e){Xn(t);const r=t;Sc(r.ORDER,"FpLegendre");const n=(r.ORDER-ae)/Qt,o=r.pow(e,n),s=r.eql(o,r.ONE),i=r.eql(o,r.ZERO),a=r.eql(o,r.neg(r.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function T0(t,e){if(e!==void 0&&th(e),t<=xe)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);const r=w0(t);if(e!==void 0&&e<r)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${r})`);const n=e!==void 0?e:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}const Ul=new WeakMap;class $l{ORDER;BITS;BYTES;isLE;ZERO=xe;ONE=ae;_lengths;_mod;constructor(e,r={}){if(e<=ae)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));const{nBitLength:o,nByteLength:s}=T0(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return ie(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return xe<=e&&e<this.ORDER}is0(e){return e===xe}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ae)===ae}neg(e){return ie(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return ie(e*e,this.ORDER)}add(e,r){return ie(e+r,this.ORDER)}sub(e,r){return ie(e-r,this.ORDER)}mul(e,r){return ie(e*r,this.ORDER)}pow(e,r){return E0(e,r,this.ORDER)}div(e,r){return ie(e*jl(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return jl(e,this.ORDER)}sqrt(e){let r=Ul.get(this);return r||Ul.set(this,r=I0(this.ORDER)),r(this,e)}toBytes(e){return this.isLE?ah(e,this.BYTES):ih(e,this.BYTES)}fromBytes(e,r=!1){$r(e);const{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);const l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?as(e):sh(e);if(a&&(c=ie(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return gh(this,e,!0)}cmov(e,r,n){return Os(n,"condition"),n?r:e}}function Ec(t,e={}){return Object.freeze($l.prototype),new $l(t,e)}const Ac=BigInt(0),Yn=BigInt(1),P0=BigInt(4),ui=16,Hl=128,N0=5,ql=2**31;function kc(t){const e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);Mn(e.fromAffine,"Point.fromAffine"),Mn(e.fromBytes,"Point.fromBytes"),Mn(e.fromHex,"Point.fromHex"),Hr(e.BASE,"Point.BASE"),Hr(e.ZERO,"Point.ZERO"),Xn(e.Fp),Xn(e.Fn)}function L0(t,e){kc(t),mh(e,t);const r=gh(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function B0(t,e,r=1){if(!Number.isSafeInteger(t)||t<r||t>e)throw new Error("invalid window size, expected ["+r+".."+e+"], got W="+t)}function _0(t,e){const r=t*(4*e+128);if(r>ql)throw new Error("invalid window size: table would need ~"+Math.ceil(r/2**20)+" MiB, max "+ql/2**20+" MiB")}function D0(t,e){if(t!==void 0){Mn(t,"randomBytes");try{const r=t(e);if(!rh(r)||r.length!==e)return}catch{return}return t}}function mh(t,e){eh(t,"points"),t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function O0(t,e,r){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,o)=>{if(!(r===void 0?e.isValid(n):or(n)&&n<r))throw new Error("invalid scalar at index "+o)})}const wh=new WeakMap;function fi(t){return wh.get(t)||1}function F0(t,e){const r=t.double(),n=[t];for(let o=1;o<e;o++)n.push(n[o-1].add(r));return n}function M0(t,e){const r=2**e,n=r/2,o=BigInt(r-1),s=[];for(;t>Ac;){let i=0;t&Yn&&(i=Number(t&o),i>=n&&(i-=r),t-=BigInt(i)),s.push(i),t>>=Yn}return s}function j0(t,e,r){const n=2**e,o=n/2,s=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<r;c++){let l=Number(t&s);t>>=i,l>o&&(l-=n,t+=Yn),a.push(l)}if(t!==Ac)throw new Error("invalid wnaf");return a}function U0(t,e,r){let n=0;for(const s of r)n=Math.max(n,s.length);let o=t;for(let s=n-1;s>=0;s--){s!==n-1&&(o=o.double());for(let i=0;i<r.length;i++){const a=r[i][s];if(a){const c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}class $0{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,r){kc(e),this.randomBytes=D0(r,ui),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,r,n){const o=Math.ceil(n/r)+1,s=2**(r-1),i=[];let a=e;for(let c=0;c<o;c++){let l=a;for(let d=0;d<s;d++)i.push(l),l=l.add(a);a=i[i.length-1].double()}return{W:r,bits:n,windows:o,comp:i}}wnafCachedCT(e,r){const{W:n,windows:o,comp:s}=e,i=2**(n-1),a=j0(r,n,o);let c=this.ZERO,l=this.BASE;for(let d=0;d<o;d++){const u=a[d],f=d*i,h=Math.abs(u)-1;let g=s[f];for(let y=1;y<i;y++)g=y===h?s[f+y]:g;const m=g.negate();u===0?l=l.add(s[f]):c=c.add(u<0?m:g)}return{p:c,f:l}}getWnafPrecomputes(e,r,n,o){let s=this.wnafPrecomputes.get(r),i=s?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(r,e,n),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(r,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,r){if(this.assertPoint(e),!ch(r,Yn,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,r,n,o){const s=fi(e);return s===1?this.fixedWindowCT(e,r,n):this.wnafCachedCT(this.getWnafPrecomputes(s,e,n,o),r)}mulCT(e,r,n){return this.validateMulInput(e,r),this.runCT(e,r,this.bits,n)}mulCTBlinded(e,r,n){if(this.validateMulInput(e,r),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");const o=this.Point.Fn.BITS+Hl,s=this.randomBytes(ui);if(!rh(s)||s.length!==ui)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;const i=r+sh(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,n)}fixedWindowCT(e,r,n){const o=N0,s=1<<o,i=y0(o),a=new Array(s);a[0]=this.ZERO;for(let d=1;d<s;d++)a[d]=a[d-1].add(e);const c=Math.ceil(n/o);let l=this.ZERO;for(let d=c-1;d>=0;d--){if(d!==c-1)for(let h=0;h<o;h++)l=l.double();const u=Number(r>>BigInt(d*o)&i);let f=a[0];for(let h=1;h<s;h++)f=h===u?a[h]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(e,r){return this.randomBytes===void 0?!1:r===Yn?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,r,n,o){return this.shouldBlind(e,n)?this.mulCTBlinded(e,r,o):this.mulCT(e,r,o)}mulUnsafe(e,r,n){if(this.assertPoint(e),!or(r))throw new Error("invalid scalar");const o=fi(e);if(o===1||r>=this.Point.Fn.ORDER)return H0(this.Point,[e],[r],!0);const s=this.getWnafPrecomputes(o,e,this.bits,n);return this.wnafCachedCT(s,r).p}setWindowSize(e,r){this.assertPoint(e),B0(r,this.bits);const n=Math.ceil((this.bits+Hl)/r)+1;_0(n*2**(r-1),this.Point.Fp.BYTES),wh.set(e,r),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return fi(e)!==1}}function H0(t,e,r,n=!1){if(kc(t),mh(e,t),Os(n,"allowOversized"),O0(r,t.Fn,n?t.Fn.ORDER**P0:void 0),e.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const o=e.map(i=>F0(i,4)),s=r.map(i=>M0(i,4));return U0(t.ZERO,o,s)}function Kl(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Xn(e),e}else return Ec(t,{isLE:r})}function q0(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);cs(r);for(const c of["p","n","h"]){const l=e[c];if(!(or(l)&&l!==Ac))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Kl(e.p,r.Fp,n),s=Kl(e.n,r.Fn,n),a=["Gx","Gy","a","d"];for(const c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function K0(t,e){return function(n){const o=t(n);return{secretKey:o,publicKey:e(o)}}}const Ao=BigInt(0),ko=BigInt(1),Io=BigInt(2),z0=BigInt(4),zl=BigInt(8);function V0(t,e,r,n){const o=t.sqr(r),s=t.sqr(n),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function W0(t,e={}){cs(e,{},{},"extraOpts");const r=e,n=q0("edwards",t,r,r.FpFnLE),{Fp:o,Fn:s}=n;let i=n.CURVE;const{h:a}=i;if(ls(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(ls(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");cs(r,{},{uvRatio:"function",randomBytes:"function"});const c=r.randomBytes===void 0?nh:r.randomBytes,l=Io<<BigInt(o.BYTES*8)-ko;function d(I){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(I)}const u=r.uvRatio===void 0?(I,v)=>{try{return{isValid:!0,value:o.sqrt(o.div(I,v))}}catch{return{isValid:!1,value:Ao}}}:r.uvRatio;if(!V0(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");const f=o.eql(i.a,o.neg(o.ONE))?I=>o.neg(I):o.eql(i.a,o.ONE)?I=>I:I=>o.mul(i.a,I);function h(I,v,A=!1){const B=A?ko:Ao;return jn("coordinate "+I,v,B,l),v}function g(I){if(!(I instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(i.Gx,i.Gy,o.ONE,o.mul(i.Gx,i.Gy));static ZERO=new m(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(v,A,B,T){this.X=h("x",v),this.Y=h("y",A),this.Z=h("z",B,!0),this.T=h("t",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(v){if(v instanceof m)throw new Error("extended point not allowed");const{x:A,y:B}=v||{};return h("x",A),h("y",B),new m(A,B,o.ONE,o.mul(A,B))}static fromBytes(v,A=!1){const B=o.BYTES,{a:T,d:N}=i;v=Gn($r(v,B,"point")),Os(A,"zip215");const k=Gn(v),x=v[B-1];k[B-1]=x&-129;const S=as(k),R=A?l:o.ORDER;jn("point.y",S,Ao,R);const P=o.sqr(S),b=o.sub(P,o.ONE),E=o.sub(o.mulN(N,P),T);let{isValid:C,value:L}=u(b,E);if(!C)throw new Error("bad point: invalid y coordinate");const M=d(L),$=(x&128)!==0;if(!A&&o.is0(L)&&$)throw new Error("bad point: x=0 and x_0=1");return $!==M&&(L=o.neg(L)),m.fromAffine({x:L,y:S})}static fromHex(v,A=!1){return m.fromBytes(p0(v),A)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=6,A=!0){return w.setWindowSize(this,v),A||this.multiply(Io),this}assertValidity(){const v=this,{a:A,d:B}=i;if(v.is0())throw new Error("bad point: ZERO");const{X:T,Y:N,Z:k,T:x}=v,S=o.sqr(T),R=o.sqr(N),P=o.sqr(k),b=o.sqr(P),E=o.mul(S,A),C=o.mul(o.add(E,R),P),L=o.add(b,o.mul(B,o.mul(S,R)));if(!o.eql(C,L))throw new Error("bad point: equation left != right (1)");const M=o.mul(T,N),$=o.mul(k,x);if(!o.eql(M,$))throw new Error("bad point: equation left != right (2)")}equals(v){g(v);const{X:A,Y:B,Z:T}=this,{X:N,Y:k,Z:x}=v,S=o.mul(A,x),R=o.mul(N,T),P=o.mul(B,x),b=o.mul(k,T);return o.eql(S,R)&&o.eql(P,b)}is0(){return this.equals(m.ZERO)}negate(){return new m(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){const{X:v,Y:A,Z:B}=this,T=o.sqr(v),N=o.sqr(A),k=o.mul(o.sqr(B),Io),x=f(T),S=o.addN(v,A),R=o.sub(o.subN(o.sqr(S),T),N),P=o.addN(x,N),b=o.subN(P,k),E=o.subN(x,N),C=o.mul(R,b),L=o.mul(P,E),M=o.mul(R,E),$=o.mul(b,P);return new m(C,L,$,M)}add(v){g(v);const{d:A}=i,{X:B,Y:T,Z:N,T:k}=this,{X:x,Y:S,Z:R,T:P}=v,b=o.mul(B,x),E=o.mul(T,S),C=o.mul(o.mulN(k,A),P),L=o.mul(N,R),M=o.sub(o.subN(o.mulN(o.addN(B,T),o.addN(x,S)),b),E),$=o.subN(L,C),j=o.addN(L,C),D=o.sub(E,f(b)),_=o.mul(M,$),O=o.mul(j,D),q=o.mul(M,D),H=o.mul($,j);return new m(_,O,H,q)}subtract(v){return g(v),this.add(v.negate())}multiply(v){if(!s.isValidNot0(v))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");const{p:A,f:B}=w.mulSecret(this,v,a,y);return y([A,B])[0]}multiplyUnsafe(v){if(!s.isValid(v))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return v===Ao?m.ZERO:this.is0()||v===ko?this:w.mulUnsafe(this,v,y)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.mulUnsafe(this,i.n).is0()}toAffine(v){const A=this;let B=v;if(B!=null&&typeof B!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof B);const{X:T,Y:N,Z:k}=A,x=A.is0();B==null&&(B=x?o.create(zl):o.inv(k));const S=o.mul(T,B),R=o.mul(N,B),P=o.mul(k,B);if(x)return{x:o.ZERO,y:o.ONE};if(!o.eql(P,o.ONE))throw new Error("invZ was invalid");return{x:S,y:R}}clearCofactor(){return a===ko?this:a===Io?this.double():a===z0?this.double().double():a===zl?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){const{x:v,y:A}=this.toAffine(),B=o.toBytes(A);return B[B.length-1]|=d(v)?128:0,B}toHex(){return h0(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const y=I=>L0(m,I),w=new $0(m,c);return w.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}const Gt=BigInt(0),ze=BigInt(1),Co=BigInt(2);function Vl(t,e){return t+e-(e>>ze<<ze)}function G0(t){const e=BigInt(6)*t;return(r,n,o)=>{const s=n+o,a=((e+o-n)*r+n)%t;return{x_2:a,x_3:s-a}}}function X0(t){return cs(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...t})}function Y0(t){const e=X0(t),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=e.scalarMultBase,c=n==="x25519";if(!c&&n!=="x448")throw new Error("invalid type");const l=i===void 0?nh:i,d=c?255:448,u=G0(r),f=c?32:56,h=BigInt(c?9:5),g=BigInt(c?121665:39081),m=c?Co**BigInt(254):Co**BigInt(447),y=c?BigInt(8)*(Co**BigInt(251)-ze):BigInt(4)*(Co**BigInt(445)-ze),w=m+y+ze,I=L=>ie(L,r),v=A(h);function A(L){return ah(I(L),f)}function B(L){const M=Gn($r(L,f,"uCoordinate"));return c&&(M[31]&=127),I(as(M))}function T(L){return as(o(Gn($r(L,f,"scalar"))))}const N=new Set(c?[Gt,ze,r-ze,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[Gt,ze,r-ze]);function k(L,M){const $=B(M);if(N.has($))throw new Error("invalid private or public key received");const j=P($,T(L));if(j===Gt)throw new Error("invalid private or public key received");return A(j)}function x(L){if(a===void 0)return k(L,v);const M=T(L);jn("scalar",M,m,w);const $=I(a(M));if($===Gt)throw new Error("invalid private or public key received");return A($)}const S=x,R=k;function P(L,M){jn("u",L,Gt,r),jn("scalar",M,m,w);const $=M,j=L;let D=ze,_=Gt,O=L,q=ze;const H=$^$>>ze;for(let W=BigInt(d-1);W>=Gt;W--){const X=Vl(r,H>>W);({x_2:D,x_3:O}=u(X,D,O)),{x_2:_,x_3:q}=u(X,_,q);const G=D+_,Y=I(G*G),se=D-_,Ne=I(se*se),Fe=Y-Ne,oe=O+q,ot=O-q,vr=I(ot*G),Tt=I(oe*se),Xe=vr+Tt,uo=vr-Tt;O=I(Xe*Xe),q=I(j*I(uo*uo)),D=I(Y*Ne),_=I(Fe*(Y+I(g*Fe)))}const K=Vl(r,$);({x_2:D,x_3:O}=u(K,D,O)),{x_2:_,x_3:q}=u(K,_,q);const z=s(_);return I(D*z)}const b={secretKey:f,publicKey:f,seed:f},E=L=>(L=L===void 0?l(f):L,$r(L,b.seed,"seed"),L),C={randomSecretKey:E};return Object.freeze(b),Object.freeze(C),Object.freeze({keygen:K0(E,S),getSharedSecret:R,getPublicKey:S,scalarMult:k,scalarMultBase:x,utils:C,GuBytes:v.slice(),lengths:b})}const Wl=BigInt(0),Z0=BigInt(1),Gl=BigInt(2),J0=BigInt(3),Q0=BigInt(5),ev=BigInt(8),Fs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),tv={p:Fs,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ev,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function yh(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=Fs,a=t*t%s*t%s,c=Je(a,Gl,s)*a%s,l=Je(c,Z0,s)*t%s,d=Je(l,Q0,s)*l%s,u=Je(d,e,s)*d%s,f=Je(u,r,s)*u%s,h=Je(f,n,s)*f%s,g=Je(h,o,s)*h%s,m=Je(g,o,s)*h%s,y=Je(m,e,s)*d%s;return{pow_p_5_8:Je(y,Gl,s)*t%s,b2:a}}function rv(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Xl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function nv(t,e){const r=Fs,n=ie(e*e*e,r),o=ie(n*n*e,r),s=yh(t*o).pow_p_5_8;let i=ie(t*n*s,r);const a=ie(e*i*i,r),c=i,l=ie(i*Xl,r),d=a===t,u=a===ie(-t,r),f=a===ie(-t*Xl,r);return d&&(i=c),(u||f)&&(i=l),C0(i,r)&&(i=ie(-i,r)),{isValid:d||u,value:i}}const Yl=W0(tv,{uvRatio:nv}),Ro=(()=>{const t=Fs,e=r=>{const{pow_p_5_8:n,b2:o}=yh(r);return ie(Je(n,J0,t)*o,t)};return Y0({P:t,type:"x25519",powPminus2:e,adjustScalarBytes:rv,scalarMultBase:r=>{const n=ie(r,Yl.Fn.ORDER);if(n===Wl)return Wl;const o=Yl.BASE.multiply(n);return ie((o.Z+o.Y)*e(ie(o.Z-o.Y,t)),t)}})})();class Zl{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(yc(e),Ct(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),nr(o)}update(e){return ss(this),this.iHash.update(e),this}digestInto(e){ss(this),Zf(e,this),this.finished=!0;const r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});const{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const bh=(()=>{const t=((e,r,n)=>new Zl(e,r).update(n).digest());return t.create=(e,r)=>new Zl(e,r),t})();function Jl(){const t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}class Ql{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}}class hi{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ql(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){const r=this.head;this.head=r.next=new Ql(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){const r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}class ov extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}}function sv(t={}){return iv(r=>{const n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function iv(t,e){e=e??{};let r=e.onEnd,n=new hi,o,s,i,a=Jl();const c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,w)=>{s=I=>{s=null,n.push(I);try{y(t(n))}catch(v){w(v)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Jl()})}},l=y=>s!=null?s(y):(n.push(y),o),d=y=>(n=new hi,s!=null?s({error:y}):(n.push({error:y}),o)),u=y=>{if(i)return o;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},f=y=>i?o:(i=!0,y!=null?d(y):l({done:!0})),h=()=>(n=new hi,f(),{done:!0}),g=y=>(f(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:g,push:u,end:f,get readableLength(){return n.size},onEmpty:async y=>{const w=y?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let I,v;w!=null&&(I=new Promise((A,B)=>{v=()=>{B(new ov)},w.addEventListener("abort",v)}));try{await Promise.race([a.promise,I])}finally{v!=null&&w!=null&&w?.removeEventListener("abort",v)}}},r==null)return o;const m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),r!=null&&(r(y),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:u,end(y){return m.end(y),r!=null&&(r(y),r=void 0),o},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},o}class Ic extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,Ic)}}const ed=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function av(t,e){const{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e;let a,c;const d=new Promise((u,f)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){f(ed(i));return}if(i&&(c=()=>{f(ed(i))},i.addEventListener("abort",c,{once:!0})),t.then(u,f),r===Number.POSITIVE_INFINITY)return;const h=new Ic;a=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(g){f(g)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?u():o instanceof Error?f(o):(h.message=o??`Promise timed out after ${r} milliseconds`,f(h))},r)}).finally(()=>{d.clear(),c&&i&&i.removeEventListener("abort",c)});return d.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},d}const cv=t=>{const e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function lv(t,e,r){let n;const o=new Promise((s,i)=>{if(r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();const a=[e].flat(),c=[],{addListener:l,removeListener:d}=cv(t),u=async(...h)=>{const g=r.multiArgs?h:h[0];if(r.filter)try{if(!await r.filter(g))return}catch(m){n(),i(m);return}c.push(g),r.count===c.length&&(n(),s(c))},f=(...h)=>{n(),i(r.rejectionMultiArgs?h:h[0])};n=()=>{for(const h of a)d(h,u);for(const h of r.rejectionEvents)a.includes(h)||d(h,f)};for(const h of a)l(h,u);for(const h of r.rejectionEvents)a.includes(h)||l(h,f);r.signal&&r.signal.addEventListener("abort",()=>{f(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){const s=av(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function dv(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};const n=lv(t,e,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}class ds extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class uv extends Error{static name="StreamClosedError";name="StreamClosedError"}function fv(t){return t.reason}function vh(t,e,r){if(e==null||t==null)return t;const n=fv;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let o;return Promise.race([t,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}const hv=Math.pow(2,20)*4;class xh extends kg{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??hv,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new re,this.writeBuffer=new re,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);const r=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",r);const n=o=>{this.onDrainPromise?.reject(o.error??new uv)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),vh(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;const e=sv(),r=s=>{e.push(s.data)};this.addEventListener("message",r);const n=s=>{e.end(s.error)};this.addEventListener("close",n);const o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new gn(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new Kb(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new gn("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new gn("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new gn(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new gn(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");const e=new Hb;this.dispatchEvent(new zb(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new wc))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0;const r=this.writeBuffer.byteLength;let n=0;for(;this.writeBuffer.byteLength>0;){const o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}const s=this.writeBuffer.sublist(0,o),i=new re(s);this.writeBuffer.consume(s.byteLength);const a=this.sendData(s);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,r,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}const e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new qb(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Dl(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Dl(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}}const pv=4194304;class td extends Error{static name="UnwrappedError";name="UnwrappedError"}class Sh extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class gv extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class mv extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function wv(t){return typeof t?.closeRead=="function"}function yv(t){return typeof t?.close=="function"}function pi(t){return wv(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:yv(t)?t.status!=="open":!1}function bv(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function vv(t,e){const r=e?.maxBufferSize??pv,n=new re;let o,s=!1;if(!bv(t))throw new Yf("Argument should be a Stream or a Multiaddr");const i=d=>{if(n.append(d.data),n.byteLength>r){const u=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${u} > ${r}`))}o?.resolve()};t.addEventListener("message",i);const a=d=>{d.error!=null?o?.reject(d.error):o?.resolve()};t.addEventListener("close",a);const c=()=>{o?.resolve()};t.addEventListener("remoteCloseWrite",c);const l={readBuffer:n,async read(d){if(s===!0)throw new td("Stream was unwrapped");if(pi(t)){if(d?.bytes==null)return null;if(n.byteLength<d.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,d.bytes),new ds(`Unexpected EOF - stream closed after reading ${n.byteLength}/${d.bytes} bytes`)}const u=d?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=u){o.resolve();break}if(await vh(o.promise,d?.signal),pi(t)){if(n.byteLength===0&&d?.bytes==null)return null;break}o=Promise.withResolvers()}const f=d?.bytes??n.byteLength;if(n.byteLength<f){if(pi(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,f),new ds(`Unexpected EOF - stream closed while reading ${n.byteLength}/${f} bytes`);return l.read(d)}const h=n.sublist(0,f);return n.consume(f),h},async write(d,u){if(s===!0)throw new td("Stream was unwrapped");t.send(d)||await dv(t,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",i),t.removeEventListener("close",a),t.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.push(n))),t}};return l}function rd(t,e={}){const r=vv(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=gr(e.maxDataLength));const n=e?.lengthDecoder??Pf,o=e?.lengthEncoder??Iy;return{async read(i){let a=-1;const c=new re;for(;;){const d=await r.read({...i,bytes:1});if(d==null)break;c.append(d);try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Sh("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new mv(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new gv(`Message length too long - ${a} > ${e.maxDataLength}`);const l=await r.read({...i,bytes:a});if(l==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new ds(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw t.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new ds(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await r.write(new re(o(i.byteLength),i),a)},async writeV(i,a){const c=new re(...i.flatMap(l=>[o(l.byteLength),l]));await r.write(c,a)},unwrap(){return r.unwrap()}}}const xv=1024*1024*4,Sv=1024*1024*4;class Ev{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new re,this.maxBufferSize=e.maxBufferSize??xv,this.maxDataLength=e.maxDataLength??Sv,this.lengthDecoder=e.lengthDecoder??Pf,this.encodingLength=e.encodingLength??gr}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new Yf(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let r;try{r=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(r<0||r>this.maxDataLength)throw new Sh("Invalid message length");const n=this.encodingLength(r),o=n+r;if(this.buffer.byteLength>=o){const s=this.buffer.sublist(n,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}}var Av={};const Zn=65535,nd=Zn-16,co=!!Av?.DUMP_SESSION_KEYS,od=16;function xa(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const us=t=>t?`"${t}" `:"";function Sa(t,e=""){if(typeof t!="boolean")throw new TypeError(us(e)+"expected boolean, got type="+typeof t);return t}function qr(t,e=""){if(typeof t!="number")throw new TypeError(us(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(us(e)+"expected integer >= 0, got "+t);return t}function ve(t,e,r=""){if(xa(t)&&(e===void 0||t.length===e))return t;e!==void 0&&qr(e,"length");const n=xa(t),o=e!==void 0?` of length ${e}`:"",s=n?`length=${t.length}`:`type=${typeof t}`,i=us(r)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}const sd=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`)};function id(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function kv(t,e){ve(t,void 0,"output");const r=e.outputLen;if(!(t.length>=r))throw new RangeError('"output" expected length >= '+r)}function bt(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function qt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Iv(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const Kr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Cv(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Rv(t){for(let e=0;e<t.length;e++)t[e]=Cv(t[e]);return t}const er=Kr?t=>t:Rv;function Tv(t,e){return!t.byteLength||!e.byteLength?!1:t.buffer===e.buffer&&t.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<t.byteOffset+t.byteLength}function Pv(t,e){if(Tv(t,e)&&t.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function Nv(t,e){return sd(t,"defaults"),sd(e,"opts"),Object.assign(t,e)}function Lv(t,e){if(t=ve(t),e=ve(e),t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Bv(t,e,r){const n=e,o=(()=>[]),s=(a,c)=>n(c,...o(a)).update(a).digest(),i=n(new Uint8Array(t),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>n(a,...c),s}const _v=(t,e)=>{function r(n,...o){if(ve(n,void 0,"key"),t.nonceLength!==void 0){const u=o[0];ve(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}const s=t.tagLength,i=t.nonceLength!==void 0?1:0;if(!t.withAAD){for(let u=i;u<o.length;u++)if(xa(o[u]))throw new Error("AAD not supported")}t.withAAD&&o[i]!==void 0&&ve(o[i],void 0,"AAD");const a=e(n,...o),c=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");ve(f,void 0,"output")}};let l=!1;return{encrypt(u,f){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,ve(u,void 0,"data"),c(a.encrypt.length,f),a.encrypt(u,f)},decrypt(u,f){if(ve(u,void 0,"data"),s&&u.length<s)throw new Error('"ciphertext" expected length >= tagLength='+s);return c(a.decrypt.length,f),a.decrypt(u,f)}}}return Object.assign(r,t),r};function Ea(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(ve(e,t,"output"),r&&!fs(e))throw new Error("invalid output, must be aligned");return e}function Dv(t,e,r){qr(t),qr(e),Sa(r);const n=new Uint8Array(16),o=Iv(n);return o.setBigUint64(0,BigInt(e),r),o.setBigUint64(8,BigInt(t),r),n}function fs(t){return t.byteOffset%4===0}function hs(t){return Uint8Array.from(ve(t))}const Eh=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),Ov=er(bt(Eh("expand 16-byte k"))),Fv=er(bt(Eh("expand 32-byte k")));function ee(t,e){return t<<e|t>>>32-e}const mn=64,Mv=16,Aa=2**32-1,ad=Uint32Array.of();function jv(t,e,r,n,o,s,i,a){const c=o.length,l=new Uint8Array(mn),d=bt(l),u=Kr&&fs(o)&&fs(s),f=u?bt(o):ad,h=u?bt(s):ad;if(!Kr){for(let g=0;g<c;i++){if(t(e,r,n,d,i,a),er(d),i>=Aa)throw new Error("arx: counter overflow");const m=Math.min(mn,c-g);for(let y=0,w;y<m;y++)w=g+y,s[w]=o[w]^l[y];g+=m}return}for(let g=0;g<c;i++){if(t(e,r,n,d,i,a),i>=Aa)throw new Error("arx: counter overflow");const m=Math.min(mn,c-g);if(u&&m===mn){const y=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,I;w<Mv;w++)I=y+w,h[I]=f[I]^d[w];g+=mn;continue}for(let y=0,w;y<m;y++)w=g+y,s[w]=o[w]^l[y];g+=m}}function Uv(t,e){const{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Nv({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return qr(o),qr(i),Sa(s),Sa(r),(a,c,l,d,u=0)=>{ve(a,void 0,"key"),ve(c,void 0,"nonce"),ve(l,void 0,"data");const f=l.length,h=d!==void 0;if(d=Ea(f,d,!1),h&&Pv(l,d),qr(u),u<0||u>=Aa)throw new Error("arx: counter overflow");const g=[];let m=a.length,y,w;if(m===32)g.push(y=hs(a)),w=Fv;else if(m===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),w=Ov,g.push(y);else throw ve(a,32,"arx key"),new Error("invalid key size");(!Kr||!fs(c))&&g.push(c=hs(c));let I=bt(y);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");const B=c.subarray(0,16);if(Kr)n(w,I,bt(B),I);else{const T=er(Uint32Array.from(w));n(T,I,bt(B),I),qt(T),er(I)}c=c.subarray(16)}else Kr||er(I);const v=16-o;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){const B=new Uint8Array(12);B.set(c,s?0:12-c.length),c=B,g.push(c)}const A=er(bt(c));try{return jv(t,w,I,A,l,d,u,i),d}finally{qt(...g)}}}function Se(t,e){return t[e++]&255|(t[e++]&255)<<8}class $v{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=hs(ve(e,32,"key"));const r=Se(e,0),n=Se(e,2),o=Se(e,4),s=Se(e,6),i=Se(e,8),a=Se(e,10),c=Se(e,12),l=Se(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let d=0;d<8;d++)this.pad[d]=Se(e,16+2*d)}process(e,r,n=!1){const o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],d=i[3],u=i[4],f=i[5],h=i[6],g=i[7],m=i[8],y=i[9],w=Se(e,r+0),I=Se(e,r+2),v=Se(e,r+4),A=Se(e,r+6),B=Se(e,r+8),T=Se(e,r+10),N=Se(e,r+12),k=Se(e,r+14);let x=s[0]+(w&8191),S=s[1]+((w>>>13|I<<3)&8191),R=s[2]+((I>>>10|v<<6)&8191),P=s[3]+((v>>>7|A<<9)&8191),b=s[4]+((A>>>4|B<<12)&8191),E=s[5]+(B>>>1&8191),C=s[6]+((B>>>14|T<<2)&8191),L=s[7]+((T>>>11|N<<5)&8191),M=s[8]+((N>>>8|k<<8)&8191),$=s[9]+(k>>>5|o),j=0,D=j+x*a+S*(5*y)+R*(5*m)+P*(5*g)+b*(5*h);j=D>>>13,D&=8191,D+=E*(5*f)+C*(5*u)+L*(5*d)+M*(5*l)+$*(5*c),j+=D>>>13,D&=8191;let _=j+x*c+S*a+R*(5*y)+P*(5*m)+b*(5*g);j=_>>>13,_&=8191,_+=E*(5*h)+C*(5*f)+L*(5*u)+M*(5*d)+$*(5*l),j+=_>>>13,_&=8191;let O=j+x*l+S*c+R*a+P*(5*y)+b*(5*m);j=O>>>13,O&=8191,O+=E*(5*g)+C*(5*h)+L*(5*f)+M*(5*u)+$*(5*d),j+=O>>>13,O&=8191;let q=j+x*d+S*l+R*c+P*a+b*(5*y);j=q>>>13,q&=8191,q+=E*(5*m)+C*(5*g)+L*(5*h)+M*(5*f)+$*(5*u),j+=q>>>13,q&=8191;let H=j+x*u+S*d+R*l+P*c+b*a;j=H>>>13,H&=8191,H+=E*(5*y)+C*(5*m)+L*(5*g)+M*(5*h)+$*(5*f),j+=H>>>13,H&=8191;let K=j+x*f+S*u+R*d+P*l+b*c;j=K>>>13,K&=8191,K+=E*a+C*(5*y)+L*(5*m)+M*(5*g)+$*(5*h),j+=K>>>13,K&=8191;let z=j+x*h+S*f+R*u+P*d+b*l;j=z>>>13,z&=8191,z+=E*c+C*a+L*(5*y)+M*(5*m)+$*(5*g),j+=z>>>13,z&=8191;let W=j+x*g+S*h+R*f+P*u+b*d;j=W>>>13,W&=8191,W+=E*l+C*c+L*a+M*(5*y)+$*(5*m),j+=W>>>13,W&=8191;let X=j+x*m+S*g+R*h+P*f+b*u;j=X>>>13,X&=8191,X+=E*d+C*l+L*c+M*a+$*(5*y),j+=X>>>13,X&=8191;let G=j+x*y+S*m+R*g+P*h+b*f;j=G>>>13,G&=8191,G+=E*u+C*d+L*l+M*c+$*a,j+=G>>>13,G&=8191,j=(j<<2)+j|0,j=j+D|0,D=j&8191,j=j>>>13,_+=j,s[0]=D,s[1]=_,s[2]=O,s[3]=q,s[4]=H,s[5]=K,s[6]=z,s[7]=W,s[8]=X,s[9]=G}finalize(){const{h:e,pad:r}=this,n=new Uint16Array(10);let o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+r[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+r[a]|0)+(i>>>16)|0,e[a]=i&65535;qt(n)}update(e){id(this),ve(e),e=hs(e);const{buffer:r,blockLen:n}=this,o=e.length;for(let s=0;s<o;){const i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,qt(this.h,this.r,this.buffer,this.pad)}digestInto(e){id(this),kv(e,this),this.finished=!0;const{buffer:r,h:n}=this;let{pos:o}=this;if(o){for(r[o++]=1;o<16;o++)r[o]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}}const Hv=Bv(32,t=>new $v(t));function qv(t,e,r,n,o,s=20){let i=t[0],a=t[1],c=t[2],l=t[3],d=e[0],u=e[1],f=e[2],h=e[3],g=e[4],m=e[5],y=e[6],w=e[7],I=o,v=r[0],A=r[1],B=r[2],T=i,N=a,k=c,x=l,S=d,R=u,P=f,b=h,E=g,C=m,L=y,M=w,$=I,j=v,D=A,_=B;for(let q=0;q<s;q+=2)T=T+S|0,$=ee($^T,16),E=E+$|0,S=ee(S^E,12),T=T+S|0,$=ee($^T,8),E=E+$|0,S=ee(S^E,7),N=N+R|0,j=ee(j^N,16),C=C+j|0,R=ee(R^C,12),N=N+R|0,j=ee(j^N,8),C=C+j|0,R=ee(R^C,7),k=k+P|0,D=ee(D^k,16),L=L+D|0,P=ee(P^L,12),k=k+P|0,D=ee(D^k,8),L=L+D|0,P=ee(P^L,7),x=x+b|0,_=ee(_^x,16),M=M+_|0,b=ee(b^M,12),x=x+b|0,_=ee(_^x,8),M=M+_|0,b=ee(b^M,7),T=T+R|0,_=ee(_^T,16),L=L+_|0,R=ee(R^L,12),T=T+R|0,_=ee(_^T,8),L=L+_|0,R=ee(R^L,7),N=N+P|0,$=ee($^N,16),M=M+$|0,P=ee(P^M,12),N=N+P|0,$=ee($^N,8),M=M+$|0,P=ee(P^M,7),k=k+b|0,j=ee(j^k,16),E=E+j|0,b=ee(b^E,12),k=k+b|0,j=ee(j^k,8),E=E+j|0,b=ee(b^E,7),x=x+S|0,D=ee(D^x,16),C=C+D|0,S=ee(S^C,12),x=x+S|0,D=ee(D^x,8),C=C+D|0,S=ee(S^C,7);let O=0;n[O++]=i+T|0,n[O++]=a+N|0,n[O++]=c+k|0,n[O++]=l+x|0,n[O++]=d+S|0,n[O++]=u+R|0,n[O++]=f+P|0,n[O++]=h+b|0,n[O++]=g+E|0,n[O++]=m+C|0,n[O++]=y+L|0,n[O++]=w+M|0,n[O++]=I+$|0,n[O++]=v+j|0,n[O++]=A+D|0,n[O++]=B+_|0}const Kv=Uv(qv,{counterRight:!1,counterLength:4,allowShortKeys:!1}),zv=new Uint8Array(16),cd=(t,e)=>{t.update(e);const r=e.length%16;r&&t.update(zv.subarray(r))},Vv=new Uint8Array(32);function ld(t,e,r,n,o){o!==void 0&&ve(o,void 0,"AAD");const s=t(e,r,Vv),i=Dv(n.length,o?o.length:0,!0),a=Hv.create(s);o&&cd(a,o),cd(a,n),a.update(i);const c=a.digest();return qt(s,i),c}const Wv=t=>(e,r,n)=>({encrypt(s,i){const a=s.length;i=Ea(a+16,i,!1),i.set(s);const c=i.subarray(0,-16);t(e,r,c,c,1);const l=ld(t,e,r,c,n);return i.set(l,a),qt(l),i},decrypt(s,i){i=Ea(s.length-16,i,!1);const a=s.subarray(0,-16),c=s.subarray(-16),l=ld(t,e,r,a,n);if(!Lv(c,l))throw qt(l),new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,r,i,i,1),qt(l),i}}),dd=_v({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},Wv(Kv));function Gv(t,e,r){return yc(t),r===void 0&&(r=new Uint8Array(t.outputLen)),bh(t,r,e)}const wn=Uint8Array.of(0),Xv=Uint8Array.of();function Yv(t,e,r,n=32,o){yc(t),It(n,"length"),Ct(e,void 0,"prk");const s=t.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(n>255*s)throw new Error("Length must be <= 255*HashLen");const i=Math.ceil(n/s);if(r===void 0?r=Xv:Ct(r,void 0,"info"),!i)return new Uint8Array;const a=new Uint8Array(i*s),{iHash:c,oHash:l}=bh.create(t,e),d=new Uint8Array(s),u=i>1?t.create():void 0;for(let h=0;h<i-1;h++){wn[0]=h+1;const g=c._cloneInto(u);h&&g.update(d),g.update(r).update(wn).digestInto(d),l._cloneInto(u).update(d).digestInto(d),a.set(d,s*h)}if(wn[0]=i,i>1&&c.update(d),c.update(r).update(wn).digestInto(d),l.update(d).digestInto(d),a.set(d,s*(i-1)),c.destroy(),l.destroy(),u?.destroy(),d!==a&&nr(d),nr(wn),n===a.length)return a;const f=a.slice(0,n);return nr(a),f}const Ah={hashSHA256(t){return di(t.subarray())},getHKDF(t,e){const r=Gv(di,e,t),o=Yv(di,r,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){const t=Ro.utils.randomSecretKey();return{publicKey:Ro.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:Ro.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return Ro.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,r,n){return dd(n,e,r).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,r,n,o){return dd(n,e,r).decrypt(t.subarray(),o)}},Zv=Ah;function Jv(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,r)=>t.generateX25519SharedKey(e.privateKey,r).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}const ps=t=>{const e=At(2);return e[0]=t>>8,e[1]=t,e};ps.bytes=2;const gs=t=>{if(t.length<2)throw RangeError("Could not decode int16BE");if(t instanceof Uint8Array){let e=0;return e+=t[0]<<8,e+=t[1],e}return t.getUint16(0)};gs.bytes=2;function Qv(t){return{xxHandshakeSuccesses:t.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:t.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:t.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:t.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:t.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function kh(t,e){!e.enabled||!co||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${J(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${J(t.privateKey,"hex")}`)):e("Missing local static keys."))}function Ih(t,e){!e.enabled||!co||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${J(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${J(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function ex(t,e){!e.enabled||!co||e(t?`REMOTE_STATIC_PUBLIC_KEY ${J(t.subarray(),"hex")}`:"Missing remote static public key.")}function Ch(t,e){!e.enabled||!co||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${J(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Rh(t,e,r){!r.enabled||!co||(r(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&J(t.k,"hex")}`),r(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&J(e.k,"hex")}`))}class Un extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=Un.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}const tx=0,rx=4294967295,nx="Cipherstate has reached maximum n, a new handshake must be performed";class ox{n;bytes;view;constructor(e=tx){this.n=e,this.bytes=_e(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>rx)throw new Error(nx)}}const zr=_e(0);class To{k;n;crypto;constructor(e,r=void 0,n=0){this.crypto=e,this.k=r,this.n=new ox(n)}hasKey(){return!!this.k}encryptWithAd(e,r){if(!this.hasKey())return r;this.n.assertValue();const n=this.crypto.encrypt(r,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,r,n){if(!this.hasKey())return r;this.n.assertValue();const o=this.crypto.decrypt(r,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}}class sx{cs;ck;h;crypto;constructor(e,r){this.crypto=e;const n=we(r,"utf-8");this.h=ax(e,n),this.ck=this.h,this.cs=new To(e)}mixKey(e){const[r,n]=this.crypto.hkdf(this.ck,e);this.ck=r,this.cs=new To(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new re(this.h,e))}encryptAndHash(e){const r=this.cs.encryptWithAd(this.h,e);return this.mixHash(r),r}decryptAndHash(e){const r=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),r}split(){const[e,r]=this.crypto.hkdf(this.ck,zr);return[new To(this.crypto,e),new To(this.crypto,r)]}}class ix{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:r,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=e;this.crypto=r,this.ss=new sx(r,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<r+32)throw new Error("message is not long enough");this.re=e.sublist(r,r+32),this.ss.mixHash(this.re)}readS(e,r=0){if(this.rs)throw new Error("remote static public key is already set");const n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<r+n)throw new Error("message is not long enough");const o=e.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class Th extends ix{writeMessageA(e){return new re(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const r=this.writeE();this.writeEE();const n=this.writeS();return this.writeES(),new re(r,n,this.ss.encryptAndHash(e))}writeMessageC(e){const r=this.writeS();return this.writeSE(),new re(r,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(r){throw new Un(`handshake stage 0 validation fail: ${r.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();const r=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+r))}catch(r){throw new Un(`handshake stage 1 validation fail: ${r.message}`)}}readMessageC(e){try{const r=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(r))}catch(r){throw new Un(`handshake stage 2 validation fail: ${r.message}`)}}}function ax(t,e){if(e.length<=32){const r=_e(32);return r.set(e),r}else return t.hash(e)}var ms;(function(t){let e;t.codec=()=>(e==null&&(e=_s((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.webtransportCerthashes!=null)for(const s of r.webtransportCerthashes)n.uint32(10),n.bytes(s);if(r.streamMuxers!=null)for(const s of r.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{const s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?r.len:r.pos+n;for(;r.pos<i;){const a=r.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new Nl('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(r.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new Nl('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(r.string());break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Bs(r,t.codec()),t.decode=(r,n)=>Ls(r,t.codec(),n)})(ms||(ms={}));var ws;(function(t){let e;t.codec=()=>(e==null&&(e=_s((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.identityKey!=null&&r.identityKey.byteLength>0&&(n.uint32(10),n.bytes(r.identityKey)),r.identitySig!=null&&r.identitySig.byteLength>0&&(n.uint32(18),n.bytes(r.identitySig)),r.extensions!=null&&(n.uint32(34),ms.codec().encode(r.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{const s={identityKey:_e(0),identitySig:_e(0)},i=n==null?r.len:r.pos+n;for(;r.pos<i;){const a=r.uint32();switch(a>>>3){case 1:{s.identityKey=r.bytes();break}case 2:{s.identitySig=r.bytes();break}case 4:{s.extensions=ms.codec().decode(r,r.uint32(),{limits:o.limits?.extensions});break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Bs(r,t.codec()),t.decode=(r,n)=>Ls(r,t.codec(),n)})(ws||(ws={}));async function Ph(t,e,r){const n=await t.sign(Lh(e));return ws.encode({identityKey:Ds(t.publicKey),identitySig:n,extensions:r})}async function Nh(t,e,r){try{const n=ws.decode(t),o=wa(n.identityKey);if(r?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${r}`);if(!e)throw new Error("Remote static does not exist");const s=Lh(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new yg(n.message)}}function Lh(t){const e=we("noise-libp2p-static-key:");return t instanceof Uint8Array?ia([e,t],e.length+t.length):(t.prepend(e),t)}class cx extends xh{stream;handshake;metrics;decoder;constructor(e,r,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=r,this.metrics=n,this.decoder=new Ev({lengthDecoder:gs,maxBufferSize:16*1024*1024,encodingLength:()=>2});const o=c=>{try{for(const l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",o);const s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);const i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);const a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){const r=new re;for(let n=0;n<e.byteLength;n+=nd){let o=n+nd;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),r.append(ps(s.byteLength)),r.append(s)}return r}decrypt(e){const r=new re;for(let n=0;n<e.byteLength;n+=Zn){let o=n+Zn;if(o>e.byteLength&&(o=e.byteLength),o-od<n)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(n,o):s=e.sublist(n,o);const i=e.subarray(n,o-od);try{const a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),r.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return r}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}}function ud(t,e,r){return new cx(t,e,r)}async function lx(t,e){const{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Ph(s,a.publicKey,l),u=new Th({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});kh(u.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(u.writeMessageA(zr),e),r.trace("Stage 0 - Initiator finished sending first message."),Ih(u.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");const f=u.readMessageB(await n.read(e));r.trace("Stage 1 - Initiator received the message."),Ch(u.re,r),ex(u.rs,r),r.trace("Initiator going to check remote's signature...");const h=await Nh(f,u.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(u.writeMessageC(d),e),r.trace("Stage 2 - Initiator sent message with signed payload.");const[g,m]=u.ss.split();return Rh(g,m,r),{payload:h,encrypt:y=>g.encryptWithAd(zr,y),decrypt:(y,w)=>m.decryptWithAd(zr,y,w)}}async function dx(t,e){const{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Ph(s,a.publicKey,l),u=new Th({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});kh(u.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),u.readMessageA(await n.read(e)),r.trace("Stage 0 - Responder received first message."),Ch(u.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(u.writeMessageB(d),e),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Ih(u.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");const f=u.readMessageC(await n.read(e));r.trace("Stage 2 - Responder received the message, finished handshake.");const h=await Nh(f,u.rs,c),[g,m]=u.ss.split();return Rh(g,m,r),{payload:h,encrypt:y=>m.encryptWithAd(zr,y),decrypt:(y,w)=>g.decryptWithAd(zr,y,w)}}class ux{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,r={}){const{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=r,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");const c=s??Zv;this.crypto=Jv(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?Qv(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??_e(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Ig]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,r){const n=e.log?.newScope("noise")??this.log,o=rd(e,{lengthEncoder:ps,lengthDecoder:gs,maxDataLength:Zn}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=wa(s.payload.identityKey);return{connection:ud(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Zr(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;const r=this.components.upgrader.getStreamMuxers();if(r!=null)for(const n of e){const o=r.get(n);if(o!=null)return o}if(e.length)throw new bg("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,r){const n=e.log?.newScope("noise")??this.log,o=rd(e,{lengthEncoder:ps,lengthDecoder:gs,maxDataLength:Zn}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=wa(s.payload.identityKey);return{connection:ud(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Zr(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,r,n,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await lx({connection:e,privateKey:r,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,r,n,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await dx({connection:e,privateKey:r,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}}function fx(t={}){return e=>new ux(e,t)}const hx="termdock-e2ee-v1",fd=3600*1e3,hd=512*1024*1024,ka=4*1024*1024,Uo=()=>{},Ms=Object.assign(Uo,{enabled:!1,error:Uo,trace:Uo,newScope:()=>Ms});Object.freeze(Ms);async function Bh(){const t=await Nb();return{privateKey:t,peerId:Zr(t.publicKey).toString()}}function px(t){return btoa(String.fromCharCode(..._b(t.privateKey)))}function pd(t){if(t.length>512||!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Invalid identity encoding");const e=Bb(Uint8Array.from(atob(t),r=>r.charCodeAt(0)));if(e.type!=="Ed25519")throw new Error("Only Ed25519 device identities are supported");return{privateKey:e,peerId:Zr(e.publicKey).toString()}}class _h{constructor(e=Uo){this.consumed=e}consumed;chunks=[];size=0;ended=!1;error;wake;push(e){if(this.ended)throw this.error??new Error("Byte stream closed");if(this.size+e.byteLength>ka)throw new Error("Secure stream buffer limit exceeded");this.chunks.push(e.slice()),this.size+=e.byteLength,this.wake?.()}end(e){this.ended=!0,this.error??=e,this.wake?.()}async*[Symbol.asyncIterator](){for(;;){if(this.error)throw this.error;const e=this.chunks.shift();if(e)this.size-=e.byteLength,yield e,this.consumed();else{if(this.ended)return;await new Promise(r=>{this.wake=r})}}}}class gx extends xh{constructor(e,r){super({log:Ms,direction:r?"outbound":"inbound",maxReadBufferLength:ka,maxWriteBufferLength:ka}),this.duplex=e,this.finished=e.sink(this.outgoing).catch(n=>{this.abort(Jr(n))}),this.readTransport()}duplex;outgoing=new _h(()=>this.onMuxerDrain());finished;async readTransport(){try{for await(const e of this.duplex.source)this.onData(e.slice());this.onTransportClosed()}catch(e){this.onTransportClosed(Jr(e))}}sendData(e){return this.outgoing.push(e.subarray()),{sentBytes:e.byteLength,canSendMore:!1}}sendReset(e){this.outgoing.end(e),this.duplex.close?.(e)}sendPause(){}sendResume(){}async close(){this.outgoing.end(),this.duplex.close?.(),this.onTransportClosed(),await this.finished}}function Jr(t){return t instanceof Error?t:new Error("Secure transport failed")}class mx extends Error{code="E2EE_REHANDSHAKE_REQUIRED";constructor(){super("Encrypted connection lifetime reached; establish a new handshake without replaying pending input")}}function wx(t){const e=t?.maxAgeMs??fd,r=t?.maxBytesPerDirection??hd;if(!Number.isSafeInteger(e)||e<=0||e>fd||!Number.isSafeInteger(r)||r<=0||r>hd)throw new Error("Encrypted connection limits cannot exceed the production maximum");return{maxAgeMs:e,maxBytesPerDirection:r}}async function yx(t){const{identity:e,duplex:r,initiator:n,targetPinnedPeerId:o,signal:s}=t,i=wx(t.limits);if(typeof Reflect.get(Promise,"withResolvers")!="function"||typeof globalThis.crypto?.getRandomValues!="function")throw new Error("End-to-end encryption requires Node.js 22+ or a modern browser with Promise.withResolvers and secure random support");if(n&&!o)throw new Error("A pinned target identity is required");const a=o?Mb(o):void 0;if(a&&a.type!=="Ed25519")throw new Error("Only Ed25519 target identities are supported");if(e.peerId!==Zr(e.privateKey.publicKey).toString())throw new Error("Local identity mismatch");if(s?.aborted)throw s.reason??new Error("Connection aborted");const c=new gx(r,n),l=new AbortController,d=setTimeout(()=>{const h=new Error("Encrypted handshake timed out");l.abort(h),c.abort(h)},15e3),u=()=>{l.abort(s?.reason),c.abort(Jr(s?.reason))};s?.addEventListener("abort",u,{once:!0}),c.addEventListener("close",()=>s?.removeEventListener("abort",u),{once:!0});const f=fx({crypto:Ah,prologueBytes:new TextEncoder().encode(hx)})({privateKey:e.privateKey,peerId:Zr(e.privateKey.publicKey),logger:{forComponent:()=>Ms},upgrader:{getStreamMuxers:()=>new Map}});try{const h=await(n?f.secureOutbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}):f.secureInbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}));if(h.remotePeer.type!=="Ed25519")throw new Error("Unsupported remote identity");return{authenticatedPeerId:h.remotePeer.toString(),duplex:bx(h.connection,i)}}catch(h){throw c.abort(Jr(h)),h}finally{clearTimeout(d),s?.removeEventListener("abort",u)}}function bx(t,e){const r=new _h,n=performance.now(),o=Date.now();let s=0,i=0,a;const c=()=>(a??=new mx,r.end(a),t.abort(a),a),l=setTimeout(c,e.maxAgeMs);typeof l=="object"&&l.unref?.();const d=(f,h)=>{if(a)throw a;if(Math.max(performance.now()-n,Date.now()-o)>=e.maxAgeMs||f+h>=e.maxBytesPerDirection)throw c()};t.addEventListener("message",f=>{try{d(i,f.data.byteLength),i+=f.data.byteLength,r.push(f.data.subarray())}catch(h){t.abort(Jr(h))}}),t.addEventListener("close",f=>{clearTimeout(l),r.end(f.error)},{once:!0});let u=!1;return{source:r,async sink(f){if(u)throw new Error("Secure sink already consumed");u=!0;try{for await(const h of f)d(s,h.byteLength),s+=h.byteLength,t.send(h)||await t.onDrain()}catch(h){throw t.abort(Jr(h)),h}},close(f){f?t.abort(f):t.close()}}}class Cc{constructor(e=64){this.limit=e}limit;items=[];wake;ended=!1;error;push(e){if(this.ended)throw new Error("Channel closed");if(this.items.length>=this.limit)throw this.end(new Error("Channel queue exceeded")),this.error;this.items.push(e),this.wake?.()}end(e){this.ended=!0,this.error??=e,this.wake?.()}async*[Symbol.asyncIterator](){for(;;){if(this.error)throw this.error;const e=this.items.shift();if(e!==void 0){yield e;continue}if(this.ended)return;await new Promise(r=>{this.wake=r}),this.wake=void 0}}}const gi=2*1024*1024,vx=new TextEncoder,xx=new TextDecoder("utf-8",{fatal:!0});class Sx{constructor(e){this.duplex=e;const r=this;this.done=e.sink((async function*(){for await(const n of r.outgoing)try{yield n}finally{r.outgoingBytes-=n.byteLength}})()),this.done.catch(n=>this.close(n instanceof Error?n:new Error("Transport failed")))}duplex;outgoing=new Cc(256);outgoingBytes=0;done;send(e){const r=vx.encode(JSON.stringify(e));if(r.length>gi)throw new Error("Record too large");const n=new Uint8Array(r.length+4);if(new DataView(n.buffer).setUint32(0,r.length),n.set(r,4),this.outgoingBytes+n.byteLength>4*1024*1024)throw new Error("Record queue byte budget exceeded");this.outgoingBytes+=n.byteLength;try{this.outgoing.push(n)}catch(o){throw this.outgoingBytes-=n.byteLength,o}}close(e){this.outgoing.end(e),this.duplex.close?.(e)}async*read(){let e=new Uint8Array(0);for await(const r of this.duplex.source){if(e.length+r.length>gi*2+8)throw new Error("Record buffer exceeded");const n=new Uint8Array(e.length+r.length);for(n.set(e),n.set(r,e.length),e=n;e.length>=4;){const o=new DataView(e.buffer,e.byteOffset,4).getUint32(0);if(o>gi||o===0)throw new Error("Invalid record size");if(e.length<o+4)break;const s=JSON.parse(xx.decode(e.subarray(4,o+4)));if(!s||typeof s!="object"||typeof s.id!="string"||typeof s.type!="string")throw new Error("Invalid record");yield s,e=e.slice(o+4)}}if(e.length)throw new Error("Truncated record")}}function Dh(t){let e="";for(let r=0;r<t.length;r+=8192)e+=String.fromCharCode(...t.subarray(r,r+8192));return btoa(e)}function Oh(t){const e=atob(t);return Uint8Array.from(e,r=>r.charCodeAt(0))}function Ex(t){const e=new Cc(64);t.binaryType="arraybuffer";const r=n=>{e.end(n),t.close(1e3)};return t.addEventListener("message",n=>{try{if(!(n.data instanceof ArrayBuffer)||n.data.byteLength>1024*1024)throw new Error("Invalid encrypted frame");e.push(new Uint8Array(n.data))}catch{r(new Error("Encrypted transport rejected frame"))}}),t.addEventListener("close",()=>e.end()),t.addEventListener("error",()=>e.end(new Error("Encrypted transport disconnected"))),{source:e,close:r,async sink(n){try{for await(const o of n)for(let s=0;s<o.length;s+=64*1024){const i=Date.now();for(;t.bufferedAmount>256*1024;){if(t.readyState!==1||Date.now()-i>15e3)throw new Error("Encrypted transport congested");await new Promise(a=>setTimeout(a,10))}if(t.readyState!==1)throw new Error("Encrypted transport closed");t.send(o.subarray(s,s+64*1024))}}catch(o){throw r(o instanceof Error?o:new Error("Encrypted transport failed")),o}}}}const Fh=8,Mh=128,Ax=5*1024*1024,kx=Mh+Fh+8,Ix=256,Po=3e4,yn=64*1024;function jt(t){return t instanceof Error?t:new Error(String(t??"Secure connection closed"))}function gd(t){if(!t.startsWith("/")||t.startsWith("//")||t.includes("#"))throw new Error("A local API path is required");return t}class jh extends EventTarget{constructor(e,r,n){super(),this.url=e,this.transmit=r,this.disconnect=n}url;transmit;disconnect;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;binaryType="arraybuffer";bufferedAmount=0;protocol="termdock-e2ee-v1";extensions="";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;send(e){if(this.readyState!==1)throw new Error("Secure socket is not open");if(typeof e!="string"||new TextEncoder().encode(e).length>1024*1024)throw new Error("Unsupported socket payload");this.transmit(e)}close(e=1e3,r=""){this.readyState!==3&&(this.disconnect(),this.finish(e,r))}accept(e){if(this.readyState!==3)if(e.type==="ws-ready"){this.readyState=1;const r=new Event("open");this.dispatchEvent(r),this.onopen?.(r)}else if(e.type==="ws-data"&&typeof e.data=="string"){const r=new MessageEvent("message",{data:e.data});this.dispatchEvent(r),this.onmessage?.(r)}else e.type==="ws-close"?this.finish(typeof e.code=="number"?e.code:1e3,typeof e.reason=="string"?e.reason:""):e.type==="error"&&this.fail(jt(e.error))}fail(e){if(this.readyState===3)return;const r=new Event("error");this.dispatchEvent(r),this.onerror?.(r),this.finish(1006,e.message)}finish(e,r){if(this.readyState===3)return;this.readyState=3;const n=new CloseEvent("close",{code:e,reason:r,wasClean:e===1e3});this.dispatchEvent(n),this.onclose?.(n)}}class Cx{constructor(e,r,n){this.channel=e,this.identity=r,this.targetPeerId=n,this.read().catch(o=>this.close(jt(o))),e.done.catch(o=>this.close(jt(o)))}channel;identity;targetPeerId;pending=new Map;waiting=[];stopped=!1;closeReason;get canSwitchTransport(){return![...this.pending.values()].some(e=>e.kind==="http")&&!this.waiting.some(e=>e.kind==="http")}get closed(){return this.stopped}hasCapacity(e){if(this.pending.size>=kx)return!1;const r=[...this.pending.values()].filter(n=>n.kind===e).length;return e==="http"?r<Fh:e==="socket"?r<Mh:!0}allocate(e){if(this.stopped)throw this.closeReason??new Error("Secure connection closed");const r=crypto.randomUUID(),n=new Cc(4);return this.pending.set(r,{queue:n,kind:e}),{id:r,queue:n}}reserve(e,r){return r?.aborted?Promise.reject(r.reason):this.stopped?Promise.reject(this.closeReason??new Error("Secure connection closed")):this.hasCapacity(e)?Promise.resolve(this.allocate(e)):this.waiting.length>=Ix?Promise.reject(new Error("连接繁忙,请稍后重试。")):new Promise((n,o)=>{const s=l=>{this.waiting=this.waiting.filter(d=>d!==c),c.cleanup(),o(l)},i=()=>s(r?.reason??new Error("Request aborted")),a=setTimeout(()=>s(new Error("连接等待超时,请重试。")),Po),c={kind:e,resolve:n,reject:o,cleanup:()=>{clearTimeout(a),r?.removeEventListener("abort",i)}};this.waiting.push(c),r?.addEventListener("abort",i,{once:!0})})}dispatchWaiting(){if(!this.stopped)for(let e=0;e<this.waiting.length;){const r=this.waiting[e];if(!this.hasCapacity(r.kind)){e++;continue}this.waiting.splice(e,1),r.cleanup(),r.resolve(this.allocate(r.kind))}}async read(){try{for await(const e of this.channel.read()){const r=this.pending.get(e.id);r&&(r.socket?(r.socket.accept(e),(e.type==="ws-close"||e.type==="error")&&this.release(e.id)):(r.queue.push(e),(e.type==="end"||e.type==="error")&&(r.cancelUpload?.(),this.release(e.id))))}}finally{this.close(new Error("Secure connection closed"))}}release(e){this.pending.get(e)?.queue.end(),this.pending.delete(e),this.dispatchWaiting()}async request(e,r){const{id:n,queue:o}=await this.reserve("request"),s=setTimeout(()=>this.close(new Error("Secure connection timed out")),Math.max(1e3,Math.min(Po,r?.timeoutMs??Po)));try{if(this.stopped)throw this.closeReason;this.channel.send({...e,id:n});const i=(await o[Symbol.asyncIterator]().next()).value;if(!i)throw new Error("Secure request closed");if(i.type==="error")throw jt(i.error);return i}finally{clearTimeout(s),this.release(n)}}openSocket(e){gd(e);let r;const n=new AbortController,o=new jh(e,s=>{r&&this.channel.send({id:r,type:"ws-data",data:s})},()=>{if(n.abort(),r)try{this.channel.send({id:r,type:"ws-close"})}finally{this.release(r)}});return this.reserve("socket",n.signal).then(s=>{if(r=s.id,o.readyState===3){this.release(r);return}const i=this.pending.get(r);if(!i)throw new Error("Secure connection closed");i.socket=o,this.channel.send({id:r,type:"ws-open",path:e})}).catch(s=>{r&&this.release(r),o.fail(jt(s))}),o}async fetch(e,r){const n=typeof location>"u"?"https://termdock.invalid":location.origin,o=e instanceof Request?e:null,s=new URL(o?.url??String(e),n);if(s.origin!==n)throw new Error("Only current-service API requests are supported");const i=new Request(s,o?new Request(o,r):r),a=i.method.toUpperCase(),c=gd(s.pathname+s.search),l=s.pathname==="/api/terminal/fs/upload"?110*1024*1024:Ax;if(i.signal.aborted)throw i.signal.reason;const d={};i.headers.forEach((A,B)=>{["cookie","authorization","host","connection","content-length"].includes(B)||(d[B]=A)});const{id:u,queue:f}=await this.reserve("http",i.signal),h=f[Symbol.asyncIterator]();let g;const m=()=>{g?.cancel().catch(()=>{})},y=this.pending.get(u);if(!y)throw new Error("Secure connection closed");y.cancelUpload=m;const w=()=>{m();try{this.channel.send({id:u,type:"cancel"})}catch{}f.end(jt(i.signal.reason??"Request aborted")),this.release(u)};i.signal.addEventListener("abort",w,{once:!0});const I=()=>{i.signal.removeEventListener("abort",w),this.release(u)},v=async()=>{let A;try{const B=(await Promise.race([h.next(),new Promise((T,N)=>{A=setTimeout(()=>N(new Error("服务响应超时,请重试。")),Po)})])).value;if(!B)throw new Error("Secure response ended unexpectedly");if(B.type==="error")throw jt(B.error);return B}finally{clearTimeout(A)}};try{if(i.signal.aborted)throw i.signal.reason;if(this.channel.send({id:u,type:"http",method:a,path:c,headers:d}),i.body){const k=i.body.getReader();g=k;let x=0,S=0;try{for(;;){const{done:R,value:P}=await k.read();if(R)break;if(x+=P.byteLength,x>l)throw new Error("Request body exceeds upload limit");for(let b=0;b<P.byteLength;b+=yn){if(this.channel.send({id:u,type:"upload",data:Dh(P.subarray(b,b+yn))}),(await v()).type!=="upload-ack")throw new Error("Invalid upload acknowledgement");S+=Math.min(yn,P.byteLength-b),r?.onUploadProgress?.(S)}}}catch(R){throw await k.cancel(R).catch(()=>{}),R}finally{g=void 0,k.releaseLock()}}if(i.signal.aborted||this.stopped)throw new Error("Request aborted");this.channel.send({id:u,type:"upload-end"});const A=await v();if(A.type!=="head"||typeof A.status!="number")throw new Error("Invalid response header");const B=new Headers(A.headers);if(a==="HEAD"||[204,205,304].includes(A.status)){if((await v()).type!=="end")throw new Error("Unexpected response body");return I(),new Response(null,{status:A.status,headers:B})}let T=!1;const N=new ReadableStream({pull:async k=>{try{T&&(this.channel.send({id:u,type:"ack"}),T=!1);const x=await v();if(x.type==="end"){k.close(),I();return}if(x.type!=="chunk"||typeof x.data!="string")throw new Error("Invalid response chunk");const S=Oh(x.data);if(S.length>yn)throw new Error("Response chunk exceeds budget");k.enqueue(S),T=!0}catch(x){k.error(x),w(),I()}},cancel:()=>{w(),I()}},{highWaterMark:yn,size:k=>k.byteLength});return new Response(N,{status:A.status,headers:B})}catch(A){throw w(),I(),A}}close(e=new Error("Secure connection closed")){if(!this.stopped){this.stopped=!0,this.closeReason=e;for(const r of this.waiting.splice(0))r.cleanup(),r.reject(e);for(const r of this.pending.values())r.queue.end(e),r.cancelUpload?.(),r.socket?.fail(e);this.pending.clear(),this.channel.close(e)}}}async function cr(t){const e=new URL(t.url);if(!["wss:","ws:"].includes(e.protocol))throw new Error("A WebSocket endpoint is required");if(e.protocol==="ws:"&&!["127.0.0.1","localhost","[::1]"].includes(e.hostname))throw new Error("Remote secure channels require WSS");const r=t.identity??await Bh(),n=(t.socketFactory??(c=>new WebSocket(c)))(e.href),o=Ex(n),s=new AbortController,i=setTimeout(()=>s.abort(new Error("Secure handshake timed out")),2e4),a=t.signal?AbortSignal.any([t.signal,s.signal]):s.signal;try{await new Promise((d,u)=>{if(a.aborted){u(a.reason);return}const f=()=>{a.removeEventListener("abort",m),n.removeEventListener("open",h),n.removeEventListener("error",g),n.removeEventListener("close",g)},h=()=>{f(),d()},g=()=>{f(),u(new Error("Secure transport unavailable"))},m=()=>{f(),u(a.reason)};a.addEventListener("abort",m,{once:!0}),n.addEventListener("open",h),n.addEventListener("error",g),n.addEventListener("close",g),n.readyState===1&&h()});const c=await yx({identity:r,duplex:o,initiator:!0,targetPinnedPeerId:t.targetPeerId,signal:a}),l=new Cx(new Sx(c.duplex),r,c.authenticatedPeerId);if(t.pairingCode)try{await l.request({type:"pair",code:t.pairingCode})}catch(d){throw l.close(jt(d)),d}return l}catch(c){throw n.close(),c}finally{clearTimeout(i)}}const md=256*1024,Rx=1024*1024;class Tx extends EventTarget{constructor(e,r,n=o=>new WebSocket(o)){if(super(),this.url=e,!/^[a-zA-Z0-9_.:-]{1,160}$/.test(r))throw new Error("Invalid target identity");this.upstream=n(e),this.deadline=setTimeout(()=>this.fail("Relay connection timed out"),2e4),this.upstream.addEventListener("message",o=>{if(this.readyState!==3)try{if(typeof o.data!="string"||new TextEncoder().encode(o.data).length>md)throw new Error("Invalid relay envelope");const s=JSON.parse(o.data);if(s.type==="ready"&&!this.requested){this.requested=!0,this.transmit({type:"open",streamId:this.streamId,serviceId:r});return}if(s.streamId!==this.streamId)return;if(s.type==="opened"&&this.readyState===0){clearTimeout(this.deadline),this.readyState=1;const l=new Event("open");this.dispatchEvent(l),this.onopen?.(l);return}if(s.type==="close"){this.finish(1001,"Relay route closed"),this.upstream.close();return}if(s.type!=="data"||this.readyState!==1||s.encoding!=="base64"||typeof s.payload!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(s.payload))throw new Error("Invalid ciphertext relay frame");const i=Oh(s.payload),a=this.binaryType==="blob"?new Blob([i]):i.buffer,c=new MessageEvent("message",{data:a});this.dispatchEvent(c),this.onmessage?.(c)}catch{this.fail("Relay protocol rejected frame")}}),this.upstream.addEventListener("close",o=>this.finish(o.code||1006,"Relay disconnected")),this.upstream.addEventListener("error",()=>this.fail("Relay transport unavailable"))}url;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;protocol="";extensions="";binaryType="arraybuffer";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;upstream;streamId=crypto.randomUUID();requested=!1;deadline;get bufferedAmount(){return this.upstream.bufferedAmount}transmit(e){const r=JSON.stringify(e);if(this.upstream.readyState!==1||this.upstream.bufferedAmount+r.length>Rx||r.length>md)throw new Error("Relay unavailable or congested");this.upstream.send(r)}send(e){if(this.readyState!==1)throw new Error("Relay socket is not open");let r;if(ArrayBuffer.isView(e))r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof ArrayBuffer)r=new Uint8Array(e);else throw new Error("Relay secure transport requires binary bytes");try{this.transmit({type:"data",streamId:this.streamId,encoding:"base64",payload:Dh(r)})}catch(n){throw this.fail("Relay transport congested"),n}}close(e=1e3,r=""){if(this.readyState!==3){try{this.requested&&this.transmit({type:"close",streamId:this.streamId})}catch{}this.finish(e,r),this.upstream.close()}}fail(e){if(this.readyState===3)return;const r=new Event("error");this.dispatchEvent(r),this.onerror?.(r),this.finish(1006,e),this.upstream.close()}finish(e,r){if(this.readyState===3)return;clearTimeout(this.deadline),this.readyState=3;const n=new CloseEvent("close",{code:e,reason:r,wasClean:e===1e3});this.dispatchEvent(n),this.onclose?.(n)}}function Uh(t){return e=>new Tx(e,t)}function Px(t){if(typeof t!="string"||!t.startsWith("/api/")||/[\\\x00-\x20\x7f#]/.test(t))return null;const e=t.split("?")[0];if(e.includes("//"))return null;try{const n=e.split("/").map((o,s)=>{if(s===0||o===""&&s===e.split("/").length-1)return o;const i=decodeURIComponent(o);if(!i||i==="."||i===".."||/[\\/\x00-\x1f\x7f]/.test(i)||/%[a-f0-9]{2}/i.test(i))throw new Error("Ambiguous API path");return i}).join("/");return n.endsWith("/")&&!n.startsWith("/api/terminal/fs/preview/")?null:n}catch{return null}}function Nx(t){if(!("serviceWorker"in navigator))return()=>{};const e=new Set,r=n=>{if(n.source!==navigator.serviceWorker.controller||n.data?.type!=="termdock-secure-fetch"||n.ports.length!==1)return;const o=n.ports[0],{path:s,method:i,headers:a,body:c,expectedTargetPeerId:l,previewPrefix:d}=n.data;let u;try{u=new URL(s,location.origin)}catch{o.close();return}if(u.origin!==location.origin||!u.pathname.startsWith("/api/")||e.size>=32||typeof i!="string"||c!==void 0&&(!(c instanceof ArrayBuffer)||c.byteLength>5*1024*1024)){o.postMessage({type:"error"}),o.close();return}if(d!==void 0&&(typeof d!="string"||!d.endsWith("/")||!/^\/api\/terminal\/fs\/preview\/[a-f0-9]{32}\//.test(d)||!["GET","HEAD"].includes(i)||!Px(u.pathname)?.startsWith(d))){o.postMessage({type:"error"}),o.close();return}const f=new AbortController;let h,g,m=!1,y=!1;const w=()=>{y||(y=!0,e.delete(w),f.abort(),h?.cancel().catch(()=>{}),o.close())};e.add(w),o.onmessage=I=>{if(I.data?.type==="cancel"){w();return}I.data?.type!=="pull"||m||y||(m=!0,(async()=>{if(!h){o.postMessage({type:"end"}),w();return}if(!g?.length){const A=await h.read();if(A.done){o.postMessage({type:"end"}),w();return}g=A.value}const v=g.slice(0,64*1024);g=g.subarray(v.length),o.postMessage({type:"chunk",data:v.buffer},[v.buffer])})().catch(()=>{o.postMessage({type:"error"}),w()}).finally(()=>{m=!1}))},o.onmessageerror=w,o.start(),(async()=>{const I=await t();if(y)return;if(l&&l!==I.targetPeerId)throw new Error("Preview target changed");const v=await I.fetch(u.pathname+u.search,{method:i,headers:a,body:["GET","HEAD"].includes(i)?void 0:c,signal:f.signal});if(y){await v.body?.cancel();return}h=v.body?.getReader();const A={};v.headers.forEach((B,T)=>{A[T]=B}),o.postMessage({type:"head",status:v.status,headers:A,bodyless:!h,targetPeerId:I.targetPeerId})})().catch(()=>{y||(o.postMessage({type:"error"}),w())})};return navigator.serviceWorker.addEventListener("message",r),()=>{navigator.serviceWorker.removeEventListener("message",r);for(const n of[...e])n()}}class Ve extends Error{constructor(){super("Device authorization expired or revoked")}}const No=new WeakMap;function on(t,e={}){const r=No.get(t);if(!t.closed&&r&&(!r.settled||Date.now()-r.at<(e.maxAgeMs??1e3)))return r.pending;const n={at:Date.now(),settled:!1,pending:void 0},o=Lx(t,e.timeoutMs??5e3).then(s=>(n.at=Date.now(),n.settled=!0,s),s=>{throw No.get(t)===n&&No.delete(t),s});return n.pending=o,No.set(t,n),o}async function Lx(t,e){const r=await t.request({type:"permissions"},{timeoutMs:e});if(r.type!=="result"||typeof r.fullService!="boolean"||!Array.isArray(r.grants))throw new Error("Invalid permission response");const n=r.grants,o=r.fullService===!0;if(!o&&n.length===0)throw new Ve;return{fullService:o,grants:n,canManage:o&&n.length>0||n.some(s=>s.actions.includes("authorization.manage"))}}const $h="termdock-secure-last-path:",Bx=10*6e4;function Hh(t){try{const e=JSON.parse(sessionStorage.getItem($h+t)||"null");return e&&typeof e.key=="string"&&Date.now()-e.at<Bx?e.key:void 0}catch{return}}function qh(t,e){try{sessionStorage.setItem($h+t,JSON.stringify({key:e,at:Date.now()}))}catch{}}function Kh(t,e,r=!1){return new Promise((n,o)=>{let s=0,i=0,a=!1,c,l;const d=new Set,u=()=>{clearTimeout(l);for(const h of d)h.abort();d.clear()},f=()=>{if(a)return;if(s>=t.length){i||(a=!0,u(),o(c||new Error("没有可用的连接路线。")));return}if(i>=(r?1:2))return;const h=t[s++],g=performance.now(),m=w=>{performance.getEntriesByName("termdock:connection-path").length>64&&performance.clearMeasures("termdock:connection-path"),performance.measure("termdock:connection-path",{start:g,end:performance.now(),detail:{path:h.key.startsWith("relay:")?"relay":"direct",ok:w}})},y=new AbortController;d.add(y),i++,h.run(y.signal).then(w=>{if(m(!0),d.delete(y),a){e(w);return}a=!0,u(),n({value:w,key:h.key})},w=>{if(m(!1),d.delete(y),i--,!a){if(c=w,w instanceof Ve){a=!0,u(),o(w);return}f()}}),clearTimeout(l),!r&&s<t.length&&(l=setTimeout(f,400))};f()})}const zh="termdock-workspace",Ia="termdock:workspace-visibility",Ca="termdock:workspace-activate";function Rc(){return window.parent!==window&&location.pathname==="/workspace.html"&&new URLSearchParams(location.search).get(zh)||"root"}let wd,yd;function St(){try{if(window.parent===window)return window.__termdockWorkspaceHost;const t=window.parent.__termdockWorkspaceHost;return t&&t!==wd&&(wd=t,yd={...t,subscribe(e){const r=t.subscribe(e),n=o=>{o.persisted||r()};return window.addEventListener("pagehide",n),()=>{r(),window.removeEventListener("pagehide",n)}}}),t?yd:void 0}catch{return}}function mi(){const t=St();return!t||t.snapshot().activeKey===Rc()}function ys(t,e=!0){return St()?.activate(t,e)??!1}function Nn(t){St()?.report(Rc(),t)}const Ra="termdock-secure-workspace-session:";function Kk(t){if(t)try{const e=JSON.parse(localStorage.getItem(Ra+t)||"null");return localStorage.removeItem(Ra+t),e&&typeof e.sessionId=="string"&&Date.now()-e.at<6e4?e.sessionId:void 0}catch{return}}function _x(t){if(window.parent!==window||window.termdockDesktop)return;if(window.__termdockWorkspaceHost)return window.__termdockWorkspaceHost;let e={activeKey:"root",items:[{key:"root",service:t,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]};try{const c=sessionStorage.getItem("termdock-secure-last-workspace"),l=t&&c!==t.targetPeerId?Kt().find(d=>d.targetPeerId===c):void 0;l?.targetPeerId&&(e={activeKey:l.targetPeerId,items:[...e.items,{key:l.targetPeerId,service:l,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]})}catch{}const r=new Set,n=new Map([["root",window]]),o=new Set,s=()=>{for(const c of[...r])c()},i=(c,l)=>{try{const d=l.document.createEvent("CustomEvent");if(d.initCustomEvent(Ia,!1,!1,{active:e.activeKey===c}),l.dispatchEvent(d),e.activeKey===c){const u=l.document.createEvent("Event");if(u.initEvent("resize",!1,!1),l.dispatchEvent(u),o.delete(c)){const f=l.document.createEvent("Event");f.initEvent(Ca,!1,!1),l.dispatchEvent(f)}}else l.document.activeElement?.blur?.()}catch{}},a={snapshot:()=>e,subscribe:c=>(r.add(c),()=>{r.delete(c)}),activate(c,l=!0){const d=ks(c);if(!d?.targetPeerId)return!1;const u=e.items.find(g=>g.service?.targetPeerId===d.targetPeerId),f=u?.key||d.targetPeerId,h=u?{...u,service:d,touchedAt:Date.now()}:{key:f,service:d,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()};e={activeKey:f,items:u?e.items.map(g=>g===u?h:g):[...e.items,h]};try{sessionStorage.setItem("termdock-secure-last-workspace",d.targetPeerId)}catch{}l&&o.add(f),s();for(const[g,m]of n)i(g,m);return!0},report(c,l){const d=e.items.find(f=>f.key===c);if(!d||l.service&&d.service?.targetPeerId&&l.service.targetPeerId!==d.service.targetPeerId)return;const u={...d,...l};JSON.stringify(u)!==JSON.stringify(d)&&(e={...e,items:e.items.map(f=>f===d?u:f)},s())},attach(c,l){l?(n.set(c,l),i(c,l)):n.delete(c)},focusSession(c,l){const d=Kt().find(f=>f.targetPeerId===c);if(!d)return!1;try{localStorage.setItem(Ra+c,JSON.stringify({sessionId:l,at:Date.now()}))}catch{return!1}a.activate(d,!1);const u=n.get(e.activeKey);if(u){const f=u.document.createEvent("CustomEvent");f.initCustomEvent("termdock:workspace-session",!1,!1,null),u.dispatchEvent(f)}return!0}};return window.__termdockWorkspaceHost=a,a}let wi;async function Ge(){return wi||(wi=(async()=>{const t=await new Promise((e,r)=>{const n=indexedDB.open("termdock-device-identity",1);n.onupgradeneeded=()=>n.result.createObjectStore("keys"),n.onsuccess=()=>e(n.result),n.onerror=()=>r(n.error)});try{const e=await new Promise((o,s)=>{const i=t.transaction("keys").objectStore("keys").get("identity");i.onsuccess=()=>o(i.result),i.onerror=()=>s(i.error)});if(e)return pd(e);const r=await Bh();let n=r;return await new Promise((o,s)=>{const i=t.transaction("keys","readwrite"),a=i.objectStore("keys"),c=a.get("identity");c.onsuccess=()=>{typeof c.result=="string"?n=pd(c.result):a.put(px(r),"identity")},i.oncomplete=()=>o(),i.onerror=()=>s(i.error)}),n}finally{t.close()}})()),wi}const lr="termdock:secure-state";let Q,bn,$e,Jn="direct",yi=!1,bd=0;const Qr=globalThis.fetch.bind(globalThis);function ne(){return Dr()}function vn(){return Q}function Dx(){return $e}function Vh(){Q?.close(),$e?.close(),Q=void 0,$e=void 0}async function Wh(){const t=await Qr("/api/auth/status",{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error("Failed to query auth status");return t.json()}async function Ox(){if(ne()){await lt();return}if((await Wh()).enabled)return;const t=await Qr("/api/auth/open/parameters",{cache:"no-store"});if(!t.ok)throw new Error("Open service unavailable");const{serviceIdentity:e}=await t.json();if(typeof e!="string"||!e)throw new Error("Invalid service identity");await et({url:location.origin,targetPeerId:e,serviceName:location.hostname})}async function Fx(t,e){const{startPasswordBootstrap:r,finishPasswordBootstrap:n}=await Vt(async()=>{const{startPasswordBootstrap:l,finishPasswordBootstrap:d}=await import("./passwordBootstrap-DwalkAEW.js");return{startPasswordBootstrap:l,finishPasswordBootstrap:d}},__vite__mapDeps([0,1,2,3])),o=l=>t===location.origin?l:new URL(l,t).href,s=async(l,d)=>{const u=await Qr(o(l),{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(15e3),...d?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}:{}});if(!u.ok)throw new Error(u.status===429?"尝试次数较多,请稍后再试。":u.status===401?"密码不正确,请重新输入。":"暂时无法登录这台服务,请稍后重试。");return u.json()},{saltHex:i}=await s("/api/auth/password/parameters"),a=await Ge(),c=await r(e,i);try{const l=await s("/api/auth/password/start",{startLoginRequest:c.startLoginRequest,clientIdentity:a.peerId});let d;try{d=await n(c,l,{clientIdentity:a.peerId,origin:location.origin})}catch{throw new Error("密码不正确,或服务身份无法验证。请检查后重试。")}return await s("/api/auth/password/finish",{attemptId:d.attemptId,finishLoginRequest:d.finishLoginRequest}),{url:t,targetPeerId:d.serverIdentity,serviceName:new URL(t).host,serviceOrigin:t}}finally{c.passwordKey=""}}async function Tc(t,e){const r=ne();if(r&&(r.serviceOrigin||r.url)===t)return await Ta(r,e),r;try{return await Fx(t,e)}catch(n){if(!(n instanceof TypeError)&&!(n instanceof DOMException))throw n;const o=(await We()).find(i=>i.targetPeerId&&(i.serviceOrigin||i.url)===t);if(!o?.targetPeerId)throw new Error("暂时连不上这台服务,请检查地址和网络。");const s={...o,targetPeerId:o.targetPeerId,serviceName:o.label};return await Ta(s,e),s}}async function Ta(t,e){const r=await Gh(t),{startPasswordBootstrap:n,finishPasswordBootstrap:o}=await Vt(async()=>{const{startPasswordBootstrap:i,finishPasswordBootstrap:a}=await import("./passwordBootstrap-DwalkAEW.js");return{startPasswordBootstrap:i,finishPasswordBootstrap:a}},__vite__mapDeps([0,1,2,3]));let s;try{const i=await r.request({type:"password-parameters"},{timeoutMs:5e3});s=await n(e,String(i.saltHex));const a=await r.request({type:"password-start",startLoginRequest:s.startLoginRequest,origin:location.origin}),c=await o(s,a,{clientIdentity:(await Ge()).peerId,origin:location.origin});if(c.serverIdentity!==t.targetPeerId)throw new Error("服务身份发生变化。");await r.request({type:"password-finish",attemptId:c.attemptId,finishLoginRequest:c.finishLoginRequest})}catch{throw new Error("暂时无法登录,请检查目标服务密码与入口授权后重试。")}finally{s&&(s.passwordKey=""),r.close()}}async function Mx(t){try{const e=ne(),r=e?.serviceOrigin||location.origin,n=await Tc(r,t);return await et({...n,routes:e?.routes,serviceName:e?.serviceName||n.serviceName}),Response.json({ok:!0})}catch(e){return Response.json({error:e instanceof Error?e.message:"暂时无法登录,请重试。",code:"INVALID_PASSWORD"},{status:401})}}async function vd(t,e){const r=Be(t),n=(await We()).find(i=>(i.serviceOrigin||i.url)===r&&i.targetPeerId);if(e===void 0&&n?.targetPeerId)try{return await et({...n,targetPeerId:n.targetPeerId,serviceName:n.label}),{}}catch(i){if(!(i instanceof Ve))throw i}if(e!==void 0){const i=await Tc(r,e);if(n?.targetPeerId&&n.targetPeerId!==i.targetPeerId)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await et({...i,routes:n?.routes,serviceName:n?.label||i.serviceName}),{}}const o=await Qr(new URL("/api/auth/open/parameters",r).href,{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(1e4)}).catch(()=>{throw new Error("暂时连不上这台服务,请检查地址和网络后重试。")});if(o.status===403)return{passwordRequired:!0};if(!o.ok)throw new Error("这台服务暂时不可用,请稍后重试。");const{serviceIdentity:s}=await o.json();if(typeof s!="string"||!s)throw new Error("这不是可连接的 Termdock 服务。");if(n?.targetPeerId&&n.targetPeerId!==s)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await et({url:r,targetPeerId:s,serviceName:n?.label||new URL(r).host,serviceOrigin:r}),{}}function dr(t){const e=[...t.routes||[]];if(t.entryServiceId&&t.entryServiceId!==t.targetPeerId&&e.unshift({url:t.url,targetPeerId:t.entryServiceId}),!e.length&&t.routes===void 0)try{const r=JSON.parse(localStorage.getItem(Za)||"null");r&&r.targetPeerId!==t.targetPeerId&&new URL(r.url).host===new URL(t.url).host&&e.push(r)}catch{}return e.flatMap((r,n)=>{try{return r.targetPeerId&&r.targetPeerId!==t.targetPeerId&&e.findIndex(o=>o.targetPeerId===r.targetPeerId)===n?[{url:Be(r.url),targetPeerId:r.targetPeerId}]:[]}catch{return[]}}).slice(0,4)}function lo(t){const e=dr(t),r=[t.serviceOrigin||t.url,...(t.routes||[]).slice(0,4).filter(o=>o.targetPeerId===t.targetPeerId).map(o=>o.url)],n=new Set;for(const o of r)try{const s=Be(o);e.some(i=>i.url===s)||n.add(s)}catch{}return[...n]}function ur(t){const e=new URL("/api/federation/secure",Be(t));return e.protocol=e.protocol==="https:"?"wss:":"ws:",e.href}async function Wt(t,e){return cr({url:ur(t.url),targetPeerId:t.targetPeerId,identity:await Ge(),signal:e?AbortSignal.any([e,AbortSignal.timeout(5e3)]):AbortSignal.timeout(5e3)})}async function Gh(t,e){const r=await Ge(),n=lo(t).map(i=>({key:`direct:${i}`,run:a=>cr({url:ur(i),targetPeerId:t.targetPeerId,identity:r,signal:AbortSignal.any([a,AbortSignal.timeout(8e3),...e?[e]:[]])})}));for(const i of dr(t))n.push({key:`relay:${i.targetPeerId}:${i.url}`,run:async a=>{e&&(a=AbortSignal.any([a,e]));const c=[Q,$e].find(d=>d&&!d.closed&&d.targetPeerId===i.targetPeerId),l=c||await Wt(i,a);try{if(a.aborted)throw a.reason;const d=await l.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(a.aborted)throw a.reason;if(typeof d.routeToken!="string")throw new Error("入口未允许此设备连接该服务。");const u=new URL(ur(i.url));return u.pathname="/api/federation/relay",u.searchParams.set("routeToken",d.routeToken),await cr({url:u.href,targetPeerId:t.targetPeerId,identity:r,socketFactory:Uh(t.targetPeerId),signal:AbortSignal.any([a,AbortSignal.timeout(8e3)])})}finally{c||l.close()}}});const o=Hh(t.targetPeerId);n.sort((i,a)=>+(a.key===o)-+(i.key===o));const s=await Kh(n,i=>i.close());return qh(t.targetPeerId,s.key),s.value}async function jx(t,e){const r=await Gh(t,e),n=()=>r.close();e.addEventListener("abort",n,{once:!0});try{if(e.aborted||(await on(r,{timeoutMs:3e3}),e.aborted))throw e.reason;return r}catch(o){throw r.close(),o}finally{e.removeEventListener("abort",n)}}async function et(t,e={}){const r=Q,n=$e,o=await Ge(),s=Be(t.serviceOrigin||t.url),i=(await We()).find(w=>w.targetPeerId===t.targetPeerId),a={...t,routes:t.routes??i?.routes},c=dr(a),l=lo(a);let d,u,f=t.pairingCode,h="direct";const g=new Set,m=new Map,y=async(w,I)=>{if(r&&!r.closed&&r.targetPeerId===w.targetPeerId)return r;if(n&&!n.closed&&n.targetPeerId===w.targetPeerId)return n;const v=m.get(w.targetPeerId);if(v&&!v.closed)return v;const A=await Wt(w,I);return g.add(A),m.set(w.targetPeerId,A),A};try{if(t.routeCode&&t.entryServiceId){const k=c.find(R=>R.targetPeerId===t.entryServiceId);if(!k)throw new Error("邀请缺少入口信息。");if((await(await y(k)).request({type:"route-pair",code:t.routeCode})).serviceId!==t.targetPeerId)throw new Error("邀请的目标服务不一致。");t.routeOnly&&await Et({id:t.targetPeerId,url:s,label:t.serviceName||new URL(s).host,targetPeerId:t.targetPeerId,serviceOrigin:s,routes:c})}const w=[],I=async(k,x)=>{const S=()=>k.close();x.addEventListener("abort",S,{once:!0});try{if(x.aborted||(await on(k),x.aborted))throw x.reason}catch(R){throw k.close(),R}finally{x.removeEventListener("abort",S)}};for(const k of l)w.push({key:`direct:${k}`,run:async x=>{const S=await cr({url:ur(k),targetPeerId:t.targetPeerId,pairingCode:f,identity:o,signal:AbortSignal.any([x,AbortSignal.timeout(8e3)])});return f=void 0,await I(S,x),{client:S,path:"direct"}}});for(const k of c)w.push({key:`relay:${k.targetPeerId}:${k.url}`,run:async x=>{let S,R;try{if(S=await y(k,x),x.aborted)throw x.reason;const P=await S.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(x.aborted)throw x.reason;if(typeof P.routeToken!="string"||!P.routeToken)throw new Error("入口未允许此设备连接该服务。");const b=new URL(ur(k.url));return b.pathname="/api/federation/relay",b.searchParams.set("routeToken",P.routeToken),R=await cr({url:b.href,targetPeerId:t.targetPeerId,pairingCode:f,identity:o,socketFactory:Uh(t.targetPeerId),signal:AbortSignal.any([x,AbortSignal.timeout(8e3)])}),f=void 0,await I(R,x),{client:R,entry:S,path:"relay"}}catch(P){throw R?.close(),S&&S!==n&&S!==r&&S.close(),P}}});const v=Hh(t.targetPeerId);w.sort((k,x)=>+(x.key===v)-+(k.key===v));const A=await Kh(w,k=>{k.client.close(),k.entry&&k.entry!==r&&k.entry!==n&&k.entry.close()},!!f);if(d=A.value.client,u=A.value.entry,h=A.value.path,qh(t.targetPeerId,A.key),Q!==r&&Q&&!Q.closed&&Q.targetPeerId===t.targetPeerId){d.close();for(const k of g)k!==$e&&k.close();return Q}h==="direct"&&new URL(s).host===location.host&&hg(t.targetPeerId);const B=(await We()).find(k=>k.targetPeerId===t.targetPeerId||!k.targetPeerId&&(k.serviceOrigin||k.url)===s),T=B?.label||t.serviceName||new URL(s).host,N={url:s,targetPeerId:t.targetPeerId,serviceName:T,serviceOrigin:s,routes:a.routes??c};if(await(e.rememberOnly?mg:Et)({id:B?.id||t.targetPeerId,...N,label:T}),_r!=="unpaired"&&_r!==t.targetPeerId&&St()&&ys({id:B?.id||t.targetPeerId,...N,label:T})){d.close();for(const k of g)k!==r&&k!==n&&k.close();return r||d}Pu(N),Q=d,Jn=h,$e=u;for(const k of new Set([r,n,...g]))k&&k!==d&&k!==u&&k.close();return _r!==t.targetPeerId?(location.reload(),new Promise(()=>{})):(window.dispatchEvent(new Event(lr)),d)}catch(w){d?.close();for(const I of g)I!==n&&I.close();throw w}}async function Ux(){const t=Q,e=ne();if(Date.now()-bd<6e4||yi||Jn!=="relay"||!t||t.closed||!t.canSwitchTransport||!e?.serviceOrigin)return;yi=!0,bd=Date.now();let r;try{for(const o of lo(e))try{r=await cr({url:ur(o),targetPeerId:e.targetPeerId,identity:await Ge(),signal:AbortSignal.timeout(3e3)}),await on(r);break}catch(s){if(r?.close(),r=void 0,s instanceof Ve)throw s}if(!r||Q!==t||!t.canSwitchTransport)return;const n=$e;Q=r,r=void 0,$e=void 0,Jn="direct",t.close(),n?.close(),window.dispatchEvent(new Event(lr))}catch(n){n instanceof Ve&&Q===t&&(Vh(),window.dispatchEvent(new Event("auth:unauthorized")))}finally{r?.close(),yi=!1}}function $x(){return Jn}async function lt(){if(Q&&!Q.closed)return Q;if(Q=void 0,bn)return bn;const t=ne();if(!t)throw new Error("DEVICE_PAIRING_REQUIRED");return bn=et(t,{rememberOnly:!0}).catch(e=>{if(Q&&!Q.closed&&Q.targetPeerId===t.targetPeerId)return Q;throw e}).finally(()=>{bn=void 0}),bn}function Hx(t){const e=new URL(t,location.href);if(Q&&!Q.closed)return Q.openSocket(e.pathname+e.search);let r;const n=new jh(t,o=>r?.send(o),()=>r?.close());return lt().then(o=>{n.readyState!==3&&(r=o.openSocket(e.pathname+e.search),r.onopen=()=>n.accept({type:"ws-ready",id:""}),r.onmessage=s=>n.accept({type:"ws-data",id:"",data:s.data}),r.onclose=s=>n.accept({type:"ws-close",id:"",code:s.code,reason:s.reason}),r.onerror=()=>n.fail(new Error("Encrypted connection unavailable")))}).catch(o=>n.fail(o)),n}function qx(){Nx(lt),window.fetch=async(t,e)=>{const r=new URL(t instanceof Request?t.url:String(t),location.href);if(!r.pathname.startsWith("/api/"))return Qr(t,e);if(r.origin!==location.origin)throw new Error("Remote business API requires a paired encrypted service");if(r.pathname==="/api/meta")return Qr(t,e);if(r.pathname==="/api/auth/status"){if(!ne()){const o=await Wh();return Response.json({enabled:o.enabled,authenticated:!1})}try{const o=await on(await lt());return Response.json({enabled:o.grants.length>0,authenticated:!0})}catch(o){if(o instanceof Ve)return Response.json({enabled:!0,authenticated:!1});throw o}}if(r.pathname==="/api/auth/login"){const s=await new Request(t instanceof Request?t:r.href,e).json();return Mx(typeof s.password=="string"?s.password:"")}if(r.pathname==="/api/csrf-token")return Response.json({csrfToken:"encrypted-device-channel"});if(r.pathname==="/api/auth/logout")return Q&&!Q.closed&&await Q.request({type:"logout"}),Q?.close(),$e?.close(),Q=void 0,$e=void 0,fg(),location.reload(),Response.json({ok:!0});const n=await lt();return t instanceof Request?n.fetch(t,e):n.fetch(r.pathname+r.search,e)}}async function Kx(t){if(!t.targetPeerId)throw new Error("请先连接这台服务,再查看可中转的服务。");for(const e of lo({...t,targetPeerId:t.targetPeerId})){let r;const n={url:e,targetPeerId:t.targetPeerId};try{r=await Wt(n)}catch{continue}try{const o=await r.request({type:"route-targets"},{timeoutMs:5e3});if(!Array.isArray(o.items))throw new Error("入口服务需要更新后才能查看中转列表。");return{route:n,canManage:o.canManage===!0,items:o.items}}catch(o){throw o instanceof Error&&/UNKNOWN|UNSUPPORTED/i.test(o.message)?new Error("入口服务需要更新后才能查看中转列表。"):o}finally{r.close()}}throw new Error("暂时连不上中转入口,请检查地址和网络后重试。")}async function zx(t,e){const r=await Wt(t);try{const n=await r.request({type:"route-targets"},{timeoutMs:5e3}),o=(Array.isArray(n.items)?n.items:[]).find(c=>c.serviceId===e);if(!o)throw new Error("该服务已不可见,请刷新列表或请入口管理员授权。");if(!o.available)throw new Error("入口暂时无法中转到这台服务,请稍后重试。");const s=(await We()).find(c=>c.targetPeerId===o.serviceId),i=[t,...(s?.routes||[]).filter(c=>c.targetPeerId!==t.targetPeerId)];if(i.length>4)throw new Error("这台服务已保存 4 个备用连接,请先移除一个后重试。");if(!o.authorized){if(!n.canManage)throw new Error("请先让入口管理员授权此设备。");await r.request({type:"route-grant",serviceId:o.serviceId,subjectId:(await Ge()).peerId})}const a=s?.serviceOrigin||s?.url||o.url||t.url;return{url:a,serviceOrigin:a,targetPeerId:o.serviceId,serviceName:s?.label||o.label||(o.url?new URL(o.url).host:`中转服务 ${o.serviceId.slice(0,8)}`),routes:i}}finally{r.close()}}async function Vx(t,e){const r=await Wt(t);try{const n=await r.request({type:"route-access"},{timeoutMs:5e3}),o=(await Ge()).peerId;return{canManage:n.canManage===!0,grants:(Array.isArray(n.grants)?n.grants:[]).filter(s=>s.subjectId===o&&s.targetServiceId===e)}}finally{r.close()}}async function Wx(t,e,r){if(r!==void 0&&(await Tc(Be(e.url),r)).targetPeerId!==e.targetPeerId)throw new Error("入口服务的身份已改变,请重新连接并确认。");const n=await Wt(e);try{await n.request({type:"route-grant",serviceId:t.targetPeerId,subjectId:(await Ge()).peerId,url:Be(t.serviceOrigin||t.url)})}finally{n.close()}}async function Gx(t,e){const r=await Wt(e);try{const n=await r.request({type:"route-access"},{timeoutMs:5e3}),o=(await Ge()).peerId,s=(Array.isArray(n.grants)?n.grants:[]).filter(i=>i.subjectId===o&&i.targetServiceId===t&&i.active);for(const i of s)await r.request({type:"route-revoke",grantId:i.id})}finally{r.close()}}async function Xh(t,e){const r=await Wt(e);try{const n=await r.request({type:"route-invite-create",serviceId:t.targetPeerId});if(typeof n.routeCode!="string"||typeof n.expiresAt!="number")throw new Error("暂时无法生成备用连接邀请。");return{routeCode:n.routeCode,expiresAt:n.expiresAt}}finally{r.close()}}async function $o(t,e){const r=(await We()).find(o=>o.id===t.id||t.targetPeerId&&o.targetPeerId===t.targetPeerId)||t;await Et({...r,url:r.serviceOrigin||r.url,entryServiceId:void 0,routes:e});const n=ne();n&&n.targetPeerId===t.targetPeerId&&Pu({...n,url:n.serviceOrigin||n.url,entryServiceId:void 0,routes:e})}async function Xx(t,e){const r=t.targetPeerId;if(!r)throw new Error("请先连接这台服务,再添加备用地址。");let n;try{n=Be(e)}catch{throw new Error("请输入有效的 HTTPS 地址,例如 https://电脑地址:9834。")}const o=async()=>(await We()).find(a=>a.targetPeerId===r)||t,s=a=>{const c=a.routes??dr({...a,targetPeerId:r});if(Be(a.serviceOrigin||a.url)===n||c.some(l=>Be(l.url)===n))throw new Error("这个地址已经在连接列表中。");if(c.length>=4)throw new Error("最多保存 4 个备用地址或入口,请先移除不再使用的连接。");return[...c,{url:n,targetPeerId:r}]};s(await o());let i;try{try{i=await cr({url:ur(n),targetPeerId:r,identity:await Ge(),signal:AbortSignal.timeout(5e3)}),await on(i)}catch(l){throw l instanceof Ve?new Error("这台服务尚未授权当前设备,请先恢复设备授权。"):new Error("无法验证这个地址。请确认能访问该地址、HTTPS 证书受信任,且运行的是同一台 Termdock 服务。")}const a=await o(),c=s(a);if(await $o(a,c),ne()?.targetPeerId===r&&_r===r&&(!Q||Q.closed)){const l=Q,d=$e;Q=i,i=void 0,$e=void 0,Jn="direct",l?.close(),d?.close(),window.dispatchEvent(new Event(lr))}return c}finally{i?.close()}}async function xd(t,e){await Ta(t,e),await et({...t,pairingCode:void 0,routeCode:void 0})}function Yx(t,e){return e.aborted?Promise.reject(e.reason):new Promise((r,n)=>{const o=()=>n(e.reason);e.addEventListener("abort",o,{once:!0}),t.then(r,n).finally(()=>e.removeEventListener("abort",o))})}function Yh(){if(window.termdockDesktop||window.parent!==window)return;if(window.__termdockCollaboration)return window.__termdockCollaboration;const t=new Map;let e=[],r=!1;const n=l=>{const d=l.targetPeerId;if(ne()?.targetPeerId===d)return lt();const u=t.get(d);if(u)return u.then(h=>h.closed?(t.get(d)===u&&t.delete(d),n(l)):h);const f=jx({...l,targetPeerId:d},AbortSignal.timeout(12e3)).then(h=>{if(r||t.get(d)!==f)throw h.close(),new Error("服务连接已移除");return h}).catch(h=>{throw t.get(d)===f&&t.delete(d),h});return t.set(d,f),f},o=()=>{const l=ne(),d=Kt();l&&!d.some(f=>f.targetPeerId===l.targetPeerId)&&d.push({...l,id:l.targetPeerId,label:l.serviceName||l.serviceOrigin||l.url});const u=new Set(d.map(f=>f.targetPeerId));for(const[f,h]of t)u.has(f)||(t.delete(f),h.then(g=>g.close()).catch(()=>{}));e=d.filter(f=>!!f.targetPeerId).map(f=>({origin:f.serviceOrigin||f.url,label:f.label,request:async(h,g="GET",m)=>{if(!/^\/collaboration-(?:federation|groups)(?:\/[^?#]*)?$/.test(h))throw new Error("无效的协作请求");const y=AbortSignal.timeout(18e3),w=await Yx(n(f),y),I=new Headers({"Content-Type":"application/json"});if(g!=="GET"&&g!=="HEAD"){const B=await w.fetch("/api/csrf-token",{signal:y});if(!B.ok)throw new Error("无法读取目标服务的请求令牌");const T=await B.json();if(typeof T.csrfToken!="string")throw new Error("目标服务的请求令牌无效");I.set("X-XSRF-TOKEN",T.csrfToken)}const v=await w.fetch(`/api/terminal/operations${h}`,{method:g,headers:I,signal:y,...m===void 0?{}:{body:JSON.stringify(m)}}),A=v.status===204?void 0:await v.json();if(!v.ok)throw new Error(A?.error||"服务不可达或未授权协作访问");return A}}))},s=new gg(()=>e),i={peers:l=>(o(),s.peers(l)),save:async(l,d)=>{o();const u=await s.save(l,d);return a(),u}},a=async()=>{r||document.hidden||!navigator.onLine||!ne()||(o(),!(e.length<2)&&await s.refresh().catch(()=>{}))};window.__termdockCollaboration=i;const c=window.setInterval(()=>{a()},2e3);return document.addEventListener("visibilitychange",a),window.addEventListener("online",a),window.addEventListener("pageshow",a),window.addEventListener("pagehide",l=>{if(!l.persisted){r=!0,clearInterval(c);for(const d of t.values())d.then(u=>u.close()).catch(()=>{});t.clear()}}),a(),i}function Zh(){if(!window.termdockDesktop)try{if(window.parent===window)return Yh();if(location.pathname==="/workspace.html"&&window.parent.location.origin===location.origin)return window.parent.__termdockCollaboration}catch{}}var Lo={},Sd;function Zx(){if(Sd)return Lo;Sd=1;var t=rg();return Lo.createRoot=t.createRoot,Lo.hydrateRoot=t.hydrateRoot,Lo}var Jx=Zx();const Qx=Tu(Jx);const Jh=(...t)=>t.filter((e,r,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===r).join(" ").trim();const eS=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const tS=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,r,n)=>n?n.toUpperCase():r.toLowerCase());const Ed=t=>{const e=tS(t);return e.charAt(0).toUpperCase()+e.slice(1)};var bi={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const rS=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1},nS=F.createContext({}),oS=()=>F.useContext(nS),sS=F.forwardRef(({color:t,size:e,strokeWidth:r,absoluteStrokeWidth:n,className:o="",children:s,iconNode:i,...a},c)=>{const{size:l=24,strokeWidth:d=2,absoluteStrokeWidth:u=!1,color:f="currentColor",className:h=""}=oS()??{},g=n??u?Number(r??d)*24/Number(e??l):r??d;return F.createElement("svg",{ref:c,...bi,width:e??l??bi.width,height:e??l??bi.height,stroke:t??f,strokeWidth:g,className:Jh("lucide",h,o),...!s&&!rS(a)&&{"aria-hidden":"true"},...a},[...i.map(([m,y])=>F.createElement(m,y)),...Array.isArray(s)?s:[s]])});const Pe=(t,e)=>{const r=F.forwardRef(({className:n,...o},s)=>F.createElement(sS,{ref:s,iconNode:e,className:Jh(`lucide-${eS(Ed(t))}`,`lucide-${t}`,n),...o}));return r.displayName=Ed(t),r};const iS=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Qh=Pe("arrow-left",iS);const aS=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],cS=Pe("arrow-right",aS);const lS=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M11.68 2.009A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673c-.824-.85-1.678-1.731-2.21-3.348",key:"xaq59h"}],["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}]],dS=Pe("bell-dot",lS);const uS=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Pc=Pe("check",uS);const fS=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],hS=Pe("chevron-down",fS);const pS=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],fr=Pe("chevron-right",pS);const gS=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],ep=Pe("copy",gS);const mS=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],wS=Pe("ellipsis",mS);const yS=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],He=Pe("loader-circle",yS);const bS=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],vS=Pe("monitor",bS);const xS=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],SS=Pe("pencil",xS);const ES=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],tp=Pe("plus",ES);const AS=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],js=Pe("server",AS);const kS=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],rp=Pe("smartphone",kS);const IS=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],CS=Pe("terminal",IS);const RS=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],TS=Pe("x",RS);let Lr=null;function PS(t){return!Lr||!t?!1:(Lr(t),!0)}function zk(t){Lr=t;const e=r=>{const{text:n,nonce:o}=r.detail??{};!n||Lr!==t||(t(n),r.stopImmediatePropagation(),o&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:o,ok:!0}})))};return window.addEventListener("termdock-insert-reference",e,!0),()=>{Lr===t&&(Lr=null),window.removeEventListener("termdock-insert-reference",e,!0)}}const NS=/^[A-Za-z0-9_@%+=:,./-]$/;function LS(t){return Array.from(t,e=>(e.codePointAt(0)??0)>127||NS.test(e)?e:`\\${e}`).join("")}function BS(t,e){if(!e)return!1;try{const r=new URL(e.serviceOrigin||e.url);return r.origin===t&&/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})$/.test(r.hostname)&&!(e.routes??[]).some(n=>n.targetPeerId!==e.targetPeerId)}catch{return!1}}function _S(t){const e=s=>s.target instanceof Element?s.target.closest("[data-termdock-terminal-dropzone]"):null,r=()=>!BS(location.origin,Dr()),n=s=>{const i=e(s);!i||!r()||!s.dataTransfer?.types.includes("Files")||(s.preventDefault(),s.stopImmediatePropagation(),s.dataTransfer.dropEffect="copy",i.dataset.nativeFileDrag="true",i.dataset.nativeFileDropState="remote")},o=s=>{const i=e(s),a=Array.from(s.dataTransfer?.files??[]);if(!i||!a.length||!r())return;s.preventDefault(),s.stopImmediatePropagation();const c=i.dataset.termdockTerminalDropzone??"";i.dataset.nativeFileDrag="true",i.dataset.nativeFileDropState="uploading",Vt(async()=>{const{uploadFiles:l}=await Promise.resolve().then(()=>Z2);return{uploadFiles:l}},void 0).then(({uploadFiles:l})=>l("/tmp",a)).then(l=>{if(l.files.length!==a.length||l.files.some(d=>!d.path))throw new Error("Upload did not return every file path");delete i.dataset.nativeFileDrag,delete i.dataset.nativeFileDropState,t({sessionKey:c,paths:l.files.map(d=>d.path)})}).catch(l=>{i.dataset.nativeFileDropState="error",i.dispatchEvent(new CustomEvent("termdock:file-drop-error",{bubbles:!0,detail:l instanceof Error?l.message:"File upload failed"})),window.setTimeout(()=>{i.dataset.nativeFileDropState==="error"&&(delete i.dataset.nativeFileDrag,delete i.dataset.nativeFileDropState)},3e3)})};return window.addEventListener("dragover",n,!0),window.addEventListener("drop",o,!0),()=>{window.removeEventListener("dragover",n,!0),window.removeEventListener("drop",o,!0)}}function np(){return typeof window>"u"?null:window.termdockDesktop??null}const vi=new Set;let Ad=!1;function Vk(t){const e=np();if(!e)return()=>{};if(vi.add(t),!Ad){const r=n=>{if(!PS(n.paths.map(LS).join(" ")+" "))for(const o of vi)o(n)};_S(r),e.onNativeFileDrop(r),Ad=!0}return()=>{vi.delete(t)}}function op(t=navigator.userAgent,e=navigator.maxTouchPoints){const r=/iPad/.test(t)||/Macintosh/.test(t)&&e>1?"iPad":/iPhone/.test(t)?"iPhone":/Android/.test(t)?"Android":/Windows/.test(t)?"Windows":/Macintosh|Mac OS X/.test(t)?"Mac":/Linux/.test(t)?"Linux":"设备",n=/Electron/.test(t)?"Termdock":/Edg\//.test(t)?"Edge":/Firefox|FxiOS/.test(t)?"Firefox":/Chrome|CriOS/.test(t)?"Chrome":/Safari/.test(t)?"Safari":"浏览器";return`${r} · ${n}`}let DS;function OS(){return DS??=(async()=>{const t=navigator.userAgent,[e,r]=op().split(" · "),n=/(?:Edg|Firefox|FxiOS|Chrome|CriOS|Version)\/([\d.]+)/g,o=[...t.matchAll(n)],s=/(?:CPU (?:iPhone )?OS |Mac OS X |Android )([\d._]+)/.exec(t)?.[1]?.replaceAll("_","."),i={system:`${e}${s?` ${s}`:""}`,client:`${r}${o.length?` ${o.at(-1)[1]}`:""}`,mode:matchMedia("(display-mode: standalone)").matches||navigator.standalone?"已安装的网页应用":"网页"},a=np();if(a){i.mode="桌面客户端";const l=/Electron\/([\d.]+)/.exec(t)?.[1];i.client=l?`Termdock(Electron ${l})`:"Termdock";try{Object.assign(i,await a.deviceInfo?.())}catch{}return i}const c=navigator.userAgentData;try{const l=await c?.getHighEntropyValues(["model","architecture","bitness","platformVersion"]);typeof l?.model=="string"&&l.model&&(i.model=l.model),typeof l?.architecture=="string"&&l.architecture&&(i.arch=`${l.architecture}${l.bitness?` ${l.bitness} 位`:""}`)}catch{}return i})()}function FS({service:t,onBusyChange:e,onConnect:r,onConnectWithPassword:n}){const[o,s]=F.useState(),[i,a]=F.useState(!0),[c,l]=F.useState(!1),[d,u]=F.useState(""),[f,h]=F.useState(0),[g,m]=F.useState(),[y,w]=F.useState("");F.useEffect(()=>{let A=!1;return a(!0),u(""),s(void 0),Kx(t).then(B=>{A||s(B)}).catch(B=>{A||u(B instanceof Error?B.message:"暂时无法读取中转列表,请重试。")}).finally(()=>{A||a(!1)}),()=>{A=!0}},[t.id,t.url,f]);const I=async A=>{if(!c){l(!0),e(!0),u("");try{await A()}catch(B){u(B instanceof Error?B.message:"暂时无法连接,请重试。")}finally{l(!1),e(!1)}}},v=async A=>{const B=await zx(o.route,A.serviceId);try{await r(B)}catch(T){if(!(T instanceof Ve))throw T;m(B)}};return p.jsxs("div",{className:"service-form",children:[g?p.jsxs("form",{className:"service-form",onSubmit:A=>{A.preventDefault(),I(async()=>{try{await n?.(g,y)}finally{w("")}})},children:[p.jsxs("p",{className:"service-help",children:["已通过“",t.label,"”连接到“",g.serviceName,"”。请登录目标服务,完成此设备的访问授权。"]}),n?p.jsxs(p.Fragment,{children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"目标服务密码"}),p.jsx("input",{type:"password",autoFocus:!0,required:!0,autoComplete:"current-password",value:y,disabled:c,onChange:A=>w(A.target.value)})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:c||!y,children:c?"正在登录…":"登录并连接"})]}):p.jsx("p",{className:"service-help",children:"请让目标服务管理员邀请此设备后再连接。"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>{m(void 0),w(""),u(""),h(A=>A+1)},children:"返回中转列表"})]}):p.jsxs(p.Fragment,{children:[p.jsxs("p",{className:"service-help",children:["通过“",t.label,"”连接下方服务。",o?.canManage?"选择未授权的服务会授权此设备使用该中转。":"这里只显示已授权给此设备的中转。","目标服务会单独验证访问权限。"]}),i?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在读取可中转的服务…"]}):o&&p.jsxs("div",{className:"service-list",children:[o.items.map(A=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:c||!A.available,onClick:()=>{I(()=>v(A))},children:[p.jsx("span",{className:"service-icon",children:p.jsx(js,{size:19})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:A.label||(A.url?new URL(A.url).host:`中转服务 ${A.serviceId.slice(0,8)}`)}),p.jsx("span",{className:"service-description",children:A.available?A.authorized?"已获中转授权 · 连接":"授权此设备并连接":"中转暂不可用"})]}),p.jsx(fr,{size:16})]},A.serviceId)),o.items.length===0&&p.jsx("p",{className:"service-empty",children:o.canManage?"暂无可中转的服务。可在本机 Mac 客户端连接目标服务,或在目标服务的“备用连接”中启用本入口。":"暂无已授权的中转服务,请让入口管理员分享备用连接邀请。"})]}),c&&p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在授权并连接目标服务…"]}),!i&&p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>h(A=>A+1),children:"刷新列表"})]}),d&&p.jsx("p",{className:"service-error",role:"alert",children:d})]})}const Pa="#termdock-invite=";function sp(t){const e=new URL(t.entryUrl);e.hash="",e.search="",e.pathname="/";const r=new TextEncoder().encode(JSON.stringify(t));return e.hash=Pa.slice(1)+btoa(String.fromCharCode(...r)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),e.href}function bs(t){const e=new URL(t);if(!["https:","http:"].includes(e.protocol)||!e.hash.startsWith(Pa))throw new Error("这不是有效的 Termdock 邀请链接");const r=e.hash.slice(Pa.length);if(r.length>8192)throw new Error("邀请链接过长");let n;try{const i=r.replace(/-/g,"+").replace(/_/g,"/");n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(atob(i),a=>a.charCodeAt(0))))}catch{throw new Error("邀请链接不完整,请重新复制")}if(n.v!==1||typeof n.serviceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(n.serviceId)||n.routeOnly!==!0&&(typeof n.code!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(n.code)))throw new Error("邀请信息无效或版本不兼容");const o=new URL(n.entryUrl);if(o.origin!==e.origin||o.username||o.password||!["https:","http:"].includes(o.protocol))throw new Error("邀请地址与服务不一致");if(o.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(o.hostname))throw new Error("远程邀请需要 HTTPS");if(n.entryServiceId!==void 0&&(typeof n.entryServiceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(n.entryServiceId)))throw new Error("邀请入口身份无效");if(n.routeCode!==void 0&&(typeof n.routeCode!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(n.routeCode)||!n.entryServiceId))throw new Error("邀请入口权限无效");if(n.routeOnly===!0&&(!n.entryServiceId||!n.routeCode||n.code!==void 0))throw new Error("备用连接邀请不完整");let s=o.origin;if(n.serviceUrl!==void 0){const i=new URL(n.serviceUrl);if(!["https:","http:"].includes(i.protocol)||i.username||i.password)throw new Error("目标服务地址无效");s=n.entryServiceId&&n.entryServiceId!==n.serviceId?i.origin:o.origin}return{url:o.origin,targetPeerId:n.serviceId,pairingCode:n.code,...n.routeOnly===!0?{routeOnly:!0}:{},serviceOrigin:s,serviceName:typeof n.name=="string"?n.name.slice(0,120):void 0,entryServiceId:n.entryServiceId,routeCode:n.routeCode}}function MS({service:t,onBusyChange:e}){const r={...t,targetPeerId:t.targetPeerId,serviceName:t.label},[n,o]=F.useState(()=>t.routes??dr(r)),[s,i]=F.useState([]),[a,c]=F.useState(!0),[l,d]=F.useState(!1),[u,f]=F.useState(""),h=D=>{d(D),e(D)},[g,m]=F.useState(),[y,w]=F.useState(""),[I,v]=F.useState(""),[A,B]=F.useState(""),[T,N]=F.useState(!1),[k,x]=F.useState(),[S,R]=F.useState(),[P,b]=F.useState(!1);F.useEffect(()=>{let D=!1;return We().then(_=>{D||i(_.filter(O=>O.targetPeerId&&O.targetPeerId!==t.targetPeerId))}).catch(()=>{D||f("暂时无法读取可用服务。")}).finally(()=>{D||c(!1)}),()=>{D=!0}},[t.targetPeerId]);const E=D=>s.find(_=>_.targetPeerId===D.targetPeerId)?.label||new URL(D.url).host,C=async D=>{h(!0),f(""),B("");try{await D()}catch(_){const O=_ instanceof Error?_.message:"";f(/AUTHORIZATION|DENIED/.test(O)?"当前设备没有入口管理权限。请让管理员分享备用连接邀请,或使用入口密码授权。":"暂时无法完成。请确认入口能连接目标服务,且目标地址、证书和授权有效。")}finally{h(!1)}},L=async(D,_)=>{const O={url:D.serviceOrigin||D.url,targetPeerId:D.targetPeerId};await C(async()=>{const q=await Vx(O,r.targetPeerId);if(!q.grants.some(K=>K.active)){if(!q.canManage&&_===void 0){m(D);return}await Wx(r,O,_)}const H=[...n.filter(K=>K.targetPeerId!==O.targetPeerId),O];await $o(t,H),o(H),m(void 0),w("")})};if(S)return p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["把链接发给需要使用此备用连接的人。它只允许通过入口连接“",t.label,"”,对方仍需获得目标服务的访问权限。"]}),p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用连接邀请"}),p.jsx("input",{readOnly:!0,value:S,onFocus:D=>D.target.select()})]}),p.jsxs("button",{type:"button",className:"service-button service-primary",onClick:()=>{navigator.clipboard.writeText(S).then(()=>b(!0)).catch(()=>f("无法自动复制,请长按链接复制。"))},children:[p.jsx(ep,{size:16}),P?"已复制":"复制邀请链接"]}),p.jsx("button",{type:"button",className:"service-button service-secondary",onClick:()=>{R(void 0),b(!1)},children:"返回备用连接"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});if(g)return p.jsxs("form",{className:"service-form",onSubmit:D=>{D.preventDefault(),L(g,y).finally(()=>w(""))},children:[p.jsxs("p",{className:"service-help",children:["需要“",g.label,"”的管理员授权。若这是你的服务,可以使用它的密码;否则请管理员分享备用连接邀请。"]}),p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"入口服务密码"}),p.jsx("input",{type:"password",required:!0,value:y,onChange:D=>w(D.target.value),autoComplete:"current-password",disabled:l,autoFocus:!0})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||!y,children:l?"正在授权…":"授权并启用"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{m(void 0),w("")},children:"取消"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});const M=n.filter(D=>D.targetPeerId===r.targetPeerId),$=n.filter(D=>D.targetPeerId!==r.targetPeerId),j=async()=>{if(!l){h(!0),N(!0),f(""),B("");try{o(await Xx({...t,routes:n},I)),v(""),B("备用地址已验证并保存。")}catch(D){f(D instanceof Error?D.message:"暂时无法添加地址,请重试。")}finally{h(!1),N(!1)}}};return p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"电脑换了网络?添加它在新网络下的地址,原地址连不上时会自动尝试。只接受同一台服务。"}),p.jsxs("form",{className:"service-form",onSubmit:D=>{D.preventDefault(),j()},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用地址"}),p.jsx("input",{value:I,onChange:D=>{v(D.target.value),f(""),B("")},required:!0,disabled:l||n.length>=4,inputMode:"url",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:192.168.10.20:9834"})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||n.length>=4||!I.trim(),children:T?p.jsxs(p.Fragment,{children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在验证…"]}):"验证并添加"})]}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u}),A&&p.jsx("p",{role:"status",className:"service-help",children:A}),n.length>=4&&p.jsx("p",{className:"service-help",children:"已保存 4 个备用连接。移除不再使用的地址或入口后,可以继续添加。"}),p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"首选地址"}),p.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url})]}),M.length>0&&p.jsx("div",{className:"service-list",children:M.map(D=>p.jsxs("div",{className:"service-route-item",children:[p.jsxs("div",{className:"service-route-line",children:[p.jsx("span",{className:"service-address service-route-address",children:D.url}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`移除地址 ${D.url}`,disabled:l,onClick:()=>x(D),children:"移除"})]}),k?.targetPeerId===D.targetPeerId&&k.url===D.url&&p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"从备用连接中移除此地址?不会停止正在运行的终端。"}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>x(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{C(async()=>{const _=n.filter(O=>O.targetPeerId!==D.targetPeerId||O.url!==D.url);await $o(t,_),o(_),x(void 0)})},children:"确认移除"})]})]})]},D.url))}),p.jsxs("details",{className:"service-relay-options",children:[p.jsxs("summary",{children:["通过其他服务中转",$.length?`(${$.length})`:""]}),p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"所有直连地址都不可用时,尝试下方已授权入口;直连恢复后自动切回。"}),$.length>0&&p.jsx("div",{className:"service-list",children:$.map(D=>p.jsxs("div",{className:"service-route-item",children:[p.jsxs("div",{className:"service-route-line",children:[p.jsx("span",{className:"service-icon",children:p.jsx(js,{size:18})}),p.jsx("span",{className:"service-name",children:E(D)}),p.jsx(Pc,{size:16,className:"service-selected"})]}),k?.targetPeerId===D.targetPeerId?p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["撤销此设备经“",E(D),"”连接目标的权限?如当前无法直连,目标服务将断开。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>x(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{C(async()=>{await Gx(r.targetPeerId,D);const _=n.filter(O=>O.targetPeerId!==D.targetPeerId);await $o(t,_),o(_),x(void 0)})},children:"确认撤销"})]})]}):p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{C(async()=>{const _=await Xh(r,D);R(sp({v:1,routeOnly:!0,serviceId:r.targetPeerId,name:t.label,serviceUrl:t.serviceOrigin||t.url,entryUrl:D.url,entryServiceId:D.targetPeerId,routeCode:_.routeCode}))})},children:"分享备用连接"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>x(D),children:"撤销授权"})]})]},D.targetPeerId))}),a?p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"添加中转入口"}),s.filter(D=>!n.some(_=>_.targetPeerId===D.targetPeerId)).map(D=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:l||n.length>=4,onClick:()=>{L(D)},children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:D.label}),p.jsx("span",{className:"service-description",children:"验证并授权后启用"})]}),p.jsx(fr,{size:16})]},D.id)),s.length===0&&p.jsx("p",{className:"service-empty",children:"添加并登录另一台服务后,可以将它设为中转入口。"})]})]})]}),l&&!T&&p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在验证连接与授权…"]})]})}function jS({current:t,renderRoutes:e,renderRelayServices:r,onOpen:n,onAdd:o,onInvite:s,hideHeader:i,onNavigation:a,onBusyChange:c,initiallyAdding:l=!1}){const[d,u]=F.useState([]),[f,h]=F.useState(!0),[g,m]=F.useState(l?{kind:"add"}:{kind:"list"}),[y,w]=F.useState(!1),I=F.useCallback(b=>{w(b),c?.(b)},[c]),[v,A]=F.useState(""),B=F.useCallback(()=>{m(b=>b.kind==="routes"||b.kind==="relay-services"?{kind:"edit",service:b.service}:{kind:"list"}),A("")},[]),T=g.kind==="add"?"添加服务":g.kind==="edit"?"服务设置":g.kind==="routes"?"备用连接":g.kind==="relay-services"?"可中转的服务":void 0;F.useEffect(()=>{a?.({title:T,...T?{back:B}:{}})},[T,B,a]),F.useEffect(()=>{let b=!1,E=0;const C=async()=>{const M=++E;try{const $=await We();!b&&E===M&&(u($),A(""))}catch{!b&&E===M&&A("暂时无法读取服务列表,请重试。")}finally{!b&&E===M&&h(!1)}};C();const L=Bu(()=>{C()});return()=>{b=!0,L()}},[]);const N=async b=>{if(!y){I(!0),A("");try{await b()}catch(E){A(E instanceof Error?E.message:"暂时无法完成,请重试。")}finally{I(!1)}}},k=g.kind==="edit"||g.kind==="routes"||g.kind==="relay-services"?d.find(b=>wt(b,g.service))||g.service:void 0,x=t?d.find(b=>wt(b,t))||t:void 0,S=d.filter(b=>!t||!wt(b,t)),R=x?[x,...S]:S,P=p.jsxs(p.Fragment,{children:[f?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{className:"service-list",children:[R.map(b=>{const E=!!t&&wt(b,t);return p.jsxs("div",{className:"service-row",children:[p.jsxs("button",{type:"button",className:"service-row-open",disabled:y||E,onClick:()=>{N(async()=>{(await n(b))?.passwordRequired&&m({kind:"add",input:b.serviceOrigin||b.url,passwordRequired:!0})})},"aria-label":E?`当前服务 ${b.label}`:`打开 ${b.label}`,children:[p.jsx("span",{className:"service-icon",children:p.jsx(js,{size:20})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:b.label}),p.jsx("span",{className:"service-description",children:E?"当前服务":new URL(b.serviceOrigin||b.url).host})]}),E?p.jsx(Pc,{size:17,className:"service-selected"}):p.jsx(fr,{size:16,className:"service-muted"})]}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`管理 ${b.label}`,disabled:y,onClick:()=>{m({kind:"edit",service:b}),A("")},children:p.jsx(wS,{size:19})})]},b.id)}),R.length===0&&p.jsx("p",{className:"service-empty",children:"还没有添加服务。连接你的电脑,或粘贴收到的邀请链接。"})]}),p.jsxs("div",{className:`service-actions${s?" service-actions-pair":""}`,children:[p.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:y,onClick:()=>{m({kind:"add"}),A("")},children:[p.jsx(tp,{size:16}),"添加服务"]}),s&&p.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:y,onClick:s,children:[p.jsx(rp,{size:16}),"邀请设备"]})]})]});return p.jsxs("div",{className:"service-manager",children:[!i&&p.jsxs("div",{className:"service-heading",children:[T&&p.jsx("button",{type:"button",className:"service-icon-button","aria-label":"返回服务",disabled:y,onClick:B,children:p.jsx(Qh,{size:20})}),p.jsx("h2",{children:T||"服务"})]}),g.kind==="relay-services"?r?.(k,I):g.kind==="routes"?e?.(k,I):g.kind==="list"?P:g.kind==="add"?p.jsx(US,{onSave:b=>N(async()=>{const E=Be(b);u(await Et({id:E,url:E,label:new URL(E).host})),B()}),initialInput:g.input,passwordRequired:g.passwordRequired,busy:y,onSubmit:async(b,E)=>{let C;return await N(async()=>{C=await o(b,E),C?.passwordRequired||B()}),C}}):p.jsx($S,{onRelayServices:r&&g.service.targetPeerId?()=>m({kind:"relay-services",service:g.service}):void 0,onRoutes:e&&g.service.targetPeerId?()=>m({kind:"routes",service:g.service}):void 0,service:k,busy:y,canRemove:!t||!wt(g.service,t),onSave:b=>{N(async()=>{u(await Et({...k,label:b})),B()})},onRemove:()=>{N(async()=>{u(await wg(g.service.id)),B()})}}),v&&p.jsx("p",{className:"service-error",role:"alert",children:v})]})}function US({busy:t,onSubmit:e,onSave:r,initialInput:n="",passwordRequired:o=!1}){const[s,i]=F.useState(n),[a,c]=F.useState(""),[l,d]=F.useState(o);return p.jsxs("form",{className:"service-form",onSubmit:async u=>{u.preventDefault(),(await e(s.trim(),l?a:void 0))?.passwordRequired&&d(!0),c("")},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务地址或邀请链接"}),p.jsx("input",{value:s,onChange:u=>{i(u.target.value),d(!1),c("")},disabled:t,required:!0,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:电脑地址:9834 或 https://…"})]}),l?p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务密码"}),p.jsx("input",{type:"password",value:a,onChange:u=>c(u.target.value),disabled:t,required:!0,autoFocus:!0,autoComplete:"current-password",placeholder:"输入这台服务的密码"})]}):p.jsx("p",{className:"service-help",children:"连接自己的服务,输入地址即可;收到邀请时,粘贴完整链接。"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:t||!s.trim()||s.includes("#termdock-invite="),onClick:()=>{r(s.trim())},children:"仅保存,不连接"}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:t||!s.trim()||l&&!a,children:t?p.jsxs(p.Fragment,{children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在连接…"]}):l?"登录并连接":"继续"})]})}function $S({service:t,busy:e,canRemove:r,onSave:n,onRemove:o,onRoutes:s,onRelayServices:i}){const[a,c]=F.useState(t.label),[l,d]=F.useState(!1);return p.jsxs("form",{className:"service-form",onSubmit:u=>{u.preventDefault(),n(a.trim())},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务名称"}),p.jsx("input",{value:a,onChange:u=>c(u.target.value),disabled:e,required:!0,maxLength:120,placeholder:"例如:办公室电脑"})]}),p.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:e||!a.trim(),children:"保存名称"}),i&&p.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:i,children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:"可中转的服务"}),p.jsx("span",{className:"service-description",children:"通过这台服务连接其他电脑"})]}),p.jsx(fr,{size:16})]}),s&&p.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:s,children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:"备用连接"}),p.jsx("span",{className:"service-description",children:"添加其他网络地址或授权入口"})]}),p.jsx(fr,{size:16})]}),r&&p.jsx("div",{className:"service-remove",children:l?p.jsxs(p.Fragment,{children:[p.jsxs("p",{className:"service-help",children:["从列表移除“",t.label,"”?不会停止服务或删除终端。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:e,onClick:()=>d(!1),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:o,children:"确认移除"})]})]}):p.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:()=>d(!0),children:"移除服务"})})]})}var Cr={},xi,kd;function HS(){return kd||(kd=1,xi=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),xi}var Si={},Ot={},Id;function mr(){if(Id)return Ot;Id=1;let t;const e=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Ot.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},Ot.getSymbolTotalCodewords=function(n){return e[n]},Ot.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Ot.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');t=n},Ot.isKanjiModeEnabled=function(){return typeof t<"u"},Ot.toSJIS=function(n){return t(n)},Ot}var Ei={},Cd;function Nc(){return Cd||(Cd=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+r)}}t.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},t.from=function(n,o){if(t.isValid(n))return n;try{return e(n)}catch{return o}}})(Ei)),Ei}var Ai,Rd;function qS(){if(Rd)return Ai;Rd=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(e){const r=Math.floor(e/8);return(this.buffer[r]>>>7-e%8&1)===1},put:function(e,r){for(let n=0;n<r;n++)this.putBit((e>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),e&&(this.buffer[r]|=128>>>this.length%8),this.length++}},Ai=t,Ai}var ki,Td;function KS(){if(Td)return ki;Td=1;function t(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return t.prototype.set=function(e,r,n,o){const s=e*this.size+r;this.data[s]=n,o&&(this.reservedBit[s]=!0)},t.prototype.get=function(e,r){return this.data[e*this.size+r]},t.prototype.xor=function(e,r,n){this.data[e*this.size+r]^=n},t.prototype.isReserved=function(e,r){return this.reservedBit[e*this.size+r]},ki=t,ki}var Ii={},Pd;function zS(){return Pd||(Pd=1,(function(t){const e=mr().getSymbolSize;t.getRowColCoords=function(n){if(n===1)return[];const o=Math.floor(n/7)+2,s=e(n),i=s===145?26:Math.ceil((s-13)/(2*o-2))*2,a=[s-7];for(let c=1;c<o-1;c++)a[c]=a[c-1]-i;return a.push(6),a.reverse()},t.getPositions=function(n){const o=[],s=t.getRowColCoords(n),i=s.length;for(let a=0;a<i;a++)for(let c=0;c<i;c++)a===0&&c===0||a===0&&c===i-1||a===i-1&&c===0||o.push([s[a],s[c]]);return o}})(Ii)),Ii}var Ci={},Nd;function VS(){if(Nd)return Ci;Nd=1;const t=mr().getSymbolSize,e=7;return Ci.getPositions=function(n){const o=t(n);return[[0,0],[o-e,0],[0,o-e]]},Ci}var Ri={},Ld;function WS(){return Ld||(Ld=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},t.from=function(o){return t.isValid(o)?parseInt(o,10):void 0},t.getPenaltyN1=function(o){const s=o.size;let i=0,a=0,c=0,l=null,d=null;for(let u=0;u<s;u++){a=c=0,l=d=null;for(let f=0;f<s;f++){let h=o.get(u,f);h===l?a++:(a>=5&&(i+=e.N1+(a-5)),l=h,a=1),h=o.get(f,u),h===d?c++:(c>=5&&(i+=e.N1+(c-5)),d=h,c=1)}a>=5&&(i+=e.N1+(a-5)),c>=5&&(i+=e.N1+(c-5))}return i},t.getPenaltyN2=function(o){const s=o.size;let i=0;for(let a=0;a<s-1;a++)for(let c=0;c<s-1;c++){const l=o.get(a,c)+o.get(a,c+1)+o.get(a+1,c)+o.get(a+1,c+1);(l===4||l===0)&&i++}return i*e.N2},t.getPenaltyN3=function(o){const s=o.size;let i=0,a=0,c=0;for(let l=0;l<s;l++){a=c=0;for(let d=0;d<s;d++)a=a<<1&2047|o.get(l,d),d>=10&&(a===1488||a===93)&&i++,c=c<<1&2047|o.get(d,l),d>=10&&(c===1488||c===93)&&i++}return i*e.N3},t.getPenaltyN4=function(o){let s=0;const i=o.data.length;for(let c=0;c<i;c++)s+=o.data[c];return Math.abs(Math.ceil(s*100/i/5)-10)*e.N4};function r(n,o,s){switch(n){case t.Patterns.PATTERN000:return(o+s)%2===0;case t.Patterns.PATTERN001:return o%2===0;case t.Patterns.PATTERN010:return s%3===0;case t.Patterns.PATTERN011:return(o+s)%3===0;case t.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case t.Patterns.PATTERN101:return o*s%2+o*s%3===0;case t.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case t.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}t.applyMask=function(o,s){const i=s.size;for(let a=0;a<i;a++)for(let c=0;c<i;c++)s.isReserved(c,a)||s.xor(c,a,r(o,c,a))},t.getBestMask=function(o,s){const i=Object.keys(t.Patterns).length;let a=0,c=1/0;for(let l=0;l<i;l++){s(l),t.applyMask(l,o);const d=t.getPenaltyN1(o)+t.getPenaltyN2(o)+t.getPenaltyN3(o)+t.getPenaltyN4(o);t.applyMask(l,o),d<c&&(c=d,a=l)}return a}})(Ri)),Ri}var Bo={},Bd;function ip(){if(Bd)return Bo;Bd=1;const t=Nc(),e=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return Bo.getBlocksCount=function(o,s){switch(s){case t.L:return e[(o-1)*4+0];case t.M:return e[(o-1)*4+1];case t.Q:return e[(o-1)*4+2];case t.H:return e[(o-1)*4+3];default:return}},Bo.getTotalCodewordsCount=function(o,s){switch(s){case t.L:return r[(o-1)*4+0];case t.M:return r[(o-1)*4+1];case t.Q:return r[(o-1)*4+2];case t.H:return r[(o-1)*4+3];default:return}},Bo}var Ti={},xn={},_d;function GS(){if(_d)return xn;_d=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let n=1;for(let o=0;o<255;o++)t[o]=n,e[n]=o,n<<=1,n&256&&(n^=285);for(let o=255;o<512;o++)t[o]=t[o-255]})(),xn.log=function(n){if(n<1)throw new Error("log("+n+")");return e[n]},xn.exp=function(n){return t[n]},xn.mul=function(n,o){return n===0||o===0?0:t[e[n]+e[o]]},xn}var Dd;function XS(){return Dd||(Dd=1,(function(t){const e=GS();t.mul=function(n,o){const s=new Uint8Array(n.length+o.length-1);for(let i=0;i<n.length;i++)for(let a=0;a<o.length;a++)s[i+a]^=e.mul(n[i],o[a]);return s},t.mod=function(n,o){let s=new Uint8Array(n);for(;s.length-o.length>=0;){const i=s[0];for(let c=0;c<o.length;c++)s[c]^=e.mul(o[c],i);let a=0;for(;a<s.length&&s[a]===0;)a++;s=s.slice(a)}return s},t.generateECPolynomial=function(n){let o=new Uint8Array([1]);for(let s=0;s<n;s++)o=t.mul(o,new Uint8Array([1,e.exp(s)]));return o}})(Ti)),Ti}var Pi,Od;function YS(){if(Od)return Pi;Od=1;const t=XS();function e(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(n){this.degree=n,this.genPoly=t.generateECPolynomial(this.degree)},e.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(n.length+this.degree);o.set(n);const s=t.mod(o,this.genPoly),i=this.degree-s.length;if(i>0){const a=new Uint8Array(this.degree);return a.set(s,i),a}return s},Pi=e,Pi}var Ni={},Li={},Bi={},Fd;function ap(){return Fd||(Fd=1,Bi.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),Bi}var at={},Md;function cp(){if(Md)return at;Md=1;const t="[0-9]+",e="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
|
|
3
|
+
]))+`;at.KANJI=new RegExp(r,"g"),at.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),at.BYTE=new RegExp(n,"g"),at.NUMERIC=new RegExp(t,"g"),at.ALPHANUMERIC=new RegExp(e,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+t+"$"),i=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return at.testKanji=function(c){return o.test(c)},at.testNumeric=function(c){return s.test(c)},at.testAlphanumeric=function(c){return i.test(c)},at}var jd;function wr(){return jd||(jd=1,(function(t){const e=ap(),r=cp();t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(s,i){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!e.isValid(i))throw new Error("Invalid version: "+i);return i>=1&&i<10?s.ccBits[0]:i<27?s.ccBits[1]:s.ccBits[2]},t.getBestModeForData=function(s){return r.testNumeric(s)?t.NUMERIC:r.testAlphanumeric(s)?t.ALPHANUMERIC:r.testKanji(s)?t.KANJI:t.BYTE},t.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},t.isValid=function(s){return s&&s.bit&&s.ccBits};function n(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+o)}}t.from=function(s,i){if(t.isValid(s))return s;try{return n(s)}catch{return i}}})(Li)),Li}var Ud;function ZS(){return Ud||(Ud=1,(function(t){const e=mr(),r=ip(),n=Nc(),o=wr(),s=ap(),i=7973,a=e.getBCHDigit(i);function c(f,h,g){for(let m=1;m<=40;m++)if(h<=t.getCapacity(m,g,f))return m}function l(f,h){return o.getCharCountIndicator(f,h)+4}function d(f,h){let g=0;return f.forEach(function(m){const y=l(m.mode,h);g+=y+m.getBitsLength()}),g}function u(f,h){for(let g=1;g<=40;g++)if(d(f,g)<=t.getCapacity(g,h,o.MIXED))return g}t.from=function(h,g){return s.isValid(h)?parseInt(h,10):g},t.getCapacity=function(h,g,m){if(!s.isValid(h))throw new Error("Invalid QR Code version");typeof m>"u"&&(m=o.BYTE);const y=e.getSymbolTotalCodewords(h),w=r.getTotalCodewordsCount(h,g),I=(y-w)*8;if(m===o.MIXED)return I;const v=I-l(m,h);switch(m){case o.NUMERIC:return Math.floor(v/10*3);case o.ALPHANUMERIC:return Math.floor(v/11*2);case o.KANJI:return Math.floor(v/13);case o.BYTE:default:return Math.floor(v/8)}},t.getBestVersionForData=function(h,g){let m;const y=n.from(g,n.M);if(Array.isArray(h)){if(h.length>1)return u(h,y);if(h.length===0)return 1;m=h[0]}else m=h;return c(m.mode,m.getLength(),y)},t.getEncodedBits=function(h){if(!s.isValid(h)||h<7)throw new Error("Invalid QR Code version");let g=h<<12;for(;e.getBCHDigit(g)-a>=0;)g^=i<<e.getBCHDigit(g)-a;return h<<12|g}})(Ni)),Ni}var _i={},$d;function JS(){if($d)return _i;$d=1;const t=mr(),e=1335,r=21522,n=t.getBCHDigit(e);return _i.getEncodedBits=function(s,i){const a=s.bit<<3|i;let c=a<<10;for(;t.getBCHDigit(c)-n>=0;)c^=e<<t.getBCHDigit(c)-n;return(a<<10|c)^r},_i}var Di={},Oi,Hd;function QS(){if(Hd)return Oi;Hd=1;const t=wr();function e(r){this.mode=t.NUMERIC,this.data=r.toString()}return e.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(n){let o,s,i;for(o=0;o+3<=this.data.length;o+=3)s=this.data.substr(o,3),i=parseInt(s,10),n.put(i,10);const a=this.data.length-o;a>0&&(s=this.data.substr(o),i=parseInt(s,10),n.put(i,a*3+1))},Oi=e,Oi}var Fi,qd;function eE(){if(qd)return Fi;qd=1;const t=wr(),e=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=t.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(o){return 11*Math.floor(o/2)+6*(o%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(o){let s;for(s=0;s+2<=this.data.length;s+=2){let i=e.indexOf(this.data[s])*45;i+=e.indexOf(this.data[s+1]),o.put(i,11)}this.data.length%2&&o.put(e.indexOf(this.data[s]),6)},Fi=r,Fi}var Mi,Kd;function tE(){if(Kd)return Mi;Kd=1;const t=wr();function e(r){this.mode=t.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return e.getBitsLength=function(n){return n*8},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(r){for(let n=0,o=this.data.length;n<o;n++)r.put(this.data[n],8)},Mi=e,Mi}var ji,zd;function rE(){if(zd)return ji;zd=1;const t=wr(),e=mr();function r(n){this.mode=t.KANJI,this.data=n}return r.getBitsLength=function(o){return o*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let o;for(o=0;o<this.data.length;o++){let s=e.toSJIS(this.data[o]);if(s>=33088&&s<=40956)s-=33088;else if(s>=57408&&s<=60351)s-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
|
|
4
|
+
Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),n.put(s,13)}},ji=r,ji}var Ui={exports:{}},Vd;function nE(){return Vd||(Vd=1,(function(t){var e={single_source_shortest_paths:function(r,n,o){var s={},i={};i[n]=0;var a=e.PriorityQueue.make();a.push(n,0);for(var c,l,d,u,f,h,g,m,y;!a.empty();){c=a.pop(),l=c.value,u=c.cost,f=r[l]||{};for(d in f)f.hasOwnProperty(d)&&(h=f[d],g=u+h,m=i[d],y=typeof i[d]>"u",(y||m>g)&&(i[d]=g,a.push(d,g),s[d]=l))}if(typeof o<"u"&&typeof i[o]>"u"){var w=["Could not find a path from ",n," to ",o,"."].join("");throw new Error(w)}return s},extract_shortest_path_from_predecessor_list:function(r,n){for(var o=[],s=n;s;)o.push(s),r[s],s=r[s];return o.reverse(),o},find_path:function(r,n,o){var s=e.single_source_shortest_paths(r,n,o);return e.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(r){var n=e.PriorityQueue,o={},s;r=r||{};for(s in n)n.hasOwnProperty(s)&&(o[s]=n[s]);return o.queue=[],o.sorter=r.sorter||n.default_sorter,o},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var o={value:r,cost:n};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=e})(Ui)),Ui.exports}var Wd;function oE(){return Wd||(Wd=1,(function(t){const e=wr(),r=QS(),n=eE(),o=tE(),s=rE(),i=cp(),a=mr(),c=nE();function l(w){return unescape(encodeURIComponent(w)).length}function d(w,I,v){const A=[];let B;for(;(B=w.exec(v))!==null;)A.push({data:B[0],index:B.index,mode:I,length:B[0].length});return A}function u(w){const I=d(i.NUMERIC,e.NUMERIC,w),v=d(i.ALPHANUMERIC,e.ALPHANUMERIC,w);let A,B;return a.isKanjiModeEnabled()?(A=d(i.BYTE,e.BYTE,w),B=d(i.KANJI,e.KANJI,w)):(A=d(i.BYTE_KANJI,e.BYTE,w),B=[]),I.concat(v,A,B).sort(function(N,k){return N.index-k.index}).map(function(N){return{data:N.data,mode:N.mode,length:N.length}})}function f(w,I){switch(I){case e.NUMERIC:return r.getBitsLength(w);case e.ALPHANUMERIC:return n.getBitsLength(w);case e.KANJI:return s.getBitsLength(w);case e.BYTE:return o.getBitsLength(w)}}function h(w){return w.reduce(function(I,v){const A=I.length-1>=0?I[I.length-1]:null;return A&&A.mode===v.mode?(I[I.length-1].data+=v.data,I):(I.push(v),I)},[])}function g(w){const I=[];for(let v=0;v<w.length;v++){const A=w[v];switch(A.mode){case e.NUMERIC:I.push([A,{data:A.data,mode:e.ALPHANUMERIC,length:A.length},{data:A.data,mode:e.BYTE,length:A.length}]);break;case e.ALPHANUMERIC:I.push([A,{data:A.data,mode:e.BYTE,length:A.length}]);break;case e.KANJI:I.push([A,{data:A.data,mode:e.BYTE,length:l(A.data)}]);break;case e.BYTE:I.push([{data:A.data,mode:e.BYTE,length:l(A.data)}])}}return I}function m(w,I){const v={},A={start:{}};let B=["start"];for(let T=0;T<w.length;T++){const N=w[T],k=[];for(let x=0;x<N.length;x++){const S=N[x],R=""+T+x;k.push(R),v[R]={node:S,lastCount:0},A[R]={};for(let P=0;P<B.length;P++){const b=B[P];v[b]&&v[b].node.mode===S.mode?(A[b][R]=f(v[b].lastCount+S.length,S.mode)-f(v[b].lastCount,S.mode),v[b].lastCount+=S.length):(v[b]&&(v[b].lastCount=S.length),A[b][R]=f(S.length,S.mode)+4+e.getCharCountIndicator(S.mode,I))}}B=k}for(let T=0;T<B.length;T++)A[B[T]].end=0;return{map:A,table:v}}function y(w,I){let v;const A=e.getBestModeForData(w);if(v=e.from(I,A),v!==e.BYTE&&v.bit<A.bit)throw new Error('"'+w+'" cannot be encoded with mode '+e.toString(v)+`.
|
|
5
|
+
Suggested mode is: `+e.toString(A));switch(v===e.KANJI&&!a.isKanjiModeEnabled()&&(v=e.BYTE),v){case e.NUMERIC:return new r(w);case e.ALPHANUMERIC:return new n(w);case e.KANJI:return new s(w);case e.BYTE:return new o(w)}}t.fromArray=function(I){return I.reduce(function(v,A){return typeof A=="string"?v.push(y(A,null)):A.data&&v.push(y(A.data,A.mode)),v},[])},t.fromString=function(I,v){const A=u(I,a.isKanjiModeEnabled()),B=g(A),T=m(B,v),N=c.find_path(T.map,"start","end"),k=[];for(let x=1;x<N.length-1;x++)k.push(T.table[N[x]].node);return t.fromArray(h(k))},t.rawSplit=function(I){return t.fromArray(u(I,a.isKanjiModeEnabled()))}})(Di)),Di}var Gd;function sE(){if(Gd)return Si;Gd=1;const t=mr(),e=Nc(),r=qS(),n=KS(),o=zS(),s=VS(),i=WS(),a=ip(),c=YS(),l=ZS(),d=JS(),u=wr(),f=oE();function h(T,N){const k=T.size,x=s.getPositions(N);for(let S=0;S<x.length;S++){const R=x[S][0],P=x[S][1];for(let b=-1;b<=7;b++)if(!(R+b<=-1||k<=R+b))for(let E=-1;E<=7;E++)P+E<=-1||k<=P+E||(b>=0&&b<=6&&(E===0||E===6)||E>=0&&E<=6&&(b===0||b===6)||b>=2&&b<=4&&E>=2&&E<=4?T.set(R+b,P+E,!0,!0):T.set(R+b,P+E,!1,!0))}}function g(T){const N=T.size;for(let k=8;k<N-8;k++){const x=k%2===0;T.set(k,6,x,!0),T.set(6,k,x,!0)}}function m(T,N){const k=o.getPositions(N);for(let x=0;x<k.length;x++){const S=k[x][0],R=k[x][1];for(let P=-2;P<=2;P++)for(let b=-2;b<=2;b++)P===-2||P===2||b===-2||b===2||P===0&&b===0?T.set(S+P,R+b,!0,!0):T.set(S+P,R+b,!1,!0)}}function y(T,N){const k=T.size,x=l.getEncodedBits(N);let S,R,P;for(let b=0;b<18;b++)S=Math.floor(b/3),R=b%3+k-8-3,P=(x>>b&1)===1,T.set(S,R,P,!0),T.set(R,S,P,!0)}function w(T,N,k){const x=T.size,S=d.getEncodedBits(N,k);let R,P;for(R=0;R<15;R++)P=(S>>R&1)===1,R<6?T.set(R,8,P,!0):R<8?T.set(R+1,8,P,!0):T.set(x-15+R,8,P,!0),R<8?T.set(8,x-R-1,P,!0):R<9?T.set(8,15-R-1+1,P,!0):T.set(8,15-R-1,P,!0);T.set(x-8,8,1,!0)}function I(T,N){const k=T.size;let x=-1,S=k-1,R=7,P=0;for(let b=k-1;b>0;b-=2)for(b===6&&b--;;){for(let E=0;E<2;E++)if(!T.isReserved(S,b-E)){let C=!1;P<N.length&&(C=(N[P]>>>R&1)===1),T.set(S,b-E,C),R--,R===-1&&(P++,R=7)}if(S+=x,S<0||k<=S){S-=x,x=-x;break}}}function v(T,N,k){const x=new r;k.forEach(function(E){x.put(E.mode.bit,4),x.put(E.getLength(),u.getCharCountIndicator(E.mode,T)),E.write(x)});const S=t.getSymbolTotalCodewords(T),R=a.getTotalCodewordsCount(T,N),P=(S-R)*8;for(x.getLengthInBits()+4<=P&&x.put(0,4);x.getLengthInBits()%8!==0;)x.putBit(0);const b=(P-x.getLengthInBits())/8;for(let E=0;E<b;E++)x.put(E%2?17:236,8);return A(x,T,N)}function A(T,N,k){const x=t.getSymbolTotalCodewords(N),S=a.getTotalCodewordsCount(N,k),R=x-S,P=a.getBlocksCount(N,k),b=x%P,E=P-b,C=Math.floor(x/P),L=Math.floor(R/P),M=L+1,$=C-L,j=new c($);let D=0;const _=new Array(P),O=new Array(P);let q=0;const H=new Uint8Array(T.buffer);for(let G=0;G<P;G++){const Y=G<E?L:M;_[G]=H.slice(D,D+Y),O[G]=j.encode(_[G]),D+=Y,q=Math.max(q,Y)}const K=new Uint8Array(x);let z=0,W,X;for(W=0;W<q;W++)for(X=0;X<P;X++)W<_[X].length&&(K[z++]=_[X][W]);for(W=0;W<$;W++)for(X=0;X<P;X++)K[z++]=O[X][W];return K}function B(T,N,k,x){let S;if(Array.isArray(T))S=f.fromArray(T);else if(typeof T=="string"){let C=N;if(!C){const L=f.rawSplit(T);C=l.getBestVersionForData(L,k)}S=f.fromString(T,C||40)}else throw new Error("Invalid data");const R=l.getBestVersionForData(S,k);if(!R)throw new Error("The amount of data is too big to be stored in a QR Code");if(!N)N=R;else if(N<R)throw new Error(`
|
|
6
6
|
The chosen QR Code version cannot contain this amount of data.
|
|
7
7
|
Minimum version required to store current data is: `+R+`.
|
|
8
|
-
`);const P=v(N,k,S),b=t.getSymbolSize(N),E=new n(b);return h(E,N),g(E),m(E,N),w(E,k,0),N>=7&&y(E,N),I(E,P),isNaN(x)&&(x=i.getBestMask(E,w.bind(null,E,k))),i.applyMask(x,E),w(E,k,x),{modules:E,version:N,errorCorrectionLevel:k,maskPattern:x,segments:S}}return
|
|
9
|
-
`;return typeof a=="function"&&a(null,y),y},Ui}var Xd;function sE(){if(Xd)return Cr;Xd=1;const t=jS(),e=rE(),r=nE(),n=oE();function o(s,i,a,c,l){const d=[].slice.call(arguments,1),u=d.length,f=typeof d[u-1]=="function";if(!f&&!t())throw new Error("Callback required as last argument");if(f){if(u<2)throw new Error("Too few arguments provided");u===2?(l=a,a=i,i=c=void 0):u===3&&(i.getContext&&typeof l>"u"?(l=c,c=void 0):(l=c,c=a,a=i,i=void 0))}else{if(u<1)throw new Error("Too few arguments provided");return u===1?(a=i,i=c=void 0):u===2&&!i.getContext&&(c=a,a=i,i=void 0),new Promise(function(h,g){try{const m=e.create(a,c);h(s(m,i,c))}catch(m){g(m)}})}try{const h=e.create(a,c);l(null,s(h,i,c))}catch(h){l(h)}}return Cr.create=e.create,Cr.toCanvas=o.bind(null,r.render),Cr.toDataURL=o.bind(null,r.renderToDataURL),Cr.toString=o.bind(null,function(s,i,a){return n.render(s,a)}),Cr}var iE=sE();const No="w-full rounded-lg border border-border bg-background px-3 py-2.5 text-base text-foreground focus:outline-none focus:ring-2 focus:ring-ring sm:text-sm",Ke="appearance-none min-h-11 rounded-lg px-3 py-2 text-sm hover:bg-hover focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",Rr=`${Ke} bg-primary text-primary-foreground hover:opacity-90`;function aE(t){return t.serviceName||new URL(t.url).hostname}function Yd(t){return t.includes("service:*")?"完整权限":t.includes("session.input")?"可操作":t.includes("session.view")?"只读":t.includes("route.use")?"仅中转":"自定义权限"}function cE({profile:t,subjectId:e}){return p.jsxs("details",{className:"mt-2 text-xs text-muted-foreground",children:[p.jsx("summary",{className:"cursor-pointer leading-relaxed",children:[t?.model||t?.hostname||t?.system,t?.route,`ID ${e.slice(-8)}`].filter(Boolean).join(" · ")}),p.jsxs("dl",{className:"mt-2 space-y-2 rounded-lg bg-surface-2 p-3",children:[[["设备型号",t?.model],["主机名称",t?.hostname],["操作系统",t?.system],["客户端",t?.client],["打开方式",t?.mode],["处理器",t?.cpu],["架构",t?.arch],["最近连接路径",t?.route],["首次记录",t?.firstSeenAt?new Date(t.firstSeenAt).toLocaleString():void 0],["最近连接",t?.lastSeenAt?new Date(t.lastSeenAt).toLocaleString():void 0],["设备标识",e]].filter(([,r])=>r).map(([r,n])=>p.jsxs("div",{children:[p.jsx("dt",{children:r}),p.jsx("dd",{className:"mt-0.5 select-text break-all text-foreground",children:n})]},r)),p.jsx("p",{className:"leading-relaxed",children:t?"系统、硬件与路径由设备报告;连接时间由服务记录。":"此设备尚未报告详情,更新客户端并重新连接后可补齐。"})]})]})}function lE(){const t=getComputedStyle(document.documentElement),e=t.getPropertyValue("--background").trim(),r=t.getPropertyValue("--foreground").trim(),n=o=>{const s=o.replace("#","");return parseInt(s.slice(0,2),16)*.299+parseInt(s.slice(2,4),16)*.587+parseInt(s.slice(4,6),16)*.114};if(!e||!r)throw new Error("Theme unavailable");return n(e)<n(r)?{dark:e,light:r}:{dark:r,light:e}}function dE({onConnect:t,onClose:e,onConnectWithPassword:r,onAddService:n,onOpenService:o,currentIdentity:s,currentServiceName:i,currentServiceId:a,currentServiceOrigin:c,hasBackup:l=!1,paired:d=!1,initialInvite:u,sessions:f=[],grants:h=[],onCreateInvite:g,onRevoke:m,onRename:y,loading:w=!1,loadError:I,onRetry:v}){const[A,B]=F.useState(!1),[T,N]=F.useState(""),[k,x]=F.useState({}),[S,R]=F.useState(""),[P,b]=F.useState(""),[E,C]=F.useState(!1),[L,M]=F.useState(!1),[$,j]=F.useState(!d),[D,_]=F.useState(!0),[O,q]=F.useState("read"),[H,K]=F.useState("all"),[z,W]=F.useState([]),[X,G]=F.useState(!1),[Y,se]=F.useState(""),[Pe,Oe]=F.useState(""),[oe,ot]=F.useState(),[vr,Rt]=F.useState(""),[Xe,ao]=F.useState("services"),[xr,Ms]=F.useState(),[js,Kc]=F.useState(""),[sn,zc]=F.useState(!1),[Vc,an]=F.useState(),[ut,co]=F.useState(!1),[Sr,Wc]=F.useState([]),Us=h.filter(U=>U.revokedAt===void 0&&(!U.expiresAt||U.expiresAt>Date.now())),$s=h.filter(U=>!Us.includes(U)),cn=[...new Set(Us.map(U=>U.subjectId))].map(U=>{const V=Us.filter(de=>de.subjectId===U);return{subjectId:U,grants:V,name:U===s?"此设备":V.find(de=>de.label)?.label||"未命名设备"}}).sort((U,V)=>+(V.subjectId===s)-+(U.subjectId===s)),Er=!xr&&!sn&&d&&!$&&!L&&!u,Vp=()=>{Ms(void 0),zc(!1),j(!1),M(!1),ot(void 0),G(!1),R(""),b(""),an(void 0)},Gc=()=>{M(!0),j(!1),G(!1),R(""),b("")},Wp=U=>U.subjectId===s?"此设备":U.label||"未命名设备",Hs=()=>{ut?co(!1):e()},ln=F.useRef(null);F.useEffect(()=>{const U=document.activeElement;return ln.current?.focus(),()=>{U?.focus()}},[]),F.useEffect(()=>{let U=!1;if(Rt(""),oe)try{iE.toDataURL(oe.url,{width:220,margin:3,errorCorrectionLevel:"M",color:lE()}).then(V=>{U||Rt(V)}).catch(()=>{})}catch{}return()=>{U=!0}},[oe]);async function qs(U){C(!0),R(""),b("");try{await t(U);const{url:V,targetPeerId:de,serviceName:Fe,serviceOrigin:Ks}=U;await Et({id:de,url:V,targetPeerId:de,label:Fe||new URL(V).host,serviceOrigin:Ks,entryServiceId:U.entryServiceId}),j(!1),b("已连接。")}catch(V){U.routeOnly&&V instanceof Ve?B(!0):R("暂时无法连接,请检查网络,或确认邀请是否仍然有效。")}finally{C(!1)}}async function Gp(U){if(U.preventDefault(),!g)return;R(""),b("");const V=z.filter(Fe=>f.some(Ks=>Ks.sessionId===Fe));if(O!=="full"&&H==="selected"&&!V.length){R("请选择至少一个 Session。");return}const de=Pe?new Date(Pe).getTime():void 0;if(de!==void 0&&(!Number.isFinite(de)||de<=Date.now())){R("授权到期时间必须晚于现在。");return}C(!0);try{const Fe=await g({...l?{includeBackup:D}:{},scope:O==="full"||H==="all"?{kind:"service"}:{kind:"sessions",sessionIds:V},actions:O==="full"?["service:*"]:O==="write"?["session.view","session.input","session.resize"]:["session.view"],...Y.trim()?{label:Y.trim()}:{},...de===void 0?{}:{expiresAt:de}});ot(Fe)}catch(Fe){R(Fe instanceof Error&&Fe.message.startsWith("无法分享备用连接:")?"无法分享备用连接:需要入口管理员授权。你也可以关闭“包含备用连接”,生成直连邀请。":"暂时无法生成邀请,请确认当前设备有授权管理权限。")}finally{C(!1)}}async function Xp(){if(oe)try{await navigator.clipboard.writeText(oe.url),b("邀请链接已复制。")}catch{R("浏览器未允许复制,请长按下方链接复制。")}}const Yp=k.title||(xr?"设备名称":sn?Xe==="devices"?"授权详情":"连接详情":ut?"选择终端":L?"邀请设备":$&&d?"添加服务":d?"服务与设备":"连接 Termdock"),Zp=!!k.back||!!xr||sn||ut||d&&($||L),Jp=()=>{if(k.back){k.back();return}ut?co(!1):Vp()},Xc=U=>U.every(V=>V.routeTargetServiceId)?`${new Set(U.map(V=>V.routeTargetServiceId)).size} 台服务`:U.some(V=>V.scope.kind==="service")?"全部终端":`${new Set(U.flatMap(V=>V.scope.kind==="sessions"?V.scope.sessionIds:[])).size} 个终端`;return eg.createPortal(p.jsx("div",{className:"fixed inset-0 z-modal-backdrop flex items-end justify-center bg-[var(--app-backdrop)] backdrop-blur-sm sm:items-center sm:p-6","data-sidebar-gesture-ignore":!0,onMouseDown:U=>{U.target===U.currentTarget&&!E&&Hs()},children:p.jsxs("div",{ref:ln,tabIndex:-1,role:"dialog","aria-modal":"true","aria-labelledby":"federation-title",className:"z-modal-panel flex max-h-[calc(100dvh-env(safe-area-inset-top)-12px)] w-full max-w-lg flex-col overflow-hidden rounded-t-2xl border border-border bg-surface font-sans text-foreground shadow-xl outline-none sm:max-h-[min(720px,90dvh)] sm:rounded-2xl",onKeyDown:U=>{if(U.key==="Escape"&&!E&&(U.stopPropagation(),Hs()),U.key!=="Tab")return;const V=ln.current?.querySelectorAll('button:not(:disabled), input:not(:disabled), textarea:not(:disabled), select:not(:disabled), [tabindex="0"], summary');if(!V?.length){U.preventDefault();return}const de=V[0],Fe=V[V.length-1];U.shiftKey&&(document.activeElement===de||document.activeElement===ln.current)?(U.preventDefault(),Fe.focus()):!U.shiftKey&&(document.activeElement===Fe||document.activeElement===ln.current)&&(U.preventDefault(),de.focus())},children:[p.jsxs("header",{className:"shrink-0 border-b border-border px-5 pt-3",children:[p.jsxs("div",{className:"flex min-h-12 items-center gap-2 pb-2",children:[Zp&&p.jsx("button",{type:"button",className:`${Ke} -ml-3 inline-flex w-11 items-center justify-center text-muted-foreground`,disabled:E,onClick:Jp,"aria-label":ut?"取消选择终端":Xe==="devices"?"返回设备":"返回服务",children:p.jsx(Yh,{size:20})}),p.jsx("h2",{id:"federation-title",className:"min-w-0 flex-1 text-base font-semibold",children:Yp}),p.jsx("button",{type:"button",className:`${Ke} -mr-3 inline-flex w-11 items-center justify-center text-muted-foreground`,disabled:E,onClick:Hs,"aria-label":"关闭",children:p.jsx(IS,{size:20})})]}),Er&&!k.title&&p.jsx("div",{className:"flex gap-6",role:"tablist","aria-label":"管理内容",children:[["services","服务"],["devices","设备"]].map(([U,V])=>p.jsxs("button",{type:"button",role:"tab","aria-selected":Xe===U,"aria-controls":`federation-${U}`,id:`federation-tab-${U}`,className:`min-h-11 border-b-2 px-1 text-sm transition ${Xe===U?"border-primary font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"}`,onClick:()=>{ao(U),G(!1),an(void 0),R(""),b("")},children:[V,U==="devices"&&cn.length>0&&p.jsx("span",{className:"ml-1.5 text-xs text-muted-foreground",children:cn.length})]},U))})]}),p.jsxs("div",{className:"min-h-0 overflow-y-auto overscroll-contain px-5 py-4 pb-[max(20px,env(safe-area-inset-bottom))]",children:[(Er&&Xe==="services"||$&&!L&&!u)&&p.jsx(OS,{renderRelayServices:(U,V)=>p.jsx(_S,{service:U,onBusyChange:V,onConnect:t,onConnectWithPassword:r}),renderRoutes:(U,V)=>p.jsx(DS,{service:U,onBusyChange:V}),hideHeader:!0,initiallyAdding:$,current:a?{id:a,targetPeerId:a,url:c||location.origin,label:i||"当前服务"}:void 0,onNavigation:x,onBusyChange:C,onInvite:g?Gc:void 0,onOpen:async U=>{if(o)return o(U);U.targetPeerId?await qs({...U,targetPeerId:U.targetPeerId,serviceName:U.label}):n&&await n(U.url)},onAdd:async(U,V)=>{if(n)return n(U,V);await qs(gs(U))}}),Er&&Xe==="devices"&&p.jsxs("section",{role:"tabpanel",id:"federation-devices","aria-labelledby":"federation-tab-devices",children:[p.jsx("p",{className:"mb-2 text-xs leading-relaxed text-muted-foreground",children:"可访问此服务的设备"}),w?p.jsxs("p",{role:"status",className:"flex items-center gap-2 py-5 text-sm text-muted-foreground",children:[p.jsx(He,{size:16,className:"animate-spin"}),"正在读取设备…"]}):p.jsxs("div",{className:"divide-y divide-border",children:[cn.map(U=>p.jsxs("div",{className:"py-3",children:[p.jsxs("div",{className:"flex items-center gap-3",children:[p.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-surface-2 text-muted-foreground",children:/iPhone|iPad|Android|手机|平板/i.test(U.grants.find(V=>V.label)?.label||(U.subjectId===s?navigator.userAgent:""))?p.jsx(Qh,{size:19}):p.jsx(wS,{size:19})}),p.jsxs("div",{className:"min-w-0 flex-1",children:[p.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[p.jsx("p",{className:"truncate text-sm font-medium",children:U.name}),y&&(m||U.subjectId===s)&&p.jsx("button",{type:"button","aria-label":`重命名 ${U.name}`,className:"inline-flex h-9 w-9 shrink-0 appearance-none items-center justify-center rounded-lg bg-transparent text-muted-foreground hover:bg-surface-2",onClick:()=>{Ms(U.subjectId),Kc(U.grants.find(V=>V.label)?.label||"")},children:p.jsx(bS,{size:14})})]}),U.subjectId===s&&U.grants.find(V=>V.label)?.label&&p.jsx("p",{className:"truncate text-xs text-muted-foreground",children:U.grants.find(V=>V.label)?.label}),p.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:[Yd(U.grants.flatMap(V=>V.actions))," · ",Xc(U.grants)]})]}),m&&U.subjectId!==s&&Vc!==U.subjectId&&p.jsx("button",{type:"button",className:`${Ke} -mr-2 text-xs text-muted-foreground hover:text-destructive`,disabled:E,"aria-label":`撤销 ${U.name} 的访问权限`,onClick:()=>an(U.subjectId),children:"撤销"})]}),p.jsx(cE,{profile:U.grants.find(V=>V.deviceProfile)?.deviceProfile,subjectId:U.subjectId}),Vc===U.subjectId&&p.jsxs("div",{className:"mt-3 rounded-lg border border-border bg-background p-3",children:[p.jsx("p",{className:"text-xs leading-relaxed",children:"撤销后,这台设备将断开连接,需重新邀请才能访问。"}),p.jsxs("div",{className:"mt-2 flex justify-end gap-2",children:[p.jsx("button",{type:"button",className:`${Ke} text-xs text-muted-foreground`,disabled:E,onClick:()=>an(void 0),children:"取消"}),p.jsx("button",{type:"button",className:`${Ke} text-xs text-destructive`,disabled:E,onClick:async()=>{C(!0),R("");try{for(const V of U.grants)await m?.(V.id);an(void 0),b("设备访问权限已撤销。")}catch{R("暂时无法撤销,请重试。")}finally{C(!1)}},children:"确认撤销"})]})]})]},U.subjectId)),cn.length===0&&!I&&p.jsxs("p",{className:"py-5 text-sm text-muted-foreground",children:["暂无设备授权。",g?"可通过邀请添加设备。":""]})]}),g&&p.jsxs("button",{type:"button",className:`${Ke} mt-4 inline-flex w-full items-center justify-center gap-2 border border-border text-sm`,disabled:E,onClick:Gc,children:[p.jsx(Jh,{size:16}),"邀请设备"]}),$s.length>0&&p.jsxs("details",{className:"mt-4 text-xs text-muted-foreground",children:[p.jsxs("summary",{className:"cursor-pointer py-2",children:["已失效的授权(",$s.length,")"]}),p.jsx("div",{className:"mt-1 space-y-2 border-l border-border pl-3",children:$s.map(U=>p.jsxs("p",{className:"flex gap-3",children:[p.jsx("span",{className:"min-w-0 flex-1 truncate",children:Wp(U)}),p.jsx("span",{className:"shrink-0",children:U.revokedAt!==void 0?"已撤销":"已到期"})]},U.id))})]})]}),xr&&p.jsxs("form",{className:"space-y-4",onSubmit:async U=>{U.preventDefault(),C(!0),R("");try{await y?.(xr,js.trim()),Ms(void 0)}catch{R("暂时无法保存设备名称,请重试。")}finally{C(!1)}},children:[p.jsxs("label",{className:"block space-y-2 text-sm",children:[p.jsx("span",{children:"设备名称"}),p.jsx("input",{autoFocus:!0,className:No,maxLength:80,required:!0,value:js,onChange:U=>Kc(U.target.value),placeholder:"例如:我的 iPhone、办公室电脑"})]}),p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"为设备起一个容易辨认的名字,会同步显示在此服务的设备列表中。"}),p.jsx("button",{type:"submit",className:`${Rr} w-full`,disabled:E||!js.trim(),children:E?"正在保存…":"保存名称"})]}),sn&&p.jsx("section",{className:"space-y-5",children:Xe==="devices"?cn.map(U=>p.jsxs("div",{className:"space-y-3",children:[p.jsx("h3",{className:"text-sm font-medium",children:U.name}),p.jsxs("dl",{className:"space-y-3 rounded-xl bg-surface-2 p-3 text-xs",children:[p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"访问权限"}),p.jsxs("dd",{className:"mt-1",children:[Yd(U.grants.flatMap(V=>V.actions))," · ",Xc(U.grants)]})]}),U.grants.map(V=>p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:V.routeTargetServiceId?"允许经此入口访问":V.scope.kind==="sessions"?"可访问终端":"有效期"}),p.jsx("dd",{className:"mt-1 leading-relaxed",children:V.routeTargetServiceId?V.routeTargetName||"指定服务":V.scope.kind==="sessions"?V.scope.sessionIds.map(de=>f.find(Fe=>Fe.sessionId===de)?.name||de).join("、"):V.expiresAt?new Date(V.expiresAt).toLocaleString():"保留至撤销"}),V.routeTargetServiceId&&m&&p.jsx("button",{type:"button",className:`${Ke} mt-1 -ml-3 text-xs text-destructive`,disabled:E,onClick:async()=>{C(!0),R("");try{await m(V.id)}catch{R("暂时无法撤销,请重试。")}finally{C(!1)}},children:"撤销此中转权限"})]},V.id)),p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"设备标识"}),p.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed text-muted-foreground select-text",children:U.subjectId})]})]})]},U.subjectId)):p.jsxs("dl",{className:"space-y-4 text-xs",children:[p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"当前服务"}),p.jsx("dd",{className:"mt-1 text-sm",children:i||"当前服务"})]}),p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"服务标识"}),p.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed select-text",children:a})]}),p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"本设备标识"}),p.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed select-text",children:s})]})]})}),u&&!L&&p.jsxs("section",{className:"space-y-5 py-1",children:[p.jsxs("div",{className:"flex items-center gap-3",children:[p.jsx("span",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-surface-2 text-muted-foreground",children:p.jsx(Os,{size:22})}),p.jsxs("div",{className:"min-w-0",children:[p.jsx("p",{className:"text-xs text-muted-foreground",children:"你受邀连接"}),p.jsx("p",{className:"mt-1 break-words text-base font-medium",children:aE(u)})]})]}),u.routeOnly&&p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"此邀请提供备用连接,目标服务仍会验证你的访问权限。"}),A?p.jsxs("form",{className:"space-y-3",onSubmit:async U=>{U.preventDefault(),C(!0),R("");try{await r?.(u,T)}catch(V){R(V instanceof Error?V.message:"暂时无法登录,请重试。")}finally{N(""),C(!1)}},children:[p.jsxs("label",{className:"block space-y-2 text-sm",children:[p.jsx("span",{children:"目标服务密码"}),p.jsx("input",{className:No,type:"password",required:!0,autoFocus:!0,autoComplete:"current-password",value:T,onChange:U=>N(U.target.value)})]}),p.jsx("button",{className:`${Rr} w-full`,disabled:E||!T,children:E?"正在登录…":"登录并连接"})]}):p.jsx("button",{type:"button",className:`${Rr} w-full text-sm`,disabled:E,onClick:()=>{qs(u)},children:E?"正在连接…":"接受邀请"})]}),L&&!ut&&p.jsx("section",{children:oe?p.jsxs("div",{className:"space-y-4 text-center",children:[p.jsx("p",{className:"text-sm font-medium",children:"用另一台设备扫描二维码"}),vr?p.jsx("img",{src:vr,width:220,height:220,className:"mx-auto max-w-full rounded-xl",alt:"设备邀请二维码"}):p.jsx("div",{className:"mx-auto flex h-48 w-48 items-center justify-center",children:p.jsx(He,{size:22,className:"animate-spin text-muted-foreground"})}),p.jsxs("p",{className:"text-xs leading-relaxed text-muted-foreground",children:["仅限一台设备使用 · ",new Date(oe.expiresAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," 前有效"]}),p.jsxs("button",{type:"button",className:`${Rr} inline-flex w-full items-center justify-center gap-2 text-sm`,onClick:()=>{Xp()},children:[p.jsx(Zh,{size:16}),"复制邀请链接"]}),p.jsxs("details",{className:"text-left text-xs text-muted-foreground",children:[p.jsx("summary",{className:"cursor-pointer py-2",children:"查看链接"}),p.jsx("p",{className:"mt-2 select-all break-all",children:oe.url})]})]}):p.jsxs("form",{className:"space-y-5",onSubmit:Gp,children:[p.jsxs("fieldset",{children:[p.jsx("legend",{className:"mb-2 text-sm font-medium",children:"访问权限"}),p.jsx("div",{className:"space-y-2",children:[["read","仅查看","查看终端画面,不可输入命令"],["write","可操作","查看终端画面,并输入命令"],["full","完整访问","包括文件、设置和权限管理"]].map(([U,V,de])=>p.jsxs("label",{className:`flex cursor-pointer items-center gap-3 rounded-xl border px-3 py-2.5 transition focus-within:ring-2 focus-within:ring-ring ${O===U?"border-primary bg-primary/10":"border-border hover:bg-surface-2"}`,children:[p.jsx("input",{type:"radio",name:"federation-permission",value:U,checked:O===U,onChange:()=>q(U),className:"sr-only"}),p.jsx("span",{"aria-hidden":"true",className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border ${O===U?"border-primary bg-primary text-primary-foreground":"border-border bg-background"}`,children:O===U&&p.jsx(Cc,{size:13,strokeWidth:3})}),p.jsxs("span",{className:"min-w-0",children:[p.jsx("span",{className:"block text-sm font-medium text-foreground",children:V}),p.jsx("span",{className:"mt-0.5 block text-xs leading-relaxed text-muted-foreground",children:de})]})]},U))})]}),O!=="full"&&p.jsxs("fieldset",{children:[p.jsx("legend",{className:"mb-2 text-sm font-medium",children:"可访问的终端"}),p.jsxs("div",{className:"flex gap-2",children:[p.jsx("button",{type:"button","aria-pressed":H==="all",className:`${Ke} flex-1 appearance-none border text-sm ${H==="all"?"border-primary bg-primary/10 text-foreground":"border-border text-muted-foreground"}`,onClick:()=>K("all"),children:"全部终端"}),p.jsxs("button",{type:"button","aria-pressed":H==="selected",className:`${Ke} inline-flex flex-1 appearance-none items-center justify-center gap-1 border text-sm ${H==="selected"?"border-primary bg-primary/10 text-foreground":"border-border text-muted-foreground"}`,onClick:()=>{Wc(z),co(!0)},children:[H==="selected"?`已选 ${z.length} 个`:"选择终端",p.jsx(fr,{size:14})]})]}),H==="all"&&p.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"包括之后新建的终端。"})]}),O==="write"&&p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"终端命令可读写该系统用户有权访问的文件。"}),O==="full"&&p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"拥有此服务的全部当前及未来权限。仅授予你完全信任的设备。"}),l&&p.jsxs("label",{className:"flex items-start gap-3 text-sm",children:[p.jsx("input",{type:"checkbox",className:"mt-0.5 h-4 w-4 accent-primary",checked:D,onChange:U=>_(U.target.checked)}),p.jsxs("span",{children:["让新设备也能使用备用连接",p.jsx("span",{className:"mt-1 block text-xs leading-relaxed text-muted-foreground",children:"需要入口管理员授权;关闭后生成直接连接邀请。"})]})]}),p.jsxs("div",{children:[p.jsxs("button",{className:`${Rr} inline-flex w-full items-center justify-center gap-2 text-sm`,type:"submit",disabled:E||w,children:[E&&p.jsx(He,{size:16,className:"animate-spin"}),E?"正在生成…":"生成邀请"]}),p.jsxs("p",{className:"mt-2 text-center text-xs leading-relaxed text-muted-foreground",children:["链接 10 分钟内有效 · 访问权限",Pe?"按设定时间到期":"保留至撤销"]})]})]})}),ut&&p.jsxs("section",{children:[p.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"仅允许访问勾选的终端。"}),p.jsxs("div",{className:"space-y-1",children:[f.map(U=>p.jsxs("label",{className:"flex min-h-12 cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-sm hover:bg-surface-2",children:[p.jsx("input",{type:"checkbox",className:"h-4 w-4 accent-primary",checked:Sr.includes(U.sessionId),onChange:V=>Wc(V.target.checked?[...Sr,U.sessionId]:Sr.filter(de=>de!==U.sessionId))}),p.jsx("span",{className:"min-w-0 break-words",children:U.name})]},U.sessionId)),!f.length&&p.jsx("p",{className:"py-4 text-sm text-muted-foreground",children:"当前没有可共享的终端。"})]})]}),I&&p.jsxs("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:[I,v&&p.jsx("button",{type:"button",className:`${Ke} ml-1 text-sm underline`,onClick:v,children:"重试"})]}),!k.title&&!$&&!xr&&!sn&&!ut&&!oe&&p.jsxs("div",{className:"mt-4 border-t border-border pt-2",children:[p.jsxs("button",{type:"button",className:`${Ke} -ml-3 inline-flex items-center gap-1 bg-transparent text-xs text-muted-foreground`,"aria-expanded":Er?void 0:X,onClick:()=>Er?zc(!0):G(U=>!U),children:[L?"有效期与备注":$?"手动连接":Xe==="devices"?"授权详情":"连接详情",Er?p.jsx(fr,{size:14}):p.jsx(dS,{size:13,className:X?"rotate-180":""})]}),X&&p.jsxs("section",{className:"space-y-3 pb-1 pt-2",children:[L&&p.jsxs(p.Fragment,{children:[p.jsxs("label",{className:"block space-y-1 text-sm",children:[p.jsx("span",{children:"设备备注(可选)"}),p.jsx("input",{className:No,value:Y,onChange:U=>se(U.target.value),placeholder:"例如:工作电脑"})]}),p.jsxs("label",{className:"block space-y-1 text-sm",children:[p.jsx("span",{children:"授权到期时间"}),p.jsx("input",{type:"datetime-local",className:No,value:Pe,onChange:U=>Oe(U.target.value)})]})]}),!L&&s&&p.jsxs("p",{className:"break-all text-xs leading-relaxed text-muted-foreground",children:["本设备身份:",s]})]})]}),S&&p.jsx("p",{role:"alert",className:"mt-3 text-sm text-destructive",children:S}),P&&p.jsx("p",{role:"status",className:"mt-3 text-sm text-muted-foreground",children:P})]}),ut&&p.jsx("footer",{className:"shrink-0 border-t border-border px-5 pt-3 pb-[max(16px,env(safe-area-inset-bottom))]",children:p.jsxs("button",{type:"button",className:`${Rr} w-full text-sm`,disabled:!Sr.length,onClick:()=>{W(Sr),K("selected"),co(!1)},children:["使用所选终端(",Sr.length,")"]})})]})}),document.body)}const uE={background:"#1C1B1A",foreground:"#CECDC3",cursor:"#CECDC3",cursorAccent:"#1C1B1A",selectionBackground:"#403E3C",selectionForeground:"#CECDC3",selectionInactiveBackground:"#403E3C50",black:"#6F6E69",red:"#AF3029",green:"#66800B",yellow:"#AD8301",blue:"#205EA6",magenta:"#A02F6F",cyan:"#24837B",white:"#CECDC3",brightBlack:"#6F6E69",brightRed:"#D14D41",brightGreen:"#879A39",brightYellow:"#D0A215",brightBlue:"#4385BE",brightMagenta:"#CE5D97",brightCyan:"#3AA99F",brightWhite:"#FFFCF0"},fE={background:"#FFFCF0",foreground:"#100F0F",cursor:"#100F0F",cursorAccent:"#FFFCF0",selectionBackground:"#CECDC3",selectionForeground:"#100F0F",selectionInactiveBackground:"#CECDC350",black:"#100F0F",red:"#AF3029",green:"#66800B",yellow:"#AD8301",blue:"#205EA6",magenta:"#A02F6F",cyan:"#24837B",white:"#575653",brightBlack:"#6F6E69",brightRed:"#D14D41",brightGreen:"#879A39",brightYellow:"#D0A215",brightBlue:"#4385BE",brightMagenta:"#CE5D97",brightCyan:"#3AA99F",brightWhite:"#100F0F"};function hE(t){return t==="light"?fE:uE}const Ta="termdock:open-services";function pE(){window.dispatchEvent(new Event(Ta))}function gE({client:t,initialSessionId:e}){const[r,n]=F.useState([]),[o,s]=F.useState(),i=F.useRef();F.useEffect(()=>{if(!e||i.current===e)return;const f=r.find(h=>h.sessionId===e||h.sourceSessionId===e);f&&(i.current=e,s(f))},[r,e]);const[a,c]=F.useState("正在读取已授权 Session"),[l,d]=F.useState(()=>document.documentElement.dataset.theme==="light"?"light":"dark");F.useEffect(()=>{const f=new MutationObserver(()=>d(document.documentElement.dataset.theme==="light"?"light":"dark"));return f.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>f.disconnect()},[]);const u=F.useRef(null);return F.useEffect(()=>{let f=!0;const h=async()=>{try{const m=await t.request({type:"session-list"});if(f){const y=m.items;n(y),s(w=>{if(!w)return c(y.length?"选择一个已授权 Session":"暂无已授权的在线 Session"),w;const I=y.find(v=>v.sessionId===w.sessionId);if(!I){c("Session 已移除或授权失效");return}return I.canWrite===w.canWrite&&I.canResize===w.canResize?w:I})}}catch{f&&c("目标不可达或授权已失效")}};h();const g=setInterval(()=>{h()},15e3);return()=>{f=!1,clearInterval(g)}},[t]),F.useEffect(()=>{if(!o||!u.current)return;let f=!1,h=0,g;const m=new tg({theme:hE(l),cursorBlink:o.canWrite,disableStdin:!o.canWrite,convertEol:!1}),y=new rg;m.loadAddon(y),m.open(u.current),o.canResize&&y.fit(),c("正在建立加密终端连接");const w=t.openSocket(`/api/terminal/${encodeURIComponent(o.sessionId)}/ws?flow=2`),I=()=>{f||!o.canResize||(y.fit(),w.readyState===1&&w.send(JSON.stringify({type:"resize",cols:m.cols,rows:m.rows})))};w.onopen=()=>c(o.canWrite?"读写":"只读"),w.onmessage=T=>{try{const N=JSON.parse(T.data);if(f)return;if(N.type==="connected"){g=typeof N.streamEpoch=="string"?N.streamEpoch:void 0,h=Number.isSafeInteger(N.replayLastSeq)?N.replayLastSeq:0,!o.canResize&&Number.isSafeInteger(N.cols)&&Number.isSafeInteger(N.rows)&&N.cols>0&&N.rows>0&&m.resize(N.cols,N.rows);const k=Array.isArray(N.replayChunks)?N.replayChunks.filter(x=>typeof x=="string").join(""):"";m.write((N.replayOutOfWindow?"\x1Bc":"")+k,I)}else N.type==="data"&&typeof N.data=="string"?m.write(N.data,()=>{f||(Number.isSafeInteger(N.seq)&&(h=Math.max(h,N.seq)),w.readyState===1&&Number.isSafeInteger(N.flowSeq)&&w.send(JSON.stringify({type:"output-ack",flowSeq:N.flowSeq,since:h,epoch:g})))}):N.type==="pty-size"&&!o.canResize&&Number.isSafeInteger(N.cols)&&Number.isSafeInteger(N.rows)&&N.cols>0&&N.rows>0?m.resize(N.cols,N.rows):N.type==="error"&&c("目标拒绝终端操作,请检查有效授权")}catch{c("终端数据无效"),w.close()}},w.onclose=()=>c("连接已断开;画面已过期,重新选择 Session 可重连"),w.onerror=()=>c("目标不可达或授权不足");const v=m.onData(T=>{o.canWrite&&w.readyState===1&&w.send(JSON.stringify({type:"input",data:T}))}),A=setInterval(()=>{w.readyState===1&&w.send(JSON.stringify({type:"ping"}))},2e4),B=new ResizeObserver(I);return B.observe(u.current),()=>{f=!0,clearInterval(A),B.disconnect(),v.dispose(),w.onclose=null,w.onerror=null,w.close(),m.dispose()}},[t,o,l]),p.jsxs("div",{className:"flex h-dvh flex-col bg-background text-foreground",children:[p.jsxs("div",{className:"flex items-center gap-3 border-b border-border p-3 text-sm",children:[p.jsxs("span",{className:"min-w-0 flex-1",children:["已授权 Session · ",a]}),p.jsx("button",{type:"button",onClick:pE,className:"min-h-11 shrink-0 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2",children:"服务与设备"})]}),p.jsx("div",{className:"flex flex-wrap gap-2 p-2",children:r.map(f=>p.jsxs("button",{className:"rounded border border-border px-3 py-2 text-sm hover:bg-surface-2",onClick:()=>s({...f}),children:[f.name," · ",f.canWrite?"读写":"只读"]},`${t.targetPeerId}:${f.sessionId}`))}),p.jsx("div",{ref:u,className:"min-h-0 flex-1 overflow-auto p-2"})]})}function Pa(t){if(!t.startsWith("remote:"))return null;const e=t.slice(7).split(":");if(e.length!==2)return null;try{const r=decodeURIComponent(e[0]),n=decodeURIComponent(e[1]);return!n||new URL(r).origin!==r||!/^https?:/.test(r)?null:{origin:r,id:n}}catch{return null}}class mE{constructor(e){this.source=e,this.peers={state:e.peerProtocol==="unsupported"?"unsupported":e.readPeers?"loading":"unavailable",checkedAt:null}}source;local=null;remote=[];peers;localInFlight=null;peerInFlight=null;listeners=new Set;disposed=!1;peerTimer;lastPeerAttempt=-1/0;generation=0;localHealthy=!1;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}snapshot(){if(!this.local)return null;const e=new Map;for(const r of this.local.groups)for(const n of r.remoteSessions??[]){const o=Pa(n.sessionId);o&&o.origin!==this.source.origin&&o.origin!==this.source.peerOrigin&&e.set(n.sessionId,{...n,status:"offline",serviceConnected:!1})}for(const r of this.remote)e.set(r.sessionId,r);for(const r of this.local.sessions)e.set(r.sessionId,r);return{groups:this.local.groups,sessions:[...e.values()],peers:this.peers,capabilities:this.local.capabilities}}emit(){if(this.disposed||!this.localHealthy)return;const e=this.snapshot();if(e)for(const r of this.listeners)r(e)}load(){if(this.disposed)return Promise.reject(new Error("协作连接已切换,请重新加载"));if(this.localInFlight)return this.localInFlight;this.refreshPeers();const e=this.generation,r=Promise.resolve().then(()=>this.source.readLocal()).then(n=>{if(this.disposed)throw new Error("协作连接已切换,请重新加载");if(e!==this.generation)return this.load();if(!Array.isArray(n.groups)||!Array.isArray(n.sessions))throw new Error("协作会话响应无效,请更新服务后重试");return this.local=n,this.localHealthy=!0,this.emit(),this.snapshot()}).catch(n=>{throw e===this.generation&&(this.localHealthy=!1),n}).finally(()=>{this.localInFlight===r&&(this.localInFlight=null)});return this.localInFlight=r,r}invalidate(){this.generation++,this.localInFlight=null,this.localHealthy=!1}refreshPeers(e=!1){if(this.disposed||!this.source.readPeers||this.peerInFlight||!e&&Date.now()-this.lastPeerAttempt<2e3)return;this.lastPeerAttempt=Date.now(),this.peers.checkedAt||(this.peers={state:"loading",checkedAt:null}),this.emit();const r=this.source.readPeers;this.peerInFlight=Promise.race([Promise.resolve().then(()=>r()),new Promise((n,o)=>{this.peerTimer=setTimeout(()=>o(new Error("跨服务会话加载超时,请检查客户端协作连接")),2e4)})]).then(n=>{if(this.disposed)return;const o=n.origin===this.source.origin||!!this.source.peerOrigin&&n.origin===this.source.peerOrigin;if(!Array.isArray(n.sessions)||this.source.peerProtocol==="v2"&&(n.protocolVersion!==2||!o)||n.origin&&!o||n.protocolVersion!==void 0&&n.protocolVersion!==2)throw new Error("客户端协作响应与当前服务不匹配,请更新客户端后重试");this.remote=n.sessions.filter(i=>{const a=Pa(i.sessionId);return a&&a.origin!==this.source.origin&&a.origin!==this.source.peerOrigin});const s=n.services?.filter(i=>i.origin!==this.source.origin&&i.origin!==this.source.peerOrigin);this.peers={state:s?.some(i=>!i.connected)?"partial":"ready",checkedAt:Date.now(),services:s}}).catch(n=>{this.disposed||(this.remote=this.remote.map(o=>({...o,status:"offline",serviceConnected:!1})),this.peers={state:"error",checkedAt:Date.now(),error:n instanceof Error?n.message:"跨服务会话加载失败"})}).finally(()=>{clearTimeout(this.peerTimer),this.peerInFlight=null,this.emit()})}dispose(){this.disposed=!0,clearTimeout(this.peerTimer),this.listeners.clear(),this.local=null,this.remote=[]}}async function wE(t,e){const r=navigator.serviceWorker?.controller;if(!r)return null;const n=new MessageChannel;return new Promise(o=>{const s=a=>{clearTimeout(i),n.port1.close(),o(a)},i=setTimeout(()=>s(null),5e3);n.port1.onmessage=a=>{try{const c=new URL(a.data.url,location.origin);s(c.origin===location.origin&&/^\/__termdock-download\/[a-f0-9-]{36}$/.test(c.pathname)?c.href:null)}catch{s(null)}},n.port1.onmessageerror=()=>s(null);try{r.postMessage({type:"termdock:prepare-download",blob:t,filename:e},[n.port2])}catch{s(null)}})}const yE=4*1024*1024,bE=256*1024,vE=1440*6e4;let Vr=0,Zd;function Tc(){return typeof indexedDB>"u"?Promise.resolve(null):Zd??=new Promise(t=>{const e=indexedDB.open(`termdock-terminal-snapshots:${_r}`,1);e.onupgradeneeded=()=>e.result.createObjectStore("snapshots",{keyPath:"id"}),e.onerror=()=>t(null),e.onblocked=()=>t(null),e.onsuccess=()=>{e.result.onversionchange=()=>{e.result.close(),Zd=void 0},t(e.result)}})}function Na(t){return!!t&&t.version===1&&typeof t.epoch=="string"&&t.epoch.length>0&&Number.isSafeInteger(t.cols)&&t.cols>0&&Number.isSafeInteger(t.rows)&&t.rows>0&&Number.isSafeInteger(t.seq)&&t.seq>0&&typeof t.data=="string"&&t.data.length*2<=bE&&t.savedAt<=Date.now()&&Date.now()-t.savedAt<vE}async function Hk(t){const e=Vr;try{const r=await Tc();return!r||e!==Vr?null:await new Promise(n=>{const o=r.transaction("snapshots").objectStore("snapshots").get(t);o.onerror=()=>n(null),o.onsuccess=()=>n(e===Vr&&Na(o.result)?o.result:null)})}catch{return null}}async function qk(t){const e=Vr;if(Na(t))try{const r=await Tc();if(!r||e!==Vr)return;await new Promise(n=>{const o=r.transaction("snapshots","readwrite"),s=o.objectStore("snapshots");s.put(t);const i=s.getAll();i.onsuccess=()=>{let a=0,c=0;for(const l of i.result.sort((d,u)=>u.savedAt-d.savedAt))a+=l.data.length*2,(++c>32||a>yE||!Na(l))&&s.delete(l.id)},o.oncomplete=()=>n(),o.onerror=o.onabort=()=>n()})}catch{}}async function ap(){Vr+=1;try{(await Tc())?.transaction("snapshots","readwrite").objectStore("snapshots").clear()}catch{}}typeof window<"u"&&window.addEventListener("auth:unauthorized",()=>{ap()});const pt=new Map,jt=new Map,xE=32*1024*1024,SE=8*1024*1024,EE=48;let Pn=0,La=0;function Pc(){La+=1,pt.clear(),Pn=0;for(const t of jt.values())t.controller.abort();jt.clear()}typeof window<"u"&&window.addEventListener("auth:unauthorized",Pc);function AE(t,e){const r=pt.get(t);if(r&&(Pn-=r.blob.size,pt.delete(t)),!(e.blob.size>SE))for(pt.set(t,e),Pn+=e.blob.size;pt.size>EE||Pn>xE;){const n=pt.keys().next().value;Pn-=pt.get(n).blob.size,pt.delete(n)}}async function cp(t,e={}){const r=new URL(t,typeof location<"u"?location.origin:"http://localhost");if(!/^\/api\/terminal\/fs\/(read|blob)$/.test(r.pathname))return fetch(t,{signal:e.signal});if(e.signal?.aborted)throw e.signal.reason??new DOMException("Aborted","AbortError");r.searchParams.delete("requestSlotId"),r.searchParams.delete("action"),r.searchParams.sort();const n=r.href;let o=jt.get(n);if(!o){const i=new AbortController,a=La,c=pt.get(n),l=new Headers,d=c?.headers.get("ETag");d&&l.set("If-None-Match",d);const u=setTimeout(()=>i.abort(new DOMException("File preview timed out. Please retry.","TimeoutError")),e.timeoutMs??15e3),f={controller:i,readers:0,promise:Promise.resolve(null)};f.promise=(async()=>{const h=await fetch(n,{headers:l,signal:i.signal,cache:"no-cache"});let g;return h.status===304&&c?g=c:g={blob:await h.blob(),headers:new Headers(h.headers),status:h.status},La===a&&!i.signal.aborted&&g.status===200&&g.headers.has("ETag")&&AE(n,g),h.status===401&&Pc(),g})().finally(()=>{clearTimeout(u),jt.get(n)===f&&jt.delete(n)}),o=f,jt.set(n,o)}const s=o;return s.readers+=1,new Promise((i,a)=>{let c=!1;const l=()=>c?!1:(c=!0,e.signal?.removeEventListener("abort",d),s.readers-=1,s.readers===0&&jt.get(n)===s&&(jt.delete(n),s.controller.abort()),!0),d=()=>{l()&&a(e.signal?.reason??new DOMException("Aborted","AbortError"))};if(e.signal?.addEventListener("abort",d,{once:!0}),e.signal?.aborted){d();return}s.promise.then(u=>{l()&&i(new Response(u.blob,{status:u.status,headers:u.headers}))},u=>{l()&&a(u)})})}const Nc="auth:unauthorized";let Br=null;class pe extends Error{constructor(e,r,n){super(e),this.status=r,this.code=n,this.name="TerminalApiError"}status;code}async function kE(){const t=await fetch("/api/terminal/update");if(!t.ok)throw new pe("Failed to load update state",t.status);return t.json()}async function IE(){const t=await Z(),e=await fetch("/api/terminal/update/check",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new pe("Failed to check for updates",e.status);return e.json()}async function CE(){const t=await Z(),e=await fetch("/api/terminal/update/restart",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!e.ok){const r=await e.json().catch(()=>({error:"Failed to restart Termdock"}));throw new pe(r.error||"Failed to restart Termdock",e.status)}return e.json()}async function RE(){const t=await fetch("/api/terminal/quota");if(!t.ok)throw new pe("Failed to fetch quota",t.status);return t.json()}async function TE(){const t=await Z(),e=await fetch("/api/terminal/quota/refresh",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new pe("Failed to refresh quota",e.status);return e.json()}const yr=8e3,lp=6e4,PE=32e3,dp=125e3,dt=1e4,Wr=45e3,up=8e3,fp=8e3,hp=15e3,NE=1e4,en=5e3;let LE=0;const Mo=[];let $i=!1;function Ot(t,e={}){if(typeof window>"u")return;const r=JSON.stringify({level:t==="error"||t==="timeout_or_abort"||t==="response_body_timeout"||t==="response_body_parse_error"?"warn":"info",message:`DIFF_API ${t}`,data:{seq:++LE,ts:Date.now(),...e}});Mo.push(r),BE()}async function BE(){if(!$i){$i=!0;try{for(;Mo.length>0;){const t=Mo[0];try{await fetch("/api/client-log",{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:!0}),Mo.shift()}catch{break}}}finally{$i=!1}}}function Lc(t,e,r){const n=new AbortController;let o=setTimeout(()=>{n.abort(new DOMException(r,"TimeoutError"))},e);const s=()=>n.abort(t?.reason);return t&&(t.aborted?s():t.addEventListener("abort",s,{once:!0})),{signal:n.signal,cleanup:()=>{o&&(clearTimeout(o),o=null),t?.removeEventListener("abort",s)}}}async function he(t,e,r,n){const{signal:o,cleanup:s}=Lc(e?.signal??void 0,r,n);try{return await fetch(t,{...e,signal:o})}catch(i){throw i instanceof DOMException&&i.name==="TimeoutError"?new Error(n):i}finally{s()}}async function pp(t,e,r){let n=null;const o=new Promise((s,i)=>{n=setTimeout(()=>i(new Error(r)),e)});try{return await Promise.race([t.text(),o])}finally{n&&clearTimeout(n)}}async function tn(t,e,r){const n=await pp(t,e,r);return JSON.parse(n)}if(typeof window<"u"&&!window.__termdockFetchPatched){window.__termdockFetchPatched=!0;const t=window.fetch.bind(window);window.fetch=async(...e)=>{const r=await t(...e);if(r.status===401){Br=null,Uc();try{window.dispatchEvent(new CustomEvent(Nc))}catch{}}return r}}async function Z(){if(Br)return Br;const t=await he("/api/csrf-token",void 0,up,"CSRF token request timed out");if(!t.ok)throw new Error("Failed to get CSRF token");const e=await tn(t,en,"CSRF token response timed out");if(!e.csrfToken)throw new Error("Invalid CSRF token response");return Br=e.csrfToken,Br}function Bc(){Uc(),Br=null}const _E=2e4,Jd=8e3,DE=1500,gp=250,ge=new Map,_c=new Map,OE=24,FE=40,ME=40;function jE(t){return t.retryState.retryCount>=2||t.pendingInputs.length>=ME?"congested":t.retryState.retryCount>=1||t.pendingInputs.length>=8?"degraded":"good"}function Qd(t){if(t.pendingInputs.length===0||t.ws.readyState!==WebSocket.OPEN)return;const e=t.pendingInputs.splice(0);for(const r of e)try{t.ws.send(JSON.stringify({type:"input",data:r}))}catch{}}function mp(t){if(t.ws.readyState!==WebSocket.OPEN)return;const e=jE(t);if(e==="good"){Qd(t);return}if(t.inputFlushTimer)return;const r=e==="congested"?FE:OE;t.inputFlushTimer=setTimeout(()=>{t.inputFlushTimer=null,Qd(t)},r)}const jn=new Map;function UE(t,e,r,n){const o=jn.get(t);o&&(jn.delete(t),e?o.resolve({success:!0,layout:r}):o.reject(new Error(n||"Tmux action failed")))}const Pr=new Map;function $E(t,e,r,n){const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/terminal/${t}/ws`,i=new URLSearchParams({flow:"2",transport:"tmux-client",active:_c.get(t)===!1?"0":"1"});e>0&&i.set("since",String(e)),r&&i.set("epoch",r);const a=n??Pr.get(t);return a&&(i.set("cols",String(a.cols)),i.set("rows",String(a.rows))),`${s}?${i}`}const Ba=new Map,_a=new Map;function HE(t,e,r){Ba.set(t,e),_a.set(t,r)}function qE(t){const e=ge.get(t);return e?.streamEpoch&&e.appliedSeq===e.lastSeq&&e.lastSeq>0?{seq:e.lastSeq,epoch:e.streamEpoch}:null}async function KE(t){const e=await Z(),r=await fetch("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({cols:t.cols||80,rows:t.rows||24,mode:t.mode||"shell",tmuxSessionName:t.tmuxSessionName,cwd:t.cwd,termType:t.termType})});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to create terminal"}));throw new Error(n.error||"Failed to create terminal session")}return r.json()}function zE(t,e,r,n={}){const{maxRetries:o=10,initialRetryDelay:s=1e3,maxRetryDelay:i=2e4,connectionTimeout:a=15e3}=n,c={maxRetries:o,initialDelayMs:s,maxDelayMs:i,connectionTimeoutMs:a,retryCount:0,retryTimeout:null,connectionTimeoutId:null,isClosed:!1,isSuspended:!1};let l=null,d=Ba.get(t)??0,u=_a.get(t);_a.delete(t),Ba.delete(t);const f=[];let h=!1,g=null;const m=new WeakSet,y=()=>{c.retryTimeout&&(clearTimeout(c.retryTimeout),c.retryTimeout=null),c.connectionTimeoutId&&(clearTimeout(c.connectionTimeoutId),c.connectionTimeoutId=null),g&&(clearTimeout(g),g=null)},w=T=>{T.wakeProbe&&(clearTimeout(T.wakeProbe.timer),T.wakeProbe=void 0),T.heartbeatTimer&&(clearInterval(T.heartbeatTimer),T.heartbeatTimer=null),T.pongTimer&&(clearTimeout(T.pongTimer),T.pongTimer=null),T.inputFlushTimer&&(clearTimeout(T.inputFlushTimer),T.inputFlushTimer=null)},I=T=>{w(T),T.heartbeatTimer=setInterval(()=>{if(T.ws.readyState===WebSocket.OPEN){try{T.ws.send(JSON.stringify({type:"ping"}))}catch{}T.pongTimer&&clearTimeout(T.pongTimer),T.pongTimer=setTimeout(()=>{if(Date.now()-T.lastInboundAt>=Jd){h=!0,w(T);try{T.ws.close()}catch{}B(new Error("WebSocket heartbeat timeout"),!1)}},Jd)}},_E)},v=()=>{if(c.isClosed=!0,y(),l){w(l),ge.delete(t);try{l.ws.close()}catch{}l=null}},A=()=>{if(c.isClosed)return;if(l){m.add(l.ws),w(l);try{l.ws.close()}catch{}}const T=$E(t,d,u,n.getDimensions?.()),N=jx(T);h=!1,c.connectionTimeoutId=setTimeout(()=>{N.readyState!==WebSocket.OPEN&&(h=!0,N.close(),B(new Error("WebSocket connection timeout"),!1))},a);const k={ws:N,onEvent:e,onError:r,reconnectNow:()=>{if(!c.isClosed&&(c.isSuspended=!1,!g)){if(y(),l){m.add(l.ws),w(l);try{l.ws.close()}catch{}}e({type:"reconnecting",attempt:Math.min(c.retryCount+1,o),maxAttempts:o}),c.retryCount=Math.min(c.retryCount+1,o),h=!0,g=setTimeout(()=>{g=null,h=!1,A()},0)}},suspendReconnect:()=>{c.isClosed||(c.isSuspended=!0,c.retryTimeout&&(clearTimeout(c.retryTimeout),c.retryTimeout=null))},retryState:c,lastSeq:d,pendingInputs:f,inputFlushTimer:null,heartbeatTimer:null,pongTimer:null,lastInboundAt:Date.now(),inboundSequence:0};N.onopen=()=>{c.isClosed||m.has(N)||h||(y(),c.retryCount=0,k.lastInboundAt=Date.now(),k.inboundSequence+=1,I(k),mp(k))},N.onmessage=x=>{if(!(c.isClosed||m.has(N)||h)){k.lastInboundAt=Date.now(),k.inboundSequence+=1;try{const S=JSON.parse(x.data);if(k.wakeProbe&&ge.get(t)===k){const P=k.wakeProbe;k.wakeProbe=void 0,clearTimeout(P.timer);for(const b of P.listeners)b()}if(S.type==="pong"){k.pongTimer&&(clearTimeout(k.pongTimer),k.pongTimer=null);return}if(S.type==="tmux-result"&&S.reqId){UE(S.reqId,S.success!==!1,S.layout,S.error);return}if(S.type==="tmux-layout"&&S.layout){e({type:"tmux-layout",layout:S.layout});return}if(S.type==="tmux-screen-sync"&&Array.isArray(S.chunks)){e({type:"tmux-screen-sync",chunks:S.chunks.filter(P=>typeof P=="string"),cols:typeof S.cols=="number"?S.cols:void 0,rows:typeof S.rows=="number"?S.rows:void 0,generation:typeof S.generation=="number"?S.generation:void 0});return}if(S.type==="active-program"){e({type:"active-program",activeProgram:S.activeProgram,activeProgramRaw:S.activeProgramRaw,activeProgramSource:S.activeProgramSource});return}if(S.type==="cwd"){e({type:"cwd",cwd:S.cwd});return}if(S.type==="agent-status"){e({type:"agent-status",agentStatus:S.agentStatus??null,agentIndicator:S.agentIndicator??null,agentStatusDetail:S.agentStatusDetail??null,agent:S.agent??null,agentMessage:S.agentMessage??null,agentNativeSessionId:S.agentNativeSessionId??null,agentResumeRecovered:S.agentResumeRecovered===!0,agentRich:S.agentRich===!0,agentActivity:typeof S.agentActivity=="number"?S.agentActivity:0,agentCwd:S.agentCwd??null,reviewed:typeof S.reviewed=="boolean"?S.reviewed:null});return}if(S.type==="git-status"){e({type:"git-status",gitStatus:S.gitStatus??null});return}if(S.type==="quota-status"&&Array.isArray(S.providers)){window.dispatchEvent(new CustomEvent("termdock:quota-update",{detail:S.providers}));return}if(S.type==="focus-mode"){e({type:"focus-mode",focusTrackingRequested:S.focusTrackingRequested===!0});return}if(S.type==="resize-ack"){e({type:"resize-ack",seq:typeof S.seq=="number"?S.seq:void 0,cols:typeof S.cols=="number"?S.cols:void 0,rows:typeof S.rows=="number"?S.rows:void 0,ok:S.ok!==!1,error:typeof S.error=="string"?S.error:void 0,screenSyncPending:S.screenSyncPending===!0,screenSyncGeneration:typeof S.screenSyncGeneration=="number"?S.screenSyncGeneration:void 0});return}if(S.type==="pty-size"){e({type:"pty-size",cols:typeof S.cols=="number"?S.cols:void 0,rows:typeof S.rows=="number"?S.rows:void 0,source:typeof S.source=="string"?S.source:void 0});return}if(S.type==="shell-title"){e({type:"shell-title",title:typeof S.title=="string"?S.title:""});return}if(S.type==="prompt-state"){e({type:"prompt-state",state:S.state==="running"?"running":"idle",exitCode:typeof S.exitCode=="number"?S.exitCode:void 0});return}const R=S;if(R.type==="connected"){k.appliedSeq=void 0,u=R.streamEpoch,k.streamEpoch=u,k.outputProtocol=R.outputProtocol,typeof R.replayLastSeq=="number"&&R.replayLastSeq>=0&&(d=R.replayLastSeq,k.lastSeq=d),e(R),wp(t,_c.get(t)??!0);return}if(R.type==="exit"){v(),e(R);return}if(R.type==="data"){if(k.appliedSeq=void 0,typeof R.seq=="number"&&R.seq<=d)return;typeof R.flowSeq=="number"&&(k.flowSeq=R.flowSeq)}e(R),R.type==="data"&&typeof R.seq=="number"&&Number.isFinite(R.seq)&&R.seq>d&&(d=R.seq,k.lastSeq=d)}catch(S){r?.(S,!1)}}},N.onerror=()=>{c.isClosed||m.has(N)||h||(y(),w(k),h||(h=!0,B(new Error("WebSocket connection error"),!1)))},N.onclose=x=>{if(!(c.isClosed||m.has(N)||h)){if(y(),w(k),h=!0,x.code===4001){console.warn("[Terminal] WS 4001: Session not found on server",{code:x.code,reason:x.reason,stack:new Error().stack}),B(new Error("Session not found on server"),!0);return}if(x.code===4003||x.code===4401){try{window.dispatchEvent(new CustomEvent(Nc))}catch{}B(new Error("Authentication required"),!0);return}B(new Error("WebSocket connection closed"),!1)}},l=k,ge.set(t,l)},B=(T,N)=>{if(!c.isClosed)if(N)r?.(T,!0),v();else{c.retryCount=Math.min(c.retryCount+1,Math.max(1,o));const k=Math.min(s*Math.pow(2,c.retryCount-1),i);if(e({type:"reconnecting",attempt:c.retryCount,maxAttempts:o}),c.isSuspended)return;c.retryTimeout=setTimeout(()=>{c.isClosed||A()},k)}};return A(),v}async function VE(t,e){const r=ge.get(t);if(r){if(r.ws.readyState===WebSocket.OPEN){r.pendingInputs.push(e),mp(r);return}if(r.ws.readyState===WebSocket.CONNECTING){r.pendingInputs.push(e);return}}const n=await Z(),o=await fetch(`/api/terminal/${t}/input`,{method:"POST",headers:{"Content-Type":"text/plain","X-XSRF-TOKEN":n},body:e});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to send input"}));throw new Error(s.error||"Failed to send terminal input")}}function WE(t,e,r={}){const n=ge.get(t);if(!n)return!1;if(n.retryState.isSuspended=!1,n.ws.readyState!==WebSocket.OPEN)return n.reconnectNow(),!0;const o=r.visible?gp:DE,s=Date.now()+o,i=n.wakeProbe,a=i?.listeners??new Set;if(e&&a.add(e),i&&i.deadline<=s)return!0;i&&clearTimeout(i.timer);const c=setTimeout(()=>{ge.get(t)!==n||n.retryState.isClosed||(n.wakeProbe=void 0,n.reconnectNow())},o);if(n.wakeProbe={timer:c,listeners:a,deadline:s},i)return!0;try{n.ws.send(JSON.stringify({type:"ping"}))}catch{clearTimeout(c),n.wakeProbe=void 0,n.reconnectNow()}return!0}function GE(t){const e=ge.get(t);return e?(e.reconnectNow(),!0):!1}function XE(){for(const t of ge.values())t.suspendReconnect()}function YE(t,e,r){const n=ge.get(t);if(!(!n||n.ws.readyState!==WebSocket.OPEN))try{n.ws.send(JSON.stringify({type:"focus",focused:e,reason:r}))}catch{}}function wp(t,e){_c.set(t,e);const r=ge.get(t);!r||r.ws.readyState!==WebSocket.OPEN||r.outputProtocol!==2||r.ws.send(JSON.stringify({type:"output-subscription",active:e,since:r.lastSeq,epoch:r.streamEpoch}))}function ZE(t){const e=ge.get(t);!e||e.ws.readyState!==WebSocket.OPEN||e.outputProtocol!==2||(e.appliedSeq=e.lastSeq,!(!e.flowSeq||e.flowSeq===e.acknowledgedFlowSeq)&&(e.acknowledgedFlowSeq=e.flowSeq,e.ws.send(JSON.stringify({type:"output-ack",flowSeq:e.flowSeq,since:e.appliedSeq,epoch:e.streamEpoch}))))}function JE(t,e,r){const n=ge.get(t);if(!(!n||n.ws.readyState!==WebSocket.OPEN))try{n.ws.send(JSON.stringify({type:"viewing",viewing:e,reason:r}))}catch{}}function QE(t){const e=ge.get(t);if(!(!e||e.ws.readyState!==WebSocket.OPEN))try{e.ws.send(JSON.stringify({type:"agent-review-ack"}))}catch{}}function e1(t,e,r){const n=ge.get(t);if(!(!n||n.ws.readyState!==WebSocket.OPEN))try{n.ws.send(JSON.stringify({type:"flow-control",paused:e,reason:r}))}catch{}}async function t1(t,e,r,n){Number.isFinite(e)&&Number.isFinite(r)&&e>=1&&r>=1&&(Pr.delete(t),Pr.set(t,{cols:Math.floor(e),rows:Math.floor(r)}),Pr.size>256&&Pr.delete(Pr.keys().next().value));const o=ge.get(t);if(o&&o.ws.readyState===WebSocket.OPEN)try{o.ws.send(JSON.stringify({type:"resize",cols:e,rows:r,seq:n}));return}catch{}const s=await Z(),i=await fetch(`/api/terminal/${t}/resize`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":s},body:JSON.stringify({cols:e,rows:r,seq:n})});if(!i.ok){const c=await i.json().catch(()=>({error:"Failed to resize terminal"}));throw new Error(c.error||"Failed to resize terminal")}const a=await i.json().catch(()=>({success:!0}));if(a?.success===!1||a?.ok===!1)throw new Error(a?.error||"Failed to resize terminal")}async function r1(t,e){const r=ge.get(t);if(r&&r.ws.readyState===WebSocket.OPEN)return e.action==="scroll"?(r.ws.send(JSON.stringify({type:"tmux",...e})),{success:!0}):new Promise((s,i)=>{const a=Math.random().toString(36).substring(7);jn.set(a,{resolve:s,reject:i}),r.ws.send(JSON.stringify({type:"tmux",reqId:a,...e})),setTimeout(()=>{jn.has(a)&&(jn.delete(a),i(new Error("Tmux action timed out")))},3e4)});const n=await Z(),o=await fetch(`/api/terminal/${t}/tmux`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify(e)});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to execute tmux action"}));throw new Error(s.error||"Failed to execute tmux action")}return o.json()}async function n1(t){const e=ge.get(t);if(e){e.retryState.isClosed=!0;try{e.ws.close()}catch{}ge.delete(t)}const r=await Z(),n=await fetch(`/api/terminal/${t}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":r}});if(n.status!==404&&!n.ok){const o=await n.json().catch(()=>({error:"Failed to close terminal"}));throw new Error(o.error||"Failed to close terminal")}}async function o1(t,e){const r=ge.get(t);if(r){r.retryState.isClosed=!0;try{r.ws.close()}catch{}ge.delete(t)}const n=await Z(),o=await fetch(`/api/terminal/${t}/restart`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify({...e.cwd?{cwd:e.cwd}:{},cols:e.cols??80,rows:e.rows??24,mode:e.mode,tmuxSessionName:e.tmuxSessionName})});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to restart terminal"}));throw new Error(s.error||"Failed to restart terminal session")}return o.json()}async function s1(t){const e=await he(`/api/terminal/${t}/health`,{method:"GET"},fp,"Terminal health check timed out");if(!e.ok){if(e.status===404)return{healthy:!1,sessionId:t};const r=await tn(e,en,"Terminal health error response timed out").catch(()=>({error:"Failed to check terminal health"}));throw new Error(r.error||"Failed to check terminal health")}return tn(e,en,"Terminal health response timed out")}async function i1(t){const e=await Z(),r=await he("/api/terminal/force-kill",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)},NE,"Terminal force-kill request timed out");if(!r.ok){const n=await tn(r,en,"Terminal force-kill error response timed out").catch(()=>({error:"Failed to force kill terminal"}));throw new Error(n.error||"Failed to force kill terminal")}}async function a1(){const t=await fetch("/api/terminal/tmux/sessions",{method:"GET"});if(!t.ok){const r=await t.json().catch(()=>({error:"Failed to list tmux sessions"}));throw new Error(r.error||"Failed to list tmux sessions")}const e=await t.json();return Array.isArray(e.sessions)?e.sessions:[]}async function c1(){const t=await fetch("/api/terminal/tmux/status",{method:"GET"});if(!t.ok){const e=await t.json().catch(()=>({error:"Failed to get tmux status"}));throw new Error(e.error||"Failed to get tmux status")}return t.json()}async function l1(t){const e=t.trim();if(!e)throw new Error("tmux session name is required");const r=await Z(),n=await fetch(`/api/terminal/tmux/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":r}});if(!n.ok){const s=await n.json().catch(()=>({error:"Failed to kill tmux session"}));throw new Error(s.error||"Failed to kill tmux session")}const o=await n.json();return{cleanedSessions:Array.isArray(o.cleanedSessions)?o.cleanedSessions:[],alreadyGone:!!o.alreadyGone}}async function d1(){const t=await Z(),e=await fetch("/api/terminal/tmux/recovery/restore-all",{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await e.json().catch(()=>({}));if(!e.ok)throw new pe(r.error||"Failed to restore tmux Agent sessions",e.status);return r}async function u1(){const t=await Z(),e=await fetch("/api/terminal/tmux/recovery",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new pe("Failed to dismiss tmux recovery",e.status)}const Lo=new Map;function f1(t){return JSON.stringify({preferredFrontendSessionId:t.preferredFrontendSessionId??null,mode:t.mode??null,tmuxSessionName:t.tmuxSessionName??null,cwd:t.cwd??null,termType:t.termType??null,createIfEmpty:t.createIfEmpty===!0,requireExisting:t.requireExisting===!0})}async function h1(){const t=await fetch("/api/terminal/session-inventory",{method:"GET"});if(!t.ok){const e=await t.json().catch(()=>({error:"Failed to load session inventory"}));throw new Error(e.error||"Failed to load session inventory")}return t.json()}async function p1(t){const e=f1(t),r=Lo.get(e);if(r)return r;const n=await Z(),o=he("/api/terminal/session-inventory/open",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify(t)},hp,"Terminal session open request timed out").then(async s=>{if(!s.ok){const i=await tn(s,en,"Terminal session open error response timed out").catch(()=>({error:"Failed to open session"}));throw new pe(i.error||"Failed to open session",s.status,typeof i.code=="string"?i.code:void 0)}return tn(s,en,"Terminal session open response timed out")}).finally(()=>{Lo.get(e)===o&&Lo.delete(e)});return Lo.set(e,o),o}async function g1(t,e){const r=await Z(),n=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(e)});if(!n.ok){const o=await n.json().catch(()=>({error:"Failed to update session"}));throw new Error(o.error||"Failed to update session")}return n.json()}async function m1(t){const e=await Z(),r=await fetch("/api/terminal/session-inventory/reorder",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({sessionIds:t})});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to reorder sessions"}));throw new Error(n.error||"Failed to reorder sessions")}return r.json()}async function w1(t){const e=await Z(),r=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to remove session"}));throw new Error(n.error||"Failed to remove session")}}async function y1(){const t=await Z(),e=await fetch("/api/terminal/session-inventory/sessions",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok){const r=await e.json().catch(()=>({error:"Failed to clear sessions"}));throw new Error(r.error||"Failed to clear sessions")}}async function b1(){const t=await fetch("/api/terminal/toolbar-presets",{method:"GET"});if(!t.ok){const e=await t.json().catch(()=>({error:"Failed to load toolbar presets"}));throw new Error(e.error||"Failed to load toolbar presets")}return t.json()}async function v1(t){const e=await Z(),r=await fetch("/api/terminal/toolbar-presets",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to save toolbar presets"})),o=new Error(n.error||"Failed to save toolbar presets");throw o.current=n.current,o.code=n.code,o}return r.json()}let Sn=null,Nn=null;const yp=1500;function ms(){return Nn&&Date.now()-Nn.readAt<yp?Promise.resolve(Nn.value):Sn||(Sn=(async()=>{const t=await fetch("/api/terminal/settings",{method:"GET"});if(!t.ok){const r=await t.json().catch(()=>({error:"Failed to load settings"}));throw new Error(r.error||"Failed to load settings")}const e=await t.json();return Nn={value:e,readAt:Date.now()},e})().finally(()=>{Sn=null}),Sn)}async function Gt(t){const e=await Z(),r=await fetch("/api/terminal/settings",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!r.ok){const o=await r.json().catch(()=>({error:"Failed to update settings"}));throw new Error(o.error||"Failed to update settings")}const n=await r.json();return Nn={value:n,readAt:Date.now()},n}async function x1(t=!1){const e=await fetch(`/api/terminal/auto-title/catalog${t?"?refresh=1":""}`);if(!e.ok)throw new Error("Failed to discover title models");const r=await e.json();return Array.isArray(r?.namers)?r.namers:[]}let En=null,Ln=null;function S1(){return Ln&&Date.now()-Ln.readAt<yp?Promise.resolve(Ln.value):En||(En=(async()=>{const t=await fetch("/api/terminal/context-draft",{method:"GET"});if(!t.ok){const r=await t.json().catch(()=>({error:"Failed to load context draft"}));throw new Error(r.error||"Failed to load context draft")}const e=await t.json();return Ln={value:e,readAt:Date.now()},e})().finally(()=>{En=null}),En)}async function E1(t,e){const r=await Z(),n=await fetch("/api/terminal/context-draft",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify({text:t,origin:e})});if(!n.ok){const s=await n.json().catch(()=>({error:"Failed to update context draft"}));throw new Error(s.error||"Failed to update context draft")}const o=await n.json();return Ln={value:o,readAt:Date.now()},o}async function bp(t){const e=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:t})});if(e.ok)return Bc(),{ok:!0};const r=await e.json().catch(()=>null);return e.status===429?{ok:!1,rateLimited:!0,retryAfterMs:typeof r?.retryAfterMs=="number"?r.retryAfterMs:void 0,error:r?.error||"Too many failed attempts. Please wait and try again."}:{ok:!1,error:r?.error||"Login failed"}}async function A1(){Pc(),ap();const t=await Z();await fetch("/api/auth/logout",{method:"POST",headers:{"X-XSRF-TOKEN":t}}),Bc()}async function k1(){const t=await fetch("/api/terminal/agent-launchers");if(!t.ok)throw new Error("Failed to detect agent launchers");const e=await t.json();return Array.isArray(e?.agents)?e.agents:[]}async function I1(){const t=await fetch("/api/terminal/agent-hooks");if(!t.ok)throw new Error("Failed to get agent hooks");const e=await t.json();return Array.isArray(e?.agents)?e.agents:[]}async function C1(t){const e=await Z(),r=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(t)}/install`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Error(n.error||"Failed to install agent hooks");return{summary:n.summary??"Installed",devMode:n.devMode===!0}}async function R1(t){const e=await Z(),r=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(t)}/uninstall`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Error(n.error||"Failed to uninstall agent hooks");return n.summary??"Removed"}class Dc extends Error{constructor(e,r,n){super(e),this.code=r,this.migration=n,this.name="AgentPluginManifestError"}code;migration}async function T1(){const t=await fetch("/api/terminal/agent-plugins");if(!t.ok)throw new Error("Failed to get agent plugins");return await t.json()}async function P1(t){const e=await Z(),r=await fetch("/api/terminal/agent-plugins",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Dc(n.error||"Failed to create agent plugin",n.code,n.migration);return n}async function N1(t){const e=await Z(),r=await fetch("/api/terminal/agent-plugins/install",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({source:t})}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Dc(n.error||"Failed to install agent plugin",n.code,n.migration);return n}async function L1(t){const e=await Z(),r=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}/check-update`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Error(n.error||"Failed to check plugin updates");return n}async function B1(t){const e=await Z(),r=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}/update`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Error(n.error||"Failed to update plugin");return n}async function _1(t){const e=await Z(),r=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}/doctor`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Error(n.error||"Failed to diagnose plugin");return n}async function D1(t){const e=await Z(),r=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(n.error||"Failed to delete agent plugin")}}async function O1(t){const e=await Z(),r=await fetch(`/api/terminal/${encodeURIComponent(t)}/agent-resume`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new pe(n.error||"Failed to resume agent session",r.status,typeof n.code=="string"?n.code:void 0);return{command:n.command??""}}async function F1(){const t=await fetch("/api/terminal/agent-resume-history",{method:"GET"});if(!t.ok)throw new Error("Failed to load Agent resume history");const e=await t.json().catch(()=>({entries:[]}));return Array.isArray(e.entries)?e.entries:[]}async function M1(t){const e=await Z(),r=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(t)}/prepare`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new pe(n.error||"Failed to prepare Agent session resume",r.status,typeof n.code=="string"?n.code:void 0);return n}async function j1(t){const e=await Z(),r=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!r.ok&&r.status!==404)throw new Error("Failed to remove Agent resume history")}async function U1(t){const e=await Z(),r=await fetch("/api/terminal/program-rules",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to update program rules"}));throw new Error(n.error||"Failed to update program rules")}return r.json()}async function $1(){const t=await Z(),e=await fetch("/api/terminal/program-rules",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Error("Failed to reset program rules");return e.json()}async function H1(){const t=await fetch("/api/terminal/program-detection");if(!t.ok)throw new Error("Failed to get program detection config");return t.json()}async function q1(t){const e=await Z(),r=await fetch("/api/terminal/program-detection",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!r.ok)throw new Error("Failed to save program detection config");return r.json()}async function K1(){const t=await Z(),e=await fetch("/api/terminal/program-detection",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Error("Failed to reset program detection config");return e.json()}const z1={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".bmp":"image/bmp",".ico":"image/x-icon",".svg":"image/svg+xml",".heic":"image/heic",".heif":"image/heif"};function Fs(t){const e=t.lastIndexOf(".");return e<0?null:z1[t.slice(e).toLowerCase()]??null}function V1(t){return Fs(t)!==null}function vp(t){const e=Fs(t);return e==="image/heic"||e==="image/heif"}const W1={".mp4":"video/mp4",".m4v":"video/x-m4v",".webm":"video/webm",".mov":"video/quicktime",".ogv":"video/ogg",".mpeg":"video/mpeg",".mpg":"video/mpeg"};function xp(t){const e=t.lastIndexOf(".");return e<0?null:W1[t.slice(e).toLowerCase()]??null}function G1(t){return xp(t)!==null}function X1(t){return`/api/terminal/fs/video?path=${encodeURIComponent(t)}&action=view_file`}const Sp=[".stl",".glb",".gltf"];function Oc(t){const e=t.lastIndexOf(".");if(e<0)return null;const r=t.slice(e).toLowerCase();return Sp.includes(r)?r:null}function Y1(t){return Oc(t)!==null}function Fc(t){const e=t.toLowerCase();return e.endsWith(".kicad_sch")?".kicad_sch":e.endsWith(".kicad_pcb")?".kicad_pcb":null}function Z1(t){return Fc(t)!==null}function J1(t){return Fc(t)===".kicad_pcb"?"pcb-front":"schematic"}const Ep=[".html",".htm"];function Q1(t){const e=t.lastIndexOf(".");if(e<0)return!1;const r=t.slice(e).toLowerCase();return Ep.includes(r)}function e2(t){return`/api/terminal/fs/preview/${t.split(/[\\/]+/).filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}const t2={".stl":"model/stl",".glb":"model/gltf-binary",".gltf":"model/gltf+json"};async function r2(t,e,r,n="list_directory",o,s="name"){const i=new URLSearchParams({path:t});r&&i.set("showHidden","true"),s!=="name"&&i.set("sort",s),i.set("action",n),o&&i.set("requestSlotId",o);const a=await he(`/api/terminal/fs/list?${i}`,{signal:e},yr,"Directory listing took too long. The folder may be on slow storage or blocked by another process.");if(!a.ok){const c=await a.json().catch(()=>({error:"Failed to list directory"}));throw new Error(c.error||"Failed to list directory")}return a.json()}async function n2(t,e,r,n,o,s="name",i,a={}){const c=new URLSearchParams({path:t,query:e,stream:"true"});o&&c.set("showHidden","true"),s==="content"&&c.set("mode","content"),i&&c.set("requestSlotId",i);for(const g of a.excludePatterns??[])c.append("exclude",g);a.caseSensitive&&c.set("caseSensitive","true"),a.wholeWord&&c.set("wholeWord","true"),a.regex&&c.set("regex","true");const l=await fetch(`/api/terminal/fs/search?${c}`,{signal:n});if(!l.ok||!l.body){const g=await l.json().catch(()=>({error:"Failed to search files"}));throw new Error(g.error||"Failed to search files")}const d=l.body.getReader(),u=new TextDecoder;let f="";const h=g=>{if(!g.trim())return;const m=JSON.parse(g);if(m.type==="meta")r({path:m.path,query:m.query,engine:m.engine,mode:m.mode,limited:m.limited});else if(m.type==="batch")r({entries:m.entries??[]});else if(m.type==="content-batch")r({contentEntries:m.contentEntries??[]});else{if(m.type==="error")throw new Error(m.message||"Search failed");m.type==="done"&&r({total:m.total,truncated:m.truncated,limited:m.limited,engine:m.engine,mode:m.mode,done:!0})}};for(;;){const{value:g,done:m}=await d.read();if(m)break;f+=u.decode(g,{stream:!0});let y=f.indexOf(`
|
|
8
|
+
`);const P=v(N,k,S),b=t.getSymbolSize(N),E=new n(b);return h(E,N),g(E),m(E,N),w(E,k,0),N>=7&&y(E,N),I(E,P),isNaN(x)&&(x=i.getBestMask(E,w.bind(null,E,k))),i.applyMask(x,E),w(E,k,x),{modules:E,version:N,errorCorrectionLevel:k,maskPattern:x,segments:S}}return Si.create=function(N,k){if(typeof N>"u"||N==="")throw new Error("No input text");let x=e.M,S,R;return typeof k<"u"&&(x=e.from(k.errorCorrectionLevel,e.M),S=l.from(k.version),R=i.from(k.maskPattern),k.toSJISFunc&&t.setToSJISFunction(k.toSJISFunc)),B(N,S,x,R)},Si}var $i={},Hi={},Xd;function lp(){return Xd||(Xd=1,(function(t){function e(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(s){return[s,s]}))),n.length===6&&n.push("F","F");const o=parseInt(n.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+n.slice(0,6).join("")}}t.getOptions=function(n){n||(n={}),n.color||(n.color={});const o=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,s=n.width&&n.width>=21?n.width:void 0,i=n.scale||4;return{width:s,scale:s?4:i,margin:o,color:{dark:e(n.color.dark||"#000000ff"),light:e(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},t.getScale=function(n,o){return o.width&&o.width>=n+o.margin*2?o.width/(n+o.margin*2):o.scale},t.getImageWidth=function(n,o){const s=t.getScale(n,o);return Math.floor((n+o.margin*2)*s)},t.qrToImageData=function(n,o,s){const i=o.modules.size,a=o.modules.data,c=t.getScale(i,s),l=Math.floor((i+s.margin*2)*c),d=s.margin*c,u=[s.color.light,s.color.dark];for(let f=0;f<l;f++)for(let h=0;h<l;h++){let g=(f*l+h)*4,m=s.color.light;if(f>=d&&h>=d&&f<l-d&&h<l-d){const y=Math.floor((f-d)/c),w=Math.floor((h-d)/c);m=u[a[y*i+w]?1:0]}n[g++]=m.r,n[g++]=m.g,n[g++]=m.b,n[g]=m.a}}})(Hi)),Hi}var Yd;function iE(){return Yd||(Yd=1,(function(t){const e=lp();function r(o,s,i){o.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=i,s.width=i,s.style.height=i+"px",s.style.width=i+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}t.render=function(s,i,a){let c=a,l=i;typeof c>"u"&&(!i||!i.getContext)&&(c=i,i=void 0),i||(l=n()),c=e.getOptions(c);const d=e.getImageWidth(s.modules.size,c),u=l.getContext("2d"),f=u.createImageData(d,d);return e.qrToImageData(f.data,s,c),r(u,l,d),u.putImageData(f,0,0),l},t.renderToDataURL=function(s,i,a){let c=a;typeof c>"u"&&(!i||!i.getContext)&&(c=i,i=void 0),c||(c={});const l=t.render(s,i,c),d=c.type||"image/png",u=c.rendererOpts||{};return l.toDataURL(d,u.quality)}})($i)),$i}var qi={},Zd;function aE(){if(Zd)return qi;Zd=1;const t=lp();function e(o,s){const i=o.a/255,a=s+'="'+o.hex+'"';return i<1?a+" "+s+'-opacity="'+i.toFixed(2).slice(1)+'"':a}function r(o,s,i){let a=o+s;return typeof i<"u"&&(a+=" "+i),a}function n(o,s,i){let a="",c=0,l=!1,d=0;for(let u=0;u<o.length;u++){const f=Math.floor(u%s),h=Math.floor(u/s);!f&&!l&&(l=!0),o[u]?(d++,u>0&&f>0&&o[u-1]||(a+=l?r("M",f+i,.5+h+i):r("m",c,0),c=0,l=!1),f+1<s&&o[u+1]||(a+=r("h",d),d=0)):c++}return a}return qi.render=function(s,i,a){const c=t.getOptions(i),l=s.modules.size,d=s.modules.data,u=l+c.margin*2,f=c.color.light.a?"<path "+e(c.color.light,"fill")+' d="M0 0h'+u+"v"+u+'H0z"/>':"",h="<path "+e(c.color.dark,"stroke")+' d="'+n(d,l,c.margin)+'"/>',g='viewBox="0 0 '+u+" "+u+'"',y='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+g+' shape-rendering="crispEdges">'+f+h+`</svg>
|
|
9
|
+
`;return typeof a=="function"&&a(null,y),y},qi}var Jd;function cE(){if(Jd)return Cr;Jd=1;const t=HS(),e=sE(),r=iE(),n=aE();function o(s,i,a,c,l){const d=[].slice.call(arguments,1),u=d.length,f=typeof d[u-1]=="function";if(!f&&!t())throw new Error("Callback required as last argument");if(f){if(u<2)throw new Error("Too few arguments provided");u===2?(l=a,a=i,i=c=void 0):u===3&&(i.getContext&&typeof l>"u"?(l=c,c=void 0):(l=c,c=a,a=i,i=void 0))}else{if(u<1)throw new Error("Too few arguments provided");return u===1?(a=i,i=c=void 0):u===2&&!i.getContext&&(c=a,a=i,i=void 0),new Promise(function(h,g){try{const m=e.create(a,c);h(s(m,i,c))}catch(m){g(m)}})}try{const h=e.create(a,c);l(null,s(h,i,c))}catch(h){l(h)}}return Cr.create=e.create,Cr.toCanvas=o.bind(null,r.render),Cr.toDataURL=o.bind(null,r.renderToDataURL),Cr.toString=o.bind(null,function(s,i,a){return n.render(s,a)}),Cr}var lE=cE();const _o="w-full rounded-lg border border-border bg-background px-3 py-2.5 text-base text-foreground focus:outline-none focus:ring-2 focus:ring-ring sm:text-sm",Ke="appearance-none min-h-11 rounded-lg px-3 py-2 text-sm hover:bg-hover focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",Rr=`${Ke} bg-primary text-primary-foreground hover:opacity-90`;function dE(t){return t.serviceName||new URL(t.url).hostname}function Qd(t){return t.includes("service:*")?"完整权限":t.includes("session.input")?"可操作":t.includes("session.view")?"只读":t.includes("route.use")?"仅中转":"自定义权限"}function uE({profile:t,subjectId:e}){return p.jsxs("details",{className:"mt-2 text-xs text-muted-foreground",children:[p.jsx("summary",{className:"cursor-pointer leading-relaxed",children:[t?.model||t?.hostname||t?.system,t?.route,`ID ${e.slice(-8)}`].filter(Boolean).join(" · ")}),p.jsxs("dl",{className:"mt-2 space-y-2 rounded-lg bg-surface-2 p-3",children:[[["设备型号",t?.model],["主机名称",t?.hostname],["操作系统",t?.system],["客户端",t?.client],["打开方式",t?.mode],["处理器",t?.cpu],["架构",t?.arch],["最近连接路径",t?.route],["首次记录",t?.firstSeenAt?new Date(t.firstSeenAt).toLocaleString():void 0],["最近连接",t?.lastSeenAt?new Date(t.lastSeenAt).toLocaleString():void 0],["设备标识",e]].filter(([,r])=>r).map(([r,n])=>p.jsxs("div",{children:[p.jsx("dt",{children:r}),p.jsx("dd",{className:"mt-0.5 select-text break-all text-foreground",children:n})]},r)),p.jsx("p",{className:"leading-relaxed",children:t?"系统、硬件与路径由设备报告;连接时间由服务记录。":"此设备尚未报告详情,更新客户端并重新连接后可补齐。"})]})]})}function fE(){const t=getComputedStyle(document.documentElement),e=t.getPropertyValue("--background").trim(),r=t.getPropertyValue("--foreground").trim(),n=o=>{const s=o.replace("#","");return parseInt(s.slice(0,2),16)*.299+parseInt(s.slice(2,4),16)*.587+parseInt(s.slice(4,6),16)*.114};if(!e||!r)throw new Error("Theme unavailable");return n(e)<n(r)?{dark:e,light:r}:{dark:r,light:e}}function hE({onConnect:t,onClose:e,onConnectWithPassword:r,onAddService:n,onOpenService:o,currentIdentity:s,currentServiceName:i,currentServiceId:a,currentServiceOrigin:c,hasBackup:l=!1,paired:d=!1,initialInvite:u,sessions:f=[],grants:h=[],onCreateInvite:g,onRevoke:m,onRename:y,loading:w=!1,loadError:I,onRetry:v}){const[A,B]=F.useState(!1),[T,N]=F.useState(""),[k,x]=F.useState({}),[S,R]=F.useState(""),[P,b]=F.useState(""),[E,C]=F.useState(!1),[L,M]=F.useState(!1),[$,j]=F.useState(!d),[D,_]=F.useState(!0),[O,q]=F.useState("read"),[H,K]=F.useState("all"),[z,W]=F.useState([]),[X,G]=F.useState(!1),[Y,se]=F.useState(""),[Ne,Fe]=F.useState(""),[oe,ot]=F.useState(),[vr,Tt]=F.useState(""),[Xe,uo]=F.useState("services"),[xr,$s]=F.useState(),[Hs,Wc]=F.useState(""),[sn,Gc]=F.useState(!1),[Xc,an]=F.useState(),[ut,fo]=F.useState(!1),[Sr,Yc]=F.useState([]),qs=h.filter(U=>U.revokedAt===void 0&&(!U.expiresAt||U.expiresAt>Date.now())),Ks=h.filter(U=>!qs.includes(U)),cn=[...new Set(qs.map(U=>U.subjectId))].map(U=>{const V=qs.filter(de=>de.subjectId===U);return{subjectId:U,grants:V,name:U===s?"此设备":V.find(de=>de.label)?.label||"未命名设备"}}).sort((U,V)=>+(V.subjectId===s)-+(U.subjectId===s)),Er=!xr&&!sn&&d&&!$&&!L&&!u,Xp=()=>{$s(void 0),Gc(!1),j(!1),M(!1),ot(void 0),G(!1),R(""),b(""),an(void 0)},Zc=()=>{M(!0),j(!1),G(!1),R(""),b("")},Yp=U=>U.subjectId===s?"此设备":U.label||"未命名设备",zs=()=>{ut?fo(!1):e()},ln=F.useRef(null);F.useEffect(()=>{const U=document.activeElement;return ln.current?.focus(),()=>{U?.focus()}},[]),F.useEffect(()=>{let U=!1;if(Tt(""),oe)try{lE.toDataURL(oe.url,{width:220,margin:3,errorCorrectionLevel:"M",color:fE()}).then(V=>{U||Tt(V)}).catch(()=>{})}catch{}return()=>{U=!0}},[oe]);async function Vs(U){C(!0),R(""),b("");try{await t(U);const{url:V,targetPeerId:de,serviceName:Me,serviceOrigin:Ws}=U;await Et({id:de,url:V,targetPeerId:de,label:Me||new URL(V).host,serviceOrigin:Ws,entryServiceId:U.entryServiceId}),j(!1),b("已连接。")}catch(V){U.routeOnly&&V instanceof Ve?B(!0):R("暂时无法连接,请检查网络,或确认邀请是否仍然有效。")}finally{C(!1)}}async function Zp(U){if(U.preventDefault(),!g)return;R(""),b("");const V=z.filter(Me=>f.some(Ws=>Ws.sessionId===Me));if(O!=="full"&&H==="selected"&&!V.length){R("请选择至少一个 Session。");return}const de=Ne?new Date(Ne).getTime():void 0;if(de!==void 0&&(!Number.isFinite(de)||de<=Date.now())){R("授权到期时间必须晚于现在。");return}C(!0);try{const Me=await g({...l?{includeBackup:D}:{},scope:O==="full"||H==="all"?{kind:"service"}:{kind:"sessions",sessionIds:V},actions:O==="full"?["service:*"]:O==="write"?["session.view","session.input","session.resize"]:["session.view"],...Y.trim()?{label:Y.trim()}:{},...de===void 0?{}:{expiresAt:de}});ot(Me)}catch(Me){R(Me instanceof Error&&Me.message.startsWith("无法分享备用连接:")?"无法分享备用连接:需要入口管理员授权。你也可以关闭“包含备用连接”,生成直连邀请。":"暂时无法生成邀请,请确认当前设备有授权管理权限。")}finally{C(!1)}}async function Jp(){if(oe)try{await navigator.clipboard.writeText(oe.url),b("邀请链接已复制。")}catch{R("浏览器未允许复制,请长按下方链接复制。")}}const Qp=k.title||(xr?"设备名称":sn?Xe==="devices"?"授权详情":"连接详情":ut?"选择终端":L?"邀请设备":$&&d?"添加服务":d?"服务与设备":"连接 Termdock"),eg=!!k.back||!!xr||sn||ut||d&&($||L),tg=()=>{if(k.back){k.back();return}ut?fo(!1):Xp()},Jc=U=>U.every(V=>V.routeTargetServiceId)?`${new Set(U.map(V=>V.routeTargetServiceId)).size} 台服务`:U.some(V=>V.scope.kind==="service")?"全部终端":`${new Set(U.flatMap(V=>V.scope.kind==="sessions"?V.scope.sessionIds:[])).size} 个终端`;return ng.createPortal(p.jsx("div",{className:"fixed inset-0 z-modal-backdrop flex items-end justify-center bg-[var(--app-backdrop)] backdrop-blur-sm sm:items-center sm:p-6","data-sidebar-gesture-ignore":!0,onMouseDown:U=>{U.target===U.currentTarget&&!E&&zs()},children:p.jsxs("div",{ref:ln,tabIndex:-1,role:"dialog","aria-modal":"true","aria-labelledby":"federation-title",className:"z-modal-panel flex max-h-[calc(100dvh-env(safe-area-inset-top)-12px)] w-full max-w-lg flex-col overflow-hidden rounded-t-2xl border border-border bg-surface font-sans text-foreground shadow-xl outline-none sm:max-h-[min(720px,90dvh)] sm:rounded-2xl",onKeyDown:U=>{if(U.key==="Escape"&&!E&&(U.stopPropagation(),zs()),U.key!=="Tab")return;const V=ln.current?.querySelectorAll('button:not(:disabled), input:not(:disabled), textarea:not(:disabled), select:not(:disabled), [tabindex="0"], summary');if(!V?.length){U.preventDefault();return}const de=V[0],Me=V[V.length-1];U.shiftKey&&(document.activeElement===de||document.activeElement===ln.current)?(U.preventDefault(),Me.focus()):!U.shiftKey&&(document.activeElement===Me||document.activeElement===ln.current)&&(U.preventDefault(),de.focus())},children:[p.jsxs("header",{className:"shrink-0 border-b border-border px-5 pt-3",children:[p.jsxs("div",{className:"flex min-h-12 items-center gap-2 pb-2",children:[eg&&p.jsx("button",{type:"button",className:`${Ke} -ml-3 inline-flex w-11 items-center justify-center text-muted-foreground`,disabled:E,onClick:tg,"aria-label":ut?"取消选择终端":Xe==="devices"?"返回设备":"返回服务",children:p.jsx(Qh,{size:20})}),p.jsx("h2",{id:"federation-title",className:"min-w-0 flex-1 text-base font-semibold",children:Qp}),p.jsx("button",{type:"button",className:`${Ke} -mr-3 inline-flex w-11 items-center justify-center text-muted-foreground`,disabled:E,onClick:zs,"aria-label":"关闭",children:p.jsx(TS,{size:20})})]}),Er&&!k.title&&p.jsx("div",{className:"flex gap-6",role:"tablist","aria-label":"管理内容",children:[["services","服务"],["devices","设备"]].map(([U,V])=>p.jsxs("button",{type:"button",role:"tab","aria-selected":Xe===U,"aria-controls":`federation-${U}`,id:`federation-tab-${U}`,className:`min-h-11 border-b-2 px-1 text-sm transition ${Xe===U?"border-primary font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"}`,onClick:()=>{uo(U),G(!1),an(void 0),R(""),b("")},children:[V,U==="devices"&&cn.length>0&&p.jsx("span",{className:"ml-1.5 text-xs text-muted-foreground",children:cn.length})]},U))})]}),p.jsxs("div",{className:"min-h-0 overflow-y-auto overscroll-contain px-5 py-4 pb-[max(20px,env(safe-area-inset-bottom))]",children:[(Er&&Xe==="services"||$&&!L&&!u)&&p.jsx(jS,{renderRelayServices:(U,V)=>p.jsx(FS,{service:U,onBusyChange:V,onConnect:t,onConnectWithPassword:r}),renderRoutes:(U,V)=>p.jsx(MS,{service:U,onBusyChange:V}),hideHeader:!0,initiallyAdding:$,current:a?{id:a,targetPeerId:a,url:c||location.origin,label:i||"当前服务"}:void 0,onNavigation:x,onBusyChange:C,onInvite:g?Zc:void 0,onOpen:async U=>{if(o)return o(U);U.targetPeerId?await Vs({...U,targetPeerId:U.targetPeerId,serviceName:U.label}):n&&await n(U.url)},onAdd:async(U,V)=>{if(n)return n(U,V);await Vs(bs(U))}}),Er&&Xe==="devices"&&p.jsxs("section",{role:"tabpanel",id:"federation-devices","aria-labelledby":"federation-tab-devices",children:[p.jsx("p",{className:"mb-2 text-xs leading-relaxed text-muted-foreground",children:"可访问此服务的设备"}),w?p.jsxs("p",{role:"status",className:"flex items-center gap-2 py-5 text-sm text-muted-foreground",children:[p.jsx(He,{size:16,className:"animate-spin"}),"正在读取设备…"]}):p.jsxs("div",{className:"divide-y divide-border",children:[cn.map(U=>p.jsxs("div",{className:"py-3",children:[p.jsxs("div",{className:"flex items-center gap-3",children:[p.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-surface-2 text-muted-foreground",children:/iPhone|iPad|Android|手机|平板/i.test(U.grants.find(V=>V.label)?.label||(U.subjectId===s?navigator.userAgent:""))?p.jsx(rp,{size:19}):p.jsx(vS,{size:19})}),p.jsxs("div",{className:"min-w-0 flex-1",children:[p.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[p.jsx("p",{className:"truncate text-sm font-medium",children:U.name}),y&&(m||U.subjectId===s)&&p.jsx("button",{type:"button","aria-label":`重命名 ${U.name}`,className:"inline-flex h-9 w-9 shrink-0 appearance-none items-center justify-center rounded-lg bg-transparent text-muted-foreground hover:bg-surface-2",onClick:()=>{$s(U.subjectId),Wc(U.grants.find(V=>V.label)?.label||"")},children:p.jsx(SS,{size:14})})]}),U.subjectId===s&&U.grants.find(V=>V.label)?.label&&p.jsx("p",{className:"truncate text-xs text-muted-foreground",children:U.grants.find(V=>V.label)?.label}),p.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:[Qd(U.grants.flatMap(V=>V.actions))," · ",Jc(U.grants)]})]}),m&&U.subjectId!==s&&Xc!==U.subjectId&&p.jsx("button",{type:"button",className:`${Ke} -mr-2 text-xs text-muted-foreground hover:text-destructive`,disabled:E,"aria-label":`撤销 ${U.name} 的访问权限`,onClick:()=>an(U.subjectId),children:"撤销"})]}),p.jsx(uE,{profile:U.grants.find(V=>V.deviceProfile)?.deviceProfile,subjectId:U.subjectId}),Xc===U.subjectId&&p.jsxs("div",{className:"mt-3 rounded-lg border border-border bg-background p-3",children:[p.jsx("p",{className:"text-xs leading-relaxed",children:"撤销后,这台设备将断开连接,需重新邀请才能访问。"}),p.jsxs("div",{className:"mt-2 flex justify-end gap-2",children:[p.jsx("button",{type:"button",className:`${Ke} text-xs text-muted-foreground`,disabled:E,onClick:()=>an(void 0),children:"取消"}),p.jsx("button",{type:"button",className:`${Ke} text-xs text-destructive`,disabled:E,onClick:async()=>{C(!0),R("");try{for(const V of U.grants)await m?.(V.id);an(void 0),b("设备访问权限已撤销。")}catch{R("暂时无法撤销,请重试。")}finally{C(!1)}},children:"确认撤销"})]})]})]},U.subjectId)),cn.length===0&&!I&&p.jsxs("p",{className:"py-5 text-sm text-muted-foreground",children:["暂无设备授权。",g?"可通过邀请添加设备。":""]})]}),g&&p.jsxs("button",{type:"button",className:`${Ke} mt-4 inline-flex w-full items-center justify-center gap-2 border border-border text-sm`,disabled:E,onClick:Zc,children:[p.jsx(tp,{size:16}),"邀请设备"]}),Ks.length>0&&p.jsxs("details",{className:"mt-4 text-xs text-muted-foreground",children:[p.jsxs("summary",{className:"cursor-pointer py-2",children:["已失效的授权(",Ks.length,")"]}),p.jsx("div",{className:"mt-1 space-y-2 border-l border-border pl-3",children:Ks.map(U=>p.jsxs("p",{className:"flex gap-3",children:[p.jsx("span",{className:"min-w-0 flex-1 truncate",children:Yp(U)}),p.jsx("span",{className:"shrink-0",children:U.revokedAt!==void 0?"已撤销":"已到期"})]},U.id))})]})]}),xr&&p.jsxs("form",{className:"space-y-4",onSubmit:async U=>{U.preventDefault(),C(!0),R("");try{await y?.(xr,Hs.trim()),$s(void 0)}catch{R("暂时无法保存设备名称,请重试。")}finally{C(!1)}},children:[p.jsxs("label",{className:"block space-y-2 text-sm",children:[p.jsx("span",{children:"设备名称"}),p.jsx("input",{autoFocus:!0,className:_o,maxLength:80,required:!0,value:Hs,onChange:U=>Wc(U.target.value),placeholder:"例如:我的 iPhone、办公室电脑"})]}),p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"为设备起一个容易辨认的名字,会同步显示在此服务的设备列表中。"}),p.jsx("button",{type:"submit",className:`${Rr} w-full`,disabled:E||!Hs.trim(),children:E?"正在保存…":"保存名称"})]}),sn&&p.jsx("section",{className:"space-y-5",children:Xe==="devices"?cn.map(U=>p.jsxs("div",{className:"space-y-3",children:[p.jsx("h3",{className:"text-sm font-medium",children:U.name}),p.jsxs("dl",{className:"space-y-3 rounded-xl bg-surface-2 p-3 text-xs",children:[p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"访问权限"}),p.jsxs("dd",{className:"mt-1",children:[Qd(U.grants.flatMap(V=>V.actions))," · ",Jc(U.grants)]})]}),U.grants.map(V=>p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:V.routeTargetServiceId?"允许经此入口访问":V.scope.kind==="sessions"?"可访问终端":"有效期"}),p.jsx("dd",{className:"mt-1 leading-relaxed",children:V.routeTargetServiceId?V.routeTargetName||"指定服务":V.scope.kind==="sessions"?V.scope.sessionIds.map(de=>f.find(Me=>Me.sessionId===de)?.name||de).join("、"):V.expiresAt?new Date(V.expiresAt).toLocaleString():"保留至撤销"}),V.routeTargetServiceId&&m&&p.jsx("button",{type:"button",className:`${Ke} mt-1 -ml-3 text-xs text-destructive`,disabled:E,onClick:async()=>{C(!0),R("");try{await m(V.id)}catch{R("暂时无法撤销,请重试。")}finally{C(!1)}},children:"撤销此中转权限"})]},V.id)),p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"设备标识"}),p.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed text-muted-foreground select-text",children:U.subjectId})]})]})]},U.subjectId)):p.jsxs("dl",{className:"space-y-4 text-xs",children:[p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"当前服务"}),p.jsx("dd",{className:"mt-1 text-sm",children:i||"当前服务"})]}),p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"服务标识"}),p.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed select-text",children:a})]}),p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"本设备标识"}),p.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed select-text",children:s})]})]})}),u&&!L&&p.jsxs("section",{className:"space-y-5 py-1",children:[p.jsxs("div",{className:"flex items-center gap-3",children:[p.jsx("span",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-surface-2 text-muted-foreground",children:p.jsx(js,{size:22})}),p.jsxs("div",{className:"min-w-0",children:[p.jsx("p",{className:"text-xs text-muted-foreground",children:"你受邀连接"}),p.jsx("p",{className:"mt-1 break-words text-base font-medium",children:dE(u)})]})]}),u.routeOnly&&p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"此邀请提供备用连接,目标服务仍会验证你的访问权限。"}),A?p.jsxs("form",{className:"space-y-3",onSubmit:async U=>{U.preventDefault(),C(!0),R("");try{await r?.(u,T)}catch(V){R(V instanceof Error?V.message:"暂时无法登录,请重试。")}finally{N(""),C(!1)}},children:[p.jsxs("label",{className:"block space-y-2 text-sm",children:[p.jsx("span",{children:"目标服务密码"}),p.jsx("input",{className:_o,type:"password",required:!0,autoFocus:!0,autoComplete:"current-password",value:T,onChange:U=>N(U.target.value)})]}),p.jsx("button",{className:`${Rr} w-full`,disabled:E||!T,children:E?"正在登录…":"登录并连接"})]}):p.jsx("button",{type:"button",className:`${Rr} w-full text-sm`,disabled:E,onClick:()=>{Vs(u)},children:E?"正在连接…":"接受邀请"})]}),L&&!ut&&p.jsx("section",{children:oe?p.jsxs("div",{className:"space-y-4 text-center",children:[p.jsx("p",{className:"text-sm font-medium",children:"用另一台设备扫描二维码"}),vr?p.jsx("img",{src:vr,width:220,height:220,className:"mx-auto max-w-full rounded-xl",alt:"设备邀请二维码"}):p.jsx("div",{className:"mx-auto flex h-48 w-48 items-center justify-center",children:p.jsx(He,{size:22,className:"animate-spin text-muted-foreground"})}),p.jsxs("p",{className:"text-xs leading-relaxed text-muted-foreground",children:["仅限一台设备使用 · ",new Date(oe.expiresAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," 前有效"]}),p.jsxs("button",{type:"button",className:`${Rr} inline-flex w-full items-center justify-center gap-2 text-sm`,onClick:()=>{Jp()},children:[p.jsx(ep,{size:16}),"复制邀请链接"]}),p.jsxs("details",{className:"text-left text-xs text-muted-foreground",children:[p.jsx("summary",{className:"cursor-pointer py-2",children:"查看链接"}),p.jsx("p",{className:"mt-2 select-all break-all",children:oe.url})]})]}):p.jsxs("form",{className:"space-y-5",onSubmit:Zp,children:[p.jsxs("fieldset",{children:[p.jsx("legend",{className:"mb-2 text-sm font-medium",children:"访问权限"}),p.jsx("div",{className:"space-y-2",children:[["read","仅查看","查看终端画面,不可输入命令"],["write","可操作","查看终端画面,并输入命令"],["full","完整访问","包括文件、设置和权限管理"]].map(([U,V,de])=>p.jsxs("label",{className:`flex cursor-pointer items-center gap-3 rounded-xl border px-3 py-2.5 transition focus-within:ring-2 focus-within:ring-ring ${O===U?"border-primary bg-primary/10":"border-border hover:bg-surface-2"}`,children:[p.jsx("input",{type:"radio",name:"federation-permission",value:U,checked:O===U,onChange:()=>q(U),className:"sr-only"}),p.jsx("span",{"aria-hidden":"true",className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border ${O===U?"border-primary bg-primary text-primary-foreground":"border-border bg-background"}`,children:O===U&&p.jsx(Pc,{size:13,strokeWidth:3})}),p.jsxs("span",{className:"min-w-0",children:[p.jsx("span",{className:"block text-sm font-medium text-foreground",children:V}),p.jsx("span",{className:"mt-0.5 block text-xs leading-relaxed text-muted-foreground",children:de})]})]},U))})]}),O!=="full"&&p.jsxs("fieldset",{children:[p.jsx("legend",{className:"mb-2 text-sm font-medium",children:"可访问的终端"}),p.jsxs("div",{className:"flex gap-2",children:[p.jsx("button",{type:"button","aria-pressed":H==="all",className:`${Ke} flex-1 appearance-none border text-sm ${H==="all"?"border-primary bg-primary/10 text-foreground":"border-border text-muted-foreground"}`,onClick:()=>K("all"),children:"全部终端"}),p.jsxs("button",{type:"button","aria-pressed":H==="selected",className:`${Ke} inline-flex flex-1 appearance-none items-center justify-center gap-1 border text-sm ${H==="selected"?"border-primary bg-primary/10 text-foreground":"border-border text-muted-foreground"}`,onClick:()=>{Yc(z),fo(!0)},children:[H==="selected"?`已选 ${z.length} 个`:"选择终端",p.jsx(fr,{size:14})]})]}),H==="all"&&p.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"包括之后新建的终端。"})]}),O==="write"&&p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"终端命令可读写该系统用户有权访问的文件。"}),O==="full"&&p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"拥有此服务的全部当前及未来权限。仅授予你完全信任的设备。"}),l&&p.jsxs("label",{className:"flex items-start gap-3 text-sm",children:[p.jsx("input",{type:"checkbox",className:"mt-0.5 h-4 w-4 accent-primary",checked:D,onChange:U=>_(U.target.checked)}),p.jsxs("span",{children:["让新设备也能使用备用连接",p.jsx("span",{className:"mt-1 block text-xs leading-relaxed text-muted-foreground",children:"需要入口管理员授权;关闭后生成直接连接邀请。"})]})]}),p.jsxs("div",{children:[p.jsxs("button",{className:`${Rr} inline-flex w-full items-center justify-center gap-2 text-sm`,type:"submit",disabled:E||w,children:[E&&p.jsx(He,{size:16,className:"animate-spin"}),E?"正在生成…":"生成邀请"]}),p.jsxs("p",{className:"mt-2 text-center text-xs leading-relaxed text-muted-foreground",children:["链接 10 分钟内有效 · 访问权限",Ne?"按设定时间到期":"保留至撤销"]})]})]})}),ut&&p.jsxs("section",{children:[p.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"仅允许访问勾选的终端。"}),p.jsxs("div",{className:"space-y-1",children:[f.map(U=>p.jsxs("label",{className:"flex min-h-12 cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-sm hover:bg-surface-2",children:[p.jsx("input",{type:"checkbox",className:"h-4 w-4 accent-primary",checked:Sr.includes(U.sessionId),onChange:V=>Yc(V.target.checked?[...Sr,U.sessionId]:Sr.filter(de=>de!==U.sessionId))}),p.jsx("span",{className:"min-w-0 break-words",children:U.name})]},U.sessionId)),!f.length&&p.jsx("p",{className:"py-4 text-sm text-muted-foreground",children:"当前没有可共享的终端。"})]})]}),I&&p.jsxs("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:[I,v&&p.jsx("button",{type:"button",className:`${Ke} ml-1 text-sm underline`,onClick:v,children:"重试"})]}),!k.title&&!$&&!xr&&!sn&&!ut&&!oe&&p.jsxs("div",{className:"mt-4 border-t border-border pt-2",children:[p.jsxs("button",{type:"button",className:`${Ke} -ml-3 inline-flex items-center gap-1 bg-transparent text-xs text-muted-foreground`,"aria-expanded":Er?void 0:X,onClick:()=>Er?Gc(!0):G(U=>!U),children:[L?"有效期与备注":$?"手动连接":Xe==="devices"?"授权详情":"连接详情",Er?p.jsx(fr,{size:14}):p.jsx(hS,{size:13,className:X?"rotate-180":""})]}),X&&p.jsxs("section",{className:"space-y-3 pb-1 pt-2",children:[L&&p.jsxs(p.Fragment,{children:[p.jsxs("label",{className:"block space-y-1 text-sm",children:[p.jsx("span",{children:"设备备注(可选)"}),p.jsx("input",{className:_o,value:Y,onChange:U=>se(U.target.value),placeholder:"例如:工作电脑"})]}),p.jsxs("label",{className:"block space-y-1 text-sm",children:[p.jsx("span",{children:"授权到期时间"}),p.jsx("input",{type:"datetime-local",className:_o,value:Ne,onChange:U=>Fe(U.target.value)})]})]}),!L&&s&&p.jsxs("p",{className:"break-all text-xs leading-relaxed text-muted-foreground",children:["本设备身份:",s]})]})]}),S&&p.jsx("p",{role:"alert",className:"mt-3 text-sm text-destructive",children:S}),P&&p.jsx("p",{role:"status",className:"mt-3 text-sm text-muted-foreground",children:P})]}),ut&&p.jsx("footer",{className:"shrink-0 border-t border-border px-5 pt-3 pb-[max(16px,env(safe-area-inset-bottom))]",children:p.jsxs("button",{type:"button",className:`${Rr} w-full text-sm`,disabled:!Sr.length,onClick:()=>{W(Sr),K("selected"),fo(!1)},children:["使用所选终端(",Sr.length,")"]})})]})}),document.body)}const pE={background:"#1C1B1A",foreground:"#CECDC3",cursor:"#CECDC3",cursorAccent:"#1C1B1A",selectionBackground:"#403E3C",selectionForeground:"#CECDC3",selectionInactiveBackground:"#403E3C50",black:"#6F6E69",red:"#AF3029",green:"#66800B",yellow:"#AD8301",blue:"#205EA6",magenta:"#A02F6F",cyan:"#24837B",white:"#CECDC3",brightBlack:"#6F6E69",brightRed:"#D14D41",brightGreen:"#879A39",brightYellow:"#D0A215",brightBlue:"#4385BE",brightMagenta:"#CE5D97",brightCyan:"#3AA99F",brightWhite:"#FFFCF0"},gE={background:"#FFFCF0",foreground:"#100F0F",cursor:"#100F0F",cursorAccent:"#FFFCF0",selectionBackground:"#CECDC3",selectionForeground:"#100F0F",selectionInactiveBackground:"#CECDC350",black:"#100F0F",red:"#AF3029",green:"#66800B",yellow:"#AD8301",blue:"#205EA6",magenta:"#A02F6F",cyan:"#24837B",white:"#575653",brightBlack:"#6F6E69",brightRed:"#D14D41",brightGreen:"#879A39",brightYellow:"#D0A215",brightBlue:"#4385BE",brightMagenta:"#CE5D97",brightCyan:"#3AA99F",brightWhite:"#100F0F"};function mE(t){return t==="light"?gE:pE}const Na="termdock:open-services";function wE(){window.dispatchEvent(new Event(Na))}function yE({client:t,initialSessionId:e}){const[r,n]=F.useState([]),[o,s]=F.useState(),i=F.useRef();F.useEffect(()=>{if(!e||i.current===e)return;const f=r.find(h=>h.sessionId===e||h.sourceSessionId===e);f&&(i.current=e,s(f))},[r,e]);const[a,c]=F.useState("正在读取已授权 Session"),[l,d]=F.useState(()=>document.documentElement.dataset.theme==="light"?"light":"dark");F.useEffect(()=>{const f=new MutationObserver(()=>d(document.documentElement.dataset.theme==="light"?"light":"dark"));return f.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>f.disconnect()},[]);const u=F.useRef(null);return F.useEffect(()=>{let f=!0;const h=async()=>{try{const m=await t.request({type:"session-list"});if(f){const y=m.items;n(y),s(w=>{if(!w)return c(y.length?"选择一个已授权 Session":"暂无已授权的在线 Session"),w;const I=y.find(v=>v.sessionId===w.sessionId);if(!I){c("Session 已移除或授权失效");return}return I.canWrite===w.canWrite&&I.canResize===w.canResize?w:I})}}catch{f&&c("目标不可达或授权已失效")}};h();const g=setInterval(()=>{h()},15e3);return()=>{f=!1,clearInterval(g)}},[t]),F.useEffect(()=>{if(!o||!u.current)return;let f=!1,h=0,g;const m=new og({theme:mE(l),cursorBlink:o.canWrite,disableStdin:!o.canWrite,convertEol:!1}),y=new sg;m.loadAddon(y),m.open(u.current),o.canResize&&y.fit(),c("正在建立加密终端连接");const w=t.openSocket(`/api/terminal/${encodeURIComponent(o.sessionId)}/ws?flow=2`),I=()=>{f||!o.canResize||(y.fit(),w.readyState===1&&w.send(JSON.stringify({type:"resize",cols:m.cols,rows:m.rows})))};w.onopen=()=>c(o.canWrite?"读写":"只读"),w.onmessage=T=>{try{const N=JSON.parse(T.data);if(f)return;if(N.type==="connected"){g=typeof N.streamEpoch=="string"?N.streamEpoch:void 0,h=Number.isSafeInteger(N.replayLastSeq)?N.replayLastSeq:0,!o.canResize&&Number.isSafeInteger(N.cols)&&Number.isSafeInteger(N.rows)&&N.cols>0&&N.rows>0&&m.resize(N.cols,N.rows);const k=Array.isArray(N.replayChunks)?N.replayChunks.filter(x=>typeof x=="string").join(""):"";m.write((N.replayOutOfWindow?"\x1Bc":"")+k,I)}else N.type==="data"&&typeof N.data=="string"?m.write(N.data,()=>{f||(Number.isSafeInteger(N.seq)&&(h=Math.max(h,N.seq)),w.readyState===1&&Number.isSafeInteger(N.flowSeq)&&w.send(JSON.stringify({type:"output-ack",flowSeq:N.flowSeq,since:h,epoch:g})))}):N.type==="pty-size"&&!o.canResize&&Number.isSafeInteger(N.cols)&&Number.isSafeInteger(N.rows)&&N.cols>0&&N.rows>0?m.resize(N.cols,N.rows):N.type==="error"&&c("目标拒绝终端操作,请检查有效授权")}catch{c("终端数据无效"),w.close()}},w.onclose=()=>c("连接已断开;画面已过期,重新选择 Session 可重连"),w.onerror=()=>c("目标不可达或授权不足");const v=m.onData(T=>{o.canWrite&&w.readyState===1&&w.send(JSON.stringify({type:"input",data:T}))}),A=setInterval(()=>{w.readyState===1&&w.send(JSON.stringify({type:"ping"}))},2e4),B=new ResizeObserver(I);return B.observe(u.current),()=>{f=!0,clearInterval(A),B.disconnect(),v.dispose(),w.onclose=null,w.onerror=null,w.close(),m.dispose()}},[t,o,l]),p.jsxs("div",{className:"flex h-dvh flex-col bg-background text-foreground",children:[p.jsxs("div",{className:"flex items-center gap-3 border-b border-border p-3 text-sm",children:[p.jsxs("span",{className:"min-w-0 flex-1",children:["已授权 Session · ",a]}),p.jsx("button",{type:"button",onClick:wE,className:"min-h-11 shrink-0 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2",children:"服务与设备"})]}),p.jsx("div",{className:"flex flex-wrap gap-2 p-2",children:r.map(f=>p.jsxs("button",{className:"rounded border border-border px-3 py-2 text-sm hover:bg-surface-2",onClick:()=>s({...f}),children:[f.name," · ",f.canWrite?"读写":"只读"]},`${t.targetPeerId}:${f.sessionId}`))}),p.jsx("div",{ref:u,className:"min-h-0 flex-1 overflow-auto p-2"})]})}function La(t){if(!t.startsWith("remote:"))return null;const e=t.slice(7).split(":");if(e.length!==2)return null;try{const r=decodeURIComponent(e[0]),n=decodeURIComponent(e[1]);return!n||new URL(r).origin!==r||!/^https?:/.test(r)?null:{origin:r,id:n}}catch{return null}}class bE{constructor(e){this.source=e,this.peers={state:e.peerProtocol==="unsupported"?"unsupported":e.readPeers?"loading":"unavailable",checkedAt:null}}source;local=null;remote=[];peers;localInFlight=null;peerInFlight=null;listeners=new Set;disposed=!1;peerTimer;lastPeerAttempt=-1/0;generation=0;localHealthy=!1;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}snapshot(){if(!this.local)return null;const e=new Map;for(const r of this.local.groups)for(const n of r.remoteSessions??[]){const o=La(n.sessionId);o&&o.origin!==this.source.origin&&o.origin!==this.source.peerOrigin&&e.set(n.sessionId,{...n,status:"offline",serviceConnected:!1})}for(const r of this.remote)e.set(r.sessionId,r);for(const r of this.local.sessions)e.set(r.sessionId,r);return{groups:this.local.groups,sessions:[...e.values()],peers:this.peers,capabilities:this.local.capabilities}}emit(){if(this.disposed||!this.localHealthy)return;const e=this.snapshot();if(e)for(const r of this.listeners)r(e)}load(){if(this.disposed)return Promise.reject(new Error("协作连接已切换,请重新加载"));if(this.localInFlight)return this.localInFlight;this.refreshPeers();const e=this.generation,r=Promise.resolve().then(()=>this.source.readLocal()).then(n=>{if(this.disposed)throw new Error("协作连接已切换,请重新加载");if(e!==this.generation)return this.load();if(!Array.isArray(n.groups)||!Array.isArray(n.sessions))throw new Error("协作会话响应无效,请更新服务后重试");return this.local=n,this.localHealthy=!0,this.emit(),this.snapshot()}).catch(n=>{throw e===this.generation&&(this.localHealthy=!1),n}).finally(()=>{this.localInFlight===r&&(this.localInFlight=null)});return this.localInFlight=r,r}invalidate(){this.generation++,this.localInFlight=null,this.localHealthy=!1}refreshPeers(e=!1){if(this.disposed||!this.source.readPeers||this.peerInFlight||!e&&Date.now()-this.lastPeerAttempt<2e3)return;this.lastPeerAttempt=Date.now(),this.peers.checkedAt||(this.peers={state:"loading",checkedAt:null}),this.emit();const r=this.source.readPeers;this.peerInFlight=Promise.race([Promise.resolve().then(()=>r()),new Promise((n,o)=>{this.peerTimer=setTimeout(()=>o(new Error("跨服务会话加载超时,请检查客户端协作连接")),2e4)})]).then(n=>{if(this.disposed)return;const o=n.origin===this.source.origin||!!this.source.peerOrigin&&n.origin===this.source.peerOrigin;if(!Array.isArray(n.sessions)||this.source.peerProtocol==="v2"&&(n.protocolVersion!==2||!o)||n.origin&&!o||n.protocolVersion!==void 0&&n.protocolVersion!==2)throw new Error("客户端协作响应与当前服务不匹配,请更新客户端后重试");this.remote=n.sessions.filter(i=>{const a=La(i.sessionId);return a&&a.origin!==this.source.origin&&a.origin!==this.source.peerOrigin});const s=n.services?.filter(i=>i.origin!==this.source.origin&&i.origin!==this.source.peerOrigin);this.peers={state:s?.some(i=>!i.connected)?"partial":"ready",checkedAt:Date.now(),services:s}}).catch(n=>{this.disposed||(this.remote=this.remote.map(o=>({...o,status:"offline",serviceConnected:!1})),this.peers={state:"error",checkedAt:Date.now(),error:n instanceof Error?n.message:"跨服务会话加载失败"})}).finally(()=>{clearTimeout(this.peerTimer),this.peerInFlight=null,this.emit()})}dispose(){this.disposed=!0,clearTimeout(this.peerTimer),this.listeners.clear(),this.local=null,this.remote=[]}}async function vE(t,e){const r=navigator.serviceWorker?.controller;if(!r)return null;const n=new MessageChannel;return new Promise(o=>{const s=a=>{clearTimeout(i),n.port1.close(),o(a)},i=setTimeout(()=>s(null),5e3);n.port1.onmessage=a=>{try{const c=new URL(a.data.url,location.origin);s(c.origin===location.origin&&/^\/__termdock-download\/[a-f0-9-]{36}$/.test(c.pathname)?c.href:null)}catch{s(null)}},n.port1.onmessageerror=()=>s(null);try{r.postMessage({type:"termdock:prepare-download",blob:t,filename:e},[n.port2])}catch{s(null)}})}const xE=4*1024*1024,SE=256*1024,EE=1440*6e4;let Vr=0,eu;function Lc(){return typeof indexedDB>"u"?Promise.resolve(null):eu??=new Promise(t=>{const e=indexedDB.open(`termdock-terminal-snapshots:${_r}`,1);e.onupgradeneeded=()=>e.result.createObjectStore("snapshots",{keyPath:"id"}),e.onerror=()=>t(null),e.onblocked=()=>t(null),e.onsuccess=()=>{e.result.onversionchange=()=>{e.result.close(),eu=void 0},t(e.result)}})}function Ba(t){return!!t&&t.version===1&&typeof t.epoch=="string"&&t.epoch.length>0&&Number.isSafeInteger(t.cols)&&t.cols>0&&Number.isSafeInteger(t.rows)&&t.rows>0&&Number.isSafeInteger(t.seq)&&t.seq>0&&typeof t.data=="string"&&t.data.length*2<=SE&&t.savedAt<=Date.now()&&Date.now()-t.savedAt<EE}async function Wk(t){const e=Vr;try{const r=await Lc();return!r||e!==Vr?null:await new Promise(n=>{const o=r.transaction("snapshots").objectStore("snapshots").get(t);o.onerror=()=>n(null),o.onsuccess=()=>n(e===Vr&&Ba(o.result)?o.result:null)})}catch{return null}}async function Gk(t){const e=Vr;if(Ba(t))try{const r=await Lc();if(!r||e!==Vr)return;await new Promise(n=>{const o=r.transaction("snapshots","readwrite"),s=o.objectStore("snapshots");s.put(t);const i=s.getAll();i.onsuccess=()=>{let a=0,c=0;for(const l of i.result.sort((d,u)=>u.savedAt-d.savedAt))a+=l.data.length*2,(++c>32||a>xE||!Ba(l))&&s.delete(l.id)},o.oncomplete=()=>n(),o.onerror=o.onabort=()=>n()})}catch{}}async function dp(){Vr+=1;try{(await Lc())?.transaction("snapshots","readwrite").objectStore("snapshots").clear()}catch{}}typeof window<"u"&&window.addEventListener("auth:unauthorized",()=>{dp()});const pt=new Map,Ut=new Map,AE=32*1024*1024,kE=8*1024*1024,IE=48;let Ln=0,_a=0;function Bc(){_a+=1,pt.clear(),Ln=0;for(const t of Ut.values())t.controller.abort();Ut.clear()}typeof window<"u"&&window.addEventListener("auth:unauthorized",Bc);function CE(t,e){const r=pt.get(t);if(r&&(Ln-=r.blob.size,pt.delete(t)),!(e.blob.size>kE))for(pt.set(t,e),Ln+=e.blob.size;pt.size>IE||Ln>AE;){const n=pt.keys().next().value;Ln-=pt.get(n).blob.size,pt.delete(n)}}async function up(t,e={}){const r=new URL(t,typeof location<"u"?location.origin:"http://localhost");if(!/^\/api\/terminal\/fs\/(read|blob)$/.test(r.pathname))return fetch(t,{signal:e.signal});if(e.signal?.aborted)throw e.signal.reason??new DOMException("Aborted","AbortError");r.searchParams.delete("requestSlotId"),r.searchParams.delete("action"),r.searchParams.sort();const n=r.href;let o=Ut.get(n);if(!o){const i=new AbortController,a=_a,c=pt.get(n),l=new Headers,d=c?.headers.get("ETag");d&&l.set("If-None-Match",d);const u=setTimeout(()=>i.abort(new DOMException("File preview timed out. Please retry.","TimeoutError")),e.timeoutMs??15e3),f={controller:i,readers:0,promise:Promise.resolve(null)};f.promise=(async()=>{const h=await fetch(n,{headers:l,signal:i.signal,cache:"no-cache"});let g;return h.status===304&&c?g=c:g={blob:await h.blob(),headers:new Headers(h.headers),status:h.status},_a===a&&!i.signal.aborted&&g.status===200&&g.headers.has("ETag")&&CE(n,g),h.status===401&&Bc(),g})().finally(()=>{clearTimeout(u),Ut.get(n)===f&&Ut.delete(n)}),o=f,Ut.set(n,o)}const s=o;return s.readers+=1,new Promise((i,a)=>{let c=!1;const l=()=>c?!1:(c=!0,e.signal?.removeEventListener("abort",d),s.readers-=1,s.readers===0&&Ut.get(n)===s&&(Ut.delete(n),s.controller.abort()),!0),d=()=>{l()&&a(e.signal?.reason??new DOMException("Aborted","AbortError"))};if(e.signal?.addEventListener("abort",d,{once:!0}),e.signal?.aborted){d();return}s.promise.then(u=>{l()&&i(new Response(u.blob,{status:u.status,headers:u.headers}))},u=>{l()&&a(u)})})}const _c="auth:unauthorized";let Br=null;class pe extends Error{constructor(e,r,n){super(e),this.status=r,this.code=n,this.name="TerminalApiError"}status;code}async function RE(){const t=await fetch("/api/terminal/update");if(!t.ok)throw new pe("Failed to load update state",t.status);return t.json()}async function TE(){const t=await Z(),e=await fetch("/api/terminal/update/check",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new pe("Failed to check for updates",e.status);return e.json()}async function PE(){const t=await Z(),e=await fetch("/api/terminal/update/restart",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!e.ok){const r=await e.json().catch(()=>({error:"Failed to restart Termdock"}));throw new pe(r.error||"Failed to restart Termdock",e.status)}return e.json()}async function NE(){const t=await fetch("/api/terminal/quota");if(!t.ok)throw new pe("Failed to fetch quota",t.status);return t.json()}async function LE(){const t=await Z(),e=await fetch("/api/terminal/quota/refresh",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new pe("Failed to refresh quota",e.status);return e.json()}const yr=8e3,fp=6e4,BE=32e3,hp=125e3,dt=1e4,Wr=45e3,pp=8e3,gp=8e3,mp=15e3,_E=1e4,en=5e3;let DE=0;const Ho=[];let Ki=!1;function Ft(t,e={}){if(typeof window>"u")return;const r=JSON.stringify({level:t==="error"||t==="timeout_or_abort"||t==="response_body_timeout"||t==="response_body_parse_error"?"warn":"info",message:`DIFF_API ${t}`,data:{seq:++DE,ts:Date.now(),...e}});Ho.push(r),OE()}async function OE(){if(!Ki){Ki=!0;try{for(;Ho.length>0;){const t=Ho[0];try{await fetch("/api/client-log",{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:!0}),Ho.shift()}catch{break}}}finally{Ki=!1}}}function Dc(t,e,r){const n=new AbortController;let o=setTimeout(()=>{n.abort(new DOMException(r,"TimeoutError"))},e);const s=()=>n.abort(t?.reason);return t&&(t.aborted?s():t.addEventListener("abort",s,{once:!0})),{signal:n.signal,cleanup:()=>{o&&(clearTimeout(o),o=null),t?.removeEventListener("abort",s)}}}async function he(t,e,r,n){const{signal:o,cleanup:s}=Dc(e?.signal??void 0,r,n);try{return await fetch(t,{...e,signal:o})}catch(i){throw i instanceof DOMException&&i.name==="TimeoutError"?new Error(n):i}finally{s()}}async function wp(t,e,r){let n=null;const o=new Promise((s,i)=>{n=setTimeout(()=>i(new Error(r)),e)});try{return await Promise.race([t.text(),o])}finally{n&&clearTimeout(n)}}async function tn(t,e,r){const n=await wp(t,e,r);return JSON.parse(n)}if(typeof window<"u"&&!window.__termdockFetchPatched){window.__termdockFetchPatched=!0;const t=window.fetch.bind(window);window.fetch=async(...e)=>{const r=await t(...e);if(r.status===401){Br=null,qc();try{window.dispatchEvent(new CustomEvent(_c))}catch{}}return r}}async function Z(){if(Br)return Br;const t=await he("/api/csrf-token",void 0,pp,"CSRF token request timed out");if(!t.ok)throw new Error("Failed to get CSRF token");const e=await tn(t,en,"CSRF token response timed out");if(!e.csrfToken)throw new Error("Invalid CSRF token response");return Br=e.csrfToken,Br}function Oc(){qc(),Br=null}const FE=2e4,tu=8e3,ME=1500,yp=250,ge=new Map,Fc=new Map,jE=24,UE=40,$E=40;function HE(t){return t.retryState.retryCount>=2||t.pendingInputs.length>=$E?"congested":t.retryState.retryCount>=1||t.pendingInputs.length>=8?"degraded":"good"}function ru(t){if(t.pendingInputs.length===0||t.ws.readyState!==WebSocket.OPEN)return;const e=t.pendingInputs.splice(0);for(const r of e)try{t.ws.send(JSON.stringify({type:"input",data:r}))}catch{}}function bp(t){if(t.ws.readyState!==WebSocket.OPEN)return;const e=HE(t);if(e==="good"){ru(t);return}if(t.inputFlushTimer)return;const r=e==="congested"?UE:jE;t.inputFlushTimer=setTimeout(()=>{t.inputFlushTimer=null,ru(t)},r)}const $n=new Map;function qE(t,e,r,n){const o=$n.get(t);o&&($n.delete(t),e?o.resolve({success:!0,layout:r}):o.reject(new Error(n||"Tmux action failed")))}const Pr=new Map;function KE(t,e,r,n){const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/terminal/${t}/ws`,i=new URLSearchParams({flow:"2",transport:"tmux-client",active:Fc.get(t)===!1?"0":"1"});e>0&&i.set("since",String(e)),r&&i.set("epoch",r);const a=n??Pr.get(t);return a&&(i.set("cols",String(a.cols)),i.set("rows",String(a.rows))),`${s}?${i}`}const Da=new Map,Oa=new Map;function zE(t,e,r){Da.set(t,e),Oa.set(t,r)}function VE(t){const e=ge.get(t);return e?.streamEpoch&&e.appliedSeq===e.lastSeq&&e.lastSeq>0?{seq:e.lastSeq,epoch:e.streamEpoch}:null}async function WE(t){const e=await Z(),r=await fetch("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({cols:t.cols||80,rows:t.rows||24,mode:t.mode||"shell",tmuxSessionName:t.tmuxSessionName,cwd:t.cwd,termType:t.termType})});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to create terminal"}));throw new Error(n.error||"Failed to create terminal session")}return r.json()}function GE(t,e,r,n={}){const{maxRetries:o=10,initialRetryDelay:s=1e3,maxRetryDelay:i=2e4,connectionTimeout:a=15e3}=n,c={maxRetries:o,initialDelayMs:s,maxDelayMs:i,connectionTimeoutMs:a,retryCount:0,retryTimeout:null,connectionTimeoutId:null,isClosed:!1,isSuspended:!1};let l=null,d=Da.get(t)??0,u=Oa.get(t);Oa.delete(t),Da.delete(t);const f=[];let h=!1,g=null;const m=new WeakSet,y=()=>{c.retryTimeout&&(clearTimeout(c.retryTimeout),c.retryTimeout=null),c.connectionTimeoutId&&(clearTimeout(c.connectionTimeoutId),c.connectionTimeoutId=null),g&&(clearTimeout(g),g=null)},w=T=>{T.wakeProbe&&(clearTimeout(T.wakeProbe.timer),T.wakeProbe=void 0),T.heartbeatTimer&&(clearInterval(T.heartbeatTimer),T.heartbeatTimer=null),T.pongTimer&&(clearTimeout(T.pongTimer),T.pongTimer=null),T.inputFlushTimer&&(clearTimeout(T.inputFlushTimer),T.inputFlushTimer=null)},I=T=>{w(T),T.heartbeatTimer=setInterval(()=>{if(T.ws.readyState===WebSocket.OPEN){try{T.ws.send(JSON.stringify({type:"ping"}))}catch{}T.pongTimer&&clearTimeout(T.pongTimer),T.pongTimer=setTimeout(()=>{if(Date.now()-T.lastInboundAt>=tu){h=!0,w(T);try{T.ws.close()}catch{}B(new Error("WebSocket heartbeat timeout"),!1)}},tu)}},FE)},v=()=>{if(c.isClosed=!0,y(),l){w(l),ge.delete(t);try{l.ws.close()}catch{}l=null}},A=()=>{if(c.isClosed)return;if(l){m.add(l.ws),w(l);try{l.ws.close()}catch{}}const T=KE(t,d,u,n.getDimensions?.()),N=Hx(T);h=!1,c.connectionTimeoutId=setTimeout(()=>{N.readyState!==WebSocket.OPEN&&(h=!0,N.close(),B(new Error("WebSocket connection timeout"),!1))},a);const k={ws:N,onEvent:e,onError:r,reconnectNow:()=>{if(!c.isClosed&&(c.isSuspended=!1,!g)){if(y(),l){m.add(l.ws),w(l);try{l.ws.close()}catch{}}e({type:"reconnecting",attempt:Math.min(c.retryCount+1,o),maxAttempts:o}),c.retryCount=Math.min(c.retryCount+1,o),h=!0,g=setTimeout(()=>{g=null,h=!1,A()},0)}},suspendReconnect:()=>{c.isClosed||(c.isSuspended=!0,c.retryTimeout&&(clearTimeout(c.retryTimeout),c.retryTimeout=null))},retryState:c,lastSeq:d,pendingInputs:f,inputFlushTimer:null,heartbeatTimer:null,pongTimer:null,lastInboundAt:Date.now(),inboundSequence:0};N.onopen=()=>{c.isClosed||m.has(N)||h||(y(),c.retryCount=0,k.lastInboundAt=Date.now(),k.inboundSequence+=1,I(k),bp(k))},N.onmessage=x=>{if(!(c.isClosed||m.has(N)||h)){k.lastInboundAt=Date.now(),k.inboundSequence+=1;try{const S=JSON.parse(x.data);if(k.wakeProbe&&ge.get(t)===k){const P=k.wakeProbe;k.wakeProbe=void 0,clearTimeout(P.timer);for(const b of P.listeners)b()}if(S.type==="pong"){k.pongTimer&&(clearTimeout(k.pongTimer),k.pongTimer=null);return}if(S.type==="tmux-result"&&S.reqId){qE(S.reqId,S.success!==!1,S.layout,S.error);return}if(S.type==="tmux-layout"&&S.layout){e({type:"tmux-layout",layout:S.layout});return}if(S.type==="tmux-screen-sync"&&Array.isArray(S.chunks)){e({type:"tmux-screen-sync",chunks:S.chunks.filter(P=>typeof P=="string"),cols:typeof S.cols=="number"?S.cols:void 0,rows:typeof S.rows=="number"?S.rows:void 0,generation:typeof S.generation=="number"?S.generation:void 0});return}if(S.type==="active-program"){e({type:"active-program",activeProgram:S.activeProgram,activeProgramRaw:S.activeProgramRaw,activeProgramSource:S.activeProgramSource});return}if(S.type==="cwd"){e({type:"cwd",cwd:S.cwd});return}if(S.type==="agent-status"){e({type:"agent-status",agentStatus:S.agentStatus??null,agentIndicator:S.agentIndicator??null,agentStatusDetail:S.agentStatusDetail??null,agent:S.agent??null,agentMessage:S.agentMessage??null,agentNativeSessionId:S.agentNativeSessionId??null,agentResumeRecovered:S.agentResumeRecovered===!0,agentRich:S.agentRich===!0,agentActivity:typeof S.agentActivity=="number"?S.agentActivity:0,agentCwd:S.agentCwd??null,reviewed:typeof S.reviewed=="boolean"?S.reviewed:null});return}if(S.type==="git-status"){e({type:"git-status",gitStatus:S.gitStatus??null});return}if(S.type==="quota-status"&&Array.isArray(S.providers)){window.dispatchEvent(new CustomEvent("termdock:quota-update",{detail:S.providers}));return}if(S.type==="focus-mode"){e({type:"focus-mode",focusTrackingRequested:S.focusTrackingRequested===!0});return}if(S.type==="resize-ack"){e({type:"resize-ack",seq:typeof S.seq=="number"?S.seq:void 0,cols:typeof S.cols=="number"?S.cols:void 0,rows:typeof S.rows=="number"?S.rows:void 0,ok:S.ok!==!1,error:typeof S.error=="string"?S.error:void 0,screenSyncPending:S.screenSyncPending===!0,screenSyncGeneration:typeof S.screenSyncGeneration=="number"?S.screenSyncGeneration:void 0});return}if(S.type==="pty-size"){e({type:"pty-size",cols:typeof S.cols=="number"?S.cols:void 0,rows:typeof S.rows=="number"?S.rows:void 0,source:typeof S.source=="string"?S.source:void 0});return}if(S.type==="shell-title"){e({type:"shell-title",title:typeof S.title=="string"?S.title:""});return}if(S.type==="prompt-state"){e({type:"prompt-state",state:S.state==="running"?"running":"idle",exitCode:typeof S.exitCode=="number"?S.exitCode:void 0});return}const R=S;if(R.type==="connected"){k.appliedSeq=void 0,u=R.streamEpoch,k.streamEpoch=u,k.outputProtocol=R.outputProtocol,typeof R.replayLastSeq=="number"&&R.replayLastSeq>=0&&(d=R.replayLastSeq,k.lastSeq=d),e(R),vp(t,Fc.get(t)??!0);return}if(R.type==="exit"){v(),e(R);return}if(R.type==="data"){if(k.appliedSeq=void 0,typeof R.seq=="number"&&R.seq<=d)return;typeof R.flowSeq=="number"&&(k.flowSeq=R.flowSeq)}e(R),R.type==="data"&&typeof R.seq=="number"&&Number.isFinite(R.seq)&&R.seq>d&&(d=R.seq,k.lastSeq=d)}catch(S){r?.(S,!1)}}},N.onerror=()=>{c.isClosed||m.has(N)||h||(y(),w(k),h||(h=!0,B(new Error("WebSocket connection error"),!1)))},N.onclose=x=>{if(!(c.isClosed||m.has(N)||h)){if(y(),w(k),h=!0,x.code===4001){console.warn("[Terminal] WS 4001: Session not found on server",{code:x.code,reason:x.reason,stack:new Error().stack}),B(new Error("Session not found on server"),!0);return}if(x.code===4003||x.code===4401){try{window.dispatchEvent(new CustomEvent(_c))}catch{}B(new Error("Authentication required"),!0);return}B(new Error("WebSocket connection closed"),!1)}},l=k,ge.set(t,l)},B=(T,N)=>{if(!c.isClosed)if(N)r?.(T,!0),v();else{c.retryCount=Math.min(c.retryCount+1,Math.max(1,o));const k=Math.min(s*Math.pow(2,c.retryCount-1),i);if(e({type:"reconnecting",attempt:c.retryCount,maxAttempts:o}),c.isSuspended)return;c.retryTimeout=setTimeout(()=>{c.isClosed||A()},k)}};return A(),v}async function XE(t,e){const r=ge.get(t);if(r){if(r.ws.readyState===WebSocket.OPEN){r.pendingInputs.push(e),bp(r);return}if(r.ws.readyState===WebSocket.CONNECTING){r.pendingInputs.push(e);return}}const n=await Z(),o=await fetch(`/api/terminal/${t}/input`,{method:"POST",headers:{"Content-Type":"text/plain","X-XSRF-TOKEN":n},body:e});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to send input"}));throw new Error(s.error||"Failed to send terminal input")}}function YE(t,e,r={}){const n=ge.get(t);if(!n)return!1;if(n.retryState.isSuspended=!1,n.ws.readyState!==WebSocket.OPEN)return n.reconnectNow(),!0;const o=r.visible?yp:ME,s=Date.now()+o,i=n.wakeProbe,a=i?.listeners??new Set;if(e&&a.add(e),i&&i.deadline<=s)return!0;i&&clearTimeout(i.timer);const c=setTimeout(()=>{ge.get(t)!==n||n.retryState.isClosed||(n.wakeProbe=void 0,n.reconnectNow())},o);if(n.wakeProbe={timer:c,listeners:a,deadline:s},i)return!0;try{n.ws.send(JSON.stringify({type:"ping"}))}catch{clearTimeout(c),n.wakeProbe=void 0,n.reconnectNow()}return!0}function ZE(t){const e=ge.get(t);return e?(e.reconnectNow(),!0):!1}function JE(){for(const t of ge.values())t.suspendReconnect()}function QE(t,e,r){const n=ge.get(t);if(!(!n||n.ws.readyState!==WebSocket.OPEN))try{n.ws.send(JSON.stringify({type:"focus",focused:e,reason:r}))}catch{}}function vp(t,e){Fc.set(t,e);const r=ge.get(t);!r||r.ws.readyState!==WebSocket.OPEN||r.outputProtocol!==2||r.ws.send(JSON.stringify({type:"output-subscription",active:e,since:r.lastSeq,epoch:r.streamEpoch}))}function e1(t){const e=ge.get(t);!e||e.ws.readyState!==WebSocket.OPEN||e.outputProtocol!==2||(e.appliedSeq=e.lastSeq,!(!e.flowSeq||e.flowSeq===e.acknowledgedFlowSeq)&&(e.acknowledgedFlowSeq=e.flowSeq,e.ws.send(JSON.stringify({type:"output-ack",flowSeq:e.flowSeq,since:e.appliedSeq,epoch:e.streamEpoch}))))}function t1(t,e,r){const n=ge.get(t);if(!(!n||n.ws.readyState!==WebSocket.OPEN))try{n.ws.send(JSON.stringify({type:"viewing",viewing:e,reason:r}))}catch{}}function r1(t){const e=ge.get(t);if(!(!e||e.ws.readyState!==WebSocket.OPEN))try{e.ws.send(JSON.stringify({type:"agent-review-ack"}))}catch{}}function n1(t,e,r){const n=ge.get(t);if(!(!n||n.ws.readyState!==WebSocket.OPEN))try{n.ws.send(JSON.stringify({type:"flow-control",paused:e,reason:r}))}catch{}}async function o1(t,e,r,n){Number.isFinite(e)&&Number.isFinite(r)&&e>=1&&r>=1&&(Pr.delete(t),Pr.set(t,{cols:Math.floor(e),rows:Math.floor(r)}),Pr.size>256&&Pr.delete(Pr.keys().next().value));const o=ge.get(t);if(o&&o.ws.readyState===WebSocket.OPEN)try{o.ws.send(JSON.stringify({type:"resize",cols:e,rows:r,seq:n}));return}catch{}const s=await Z(),i=await fetch(`/api/terminal/${t}/resize`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":s},body:JSON.stringify({cols:e,rows:r,seq:n})});if(!i.ok){const c=await i.json().catch(()=>({error:"Failed to resize terminal"}));throw new Error(c.error||"Failed to resize terminal")}const a=await i.json().catch(()=>({success:!0}));if(a?.success===!1||a?.ok===!1)throw new Error(a?.error||"Failed to resize terminal")}async function s1(t,e){const r=ge.get(t);if(r&&r.ws.readyState===WebSocket.OPEN)return e.action==="scroll"?(r.ws.send(JSON.stringify({type:"tmux",...e})),{success:!0}):new Promise((s,i)=>{const a=Math.random().toString(36).substring(7);$n.set(a,{resolve:s,reject:i}),r.ws.send(JSON.stringify({type:"tmux",reqId:a,...e})),setTimeout(()=>{$n.has(a)&&($n.delete(a),i(new Error("Tmux action timed out")))},3e4)});const n=await Z(),o=await fetch(`/api/terminal/${t}/tmux`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify(e)});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to execute tmux action"}));throw new Error(s.error||"Failed to execute tmux action")}return o.json()}async function i1(t){const e=ge.get(t);if(e){e.retryState.isClosed=!0;try{e.ws.close()}catch{}ge.delete(t)}const r=await Z(),n=await fetch(`/api/terminal/${t}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":r}});if(n.status!==404&&!n.ok){const o=await n.json().catch(()=>({error:"Failed to close terminal"}));throw new Error(o.error||"Failed to close terminal")}}async function a1(t,e){const r=ge.get(t);if(r){r.retryState.isClosed=!0;try{r.ws.close()}catch{}ge.delete(t)}const n=await Z(),o=await fetch(`/api/terminal/${t}/restart`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify({...e.cwd?{cwd:e.cwd}:{},cols:e.cols??80,rows:e.rows??24,mode:e.mode,tmuxSessionName:e.tmuxSessionName})});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to restart terminal"}));throw new Error(s.error||"Failed to restart terminal session")}return o.json()}async function c1(t){const e=await he(`/api/terminal/${t}/health`,{method:"GET"},gp,"Terminal health check timed out");if(!e.ok){if(e.status===404)return{healthy:!1,sessionId:t};const r=await tn(e,en,"Terminal health error response timed out").catch(()=>({error:"Failed to check terminal health"}));throw new Error(r.error||"Failed to check terminal health")}return tn(e,en,"Terminal health response timed out")}async function l1(t){const e=await Z(),r=await he("/api/terminal/force-kill",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)},_E,"Terminal force-kill request timed out");if(!r.ok){const n=await tn(r,en,"Terminal force-kill error response timed out").catch(()=>({error:"Failed to force kill terminal"}));throw new Error(n.error||"Failed to force kill terminal")}}async function d1(){const t=await fetch("/api/terminal/tmux/sessions",{method:"GET"});if(!t.ok){const r=await t.json().catch(()=>({error:"Failed to list tmux sessions"}));throw new Error(r.error||"Failed to list tmux sessions")}const e=await t.json();return Array.isArray(e.sessions)?e.sessions:[]}async function u1(){const t=await fetch("/api/terminal/tmux/status",{method:"GET"});if(!t.ok){const e=await t.json().catch(()=>({error:"Failed to get tmux status"}));throw new Error(e.error||"Failed to get tmux status")}return t.json()}async function f1(t){const e=t.trim();if(!e)throw new Error("tmux session name is required");const r=await Z(),n=await fetch(`/api/terminal/tmux/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":r}});if(!n.ok){const s=await n.json().catch(()=>({error:"Failed to kill tmux session"}));throw new Error(s.error||"Failed to kill tmux session")}const o=await n.json();return{cleanedSessions:Array.isArray(o.cleanedSessions)?o.cleanedSessions:[],alreadyGone:!!o.alreadyGone}}async function h1(){const t=await Z(),e=await fetch("/api/terminal/tmux/recovery/restore-all",{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await e.json().catch(()=>({}));if(!e.ok)throw new pe(r.error||"Failed to restore tmux Agent sessions",e.status);return r}async function p1(){const t=await Z(),e=await fetch("/api/terminal/tmux/recovery",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new pe("Failed to dismiss tmux recovery",e.status)}const Do=new Map;function g1(t){return JSON.stringify({preferredFrontendSessionId:t.preferredFrontendSessionId??null,mode:t.mode??null,tmuxSessionName:t.tmuxSessionName??null,cwd:t.cwd??null,termType:t.termType??null,createIfEmpty:t.createIfEmpty===!0,requireExisting:t.requireExisting===!0})}async function m1(){const t=await fetch("/api/terminal/session-inventory",{method:"GET"});if(!t.ok){const e=await t.json().catch(()=>({error:"Failed to load session inventory"}));throw new Error(e.error||"Failed to load session inventory")}return t.json()}async function w1(t){const e=g1(t),r=Do.get(e);if(r)return r;const n=await Z(),o=he("/api/terminal/session-inventory/open",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify(t)},mp,"Terminal session open request timed out").then(async s=>{if(!s.ok){const i=await tn(s,en,"Terminal session open error response timed out").catch(()=>({error:"Failed to open session"}));throw new pe(i.error||"Failed to open session",s.status,typeof i.code=="string"?i.code:void 0)}return tn(s,en,"Terminal session open response timed out")}).finally(()=>{Do.get(e)===o&&Do.delete(e)});return Do.set(e,o),o}async function y1(t,e){const r=await Z(),n=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(e)});if(!n.ok){const o=await n.json().catch(()=>({error:"Failed to update session"}));throw new Error(o.error||"Failed to update session")}return n.json()}async function b1(t){const e=await Z(),r=await fetch("/api/terminal/session-inventory/reorder",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({sessionIds:t})});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to reorder sessions"}));throw new Error(n.error||"Failed to reorder sessions")}return r.json()}async function v1(t){const e=await Z(),r=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to remove session"}));throw new Error(n.error||"Failed to remove session")}}async function x1(){const t=await Z(),e=await fetch("/api/terminal/session-inventory/sessions",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok){const r=await e.json().catch(()=>({error:"Failed to clear sessions"}));throw new Error(r.error||"Failed to clear sessions")}}async function S1(){const t=await fetch("/api/terminal/toolbar-presets",{method:"GET"});if(!t.ok){const e=await t.json().catch(()=>({error:"Failed to load toolbar presets"}));throw new Error(e.error||"Failed to load toolbar presets")}return t.json()}async function E1(t){const e=await Z(),r=await fetch("/api/terminal/toolbar-presets",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to save toolbar presets"})),o=new Error(n.error||"Failed to save toolbar presets");throw o.current=n.current,o.code=n.code,o}return r.json()}let Sn=null,Bn=null;const xp=1500;function Hn(){return Bn&&Date.now()-Bn.readAt<xp?Promise.resolve(Bn.value):Sn||(Sn=(async()=>{const t=await fetch("/api/terminal/settings",{method:"GET"});if(!t.ok){const r=await t.json().catch(()=>({error:"Failed to load settings"}));throw new Error(r.error||"Failed to load settings")}const e=await t.json();return Bn={value:e,readAt:Date.now()},e})().finally(()=>{Sn=null}),Sn)}async function $t(t){const e=await Z(),r=await fetch("/api/terminal/settings",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!r.ok){const o=await r.json().catch(()=>({error:"Failed to update settings"}));throw new Error(o.error||"Failed to update settings")}const n=await r.json();return Bn={value:n,readAt:Date.now()},n}async function A1(t=!1){const e=await fetch(`/api/terminal/auto-title/catalog${t?"?refresh=1":""}`);if(!e.ok)throw new Error("Failed to discover title models");const r=await e.json();return Array.isArray(r?.namers)?r.namers:[]}let En=null,_n=null;function k1(){return _n&&Date.now()-_n.readAt<xp?Promise.resolve(_n.value):En||(En=(async()=>{const t=await fetch("/api/terminal/context-draft",{method:"GET"});if(!t.ok){const r=await t.json().catch(()=>({error:"Failed to load context draft"}));throw new Error(r.error||"Failed to load context draft")}const e=await t.json();return _n={value:e,readAt:Date.now()},e})().finally(()=>{En=null}),En)}async function I1(t,e){const r=await Z(),n=await fetch("/api/terminal/context-draft",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify({text:t,origin:e})});if(!n.ok){const s=await n.json().catch(()=>({error:"Failed to update context draft"}));throw new Error(s.error||"Failed to update context draft")}const o=await n.json();return _n={value:o,readAt:Date.now()},o}async function Sp(t){const e=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:t})});if(e.ok)return Oc(),{ok:!0};const r=await e.json().catch(()=>null);return e.status===429?{ok:!1,rateLimited:!0,retryAfterMs:typeof r?.retryAfterMs=="number"?r.retryAfterMs:void 0,error:r?.error||"Too many failed attempts. Please wait and try again."}:{ok:!1,error:r?.error||"Login failed"}}async function C1(){Bc(),dp();const t=await Z();await fetch("/api/auth/logout",{method:"POST",headers:{"X-XSRF-TOKEN":t}}),Oc()}async function R1(){const t=await fetch("/api/terminal/agent-launchers");if(!t.ok)throw new Error("Failed to detect agent launchers");const e=await t.json();return Array.isArray(e?.agents)?e.agents:[]}async function T1(){const t=await fetch("/api/terminal/agent-hooks");if(!t.ok)throw new Error("Failed to get agent hooks");const e=await t.json();return Array.isArray(e?.agents)?e.agents:[]}async function P1(t){const e=await Z(),r=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(t)}/install`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Error(n.error||"Failed to install agent hooks");return{summary:n.summary??"Installed",devMode:n.devMode===!0}}async function N1(t){const e=await Z(),r=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(t)}/uninstall`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Error(n.error||"Failed to uninstall agent hooks");return n.summary??"Removed"}class Mc extends Error{constructor(e,r,n){super(e),this.code=r,this.migration=n,this.name="AgentPluginManifestError"}code;migration}async function L1(){const t=await fetch("/api/terminal/agent-plugins");if(!t.ok)throw new Error("Failed to get agent plugins");return await t.json()}async function B1(t){const e=await Z(),r=await fetch("/api/terminal/agent-plugins",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Mc(n.error||"Failed to create agent plugin",n.code,n.migration);return n}async function _1(t){const e=await Z(),r=await fetch("/api/terminal/agent-plugins/install",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({source:t})}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Mc(n.error||"Failed to install agent plugin",n.code,n.migration);return n}async function D1(t){const e=await Z(),r=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}/check-update`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Error(n.error||"Failed to check plugin updates");return n}async function O1(t){const e=await Z(),r=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}/update`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Error(n.error||"Failed to update plugin");return n}async function F1(t){const e=await Z(),r=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}/doctor`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Error(n.error||"Failed to diagnose plugin");return n}async function M1(t){const e=await Z(),r=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(n.error||"Failed to delete agent plugin")}}async function j1(t){const e=await Z(),r=await fetch(`/api/terminal/${encodeURIComponent(t)}/agent-resume`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new pe(n.error||"Failed to resume agent session",r.status,typeof n.code=="string"?n.code:void 0);return{command:n.command??""}}async function U1(){const t=await fetch("/api/terminal/agent-resume-history",{method:"GET"});if(!t.ok)throw new Error("Failed to load Agent resume history");const e=await t.json().catch(()=>({entries:[]}));return Array.isArray(e.entries)?e.entries:[]}async function $1(t){const e=await Z(),r=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(t)}/prepare`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new pe(n.error||"Failed to prepare Agent session resume",r.status,typeof n.code=="string"?n.code:void 0);return n}async function H1(t){const e=await Z(),r=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!r.ok&&r.status!==404)throw new Error("Failed to remove Agent resume history")}async function q1(t){const e=await Z(),r=await fetch("/api/terminal/program-rules",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to update program rules"}));throw new Error(n.error||"Failed to update program rules")}return r.json()}async function K1(){const t=await Z(),e=await fetch("/api/terminal/program-rules",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Error("Failed to reset program rules");return e.json()}async function z1(){const t=await fetch("/api/terminal/program-detection");if(!t.ok)throw new Error("Failed to get program detection config");return t.json()}async function V1(t){const e=await Z(),r=await fetch("/api/terminal/program-detection",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!r.ok)throw new Error("Failed to save program detection config");return r.json()}async function W1(){const t=await Z(),e=await fetch("/api/terminal/program-detection",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Error("Failed to reset program detection config");return e.json()}const G1={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".bmp":"image/bmp",".ico":"image/x-icon",".svg":"image/svg+xml",".heic":"image/heic",".heif":"image/heif"};function Us(t){const e=t.lastIndexOf(".");return e<0?null:G1[t.slice(e).toLowerCase()]??null}function X1(t){return Us(t)!==null}function Ep(t){const e=Us(t);return e==="image/heic"||e==="image/heif"}const Y1={".mp4":"video/mp4",".m4v":"video/x-m4v",".webm":"video/webm",".mov":"video/quicktime",".ogv":"video/ogg",".mpeg":"video/mpeg",".mpg":"video/mpeg"};function Ap(t){const e=t.lastIndexOf(".");return e<0?null:Y1[t.slice(e).toLowerCase()]??null}function Z1(t){return Ap(t)!==null}function J1(t){return`/api/terminal/fs/video?path=${encodeURIComponent(t)}&action=view_file`}const kp=[".stl",".glb",".gltf"];function jc(t){const e=t.lastIndexOf(".");if(e<0)return null;const r=t.slice(e).toLowerCase();return kp.includes(r)?r:null}function Q1(t){return jc(t)!==null}function Uc(t){const e=t.toLowerCase();return e.endsWith(".kicad_sch")?".kicad_sch":e.endsWith(".kicad_pcb")?".kicad_pcb":null}function e2(t){return Uc(t)!==null}function t2(t){return Uc(t)===".kicad_pcb"?"pcb-front":"schematic"}const Ip=[".html",".htm"];function r2(t){const e=t.lastIndexOf(".");if(e<0)return!1;const r=t.slice(e).toLowerCase();return Ip.includes(r)}function n2(t){return`/api/terminal/fs/preview/${t.split(/[\\/]+/).filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}const o2={".stl":"model/stl",".glb":"model/gltf-binary",".gltf":"model/gltf+json"};async function s2(t,e,r,n="list_directory",o,s="name"){const i=new URLSearchParams({path:t});r&&i.set("showHidden","true"),s!=="name"&&i.set("sort",s),i.set("action",n),o&&i.set("requestSlotId",o);const a=await he(`/api/terminal/fs/list?${i}`,{signal:e},yr,"Directory listing took too long. The folder may be on slow storage or blocked by another process.");if(!a.ok){const c=await a.json().catch(()=>({error:"Failed to list directory"}));throw new Error(c.error||"Failed to list directory")}return a.json()}async function i2(t,e,r,n,o,s="name",i,a={}){const c=new URLSearchParams({path:t,query:e,stream:"true"});o&&c.set("showHidden","true"),s==="content"&&c.set("mode","content"),i&&c.set("requestSlotId",i);for(const g of a.excludePatterns??[])c.append("exclude",g);a.caseSensitive&&c.set("caseSensitive","true"),a.wholeWord&&c.set("wholeWord","true"),a.regex&&c.set("regex","true");const l=await fetch(`/api/terminal/fs/search?${c}`,{signal:n});if(!l.ok||!l.body){const g=await l.json().catch(()=>({error:"Failed to search files"}));throw new Error(g.error||"Failed to search files")}const d=l.body.getReader(),u=new TextDecoder;let f="";const h=g=>{if(!g.trim())return;const m=JSON.parse(g);if(m.type==="meta")r({path:m.path,query:m.query,engine:m.engine,mode:m.mode,limited:m.limited});else if(m.type==="batch")r({entries:m.entries??[]});else if(m.type==="content-batch")r({contentEntries:m.contentEntries??[]});else{if(m.type==="error")throw new Error(m.message||"Search failed");m.type==="done"&&r({total:m.total,truncated:m.truncated,limited:m.limited,engine:m.engine,mode:m.mode,done:!0})}};for(;;){const{value:g,done:m}=await d.read();if(m)break;f+=u.decode(g,{stream:!0});let y=f.indexOf(`
|
|
10
10
|
`);for(;y>=0;)h(f.slice(0,y)),f=f.slice(y+1),y=f.indexOf(`
|
|
11
|
-
`)}f+=u.decode(),h(f)}async function
|
|
11
|
+
`)}f+=u.decode(),h(f)}async function a2(t,e,r){const n=new URLSearchParams;for(const d of t)n.append("root",d);const o=await fetch(`/api/terminal/fs/watch?${n}`,{signal:r});if(!o.ok||!o.body){const d=await o.json().catch(()=>({error:"Failed to watch files"}));throw new Error(d.error||"Failed to watch files")}const s=o.body.getReader(),i=new TextDecoder;let a="",c=null;const l=d=>{if(!d.trim())return;const u=JSON.parse(d);if(u.type==="events"&&u.events?.length){e(u.events);const f=u.events.find(h=>h.type==="rescan-required"&&h.reason!=="event-storm"&&h.reason!=="reconnected"&&h.reason!=="directory-rescan"&&h.reason!=="polling-fallback");f?.reason&&(c=f.reason)}};for(;;){const{value:d,done:u}=await s.read();if(u)break;a+=i.decode(d,{stream:!0});let f=a.indexOf(`
|
|
12
12
|
`);for(;f>=0;)l(a.slice(0,f)),a=a.slice(f+1),f=a.indexOf(`
|
|
13
|
-
`)}if(a+=i.decode(),l(a),c)throw new Error(c)}function s2(t){if(!t)return;const e=new URLSearchParams({requestSlotId:t,action:"cancel_io_slot"});fetch(`/api/terminal/fs/cancel-slot?${e}`,{method:"GET",keepalive:!0}).catch(()=>{})}async function i2(t,e,r="view_file",n){const o=new URLSearchParams({path:t,action:r});n&&o.set("requestSlotId",n);const s=await cp(`/api/terminal/fs/read?${o}`,{signal:e,timeoutMs:yr});if(!s.ok){const i=await s.json().catch(()=>({error:"Failed to read file"}));throw new Error(i.error||"Failed to read file")}return s.json()}async function a2(t,e,r="HEAD",n,o="ref"){const s=new URLSearchParams({path:t,cwd:e,ref:r,action:"git_blob"});o==="index"&&s.set("source","index");const i=await he(`/api/terminal/fs/git-blob?${s}`,{signal:n},yr,"Git blob preview took too long.");if(!i.ok){const a=await i.json().catch(()=>({error:"Failed to read git blob"}));throw new Error(a.error||"Failed to read git blob")}return i.json()}async function c2(t,e,r="view_file",n){const o=new URLSearchParams({path:t,action:r});n&&o.set("requestSlotId",n);const s=await cp(`/api/terminal/fs/blob?${o}`,{signal:e,timeoutMs:vp(t)?PE:yr});if(!s.ok){const c=await s.json().catch(()=>({error:"Failed to load image preview"}));throw new Error(c.error||"Failed to load image preview")}const i=await s.blob(),a=s.headers.get("Content-Length");return{blob:i,path:t,size:a?Number(a):null,modified:s.headers.get("Last-Modified"),mimeType:s.headers.get("Content-Type")||i.type||Fs(t)||"application/octet-stream"}}function Mc(t,e){try{const r=decodeURIComponent(t.headers.get("X-Termdock-Source-Path")||"");return r.startsWith("/")&&!/[\r\n\0]/.test(r)?r:e}catch{return e}}async function l2(t,e,r,n="view_file",o){const s=new URLSearchParams({path:t,view:e,action:n});o&&s.set("requestSlotId",o);const i="KiCad preview rendering or transfer timed out.",a=Lc(r,dp,i);try{const c=await fetch(`/api/terminal/fs/eda-preview?${s}`,{signal:a.signal});if(!c.ok){const u=await c.json().catch(()=>({error:"Failed to render KiCad preview"}));throw new Error(u.error||"Failed to render KiCad preview")}const l=await c.blob(),d=c.headers.get("Content-Length");return{blob:l,path:Mc(c,t),view:e,size:d?Number(d):null,modified:c.headers.get("Last-Modified"),mimeType:c.headers.get("Content-Type")||l.type||"image/svg+xml"}}catch(c){throw a.signal.aborted&&!r?.aborted?new Error(i):c}finally{a.cleanup()}}async function d2(t,e,r,n,o){const s=new URLSearchParams({path:t,view:e,x:String(r),y:String(n)}),i=await he(`/api/terminal/fs/eda-inspect?${s}`,{signal:o},8e3,"KiCad point inspection timed out.");if(!i.ok){const a=await i.json().catch(()=>({error:"Failed to inspect KiCad point"}));throw new Error(a.error||"Failed to inspect KiCad point")}return i.json()}async function u2(t,e,r="view_file",n){const o=new URLSearchParams({path:t,action:r});n&&o.set("requestSlotId",n);const i=Lc(e,lp,"3D model transfer timed out. Please retry.");try{const a=await fetch(`/api/terminal/fs/download?${o}`,{signal:i.signal});if(!a.ok){const u=await a.json().catch(()=>({error:"Failed to load 3D model preview"}));throw new Error(u.error||"Failed to load 3D model preview")}const c=await a.blob(),l=a.headers.get("Content-Length"),d=Oc(t)??"";return{blob:c,path:Mc(a,t),size:l?Number(l):null,modified:a.headers.get("Last-Modified"),ext:d,mimeType:a.headers.get("Content-Type")||c.type||t2[d]||"application/octet-stream"}}finally{i.cleanup()}}function eu(){return typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}async function f2(t){const e=`/api/terminal/fs/download?path=${encodeURIComponent(t)}`,r=await fetch(e);if(!r.ok){const c=await r.json().catch(()=>({error:"Failed to download file"}));throw new Error(c.error||"Failed to download file")}const n=await r.blob(),o=Ap(r.headers.get("Content-Disposition")||"")??t.split("/").pop()?.split("\\").pop()??"download",s=window.showSaveFilePicker;if(typeof s=="function")try{const l=await(await s({suggestedName:o})).createWritable();await l.write(n),await l.close();return}catch(c){if(c instanceof DOMException&&c.name==="AbortError")return}if(eu()){const c=new File([n],o,{type:n.type||"application/octet-stream"});if(typeof navigator<"u"&&"share"in navigator&&(!navigator.canShare||navigator.canShare({files:[c]})))try{await navigator.share({files:[c]});return}catch(d){if(d instanceof DOMException&&d.name==="AbortError")return}}if(eu()){const c=await wE(n,o);if(c){window.location.assign(c);return}}const i=URL.createObjectURL(n),a=document.createElement("a");a.href=i,a.download=o,a.rel="noopener",a.style.display="none",document.body.appendChild(a),a.click(),setTimeout(()=>{URL.revokeObjectURL(i),a.remove()},4e3)}async function h2(t){const e=await Z(),r=new URLSearchParams({path:t,confirm:"true"}),n=await he(`/api/terminal/fs/file?${r}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}},yr,"File deletion took too long.");if(!n.ok){const o=await n.json().catch(()=>({error:"Failed to delete file"}));throw new Error(o.error||"Failed to delete file")}}async function p2(t,e,r,n){const o=new FormData;for(const u of e)o.append("files",u);const s=`/api/terminal/fs/upload?dir=${encodeURIComponent(t)}`,i=await Z();n?.(0);const a={"X-XSRF-TOKEN":i};let c=o;if(n){const u=new Response(o);a["Content-Type"]=u.headers.get("Content-Type"),c=await u.blob()}const l=await he(s,{method:"POST",headers:a,body:c,signal:r,onUploadProgress:c instanceof Blob&&n?u=>n(Math.min(99,Math.floor(u/Math.max(1,c.size)*100))):void 0},12e4,"Upload timed out");if(!l.ok){const u=await l.json().catch(()=>({error:"Upload failed"}));throw new Error(u.error||"Upload failed")}const d=await l.json();return n?.(100),d}async function g2(t){const e=await he("/api/terminal/fs/local-open-availability",{signal:t},yr,"Local file browser availability check timed out");return e.ok?e.json():{available:!1}}async function m2(t){const e=await Z(),r=await he("/api/terminal/fs/open-in-file-browser",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({path:t})},yr,"Opening file browser timed out");if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to open file browser"}));throw new Error(n.error||"Failed to open file browser")}}function Ap(t){if(!t)return null;const e=/(?:^|;)\s*filename\*=\s*(?:UTF-8'')?([^;]+)/i.exec(t);if(e){const n=e[1].trim().replace(/^"|"$/g,"");try{return decodeURIComponent(n)}catch{return n}}const r=/(?:^|;)\s*filename=\s*(?:"([^"]*)"|([^;]+))/i.exec(t);return r?(r[1]??r[2]).trim():null}function w2(t,e){e?.algorithm&&e.algorithm!=="default"&&t.set("algorithm",e.algorithm),e?.whitespace&&e.whitespace!=="default"&&t.set("whitespace",e.whitespace),e?.context==="all"?t.set("context","all"):typeof e?.context=="number"&&t.set("context",String(e.context))}async function y2(t,e,r,n,o=t?"view_diff":"view_all_changes",s,i,a,c){const l=new URLSearchParams;t&&l.set("path",t),r&&l.set("cwd",r),l.set("action",o),w2(l,c),s&&l.set("traceId",s),i&&l.set("interactionId",i),a&&l.set("requestSlotId",a);const d=!!t&&o==="view_diff",u=typeof performance<"u"?performance.now():Date.now();Ot("request_start",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:r,action:o,cached:!!e,algorithm:c?.algorithm??"default",whitespace:c?.whitespace??"default",context:c?.context===void 0?"default":String(c.context),timeoutMs:d?Wr:dt});const f=await he(`/api/terminal/fs/diff?${l}`,{signal:n},d?Wr:dt,d?"Git diff is still running for this file. It may be blocked by repository IO or another Git process.":"Git diff took too long. The repository may be busy, on slow storage, or locked by another Git process.").catch(m=>{throw Ot("timeout_or_abort",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:r,action:o,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u),message:m instanceof Error?m.message:String(m),signalAborted:!!n?.aborted,signalReason:n?.aborted?String(n.reason??""):void 0}),m});if(Ot("response_headers",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:r,action:o,status:f.status,ok:f.ok,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u)}),!f.ok){const m=await f.json().catch(()=>({error:"Failed to get diff"}));throw Ot("error",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:r,action:o,status:f.status,message:m.error||"Failed to get diff"}),new Error(m.error||"Failed to get diff")}Ot("response_body_start",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:r,action:o,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u),contentLength:f.headers.get("Content-Length")});let h;try{h=await pp(f,d?Wr:dt,d?"Git diff response body is still loading for this file.":"Git diff response body took too long.")}catch(m){throw Ot("response_body_timeout",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:r,action:o,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u),message:m instanceof Error?m.message:String(m),signalAborted:!!n?.aborted,signalReason:n?.aborted?String(n.reason??""):void 0}),m}let g;try{g=JSON.parse(h)}catch(m){throw Ot("response_body_parse_error",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:r,action:o,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u),bytes:h.length,snippet:h.slice(0,160),message:m instanceof Error?m.message:String(m)}),m}return Ot("response_body",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:r,action:o,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u),bytes:g.diff?.length??0,error:g.error??null,truncated:!!g.truncated,tooLarge:!!g.tooLarge}),g}async function b2(t,e,r="load_git_details",n){const o=new URLSearchParams;t&&o.set("cwd",t),o.set("action",r),n&&o.set("requestSlotId",n);const s=o.toString(),i=await he(`/api/terminal/fs/git-context${s?`?${s}`:""}`,{signal:e},dt,"Git details took too long. The repository may be busy, on slow storage, or locked by another Git process.");if(!i.ok){const a=await i.json().catch(()=>({error:"Failed to get git context"}));throw new Error(a.error||"Failed to get git context")}return i.json()}async function v2(t={},e){const r=new URLSearchParams;t.workspaceRoot&&r.set("workspaceRoot",t.workspaceRoot),t.repoRoot&&r.set("repoRoot",t.repoRoot);const n=r.toString(),o=await he(`/api/terminal/fs/change-audit${n?`?${n}`:""}`,{signal:e},dt,"Change audit explanations took too long to load.");if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to get change audit explanations"}));throw new Error(s.error||"Failed to get change audit explanations")}return o.json()}async function x2(t,e){const r=new URLSearchParams;t.cwd&&r.set("cwd",t.cwd),t.repoRoot&&r.set("repoRoot",t.repoRoot),r.set("base",t.base),t.head&&r.set("head",t.head),t.includeUncommitted===!1&&r.set("includeUncommitted","0"),r.set("action","load_branch_diff"),t.requestSlotId&&r.set("requestSlotId",t.requestSlotId);const n=await he(`/api/terminal/fs/branch-diff?${r}`,{signal:e},Wr,"Branch diff took too long. The repository may be busy, on slow storage, or locked by another Git process.");if(!n.ok){const o=await n.json().catch(()=>({error:"Failed to get branch diff"}));throw new Error(o.error||"Failed to get branch diff")}return n.json()}async function S2(t,e){const r=new URLSearchParams;t.cwd&&r.set("cwd",t.cwd),t.repoRoot&&r.set("repoRoot",t.repoRoot),r.set("commit",t.commit),r.set("action","load_commit_diff"),t.requestSlotId&&r.set("requestSlotId",t.requestSlotId);const n=await he(`/api/terminal/fs/commit-diff?${r}`,{signal:e},Wr,"Commit diff took too long. The repository may be busy, on slow storage, or locked by another Git process.");if(!n.ok){const o=await n.json().catch(()=>({error:"Failed to get commit diff"}));throw new Error(o.error||"Failed to get commit diff")}return n.json()}async function E2(t,e){const r=new URLSearchParams;t.cwd&&r.set("cwd",t.cwd),t.repoRoot&&r.set("repoRoot",t.repoRoot),r.set("limit",String(t.limit)),typeof t.skip=="number"&&r.set("skip",String(t.skip)),t.query&&r.set("query",t.query),r.set("action","load_recent_commits"),t.requestSlotId&&r.set("requestSlotId",t.requestSlotId);const n=await he(`/api/terminal/fs/git-recent-commits?${r}`,{signal:e},dt,"Recent commits took too long. The repository may be busy, on slow storage, or locked by another Git process.");if(!n.ok){const o=await n.json().catch(()=>({error:"Failed to get recent commits"}));throw new Error(o.error||"Failed to get recent commits")}return n.json()}async function A2(t={},e){const r=new URLSearchParams;t.workspaceRoot&&r.set("workspaceRoot",t.workspaceRoot),t.repoRoot&&r.set("repoRoot",t.repoRoot),t.baseRef&&r.set("baseRef",t.baseRef),t.branchName&&r.set("branchName",t.branchName);const n=r.toString(),o=await he(`/api/terminal/fs/branch-audit${n?`?${n}`:""}`,{signal:e},dt,"Branch explanations took too long to load.");if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to get branch explanations"}));throw new Error(s.error||"Failed to get branch explanations")}return o.json()}async function k2(t={}){const e=await Z(),r=await he("/api/terminal/fs/change-audit",{method:"DELETE",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)},dt,"Change audit explanations took too long to clear.");if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to clear change audit explanations"}));throw new Error(n.error||"Failed to clear change audit explanations")}return r.json()}async function I2(t={}){const e=await Z(),r=await he("/api/terminal/fs/branch-audit",{method:"DELETE",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)},dt,"Branch explanations took too long to clear.");if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to clear branch explanations"}));throw new Error(n.error||"Failed to clear branch explanations")}return r.json()}async function C2(t,e,r){const n=new URLSearchParams;t&&n.set("cwd",t),n.set("action","load_untracked_files"),r&&n.set("requestSlotId",r);const o=n.toString();return(await he(`/api/terminal/fs/untracked-files${o?`?${o}`:""}`,{signal:e},Wr,"Untracked file scan took too long. The repository may be busy, on slow storage, or locked by another Git process.")).json()}async function R2(t,e,r={}){const n=new URLSearchParams;t&&n.set("cwd",t),r.includeNested&&n.set("includeNested","true"),r.refresh&&n.set("refresh","true"),r.cacheOnly&&n.set("cacheOnly","true"),n.set("action",r.action??(r.refresh?"manual_git_refresh":"open_sidebar_git_refresh")),r.requestSlotId&&n.set("requestSlotId",r.requestSlotId);const o=n.toString(),s=`/api/terminal/fs/git-bundle${o?`?${o}`:""}`,i=r.requestTimeoutMs===null?await fetch(s,{signal:e}):await he(s,{signal:e},r.requestTimeoutMs??dt,"Git status refresh took too long. The repository may be busy, on slow storage, or locked by another Git process.");if(!i.ok){const a=await i.json().catch(()=>({error:"Failed to get git bundle"}));throw new Error(a.error||"Failed to get git bundle")}return i.json()}async function T2(t){const e=await Z(),r=await fetch("/api/terminal/fs/git-action",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:"Git action failed"})),o=n.confirmationPhrase?`${n.error||"Git action failed"} (${n.confirmationPhrase})`:n.error||"Git action failed";throw new Error(o)}return r.json()}async function P2(t){const e=new URLSearchParams;t.cwd&&e.set("cwd",t.cwd),t.action&&e.set("action",t.action),t.jobId&&e.set("jobId",t.jobId);const r=await fetch(`/api/terminal/fs/git-action/status?${e}`);if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to get Git action status"}));throw new Error(n.error||"Failed to get Git action status")}return r.json()}async function N2(t){const e=await Z(),r=await fetch("/api/terminal/fs/apply-hunk",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to apply diff hunk"}));throw new Error(n.error||"Failed to apply diff hunk")}return r.json()}async function De(t,e){const r=e?.method?.toUpperCase()??"GET",n=new Headers(e?.headers);r!=="GET"&&r!=="HEAD"&&n.set("X-XSRF-TOKEN",await Z()),e?.body&&n.set("Content-Type","application/json");const o=await fetch(`/api/terminal/operations${t}`,{...e,headers:n});if(!o.ok){const s=await o.json().catch(()=>({error:"操作失败"}));throw new pe(s.error||"操作失败",o.status)}return o.status===204?void 0:await o.json()}function L2(){return De("/automations")}function B2(t){return De("/automations",{method:"POST",body:JSON.stringify(t)})}function _2(t){return De(`/automations/${encodeURIComponent(t)}/run`,{method:"POST"})}function D2(t,e){return De(`/automations/${encodeURIComponent(t)}/enabled`,{method:"POST",body:JSON.stringify({enabled:e})})}function O2(t){return De(`/automations/${encodeURIComponent(t)}`,{method:"DELETE"})}let Xt=null,tu="",ru;const Da=new Set;function jc(){return De("/collaboration-groups",{signal:AbortSignal.timeout(1e4)})}function br(){const t=Dr(),e=t?.serviceOrigin??window.location?.origin??"",r=`${t?.targetPeerId??""}:${e}`,n=window.termdockDesktop;if(!Xt||r!==tu||n!==ru){Xt?.dispose(),tu=r,ru=n;const o=!n?.collaboration||n.collaboration.protocolVersion===2,s=n?void 0:Gh(),i=n?.collaboration?o&&n.collaboration.peers&&n.collaborationPeers?()=>n.collaborationPeers():void 0:n?.collaborationList?()=>n.collaborationList():s?()=>s.peers(e):void 0;Xt=new mE({origin:e,peerOrigin:n?window.location.origin:void 0,readLocal:jc,readPeers:i,peerProtocol:!o||n?.collaboration?.peers&&!n.collaborationPeers?"unsupported":n?.collaboration?.peers||s?"v2":"legacy"}),Xt.subscribe(a=>{for(const c of Da)c(a)})}return Xt}function Uc(){Xt?.dispose(),Xt=null}function F2(t){return Da.add(t),()=>{Da.delete(t)}}function M2(){br().refreshPeers(!0)}function j2(){return br().load()}async function U2(t){const e=await jc(),r=t.id?e.groups.find(c=>c.id===t.id):void 0;if(t.id&&!r)throw new pe("协作组已删除,请刷新列表",404);if(r&&t.expectedUpdatedAt!==void 0&&t.expectedUpdatedAt!==r.updatedAt)throw new pe("协作组已被修改,请重新打开成员管理后再保存",409);const n=[...new Set(t.sessionIds)];if(!t.name.trim()||n.length<2)throw new pe("协作组至少需要两个有效会话",400);const o=new Set([...e.sessions.map(c=>c.sessionId),...r?.sessionIds??[]]),s=n.filter(c=>!o.has(c));if(s.some(c=>!Pa(c)))throw new pe("所选会话已变化,请刷新后重新选择;尚未保存任何修改",409);const i={...t,sessionIds:n,...r?{expectedUpdatedAt:t.expectedUpdatedAt??r.updatedAt}:{}};let a;if(s.length){const c=window.termdockDesktop;if(c){if(!c.collaborationSave||c.collaboration&&(c.collaboration.protocolVersion!==2||!c.collaboration.save))throw new pe("当前 Mac 客户端需要更新后才能添加跨服务成员;当前服务内仍可组队",409);if(r&&!r.federated&&c.collaboration?.protocolVersion!==2)throw new pe("将已有组转换为跨服务组需要更新 Mac 客户端;原组和记录均未修改",409);const l=window.location.origin;if(!c.collaboration&&Dr()?.serviceOrigin&&Dr().serviceOrigin!==l)throw new pe("旧版客户端无法在入口页面中添加跨服务成员,请更新客户端后重试",409);a=await c.collaborationSave({...i,expectedOrigin:l})}else{const l=Gh();if(!l)throw new pe("跨服务连接尚未就绪,请重新打开页面",409);a=await l.save(Dr()?.serviceOrigin??window.location.origin,i)}}else a=await De("/collaboration-groups",{method:"POST",body:JSON.stringify(i)});return br().invalidate(),a}async function $2(t){if((await jc()).capabilities?.groupMove!==1)throw new pe("当前服务需要升级后才能在协作组之间移动成员;原成员关系未修改",409);await De("/collaboration-groups/move-member",{method:"POST",body:JSON.stringify(t)}),br().invalidate()}function H2(t,e){return De(`/collaboration-groups/${encodeURIComponent(t)}/spawn`,{method:"POST",body:JSON.stringify(e)}).then(r=>(br().invalidate(),r))}function q2(t,e,r){return De(`/collaboration-groups/${encodeURIComponent(t)}/role`,{method:"POST",body:JSON.stringify({sessionId:e,role:r})}).then(n=>(br().invalidate(),n))}function K2(t,e){const r=e===void 0?"":`?expectedUpdatedAt=${encodeURIComponent(e)}`;return De(`/collaboration-groups/${encodeURIComponent(t)}${r}`,{method:"DELETE"}).then(()=>{br().invalidate()})}function z2(t){return De(`/collaboration-groups/${encodeURIComponent(t)}/messages`)}function V2(t,e){return De(`/collaboration-groups/${encodeURIComponent(t)}/messages`,{method:"POST",body:JSON.stringify(e)})}function W2(t){return De(`/session-search?q=${encodeURIComponent(t)}`)}const G2=Object.freeze(Object.defineProperty({__proto__:null,AUTH_UNAUTHORIZED_EVENT:Nc,AgentPluginManifestError:Dc,EDA_PREVIEW_REQUEST_TIMEOUT_MS:dp,HTML_EXTENSIONS:Ep,MODEL_3D_EXTS:Sp,MODEL_PREVIEW_REQUEST_TIMEOUT_MS:lp,TERMINAL_CSRF_REQUEST_TIMEOUT_MS:up,TERMINAL_HEALTH_REQUEST_TIMEOUT_MS:fp,TERMINAL_SESSION_OPEN_REQUEST_TIMEOUT_MS:hp,TerminalApiError:pe,VISIBLE_WAKEUP_PROBE_TIMEOUT_MS:gp,acknowledgeTerminalOutput:ZE,applyDiffHunk:N2,buildHtmlPreviewUrl:e2,buildVideoPreviewUrl:X1,cancelIoSlot:s2,checkAgentPluginUpdate:L1,checkTermdockUpdate:IE,checkTerminalHealth:s1,clearBranchAuditRecords:I2,clearChangeAuditRecords:k2,clearSessionInventoryEntries:y1,closeTerminal:n1,confirmTermdockUpdateRestart:CE,connectTerminalStream:zE,createAgentPlugin:P1,createTerminalSession:KE,deleteAgentPlugin:D1,deleteFile:h2,dismissTmuxRecovery:u1,doctorAgentPlugin:_1,downloadFile:f2,fetchQuota:RE,forceKillTerminal:i1,getAgentHooks:I1,getAgentLaunchers:k1,getAgentPlugins:T1,getAppliedTerminalCursor:qE,getBranchAuditRecords:A2,getBranchDiff:x2,getChangeAuditRecords:v2,getCommitDiff:S2,getContextDraft:S1,getDefaultEdaPreviewView:J1,getEdaExtForPath:Fc,getFileDiff:y2,getGitActionStatus:P2,getGitBlobContent:a2,getGitBundle:R2,getGitContext:b2,getImageMimeTypeForPath:Fs,getLocalFileBrowserAvailability:g2,getModel3dExtForPath:Oc,getProgramDetection:H1,getRecentCommits:E2,getSessionInventory:h1,getSettings:ms,getTermdockUpdateState:kE,getTitleNamerCatalog:x1,getTmuxStatus:c1,getToolbarPresetsDoc:b1,getUntrackedFiles:C2,getVideoMimeTypeForPath:xp,inspectEdaPoint:d2,installAgentHooks:C1,installAgentPluginSource:N1,isHeicImagePath:vp,isPreviewableEdaPath:Z1,isPreviewableHtmlPath:Q1,isPreviewableImagePath:V1,isPreviewableModel3dPath:Y1,isPreviewableVideoPath:G1,killTmuxSession:l1,listAgentAutomations:L2,listAgentResumeHistory:F1,listCollaborationGroups:j2,listCollaborationMessages:z2,listDirectory:r2,listTmuxSessions:a1,loginWithPassword:bp,logout:A1,moveCollaborationMember:$2,openInFileBrowser:m2,openSessionInventoryEntry:p1,parseFilenameFromContentDisposition:Ap,prepareAgentResumeHistory:M1,probeTerminalConnection:WE,readEdaPreviewBlob:l2,readFileContent:i2,readImagePreviewBlob:c2,readModel3dBlob:u2,readPreviewSourcePath:Mc,reconnectTerminalConnectionNow:GE,refreshQuota:TE,removeAgentAutomation:O2,removeAgentResumeHistory:j1,removeCollaborationGroup:K2,removeSessionInventoryEntry:w1,reorderSessionInventoryEntries:m1,replaceProgramDetection:q1,replaceProgramRules:U1,replaceToolbarPresetsDoc:v1,resetCollaborationDirectory:Uc,resetCsrfTokenCache:Bc,resetProgramDetection:K1,resetProgramRules:$1,resizeTerminal:t1,restartTerminalSession:o1,restoreAllTmuxAgentSessions:d1,resumeAgentSession:O1,retryCollaborationPeers:M2,runAgentAutomation:_2,runGitAction:T2,saveAgentAutomation:B2,saveCollaborationGroup:U2,searchFilesStream:n2,searchTerminalSessions:W2,sendAgentReviewAck:QE,sendCollaborationMessage:V2,sendTerminalFlowControlState:e1,sendTerminalFocusState:YE,sendTerminalInput:VE,sendTerminalViewingState:JE,sendTmuxAction:r1,setAgentAutomationEnabled:D2,setCollaborationMemberRole:q2,setTerminalOutputSubscription:wp,setTerminalSnapshotCursor:HE,spawnCollaborationAgent:H2,subscribeCollaborationGroups:F2,suspendTerminalConnectionReconnects:XE,uninstallAgentHooks:R1,updateAgentPlugin:B1,updateContextDraft:E1,updateSessionInventoryEntry:g1,updateSettings:Gt,uploadFiles:p2,watchFileSystem:o2},Symbol.toStringTag,{value:"Module"})),X2={app:{name:"Termdock"},common:{cancel:"Cancel",close:"Close",save:"Save",reset:"Reset",loading:"Loading…",error:"Error",retry:"Retry",refresh:"Refresh",search:"Search",clear:"Clear",delete:"Delete",on:"On",off:"Off",back:"Back",copy:"Copy",decrease:"Decrease",increase:"Increase",use:"Use",previous:"Previous",next:"Next"},login:{prompt:"termdock login",placeholder:"Enter password",placeholderBlocked:({s:t})=>`Please wait ${t}s`,submit:"Sign in",invalidPassword:"Incorrect password",failed:"Login failed"},sidebar:{sessions:"Sessions",noSessions:"No open sessions yet.",noMatchingSessions:"No matching sessions.",toggleSearch:"Toggle search",settings:"Settings",moreActions:"More actions",subscriptionQuota:"Subscription quota",pinSidebar:"Keep sidebar open",unpinSidebar:"Stop keeping sidebar open",runningSessionButton:"Running sessions button",runningSessionButtonHint:"Tap to cycle, swipe sideways to select, hold to drag",updateAvailable:({version:t})=>`Termdock ${t} is available`,updateInstalling:"Installing in the background without interrupting this service.",updateReady:"The update is installed and ready for a confirmed restart.",updateRestart:"Restart and finish update",updateRestartConfirm:({version:t})=>`Restart Termdock and switch to ${t}? This page will reconnect briefly and sessions will stay open.`,updateRestarting:"Restarting; this page will reconnect automatically…",updateFailed:"Automatic installation failed. This reminder will remain.",updateRetry:"Try again",filterSessions:"Filter sessions",clearSearch:"Clear search",groupByFolder:"Group by folder",groupByFolderTitle:"Collapse sessions into groups by working directory. Mutually exclusive with drag sorting.",ungrouped:"Other",needsAttention:"Needs attention",waitingForYou:"Waiting for you",completedUnread:"Completed · unread",closeSession:({name:t})=>`Close ${t}`,newShell:"Shell",newTmux:"Tmux",newTmuxDisabled:"tmux not available on server",confirmNewShell:"Create Shell?",confirmNewTmux:"Create Tmux?",newSession:"New terminal",newSessionWithAgent:({agent:t})=>`New ${t}`,moreLaunchOptions:"More launch options",recoverableSessions:"Recoverable sessions",refreshRecoverableSessions:"Refresh recoverable sessions",restoreRecoverableSession:({name:t})=>`Restore ${t}`,restoringRecoverableSession:"Restoring…",restore:"Restore",newSessionAdvanced:"Quick-launch agent",newSessionComposerTitle:"Start a session",newSessionHint:"Choose how and where it starts",launchSessionWith:({name:t})=>`Start ${t}`,setNewSessionDefault:({name:t})=>`Set ${t} as default`,currentNewSessionDefault:({name:t})=>`${t} is the current default`,currentDefaultAgent:({name:t})=>`Current default: ${t}`,defaultAgent:"Default",makeDefault:"Make default",sessionMode:"Run mode",tmuxKeepsRunning:"Keeps running after disconnect",resumeHistory:"Recent conversations",resumeHistoryCount:({n:t})=>`${t} saved`,resumeHistoryLoading:"Loading recent Agent conversations…",resumeHistoryAction:({title:t})=>`Resume ${t}`,resumeHistoryRemove:({title:t})=>`Remove ${t} from recent conversations`,resumeHistoryLoadFailed:"Could not load recent Agent conversations.",resumeHistoryFailed:"Could not prepare this Agent conversation for resume.",resumeHistoryRemoveFailed:"Could not remove the conversation from history.",workingDirectory:"Working directory",directoryPlaceholder:"Enter a directory path",browseDirectories:"Browse",hideDirectoryBrowser:"Hide browser",chooseDirectory:"Choose working directory",directoryPickerHint:"Open a folder, then confirm the current location.",useThisFolder:"Use folder",recentDirectories:"Recent directories",startCommand:"Start command",customCommand:"Other command",commandPlaceholder:"Optional, e.g. codex",detectAgents:"Detect agents again",savePreset:"Save as preset",createAndRun:"Create and run",createSession:"Create terminal",openLeftSidebar:"Open left sidebar",openRightSidebar:"Open right sidebar",closeSidebar:"Close sidebar"},rightSidebar:{workspace:"Workspace",currentProject:"Project",browsingLocation:"Browsing",parentFolder:"Parent folder",backToProjectRoot:"Back to project",refreshFiles:"Refresh current folder",resizeFileTree:"Drag to resize file browser",pinCurrentFolder:"Pin current folder to this project",unpinCurrentFolder:"Unpin current folder",showHiddenFiles:"Show hidden files",hideHiddenFiles:"Hide hidden files",insertCurrentFolder:"Insert current folder reference",insertCurrentFolderShort:"Insert",pinnedFolders:"Pinned",unpinFolder:({name:t})=>`Unpin ${t}`,fileWatchUnavailable:({message:t})=>`File watcher unavailable: ${t}. Click to refresh manually.`,browsingOutsideProject:"Browsing outside current project",browsingOutsideProjectHint:"Git and Changes still use the current project. File references from here are inserted as external paths.",toggleSearch:"Toggle search",refreshGit:"Refresh Git status",gitLastUpdated:({time:t})=>`Last updated: ${t}`,close:"Close",filterChanges:"Filter changes or files",searchPlaceholderContent:"Search text in files…",searchModeName:"File",searchModeContent:"Content",clearSearch:"Clear search",searchScope:"Scope",searchScopePlaceholder:"Relative folder or absolute path",resetSearchScope:"Reset to current folder",searchOptions:"Search options",searchExclude:"Exclude",searchExcludePlaceholder:"dist/**, *.lock",clearSearchExclude:"Clear exclusions",contentSearchOptions:"Content search options",matchCase:"Match case",matchWholeWord:"Whole word",useRegex:"Regex",insertGitContext:"Insert current Git context into terminal",copyGitContext:"Copy Git context",insertChangeAuditPrompt:"Explain changes",insertChangeAuditPromptTitle:"Insert the change audit prompt into the current session",changeAuditShort:"Explain changes",changeAuditLoading:"Loading hunk explanations…",changeAuditLoaded:({count:t})=>`${t} hunk explanation${t===1?"":"s"} loaded`,changeAuditLoadedAt:({time:t})=>`Generated ${t}`,changeAuditRegenerate:"Regenerate",changeAuditRefreshStale:"Fill stale",changeAuditRefreshStaleTitle:"Insert a prompt to refresh stale hunk explanations",clearChangeAudit:"Clear",clearChangeAuditTitle:"Clear hunk explanations for the current repository",changeAuditClearFailed:({message:t})=>`Failed to clear hunk explanations: ${t}`,changeAuditScopeAll:"All repositories",changeAuditScopeLabel:"Explain scope",branchAuditTitle:"Branch explanation",branchAuditShort:"Explain branch changes",branchAuditBaseLabel:"Base branch",branchAuditBasePlaceholder:"Base branch, e.g. master",branchAuditBaseSearchPlaceholder:"Search base branch",branchAuditBaseEmpty:"No branch options. Type a branch name directly.",branchAuditGenerate:"Generate",branchAuditRegenerate:"Regenerate",branchAuditGenerateTitle:"Insert a prompt to explain this branch against the base branch",branchAuditViewDiff:"View diff",branchAuditViewDiffTitle:"View target branch changes against the base branch",branchAuditDiffLoading:"Loading branch diff...",branchAuditDiffEmpty:"No changes between this branch and the base branch.",branchAuditMissingBase:({repo:t})=>`${t} has no base branch set`,branchAuditRefreshDiff:"Refresh diff",branchAuditRefreshStale:"Fill stale",branchAuditRefreshStaleTitle:"Insert a prompt to refresh stale branch explanations",branchAuditClearTitle:"Clear current branch explanation",branchAuditClearFailed:({message:t})=>`Failed to clear branch explanation: ${t}`,branchAuditCommitCount:({count:t})=>`${t} commit${t===1?"":"s"}`,branchAuditFileCount:({count:t})=>`${t} file${t===1?"":"s"}`,branchAuditTruncated:"diff truncated",branchAuditCurrent:"Saved explanation",branchAuditStale:"Explanation is stale",branchAuditEmpty:"No branch explanation yet. Generate one to persist it here for later review.",branchAuditView:"View explanations",branchAuditSaved:({count:t})=>`${t} hunk explanation${t===1?"":"s"} saved`,branchAuditGeneratedAt:({time:t})=>`Generated ${t}`,insertPreset:({label:t})=>`Insert: ${t}`,tabChanges:"Changes",tabGit:"Git",tabFiles:"Files",inserted:"Inserted",copied:"Copied",toggleContextDraft:"Toggle context draft",contextDraftTitle:"Context draft",contextDraftHint:"References are added here while enabled. Keep browsing, add instructions, then insert once.",contextDraftPlaceholder:"Compose a longer prompt here. Keep using sidebar references to add context…",contextDraftCollapse:"Collapse context draft",contextDraftExpand:"Expand context draft",contextDraftDisable:"Disable context draft",contextDraftClear:"Clear draft",contextDraftInsert:"Insert",contextDraftInsertAndSend:"Insert & send",contextDraftInserted:"Inserted",contextDraftSent:"Sent",contextDraftSend:"Send draft",contextDraftAppended:"Reference added",contextDraftResize:"Drag to resize, double-click for default height",contextDraftAutoCollapseAfterSend:"Collapse after insert/send",contextDraftInsertFailed:"Terminal disconnected — draft kept",contextDraftCharacterCount:({count:t})=>`${t} chars`,selectFilePrompt:"Select a file to preview its contents",backToFileList:"Back to file list",backToPreviousPreview:"Back to source document",insertLineRef:({lineLabel:t})=>`Insert ${t}`,insertFileRef:"Insert",copyFileRef:"Copy file reference",findInFile:"Find in file",findInFilePlaceholder:"Find in this file…",previousSearchMatch:"Previous match",nextSearchMatch:"Next match",closeFileSearch:"Close file search",downloadFile:"Download file",downloadFailed:"Download failed",uploadFile:"Upload file",uploadFiles:"Upload files",insertLocalFile:"Insert local file",insertLocalImage:"Insert local image",layoutMode:"Display mode",layoutModeAuto:"Auto",layoutModeNarrow:"Narrow",layoutModeWide:"Wide",dropToUpload:"Drop files to upload",uploading:"Uploading…",uploadSuccess:({count:t})=>`${t} file${t===1?"":"s"} uploaded`,uploadFailed:"Upload failed",binaryPreviewHint:"Binary files cannot be previewed. Use the download button above to save it.",selectedLineHint:({lineLabel:t})=>`Selected ${t} · tap "Insert" below to add to terminal`,multiLineHint:"Multi-line select: tap start line, then end line",loadingImage:"Loading image…",imagePreviewHint:"Pinch or ⌘/Ctrl + scroll to zoom · double-tap to reset",imageLoadFailed:"Failed to load image preview",loadingVideo:"Loading video…",videoPreviewHint:"Click to play · hold for 2× · drag to seek",videoLoadFailed:"Failed to load video preview",videoUnsupported:"Your browser does not support this video format",videoPlay:"Play",videoPause:"Pause",videoLongPressSpeed:"Playing at 2×",videoRotate:"Rotate 90° clockwise",videoFullscreenEnter:"Enter fullscreen",videoFullscreenExit:"Exit fullscreen",model3dLoading:"Loading 3D model…",model3dExplode:"Exploded view",model3dExplodeAxis:"Explosion axis (viewer coordinates)",model3dExplodeAmount:"Explosion amount",model3dHome:"Reset view",model3dFit:"Fit visible parts",model3dFront:"Front view",model3dTop:"Top view",model3dRight:"Right view",model3dAssemble:"Restore assembly",model3dExplodedNotice:"Exploded · dimensions and references remain assembled",model3dLoadFailed:"Failed to load 3D model preview",model3dTimeout:"3D model transfer timed out. Check your connection and retry.",model3dDimensions:({dims:t})=>`Dimensions: ${t}`,model3dHintMouse:"Drag to orbit · two-finger pan · pinch or scroll to zoom",model3dHintTouch:"One finger to orbit · two fingers to zoom & pan",model3dFullscreenEnter:"Fullscreen",model3dFullscreenExit:"Exit fullscreen",model3dBgToLight:"Light background",model3dBgToDark:"Dark background",model3dRefresh:"Reload model",model3dClipToggle:"Section view",model3dClipPosition:"Section position",model3dClipFlip:"Flip section direction",model3dFeatureToggle:"Features",model3dFeatureStatus:({total:t,positioned:e})=>`Features: ${t} · positioned ${e}`,model3dFeatureInsert:"Insert reference",model3dGlossaryToggle:"Modeling terms",model3dPickToggle:"Select part / reference",model3dPickHint:"Select a part to hide it or insert a point reference",model3dHidePart:"Hide part",model3dShowAllParts:({count:t})=>`Show all (${t})`,model3dParts:"Parts",model3dCloseParts:"Close parts",model3dSearchParts:"Find a part",model3dClearPartSearch:"Clear part search",model3dHiddenParts:({count:t})=>`${t} hidden`,model3dShowNamedPart:({name:t})=>`Show ${t}`,model3dHideNamedPart:({name:t})=>`Hide ${t}`,model3dIsolateNamedPart:({name:t})=>`Only show ${t}`,model3dIsolatePart:"Only this part",model3dShowPart:"Show part",model3dNoParts:"No matching parts",model3dUndoVisibility:"Undo",model3dClearSelection:"Clear selection",model3dAllPartsVisible:"All parts visible",model3dInspectHint:"Drag to orbit · double-tap to zoom · double-tap empty space to fit",model3dUnnamedPart:({index:t})=>`Part ${t}`,model3dCanvas:"3D model",model3dMore:"More model options",edaLoading:"Rendering KiCad file…",reviewTargetChanged:"The active session changed. Return to the original session before inserting this reference.",reviewReference:"Review reference",reviewReferenceHint:"Add context, then insert. Nothing is sent automatically.",reviewSnapshot:"Snapshot of the selected viewer",reviewCapturing:"Capturing this view…",reviewIncludeImage:"Include snapshot (stored temporarily on this server)",reviewCaptureFailed:"Snapshot unavailable; location can still be inserted.",reviewNote:"Your comment (optional)",reviewNotePlaceholder:"What should change here?",reviewDetails:"View location and quoted content",reviewUploading:"Preparing reference…",reviewAddToDraft:"Add to context draft",reviewInsert:"Insert reference",reviewUploadFailed:"Could not prepare the reference. Your comment is kept. Retry, or uncheck the snapshot to insert text only.",edaLoadFailed:"Failed to render KiCad preview",edaTimeout:"KiCad preview rendering or transfer timed out. Please retry.",edaRefresh:"Render again",edaPickHint:"Click a schematic or PCB location to create an electronics annotation",edaPickedPosition:({x:t,y:e})=>`Selected ${t}%, ${e}%`,edaPickedBoardPosition:({x:t,y:e,object:r})=>`Board ${t}, ${e} mm · ${r}`,edaInspecting:"Reading board coordinates and nearby object…",edaNoNearbyObject:"No nearby object",edaInsertAnnotation:"Insert electronics annotation",csvUnnamedColumn:({index:t})=>`Column ${t}`,csvSelectedCell:({row:t,column:e})=>`Row ${t} · ${e}`,csvPickHint:({rows:t,columns:e})=>`${t} records · ${e} columns; click a cell to reference`,csvInsertAnnotation:"Insert table annotation",csvTablePreview:"Table preview: select a cell to reference its record",kicadLocalStateNotice:"This is local UI state and is not part of schematic, PCB, or manufacturing review.",kicadShowRawJson:"Show raw JSON",kicadProjectPickHint:"Select a setting to insert a reference",kicadInsertSetting:"Insert setting",markdownPreview:"Preview",markdownSource:"Source",markdownPreviewHint:"Tap a line/section to reference, tap another to extend; drag the left rail to select a range",htmlPreview:"Preview",htmlSource:"Source",htmlPreviewHint:"Sandboxed iframe preview; scripts run sandboxed",htmlFullscreenEnter:"Enter fullscreen preview",htmlFullscreenExit:"Exit fullscreen preview",markdownOutline:"Markdown outline",markdownOutlineShort:"Outline",closeMarkdownOutline:"Close outline",changedFromPath:({path:t})=>`from ${t}`,selectedLineFooter:({lineLabel:t})=>`Selected ${t}`,clearSelection:"Clear",allChanges:"All changes",backToChangeList:"Back to list",allRepositories:"All repositories",allRepositoriesShort:"All",repositories:"Repositories",gitRepositorySectionTitle:"Repository",gitRepositoryLabel:"Repository",gitRepositoryPlaceholder:"Select repository",gitRepositorySearchPlaceholder:"Search repositories",gitRepositoryEmpty:"No available repositories",selectRepositoryForGitActions:"Select a repository before running Git actions",selectRepositoryForDiff:"Select a repository or file to view diff",repoChangedCount:({count:t})=>`${t} change${t===1?"":"s"}`,repoStagedCount:({count:t})=>`${t} staged`,noChanges:"No changes",noMatchingChanges:"No matching changes",loadingGitChanges:"Loading Git changes…",loadingGitChangesSlow:"Large repositories can take a few seconds.",refreshingGitChanges:"Refreshing Git changes…",gitChangesLoadFailed:"Unable to load Git changes",retryGitChanges:"Retry",insertThisFile:"Insert this file reference into terminal",viewDiff:"View diff",diffViewMode:"Change file display mode",diffViewModeList:"Flat list",diffViewModeTree:"Folder tree",diffViewModeAi:"AI walkthrough",changeWalkthroughEmpty:"No AI walkthrough yet. Generate explanations to show the overview, flow, and checks here.",gitInfo:"Git context",wrapLongLines:"Wrap long lines",wrapOn:"Wrapped",wrapOff:"Raw",horizontalScrollHint:"Swipe left/right to see the full diff",stageFile:"Stage",stageAll:"Stage all",unstageFile:"Unstage",stashFile:"Stash",stashAll:"Stash all",restoreFile:"Restore",gitQuickActions:"Git Actions",gitUnavailable:"Current directory is not a Git repository",branchSectionTitle:"Current branch",currentBranchLabel:"Branch",switchBranchPlaceholder:"Select branch",switchBranchSearchPlaceholder:"Search local branch",switchNoBranches:"No local branches",switchBranch:"Switch",noStagedChangesShort:"no staged",stagedCount:({count:t})=>`${t} staged`,stagedCountShort:({count:t})=>`${t} staged`,commitSectionTitle:"Commit",commitReadyHint:({count:t})=>`${t} file${t===1?"":"s"} ready`,commitMessagePlaceholder:"Commit message",commitChanges:"Commit",commitNeedsStaged:"Stage changes before committing",recentCommitsTitle:"Recent commits",recentCommitsSearchPlaceholder:"Search commit hash or message",recentCommitsLoadMore:"Load more commits",recentCommitsEmpty:"No commit history",pushSectionTitle:"Remote sync",pushRemoteLabel:"Remote",pushRemotePlaceholder:"origin",pushRemoteSearchPlaceholder:"Search remote",pushNoRemotes:"No remotes",pushBranchLabel:"Target",pushBranchPlaceholder:({branch:t})=>`${t}`,pushBranchSearchPlaceholder:"Search branch",pushNoBranches:"No branches",pushUpstreamBadge:"upstream",pushCurrentBranchBadge:"current",pushNoUpstream:"No upstream configured",pushUpToDate:"Up to date with remote",pushAheadCount:({count:t})=>`${t} commit${t===1?"":"s"} to push`,pushBehindCount:({count:t})=>`${t} commit${t===1?"":"s"} to pull`,pushDivergedCount:({ahead:t,behind:e})=>`${t} ahead / ${e} behind`,pullChanges:"Pull",pushChanges:"Push",gitActionRunning:"Running…",gitActionFailed:({message:t})=>`Git action failed: ${t}`,confirmRestoreTitle:"Discard changes?",confirmRestoreDescription:({path:t})=>`This will discard unstaged changes in ${t}. Termdock cannot recover them.`,confirmRestorePhrase:"discard changes",confirmRestorePlaceholder:"Type “discard changes” to confirm",confirmStashAllTitle:"Stash all changes?",confirmStashAllDescription:"This moves current working tree changes, including untracked files, into a stash.",confirmAction:"Confirm",renderingHtml:"Rendering HTML…",footnotes:"Footnotes",backToFootnote:({index:t})=>`Back to footnote ${t}`,openMermaidDiagram:"Open Mermaid diagram",mermaidDiagram:"Mermaid diagram",renderingDiagram:"Rendering diagram…",markdownImage:"Markdown image",image:"Image",previousImage:"Previous image",nextImage:"Next image",closeImagePreview:"Close image preview",emptyFile:"Empty file.",insertReference:({reference:t})=>`Insert reference: ${t}`,copyReference:({reference:t})=>`Copy reference: ${t}`,byteCount:({count:t})=>`${t} bytes`,previewTruncated:"Preview truncated to 1 MB",branchCandidatesLoading:"Loading branch candidates…",includeUncommitted:"Include local uncommitted changes",includeUncommittedHint:"Include working tree and untracked diffs when viewing or explaining changes",missingBaseReposSkipped:({repositories:t})=>`Repositories without a base branch will be skipped: ${t}`,localBranch:"local",remoteBranch:"remote"},fileTree:{insertRef:"Insert",insertRefTitle:"Insert file reference into active terminal",openDirRoot:"Open",openDirRootTitle:"Use this folder as the current browsing root",openInFileBrowser:"Reveal in Finder",openInFileBrowserTitle:"Open this item in the system file browser",openInFileBrowserFailed:"Failed to open file browser",moreDirActions:"More folder actions",searchFromDir:"Search from here",searchFromDirTitle:"Search only this folder and its descendants",pinDir:"Pin",pinDirTitle:"Pin this folder to the current project",unpinDir:"Pinned",unpinDirTitle:"Unpin this folder",pinFileTitle:"Pin this file to the current project",unpinFileTitle:"Unpin this file",pinFile:"Pin",unpinFile:"Unpin",moreFileActions:"More file actions",deleteFile:"Delete file",deleteFileConfirm:({name:t})=>`Delete “${t}”? This action cannot be undone.`,deleteFileFailed:({message:t})=>`Failed to delete file: ${t}`,noWorkingDir:"No working directory detected.",emptyDir:"Empty directory.",noMatchingFiles:"No matching files.",searching:"Searching files…",searchingWithCount:({count:t})=>`Searching… ${t} found`,searchResults:({count:t})=>`${t} results`,searchScope:"Search scope",searchTruncatedHint:({count:t})=>`Fallback search scanned a large directory and stopped after ${t} matches. Install ripgrep or refine the query for complete results.`,searchStillRunning:"Search is still running. More results will appear automatically.",showingSearchResults:({shown:t,total:e})=>`Showing ${t} of ${e}`,loadMoreSearchResults:({shown:t,total:e})=>`Show more (${t}/${e})`,contentMatchesCount:({count:t})=>`${t} file${t===1?"":"s"} with matches`,moreMatches:({count:t})=>`+${t} more match${t===1?"":"es"}`,noContentMatches:"No matches found in file contents.",contentSearchNeedsRipgrep:"Content search requires ripgrep (rg). Install it on the server to search inside files.",truncatedHint:"Showing first 1000 entries. Use search or open a smaller folder for better performance.",dropToUploadHere:"Upload here",symbolicLink:"Symbolic link",sortByModified:"Sort by recent changes",sortByName:"Sort by name",sortedByModified:"Sorted by recent changes"},diffViewer:{noFileChanges:"No changes in this file.",noUnstagedChanges:"No unstaged changes.",emptyHint:"Make some changes, or pull from a remote.",loading:"Loading diff…",insertAllDiff:"Insert current diff as context",insertFileDiff:"Insert this file's diff",insertHunkDiff:"Insert this hunk",insertHunkShort:"Insert",insertFileShort:"Insert",insertAllShort:"Insert all",stageHunk:"Stage",stageHunkTitle:"Stage only this hunk (git apply --cached)",revertHunk:"Revert",revertHunkTitle:"Revert this hunk in the worktree (cannot be undone)",revertHunkConfirm:"Confirm revert?",hunkActionApplying:"Applying…",hunkActionUnavailable:"Cannot build a patch for this hunk",hunkActionFailed:({message:t})=>`Failed: ${t}. If the changes moved on, refresh and retry.`,auditExplanation:"Change meaning",auditStale:"Explanation stale",auditClear:"Clear explanation",auditGeneratedAt:({time:t})=>`Generated ${t}`,allDiffLabel:"all changes",allChangesLabel:"all changes",workingTree:"Working tree changes",allUnstaged:"All unstaged changes",binaryOrEmpty:"No textual changes to display.",noFinalNewline:"No newline at end of file",noHunks:"No hunks",hunkOutline:"Hunks",expandHunkRail:"Show hunk list",collapseHunkRail:"Hide hunk list",prevHunk:"Previous hunk",nextHunk:"Next hunk",prevFile:"Previous",nextFile:"Next",expandFile:"Expand file",collapseFile:"Collapse file",expandAll:"Expand all",collapseAll:"Collapse all",collapseHunk:"Collapse hunk",useBracketKeysHint:"Press [ / ] to jump between hunks",unified:"Unified",unifiedMode:"Unified view",split:"Split",splitMode:"Side-by-side view",moreActions:"More actions",view:"View",loadingPreviousFile:"Loading previous file…",loadingNextFile:"Loading next file…",resizeNavigation:"Resize diff navigation",focusPathHint:"Select a label to focus its path",whitespace:"Whitespace",whitespaceDefault:"Default",whitespaceTrim:"Ignore trailing",whitespaceIgnore:"Ignore all",whitespaceIgnoreBlankLines:"Ignore blank lines",context:"Context",contextLines:({count:t})=>`${t} lines`,contextAll:"All"},settings:{title:"Settings",font:"Font",render:"Render",theme:"Theme",darkTheme:"Dark",lightTheme:"Light",newTab:"New tab",debug:"Debug",noSleep:"No sleep",noSleepUnavailable:"No network — disabled",updateTitle:"Termdock update",updateRuntimeTitle:"CLI and service runtime",updateHint:"A manual check downloads and installs a new version immediately. The service restarts only after you confirm.",updateCheck:"Check for updates",updateCheckAgain:"Check again",updateChecking:"Checking npm for the latest version…",updateCheckingShort:"Checking…",updateInstallingShort:"Installing…",updateCurrent:"Termdock is up to date.",desktopUpdateTitle:"macOS desktop app",desktopUpdateHint:"Manually check signed desktop releases published on GitHub.",desktopUpdateUnsupported:"In-app updates require an installed, signed macOS app.",desktopUpdateChecking:"Checking for a desktop update…",desktopUpdateCurrent:"The desktop app is up to date.",desktopUpdateDownloading:"A new version is downloading in the background…",desktopUpdateReady:"The desktop update is downloaded and ready to install.",desktopUpdateInstalling:"Restarting to install the desktop update…",desktopUpdateCheck:"Check desktop app",desktopUpdateCheckAgain:"Check again",desktopUpdateRestart:"Restart and install",desktopUpdateRestartConfirm:"Restart Termdock and install the downloaded desktop update? The terminal service and tmux sessions will remain running.",notifications:"Notify",notificationsTitle:"Notification settings",notificationsHint:"Notify when an AI task finishes while Termdock is hidden.",notificationsPageHint:"Choose which Termdock events can send system notifications. The master switch controls browser permission and delivery; event switches decide what should notify you.",notificationsMaster:"System notifications",notificationsMasterHint:"Allow Termdock to send notifications when it is hidden or running as an installed PWA.",notificationsIOSInstallHint:"On iPhone and iPad, install Termdock to the Home Screen before enabling notifications.",notificationsPermission:"Permission",notificationsPermissionSystem:"Managed by macOS",notificationsTest:"Send test",notificationsTestChecking:"Waiting for macOS to confirm delivery…",notificationsTestDelivered:"Delivered to Notification Center. If no banner appeared, check the alert style and Focus.",notificationsTestFailed:"macOS did not deliver the notification. Allow Termdock in System Settings.",notificationsOpenSystemSettings:"Open system notification settings",notificationsAlertStyle:"Alert style",notificationsAlertStyleHint:"Browsers and Android still decide the final heads-up behavior. Termdock can only request quiet/default/sticky notification options.",notificationsStyleNormal:"Default",notificationsStyleNormalHint:"Sound/vibration if allowed",notificationsStyleQuiet:"Quiet",notificationsStyleQuietHint:"Status tray, no sound",notificationsStylePersistent:"Sticky",notificationsStylePersistentHint:"Stay until dismissed",notificationsEvents:"Events",notificationsAiFinished:"AI task finished",notificationsAiFinishedHint:"Notify when an AI agent stops while Termdock is in the background.",notificationsSessionExited:"Terminal exited",notificationsSessionExitedHint:"Notify when a terminal process exits on its own (closing it yourself does not trigger; delivered via Web Push).",notificationsFutureHint:"More notification types can be added here later without changing the top-level settings layout.",notificationsOffSummary:"System notifications disabled",notificationsAiOnSummary:"AI task finished enabled",notificationsExitOnSummary:"Terminal exit enabled",notificationsBothOnSummary:"AI task finished and terminal exit enabled",notificationsNoEventsSummary:"No notification events enabled",notificationsDenied:"Browser notification permission is blocked. Enable it in site settings.",notificationsUnsupported:"Notifications require a secure context and service worker support.",notificationsTestBody:"Notifications are enabled. You will be notified when an AI task finishes in the background.",shell:"Shell",tmux:"Tmux",auto:"Auto",webgl:"WebGL",canvas:"Built-in",tmuxServer:"Tmux server",tmuxUnavailable:"unavailable",noTmuxSessions:"No tmux sessions on the server.",installTmuxHint:"Install tmux on the server to enable.",refresh:"Refresh",attached:"Attached",restorable:"Restorable",attach:"Attach",attaching:"Attaching…",destroy:"Destroy",sessions:({n:t})=>`${t} session${t===1?"":"s"}`,windows:({n:t})=>`${t} window${t===1?"":"s"}`,keyboardToolbar:"Keyboard toolbar",aiAgentDetection:"AI agent detection",signOut:"Sign out",language:"Language",programNamePlaceholder:"Program name (e.g. claude)",patternPlaceholder:"Regex pattern (e.g. Thinking|Generating)",statusPlaceholder:"Status",addProgram:"Add program",addPattern:"Add pattern",resetDefaults:"Reset defaults",invalidRegex:"Invalid regex",removeProgram:"Remove program",removeRule:"Remove rule",keepLabel:"keep",customColor:"Custom color",tabIndicator:"Tab indicator style",toolbarPresets:"Toolbar presets",detectionRules:"Detection rules",agentHooksHint:"With hooks installed, agents report their own status: working (green), waiting for you (amber), turn done (check) — and you get a notification the moment one needs your input. Hooks install globally but only fire inside termdock terminals.",agentHooksInstall:"Install",agentHooksInstalled:"Installed",agentHooksOutdated:"Outdated",agentHooksNeedsApproval:"Needs approval",agentHooksApprovalHint:"Run /hooks in Codex and approve the Termdock hooks",agentHooksNotInstalled:"Not installed",agentHooksUninstall:"Uninstall",agentHooksReinstall:"Reinstall",agentHooksDevMode:"Dev mode: hooks point at TS sources and need a built install to fire",agentHooksTarget:"writes to",agentAutoRename:"Automatic session titles",agentAutoRenameHint:"Update the title from recent work when an agent finishes a turn. Off by default; manual titles are never overwritten. External plugin CLIs run only after their title feature is enabled.",agentAutoRenameToggle:"Toggle automatic titles for this agent",agentAutoRenameShort:"Auto title",agentAutoRenameNamer:"Title agent",agentAutoRenameFollow:"Follow current session",agentAutoRenameModelsFromCli:"Models discovered from local CLIs",agentAutoRenameRefreshModels:"Refresh CLI models",agentAutoRenameCliDefault:"CLI default model",agentAutoRenameAutomatic:"Automatic selection",agentAutoRenameNoCli:"No supported title CLI detected",agentAutoRenameAdvanced:"Advanced title preferences",agentAutoRenamePreference:"Additional preferences",agentAutoRenamePreferenceHint:"Optional. Add preferences for title style or emphasis; Termdock keeps its default naming rules. Saved when you leave the field.",agentAutoRenamePreferencePlaceholder:"For example: emphasize user value; use action phrases; avoid technical jargon",agentAutoRenamePayloadLimit:"User-message context limit (characters)",agentAutoRenamePayloadLimitHint:"Total raw prompt-submit payload characters retained. Default 12000; range 1000–64000.",agentPlugins:"Agent Plugins",agentPluginAdd:"Add Plugin",agentPluginHint:"Install from an HTTPS Git repository or local directory after reviewing the source. Hooks and executable title CLIs require separate user opt-in.",agentPluginCreate:"Create Plugin",agentPluginDelete:"Delete Plugin",agentPluginInvalid:"Invalid plugin manifest",agentPluginCopyAiPrompt:"Copy AI fix prompt",agentPluginCopied:"Copied",agentPluginSourcePlaceholder:"https://github.com/user/agent-plugin or local directory",agentPluginInstallPackage:"Install plugin",agentPluginAdvancedManifest:"Advanced: paste manifest.json",agentPluginUpdateAvailable:"Update available",agentPluginManualSource:"Manual manifest",agentPluginUpdate:"Update",agentPluginCheck:"Check",agentPluginDoctor:"Diagnose",agentPluginDoctorHint:"Explicitly probe plugin models without generating a title",agentPluginDoctorStatusOk:"Title and model capabilities are healthy",agentPluginDoctorStatusMissing:"titleNamer is not declared",agentPluginDoctorStatusCliDefault:"Titles are available using the CLI default model",agentPluginDoctorStatusNoModels:"No usable model data was returned",agentPluginDoctorStatusFailed:"Model probe failed",agentPluginDoctorModels:"usable models",agentPluginDoctorAutomatic:"automatic",agentPluginDoctorCliDefault:"When no model is specified, the Agent CLI default model is used",agentAutoRenameInterval:"Recheck interval",agentAutoRenameMinutes:"minutes",mobileKeyboard:"Mobile keyboard",saving:"Saving…",rulesHint:"Configure regex patterns to detect what an AI tool is doing in a terminal tab. Each rule can choose its label, color, icon style and how long the indicator is kept after output quiets down. When it stops and you haven't viewed the tab yet, the tab keeps a yellow review hint.",programsHelp:"Supports multiple programs in one config. Separate with commas.",programLabelResolution:"Program label resolution",rawCommandMapping:"Raw command mapping",rawCommandMappingHint:"Rules below map the raw command line to the tab display label. User rules run before built-ins.",genericProgramNames:"Generic program names",genericProgramNamesHint:"Trigger ps-based deep detection (e.g. node, python)",wrapperScriptNames:"Wrapper script names",wrapperScriptNamesHint:"CLI wrappers that launch another tool (e.g. aiden, npx)",shellNamesConfig:"Shell names",shellNamesHint:"Filtered out from tab display (e.g. bash, zsh)",addTag:"+ add",customRules:"Custom rules",addRule:"Add rule",localAccess:"Local access",localAccessHint:"Use this LAN URL from your phone after trusting the local CA. Open Mobile setup on your phone to download the CA certificate.",resetAutoName:"Reset auto",onboardingUrl:"Mobile setup",httpsActive:"HTTPS active",httpsInactive:"HTTPS inactive",caMissing:"CA download unavailable",closeSettings:"Close settings",desktopTitle:"Termdock Desktop",desktopStatusLoading:"Reading native macOS status…",desktopSwitchService:"Switch service",desktopInstallCli:"Install / Repair CLI",desktopCliUpdated:"CLI status updated",desktopOpenDataDirectory:"Open data directory"},toolbarPresets:{preview:"Preview",presets:"Presets",label:"Label",new:"New",reset:"Reset",presetLabelPlaceholder:"Preset label",deletePreset:({name:t})=>`Delete preset ${t}`,matchPrograms:"Match programs",typeEnterHint:"Type & Enter",programsPlaceholder:"vim, nvim, /^claude(-code)?$/i …",programsHelp:"Plain names match as case-insensitive substrings. Wrap in /…/flags for regex (tested against the lowercase program name).",altSlot:"Alt modifier slot",altSlotHint:"Reserve one preview slot for the Alt key.",desktopVisibility:"Show on desktop",desktopVisibilityHint:"Desktop shows only this preset’s custom actions, not the basic keyboard shortcuts.",rowLayout:"Row layout",rowLayoutHint:"Buttons per expanded row.",addRow:"Row",rowN:({n:t})=>`Row ${t}`,del:"Del",buttons:"Buttons",buttonsHint:"Tap to edit. Use ↑↓ to reorder.",addButton:"Add button",noCustomButtons:"No custom buttons yet. Add one to override the default toolbar.",moveUp:"Move up",moveDown:"Move down",removeRow:({n:t})=>`Remove row ${t}`,removeAction:({name:t})=>`Remove ${t}`,labelField:"Label",labelPlaceholder:"Label shown on the button",sequence:"Sequence",sequencePlaceholder:"e.g. /undo or \\t or /||undo",sequenceHint:"Double-tap sequence",doubleTap:"Double-tap sequence",doubleTapAdd:"+ Add",doubleTapPlaceholder:"e.g. /undo\\r or /||undo ||\\r",remove:"Remove",noSequence:"No sequence",preset:"Preset",overCapacityHint:"More buttons than slots. Extra rows will use the last row size."},agentRules:{ruleColors:{green:"Green",yellow:"Yellow",red:"Red",blue:"Blue",purple:"Purple",orange:"Orange",gray:"Gray"}},tab:{session:"Session",new:"New session",rename:"Rename",renameHint:"Change the tab display name",renamePlaceholder:"Leave empty to reset to default",copyCwd:"Copy cwd",copyCwdHint:"Copy the current working directory",resumeAgent:"Resume agent session",resumeAgentHint:"Resume the last conversation by its native session id",resumeAgentAvailable:"Agent conversation available to resume",resumeAgentRecoveredTitle:({agent:t})=>`${t} conversation available`,resumeAgentRecoveredHint:"This terminal was rebuilt after an interruption. Continue where you left off.",resumeAgentNow:"Resume",resumeAgentLater:"Dismiss for now",resumeAgentSubmitting:"Submitting the native resume command…",resumeAgentWaiting:"Waiting for the Agent to confirm the restored conversation…",resumeAgentSuccess:({agent:t})=>`${t} conversation restored`,resumeAgentFailed:"Could not resume the Agent conversation. You can retry.",resumeAgentConflict:"This Agent conversation is already open in another terminal.",resumeAgentBusy:"Wait for the current Agent turn to finish before resuming.",resumeAgentTimeout:"The Agent did not confirm the restored conversation. Check the terminal or retry.",tmuxRecoveryTitle:({count:t})=>`tmux exited unexpectedly; ${t} Agent session(s) can be restored`,tmuxRecoveryHint:"Termdock kept the native session IDs. Restore continues each conversation in its original tab.",tmuxRecoveryRestoreAll:"Restore all",tmuxRecoveryRestoring:"Restoring…",tmuxRecoveryDismiss:"Not now",tmuxRecoveryPartial:({restored:t,failed:e})=>`Restored ${t}; ${e} still need attention.`,tmuxRecoveryFailed:"Recovery failed. Check the terminals and try again.",tmuxRecoveryDismissFailed:"Could not dismiss the recovery notice.",copied:"Copied",close:"Close session",closeHint:"Remove this tab from the list",longPressTip:"Tip: hold a tab still for a moment to open actions; hold and drag to reorder.",sessionsTitle:"Sessions",explorerTitle:"Explorer",split:"Split",splitTitle:"Add to split workspace",splitNew:"New session in workspace",splitNewHint:"Uses the current directory and default type; add as many panes as needed",splitExisting:"Choose a session or workspace",splitExistingHint:"Create multiple independent workspaces; choosing another workspace merges them",splitCurrent:"Current",splitClose:"Exit split",splitLayout:"Split layout",splitHorizontal:"Side by side",splitVertical:"Stacked",splitGrid:"Grid",splitWorkspace:"Split group",splitWorkspaces:"Split workspaces",splitRename:"Rename split group",splitRemovePane:"Remove from split",splitExistingGroups:"Existing split groups",splitAvailableSessions:"Available sessions",splitOccupied:"Grouped",splitUnavailableGrouped:"Grouped mode only supports sessions in the same directory",splitEndedGrouped:"Split ended: grouped mode does not support mixed directories",splitNoOtherSessions:"No other sessions are available",sessionCount:({count:t})=>`${t} session${t===1?"":"s"}`,closeChooserTitle:"Destroy tmux session?",closeChooserDescription:"This will stop the session and every process inside it. This cannot be undone.",destroySession:"Destroy session",confirmDestroySession:"Confirm destroy",destroySessionHint:"Stop the tmux session and every process inside it.",dragToClose:"Drag here to close",releaseToClose:"Release to confirm"},agent:{aiRunning:"AI running",needsReview:"Needs review",finishedReview:"AI finished — needs review",aiWaiting:"AI waiting",copyMode:"Copy mode",jumpToNext:"Jump to next session needing attention",jumpToNextRunning:"Jump to next running session",selectRunningSession:"Select a running session",runningSessionGestureHint:"Tap to cycle · swipe sideways to select · hold to drag",currentSession:"Current"},connection:{reconnecting:"Reconnecting…"},desktopServices:{switchService:"Switch Termdock service",openServices:"Open services",idle:"Idle",manageServices:"Manage services and names"},terminal:{input:"Terminal input",error:"Error",dropFilesToPastePaths:"Drop files to paste paths",loading:"Loading terminal…",initializing:"Initializing terminal engine…",failedToLoad:"Failed to load terminal",unknownError:"An unknown error occurred",componentFailed:"Terminal component failed to load",paste:"Paste",copied:"Copied",copyFailed:"Copy failed",longPressSelectsText:"Long press selects text",longPressSendsArrows:"Long press sends arrow keys",switchLongPressToArrows:"Switch long press to arrow keys",switchLongPressToCopy:"Switch long press to copy selection"},quota:{title:"Subscription Quota",noProviders:"No subscription providers detected.",noProvidersHint:"Quota tracking becomes available when you use AI coding agents with API keys or OAuth login.",exhausted:"Exhausted",left:({n:t})=>`${t} left`,updated:({time:t})=>`Updated ${t}`,refresh:"Refresh",close:"Close"},errorBoundary:{title:"Something went wrong",unexpected:"An unexpected error occurred",retry:"Try Again",copyDetails:"Copy error details",copied:"Copied",copyFailed:"Copy failed"},error:{type:{network:"Network error",session:"Session error",terminal:"Terminal error",auth:"Authentication error",validation:"Validation error",unknown:"Unknown error"},severity:{low:"Notice: ",medium:"Warning: ",high:"Error: ",critical:"Critical: "},suggestion:{networkCheck:"Check your network connection",networkRetry:"Try reconnecting",networkProxy:"Check proxy settings",networkWait:"Wait for the network to recover",sessionRecreate:"Recreate the session",sessionServer:"Check the server status",sessionCache:"Clear your browser cache",terminalRestart:"Restart the terminal",terminalConfig:"Check the terminal configuration",terminalClear:"Clear the terminal output",authRelogin:"Sign in again",authCredentials:"Check your credentials",authAdmin:"Contact the administrator",validationFormat:"Check the input format",validationParams:"Verify your parameters",validationDocs:"See the documentation",unknownReload:"Reload the page",unknownApp:"Restart the app",unknownSupport:"Contact support"}}},Y2={app:{name:"Termdock"},common:{cancel:"取消",close:"关闭",save:"保存",reset:"重置",loading:"加载中…",error:"错误",retry:"重试",refresh:"刷新",search:"搜索",clear:"清除",delete:"删除",on:"开",off:"关",back:"返回",copy:"复制",decrease:"减少",increase:"增加",use:"使用",previous:"上一个",next:"下一个"},login:{prompt:"termdock login",placeholder:"请输入密码",placeholderBlocked:({s:t})=>`请稍候 ${t}s`,submit:"登录",invalidPassword:"密码错误",failed:"登录失败"},sidebar:{sessions:"会话",noSessions:"暂无打开的会话。",noMatchingSessions:"没有匹配的会话。",toggleSearch:"切换搜索",settings:"设置",moreActions:"更多操作",subscriptionQuota:"订阅额度",pinSidebar:"常驻边栏",unpinSidebar:"取消常驻",runningSessionButton:"运行中会话按钮",runningSessionButtonHint:"轻点循环,横向滑动选择,长按拖动",updateAvailable:({version:t})=>`Termdock ${t} 可用`,updateInstalling:"正在后台安装,不会中断当前服务。",updateReady:"更新已安装,确认后将重启服务。",updateRestart:"重启并完成更新",updateRestartConfirm:({version:t})=>`确认重启 Termdock 并切换到 ${t}?当前网页会短暂重连,会话不会被关闭。`,updateRestarting:"正在重启,网页将自动重连…",updateFailed:"自动安装失败,提醒会保留。",updateRetry:"重新尝试",filterSessions:"过滤会话",clearSearch:"清除搜索",groupByFolder:"按文件夹分组",groupByFolderTitle:"按工作目录把会话归组折叠;与拖拽排序互斥。",ungrouped:"其他",needsAttention:"待处理",waitingForYou:"等你操作",completedUnread:"完成待查看",closeSession:({name:t})=>`关闭 ${t}`,newShell:"Shell",newTmux:"Tmux",newTmuxDisabled:"服务端未安装 tmux",confirmNewShell:"创建 Shell?",confirmNewTmux:"创建 Tmux?",newSession:"新建 Terminal",newSessionWithAgent:({agent:t})=>`新建 ${t}`,moreLaunchOptions:"更多启动选项",recoverableSessions:"可恢复会话",refreshRecoverableSessions:"刷新可恢复会话",restoreRecoverableSession:({name:t})=>`恢复 ${t}`,restoringRecoverableSession:"恢复中…",restore:"恢复",newSessionAdvanced:"快速启动 Agent",newSessionComposerTitle:"开始新会话",newSessionHint:"选好运行方式和目录后再启动",launchSessionWith:({name:t})=>`启动 ${t}`,setNewSessionDefault:({name:t})=>`将 ${t} 设为默认`,currentNewSessionDefault:({name:t})=>`${t} 是当前默认`,currentDefaultAgent:({name:t})=>`当前默认:${t}`,defaultAgent:"默认",makeDefault:"设为默认",sessionMode:"运行方式",tmuxKeepsRunning:"断开后继续运行",resumeHistory:"最近会话",resumeHistoryCount:({n:t})=>`已保存 ${t} 条`,resumeHistoryLoading:"正在载入最近的 Agent 会话…",resumeHistoryAction:({title:t})=>`恢复 ${t}`,resumeHistoryRemove:({title:t})=>`从最近会话中移除 ${t}`,resumeHistoryLoadFailed:"无法载入最近的 Agent 会话。",resumeHistoryFailed:"无法准备恢复该 Agent 会话。",resumeHistoryRemoveFailed:"无法从历史中移除该会话。",workingDirectory:"工作目录",directoryPlaceholder:"输入目录路径",browseDirectories:"浏览目录",hideDirectoryBrowser:"收起目录",chooseDirectory:"选择工作目录",directoryPickerHint:"进入文件夹,确认后才会更改工作目录。",useThisFolder:"使用此目录",recentDirectories:"最近使用的目录",startCommand:"启动命令",customCommand:"其他命令",commandPlaceholder:"可选,例如 codex",detectAgents:"重新检测 Agent",savePreset:"保存为预设",createAndRun:"创建并运行",createSession:"创建 Terminal",openLeftSidebar:"打开左侧边栏",openRightSidebar:"打开右侧边栏",closeSidebar:"关闭边栏"},rightSidebar:{workspace:"工作区",currentProject:"项目",browsingLocation:"浏览中",parentFolder:"上一级目录",backToProjectRoot:"回到当前项目",refreshFiles:"刷新当前目录",resizeFileTree:"拖动调整文件目录宽度",pinCurrentFolder:"固定当前目录到这个项目",unpinCurrentFolder:"取消固定当前目录",showHiddenFiles:"显示隐藏文件",hideHiddenFiles:"不显示隐藏文件",insertCurrentFolder:"引用当前目录",insertCurrentFolderShort:"引用",pinnedFolders:"固定",unpinFolder:({name:t})=>`取消固定 ${t}`,fileWatchUnavailable:({message:t})=>`文件监听不可用:${t}。可点击手动刷新。`,browsingOutsideProject:"正在浏览当前项目外目录",browsingOutsideProjectHint:"Git 和改动仍使用当前项目;这里引用的文件会按外部路径插入。",toggleSearch:"切换搜索",refreshGit:"刷新 Git 状态",gitLastUpdated:({time:t})=>`上次更新:${t}`,close:"关闭",filterChanges:"过滤改动或文件",searchPlaceholderContent:"在文件内容中搜索…",searchModeName:"文件",searchModeContent:"内容",clearSearch:"清除搜索",searchScope:"范围",searchScopePlaceholder:"相对目录或绝对路径",resetSearchScope:"恢复搜索当前目录",searchOptions:"搜索选项",searchExclude:"排除",searchExcludePlaceholder:"dist/**, *.lock",clearSearchExclude:"清空排除规则",contentSearchOptions:"内容搜索选项",matchCase:"区分大小写",matchWholeWord:"全词",useRegex:"正则",insertGitContext:"把当前 Git 信息插入 Terminal",copyGitContext:"复制 Git 信息",insertChangeAuditPrompt:"解释当前改动",insertChangeAuditPromptTitle:"把更改审计提示词插入当前会话",changeAuditShort:"解释当前改动",changeAuditLoading:"正在加载 hunk 解释…",changeAuditLoaded:({count:t})=>`已加载 ${t} 条 hunk 解释`,changeAuditLoadedAt:({time:t})=>`最近生成 ${t}`,changeAuditRegenerate:"重新生成",changeAuditRefreshStale:"补充失效",changeAuditRefreshStaleTitle:"为已失效的 hunk 解释插入补充生成提示词",clearChangeAudit:"清理",clearChangeAuditTitle:"清理当前仓库的 hunk 解释",changeAuditClearFailed:({message:t})=>`清理 hunk 解释失败:${t}`,changeAuditScopeAll:"全部仓库",changeAuditScopeLabel:"解释范围",branchAuditTitle:"分支解释",branchAuditShort:"解释分支改动",branchAuditBaseLabel:"基线分支",branchAuditBasePlaceholder:"基线分支,例如 master",branchAuditBaseSearchPlaceholder:"搜索基线分支",branchAuditBaseEmpty:"没有可选分支,可直接输入分支名",branchAuditGenerate:"生成解释",branchAuditRegenerate:"重新生成",branchAuditGenerateTitle:"生成当前分支相对于基线分支的解释提示词",branchAuditViewDiff:"查看对比",branchAuditViewDiffTitle:"查看目标分支相对于基线分支的改动",branchAuditDiffLoading:"正在加载分支对比…",branchAuditDiffEmpty:"当前分支相对于基线分支暂无改动。",branchAuditMissingBase:({repo:t})=>`${t} 未设置基线分支`,branchAuditRefreshDiff:"刷新对比",branchAuditRefreshStale:"补充失效",branchAuditRefreshStaleTitle:"为已失效的分支解释插入补充生成提示词",branchAuditClearTitle:"清理当前分支解释",branchAuditClearFailed:({message:t})=>`清理分支解释失败:${t}`,branchAuditCommitCount:({count:t})=>`${t} 个提交`,branchAuditFileCount:({count:t})=>`${t} 个文件`,branchAuditTruncated:"diff 已截断",branchAuditCurrent:"已保存解释",branchAuditStale:"解释已失效",branchAuditEmpty:"暂无分支解释。生成后会持久化保存,可随时回来查看。",branchAuditView:"查看解释",branchAuditSaved:({count:t})=>`已保存 ${t} 条 hunk 解释`,branchAuditGeneratedAt:({time:t})=>`生成于 ${t}`,insertPreset:({label:t})=>`插入:${t}`,tabChanges:"改动",tabGit:"Git",tabFiles:"文件",inserted:"已插入",copied:"已复制",toggleContextDraft:"切换上下文草稿",contextDraftTitle:"上下文草稿",contextDraftHint:"启用后,引用会追加到这里;可以继续浏览、补写描述,最后一次插入。",contextDraftPlaceholder:"在这里组织长提示词,继续点击侧栏中的引用来追加上下文…",contextDraftCollapse:"收起上下文草稿",contextDraftExpand:"展开上下文草稿",contextDraftDisable:"停用上下文草稿",contextDraftClear:"清空草稿",contextDraftInsert:"插入",contextDraftInsertAndSend:"插入并发送",contextDraftInserted:"已插入",contextDraftSent:"已发送",contextDraftSend:"发送草稿",contextDraftAppended:"已追加引用",contextDraftResize:"拖动调整高度,双击恢复默认",contextDraftAutoCollapseAfterSend:"插入/发送后收起",contextDraftInsertFailed:"终端未连接,草稿已保留",contextDraftCharacterCount:({count:t})=>`${t} 字`,selectFilePrompt:"选择文件以预览内容",backToFileList:"返回文件列表",backToPreviousPreview:"返回来源文档",insertLineRef:({lineLabel:t})=>`引用${t}`,insertFileRef:"引用",copyFileRef:"复制文件引用",findInFile:"在文件内查找",findInFilePlaceholder:"在当前文件中查找…",previousSearchMatch:"上一个匹配项",nextSearchMatch:"下一个匹配项",closeFileSearch:"关闭文件搜索",downloadFile:"下载文件",downloadFailed:"下载失败",uploadFile:"上传文件",uploadFiles:"上传文件",insertLocalFile:"插入本地文件",insertLocalImage:"插入本地图片",layoutMode:"显示模式",layoutModeAuto:"自动",layoutModeNarrow:"窄版",layoutModeWide:"宽版",dropToUpload:"拖放文件以上传",uploading:"上传中…",uploadSuccess:({count:t})=>`已上传 ${t} 个文件`,uploadFailed:"上传失败",binaryPreviewHint:"二进制文件无法预览,请使用上方下载按钮保存到本地",selectedLineHint:({lineLabel:t})=>`已选 ${t} · 点下方「引用」按钮插入`,multiLineHint:"多行引用:先点起始行,再点结束行",loadingImage:"正在加载图片…",imagePreviewHint:"双指捏合或 ⌘/Ctrl + 滚动缩放 · 双击还原",imageLoadFailed:"图片预览加载失败",loadingVideo:"正在加载视频…",videoPreviewHint:"点击播放 · 长按 2× · 可拖动进度条",videoLoadFailed:"视频预览加载失败",videoUnsupported:"当前浏览器不支持该视频格式",videoPlay:"播放",videoPause:"暂停",videoLongPressSpeed:"长按 2× 播放",videoRotate:"顺时针旋转 90°",videoFullscreenEnter:"全屏播放",videoFullscreenExit:"退出全屏",model3dLoading:"正在加载 3D 模型…",model3dExplode:"爆炸展开",model3dExplodeAxis:"展开方向(查看器坐标)",model3dExplodeAmount:"展开程度",model3dHome:"回正并看全",model3dFit:"看全可见零件",model3dFront:"正视图",model3dTop:"俯视图",model3dRight:"右视图",model3dAssemble:"恢复装配",model3dExplodedNotice:"爆炸展示 · 尺寸与引用仍为原始装配坐标",model3dLoadFailed:"3D 模型预览加载失败",model3dTimeout:"3D 模型传输超时,请检查连接后重试。",model3dDimensions:({dims:t})=>`尺寸: ${t}`,model3dHintMouse:"拖拽旋转 / 双指平移 / 捏合或滚轮缩放",model3dHintTouch:"单指旋转 / 双指缩放平移",model3dFullscreenEnter:"全屏查看",model3dFullscreenExit:"退出全屏",model3dBgToLight:"切换为白底",model3dBgToDark:"切换为黑底",model3dRefresh:"重新加载模型",model3dClipToggle:"切面查看",model3dClipPosition:"切面位置",model3dClipFlip:"反转切面方向",model3dFeatureToggle:"特征标注",model3dFeatureStatus:({total:t,positioned:e})=>`特征: ${t} 个 · 已定位 ${e}`,model3dFeatureInsert:"引用",model3dGlossaryToggle:"建模名词说明",model3dPickToggle:"选择零件 / 引用",model3dPickHint:"点选零件后可临时隐藏,或引用所选位置",model3dHidePart:"隐藏零件",model3dShowAllParts:({count:t})=>`显示全部(${t})`,model3dParts:"零件",model3dCloseParts:"关闭零件列表",model3dSearchParts:"查找零件",model3dClearPartSearch:"清空零件搜索",model3dHiddenParts:({count:t})=>`已隐藏 ${t}`,model3dShowNamedPart:({name:t})=>`显示 ${t}`,model3dHideNamedPart:({name:t})=>`隐藏 ${t}`,model3dIsolateNamedPart:({name:t})=>`只看 ${t}`,model3dIsolatePart:"只看此件",model3dShowPart:"显示零件",model3dNoParts:"没有匹配的零件",model3dUndoVisibility:"撤销",model3dClearSelection:"取消选择",model3dAllPartsVisible:"全部可见",model3dInspectHint:"单指旋转 · 双指缩放平移 · 双击局部放大,双击空白看全",model3dUnnamedPart:({index:t})=>`零件 ${t}`,model3dCanvas:"三维模型",model3dMore:"更多模型选项",edaLoading:"正在渲染 KiCad 文件…",reviewTargetChanged:"当前会话已切换,请回到创建这条引用的会话后再插入。",reviewReference:"审阅引用",reviewReferenceHint:"补充意见后插入,不会自动发送。",reviewSnapshot:"选中位置的视图快照",reviewCapturing:"正在截取当前视图…",reviewIncludeImage:"附带截图(临时保存在当前服务器)",reviewCaptureFailed:"截图未成功,仍可插入定位信息。",reviewNote:"你的意见(可选)",reviewNotePlaceholder:"例如:这里太厚了,能否减薄?",reviewDetails:"查看定位信息和引用原文",reviewUploading:"正在准备引用…",reviewAddToDraft:"加入引用草稿",reviewInsert:"插入引用",reviewUploadFailed:"引用准备失败,意见已保留。请重试,或取消附带截图后只插入文字。",edaLoadFailed:"KiCad 预览渲染失败",edaTimeout:"KiCad 预览生成或传输超时,请重试。",edaRefresh:"重新渲染",edaPickHint:"点击原理图或 PCB 上的问题位置,生成电子标注",edaPickedPosition:({x:t,y:e})=>`已选位置 ${t}%, ${e}%`,edaPickedBoardPosition:({x:t,y:e,object:r})=>`板坐标 ${t}, ${e} mm · ${r}`,edaInspecting:"正在读取板坐标和附近对象…",edaNoNearbyObject:"附近无对象",edaInsertAnnotation:"引用电子标注",csvUnnamedColumn:({index:t})=>`第 ${t} 列`,csvSelectedCell:({row:t,column:e})=>`已选第 ${t} 行 · ${e}`,csvPickHint:({rows:t,columns:e})=>`${t} 条记录 · ${e} 列,点击单元格引用`,csvInsertAnnotation:"引用表格标注",csvTablePreview:"表格预览:点击单元格后可引用完整记录",kicadLocalStateNotice:"这是本机界面状态文件,不参与原理图、PCB 或生产审查。",kicadShowRawJson:"查看原始 JSON",kicadProjectPickHint:"点击一项配置后可插入引用",kicadInsertSetting:"引用配置",markdownPreview:"预览",markdownSource:"源码",markdownPreviewHint:"点按行/段落引用,再点一行扩选;拖左侧竖条可连续框选",htmlPreview:"预览",htmlSource:"源码",htmlPreviewHint:"HTML 沙箱 iframe 预览,脚本受限",htmlFullscreenEnter:"全屏预览",htmlFullscreenExit:"退出全屏预览",markdownOutline:"Markdown 目录",markdownOutlineShort:"目录",closeMarkdownOutline:"关闭目录",changedFromPath:({path:t})=>`来自 ${t}`,selectedLineFooter:({lineLabel:t})=>`已选 ${t}`,clearSelection:"清除",allChanges:"全部改动",backToChangeList:"返回目录",allRepositories:"全部仓库",allRepositoriesShort:"全部",repositories:"仓库",gitRepositorySectionTitle:"操作仓库",gitRepositoryLabel:"仓库",gitRepositoryPlaceholder:"选择仓库",gitRepositorySearchPlaceholder:"搜索仓库",gitRepositoryEmpty:"没有可操作的仓库",selectRepositoryForGitActions:"请选择一个仓库后再执行 Git 操作",selectRepositoryForDiff:"选择一个仓库或文件查看 diff",repoChangedCount:({count:t})=>`${t} 个改动`,repoStagedCount:({count:t})=>`${t} 已暂存`,noChanges:"没有改动",noMatchingChanges:"没有匹配的改动",loadingGitChanges:"正在加载 Git 改动…",loadingGitChangesSlow:"仓库较大时可能需要几秒。",refreshingGitChanges:"正在刷新 Git 改动…",gitChangesLoadFailed:"无法加载 Git 改动",retryGitChanges:"重试",insertThisFile:"把这个文件引用插入 Terminal",viewDiff:"查看 diff",diffViewMode:"改动文件展示方式",diffViewModeList:"平铺列表",diffViewModeTree:"目录结构",diffViewModeAi:"AI 导览",changeWalkthroughEmpty:"暂无 AI 导览。生成解释后会在这里展示总览、链路和验证点。",gitInfo:"Git 信息",wrapLongLines:"长行换行",wrapOn:"已换行",wrapOff:"原始",horizontalScrollHint:"左右滑动查看完整 diff",stageFile:"暂存",stageAll:"全部暂存",unstageFile:"取消暂存",stashFile:"贮藏",stashAll:"全部贮藏",restoreFile:"丢弃",gitQuickActions:"Git 操作",gitUnavailable:"当前目录不是 Git 仓库",branchSectionTitle:"当前分支",currentBranchLabel:"分支",switchBranchPlaceholder:"选择分支",switchBranchSearchPlaceholder:"搜索本地分支",switchNoBranches:"没有本地分支",switchBranch:"切换",noStagedChangesShort:"无暂存",stagedCount:({count:t})=>`已暂存 ${t}`,stagedCountShort:({count:t})=>`已暂存 ${t}`,commitSectionTitle:"提交",commitReadyHint:({count:t})=>`${t} 个文件已准备提交`,commitMessagePlaceholder:"提交信息",commitChanges:"提交",commitNeedsStaged:"请先暂存要提交的改动",recentCommitsTitle:"近期提交",recentCommitsSearchPlaceholder:"搜索提交 hash 或信息",recentCommitsLoadMore:"加载更多提交",recentCommitsEmpty:"暂无提交历史",pushSectionTitle:"同步远端",pushRemoteLabel:"Remote",pushRemotePlaceholder:"origin",pushRemoteSearchPlaceholder:"搜索 Remote",pushNoRemotes:"没有 Remote",pushBranchLabel:"目标分支",pushBranchPlaceholder:({branch:t})=>`${t}`,pushBranchSearchPlaceholder:"搜索分支",pushNoBranches:"没有分支",pushUpstreamBadge:"upstream",pushCurrentBranchBadge:"当前",pushNoUpstream:"当前分支未设置 upstream",pushUpToDate:"与远端同步",pushAheadCount:({count:t})=>`领先远端 ${t} 个提交`,pushBehindCount:({count:t})=>`落后远端 ${t} 个提交`,pushDivergedCount:({ahead:t,behind:e})=>`领先 ${t} / 落后 ${e} 个提交`,pullChanges:"拉取",pushChanges:"推送",gitActionRunning:"执行中…",gitActionFailed:({message:t})=>`Git 操作失败:${t}`,confirmRestoreTitle:"确认丢弃改动",confirmRestoreDescription:({path:t})=>`将丢弃 ${t} 的未暂存改动,此操作不可从 Termdock 恢复。`,confirmRestorePhrase:"丢弃改动",confirmRestorePlaceholder:"输入“丢弃改动”确认",confirmStashAllTitle:"确认贮藏全部改动",confirmStashAllDescription:"会把当前工作区改动(包含未跟踪文件)移入贮藏。",confirmAction:"确认",renderingHtml:"正在渲染 HTML…",footnotes:"脚注",backToFootnote:({index:t})=>`返回脚注 ${t}`,openMermaidDiagram:"打开 Mermaid 图表",mermaidDiagram:"Mermaid 图表",renderingDiagram:"正在渲染图表…",markdownImage:"Markdown 图片",image:"图片",previousImage:"上一张图片",nextImage:"下一张图片",closeImagePreview:"关闭图片预览",emptyFile:"空文件。",insertReference:({reference:t})=>`插入引用:${t}`,copyReference:({reference:t})=>`复制引用:${t}`,byteCount:({count:t})=>`${t} 字节`,previewTruncated:"预览已截断至 1 MB",branchCandidatesLoading:"正在加载分支候选…",includeUncommitted:"包含本地未提交改动",includeUncommittedHint:"查看对比或生成解释时纳入工作区和未跟踪文件的 diff",missingBaseReposSkipped:({repositories:t})=>`未设置基线的仓库会跳过:${t}`,localBranch:"本地",remoteBranch:"远端"},fileTree:{insertRef:"引用",insertRefTitle:"Insert file reference into active terminal",openDirRoot:"进入",openDirRootTitle:"把这个目录作为当前浏览根目录",openInFileBrowser:"在 Finder 中显示",openInFileBrowserTitle:"在系统文件浏览器中打开这个项目",openInFileBrowserFailed:"打开文件浏览器失败",moreDirActions:"更多目录操作",searchFromDir:"从这里搜索",searchFromDirTitle:"只搜索这个目录及其子目录",pinDir:"固定",pinDirTitle:"固定这个目录到当前项目",unpinDir:"已固定",unpinDirTitle:"取消固定这个目录",pinFileTitle:"固定这个文件到当前项目",unpinFileTitle:"取消固定这个文件",pinFile:"固定",unpinFile:"已固定",moreFileActions:"更多文件操作",deleteFile:"删除文件",deleteFileConfirm:({name:t})=>`确认删除“${t}”?此操作无法撤销。`,deleteFileFailed:({message:t})=>`删除文件失败:${t}`,noWorkingDir:"未检测到工作目录。",emptyDir:"空目录。",noMatchingFiles:"没有匹配的文件。",searching:"正在搜索文件…",searchingWithCount:({count:t})=>`搜索中…已找到 ${t} 项`,searchResults:({count:t})=>`${t} 个结果`,searchScope:"搜索范围",searchTruncatedHint:({count:t})=>`降级搜索已扫描大量目录并在找到 ${t} 项后停止。安装 ripgrep 或输入更精确关键词可获得完整结果。`,searchStillRunning:"搜索仍在进行,更多结果会自动出现。",showingSearchResults:({shown:t,total:e})=>`正在展示 ${t}/${e}`,loadMoreSearchResults:({shown:t,total:e})=>`查看更多(${t}/${e})`,contentMatchesCount:({count:t})=>`${t} 个文件命中`,moreMatches:({count:t})=>`还有 ${t} 处匹配`,noContentMatches:"文件内容中没有匹配。",contentSearchNeedsRipgrep:"内容搜索需要 ripgrep(rg),请在服务端安装后再在文件内搜索。",truncatedHint:"仅展示前 1000 项。使用搜索或打开更小的文件夹以获得更好性能。",dropToUploadHere:"上传到这里",symbolicLink:"符号链接",sortByModified:"按最近修改排序",sortByName:"按名称排序",sortedByModified:"已按最近修改排序"},diffViewer:{noFileChanges:"此文件无改动。",noUnstagedChanges:"没有未暂存的改动。",emptyHint:"做一些改动,或从远程拉取。",loading:"正在加载 diff…",insertAllDiff:"把当前 diff 内容作为上下文插入 Terminal",insertFileDiff:"引用这个文件的 diff",insertHunkDiff:"引用这段 diff hunk",insertHunkShort:"引用",insertFileShort:"引用",insertAllShort:"全部",stageHunk:"暂存",stageHunkTitle:"只把这个 hunk 加入暂存区 (git apply --cached)",revertHunk:"撤销",revertHunkTitle:"撤销这个 hunk 的工作区改动(不可恢复)",revertHunkConfirm:"确认撤销?",hunkActionApplying:"应用中…",hunkActionUnavailable:"无法为这个 hunk 构造补丁",hunkActionFailed:({message:t})=>`操作失败:${t}。如改动已变化,请刷新后重试。`,auditExplanation:"更改意义",auditStale:"解释已失效",auditClear:"清除解释",auditGeneratedAt:({time:t})=>`生成于 ${t}`,allDiffLabel:"全部 diff",allChangesLabel:"全部改动",workingTree:"工作区改动",allUnstaged:"所有未暂存改动",binaryOrEmpty:"没有可显示的文本改动。",noFinalNewline:"文件末尾没有换行符",noHunks:"没有 hunk",hunkOutline:"Hunk 列表",expandHunkRail:"显示 hunk 列表",collapseHunkRail:"隐藏 hunk 列表",prevHunk:"上一个 hunk",nextHunk:"下一个 hunk",prevFile:"上一个",nextFile:"下一个",expandFile:"展开文件",collapseFile:"折叠文件",expandAll:"全部展开",collapseAll:"全部折叠",collapseHunk:"折叠 hunk",useBracketKeysHint:"按 [ / ] 在 hunk 之间跳转",unified:"统一",unifiedMode:"统一视图",split:"分屏",splitMode:"左右分屏视图",moreActions:"更多操作",view:"视图",loadingPreviousFile:"正在加载上一个文件…",loadingNextFile:"正在加载下一个文件…",resizeNavigation:"调整 diff 导航宽度",focusPathHint:"点击标注聚焦路径",whitespace:"空白",whitespaceDefault:"默认",whitespaceTrim:"忽略行尾空白",whitespaceIgnore:"忽略所有空白",whitespaceIgnoreBlankLines:"忽略空行",context:"上下文",contextLines:({count:t})=>`${t} 行`,contextAll:"全部"},settings:{title:"设置",font:"字体",render:"渲染",theme:"主题",darkTheme:"深色",lightTheme:"浅色",newTab:"新标签",debug:"调试",noSleep:"常亮",noSleepUnavailable:"无网络 — 已禁用",updateTitle:"Termdock 更新",updateRuntimeTitle:"CLI 与服务 Runtime",updateHint:"手动检查会立即下载并安装新版本;服务只会在你确认后重启。",updateCheck:"检查更新",updateCheckAgain:"再次检查",updateChecking:"正在检查 npm 上的最新版本…",updateCheckingShort:"检查中…",updateInstallingShort:"安装中…",updateCurrent:"Termdock 已是最新版本。",desktopUpdateTitle:"macOS 桌面版",desktopUpdateHint:"手动检查 GitHub 发布的签名桌面版本。",desktopUpdateUnsupported:"仅签名安装的 macOS 桌面版支持应用内更新。",desktopUpdateChecking:"正在检查桌面版更新…",desktopUpdateCurrent:"桌面版已是最新版本。",desktopUpdateDownloading:"发现新版本,正在后台下载…",desktopUpdateReady:"桌面版更新已下载,可以重启安装。",desktopUpdateInstalling:"正在重启并安装桌面版更新…",desktopUpdateCheck:"检查桌面版",desktopUpdateCheckAgain:"再次检查",desktopUpdateRestart:"重启并安装",desktopUpdateRestartConfirm:"重启 Termdock 并安装已下载的桌面版更新?终端服务和 tmux 会话不会被停止。",notifications:"通知",notificationsTitle:"通知设置",notificationsHint:"Termdock 在后台时,AI 任务结束后发送系统通知。",notificationsPageHint:"选择哪些 Termdock 事件可以发送系统通知。总开关负责浏览器权限和投递,事件开关决定具体哪些内容提醒你。",notificationsMaster:"系统通知",notificationsMasterHint:"允许 Termdock 在隐藏或作为 PWA 安装运行时发送通知。",notificationsIOSInstallHint:"在 iPhone 或 iPad 上,请先将 Termdock 添加到主屏幕,再开启通知。",notificationsPermission:"权限",notificationsPermissionSystem:"由 macOS 管理",notificationsTest:"发送测试",notificationsTestChecking:"正在等待 macOS 确认投递…",notificationsTestDelivered:"已投递到通知中心;若没有横幅,请检查提醒样式和专注模式。",notificationsTestFailed:"macOS 未投递通知,请在系统设置中允许 Termdock 通知。",notificationsOpenSystemSettings:"打开系统通知设置",notificationsAlertStyle:"提醒方式",notificationsAlertStyleHint:"最终是否横幅弹出仍由浏览器和 Android 系统决定。Termdock 只能请求静默、默认或持续显示等通知选项。",notificationsStyleNormal:"默认",notificationsStyleNormalHint:"允许时声音/震动",notificationsStyleQuiet:"静默",notificationsStyleQuietHint:"仅状态栏,无声音",notificationsStylePersistent:"持续",notificationsStylePersistentHint:"保留到手动关闭",notificationsEvents:"事件",notificationsAiFinished:"AI 任务结束",notificationsAiFinishedHint:"当 Termdock 在后台时,AI agent 停止后发送通知。",notificationsSessionExited:"终端退出",notificationsSessionExitedHint:"终端进程自行结束时发送通知(主动关闭不触发,经 Web Push 投递)。",notificationsFutureHint:"后续可以在这里继续增加更多通知类型,不需要改变顶层设置布局。",notificationsOffSummary:"系统通知已关闭",notificationsAiOnSummary:"AI 任务结束通知已开启",notificationsExitOnSummary:"终端退出通知已开启",notificationsBothOnSummary:"AI 任务结束、终端退出通知已开启",notificationsNoEventsSummary:"暂无开启的通知事件",notificationsDenied:"浏览器通知权限已被阻止,请在站点设置中开启。",notificationsUnsupported:"通知需要安全上下文和 Service Worker 支持。",notificationsTestBody:"通知已开启。后台 AI 任务结束后会提醒你。",shell:"Shell",tmux:"Tmux",auto:"自动",webgl:"WebGL",canvas:"内置",tmuxServer:"Tmux 服务",tmuxUnavailable:"不可用",noTmuxSessions:"服务端没有 tmux 会话。",installTmuxHint:"请在服务端安装 tmux 后启用。",refresh:"刷新",attached:"已连接",restorable:"可恢复",attach:"连接",attaching:"连接中…",destroy:"销毁",sessions:({n:t})=>`${t} 个会话`,windows:({n:t})=>`${t} 个窗口`,keyboardToolbar:"键盘工具栏",aiAgentDetection:"AI 代理检测",signOut:"退出登录",language:"语言",programNamePlaceholder:"程序名(如 claude)",patternPlaceholder:"正则表达式(如 Thinking|Generating)",statusPlaceholder:"状态",addProgram:"添加程序",addPattern:"添加规则",resetDefaults:"恢复默认",invalidRegex:"无效的正则",removeProgram:"移除程序",removeRule:"移除规则",keepLabel:"保持",customColor:"自定义颜色",tabIndicator:"标签指示器样式",toolbarPresets:"工具栏预设",detectionRules:"检测规则",agentHooksHint:"安装 hooks 后,agent 会主动上报状态:回合进行中(绿)、等你授权/回答(黄)、回合完成(对勾),并在等待你输入时推送通知。hooks 全局安装但只在 termdock 的终端里生效。",agentHooksInstall:"安装",agentHooksInstalled:"已安装",agentHooksOutdated:"需更新",agentHooksNeedsApproval:"待授权",agentHooksApprovalHint:"在 Codex 中输入 /hooks,批准 Termdock Hook 后生效",agentHooksNotInstalled:"未安装",agentHooksUninstall:"卸载",agentHooksReinstall:"重新安装",agentHooksDevMode:"开发模式:hooks 指向 TS 源码,需要构建后的版本才能生效",agentHooksTarget:"写入",agentAutoRename:"自动更新会话标题",agentAutoRenameHint:"Agent 完成一轮后,根据近期内容更新标题。默认全部关闭,手工命名的会话不会被覆盖;启用外部插件标题后才会执行其 CLI。",agentAutoRenameToggle:"切换此 Agent 的自动标题",agentAutoRenameShort:"自动标题",agentAutoRenameNamer:"起名 Agent",agentAutoRenameFollow:"跟随当前会话",agentAutoRenameModelsFromCli:"模型由本机 CLI 动态提供",agentAutoRenameRefreshModels:"重新查询 CLI 模型",agentAutoRenameCliDefault:"CLI 默认模型",agentAutoRenameAutomatic:"自动选择",agentAutoRenameNoCli:"未检测到可用于起名的 CLI",agentAutoRenameAdvanced:"高级标题偏好",agentAutoRenamePreference:"补充偏好",agentAutoRenamePreferenceHint:"可选。仅补充你对标题风格或重点的偏好;Termdock 的默认起名规则仍会保留。离开输入框时自动保存。",agentAutoRenamePreferencePlaceholder:"例如:突出用户收益;优先使用动宾结构;避免技术术语",agentAutoRenamePayloadLimit:"用户消息上下文上限(字符)",agentAutoRenamePayloadLimitHint:"保留 prompt-submit 原始 payload 的总字符数,默认 12000,可设置 1000–64000。",agentPlugins:"Agent 插件",agentPluginAdd:"添加插件",agentPluginHint:"从 HTTPS Git 仓库或本地目录安装;请先审查来源。Hooks 和可执行的标题 CLI 均需用户分别启用。",agentPluginCreate:"创建插件",agentPluginDelete:"删除插件",agentPluginInvalid:"插件配置无效",agentPluginCopyAiPrompt:"复制 AI 修复提示",agentPluginCopied:"已复制",agentPluginSourcePlaceholder:"https://github.com/user/agent-plugin 或本地目录",agentPluginInstallPackage:"安装插件",agentPluginAdvancedManifest:"高级:直接粘贴 manifest.json",agentPluginUpdateAvailable:"有更新",agentPluginManualSource:"手动 manifest",agentPluginUpdate:"更新",agentPluginCheck:"检查更新",agentPluginDoctor:"诊断",agentPluginDoctorHint:"显式运行插件模型探测,不会调用标题生成",agentPluginDoctorStatusOk:"标题与模型能力正常",agentPluginDoctorStatusMissing:"未声明 titleNamer",agentPluginDoctorStatusCliDefault:"标题可用,使用 CLI 默认模型",agentPluginDoctorStatusNoModels:"没有可用的模型数据",agentPluginDoctorStatusFailed:"模型探测失败",agentPluginDoctorModels:"个可用模型",agentPluginDoctorAutomatic:"自动选择",agentPluginDoctorCliDefault:"未指定模型时使用 Agent CLI 默认模型",agentAutoRenameInterval:"重新判断间隔",agentAutoRenameMinutes:"分钟",mobileKeyboard:"移动键盘",saving:"保存中…",rulesHint:"配置正则表达式来识别 AI 工具在终端标签中的状态。每条规则可独立设置标签、颜色、图标样式以及输出静默后指示器保留的时长。停止后若你未查看该标签,标签会保留一个黄色待查看提示。",programsHelp:"支持在一个配置中匹配多个程序,用英文逗号分隔。",programLabelResolution:"程序名识别",rawCommandMapping:"原始命令映射",rawCommandMappingHint:"以下规则将原始命令行映射为标签显示名。用户规则优先于内置规则。",genericProgramNames:"通用程序名",genericProgramNamesHint:"触发 ps 深度识别(如 node, python)",wrapperScriptNames:"包装脚本名",wrapperScriptNamesHint:"CLI 包装器,启动其他工具(如 aiden, npx)",shellNamesConfig:"Shell 名称",shellNamesHint:"从标签显示中过滤(如 bash, zsh)",addTag:"+ 添加",customRules:"自定义规则",addRule:"添加规则",localAccess:"本地访问",localAccessHint:"手机信任本地 CA 后,可通过这个局域网地址访问。请先在手机上打开「手机引导」地址下载 CA 证书。",resetAutoName:"恢复自动",onboardingUrl:"手机引导",httpsActive:"HTTPS 已启用",httpsInactive:"HTTPS 未启用",caMissing:"未配置 CA 下载",closeSettings:"关闭设置",desktopTitle:"Termdock 桌面端",desktopStatusLoading:"正在读取 macOS 原生状态…",desktopSwitchService:"切换服务",desktopInstallCli:"安装 / 修复 CLI",desktopCliUpdated:"CLI 状态已更新",desktopOpenDataDirectory:"打开数据目录"},toolbarPresets:{preview:"预览",presets:"预设",label:"标签",new:"新建",reset:"重置",presetLabelPlaceholder:"预设名称",deletePreset:({name:t})=>`删除预设 ${t}`,matchPrograms:"匹配程序",typeEnterHint:"输入后回车",programsPlaceholder:"vim, nvim, /^claude(-code)?$/i …",programsHelp:"纯字符串按大小写不敏感子串匹配。用 /…/flags 包裹则为正则(针对小写程序名测试)。",altSlot:"Alt 修饰键槽",altSlotHint:"在预览中保留一个 Alt 键槽位。",desktopVisibility:"桌面端显示",desktopVisibilityHint:"桌面端只显示该预设的自定义按钮,不显示基础快捷键。",rowLayout:"行布局",rowLayoutHint:"每行按钮数。",addRow:"行",rowN:({n:t})=>`第 ${t} 行`,del:"删",buttons:"按钮",buttonsHint:"点击编辑,使用 ↑↓ 排序。",addButton:"添加按钮",noCustomButtons:"暂无自定义按钮。添加一个来覆盖默认工具栏。",moveUp:"上移",moveDown:"下移",removeRow:({n:t})=>`移除第 ${t} 行`,removeAction:({name:t})=>`移除 ${t}`,labelField:"标签",labelPlaceholder:"按钮上显示的文本",sequence:"序列",sequencePlaceholder:"例如 /undo 或 \\t 或 /||undo",sequenceHint:"双击序列",doubleTap:"双击序列",doubleTapAdd:"+ 添加",doubleTapPlaceholder:"例如 /undo\\r 或 /||undo ||\\r",remove:"移除",noSequence:"无序列",preset:"预设",overCapacityHint:"按钮数超过槽位,多余按钮将使用最后一行的尺寸。"},agentRules:{ruleColors:{green:"绿",yellow:"黄",red:"红",blue:"蓝",purple:"紫",orange:"橙",gray:"灰"}},tab:{session:"会话",new:"新建会话",rename:"重命名",renameHint:"修改标签的显示名称",renamePlaceholder:"留空则恢复默认名称",copyCwd:"复制当前目录",copyCwdHint:"复制当前工作目录",resumeAgent:"恢复 Agent 会话",resumeAgentHint:"用原生 session id 恢复上次对话",resumeAgentAvailable:"有可恢复的 Agent 对话",resumeAgentRecoveredTitle:({agent:t})=>`可继续上次的 ${t} 对话`,resumeAgentRecoveredHint:"Terminal 曾异常中断,已重新创建;可以从上次对话继续。",resumeAgentNow:"恢复",resumeAgentLater:"暂不恢复",resumeAgentSubmitting:"正在提交原生恢复命令…",resumeAgentWaiting:"正在等待 Agent 确认已载入原会话…",resumeAgentSuccess:({agent:t})=>`${t} 会话已恢复`,resumeAgentFailed:"Agent 会话恢复失败,可以重试。",resumeAgentConflict:"该 Agent 会话已在另一个 Terminal 中打开。",resumeAgentBusy:"当前 Agent 回合尚未结束,暂时不能恢复。",resumeAgentTimeout:"Agent 未确认已载入原会话,请查看 Terminal 输出或重试。",tmuxRecoveryTitle:({count:t})=>`检测到 tmux 异常退出,${t} 个 Agent 可恢复`,tmuxRecoveryHint:"Termdock 保留了原生会话 ID。恢复操作会在原标签页中继续之前的对话。",tmuxRecoveryRestoreAll:"恢复全部",tmuxRecoveryRestoring:"正在恢复…",tmuxRecoveryDismiss:"暂不处理",tmuxRecoveryPartial:({restored:t,failed:e})=>`已恢复 ${t} 个,${e} 个需要重试。`,tmuxRecoveryFailed:"恢复失败,请检查终端状态后重试。",tmuxRecoveryDismissFailed:"暂时无法关闭该恢复提示。",copied:"已复制",close:"关闭会话",closeHint:"从列表移除该标签",longPressTip:"提示:按住标签不动约半秒打开操作菜单,按住并拖动可排序。",sessionsTitle:"会话",explorerTitle:"资源管理器",split:"分屏",splitTitle:"添加到分屏工作区",splitNew:"新建会话并加入",splitNewHint:"沿用当前目录和默认会话类型;可连续加入多个会话",splitExisting:"选择已有会话或工作区",splitExistingHint:"会话可组成多个独立工作区;选择另一工作区会将两组合并",splitCurrent:"当前",splitClose:"退出分屏",splitLayout:"分屏布局",splitHorizontal:"左右",splitVertical:"上下",splitGrid:"网格",splitWorkspace:"分屏组",splitWorkspaces:"分屏工作区",splitRename:"重命名分屏组",splitRemovePane:"移出分屏",splitExistingGroups:"已有分屏组",splitAvailableSessions:"可加入的会话",splitOccupied:"已成组",splitUnavailableGrouped:"分组模式下只能分屏同一目录的会话",splitEndedGrouped:"已退出分屏:分组模式不支持跨目录组合",splitNoOtherSessions:"没有可组合的其他会话",sessionCount:({count:t})=>`${t} 个会话`,closeChooserTitle:"销毁 Tmux 会话?",closeChooserDescription:"确认后会终止该会话及其中的所有进程,此操作无法撤销。",destroySession:"销毁会话",confirmDestroySession:"确认销毁",destroySessionHint:"终止 tmux 会话及其中的所有进程。",dragToClose:"拖到此处关闭",releaseToClose:"松手后确认"},agent:{aiRunning:"AI 运行中",needsReview:"需要查看",finishedReview:"AI 已完成 — 需要查看",aiWaiting:"AI 等待中",copyMode:"Copy 模式",jumpToNext:"跳到下一个待处理",jumpToNextRunning:"跳到下一个运行中会话",selectRunningSession:"选择运行中的 Session",runningSessionGestureHint:"轻点循环 · 横向滑动选择 · 长按拖动",currentSession:"当前"},connection:{reconnecting:"正在重连…"},desktopServices:{switchService:"切换 Termdock 服务",openServices:"已打开的服务",idle:"空闲",manageServices:"管理服务与名称"},terminal:{input:"终端输入",error:"错误",dropFilesToPastePaths:"拖放文件以输入路径",loading:"正在加载终端…",initializing:"正在初始化终端引擎…",failedToLoad:"终端加载失败",unknownError:"发生未知错误",componentFailed:"终端组件加载失败",paste:"粘贴",copied:"已复制",copyFailed:"复制失败",longPressSelectsText:"长按选择文本",longPressSendsArrows:"长按发送方向键",switchLongPressToArrows:"将长按切换为方向键",switchLongPressToCopy:"将长按切换为复制所选文本"},quota:{title:"订阅配额",noProviders:"未检测到订阅服务。",noProvidersHint:"使用 AI 编程工具并登录后,自动显示配额信息。",exhausted:"已用完",left:({n:t})=>`剩余 ${t}`,updated:({time:t})=>`${t} 更新`,refresh:"刷新",close:"关闭"},errorBoundary:{title:"出现了一些问题",unexpected:"发生意外错误",retry:"重试",copyDetails:"复制错误信息",copied:"已复制",copyFailed:"复制失败"},error:{type:{network:"网络连接错误",session:"会话错误",terminal:"终端错误",auth:"认证错误",validation:"验证错误",unknown:"未知错误"},severity:{low:"提示:",medium:"警告:",high:"错误:",critical:"严重错误:"},suggestion:{networkCheck:"检查网络连接",networkRetry:"尝试重新连接",networkProxy:"检查代理设置",networkWait:"等待网络恢复",sessionRecreate:"重新创建会话",sessionServer:"检查服务器状态",sessionCache:"清理浏览器缓存",terminalRestart:"重启终端",terminalConfig:"检查终端配置",terminalClear:"清除终端输出",authRelogin:"重新登录",authCredentials:"检查凭证",authAdmin:"联系管理员",validationFormat:"检查输入格式",validationParams:"验证参数",validationDocs:"参考文档",unknownReload:"刷新页面",unknownApp:"重启应用",unknownSupport:"联系技术支持"}}},Z2=["en","zh"],rn="en",Oa="termdock:locale",jo={en:X2,zh:Y2};function J2(t){return typeof t=="string"&&Z2.includes(t)}function Q2(){if(typeof window>"u")return rn;try{const e=window.localStorage.getItem(Oa);if(J2(e))return e}catch{}return(window.navigator?.language?.toLowerCase()??"").startsWith("zh")?"zh":rn}const kp=F.createContext(null);function Fa(t,e){const r=e.split(".");let n=t;for(const o of r)if(n&&typeof n=="object"&&o in n)n=n[o];else return;return n}function Ma(t,e){return typeof t=="function"?t(e??{}):typeof t!="string"?String(t):e?t.replace(/\{(\w+)\}/g,(r,n)=>Object.prototype.hasOwnProperty.call(e,n)?String(e[n]):r):t}function eA({children:t}){const[e,r]=F.useState(()=>Q2()),n=Ue.useRef(!1);F.useEffect(()=>{typeof window>"u"||ms().then(c=>{if(c?.locale==="zh"||c?.locale==="en"){if(c.locale===e||c.locale==="en"&&e!=="en")return;r(c.locale);try{window.localStorage.setItem(Oa,c.locale)}catch{}}}).catch(()=>{})},[]),F.useEffect(()=>{if(!(typeof window>"u")){try{window.localStorage.setItem(Oa,e)}catch{}n.current&&(n.current=!1,Gt({locale:e}).catch(()=>{})),document.documentElement.lang=e==="zh"?"zh-CN":"en"}},[e]);const o=F.useCallback(c=>{n.current=!0,r(c)},[]),s=jo[e]??jo[rn],i=F.useCallback((c,l)=>{const d=Fa(s,c);if(d===void 0){const u=Fa(jo[rn],c);return u===void 0?c:Ma(u,l)}return Ma(d,l)},[s]),a=F.useMemo(()=>({locale:e,setLocale:o,t:i}),[e,o,i]);return p.jsx(kp.Provider,{value:a,children:t})}function $c(){const t=F.useContext(kp);return t||{locale:rn,setLocale:()=>{},t:(e,r)=>{const n=Fa(jo[rn],e);return n===void 0?e:Ma(n,r)}}}const tA=String.raw`
|
|
13
|
+
`)}if(a+=i.decode(),l(a),c)throw new Error(c)}function c2(t){if(!t)return;const e=new URLSearchParams({requestSlotId:t,action:"cancel_io_slot"});fetch(`/api/terminal/fs/cancel-slot?${e}`,{method:"GET",keepalive:!0}).catch(()=>{})}async function l2(t,e,r="view_file",n){const o=new URLSearchParams({path:t,action:r});n&&o.set("requestSlotId",n);const s=await up(`/api/terminal/fs/read?${o}`,{signal:e,timeoutMs:yr});if(!s.ok){const i=await s.json().catch(()=>({error:"Failed to read file"}));throw new Error(i.error||"Failed to read file")}return s.json()}async function d2(t,e,r="HEAD",n,o="ref"){const s=new URLSearchParams({path:t,cwd:e,ref:r,action:"git_blob"});o==="index"&&s.set("source","index");const i=await he(`/api/terminal/fs/git-blob?${s}`,{signal:n},yr,"Git blob preview took too long.");if(!i.ok){const a=await i.json().catch(()=>({error:"Failed to read git blob"}));throw new Error(a.error||"Failed to read git blob")}return i.json()}async function u2(t,e,r="view_file",n){const o=new URLSearchParams({path:t,action:r});n&&o.set("requestSlotId",n);const s=await up(`/api/terminal/fs/blob?${o}`,{signal:e,timeoutMs:Ep(t)?BE:yr});if(!s.ok){const c=await s.json().catch(()=>({error:"Failed to load image preview"}));throw new Error(c.error||"Failed to load image preview")}const i=await s.blob(),a=s.headers.get("Content-Length");return{blob:i,path:t,size:a?Number(a):null,modified:s.headers.get("Last-Modified"),mimeType:s.headers.get("Content-Type")||i.type||Us(t)||"application/octet-stream"}}function $c(t,e){try{const r=decodeURIComponent(t.headers.get("X-Termdock-Source-Path")||"");return r.startsWith("/")&&!/[\r\n\0]/.test(r)?r:e}catch{return e}}async function f2(t,e,r,n="view_file",o){const s=new URLSearchParams({path:t,view:e,action:n});o&&s.set("requestSlotId",o);const i="KiCad preview rendering or transfer timed out.",a=Dc(r,hp,i);try{const c=await fetch(`/api/terminal/fs/eda-preview?${s}`,{signal:a.signal});if(!c.ok){const u=await c.json().catch(()=>({error:"Failed to render KiCad preview"}));throw new Error(u.error||"Failed to render KiCad preview")}const l=await c.blob(),d=c.headers.get("Content-Length");return{blob:l,path:$c(c,t),view:e,size:d?Number(d):null,modified:c.headers.get("Last-Modified"),mimeType:c.headers.get("Content-Type")||l.type||"image/svg+xml"}}catch(c){throw a.signal.aborted&&!r?.aborted?new Error(i):c}finally{a.cleanup()}}async function h2(t,e,r,n,o){const s=new URLSearchParams({path:t,view:e,x:String(r),y:String(n)}),i=await he(`/api/terminal/fs/eda-inspect?${s}`,{signal:o},8e3,"KiCad point inspection timed out.");if(!i.ok){const a=await i.json().catch(()=>({error:"Failed to inspect KiCad point"}));throw new Error(a.error||"Failed to inspect KiCad point")}return i.json()}async function p2(t,e,r="view_file",n){const o=new URLSearchParams({path:t,action:r});n&&o.set("requestSlotId",n);const i=Dc(e,fp,"3D model transfer timed out. Please retry.");try{const a=await fetch(`/api/terminal/fs/download?${o}`,{signal:i.signal});if(!a.ok){const u=await a.json().catch(()=>({error:"Failed to load 3D model preview"}));throw new Error(u.error||"Failed to load 3D model preview")}const c=await a.blob(),l=a.headers.get("Content-Length"),d=jc(t)??"";return{blob:c,path:$c(a,t),size:l?Number(l):null,modified:a.headers.get("Last-Modified"),ext:d,mimeType:a.headers.get("Content-Type")||c.type||o2[d]||"application/octet-stream"}}finally{i.cleanup()}}function nu(){return typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}async function g2(t){const e=`/api/terminal/fs/download?path=${encodeURIComponent(t)}`,r=await fetch(e);if(!r.ok){const c=await r.json().catch(()=>({error:"Failed to download file"}));throw new Error(c.error||"Failed to download file")}const n=await r.blob(),o=Cp(r.headers.get("Content-Disposition")||"")??t.split("/").pop()?.split("\\").pop()??"download",s=window.showSaveFilePicker;if(typeof s=="function")try{const l=await(await s({suggestedName:o})).createWritable();await l.write(n),await l.close();return}catch(c){if(c instanceof DOMException&&c.name==="AbortError")return}if(nu()){const c=new File([n],o,{type:n.type||"application/octet-stream"});if(typeof navigator<"u"&&"share"in navigator&&(!navigator.canShare||navigator.canShare({files:[c]})))try{await navigator.share({files:[c]});return}catch(d){if(d instanceof DOMException&&d.name==="AbortError")return}}if(nu()){const c=await vE(n,o);if(c){window.location.assign(c);return}}const i=URL.createObjectURL(n),a=document.createElement("a");a.href=i,a.download=o,a.rel="noopener",a.style.display="none",document.body.appendChild(a),a.click(),setTimeout(()=>{URL.revokeObjectURL(i),a.remove()},4e3)}async function m2(t){const e=await Z(),r=new URLSearchParams({path:t,confirm:"true"}),n=await he(`/api/terminal/fs/file?${r}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}},yr,"File deletion took too long.");if(!n.ok){const o=await n.json().catch(()=>({error:"Failed to delete file"}));throw new Error(o.error||"Failed to delete file")}}async function w2(t,e,r,n){const o=new FormData;for(const u of e)o.append("files",u);const s=`/api/terminal/fs/upload?dir=${encodeURIComponent(t)}`,i=await Z();n?.(0);const a={"X-XSRF-TOKEN":i};let c=o;if(n){const u=new Response(o);a["Content-Type"]=u.headers.get("Content-Type"),c=await u.blob()}const l=await he(s,{method:"POST",headers:a,body:c,signal:r,onUploadProgress:c instanceof Blob&&n?u=>n(Math.min(99,Math.floor(u/Math.max(1,c.size)*100))):void 0},12e4,"Upload timed out");if(!l.ok){const u=await l.json().catch(()=>({error:"Upload failed"}));throw new Error(u.error||"Upload failed")}const d=await l.json();return n?.(100),d}async function y2(t){const e=await he("/api/terminal/fs/local-open-availability",{signal:t},yr,"Local file browser availability check timed out");return e.ok?e.json():{available:!1}}async function b2(t){const e=await Z(),r=await he("/api/terminal/fs/open-in-file-browser",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({path:t})},yr,"Opening file browser timed out");if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to open file browser"}));throw new Error(n.error||"Failed to open file browser")}}function Cp(t){if(!t)return null;const e=/(?:^|;)\s*filename\*=\s*(?:UTF-8'')?([^;]+)/i.exec(t);if(e){const n=e[1].trim().replace(/^"|"$/g,"");try{return decodeURIComponent(n)}catch{return n}}const r=/(?:^|;)\s*filename=\s*(?:"([^"]*)"|([^;]+))/i.exec(t);return r?(r[1]??r[2]).trim():null}function v2(t,e){e?.algorithm&&e.algorithm!=="default"&&t.set("algorithm",e.algorithm),e?.whitespace&&e.whitespace!=="default"&&t.set("whitespace",e.whitespace),e?.context==="all"?t.set("context","all"):typeof e?.context=="number"&&t.set("context",String(e.context))}async function x2(t,e,r,n,o=t?"view_diff":"view_all_changes",s,i,a,c){const l=new URLSearchParams;t&&l.set("path",t),r&&l.set("cwd",r),l.set("action",o),v2(l,c),s&&l.set("traceId",s),i&&l.set("interactionId",i),a&&l.set("requestSlotId",a);const d=!!t&&o==="view_diff",u=typeof performance<"u"?performance.now():Date.now();Ft("request_start",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:r,action:o,cached:!!e,algorithm:c?.algorithm??"default",whitespace:c?.whitespace??"default",context:c?.context===void 0?"default":String(c.context),timeoutMs:d?Wr:dt});const f=await he(`/api/terminal/fs/diff?${l}`,{signal:n},d?Wr:dt,d?"Git diff is still running for this file. It may be blocked by repository IO or another Git process.":"Git diff took too long. The repository may be busy, on slow storage, or locked by another Git process.").catch(m=>{throw Ft("timeout_or_abort",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:r,action:o,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u),message:m instanceof Error?m.message:String(m),signalAborted:!!n?.aborted,signalReason:n?.aborted?String(n.reason??""):void 0}),m});if(Ft("response_headers",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:r,action:o,status:f.status,ok:f.ok,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u)}),!f.ok){const m=await f.json().catch(()=>({error:"Failed to get diff"}));throw Ft("error",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:r,action:o,status:f.status,message:m.error||"Failed to get diff"}),new Error(m.error||"Failed to get diff")}Ft("response_body_start",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:r,action:o,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u),contentLength:f.headers.get("Content-Length")});let h;try{h=await wp(f,d?Wr:dt,d?"Git diff response body is still loading for this file.":"Git diff response body took too long.")}catch(m){throw Ft("response_body_timeout",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:r,action:o,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u),message:m instanceof Error?m.message:String(m),signalAborted:!!n?.aborted,signalReason:n?.aborted?String(n.reason??""):void 0}),m}let g;try{g=JSON.parse(h)}catch(m){throw Ft("response_body_parse_error",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:r,action:o,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u),bytes:h.length,snippet:h.slice(0,160),message:m instanceof Error?m.message:String(m)}),m}return Ft("response_body",{traceId:s,interactionId:i,requestSlotId:a,filePath:t,cwd:r,action:o,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-u),bytes:g.diff?.length??0,error:g.error??null,truncated:!!g.truncated,tooLarge:!!g.tooLarge}),g}async function S2(t,e,r="load_git_details",n){const o=new URLSearchParams;t&&o.set("cwd",t),o.set("action",r),n&&o.set("requestSlotId",n);const s=o.toString(),i=await he(`/api/terminal/fs/git-context${s?`?${s}`:""}`,{signal:e},dt,"Git details took too long. The repository may be busy, on slow storage, or locked by another Git process.");if(!i.ok){const a=await i.json().catch(()=>({error:"Failed to get git context"}));throw new Error(a.error||"Failed to get git context")}return i.json()}async function E2(t={},e){const r=new URLSearchParams;t.workspaceRoot&&r.set("workspaceRoot",t.workspaceRoot),t.repoRoot&&r.set("repoRoot",t.repoRoot);const n=r.toString(),o=await he(`/api/terminal/fs/change-audit${n?`?${n}`:""}`,{signal:e},dt,"Change audit explanations took too long to load.");if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to get change audit explanations"}));throw new Error(s.error||"Failed to get change audit explanations")}return o.json()}async function A2(t,e){const r=new URLSearchParams;t.cwd&&r.set("cwd",t.cwd),t.repoRoot&&r.set("repoRoot",t.repoRoot),r.set("base",t.base),t.head&&r.set("head",t.head),t.includeUncommitted===!1&&r.set("includeUncommitted","0"),r.set("action","load_branch_diff"),t.requestSlotId&&r.set("requestSlotId",t.requestSlotId);const n=await he(`/api/terminal/fs/branch-diff?${r}`,{signal:e},Wr,"Branch diff took too long. The repository may be busy, on slow storage, or locked by another Git process.");if(!n.ok){const o=await n.json().catch(()=>({error:"Failed to get branch diff"}));throw new Error(o.error||"Failed to get branch diff")}return n.json()}async function k2(t,e){const r=new URLSearchParams;t.cwd&&r.set("cwd",t.cwd),t.repoRoot&&r.set("repoRoot",t.repoRoot),r.set("commit",t.commit),r.set("action","load_commit_diff"),t.requestSlotId&&r.set("requestSlotId",t.requestSlotId);const n=await he(`/api/terminal/fs/commit-diff?${r}`,{signal:e},Wr,"Commit diff took too long. The repository may be busy, on slow storage, or locked by another Git process.");if(!n.ok){const o=await n.json().catch(()=>({error:"Failed to get commit diff"}));throw new Error(o.error||"Failed to get commit diff")}return n.json()}async function I2(t,e){const r=new URLSearchParams;t.cwd&&r.set("cwd",t.cwd),t.repoRoot&&r.set("repoRoot",t.repoRoot),r.set("limit",String(t.limit)),typeof t.skip=="number"&&r.set("skip",String(t.skip)),t.query&&r.set("query",t.query),r.set("action","load_recent_commits"),t.requestSlotId&&r.set("requestSlotId",t.requestSlotId);const n=await he(`/api/terminal/fs/git-recent-commits?${r}`,{signal:e},dt,"Recent commits took too long. The repository may be busy, on slow storage, or locked by another Git process.");if(!n.ok){const o=await n.json().catch(()=>({error:"Failed to get recent commits"}));throw new Error(o.error||"Failed to get recent commits")}return n.json()}async function C2(t={},e){const r=new URLSearchParams;t.workspaceRoot&&r.set("workspaceRoot",t.workspaceRoot),t.repoRoot&&r.set("repoRoot",t.repoRoot),t.baseRef&&r.set("baseRef",t.baseRef),t.branchName&&r.set("branchName",t.branchName);const n=r.toString(),o=await he(`/api/terminal/fs/branch-audit${n?`?${n}`:""}`,{signal:e},dt,"Branch explanations took too long to load.");if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to get branch explanations"}));throw new Error(s.error||"Failed to get branch explanations")}return o.json()}async function R2(t={}){const e=await Z(),r=await he("/api/terminal/fs/change-audit",{method:"DELETE",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)},dt,"Change audit explanations took too long to clear.");if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to clear change audit explanations"}));throw new Error(n.error||"Failed to clear change audit explanations")}return r.json()}async function T2(t={}){const e=await Z(),r=await he("/api/terminal/fs/branch-audit",{method:"DELETE",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)},dt,"Branch explanations took too long to clear.");if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to clear branch explanations"}));throw new Error(n.error||"Failed to clear branch explanations")}return r.json()}async function P2(t,e,r){const n=new URLSearchParams;t&&n.set("cwd",t),n.set("action","load_untracked_files"),r&&n.set("requestSlotId",r);const o=n.toString();return(await he(`/api/terminal/fs/untracked-files${o?`?${o}`:""}`,{signal:e},Wr,"Untracked file scan took too long. The repository may be busy, on slow storage, or locked by another Git process.")).json()}async function N2(t,e,r={}){const n=new URLSearchParams;t&&n.set("cwd",t),r.includeNested&&n.set("includeNested","true"),r.refresh&&n.set("refresh","true"),r.cacheOnly&&n.set("cacheOnly","true"),r.discoverOnly&&n.set("discoverOnly","true"),n.set("action",r.action??(r.refresh?"manual_git_refresh":"open_sidebar_git_refresh")),r.requestSlotId&&n.set("requestSlotId",r.requestSlotId);const o=n.toString(),s=`/api/terminal/fs/git-bundle${o?`?${o}`:""}`,i=r.requestTimeoutMs===null?await fetch(s,{signal:e}):await he(s,{signal:e},r.requestTimeoutMs??dt,"Git status refresh took too long. The repository may be busy, on slow storage, or locked by another Git process.");if(!i.ok){const a=await i.json().catch(()=>({error:"Failed to get git bundle"}));throw new Error(a.error||"Failed to get git bundle")}return i.json()}async function L2(t){const e=await Z(),r=await fetch("/api/terminal/fs/git-action",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:"Git action failed"})),o=n.confirmationPhrase?`${n.error||"Git action failed"} (${n.confirmationPhrase})`:n.error||"Git action failed";throw new Error(o)}return r.json()}async function B2(t){const e=new URLSearchParams;t.cwd&&e.set("cwd",t.cwd),t.action&&e.set("action",t.action),t.jobId&&e.set("jobId",t.jobId);const r=await fetch(`/api/terminal/fs/git-action/status?${e}`);if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to get Git action status"}));throw new Error(n.error||"Failed to get Git action status")}return r.json()}async function _2(t){const e=await Z(),r=await fetch("/api/terminal/fs/apply-hunk",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to apply diff hunk"}));throw new Error(n.error||"Failed to apply diff hunk")}return r.json()}async function Oe(t,e){const r=e?.method?.toUpperCase()??"GET",n=new Headers(e?.headers);r!=="GET"&&r!=="HEAD"&&n.set("X-XSRF-TOKEN",await Z()),e?.body&&n.set("Content-Type","application/json");const o=await fetch(`/api/terminal/operations${t}`,{...e,headers:n});if(!o.ok){const s=await o.json().catch(()=>({error:"操作失败"}));throw new pe(s.error||"操作失败",o.status)}return o.status===204?void 0:await o.json()}function D2(){return Oe("/automations")}function O2(t){return Oe("/automations",{method:"POST",body:JSON.stringify(t)})}function F2(t){return Oe(`/automations/${encodeURIComponent(t)}/run`,{method:"POST"})}function M2(t,e){return Oe(`/automations/${encodeURIComponent(t)}/enabled`,{method:"POST",body:JSON.stringify({enabled:e})})}function j2(t){return Oe(`/automations/${encodeURIComponent(t)}`,{method:"DELETE"})}let Xt=null,ou="",su;const Fa=new Set;function Hc(){return Oe("/collaboration-groups",{signal:AbortSignal.timeout(1e4)})}function br(){const t=Dr(),e=t?.serviceOrigin??window.location?.origin??"",r=`${t?.targetPeerId??""}:${e}`,n=window.termdockDesktop;if(!Xt||r!==ou||n!==su){Xt?.dispose(),ou=r,su=n;const o=!n?.collaboration||n.collaboration.protocolVersion===2,s=n?void 0:Zh(),i=n?.collaboration?o&&n.collaboration.peers&&n.collaborationPeers?()=>n.collaborationPeers():void 0:n?.collaborationList?()=>n.collaborationList():s?()=>s.peers(e):void 0;Xt=new bE({origin:e,peerOrigin:n?window.location.origin:void 0,readLocal:Hc,readPeers:i,peerProtocol:!o||n?.collaboration?.peers&&!n.collaborationPeers?"unsupported":n?.collaboration?.peers||s?"v2":"legacy"}),Xt.subscribe(a=>{for(const c of Fa)c(a)})}return Xt}function qc(){Xt?.dispose(),Xt=null}function U2(t){return Fa.add(t),()=>{Fa.delete(t)}}function $2(){br().refreshPeers(!0)}function H2(){return br().load()}async function q2(t){const e=await Hc(),r=t.id?e.groups.find(c=>c.id===t.id):void 0;if(t.id&&!r)throw new pe("协作组已删除,请刷新列表",404);if(r&&t.expectedUpdatedAt!==void 0&&t.expectedUpdatedAt!==r.updatedAt)throw new pe("协作组已被修改,请重新打开成员管理后再保存",409);const n=[...new Set(t.sessionIds)];if(!t.name.trim()||n.length<2)throw new pe("协作组至少需要两个有效会话",400);const o=new Set([...e.sessions.map(c=>c.sessionId),...r?.sessionIds??[]]),s=n.filter(c=>!o.has(c));if(s.some(c=>!La(c)))throw new pe("所选会话已变化,请刷新后重新选择;尚未保存任何修改",409);const i={...t,sessionIds:n,...r?{expectedUpdatedAt:t.expectedUpdatedAt??r.updatedAt}:{}};let a;if(s.length){const c=window.termdockDesktop;if(c){if(!c.collaborationSave||c.collaboration&&(c.collaboration.protocolVersion!==2||!c.collaboration.save))throw new pe("当前 Mac 客户端需要更新后才能添加跨服务成员;当前服务内仍可组队",409);if(r&&!r.federated&&c.collaboration?.protocolVersion!==2)throw new pe("将已有组转换为跨服务组需要更新 Mac 客户端;原组和记录均未修改",409);const l=window.location.origin;if(!c.collaboration&&Dr()?.serviceOrigin&&Dr().serviceOrigin!==l)throw new pe("旧版客户端无法在入口页面中添加跨服务成员,请更新客户端后重试",409);a=await c.collaborationSave({...i,expectedOrigin:l})}else{const l=Zh();if(!l)throw new pe("跨服务连接尚未就绪,请重新打开页面",409);a=await l.save(Dr()?.serviceOrigin??window.location.origin,i)}}else a=await Oe("/collaboration-groups",{method:"POST",body:JSON.stringify(i)});return br().invalidate(),a}async function K2(t){if((await Hc()).capabilities?.groupMove!==1)throw new pe("当前服务需要升级后才能在协作组之间移动成员;原成员关系未修改",409);await Oe("/collaboration-groups/move-member",{method:"POST",body:JSON.stringify(t)}),br().invalidate()}function z2(t,e){return Oe(`/collaboration-groups/${encodeURIComponent(t)}/spawn`,{method:"POST",body:JSON.stringify(e)}).then(r=>(br().invalidate(),r))}function V2(t,e,r){return Oe(`/collaboration-groups/${encodeURIComponent(t)}/role`,{method:"POST",body:JSON.stringify({sessionId:e,role:r})}).then(n=>(br().invalidate(),n))}function W2(t,e){const r=e===void 0?"":`?expectedUpdatedAt=${encodeURIComponent(e)}`;return Oe(`/collaboration-groups/${encodeURIComponent(t)}${r}`,{method:"DELETE"}).then(()=>{br().invalidate()})}function G2(t){return Oe(`/collaboration-groups/${encodeURIComponent(t)}/messages`)}function X2(t,e){return Oe(`/collaboration-groups/${encodeURIComponent(t)}/messages`,{method:"POST",body:JSON.stringify(e)})}function Y2(t){return Oe(`/session-search?q=${encodeURIComponent(t)}`)}const Z2=Object.freeze(Object.defineProperty({__proto__:null,AUTH_UNAUTHORIZED_EVENT:_c,AgentPluginManifestError:Mc,EDA_PREVIEW_REQUEST_TIMEOUT_MS:hp,HTML_EXTENSIONS:Ip,MODEL_3D_EXTS:kp,MODEL_PREVIEW_REQUEST_TIMEOUT_MS:fp,TERMINAL_CSRF_REQUEST_TIMEOUT_MS:pp,TERMINAL_HEALTH_REQUEST_TIMEOUT_MS:gp,TERMINAL_SESSION_OPEN_REQUEST_TIMEOUT_MS:mp,TerminalApiError:pe,VISIBLE_WAKEUP_PROBE_TIMEOUT_MS:yp,acknowledgeTerminalOutput:e1,applyDiffHunk:_2,buildHtmlPreviewUrl:n2,buildVideoPreviewUrl:J1,cancelIoSlot:c2,checkAgentPluginUpdate:D1,checkTermdockUpdate:TE,checkTerminalHealth:c1,clearBranchAuditRecords:T2,clearChangeAuditRecords:R2,clearSessionInventoryEntries:x1,closeTerminal:i1,confirmTermdockUpdateRestart:PE,connectTerminalStream:GE,createAgentPlugin:B1,createTerminalSession:WE,deleteAgentPlugin:M1,deleteFile:m2,dismissTmuxRecovery:p1,doctorAgentPlugin:F1,downloadFile:g2,fetchQuota:NE,forceKillTerminal:l1,getAgentHooks:T1,getAgentLaunchers:R1,getAgentPlugins:L1,getAppliedTerminalCursor:VE,getBranchAuditRecords:C2,getBranchDiff:A2,getChangeAuditRecords:E2,getCommitDiff:k2,getContextDraft:k1,getDefaultEdaPreviewView:t2,getEdaExtForPath:Uc,getFileDiff:x2,getGitActionStatus:B2,getGitBlobContent:d2,getGitBundle:N2,getGitContext:S2,getImageMimeTypeForPath:Us,getLocalFileBrowserAvailability:y2,getModel3dExtForPath:jc,getProgramDetection:z1,getRecentCommits:I2,getSessionInventory:m1,getSettings:Hn,getTermdockUpdateState:RE,getTitleNamerCatalog:A1,getTmuxStatus:u1,getToolbarPresetsDoc:S1,getUntrackedFiles:P2,getVideoMimeTypeForPath:Ap,inspectEdaPoint:h2,installAgentHooks:P1,installAgentPluginSource:_1,isHeicImagePath:Ep,isPreviewableEdaPath:e2,isPreviewableHtmlPath:r2,isPreviewableImagePath:X1,isPreviewableModel3dPath:Q1,isPreviewableVideoPath:Z1,killTmuxSession:f1,listAgentAutomations:D2,listAgentResumeHistory:U1,listCollaborationGroups:H2,listCollaborationMessages:G2,listDirectory:s2,listTmuxSessions:d1,loginWithPassword:Sp,logout:C1,moveCollaborationMember:K2,openInFileBrowser:b2,openSessionInventoryEntry:w1,parseFilenameFromContentDisposition:Cp,prepareAgentResumeHistory:$1,probeTerminalConnection:YE,readEdaPreviewBlob:f2,readFileContent:l2,readImagePreviewBlob:u2,readModel3dBlob:p2,readPreviewSourcePath:$c,reconnectTerminalConnectionNow:ZE,refreshQuota:LE,removeAgentAutomation:j2,removeAgentResumeHistory:H1,removeCollaborationGroup:W2,removeSessionInventoryEntry:v1,reorderSessionInventoryEntries:b1,replaceProgramDetection:V1,replaceProgramRules:q1,replaceToolbarPresetsDoc:E1,resetCollaborationDirectory:qc,resetCsrfTokenCache:Oc,resetProgramDetection:W1,resetProgramRules:K1,resizeTerminal:o1,restartTerminalSession:a1,restoreAllTmuxAgentSessions:h1,resumeAgentSession:j1,retryCollaborationPeers:$2,runAgentAutomation:F2,runGitAction:L2,saveAgentAutomation:O2,saveCollaborationGroup:q2,searchFilesStream:i2,searchTerminalSessions:Y2,sendAgentReviewAck:r1,sendCollaborationMessage:X2,sendTerminalFlowControlState:n1,sendTerminalFocusState:QE,sendTerminalInput:XE,sendTerminalViewingState:t1,sendTmuxAction:s1,setAgentAutomationEnabled:M2,setCollaborationMemberRole:V2,setTerminalOutputSubscription:vp,setTerminalSnapshotCursor:zE,spawnCollaborationAgent:z2,subscribeCollaborationGroups:U2,suspendTerminalConnectionReconnects:JE,uninstallAgentHooks:N1,updateAgentPlugin:O1,updateContextDraft:I1,updateSessionInventoryEntry:y1,updateSettings:$t,uploadFiles:w2,watchFileSystem:a2},Symbol.toStringTag,{value:"Module"})),J2={app:{name:"Termdock"},common:{cancel:"Cancel",close:"Close",save:"Save",reset:"Reset",loading:"Loading…",error:"Error",retry:"Retry",refresh:"Refresh",search:"Search",clear:"Clear",delete:"Delete",on:"On",off:"Off",back:"Back",copy:"Copy",decrease:"Decrease",increase:"Increase",use:"Use",previous:"Previous",next:"Next"},login:{prompt:"termdock login",placeholder:"Enter password",placeholderBlocked:({s:t})=>`Please wait ${t}s`,submit:"Sign in",invalidPassword:"Incorrect password",failed:"Login failed"},sidebar:{sessions:"Sessions",noSessions:"No open sessions yet.",noMatchingSessions:"No matching sessions.",toggleSearch:"Toggle search",settings:"Settings",moreActions:"More actions",subscriptionQuota:"Subscription quota",pinSidebar:"Keep sidebar open",unpinSidebar:"Stop keeping sidebar open",runningSessionButton:"Running sessions button",runningSessionButtonHint:"Tap to cycle, swipe sideways to select, hold to drag",updateAvailable:({version:t})=>`Termdock ${t} is available`,updateInstalling:"Installing in the background without interrupting this service.",updateReady:"The update is installed and ready for a confirmed restart.",updateRestart:"Restart and finish update",updateRestartConfirm:({version:t})=>`Restart Termdock and switch to ${t}? This page will reconnect briefly and sessions will stay open.`,updateRestarting:"Restarting; this page will reconnect automatically…",updateFailed:"Automatic installation failed. This reminder will remain.",updateRetry:"Try again",filterSessions:"Filter sessions",clearSearch:"Clear search",groupByFolder:"Group by folder",groupByFolderTitle:"Collapse sessions into groups by working directory. Mutually exclusive with drag sorting.",ungrouped:"Other",needsAttention:"Needs attention",waitingForYou:"Waiting for you",completedUnread:"Completed · unread",closeSession:({name:t})=>`Close ${t}`,newShell:"Shell",newTmux:"Tmux",newTmuxDisabled:"tmux not available on server",confirmNewShell:"Create Shell?",confirmNewTmux:"Create Tmux?",newSession:"New terminal",newSessionWithAgent:({agent:t})=>`New ${t}`,moreLaunchOptions:"More launch options",recoverableSessions:"Recoverable sessions",refreshRecoverableSessions:"Refresh recoverable sessions",restoreRecoverableSession:({name:t})=>`Restore ${t}`,restoringRecoverableSession:"Restoring…",restore:"Restore",newSessionAdvanced:"Quick-launch agent",newSessionComposerTitle:"Start a session",newSessionHint:"Choose how and where it starts",launchSessionWith:({name:t})=>`Start ${t}`,setNewSessionDefault:({name:t})=>`Set ${t} as default`,currentNewSessionDefault:({name:t})=>`${t} is the current default`,currentDefaultAgent:({name:t})=>`Current default: ${t}`,defaultAgent:"Default",makeDefault:"Make default",sessionMode:"Run mode",tmuxKeepsRunning:"Keeps running after disconnect",resumeHistory:"Recent conversations",resumeHistoryCount:({n:t})=>`${t} saved`,resumeHistoryLoading:"Loading recent Agent conversations…",resumeHistoryAction:({title:t})=>`Resume ${t}`,resumeHistoryRemove:({title:t})=>`Remove ${t} from recent conversations`,resumeHistoryLoadFailed:"Could not load recent Agent conversations.",resumeHistoryFailed:"Could not prepare this Agent conversation for resume.",resumeHistoryRemoveFailed:"Could not remove the conversation from history.",workingDirectory:"Working directory",directoryPlaceholder:"Enter a directory path",browseDirectories:"Browse",hideDirectoryBrowser:"Hide browser",chooseDirectory:"Choose working directory",directoryPickerHint:"Open a folder, then confirm the current location.",useThisFolder:"Use folder",recentDirectories:"Recent directories",startCommand:"Start command",customCommand:"Other command",commandPlaceholder:"Optional, e.g. codex",detectAgents:"Detect agents again",savePreset:"Save as preset",createAndRun:"Create and run",createSession:"Create terminal",openLeftSidebar:"Open left sidebar",openRightSidebar:"Open right sidebar",closeSidebar:"Close sidebar"},rightSidebar:{workspace:"Workspace",currentProject:"Project",browsingLocation:"Browsing",parentFolder:"Parent folder",backToProjectRoot:"Back to project",refreshFiles:"Refresh current folder",resizeFileTree:"Drag to resize file browser",pinCurrentFolder:"Pin current folder to this project",unpinCurrentFolder:"Unpin current folder",showHiddenFiles:"Show hidden files",hideHiddenFiles:"Hide hidden files",insertCurrentFolder:"Insert current folder reference",insertCurrentFolderShort:"Insert",pinnedFolders:"Pinned",unpinFolder:({name:t})=>`Unpin ${t}`,fileWatchUnavailable:({message:t})=>`File watcher unavailable: ${t}. Click to refresh manually.`,browsingOutsideProject:"Browsing outside current project",browsingOutsideProjectHint:"Git and Changes still use the current project. File references from here are inserted as external paths.",toggleSearch:"Toggle search",refreshGit:"Refresh Git status",gitLastUpdated:({time:t})=>`Last updated: ${t}`,close:"Close",filterChanges:"Filter changes or files",searchPlaceholderContent:"Search text in files…",searchModeName:"File",searchModeContent:"Content",clearSearch:"Clear search",searchScope:"Scope",searchScopePlaceholder:"Relative folder or absolute path",resetSearchScope:"Reset to current folder",searchOptions:"Search options",searchExclude:"Exclude",searchExcludePlaceholder:"dist/**, *.lock",clearSearchExclude:"Clear exclusions",contentSearchOptions:"Content search options",matchCase:"Match case",matchWholeWord:"Whole word",useRegex:"Regex",insertGitContext:"Insert current Git context into terminal",copyGitContext:"Copy Git context",insertChangeAuditPrompt:"Explain changes",insertChangeAuditPromptTitle:"Insert the change audit prompt into the current session",changeAuditShort:"Explain changes",changeAuditLoading:"Loading hunk explanations…",changeAuditLoaded:({count:t})=>`${t} hunk explanation${t===1?"":"s"} loaded`,changeAuditLoadedAt:({time:t})=>`Generated ${t}`,changeAuditRegenerate:"Regenerate",changeAuditRefreshStale:"Fill stale",changeAuditRefreshStaleTitle:"Insert a prompt to refresh stale hunk explanations",clearChangeAudit:"Clear",clearChangeAuditTitle:"Clear hunk explanations for the current repository",changeAuditClearFailed:({message:t})=>`Failed to clear hunk explanations: ${t}`,changeAuditScopeAll:"All repositories",changeAuditScopeLabel:"Explain scope",branchAuditTitle:"Branch explanation",branchAuditShort:"Explain branch changes",branchAuditBaseLabel:"Base branch",branchAuditBasePlaceholder:"Base branch, e.g. master",branchAuditBaseSearchPlaceholder:"Search base branch",branchAuditBaseEmpty:"No branch options. Type a branch name directly.",branchAuditGenerate:"Generate",branchAuditRegenerate:"Regenerate",branchAuditGenerateTitle:"Insert a prompt to explain this branch against the base branch",branchAuditViewDiff:"View diff",branchAuditViewDiffTitle:"View target branch changes against the base branch",branchAuditDiffLoading:"Loading branch diff...",branchAuditDiffEmpty:"No changes between this branch and the base branch.",branchAuditMissingBase:({repo:t})=>`${t} has no base branch set`,branchAuditRefreshDiff:"Refresh diff",branchAuditRefreshStale:"Fill stale",branchAuditRefreshStaleTitle:"Insert a prompt to refresh stale branch explanations",branchAuditClearTitle:"Clear current branch explanation",branchAuditClearFailed:({message:t})=>`Failed to clear branch explanation: ${t}`,branchAuditCommitCount:({count:t})=>`${t} commit${t===1?"":"s"}`,branchAuditFileCount:({count:t})=>`${t} file${t===1?"":"s"}`,branchAuditTruncated:"diff truncated",branchAuditCurrent:"Saved explanation",branchAuditStale:"Explanation is stale",branchAuditEmpty:"No branch explanation yet. Generate one to persist it here for later review.",branchAuditView:"View explanations",branchAuditSaved:({count:t})=>`${t} hunk explanation${t===1?"":"s"} saved`,branchAuditGeneratedAt:({time:t})=>`Generated ${t}`,insertPreset:({label:t})=>`Insert: ${t}`,tabChanges:"Changes",tabGit:"Git",tabFiles:"Files",inserted:"Inserted",copied:"Copied",toggleContextDraft:"Toggle context draft",contextDraftTitle:"Context draft",contextDraftHint:"References are added here while enabled. Keep browsing, add instructions, then insert once.",contextDraftPlaceholder:"Compose a longer prompt here. Keep using sidebar references to add context…",contextDraftCollapse:"Collapse context draft",contextDraftExpand:"Expand context draft",contextDraftDisable:"Disable context draft",contextDraftClear:"Clear draft",contextDraftInsert:"Insert",contextDraftInsertAndSend:"Insert & send",contextDraftInserted:"Inserted",contextDraftSent:"Sent",contextDraftSend:"Send draft",contextDraftAppended:"Reference added",contextDraftResize:"Drag to resize, double-click for default height",contextDraftAutoCollapseAfterSend:"Collapse after insert/send",contextDraftInsertFailed:"Terminal disconnected — draft kept",contextDraftCharacterCount:({count:t})=>`${t} chars`,selectFilePrompt:"Select a file to preview its contents",backToFileList:"Back to file list",backToPreviousPreview:"Back to source document",insertLineRef:({lineLabel:t})=>`Insert ${t}`,insertFileRef:"Insert",copyFileRef:"Copy file reference",findInFile:"Find in file",findInFilePlaceholder:"Find in this file…",previousSearchMatch:"Previous match",nextSearchMatch:"Next match",closeFileSearch:"Close file search",downloadFile:"Download file",downloadFailed:"Download failed",uploadFile:"Upload file",uploadFiles:"Upload files",insertLocalFile:"Insert local file",insertLocalImage:"Insert local image",layoutMode:"Display mode",layoutModeAuto:"Auto",layoutModeNarrow:"Narrow",layoutModeWide:"Wide",dropToUpload:"Drop files to upload",uploading:"Uploading…",uploadSuccess:({count:t})=>`${t} file${t===1?"":"s"} uploaded`,uploadFailed:"Upload failed",binaryPreviewHint:"Binary files cannot be previewed. Use the download button above to save it.",selectedLineHint:({lineLabel:t})=>`Selected ${t} · tap "Insert" below to add to terminal`,multiLineHint:"Multi-line select: tap start line, then end line",loadingImage:"Loading image…",imagePreviewHint:"Pinch or ⌘/Ctrl + scroll to zoom · double-tap to reset",imageLoadFailed:"Failed to load image preview",loadingVideo:"Loading video…",videoPreviewHint:"Click to play · hold for 2× · drag to seek",videoLoadFailed:"Failed to load video preview",videoUnsupported:"Your browser does not support this video format",videoPlay:"Play",videoPause:"Pause",videoLongPressSpeed:"Playing at 2×",videoRotate:"Rotate 90° clockwise",videoFullscreenEnter:"Enter fullscreen",videoFullscreenExit:"Exit fullscreen",model3dLoading:"Loading 3D model…",model3dExplode:"Exploded view",model3dExplodeAxis:"Explosion axis (viewer coordinates)",model3dExplodeAmount:"Explosion amount",model3dHome:"Reset view",model3dFit:"Fit visible parts",model3dFront:"Front view",model3dTop:"Top view",model3dRight:"Right view",model3dAssemble:"Restore assembly",model3dExplodedNotice:"Exploded · dimensions and references remain assembled",model3dLoadFailed:"Failed to load 3D model preview",model3dTimeout:"3D model transfer timed out. Check your connection and retry.",model3dDimensions:({dims:t})=>`Dimensions: ${t}`,model3dHintMouse:"Drag to orbit · two-finger pan · pinch or scroll to zoom",model3dHintTouch:"One finger to orbit · two fingers to zoom & pan",model3dFullscreenEnter:"Fullscreen",model3dFullscreenExit:"Exit fullscreen",model3dBgToLight:"Light background",model3dBgToDark:"Dark background",model3dRefresh:"Reload model",model3dClipToggle:"Section view",model3dClipPosition:"Section position",model3dClipFlip:"Flip section direction",model3dFeatureToggle:"Features",model3dFeatureStatus:({total:t,positioned:e})=>`Features: ${t} · positioned ${e}`,model3dFeatureInsert:"Insert reference",model3dGlossaryToggle:"Modeling terms",model3dPickToggle:"Select part / reference",model3dPickHint:"Select a part to hide it or insert a point reference",model3dHidePart:"Hide part",model3dShowAllParts:({count:t})=>`Show all (${t})`,model3dParts:"Parts",model3dCloseParts:"Close parts",model3dSearchParts:"Find a part",model3dClearPartSearch:"Clear part search",model3dHiddenParts:({count:t})=>`${t} hidden`,model3dShowNamedPart:({name:t})=>`Show ${t}`,model3dHideNamedPart:({name:t})=>`Hide ${t}`,model3dIsolateNamedPart:({name:t})=>`Only show ${t}`,model3dIsolatePart:"Only this part",model3dShowPart:"Show part",model3dNoParts:"No matching parts",model3dUndoVisibility:"Undo",model3dClearSelection:"Clear selection",model3dAllPartsVisible:"All parts visible",model3dInspectHint:"Drag to orbit · double-tap to zoom · double-tap empty space to fit",model3dUnnamedPart:({index:t})=>`Part ${t}`,model3dCanvas:"3D model",model3dMore:"More model options",edaLoading:"Rendering KiCad file…",reviewTargetChanged:"The active session changed. Return to the original session before inserting this reference.",reviewReference:"Review reference",reviewReferenceHint:"Add context, then insert. Nothing is sent automatically.",reviewSnapshot:"Snapshot of the selected viewer",reviewCapturing:"Capturing this view…",reviewIncludeImage:"Include snapshot (stored temporarily on this server)",reviewCaptureFailed:"Snapshot unavailable; location can still be inserted.",reviewNote:"Your comment (optional)",reviewNotePlaceholder:"What should change here?",reviewDetails:"View location and quoted content",reviewUploading:"Preparing reference…",reviewAddToDraft:"Add to context draft",reviewInsert:"Insert reference",reviewUploadFailed:"Could not prepare the reference. Your comment is kept. Retry, or uncheck the snapshot to insert text only.",edaLoadFailed:"Failed to render KiCad preview",edaTimeout:"KiCad preview rendering or transfer timed out. Please retry.",edaRefresh:"Render again",edaPickHint:"Click a schematic or PCB location to create an electronics annotation",edaPickedPosition:({x:t,y:e})=>`Selected ${t}%, ${e}%`,edaPickedBoardPosition:({x:t,y:e,object:r})=>`Board ${t}, ${e} mm · ${r}`,edaInspecting:"Reading board coordinates and nearby object…",edaNoNearbyObject:"No nearby object",edaInsertAnnotation:"Insert electronics annotation",csvUnnamedColumn:({index:t})=>`Column ${t}`,csvSelectedCell:({row:t,column:e})=>`Row ${t} · ${e}`,csvPickHint:({rows:t,columns:e})=>`${t} records · ${e} columns; click a cell to reference`,csvInsertAnnotation:"Insert table annotation",csvTablePreview:"Table preview: select a cell to reference its record",kicadLocalStateNotice:"This is local UI state and is not part of schematic, PCB, or manufacturing review.",kicadShowRawJson:"Show raw JSON",kicadProjectPickHint:"Select a setting to insert a reference",kicadInsertSetting:"Insert setting",markdownPreview:"Preview",markdownSource:"Source",markdownPreviewHint:"Tap a line/section to reference, tap another to extend; drag the left rail to select a range",htmlPreview:"Preview",htmlSource:"Source",htmlPreviewHint:"Sandboxed iframe preview; scripts run sandboxed",htmlFullscreenEnter:"Enter fullscreen preview",htmlFullscreenExit:"Exit fullscreen preview",markdownOutline:"Markdown outline",markdownOutlineShort:"Outline",closeMarkdownOutline:"Close outline",changedFromPath:({path:t})=>`from ${t}`,selectedLineFooter:({lineLabel:t})=>`Selected ${t}`,clearSelection:"Clear",allChanges:"All changes",backToChangeList:"Back to list",allRepositories:"All repositories",allRepositoriesShort:"All",repositories:"Repositories",gitRepositorySectionTitle:"Repository",gitRepositoryLabel:"Repository",gitRepositoryPlaceholder:"Select repository",gitRepositorySearchPlaceholder:"Search repositories",gitRepositoryEmpty:"No available repositories",selectRepositoryForGitActions:"Select a repository before running Git actions",selectRepositoryForDiff:"Select a repository or file to view diff",repoNotLoaded:"Tap to load",repoChangedCount:({count:t})=>`${t} change${t===1?"":"s"}`,repoStagedCount:({count:t})=>`${t} staged`,noChanges:"No changes",noMatchingChanges:"No matching changes",loadingGitChanges:"Loading Git changes…",loadingGitChangesSlow:"Large repositories can take a few seconds.",refreshingGitChanges:"Refreshing Git changes…",gitChangesLoadFailed:"Unable to load Git changes",retryGitChanges:"Retry",insertThisFile:"Insert this file reference into terminal",viewDiff:"View diff",diffViewMode:"Change file display mode",diffViewModeList:"Flat list",diffViewModeTree:"Folder tree",diffViewModeAi:"AI walkthrough",changeWalkthroughEmpty:"No AI walkthrough yet. Generate explanations to show the overview, flow, and checks here.",gitInfo:"Git context",wrapLongLines:"Wrap long lines",wrapOn:"Wrapped",wrapOff:"Raw",multiRepoScan:"Sub-repos",multiRepoScanTitle:"Scan this workspace for nested Git repositories. Off keeps a single-repo view, which opens much faster on large repos.",horizontalScrollHint:"Swipe left/right to see the full diff",stageFile:"Stage",stageAll:"Stage all",unstageFile:"Unstage",stashFile:"Stash",stashAll:"Stash all",restoreFile:"Restore",gitQuickActions:"Git Actions",gitUnavailable:"Current directory is not a Git repository",branchSectionTitle:"Current branch",currentBranchLabel:"Branch",switchBranchPlaceholder:"Select branch",switchBranchSearchPlaceholder:"Search local branch",switchNoBranches:"No local branches",switchBranch:"Switch",noStagedChangesShort:"no staged",stagedCount:({count:t})=>`${t} staged`,stagedCountShort:({count:t})=>`${t} staged`,commitSectionTitle:"Commit",commitReadyHint:({count:t})=>`${t} file${t===1?"":"s"} ready`,commitMessagePlaceholder:"Commit message",commitChanges:"Commit",commitNeedsStaged:"Stage changes before committing",recentCommitsTitle:"Recent commits",recentCommitsSearchPlaceholder:"Search commit hash or message",recentCommitsLoadMore:"Load more commits",recentCommitsEmpty:"No commit history",pushSectionTitle:"Remote sync",pushRemoteLabel:"Remote",pushRemotePlaceholder:"origin",pushRemoteSearchPlaceholder:"Search remote",pushNoRemotes:"No remotes",pushBranchLabel:"Target",pushBranchPlaceholder:({branch:t})=>`${t}`,pushBranchSearchPlaceholder:"Search branch",pushNoBranches:"No branches",pushUpstreamBadge:"upstream",pushCurrentBranchBadge:"current",pushNoUpstream:"No upstream configured",pushUpToDate:"Up to date with remote",pushAheadCount:({count:t})=>`${t} commit${t===1?"":"s"} to push`,pushBehindCount:({count:t})=>`${t} commit${t===1?"":"s"} to pull`,pushDivergedCount:({ahead:t,behind:e})=>`${t} ahead / ${e} behind`,pullChanges:"Pull",pushChanges:"Push",gitActionRunning:"Running…",gitActionFailed:({message:t})=>`Git action failed: ${t}`,confirmRestoreTitle:"Discard changes?",confirmRestoreDescription:({path:t})=>`This will discard unstaged changes in ${t}. Termdock cannot recover them.`,confirmRestorePhrase:"discard changes",confirmRestorePlaceholder:"Type “discard changes” to confirm",confirmStashAllTitle:"Stash all changes?",confirmStashAllDescription:"This moves current working tree changes, including untracked files, into a stash.",confirmAction:"Confirm",renderingHtml:"Rendering HTML…",footnotes:"Footnotes",backToFootnote:({index:t})=>`Back to footnote ${t}`,openMermaidDiagram:"Open Mermaid diagram",mermaidDiagram:"Mermaid diagram",renderingDiagram:"Rendering diagram…",markdownImage:"Markdown image",image:"Image",previousImage:"Previous image",nextImage:"Next image",closeImagePreview:"Close image preview",emptyFile:"Empty file.",insertReference:({reference:t})=>`Insert reference: ${t}`,copyReference:({reference:t})=>`Copy reference: ${t}`,byteCount:({count:t})=>`${t} bytes`,previewTruncated:"Preview truncated to 1 MB",branchCandidatesLoading:"Loading branch candidates…",includeUncommitted:"Include local uncommitted changes",includeUncommittedHint:"Include working tree and untracked diffs when viewing or explaining changes",missingBaseReposSkipped:({repositories:t})=>`Repositories without a base branch will be skipped: ${t}`,localBranch:"local",remoteBranch:"remote"},fileTree:{insertRef:"Insert",insertRefTitle:"Insert file reference into active terminal",openDirRoot:"Open",openDirRootTitle:"Use this folder as the current browsing root",openInFileBrowser:"Reveal in Finder",openInFileBrowserTitle:"Open this item in the system file browser",openInFileBrowserFailed:"Failed to open file browser",moreDirActions:"More folder actions",searchFromDir:"Search from here",searchFromDirTitle:"Search only this folder and its descendants",pinDir:"Pin",pinDirTitle:"Pin this folder to the current project",unpinDir:"Pinned",unpinDirTitle:"Unpin this folder",pinFileTitle:"Pin this file to the current project",unpinFileTitle:"Unpin this file",pinFile:"Pin",unpinFile:"Unpin",moreFileActions:"More file actions",deleteFile:"Delete file",deleteFileConfirm:({name:t})=>`Delete “${t}”? This action cannot be undone.`,deleteFileFailed:({message:t})=>`Failed to delete file: ${t}`,noWorkingDir:"No working directory detected.",emptyDir:"Empty directory.",noMatchingFiles:"No matching files.",searching:"Searching files…",searchingWithCount:({count:t})=>`Searching… ${t} found`,searchResults:({count:t})=>`${t} results`,searchScope:"Search scope",searchTruncatedHint:({count:t})=>`Fallback search scanned a large directory and stopped after ${t} matches. Install ripgrep or refine the query for complete results.`,searchStillRunning:"Search is still running. More results will appear automatically.",showingSearchResults:({shown:t,total:e})=>`Showing ${t} of ${e}`,loadMoreSearchResults:({shown:t,total:e})=>`Show more (${t}/${e})`,contentMatchesCount:({count:t})=>`${t} file${t===1?"":"s"} with matches`,moreMatches:({count:t})=>`+${t} more match${t===1?"":"es"}`,noContentMatches:"No matches found in file contents.",contentSearchNeedsRipgrep:"Content search requires ripgrep (rg). Install it on the server to search inside files.",truncatedHint:"Showing first 1000 entries. Use search or open a smaller folder for better performance.",dropToUploadHere:"Upload here",symbolicLink:"Symbolic link",sortByModified:"Sort by recent changes",sortByName:"Sort by name",sortedByModified:"Sorted by recent changes"},diffViewer:{noFileChanges:"No changes in this file.",noUnstagedChanges:"No unstaged changes.",emptyHint:"Make some changes, or pull from a remote.",loading:"Loading diff…",insertAllDiff:"Insert current diff as context",insertFileDiff:"Insert this file's diff",insertHunkDiff:"Insert this hunk",insertHunkShort:"Insert",insertFileShort:"Insert",insertAllShort:"Insert all",stageHunk:"Stage",stageHunkTitle:"Stage only this hunk (git apply --cached)",revertHunk:"Revert",revertHunkTitle:"Revert this hunk in the worktree (cannot be undone)",revertHunkConfirm:"Confirm revert?",hunkActionApplying:"Applying…",hunkActionUnavailable:"Cannot build a patch for this hunk",hunkActionFailed:({message:t})=>`Failed: ${t}. If the changes moved on, refresh and retry.`,auditExplanation:"Change meaning",auditStale:"Explanation stale",auditClear:"Clear explanation",auditGeneratedAt:({time:t})=>`Generated ${t}`,allDiffLabel:"all changes",allChangesLabel:"all changes",workingTree:"Working tree changes",allUnstaged:"All unstaged changes",binaryOrEmpty:"No textual changes to display.",noFinalNewline:"No newline at end of file",noHunks:"No hunks",hunkOutline:"Hunks",expandHunkRail:"Show hunk list",collapseHunkRail:"Hide hunk list",prevHunk:"Previous hunk",nextHunk:"Next hunk",prevFile:"Previous",nextFile:"Next",expandFile:"Expand file",collapseFile:"Collapse file",expandAll:"Expand all",collapseAll:"Collapse all",collapseHunk:"Collapse hunk",useBracketKeysHint:"Press [ / ] to jump between hunks",unified:"Unified",unifiedMode:"Unified view",split:"Split",splitMode:"Side-by-side view",moreActions:"More actions",view:"View",loadingPreviousFile:"Loading previous file…",loadingNextFile:"Loading next file…",resizeNavigation:"Resize diff navigation",focusPathHint:"Select a label to focus its path",whitespace:"Whitespace",whitespaceDefault:"Default",whitespaceTrim:"Ignore trailing",whitespaceIgnore:"Ignore all",whitespaceIgnoreBlankLines:"Ignore blank lines",context:"Context",contextLines:({count:t})=>`${t} lines`,contextAll:"All"},settings:{title:"Settings",font:"Font",render:"Render",theme:"Theme",darkTheme:"Dark",lightTheme:"Light",newTab:"New tab",debug:"Debug",noSleep:"No sleep",noSleepUnavailable:"No network — disabled",updateTitle:"Termdock update",updateRuntimeTitle:"CLI and service runtime",updateHint:"A manual check downloads and installs a new version immediately. The service restarts only after you confirm.",updateCheck:"Check for updates",updateCheckAgain:"Check again",updateChecking:"Checking npm for the latest version…",updateCheckingShort:"Checking…",updateInstallingShort:"Installing…",updateCurrent:"Termdock is up to date.",desktopUpdateTitle:"macOS desktop app",desktopUpdateHint:"Manually check signed desktop releases published on GitHub.",desktopUpdateUnsupported:"In-app updates require an installed, signed macOS app.",desktopUpdateChecking:"Checking for a desktop update…",desktopUpdateCurrent:"The desktop app is up to date.",desktopUpdateDownloading:"A new version is downloading in the background…",desktopUpdateReady:"The desktop update is downloaded and ready to install.",desktopUpdateInstalling:"Restarting to install the desktop update…",desktopUpdateCheck:"Check desktop app",desktopUpdateCheckAgain:"Check again",desktopUpdateRestart:"Restart and install",desktopUpdateRestartConfirm:"Restart Termdock and install the downloaded desktop update? The terminal service and tmux sessions will remain running.",notifications:"Notify",notificationsTitle:"Notification settings",notificationsHint:"Notify when an AI task finishes while Termdock is hidden.",notificationsPageHint:"Choose which Termdock events can send system notifications. The master switch controls browser permission and delivery; event switches decide what should notify you.",notificationsMaster:"System notifications",notificationsMasterHint:"Allow Termdock to send notifications when it is hidden or running as an installed PWA.",notificationsIOSInstallHint:"On iPhone and iPad, install Termdock to the Home Screen before enabling notifications.",notificationsPermission:"Permission",notificationsPermissionSystem:"Managed by macOS",notificationsTest:"Send test",notificationsTestChecking:"Waiting for macOS to confirm delivery…",notificationsTestDelivered:"Delivered to Notification Center. If no banner appeared, check the alert style and Focus.",notificationsTestFailed:"macOS did not deliver the notification. Allow Termdock in System Settings.",notificationsOpenSystemSettings:"Open system notification settings",notificationsAlertStyle:"Alert style",notificationsAlertStyleHint:"Browsers and Android still decide the final heads-up behavior. Termdock can only request quiet/default/sticky notification options.",notificationsStyleNormal:"Default",notificationsStyleNormalHint:"Sound/vibration if allowed",notificationsStyleQuiet:"Quiet",notificationsStyleQuietHint:"Status tray, no sound",notificationsStylePersistent:"Sticky",notificationsStylePersistentHint:"Stay until dismissed",notificationsEvents:"Events",notificationsAiFinished:"AI task finished",notificationsAiFinishedHint:"Notify when an AI agent stops while Termdock is in the background.",notificationsSessionExited:"Terminal exited",notificationsSessionExitedHint:"Notify when a terminal process exits on its own (closing it yourself does not trigger; delivered via Web Push).",notificationsFutureHint:"More notification types can be added here later without changing the top-level settings layout.",notificationsOffSummary:"System notifications disabled",notificationsAiOnSummary:"AI task finished enabled",notificationsExitOnSummary:"Terminal exit enabled",notificationsBothOnSummary:"AI task finished and terminal exit enabled",notificationsNoEventsSummary:"No notification events enabled",notificationsDenied:"Browser notification permission is blocked. Enable it in site settings.",notificationsUnsupported:"Notifications require a secure context and service worker support.",notificationsTestBody:"Notifications are enabled. You will be notified when an AI task finishes in the background.",shell:"Shell",tmux:"Tmux",auto:"Auto",webgl:"WebGL",canvas:"Built-in",tmuxServer:"Tmux server",tmuxUnavailable:"unavailable",noTmuxSessions:"No tmux sessions on the server.",installTmuxHint:"Install tmux on the server to enable.",refresh:"Refresh",attached:"Attached",restorable:"Restorable",attach:"Attach",attaching:"Attaching…",destroy:"Destroy",sessions:({n:t})=>`${t} session${t===1?"":"s"}`,windows:({n:t})=>`${t} window${t===1?"":"s"}`,keyboardToolbar:"Keyboard toolbar",aiAgentDetection:"AI agent detection",signOut:"Sign out",language:"Language",programNamePlaceholder:"Program name (e.g. claude)",patternPlaceholder:"Regex pattern (e.g. Thinking|Generating)",statusPlaceholder:"Status",addProgram:"Add program",addPattern:"Add pattern",resetDefaults:"Reset defaults",invalidRegex:"Invalid regex",removeProgram:"Remove program",removeRule:"Remove rule",keepLabel:"keep",customColor:"Custom color",tabIndicator:"Tab indicator style",toolbarPresets:"Toolbar presets",detectionRules:"Detection rules",agentHooksHint:"With hooks installed, agents report their own status: working (green), waiting for you (amber), turn done (check) — and you get a notification the moment one needs your input. Hooks install globally but only fire inside termdock terminals.",agentHooksInstall:"Install",agentHooksInstalled:"Installed",agentHooksOutdated:"Outdated",agentHooksNeedsApproval:"Needs approval",agentHooksApprovalHint:"Run /hooks in Codex and approve the Termdock hooks",agentHooksNotInstalled:"Not installed",agentHooksUninstall:"Uninstall",agentHooksReinstall:"Reinstall",agentHooksDevMode:"Dev mode: hooks point at TS sources and need a built install to fire",agentHooksTarget:"writes to",agentAutoRename:"Automatic session titles",agentAutoRenameHint:"Update the title from recent work when an agent finishes a turn. Off by default; manual titles are never overwritten. External plugin CLIs run only after their title feature is enabled.",agentAutoRenameToggle:"Toggle automatic titles for this agent",agentAutoRenameShort:"Auto title",agentAutoRenameNamer:"Title agent",agentAutoRenameFollow:"Follow current session",agentAutoRenameModelsFromCli:"Models discovered from local CLIs",agentAutoRenameRefreshModels:"Refresh CLI models",agentAutoRenameCliDefault:"CLI default model",agentAutoRenameAutomatic:"Automatic selection",agentAutoRenameNoCli:"No supported title CLI detected",agentAutoRenameAdvanced:"Advanced title preferences",agentAutoRenamePreference:"Additional preferences",agentAutoRenamePreferenceHint:"Optional. Add preferences for title style or emphasis; Termdock keeps its default naming rules. Saved when you leave the field.",agentAutoRenamePreferencePlaceholder:"For example: emphasize user value; use action phrases; avoid technical jargon",agentAutoRenamePayloadLimit:"User-message context limit (characters)",agentAutoRenamePayloadLimitHint:"Total raw prompt-submit payload characters retained. Default 12000; range 1000–64000.",agentPlugins:"Agent Plugins",agentPluginAdd:"Add Plugin",agentPluginHint:"Install from an HTTPS Git repository or local directory after reviewing the source. Hooks and executable title CLIs require separate user opt-in.",agentPluginCreate:"Create Plugin",agentPluginDelete:"Delete Plugin",agentPluginInvalid:"Invalid plugin manifest",agentPluginCopyAiPrompt:"Copy AI fix prompt",agentPluginCopied:"Copied",agentPluginSourcePlaceholder:"https://github.com/user/agent-plugin or local directory",agentPluginInstallPackage:"Install plugin",agentPluginAdvancedManifest:"Advanced: paste manifest.json",agentPluginUpdateAvailable:"Update available",agentPluginManualSource:"Manual manifest",agentPluginUpdate:"Update",agentPluginCheck:"Check",agentPluginDoctor:"Diagnose",agentPluginDoctorHint:"Explicitly probe plugin models without generating a title",agentPluginDoctorStatusOk:"Title and model capabilities are healthy",agentPluginDoctorStatusMissing:"titleNamer is not declared",agentPluginDoctorStatusCliDefault:"Titles are available using the CLI default model",agentPluginDoctorStatusNoModels:"No usable model data was returned",agentPluginDoctorStatusFailed:"Model probe failed",agentPluginDoctorModels:"usable models",agentPluginDoctorAutomatic:"automatic",agentPluginDoctorCliDefault:"When no model is specified, the Agent CLI default model is used",agentAutoRenameInterval:"Recheck interval",agentAutoRenameMinutes:"minutes",mobileKeyboard:"Mobile keyboard",saving:"Saving…",rulesHint:"Configure regex patterns to detect what an AI tool is doing in a terminal tab. Each rule can choose its label, color, icon style and how long the indicator is kept after output quiets down. When it stops and you haven't viewed the tab yet, the tab keeps a yellow review hint.",programsHelp:"Supports multiple programs in one config. Separate with commas.",programLabelResolution:"Program label resolution",rawCommandMapping:"Raw command mapping",rawCommandMappingHint:"Rules below map the raw command line to the tab display label. User rules run before built-ins.",genericProgramNames:"Generic program names",genericProgramNamesHint:"Trigger ps-based deep detection (e.g. node, python)",wrapperScriptNames:"Wrapper script names",wrapperScriptNamesHint:"CLI wrappers that launch another tool (e.g. aiden, npx)",shellNamesConfig:"Shell names",shellNamesHint:"Filtered out from tab display (e.g. bash, zsh)",addTag:"+ add",customRules:"Custom rules",addRule:"Add rule",localAccess:"Local access",localAccessHint:"Use this LAN URL from your phone after trusting the local CA. Open Mobile setup on your phone to download the CA certificate.",resetAutoName:"Reset auto",onboardingUrl:"Mobile setup",httpsActive:"HTTPS active",httpsInactive:"HTTPS inactive",caMissing:"CA download unavailable",closeSettings:"Close settings",desktopTitle:"Termdock Desktop",desktopStatusLoading:"Reading native macOS status…",desktopSwitchService:"Switch service",desktopInstallCli:"Install / Repair CLI",desktopCliUpdated:"CLI status updated",desktopOpenDataDirectory:"Open data directory"},toolbarPresets:{preview:"Preview",presets:"Presets",label:"Label",new:"New",reset:"Reset",presetLabelPlaceholder:"Preset label",deletePreset:({name:t})=>`Delete preset ${t}`,matchPrograms:"Match programs",typeEnterHint:"Type & Enter",programsPlaceholder:"vim, nvim, /^claude(-code)?$/i …",programsHelp:"Plain names match as case-insensitive substrings. Wrap in /…/flags for regex (tested against the lowercase program name).",altSlot:"Alt modifier slot",altSlotHint:"Reserve one preview slot for the Alt key.",desktopVisibility:"Show on desktop",desktopVisibilityHint:"Desktop shows only this preset’s custom actions, not the basic keyboard shortcuts.",rowLayout:"Row layout",rowLayoutHint:"Buttons per expanded row.",addRow:"Row",rowN:({n:t})=>`Row ${t}`,del:"Del",buttons:"Buttons",buttonsHint:"Tap to edit. Use ↑↓ to reorder.",addButton:"Add button",noCustomButtons:"No custom buttons yet. Add one to override the default toolbar.",moveUp:"Move up",moveDown:"Move down",removeRow:({n:t})=>`Remove row ${t}`,removeAction:({name:t})=>`Remove ${t}`,labelField:"Label",labelPlaceholder:"Label shown on the button",sequence:"Sequence",sequencePlaceholder:"e.g. /undo or \\t or /||undo",sequenceHint:"Double-tap sequence",doubleTap:"Double-tap sequence",doubleTapAdd:"+ Add",doubleTapPlaceholder:"e.g. /undo\\r or /||undo ||\\r",remove:"Remove",noSequence:"No sequence",preset:"Preset",overCapacityHint:"More buttons than slots. Extra rows will use the last row size."},agentRules:{ruleColors:{green:"Green",yellow:"Yellow",red:"Red",blue:"Blue",purple:"Purple",orange:"Orange",gray:"Gray"}},tab:{session:"Session",new:"New session",rename:"Rename",renameHint:"Change the tab display name",renamePlaceholder:"Leave empty to reset to default",copyCwd:"Copy cwd",copyCwdHint:"Copy the current working directory",resumeAgent:"Resume agent session",resumeAgentHint:"Resume the last conversation by its native session id",resumeAgentAvailable:"Agent conversation available to resume",resumeAgentRecoveredTitle:({agent:t})=>`${t} conversation available`,resumeAgentRecoveredHint:"This terminal was rebuilt after an interruption. Continue where you left off.",resumeAgentNow:"Resume",resumeAgentLater:"Dismiss for now",resumeAgentSubmitting:"Submitting the native resume command…",resumeAgentWaiting:"Waiting for the Agent to confirm the restored conversation…",resumeAgentSuccess:({agent:t})=>`${t} conversation restored`,resumeAgentFailed:"Could not resume the Agent conversation. You can retry.",resumeAgentConflict:"This Agent conversation is already open in another terminal.",resumeAgentBusy:"Wait for the current Agent turn to finish before resuming.",resumeAgentTimeout:"The Agent did not confirm the restored conversation. Check the terminal or retry.",tmuxRecoveryTitle:({count:t})=>`tmux exited unexpectedly; ${t} Agent session(s) can be restored`,tmuxRecoveryHint:"Termdock kept the native session IDs. Restore continues each conversation in its original tab.",tmuxRecoveryRestoreAll:"Restore all",tmuxRecoveryRestoring:"Restoring…",tmuxRecoveryDismiss:"Not now",tmuxRecoveryPartial:({restored:t,failed:e})=>`Restored ${t}; ${e} still need attention.`,tmuxRecoveryFailed:"Recovery failed. Check the terminals and try again.",tmuxRecoveryDismissFailed:"Could not dismiss the recovery notice.",copied:"Copied",close:"Close session",closeHint:"Remove this tab from the list",longPressTip:"Tip: hold a tab still for a moment to open actions; hold and drag to reorder.",sessionsTitle:"Sessions",explorerTitle:"Explorer",split:"Split",splitTitle:"Add to split workspace",splitNew:"New session in workspace",splitNewHint:"Uses the current directory and default type; add as many panes as needed",splitExisting:"Choose a session or workspace",splitExistingHint:"Create multiple independent workspaces; choosing another workspace merges them",splitCurrent:"Current",splitClose:"Exit split",splitLayout:"Split layout",splitHorizontal:"Side by side",splitVertical:"Stacked",splitGrid:"Grid",splitWorkspace:"Split group",splitWorkspaces:"Split workspaces",splitRename:"Rename split group",splitRemovePane:"Remove from split",splitExistingGroups:"Existing split groups",splitAvailableSessions:"Available sessions",splitOccupied:"Grouped",splitUnavailableGrouped:"Grouped mode only supports sessions in the same directory",splitEndedGrouped:"Split ended: grouped mode does not support mixed directories",splitNoOtherSessions:"No other sessions are available",sessionCount:({count:t})=>`${t} session${t===1?"":"s"}`,closeChooserTitle:"Destroy tmux session?",closeChooserDescription:"This will stop the session and every process inside it. This cannot be undone.",destroySession:"Destroy session",confirmDestroySession:"Confirm destroy",destroySessionHint:"Stop the tmux session and every process inside it.",dragToClose:"Drag here to close",releaseToClose:"Release to confirm"},agent:{aiRunning:"AI running",needsReview:"Needs review",finishedReview:"AI finished — needs review",aiWaiting:"AI waiting",copyMode:"Copy mode",jumpToNext:"Jump to next session needing attention",jumpToNextRunning:"Jump to next running session",selectRunningSession:"Select a running session",runningSessionGestureHint:"Tap to cycle · swipe sideways to select · hold to drag",currentSession:"Current"},connection:{reconnecting:"Reconnecting…"},desktopServices:{switchService:"Switch Termdock service",openServices:"Open services",idle:"Idle",manageServices:"Manage services and names"},terminal:{input:"Terminal input",error:"Error",dropFilesToPastePaths:"Drop files to paste paths",loading:"Loading terminal…",initializing:"Initializing terminal engine…",failedToLoad:"Failed to load terminal",unknownError:"An unknown error occurred",componentFailed:"Terminal component failed to load",paste:"Paste",copied:"Copied",copyFailed:"Copy failed",longPressSelectsText:"Long press selects text",longPressSendsArrows:"Long press sends arrow keys",switchLongPressToArrows:"Switch long press to arrow keys",switchLongPressToCopy:"Switch long press to copy selection"},quota:{title:"Subscription Quota",noProviders:"No subscription providers detected.",noProvidersHint:"Quota tracking becomes available when you use AI coding agents with API keys or OAuth login.",exhausted:"Exhausted",left:({n:t})=>`${t} left`,updated:({time:t})=>`Updated ${t}`,refresh:"Refresh",close:"Close"},errorBoundary:{title:"Something went wrong",unexpected:"An unexpected error occurred",retry:"Try Again",copyDetails:"Copy error details",copied:"Copied",copyFailed:"Copy failed"},error:{type:{network:"Network error",session:"Session error",terminal:"Terminal error",auth:"Authentication error",validation:"Validation error",unknown:"Unknown error"},severity:{low:"Notice: ",medium:"Warning: ",high:"Error: ",critical:"Critical: "},suggestion:{networkCheck:"Check your network connection",networkRetry:"Try reconnecting",networkProxy:"Check proxy settings",networkWait:"Wait for the network to recover",sessionRecreate:"Recreate the session",sessionServer:"Check the server status",sessionCache:"Clear your browser cache",terminalRestart:"Restart the terminal",terminalConfig:"Check the terminal configuration",terminalClear:"Clear the terminal output",authRelogin:"Sign in again",authCredentials:"Check your credentials",authAdmin:"Contact the administrator",validationFormat:"Check the input format",validationParams:"Verify your parameters",validationDocs:"See the documentation",unknownReload:"Reload the page",unknownApp:"Restart the app",unknownSupport:"Contact support"}}},Q2={app:{name:"Termdock"},common:{cancel:"取消",close:"关闭",save:"保存",reset:"重置",loading:"加载中…",error:"错误",retry:"重试",refresh:"刷新",search:"搜索",clear:"清除",delete:"删除",on:"开",off:"关",back:"返回",copy:"复制",decrease:"减少",increase:"增加",use:"使用",previous:"上一个",next:"下一个"},login:{prompt:"termdock login",placeholder:"请输入密码",placeholderBlocked:({s:t})=>`请稍候 ${t}s`,submit:"登录",invalidPassword:"密码错误",failed:"登录失败"},sidebar:{sessions:"会话",noSessions:"暂无打开的会话。",noMatchingSessions:"没有匹配的会话。",toggleSearch:"切换搜索",settings:"设置",moreActions:"更多操作",subscriptionQuota:"订阅额度",pinSidebar:"常驻边栏",unpinSidebar:"取消常驻",runningSessionButton:"运行中会话按钮",runningSessionButtonHint:"轻点循环,横向滑动选择,长按拖动",updateAvailable:({version:t})=>`Termdock ${t} 可用`,updateInstalling:"正在后台安装,不会中断当前服务。",updateReady:"更新已安装,确认后将重启服务。",updateRestart:"重启并完成更新",updateRestartConfirm:({version:t})=>`确认重启 Termdock 并切换到 ${t}?当前网页会短暂重连,会话不会被关闭。`,updateRestarting:"正在重启,网页将自动重连…",updateFailed:"自动安装失败,提醒会保留。",updateRetry:"重新尝试",filterSessions:"过滤会话",clearSearch:"清除搜索",groupByFolder:"按文件夹分组",groupByFolderTitle:"按工作目录把会话归组折叠;与拖拽排序互斥。",ungrouped:"其他",needsAttention:"待处理",waitingForYou:"等你操作",completedUnread:"完成待查看",closeSession:({name:t})=>`关闭 ${t}`,newShell:"Shell",newTmux:"Tmux",newTmuxDisabled:"服务端未安装 tmux",confirmNewShell:"创建 Shell?",confirmNewTmux:"创建 Tmux?",newSession:"新建 Terminal",newSessionWithAgent:({agent:t})=>`新建 ${t}`,moreLaunchOptions:"更多启动选项",recoverableSessions:"可恢复会话",refreshRecoverableSessions:"刷新可恢复会话",restoreRecoverableSession:({name:t})=>`恢复 ${t}`,restoringRecoverableSession:"恢复中…",restore:"恢复",newSessionAdvanced:"快速启动 Agent",newSessionComposerTitle:"开始新会话",newSessionHint:"选好运行方式和目录后再启动",launchSessionWith:({name:t})=>`启动 ${t}`,setNewSessionDefault:({name:t})=>`将 ${t} 设为默认`,currentNewSessionDefault:({name:t})=>`${t} 是当前默认`,currentDefaultAgent:({name:t})=>`当前默认:${t}`,defaultAgent:"默认",makeDefault:"设为默认",sessionMode:"运行方式",tmuxKeepsRunning:"断开后继续运行",resumeHistory:"最近会话",resumeHistoryCount:({n:t})=>`已保存 ${t} 条`,resumeHistoryLoading:"正在载入最近的 Agent 会话…",resumeHistoryAction:({title:t})=>`恢复 ${t}`,resumeHistoryRemove:({title:t})=>`从最近会话中移除 ${t}`,resumeHistoryLoadFailed:"无法载入最近的 Agent 会话。",resumeHistoryFailed:"无法准备恢复该 Agent 会话。",resumeHistoryRemoveFailed:"无法从历史中移除该会话。",workingDirectory:"工作目录",directoryPlaceholder:"输入目录路径",browseDirectories:"浏览目录",hideDirectoryBrowser:"收起目录",chooseDirectory:"选择工作目录",directoryPickerHint:"进入文件夹,确认后才会更改工作目录。",useThisFolder:"使用此目录",recentDirectories:"最近使用的目录",startCommand:"启动命令",customCommand:"其他命令",commandPlaceholder:"可选,例如 codex",detectAgents:"重新检测 Agent",savePreset:"保存为预设",createAndRun:"创建并运行",createSession:"创建 Terminal",openLeftSidebar:"打开左侧边栏",openRightSidebar:"打开右侧边栏",closeSidebar:"关闭边栏"},rightSidebar:{workspace:"工作区",currentProject:"项目",browsingLocation:"浏览中",parentFolder:"上一级目录",backToProjectRoot:"回到当前项目",refreshFiles:"刷新当前目录",resizeFileTree:"拖动调整文件目录宽度",pinCurrentFolder:"固定当前目录到这个项目",unpinCurrentFolder:"取消固定当前目录",showHiddenFiles:"显示隐藏文件",hideHiddenFiles:"不显示隐藏文件",insertCurrentFolder:"引用当前目录",insertCurrentFolderShort:"引用",pinnedFolders:"固定",unpinFolder:({name:t})=>`取消固定 ${t}`,fileWatchUnavailable:({message:t})=>`文件监听不可用:${t}。可点击手动刷新。`,browsingOutsideProject:"正在浏览当前项目外目录",browsingOutsideProjectHint:"Git 和改动仍使用当前项目;这里引用的文件会按外部路径插入。",toggleSearch:"切换搜索",refreshGit:"刷新 Git 状态",gitLastUpdated:({time:t})=>`上次更新:${t}`,close:"关闭",filterChanges:"过滤改动或文件",searchPlaceholderContent:"在文件内容中搜索…",searchModeName:"文件",searchModeContent:"内容",clearSearch:"清除搜索",searchScope:"范围",searchScopePlaceholder:"相对目录或绝对路径",resetSearchScope:"恢复搜索当前目录",searchOptions:"搜索选项",searchExclude:"排除",searchExcludePlaceholder:"dist/**, *.lock",clearSearchExclude:"清空排除规则",contentSearchOptions:"内容搜索选项",matchCase:"区分大小写",matchWholeWord:"全词",useRegex:"正则",insertGitContext:"把当前 Git 信息插入 Terminal",copyGitContext:"复制 Git 信息",insertChangeAuditPrompt:"解释当前改动",insertChangeAuditPromptTitle:"把更改审计提示词插入当前会话",changeAuditShort:"解释当前改动",changeAuditLoading:"正在加载 hunk 解释…",changeAuditLoaded:({count:t})=>`已加载 ${t} 条 hunk 解释`,changeAuditLoadedAt:({time:t})=>`最近生成 ${t}`,changeAuditRegenerate:"重新生成",changeAuditRefreshStale:"补充失效",changeAuditRefreshStaleTitle:"为已失效的 hunk 解释插入补充生成提示词",clearChangeAudit:"清理",clearChangeAuditTitle:"清理当前仓库的 hunk 解释",changeAuditClearFailed:({message:t})=>`清理 hunk 解释失败:${t}`,changeAuditScopeAll:"全部仓库",changeAuditScopeLabel:"解释范围",branchAuditTitle:"分支解释",branchAuditShort:"解释分支改动",branchAuditBaseLabel:"基线分支",branchAuditBasePlaceholder:"基线分支,例如 master",branchAuditBaseSearchPlaceholder:"搜索基线分支",branchAuditBaseEmpty:"没有可选分支,可直接输入分支名",branchAuditGenerate:"生成解释",branchAuditRegenerate:"重新生成",branchAuditGenerateTitle:"生成当前分支相对于基线分支的解释提示词",branchAuditViewDiff:"查看对比",branchAuditViewDiffTitle:"查看目标分支相对于基线分支的改动",branchAuditDiffLoading:"正在加载分支对比…",branchAuditDiffEmpty:"当前分支相对于基线分支暂无改动。",branchAuditMissingBase:({repo:t})=>`${t} 未设置基线分支`,branchAuditRefreshDiff:"刷新对比",branchAuditRefreshStale:"补充失效",branchAuditRefreshStaleTitle:"为已失效的分支解释插入补充生成提示词",branchAuditClearTitle:"清理当前分支解释",branchAuditClearFailed:({message:t})=>`清理分支解释失败:${t}`,branchAuditCommitCount:({count:t})=>`${t} 个提交`,branchAuditFileCount:({count:t})=>`${t} 个文件`,branchAuditTruncated:"diff 已截断",branchAuditCurrent:"已保存解释",branchAuditStale:"解释已失效",branchAuditEmpty:"暂无分支解释。生成后会持久化保存,可随时回来查看。",branchAuditView:"查看解释",branchAuditSaved:({count:t})=>`已保存 ${t} 条 hunk 解释`,branchAuditGeneratedAt:({time:t})=>`生成于 ${t}`,insertPreset:({label:t})=>`插入:${t}`,tabChanges:"改动",tabGit:"Git",tabFiles:"文件",inserted:"已插入",copied:"已复制",toggleContextDraft:"切换上下文草稿",contextDraftTitle:"上下文草稿",contextDraftHint:"启用后,引用会追加到这里;可以继续浏览、补写描述,最后一次插入。",contextDraftPlaceholder:"在这里组织长提示词,继续点击侧栏中的引用来追加上下文…",contextDraftCollapse:"收起上下文草稿",contextDraftExpand:"展开上下文草稿",contextDraftDisable:"停用上下文草稿",contextDraftClear:"清空草稿",contextDraftInsert:"插入",contextDraftInsertAndSend:"插入并发送",contextDraftInserted:"已插入",contextDraftSent:"已发送",contextDraftSend:"发送草稿",contextDraftAppended:"已追加引用",contextDraftResize:"拖动调整高度,双击恢复默认",contextDraftAutoCollapseAfterSend:"插入/发送后收起",contextDraftInsertFailed:"终端未连接,草稿已保留",contextDraftCharacterCount:({count:t})=>`${t} 字`,selectFilePrompt:"选择文件以预览内容",backToFileList:"返回文件列表",backToPreviousPreview:"返回来源文档",insertLineRef:({lineLabel:t})=>`引用${t}`,insertFileRef:"引用",copyFileRef:"复制文件引用",findInFile:"在文件内查找",findInFilePlaceholder:"在当前文件中查找…",previousSearchMatch:"上一个匹配项",nextSearchMatch:"下一个匹配项",closeFileSearch:"关闭文件搜索",downloadFile:"下载文件",downloadFailed:"下载失败",uploadFile:"上传文件",uploadFiles:"上传文件",insertLocalFile:"插入本地文件",insertLocalImage:"插入本地图片",layoutMode:"显示模式",layoutModeAuto:"自动",layoutModeNarrow:"窄版",layoutModeWide:"宽版",dropToUpload:"拖放文件以上传",uploading:"上传中…",uploadSuccess:({count:t})=>`已上传 ${t} 个文件`,uploadFailed:"上传失败",binaryPreviewHint:"二进制文件无法预览,请使用上方下载按钮保存到本地",selectedLineHint:({lineLabel:t})=>`已选 ${t} · 点下方「引用」按钮插入`,multiLineHint:"多行引用:先点起始行,再点结束行",loadingImage:"正在加载图片…",imagePreviewHint:"双指捏合或 ⌘/Ctrl + 滚动缩放 · 双击还原",imageLoadFailed:"图片预览加载失败",loadingVideo:"正在加载视频…",videoPreviewHint:"点击播放 · 长按 2× · 可拖动进度条",videoLoadFailed:"视频预览加载失败",videoUnsupported:"当前浏览器不支持该视频格式",videoPlay:"播放",videoPause:"暂停",videoLongPressSpeed:"长按 2× 播放",videoRotate:"顺时针旋转 90°",videoFullscreenEnter:"全屏播放",videoFullscreenExit:"退出全屏",model3dLoading:"正在加载 3D 模型…",model3dExplode:"爆炸展开",model3dExplodeAxis:"展开方向(查看器坐标)",model3dExplodeAmount:"展开程度",model3dHome:"回正并看全",model3dFit:"看全可见零件",model3dFront:"正视图",model3dTop:"俯视图",model3dRight:"右视图",model3dAssemble:"恢复装配",model3dExplodedNotice:"爆炸展示 · 尺寸与引用仍为原始装配坐标",model3dLoadFailed:"3D 模型预览加载失败",model3dTimeout:"3D 模型传输超时,请检查连接后重试。",model3dDimensions:({dims:t})=>`尺寸: ${t}`,model3dHintMouse:"拖拽旋转 / 双指平移 / 捏合或滚轮缩放",model3dHintTouch:"单指旋转 / 双指缩放平移",model3dFullscreenEnter:"全屏查看",model3dFullscreenExit:"退出全屏",model3dBgToLight:"切换为白底",model3dBgToDark:"切换为黑底",model3dRefresh:"重新加载模型",model3dClipToggle:"切面查看",model3dClipPosition:"切面位置",model3dClipFlip:"反转切面方向",model3dFeatureToggle:"特征标注",model3dFeatureStatus:({total:t,positioned:e})=>`特征: ${t} 个 · 已定位 ${e}`,model3dFeatureInsert:"引用",model3dGlossaryToggle:"建模名词说明",model3dPickToggle:"选择零件 / 引用",model3dPickHint:"点选零件后可临时隐藏,或引用所选位置",model3dHidePart:"隐藏零件",model3dShowAllParts:({count:t})=>`显示全部(${t})`,model3dParts:"零件",model3dCloseParts:"关闭零件列表",model3dSearchParts:"查找零件",model3dClearPartSearch:"清空零件搜索",model3dHiddenParts:({count:t})=>`已隐藏 ${t}`,model3dShowNamedPart:({name:t})=>`显示 ${t}`,model3dHideNamedPart:({name:t})=>`隐藏 ${t}`,model3dIsolateNamedPart:({name:t})=>`只看 ${t}`,model3dIsolatePart:"只看此件",model3dShowPart:"显示零件",model3dNoParts:"没有匹配的零件",model3dUndoVisibility:"撤销",model3dClearSelection:"取消选择",model3dAllPartsVisible:"全部可见",model3dInspectHint:"单指旋转 · 双指缩放平移 · 双击局部放大,双击空白看全",model3dUnnamedPart:({index:t})=>`零件 ${t}`,model3dCanvas:"三维模型",model3dMore:"更多模型选项",edaLoading:"正在渲染 KiCad 文件…",reviewTargetChanged:"当前会话已切换,请回到创建这条引用的会话后再插入。",reviewReference:"审阅引用",reviewReferenceHint:"补充意见后插入,不会自动发送。",reviewSnapshot:"选中位置的视图快照",reviewCapturing:"正在截取当前视图…",reviewIncludeImage:"附带截图(临时保存在当前服务器)",reviewCaptureFailed:"截图未成功,仍可插入定位信息。",reviewNote:"你的意见(可选)",reviewNotePlaceholder:"例如:这里太厚了,能否减薄?",reviewDetails:"查看定位信息和引用原文",reviewUploading:"正在准备引用…",reviewAddToDraft:"加入引用草稿",reviewInsert:"插入引用",reviewUploadFailed:"引用准备失败,意见已保留。请重试,或取消附带截图后只插入文字。",edaLoadFailed:"KiCad 预览渲染失败",edaTimeout:"KiCad 预览生成或传输超时,请重试。",edaRefresh:"重新渲染",edaPickHint:"点击原理图或 PCB 上的问题位置,生成电子标注",edaPickedPosition:({x:t,y:e})=>`已选位置 ${t}%, ${e}%`,edaPickedBoardPosition:({x:t,y:e,object:r})=>`板坐标 ${t}, ${e} mm · ${r}`,edaInspecting:"正在读取板坐标和附近对象…",edaNoNearbyObject:"附近无对象",edaInsertAnnotation:"引用电子标注",csvUnnamedColumn:({index:t})=>`第 ${t} 列`,csvSelectedCell:({row:t,column:e})=>`已选第 ${t} 行 · ${e}`,csvPickHint:({rows:t,columns:e})=>`${t} 条记录 · ${e} 列,点击单元格引用`,csvInsertAnnotation:"引用表格标注",csvTablePreview:"表格预览:点击单元格后可引用完整记录",kicadLocalStateNotice:"这是本机界面状态文件,不参与原理图、PCB 或生产审查。",kicadShowRawJson:"查看原始 JSON",kicadProjectPickHint:"点击一项配置后可插入引用",kicadInsertSetting:"引用配置",markdownPreview:"预览",markdownSource:"源码",markdownPreviewHint:"点按行/段落引用,再点一行扩选;拖左侧竖条可连续框选",htmlPreview:"预览",htmlSource:"源码",htmlPreviewHint:"HTML 沙箱 iframe 预览,脚本受限",htmlFullscreenEnter:"全屏预览",htmlFullscreenExit:"退出全屏预览",markdownOutline:"Markdown 目录",markdownOutlineShort:"目录",closeMarkdownOutline:"关闭目录",changedFromPath:({path:t})=>`来自 ${t}`,selectedLineFooter:({lineLabel:t})=>`已选 ${t}`,clearSelection:"清除",allChanges:"全部改动",backToChangeList:"返回目录",allRepositories:"全部仓库",allRepositoriesShort:"全部",repositories:"仓库",gitRepositorySectionTitle:"操作仓库",gitRepositoryLabel:"仓库",gitRepositoryPlaceholder:"选择仓库",gitRepositorySearchPlaceholder:"搜索仓库",gitRepositoryEmpty:"没有可操作的仓库",selectRepositoryForGitActions:"请选择一个仓库后再执行 Git 操作",selectRepositoryForDiff:"选择一个仓库或文件查看 diff",repoNotLoaded:"点击加载",repoChangedCount:({count:t})=>`${t} 个改动`,repoStagedCount:({count:t})=>`${t} 已暂存`,noChanges:"没有改动",noMatchingChanges:"没有匹配的改动",loadingGitChanges:"正在加载 Git 改动…",loadingGitChangesSlow:"仓库较大时可能需要几秒。",refreshingGitChanges:"正在刷新 Git 改动…",gitChangesLoadFailed:"无法加载 Git 改动",retryGitChanges:"重试",insertThisFile:"把这个文件引用插入 Terminal",viewDiff:"查看 diff",diffViewMode:"改动文件展示方式",diffViewModeList:"平铺列表",diffViewModeTree:"目录结构",diffViewModeAi:"AI 导览",changeWalkthroughEmpty:"暂无 AI 导览。生成解释后会在这里展示总览、链路和验证点。",gitInfo:"Git 信息",wrapLongLines:"长行换行",wrapOn:"已换行",wrapOff:"原始",multiRepoScan:"多子仓",multiRepoScanTitle:"扫描当前工作区下的嵌套 Git 仓库。关闭时只看单个仓库,大仓库打开更快。",horizontalScrollHint:"左右滑动查看完整 diff",stageFile:"暂存",stageAll:"全部暂存",unstageFile:"取消暂存",stashFile:"贮藏",stashAll:"全部贮藏",restoreFile:"丢弃",gitQuickActions:"Git 操作",gitUnavailable:"当前目录不是 Git 仓库",branchSectionTitle:"当前分支",currentBranchLabel:"分支",switchBranchPlaceholder:"选择分支",switchBranchSearchPlaceholder:"搜索本地分支",switchNoBranches:"没有本地分支",switchBranch:"切换",noStagedChangesShort:"无暂存",stagedCount:({count:t})=>`已暂存 ${t}`,stagedCountShort:({count:t})=>`已暂存 ${t}`,commitSectionTitle:"提交",commitReadyHint:({count:t})=>`${t} 个文件已准备提交`,commitMessagePlaceholder:"提交信息",commitChanges:"提交",commitNeedsStaged:"请先暂存要提交的改动",recentCommitsTitle:"近期提交",recentCommitsSearchPlaceholder:"搜索提交 hash 或信息",recentCommitsLoadMore:"加载更多提交",recentCommitsEmpty:"暂无提交历史",pushSectionTitle:"同步远端",pushRemoteLabel:"Remote",pushRemotePlaceholder:"origin",pushRemoteSearchPlaceholder:"搜索 Remote",pushNoRemotes:"没有 Remote",pushBranchLabel:"目标分支",pushBranchPlaceholder:({branch:t})=>`${t}`,pushBranchSearchPlaceholder:"搜索分支",pushNoBranches:"没有分支",pushUpstreamBadge:"upstream",pushCurrentBranchBadge:"当前",pushNoUpstream:"当前分支未设置 upstream",pushUpToDate:"与远端同步",pushAheadCount:({count:t})=>`领先远端 ${t} 个提交`,pushBehindCount:({count:t})=>`落后远端 ${t} 个提交`,pushDivergedCount:({ahead:t,behind:e})=>`领先 ${t} / 落后 ${e} 个提交`,pullChanges:"拉取",pushChanges:"推送",gitActionRunning:"执行中…",gitActionFailed:({message:t})=>`Git 操作失败:${t}`,confirmRestoreTitle:"确认丢弃改动",confirmRestoreDescription:({path:t})=>`将丢弃 ${t} 的未暂存改动,此操作不可从 Termdock 恢复。`,confirmRestorePhrase:"丢弃改动",confirmRestorePlaceholder:"输入“丢弃改动”确认",confirmStashAllTitle:"确认贮藏全部改动",confirmStashAllDescription:"会把当前工作区改动(包含未跟踪文件)移入贮藏。",confirmAction:"确认",renderingHtml:"正在渲染 HTML…",footnotes:"脚注",backToFootnote:({index:t})=>`返回脚注 ${t}`,openMermaidDiagram:"打开 Mermaid 图表",mermaidDiagram:"Mermaid 图表",renderingDiagram:"正在渲染图表…",markdownImage:"Markdown 图片",image:"图片",previousImage:"上一张图片",nextImage:"下一张图片",closeImagePreview:"关闭图片预览",emptyFile:"空文件。",insertReference:({reference:t})=>`插入引用:${t}`,copyReference:({reference:t})=>`复制引用:${t}`,byteCount:({count:t})=>`${t} 字节`,previewTruncated:"预览已截断至 1 MB",branchCandidatesLoading:"正在加载分支候选…",includeUncommitted:"包含本地未提交改动",includeUncommittedHint:"查看对比或生成解释时纳入工作区和未跟踪文件的 diff",missingBaseReposSkipped:({repositories:t})=>`未设置基线的仓库会跳过:${t}`,localBranch:"本地",remoteBranch:"远端"},fileTree:{insertRef:"引用",insertRefTitle:"Insert file reference into active terminal",openDirRoot:"进入",openDirRootTitle:"把这个目录作为当前浏览根目录",openInFileBrowser:"在 Finder 中显示",openInFileBrowserTitle:"在系统文件浏览器中打开这个项目",openInFileBrowserFailed:"打开文件浏览器失败",moreDirActions:"更多目录操作",searchFromDir:"从这里搜索",searchFromDirTitle:"只搜索这个目录及其子目录",pinDir:"固定",pinDirTitle:"固定这个目录到当前项目",unpinDir:"已固定",unpinDirTitle:"取消固定这个目录",pinFileTitle:"固定这个文件到当前项目",unpinFileTitle:"取消固定这个文件",pinFile:"固定",unpinFile:"已固定",moreFileActions:"更多文件操作",deleteFile:"删除文件",deleteFileConfirm:({name:t})=>`确认删除“${t}”?此操作无法撤销。`,deleteFileFailed:({message:t})=>`删除文件失败:${t}`,noWorkingDir:"未检测到工作目录。",emptyDir:"空目录。",noMatchingFiles:"没有匹配的文件。",searching:"正在搜索文件…",searchingWithCount:({count:t})=>`搜索中…已找到 ${t} 项`,searchResults:({count:t})=>`${t} 个结果`,searchScope:"搜索范围",searchTruncatedHint:({count:t})=>`降级搜索已扫描大量目录并在找到 ${t} 项后停止。安装 ripgrep 或输入更精确关键词可获得完整结果。`,searchStillRunning:"搜索仍在进行,更多结果会自动出现。",showingSearchResults:({shown:t,total:e})=>`正在展示 ${t}/${e}`,loadMoreSearchResults:({shown:t,total:e})=>`查看更多(${t}/${e})`,contentMatchesCount:({count:t})=>`${t} 个文件命中`,moreMatches:({count:t})=>`还有 ${t} 处匹配`,noContentMatches:"文件内容中没有匹配。",contentSearchNeedsRipgrep:"内容搜索需要 ripgrep(rg),请在服务端安装后再在文件内搜索。",truncatedHint:"仅展示前 1000 项。使用搜索或打开更小的文件夹以获得更好性能。",dropToUploadHere:"上传到这里",symbolicLink:"符号链接",sortByModified:"按最近修改排序",sortByName:"按名称排序",sortedByModified:"已按最近修改排序"},diffViewer:{noFileChanges:"此文件无改动。",noUnstagedChanges:"没有未暂存的改动。",emptyHint:"做一些改动,或从远程拉取。",loading:"正在加载 diff…",insertAllDiff:"把当前 diff 内容作为上下文插入 Terminal",insertFileDiff:"引用这个文件的 diff",insertHunkDiff:"引用这段 diff hunk",insertHunkShort:"引用",insertFileShort:"引用",insertAllShort:"全部",stageHunk:"暂存",stageHunkTitle:"只把这个 hunk 加入暂存区 (git apply --cached)",revertHunk:"撤销",revertHunkTitle:"撤销这个 hunk 的工作区改动(不可恢复)",revertHunkConfirm:"确认撤销?",hunkActionApplying:"应用中…",hunkActionUnavailable:"无法为这个 hunk 构造补丁",hunkActionFailed:({message:t})=>`操作失败:${t}。如改动已变化,请刷新后重试。`,auditExplanation:"更改意义",auditStale:"解释已失效",auditClear:"清除解释",auditGeneratedAt:({time:t})=>`生成于 ${t}`,allDiffLabel:"全部 diff",allChangesLabel:"全部改动",workingTree:"工作区改动",allUnstaged:"所有未暂存改动",binaryOrEmpty:"没有可显示的文本改动。",noFinalNewline:"文件末尾没有换行符",noHunks:"没有 hunk",hunkOutline:"Hunk 列表",expandHunkRail:"显示 hunk 列表",collapseHunkRail:"隐藏 hunk 列表",prevHunk:"上一个 hunk",nextHunk:"下一个 hunk",prevFile:"上一个",nextFile:"下一个",expandFile:"展开文件",collapseFile:"折叠文件",expandAll:"全部展开",collapseAll:"全部折叠",collapseHunk:"折叠 hunk",useBracketKeysHint:"按 [ / ] 在 hunk 之间跳转",unified:"统一",unifiedMode:"统一视图",split:"分屏",splitMode:"左右分屏视图",moreActions:"更多操作",view:"视图",loadingPreviousFile:"正在加载上一个文件…",loadingNextFile:"正在加载下一个文件…",resizeNavigation:"调整 diff 导航宽度",focusPathHint:"点击标注聚焦路径",whitespace:"空白",whitespaceDefault:"默认",whitespaceTrim:"忽略行尾空白",whitespaceIgnore:"忽略所有空白",whitespaceIgnoreBlankLines:"忽略空行",context:"上下文",contextLines:({count:t})=>`${t} 行`,contextAll:"全部"},settings:{title:"设置",font:"字体",render:"渲染",theme:"主题",darkTheme:"深色",lightTheme:"浅色",newTab:"新标签",debug:"调试",noSleep:"常亮",noSleepUnavailable:"无网络 — 已禁用",updateTitle:"Termdock 更新",updateRuntimeTitle:"CLI 与服务 Runtime",updateHint:"手动检查会立即下载并安装新版本;服务只会在你确认后重启。",updateCheck:"检查更新",updateCheckAgain:"再次检查",updateChecking:"正在检查 npm 上的最新版本…",updateCheckingShort:"检查中…",updateInstallingShort:"安装中…",updateCurrent:"Termdock 已是最新版本。",desktopUpdateTitle:"macOS 桌面版",desktopUpdateHint:"手动检查 GitHub 发布的签名桌面版本。",desktopUpdateUnsupported:"仅签名安装的 macOS 桌面版支持应用内更新。",desktopUpdateChecking:"正在检查桌面版更新…",desktopUpdateCurrent:"桌面版已是最新版本。",desktopUpdateDownloading:"发现新版本,正在后台下载…",desktopUpdateReady:"桌面版更新已下载,可以重启安装。",desktopUpdateInstalling:"正在重启并安装桌面版更新…",desktopUpdateCheck:"检查桌面版",desktopUpdateCheckAgain:"再次检查",desktopUpdateRestart:"重启并安装",desktopUpdateRestartConfirm:"重启 Termdock 并安装已下载的桌面版更新?终端服务和 tmux 会话不会被停止。",notifications:"通知",notificationsTitle:"通知设置",notificationsHint:"Termdock 在后台时,AI 任务结束后发送系统通知。",notificationsPageHint:"选择哪些 Termdock 事件可以发送系统通知。总开关负责浏览器权限和投递,事件开关决定具体哪些内容提醒你。",notificationsMaster:"系统通知",notificationsMasterHint:"允许 Termdock 在隐藏或作为 PWA 安装运行时发送通知。",notificationsIOSInstallHint:"在 iPhone 或 iPad 上,请先将 Termdock 添加到主屏幕,再开启通知。",notificationsPermission:"权限",notificationsPermissionSystem:"由 macOS 管理",notificationsTest:"发送测试",notificationsTestChecking:"正在等待 macOS 确认投递…",notificationsTestDelivered:"已投递到通知中心;若没有横幅,请检查提醒样式和专注模式。",notificationsTestFailed:"macOS 未投递通知,请在系统设置中允许 Termdock 通知。",notificationsOpenSystemSettings:"打开系统通知设置",notificationsAlertStyle:"提醒方式",notificationsAlertStyleHint:"最终是否横幅弹出仍由浏览器和 Android 系统决定。Termdock 只能请求静默、默认或持续显示等通知选项。",notificationsStyleNormal:"默认",notificationsStyleNormalHint:"允许时声音/震动",notificationsStyleQuiet:"静默",notificationsStyleQuietHint:"仅状态栏,无声音",notificationsStylePersistent:"持续",notificationsStylePersistentHint:"保留到手动关闭",notificationsEvents:"事件",notificationsAiFinished:"AI 任务结束",notificationsAiFinishedHint:"当 Termdock 在后台时,AI agent 停止后发送通知。",notificationsSessionExited:"终端退出",notificationsSessionExitedHint:"终端进程自行结束时发送通知(主动关闭不触发,经 Web Push 投递)。",notificationsFutureHint:"后续可以在这里继续增加更多通知类型,不需要改变顶层设置布局。",notificationsOffSummary:"系统通知已关闭",notificationsAiOnSummary:"AI 任务结束通知已开启",notificationsExitOnSummary:"终端退出通知已开启",notificationsBothOnSummary:"AI 任务结束、终端退出通知已开启",notificationsNoEventsSummary:"暂无开启的通知事件",notificationsDenied:"浏览器通知权限已被阻止,请在站点设置中开启。",notificationsUnsupported:"通知需要安全上下文和 Service Worker 支持。",notificationsTestBody:"通知已开启。后台 AI 任务结束后会提醒你。",shell:"Shell",tmux:"Tmux",auto:"自动",webgl:"WebGL",canvas:"内置",tmuxServer:"Tmux 服务",tmuxUnavailable:"不可用",noTmuxSessions:"服务端没有 tmux 会话。",installTmuxHint:"请在服务端安装 tmux 后启用。",refresh:"刷新",attached:"已连接",restorable:"可恢复",attach:"连接",attaching:"连接中…",destroy:"销毁",sessions:({n:t})=>`${t} 个会话`,windows:({n:t})=>`${t} 个窗口`,keyboardToolbar:"键盘工具栏",aiAgentDetection:"AI 代理检测",signOut:"退出登录",language:"语言",programNamePlaceholder:"程序名(如 claude)",patternPlaceholder:"正则表达式(如 Thinking|Generating)",statusPlaceholder:"状态",addProgram:"添加程序",addPattern:"添加规则",resetDefaults:"恢复默认",invalidRegex:"无效的正则",removeProgram:"移除程序",removeRule:"移除规则",keepLabel:"保持",customColor:"自定义颜色",tabIndicator:"标签指示器样式",toolbarPresets:"工具栏预设",detectionRules:"检测规则",agentHooksHint:"安装 hooks 后,agent 会主动上报状态:回合进行中(绿)、等你授权/回答(黄)、回合完成(对勾),并在等待你输入时推送通知。hooks 全局安装但只在 termdock 的终端里生效。",agentHooksInstall:"安装",agentHooksInstalled:"已安装",agentHooksOutdated:"需更新",agentHooksNeedsApproval:"待授权",agentHooksApprovalHint:"在 Codex 中输入 /hooks,批准 Termdock Hook 后生效",agentHooksNotInstalled:"未安装",agentHooksUninstall:"卸载",agentHooksReinstall:"重新安装",agentHooksDevMode:"开发模式:hooks 指向 TS 源码,需要构建后的版本才能生效",agentHooksTarget:"写入",agentAutoRename:"自动更新会话标题",agentAutoRenameHint:"Agent 完成一轮后,根据近期内容更新标题。默认全部关闭,手工命名的会话不会被覆盖;启用外部插件标题后才会执行其 CLI。",agentAutoRenameToggle:"切换此 Agent 的自动标题",agentAutoRenameShort:"自动标题",agentAutoRenameNamer:"起名 Agent",agentAutoRenameFollow:"跟随当前会话",agentAutoRenameModelsFromCli:"模型由本机 CLI 动态提供",agentAutoRenameRefreshModels:"重新查询 CLI 模型",agentAutoRenameCliDefault:"CLI 默认模型",agentAutoRenameAutomatic:"自动选择",agentAutoRenameNoCli:"未检测到可用于起名的 CLI",agentAutoRenameAdvanced:"高级标题偏好",agentAutoRenamePreference:"补充偏好",agentAutoRenamePreferenceHint:"可选。仅补充你对标题风格或重点的偏好;Termdock 的默认起名规则仍会保留。离开输入框时自动保存。",agentAutoRenamePreferencePlaceholder:"例如:突出用户收益;优先使用动宾结构;避免技术术语",agentAutoRenamePayloadLimit:"用户消息上下文上限(字符)",agentAutoRenamePayloadLimitHint:"保留 prompt-submit 原始 payload 的总字符数,默认 12000,可设置 1000–64000。",agentPlugins:"Agent 插件",agentPluginAdd:"添加插件",agentPluginHint:"从 HTTPS Git 仓库或本地目录安装;请先审查来源。Hooks 和可执行的标题 CLI 均需用户分别启用。",agentPluginCreate:"创建插件",agentPluginDelete:"删除插件",agentPluginInvalid:"插件配置无效",agentPluginCopyAiPrompt:"复制 AI 修复提示",agentPluginCopied:"已复制",agentPluginSourcePlaceholder:"https://github.com/user/agent-plugin 或本地目录",agentPluginInstallPackage:"安装插件",agentPluginAdvancedManifest:"高级:直接粘贴 manifest.json",agentPluginUpdateAvailable:"有更新",agentPluginManualSource:"手动 manifest",agentPluginUpdate:"更新",agentPluginCheck:"检查更新",agentPluginDoctor:"诊断",agentPluginDoctorHint:"显式运行插件模型探测,不会调用标题生成",agentPluginDoctorStatusOk:"标题与模型能力正常",agentPluginDoctorStatusMissing:"未声明 titleNamer",agentPluginDoctorStatusCliDefault:"标题可用,使用 CLI 默认模型",agentPluginDoctorStatusNoModels:"没有可用的模型数据",agentPluginDoctorStatusFailed:"模型探测失败",agentPluginDoctorModels:"个可用模型",agentPluginDoctorAutomatic:"自动选择",agentPluginDoctorCliDefault:"未指定模型时使用 Agent CLI 默认模型",agentAutoRenameInterval:"重新判断间隔",agentAutoRenameMinutes:"分钟",mobileKeyboard:"移动键盘",saving:"保存中…",rulesHint:"配置正则表达式来识别 AI 工具在终端标签中的状态。每条规则可独立设置标签、颜色、图标样式以及输出静默后指示器保留的时长。停止后若你未查看该标签,标签会保留一个黄色待查看提示。",programsHelp:"支持在一个配置中匹配多个程序,用英文逗号分隔。",programLabelResolution:"程序名识别",rawCommandMapping:"原始命令映射",rawCommandMappingHint:"以下规则将原始命令行映射为标签显示名。用户规则优先于内置规则。",genericProgramNames:"通用程序名",genericProgramNamesHint:"触发 ps 深度识别(如 node, python)",wrapperScriptNames:"包装脚本名",wrapperScriptNamesHint:"CLI 包装器,启动其他工具(如 aiden, npx)",shellNamesConfig:"Shell 名称",shellNamesHint:"从标签显示中过滤(如 bash, zsh)",addTag:"+ 添加",customRules:"自定义规则",addRule:"添加规则",localAccess:"本地访问",localAccessHint:"手机信任本地 CA 后,可通过这个局域网地址访问。请先在手机上打开「手机引导」地址下载 CA 证书。",resetAutoName:"恢复自动",onboardingUrl:"手机引导",httpsActive:"HTTPS 已启用",httpsInactive:"HTTPS 未启用",caMissing:"未配置 CA 下载",closeSettings:"关闭设置",desktopTitle:"Termdock 桌面端",desktopStatusLoading:"正在读取 macOS 原生状态…",desktopSwitchService:"切换服务",desktopInstallCli:"安装 / 修复 CLI",desktopCliUpdated:"CLI 状态已更新",desktopOpenDataDirectory:"打开数据目录"},toolbarPresets:{preview:"预览",presets:"预设",label:"标签",new:"新建",reset:"重置",presetLabelPlaceholder:"预设名称",deletePreset:({name:t})=>`删除预设 ${t}`,matchPrograms:"匹配程序",typeEnterHint:"输入后回车",programsPlaceholder:"vim, nvim, /^claude(-code)?$/i …",programsHelp:"纯字符串按大小写不敏感子串匹配。用 /…/flags 包裹则为正则(针对小写程序名测试)。",altSlot:"Alt 修饰键槽",altSlotHint:"在预览中保留一个 Alt 键槽位。",desktopVisibility:"桌面端显示",desktopVisibilityHint:"桌面端只显示该预设的自定义按钮,不显示基础快捷键。",rowLayout:"行布局",rowLayoutHint:"每行按钮数。",addRow:"行",rowN:({n:t})=>`第 ${t} 行`,del:"删",buttons:"按钮",buttonsHint:"点击编辑,使用 ↑↓ 排序。",addButton:"添加按钮",noCustomButtons:"暂无自定义按钮。添加一个来覆盖默认工具栏。",moveUp:"上移",moveDown:"下移",removeRow:({n:t})=>`移除第 ${t} 行`,removeAction:({name:t})=>`移除 ${t}`,labelField:"标签",labelPlaceholder:"按钮上显示的文本",sequence:"序列",sequencePlaceholder:"例如 /undo 或 \\t 或 /||undo",sequenceHint:"双击序列",doubleTap:"双击序列",doubleTapAdd:"+ 添加",doubleTapPlaceholder:"例如 /undo\\r 或 /||undo ||\\r",remove:"移除",noSequence:"无序列",preset:"预设",overCapacityHint:"按钮数超过槽位,多余按钮将使用最后一行的尺寸。"},agentRules:{ruleColors:{green:"绿",yellow:"黄",red:"红",blue:"蓝",purple:"紫",orange:"橙",gray:"灰"}},tab:{session:"会话",new:"新建会话",rename:"重命名",renameHint:"修改标签的显示名称",renamePlaceholder:"留空则恢复默认名称",copyCwd:"复制当前目录",copyCwdHint:"复制当前工作目录",resumeAgent:"恢复 Agent 会话",resumeAgentHint:"用原生 session id 恢复上次对话",resumeAgentAvailable:"有可恢复的 Agent 对话",resumeAgentRecoveredTitle:({agent:t})=>`可继续上次的 ${t} 对话`,resumeAgentRecoveredHint:"Terminal 曾异常中断,已重新创建;可以从上次对话继续。",resumeAgentNow:"恢复",resumeAgentLater:"暂不恢复",resumeAgentSubmitting:"正在提交原生恢复命令…",resumeAgentWaiting:"正在等待 Agent 确认已载入原会话…",resumeAgentSuccess:({agent:t})=>`${t} 会话已恢复`,resumeAgentFailed:"Agent 会话恢复失败,可以重试。",resumeAgentConflict:"该 Agent 会话已在另一个 Terminal 中打开。",resumeAgentBusy:"当前 Agent 回合尚未结束,暂时不能恢复。",resumeAgentTimeout:"Agent 未确认已载入原会话,请查看 Terminal 输出或重试。",tmuxRecoveryTitle:({count:t})=>`检测到 tmux 异常退出,${t} 个 Agent 可恢复`,tmuxRecoveryHint:"Termdock 保留了原生会话 ID。恢复操作会在原标签页中继续之前的对话。",tmuxRecoveryRestoreAll:"恢复全部",tmuxRecoveryRestoring:"正在恢复…",tmuxRecoveryDismiss:"暂不处理",tmuxRecoveryPartial:({restored:t,failed:e})=>`已恢复 ${t} 个,${e} 个需要重试。`,tmuxRecoveryFailed:"恢复失败,请检查终端状态后重试。",tmuxRecoveryDismissFailed:"暂时无法关闭该恢复提示。",copied:"已复制",close:"关闭会话",closeHint:"从列表移除该标签",longPressTip:"提示:按住标签不动约半秒打开操作菜单,按住并拖动可排序。",sessionsTitle:"会话",explorerTitle:"资源管理器",split:"分屏",splitTitle:"添加到分屏工作区",splitNew:"新建会话并加入",splitNewHint:"沿用当前目录和默认会话类型;可连续加入多个会话",splitExisting:"选择已有会话或工作区",splitExistingHint:"会话可组成多个独立工作区;选择另一工作区会将两组合并",splitCurrent:"当前",splitClose:"退出分屏",splitLayout:"分屏布局",splitHorizontal:"左右",splitVertical:"上下",splitGrid:"网格",splitWorkspace:"分屏组",splitWorkspaces:"分屏工作区",splitRename:"重命名分屏组",splitRemovePane:"移出分屏",splitExistingGroups:"已有分屏组",splitAvailableSessions:"可加入的会话",splitOccupied:"已成组",splitUnavailableGrouped:"分组模式下只能分屏同一目录的会话",splitEndedGrouped:"已退出分屏:分组模式不支持跨目录组合",splitNoOtherSessions:"没有可组合的其他会话",sessionCount:({count:t})=>`${t} 个会话`,closeChooserTitle:"销毁 Tmux 会话?",closeChooserDescription:"确认后会终止该会话及其中的所有进程,此操作无法撤销。",destroySession:"销毁会话",confirmDestroySession:"确认销毁",destroySessionHint:"终止 tmux 会话及其中的所有进程。",dragToClose:"拖到此处关闭",releaseToClose:"松手后确认"},agent:{aiRunning:"AI 运行中",needsReview:"需要查看",finishedReview:"AI 已完成 — 需要查看",aiWaiting:"AI 等待中",copyMode:"Copy 模式",jumpToNext:"跳到下一个待处理",jumpToNextRunning:"跳到下一个运行中会话",selectRunningSession:"选择运行中的 Session",runningSessionGestureHint:"轻点循环 · 横向滑动选择 · 长按拖动",currentSession:"当前"},connection:{reconnecting:"正在重连…"},desktopServices:{switchService:"切换 Termdock 服务",openServices:"已打开的服务",idle:"空闲",manageServices:"管理服务与名称"},terminal:{input:"终端输入",error:"错误",dropFilesToPastePaths:"拖放文件以输入路径",loading:"正在加载终端…",initializing:"正在初始化终端引擎…",failedToLoad:"终端加载失败",unknownError:"发生未知错误",componentFailed:"终端组件加载失败",paste:"粘贴",copied:"已复制",copyFailed:"复制失败",longPressSelectsText:"长按选择文本",longPressSendsArrows:"长按发送方向键",switchLongPressToArrows:"将长按切换为方向键",switchLongPressToCopy:"将长按切换为复制所选文本"},quota:{title:"订阅配额",noProviders:"未检测到订阅服务。",noProvidersHint:"使用 AI 编程工具并登录后,自动显示配额信息。",exhausted:"已用完",left:({n:t})=>`剩余 ${t}`,updated:({time:t})=>`${t} 更新`,refresh:"刷新",close:"关闭"},errorBoundary:{title:"出现了一些问题",unexpected:"发生意外错误",retry:"重试",copyDetails:"复制错误信息",copied:"已复制",copyFailed:"复制失败"},error:{type:{network:"网络连接错误",session:"会话错误",terminal:"终端错误",auth:"认证错误",validation:"验证错误",unknown:"未知错误"},severity:{low:"提示:",medium:"警告:",high:"错误:",critical:"严重错误:"},suggestion:{networkCheck:"检查网络连接",networkRetry:"尝试重新连接",networkProxy:"检查代理设置",networkWait:"等待网络恢复",sessionRecreate:"重新创建会话",sessionServer:"检查服务器状态",sessionCache:"清理浏览器缓存",terminalRestart:"重启终端",terminalConfig:"检查终端配置",terminalClear:"清除终端输出",authRelogin:"重新登录",authCredentials:"检查凭证",authAdmin:"联系管理员",validationFormat:"检查输入格式",validationParams:"验证参数",validationDocs:"参考文档",unknownReload:"刷新页面",unknownApp:"重启应用",unknownSupport:"联系技术支持"}}},eA=["en","zh"],rn="en",Ma="termdock:locale",qo={en:J2,zh:Q2};function tA(t){return typeof t=="string"&&eA.includes(t)}function rA(){if(typeof window>"u")return rn;try{const e=window.localStorage.getItem(Ma);if(tA(e))return e}catch{}return(window.navigator?.language?.toLowerCase()??"").startsWith("zh")?"zh":rn}const Rp=F.createContext(null);function ja(t,e){const r=e.split(".");let n=t;for(const o of r)if(n&&typeof n=="object"&&o in n)n=n[o];else return;return n}function Ua(t,e){return typeof t=="function"?t(e??{}):typeof t!="string"?String(t):e?t.replace(/\{(\w+)\}/g,(r,n)=>Object.prototype.hasOwnProperty.call(e,n)?String(e[n]):r):t}function nA({children:t}){const[e,r]=F.useState(()=>rA()),n=Ue.useRef(!1);F.useEffect(()=>{typeof window>"u"||Hn().then(c=>{if(c?.locale==="zh"||c?.locale==="en"){if(c.locale===e||c.locale==="en"&&e!=="en")return;r(c.locale);try{window.localStorage.setItem(Ma,c.locale)}catch{}}}).catch(()=>{})},[]),F.useEffect(()=>{if(!(typeof window>"u")){try{window.localStorage.setItem(Ma,e)}catch{}n.current&&(n.current=!1,$t({locale:e}).catch(()=>{})),document.documentElement.lang=e==="zh"?"zh-CN":"en"}},[e]);const o=F.useCallback(c=>{n.current=!0,r(c)},[]),s=qo[e]??qo[rn],i=F.useCallback((c,l)=>{const d=ja(s,c);if(d===void 0){const u=ja(qo[rn],c);return u===void 0?c:Ua(u,l)}return Ua(d,l)},[s]),a=F.useMemo(()=>({locale:e,setLocale:o,t:i}),[e,o,i]);return p.jsx(Rp.Provider,{value:a,children:t})}function Kc(){const t=F.useContext(Rp);return t||{locale:rn,setLocale:()=>{},t:(e,r)=>{const n=ja(qo[rn],e);return n===void 0?e:Ua(n,r)}}}const oA=String.raw`
|
|
14
14
|
████████ ███████ ██████ ███ ███ ██████ ██████ ██████ ██ ██
|
|
15
15
|
██ ██ ██ ██ ████ ████ ██ ██ ██ ██ ██ ██ ██
|
|
16
16
|
██ █████ ██████ ██ ████ ██ ██ ██ ██ ██ ██ █████
|
|
17
17
|
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
|
|
18
18
|
██ ███████ ██ ██ ██ ██ ██████ ██████ ██████ ██ ██
|
|
19
|
-
`;function
|
|
19
|
+
`;function sA({onLoginSuccess:t}){const{t:e}=Kc(),[r,n]=F.useState(""),[o,s]=F.useState(!1),[i,a]=F.useState(null),[c,l]=F.useState(0),d=F.useRef(null);F.useEffect(()=>{d.current?.focus()},[]),F.useEffect(()=>{if(c<=0)return;const m=setInterval(()=>{l(y=>y>1?y-1:0)},1e3);return()=>clearInterval(m)},[c]);const u=c>0,f=!o&&!u&&r.length>0,h=async m=>{if(m.preventDefault(),!!f){s(!0),a(null);try{const y=await Sp(r);if(y.ok){n(""),t();return}a(y.error||e("login.invalidPassword")),y.rateLimited&&typeof y.retryAfterMs=="number"&&l(Math.max(1,Math.ceil(y.retryAfterMs/1e3)))}catch(y){a(y instanceof Error?y.message:e("login.failed"))}finally{s(!1)}}},g=u?e("login.placeholderBlocked",{s:c}):e("login.placeholder");return p.jsxs("div",{className:"flex w-screen flex-col items-center justify-center bg-background px-4 text-foreground",style:{height:"var(--app-vh, 100vh)",paddingTop:"env(safe-area-inset-top, 0px)",paddingBottom:"20vh",gap:"clamp(20px, 4vh, 40px)"},children:[p.jsx("pre",{"aria-hidden":!0,className:"max-w-full select-none overflow-hidden whitespace-pre leading-[1.05] text-primary/80 font-mono",style:{fontSize:"clamp(5px, 2vw, 14px)"},children:oA}),p.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground font-mono",children:[p.jsx("span",{className:"text-primary",children:"$"}),p.jsx("span",{children:e("login.prompt")}),p.jsx("span",{className:"terminal-cursor","aria-hidden":!0,children:"▍"})]}),p.jsxs("form",{onSubmit:h,className:"w-full max-w-xs",children:[p.jsxs("div",{className:`flex items-center gap-1 rounded-full border bg-surface-2 p-1 pl-4 transition ${i?"border-destructive/60":"border-border"}`,children:[p.jsx("input",{ref:d,type:"password",autoComplete:"current-password",value:r,placeholder:g,onChange:m=>{n(m.target.value),i&&a(null)},disabled:o||u,className:"flex-1 bg-transparent text-foreground placeholder:text-muted-foreground/70 focus:outline-none disabled:opacity-60",style:{minWidth:0,fontSize:"16px"}}),p.jsx("button",{type:"submit",disabled:!f,"aria-label":e("login.submit"),className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground transition hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-40",children:o?p.jsx(He,{size:16,className:"animate-spin"}):p.jsx(cS,{size:16})})]}),i&&!u?p.jsx("div",{className:"mt-3 text-center text-xs text-destructive",children:i}):null]}),p.jsx("style",{children:`
|
|
20
20
|
@keyframes terminal-blink {
|
|
21
21
|
0%, 49% { opacity: 1; }
|
|
22
22
|
50%, 100% { opacity: 0; }
|
|
@@ -26,9 +26,9 @@ Minimum version required to store current data is: `+R+`.
|
|
|
26
26
|
animation: terminal-blink 1.05s steps(1, end) infinite;
|
|
27
27
|
color: var(--primary);
|
|
28
28
|
}
|
|
29
|
-
`})]})}const nA={activeKey:"root",items:[]},oA=()=>()=>{},sA=()=>nA,ja="termdock:open-saved-service";function Kk(t,e){F.useEffect(()=>{window.termdockDesktop?.reportServiceActivity?.({runningCount:t,reviewCount:e}),Tn({runningCount:t,reviewCount:e})},[t,e])}function iA(){return window.termdockDesktop?null:p.jsx(aA,{})}function aA(){const[t,e]=F.useState([]),[r,n]=F.useState([]),[o,s]=F.useState(ne()?.targetPeerId),[i,a]=F.useState(""),c=F.useRef(null),l=St(),d=F.useSyncExternalStore(l?.subscribe||oA,l?.snapshot||sA);F.useEffect(()=>{let g=!1,m=0;const y=()=>{const v=++m;s(ne()?.targetPeerId),We().then(A=>{if(!(g||v!==m)){try{const B="termdock-secure-service-order",T=JSON.parse(localStorage.getItem(B)||"[]"),N=Array.isArray(T)?T.filter(R=>typeof R=="string"):[],k=R=>R.targetPeerId||R.id,x=[...N.filter(R=>A.some(P=>k(P)===R)),...A.map(k).filter(R=>!N.includes(R))];A.sort((R,P)=>x.indexOf(k(R))-x.indexOf(k(P)));const S=JSON.stringify(x);S!==localStorage.getItem(B)&&localStorage.setItem(B,S)}catch{}e(A)}}).catch(()=>{})};y();const w=Pu(y),I=window.termdockDesktop?.onServiceActivity?.(n);return window.addEventListener(lr,y),()=>{g=!0,w(),I?.(),window.removeEventListener(lr,y)}},[]),F.useEffect(()=>{const g=c.current,m=g?.querySelector('[aria-current="page"]');if(!g||!m)return;const y=m.offsetLeft,w=y+m.offsetWidth;y<g.scrollLeft?g.scrollLeft=y:w>g.scrollLeft+g.clientWidth&&(g.scrollLeft=w-g.clientWidth)},[o,t]);const u=async g=>{if(a(""),!(g.targetPeerId&&g.targetPeerId===o))try{const m=window.termdockDesktop;if(m?.openServiceConnection){const y=await m.openServiceConnection(g);if(!y.ok)throw new Error(y.error||"暂时无法打开服务")}else ps(g)||window.dispatchEvent(new CustomEvent(ja,{detail:g}))}catch(m){a(m instanceof Error?m.message:"暂时无法切换服务")}},f=g=>{const m=d.items.find(w=>w.service?.targetPeerId===g.targetPeerId),y=r.find(w=>w.targetPeerId&&w.targetPeerId===g.targetPeerId||w.origin===(g.serviceOrigin||g.url));return{phase:m?.phase,running:m?.runningCount??y?.runningCount??0,review:m?.reviewCount??y?.reviewCount??0}},h=g=>{const m=f(g);return m.review?p.jsxs("span",{className:"inline-flex shrink-0 items-center gap-0.5 text-[color:var(--warning)]",title:"等待处理",children:[p.jsx(aS,{size:11}),m.review]}):m.phase==="connecting"||m.phase==="reconnecting"?p.jsx(He,{size:12,className:"shrink-0 animate-spin","aria-label":"正在连接"}):m.phase==="offline"||m.phase==="login"?p.jsx("span",{className:"shrink-0 text-[color:var(--warning)]",title:m.phase==="login"?"需要登录":"连接已断开",children:"!"}):m.running?p.jsx("span",{className:"shrink-0 text-[color:var(--success)]",title:"运行中",children:m.running}):null};return t.length<=1?null:p.jsxs("div",{className:"min-w-0 shrink-0 px-2 py-2","data-sidebar-gesture-ignore":!0,children:[p.jsx("nav",{ref:c,"aria-label":"切换服务",className:"relative flex min-w-0 gap-1 overflow-x-auto overscroll-x-contain rounded-lg [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:t.map(g=>p.jsxs("button",{type:"button",onClick:()=>{u(g)},"aria-current":g.targetPeerId===o?"page":void 0,title:g.label,style:{flex:t.length>3?"0 0 30%":"1 1 0%"},className:`inline-flex min-h-10 min-w-0 items-center justify-center gap-1 rounded-lg px-2 text-[12px] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary ${g.targetPeerId===o?"bg-surface-elevated font-semibold text-foreground":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,children:[p.jsx("span",{className:"truncate",children:g.label}),h(g)]},g.id))}),i&&p.jsx("p",{role:"alert",className:"mt-1 text-[11px] text-[color:var(--warning)]",children:i})]})}function Hi(t,e,r=new Set){for(const n of t.keys()){if(t.size<=e)break;r.has(n)||t.delete(n)}return t}const cA={},nu=t=>{let e;const r=new Set,n=(d,u)=>{const f=typeof d=="function"?d(e):d;if(!Object.is(f,e)){const h=e;e=u??(typeof f!="object"||f===null)?f:Object.assign({},e,f),r.forEach(g=>g(e,h))}},o=()=>e,c={setState:n,getState:o,getInitialState:()=>l,subscribe:d=>(r.add(d),()=>r.delete(d)),destroy:()=>{(cA?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),r.clear()}},l=e=t(n,o,c);return c},lA=t=>t?nu(t):nu;var qi={exports:{}},Ki={},zi={exports:{}},Vi={};var ou;function dA(){if(ou)return Vi;ou=1;var t=Wa();function e(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}var r=typeof Object.is=="function"?Object.is:e,n=t.useState,o=t.useEffect,s=t.useLayoutEffect,i=t.useDebugValue;function a(u,f){var h=f(),g=n({inst:{value:h,getSnapshot:f}}),m=g[0].inst,y=g[1];return s(function(){m.value=h,m.getSnapshot=f,c(m)&&y({inst:m})},[u,h,f]),o(function(){return c(m)&&y({inst:m}),u(function(){c(m)&&y({inst:m})})},[u]),i(h),h}function c(u){var f=u.getSnapshot;u=u.value;try{var h=f();return!r(u,h)}catch{return!0}}function l(u,f){return f()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?l:a;return Vi.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:d,Vi}var su;function uA(){return su||(su=1,zi.exports=dA()),zi.exports}var iu;function fA(){if(iu)return Ki;iu=1;var t=Wa(),e=uA();function r(l,d){return l===d&&(l!==0||1/l===1/d)||l!==l&&d!==d}var n=typeof Object.is=="function"?Object.is:r,o=e.useSyncExternalStore,s=t.useRef,i=t.useEffect,a=t.useMemo,c=t.useDebugValue;return Ki.useSyncExternalStoreWithSelector=function(l,d,u,f,h){var g=s(null);if(g.current===null){var m={hasValue:!1,value:null};g.current=m}else m=g.current;g=a(function(){function w(T){if(!I){if(I=!0,v=T,T=f(T),h!==void 0&&m.hasValue){var N=m.value;if(h(N,T))return A=N}return A=T}if(N=A,n(v,T))return N;var k=f(T);return h!==void 0&&h(N,k)?(v=T,N):(v=T,A=k)}var I=!1,v,A,B=u===void 0?null:u;return[function(){return w(d())},B===null?void 0:function(){return w(B())}]},[d,u,f,h]);var y=o(l,g[0],g[1]);return i(function(){m.hasValue=!0,m.value=y},[y]),c(y),y},Ki}var au;function hA(){return au||(au=1,qi.exports=fA()),qi.exports}var pA=hA();const gA=Iu(pA),Ip={},{useDebugValue:mA}=Ue,{useSyncExternalStoreWithSelector:wA}=gA;let cu=!1;const yA=t=>t;function bA(t,e=yA,r){(Ip?"production":void 0)!=="production"&&r&&!cu&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),cu=!0);const n=wA(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,r);return mA(n),n}const lu=t=>{(Ip?"production":void 0)!=="production"&&typeof t!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof t=="function"?lA(t):t,r=(n,o)=>bA(e,n,o);return Object.assign(r,e),r},vA=t=>t?lu(t):lu;function Vt(t,e){if(typeof window>"u")return null;try{const r=window.localStorage.getItem(t);if(r===null||r==="")return null;const n=JSON.parse(r);return e(n)?n:null}catch{return null}}function nt(t,e){if(!(typeof window>"u"))try{window.localStorage.setItem(t,JSON.stringify(e))}catch{}}function Wi(t){if(!(typeof window>"u"))try{window.localStorage.removeItem(t)}catch{}}const Un=new Map,Gr=new Map,Uo=new Map;function zk(t,e,r){if(typeof window>"u")return;const n=Date.now(),o=Uo.get(t)??0,s=n-o;if(s>=r){Uo.set(t,n),nt(t,e);return}if(Gr.set(t,e),Un.has(t))return;const i=r-s,a=setTimeout(()=>{Un.delete(t);const c=Gr.get(t);Gr.delete(t),Uo.set(t,Date.now()),c!==void 0&&nt(t,c)},i);Un.set(t,a)}function xA(t){const e=Un.get(t);e&&(clearTimeout(e),Un.delete(t));const r=Gr.get(t);r!==void 0&&(Gr.delete(t),Uo.set(t,Date.now()),nt(t,r))}function Vk(t,e){if(t===e)return!0;try{return JSON.stringify(t)===JSON.stringify(e)}catch{return!1}}if(typeof window<"u"){const t=()=>{for(const e of Gr.keys())xA(e)};window.addEventListener("pagehide",t),window.addEventListener("termdock:before-update",t),document.addEventListener("visibilitychange",()=>{document.hidden&&t()})}const SA=600,Yn=320,EA=280,AA=5;function Wk(t,e,r=0){const n=Math.max(Yn,e-Math.max(0,r)-AA*(r>0?2:1)-EA);return Math.min(n,Math.max(Yn,t))}const Cp="termdock:right-sidebar:tabs-by-session:v2",Rp="termdock:right-sidebar:explorer-roots-by-session:v2",Hc="termdock:right-sidebar:pinned-explorer-roots:v1",Tp="termdock:right-sidebar:selected-files-by-session:v2",Pp="termdock:right-sidebar:show-hidden-files:v1",Ua="termdock:right-sidebar:file-sort-modes:v1",du="termdock-sidebar-group-by-folder",Np="termdock-sidebar-collapsed-folder-groups",Lp="termdock-left-sidebar-pinned",Bp="termdock-left-sidebar-width",_p="termdock-right-sidebar-pinned",Dp="termdock-right-sidebar-width",qc="termdock:right-sidebar:widths-by-session:v1",Op="termdock:right-sidebar:split-state-initialized:v1",Fp="termdock-right-sidebar-layout-preference";function kA(){if(typeof window>"u")return!0;try{const t=window.localStorage.getItem(Lp);return t===null?!0:t==="1"}catch{return!0}}function uu(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Lp,t?"1":"0")}catch{}}function IA(){if(typeof window>"u")return 300;try{const t=window.localStorage.getItem(Bp);if(!t)return 300;const e=parseInt(t,10);return Number.isFinite(e)&&e>=200&&e<=500?e:300}catch{return 300}}function CA(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Bp,String(t))}catch{}}function RA(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(_p)==="1"}catch{return!1}}function fu(t){if(!(typeof window>"u"))try{window.localStorage.setItem(_p,t?"1":"0")}catch{}}function $o(){if(typeof window>"u")return 760;try{const t=window.localStorage.getItem(Dp);if(!t)return 760;const e=parseInt(t,10);return Number.isFinite(e)&&e>=Yn?e:760}catch{return 760}}function TA(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Dp,String(t))}catch{}}function PA(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="number"&&Number.isFinite(e)&&e>=Yn)}function ws(){return Vt(qc,PA)??{}}function hu(t,e){if(!t){TA(e);return}nt(qc,{...ws(),[t]:e})}function NA(){if(typeof window>"u")return"auto";try{const t=window.localStorage.getItem(Fp);return t==="narrow"||t==="wide"?t:"auto"}catch{return"auto"}}function LA(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Fp,t)}catch{}}function Gk(t,e,r){return!e||r==="auto"?t<SA:r==="narrow"}function BA(){return!0}function pu(t){if(!(typeof window>"u"))try{t?window.localStorage.setItem(du,"1"):window.localStorage.setItem(du,"0")}catch{}}function _A(){if(typeof window>"u")return new Set;try{const t=window.localStorage.getItem(Np);if(!t)return new Set;const e=JSON.parse(t);return Array.isArray(e)?new Set(e.filter(r=>typeof r=="string")):new Set}catch{return new Set}}function DA(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Np,JSON.stringify([...t]))}catch{}}function OA(t){return t==="git"||t==="files"||t==="diff"}function FA(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(OA)}function $a(){return Vt(Cp,FA)??{}}function Gi(t,e){t&&nt(Cp,{...$a(),[t]:e})}function MA(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="string")}function gu(){return Vt(Rp,MA)??{}}function Bo(t){nt(Rp,t)}function jA(t){return t!==null&&typeof t=="object"&&typeof t.path=="string"&&(t.kind==="file"||t.kind==="directory")}function UA(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>Array.isArray(e)&&e.every(r=>typeof r=="string"||jA(r)))}function Mp(t){const e=new Set,r=[];for(const n of t){const o=typeof n=="string"?{path:n,kind:"directory"}:n;!o.path||e.has(o.path)||(e.add(o.path),r.push(o))}return r}function $A(){const t=Vt(Hc,UA)??{},e={};for(const[r,n]of Object.entries(t))e[r]=Mp(n);return e}function mu(t){nt(Hc,t)}function HA(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="string")}function Ha(){return Vt(Tp,HA)??{}}function An(t,e){if(!t)return;const r={...Ha()};e?r[t]=e:delete r[t],nt(Tp,r)}function ys(t,e){return e?t?`${t}\0${e}`:e:null}function qa(t,e,r){return r?`split-workspace\0${r}`:ys(t,e)}function Xk(t,e,r){const n=ws(),o=qa(t,e,r);if(o&&n[o]!==void 0)return n[o];if(r){const s=ys(t,e);if(s&&n[s]!==void 0)return n[s]}return $o()}function jp(){const t=Vt(Op,e=>Array.isArray(e)&&e.every(r=>typeof r=="string"));return new Set(t??[])}function qA(t){const e=jp();e.has(t)||(e.add(t),nt(Op,[...e]))}function KA(t){return typeof t=="boolean"}function zA(){return Vt(Pp,KA)??!1}function VA(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>e==="modified")}function WA(){return Vt(Ua,VA)??{}}let kn=null;const Xi=new Map;let In=null;const Yi=globalThis.crypto?.randomUUID?.()??`pins-${Math.random().toString(36).slice(2)}`;function GA(t){const e=t.replace(/\/+$/,"")||"/";return e==="/"?"/":e.slice(0,e.lastIndexOf("/"))||"/"}function Tr(t,e){const r=t.replace(/\/+$/,"")||"/";return e===r||e.startsWith(`${r}/`)}function wu(t,e="name"){return[...t].sort((r,n)=>{if(r.type==="directory"&&n.type!=="directory")return-1;if(r.type!=="directory"&&n.type==="directory")return 1;if(e==="modified"){const o=Date.parse(n.modified??"")-Date.parse(r.modified??"");if(Number.isFinite(o)&&o!==0)return o}return r.name.localeCompare(n.name)})}function XA(t){return t.entry?{name:t.entry.name,path:t.entry.path,type:t.entry.type,isSymlink:t.entry.isSymlink,modified:t.entry.modified,expanded:!1,loaded:!1,children:t.entry.type==="directory"?[]:void 0}:null}const Me=vA(t=>({leftOpen:!1,rightOpen:!1,leftPinned:kA(),leftSidebarWidth:IA(),rightPinned:RA(),rightSidebarWidth:$o(),rightSidebarLayoutPreference:NA(),rightTab:"files",rightSearchOpen:!1,rootPath:null,contextKey:null,rightSidebarWidthContextKey:null,explorerRoot:null,explorerRootCache:gu(),pinnedExplorerRootsCache:$A(),pinnedExplorerRootsHydrated:!1,expandedPaths:new Set,selectedFilePath:null,directoryCache:new Map,fileSortModes:WA(),fileSortModesHydrated:!1,showHiddenFiles:zA(),groupByFolder:BA(),collapsedGroups:_A(),changedFiles:new Map,fileChangeVersions:new Map,fileWatchEpoch:0,gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null,gitBundleError:null,gitBundleLastLoadedAt:null,gitBundleCacheInfo:null,projectStateCache:new Map,openLeft:()=>t({leftOpen:!0}),closeLeft:()=>t({leftOpen:!1}),toggleLeft:()=>t(e=>({leftOpen:!e.leftOpen,rightOpen:e.leftOpen?e.rightOpen:!1})),toggleLeftPinned:()=>t(e=>{const r=!e.leftPinned;return uu(r),{leftPinned:r,leftOpen:!0}}),setLeftPinned:e=>t(()=>(uu(e),{leftPinned:e})),setLeftSidebarWidth:e=>t(r=>{const n=Math.min(Math.max(e,200),500);return r.leftSidebarWidth===n?r:(CA(n),{leftSidebarWidth:n})}),toggleRightPinned:()=>t(e=>{const r=!e.rightPinned;return fu(r),{rightPinned:r,rightOpen:!0}}),setRightPinned:e=>t(()=>(fu(e),{rightPinned:e})),setRightSidebarWidth:e=>t(r=>{const n=Math.max(e,Yn);return r.rightSidebarWidth===n?r:(hu(r.rightSidebarWidthContextKey,n),{rightSidebarWidth:n})}),setRightSidebarLayoutPreference:e=>t(r=>r.rightSidebarLayoutPreference===e?r:(LA(e),{rightSidebarLayoutPreference:e})),openRight:()=>t({rightOpen:!0}),closeRight:()=>t({rightOpen:!1,rightSearchOpen:!1}),toggleRight:()=>t(e=>({rightOpen:!e.rightOpen,rightSearchOpen:e.rightOpen?!1:e.rightSearchOpen,leftOpen:e.rightOpen?e.leftOpen:!1})),closeAll:()=>t({leftOpen:!1,rightOpen:!1,rightSearchOpen:!1}),setRightTab:e=>t(r=>(Gi(r.contextKey,e),{rightTab:e})),openRightSearch:()=>t({rightSearchOpen:!0}),closeRightSearch:()=>t({rightSearchOpen:!1}),setRightSearchOpen:e=>t({rightSearchOpen:e}),setRootPath:(e,r=null,n=null)=>t(o=>{const s=ys(r,e),i=qa(r,e,n),a=n?i:s;if(o.contextKey===a&&o.rightSidebarWidthContextKey===i)return e===o.rootPath?o:{rootPath:e};const c=new Map(o.projectStateCache);o.contextKey&&c.set(o.contextKey,{rightTab:o.rightTab,explorerRoot:o.explorerRoot,expandedPaths:new Set(o.expandedPaths),selectedFilePath:o.selectedFilePath,directoryCache:new Map(o.directoryCache),changedFiles:new Map(o.changedFiles),gitBundleError:o.gitBundleError,gitBundleLastLoadedAt:o.gitBundleLastLoadedAt,gitBundleCacheInfo:o.gitBundleCacheInfo});const l=n?jp().has(n):!1;let d={...gu(),...o.explorerRootCache};const u=!!n&&!l,f=u&&s?o.contextKey===s?{rightTab:o.rightTab,explorerRoot:o.explorerRoot,expandedPaths:new Set(o.expandedPaths),selectedFilePath:o.selectedFilePath,directoryCache:new Map(o.directoryCache),changedFiles:new Map(o.changedFiles),gitBundleError:o.gitBundleError,gitBundleLastLoadedAt:o.gitBundleLastLoadedAt,gitBundleCacheInfo:o.gitBundleCacheInfo}:c.get(s):void 0;if(u&&n){const v=f?.rightTab??(s?$a()[s]:void 0)??"files",A=f?.explorerRoot??(s?o.explorerRootCache[s]:void 0)??e,B=f?.selectedFilePath??(s?Ha()[s]:void 0)??null,T={rightTab:v,explorerRoot:A,expandedPaths:new Set(f?.expandedPaths??[]),selectedFilePath:B,directoryCache:new Map(f?.directoryCache??[]),changedFiles:new Map(f?.changedFiles??[]),gitBundleError:f?.gitBundleError??null,gitBundleLastLoadedAt:f?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:f?.gitBundleCacheInfo??null};a&&(c.set(a,T),Gi(a,v),An(a,B),A&&(d={...d,[a]:A},Bo(d))),qA(n)}Hi(c,12,new Set(a?[a]:[]));const h=a?c.get(a):void 0,g=a?$a()[a]:void 0,m=ws();let y=i?m[i]:void 0;n&&i&&y===void 0&&(y=(s?m[s]:void 0)??$o(),hu(i,y));const w=a?d[a]:void 0,I=a?Ha()[a]:void 0;return{rootPath:e,contextKey:a,rightSidebarWidthContextKey:i,rightSidebarWidth:y??$o(),rightTab:h?.rightTab??g??"files",explorerRoot:h?.explorerRoot??w??e,expandedPaths:h?new Set(h.expandedPaths):new Set,selectedFilePath:h?.selectedFilePath??I??null,explorerRootCache:d,directoryCache:h?new Map(h.directoryCache):new Map,changedFiles:h?new Map(h.changedFiles):new Map,gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null,gitBundleError:h?.gitBundleError??null,gitBundleLastLoadedAt:h?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:h?.gitBundleCacheInfo??null,projectStateCache:c}}),inheritRightSidebarStateFromSplitWorkspace:(e,r)=>t(n=>{if(!e||r.length===0)return n;const o=ws(),s=qa(null,null,e);if(!s)return n;const i=o[s]??(n.rightSidebarWidthContextKey===s?n.rightSidebarWidth:void 0),a=n.contextKey===s?{rightTab:n.rightTab,explorerRoot:n.explorerRoot,expandedPaths:new Set(n.expandedPaths),selectedFilePath:n.selectedFilePath,directoryCache:new Map(n.directoryCache),changedFiles:new Map(n.changedFiles),gitBundleError:n.gitBundleError,gitBundleLastLoadedAt:n.gitBundleLastLoadedAt,gitBundleCacheInfo:n.gitBundleCacheInfo}:n.projectStateCache.get(s);if(i===void 0&&!a)return n;const c={...o},l=new Map(n.projectStateCache),d={...n.explorerRootCache};for(const u of r){const f=ys(u.sessionId,u.rootPath);f&&(i!==void 0&&(c[f]=i),a&&(l.set(f,{...a,expandedPaths:new Set(a.expandedPaths),directoryCache:new Map(a.directoryCache),changedFiles:new Map(a.changedFiles)}),Gi(f,a.rightTab),An(f,a.selectedFilePath),a.explorerRoot?d[f]=a.explorerRoot:delete d[f]))}return i!==void 0&&nt(qc,c),a&&Bo(d),Hi(l,12,new Set(n.contextKey?[n.contextKey]:[])),{projectStateCache:l,explorerRootCache:d}}),setExplorerRoot:e=>t(r=>{if(r.explorerRoot===e)return r;const n={...r.explorerRootCache};return r.contextKey&&e&&(n[r.contextKey]=e,Bo(n)),{explorerRoot:e,explorerRootCache:n}}),resetExplorerToProject:()=>t(e=>{if(e.explorerRoot===e.rootPath)return e;const r={...e.explorerRootCache};return e.contextKey&&e.rootPath&&(r[e.contextKey]=e.rootPath,Bo(r)),{explorerRoot:e.rootPath,explorerRootCache:r}}),pinExplorerRoot:(e,r="directory")=>t(n=>{if(!n.rootPath||!e)return n;const o=n.rootPath,s=n.pinnedExplorerRootsCache[n.rootPath]??[];if(s.some(a=>a.path===e))return n;const i={...n.pinnedExplorerRootsCache,[n.rootPath]:[{path:e,kind:r},...s].slice(0,12)};return mu(i),(async()=>{try{await Me.getState().hydratePinnedExplorerRoots();const a=await Gt({pinnedExplorerRoot:{rootPath:o,path:e,kind:r,pinned:!0},pinnedExplorerRootsOrigin:Yi});Me.getState().syncPinnedExplorerRoots(a.pinnedExplorerRoots??{})}catch{}})(),{pinnedExplorerRootsCache:i}}),unpinExplorerRoot:e=>t(r=>{if(!r.rootPath||!e)return r;const n=r.rootPath,o=r.pinnedExplorerRootsCache[r.rootPath]??[],s=o.find(c=>c.path===e);if(!o.some(c=>c.path===e))return r;const i=o.filter(c=>c.path!==e),a={...r.pinnedExplorerRootsCache};return i.length>0?a[r.rootPath]=i:delete a[r.rootPath],mu(a),(async()=>{try{await Me.getState().hydratePinnedExplorerRoots();const c=await Gt({pinnedExplorerRoot:{rootPath:n,path:e,kind:s?.kind??"directory",pinned:!1},pinnedExplorerRootsOrigin:Yi});Me.getState().syncPinnedExplorerRoots(c.pinnedExplorerRoots??{})}catch{}})(),{pinnedExplorerRootsCache:a}}),hydratePinnedExplorerRoots:async()=>{if(!Me.getState().pinnedExplorerRootsHydrated)return In||(In=(async()=>{const e=Me.getState().pinnedExplorerRootsCache;let n=(await ms()).pinnedExplorerRoots??{};Object.keys(n).length===0&&Object.keys(e).length>0&&(n=(await Gt({pinnedExplorerRoots:e,pinnedExplorerRootsOrigin:Yi})).pinnedExplorerRoots??e),Me.getState().syncPinnedExplorerRoots(n)})().finally(()=>{In=null}),In)},syncPinnedExplorerRoots:e=>t(()=>{const r={};for(const[n,o]of Object.entries(e)){const s=Mp(o);s.length>0&&(r[n]=s.slice(0,12))}return Wi(Hc),{pinnedExplorerRootsCache:r,pinnedExplorerRootsHydrated:!0}}),toggleExpanded:e=>t(r=>{const n=new Set(r.expandedPaths);return n.has(e)?n.delete(e):n.add(e),{expandedPaths:n}}),selectFile:e=>t(r=>(An(r.contextKey,e),{selectedFilePath:e})),toggleShowHiddenFiles:()=>t(e=>{const r=!e.showHiddenFiles;nt(Pp,r);const n=new Map(e.projectStateCache);for(const[o,s]of n)n.set(o,{...s,directoryCache:new Map});return{showHiddenFiles:r,directoryCache:new Map,projectStateCache:n}}),toggleGroupByFolder:()=>t(e=>{const r=!e.groupByFolder;return pu(r),{groupByFolder:r}}),setGroupByFolder:e=>t(r=>r.groupByFolder===e?r:(pu(e),{groupByFolder:e})),toggleGroupCollapsed:e=>t(r=>{const n=new Set(r.collapsedGroups);return n.has(e)?n.delete(e):n.add(e),DA(n),{collapsedGroups:n}}),setDirectoryCache:(e,r)=>t(n=>{const o=new Map(n.directoryCache);return o.delete(e),o.set(e,r),Hi(o,128,new Set([...n.expandedPaths,e,n.explorerRoot??n.rootPath??""])),{directoryCache:o}}),reconcileDirectoryCache:(e,r)=>t(n=>{const o=n.directoryCache.get(e);if(!o)return n;const s=new Map(o.map(d=>[d.path,d])),i=new Set(r.map(d=>d.path)),a=new Map(n.directoryCache),c=r.map(d=>{const u=s.get(d.path);return{name:d.name,path:d.path,type:d.type,isSymlink:d.isSymlink,modified:d.modified,expanded:u?.expanded??!1,loaded:u?.loaded??!1,children:d.type==="directory"?u?.children??[]:void 0}});a.set(e,wu(c,n.fileSortModes[e]??"name"));for(const d of o)if(!i.has(d.path))for(const u of a.keys())Tr(d.path,u)&&a.delete(u);let l=n.selectedFilePath;return l&&o.find(u=>!i.has(u.path)&&Tr(u.path,l))&&(l=null,An(n.rootPath,null)),{directoryCache:a,selectedFilePath:l}}),hydrateFileSortModes:async()=>{if(!Me.getState().fileSortModesHydrated)return kn||(kn=(async()=>{const e=Me.getState().fileSortModes;let n=(await ms()).fileSortModes??{};Object.keys(n).length===0&&Object.keys(e).length>0&&(n=(await Gt({fileSortModes:e})).fileSortModes??e),Wi(Ua),t({fileSortModes:n,fileSortModesHydrated:!0,directoryCache:new Map})})().finally(()=>{kn=null}),kn)},setDirectorySortMode:async(e,r)=>{try{await Me.getState().hydrateFileSortModes()}catch{}const n=Me.getState().fileSortModes[e]??"name",o=(Xi.get(e)??0)+1;Xi.set(e,o),t(s=>{const i={...s.fileSortModes};r==="modified"?i[e]=r:delete i[e];const a=new Map(s.directoryCache);return a.delete(e),{fileSortModes:i,fileSortModesHydrated:!0,directoryCache:a}});try{await Gt({fileSortMode:{path:e,mode:r}}),Wi(Ua)}catch{if(Xi.get(e)!==o)return;t(s=>{const i={...s.fileSortModes};n==="modified"?i[e]=n:delete i[e];const a=new Map(s.directoryCache);return a.delete(e),{fileSortModes:i,directoryCache:a}})}},invalidateDirectoryCache:(e,r=!1)=>t(n=>{const o=new Map(n.directoryCache);for(const s of o.keys())(s===e||r&&Tr(e,s))&&o.delete(s);return{directoryCache:o}}),applyFileWatchEvents:e=>t(r=>{if(e.length===0)return r;const n=new Map(r.directoryCache),o=new Map(r.fileChangeVersions);let s=r.selectedFilePath,i=!1,a=!1,c=!1;const l=d=>{o.set(d,(o.get(d)??0)+1),a=!0};for(const d of e){if(d.type==="rescan-required"){c=!0,s&&Tr(d.path,s)&&l(s);continue}const u=GA(d.path),f=n.get(u);if(d.type==="deleted"){if(l(d.path),s&&Tr(d.path,s)&&(s=null,An(r.rootPath,null)),f){const y=f.filter(w=>w.path!==d.path);y.length!==f.length&&(n.set(u,y),i=!0)}for(const y of n.keys())Tr(d.path,y)&&(n.delete(y),i=!0);continue}l(d.path);const h=XA(d);if(!h||!f)continue;const g=f.find(y=>y.path===h.path),m=wu(g?f.map(y=>y.path===h.path?{...y,...h,children:y.children}:y):[...f,h],r.fileSortModes[u]??"name");n.set(u,m),i=!0}return!i&&!a&&!c?r:{directoryCache:i?n:r.directoryCache,selectedFilePath:s,fileChangeVersions:a?o:r.fileChangeVersions,fileWatchEpoch:c?r.fileWatchEpoch+1:r.fileWatchEpoch}}),bumpFileWatchEpoch:()=>t(e=>({fileWatchEpoch:e.fileWatchEpoch+1})),setChangedFiles:e=>t({changedFiles:e}),beginGitBundleLoading:e=>t({gitBundleLoading:!0,gitBundleSlow:!1,gitBundleLoadingOwner:e}),setGitBundleSlowFor:(e,r)=>t(n=>n.gitBundleLoadingOwner===e?{gitBundleSlow:r}:n),finishGitBundleLoading:e=>t(r=>r.gitBundleLoadingOwner===e?{gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null}:r),resetGitBundleLoading:()=>t({gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null}),setGitBundleError:e=>t({gitBundleError:e}),markGitBundleLoaded:(e=null)=>t({gitBundleLastLoadedAt:Date.now(),gitBundleCacheInfo:e})})),Zi=(()=>{if(location.hash.startsWith("#termdock-invite="))try{return gs(location.href)}catch{return}finally{history.replaceState(null,"",location.pathname+location.search)}})(),Ka="termdock-secure-open-session";let Ji,Cn;function YA(){try{const t=JSON.parse(sessionStorage.getItem(Ka)??"null");return t?.serviceId===ne()?.targetPeerId?t.sessionId:void 0}catch{return}}function ZA({children:t}){const[e,r]=F.useState(Zi),[n,o]=F.useState(!1),[s,i]=F.useState(!!Zi),[a,c]=F.useState(!Zi),[l,d]=F.useState(!1),[u,f]=F.useState("正在连接服务…"),[h,g]=F.useState([]),[m,y]=F.useState([]),[w,I]=F.useState(!1),[v,A]=F.useState(!1),[B,T]=F.useState(""),[N,k]=F.useState(!1),[x,S]=F.useState(""),[R,P]=F.useState(ne()?.serviceName??location.hostname),[b,E]=F.useState(YA);F.useEffect(()=>{Ge().then(_=>T(_.peerId)).catch(()=>d(!0))},[]),F.useEffect(()=>{const _=O=>{const{origin:q,sessionId:H}=O.detail;try{const z=JSON.parse(localStorage.getItem("termdock.federation.connections.v1")??"[]").find(W=>io(W).some(X=>new URL(X).origin===new URL(q).origin));if(!z){i(!0);return}if(St()?.focusSession(z.targetPeerId,H))return;sessionStorage.setItem(Ka,JSON.stringify({serviceId:z.targetPeerId,sessionId:H})),et(z).then(()=>{E(H),o(!0)}).catch(()=>{d(!0),i(!0)})}catch{i(!0)}};return window.addEventListener("termdock:open-remote-session",_),()=>window.removeEventListener("termdock:open-remote-session",_)},[]);const C=async(_=5e3)=>{const O=await lt(),q=await on(O,{timeoutMs:_}),H=Mx(),K=Lx()?.targetPeerId;Promise.all([BS(),We()]).then(([W,X])=>{const G=X.find(se=>se.targetPeerId===K),Y=H==="relay"?`经 ${G?.label||K?.slice(-12)||"入口服务"} 中转`:"直连";return O.request({type:"device-name",name:tp(),onlyIfMissing:!0,profile:{...W,route:Y}})}).catch(()=>{}),I(q.fullService),A(q.canManage),o(!0),c(!1),d(!1);const z=ne();Tn({phase:"ready",...z?{service:{...z,id:z.targetPeerId,label:z.serviceName||location.host}}:{}}),hi()&&Fx()};F.useEffect(()=>{let _=!1,O=!1,q=0,H;const K=async()=>{if(_||O||q&&(document.hidden||!hi()))return;if(!navigator.onLine){c(!0),d(!0),f("网络已断开,恢复后会自动连接"),Tn({phase:"offline"});return}O=!0,clearTimeout(H);const Pe=performance.now(),Oe=vn();try{if(Hn&&!ne())throw new Error("工作区的服务记录已移除,请重新添加服务。");Cn??=window.termdockDesktop?.getServiceConnection?.();const oe=await Cn;if(oe?.invitation){r(gs(oe.invitation)),i(!0),c(!1);return}if(!ne()){if(e){c(!1);return}if(Ji??=(async()=>{if(oe?.targetPeerId){await et({...oe,targetPeerId:oe.targetPeerId,serviceName:oe.label});return}const ot=await window.termdockDesktop?.getLocalInvite?.();ot?await et(ot):await Bx()})(),await Ji,!ne()){_||(o(!1),c(!1),d(!1));return}}_||await C(Oe?.canSwitchTransport?2500:5e3),q=0,performance.measure("termdock:connection-ready",{start:Pe,end:performance.now()})}catch(oe){if(_)return;oe instanceof Ve?(o(!1),c(!1),i(!1),d(!1),Tn({phase:"login"})):(Oe&&vn()===Oe&&qh(),d(!0),c(!0),Ji=void 0,f("连接暂未恢复,正在重试…"),Tn({phase:"reconnecting"}),q++,H=setTimeout(()=>{K()},Math.min(5e3,300*2**Math.min(q-1,5))),console.debug("[connection] retry",{elapsedMs:Math.round(performance.now()-Pe),attempt:q,reason:oe instanceof Error?oe.message:"unknown"}))}finally{O=!1}},z=()=>{document.visibilityState==="visible"&&hi()&&K()},W=z,X=()=>{q=0,z()},G=()=>{Me.getState().openLeft(),z()};window.addEventListener(Aa,z),window.addEventListener(ka,G),Hn&&Me.getState().openLeft(),St()?.attach(kc(),window),K(),document.addEventListener("visibilitychange",W),window.addEventListener("focus",z),window.addEventListener("online",X);const Y=navigator.connection;Y?.addEventListener("change",X),window.addEventListener("auth:unauthorized",z),window.addEventListener(lr,z);const se=setInterval(z,3e4);return()=>{_=!0,clearTimeout(H),clearInterval(se),window.removeEventListener(Aa,z),window.removeEventListener(ka,G),document.removeEventListener("visibilitychange",W),window.removeEventListener("focus",z),window.removeEventListener("online",X),Y?.removeEventListener("change",X),window.removeEventListener("auth:unauthorized",z),window.removeEventListener(lr,z)}},[]);const L=async()=>{const _=vn();if(_){k(!0),S("");try{const O=await _.request({type:"session-list"});y(O.items)}catch{S("暂时无法读取终端列表,请重试。")}try{if(v){const O=await _.request({type:"grants-list"}),q=O.subjectLabels??{},H=await _.request({type:"route-access"}),K=await We(),z=(Array.isArray(H.grants)?H.grants:[]).map(W=>({id:`route:${W.id}`,subjectId:W.subjectId,scope:{kind:"service"},actions:["route.use"],routeTargetServiceId:W.targetServiceId,routeTargetName:K.find(X=>X.targetPeerId===W.targetServiceId)?.label||"指定服务",...W.active?{}:{revokedAt:W.revokedAt??0}}));g([...O.grants,...z].map(W=>({...W,label:q[W.subjectId],deviceProfile:O.deviceProfiles?.[W.subjectId]})))}else{const O=await _.request({type:"permissions"});g(O.grants??[])}}catch{S("暂时无法读取设备权限,请重试。")}finally{k(!1)}}};F.useEffect(()=>{const _=()=>{i(!0),n&&L()};return window.addEventListener(Ta,_),()=>window.removeEventListener(Ta,_)},[n,v]);const M=async _=>{if(!_.pairingCode&&!_.routeCode&&ne()?.targetPeerId!==_.targetPeerId&&St()){const O={..._,id:_.targetPeerId,label:_.serviceName||new URL(_.serviceOrigin||_.url).host};if(await Et(O),ps(O)){i(!1);return}}await et(_),Cn&&(Cn=Cn.then(O=>O?{...O,invitation:void 0}:null)),r(void 0),E(void 0),sessionStorage.removeItem(Ka),P(_.serviceName??new URL(_.url).hostname),await C(),i(!1),d(!1)},$=async _=>{const O=window.termdockDesktop;if(O?.openServiceConnection){const q=await O.openServiceConnection(_);if(!q.ok)throw new Error(q.error||"暂时无法打开这台服务。");i(!1);return}if(ps(_)){i(!1);return}if(_.targetPeerId)try{await M({..._,targetPeerId:_.targetPeerId,serviceName:_.label});return}catch(q){if(!(q instanceof Ve))throw q}return wd(_.serviceOrigin||_.url)};F.useEffect(()=>{const _=O=>{$(O.detail).catch(q=>{i(!0),S(q instanceof Error?q.message:"暂时无法打开服务")})};return window.addEventListener(ja,_),()=>window.removeEventListener(ja,_)});const j=async(_,O)=>{if(_.includes("#termdock-invite=")){const H=gs(_);if(window.termdockDesktop?.openServiceConnection){const K=await window.termdockDesktop.openServiceConnection({id:H.targetPeerId,url:H.url,label:H.serviceName||new URL(H.serviceOrigin||H.url).host,targetPeerId:H.targetPeerId,serviceOrigin:H.serviceOrigin,entryServiceId:H.entryServiceId},_);if(!K.ok)throw new Error(K.error||"暂时无法打开邀请。");i(!1);return}if(O!==void 0&&H.routeOnly){await yd(H,O),await C(),i(!1);return}try{await M(H)}catch(K){if(H.routeOnly&&K instanceof Ve)return{passwordRequired:!0};throw K}return}const q=Le(_);return window.termdockDesktop?.openServiceConnection?$({id:q,url:q,label:new URL(q).host}):wd(q,O)},D=async _=>{const O=await lt(),{includeBackup:q=!0,...H}=_,K=ne(),z=K?dr(K):[];let W;if(q&&z.length){for(const Y of z)try{const se=await Vh({...K,targetPeerId:O.targetPeerId},Y);W={...Y,routeCode:se.routeCode};break}catch{}if(!W)throw new Error("无法分享备用连接:需要入口管理员授权。也可以关闭此选项,生成直接连接邀请。")}let X=K?.serviceOrigin||location.origin;if(["localhost","127.0.0.1","[::1]"].includes(new URL(X).hostname)){const se=await(await O.fetch("/api/terminal/settings")).json();typeof se.localAccess?.url=="string"&&(X=se.localAccess.url)}const G=await O.request({type:"invite-create",...H});if(typeof G.code!="string"||typeof G.expiresAt!="number")throw new Error("暂时无法生成邀请。");return{url:rp({v:1,serviceId:O.targetPeerId,code:G.code,entryUrl:W?.url||X,serviceUrl:X,name:R,entryServiceId:W?.targetPeerId,routeCode:W?.routeCode}),expiresAt:G.expiresAt}};return p.jsxs(p.Fragment,{children:[n?w&&!b?t:p.jsx(gE,{client:vn(),initialSessionId:b}):a?p.jsx("div",{className:"flex h-full min-h-0 flex-col items-center justify-center bg-[var(--chrome-bg)] px-6 text-foreground",children:p.jsxs("div",{className:"flex w-full max-w-xs flex-col items-center text-center",children:[p.jsx("div",{className:"mb-5 flex h-12 w-12 items-center justify-center rounded-2xl bg-surface-2 text-muted-foreground","aria-hidden":"true",children:p.jsx(AS,{size:24,strokeWidth:1.5})}),p.jsx("h1",{className:"max-w-full truncate text-base font-medium tracking-tight",title:R,children:R}),p.jsxs("div",{role:"status",className:"mt-2 flex max-w-full items-center justify-center gap-2 text-xs leading-5 text-muted-foreground",children:[!l&&p.jsx(He,{size:13,className:"shrink-0 animate-spin motion-reduce:animate-none","aria-hidden":"true"}),p.jsx("span",{children:u})]}),l&&p.jsx("p",{className:"mt-2 text-xs leading-5 text-muted-foreground",children:"登录信息已保留"}),p.jsx("button",{type:"button",className:"mt-6 min-h-11 rounded-lg px-4 text-xs text-muted-foreground transition-colors hover:bg-surface-2 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>i(!0),children:"管理服务"})]})}):p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"fixed left-0 right-0 top-[var(--safe-top-inset)] z-chrome sm:right-auto sm:w-72",children:p.jsx(iA,{})}),p.jsx(rA,{onLoginSuccess:()=>{C().catch(()=>d(!0))}})]}),s&&p.jsx(dE,{onConnect:M,onClose:()=>i(!1),onAddService:j,onOpenService:$,onConnectWithPassword:async(_,O)=>{await yd(_,O),await C(),i(!1)},paired:n||!!ne(),initialInvite:e,currentServiceName:R,currentServiceId:vn()?.targetPeerId||ne()?.targetPeerId,currentServiceOrigin:ne()?.serviceOrigin,currentIdentity:B,grants:h,sessions:m,loading:N,loadError:x,onRetry:()=>{L()},onRename:async(_,O)=>{await(await lt()).request({type:"device-name",subjectId:_,name:O}),await L()},hasBackup:!!ne()&&dr(ne()).length>0,onCreateInvite:v?D:void 0,onRevoke:v?async _=>{await(await lt()).request(_.startsWith("route:")?{type:"route-revoke",grantId:_.slice(6)}:{type:"revoke",grantId:_}),await L()}:void 0})]})}function JA(t,e,r){const n=t?.name||"Error",o=t?.message||"Unexpected error";return["Termdock error report",`Time: ${r.capturedAt}`,`URL: ${r.url}`,`User agent: ${r.userAgent}`,"",`${n}: ${o}`,t?.stack?`
|
|
29
|
+
`})]})}const iA={activeKey:"root",items:[]},aA=()=>()=>{},cA=()=>iA,$a="termdock:open-saved-service";function Xk(t,e){F.useEffect(()=>{window.termdockDesktop?.reportServiceActivity?.({runningCount:t,reviewCount:e}),Nn({runningCount:t,reviewCount:e})},[t,e])}function lA(){return window.termdockDesktop?null:p.jsx(dA,{})}function dA(){const[t,e]=F.useState([]),[r,n]=F.useState([]),[o,s]=F.useState(ne()?.targetPeerId),[i,a]=F.useState(""),c=F.useRef(null),l=St(),d=F.useSyncExternalStore(l?.subscribe||aA,l?.snapshot||cA);F.useEffect(()=>{let g=!1,m=0;const y=()=>{const v=++m;s(ne()?.targetPeerId),We().then(A=>{if(!(g||v!==m)){try{const B="termdock-secure-service-order",T=JSON.parse(localStorage.getItem(B)||"[]"),N=Array.isArray(T)?T.filter(R=>typeof R=="string"):[],k=R=>R.targetPeerId||R.id,x=[...N.filter(R=>A.some(P=>k(P)===R)),...A.map(k).filter(R=>!N.includes(R))];A.sort((R,P)=>x.indexOf(k(R))-x.indexOf(k(P)));const S=JSON.stringify(x);S!==localStorage.getItem(B)&&localStorage.setItem(B,S)}catch{}e(A)}}).catch(()=>{})};y();const w=Bu(y),I=window.termdockDesktop?.onServiceActivity?.(n);return window.addEventListener(lr,y),()=>{g=!0,w(),I?.(),window.removeEventListener(lr,y)}},[]),F.useEffect(()=>{const g=c.current,m=g?.querySelector('[aria-current="page"]');if(!g||!m)return;const y=m.offsetLeft,w=y+m.offsetWidth;y<g.scrollLeft?g.scrollLeft=y:w>g.scrollLeft+g.clientWidth&&(g.scrollLeft=w-g.clientWidth)},[o,t]);const u=async g=>{if(a(""),!(g.targetPeerId&&g.targetPeerId===o))try{const m=window.termdockDesktop;if(m?.openServiceConnection){const y=await m.openServiceConnection(g);if(!y.ok)throw new Error(y.error||"暂时无法打开服务")}else ys(g)||window.dispatchEvent(new CustomEvent($a,{detail:g}))}catch(m){a(m instanceof Error?m.message:"暂时无法切换服务")}},f=g=>{const m=d.items.find(w=>w.service?.targetPeerId===g.targetPeerId),y=r.find(w=>w.targetPeerId&&w.targetPeerId===g.targetPeerId||w.origin===(g.serviceOrigin||g.url));return{phase:m?.phase,running:m?.runningCount??y?.runningCount??0,review:m?.reviewCount??y?.reviewCount??0}},h=g=>{const m=f(g);return m.review?p.jsxs("span",{className:"inline-flex shrink-0 items-center gap-0.5 text-[color:var(--warning)]",title:"等待处理",children:[p.jsx(dS,{size:11}),m.review]}):m.phase==="connecting"||m.phase==="reconnecting"?p.jsx(He,{size:12,className:"shrink-0 animate-spin","aria-label":"正在连接"}):m.phase==="offline"||m.phase==="login"?p.jsx("span",{className:"shrink-0 text-[color:var(--warning)]",title:m.phase==="login"?"需要登录":"连接已断开",children:"!"}):m.running?p.jsx("span",{className:"shrink-0 text-[color:var(--success)]",title:"运行中",children:m.running}):null};return t.length<=1?null:p.jsxs("div",{className:"min-w-0 shrink-0 px-2 py-2","data-sidebar-gesture-ignore":!0,children:[p.jsx("nav",{ref:c,"aria-label":"切换服务",className:"relative flex min-w-0 gap-1 overflow-x-auto overscroll-x-contain rounded-lg [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:t.map(g=>p.jsxs("button",{type:"button",onClick:()=>{u(g)},"aria-current":g.targetPeerId===o?"page":void 0,title:g.label,style:{flex:t.length>3?"0 0 30%":"1 1 0%"},className:`inline-flex min-h-10 min-w-0 items-center justify-center gap-1 rounded-lg px-2 text-[12px] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary ${g.targetPeerId===o?"bg-surface-elevated font-semibold text-foreground":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,children:[p.jsx("span",{className:"truncate",children:g.label}),h(g)]},g.id))}),i&&p.jsx("p",{role:"alert",className:"mt-1 text-[11px] text-[color:var(--warning)]",children:i})]})}function zi(t,e,r=new Set){for(const n of t.keys()){if(t.size<=e)break;r.has(n)||t.delete(n)}return t}const uA={},iu=t=>{let e;const r=new Set,n=(d,u)=>{const f=typeof d=="function"?d(e):d;if(!Object.is(f,e)){const h=e;e=u??(typeof f!="object"||f===null)?f:Object.assign({},e,f),r.forEach(g=>g(e,h))}},o=()=>e,c={setState:n,getState:o,getInitialState:()=>l,subscribe:d=>(r.add(d),()=>r.delete(d)),destroy:()=>{(uA?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),r.clear()}},l=e=t(n,o,c);return c},fA=t=>t?iu(t):iu;var Vi={exports:{}},Wi={},Gi={exports:{}},Xi={};var au;function hA(){if(au)return Xi;au=1;var t=Ya();function e(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}var r=typeof Object.is=="function"?Object.is:e,n=t.useState,o=t.useEffect,s=t.useLayoutEffect,i=t.useDebugValue;function a(u,f){var h=f(),g=n({inst:{value:h,getSnapshot:f}}),m=g[0].inst,y=g[1];return s(function(){m.value=h,m.getSnapshot=f,c(m)&&y({inst:m})},[u,h,f]),o(function(){return c(m)&&y({inst:m}),u(function(){c(m)&&y({inst:m})})},[u]),i(h),h}function c(u){var f=u.getSnapshot;u=u.value;try{var h=f();return!r(u,h)}catch{return!0}}function l(u,f){return f()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?l:a;return Xi.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:d,Xi}var cu;function pA(){return cu||(cu=1,Gi.exports=hA()),Gi.exports}var lu;function gA(){if(lu)return Wi;lu=1;var t=Ya(),e=pA();function r(l,d){return l===d&&(l!==0||1/l===1/d)||l!==l&&d!==d}var n=typeof Object.is=="function"?Object.is:r,o=e.useSyncExternalStore,s=t.useRef,i=t.useEffect,a=t.useMemo,c=t.useDebugValue;return Wi.useSyncExternalStoreWithSelector=function(l,d,u,f,h){var g=s(null);if(g.current===null){var m={hasValue:!1,value:null};g.current=m}else m=g.current;g=a(function(){function w(T){if(!I){if(I=!0,v=T,T=f(T),h!==void 0&&m.hasValue){var N=m.value;if(h(N,T))return A=N}return A=T}if(N=A,n(v,T))return N;var k=f(T);return h!==void 0&&h(N,k)?(v=T,N):(v=T,A=k)}var I=!1,v,A,B=u===void 0?null:u;return[function(){return w(d())},B===null?void 0:function(){return w(B())}]},[d,u,f,h]);var y=o(l,g[0],g[1]);return i(function(){m.hasValue=!0,m.value=y},[y]),c(y),y},Wi}var du;function mA(){return du||(du=1,Vi.exports=gA()),Vi.exports}var wA=mA();const yA=Tu(wA),Tp={},{useDebugValue:bA}=Ue,{useSyncExternalStoreWithSelector:vA}=yA;let uu=!1;const xA=t=>t;function SA(t,e=xA,r){(Tp?"production":void 0)!=="production"&&r&&!uu&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),uu=!0);const n=vA(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,r);return bA(n),n}const fu=t=>{(Tp?"production":void 0)!=="production"&&typeof t!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof t=="function"?fA(t):t,r=(n,o)=>SA(e,n,o);return Object.assign(r,e),r},EA=t=>t?fu(t):fu;function Rt(t,e){if(typeof window>"u")return null;try{const r=window.localStorage.getItem(t);if(r===null||r==="")return null;const n=JSON.parse(r);return e(n)?n:null}catch{return null}}function nt(t,e){if(!(typeof window>"u"))try{window.localStorage.setItem(t,JSON.stringify(e))}catch{}}function An(t){if(!(typeof window>"u"))try{window.localStorage.removeItem(t)}catch{}}const qn=new Map,Gr=new Map,Ko=new Map;function Yk(t,e,r){if(typeof window>"u")return;const n=Date.now(),o=Ko.get(t)??0,s=n-o;if(s>=r){Ko.set(t,n),nt(t,e);return}if(Gr.set(t,e),qn.has(t))return;const i=r-s,a=setTimeout(()=>{qn.delete(t);const c=Gr.get(t);Gr.delete(t),Ko.set(t,Date.now()),c!==void 0&&nt(t,c)},i);qn.set(t,a)}function AA(t){const e=qn.get(t);e&&(clearTimeout(e),qn.delete(t));const r=Gr.get(t);r!==void 0&&(Gr.delete(t),Ko.set(t,Date.now()),nt(t,r))}function Zk(t,e){if(t===e)return!0;try{return JSON.stringify(t)===JSON.stringify(e)}catch{return!1}}if(typeof window<"u"){const t=()=>{for(const e of Gr.keys())AA(e)};window.addEventListener("pagehide",t),window.addEventListener("termdock:before-update",t),document.addEventListener("visibilitychange",()=>{document.hidden&&t()})}const kA=600,Qn=320,IA=280,CA=5;function Jk(t,e,r=0){const n=Math.max(Qn,e-Math.max(0,r)-CA*(r>0?2:1)-IA);return Math.min(n,Math.max(Qn,t))}const Pp="termdock:right-sidebar:tabs-by-session:v2",Np="termdock:right-sidebar:explorer-roots-by-session:v2",zc="termdock:right-sidebar:pinned-explorer-roots:v1",Lp="termdock:right-sidebar:selected-files-by-session:v2",Bp="termdock:right-sidebar:show-hidden-files:v1",Ha="termdock:right-sidebar:file-sort-modes:v1",qa="termdock:right-sidebar:nested-git-scan-roots:v1",hu="termdock-sidebar-group-by-folder",_p="termdock-sidebar-collapsed-folder-groups",Dp="termdock-left-sidebar-pinned",Op="termdock-left-sidebar-width",Fp="termdock-right-sidebar-pinned",Mp="termdock-right-sidebar-width",Vc="termdock:right-sidebar:widths-by-session:v1",jp="termdock:right-sidebar:split-state-initialized:v1",Up="termdock-right-sidebar-layout-preference";function RA(){if(typeof window>"u")return!0;try{const t=window.localStorage.getItem(Dp);return t===null?!0:t==="1"}catch{return!0}}function pu(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Dp,t?"1":"0")}catch{}}function TA(){if(typeof window>"u")return 300;try{const t=window.localStorage.getItem(Op);if(!t)return 300;const e=parseInt(t,10);return Number.isFinite(e)&&e>=200&&e<=500?e:300}catch{return 300}}function PA(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Op,String(t))}catch{}}function NA(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Fp)==="1"}catch{return!1}}function gu(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Fp,t?"1":"0")}catch{}}function zo(){if(typeof window>"u")return 760;try{const t=window.localStorage.getItem(Mp);if(!t)return 760;const e=parseInt(t,10);return Number.isFinite(e)&&e>=Qn?e:760}catch{return 760}}function LA(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Mp,String(t))}catch{}}function BA(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="number"&&Number.isFinite(e)&&e>=Qn)}function vs(){return Rt(Vc,BA)??{}}function mu(t,e){if(!t){LA(e);return}nt(Vc,{...vs(),[t]:e})}function _A(){if(typeof window>"u")return"auto";try{const t=window.localStorage.getItem(Up);return t==="narrow"||t==="wide"?t:"auto"}catch{return"auto"}}function DA(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Up,t)}catch{}}function Qk(t,e,r){return!e||r==="auto"?t<kA:r==="narrow"}function OA(){return!0}function wu(t){if(!(typeof window>"u"))try{t?window.localStorage.setItem(hu,"1"):window.localStorage.setItem(hu,"0")}catch{}}function FA(){if(typeof window>"u")return new Set;try{const t=window.localStorage.getItem(_p);if(!t)return new Set;const e=JSON.parse(t);return Array.isArray(e)?new Set(e.filter(r=>typeof r=="string")):new Set}catch{return new Set}}function MA(t){if(!(typeof window>"u"))try{window.localStorage.setItem(_p,JSON.stringify([...t]))}catch{}}function jA(t){return t==="git"||t==="files"||t==="diff"}function UA(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(jA)}function Ka(){return Rt(Pp,UA)??{}}function Yi(t,e){t&&nt(Pp,{...Ka(),[t]:e})}function $A(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="string")}function yu(){return Rt(Np,$A)??{}}function Oo(t){nt(Np,t)}function HA(t){return t!==null&&typeof t=="object"&&typeof t.path=="string"&&(t.kind==="file"||t.kind==="directory")}function qA(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>Array.isArray(e)&&e.every(r=>typeof r=="string"||HA(r)))}function $p(t){const e=new Set,r=[];for(const n of t){const o=typeof n=="string"?{path:n,kind:"directory"}:n;!o.path||e.has(o.path)||(e.add(o.path),r.push(o))}return r}function KA(){const t=Rt(zc,qA)??{},e={};for(const[r,n]of Object.entries(t))e[r]=$p(n);return e}function bu(t){nt(zc,t)}function zA(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="string")}function za(){return Rt(Lp,zA)??{}}function kn(t,e){if(!t)return;const r={...za()};e?r[t]=e:delete r[t],nt(Lp,r)}function xs(t,e){return e?t?`${t}\0${e}`:e:null}function Va(t,e,r){return r?`split-workspace\0${r}`:xs(t,e)}function eI(t,e,r){const n=vs(),o=Va(t,e,r);if(o&&n[o]!==void 0)return n[o];if(r){const s=xs(t,e);if(s&&n[s]!==void 0)return n[s]}return zo()}function Hp(){const t=Rt(jp,e=>Array.isArray(e)&&e.every(r=>typeof r=="string"));return new Set(t??[])}function VA(t){const e=Hp();e.has(t)||(e.add(t),nt(jp,[...e]))}function WA(t){return typeof t=="boolean"}function GA(){return Rt(Bp,WA)??!1}function XA(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>e==="modified")}function YA(){return Rt(Ha,XA)??{}}function ZA(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>e===!0)}function JA(){return Rt(qa,ZA)??{}}let In=null;const Zi=new Map;let Cn=null;const Fo=new Map;let Rn=null;const Ji=globalThis.crypto?.randomUUID?.()??`pins-${Math.random().toString(36).slice(2)}`;function QA(t){const e=t.replace(/\/+$/,"")||"/";return e==="/"?"/":e.slice(0,e.lastIndexOf("/"))||"/"}function Tr(t,e){const r=t.replace(/\/+$/,"")||"/";return e===r||e.startsWith(`${r}/`)}function vu(t,e="name"){return[...t].sort((r,n)=>{if(r.type==="directory"&&n.type!=="directory")return-1;if(r.type!=="directory"&&n.type==="directory")return 1;if(e==="modified"){const o=Date.parse(n.modified??"")-Date.parse(r.modified??"");if(Number.isFinite(o)&&o!==0)return o}return r.name.localeCompare(n.name)})}function ek(t){return t.entry?{name:t.entry.name,path:t.entry.path,type:t.entry.type,isSymlink:t.entry.isSymlink,modified:t.entry.modified,expanded:!1,loaded:!1,children:t.entry.type==="directory"?[]:void 0}:null}const Ie=EA(t=>({leftOpen:!1,rightOpen:!1,leftPinned:RA(),leftSidebarWidth:TA(),rightPinned:NA(),rightSidebarWidth:zo(),rightSidebarLayoutPreference:_A(),rightTab:"files",rightSearchOpen:!1,rootPath:null,contextKey:null,rightSidebarWidthContextKey:null,explorerRoot:null,explorerRootCache:yu(),pinnedExplorerRootsCache:KA(),pinnedExplorerRootsHydrated:!1,expandedPaths:new Set,selectedFilePath:null,directoryCache:new Map,fileSortModes:YA(),fileSortModesHydrated:!1,nestedGitScanRoots:JA(),nestedGitScanRootsHydrated:!1,showHiddenFiles:GA(),groupByFolder:OA(),collapsedGroups:FA(),changedFiles:new Map,fileChangeVersions:new Map,fileWatchEpoch:0,gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null,gitBundleError:null,gitBundleLastLoadedAt:null,gitBundleCacheInfo:null,projectStateCache:new Map,openLeft:()=>t({leftOpen:!0}),closeLeft:()=>t({leftOpen:!1}),toggleLeft:()=>t(e=>({leftOpen:!e.leftOpen,rightOpen:e.leftOpen?e.rightOpen:!1})),toggleLeftPinned:()=>t(e=>{const r=!e.leftPinned;return pu(r),{leftPinned:r,leftOpen:!0}}),setLeftPinned:e=>t(()=>(pu(e),{leftPinned:e})),setLeftSidebarWidth:e=>t(r=>{const n=Math.min(Math.max(e,200),500);return r.leftSidebarWidth===n?r:(PA(n),{leftSidebarWidth:n})}),toggleRightPinned:()=>t(e=>{const r=!e.rightPinned;return gu(r),{rightPinned:r,rightOpen:!0}}),setRightPinned:e=>t(()=>(gu(e),{rightPinned:e})),setRightSidebarWidth:e=>t(r=>{const n=Math.max(e,Qn);return r.rightSidebarWidth===n?r:(mu(r.rightSidebarWidthContextKey,n),{rightSidebarWidth:n})}),setRightSidebarLayoutPreference:e=>t(r=>r.rightSidebarLayoutPreference===e?r:(DA(e),{rightSidebarLayoutPreference:e})),openRight:()=>t({rightOpen:!0}),closeRight:()=>t({rightOpen:!1,rightSearchOpen:!1}),toggleRight:()=>t(e=>({rightOpen:!e.rightOpen,rightSearchOpen:e.rightOpen?!1:e.rightSearchOpen,leftOpen:e.rightOpen?e.leftOpen:!1})),closeAll:()=>t({leftOpen:!1,rightOpen:!1,rightSearchOpen:!1}),setRightTab:e=>t(r=>(Yi(r.contextKey,e),{rightTab:e})),openRightSearch:()=>t({rightSearchOpen:!0}),closeRightSearch:()=>t({rightSearchOpen:!1}),setRightSearchOpen:e=>t({rightSearchOpen:e}),setRootPath:(e,r=null,n=null)=>t(o=>{const s=xs(r,e),i=Va(r,e,n),a=n?i:s;if(o.contextKey===a&&o.rightSidebarWidthContextKey===i)return e===o.rootPath?o:{rootPath:e};const c=new Map(o.projectStateCache);o.contextKey&&c.set(o.contextKey,{rightTab:o.rightTab,explorerRoot:o.explorerRoot,expandedPaths:new Set(o.expandedPaths),selectedFilePath:o.selectedFilePath,directoryCache:new Map(o.directoryCache),changedFiles:new Map(o.changedFiles),gitBundleError:o.gitBundleError,gitBundleLastLoadedAt:o.gitBundleLastLoadedAt,gitBundleCacheInfo:o.gitBundleCacheInfo});const l=n?Hp().has(n):!1;let d={...yu(),...o.explorerRootCache};const u=!!n&&!l,f=u&&s?o.contextKey===s?{rightTab:o.rightTab,explorerRoot:o.explorerRoot,expandedPaths:new Set(o.expandedPaths),selectedFilePath:o.selectedFilePath,directoryCache:new Map(o.directoryCache),changedFiles:new Map(o.changedFiles),gitBundleError:o.gitBundleError,gitBundleLastLoadedAt:o.gitBundleLastLoadedAt,gitBundleCacheInfo:o.gitBundleCacheInfo}:c.get(s):void 0;if(u&&n){const v=f?.rightTab??(s?Ka()[s]:void 0)??"files",A=f?.explorerRoot??(s?o.explorerRootCache[s]:void 0)??e,B=f?.selectedFilePath??(s?za()[s]:void 0)??null,T={rightTab:v,explorerRoot:A,expandedPaths:new Set(f?.expandedPaths??[]),selectedFilePath:B,directoryCache:new Map(f?.directoryCache??[]),changedFiles:new Map(f?.changedFiles??[]),gitBundleError:f?.gitBundleError??null,gitBundleLastLoadedAt:f?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:f?.gitBundleCacheInfo??null};a&&(c.set(a,T),Yi(a,v),kn(a,B),A&&(d={...d,[a]:A},Oo(d))),VA(n)}zi(c,12,new Set(a?[a]:[]));const h=a?c.get(a):void 0,g=a?Ka()[a]:void 0,m=vs();let y=i?m[i]:void 0;n&&i&&y===void 0&&(y=(s?m[s]:void 0)??zo(),mu(i,y));const w=a?d[a]:void 0,I=a?za()[a]:void 0;return{rootPath:e,contextKey:a,rightSidebarWidthContextKey:i,rightSidebarWidth:y??zo(),rightTab:h?.rightTab??g??"files",explorerRoot:h?.explorerRoot??w??e,expandedPaths:h?new Set(h.expandedPaths):new Set,selectedFilePath:h?.selectedFilePath??I??null,explorerRootCache:d,directoryCache:h?new Map(h.directoryCache):new Map,changedFiles:h?new Map(h.changedFiles):new Map,gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null,gitBundleError:h?.gitBundleError??null,gitBundleLastLoadedAt:h?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:h?.gitBundleCacheInfo??null,projectStateCache:c}}),inheritRightSidebarStateFromSplitWorkspace:(e,r)=>t(n=>{if(!e||r.length===0)return n;const o=vs(),s=Va(null,null,e);if(!s)return n;const i=o[s]??(n.rightSidebarWidthContextKey===s?n.rightSidebarWidth:void 0),a=n.contextKey===s?{rightTab:n.rightTab,explorerRoot:n.explorerRoot,expandedPaths:new Set(n.expandedPaths),selectedFilePath:n.selectedFilePath,directoryCache:new Map(n.directoryCache),changedFiles:new Map(n.changedFiles),gitBundleError:n.gitBundleError,gitBundleLastLoadedAt:n.gitBundleLastLoadedAt,gitBundleCacheInfo:n.gitBundleCacheInfo}:n.projectStateCache.get(s);if(i===void 0&&!a)return n;const c={...o},l=new Map(n.projectStateCache),d={...n.explorerRootCache};for(const u of r){const f=xs(u.sessionId,u.rootPath);f&&(i!==void 0&&(c[f]=i),a&&(l.set(f,{...a,expandedPaths:new Set(a.expandedPaths),directoryCache:new Map(a.directoryCache),changedFiles:new Map(a.changedFiles)}),Yi(f,a.rightTab),kn(f,a.selectedFilePath),a.explorerRoot?d[f]=a.explorerRoot:delete d[f]))}return i!==void 0&&nt(Vc,c),a&&Oo(d),zi(l,12,new Set(n.contextKey?[n.contextKey]:[])),{projectStateCache:l,explorerRootCache:d}}),setExplorerRoot:e=>t(r=>{if(r.explorerRoot===e)return r;const n={...r.explorerRootCache};return r.contextKey&&e&&(n[r.contextKey]=e,Oo(n)),{explorerRoot:e,explorerRootCache:n}}),resetExplorerToProject:()=>t(e=>{if(e.explorerRoot===e.rootPath)return e;const r={...e.explorerRootCache};return e.contextKey&&e.rootPath&&(r[e.contextKey]=e.rootPath,Oo(r)),{explorerRoot:e.rootPath,explorerRootCache:r}}),pinExplorerRoot:(e,r="directory")=>t(n=>{if(!n.rootPath||!e)return n;const o=n.rootPath,s=n.pinnedExplorerRootsCache[n.rootPath]??[];if(s.some(a=>a.path===e))return n;const i={...n.pinnedExplorerRootsCache,[n.rootPath]:[{path:e,kind:r},...s].slice(0,12)};return bu(i),(async()=>{try{await Ie.getState().hydratePinnedExplorerRoots();const a=await $t({pinnedExplorerRoot:{rootPath:o,path:e,kind:r,pinned:!0},pinnedExplorerRootsOrigin:Ji});Ie.getState().syncPinnedExplorerRoots(a.pinnedExplorerRoots??{})}catch{}})(),{pinnedExplorerRootsCache:i}}),unpinExplorerRoot:e=>t(r=>{if(!r.rootPath||!e)return r;const n=r.rootPath,o=r.pinnedExplorerRootsCache[r.rootPath]??[],s=o.find(c=>c.path===e);if(!o.some(c=>c.path===e))return r;const i=o.filter(c=>c.path!==e),a={...r.pinnedExplorerRootsCache};return i.length>0?a[r.rootPath]=i:delete a[r.rootPath],bu(a),(async()=>{try{await Ie.getState().hydratePinnedExplorerRoots();const c=await $t({pinnedExplorerRoot:{rootPath:n,path:e,kind:s?.kind??"directory",pinned:!1},pinnedExplorerRootsOrigin:Ji});Ie.getState().syncPinnedExplorerRoots(c.pinnedExplorerRoots??{})}catch{}})(),{pinnedExplorerRootsCache:a}}),hydratePinnedExplorerRoots:async()=>{if(!Ie.getState().pinnedExplorerRootsHydrated)return Rn||(Rn=(async()=>{const e=Ie.getState().pinnedExplorerRootsCache;let n=(await Hn()).pinnedExplorerRoots??{};Object.keys(n).length===0&&Object.keys(e).length>0&&(n=(await $t({pinnedExplorerRoots:e,pinnedExplorerRootsOrigin:Ji})).pinnedExplorerRoots??e),Ie.getState().syncPinnedExplorerRoots(n)})().finally(()=>{Rn=null}),Rn)},syncPinnedExplorerRoots:e=>t(()=>{const r={};for(const[n,o]of Object.entries(e)){const s=$p(o);s.length>0&&(r[n]=s.slice(0,12))}return An(zc),{pinnedExplorerRootsCache:r,pinnedExplorerRootsHydrated:!0}}),toggleExpanded:e=>t(r=>{const n=new Set(r.expandedPaths);return n.has(e)?n.delete(e):n.add(e),{expandedPaths:n}}),selectFile:e=>t(r=>(kn(r.contextKey,e),{selectedFilePath:e})),toggleShowHiddenFiles:()=>t(e=>{const r=!e.showHiddenFiles;nt(Bp,r);const n=new Map(e.projectStateCache);for(const[o,s]of n)n.set(o,{...s,directoryCache:new Map});return{showHiddenFiles:r,directoryCache:new Map,projectStateCache:n}}),toggleGroupByFolder:()=>t(e=>{const r=!e.groupByFolder;return wu(r),{groupByFolder:r}}),setGroupByFolder:e=>t(r=>r.groupByFolder===e?r:(wu(e),{groupByFolder:e})),toggleGroupCollapsed:e=>t(r=>{const n=new Set(r.collapsedGroups);return n.has(e)?n.delete(e):n.add(e),MA(n),{collapsedGroups:n}}),setDirectoryCache:(e,r)=>t(n=>{const o=new Map(n.directoryCache);return o.delete(e),o.set(e,r),zi(o,128,new Set([...n.expandedPaths,e,n.explorerRoot??n.rootPath??""])),{directoryCache:o}}),reconcileDirectoryCache:(e,r)=>t(n=>{const o=n.directoryCache.get(e);if(!o)return n;const s=new Map(o.map(d=>[d.path,d])),i=new Set(r.map(d=>d.path)),a=new Map(n.directoryCache),c=r.map(d=>{const u=s.get(d.path);return{name:d.name,path:d.path,type:d.type,isSymlink:d.isSymlink,modified:d.modified,expanded:u?.expanded??!1,loaded:u?.loaded??!1,children:d.type==="directory"?u?.children??[]:void 0}});a.set(e,vu(c,n.fileSortModes[e]??"name"));for(const d of o)if(!i.has(d.path))for(const u of a.keys())Tr(d.path,u)&&a.delete(u);let l=n.selectedFilePath;return l&&o.find(u=>!i.has(u.path)&&Tr(u.path,l))&&(l=null,kn(n.rootPath,null)),{directoryCache:a,selectedFilePath:l}}),hydrateFileSortModes:async()=>{if(!Ie.getState().fileSortModesHydrated)return In||(In=(async()=>{const e=Ie.getState().fileSortModes;let n=(await Hn()).fileSortModes??{};Object.keys(n).length===0&&Object.keys(e).length>0&&(n=(await $t({fileSortModes:e})).fileSortModes??e),An(Ha),t({fileSortModes:n,fileSortModesHydrated:!0,directoryCache:new Map})})().finally(()=>{In=null}),In)},setDirectorySortMode:async(e,r)=>{try{await Ie.getState().hydrateFileSortModes()}catch{}const n=Ie.getState().fileSortModes[e]??"name",o=(Zi.get(e)??0)+1;Zi.set(e,o),t(s=>{const i={...s.fileSortModes};r==="modified"?i[e]=r:delete i[e];const a=new Map(s.directoryCache);return a.delete(e),{fileSortModes:i,fileSortModesHydrated:!0,directoryCache:a}});try{await $t({fileSortMode:{path:e,mode:r}}),An(Ha)}catch{if(Zi.get(e)!==o)return;t(s=>{const i={...s.fileSortModes};n==="modified"?i[e]=n:delete i[e];const a=new Map(s.directoryCache);return a.delete(e),{fileSortModes:i,directoryCache:a}})}},hydrateNestedGitScanRoots:async()=>{if(!Ie.getState().nestedGitScanRootsHydrated)return Cn||(Cn=(async()=>{const r=(await Hn()).nestedGitScanRoots??{};An(qa),t({nestedGitScanRoots:r,nestedGitScanRootsHydrated:!0})})().finally(()=>{Cn=null}),Cn)},setNestedGitScanRoot:async(e,r)=>{try{await Ie.getState().hydrateNestedGitScanRoots()}catch{}const n=!!Ie.getState().nestedGitScanRoots[e],o=(Fo.get(e)??0)+1;Fo.set(e,o),t(s=>{const i={...s.nestedGitScanRoots};return r?i[e]=!0:delete i[e],{nestedGitScanRoots:i,nestedGitScanRootsHydrated:!0}});try{const s=await $t({nestedGitScanRoot:{rootPath:e,enabled:r}});if(Fo.get(e)!==o)return;t({nestedGitScanRoots:s.nestedGitScanRoots??{}}),An(qa)}catch{if(Fo.get(e)!==o)return;t(s=>{const i={...s.nestedGitScanRoots};return n?i[e]=!0:delete i[e],{nestedGitScanRoots:i}})}},invalidateDirectoryCache:(e,r=!1)=>t(n=>{const o=new Map(n.directoryCache);for(const s of o.keys())(s===e||r&&Tr(e,s))&&o.delete(s);return{directoryCache:o}}),applyFileWatchEvents:e=>t(r=>{if(e.length===0)return r;const n=new Map(r.directoryCache),o=new Map(r.fileChangeVersions);let s=r.selectedFilePath,i=!1,a=!1,c=!1;const l=d=>{o.set(d,(o.get(d)??0)+1),a=!0};for(const d of e){if(d.type==="rescan-required"){c=!0,s&&Tr(d.path,s)&&l(s);continue}const u=QA(d.path),f=n.get(u);if(d.type==="deleted"){if(l(d.path),s&&Tr(d.path,s)&&(s=null,kn(r.rootPath,null)),f){const y=f.filter(w=>w.path!==d.path);y.length!==f.length&&(n.set(u,y),i=!0)}for(const y of n.keys())Tr(d.path,y)&&(n.delete(y),i=!0);continue}l(d.path);const h=ek(d);if(!h||!f)continue;const g=f.find(y=>y.path===h.path),m=vu(g?f.map(y=>y.path===h.path?{...y,...h,children:y.children}:y):[...f,h],r.fileSortModes[u]??"name");n.set(u,m),i=!0}return!i&&!a&&!c?r:{directoryCache:i?n:r.directoryCache,selectedFilePath:s,fileChangeVersions:a?o:r.fileChangeVersions,fileWatchEpoch:c?r.fileWatchEpoch+1:r.fileWatchEpoch}}),bumpFileWatchEpoch:()=>t(e=>({fileWatchEpoch:e.fileWatchEpoch+1})),setChangedFiles:e=>t({changedFiles:e}),beginGitBundleLoading:e=>t({gitBundleLoading:!0,gitBundleSlow:!1,gitBundleLoadingOwner:e}),setGitBundleSlowFor:(e,r)=>t(n=>n.gitBundleLoadingOwner===e?{gitBundleSlow:r}:n),finishGitBundleLoading:e=>t(r=>r.gitBundleLoadingOwner===e?{gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null}:r),resetGitBundleLoading:()=>t({gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null}),setGitBundleError:e=>t({gitBundleError:e}),markGitBundleLoaded:(e=null)=>t({gitBundleLastLoadedAt:Date.now(),gitBundleCacheInfo:e})})),Qi=(()=>{if(location.hash.startsWith("#termdock-invite="))try{return bs(location.href)}catch{return}finally{history.replaceState(null,"",location.pathname+location.search)}})(),Wa="termdock-secure-open-session";let ea,Tn;function tk(){try{const t=JSON.parse(sessionStorage.getItem(Wa)??"null");return t?.serviceId===ne()?.targetPeerId?t.sessionId:void 0}catch{return}}function rk({children:t}){const[e,r]=F.useState(Qi),[n,o]=F.useState(!1),[s,i]=F.useState(!!Qi),[a,c]=F.useState(!Qi),[l,d]=F.useState(!1),[u,f]=F.useState("正在连接服务…"),[h,g]=F.useState([]),[m,y]=F.useState([]),[w,I]=F.useState(!1),[v,A]=F.useState(!1),[B,T]=F.useState(""),[N,k]=F.useState(!1),[x,S]=F.useState(""),[R,P]=F.useState(ne()?.serviceName??location.hostname),[b,E]=F.useState(tk);F.useEffect(()=>{Ge().then(_=>T(_.peerId)).catch(()=>d(!0))},[]),F.useEffect(()=>{const _=O=>{const{origin:q,sessionId:H}=O.detail;try{const z=JSON.parse(localStorage.getItem("termdock.federation.connections.v1")??"[]").find(W=>lo(W).some(X=>new URL(X).origin===new URL(q).origin));if(!z){i(!0);return}if(St()?.focusSession(z.targetPeerId,H))return;sessionStorage.setItem(Wa,JSON.stringify({serviceId:z.targetPeerId,sessionId:H})),et(z).then(()=>{E(H),o(!0)}).catch(()=>{d(!0),i(!0)})}catch{i(!0)}};return window.addEventListener("termdock:open-remote-session",_),()=>window.removeEventListener("termdock:open-remote-session",_)},[]);const C=async(_=5e3)=>{const O=await lt(),q=await on(O,{timeoutMs:_}),H=$x(),K=Dx()?.targetPeerId;Promise.all([OS(),We()]).then(([W,X])=>{const G=X.find(se=>se.targetPeerId===K),Y=H==="relay"?`经 ${G?.label||K?.slice(-12)||"入口服务"} 中转`:"直连";return O.request({type:"device-name",name:op(),onlyIfMissing:!0,profile:{...W,route:Y}})}).catch(()=>{}),I(q.fullService),A(q.canManage),o(!0),c(!1),d(!1);const z=ne();Nn({phase:"ready",...z?{service:{...z,id:z.targetPeerId,label:z.serviceName||location.host}}:{}}),mi()&&Ux()};F.useEffect(()=>{let _=!1,O=!1,q=0,H;const K=async()=>{if(_||O||q&&(document.hidden||!mi()))return;if(!navigator.onLine){c(!0),d(!0),f("网络已断开,恢复后会自动连接"),Nn({phase:"offline"});return}O=!0,clearTimeout(H);const Ne=performance.now(),Fe=vn();try{if(zn&&!ne())throw new Error("工作区的服务记录已移除,请重新添加服务。");Tn??=window.termdockDesktop?.getServiceConnection?.();const oe=await Tn;if(oe?.invitation){r(bs(oe.invitation)),i(!0),c(!1);return}if(!ne()){if(e){c(!1);return}if(ea??=(async()=>{if(oe?.targetPeerId){await et({...oe,targetPeerId:oe.targetPeerId,serviceName:oe.label});return}const ot=await window.termdockDesktop?.getLocalInvite?.();ot?await et(ot):await Ox()})(),await ea,!ne()){_||(o(!1),c(!1),d(!1));return}}_||await C(Fe?.canSwitchTransport?2500:5e3),q=0,performance.measure("termdock:connection-ready",{start:Ne,end:performance.now()})}catch(oe){if(_)return;oe instanceof Ve?(o(!1),c(!1),i(!1),d(!1),Nn({phase:"login"})):(Fe&&vn()===Fe&&Vh(),d(!0),c(!0),ea=void 0,f("连接暂未恢复,正在重试…"),Nn({phase:"reconnecting"}),q++,H=setTimeout(()=>{K()},Math.min(5e3,300*2**Math.min(q-1,5))),console.debug("[connection] retry",{elapsedMs:Math.round(performance.now()-Ne),attempt:q,reason:oe instanceof Error?oe.message:"unknown"}))}finally{O=!1}},z=()=>{document.visibilityState==="visible"&&mi()&&K()},W=z,X=()=>{q=0,z()},G=()=>{Ie.getState().openLeft(),z()};window.addEventListener(Ia,z),window.addEventListener(Ca,G),zn&&Ie.getState().openLeft(),St()?.attach(Rc(),window),K(),document.addEventListener("visibilitychange",W),window.addEventListener("focus",z),window.addEventListener("online",X);const Y=navigator.connection;Y?.addEventListener("change",X),window.addEventListener("auth:unauthorized",z),window.addEventListener(lr,z);const se=setInterval(z,3e4);return()=>{_=!0,clearTimeout(H),clearInterval(se),window.removeEventListener(Ia,z),window.removeEventListener(Ca,G),document.removeEventListener("visibilitychange",W),window.removeEventListener("focus",z),window.removeEventListener("online",X),Y?.removeEventListener("change",X),window.removeEventListener("auth:unauthorized",z),window.removeEventListener(lr,z)}},[]);const L=async()=>{const _=vn();if(_){k(!0),S("");try{const O=await _.request({type:"session-list"});y(O.items)}catch{S("暂时无法读取终端列表,请重试。")}try{if(v){const O=await _.request({type:"grants-list"}),q=O.subjectLabels??{},H=await _.request({type:"route-access"}),K=await We(),z=(Array.isArray(H.grants)?H.grants:[]).map(W=>({id:`route:${W.id}`,subjectId:W.subjectId,scope:{kind:"service"},actions:["route.use"],routeTargetServiceId:W.targetServiceId,routeTargetName:K.find(X=>X.targetPeerId===W.targetServiceId)?.label||"指定服务",...W.active?{}:{revokedAt:W.revokedAt??0}}));g([...O.grants,...z].map(W=>({...W,label:q[W.subjectId],deviceProfile:O.deviceProfiles?.[W.subjectId]})))}else{const O=await _.request({type:"permissions"});g(O.grants??[])}}catch{S("暂时无法读取设备权限,请重试。")}finally{k(!1)}}};F.useEffect(()=>{const _=()=>{i(!0),n&&L()};return window.addEventListener(Na,_),()=>window.removeEventListener(Na,_)},[n,v]);const M=async _=>{if(!_.pairingCode&&!_.routeCode&&ne()?.targetPeerId!==_.targetPeerId&&St()){const O={..._,id:_.targetPeerId,label:_.serviceName||new URL(_.serviceOrigin||_.url).host};if(await Et(O),ys(O)){i(!1);return}}await et(_),Tn&&(Tn=Tn.then(O=>O?{...O,invitation:void 0}:null)),r(void 0),E(void 0),sessionStorage.removeItem(Wa),P(_.serviceName??new URL(_.url).hostname),await C(),i(!1),d(!1)},$=async _=>{const O=window.termdockDesktop;if(O?.openServiceConnection){const q=await O.openServiceConnection(_);if(!q.ok)throw new Error(q.error||"暂时无法打开这台服务。");i(!1);return}if(ys(_)){i(!1);return}if(_.targetPeerId)try{await M({..._,targetPeerId:_.targetPeerId,serviceName:_.label});return}catch(q){if(!(q instanceof Ve))throw q}return vd(_.serviceOrigin||_.url)};F.useEffect(()=>{const _=O=>{$(O.detail).catch(q=>{i(!0),S(q instanceof Error?q.message:"暂时无法打开服务")})};return window.addEventListener($a,_),()=>window.removeEventListener($a,_)});const j=async(_,O)=>{if(_.includes("#termdock-invite=")){const H=bs(_);if(window.termdockDesktop?.openServiceConnection){const K=await window.termdockDesktop.openServiceConnection({id:H.targetPeerId,url:H.url,label:H.serviceName||new URL(H.serviceOrigin||H.url).host,targetPeerId:H.targetPeerId,serviceOrigin:H.serviceOrigin,entryServiceId:H.entryServiceId},_);if(!K.ok)throw new Error(K.error||"暂时无法打开邀请。");i(!1);return}if(O!==void 0&&H.routeOnly){await xd(H,O),await C(),i(!1);return}try{await M(H)}catch(K){if(H.routeOnly&&K instanceof Ve)return{passwordRequired:!0};throw K}return}const q=Be(_);return window.termdockDesktop?.openServiceConnection?$({id:q,url:q,label:new URL(q).host}):vd(q,O)},D=async _=>{const O=await lt(),{includeBackup:q=!0,...H}=_,K=ne(),z=K?dr(K):[];let W;if(q&&z.length){for(const Y of z)try{const se=await Xh({...K,targetPeerId:O.targetPeerId},Y);W={...Y,routeCode:se.routeCode};break}catch{}if(!W)throw new Error("无法分享备用连接:需要入口管理员授权。也可以关闭此选项,生成直接连接邀请。")}let X=K?.serviceOrigin||location.origin;if(["localhost","127.0.0.1","[::1]"].includes(new URL(X).hostname)){const se=await(await O.fetch("/api/terminal/settings")).json();typeof se.localAccess?.url=="string"&&(X=se.localAccess.url)}const G=await O.request({type:"invite-create",...H});if(typeof G.code!="string"||typeof G.expiresAt!="number")throw new Error("暂时无法生成邀请。");return{url:sp({v:1,serviceId:O.targetPeerId,code:G.code,entryUrl:W?.url||X,serviceUrl:X,name:R,entryServiceId:W?.targetPeerId,routeCode:W?.routeCode}),expiresAt:G.expiresAt}};return p.jsxs(p.Fragment,{children:[n?w&&!b?t:p.jsx(yE,{client:vn(),initialSessionId:b}):a?p.jsx("div",{className:"flex h-full min-h-0 flex-col items-center justify-center bg-[var(--chrome-bg)] px-6 text-foreground",children:p.jsxs("div",{className:"flex w-full max-w-xs flex-col items-center text-center",children:[p.jsx("div",{className:"mb-5 flex h-12 w-12 items-center justify-center rounded-2xl bg-surface-2 text-muted-foreground","aria-hidden":"true",children:p.jsx(CS,{size:24,strokeWidth:1.5})}),p.jsx("h1",{className:"max-w-full truncate text-base font-medium tracking-tight",title:R,children:R}),p.jsxs("div",{role:"status",className:"mt-2 flex max-w-full items-center justify-center gap-2 text-xs leading-5 text-muted-foreground",children:[!l&&p.jsx(He,{size:13,className:"shrink-0 animate-spin motion-reduce:animate-none","aria-hidden":"true"}),p.jsx("span",{children:u})]}),l&&p.jsx("p",{className:"mt-2 text-xs leading-5 text-muted-foreground",children:"登录信息已保留"}),p.jsx("button",{type:"button",className:"mt-6 min-h-11 rounded-lg px-4 text-xs text-muted-foreground transition-colors hover:bg-surface-2 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>i(!0),children:"管理服务"})]})}):p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"fixed left-0 right-0 top-[var(--safe-top-inset)] z-chrome sm:right-auto sm:w-72",children:p.jsx(lA,{})}),p.jsx(sA,{onLoginSuccess:()=>{C().catch(()=>d(!0))}})]}),s&&p.jsx(hE,{onConnect:M,onClose:()=>i(!1),onAddService:j,onOpenService:$,onConnectWithPassword:async(_,O)=>{await xd(_,O),await C(),i(!1)},paired:n||!!ne(),initialInvite:e,currentServiceName:R,currentServiceId:vn()?.targetPeerId||ne()?.targetPeerId,currentServiceOrigin:ne()?.serviceOrigin,currentIdentity:B,grants:h,sessions:m,loading:N,loadError:x,onRetry:()=>{L()},onRename:async(_,O)=>{await(await lt()).request({type:"device-name",subjectId:_,name:O}),await L()},hasBackup:!!ne()&&dr(ne()).length>0,onCreateInvite:v?D:void 0,onRevoke:v?async _=>{await(await lt()).request(_.startsWith("route:")?{type:"route-revoke",grantId:_.slice(6)}:{type:"revoke",grantId:_}),await L()}:void 0})]})}function nk(t,e,r){const n=t?.name||"Error",o=t?.message||"Unexpected error";return["Termdock error report",`Time: ${r.capturedAt}`,`URL: ${r.url}`,`User agent: ${r.userAgent}`,"",`${n}: ${o}`,t?.stack?`
|
|
30
30
|
Stack:
|
|
31
31
|
${t.stack}`:"",e?`
|
|
32
32
|
React component stack:
|
|
33
33
|
${e.trim()}`:""].filter(Boolean).join(`
|
|
34
|
-
`)}async function QA(t){try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(t),!0}catch{}const e=document.createElement("textarea");e.value=t,e.setAttribute("readonly",""),e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select();try{return document.execCommand("copy")}catch{return!1}finally{e.remove()}}function ek({error:t,componentStack:e}){const{t:r}=$c(),[n,o]=Ue.useState("idle"),s=async()=>{const i=JA(t,e,{url:window.location.href,userAgent:navigator.userAgent,capturedAt:new Date().toISOString()});o(await QA(i)?"copied":"failed")};return p.jsx("div",{className:"flex h-full items-center justify-center p-4",children:p.jsxs("div",{className:"flex flex-col items-center gap-3 text-center max-w-md",children:[p.jsx("div",{className:"w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center",children:p.jsx("svg",{className:"w-6 h-6 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:p.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),p.jsxs("div",{className:"space-y-1",children:[p.jsx("h3",{className:"font-medium text-foreground",children:r("errorBoundary.title")}),p.jsx("p",{className:"text-sm text-muted-foreground",children:t?.message||r("errorBoundary.unexpected")})]}),p.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-center gap-2",children:[p.jsx("button",{type:"button",onClick:()=>{s()},className:"rounded-full bg-surface-2 px-5 py-2.5 text-sm font-medium text-foreground ring-1 ring-border/15 transition hover:bg-surface-elevated active:scale-[0.97]",children:r(n==="copied"?"errorBoundary.copied":n==="failed"?"errorBoundary.copyFailed":"errorBoundary.copyDetails")}),p.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"rounded-full bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground shadow-sm transition-all hover:bg-primary/90 active:scale-[0.97]",children:r("errorBoundary.retry")})]})]})})}class tk extends Ue.Component{state={hasError:!1,error:null,componentStack:""};static getDerivedStateFromError(e){return{hasError:!0,error:e,componentStack:""}}componentDidCatch(e,r){console.error("Terminal error caught by boundary:",e,r),this.setState({componentStack:r.componentStack??""})}render(){return this.state.hasError?this.props.fallback?this.props.fallback:p.jsx(ek,{error:this.state.error,componentStack:this.state.componentStack}):this.props.children}}function me(){try{if(window.parent!==window&&location.pathname==="/workspace.html"&&window.parent.location.origin===location.origin&&window.parent.__termdockWorkspaceHost)return window.parent}catch{}return window}const rk="debug",nk="termdock:debug";function yu(t){return t?new Set(t.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean)):new Set}function ok(){if(typeof window>"u")return new Set;const t=yu(new URLSearchParams(window.location.search).get(rk));let e=new Set;try{e=yu(window.localStorage.getItem(nk))}catch{e=new Set}const r=new Set([...t,...e]);return r.has("1")||r.has("true")||r.has("*")||r.has("all")?new Set(["*"]):r}function sk(t){const e=ok();return e.has("*")||e.has(t)}function ik(t){const e=sk(t);return(...r)=>{e&&console.log(`[debug:${t}]`,...r)}}const bu=80,ak=60,ck="termdock:viewport-keyboard-change",lk="termdock:viewport-layout-change",vt=240,vu=640,xu=360;function dk({measuredHeight:t,documentVisible:e,editableFocused:r}){return e&&r&&t>0}function Su(){if(typeof document>"u")return!1;const t=document.activeElement;return t instanceof HTMLElement&&t.matches('input:not([type="hidden"]), textarea, select, [contenteditable]:not([contenteditable="false"])')}const bs=t=>{const e=typeof t=="number"?t:Number.parseFloat(typeof t=="string"?t:"0");return Number.isFinite(e)&&e>0?Math.round(e):0},Up=(t,e)=>{const r=t.map(bs).filter(n=>n>0);return r.find(n=>n>=vt)??r[0]??e},$n=()=>typeof window>"u"?vu:Up([me().innerHeight,document.documentElement?.clientHeight,document.body?.clientHeight,me().visualViewport?.height,window.screen?.availHeight,window.screen?.height],vu),$p=()=>typeof window>"u"?xu:Up([me().innerWidth,document.documentElement?.clientWidth,document.body?.clientWidth,me().visualViewport?.width,window.screen?.availWidth,window.screen?.width],xu),Ft=t=>{const e=Number.parseFloat(t||"0");return Number.isFinite(e)?Math.max(0,Math.round(e)):0},uk=()=>typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,fk=()=>typeof window>"u"?!1:me().navigator.standalone===!0||me().matchMedia?.("(display-mode: standalone)").matches===!0,Hp=()=>{if(typeof window>"u"||!uk()||!fk())return{top:0,right:0,bottom:0,left:0};if(!($n()>=$p()))return{top:0,right:0,bottom:0,left:0};const e=window.screen?.width||window.innerWidth,r=window.screen?.height||window.innerHeight,n=Math.min(e,r),o=Math.max(e,r);return n>=700?{top:20,right:0,bottom:20,left:0}:o<780?{top:20,right:0,bottom:0,left:0}:{top:o>=852?59:o>=844?47:44,right:0,bottom:34,left:0}};function hk(t="--app-vh"){if(typeof window>"u"||typeof document>"u")return;const e=bs(me().visualViewport?.height),r=Math.max(0,Math.round(me().visualViewport?.offsetTop??0)),n=$n(),s=e>=vt?Math.min(n,e+r):n,i=Math.max(n,s),a=document.documentElement.style;a.setProperty(t,`${Math.max(s,vt)}px`),a.setProperty("--app-base-vh",`${Math.max(i,vt)}px`),a.setProperty("--app-visible-vh",`${Math.max(s,vt)}px`),a.setProperty("--app-vv-offset-top",`${r}px`),a.setProperty("--kb-translate-y","0px"),a.setProperty("--kb-margin-top","0px"),a.setProperty("--kb-height","0px");const c=Hp();c.top>0&&a.setProperty("--safe-top-inset",`${c.top}px`),c.right>0&&a.setProperty("--safe-right-inset",`${c.right}px`),c.bottom>0&&a.setProperty("--safe-bottom-inset",`${c.bottom}px`),c.left>0&&a.setProperty("--safe-left-inset",`${c.left}px`)}function Yk(t={}){const{cssVarName:e="--app-vh"}=t,r=Ue.useMemo(()=>ik("viewport"),[]),n=Ue.useCallback(()=>{if(typeof window>"u")return 0;const d=me().visualViewport,u=$n();if(!d)return u;const f=bs(d.height);if(f<vt&&u>=vt)return u;const h=d.offsetTop,m=f<u-1&&h>0&&h<=96?f+h:f,y=Math.max(0,Math.min(u,m));return y>0?Math.round(y):u},[]),[o,s]=Ue.useState(n),i=Ue.useRef(0),a=Ue.useRef(0),c=Ue.useRef(0),l=Ue.useRef(!1);return Ue.useEffect(()=>{if(typeof window>"u")return;let d=null,u=null;const f=()=>{if(u?.isConnected)return u;try{return u=document.createElement("div"),u.setAttribute("aria-hidden","true"),u.style.cssText=["position:fixed","top:0","left:0","width:0","height:0","visibility:hidden","pointer-events:none","padding-top:constant(safe-area-inset-top)","padding-top:env(safe-area-inset-top,0px)","padding-right:constant(safe-area-inset-right)","padding-right:env(safe-area-inset-right,0px)","padding-bottom:constant(safe-area-inset-bottom)","padding-bottom:env(safe-area-inset-bottom,0px)","padding-left:constant(safe-area-inset-left)","padding-left:env(safe-area-inset-left,0px)"].join(";"),(document.body||document.documentElement).appendChild(u),u}catch{}return null},h=()=>{let P={top:0,right:0,bottom:0,left:0};try{const L=f();if(L){const M=getComputedStyle(L);P={top:Ft(M.paddingTop),right:Ft(M.paddingRight),bottom:Ft(M.paddingBottom),left:Ft(M.paddingLeft)}}}catch{}const b=me();if(b!==window){const L=b.getComputedStyle(b.document.documentElement);P={top:Math.max(P.top,Ft(L.getPropertyValue("--safe-top-inset"))),right:Math.max(P.right,Ft(L.getPropertyValue("--safe-right-inset"))),bottom:Math.max(P.bottom,Ft(L.getPropertyValue("--safe-bottom-inset"))),left:Math.max(P.left,Ft(L.getPropertyValue("--safe-left-inset")))}}const E=Hp(),C={top:Math.max(P.top,E.top),right:Math.max(P.right,E.right),bottom:Math.max(P.bottom,E.bottom),left:Math.max(P.left,E.left)};return document.documentElement.style.setProperty("--safe-top-inset",`${C.top}px`),document.documentElement.style.setProperty("--safe-right-inset",`${C.right}px`),document.documentElement.style.setProperty("--safe-bottom-inset",`${C.bottom}px`),document.documentElement.style.setProperty("--safe-left-inset",`${C.left}px`),C},g=(P,b,E,C)=>{const L=Math.max(b,E);if(i.current===0){i.current=L,a.current=P,document.documentElement.style.setProperty("--app-base-vh",`${L}px`);return}const M=Math.abs(P-a.current),$=C<=bu;(M>ak||$)&&(i.current=L,a.current=P,document.documentElement.style.setProperty("--app-base-vh",`${L}px`))},m=(P="event")=>{d=null;const b=n(),E=Math.round(me().visualViewport?.offsetTop??0),C=bs(me().visualViewport?.height),L=C>=vt?C:b,M=$n(),$=$p(),j=Math.max(0,L+E),D=h(),_=D.bottom,O=Math.max(0,i.current-j-_);g($,M,j,O),s(Rt=>Rt===b?Rt:b);const q=Number.parseInt(document.documentElement.style.getPropertyValue(e)||"0",10);document.documentElement.style.setProperty(e,`${b}px`),document.documentElement.style.setProperty("--app-vv-offset-top",`${E}px`);const H=i.current,K=Math.min(b,L),z=Math.max(0,Math.min(H,j)),W=Math.max(0,Math.round(H-z-_)),X=Su(),G=dk({measuredHeight:W,documentVisible:document.visibilityState==="visible",editableFocused:X}),Y=G?W:0,se=Y>=bu,Pe=-Y,Oe=Y;document.documentElement.style.setProperty("--kb-translate-y",`${Pe}px`),document.documentElement.style.setProperty("--kb-margin-top",`${Oe}px`),document.documentElement.style.setProperty("--kb-height",`${Y}px`),document.documentElement.style.setProperty("--app-visible-vh",`${z}px`);const oe=Math.abs(Y-c.current)>1,ot=se!==l.current;(oe||ot)&&(c.current=Y,l.current=se,document.dispatchEvent(new CustomEvent(ck,{detail:{baseHeight:H,visibleHeight:z,visualViewportHeight:L,offsetTop:E,keyboardHeight:Y,isOpen:se,source:P}}))),(q!==b||E>0||oe||ot)&&r("sync",{cssVarName:e,innerHeight:M,baseHeight:H,rawViewportHeight:L,offsetTop:E,visibleHeight:z,rawHeight:b,appliedHeight:b,keyboardViewportHeight:K,measuredKeyboardHeight:W,editableFocused:X,applyKeyboardInset:G,keyboardHeight:Y,isKeyboardOpen:se,safeAreaInsets:D,source:P}),document.dispatchEvent(new CustomEvent(lk,{detail:{height:b,baseHeight:H,visibleHeight:z,offsetTop:E,source:P}}))},y=(P="event")=>{(P.includes("visibilitychange")||P.includes("pageshow"))&&r("schedule",{source:P}),d===null&&(d=window.requestAnimationFrame(()=>m(P)))};y("mount");const w=()=>y("resize"),I=()=>y("orientationchange"),v=()=>y("visualViewport.resize"),A=()=>y("visualViewport.scroll"),B=()=>y("focusin"),T=()=>y("focusout"),N=P=>{const b=document.activeElement;b instanceof HTMLElement&&Su()&&b.blur(),c.current=0,l.current=!1;const E=Math.max(i.current,$n(),vt),C=document.documentElement.style;C.setProperty(e,`${E}px`),C.setProperty("--app-visible-vh",`${E}px`),C.setProperty("--app-vv-offset-top","0px"),C.setProperty("--kb-translate-y","0px"),C.setProperty("--kb-margin-top","0px"),C.setProperty("--kb-height","0px"),s(L=>L===E?L:E),r("keyboard session reset",{source:P,baseHeight:E})};window.addEventListener("resize",w),window.addEventListener("orientationchange",I),me().visualViewport?.addEventListener("resize",v),me().visualViewport?.addEventListener("scroll",A),document.addEventListener("focusin",B),document.addEventListener("focusout",T);const k=P=>{r("resume",{source:P,innerHeight:Math.round(window.innerHeight),visualViewport:me().visualViewport?{width:Math.round(me().visualViewport.width),height:Math.round(me().visualViewport.height),offsetTop:Math.round(me().visualViewport.offsetTop)}:null,hidden:document.hidden}),y(P)},x=()=>{document.hidden?N("visibilitychange:hidden"):k("visibilitychange")},S=()=>k("pageshow"),R=()=>N("pagehide");return document.addEventListener("visibilitychange",x),window.addEventListener("pageshow",S),window.addEventListener("pagehide",R),()=>{window.removeEventListener("resize",w),window.removeEventListener("orientationchange",I),me().visualViewport?.removeEventListener("resize",v),me().visualViewport?.removeEventListener("scroll",A),document.removeEventListener("focusin",B),document.removeEventListener("focusout",T),document.removeEventListener("visibilitychange",x),window.removeEventListener("pageshow",S),window.removeEventListener("pagehide",R),d!==null&&window.cancelAnimationFrame(d),u?.remove()}},[e,r,n]),o}const Eu=5*6e4;let za,qp=!1,Kp=!1,Au=!1;const Va=new Set;function ku(){qp=!0,Va.forEach(t=>t())}function pk(){return F.useSyncExternalStore(t=>(Va.add(t),()=>{Va.delete(t)}),()=>qp,()=>!1)}function gk(){window.dispatchEvent(new Event("termdock:before-update")),Kp=!0,za?.waiting?za.waiting.postMessage({type:"SKIP_WAITING"}):window.location.reload()}function mk(t,e){let r=t;return()=>{if(!r){r=!0;return}e()}}function wk(){if(Au||typeof window>"u"||!("serviceWorker"in navigator))return;Au=!0,navigator.serviceWorker.addEventListener("controllerchange",mk(!!navigator.serviceWorker.controller,()=>{Kp?window.location.reload():ku()}));const t=()=>{navigator.serviceWorker.register("/sw.js",{scope:"/",updateViaCache:"none"}).then(e=>{za=e;const r=()=>{e.waiting&&ku()},n=()=>{const i=e.installing;i?.addEventListener("statechange",()=>{i.state==="installed"&&navigator.serviceWorker.controller&&r()})};e.addEventListener("updatefound",n),n(),r();let o=0;const s=()=>{document.visibilityState!=="visible"||Date.now()-o<Eu||(o=Date.now(),e.update().then(r).catch(()=>{}))};s(),window.setInterval(s,Eu),document.addEventListener("visibilitychange",s)}).catch(()=>{})};document.readyState==="complete"?t():window.addEventListener("load",t,{once:!0})}function yk(){const t=pk(),[e,r]=F.useState(!1),{locale:n}=$c();if(!t||e)return null;const o=n==="zh";return p.jsxs("div",{role:"status",className:"fixed bottom-16 left-1/2 z-toast flex max-w-[calc(100%-2rem)] -translate-x-1/2 items-center gap-3 rounded-lg border border-border bg-background px-4 py-3 text-sm text-foreground shadow-lg",children:[p.jsx("span",{children:o?"新版本已就绪":"An update is ready"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-primary",onClick:gk,children:o?"重新加载":"Reload"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-muted-foreground",onClick:()=>r(!0),children:o?"稍后":"Later"})]})}function zp(t){const e=document.querySelector('meta[name="theme-color"]');e&&e.setAttribute("content",t==="light"?"#FFFCF0":"#1C1B1A")}const bk={activeKey:"root",items:[]},vk=()=>()=>{},xk=()=>bk;function Sk({host:t,item:e,active:r}){const n=F.useRef(null);return F.useEffect(()=>{n.current?.toggleAttribute("inert",!r)},[r]),F.useEffect(()=>()=>t.attach(e.key,null),[t,e.key]),p.jsx("iframe",{ref:n,title:e.service?.label||"服务工作区",src:`/workspace.html?${Hh}=${encodeURIComponent(e.key)}`,className:"fixed inset-0 w-full border-0 bg-[var(--chrome-bg)]",style:{height:"var(--app-base-vh, 100%)",visibility:r?"visible":"hidden",pointerEvents:r?"auto":"none"},"aria-hidden":!r,tabIndex:r?0:-1,allow:"clipboard-read; clipboard-write; fullscreen",onLoad:o=>t.attach(e.key,o.currentTarget.contentWindow)})}function Ek({children:t}){const e=window.parent===window?St():void 0,r=F.useSyncExternalStore(e?.subscribe||vk,e?.snapshot||xk),n=F.useRef(null);return F.useEffect(()=>{n.current?.toggleAttribute("inert",r.activeKey!=="root")},[r.activeKey]),F.useEffect(()=>{if(!e)return;const o=()=>{try{const s=JSON.parse(localStorage.getItem("termdock-color-theme")||"null");(s==="dark"||s==="light")&&(document.documentElement.dataset.theme=s,zp(s))}catch{}};return window.addEventListener("storage",o),()=>window.removeEventListener("storage",o)},[e]),F.useEffect(()=>{if(!e||!("serviceWorker"in navigator))return;const o=a=>{if(a.source!==navigator.serviceWorker.controller)return;const c=a.data;c?.type==="termdock:focus-session"&&typeof c.targetPeerId=="string"&&typeof c.sessionId=="string"&&e.focusSession(c.targetPeerId,c.sessionId)&&(a.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),a.stopImmediatePropagation())},s=async()=>{if("caches"in window)try{const a=await caches.open("termdock-notification-target-v1"),c=await a.match("/__termdock-notification-target");if(!c)return;const l=await c.json();typeof l.targetPeerId=="string"&&typeof l.sessionId=="string"&&Date.now()-l.clickedAt<3e4&&e.focusSession(l.targetPeerId,l.sessionId)&&await a.delete("/__termdock-notification-target")}catch{}},i=()=>{document.hidden||s()};return navigator.serviceWorker.addEventListener("message",o),document.addEventListener("visibilitychange",i),s(),()=>{navigator.serviceWorker.removeEventListener("message",o),document.removeEventListener("visibilitychange",i)}},[e]),e?p.jsxs("div",{className:"relative h-full w-full overflow-hidden bg-[var(--chrome-bg)]",children:[p.jsx("div",{ref:n,className:"h-full w-full","aria-hidden":r.activeKey!=="root",style:{visibility:r.activeKey==="root"?"visible":"hidden"},children:t}),r.items.filter(o=>o.key!=="root").map(o=>p.jsx(Sk,{host:e,item:o,active:r.activeKey===o.key},o.key))]}):t}const Ak=F.lazy(()=>Kt(()=>import("./App-B2nTzqxn.js").then(t=>t.A),__vite__mapDeps([4,2,1,5,6,3,7,8]))),kk=F.lazy(()=>Kt(()=>import("./DagPlayground-BrvWN-BF.js"),__vite__mapDeps([9,10,2,1,11,8,3])).then(t=>({default:t.DagPlayground}))),Ik=F.lazy(()=>Kt(()=>import("./DiffLab-B_6noZdn.js"),__vite__mapDeps([12,2,1,13,7,14,3])).then(t=>({default:t.DiffLab}))),Ck=F.lazy(()=>Kt(()=>import("./DiffReviewLab-DgGq28V3.js"),__vite__mapDeps([15,2,1,16,5,6,11,13,7,14,3])).then(t=>({default:t.DiffReviewLab})));hk();Ux();window.parent===window&&wk();const Bn=ne();Bn&&Kt(()=>import("./App-B2nTzqxn.js").then(t=>t.A),__vite__mapDeps([4,2,1,5,6,3,7,8])).catch(()=>{});!new URLSearchParams(location.search).has("dag-playground")&&!new URLSearchParams(location.search).has("diff-lab")&&!new URLSearchParams(location.search).has("diff-review-lab")&&(Nx(Bn?{...Bn,id:Bn.targetPeerId,label:Bn.serviceName||location.host}:void 0),Wh());try{const t=JSON.parse(window.localStorage.getItem("termdock-color-theme")||"null");(t==="dark"||t==="light")&&(document.documentElement.dataset.theme=t,zp(t))}catch{}Yx.createRoot(document.getElementById("root")).render(p.jsx(Ue.StrictMode,{children:p.jsxs(eA,{children:[window.parent===window&&p.jsx(yk,{}),p.jsx(tk,{children:p.jsx(F.Suspense,{fallback:p.jsx("div",{className:"termdock-boot",role:"status",children:"Loading Termdock"}),children:(()=>{const t=new URLSearchParams(window.location.search);return t.get("dag-playground")==="1"?p.jsx(kk,{}):t.get("diff-review-lab")==="1"?p.jsx(Ck,{}):t.get("diff-lab")==="1"?p.jsx(Ik,{}):p.jsx(Ek,{children:p.jsx(ZA,{children:p.jsx(Ak,{})})})})()})})]})}));export{KE as $,Dc as A,aS as B,Cc as C,nr as D,dp as E,I2 as F,k2 as G,y1 as H,n1 as I,CE as J,zE as K,He as L,lp as M,io as N,dr as O,AA as P,jk as Q,vA as R,Os as S,AS as T,P1 as U,lk as V,Aa as W,IS as X,ik as Y,Te as Z,Kt as _,Yh as a,A1 as a$,ii as a0,D1 as a1,h2 as a2,u1 as a3,_1 as a4,f2 as a5,TS as a6,cp as a7,RE as a8,xA as a9,c1 as aA,b1 as aB,C2 as aC,xp as aD,St as aE,Su as aF,Yf as aG,mh as aH,d2 as aI,C1 as aJ,N1 as aK,vp as aL,Z1 as aM,Q1 as aN,V1 as aO,Y1 as aP,G1 as aQ,hi as aR,p as aS,Mk as aT,l1 as aU,L2 as aV,F1 as aW,j2 as aX,z2 as aY,r2 as aZ,a1 as a_,i1 as aa,lt as ab,I1 as ac,k1 as ad,T1 as ae,qE as af,A2 as ag,x2 as ah,v2 as ai,S2 as aj,S1 as ak,J1 as al,y2 as am,P2 as an,a2 as ao,R2 as ap,b2 as aq,g2 as ar,H1 as as,E2 as at,h1 as au,ms as av,ep as aw,kE as ax,hE as ay,x1 as az,sS as b,R1 as b$,$2 as b0,m2 as b1,pE as b2,p1 as b3,M1 as b4,WE as b5,Vt as b6,l2 as b7,i2 as b8,c2 as b9,T2 as bA,B2 as bB,U2 as bC,ne as bD,n2 as bE,W2 as bF,jx as bG,QE as bH,V2 as bI,e1 as bJ,YE as bK,VE as bL,JE as bM,r1 as bN,D2 as bO,q2 as bP,wp as bQ,HE as bR,ai as bS,Vk as bT,H2 as bU,F2 as bV,$k as bW,XE as bX,Ok as bY,zp as bZ,_k as b_,u2 as ba,Xk as bb,Hk as bc,GE as bd,TE as be,Uk as bf,Pa as bg,O2 as bh,j1 as bi,K2 as bj,w1 as bk,m1 as bl,q1 as bm,U1 as bn,v1 as bo,K1 as bp,$1 as bq,t1 as br,Gk as bs,o1 as bt,d1 as bu,O1 as bv,M2 as bw,Dk as bx,CS as by,_2 as bz,dS as c,B1 as c0,E1 as c1,g1 as c2,Gt as c3,p2 as c4,$c as c5,Kk as c6,Me as c7,Yk as c8,me as c9,o2 as ca,nt as cb,zk as cc,qk as cd,fr as d,Zh as e,pS as f,tk as g,bS as h,Jh as i,iA as j,pe as k,ZE as l,gc as m,It as n,N2 as o,Fk as p,e2 as q,X1 as r,mc as s,s2 as t,Cx as u,L1 as v,Qb as w,IE as x,s1 as y,Wk as z};
|
|
34
|
+
`)}async function ok(t){try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(t),!0}catch{}const e=document.createElement("textarea");e.value=t,e.setAttribute("readonly",""),e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select();try{return document.execCommand("copy")}catch{return!1}finally{e.remove()}}function sk({error:t,componentStack:e}){const{t:r}=Kc(),[n,o]=Ue.useState("idle"),s=async()=>{const i=nk(t,e,{url:window.location.href,userAgent:navigator.userAgent,capturedAt:new Date().toISOString()});o(await ok(i)?"copied":"failed")};return p.jsx("div",{className:"flex h-full items-center justify-center p-4",children:p.jsxs("div",{className:"flex flex-col items-center gap-3 text-center max-w-md",children:[p.jsx("div",{className:"w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center",children:p.jsx("svg",{className:"w-6 h-6 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:p.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),p.jsxs("div",{className:"space-y-1",children:[p.jsx("h3",{className:"font-medium text-foreground",children:r("errorBoundary.title")}),p.jsx("p",{className:"text-sm text-muted-foreground",children:t?.message||r("errorBoundary.unexpected")})]}),p.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-center gap-2",children:[p.jsx("button",{type:"button",onClick:()=>{s()},className:"rounded-full bg-surface-2 px-5 py-2.5 text-sm font-medium text-foreground ring-1 ring-border/15 transition hover:bg-surface-elevated active:scale-[0.97]",children:r(n==="copied"?"errorBoundary.copied":n==="failed"?"errorBoundary.copyFailed":"errorBoundary.copyDetails")}),p.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"rounded-full bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground shadow-sm transition-all hover:bg-primary/90 active:scale-[0.97]",children:r("errorBoundary.retry")})]})]})})}class ik extends Ue.Component{state={hasError:!1,error:null,componentStack:""};static getDerivedStateFromError(e){return{hasError:!0,error:e,componentStack:""}}componentDidCatch(e,r){console.error("Terminal error caught by boundary:",e,r),this.setState({componentStack:r.componentStack??""})}render(){return this.state.hasError?this.props.fallback?this.props.fallback:p.jsx(sk,{error:this.state.error,componentStack:this.state.componentStack}):this.props.children}}function me(){try{if(window.parent!==window&&location.pathname==="/workspace.html"&&window.parent.location.origin===location.origin&&window.parent.__termdockWorkspaceHost)return window.parent}catch{}return window}const ak="debug",ck="termdock:debug";function xu(t){return t?new Set(t.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean)):new Set}function lk(){if(typeof window>"u")return new Set;const t=xu(new URLSearchParams(window.location.search).get(ak));let e=new Set;try{e=xu(window.localStorage.getItem(ck))}catch{e=new Set}const r=new Set([...t,...e]);return r.has("1")||r.has("true")||r.has("*")||r.has("all")?new Set(["*"]):r}function dk(t){const e=lk();return e.has("*")||e.has(t)}function uk(t){const e=dk(t);return(...r)=>{e&&console.log(`[debug:${t}]`,...r)}}const Su=80,fk=60,hk="termdock:viewport-keyboard-change",pk="termdock:viewport-layout-change",vt=240,Eu=640,Au=360;function gk({measuredHeight:t,documentVisible:e,editableFocused:r}){return e&&r&&t>0}function ku(){if(typeof document>"u")return!1;const t=document.activeElement;return t instanceof HTMLElement&&t.matches('input:not([type="hidden"]), textarea, select, [contenteditable]:not([contenteditable="false"])')}const Ss=t=>{const e=typeof t=="number"?t:Number.parseFloat(typeof t=="string"?t:"0");return Number.isFinite(e)&&e>0?Math.round(e):0},qp=(t,e)=>{const r=t.map(Ss).filter(n=>n>0);return r.find(n=>n>=vt)??r[0]??e},Kn=()=>typeof window>"u"?Eu:qp([me().innerHeight,document.documentElement?.clientHeight,document.body?.clientHeight,me().visualViewport?.height,window.screen?.availHeight,window.screen?.height],Eu),Kp=()=>typeof window>"u"?Au:qp([me().innerWidth,document.documentElement?.clientWidth,document.body?.clientWidth,me().visualViewport?.width,window.screen?.availWidth,window.screen?.width],Au),Mt=t=>{const e=Number.parseFloat(t||"0");return Number.isFinite(e)?Math.max(0,Math.round(e)):0},mk=()=>typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,wk=()=>typeof window>"u"?!1:me().navigator.standalone===!0||me().matchMedia?.("(display-mode: standalone)").matches===!0,zp=()=>{if(typeof window>"u"||!mk()||!wk())return{top:0,right:0,bottom:0,left:0};if(!(Kn()>=Kp()))return{top:0,right:0,bottom:0,left:0};const e=window.screen?.width||window.innerWidth,r=window.screen?.height||window.innerHeight,n=Math.min(e,r),o=Math.max(e,r);return n>=700?{top:20,right:0,bottom:20,left:0}:o<780?{top:20,right:0,bottom:0,left:0}:{top:o>=852?59:o>=844?47:44,right:0,bottom:34,left:0}};function yk(t="--app-vh"){if(typeof window>"u"||typeof document>"u")return;const e=Ss(me().visualViewport?.height),r=Math.max(0,Math.round(me().visualViewport?.offsetTop??0)),n=Kn(),s=e>=vt?Math.min(n,e+r):n,i=Math.max(n,s),a=document.documentElement.style;a.setProperty(t,`${Math.max(s,vt)}px`),a.setProperty("--app-base-vh",`${Math.max(i,vt)}px`),a.setProperty("--app-visible-vh",`${Math.max(s,vt)}px`),a.setProperty("--app-vv-offset-top",`${r}px`),a.setProperty("--kb-translate-y","0px"),a.setProperty("--kb-margin-top","0px"),a.setProperty("--kb-height","0px");const c=zp();c.top>0&&a.setProperty("--safe-top-inset",`${c.top}px`),c.right>0&&a.setProperty("--safe-right-inset",`${c.right}px`),c.bottom>0&&a.setProperty("--safe-bottom-inset",`${c.bottom}px`),c.left>0&&a.setProperty("--safe-left-inset",`${c.left}px`)}function tI(t={}){const{cssVarName:e="--app-vh"}=t,r=Ue.useMemo(()=>uk("viewport"),[]),n=Ue.useCallback(()=>{if(typeof window>"u")return 0;const d=me().visualViewport,u=Kn();if(!d)return u;const f=Ss(d.height);if(f<vt&&u>=vt)return u;const h=d.offsetTop,m=f<u-1&&h>0&&h<=96?f+h:f,y=Math.max(0,Math.min(u,m));return y>0?Math.round(y):u},[]),[o,s]=Ue.useState(n),i=Ue.useRef(0),a=Ue.useRef(0),c=Ue.useRef(0),l=Ue.useRef(!1);return Ue.useEffect(()=>{if(typeof window>"u")return;let d=null,u=null;const f=()=>{if(u?.isConnected)return u;try{return u=document.createElement("div"),u.setAttribute("aria-hidden","true"),u.style.cssText=["position:fixed","top:0","left:0","width:0","height:0","visibility:hidden","pointer-events:none","padding-top:constant(safe-area-inset-top)","padding-top:env(safe-area-inset-top,0px)","padding-right:constant(safe-area-inset-right)","padding-right:env(safe-area-inset-right,0px)","padding-bottom:constant(safe-area-inset-bottom)","padding-bottom:env(safe-area-inset-bottom,0px)","padding-left:constant(safe-area-inset-left)","padding-left:env(safe-area-inset-left,0px)"].join(";"),(document.body||document.documentElement).appendChild(u),u}catch{}return null},h=()=>{let P={top:0,right:0,bottom:0,left:0};try{const L=f();if(L){const M=getComputedStyle(L);P={top:Mt(M.paddingTop),right:Mt(M.paddingRight),bottom:Mt(M.paddingBottom),left:Mt(M.paddingLeft)}}}catch{}const b=me();if(b!==window){const L=b.getComputedStyle(b.document.documentElement);P={top:Math.max(P.top,Mt(L.getPropertyValue("--safe-top-inset"))),right:Math.max(P.right,Mt(L.getPropertyValue("--safe-right-inset"))),bottom:Math.max(P.bottom,Mt(L.getPropertyValue("--safe-bottom-inset"))),left:Math.max(P.left,Mt(L.getPropertyValue("--safe-left-inset")))}}const E=zp(),C={top:Math.max(P.top,E.top),right:Math.max(P.right,E.right),bottom:Math.max(P.bottom,E.bottom),left:Math.max(P.left,E.left)};return document.documentElement.style.setProperty("--safe-top-inset",`${C.top}px`),document.documentElement.style.setProperty("--safe-right-inset",`${C.right}px`),document.documentElement.style.setProperty("--safe-bottom-inset",`${C.bottom}px`),document.documentElement.style.setProperty("--safe-left-inset",`${C.left}px`),C},g=(P,b,E,C)=>{const L=Math.max(b,E);if(i.current===0){i.current=L,a.current=P,document.documentElement.style.setProperty("--app-base-vh",`${L}px`);return}const M=Math.abs(P-a.current),$=C<=Su;(M>fk||$)&&(i.current=L,a.current=P,document.documentElement.style.setProperty("--app-base-vh",`${L}px`))},m=(P="event")=>{d=null;const b=n(),E=Math.round(me().visualViewport?.offsetTop??0),C=Ss(me().visualViewport?.height),L=C>=vt?C:b,M=Kn(),$=Kp(),j=Math.max(0,L+E),D=h(),_=D.bottom,O=Math.max(0,i.current-j-_);g($,M,j,O),s(Tt=>Tt===b?Tt:b);const q=Number.parseInt(document.documentElement.style.getPropertyValue(e)||"0",10);document.documentElement.style.setProperty(e,`${b}px`),document.documentElement.style.setProperty("--app-vv-offset-top",`${E}px`);const H=i.current,K=Math.min(b,L),z=Math.max(0,Math.min(H,j)),W=Math.max(0,Math.round(H-z-_)),X=ku(),G=gk({measuredHeight:W,documentVisible:document.visibilityState==="visible",editableFocused:X}),Y=G?W:0,se=Y>=Su,Ne=-Y,Fe=Y;document.documentElement.style.setProperty("--kb-translate-y",`${Ne}px`),document.documentElement.style.setProperty("--kb-margin-top",`${Fe}px`),document.documentElement.style.setProperty("--kb-height",`${Y}px`),document.documentElement.style.setProperty("--app-visible-vh",`${z}px`);const oe=Math.abs(Y-c.current)>1,ot=se!==l.current;(oe||ot)&&(c.current=Y,l.current=se,document.dispatchEvent(new CustomEvent(hk,{detail:{baseHeight:H,visibleHeight:z,visualViewportHeight:L,offsetTop:E,keyboardHeight:Y,isOpen:se,source:P}}))),(q!==b||E>0||oe||ot)&&r("sync",{cssVarName:e,innerHeight:M,baseHeight:H,rawViewportHeight:L,offsetTop:E,visibleHeight:z,rawHeight:b,appliedHeight:b,keyboardViewportHeight:K,measuredKeyboardHeight:W,editableFocused:X,applyKeyboardInset:G,keyboardHeight:Y,isKeyboardOpen:se,safeAreaInsets:D,source:P}),document.dispatchEvent(new CustomEvent(pk,{detail:{height:b,baseHeight:H,visibleHeight:z,offsetTop:E,source:P}}))},y=(P="event")=>{(P.includes("visibilitychange")||P.includes("pageshow"))&&r("schedule",{source:P}),d===null&&(d=window.requestAnimationFrame(()=>m(P)))};y("mount");const w=()=>y("resize"),I=()=>y("orientationchange"),v=()=>y("visualViewport.resize"),A=()=>y("visualViewport.scroll"),B=()=>y("focusin"),T=()=>y("focusout"),N=P=>{const b=document.activeElement;b instanceof HTMLElement&&ku()&&b.blur(),c.current=0,l.current=!1;const E=Math.max(i.current,Kn(),vt),C=document.documentElement.style;C.setProperty(e,`${E}px`),C.setProperty("--app-visible-vh",`${E}px`),C.setProperty("--app-vv-offset-top","0px"),C.setProperty("--kb-translate-y","0px"),C.setProperty("--kb-margin-top","0px"),C.setProperty("--kb-height","0px"),s(L=>L===E?L:E),r("keyboard session reset",{source:P,baseHeight:E})};window.addEventListener("resize",w),window.addEventListener("orientationchange",I),me().visualViewport?.addEventListener("resize",v),me().visualViewport?.addEventListener("scroll",A),document.addEventListener("focusin",B),document.addEventListener("focusout",T);const k=P=>{r("resume",{source:P,innerHeight:Math.round(window.innerHeight),visualViewport:me().visualViewport?{width:Math.round(me().visualViewport.width),height:Math.round(me().visualViewport.height),offsetTop:Math.round(me().visualViewport.offsetTop)}:null,hidden:document.hidden}),y(P)},x=()=>{document.hidden?N("visibilitychange:hidden"):k("visibilitychange")},S=()=>k("pageshow"),R=()=>N("pagehide");return document.addEventListener("visibilitychange",x),window.addEventListener("pageshow",S),window.addEventListener("pagehide",R),()=>{window.removeEventListener("resize",w),window.removeEventListener("orientationchange",I),me().visualViewport?.removeEventListener("resize",v),me().visualViewport?.removeEventListener("scroll",A),document.removeEventListener("focusin",B),document.removeEventListener("focusout",T),document.removeEventListener("visibilitychange",x),window.removeEventListener("pageshow",S),window.removeEventListener("pagehide",R),d!==null&&window.cancelAnimationFrame(d),u?.remove()}},[e,r,n]),o}const Iu=5*6e4;let Ga,Vp=!1,Wp=!1,Cu=!1;const Xa=new Set;function Ru(){Vp=!0,Xa.forEach(t=>t())}function bk(){return F.useSyncExternalStore(t=>(Xa.add(t),()=>{Xa.delete(t)}),()=>Vp,()=>!1)}function vk(){window.dispatchEvent(new Event("termdock:before-update")),Wp=!0,Ga?.waiting?Ga.waiting.postMessage({type:"SKIP_WAITING"}):window.location.reload()}function xk(t,e){let r=t;return()=>{if(!r){r=!0;return}e()}}function Sk(){if(Cu||typeof window>"u"||!("serviceWorker"in navigator))return;Cu=!0,navigator.serviceWorker.addEventListener("controllerchange",xk(!!navigator.serviceWorker.controller,()=>{Wp?window.location.reload():Ru()}));const t=()=>{navigator.serviceWorker.register("/sw.js",{scope:"/",updateViaCache:"none"}).then(e=>{Ga=e;const r=()=>{e.waiting&&Ru()},n=()=>{const i=e.installing;i?.addEventListener("statechange",()=>{i.state==="installed"&&navigator.serviceWorker.controller&&r()})};e.addEventListener("updatefound",n),n(),r();let o=0;const s=()=>{document.visibilityState!=="visible"||Date.now()-o<Iu||(o=Date.now(),e.update().then(r).catch(()=>{}))};s(),window.setInterval(s,Iu),document.addEventListener("visibilitychange",s)}).catch(()=>{})};document.readyState==="complete"?t():window.addEventListener("load",t,{once:!0})}function Ek(){const t=bk(),[e,r]=F.useState(!1),{locale:n}=Kc();if(!t||e)return null;const o=n==="zh";return p.jsxs("div",{role:"status",className:"fixed bottom-16 left-1/2 z-toast flex max-w-[calc(100%-2rem)] -translate-x-1/2 items-center gap-3 rounded-lg border border-border bg-background px-4 py-3 text-sm text-foreground shadow-lg",children:[p.jsx("span",{children:o?"新版本已就绪":"An update is ready"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-primary",onClick:vk,children:o?"重新加载":"Reload"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-muted-foreground",onClick:()=>r(!0),children:o?"稍后":"Later"})]})}function Gp(t){const e=document.querySelector('meta[name="theme-color"]');e&&e.setAttribute("content",t==="light"?"#FFFCF0":"#1C1B1A")}const Ak={activeKey:"root",items:[]},kk=()=>()=>{},Ik=()=>Ak;function Ck({host:t,item:e,active:r}){const n=F.useRef(null);return F.useEffect(()=>{n.current?.toggleAttribute("inert",!r)},[r]),F.useEffect(()=>()=>t.attach(e.key,null),[t,e.key]),p.jsx("iframe",{ref:n,title:e.service?.label||"服务工作区",src:`/workspace.html?${zh}=${encodeURIComponent(e.key)}`,className:"fixed inset-0 w-full border-0 bg-[var(--chrome-bg)]",style:{height:"var(--app-base-vh, 100%)",visibility:r?"visible":"hidden",pointerEvents:r?"auto":"none"},"aria-hidden":!r,tabIndex:r?0:-1,allow:"clipboard-read; clipboard-write; fullscreen",onLoad:o=>t.attach(e.key,o.currentTarget.contentWindow)})}function Rk({children:t}){const e=window.parent===window?St():void 0,r=F.useSyncExternalStore(e?.subscribe||kk,e?.snapshot||Ik),n=F.useRef(null);return F.useEffect(()=>{n.current?.toggleAttribute("inert",r.activeKey!=="root")},[r.activeKey]),F.useEffect(()=>{if(!e)return;const o=()=>{try{const s=JSON.parse(localStorage.getItem("termdock-color-theme")||"null");(s==="dark"||s==="light")&&(document.documentElement.dataset.theme=s,Gp(s))}catch{}};return window.addEventListener("storage",o),()=>window.removeEventListener("storage",o)},[e]),F.useEffect(()=>{if(!e||!("serviceWorker"in navigator))return;const o=a=>{if(a.source!==navigator.serviceWorker.controller)return;const c=a.data;c?.type==="termdock:focus-session"&&typeof c.targetPeerId=="string"&&typeof c.sessionId=="string"&&e.focusSession(c.targetPeerId,c.sessionId)&&(a.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),a.stopImmediatePropagation())},s=async()=>{if("caches"in window)try{const a=await caches.open("termdock-notification-target-v1"),c=await a.match("/__termdock-notification-target");if(!c)return;const l=await c.json();typeof l.targetPeerId=="string"&&typeof l.sessionId=="string"&&Date.now()-l.clickedAt<3e4&&e.focusSession(l.targetPeerId,l.sessionId)&&await a.delete("/__termdock-notification-target")}catch{}},i=()=>{document.hidden||s()};return navigator.serviceWorker.addEventListener("message",o),document.addEventListener("visibilitychange",i),s(),()=>{navigator.serviceWorker.removeEventListener("message",o),document.removeEventListener("visibilitychange",i)}},[e]),e?p.jsxs("div",{className:"relative h-full w-full overflow-hidden bg-[var(--chrome-bg)]",children:[p.jsx("div",{ref:n,className:"h-full w-full","aria-hidden":r.activeKey!=="root",style:{visibility:r.activeKey==="root"?"visible":"hidden"},children:t}),r.items.filter(o=>o.key!=="root").map(o=>p.jsx(Ck,{host:e,item:o,active:r.activeKey===o.key},o.key))]}):t}const Tk=F.lazy(()=>Vt(()=>import("./App-DzU5e73Z.js").then(t=>t.A),__vite__mapDeps([4,2,1,5,6,3,7,8]))),Pk=F.lazy(()=>Vt(()=>import("./DagPlayground-Badsbf-8.js"),__vite__mapDeps([9,10,2,1,11,8,3])).then(t=>({default:t.DagPlayground}))),Nk=F.lazy(()=>Vt(()=>import("./DiffLab-D_xUbRBZ.js"),__vite__mapDeps([12,2,1,13,7,14,3])).then(t=>({default:t.DiffLab}))),Lk=F.lazy(()=>Vt(()=>import("./DiffReviewLab-DS0B2tZH.js"),__vite__mapDeps([15,2,1,16,5,6,11,13,7,14,3])).then(t=>({default:t.DiffReviewLab})));yk();qx();window.parent===window&&Sk();const Dn=ne();Dn&&Vt(()=>import("./App-DzU5e73Z.js").then(t=>t.A),__vite__mapDeps([4,2,1,5,6,3,7,8])).catch(()=>{});!new URLSearchParams(location.search).has("dag-playground")&&!new URLSearchParams(location.search).has("diff-lab")&&!new URLSearchParams(location.search).has("diff-review-lab")&&(_x(Dn?{...Dn,id:Dn.targetPeerId,label:Dn.serviceName||location.host}:void 0),Yh());try{const t=JSON.parse(window.localStorage.getItem("termdock-color-theme")||"null");(t==="dark"||t==="light")&&(document.documentElement.dataset.theme=t,Gp(t))}catch{}Qx.createRoot(document.getElementById("root")).render(p.jsx(Ue.StrictMode,{children:p.jsxs(nA,{children:[window.parent===window&&p.jsx(Ek,{}),p.jsx(ik,{children:p.jsx(F.Suspense,{fallback:p.jsx("div",{className:"termdock-boot",role:"status",children:"Loading Termdock"}),children:(()=>{const t=new URLSearchParams(window.location.search);return t.get("dag-playground")==="1"?p.jsx(Pk,{}):t.get("diff-review-lab")==="1"?p.jsx(Lk,{}):t.get("diff-lab")==="1"?p.jsx(Nk,{}):p.jsx(Rk,{children:p.jsx(rk,{children:p.jsx(Tk,{})})})})()})})]})}));export{WE as $,Mc as A,dS as B,Pc as C,nr as D,hp as E,T2 as F,R2 as G,x1 as H,i1 as I,PE as J,GE as K,He as L,fp as M,lo as N,dr as O,CA as P,Kk as Q,EA as R,js as S,CS as T,B1 as U,pk as V,Ia as W,TS as X,uk as Y,Pe as Z,Vt as _,Qh as a,C1 as a$,li as a0,M1 as a1,m2 as a2,p1 as a3,F1 as a4,g2 as a5,LS as a6,up as a7,NE as a8,AA as a9,u1 as aA,S1 as aB,P2 as aC,Ap as aD,St as aE,ku as aF,Qf as aG,bh as aH,h2 as aI,P1 as aJ,_1 as aK,Ep as aL,e2 as aM,r2 as aN,X1 as aO,Q1 as aP,Z1 as aQ,mi as aR,p as aS,qk as aT,f1 as aU,D2 as aV,U1 as aW,H2 as aX,G2 as aY,s2 as aZ,d1 as a_,l1 as aa,lt as ab,T1 as ac,R1 as ad,L1 as ae,VE as af,C2 as ag,A2 as ah,E2 as ai,k2 as aj,k1 as ak,t2 as al,x2 as am,B2 as an,d2 as ao,N2 as ap,S2 as aq,y2 as ar,z1 as as,I2 as at,m1 as au,Hn as av,np as aw,RE as ax,mE as ay,A1 as az,cS as b,N1 as b$,K2 as b0,b2 as b1,wE as b2,w1 as b3,$1 as b4,YE as b5,Rt as b6,f2 as b7,l2 as b8,u2 as b9,L2 as bA,O2 as bB,q2 as bC,ne as bD,i2 as bE,Y2 as bF,Hx as bG,r1 as bH,X2 as bI,n1 as bJ,QE as bK,XE as bL,t1 as bM,s1 as bN,M2 as bO,V2 as bP,vp as bQ,zE as bR,di as bS,Zk as bT,z2 as bU,U2 as bV,Vk as bW,JE as bX,$k as bY,Gp as bZ,jk as b_,p2 as ba,eI as bb,Wk as bc,ZE as bd,LE as be,zk as bf,La as bg,j2 as bh,H1 as bi,W2 as bj,v1 as bk,b1 as bl,V1 as bm,q1 as bn,E1 as bo,W1 as bp,K1 as bq,o1 as br,Qk as bs,a1 as bt,h1 as bu,j1 as bv,$2 as bw,Uk as bx,PS as by,F2 as bz,hS as c,O1 as c0,I1 as c1,y1 as c2,$t as c3,w2 as c4,Kc as c5,Xk as c6,Ie as c7,tI as c8,me as c9,a2 as ca,nt as cb,Yk as cc,Gk as cd,fr as d,ep as e,wS as f,ik as g,SS as h,tp as i,lA as j,pe as k,e1 as l,yc as m,It as n,_2 as o,Hk as p,n2 as q,J1 as r,bc as s,c2 as t,Px as u,D1 as v,r0 as w,TE as x,c1 as y,Jk as z};
|